From 1a8cbece96d1a22ca508aba8a72cf4faa270d3a9 Mon Sep 17 00:00:00 2001 From: Makiko Shukunobe Date: Tue, 2 Jul 2024 16:12:21 -0400 Subject: [PATCH 01/75] Checks: fix flake8 E741 remainder (#3928) * Rename l to line when using `f.readlines()`. * Remove "l"s from parameters since they aren't used. * Rename "l" to "lx" to assign a lexer object. * Add "# noqa: E741" as renaming parameters won't be applicable in this case. * Rename "l" to "ln" as line number. * Rename "l" to "layer" when looping through the layer list. * Remove E741 for files in the 'locale', `python`, and `scripts` directory. * Rename "ln" to "line_number". --- .flake8 | 14 ++++------- locale/grass_po_stats.py | 8 +++---- python/grass/pygrass/raster/rowio.py | 6 ++--- python/grass/temporal/temporal_algebra.py | 12 +++++----- .../temporal/temporal_raster3d_algebra.py | 8 +++---- .../grass/temporal/temporal_raster_algebra.py | 8 +++---- .../grass/temporal/temporal_vector_algebra.py | 8 +++---- scripts/d.rast.leg/d.rast.leg.py | 2 +- scripts/db.univar/db.univar.py | 14 +++++------ scripts/r.in.wms/wms_cap_parsers.py | 24 +++++++++---------- 10 files changed, 50 insertions(+), 54 deletions(-) diff --git a/.flake8 b/.flake8 index 9786c9775a3..7019d947c03 100644 --- a/.flake8 +++ b/.flake8 @@ -39,7 +39,7 @@ per-file-ignores = doc/python/vector_example_ctypes.py: F403, F405 doc/python/m.distance.py: F403, F405, E501 doc/gui/wxpython/example/dialogs.py: F401 - locale/grass_po_stats.py: E122, E128, E231, E401, E722, E741 + locale/grass_po_stats.py: E122, E128, E231, E401, E722 gui/scripts/d.wms.py: E501 gui/wxpython/core/gcmd.py: E402 gui/wxpython/core/gthread.py: F841 @@ -126,7 +126,6 @@ per-file-ignores = python/grass/pygrass/vector/__init__.py: E402 python/grass/pygrass/modules/interface/*.py: F401 python/grass/pygrass/modules/grid/*.py: F401 - python/grass/pygrass/raster/rowio.py: E741 python/grass/pygrass/raster/category.py: E721 python/grass/pygrass/rpc/__init__.py: F401, F403 python/grass/pygrass/utils.py: E402 @@ -136,13 +135,11 @@ per-file-ignores = python/grass/temporal/datetime_math.py: F841, E722 python/grass/temporal/open_stds.py: F841 python/grass/temporal/spatial_topology_dataset_connector.py: E722 - python/grass/temporal/temporal_algebra.py: E741, F841, E722 + python/grass/temporal/temporal_algebra.py: F841, E722 python/grass/temporal/temporal_granularity.py: F841, E722 - python/grass/temporal/temporal_raster_algebra.py: E741 python/grass/temporal/temporal_raster_base_algebra.py: F841, E722 - python/grass/temporal/temporal_raster3d_algebra.py: E741 python/grass/temporal/temporal_topology_dataset_connector.py: E722 - python/grass/temporal/temporal_vector_algebra.py: E741, F841 + python/grass/temporal/temporal_vector_algebra.py: F841 python/grass/temporal/univar_statistics.py: E231 # Current benchmarks/tests are changing sys.path before import. # Possibly, a different approach should be taken there anyway. @@ -161,7 +158,7 @@ per-file-ignores = # E402 module level import not at top of file scripts/d.polar/d.polar.py: F841 scripts/r.in.wms/wms_gdal_drv.py: F841, E722 - scripts/r.in.wms/wms_cap_parsers.py: F841, E741 + scripts/r.in.wms/wms_cap_parsers.py: F841 scripts/r.in.wms/wms_drv.py: E402, E722 scripts/r.in.wms/srs.py: E722 scripts/r.semantic.label/r.semantic.label.py: F841, E501 @@ -170,8 +167,7 @@ per-file-ignores = scripts/g.extension/g.extension.py: F841, E722, E501 scripts/v.unpack/v.unpack.py: F841, E722, E501 scripts/v.import/v.import.py: F841, E722, E501 - scripts/db.univar/db.univar.py: E741, E501 - scripts/d.rast.leg/d.rast.leg.py: E741 + scripts/db.univar/db.univar.py: E501 scripts/d.frame/d.frame.py: E722 scripts/i.pansharpen/i.pansharpen.py: E722, E501 scripts/r.in.srtm/r.in.srtm.py: E722 diff --git a/locale/grass_po_stats.py b/locale/grass_po_stats.py index 81ccbab167d..b5f15026691 100644 --- a/locale/grass_po_stats.py +++ b/locale/grass_po_stats.py @@ -72,9 +72,9 @@ def read_msgfmt_statistics(msg, lgood, lfuzzy, lbad): def langDefinition(fil): f = codecs.open(fil, encoding="utf-8", errors="replace", mode="r") - for l in f.readlines(): - if '"Language-Team:' in l: - lang = l.split(" ")[1:-1] + for line in f.readlines(): + if '"Language-Team:' in line: + lang = line.split(" ")[1:-1] break f.close() if len(lang) == 2: @@ -136,7 +136,7 @@ def writejson(stats, outfile): # load dictionary into json format fjson = json.dumps(stats, sort_keys=True, indent=4) # write a string with pretty style - outjson = os.linesep.join([l.rstrip() for l in fjson.splitlines()]) + outjson = os.linesep.join([line.rstrip() for line in fjson.splitlines()]) # write out file fout = open(outfile, "w") fout.write(outjson) diff --git a/python/grass/pygrass/raster/rowio.py b/python/grass/pygrass/raster/rowio.py index 62c5683ef68..377843642a1 100644 --- a/python/grass/pygrass/raster/rowio.py +++ b/python/grass/pygrass/raster/rowio.py @@ -18,17 +18,17 @@ ) -def getmaprow_CELL(fd, buf, row, l): +def getmaprow_CELL(fd, buf, row): librast.Rast_get_c_row(fd, ctypes.cast(buf, ctypes.POINTER(librast.CELL)), row) return 1 -def getmaprow_FCELL(fd, buf, row, l): +def getmaprow_FCELL(fd, buf, row): librast.Rast_get_f_row(fd, ctypes.cast(buf, ctypes.POINTER(librast.FCELL)), row) return 1 -def getmaprow_DCELL(fd, buf, row, l): +def getmaprow_DCELL(fd, buf, row): librast.Rast_get_d_row(fd, ctypes.cast(buf, ctypes.POINTER(librast.DCELL)), row) return 1 diff --git a/python/grass/temporal/temporal_algebra.py b/python/grass/temporal/temporal_algebra.py index 0d6d200ff29..6bf96eea68e 100644 --- a/python/grass/temporal/temporal_algebra.py +++ b/python/grass/temporal/temporal_algebra.py @@ -870,7 +870,7 @@ def setup_common_granularity(self, expression, stdstype="strds", lexer=None): :return: True if successful, False otherwise """ - l = lexer + lx = lexer # Split the expression to ignore the left part expressions = expression.split("=")[1:] expression = " ".join(expressions) @@ -886,17 +886,17 @@ def setup_common_granularity(self, expression, stdstype="strds", lexer=None): return False # detect all STDS - if l is None: - l = TemporalAlgebraLexer() - l.build() - l.lexer.input(expression) + if lx is None: + lx = TemporalAlgebraLexer() + lx.build() + lx.lexer.input(expression) name_list = [] tokens = [] count = 0 while True: - tok = l.lexer.token() + tok = lx.lexer.token() if not tok: break diff --git a/python/grass/temporal/temporal_raster3d_algebra.py b/python/grass/temporal/temporal_raster3d_algebra.py index 56b3ac82751..b8920e27848 100644 --- a/python/grass/temporal/temporal_raster3d_algebra.py +++ b/python/grass/temporal/temporal_raster3d_algebra.py @@ -54,12 +54,12 @@ def __init__( def parse(self, expression, basename=None, overwrite=False): # Check for space time dataset type definitions from temporal algebra - l = TemporalRasterAlgebraLexer() - l.build() - l.lexer.input(expression) + lx = TemporalRasterAlgebraLexer() + lx.build() + lx.lexer.input(expression) while True: - tok = l.lexer.token() + tok = lx.lexer.token() if not tok: break diff --git a/python/grass/temporal/temporal_raster_algebra.py b/python/grass/temporal/temporal_raster_algebra.py index 76e1a08af66..182a679c6a7 100644 --- a/python/grass/temporal/temporal_raster_algebra.py +++ b/python/grass/temporal/temporal_raster_algebra.py @@ -100,12 +100,12 @@ def __init__( def parse(self, expression, basename=None, overwrite=False): # Check for space time dataset type definitions from temporal algebra - l = TemporalRasterAlgebraLexer() - l.build() - l.lexer.input(expression) + lx = TemporalRasterAlgebraLexer() + lx.build() + lx.lexer.input(expression) while True: - tok = l.lexer.token() + tok = lx.lexer.token() if not tok: break diff --git a/python/grass/temporal/temporal_vector_algebra.py b/python/grass/temporal/temporal_vector_algebra.py index 5bdf51455d9..a5c5bc27533 100644 --- a/python/grass/temporal/temporal_vector_algebra.py +++ b/python/grass/temporal/temporal_vector_algebra.py @@ -153,12 +153,12 @@ def __init__(self, pid=None, run=False, debug=True, spatial=False): def parse(self, expression, basename=None, overwrite=False): # Check for space time dataset type definitions from temporal algebra - l = TemporalVectorAlgebraLexer() - l.build() - l.lexer.input(expression) + lx = TemporalVectorAlgebraLexer() + lx.build() + lx.lexer.input(expression) while True: - tok = l.lexer.token() + tok = lx.lexer.token() if not tok: break diff --git a/scripts/d.rast.leg/d.rast.leg.py b/scripts/d.rast.leg/d.rast.leg.py index 855bf85e684..1ea93b8e467 100755 --- a/scripts/d.rast.leg/d.rast.leg.py +++ b/scripts/d.rast.leg/d.rast.leg.py @@ -66,7 +66,7 @@ import grass.script as grass -def make_frame(f, b, t, l, r): +def make_frame(f, b, t, l, r): # noqa: E741 (fl, fr, ft, fb) = f t /= 100.0 diff --git a/scripts/db.univar/db.univar.py b/scripts/db.univar/db.univar.py index 1ffc81d8c3e..8a91656d4b6 100755 --- a/scripts/db.univar/db.univar.py +++ b/scripts/db.univar/db.univar.py @@ -313,23 +313,23 @@ def main(): pval[i] = 0 inf = open(tmp + ".sort") - l = 1 + line_number = 1 for line in inf: line = line.rstrip("\r\n") if len(line) == 0: continue - if l == q25pos: + if line_number == q25pos: q25 = float(line) - if l == q50apos: + if line_number == q50apos: q50a = float(line) - if l == q50bpos: + if line_number == q50bpos: q50b = float(line) - if l == q75pos: + if line_number == q75pos: q75 = float(line) for i in range(len(ppos)): - if l == ppos[i]: + if line_number == ppos[i]: pval[i] = float(line) - l += 1 + line_number += 1 q50 = (q50a + q50b) / 2 diff --git a/scripts/r.in.wms/wms_cap_parsers.py b/scripts/r.in.wms/wms_cap_parsers.py index a053942ee77..4137c114deb 100644 --- a/scripts/r.in.wms/wms_cap_parsers.py +++ b/scripts/r.in.wms/wms_cap_parsers.py @@ -140,9 +140,9 @@ def _checkLayerTree(self, parent_layer, first=True): layers = parent_layer.findall(self.xml_ns.Ns("Layer")) - for l in layers: - self._initLayer(l, parent_layer) - self._checkLayerTree(l, False) + for layer in layers: + self._initLayer(layer, parent_layer) + self._checkLayerTree(layer, False) def _initLayer(self, layer, parent_layer): """Inherit elements from parent layer @@ -340,10 +340,10 @@ def __init__(self, cap_file): self._findall(contents, "TileMatrixSet", self.xml_ns.NsWmts) layers = self._findall(contents, "Layer", self.xml_ns.NsWmts) - for l in layers: - if not self._checkLayer(l): + for layer in layers: + if not self._checkLayer(layer): grass.debug("Removed invalid element.", 4) - contents.remove(l) + contents.remove(layer) # are there any elements after the check self._findall(contents, "Layer", self.xml_ns.NsWmts) @@ -580,12 +580,12 @@ def _checkLayerTree(self, parent_layer, first=True): layers = parent_layer.findall("TiledGroup") layers += parent_layer.findall("TiledGroups") - for l in layers: - if not self._checkLayer(l): - grass.debug(("Removed invalid <%s> element." % l.tag), 4) - parent_layer.remove(l) - if l.tag == "TiledGroups": - self._checkLayerTree(l, False) + for layer in layers: + if not self._checkLayer(layer): + grass.debug(("Removed invalid <%s> element." % layer.tag), 4) + parent_layer.remove(layer) + if layer.tag == "TiledGroups": + self._checkLayerTree(layer, False) def _find(self, etreeElement, tag): """!Find child element. From 277a147cc6d0771a8e85a6b5ad7f26310fe7e86b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Edouard=20Choini=C3=A8re?= <27212526+echoix@users.noreply.github.com> Date: Tue, 2 Jul 2024 23:56:36 -0400 Subject: [PATCH 02/75] checks(ruff): Configure ruff linter (#3972) --- .github/workflows/post-pr-reviews.yml | 19 + .github/workflows/python-code-quality.yml | 16 + .pre-commit-config.yaml | 8 + pyproject.toml | 459 +++++++++++++++++++++- 4 files changed, 500 insertions(+), 2 deletions(-) diff --git a/.github/workflows/post-pr-reviews.yml b/.github/workflows/post-pr-reviews.yml index 7bfa9b9091f..e35d58be50e 100644 --- a/.github/workflows/post-pr-reviews.yml +++ b/.github/workflows/post-pr-reviews.yml @@ -47,6 +47,7 @@ jobs: INPUT_TOOL_NAMES: >- black clang-format + ruff - name: Post Black suggestions if: ${{ steps.tools.outputs.black == 'true' }} run: | @@ -83,3 +84,21 @@ jobs: CI_REPO_OWNER: ${{ github.event.workflow_run.repository.owner.login }} CI_REPO_NAME: ${{ github.event.workflow_run.repository.name }} # CI_PULL_REQUEST: "" # Populated from reviewdog's "-guess" flag since hard to get + - name: Post Ruff suggestions + if: ${{ steps.tools.outputs.black == 'true' }} + run: | + TMPFILE="diff-${INPUT_TOOL_NAME}.patch" + GITHUB_ACTIONS="" reviewdog \ + -name="${INPUT_TOOL_NAME:-reviewdog-suggester}" \ + -f=diff \ + -f.diff.strip=1 \ + -filter-mode=nofilter \ + -guess \ + -reporter="github-pr-review" < "${TMPFILE}" + env: + INPUT_TOOL_NAME: ruff + REVIEWDOG_GITHUB_API_TOKEN: ${{ secrets.GITHUB_TOKEN }} + CI_COMMIT: ${{ github.event.workflow_run.head_sha }} + CI_REPO_OWNER: ${{ github.event.workflow_run.repository.owner.login }} + CI_REPO_NAME: ${{ github.event.workflow_run.repository.name }} + # CI_PULL_REQUEST: "" # Populated from reviewdog's "-guess" flag since hard to get diff --git a/.github/workflows/python-code-quality.yml b/.github/workflows/python-code-quality.yml index d54ceb5e0d9..9565c32eaea 100644 --- a/.github/workflows/python-code-quality.yml +++ b/.github/workflows/python-code-quality.yml @@ -35,6 +35,8 @@ jobs: PYLINT_VERSION: "2.12.2" # renovate: datasource=pypi depName=bandit BANDIT_VERSION: "1.7.9" + # renovate: datasource=pypi depName=ruff + RUFF_VERSION: "0.5.0" runs-on: ${{ matrix.os }} permissions: @@ -50,6 +52,7 @@ jobs: echo Flake8: ${{ env.FLAKE8_VERSION }} echo Pylint: ${{ env.PYLINT_VERSION }} echo Bandit: ${{ env.BANDIT_VERSION }} + echo Ruff: ${{ env.RUFF_VERSION }} - uses: actions/checkout@692973e3d937129bcbf40652eb9f2f61becf3332 # v4.1.7 @@ -61,6 +64,19 @@ jobs: - name: Upgrade pip run: python -m pip install --upgrade pip + - name: Install Ruff + run: pip install ruff==${{ env.RUFF_VERSION }} + - name: Run Ruff + run: ruff check --output-format=github . --preview --fix + - name: Create and uploads code suggestions to apply for Ruff + # Will fail fast here if there are changes required + id: diff-ruff + uses: ./.github/actions/create-upload-suggestions + with: + tool-name: ruff + # To keep repo's file structure in formatted changes artifact + extra-upload-changes: pyproject.toml + - name: Install Black only run: pip install black[jupyter]==${{ env.BLACK_VERSION }} diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index d596da4f85c..2f87a239105 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -35,6 +35,14 @@ repos: python/libgrass_interface_generator/ctypesgen/| lib/fonts/fonts/.* ) + - repo: https://github.com/astral-sh/ruff-pre-commit + # Ruff version. + rev: v0.5.0 + hooks: + # Run the linter. + - id: ruff + types_or: [python, pyi, jupyter] + args: [--fix, --preview] - repo: https://github.com/igorshubovych/markdownlint-cli rev: v0.41.0 hooks: diff --git a/pyproject.toml b/pyproject.toml index 659b26abcde..e5d0c3b2240 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,3 +1,7 @@ +[project] +name = "grass" +requires-python = ">=3.9" + [tool.black] required-version = '24' line-length = 88 @@ -9,6 +13,452 @@ extend-exclude = ''' ) ''' +[tool.ruff] +required-version = ">=0.5.0" + +builtins = ["_"] + +# In addition to the standard set of exclusions, omit the following files or folders. +extend-exclude = ["python/libgrass_interface_generator"] +# In addition to the standard set of inclusions, include `.ipynb` files. +extend-include = ["*.ipynb"] + +[tool.ruff.lint] +# See https://docs.astral.sh/ruff/rules/ +select = [ + "A", # flake8-builtins (A) + "AIR", # Airflow (AIR) + "ANN", # flake8-annotations (ANN) + "ARG", # flake8-unused-arguments (ARG) + "B", # flake8-bugbear (B) + "BLE", # flake8-blind-except (BLE) + "C4", # flake8-comprehensions (C4) + "COM", # flake8-commas (COM) + "D", # pydocstyle (D) + "DTZ", # flake8-datetimez (DTZ) + "E4", # pycodestyle (E, W) + "E7", # pycodestyle (E, W) + "E9", # pycodestyle (E, W) + "F", # Pyflakes (F) + "FA", # flake8-future-annotations (FA) + "FBT", # flake8-boolean-trap (FBT) + "FLY", # flynt (FLY) + "FURB", # refurb (FURB) + "G", # flake8-logging-format (G) + "I", # isort (I) + "ICN", # flake8-import-conventions (ICN) + "INT", # flake8-gettext (INT) + "ISC", # flake8-implicit-str-concat (ISC) + "LOG", # flake8-logging (LOG) + "NPY", # NumPy-specific rules (NPY) + "PERF", # Perflint (PERF) + "PGH", # pygrep-hooks (PGH) + "PIE", # flake8-pie (PIE) + "PLC", # Pylint (PL) Convention (C) + "PLE", # Pylint (PL) Error (E) + "PLR", # Pylint (PL) Refactor (R) + "PLW", # Pylint (PL) Warning (W) + "PT", # flake8-pytest-style (PT) + "PTH", # flake8-use-pathlib (PTH) + "PTH105", # flake8-use-pathlib (PTH) + "PYI", # flake8-pyi (PYI) + "Q", # flake8-quotes (Q) + "RET", # flake8-return (RET) + "RSE", # flake8-raise (RSE) + "RUF", # Ruff-specific rules (RUF) + "S", # flake8-bandit (S) + "SIM", # flake8-simplify (SIM) + "SLF", # flake8-self (SLF) + "SLOT", # flake8-slots (SLOT) + "T10", # flake8-debugger (T10) + "TCH", # flake8-type-checking (TCH) + "TID", # flake8-tidy-imports (TID) + "TRY", # tryceratops (TRY) + "UP", # pyupgrade (UP) + "W", # pycodestyle (E, W) + "YTT", # flake8-2020 (YTT) +] + +ignore = [ + # See https://docs.astral.sh/ruff/rules/ + # *GRASS TODO: fix the issues, or use https://docs.astral.sh/ruff/settings/#lint_per-file-ignores + "A001", # builtin-variable-shadowing + "A002", # builtin-argument-shadowing + "ANN", # flake8-annotations (ANN) + "ARG001", # unused-function-argument + "ARG002", # unused-method-argument + "ARG005", # unused-lambda-argument + "B004", # unreliable-callable-check + "B006", # mutable-argument-default + "B007", # unused-loop-control-variable + "B008", # function-call-in-default-argument + "B009", # get-attr-with-constant + "B015", # useless-comparison + "B018", # useless-expression + "B020", # loop-variable-overrides-iterator + "B023", # function-uses-loop-variable + "B026", # star-arg-unpacking-after-keyword-arg + "B028", # no-explicit-stacklevel + "B034", # re-sub-positional-args + "B904", # raise-without-from-inside-except + "B909", # loop-iterator-mutation + "BLE001", # blind-except + "C400", # unnecessary-generator-list + "C401", # unnecessary-generator-set + "C403", # unnecessary-list-comprehension-set + "C404", # unnecessary-list-comprehension-dict + "C405", # unnecessary-literal-set + "C414", # unnecessary-double-cast-or-process + "C416", # unnecessary-comprehension + "C417", # unnecessary-map + "C419", # unnecessary-comprehension-in-call + "COM812", # missing-trailing-comma + "COM818", # trailing-comma-on-bare-tuple + "D1", + "D2", + "D300", # triple-single-quotes + "D301", # escape-sequence-in-docstring + "D400", # ends-in-period + "D401", # non-imperative-mood + "D402", # no-signature + "D403", # first-line-capitalized + "D404", # docstring-starts-with-this + "D405", # capitalize-section-name + "D406", # new-line-after-section-name + "D407", # dashed-underline-after-section + "D409", # section-underline-matches-section-length + "D411", # no-blank-line-before-section + "D412", # blank-lines-between-header-and-content + "D413", # blank-line-after-last-section + "D415", # ends-in-punctuation + "D416", # section-name-ends-in-colon + "D419", # empty-docstring + "DTZ001", # call-datetime-without-tzinfo + "DTZ002", # call-datetime-today + "DTZ005", # call-datetime-now-without-tzinfo + "DTZ006", # call-datetime-fromtimestamp + "DTZ007", # call-datetime-strptime-without-zone + "DTZ011", # call-date-today + "E401", # multiple-imports-on-one-line + "E402", # module-import-not-at-top-of-file + "E713", # not-in-test + "E714", # not-is-test + "E721", # type-comparison + "E722", # bare-except + "E731", # lambda-assignment + "E741", # ambiguous-variable-name + "F401", # unused-import + "F403", # undefined-local-with-import-star + "F405", # undefined-local-with-import-star-usage + "F601", # multi-value-repeated-key-literal + "F632", # is-literal + "F811", # redefined-while-unused + "F821", # undefined-name + "F822", # undefined-export + "F841", # unused-variable, + "FBT001", # boolean-type-hint-positional-argument + "FBT002", # boolean-default-value-positional-argument + "FBT003", # boolean-positional-value-in-call + "FURB101", # read-whole-file + "FURB103", # write-whole-file. + "FURB105", # print-empty-string + "FURB110", # if-exp-instead-of-or-operator + "FURB113", # repeated-append + "FURB116", # f-string-number-format + "FURB116", # f-string-number-format + "FURB118", # reimplemented-operator + "FURB129", # readlines-in-for + "FURB131", # delete-full-slice + "FURB136", # if-expr-min-max + "FURB140", # reimplemented-starmap + "FURB142", # for-loop-set-mutations + "FURB148", # unnecessary-enumerate + "FURB152", # math-constant + "FURB154", # repeated-global + "FURB171", # single-item-membership-test + "FURB192", # sorted-min-max + "G002", # logging-percent-format + "G003", # logging-string-concat + "I001", # unsorted-imports + "ICN001", # unconventional-import-alias + "ISC003", # explicit-string-concatenation + "PERF102", # incorrect-dict-iterator + "PERF203", # try-except-in-loop + "PERF401", # manual-list-comprehension + "PERF402", # manual-list-copy + "PERF403", # manual-dict-comprehension + "PIE790", # unnecessary-placeholder + "PIE794", # duplicate-class-field-definition + "PIE808", # unnecessary-range-start + "PIE810", # multiple-starts-ends-with + "PLC0206", # dict-index-missing-items + "PLC0414", # useless-import-alias + "PLC0415", # import-outside-top-level + "PLC1901", # compare-to-empty-string + "PLC2701", # import-private-name + "PLC2801", # unnecessary-dunder-call + "PLE0704", # misplaced-bare-raise + "PLR0124", # comparison-with-itself + "PLR0202", # no-classmethod-decorator + "PLR0904", # too-many-public-methods + "PLR0911", # too-many-return-statements + "PLR0912", # too-many-branches + "PLR0913", # too-many-arguments + "PLR0914", # too-many-locals + "PLR0915", # too-many-statements + "PLR0916", # too-many-boolean-expressions + "PLR0917", # too-many-positional + "PLR1702", # too-many-nested-blocks + "PLR1704", # redefined-argument-from-local + "PLR1714", # repeated-equality-comparison + "PLR1733", # unnecessary-dict-index-lookup + "PLR2004", # magic-value-comparison + "PLR2044", # empty-comment + "PLR5501", # collapsible-else-if + "PLR6104", # non-augmented-assignment + "PLR6201", # literal-membership + "PLR6301", # no-self-use + "PLW0127", # self-assigning-variable + "PLW0406", # import-self + "PLW0602", # global-variable-not-assigned + "PLW0603", # global-statement + "PLW0604", # global-at-module-level + "PLW1508", # invalid-envvar-default + "PLW1510", # subprocess-run-without-check + "PLW1514", # unspecified-encoding + "PLW1641", # eq-without-hash + "PLW2901", # redefined-loop-name + "PLW3201", # nested-min-max + "PT001", # pytest-fixture-incorrect-parentheses-style + "PT004", # pytest-missing-fixture-name-underscore + "PT006", # pytest-parametrize-names-wrong-type + "PT009", # pytest-unittest-assertion + "PT011", # pytest-raises-too-broad + "PT018", # pytest-composite-assertion + "PT023", # pytest-incorrect-mark-parentheses-style + "PTH100", # os-path-abspath + "PTH101", # os-chmod + "PTH102", # os-mkdir + "PTH103", # os-makedirs + "PTH104", # os-rename + "PTH106", # os-rmdir + "PTH107", # os-remove + "PTH108", # os-unlink + "PTH109", # os-getcwd + "PTH110", # os-path-exists + "PTH111", # os-path-expanduser + "PTH112", # os-path-isdir + "PTH113", # os-path-isfile + "PTH116", # os-stat + "PTH117", # os-path-isabs + "PTH118", # os-path-join + "PTH119", # os-path-basename + "PTH120", # os-path-dirname + "PTH122", # os-path-splitext + "PTH123", # builtin-open + "PTH202", # os-path-getsize + "PTH204", # os-path-getmtime + "PTH207", # glob + "RET50", # flake8-return (RET) + "RSE102", # unnecessary-paren-on-raise-exception + "RUF002", # ambiguous-unicode-character-docstring + "RUF003", # ambiguous-unicode-character-comment + "RUF005", # collection-literal-concatenation + "RUF012", # mutable-class-default + "RUF013", # unnecessary-iterable-allocation-for-first-element + "RUF015", # unnecessary-iterable-allocation-for-first-element + "RUF019", # unnecessary-key-check + "RUF021", # parenthesize-chained-operators + "RUF027", # missing-f-string-syntax + "RUF100", # unused-noqa + "S101", #assert + "S108", # hardcoded-temp-file + "S110", # try-except-pass + "S112", # try-except-continue + "S113", # request-without-timeout + "S202", # tarfile-unsafe-members + "S307", # suspicious-eval-usage + "S310", # suspicious-url-open-usage + "S311", # suspicious-non-cryptographic-random-usage + "S314", # suspicious-xml-element-tree-usage + "S324", # hashlib-insecure-hash-function + "S403", # suspicious-pickle-import + "S404", # suspicious-subprocess-import + "S405", # suspicious-xml-etree-import + "S406", # suspicious-xml-sax-import + "S602", # subprocess-popen-with-shell-equals-true + "S603", # subprocess-without-shell-equals-true + "S604", # call-with-shell-equals-true + "S606", # start-process-with-no-shell + "S607", # start-process-with-partial-path + "S608", # hardcoded-sql-expression + "SIM101", # duplicate-isinstance-call + "SIM102", # collapsible-if + "SIM103", # needless-bool + "SIM105", # suppressible-exception + "SIM108", # if-else-block-instead-of-if-exp + "SIM109", # compare-with-tuple + "SIM110", # reimplemented-builtin + "SIM113", # enumerate-for-loop + "SIM114", # if-with-same-arms + "SIM115", # open-file-with-context-handler + "SIM116", # if-else-block-instead-of-dict-lookup + "SIM117", # multiple-with-statements + "SIM118", # in-dict-keys + "SIM201", # negate-equal-op + "SIM210", # if-expr-with-true-false + "SIM211", # if-expr-with-false-true + "SIM223", # expr-and-false + "SIM300", # yoda-conditions + "SIM401", # if-else-block-instead-of-dict-get + "SLF001", # private-member-access + "TRY002", # raise-vanilla-class + "TRY003", # raise-vanilla-args + "TRY004", # type-check-without-type-error + "TRY201", # verbose-raise + "TRY300", # try-consider-else + "TRY301", # raise-within-try + "TRY302", # useless-try-except + "UP015", # redundant-open-modes + "UP018", # native-literals + "UP022", # replace-stdout-stderr + "UP030", # format-literals + "UP031", # printf-string-formatting + "UP032", # f-string + "UP034", # extraneous-parentheses + "UP036", # outdated-version-block + "W391", # too-many-newlines-at-end-of-file + "W605", # invalid-escape-sequence + "YTT204", # sys-version-info-minor-cmp-int +] + + +[tool.ruff.lint.per-file-ignores] +# See https://docs.astral.sh/ruff/settings/#lint_per-file-ignores +# "INT002", # f-string-in-get-text-func-call +# "INT001", # format-in-get-text-func-call +# "INT003", # printf-in-get-text-func-call +# Ignore `E402` (import violations) in all `__init__.py` files +"*/testsuite/**.py" = ["PT009", "PT027"] +"__init__.py" = ["E402"] +"general/g.parser/test.py" = ["INT003"] +"gui/wxpython/animation/dialogs.py" = ["INT002"] +"gui/wxpython/animation/temporal_manager.py" = ["INT003"] +"gui/wxpython/core/debug.py" = ["INT002"] +"gui/wxpython/core/render.py" = ["INT003"] +"gui/wxpython/gcp/manager.py" = ["INT002"] +"gui/wxpython/gmodeler/model.py" = ["INT001"] +"gui/wxpython/gmodeler/panels.py" = ["INT002", "INT003"] +"gui/wxpython/gui_core/ghelp.py" = ["INT003"] +"gui/wxpython/gui_core/gselect.py" = ["INT002"] +"gui/wxpython/gui_core/pyedit.py" = ["INT002"] +"gui/wxpython/gui_core/pystc.py" = ["INT002"] +"gui/wxpython/gui_core/query.py" = ["INT003"] +"gui/wxpython/history/browser.py" = ["INT002"] +"gui/wxpython/iclass/dialogs.py" = ["INT003"] +"gui/wxpython/iclass/frame.py" = ["FLY002", "INT003"] +"gui/wxpython/iclass/plots.py" = ["INT003"] +"gui/wxpython/image2target/ii2t_gis_set.py" = ["INT003"] +"gui/wxpython/iscatt/controllers.py" = ["INT003"] +"gui/wxpython/iscatt/dialogs.py" = ["INT003"] +"gui/wxpython/iscatt/frame.py" = ["INT003"] +"gui/wxpython/iscatt/iscatt_core.py" = ["INT003"] +"gui/wxpython/iscatt/plots.py" = ["PLW0108"] +"gui/wxpython/lmgr/frame.py" = ["INT003"] +"gui/wxpython/lmgr/workspace.py" = ["INT002"] +"gui/wxpython/location_wizard/dialogs.py" = ["INT003"] +"gui/wxpython/location_wizard/wizard.py" = ["INT003"] +"gui/wxpython/main_window/frame.py" = ["INT003"] +"gui/wxpython/mapdisp/frame.py" = ["INT003"] +"gui/wxpython/mapdisp/test_mapdisp.py" = ["INT003"] +"gui/wxpython/mapwin/analysis.py" = ["INT003"] +"gui/wxpython/psmap/utils.py" = ["PGH004"] +"gui/wxpython/rdigit/g.gui.rdigit.py" = ["INT002"] +"gui/wxpython/rlisetup/frame.py" = ["INT002"] +"gui/wxpython/rlisetup/functions.py" = ["INT003"] +"gui/wxpython/rlisetup/wizard.py" = ["INT003"] +"gui/wxpython/startup/locdownload.py" = ["INT002"] +"gui/wxpython/timeline/frame.py" = ["FLY002", "INT003"] +"gui/wxpython/tplot/frame.py" = ["FLY002", "INT002", "INT003"] +"gui/wxpython/vnet/vnet_data.py" = ["INT003"] +"gui/wxpython/web_services/dialogs.py" = ["INT003"] +"gui/wxpython/web_services/widgets.py" = ["INT003"] +"gui/wxpython/wxgui.py" = ["INT002"] +"gui/wxpython/wxplot/profile.py" = ["NPY001"] +"lib/init/grass.py" = ["INT003"] +"python/grass/__init__.py" = ["PYI056"] +"python/grass/gunittest/loader.py" = ["PYI024"] +"python/grass/gunittest/multireport.py" = ["PYI024"] +"python/grass/gunittest/testsuite/test_assertions_rast3d.py" = ["FLY002"] +"python/grass/jupyter/tests/reprojection_renderer_test.py" = ["PT013"] +"python/grass/jupyter/testsuite/interactivemap_test.py" = ["PGH004"] +"python/grass/jupyter/testsuite/map_test.py" = ["PGH004"] +"python/grass/pygrass/raster/__init__.py" = ["NPY002"] +"python/grass/pygrass/raster/category.py" = ["INT002"] +"python/grass/pygrass/raster/testsuite/test_numpy.py" = ["NPY002"] +"python/grass/pygrass/vector/__init__.py" = ["INT003"] +"python/grass/pygrass/vector/geometry.py" = ["PYI024"] +"python/grass/pygrass/vector/sql.py" = ["FLY002"] +"python/grass/pygrass/vector/testsuite/test_table.py" = ["NPY002", "PLW0108"] +"python/grass/pygrass/vector/testsuite/test_vector3d.py" = ["NPY002"] +"python/grass/script/raster.py" = ["INT003"] +"python/grass/temporal/abstract_space_time_dataset.py" = ["INT003"] +"python/grass/temporal/aggregation.py" = ["INT003"] +"python/grass/temporal/c_libraries_interface.py" = ["INT003"] +"python/grass/temporal/core.py" = ["INT002", "INT003"] +"python/grass/temporal/datetime_math.py" = ["INT003"] +"python/grass/temporal/mapcalc.py" = ["INT003"] +"python/grass/temporal/space_time_datasets.py" = ["INT003"] +"python/grass/temporal/stds_export.py" = ["INT003"] +"python/grass/temporal/stds_import.py" = ["INT003"] +"python/grass/temporal/temporal_algebra.py" = ["INT003"] +"python/grass/temporal/temporal_raster_base_algebra.py" = ["INT003"] +"python/grass/temporal/univar_statistics.py" = ["INT002"] +"raster3d/r3.flow/testsuite/r3flow_test.py" = ["FLY002"] +"raster3d/r3.gradient/testsuite/r3gradient_test.py" = ["FLY002"] +"scripts/d.polar/d.polar.py" = ["INT002"] +"scripts/g.extension.all/g.extension.all.py" = ["INT002"] +"scripts/g.extension/g.extension.py" = ["INT002"] +"scripts/i.oif/i.oif.py" = ["INT003"] +"scripts/i.pansharpen/i.pansharpen.py" = ["FLY002", "INT003"] +"scripts/i.spectral/i.spectral.py" = ["FLY002", "INT002"] +"scripts/r.in.srtm/r.in.srtm.py" = ["FLY002"] +"scripts/r.in.wms/wms_base.py" = ["INT003"] +"scripts/r.in.wms/wms_cap_parsers.py" = ["INT003"] +"scripts/r.in.wms/wms_drv.py" = ["INT003"] +"scripts/r.in.wms/wms_gdal_drv.py" = ["INT003"] +"scripts/r.pack/r.pack.py" = ["INT003"] +"scripts/r.tileset/r.tileset.py" = ["INT003"] +"scripts/r.unpack/r.unpack.py" = ["INT002"] +"scripts/v.rast.stats/v.rast.stats.py" = ["INT002"] +"scripts/v.to.lines/v.to.lines.py" = ["INT003"] +"scripts/v.unpack/v.unpack.py" = ["INT002", "INT003"] +"scripts/v.what.strds/v.what.strds.py" = ["INT003"] +"temporal/t.rast.accdetect/t.rast.accdetect.py" = ["INT003"] +"temporal/t.rast.accumulate/t.rast.accumulate.py" = ["INT003"] +"temporal/t.rast.algebra/testsu*/*_algebra_arithmetic.py" = ["FLY002"] +"temporal/t.rast.export/t.rast.export.py" = ["INT002"] +"temporal/t.rast.gapfill/t.rast.gapfill.py" = ["INT003"] +"temporal/t.rast.list/t.rast.list.py" = ["INT002"] +"temporal/t.rast.out.vtk/t.rast.out.vtk.py" = ["INT003"] +"temporal/t.rast.series/t.rast.series.py" = ["INT002"] +"temporal/t.rast.to.rast3/t.rast.to.rast3.py" = ["INT003"] +"temporal/t.rast.what/t.rast.what.py" = ["INT003"] +"temporal/t.register/testsu*/*_raster_different_local.py" = ["FLY002"] +"temporal/t.register/testsu*/*_raster_mapmetadata.py" = ["FLY002"] +"temporal/t.register/testsuite/test_t_register_raster.py" = ["FLY002"] +"temporal/t.register/testsuite/test_t_register_raster_file.py" = ["FLY002"] +"temporal/t.remove/t.remove.py" = ["INT002", "INT003"] +"temporal/t.unregister/t.unregister.py" = ["INT003"] +"temporal/t.vect.observe.strds/t.vect.observe.strds.py" = ["INT003"] +"utils/generate_release_notes.py" = ["PGH004"] +"utils/mkhtml.py" = ["INT002"] +"vector/v.fill.holes/examples.ipynb" = ["PTH201"] + +[tool.ruff.lint.flake8-import-conventions.extend-aliases] +# Declare a custom aliases, checked with rule ICN001 +"grass.script" = "gs" + [tool.pytest.ini_options] minversion = "6.0" python_files = "*/tests/*_test.py" @@ -28,5 +478,10 @@ markers = [ [tool.bandit] -exclude_dirs = ["./testsuite", "*/tests/*", "*/testsuite/*", "utils/test_generate_last_commit_file.py"] -skips = ["B324","B110", "B101", "B112", "B311", "B404", "B603"] +exclude_dirs = [ + "./testsuite", + "*/tests/*", + "*/testsuite/*", + "utils/test_generate_last_commit_file.py", +] +skips = ["B324", "B110", "B101", "B112", "B311", "B404", "B603"] From 5513912d6c6478cd14eb247a0ff3f434ac6f18fe Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Wed, 3 Jul 2024 08:03:55 -0400 Subject: [PATCH 03/75] CI(deps): Update docker/build-push-action action to v6.3.0 (#3976) --- .github/workflows/docker.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/docker.yml b/.github/workflows/docker.yml index 61942fa6df0..db9351e7e53 100644 --- a/.github/workflows/docker.yml +++ b/.github/workflows/docker.yml @@ -76,7 +76,7 @@ jobs: password: ${{ secrets.DOCKERHUB_TOKEN }} - name: Build and push id: docker_build - uses: docker/build-push-action@15560696de535e4014efeff63c48f16952e52dd1 # v6.2.0 + uses: docker/build-push-action@1a162644f9a7e87d8f4b053101d1d9a712edc18c # v6.3.0 with: push: true pull: true From 6424f9aa799bc8fdb4ef686ca29eee3d25ba5ed2 Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Wed, 3 Jul 2024 13:14:11 +0000 Subject: [PATCH 04/75] CI(deps): Update docker/setup-qemu-action action to v3.1.0 (#3977) --- .github/workflows/docker.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/docker.yml b/.github/workflows/docker.yml index db9351e7e53..53d27ccb901 100644 --- a/.github/workflows/docker.yml +++ b/.github/workflows/docker.yml @@ -66,7 +66,7 @@ jobs: latest=false suffix=-${{ matrix.os }} - name: Set up QEMU - uses: docker/setup-qemu-action@68827325e0b33c7199eb31dd4e31fbe9023e06e3 # v3.0.0 + uses: docker/setup-qemu-action@5927c834f5b4fdf503fca6f4c7eccda82949e1ee # v3.1.0 - name: Set up Docker Buildx uses: docker/setup-buildx-action@d70bba72b1f3fd22344832f00baa16ece964efeb # v3.3.0 - name: Login to DockerHub From 71ed433fe321fefe715da12ae54db4643548d244 Mon Sep 17 00:00:00 2001 From: Kriti Birda <164247895+kritibirda26@users.noreply.github.com> Date: Thu, 4 Jul 2024 00:28:09 +0530 Subject: [PATCH 05/75] r.univar: add JSON support (#3783) * Add JSON support to r.univar Use parson to add json output format support to the r.univar module. * Apply suggestions from code review --------- Co-authored-by: Nicklas Larsson --- raster/r.univar/Makefile | 4 +- raster/r.univar/globals.h | 6 +- raster/r.univar/r.univar.html | 38 ++++++ raster/r.univar/r.univar_main.c | 14 +- raster/r.univar/r3.univar_main.c | 14 +- raster/r.univar/stats.c | 149 +++++++++++++++++---- raster/r.univar/testsuite/test_r_univar.py | 70 +++++++++- 7 files changed, 260 insertions(+), 35 deletions(-) diff --git a/raster/r.univar/Makefile b/raster/r.univar/Makefile index f14d55967db..1513d3496a8 100644 --- a/raster/r.univar/Makefile +++ b/raster/r.univar/Makefile @@ -1,8 +1,8 @@ MODULE_TOPDIR = ../.. -LIBES2 = $(RASTERLIB) $(GISLIB) $(MATHLIB) $(OPENMP_LIBPATH) $(OPENMP_LIB) -LIBES3 = $(RASTER3DLIB) $(RASTERLIB) $(GISLIB) $(MATHLIB) $(OPENMP_LIBPATH) $(OPENMP_LIB) +LIBES2 = $(RASTERLIB) $(GISLIB) $(MATHLIB) $(OPENMP_LIBPATH) $(OPENMP_LIB) $(PARSONLIB) +LIBES3 = $(RASTER3DLIB) $(RASTERLIB) $(GISLIB) $(MATHLIB) $(OPENMP_LIBPATH) $(OPENMP_LIB) $(PARSONLIB) DEPENDENCIES = $(RASTER3DDEP) $(GISDEP) $(RASTERDEP) EXTRA_CFLAGS = $(OPENMP_CFLAGS) EXTRA_INC = $(OPENMP_INCPATH) diff --git a/raster/r.univar/globals.h b/raster/r.univar/globals.h index 38599361109..a2bbc184f4a 100644 --- a/raster/r.univar/globals.h +++ b/raster/r.univar/globals.h @@ -52,18 +52,20 @@ typedef struct { /* command line options are the same for raster and raster3d maps */ typedef struct { struct Option *inputfile, *zonefile, *percentile, *output_file, *separator, - *nprocs; + *nprocs, *format; struct Flag *shell_style, *extended, *table, *use_rast_region; } param_type; extern param_type param; extern zone_type zone_info; +enum OutputFormat { PLAIN, JSON }; + /* fn prototypes */ void heapsort_double(double *data, size_t n); void heapsort_float(float *data, size_t n); void heapsort_int(int *data, size_t n); -int print_stats(univar_stat *stats); +int print_stats(univar_stat *stats, enum OutputFormat format); int print_stats_table(univar_stat *stats); univar_stat *create_univar_stat_struct(int map_type, int n_perc); void free_univar_stat_struct(univar_stat *stats); diff --git a/raster/r.univar/r.univar.html b/raster/r.univar/r.univar.html index eaedaa0aae8..5220bc64a44 100644 --- a/raster/r.univar/r.univar.html +++ b/raster/r.univar/r.univar.html @@ -238,6 +238,44 @@

Zonal statistics

dataset) viewed through Libre/Open Office Calc. +

JSON Output

+
+r.univar -e elevation percentile=98 format=json
+
+will output the results in JSON format: + +
+[
+    {
+        "n": 2025000,
+        "null_cells": 0,
+        "cells": 2025000,
+        "min": 55.578792572021484,
+        "max": 156.32986450195312,
+        "range": 100.75107192993164,
+        "mean": 110.37544027560575,
+        "mean_of_abs": 110.37544027560575,
+        "stddev": 20.315323320598083,
+        "variance": 412.7123616204363,
+        "coeff_var": 18.40565552433679,
+        "sum": 223510266.55810165,
+        "first_quartile": 94.789985656738281,
+        "median": 108.87990570068359,
+        "third_quartile": 126.79196929931641,
+         "percentiles": [
+            {
+                "percentile": 98,
+                "value": 147.7265625
+            },
+            {
+                "percentile": 9,
+                "value": 83.494270324707031
+            }
+        ]
+    }
+]
+
+

TODO

To be implemented mode, skewness, kurtosis. diff --git a/raster/r.univar/r.univar_main.c b/raster/r.univar/r.univar_main.c index 3c070ca827d..84550a87347 100644 --- a/raster/r.univar/r.univar_main.c +++ b/raster/r.univar/r.univar_main.c @@ -110,6 +110,9 @@ void set_params(void) _("Table output format instead of standard output format"); param.table->guisection = _("Formatting"); + param.format = G_define_standard_option(G_OPT_F_FORMAT); + param.format->guisection = _("Print"); + param.use_rast_region = G_define_flag(); param.use_rast_region->key = 'r'; param.use_rast_region->description = @@ -140,6 +143,8 @@ int main(int argc, char *argv[]) const char *mapset, *name; int t; + enum OutputFormat format; + G_gisinit(argv[0]); module = G_define_module(); @@ -175,6 +180,13 @@ int main(int argc, char *argv[]) } } + if (strcmp(param.format->answer, "json") == 0) { + format = JSON; + } + else { + format = PLAIN; + } + /* set nprocs parameter */ int nprocs; sscanf(param.nprocs->answer, "%d", &nprocs); @@ -283,7 +295,7 @@ int main(int argc, char *argv[]) if (param.table->answer) print_stats_table(stats); else - print_stats(stats); + print_stats(stats, format); /* release memory */ free_univar_stat_struct(stats); diff --git a/raster/r.univar/r3.univar_main.c b/raster/r.univar/r3.univar_main.c index 5ad71240bbd..28fdb69acd5 100644 --- a/raster/r.univar/r3.univar_main.c +++ b/raster/r.univar/r3.univar_main.c @@ -66,6 +66,9 @@ void set_params(void) param.table->description = _("Table output format instead of standard output format"); + param.format = G_define_standard_option(G_OPT_F_FORMAT); + param.format->guisection = _("Print"); + return; } @@ -91,6 +94,8 @@ int main(int argc, char *argv[]) struct GModule *module; + enum OutputFormat format; + G_gisinit(argv[0]); module = G_define_module(); @@ -129,6 +134,13 @@ int main(int argc, char *argv[]) } } + if (strcmp(param.format->answer, "json") == 0) { + format = JSON; + } + else { + format = PLAIN; + } + /* table field separator */ zone_info.sep = G_option_to_separator(param.separator); @@ -318,7 +330,7 @@ int main(int argc, char *argv[]) if (param.table->answer) print_stats_table(stats); else - print_stats(stats); + print_stats(stats, format); /* release memory */ free_univar_stat_struct(stats); diff --git a/raster/r.univar/stats.c b/raster/r.univar/stats.c index efdcbe22f57..97367976103 100644 --- a/raster/r.univar/stats.c +++ b/raster/r.univar/stats.c @@ -11,6 +11,7 @@ * */ +#include #include "globals.h" /* *************************************************************** */ @@ -81,8 +82,20 @@ void free_univar_stat_struct(univar_stat *stats) /* *************************************************************** */ /* **** compute and print univar statistics to stdout ************ */ /* *************************************************************** */ -int print_stats(univar_stat *stats) +int print_stats(univar_stat *stats, enum OutputFormat format) { + JSON_Value *root_value, *zone_value; + JSON_Array *root_array; + JSON_Object *zone_object; + + if (format == JSON) { + root_value = json_value_init_array(); + if (root_value == NULL) { + G_fatal_error(_("Failed to initialize JSON array. Out of memory?")); + } + root_array = json_array(root_value); + } + int z, n_zones = zone_info.n_zones; if (n_zones == 0) @@ -117,7 +130,7 @@ int print_stats(univar_stat *stats) sprintf(sum_str, "%.15g", stats[z].sum); G_trim_decimal(sum_str); - if (!param.shell_style->answer) { + if (!param.shell_style->answer && format == PLAIN) { if (zone_info.n_zones) { int z_cat = z + zone_info.min; @@ -131,26 +144,61 @@ int print_stats(univar_stat *stats) fprintf(stdout, "Of the non-null cells:\n----------------------\n"); } - if (param.shell_style->answer) { + if (param.shell_style->answer || format == JSON) { + if (format == JSON) { + zone_value = json_value_init_object(); + zone_object = json_object(zone_value); + } if (zone_info.n_zones) { int z_cat = z + zone_info.min; - fprintf(stdout, "zone=%d;%s\n", z_cat, + switch (format) { + case PLAIN: + fprintf(stdout, "zone=%d;%s\n", z_cat, + Rast_get_c_cat(&z_cat, &(zone_info.cats))); + break; + case JSON: + json_object_set_number(zone_object, "zone_number", z_cat); + json_object_set_string( + zone_object, "zone_category", Rast_get_c_cat(&z_cat, &(zone_info.cats))); + break; + } + } + switch (format) { + case PLAIN: + fprintf(stdout, "n=%lu\n", stats[z].n); + fprintf(stdout, "null_cells=%lu\n", stats[z].size - stats[z].n); + fprintf(stdout, "cells=%lu\n", stats[z].size); + fprintf(stdout, "min=%.15g\n", stats[z].min); + fprintf(stdout, "max=%.15g\n", stats[z].max); + fprintf(stdout, "range=%.15g\n", stats[z].max - stats[z].min); + fprintf(stdout, "mean=%.15g\n", mean); + fprintf(stdout, "mean_of_abs=%.15g\n", + stats[z].sum_abs / stats[z].n); + fprintf(stdout, "stddev=%.15g\n", stdev); + fprintf(stdout, "variance=%.15g\n", variance); + fprintf(stdout, "coeff_var=%.15g\n", var_coef); + fprintf(stdout, "sum=%s\n", sum_str); + break; + case JSON: + json_object_set_number(zone_object, "n", stats[z].n); + json_object_set_number(zone_object, "null_cells", + stats[z].size - stats[z].n); + json_object_set_number(zone_object, "cells", stats[z].size); + json_object_set_number(zone_object, "min", stats[z].min); + json_object_set_number(zone_object, "max", stats[z].max); + json_object_set_number(zone_object, "range", + stats[z].max - stats[z].min); + json_object_set_number(zone_object, "mean", mean); + json_object_set_number(zone_object, "mean_of_abs", + stats[z].sum_abs / stats[z].n); + json_object_set_number(zone_object, "stddev", stdev); + json_object_set_number(zone_object, "variance", variance); + json_object_set_number(zone_object, "coeff_var", var_coef); + json_object_set_number(zone_object, "sum", stats[z].sum); + break; } - fprintf(stdout, "n=%lu\n", stats[z].n); - fprintf(stdout, "null_cells=%lu\n", stats[z].size - stats[z].n); - fprintf(stdout, "cells=%lu\n", stats[z].size); - fprintf(stdout, "min=%.15g\n", stats[z].min); - fprintf(stdout, "max=%.15g\n", stats[z].max); - fprintf(stdout, "range=%.15g\n", stats[z].max - stats[z].min); - fprintf(stdout, "mean=%.15g\n", mean); - fprintf(stdout, "mean_of_abs=%.15g\n", - stats[z].sum_abs / stats[z].n); - fprintf(stdout, "stddev=%.15g\n", stdev); - fprintf(stdout, "variance=%.15g\n", variance); - fprintf(stdout, "coeff_var=%.15g\n", var_coef); - fprintf(stdout, "sum=%s\n", sum_str); } else { fprintf(stdout, "n: %lu\n", stats[z].n); @@ -244,17 +292,57 @@ int print_stats(univar_stat *stats) } } - if (param.shell_style->answer) { - fprintf(stdout, "first_quartile=%g\n", quartile_25); - fprintf(stdout, "median=%g\n", median); - fprintf(stdout, "third_quartile=%g\n", quartile_75); + if (param.shell_style->answer || format == JSON) { + switch (format) { + case PLAIN: + fprintf(stdout, "first_quartile=%g\n", quartile_25); + fprintf(stdout, "median=%g\n", median); + fprintf(stdout, "third_quartile=%g\n", quartile_75); + break; + case JSON: + json_object_set_number(zone_object, "first_quartile", + quartile_25); + json_object_set_number(zone_object, "median", median); + json_object_set_number(zone_object, "third_quartile", + quartile_75); + break; + } + + JSON_Value *percentiles_array_value, *percentile_value; + JSON_Array *percentiles_array; + JSON_Object *percentile_object; + + if (format == JSON) { + percentiles_array_value = json_value_init_array(); + percentiles_array = json_array(percentiles_array_value); + } + for (i = 0; i < stats[z].n_perc; i++) { char buf[24]; - sprintf(buf, "%.15g", stats[z].perc[i]); + snprintf(buf, sizeof(buf), "%.15g", stats[z].perc[i]); G_strchg(buf, '.', '_'); - fprintf(stdout, "percentile_%s=%g\n", buf, - quartile_perc[i]); + switch (format) { + case PLAIN: + fprintf(stdout, "percentile_%s=%g\n", buf, + quartile_perc[i]); + break; + case JSON: + percentile_value = json_value_init_object(); + percentile_object = json_object(percentile_value); + json_object_set_number(percentile_object, "percentile", + stats[z].perc[i]); + json_object_set_number(percentile_object, "value", + quartile_perc[i]); + json_array_append_value(percentiles_array, + percentile_value); + break; + } + } + + if (format == JSON) { + json_object_set_value(zone_object, "percentiles", + percentiles_array_value); } } else { @@ -301,6 +389,19 @@ int print_stats(univar_stat *stats) * above with zone */ /* if (!(param.shell_style->answer)) G_message("\n"); */ + if (format == JSON) { + json_array_append_value(root_array, zone_value); + } + } + + if (format == JSON) { + char *serialized_string = json_serialize_to_string_pretty(root_value); + if (serialized_string == NULL) { + G_fatal_error(_("Failed to initialize pretty JSON string.")); + } + puts(serialized_string); + json_free_serialized_string(serialized_string); + json_value_free(root_value); } return 1; diff --git a/raster/r.univar/testsuite/test_r_univar.py b/raster/r.univar/testsuite/test_r_univar.py index c03aea5dcfa..de28f0753d5 100644 --- a/raster/r.univar/testsuite/test_r_univar.py +++ b/raster/r.univar/testsuite/test_r_univar.py @@ -3,8 +3,13 @@ @author Soeren Gebbert """ +import json +from itertools import zip_longest + from grass.gunittest.case import TestCase +from grass.gunittest.gmodules import SimpleModule + class TestRasterUnivar(TestCase): @classmethod @@ -562,11 +567,66 @@ def test_zone_with_gap_in_cats(self): sep="=", ) - -class TestAccumulateFails(TestCase): - def test_error_handling(self): - # No vector map, no strds, no coordinates - self.assertModuleFail("r.univar", flags="r", map="map_a", zones="map_b") + def test_json(self): + reference = [ + { + "zone_number": 1, + "zone_category": "", + "n": 3420, + "null_cells": 0, + "cells": 3420, + "min": 102, + "max": 309, + "range": 207, + "mean": 205.5, + "mean_of_abs": 205.5, + "stddev": 56.611983419296187, + "variance": 3204.9166666666665, + "coeff_var": 27.548410423015174, + "sum": 702810, + "first_quartile": 155, + "median": 205.5, + "percentiles": [{"percentile": 90, "value": 282}], + "third_quartile": 255, + }, + { + "zone_number": 2, + "zone_category": "", + "n": 12780, + "null_cells": 0, + "cells": 12780, + "min": 121, + "max": 380, + "range": 259, + "mean": 250.5, + "mean_of_abs": 250.5, + "stddev": 59.957623924457401, + "variance": 3594.9166666666665, + "coeff_var": 23.935179211360243, + "sum": 3201390, + "first_quartile": 200, + "median": 250.5, + "percentiles": [{"percentile": 90, "value": 330}], + "third_quartile": 300, + }, + ] + + module = SimpleModule( + "r.univar", + map=["map_a", "map_b"], + zones="zone_map", + flags="ge", + format="json", + ) + self.runModule(module) + output = json.loads(module.outputs.stdout) + for expected, received in zip_longest(reference, output): + self.assertCountEqual(list(expected.keys()), list(received.keys())) + for key in expected: + if isinstance(expected[key], float): + self.assertAlmostEqual(expected[key], received[key], places=6) + else: + self.assertEqual(expected[key], received[key]) if __name__ == "__main__": From cc752697505e277c2a15f8a1e7e68f3f16b13be7 Mon Sep 17 00:00:00 2001 From: Kriti Birda <164247895+kritibirda26@users.noreply.github.com> Date: Thu, 4 Jul 2024 00:35:29 +0530 Subject: [PATCH 06/75] v.univar: add JSON support (#3784) * Add JSON support to v.univar Use parson to add json output format support to the v.univar module. * update percentile format * rename test file --- vector/v.univar/Makefile | 2 +- vector/v.univar/main.c | 92 ++++++++++++++++++- .../{v_univar_test.py => test_v_univar.py} | 44 +++++++++ vector/v.univar/v.univar.html | 35 +++++++ 4 files changed, 169 insertions(+), 4 deletions(-) rename vector/v.univar/testsuite/{v_univar_test.py => test_v_univar.py} (69%) diff --git a/vector/v.univar/Makefile b/vector/v.univar/Makefile index 2c450d3bc44..c2279a5061a 100644 --- a/vector/v.univar/Makefile +++ b/vector/v.univar/Makefile @@ -3,7 +3,7 @@ MODULE_TOPDIR = ../.. PGM=v.univar -LIBES = $(VECTORLIB) $(DBMILIB) $(GISLIB) $(MATHLIB) +LIBES = $(VECTORLIB) $(DBMILIB) $(GISLIB) $(MATHLIB) $(PARSONLIB) DEPENDENCIES = $(VECTORDEP) $(DBMIDEP) $(GISDEP) EXTRA_INC = $(VECT_INC) EXTRA_CFLAGS = $(VECT_CFLAGS) diff --git a/vector/v.univar/main.c b/vector/v.univar/main.c index 149935e14e5..f84bf118fab 100644 --- a/vector/v.univar/main.c +++ b/vector/v.univar/main.c @@ -43,11 +43,14 @@ #include #include #include +#include static void select_from_geometry(void); static void select_from_database(void); static void summary(void); +enum OutputFormat { PLAIN, JSON }; + struct Option *field_opt, *where_opt, *col_opt; struct Flag *shell_flag, *ext_flag, *weight_flag, *geometry; struct Map_info Map; @@ -80,10 +83,12 @@ double total_size = 0.0; /* total size: length/area */ /* Extended statistics */ int perc; +enum OutputFormat format; + int main(int argc, char *argv[]) { struct GModule *module; - struct Option *map_opt, *type_opt, *percentile; + struct Option *map_opt, *type_opt, *percentile, *format_opt; module = G_define_module(); G_add_keyword(_("vector")); @@ -136,6 +141,9 @@ int main(int argc, char *argv[]) geometry->description = _("Calculate geometric distances instead of attribute statistics"); + format_opt = G_define_standard_option(G_OPT_F_FORMAT); + format_opt->guisection = _("Print"); + G_gisinit(argv[0]); if (G_parser(argc, argv)) @@ -147,6 +155,13 @@ int main(int argc, char *argv[]) col_opt->key, col_opt->description); } + if (strcmp(format_opt->answer, "json") == 0) { + format = JSON; + } + else { + format = PLAIN; + } + otype = Vect_option_to_types(type_opt); perc = atoi(percentile->answer); @@ -546,6 +561,9 @@ void select_from_database(void) void summary(void) { + JSON_Value *root_value; + JSON_Object *root_object; + if (compatible) { if (!geometry->answer && weight_flag->answer) { mean = sum / total_size; @@ -582,7 +600,49 @@ void summary(void) G_debug(3, "otype %d:", otype); - if (shell_flag->answer) { + if (format == JSON) { + root_value = json_value_init_object(); + if (root_value == NULL) { + G_fatal_error( + _("Failed to initialize JSON object. Out of memory?")); + } + root_object = json_object(root_value); + + json_object_set_number(root_object, "n", count); + if (geometry->answer) { + json_object_set_number(root_object, "nzero", nzero); + } + else { + json_object_set_number(root_object, "missing", nmissing); + json_object_set_number(root_object, "nnull", nnull); + } + if (count > 0) { + json_object_set_number(root_object, "min", min); + json_object_set_number(root_object, "max", max); + json_object_set_number(root_object, "range", max - min); + json_object_set_number(root_object, "sum", sum); + if (compatible) { + json_object_set_number(root_object, "mean", mean); + json_object_set_number(root_object, "mean_abs", mean_abs); + if (geometry->answer || !weight_flag->answer) { + json_object_set_number(root_object, "population_stddev", + pop_stdev); + json_object_set_number(root_object, "population_variance", + pop_variance); + json_object_set_number(root_object, + "population_coeff_variation", + pop_coeff_variation); + json_object_set_number(root_object, "sample_stddev", + sample_stdev); + json_object_set_number(root_object, "sample_variance", + sample_variance); + json_object_set_number(root_object, "kurtosis", kurtosis); + json_object_set_number(root_object, "skewness", skewness); + } + } + } + } + else if (shell_flag->answer) { fprintf(stdout, "n=%d\n", count); if (geometry->answer) { fprintf(stdout, "nzero=%d\n", nzero); @@ -688,7 +748,23 @@ void summary(void) quartile_perc = (Cvarr.value[qpos_perc]).val.d; } - if (shell_flag->answer) { + if (format == JSON) { + json_object_set_number(root_object, "first_quartile", quartile_25); + json_object_set_number(root_object, "median", median); + json_object_set_number(root_object, "third_quartile", quartile_75); + + JSON_Value *percentiles_array_value = json_value_init_array(); + JSON_Array *percentiles_array = json_array(percentiles_array_value); + JSON_Value *percentile_value = json_value_init_object(); + JSON_Object *percentile_object = json_object(percentile_value); + + json_object_set_number(percentile_object, "percentile", perc); + json_object_set_number(percentile_object, "value", quartile_perc); + json_array_append_value(percentiles_array, percentile_value); + json_object_set_value(root_object, "percentiles", + percentiles_array_value); + } + else if (shell_flag->answer) { fprintf(stdout, "first_quartile=%g\n", quartile_25); fprintf(stdout, "median=%g\n", median); fprintf(stdout, "third_quartile=%g\n", quartile_75); @@ -712,4 +788,14 @@ void summary(void) fprintf(stdout, "%dth percentile: %g\n", perc, quartile_perc); } } + + if (format == JSON) { + char *serialized_string = json_serialize_to_string_pretty(root_value); + if (serialized_string == NULL) { + G_fatal_error(_("Failed to initialize pretty JSON string.")); + } + puts(serialized_string); + json_free_serialized_string(serialized_string); + json_value_free(root_value); + } } diff --git a/vector/v.univar/testsuite/v_univar_test.py b/vector/v.univar/testsuite/test_v_univar.py similarity index 69% rename from vector/v.univar/testsuite/v_univar_test.py rename to vector/v.univar/testsuite/test_v_univar.py index 33fd0425c1d..166d47a5350 100644 --- a/vector/v.univar/testsuite/v_univar_test.py +++ b/vector/v.univar/testsuite/test_v_univar.py @@ -9,6 +9,9 @@ for details. """ +import json +from itertools import zip_longest + from grass.gunittest.case import TestCase from grass.gunittest.main import test from grass.gunittest.gmodules import SimpleModule @@ -126,6 +129,47 @@ def test_output2(self): map="roadsmajor", column="MAJORRDS_", reference=univar_string, precision=3 ) + def test_json(self): + """Testing output in JSON fomrat""" + module = SimpleModule( + "v.univar", map="geology", column="PERIMETER", flags="e", format="json" + ) + self.runModule(module) + + expected = { + "n": 1832, + "missing": 0, + "nnull": 0, + "min": 166.946991, + "max": 2729482.25, + "range": 2729315.3030090001, + "sum": 78876146.145385057, + "mean": 43054.664926520229, + "mean_abs": 43054.664926520229, + "population_stddev": 132689.08650029532, + "population_variance": 17606393676.282852, + "population_coeff_variation": 3.0818747916573215, + "sample_stddev": 132725.31560308655, + "sample_variance": 17616009401.938931, + "kurtosis": 139.15698418811229, + "skewness": 9.7065048189730767, + "first_quartile": 3699.3234859999998, + "median": 10308.4453125, + "third_quartile": 29259.074218999998, + "percentiles": [{"percentile": 90, "value": 86449.734375}], + } + results = json.loads(module.outputs.stdout) + + expected_percentiles = expected.pop("percentiles") + result_percentiles = results.pop("percentiles") + for p1, p2 in zip_longest(expected_percentiles, result_percentiles): + self.assertEqual(p1["percentile"], p2["percentile"]) + self.assertAlmostEqual(p1["value"], p2["value"]) + + self.assertCountEqual(list(expected.keys()), list(results.keys())) + for key in expected: + self.assertAlmostEqual(expected[key], results[key]) + if __name__ == "__main__": test() diff --git a/vector/v.univar/v.univar.html b/vector/v.univar/v.univar.html index dfc2a98ad26..ee9c6f77582 100644 --- a/vector/v.univar/v.univar.html +++ b/vector/v.univar/v.univar.html @@ -121,6 +121,41 @@

Calculate statistic of distance between sampling points

skewness: 0.238688 +

Output in JSON format

+
+v.univar -e samples column=heights type=point format=json
+
+will output the results in JSON format: +
+{
+    "n": 1832,
+    "missing": 0,
+    "nnull": 0,
+    "min": 166.946991,
+    "max": 2729482.25,
+    "range": 2729315.3030090001,
+    "sum": 78876146.145385057,
+    "mean": 43054.664926520229,
+    "mean_abs": 43054.664926520229,
+    "population_stddev": 132689.08650029532,
+    "population_variance": 17606393676.282852,
+    "population_coeff_variation": 3.0818747916573215,
+    "sample_stddev": 132725.31560308655,
+    "sample_variance": 17616009401.938931,
+    "kurtosis": 139.15698418811229,
+    "skewness": 9.7065048189730767,
+    "first_quartile": 3699.3234859999998,
+    "median": 10308.4453125,
+    "third_quartile": 29259.074218999998,
+    "percentiles": [
+        {
+            "percentile": 90,
+            "value": 86449.734375
+        }
+    ]
+}
+
+

SEE ALSO

From 56eaf9ebe053f9bd787107a6f99c7467c90056a2 Mon Sep 17 00:00:00 2001 From: ShubhamDesai <42180509+ShubhamDesai@users.noreply.github.com> Date: Wed, 3 Jul 2024 18:53:55 -0400 Subject: [PATCH 07/75] d.labels: Reduce scope of minreg and maxreg variables in main.c (#3979) Reduce scope of minreg and maxreg variables in d.labels/main.c Co-authored-by: Shubham Vasudeo Desai --- display/d.labels/main.c | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/display/d.labels/main.c b/display/d.labels/main.c index 75dfed09fd0..301469710f7 100644 --- a/display/d.labels/main.c +++ b/display/d.labels/main.c @@ -28,7 +28,7 @@ int main(int argc, char **argv) struct Cell_head window; char *label_name; const char *mapset; - double minreg, maxreg, reg, dx, dy; + double reg, dx, dy; FILE *infile; struct Option *opt1; struct Option *maxreg_opt, *minreg_opt; @@ -91,7 +91,7 @@ int main(int argc, char **argv) dy = window.north - window.south; reg = sqrt(dx * dx + dy * dy); if (minreg_opt->answer) { - minreg = atof(minreg_opt->answer); + double minreg = atof(minreg_opt->answer); if (reg < minreg) { G_warning( _("Region size is lower than minreg, nothing displayed.")); @@ -100,7 +100,7 @@ int main(int argc, char **argv) } } if (maxreg_opt->answer) { - maxreg = atof(maxreg_opt->answer); + double maxreg = atof(maxreg_opt->answer); if (reg > maxreg) { G_warning( _("Region size is greater than maxreg, nothing displayed.")); From 66c4df0988b7755c5a729d783ef30309f1f46d02 Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Thu, 4 Jul 2024 11:48:14 +0000 Subject: [PATCH 08/75] CI(deps): Update docker/setup-buildx-action action to v3.4.0 (#3982) --- .github/workflows/docker.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/docker.yml b/.github/workflows/docker.yml index 53d27ccb901..a10ec7545a0 100644 --- a/.github/workflows/docker.yml +++ b/.github/workflows/docker.yml @@ -68,7 +68,7 @@ jobs: - name: Set up QEMU uses: docker/setup-qemu-action@5927c834f5b4fdf503fca6f4c7eccda82949e1ee # v3.1.0 - name: Set up Docker Buildx - uses: docker/setup-buildx-action@d70bba72b1f3fd22344832f00baa16ece964efeb # v3.3.0 + uses: docker/setup-buildx-action@4fd812986e6c8c2a69e18311145f9371337f27d4 # v3.4.0 - name: Login to DockerHub uses: docker/login-action@0d4c9c5ea7693da7b068278f7b52bda2a190a446 # v3.2.0 with: From 79726a09e7efcf3bedda7b6f7e0fcdee1dfb9d7c Mon Sep 17 00:00:00 2001 From: ShubhamDesai <42180509+ShubhamDesai@users.noreply.github.com> Date: Thu, 4 Jul 2024 12:40:28 -0400 Subject: [PATCH 09/75] d.legend.vect: Reduce scope of 'bg_w' variable in draw.c (#3980) Reduce scope of 'bg_w' variable in d.legend.vect/draw.c Co-authored-by: Shubham Vasudeo Desai --- display/d.legend.vect/draw.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/display/d.legend.vect/draw.c b/display/d.legend.vect/draw.c index 6f23c0f4924..3de72c7f2a9 100644 --- a/display/d.legend.vect/draw.c +++ b/display/d.legend.vect/draw.c @@ -43,7 +43,7 @@ void draw(char *file_name, double LL, double LT, char *title, int cols, double symb_h, symb_w, def_symb_h, def_symb_w; int item_count, item; double it_per_col; - double margin, bg_h, bg_w; + double margin, bg_h; char **tokens; D_get_src(&dt, &db, &dl, &dr); @@ -264,7 +264,7 @@ void draw(char *file_name, double LL, double LT, char *title, int cols, /* Draw background */ if (do_bg) { double x0bg, y0bg, x1bg, y1bg; - + double bg_w; if (title_w > offs_x + maxlblw) bg_w = title_w; else From cb1e9b351494d45d941e4a68b87ecea0fc2d70b7 Mon Sep 17 00:00:00 2001 From: ShubhamDesai <42180509+ShubhamDesai@users.noreply.github.com> Date: Thu, 4 Jul 2024 12:40:46 -0400 Subject: [PATCH 10/75] lib: Fix uninitialized variable 'encoding' in parser_interface.c (#3975) Fix uninitialized variable 'encoding' in parser_interface.c Co-authored-by: Shubham Vasudeo Desai --- lib/gis/parser_interface.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/gis/parser_interface.c b/lib/gis/parser_interface.c index 735d925ff3c..d2c35fc96ab 100644 --- a/lib/gis/parser_interface.c +++ b/lib/gis/parser_interface.c @@ -107,7 +107,7 @@ void G__usage_xml(void) char *type; char *s, *top; int i; - const char *encoding; + const char *encoding = NULL; int new_prompt = 0; new_prompt = G__uses_new_gisprompt(); From 931e79ac75f5656a5e2df149b051975846b7748a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Edouard=20Choini=C3=A8re?= <27212526+echoix@users.noreply.github.com> Date: Thu, 4 Jul 2024 16:03:54 -0400 Subject: [PATCH 11/75] CI(ruff): Fine tune posting Ruff suggestions (#3978) * CI(ruff): Fix typo in ruff suggestions * CI(ruff): Upload suggestions even if not all linting errors were fixed * CI(ruff): Try suggesting more changes * CI(ruff): Upload suggestions even if not all linting errors were fixed but do not run when cancelled --- .github/workflows/post-pr-reviews.yml | 2 +- .github/workflows/python-code-quality.yml | 4 +++- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/.github/workflows/post-pr-reviews.yml b/.github/workflows/post-pr-reviews.yml index e35d58be50e..00f7c5f828e 100644 --- a/.github/workflows/post-pr-reviews.yml +++ b/.github/workflows/post-pr-reviews.yml @@ -85,7 +85,7 @@ jobs: CI_REPO_NAME: ${{ github.event.workflow_run.repository.name }} # CI_PULL_REQUEST: "" # Populated from reviewdog's "-guess" flag since hard to get - name: Post Ruff suggestions - if: ${{ steps.tools.outputs.black == 'true' }} + if: ${{ steps.tools.outputs.ruff == 'true' }} run: | TMPFILE="diff-${INPUT_TOOL_NAME}.patch" GITHUB_ACTIONS="" reviewdog \ diff --git a/.github/workflows/python-code-quality.yml b/.github/workflows/python-code-quality.yml index 9565c32eaea..1f28d13b5d8 100644 --- a/.github/workflows/python-code-quality.yml +++ b/.github/workflows/python-code-quality.yml @@ -67,10 +67,12 @@ jobs: - name: Install Ruff run: pip install ruff==${{ env.RUFF_VERSION }} - name: Run Ruff - run: ruff check --output-format=github . --preview --fix + run: ruff check --output-format=github . --preview --fix --unsafe-fixes - name: Create and uploads code suggestions to apply for Ruff # Will fail fast here if there are changes required id: diff-ruff + # To run after ruff step exits with failure when rules don't have fixes available + if: ${{ !cancelled() }} uses: ./.github/actions/create-upload-suggestions with: tool-name: ruff From d880ec0a6d88ce64a10f18c7d3e8701bf8e8972f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Edouard=20Choini=C3=A8re?= <27212526+echoix@users.noreply.github.com> Date: Thu, 4 Jul 2024 18:40:36 -0400 Subject: [PATCH 12/75] style: Fix unconventional-import-alias (ICN001) (consolidate `import grass.script as gs`) (#3981) * style: Unignore unconventional-import-alias (ICN001) ruff rule * style: Use convention `import matplotlib as mpl` * style: Use convention `import numpy as np` * style: Use convention `import grass.script as gs` * test: Remove unused grass.script in test file * style: Add missing alias to `import grass.script as gs` * style: Alias `import grass.script as gs` when already imported at file-level * Remove duplicated grass.script lazy import in wxpython/gui_core/ghelp.py --- gui/wxpython/animation/frame.py | 6 +- gui/wxpython/animation/g.gui.animation.py | 6 +- gui/wxpython/animation/temporal_manager.py | 124 +++++----- gui/wxpython/animation/utils.py | 4 +- gui/wxpython/core/debug.py | 4 +- gui/wxpython/core/gconsole.py | 12 +- gui/wxpython/core/giface.py | 12 +- gui/wxpython/datacatalog/g.gui.datacatalog.py | 4 +- gui/wxpython/datacatalog/tree.py | 50 ++--- gui/wxpython/dbmgr/base.py | 18 +- gui/wxpython/dbmgr/g.gui.dbmgr.py | 12 +- gui/wxpython/dbmgr/sqlbuilder.py | 8 +- gui/wxpython/dbmgr/vinfo.py | 6 +- gui/wxpython/gcp/g.gui.gcp.py | 4 +- gui/wxpython/gcp/manager.py | 14 +- gui/wxpython/gmodeler/g.gui.gmodeler.py | 4 +- gui/wxpython/gui_core/ghelp.py | 13 +- gui/wxpython/gui_core/gselect.py | 70 +++--- gui/wxpython/gui_core/preferences.py | 20 +- gui/wxpython/gui_core/pyedit.py | 6 +- gui/wxpython/gui_core/vselect.py | 8 +- gui/wxpython/iclass/dialogs.py | 12 +- gui/wxpython/iclass/digit.py | 4 +- gui/wxpython/iclass/frame.py | 12 +- gui/wxpython/iclass/g.gui.iclass.py | 28 +-- gui/wxpython/iclass/statistics.py | 8 +- gui/wxpython/iclass/toolbars.py | 4 +- .../image2target/g.gui.image2target.py | 4 +- gui/wxpython/image2target/ii2t_manager.py | 8 +- gui/wxpython/iscatt/controllers.py | 8 +- gui/wxpython/iscatt/dialogs.py | 6 +- gui/wxpython/iscatt/iscatt_core.py | 14 +- gui/wxpython/iscatt/plots.py | 16 +- gui/wxpython/lmgr/pyshell.py | 8 +- gui/wxpython/location_wizard/dialogs.py | 4 +- gui/wxpython/mapdisp/frame.py | 26 +-- gui/wxpython/mapdisp/test_mapdisp.py | 10 +- gui/wxpython/mapswipe/frame.py | 30 +-- gui/wxpython/mapswipe/g.gui.mapswipe.py | 8 +- gui/wxpython/mapwin/buffered.py | 10 +- gui/wxpython/modules/colorrules.py | 32 +-- gui/wxpython/modules/mcalc_builder.py | 6 +- gui/wxpython/nviz/mapwindow.py | 33 ++- gui/wxpython/nviz/tools.py | 6 +- gui/wxpython/nviz/wxnviz.py | 4 +- gui/wxpython/photo2image/g.gui.photo2image.py | 14 +- gui/wxpython/photo2image/ip2i_manager.py | 8 +- gui/wxpython/psmap/dialogs.py | 32 +-- gui/wxpython/psmap/frame.py | 40 ++-- gui/wxpython/psmap/g.gui.psmap.py | 4 +- gui/wxpython/psmap/instructions.py | 36 +-- gui/wxpython/psmap/utils.py | 48 ++-- gui/wxpython/rlisetup/g.gui.rlisetup.py | 4 +- gui/wxpython/timeline/frame.py | 12 +- gui/wxpython/timeline/g.gui.timeline.py | 6 +- gui/wxpython/tplot/frame.py | 16 +- gui/wxpython/tplot/g.gui.tplot.py | 16 +- gui/wxpython/vdigit/g.gui.vdigit.py | 22 +- gui/wxpython/vdigit/toolbars.py | 11 +- gui/wxpython/web_services/dialogs.py | 16 +- gui/wxpython/web_services/widgets.py | 6 +- gui/wxpython/wxplot/base.py | 16 +- gui/wxpython/wxplot/histogram.py | 4 +- gui/wxpython/wxplot/profile.py | 28 +-- gui/wxpython/wxplot/scatter.py | 6 +- .../test_imagery_signature_management.py | 14 +- pyproject.toml | 1 - python/grass/benchmark/plots.py | 4 +- python/grass/gunittest/multireport.py | 4 +- python/grass/gunittest/reporters.py | 4 +- python/grass/imaging/images2avi.py | 10 +- python/grass/pygrass/gis/region.py | 4 +- python/grass/pygrass/tests/benchmark.py | 18 +- python/grass/script/array.py | 22 +- python/grass/temporal/aggregation.py | 18 +- python/grass/temporal/core.py | 18 +- python/grass/temporal/extract.py | 26 +-- python/grass/temporal/gui_support.py | 8 +- python/grass/temporal/mapcalc.py | 22 +- python/grass/temporal/stds_export.py | 42 ++-- python/grass/temporal/stds_import.py | 124 +++++----- .../testsuite/test_register_function.py | 6 +- .../unittests_temporal_algebra_grs.py | 1 - .../unittests_temporal_algebra_mixed_stds.py | 1 - .../unittests_temporal_conditionals.py | 1 - .../unittests_temporal_raster3d_algebra.py | 4 +- raster/r.solute.transport/seguin_verify.py | 72 +++--- .../r.solute.transport/seguin_verify_well.py | 70 +++--- scripts/d.rast.edit/d.rast.edit.py | 56 ++--- scripts/d.rast.leg/d.rast.leg.py | 28 ++- scripts/db.dropcolumn/db.dropcolumn.py | 31 ++- scripts/db.droptable/db.droptable.py | 30 +-- scripts/db.in.ogr/db.in.ogr.py | 48 ++-- scripts/db.univar/db.univar.py | 38 ++-- scripts/g.extension.all/g.extension.all.py | 46 ++-- scripts/i.colors.enhance/i.colors.enhance.py | 52 ++--- scripts/i.image.mosaic/i.image.mosaic.py | 24 +- scripts/i.in.spotvgt/i.in.spotvgt.py | 82 +++---- scripts/i.pansharpen/i.pansharpen.py | 212 +++++++++--------- scripts/i.tasscap/i.tasscap.py | 26 +-- scripts/r.blend/r.blend.py | 44 ++-- scripts/r.buffer.lowmem/r.buffer.lowmem.py | 38 ++-- scripts/r.colors.stddev/r.colors.stddev.py | 22 +- scripts/r.fillnulls/r.fillnulls.py | 188 ++++++++-------- scripts/r.grow/r.grow.py | 32 +-- scripts/r.import/r.import.py | 142 ++++++------ scripts/r.in.aster/r.in.aster.py | 34 +-- scripts/r.in.srtm/r.in.srtm.py | 44 ++-- scripts/r.in.wms/r.in.wms.py | 24 +- scripts/r.in.wms/wms_base.py | 148 ++++++------ scripts/r.in.wms/wms_cap_parsers.py | 34 +-- scripts/r.in.wms/wms_drv.py | 76 +++---- scripts/r.in.wms/wms_gdal_drv.py | 22 +- scripts/r.mask/r.mask.py | 70 +++--- scripts/r.plane/r.plane.py | 24 +- scripts/r.reclass.area/r.reclass.area.py | 76 +++---- scripts/r.rgb/r.rgb.py | 14 +- scripts/v.centroids/v.centroids.py | 10 +- scripts/v.clip/v.clip.py | 30 ++- scripts/v.db.addcolumn/v.db.addcolumn.py | 38 ++-- scripts/v.db.addtable/v.db.addtable.py | 54 +++-- scripts/v.db.dropcolumn/v.db.dropcolumn.py | 28 +-- scripts/v.db.droprow/v.db.droprow.py | 8 +- scripts/v.db.droptable/v.db.droptable.py | 40 ++-- .../v.db.reconnect.all/v.db.reconnect.all.py | 58 ++--- .../v.db.renamecolumn/v.db.renamecolumn.py | 34 +-- scripts/v.db.univar/v.db.univar.py | 16 +- scripts/v.db.update/v.db.update.py | 32 +-- scripts/v.import/v.import.py | 94 ++++---- scripts/v.in.geonames/v.in.geonames.py | 22 +- scripts/v.rast.stats/v.rast.stats.py | 82 ++++--- scripts/v.report/v.report.py | 26 +-- scripts/v.to.lines/v.to.lines.py | 78 +++---- .../v.what.strds/testsuite/test_what_strds.py | 6 +- scripts/v.what.strds/v.what.strds.py | 34 +-- scripts/wxpyimgview/wxpyimgview.py | 4 +- scripts/wxpyimgview/wxpyimgview_gui.py | 8 +- temporal/t.copy/t.copy.py | 24 +- temporal/t.create/t.create.py | 6 +- temporal/t.info/t.info.py | 10 +- temporal/t.list/t.list.py | 10 +- temporal/t.merge/t.merge.py | 18 +- temporal/t.rast.accdetect/t.rast.accdetect.py | 62 +++-- .../t.rast.accumulate/t.rast.accumulate.py | 44 ++-- .../t.rast.aggregate.ds.py | 18 +- temporal/t.rast.aggregate/t.rast.aggregate.py | 12 +- temporal/t.rast.algebra/t.rast.algebra.py | 12 +- temporal/t.rast.colors/t.rast.colors.py | 12 +- temporal/t.rast.contour/t.rast.contour.py | 20 +- temporal/t.rast.export/t.rast.export.py | 12 +- .../testsuite/test_rast_export.py | 4 +- temporal/t.rast.extract/t.rast.extract.py | 4 +- temporal/t.rast.gapfill/t.rast.gapfill.py | 24 +- temporal/t.rast.import/t.rast.import.py | 4 +- temporal/t.rast.mapcalc/t.rast.mapcalc.py | 4 +- temporal/t.rast.neighbors/t.rast.neighbors.py | 18 +- temporal/t.rast.out.vtk/t.rast.out.vtk.py | 24 +- temporal/t.rast.series/t.rast.series.py | 18 +- temporal/t.rast.to.rast3/t.rast.to.rast3.py | 32 +-- temporal/t.rast.to.vect/t.rast.to.vect.py | 20 +- temporal/t.rast.what/t.rast.what.py | 32 +-- temporal/t.rast3d.algebra/t.rast3d.algebra.py | 12 +- .../testsuite/test_raster3d_algebra.py | 4 +- temporal/t.rast3d.extract/t.rast3d.extract.py | 4 +- temporal/t.rast3d.list/t.rast3d.list.py | 6 +- temporal/t.rast3d.mapcalc/t.rast3d.mapcalc.py | 4 +- temporal/t.register/t.register.py | 8 +- temporal/t.remove/t.remove.py | 16 +- temporal/t.rename/t.rename.py | 14 +- temporal/t.sample/t.sample.py | 6 +- temporal/t.select/t.select.py | 8 +- temporal/t.shift/t.shift.py | 6 +- temporal/t.snap/t.snap.py | 4 +- temporal/t.support/t.support.py | 6 +- temporal/t.topology/t.topology.py | 4 +- temporal/t.unregister/t.unregister.py | 24 +- temporal/t.vect.algebra/t.vect.algebra.py | 8 +- temporal/t.vect.db.select/t.vect.db.select.py | 10 +- temporal/t.vect.export/t.vect.export.py | 4 +- temporal/t.vect.extract/t.vect.extract.py | 4 +- temporal/t.vect.import/t.vect.import.py | 4 +- temporal/t.vect.list/t.vect.list.py | 6 +- .../t.vect.observe.strds.py | 36 +-- temporal/t.vect.univar/t.vect.univar.py | 6 +- .../t.vect.what.strds/t.vect.what.strds.py | 30 +-- utils/ppmrotate.py | 20 +- utils/thumbnails.py | 22 +- 187 files changed, 2283 insertions(+), 2389 deletions(-) diff --git a/gui/wxpython/animation/frame.py b/gui/wxpython/animation/frame.py index 4fe0457ee66..1cf3b419b74 100644 --- a/gui/wxpython/animation/frame.py +++ b/gui/wxpython/animation/frame.py @@ -22,7 +22,7 @@ import wx import wx.aui -import grass.script as gcore +import grass.script as gs import grass.temporal as tgis from grass.exceptions import FatalError from core import globalvar @@ -42,7 +42,7 @@ MAX_COUNT = 4 TMP_DIR = None -gcore.set_raise_on_error(True) +gs.set_raise_on_error(True) class AnimationFrame(wx.Frame): @@ -71,7 +71,7 @@ def __init__( # create temporal directory and ensure it's deleted after programs ends # (stored in MAPSET/.tmp/) global TMP_DIR - TMP_DIR = gcore.tempdir() + TMP_DIR = gs.tempdir() self.animations = [Animation() for i in range(MAX_COUNT)] self.windows = [] diff --git a/gui/wxpython/animation/g.gui.animation.py b/gui/wxpython/animation/g.gui.animation.py index f8bedae83eb..911c6c472dd 100644 --- a/gui/wxpython/animation/g.gui.animation.py +++ b/gui/wxpython/animation/g.gui.animation.py @@ -51,12 +51,12 @@ # % guisection: Input # %end -import grass.script as gscript +import grass.script as gs from grass.exceptions import FatalError def main(): - options, flags = gscript.parser() + options, flags = gs.parser() # import wx only after running parser # to avoid issues when only interface is needed @@ -89,7 +89,7 @@ def main(): numInputs += 1 if numInputs > 1: - gscript.fatal( + gs.fatal( _("%s=, %s=, %s= and %s= are mutually exclusive.") % ("raster", "vector", "strds", "stvds") ) diff --git a/gui/wxpython/animation/temporal_manager.py b/gui/wxpython/animation/temporal_manager.py index fc1be449fb7..4c1816fea19 100644 --- a/gui/wxpython/animation/temporal_manager.py +++ b/gui/wxpython/animation/temporal_manager.py @@ -19,7 +19,7 @@ import datetime -import grass.script as grass +import grass.script as gs import grass.temporal as tgis from core.gcmd import GException from core.settings import UserSettings @@ -389,7 +389,7 @@ def test(): def createAbsoluteInterval(): - grass.run_command( + gs.run_command( "g.region", s=0, n=80, @@ -403,21 +403,21 @@ def createAbsoluteInterval(): quiet=True, ) - grass.mapcalc(exp="prec_1 = rand(0, 550)", overwrite=True) - grass.mapcalc(exp="prec_2 = rand(0, 450)", overwrite=True) - grass.mapcalc(exp="prec_3 = rand(0, 320)", overwrite=True) - grass.mapcalc(exp="prec_4 = rand(0, 510)", overwrite=True) - grass.mapcalc(exp="prec_5 = rand(0, 300)", overwrite=True) - grass.mapcalc(exp="prec_6 = rand(0, 650)", overwrite=True) - - grass.mapcalc(exp="temp_1 = rand(0, 550)", overwrite=True) - grass.mapcalc(exp="temp_2 = rand(0, 450)", overwrite=True) - grass.mapcalc(exp="temp_3 = rand(0, 320)", overwrite=True) - grass.mapcalc(exp="temp_4 = rand(0, 510)", overwrite=True) - grass.mapcalc(exp="temp_5 = rand(0, 300)", overwrite=True) - grass.mapcalc(exp="temp_6 = rand(0, 650)", overwrite=True) - - n1 = grass.read_command("g.tempfile", pid=1, flags="d").strip() + gs.mapcalc(exp="prec_1 = rand(0, 550)", overwrite=True) + gs.mapcalc(exp="prec_2 = rand(0, 450)", overwrite=True) + gs.mapcalc(exp="prec_3 = rand(0, 320)", overwrite=True) + gs.mapcalc(exp="prec_4 = rand(0, 510)", overwrite=True) + gs.mapcalc(exp="prec_5 = rand(0, 300)", overwrite=True) + gs.mapcalc(exp="prec_6 = rand(0, 650)", overwrite=True) + + gs.mapcalc(exp="temp_1 = rand(0, 550)", overwrite=True) + gs.mapcalc(exp="temp_2 = rand(0, 450)", overwrite=True) + gs.mapcalc(exp="temp_3 = rand(0, 320)", overwrite=True) + gs.mapcalc(exp="temp_4 = rand(0, 510)", overwrite=True) + gs.mapcalc(exp="temp_5 = rand(0, 300)", overwrite=True) + gs.mapcalc(exp="temp_6 = rand(0, 650)", overwrite=True) + + n1 = gs.read_command("g.tempfile", pid=1, flags="d").strip() fd = open(n1, "w") fd.write( "prec_1|2001-01-01|2001-02-01\n" @@ -429,7 +429,7 @@ def createAbsoluteInterval(): ) fd.close() - n2 = grass.read_command("g.tempfile", pid=2, flags="d").strip() + n2 = gs.read_command("g.tempfile", pid=2, flags="d").strip() fd = open(n2, "w") fd.write( "temp_1|2000-10-01|2001-01-01\n" @@ -442,14 +442,14 @@ def createAbsoluteInterval(): fd.close() name1 = "absinterval1" name2 = "absinterval2" - grass.run_command( + gs.run_command( "t.unregister", type="raster", maps="prec_1,prec_2,prec_3,prec_4,prec_5,prec_6," "temp_1,temp_2,temp_3,temp_4,temp_5,temp_6", ) for name, fname in zip((name1, name2), (n1, n2)): - grass.run_command( + gs.run_command( "t.create", overwrite=True, type="strds", @@ -458,15 +458,13 @@ def createAbsoluteInterval(): title="A test with input files", descr="A test with input files", ) - grass.run_command( - "t.register", flags="i", input=name, file=fname, overwrite=True - ) + gs.run_command("t.register", flags="i", input=name, file=fname, overwrite=True) return name1, name2 def createRelativeInterval(): - grass.run_command( + gs.run_command( "g.region", s=0, n=80, @@ -480,21 +478,21 @@ def createRelativeInterval(): quiet=True, ) - grass.mapcalc(exp="prec_1 = rand(0, 550)", overwrite=True) - grass.mapcalc(exp="prec_2 = rand(0, 450)", overwrite=True) - grass.mapcalc(exp="prec_3 = rand(0, 320)", overwrite=True) - grass.mapcalc(exp="prec_4 = rand(0, 510)", overwrite=True) - grass.mapcalc(exp="prec_5 = rand(0, 300)", overwrite=True) - grass.mapcalc(exp="prec_6 = rand(0, 650)", overwrite=True) - - grass.mapcalc(exp="temp_1 = rand(0, 550)", overwrite=True) - grass.mapcalc(exp="temp_2 = rand(0, 450)", overwrite=True) - grass.mapcalc(exp="temp_3 = rand(0, 320)", overwrite=True) - grass.mapcalc(exp="temp_4 = rand(0, 510)", overwrite=True) - grass.mapcalc(exp="temp_5 = rand(0, 300)", overwrite=True) - grass.mapcalc(exp="temp_6 = rand(0, 650)", overwrite=True) - - n1 = grass.read_command("g.tempfile", pid=1, flags="d").strip() + gs.mapcalc(exp="prec_1 = rand(0, 550)", overwrite=True) + gs.mapcalc(exp="prec_2 = rand(0, 450)", overwrite=True) + gs.mapcalc(exp="prec_3 = rand(0, 320)", overwrite=True) + gs.mapcalc(exp="prec_4 = rand(0, 510)", overwrite=True) + gs.mapcalc(exp="prec_5 = rand(0, 300)", overwrite=True) + gs.mapcalc(exp="prec_6 = rand(0, 650)", overwrite=True) + + gs.mapcalc(exp="temp_1 = rand(0, 550)", overwrite=True) + gs.mapcalc(exp="temp_2 = rand(0, 450)", overwrite=True) + gs.mapcalc(exp="temp_3 = rand(0, 320)", overwrite=True) + gs.mapcalc(exp="temp_4 = rand(0, 510)", overwrite=True) + gs.mapcalc(exp="temp_5 = rand(0, 300)", overwrite=True) + gs.mapcalc(exp="temp_6 = rand(0, 650)", overwrite=True) + + n1 = gs.read_command("g.tempfile", pid=1, flags="d").strip() fd = open(n1, "w") fd.write( "prec_1|1|4\n" @@ -506,7 +504,7 @@ def createRelativeInterval(): ) fd.close() - n2 = grass.read_command("g.tempfile", pid=2, flags="d").strip() + n2 = gs.read_command("g.tempfile", pid=2, flags="d").strip() fd = open(n2, "w") fd.write( "temp_1|5|6\n" @@ -519,14 +517,14 @@ def createRelativeInterval(): fd.close() name1 = "relinterval1" name2 = "relinterval2" - grass.run_command( + gs.run_command( "t.unregister", type="raster", maps="prec_1,prec_2,prec_3,prec_4,prec_5,prec_6," "temp_1,temp_2,temp_3,temp_4,temp_5,temp_6", ) for name, fname in zip((name1, name2), (n1, n2)): - grass.run_command( + gs.run_command( "t.create", overwrite=True, type="strds", @@ -535,7 +533,7 @@ def createRelativeInterval(): title="A test with input files", descr="A test with input files", ) - grass.run_command( + gs.run_command( "t.register", flags="i", input=name, @@ -547,7 +545,7 @@ def createRelativeInterval(): def createAbsolutePoint(): - grass.run_command( + gs.run_command( "g.region", s=0, n=80, @@ -561,14 +559,14 @@ def createAbsolutePoint(): quiet=True, ) - grass.mapcalc(exp="prec_1 = rand(0, 550)", overwrite=True) - grass.mapcalc(exp="prec_2 = rand(0, 450)", overwrite=True) - grass.mapcalc(exp="prec_3 = rand(0, 320)", overwrite=True) - grass.mapcalc(exp="prec_4 = rand(0, 510)", overwrite=True) - grass.mapcalc(exp="prec_5 = rand(0, 300)", overwrite=True) - grass.mapcalc(exp="prec_6 = rand(0, 650)", overwrite=True) + gs.mapcalc(exp="prec_1 = rand(0, 550)", overwrite=True) + gs.mapcalc(exp="prec_2 = rand(0, 450)", overwrite=True) + gs.mapcalc(exp="prec_3 = rand(0, 320)", overwrite=True) + gs.mapcalc(exp="prec_4 = rand(0, 510)", overwrite=True) + gs.mapcalc(exp="prec_5 = rand(0, 300)", overwrite=True) + gs.mapcalc(exp="prec_6 = rand(0, 650)", overwrite=True) - n1 = grass.read_command("g.tempfile", pid=1, flags="d").strip() + n1 = gs.read_command("g.tempfile", pid=1, flags="d").strip() fd = open(n1, "w") fd.write( "prec_1|2001-01-01\n" @@ -580,7 +578,7 @@ def createAbsolutePoint(): ) fd.close() name = "abspoint" - grass.run_command( + gs.run_command( "t.create", overwrite=True, type="strds", @@ -590,12 +588,12 @@ def createAbsolutePoint(): descr="A test with input files", ) - grass.run_command("t.register", flags="i", input=name, file=n1, overwrite=True) + gs.run_command("t.register", flags="i", input=name, file=n1, overwrite=True) return name def createRelativePoint(): - grass.run_command( + gs.run_command( "g.region", s=0, n=80, @@ -609,19 +607,19 @@ def createRelativePoint(): quiet=True, ) - grass.mapcalc(exp="prec_1 = rand(0, 550)", overwrite=True) - grass.mapcalc(exp="prec_2 = rand(0, 450)", overwrite=True) - grass.mapcalc(exp="prec_3 = rand(0, 320)", overwrite=True) - grass.mapcalc(exp="prec_4 = rand(0, 510)", overwrite=True) - grass.mapcalc(exp="prec_5 = rand(0, 300)", overwrite=True) - grass.mapcalc(exp="prec_6 = rand(0, 650)", overwrite=True) + gs.mapcalc(exp="prec_1 = rand(0, 550)", overwrite=True) + gs.mapcalc(exp="prec_2 = rand(0, 450)", overwrite=True) + gs.mapcalc(exp="prec_3 = rand(0, 320)", overwrite=True) + gs.mapcalc(exp="prec_4 = rand(0, 510)", overwrite=True) + gs.mapcalc(exp="prec_5 = rand(0, 300)", overwrite=True) + gs.mapcalc(exp="prec_6 = rand(0, 650)", overwrite=True) - n1 = grass.read_command("g.tempfile", pid=1, flags="d").strip() + n1 = gs.read_command("g.tempfile", pid=1, flags="d").strip() fd = open(n1, "w") fd.write("prec_1|1\nprec_2|3\nprec_3|5\nprec_4|7\nprec_5|11\nprec_6|13\n") fd.close() name = "relpoint" - grass.run_command( + gs.run_command( "t.create", overwrite=True, type="strds", @@ -631,7 +629,7 @@ def createRelativePoint(): descr="A test with input files", ) - grass.run_command("t.register", unit="day", input=name, file=n1, overwrite=True) + gs.run_command("t.register", unit="day", input=name, file=n1, overwrite=True) return name diff --git a/gui/wxpython/animation/utils.py b/gui/wxpython/animation/utils.py index 23d8f23b444..7f20c74f4cc 100644 --- a/gui/wxpython/animation/utils.py +++ b/gui/wxpython/animation/utils.py @@ -31,7 +31,7 @@ hasPIL = False import grass.temporal as tgis -import grass.script as grass +import grass.script as gs from grass.script.utils import encode from gui_core.wrap import EmptyBitmap @@ -87,7 +87,7 @@ def validateMapNames(names, etype): Input is list of map names. Raises GException if map doesn't exist. """ - mapDict = grass.list_grouped(etype) + mapDict = gs.list_grouped(etype) newNames = [] for name in names: diff --git a/gui/wxpython/core/debug.py b/gui/wxpython/core/debug.py index 86bb006d603..cf642d1df4c 100644 --- a/gui/wxpython/core/debug.py +++ b/gui/wxpython/core/debug.py @@ -22,7 +22,7 @@ import os import sys -import grass.script as grass +import grass.script as gs class DebugMsg: @@ -41,7 +41,7 @@ def __init__(self): def SetLevel(self): """Initialize gui debug level""" try: - self.debuglevel = int(grass.gisenv().get("WX_DEBUG", 0)) + self.debuglevel = int(gs.gisenv().get("WX_DEBUG", 0)) if self.debuglevel < 0 or self.debuglevel > 5: raise ValueError(_("Wx debug level {0}.").format(self.debuglevel)) except ValueError as e: diff --git a/gui/wxpython/core/gconsole.py b/gui/wxpython/core/gconsole.py index ff566cdef88..05dc0ea7519 100644 --- a/gui/wxpython/core/gconsole.py +++ b/gui/wxpython/core/gconsole.py @@ -35,7 +35,7 @@ import wx from wx.lib.newevent import NewEvent -import grass.script as grass +import grass.script as gs from grass.script import task as gtask from grass.pydispatch.signal import Signal @@ -401,7 +401,7 @@ def __init__(self, guiparent=None, giface=None, ignoredCmdPattern=None): def Redirect(self): """Redirect stdout/stderr""" - if Debug.GetLevel() == 0 and grass.debug_level(force=True) == 0: + if Debug.GetLevel() == 0 and gs.debug_level(force=True) == 0: # don't redirect when debugging is enabled sys.stdout = self.cmdStdOut sys.stderr = self.cmdStdErr @@ -825,12 +825,12 @@ def OnCmdDone(self, event): lnames = [p.get("value")] for lname in lnames: if "@" not in lname: - lname += "@" + grass.gisenv()["MAPSET"] - if grass.find_file(lname, element=p.get("element"))["fullname"]: + lname += "@" + gs.gisenv()["MAPSET"] + if gs.find_file(lname, element=p.get("element"))["fullname"]: self.mapCreated.emit( name=lname, ltype=prompt, add=event.addLayer ) - gisenv = grass.gisenv() + gisenv = gs.gisenv() self._giface.grassdbChanged.emit( grassdb=gisenv["GISDBASE"], location=gisenv["LOCATION_NAME"], @@ -844,7 +844,7 @@ def OnCmdDone(self, event): for p in task.get_options()["flags"]: if p.get("name") == "r" and p.get("value"): action = "delete" - gisenv = grass.gisenv() + gisenv = gs.gisenv() self._giface.grassdbChanged.emit( grassdb=gisenv["GISDBASE"], location=gisenv["LOCATION_NAME"], diff --git a/gui/wxpython/core/giface.py b/gui/wxpython/core/giface.py index 951c9cb42dd..f226d44eae9 100644 --- a/gui/wxpython/core/giface.py +++ b/gui/wxpython/core/giface.py @@ -18,7 +18,7 @@ import os import sys -import grass.script as grass +import grass.script as gs from grass.pydispatch.signal import Signal @@ -275,7 +275,7 @@ def _onCmdOutput(self, event): def _onCmdProgress(self, event): """Update progress message info""" - grass.percent(event.value, 100, 1) + gs.percent(event.value, 100, 1) event.Skip() def RunCmd( @@ -306,18 +306,18 @@ def Help(self, entry): self._gconsole.RunCmd(["g.manual", "entry=%s" % entry]) def WriteLog(self, text, wrap=None, notification=Notification.HIGHLIGHT): - self._write(grass.message, text) + self._write(gs.message, text) def WriteCmdLog(self, text, pid=None, notification=Notification.MAKE_VISIBLE): if pid: text = "(" + str(pid) + ") " + text - self._write(grass.message, text) + self._write(gs.message, text) def WriteWarning(self, text): - self._write(grass.warning, text) + self._write(gs.warning, text) def WriteError(self, text): - self._write(grass.error, text) + self._write(gs.error, text) def _write(self, function, text): orig = os.getenv("GRASS_MESSAGE_FORMAT") diff --git a/gui/wxpython/datacatalog/g.gui.datacatalog.py b/gui/wxpython/datacatalog/g.gui.datacatalog.py index 3241398bb09..d9dab11d095 100644 --- a/gui/wxpython/datacatalog/g.gui.datacatalog.py +++ b/gui/wxpython/datacatalog/g.gui.datacatalog.py @@ -25,11 +25,11 @@ # % keyword: map management # %end -import grass.script as gscript +import grass.script as gs def main(): - options, flags = gscript.parser() + options, flags = gs.parser() # import wx only after running parser # to avoid issues when only interface is needed diff --git a/gui/wxpython/datacatalog/tree.py b/gui/wxpython/datacatalog/tree.py index f9c3b0a827b..542282802be 100644 --- a/gui/wxpython/datacatalog/tree.py +++ b/gui/wxpython/datacatalog/tree.py @@ -64,7 +64,7 @@ from grass.pydispatch.signal import Signal -import grass.script as gscript +import grass.script as gs from grass.script import gisenv from grass.grassdb.data import map_exists from grass.grassdb.checks import ( @@ -79,14 +79,14 @@ def getLocationTree(gisdbase, location, queue, mapsets=None, lazy=False): """Creates dictionary with mapsets, elements, layers for given location. Returns tuple with the dictionary and error (or None)""" - tmp_gisrc_file, env = gscript.create_environment(gisdbase, location, "PERMANENT") + tmp_gisrc_file, env = gs.create_environment(gisdbase, location, "PERMANENT") env["GRASS_SKIP_MAPSET_OWNER_CHECK"] = "1" maps_dict = {} elements = ["raster", "raster_3d", "vector"] try: if not mapsets: - mapsets = gscript.read_command( + mapsets = gs.read_command( "g.mapsets", flags="l", separator="comma", quiet=True, env=env ).strip() except CalledModuleError: @@ -96,7 +96,7 @@ def getLocationTree(gisdbase, location, queue, mapsets=None, lazy=False): _("Failed to read mapsets from project <{l}>.").format(l=location), ) ) - gscript.try_remove(tmp_gisrc_file) + gs.try_remove(tmp_gisrc_file) return else: mapsets = mapsets.split(",") @@ -107,7 +107,7 @@ def getLocationTree(gisdbase, location, queue, mapsets=None, lazy=False): queue.put((maps_dict, None)) return try: - maplist = gscript.read_command( + maplist = gs.read_command( "g.list", flags="mt", type=elements, @@ -122,7 +122,7 @@ def getLocationTree(gisdbase, location, queue, mapsets=None, lazy=False): _("Failed to read maps from project <{l}>.").format(l=location), ) ) - gscript.try_remove(tmp_gisrc_file) + gs.try_remove(tmp_gisrc_file) return else: # fill dictionary @@ -134,7 +134,7 @@ def getLocationTree(gisdbase, location, queue, mapsets=None, lazy=False): maps_dict[mapset].append({"name": name, "type": ltype}) queue.put((maps_dict, None)) - gscript.try_remove(tmp_gisrc_file) + gs.try_remove(tmp_gisrc_file) class NameEntryDialog(TextEntryDialog): @@ -254,7 +254,7 @@ def __init__( self.current_location_node = None self.current_mapset_node = None self.UpdateCurrentDbLocationMapsetNode() - self._lastWatchdogUpdate = gscript.clock() + self._lastWatchdogUpdate = gs.clock() self._updateMapsetWhenIdle = None # mapset watchdog @@ -619,7 +619,7 @@ def _onUpdateMapsetWhenIdle(self, event): def _onWatchdogMapsetReload(self, event_path): """Reload mapset node associated with watchdog event. Check if events come to quickly and skip them.""" - time = gscript.clock() + time = gs.clock() time_diff = time - self._lastWatchdogUpdate self._lastWatchdogUpdate = time if (time_diff) < 0.5: @@ -719,7 +719,7 @@ def _quickLoading(self): something when loading for the first time""" if self._model.root.children: return - gisenv = gscript.gisenv() + gisenv = gs.gisenv() for grassdatabase in self.grassdatabases: grassdb_node = self._model.AppendNode( parent=self._model.root, data={"type": "grassdb", "name": grassdatabase} @@ -910,7 +910,7 @@ def OnDoubleClick(self, node): def ExpandCurrentLocation(self): """Expand current location""" - location = gscript.gisenv()["LOCATION_NAME"] + location = gs.gisenv()["LOCATION_NAME"] item = self._model.SearchNodes(name=location, type="location") if item: self.Select(item[0], select=True) @@ -988,7 +988,7 @@ def SetRestriction(self, restrict): self._restricted = restrict def _runCommand(self, prog, **kwargs): - cmdString = " ".join(gscript.make_command(prog, **kwargs)) + cmdString = " ".join(gs.make_command(prog, **kwargs)) ret = RunCommand(prog, parent=self, **kwargs) return ret, cmdString @@ -1026,7 +1026,7 @@ def OnCopyMap(self, event): def OnRenameMap(self, event): """Rename layer with dialog""" old_name = self.selected_layer[0].data["name"] - gisrc, env = gscript.create_environment( + gisrc, env = gs.create_environment( self.selected_grassdb[0].data["name"], self.selected_location[0].data["name"], self.selected_mapset[0].data["name"], @@ -1227,7 +1227,7 @@ def OnEditLabel(self, node, event): def Rename(self, old, new): """Rename layer""" string = old + "," + new - gisrc, env = gscript.create_environment( + gisrc, env = gs.create_environment( self.selected_grassdb[0].data["name"], self.selected_location[0].data["name"], self.selected_mapset[0].data["name"], @@ -1240,7 +1240,7 @@ def Rename(self, old, new): renamed, cmd = self._runCommand("g.rename", raster=string, env=env) else: renamed, cmd = self._runCommand("g.rename", raster3d=string, env=env) - gscript.try_remove(gisrc) + gs.try_remove(gisrc) if renamed == 0: self.showNotification.emit(message=_("{cmd} -- completed").format(cmd=cmd)) Debug.msg(1, "LAYER RENAMED TO: " + new) @@ -1264,12 +1264,12 @@ def OnPasteMap(self, event): return for i in range(len(self.copy_layer)): - gisrc, env = gscript.create_environment( + gisrc, env = gs.create_environment( self.selected_grassdb[0].data["name"], self.selected_location[0].data["name"], self.selected_mapset[0].data["name"], ) - gisrc2, env2 = gscript.create_environment( + gisrc2, env2 = gs.create_environment( self.copy_grassdb[i].data["name"], self.copy_location[i].data["name"], self.copy_mapset[i].data["name"], @@ -1355,8 +1355,8 @@ def OnPasteMap(self, event): action="new", ) - gscript.try_remove(gisrc) - gscript.try_remove(gisrc2) + gs.try_remove(gisrc) + gs.try_remove(gisrc2) # expand selected mapset else: if self.copy_layer[i].data["type"] == "raster_3d": @@ -1423,8 +1423,8 @@ def _onDoneReprojection( ) if not cMode: self._removeMapAfterCopy(cLayer, cMapset, iEnv) - gscript.try_remove(iGisrc) - gscript.try_remove(oGisrc) + gs.try_remove(iGisrc) + gs.try_remove(oGisrc) self.ExpandNode(sMapset, recursive=True) def _removeMapAfterCopy(self, cLayer, cMapset, env): @@ -1526,7 +1526,7 @@ def OnDeleteMap(self, event): label = _("Deleting {name}...").format(name=names) self.showNotification.emit(message=label) for i in range(len(self.selected_layer)): - gisrc, env = gscript.create_environment( + gisrc, env = gs.create_environment( self.selected_grassdb[i].data["name"], self.selected_location[i].data["name"], self.selected_mapset[i].data["name"], @@ -1538,7 +1538,7 @@ def OnDeleteMap(self, event): name=self.selected_layer[i].data["name"], env=env, ) - gscript.try_remove(gisrc) + gs.try_remove(gisrc) if removed == 0: self._giface.grassdbChanged.emit( grassdb=self.selected_grassdb[i].data["name"], @@ -1886,7 +1886,7 @@ def OnMetadata(self, event): """Show metadata of any raster/vector/3draster""" def done(event): - gscript.try_remove(event.userData) + gs.try_remove(event.userData) for i in range(len(self.selected_layer)): if self.selected_layer[i].data["type"] == "raster": @@ -1903,7 +1903,7 @@ def done(event): ) ) - gisrc, env = gscript.create_environment( + gisrc, env = gs.create_environment( self.selected_grassdb[i].data["name"], self.selected_location[i].data["name"], self.selected_mapset[i].data["name"], diff --git a/gui/wxpython/dbmgr/base.py b/gui/wxpython/dbmgr/base.py index d0af1b18a0a..abef5b8daec 100644 --- a/gui/wxpython/dbmgr/base.py +++ b/gui/wxpython/dbmgr/base.py @@ -50,7 +50,7 @@ import wx.lib.flatnotebook as FN import wx.lib.scrolledpanel as scrolled -import grass.script as grass +import grass.script as gs from grass.script.utils import decode from dbmgr.sqlbuilder import SQLBuilderSelect, SQLBuilderUpdate @@ -783,8 +783,8 @@ def __init__( # the current mapset mapInfo = None if self.dbMgrData["vectName"]: - mapInfo = grass.find_file(name=self.dbMgrData["vectName"], element="vector") - if not mapInfo or mapInfo["mapset"] != grass.gisenv()["MAPSET"]: + mapInfo = gs.find_file(name=self.dbMgrData["vectName"], element="vector") + if not mapInfo or mapInfo["mapset"] != gs.gisenv()["MAPSET"]: self.dbMgrData["editable"] = False else: self.dbMgrData["editable"] = True @@ -818,8 +818,8 @@ def ChangeVectorMap(self, vectorName): # vector attributes can be changed only if vector map is in # the current mapset - mapInfo = grass.find_file(name=self.dbMgrData["vectName"], element="vector") - if not mapInfo or mapInfo["mapset"] != grass.gisenv()["MAPSET"]: + mapInfo = gs.find_file(name=self.dbMgrData["vectName"], element="vector") + if not mapInfo or mapInfo["mapset"] != gs.gisenv()["MAPSET"]: self.dbMgrData["editable"] = False else: self.dbMgrData["editable"] = True @@ -3117,12 +3117,12 @@ def __init__(self, parent, id, parentDialog, style=wx.BK_DEFAULT): # get default values # self.defaultConnect = {} - genv = grass.gisenv() - vectMap = grass.find_file( + genv = gs.gisenv() + vectMap = gs.find_file( name=vectName, element="vector", ) - vectGisrc, vectEnv = grass.create_environment( + vectGisrc, vectEnv = gs.create_environment( gisdbase=genv["GISDBASE"], location=genv["LOCATION_NAME"], mapset=vectMap["mapset"], @@ -3134,7 +3134,7 @@ def __init__(self, parent, id, parentDialog, style=wx.BK_DEFAULT): read=True, quiet=True, ) - grass.utils.try_remove(vectGisrc) + gs.utils.try_remove(vectGisrc) for line in connect.splitlines(): item, value = line.split(":", 1) diff --git a/gui/wxpython/dbmgr/g.gui.dbmgr.py b/gui/wxpython/dbmgr/g.gui.dbmgr.py index 920ffebb7d8..ba96b3d44c1 100755 --- a/gui/wxpython/dbmgr/g.gui.dbmgr.py +++ b/gui/wxpython/dbmgr/g.gui.dbmgr.py @@ -28,11 +28,11 @@ # %option G_OPT_V_MAP # %end -import grass.script as gscript +import grass.script as gs def main(): - options, flags = gscript.parser() + options, flags = gs.parser() import wx @@ -42,13 +42,13 @@ def main(): from dbmgr.manager import AttributeManager - mapName = gscript.find_file(options["map"], element="vector")["fullname"] + mapName = gs.find_file(options["map"], element="vector")["fullname"] if not mapName: - gscript.set_raise_on_error(False) - gscript.fatal(_("Vector map <%s> not found") % options["map"]) + gs.set_raise_on_error(False) + gs.fatal(_("Vector map <%s> not found") % options["map"]) app = wx.App() - gscript.message(_("Loading attribute data for vector map <%s>...") % mapName) + gs.message(_("Loading attribute data for vector map <%s>...") % mapName) f = AttributeManager( parent=None, id=wx.ID_ANY, diff --git a/gui/wxpython/dbmgr/sqlbuilder.py b/gui/wxpython/dbmgr/sqlbuilder.py index 44542c90ded..5884c567d18 100644 --- a/gui/wxpython/dbmgr/sqlbuilder.py +++ b/gui/wxpython/dbmgr/sqlbuilder.py @@ -45,7 +45,7 @@ StaticBox, ) -import grass.script as grass +import grass.script as gs class SQLBuilder(wx.Frame): @@ -67,9 +67,9 @@ def __init__(self, parent, title, vectmap, modeChoices=[], id=wx.ID_ANY, layer=1 # variables self.vectmap = vectmap # fullname if "@" not in self.vectmap: - self.vectmap = grass.find_file(self.vectmap, element="vector")["fullname"] + self.vectmap = gs.find_file(self.vectmap, element="vector")["fullname"] if not self.vectmap: - grass.fatal(_("Vector map <%s> not found") % vectmap) + gs.fatal(_("Vector map <%s> not found") % vectmap) self.mapname, self.mapset = self.vectmap.split("@", 1) # db info @@ -371,7 +371,7 @@ def OnUniqueValues(self, event, justsample=False): ) if justsample: sql += " LIMIT {}".format(255) - data = grass.db_select( + data = gs.db_select( sql=sql, database=self.database, driver=self.driver, sep="{_sep_}" ) if not data: diff --git a/gui/wxpython/dbmgr/vinfo.py b/gui/wxpython/dbmgr/vinfo.py index 7c3d92dd6c0..7788a4e6576 100644 --- a/gui/wxpython/dbmgr/vinfo.py +++ b/gui/wxpython/dbmgr/vinfo.py @@ -22,7 +22,7 @@ from gui_core.wrap import StaticText from core.gcmd import RunCommand, GError from core.settings import UserSettings -import grass.script as grass +import grass.script as gs def GetUnicodeValue(value): @@ -106,12 +106,12 @@ def SelectByPoint(self, queryCoords, qdist): nselected = 0 try: - data = grass.vector_what( + data = gs.vector_what( map=self.map, coord=(float(queryCoords[0]), float(queryCoords[1])), distance=float(qdist), ) - except grass.ScriptError: + except gs.ScriptError: GError( parent=None, message=_( diff --git a/gui/wxpython/gcp/g.gui.gcp.py b/gui/wxpython/gcp/g.gui.gcp.py index 1c991856c2a..32ef2c4fc0d 100755 --- a/gui/wxpython/gcp/g.gui.gcp.py +++ b/gui/wxpython/gcp/g.gui.gcp.py @@ -36,7 +36,7 @@ import os -import grass.script as gscript +import grass.script as gs def main(): @@ -45,7 +45,7 @@ def main(): .. todo:: use command line options as an alternative to wizard """ - options, flags = gscript.parser() + options, flags = gs.parser() import wx diff --git a/gui/wxpython/gcp/manager.py b/gui/wxpython/gcp/manager.py index 33696be3b4a..cee0ff416f3 100644 --- a/gui/wxpython/gcp/manager.py +++ b/gui/wxpython/gcp/manager.py @@ -43,7 +43,7 @@ else: from wx import wizard as wiz -import grass.script as grass +import grass.script as gs from core import utils @@ -113,7 +113,7 @@ def __init__(self, parent, giface): # # get environmental variables # - self.grassdatabase = grass.gisenv()["GISDBASE"] + self.grassdatabase = gs.gisenv()["GISDBASE"] # # read original environment settings @@ -1761,7 +1761,7 @@ def _getOverWriteDialog(self, maptype, overwrite): """ if maptype == "raster": self.grwiz.SwitchEnv("source") - maps = grass.read_command( + maps = gs.read_command( "i.group", flags="gl", group=self.xygroup, @@ -1773,7 +1773,7 @@ def _getOverWriteDialog(self, maptype, overwrite): for map in maps: if map: map_name = map.split("@")[0] + self.extension - found = grass.find_file( + found = gs.find_file( name=map_name, element="cell", mapset=self.currentmapset, @@ -1783,7 +1783,7 @@ def _getOverWriteDialog(self, maptype, overwrite): map_name = ", ".join(found_maps) else: self.grwiz.SwitchEnv("target") - found = grass.find_file( + found = gs.find_file( name=self.outname, element="vector", mapset=self.currentmapset, @@ -2366,13 +2366,13 @@ def OnZoomMenuGCP(self, event): def OnSize(self, event): """Adjust Map Windows after GCP Map Display has been resized""" # re-render image on idle - self.resize = grass.clock() + self.resize = gs.clock() super(MapPanel, self).OnSize(event) def OnIdle(self, event): """GCP Map Display resized, adjust Map Windows""" if self.GetMapToolbar(): - if self.resize and self.resize + 0.2 < grass.clock(): + if self.resize and self.resize + 0.2 < gs.clock(): srcwidth, srcheight = self.SrcMapWindow.GetSize() tgtwidth, tgtheight = self.TgtMapWindow.GetSize() srcwidth = (srcwidth + tgtwidth) / 2 diff --git a/gui/wxpython/gmodeler/g.gui.gmodeler.py b/gui/wxpython/gmodeler/g.gui.gmodeler.py index c2f24752583..01d15afbcfa 100755 --- a/gui/wxpython/gmodeler/g.gui.gmodeler.py +++ b/gui/wxpython/gmodeler/g.gui.gmodeler.py @@ -34,11 +34,11 @@ # % guisection: Model # %end -import grass.script as gscript +import grass.script as gs def main(): - options, flags = gscript.parser() + options, flags = gs.parser() import wx diff --git a/gui/wxpython/gui_core/ghelp.py b/gui/wxpython/gui_core/ghelp.py index 1d0a74d19ad..8366e464a66 100644 --- a/gui/wxpython/gui_core/ghelp.py +++ b/gui/wxpython/gui_core/ghelp.py @@ -37,7 +37,7 @@ from wx import AboutDialogInfo from wx import AboutBox -import grass.script as grass +import grass.script as gs from grass.exceptions import CalledModuleError # needed just for testing @@ -111,7 +111,7 @@ def _doLayout(self): def _pageInfo(self): """Info page""" # get version and web site - vInfo = grass.version() + vInfo = gs.version() if not vInfo: sys.stderr.write(_("Unable to get GRASS version\n")) @@ -245,7 +245,7 @@ def _pageInfo(self): pos=(row, 0), flag=wx.ALIGN_RIGHT, ) - self.langUsed = grass.gisenv().get("LANG", None) + self.langUsed = gs.gisenv().get("LANG", None) if not self.langUsed: import locale @@ -329,10 +329,7 @@ def _pageLicense(self): def _pageCitation(self): """Citation information""" try: - # import only when needed - import grass.script as gscript - - text = gscript.read_command("g.version", flags="x") + text = gs.read_command("g.version", flags="x") except CalledModuleError as error: text = _( "Unable to provide citation suggestion," @@ -973,7 +970,7 @@ def ShowAboutDialog(prgName, startYear): def _grassDevTeam(start): try: - end = grass.version()["date"] + end = gs.version()["date"] except KeyError: sys.stderr.write(_("Unable to get GRASS version\n")) diff --git a/gui/wxpython/gui_core/gselect.py b/gui/wxpython/gui_core/gselect.py index ae2d3669146..bed849f0c26 100644 --- a/gui/wxpython/gui_core/gselect.py +++ b/gui/wxpython/gui_core/gselect.py @@ -54,7 +54,7 @@ import wx.lib.filebrowsebutton as filebrowse -import grass.script as grass +import grass.script as gs from grass.script import task as gtask from grass.exceptions import CalledModuleError @@ -212,7 +212,7 @@ def __init__(self, parent, ftype, **kwargs): def _isElement(self, vectorName): """Check if element should be filtered out""" try: - if int(grass.vector_info_topo(vectorName)[self.ftype]) < 1: + if int(gs.vector_info_topo(vectorName)[self.ftype]) < 1: return False except KeyError: return False @@ -495,7 +495,7 @@ def _getElementList(self, element, mapsets=None, elements=None, exclude=False): :param exclude: True to exclude, False for forcing the list (elements) """ # get current mapset - curr_mapset = grass.gisenv()["MAPSET"] + curr_mapset = gs.gisenv()["MAPSET"] # map element types to g.list types elementdict = { @@ -533,7 +533,7 @@ def _getElementList(self, element, mapsets=None, elements=None, exclude=False): else: filesdict = None else: - filesdict = grass.list_grouped(renamed_elements, check_search_path=False) + filesdict = gs.list_grouped(renamed_elements, check_search_path=False) # add extra items first if self.extraItems: @@ -546,7 +546,7 @@ def _getElementList(self, element, mapsets=None, elements=None, exclude=False): # list of mapsets in current location if mapsets is None: - mapsets = grass.mapsets(search_path=True) + mapsets = gs.mapsets(search_path=True) # current mapset first if curr_mapset in mapsets and mapsets[0] != curr_mapset: @@ -635,7 +635,7 @@ def _addItems(self, elist, elements, mapset, exclude, node): :param exclude: True to exclude, False for forcing the list :param node: parent node """ - elist = grass.naturally_sorted(elist) + elist = gs.naturally_sorted(elist) for elem in elist: if elem != "": fullqElem = elem + "@" + mapset @@ -838,7 +838,7 @@ def _CheckDBConnection(self): # if map is not defined (happens with vnet initialization) or it # doesn't exist try: - self.layers = grass.vector_db(map=self.map, stderr=nuldev) + self.layers = gs.vector_db(map=self.map, stderr=nuldev) except CalledModuleError: return False finally: # always close nuldev @@ -862,7 +862,7 @@ def _DescribeTables(self): self.layers[layer]["database"], ), ) - for item in grass.db_describe( + for item in gs.db_describe( table=self.layers[layer]["table"], driver=self.layers[layer]["driver"], database=self.layers[layer]["database"], @@ -1066,7 +1066,7 @@ def InsertTables(self, driver=None, database=None): items = [] if not driver or not database: - connect = grass.db_connection() + connect = gs.db_connection() driver = connect["driver"] database = connect["database"] @@ -1233,7 +1233,7 @@ def __init__(self, parent, **kwargs): labelText="", dialogTitle=_("Choose GIS Data Directory"), buttonText=_("Browse"), - startDirectory=grass.gisenv()["GISDBASE"], + startDirectory=gs.gisenv()["GISDBASE"], **kwargs, ) @@ -1253,7 +1253,7 @@ def __init__( self.SetName("LocationSelect") if not gisdbase: - self.gisdbase = grass.gisenv()["GISDBASE"] + self.gisdbase = gs.gisenv()["GISDBASE"] else: self.gisdbase = gisdbase @@ -1300,12 +1300,12 @@ def __init__( self.value = "" self.multiple = multiple if not gisdbase: - self.gisdbase = grass.gisenv()["GISDBASE"] + self.gisdbase = gs.gisenv()["GISDBASE"] else: self.gisdbase = gisdbase if not location: - self.location = grass.gisenv()["LOCATION_NAME"] + self.location = gs.gisenv()["LOCATION_NAME"] else: self.location = location @@ -1351,7 +1351,7 @@ def _getMapsets(self): else: mlist = GetListOfMapsets(self.gisdbase, self.location, selectable=False) - gisenv = grass.gisenv() + gisenv = gs.gisenv() if ( self.skipCurrent and gisenv["LOCATION_NAME"] == self.location @@ -1375,7 +1375,7 @@ def Insert(self, group): """Insert subgroups for defined group""" if not group: return - gisenv = grass.gisenv() + gisenv = gs.gisenv() try: name, mapset = group.split("@", 1) except ValueError: @@ -1700,7 +1700,7 @@ def __init__( "v.external.out", parent=self, read=True, - parse=grass.parse_key_val, + parse=gs.parse_key_val, flags="g", ) if current["format"] == "native": @@ -2199,9 +2199,9 @@ def SetDatabase(self, db): if dbNames is not None: self.dbWidgets["choice"].SetItems(sorted(dbNames)) self.dbWidgets["choice"].SetSelection(0) - elif grass.find_program(self._psql, "--help"): + elif gs.find_program(self._psql, "--help"): if not self.dbWidgets["choice"].GetItems(): - p = grass.Popen([self._psql, "-ltA"], stdout=grass.PIPE) + p = gs.Popen([self._psql, "-ltA"], stdout=gs.PIPE) ret = p.communicate()[0] if ret: dbNames = [] @@ -2243,7 +2243,7 @@ def hasRastSameProjAsLocation(dsn, table=None): if "PG:" in dsn: dsn = dsn.replace("PG:", "") - p = grass.Popen( + p = gs.Popen( [ self._psql, "-t", @@ -2252,7 +2252,7 @@ def hasRastSameProjAsLocation(dsn, table=None): "-c", f"SELECT ST_SRID(rast) AS srid FROM {table} WHERE rid=1;", ], - stdout=grass.PIPE, + stdout=gs.PIPE, ) ret, error = p.communicate() if error: @@ -2271,13 +2271,13 @@ def hasRastSameProjAsLocation(dsn, table=None): dsn, conn_param="host", ), - error=grass.utils.decode(error), + error=gs.utils.decode(error), ), ), ) if ret: - raster_srid = grass.utils.decode(ret).replace(os.linesep, "") - location_srid = grass.parse_command("g.proj", flags="g") + raster_srid = gs.utils.decode(ret).replace(os.linesep, "") + location_srid = gs.parse_command("g.proj", flags="g") if raster_srid == location_srid["srid"].split(":")[-1]: projectionMatch = "1" else: @@ -2518,7 +2518,7 @@ def _getPGDBtables(self, dsn): AND schemaname != 'pg_catalog'; """ # Get tables list - p = grass.Popen( + p = gs.Popen( [ self._psql, "-t", @@ -2527,7 +2527,7 @@ def _getPGDBtables(self, dsn): "-c", f"{tables_list_sql}", ], - stdout=grass.PIPE, + stdout=gs.PIPE, ) ret, error = p.communicate() if error: @@ -2544,12 +2544,12 @@ def _getPGDBtables(self, dsn): dsn, conn_param="host", ), - error=grass.utils.decode(error), + error=gs.utils.decode(error), ), ), ) if ret: - ret = grass.utils.decode(ret) + ret = gs.utils.decode(ret) tables = [i.strip() for i in ret.split(os.linesep) if i] Debug.msg(3, f"GdalSelect._getPGDBtables(): return {tables}") return tables @@ -2599,7 +2599,7 @@ def _getPGDBRasters(self, dsn): field_sep = "," dsn = dsn.replace("PG:", "") - if grass.find_program(self._psql, "--help"): + if gs.find_program(self._psql, "--help"): tables = self._getPGDBtables(dsn) # Get tables columns data types list if tables: @@ -2607,7 +2607,7 @@ def _getPGDBRasters(self, dsn): tables_cols_data_types_sql = self._getPGDBTablesColumnsTypesSql( tables=tables_with_quotes, ) - p = grass.Popen( + p = gs.Popen( [ self._psql, "-t", @@ -2618,7 +2618,7 @@ def _getPGDBRasters(self, dsn): "-c", f"{tables_cols_data_types_sql}", ], - stdout=grass.PIPE, + stdout=gs.PIPE, ) ret, error = p.communicate() if error: @@ -2636,14 +2636,14 @@ def _getPGDBRasters(self, dsn): dsn, conn_param="host", ), - error=grass.utils.decode(error), + error=gs.utils.decode(error), ), ), ) if ret: import re - tables_cols = grass.utils.decode(ret) + tables_cols = gs.utils.decode(ret) rasters_cols = re.findall( rf".*.{raster_col_type}", tables_cols, @@ -2704,9 +2704,9 @@ def __init__( def UpdateItems(self, dbase, location, mapset): """Update list of maps""" if not dbase: - dbase = grass.gisenv()["GISDBASE"] + dbase = gs.gisenv()["GISDBASE"] if not mapset: - mapset = grass.gisenv()["MAPSET"] + mapset = gs.gisenv()["MAPSET"] if self.isRaster: ret = RunCommand( "r.proj", @@ -3176,7 +3176,7 @@ def _append_mapset_signatures(self, mapset, element, items): sig_list = list_ptr() count = I_signatures_list_by_type(sig_type, mapset, ctypes.byref(sig_list)) for n in range(count): - items.append(grass.decode(sig_list[n])) + items.append(gs.decode(sig_list[n])) I_free_signatures_list(count, ctypes.byref(sig_list)) diff --git a/gui/wxpython/gui_core/preferences.py b/gui/wxpython/gui_core/preferences.py index 030e0ddba6e..3c3df8e8e42 100644 --- a/gui/wxpython/gui_core/preferences.py +++ b/gui/wxpython/gui_core/preferences.py @@ -42,7 +42,7 @@ import wx.lib.scrolledpanel as SP from grass.pydispatch.signal import Signal -import grass.script as grass +import grass.script as gs from grass.exceptions import OpenError from core import globalvar @@ -1300,7 +1300,7 @@ def _createCmdPage(self, notebook): self.nprocs = TextCtrl( parent=panel, id=wx.ID_ANY, - value=grass.gisenv().get("NPROCS", ""), + value=gs.gisenv().get("NPROCS", ""), validator=IntegerValidator(), name="NumberOfProcs", ) @@ -1324,7 +1324,7 @@ def _createCmdPage(self, notebook): self.memorymb = TextCtrl( parent=panel, id=wx.ID_ANY, - value=grass.gisenv().get("MEMORYMB", ""), + value=gs.gisenv().get("MEMORYMB", ""), validator=IntegerValidator(), name="MemorySizeMB", ) @@ -2288,18 +2288,18 @@ def OnSave(self, event): group="language", key="locale", subkey="lc_all", value=None ) lang = None - env = grass.gisenv() + env = gs.gisenv() # Set gisenv MEMORYMB var value memorydb_gisenv = "MEMORYMB" memorymb = self.memorymb.GetValue() if memorymb: - grass.run_command( + gs.run_command( "g.gisenv", set=f"{memorydb_gisenv}={memorymb}", ) elif env.get(memorydb_gisenv): - grass.run_command( + gs.run_command( "g.gisenv", unset=memorydb_gisenv, ) @@ -2307,12 +2307,12 @@ def OnSave(self, event): nprocs_gisenv = "NPROCS" nprocs = self.nprocs.GetValue() if nprocs: - grass.run_command( + gs.run_command( "g.gisenv", set=f"{nprocs_gisenv}={nprocs}", ) elif env.get(nprocs_gisenv): - grass.run_command( + gs.run_command( "g.gisenv", unset=nprocs_gisenv, ) @@ -2338,7 +2338,7 @@ def __init__( self.all_mapsets_ordered = ListOfMapsets(get="ordered") self.accessible_mapsets = ListOfMapsets(get="accessible") - self.curr_mapset = grass.gisenv()["MAPSET"] + self.curr_mapset = gs.gisenv()["MAPSET"] # make a checklistbox from available mapsets and check those that are # active @@ -2422,7 +2422,7 @@ def LoadData(self): self.InsertColumn(0, _("Mapset")) self.InsertColumn(1, _("Owner")) ### self.InsertColumn(2, _('Group')) - gisenv = grass.gisenv() + gisenv = gs.gisenv() locationPath = os.path.join(gisenv["GISDBASE"], gisenv["LOCATION_NAME"]) for mapset in self.parent.all_mapsets_ordered: diff --git a/gui/wxpython/gui_core/pyedit.py b/gui/wxpython/gui_core/pyedit.py index d590c5fbc8b..7c56a7f7c07 100644 --- a/gui/wxpython/gui_core/pyedit.py +++ b/gui/wxpython/gui_core/pyedit.py @@ -19,7 +19,7 @@ import wx -import grass.script as gscript +import grass.script as gs from grass.script.utils import try_remove # needed just for testing @@ -356,7 +356,7 @@ def _writeFile(self, file_path, content, additional_err_message=""): def OnRun(self, event): """Run Python script""" if not self.filename: - self.filename = gscript.tempfile() + ".py" + self.filename = gs.tempfile() + ".py" self.tempfile = True file_is_written = self._writeFile( file_path=self.filename, @@ -623,7 +623,7 @@ def OnHelp(self, event): # inspired by g.manual but simple not using GRASS_HTML_BROWSER # not using g.manual because it does not show entry = "libpython/script_intro.html" - major, minor, patch = gscript.version()["version"].split(".") + major, minor, patch = gs.version()["version"].split(".") url = "https://grass.osgeo.org/grass%s%s/manuals/%s" % (major, minor, entry) open_url(url) diff --git a/gui/wxpython/gui_core/vselect.py b/gui/wxpython/gui_core/vselect.py index 6800773c6c6..cefcc596628 100644 --- a/gui/wxpython/gui_core/vselect.py +++ b/gui/wxpython/gui_core/vselect.py @@ -29,7 +29,7 @@ from core.gcmd import RunCommand from gui_core.wrap import Button, ListCtrl -import grass.script as grass +import grass.script as gs from grass.pydispatch.signal import Signal @@ -299,13 +299,13 @@ def QuerySelectedMap(self): mapInfo = self.mapWin.GetMap() threshold = 10.0 * ((mapInfo.region["e"] - mapInfo.region["w"]) / mapInfo.width) try: - query = grass.vector_what( + query = gs.vector_what( map=[self.mapName], coord=self.mapWin.GetLastEN(), distance=threshold, skip_attributes=True, ) - except grass.ScriptError: + except gs.ScriptError: GError( parent=self, message=_("Failed to query vector map(s) <%s>.") % self.map ) @@ -358,7 +358,7 @@ def OnExportMap(self, event): if ret == 0: tree = self._giface.GetLayerTree() if tree: - outMap = f"{outMap}@{grass.gisenv()['MAPSET']}" + outMap = f"{outMap}@{gs.gisenv()['MAPSET']}" tree.AddLayer( ltype="vector", lname=outMap, diff --git a/gui/wxpython/iclass/dialogs.py b/gui/wxpython/iclass/dialogs.py index 05a03504b14..8aaac14c4c8 100644 --- a/gui/wxpython/iclass/dialogs.py +++ b/gui/wxpython/iclass/dialogs.py @@ -43,7 +43,7 @@ ListCtrl, ) -import grass.script as grass +import grass.script as gs class IClassGroupDialog(SimpleDialog): @@ -71,7 +71,7 @@ def __init__( self.groupSelect = gselect.Select( parent=self.panel, type="group", - mapsets=[grass.gisenv()["MAPSET"]], + mapsets=[gs.gisenv()["MAPSET"]], size=globalvar.DIALOG_GSELECT_SIZE, validator=SimpleValidator(callback=self.ValidatorCallback), ) @@ -186,7 +186,7 @@ def GetGroupBandsErr(self, parent): """ gr, s = self.GetData() - group = grass.find_file(name=gr, element="group") + group = gs.find_file(name=gr, element="group") bands = [] g = group["name"] @@ -617,7 +617,7 @@ def __init__( self.fileName = file - env = grass.gisenv() + env = gs.gisenv() # inconsistent group and subgroup name # path: @@ -785,7 +785,7 @@ def __layout(self): self.vectorNameCtrl = gselect.Select( parent=self.panel, type="vector", - mapsets=[grass.gisenv()["MAPSET"]], + mapsets=[gs.gisenv()["MAPSET"]], size=globalvar.DIALOG_GSELECT_SIZE, ) if self.vectorName: @@ -830,7 +830,7 @@ def OnOK(self, event): """Checks if map exists and can be overwritten.""" overwrite = UserSettings.Get(group="cmd", key="overwrite", subkey="enabled") vName = self.GetVectorName() - res = grass.find_file(vName, element="vector") + res = gs.find_file(vName, element="vector") if res["fullname"] and overwrite is False: qdlg = wx.MessageDialog( parent=self, diff --git a/gui/wxpython/iclass/digit.py b/gui/wxpython/iclass/digit.py index 1564c5ef445..691c1e75080 100644 --- a/gui/wxpython/iclass/digit.py +++ b/gui/wxpython/iclass/digit.py @@ -30,7 +30,7 @@ except ImportError: pass -import grass.script as grass +import grass.script as gs class IClassVDigitWindow(VDigitWindow): @@ -53,7 +53,7 @@ def _onLeftDown(self, event): if not action: return - region = grass.region() + region = gs.region() e, n = self.Pixel2Cell(event.GetPosition()) if not ( (region["s"] <= n <= region["n"]) and (region["w"] <= e <= region["e"]) diff --git a/gui/wxpython/iclass/frame.py b/gui/wxpython/iclass/frame.py index 5f383a7e058..3a8626a76ee 100644 --- a/gui/wxpython/iclass/frame.py +++ b/gui/wxpython/iclass/frame.py @@ -36,7 +36,7 @@ haveIClass = False errMsg = _("Loading imagery lib failed.\n%s") % e -import grass.script as grass +import grass.script as gs from mapdisp import statusbar as sb from mapdisp.main import StandaloneMapDisplayGrassInterface @@ -225,7 +225,7 @@ def _cleanup(self): def _getTempVectorName(self): """Return new name for temporary vector map (training areas)""" - vectorPath = grass.tempfile(create=False) + vectorPath = gs.tempfile(create=False) return "trAreas" + os.path.basename(vectorPath).replace(".", "") @@ -603,7 +603,7 @@ def AddBands(self): if dlg.ShowModal() == wx.ID_OK: if dlg.GetGroupBandsErr(parent=self): g, s = dlg.GetData() - group = grass.find_file(name=g, element="group") + group = gs.find_file(name=g, element="group") self.g["group"] = group["name"] self.g["subgroup"] = s self.groupSet.emit( @@ -644,7 +644,7 @@ def _checkImportedTopo(self, vector): :return: warning message (empty if topology is ok) """ - topo = grass.vector_info_topo(map=vector) + topo = gs.vector_info_topo(map=vector) warning = "" if topo["areas"] == 0: @@ -864,7 +864,7 @@ def ExportAreas(self, vectorName, withTable): return False try: - dbInfo = grass.vector_db(vectorName)[1] + dbInfo = gs.vector_db(vectorName)[1] except KeyError: wx.EndBusyCursor() return False @@ -1302,7 +1302,7 @@ def CheckInput(self, group, vector): regionBox = bound_box() Vect_get_map_box(self.poMapInfo, byref(regionBox)) - rasterInfo = grass.raster_info(groupLayers[0]) + rasterInfo = gs.raster_info(groupLayers[0]) if ( regionBox.N > rasterInfo["north"] diff --git a/gui/wxpython/iclass/g.gui.iclass.py b/gui/wxpython/iclass/g.gui.iclass.py index a452754bfb9..abf96a5f404 100755 --- a/gui/wxpython/iclass/g.gui.iclass.py +++ b/gui/wxpython/iclass/g.gui.iclass.py @@ -50,12 +50,12 @@ # %end import os -import grass.script as gscript +import grass.script as gs def main(): - gscript.set_raise_on_error(False) - options, flags = gscript.parser() + gs.set_raise_on_error(False) + options, flags = gs.parser() import wx @@ -71,28 +71,28 @@ def main(): if options["group"]: if not options["subgroup"]: - gscript.fatal(_("Name of subgroup required")) - group_name = gscript.find_file(name=options["group"], element="group")["name"] + gs.fatal(_("Name of subgroup required")) + group_name = gs.find_file(name=options["group"], element="group")["name"] if not group_name: - gscript.fatal(_("Group <%s> not found") % options["group"]) - subgroups = gscript.read_command( + gs.fatal(_("Group <%s> not found") % options["group"]) + subgroups = gs.read_command( "i.group", group=group_name, flags="sg" ).splitlines() if options["subgroup"] not in subgroups: - gscript.fatal(_("Subgroup <%s> not found") % options["subgroup"]) + gs.fatal(_("Subgroup <%s> not found") % options["subgroup"]) subgroup_name = options["subgroup"] if options["map"]: - map_name = gscript.find_file(name=options["map"], element="cell")["fullname"] + map_name = gs.find_file(name=options["map"], element="cell")["fullname"] if not map_name: - gscript.fatal(_("Raster map <%s> not found") % options["map"]) + gs.fatal(_("Raster map <%s> not found") % options["map"]) if options["trainingmap"]: - trainingmap_name = gscript.find_file( - name=options["trainingmap"], element="vector" - )["fullname"] + trainingmap_name = gs.find_file(name=options["trainingmap"], element="vector")[ + "fullname" + ] if not trainingmap_name: - gscript.fatal(_("Vector map <%s> not found") % options["trainingmap"]) + gs.fatal(_("Vector map <%s> not found") % options["trainingmap"]) # define display driver driver = UserSettings.Get(group="display", key="driver", subkey="type") diff --git a/gui/wxpython/iclass/statistics.py b/gui/wxpython/iclass/statistics.py index c083912988c..059ce5e6b03 100644 --- a/gui/wxpython/iclass/statistics.py +++ b/gui/wxpython/iclass/statistics.py @@ -20,7 +20,7 @@ import os from ctypes import * -import grass.script as grass +import grass.script as gs try: from grass.lib.imagery import * @@ -114,7 +114,7 @@ def SetBaseStatistics(self, cat, name, color): self.name = name self.color = color - rasterPath = grass.tempfile(create=False) + rasterPath = gs.tempfile(create=False) name = name.replace(" ", "_") self.rasterName = name + "_" + os.path.basename(rasterPath) @@ -135,12 +135,12 @@ def SetFromcStatistics(self, cStatistics): name = c_char_p() I_iclass_statistics_get_name(cStatistics, byref(name)) if self.name != name.value: - set_stats["name"] = grass.decode(name.value) + set_stats["name"] = gs.decode(name.value) color = c_char_p() I_iclass_statistics_get_color(cStatistics, byref(color)) if self.color != color.value: - set_stats["color"] = grass.decode(color.value) + set_stats["color"] = gs.decode(color.value) nbands = c_int() I_iclass_statistics_get_nbands(cStatistics, byref(nbands)) diff --git a/gui/wxpython/iclass/toolbars.py b/gui/wxpython/iclass/toolbars.py index 6ba1db44ae5..4ca67656fb9 100644 --- a/gui/wxpython/iclass/toolbars.py +++ b/gui/wxpython/iclass/toolbars.py @@ -26,7 +26,7 @@ from gui_core.forms import GUI from gui_core.wrap import StaticText -import grass.script as grass +import grass.script as gs iClassIcons = { "opacity": MetaIcon(img="layer-opacity", label=_("Set opacity level")), @@ -398,7 +398,7 @@ def OnSelectLayer(self, event): def OnAddRast(self, event): dlg = IClassMapDialog(self, title=_("Add raster map"), element="raster") if dlg.ShowModal() == wx.ID_OK: - raster = grass.find_file(name=dlg.GetMap(), element="cell") + raster = gs.find_file(name=dlg.GetMap(), element="cell") if raster["fullname"]: self.mapManager.AddLayer(name=raster["fullname"]) diff --git a/gui/wxpython/image2target/g.gui.image2target.py b/gui/wxpython/image2target/g.gui.image2target.py index d78ff78ae95..97c67b20354 100755 --- a/gui/wxpython/image2target/g.gui.image2target.py +++ b/gui/wxpython/image2target/g.gui.image2target.py @@ -104,14 +104,14 @@ import os -import grass.script as gscript +import grass.script as gs def main(): """ Sets the GRASS display driver """ - options, flags = gscript.parser() + options, flags = gs.parser() import wx diff --git a/gui/wxpython/image2target/ii2t_manager.py b/gui/wxpython/image2target/ii2t_manager.py index 2740d5c09a0..2367c053748 100644 --- a/gui/wxpython/image2target/ii2t_manager.py +++ b/gui/wxpython/image2target/ii2t_manager.py @@ -49,7 +49,7 @@ else: from wx import wizard as wiz -import grass.script as grass +import grass.script as gs from core import utils @@ -153,7 +153,7 @@ def __init__(self, parent, giface): # # get environmental variables # - self.grassdatabase = grass.gisenv()["GISDBASE"] + self.grassdatabase = gs.gisenv()["GISDBASE"] # # read original environment settings @@ -2304,13 +2304,13 @@ def OnZoomMenuGCP(self, event): def OnSize(self, event): """Adjust Map Windows after GCP Map Display has been resized""" # re-render image on idle - self.resize = grass.clock() + self.resize = gs.clock() super(MapPanel, self).OnSize(event) def OnIdle(self, event): """GCP Map Display resized, adjust Map Windows""" if self.GetMapToolbar(): - if self.resize and self.resize + 0.2 < grass.clock(): + if self.resize and self.resize + 0.2 < gs.clock(): srcwidth, srcheight = self.SrcMapWindow.GetSize() tgtwidth, tgtheight = self.TgtMapWindow.GetSize() srcwidth = (srcwidth + tgtwidth) / 2 diff --git a/gui/wxpython/iscatt/controllers.py b/gui/wxpython/iscatt/controllers.py index 3ebfa1a875b..e527d6b2edb 100644 --- a/gui/wxpython/iscatt/controllers.py +++ b/gui/wxpython/iscatt/controllers.py @@ -40,7 +40,7 @@ from iscatt.dialogs import AddScattPlotDialog, ExportCategoryRaster from iclass.dialogs import IClassGroupDialog -import grass.script as grass +import grass.script as gs from grass.pydispatch.signal import Signal @@ -969,7 +969,7 @@ def SetData(self): bands = dlg.GetGroupBandsErr(parent=self.scatt_mgr.guiparent) if bands: name, s = dlg.GetData() - group = grass.find_file(name=name, element="group") + group = gs.find_file(name=name, element="group") self.set_g["group"] = group["name"] self.set_g["subg"] = s @@ -988,7 +988,7 @@ def EmptyCategories(self): def UpdateCategoryRaster(self, cat_id, attrs, render=True): cat_rast = self.scatt_mgr.core.GetCatRast(cat_id) - if not grass.find_file(cat_rast, element="cell", mapset=".")["file"]: + if not gs.find_file(cat_rast, element="cell", mapset=".")["file"]: return cats_attrs = self.cats_mgr.GetCategoryAttrs(cat_id) @@ -1063,7 +1063,7 @@ def UpdateCategoryRaster(self, cat_id, attrs, render=True): if not cat_rast: return - if not grass.find_file(cat_rast, element="cell", mapset=".")["file"]: + if not gs.find_file(cat_rast, element="cell", mapset=".")["file"]: return cats_attrs = self.cats_mgr.GetCategoryAttrs(cat_id) train_mgr, preview_mgr = self.iclass_frame.GetMapManagers() diff --git a/gui/wxpython/iscatt/dialogs.py b/gui/wxpython/iscatt/dialogs.py index 5ac172515fe..4129015e88d 100644 --- a/gui/wxpython/iscatt/dialogs.py +++ b/gui/wxpython/iscatt/dialogs.py @@ -22,7 +22,7 @@ from gui_core.gselect import Select import wx.lib.colourselect as csel -import grass.script as grass +import grass.script as gs from core import globalvar from core.gcmd import GMessage @@ -286,7 +286,7 @@ def __layout(self): self.vectorNameCtrl = Select( parent=self.panel, type="raster", - mapsets=[grass.gisenv()["MAPSET"]], + mapsets=[gs.gisenv()["MAPSET"]], size=globalvar.DIALOG_GSELECT_SIZE, ) if self.rasterName: @@ -322,7 +322,7 @@ def OnOK(self, event): """Checks if map exists and can be overwritten.""" overwrite = UserSettings.Get(group="cmd", key="overwrite", subkey="enabled") rast_name = self.GetRasterName() - res = grass.find_file(rast_name, element="cell") + res = gs.find_file(rast_name, element="cell") if res["fullname"] and overwrite is False: qdlg = wx.MessageDialog( parent=self, diff --git a/gui/wxpython/iscatt/iscatt_core.py b/gui/wxpython/iscatt/iscatt_core.py index caa2916acce..c663233a5e8 100644 --- a/gui/wxpython/iscatt/iscatt_core.py +++ b/gui/wxpython/iscatt/iscatt_core.py @@ -30,7 +30,7 @@ from core.gcmd import GException, RunCommand -import grass.script as grass +import grass.script as gs from iscatt.core_c import CreateCatRast, ComputeScatts, UpdateCatRast, Rasterize @@ -361,7 +361,7 @@ def _create_grass_region_env(self, bbox): new_r["nsres"] = r["nsres"] new_r["ewres"] = r["ewres"] - return {"GRASS_REGION": grass.region_env(**new_r)} + return {"GRASS_REGION": gs.region_env(**new_r)} class AnalyzedData: @@ -446,7 +446,7 @@ def DeleteCategory(self, cat_id): return False for scatt in self.cats[cat_id].values(): - grass.try_remove(scatt["np_vals"]) + gs.try_remove(scatt["np_vals"]) del scatt["np_vals"] del self.cats[cat_id] @@ -476,7 +476,7 @@ def AddScattPlot(self, cat_id, scatt_id): b_i["b1"]["max"] - b_i["b1"]["min"] + 1, ) - np_vals = np.memmap(grass.tempfile(), dtype=self.dtype, mode="w+", shape=shape) + np_vals = np.memmap(gs.tempfile(), dtype=self.dtype, mode="w+", shape=shape) self.cats[cat_id][scatt_id] = {"np_vals": np_vals} @@ -580,7 +580,7 @@ def AddCategory(self, cat_id): self.cats_rasts_conds[cat_id] = None self.cats_rasts[cat_id] = None else: - self.cats_rasts_conds[cat_id] = grass.tempfile() + self.cats_rasts_conds[cat_id] = gs.tempfile() self.cats_rasts[cat_id] = "temp_cat_rast_%d_%d" % (cat_id, os.getpid()) region = self.an_data.GetRegion() CreateCatRast(region, self.cats_rasts_conds[cat_id]) @@ -590,7 +590,7 @@ def AddCategory(self, cat_id): def DeleteCategory(self, cat_id): ScattPlotsCondsData.DeleteCategory(self, cat_id) - grass.try_remove(self.cats_rasts_conds[cat_id]) + gs.try_remove(self.cats_rasts_conds[cat_id]) del self.cats_rasts_conds[cat_id] RunCommand("g.remove", flags="f", type="raster", name=self.cats_rasts[cat_id]) @@ -695,7 +695,7 @@ def eigsorted(cov): def CleanUp(self): ScattPlotsCondsData.CleanUp(self) for tmp in self.cats_rasts_conds.values(): - grass.try_remove(tmp) + gs.try_remove(tmp) for tmp in self.cats_rasts.values(): RunCommand("g.remove", flags="f", type="raster", name=tmp, getErrorMsg=True) diff --git a/gui/wxpython/iscatt/plots.py b/gui/wxpython/iscatt/plots.py index a955250db10..9930364c1b3 100644 --- a/gui/wxpython/iscatt/plots.py +++ b/gui/wxpython/iscatt/plots.py @@ -29,9 +29,9 @@ from gui_core.wrap import Menu, NewId try: - import matplotlib + import matplotlib as mpl - matplotlib.use("WXAgg") + mpl.use("WXAgg") from matplotlib.figure import Figure from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg as FigCanvas from matplotlib.lines import Line2D @@ -47,7 +47,7 @@ ).format(e) ) -import grass.script as grass +import grass.script as gs from grass.pydispatch.signal import Signal @@ -242,7 +242,7 @@ def Plot(self, cats_order, scatts, ellipses, styles): ) callafter_list.append([self.axes.draw_artist, [img]]) - callafter_list.append([grass.try_remove, [merged_img.filename]]) + callafter_list.append([gs.try_remove, [merged_img.filename]]) for cat_id in cats_order: if cat_id == 0: @@ -448,7 +448,7 @@ def MergeImg(cats_order, scatts, styles, rend_dt, output_queue): init = True merged_img = None - merge_tmp = grass.tempfile() + merge_tmp = gs.tempfile() for cat_id in cats_order: if cat_id not in scatts: continue @@ -496,7 +496,7 @@ def MergeImg(cats_order, scatts, styles, rend_dt, output_queue): rend_dt[cat_id]["color"] = styles[cat_id]["color"] rend_dt[cat_id]["dt"] = np.memmap( - grass.tempfile(), dtype="uint8", mode="w+", shape=(sh[0], sh[1], 4) + gs.tempfile(), dtype="uint8", mode="w+", shape=(sh[0], sh[1], 4) ) # colored_cat = np.zeros(dtype='uint8', ) @@ -580,7 +580,7 @@ def _renderCat(cat_id, rend_dt, scatt, styles): def _getColorMap(cat_id, styles): - cmap = matplotlib.cm.jet + cmap = mpl.cm.jet if cat_id == 0: cmap.set_bad("w", 1.0) cmap._init() @@ -1035,7 +1035,7 @@ def imshow( if norm is not None: assert isinstance(norm, mcolors.Normalize) if aspect is None: - aspect = matplotlib.rcParams["image.aspect"] + aspect = mpl.rcParams["image.aspect"] axes.set_aspect(aspect) if extent: diff --git a/gui/wxpython/lmgr/pyshell.py b/gui/wxpython/lmgr/pyshell.py index 5bb1cb2d0dd..ffbb8f67a92 100644 --- a/gui/wxpython/lmgr/pyshell.py +++ b/gui/wxpython/lmgr/pyshell.py @@ -26,7 +26,7 @@ from wx.py.shell import Shell as PyShell from wx.py.version import VERSION -import grass.script as grass +import grass.script as gs from gui_core.wrap import Button, ClearButton, IsDark from gui_core.pystc import SetDarkMode @@ -58,7 +58,7 @@ def __init__( "parent": self, "id": wx.ID_ANY, "introText": self.intro, - "locals": {"gs": grass, "AddLayer": self.AddLayer, "help": self.Help}, + "locals": {"gs": gs, "AddLayer": self.AddLayer, "help": self.Help}, } # useStockId (available since wxPython 4.0.2) should be False on macOS if sys.platform == "darwin" and CheckWxVersion([4, 0, 2]): @@ -119,14 +119,14 @@ def AddLayer(self, name, ltype="auto"): fname = None if ltype == "raster" or ltype != "vector": # check for raster - fname = grass.find_file(name, element="cell")["fullname"] + fname = gs.find_file(name, element="cell")["fullname"] if fname: ltype = "raster" lcmd = "d.rast" if not fname and (ltype == "vector" or ltype != "raster"): # if not found check for vector - fname = grass.find_file(name, element="vector")["fullname"] + fname = gs.find_file(name, element="vector")["fullname"] if fname: ltype = "vector" lcmd = "d.vect" diff --git a/gui/wxpython/location_wizard/dialogs.py b/gui/wxpython/location_wizard/dialogs.py index da706b96599..aa3954dab25 100644 --- a/gui/wxpython/location_wizard/dialogs.py +++ b/gui/wxpython/location_wizard/dialogs.py @@ -757,11 +757,11 @@ def GetTransform(self): def testRegionDef(): import wx.lib.inspection - import grass.script as gscript + import grass.script as gs app = wx.App() - dlg = RegionDef(None, location=gscript.gisenv()["LOCATION_NAME"]) + dlg = RegionDef(None, location=gs.gisenv()["LOCATION_NAME"]) dlg.Show() wx.lib.inspection.InspectionTool().Show() app.MainLoop() diff --git a/gui/wxpython/mapdisp/frame.py b/gui/wxpython/mapdisp/frame.py index 7f3a1d519d5..96f147c3cb0 100644 --- a/gui/wxpython/mapdisp/frame.py +++ b/gui/wxpython/mapdisp/frame.py @@ -58,7 +58,7 @@ from mapdisp import statusbar as sb from main_window.page import MainPageBase -import grass.script as grass +import grass.script as gs from grass.pydispatch.signal import Signal @@ -830,12 +830,12 @@ def _DToRastDone(): self._giface.WriteError(_("Failed to run d.to.rast:\n") + messages) return # set region for composite - grass.use_temp_region() + gs.use_temp_region() returncode, messages = RunCommand( "g.region", raster=tmpName + ".red", quiet=True, getErrorMsg=True ) if not returncode == 0: - grass.del_temp_region() + gs.del_temp_region() self._giface.WriteError(_("Failed to run d.to.rast:\n") + messages) return # composite @@ -849,7 +849,7 @@ def _DToRastDone(): overwrite=overwrite, getErrorMsg=True, ) - grass.del_temp_region() + gs.del_temp_region() RunCommand( "g.remove", type="raster", @@ -859,7 +859,7 @@ def _DToRastDone(): ) if not returncode == 0: self._giface.WriteError(_("Failed to run d.to.rast:\n") + messages) - grass.try_remove(pngFile) + gs.try_remove(pngFile) return # alignExtent changes only region variable @@ -876,7 +876,7 @@ def _DToRastDone(): w=region["w"], quiet=True, ) - grass.try_remove(pngFile) + gs.try_remove(pngFile) if self.IsPaneShown("3d"): self._giface.WriteError(_("d.to.rast can be used only in 2D mode.")) @@ -896,7 +896,7 @@ def _DToRastDone(): return # output file as PNG tmpName = "d_to_rast_tmp" - pngFile = grass.tempfile(create=False) + ".png" + pngFile = gs.tempfile(create=False) + ".png" dOutFileCmd = ["d.out.file", "output=" + pngFile, "format=png"] self.DOutFile(dOutFileCmd, callback=_DToRastDone) @@ -1082,21 +1082,21 @@ def QueryMap(self, east, north, qdist, rast, vect): vectQuery = [] env = os.environ.copy() for raster in rast: - env["GRASS_REGION"] = grass.region_env(raster=raster) - rastQuery += grass.raster_what( + env["GRASS_REGION"] = gs.region_env(raster=raster) + rastQuery += gs.raster_what( map=raster, coord=(east, north), localized=True, env=env ) if vect: encoding = UserSettings.Get(group="atm", key="encoding", subkey="value") try: - vectQuery = grass.vector_what( + vectQuery = gs.vector_what( map=vect, coord=(east, north), distance=qdist, encoding=encoding, multiple=True, ) - except grass.ScriptError: + except gs.ScriptError: GError( parent=self, message=_( @@ -1628,7 +1628,7 @@ def AddRDigit(self): ), ) rasters = self.GetMap().GetListOfLayers( - ltype="raster", mapset=grass.gisenv()["MAPSET"] + ltype="raster", mapset=gs.gisenv()["MAPSET"] ) self.toolbars["rdigit"].UpdateRasterLayers(rasters) self.toolbars["rdigit"].SelectDefault() @@ -1659,7 +1659,7 @@ def AddRDigit(self): self.rdigit.Start() def _updateRDigitLayers(self, layer): - mapset = grass.gisenv()["MAPSET"] + mapset = gs.gisenv()["MAPSET"] self.toolbars["rdigit"].UpdateRasterLayers( rasters=self.GetMap().GetListOfLayers(ltype="raster", mapset=mapset) ) diff --git a/gui/wxpython/mapdisp/test_mapdisp.py b/gui/wxpython/mapdisp/test_mapdisp.py index d3b6850eba7..7a61e196ba9 100755 --- a/gui/wxpython/mapdisp/test_mapdisp.py +++ b/gui/wxpython/mapdisp/test_mapdisp.py @@ -53,7 +53,7 @@ import sys import wx -import grass.script as grass +import grass.script as gs from grass.script.setup import set_gui_path @@ -88,7 +88,7 @@ def GetMapWindow(self): # this is a copy of method from some frame class def copyOfInitMap(map_, width, height): """Initialize map display, set dimensions and map region""" - if not grass.find_program("g.region", "--help"): + if not gs.find_program("g.region", "--help"): sys.exit( _("GRASS module '%s' not found. Unable to start map display window.") % "g.region" @@ -306,7 +306,7 @@ def main(): # TODO: should messages here be translatable? # (for test its great, for translator not) - options, flags = grass.parser() + options, flags = gs.parser() test = options["test"] app = wx.App() @@ -356,9 +356,7 @@ def main(): tester.testMapWindowRlisetup(map_) else: # TODO: this should not happen but happens - import grass.script as sgrass - - sgrass.fatal(_("Unknown value %s of test parameter." % test)) + gs.fatal(_("Unknown value %s of test parameter." % test)) app.MainLoop() diff --git a/gui/wxpython/mapswipe/frame.py b/gui/wxpython/mapswipe/frame.py index ad9c54118c9..1f4c3e964fe 100644 --- a/gui/wxpython/mapswipe/frame.py +++ b/gui/wxpython/mapswipe/frame.py @@ -19,7 +19,7 @@ import os import wx -import grass.script as grass +import grass.script as gs from gui_core.mapdisp import DoubleMapPanel, FrameMixin from gui_core.dialogs import GetImageHandlers @@ -222,11 +222,11 @@ def OnSashChanged(self, event): def OnSize(self, event): Debug.msg(4, "SwipeMapPanel.OnSize()") - self.resize = grass.clock() + self.resize = gs.clock() super().OnSize(event) def OnIdle(self, event): - if self.resize and grass.clock() - self.resize > 0.2: + if self.resize and gs.clock() - self.resize > 0.2: w1 = self.GetFirstWindow() w2 = self.GetSecondWindow() @@ -472,7 +472,7 @@ def OnApplyInputChanges(self): def SetFirstRaster(self, name): """Set raster map to first Map""" if name: - raster = grass.find_file(name=name, element="cell") + raster = gs.find_file(name=name, element="cell") if raster.get("fullname"): self.rasters["first"] = raster["fullname"] self.SetLayer(name=raster["fullname"], mapInstance=self.GetFirstMap()) @@ -483,7 +483,7 @@ def SetFirstRaster(self, name): def SetSecondRaster(self, name): """Set raster map to second Map""" if name: - raster = grass.find_file(name=name, element="cell") + raster = gs.find_file(name=name, element="cell") if raster.get("fullname"): self.rasters["second"] = raster["fullname"] self.SetLayer(name=raster["fullname"], mapInstance=self.GetSecondMap()) @@ -536,8 +536,8 @@ def _saveToFile(self, fileName, fileType): w2 = self.splitter.GetWindow2() lineWidth = 1 # render to temporary files - filename1 = grass.tempfile(False) + "1" - filename2 = grass.tempfile(False) + "2" + filename1 = gs.tempfile(False) + "1" + filename2 = gs.tempfile(False) + "2" width, height = self.splitter.GetClientSize() class _onDone: @@ -581,8 +581,8 @@ def process(self2): im.SaveFile(fileName, fileType) # remove temporary files - grass.try_remove(filename1) - grass.try_remove(filename2) + gs.try_remove(filename1) + gs.try_remove(filename2) callback = _onDone() if self._mode == "swipe": @@ -755,27 +755,27 @@ def Query(self, x, y): env = os.environ.copy() if rasters[0]: for raster in rasters[0]: - env["GRASS_REGION"] = grass.region_env(raster=raster) + env["GRASS_REGION"] = gs.region_env(raster=raster) result.extend( - grass.raster_what( + gs.raster_what( map=raster, coord=(east, north), localized=True, env=env ) ) if vectors[0]: result.extend( - grass.vector_what(map=vectors[0], coord=(east, north), distance=qdist) + gs.vector_what(map=vectors[0], coord=(east, north), distance=qdist) ) if rasters[1]: for raster in rasters[1]: - env["GRASS_REGION"] = grass.region_env(raster=raster) + env["GRASS_REGION"] = gs.region_env(raster=raster) result.extend( - grass.raster_what( + gs.raster_what( map=raster, coord=(east, north), localized=True, env=env ) ) if vectors[1]: result.extend( - grass.vector_what(map=vectors[1], coord=(east, north), distance=qdist) + gs.vector_what(map=vectors[1], coord=(east, north), distance=qdist) ) result = PrepareQueryResults(coordinates=(east, north), result=result) diff --git a/gui/wxpython/mapswipe/g.gui.mapswipe.py b/gui/wxpython/mapswipe/g.gui.mapswipe.py index c887be2548d..d4f19c0244a 100755 --- a/gui/wxpython/mapswipe/g.gui.mapswipe.py +++ b/gui/wxpython/mapswipe/g.gui.mapswipe.py @@ -45,11 +45,11 @@ # %end import os -import grass.script as gscript +import grass.script as gs def main(): - options, flags = gscript.parser() + options, flags = gs.parser() import wx @@ -74,9 +74,9 @@ def main(): for mapName in [first, second]: if mapName: - gfile = gscript.find_file(name=mapName) + gfile = gs.find_file(name=mapName) if not gfile["name"]: - gscript.fatal(_("Raster map <%s> not found") % mapName) + gs.fatal(_("Raster map <%s> not found") % mapName) app = wx.App() diff --git a/gui/wxpython/mapwin/buffered.py b/gui/wxpython/mapwin/buffered.py index 3d096031a1d..ad7bcd986a1 100644 --- a/gui/wxpython/mapwin/buffered.py +++ b/gui/wxpython/mapwin/buffered.py @@ -31,7 +31,7 @@ from grass.pydispatch.signal import Signal from core.globalvar import wxPythonPhoenix -import grass.script as grass +import grass.script as gs from gui_core.dialogs import SavedRegion from gui_core.wrap import ( @@ -664,7 +664,7 @@ def OnPaint(self, event): def OnSize(self, event): """Scale map image so that it is the same size as the Window""" # re-render image on idle - self.resize = grass.clock() + self.resize = gs.clock() def OnIdle(self, event): """Only re-render a composite map image from GRASS during @@ -673,7 +673,7 @@ def OnIdle(self, event): # use OnInternalIdle() instead ? - if self.resize and self.resize + 0.2 < grass.clock(): + if self.resize and self.resize + 0.2 < gs.clock(): Debug.msg(3, "BufferedWindow.OnSize():") # set size of the input image @@ -2129,7 +2129,7 @@ def SetRegion(self, zoomOnly=True): return region = dlg.GetName() - if not grass.find_file(name=region, element="windows")["name"]: + if not gs.find_file(name=region, element="windows")["name"]: GError( parent=self, message=_("Region <%s> not found. Operation canceled.") % region, @@ -2171,7 +2171,7 @@ def SaveRegion(self, display=True): return # test to see if it already exists and ask permission to overwrite - if grass.find_file(name=dlg.GetName(), element="windows")["name"]: + if gs.find_file(name=dlg.GetName(), element="windows")["name"]: overwrite = wx.MessageBox( parent=self, message=_( diff --git a/gui/wxpython/modules/colorrules.py b/gui/wxpython/modules/colorrules.py index 2fb97ae3aab..6feeb22cab2 100644 --- a/gui/wxpython/modules/colorrules.py +++ b/gui/wxpython/modules/colorrules.py @@ -32,7 +32,7 @@ import wx.lib.scrolledpanel as scrolled import wx.lib.filebrowsebutton as filebrowse -import grass.script as grass +import grass.script as gs from grass.script.task import cmdlist_to_tuple from core import globalvar @@ -941,7 +941,7 @@ def OnSelectionInput(self, event): self.saveRules.SetValue("") if self.inmap: - if not grass.find_file(name=self.inmap, element="cell")["file"]: + if not gs.find_file(name=self.inmap, element="cell")["file"]: self.inmap = None if not self.inmap: @@ -956,7 +956,7 @@ def OnSelectionInput(self, event): self.LoadTable() return - info = grass.raster_info(map=self.inmap) + info = gs.raster_info(map=self.inmap) if info: self.properties["min"] = info["min"] @@ -1013,15 +1013,15 @@ def OnPreview(self, tmp=True): name, mapset = self.inmap.split("@") except ValueError: name = self.inmap - mapset = grass.find_file(self.inmap, element="cell")["mapset"] + mapset = gs.find_file(self.inmap, element="cell")["mapset"] if not mapset: return self._tmp = tmp self._old_colrtable = None - if mapset == grass.gisenv()["MAPSET"]: - self._old_colrtable = grass.find_file(name=name, element="colr")["file"] + if mapset == gs.gisenv()["MAPSET"]: + self._old_colrtable = gs.find_file(name=name, element="colr")["file"] else: - self._old_colrtable = grass.find_file(name=name, element="colr2/" + mapset)[ + self._old_colrtable = gs.find_file(name=name, element="colr2/" + mapset)[ "file" ] @@ -1055,7 +1055,7 @@ def __init__(self, parent, attributeType, **kwargs): self.mapType = "vector" self.attributeType = attributeType # color, size, width # in version 7 v.colors used, otherwise color column only - self.version7 = int(grass.version()["version"].split(".")[0]) >= 7 + self.version7 = int(gs.version()["version"].split(".")[0]) >= 7 self.colorTable = False self.updateColumn = True # vector properties @@ -1244,8 +1244,8 @@ def OnPaneChanged(self, event=None): def CheckMapset(self): """Check if current vector is in current mapset""" if ( - grass.find_file(name=self.inmap, element="vector")["mapset"] - == grass.gisenv()["MAPSET"] + gs.find_file(name=self.inmap, element="vector")["mapset"] + == gs.gisenv()["MAPSET"] ): return True else: @@ -1320,7 +1320,7 @@ def OnSelectionInput(self, event): self.saveRules.SetValue("") if self.inmap: - if not grass.find_file(name=self.inmap, element="vector")["file"]: + if not gs.find_file(name=self.inmap, element="vector")["file"]: self.inmap = None self.UpdateDialog() @@ -1338,7 +1338,7 @@ def UpdateDialog(self): message = _( "Selected map <%(map)s> is not in current mapset <%(mapset)s>. " "Attribute table cannot be edited." - ) % {"map": self.inmap, "mapset": grass.gisenv()["MAPSET"]} + ) % {"map": self.inmap, "mapset": gs.gisenv()["MAPSET"]} wx.CallAfter(GMessage, parent=self, message=message) self.DisableClearAll() return @@ -1732,17 +1732,17 @@ def OnTablePreview(self, tmp): name, mapset = self.inmap.split("@") except ValueError: name = self.inmap - mapset = grass.find_file(self.inmap, element="cell")["mapset"] + mapset = gs.find_file(self.inmap, element="cell")["mapset"] if not mapset: return old_colrtable = None - if mapset == grass.gisenv()["MAPSET"]: - old_colrtable = grass.find_file( + if mapset == gs.gisenv()["MAPSET"]: + old_colrtable = gs.find_file( name="colr", element=os.path.join("vector", name) )["file"] else: - old_colrtable = grass.find_file( + old_colrtable = gs.find_file( name=name, element=os.path.join("vcolr2", mapset) )["file"] diff --git a/gui/wxpython/modules/mcalc_builder.py b/gui/wxpython/modules/mcalc_builder.py index 221e5198955..e157375b4a4 100644 --- a/gui/wxpython/modules/mcalc_builder.py +++ b/gui/wxpython/modules/mcalc_builder.py @@ -20,7 +20,7 @@ import re import wx -import grass.script as grass +import grass.script as gs from core import globalvar from core.gcmd import GError, RunCommand @@ -700,14 +700,14 @@ def OnDone(self, event): """ if event.returncode != 0: return - name = self.newmaptxt.GetValue().strip(' "') + "@" + grass.gisenv()["MAPSET"] + name = self.newmaptxt.GetValue().strip(' "') + "@" + gs.gisenv()["MAPSET"] ltype = "raster" if self.rast3d: ltype = "raster_3d" self._giface.mapCreated.emit( name=name, ltype=ltype, add=self.addbox.IsChecked() ) - gisenv = grass.gisenv() + gisenv = gs.gisenv() self._giface.grassdbChanged.emit( grassdb=gisenv["GISDBASE"], location=gisenv["LOCATION_NAME"], diff --git a/gui/wxpython/nviz/mapwindow.py b/gui/wxpython/nviz/mapwindow.py index 40fb23e6a38..3d282cc3c14 100644 --- a/gui/wxpython/nviz/mapwindow.py +++ b/gui/wxpython/nviz/mapwindow.py @@ -31,7 +31,7 @@ from wx import glcanvas from wx.glcanvas import WX_GL_RGBA, WX_GL_DOUBLEBUFFER, WX_GL_DEPTH_SIZE -import grass.script as grass +import grass.script as gs from grass.pydispatch.signal import Signal from core.gcmd import GMessage, GException, GError @@ -1190,7 +1190,7 @@ def UpdateMap(self, render=True, reRenderTool=False): if not self.parent.mapWindowProperties.autoRender and not reRenderTool: return - start = grass.clock() + start = gs.clock() self.resize = False @@ -1234,7 +1234,7 @@ def UpdateMap(self, render=True, reRenderTool=False): self._display.Start2D() self.DrawImages() - stop = grass.clock() + stop = gs.clock() if self.render["quick"] is False: if sys.platform != "darwin": @@ -1364,7 +1364,7 @@ def LoadDataLayers(self): item = self.tree.GetFirstChild(self.tree.root)[0] self._GetDataLayers(item, listOfItems) - start = grass.clock() + start = gs.clock() while len(listOfItems) > 0: item = listOfItems.pop() @@ -1382,7 +1382,7 @@ def LoadDataLayers(self): self.LoadRaster3d(item) elif type == "vector": layer = self.tree.GetLayerInfo(item, key="maplayer") - vInfo = grass.vector_info_topo(layer.GetName()) + vInfo = gs.vector_info_topo(layer.GetName()) if (vInfo["points"]) > 0: # include vInfo['centroids'] to initially load # centroids @@ -1399,7 +1399,7 @@ def LoadDataLayers(self): except: pass - stop = grass.clock() + stop = gs.clock() Debug.msg(1, "GLWindow.LoadDataLayers(): time = %f" % (stop - start)) @@ -1416,7 +1416,7 @@ def UnloadDataLayers(self, force=False): item = self.tree.GetFirstChild(self.tree.root)[0] self._GetDataLayers(item, listOfItems) - start = grass.clock() + start = gs.clock() update = False layersTmp = self.layers[:] @@ -1431,7 +1431,7 @@ def UnloadDataLayers(self, force=False): self.UnloadRaster3d(layer) elif ltype == "vector": maplayer = self.tree.GetLayerInfo(layer, key="maplayer") - vInfo = grass.vector_info_topo(maplayer.GetName()) + vInfo = gs.vector_info_topo(maplayer.GetName()) if (vInfo["points"] + vInfo["centroids"]) > 0: self.UnloadVector(layer, points=True) if (vInfo["lines"] + vInfo["boundaries"]) > 0 or vInfo["map3d"]: @@ -1447,7 +1447,7 @@ def UnloadDataLayers(self, force=False): self.lmgr.nviz.UpdateSettings() self.UpdateView(None) - stop = grass.clock() + stop = gs.clock() Debug.msg(1, "GLWindow.UnloadDataLayers(): time = %f" % (stop - start)) @@ -1883,12 +1883,12 @@ def ResetView(self): # hack for latlon projection # TODO find more precise way or better rewrite it in OGSF self.iview["z-exag"]["llRatio"] = 1 - if grass.locn_is_latlong(): + if gs.locn_is_latlong(): self.iview["z-exag"]["llRatio"] = ( math.pi / 180 * 6371000 - * math.cos((grass.region()["n"] + grass.region()["s"]) / 2) + * math.cos((gs.region()["n"] + gs.region()["s"]) / 2) ) self.view["z-exag"]["value"] = round( @@ -1996,7 +1996,7 @@ def UpdateSurfaceProperties(self, id, data): if isinstance(value, str): if len(value) == 0: # ignore empty values (TODO: warning) continue - if map and not grass.find_file(value, element="cell")["fullname"]: + if map and not gs.find_file(value, element="cell")["fullname"]: continue if attrb == "color": self._display.SetSurfaceColor(id, map, str(value)) @@ -2115,10 +2115,7 @@ def UpdateVolumeProperties(self, id, data, isosurfId=None): if isinstance(value, str): if len(value) == 0: # ignore empty values (TODO: warning) continue - if ( - map - and not grass.find_file(value, element="grid3")["fullname"] - ): + if map and not gs.find_file(value, element="grid3")["fullname"]: continue if attrb == "color": self._display.SetIsosurfaceColor(id, isosurfId, map, str(value)) @@ -2387,7 +2384,7 @@ def ReloadLayersData(self): if type == "raster": self.nvizDefault.SetSurfaceDefaultProp(data["surface"]) if type == "vector": - vInfo = grass.vector_info_topo(layer.GetName()) + vInfo = gs.vector_info_topo(layer.GetName()) if (vInfo["points"] + vInfo["centroids"]) > 0: self.nvizDefault.SetVectorPointsDefaultProp( data["vector"]["points"], self._display.GetLongDim() @@ -2529,7 +2526,7 @@ def NvizCmdCommand(self): ] for vector in vectors: layerName = self.tree.GetLayerInfo(vector, key="maplayer").GetName() - vInfo = grass.vector_info_topo(layerName) + vInfo = gs.vector_info_topo(layerName) nvizData = self.tree.GetLayerInfo(vector, key="nviz")["vector"] if (vInfo["lines"] + vInfo["boundaries"]) > 0: cmdLines += ( diff --git a/gui/wxpython/nviz/tools.py b/gui/wxpython/nviz/tools.py index cff26db4ca8..1814772839c 100644 --- a/gui/wxpython/nviz/tools.py +++ b/gui/wxpython/nviz/tools.py @@ -43,7 +43,7 @@ import wx.lib.agw.floatspin as fs except ImportError: fs = None -import grass.script as grass +import grass.script as gs from core import globalvar from gui_core.gselect import VectorDBInfo @@ -5377,7 +5377,7 @@ def UpdateCPlanePage(self, index): def UpdateSurfacePage(self, layer, data, updateName=True): """Update surface page""" - desc = grass.raster_info(layer.name)["title"] + desc = gs.raster_info(layer.name)["title"] if updateName: self.FindWindowById(self.win["surface"]["map"]).SetValue(layer.name) self.FindWindowById(self.win["surface"]["desc"]).SetLabel(desc) @@ -5503,7 +5503,7 @@ def UpdateSurfacePage(self, layer, data, updateName=True): def UpdateVectorPage(self, layer, data, updateName=True): """Update vector page""" - vInfo = grass.vector_info_topo(layer.GetName()) + vInfo = gs.vector_info_topo(layer.GetName()) if not vInfo: return if vInfo["map3d"]: diff --git a/gui/wxpython/nviz/wxnviz.py b/gui/wxpython/nviz/wxnviz.py index 2ca63708f0d..f967d830d5d 100644 --- a/gui/wxpython/nviz/wxnviz.py +++ b/gui/wxpython/nviz/wxnviz.py @@ -61,7 +61,7 @@ from core.gcmd import DecodeString from core.globalvar import wxPythonPhoenix from gui_core.wrap import Rect -import grass.script as grass +import grass.script as gs log = None progress = None @@ -2162,7 +2162,7 @@ def __del__(self): """Delete texture""" if self.textureId: Nviz_del_texture(self.textureId) - grass.try_remove(self.path) + gs.try_remove(self.path) def Resize(self): """Resize image to match 2^n""" diff --git a/gui/wxpython/photo2image/g.gui.photo2image.py b/gui/wxpython/photo2image/g.gui.photo2image.py index 315f33fe6f1..21635175374 100755 --- a/gui/wxpython/photo2image/g.gui.photo2image.py +++ b/gui/wxpython/photo2image/g.gui.photo2image.py @@ -71,12 +71,12 @@ @author Vaclav Petras (standalone module) """ import os -import grass.script as gscript +import grass.script as gs def main(): """Sets the GRASS display driver""" - options, flags = gscript.parser() + options, flags = gs.parser() import wx from grass.script.setup import set_gui_path @@ -96,29 +96,29 @@ def main(): if options["group"]: group = options["group"] else: - gscript.fatal(_("Please provide a group name to process")) + gs.fatal(_("Please provide a group name to process")) if options["raster"]: raster = options["raster"] else: - gscript.fatal(_("Please provide a raster map name to process")) + gs.fatal(_("Please provide a raster map name to process")) if options["camera"]: camera = options["camera"] else: - gscript.fatal(_("Please provide a camera name (generated by i.ortho.camera)")) + gs.fatal(_("Please provide a camera name (generated by i.ortho.camera)")) if options["order"]: order = options["order"] else: - gscript.fatal( + gs.fatal( _("Please provive an order value (1 if 4 Fiducials, 2 if 8 Fiducials)") ) if options["extension"]: extension = options["extension"] else: - gscript.fatal(_("Please provive an output files extension (used by i.rectify)")) + gs.fatal(_("Please provive an output files extension (used by i.rectify)")) app = wx.App() diff --git a/gui/wxpython/photo2image/ip2i_manager.py b/gui/wxpython/photo2image/ip2i_manager.py index 34346f39cae..10439b7b390 100644 --- a/gui/wxpython/photo2image/ip2i_manager.py +++ b/gui/wxpython/photo2image/ip2i_manager.py @@ -35,7 +35,7 @@ from wx.lib.mixins.listctrl import ColumnSorterMixin, ListCtrlAutoWidthMixin import wx.lib.colourselect as csel -import grass.script as grass +import grass.script as gs from core import utils, globalvar from core.render import Map @@ -113,7 +113,7 @@ def __init__( # # get environmental variables # - self.grassdatabase = grass.gisenv()["GISDBASE"] + self.grassdatabase = gs.gisenv()["GISDBASE"] # # read original environment settings @@ -1585,13 +1585,13 @@ def OnZoomMenuGCP(self, event): def OnSize(self, event): """Adjust Map Windows after GCP Map Display has been resized""" # re-render image on idle - self.resize = grass.clock() + self.resize = gs.clock() super(MapPanel, self).OnSize(event) def OnIdle(self, event): """GCP Map Display resized, adjust Map Windows""" if self.GetMapToolbar(): - if self.resize and self.resize + 0.2 < grass.clock(): + if self.resize and self.resize + 0.2 < gs.clock(): srcwidth, srcheight = self.SrcMapWindow.GetSize() tgtwidth, tgtheight = self.TgtMapWindow.GetSize() srcwidth = (srcwidth + tgtwidth) / 2 diff --git a/gui/wxpython/psmap/dialogs.py b/gui/wxpython/psmap/dialogs.py index 7924b3d807e..73653bbfd3a 100644 --- a/gui/wxpython/psmap/dialogs.py +++ b/gui/wxpython/psmap/dialogs.py @@ -49,7 +49,7 @@ else: from wx import PyValidator as Validator -import grass.script as grass +import grass.script as gs from core.utils import PilImageToWxImage from dbmgr.vinfo import VectorDBInfo @@ -1376,7 +1376,7 @@ def update(self): if mapFrameDict["drawMap"]: if mapFrameDict["mapType"] == "raster": - mapFile = grass.find_file(mapFrameDict["map"], element="cell") + mapFile = gs.find_file(mapFrameDict["map"], element="cell") if mapFile["file"] == "": GMessage("Raster %s not found" % mapFrameDict["map"]) return False @@ -1390,7 +1390,7 @@ def update(self): self.instruction.AddInstruction(raster) elif mapFrameDict["mapType"] == "vector": - mapFile = grass.find_file(mapFrameDict["map"], element="vector") + mapFile = gs.find_file(mapFrameDict["map"], element="vector") if mapFile["file"] == "": GMessage("Vector %s not found" % mapFrameDict["map"]) return False @@ -1402,7 +1402,7 @@ def update(self): if each[0] == mapFrameDict["map"]: isAdded = True if not isAdded: - topoInfo = grass.vector_info_topo(map=mapFrameDict["map"]) + topoInfo = gs.vector_info_topo(map=mapFrameDict["map"]) if topoInfo: if bool(topoInfo["areas"]): topoType = "areas" @@ -1449,7 +1449,7 @@ def update(self): mapFrameDict["center"] = self.center[0] # set region if self.mapType == "raster": - self.env["GRASS_REGION"] = grass.region_env( + self.env["GRASS_REGION"] = gs.region_env( raster=mapFrameDict["map"], env=self.env ) if self.mapType == "vector": @@ -1460,13 +1460,13 @@ def update(self): rasterId = None if rasterId: - self.env["GRASS_REGION"] = grass.region_env( + self.env["GRASS_REGION"] = gs.region_env( vector=mapFrameDict["map"], raster=self.instruction[rasterId]["raster"], env=self.env, ) else: - self.env["GRASS_REGION"] = grass.region_env( + self.env["GRASS_REGION"] = gs.region_env( vector=mapFrameDict["map"], env=self.env ) @@ -1499,7 +1499,7 @@ def update(self): mapFrameDict["scale"] = self.scale[1] mapFrameDict["center"] = self.center[1] # set region - self.env["GRASS_REGION"] = grass.region_env( + self.env["GRASS_REGION"] = gs.region_env( region=mapFrameDict["region"], env=self.env ) else: @@ -1525,7 +1525,7 @@ def update(self): mapFrameDict["scale"] = self.scale[2] mapFrameDict["center"] = self.center[2] - region = grass.region(env=None) + region = gs.region(env=None) raster = self.instruction.FindInstructionByType("raster") if raster: @@ -1534,7 +1534,7 @@ def update(self): rasterId = None if rasterId: # because of resolution - self.env["GRASS_REGION"] = grass.region_env( + self.env["GRASS_REGION"] = gs.region_env( n=region["n"], s=region["s"], e=region["e"], @@ -1543,7 +1543,7 @@ def update(self): env=self.env, ) else: - self.env["GRASS_REGION"] = grass.region_env( + self.env["GRASS_REGION"] = gs.region_env( n=region["n"], s=region["s"], e=region["e"], @@ -1888,13 +1888,13 @@ def _layout(self): def OnVector(self, event): """Gets info about toplogy and enables/disables choices point/line/area""" vmap = self.select.GetValue() - if not grass.find_file( + if not gs.find_file( vmap, element="vector", )["name"]: return - topoInfo = grass.vector_info_topo(map=vmap) + topoInfo = gs.vector_info_topo(map=vmap) if topoInfo: self.vectorType.EnableItem(2, bool(topoInfo["areas"])) self.vectorType.EnableItem( @@ -2178,7 +2178,7 @@ def __init__(self, parent, id, vectors, tmpSettings): try: self.mapDBInfo = VectorDBInfo(self.vectorName) self.layers = self.mapDBInfo.layers.keys() - except grass.ScriptError: + except gs.ScriptError: self.connection = False self.layers = [] if not self.layers: @@ -3540,7 +3540,7 @@ def _rasterLegend(self, notebook): self.ticks.SetValue(False) # range if self.rasterId and self.instruction[self.rasterId]["raster"]: - rinfo = grass.raster_info(self.instruction[self.rasterId]["raster"]) + rinfo = gs.raster_info(self.instruction[self.rasterId]["raster"]) self.minim, self.maxim = rinfo["min"], rinfo["max"] else: self.minim, self.maxim = 0, 0 @@ -4918,7 +4918,7 @@ def _scalebarPanel(self): if self.scalebarDict["length"]: self.lengthTextCtrl.SetValue(str(self.scalebarDict["length"])) else: # estimate default - reg = grass.region(env=self.env) + reg = gs.region(env=self.env) w = int((reg["e"] - reg["w"]) / 3) w = round(w, -len(str(w)) + 2) # 12345 -> 12000 self.lengthTextCtrl.SetValue(str(w)) diff --git a/gui/wxpython/psmap/frame.py b/gui/wxpython/psmap/frame.py index 26fa77053ef..650d970b10d 100644 --- a/gui/wxpython/psmap/frame.py +++ b/gui/wxpython/psmap/frame.py @@ -28,7 +28,7 @@ except ImportError: import wx.lib.flatnotebook as FN -import grass.script as grass +import grass.script as gs from core import globalvar from gui_core.menu import Menu @@ -170,8 +170,8 @@ def __init__( self.getInitMap() # image path - env = grass.gisenv() - self.imgName = grass.tempfile() + env = gs.gisenv() + self.imgName = gs.tempfile() # canvas for preview self.previewCanvas = PsMapBufferedWindow( @@ -310,7 +310,7 @@ def OnPDFFile(self, event): """Generate PDF from PS with ps2pdf if available""" if not sys.platform == "win32": try: - p = grass.Popen(["ps2pdf"], stderr=grass.PIPE) + p = gs.Popen(["ps2pdf"], stderr=gs.PIPE) p.stderr.close() except OSError: @@ -333,7 +333,7 @@ def OnPreview(self, event): def PSFile(self, filename=None, pdf=False): """Create temporary instructions file and run ps.map with output = filename""" - instrFile = grass.tempfile() + instrFile = gs.tempfile() instrFileFd = open(instrFile, mode="wb") content = self.InstructionFile() if not content: @@ -343,7 +343,7 @@ def PSFile(self, filename=None, pdf=False): instrFileFd.close() temp = False - regOld = grass.region(env=self.env) + regOld = gs.region(env=self.env) if pdf: pdfname = filename @@ -352,7 +352,7 @@ def PSFile(self, filename=None, pdf=False): # preview or pdf if not filename or (filename and pdf): temp = True - filename = grass.tempfile() + filename = gs.tempfile() if not pdf: # lower resolution for preview if self.instruction.FindInstructionByType("map"): mapId = self.instruction.FindInstructionByType("map").id @@ -398,9 +398,9 @@ def OnCmdDone(self, event): message=_("Ps.map exited with return code %s") % event.returncode, ) - grass.try_remove(event.userData["instrFile"]) + gs.try_remove(event.userData["instrFile"]) if event.userData["temp"]: - grass.try_remove(event.userData["filename"]) + gs.try_remove(event.userData["filename"]) return if event.userData["pdfname"]: @@ -452,7 +452,7 @@ def OnCmdDone(self, event): " Please install it to create PDF.\n\n " ).format(pdf_rendering_prog) try: - proc = grass.Popen(command) + proc = gs.Popen(command) ret = proc.wait() if ret > 0: GMessage( @@ -483,7 +483,7 @@ def OnCmdDone(self, event): # show preview only when user doesn't want to create ps or pdf if havePILImage and event.userData["temp"] and not event.userData["pdfname"]: - self.env["GRASS_REGION"] = grass.region_env( + self.env["GRASS_REGION"] = gs.region_env( cols=event.userData["regionOld"]["cols"], rows=event.userData["regionOld"]["rows"], env=self.env, @@ -530,9 +530,9 @@ def OnCmdDone(self, event): del busy self.SetStatusText(_("Preview generated"), 0) - grass.try_remove(event.userData["instrFile"]) + gs.try_remove(event.userData["instrFile"]) if event.userData["temp"]: - grass.try_remove(event.userData["filename"]) + gs.try_remove(event.userData["filename"]) self.delayedCall = wx.CallLater( 4000, @@ -1066,7 +1066,7 @@ def getTextExtent(self, textDict): def getInitMap(self): """Create default map frame when no map is selected, needed for coordinates in map units""" - instrFile = grass.tempfile() + instrFile = gs.tempfile() instrFileFd = open(instrFile, mode="wb") content = self.InstructionFile() if not content: @@ -1079,9 +1079,9 @@ def getInitMap(self): mapInitRect = GetMapBounds( instrFile, portrait=(page["Orientation"] == "Portrait"), env=self.env ) - grass.try_remove(instrFile) + gs.try_remove(instrFile) - region = grass.region(env=self.env) + region = gs.region(env=self.env) units = UnitConversion(self) realWidth = units.convert( value=abs(region["w"] - region["e"]), fromUnit="meter", toUnit="inch" @@ -1246,11 +1246,11 @@ def DialogDataChanged(self, id): if itype in {"map", "vector", "raster", "labels"}: if itype == "raster": # set resolution try: - info = grass.raster_info(self.instruction[id]["raster"]) - self.env["GRASS_REGION"] = grass.region_env( + info = gs.raster_info(self.instruction[id]["raster"]) + self.env["GRASS_REGION"] = gs.region_env( nsres=info["nsres"], ewres=info["ewres"], env=self.env ) - except grass.CalledModuleError: # fails after switching location + except gs.CalledModuleError: # fails after switching location pass # change current raster in raster legend @@ -1353,7 +1353,7 @@ def OnCloseWindow(self, event): os.remove(self.imgName) except OSError: pass - grass.set_raise_on_error(False) + gs.set_raise_on_error(False) if hasattr(self, "delayedCall") and self.delayedCall.IsRunning(): self.delayedCall.Stop() self.Destroy() diff --git a/gui/wxpython/psmap/g.gui.psmap.py b/gui/wxpython/psmap/g.gui.psmap.py index 50e4518e5a3..7e855d5e143 100755 --- a/gui/wxpython/psmap/g.gui.psmap.py +++ b/gui/wxpython/psmap/g.gui.psmap.py @@ -32,11 +32,11 @@ # % required: no # %end -import grass.script as gscript +import grass.script as gs def main(): - options, flags = gscript.parser() + options, flags = gs.parser() import wx diff --git a/gui/wxpython/psmap/instructions.py b/gui/wxpython/psmap/instructions.py index 89fea9d2455..a123baaaba4 100644 --- a/gui/wxpython/psmap/instructions.py +++ b/gui/wxpython/psmap/instructions.py @@ -38,7 +38,7 @@ from time import strftime, localtime import wx -import grass.script as grass +import grass.script as gs from grass.script.task import cmdlist_to_tuple from core.gcmd import GError, GMessage, GWarning @@ -65,7 +65,7 @@ def __init__(self, parent, objectsToDraw, env): def __str__(self): """Returns text for instruction file""" comment = "# timestamp: " + strftime("%Y-%m-%d %H:%M", localtime()) + "\n" - env = grass.gisenv() + env = gs.gisenv() comment += "# location: %s\n" % env["LOCATION_NAME"] comment += "# mapset: %s\n" % env["MAPSET"] comment += ( @@ -166,7 +166,7 @@ def Read(self, filename): # then run ps.map -b to get information for maploc # compute scale and center map = self.FindInstructionByType("map") - region = grass.region(env=self.env) + region = gs.region(env=self.env) map["center"] = (region["n"] + region["s"]) / 2, (region["w"] + region["e"]) / 2 mapRect = GetMapBounds( self.filename, portrait=(orientation == "Portrait"), env=self.env @@ -523,16 +523,16 @@ def SetRegion(self, regionInstruction): map["scaleType"] = 2 else: map["scaleType"] = 2 - region = grass.region(env=None) + region = gs.region(env=None) cmd = ["g.region", region] cmdString = GetCmdString(cmd).replace("g.region", "") GMessage( _("Instruction file will be loaded with following region: %s\n") % cmdString ) try: - self.env["GRASS_REGION"] = grass.region_env(env=self.env, **cmd[1]) + self.env["GRASS_REGION"] = gs.region_env(env=self.env, **cmd[1]) - except grass.ScriptError as e: + except gs.ScriptError as e: GError(_("Region cannot be set\n%s") % e) return False @@ -579,7 +579,7 @@ def Read(self, instruction, text, **kwargs): def PercentToReal(self, e, n): """Converts text coordinates from percent of region to map coordinates""" e, n = float(e.strip("%")), float(n.strip("%")) - region = grass.region(env=self.env) + region = gs.region(env=self.env) N = region["s"] + (region["n"] - region["s"]) / 100 * n E = region["w"] + (region["e"] - region["w"]) / 100 * e return E, N @@ -627,7 +627,7 @@ def __str__(self): comment = "" # region settings - region = grass.region(env=self.env) + region = gs.region(env=self.env) if self.instruction["scaleType"] == 0: # match map map = self.instruction["map"] if self.instruction["mapType"] == "raster": @@ -826,7 +826,7 @@ def Read(self, instruction, text, **kwargs): if len(line.split()) > 1: pformat = line.split()[1] availableFormats = self._toDict( - grass.read_command("ps.map", flags="p", quiet=True) + gs.read_command("ps.map", flags="p", quiet=True) ) # e.g. paper a3 try: @@ -1751,13 +1751,13 @@ def EstimateHeight(self, raster, discrete, fontsize, cols=None, height=None): else: cols = 1 - rinfo = grass.raster_info(raster) + rinfo = gs.raster_info(raster) if rinfo["datatype"] in {"DCELL", "FCELL"}: minim, maxim = rinfo["min"], rinfo["max"] rows = ceil(maxim / cols) else: cat = ( - grass.read_command("r.category", map=raster, sep=":") + gs.read_command("r.category", map=raster, sep=":") .strip() .split("\n") ) @@ -1775,7 +1775,7 @@ def EstimateWidth( """Estimate size to draw raster legend""" if discrete == "n": - rinfo = grass.raster_info(raster) + rinfo = gs.raster_info(raster) minim, maxim = rinfo["min"], rinfo["max"] if width: width = width @@ -1927,8 +1927,8 @@ def Read(self, instruction, text): GError(_("Failed to read instruction %s") % instruction) return False try: - info = grass.find_file(map, element="cell") - except grass.ScriptError as e: + info = gs.find_file(map, element="cell") + except gs.ScriptError as e: GError(message=e.value) return False instr["raster"] = info["fullname"] @@ -1971,8 +1971,8 @@ def Read(self, instruction, text, **kwargs): # name of vector map vmap = line.split()[1] try: - info = grass.find_file(vmap, element="vector") - except grass.ScriptError as e: + info = gs.find_file(vmap, element="vector") + except gs.ScriptError as e: GError(message=e.value) return False vmap = info["fullname"] @@ -2143,8 +2143,8 @@ def Read(self, instruction, text, **kwargs): """Read instruction and save information""" instr = {} try: - info = grass.find_file(name=text[0].split()[1], element="vector") - except grass.ScriptError as e: + info = gs.find_file(name=text[0].split()[1], element="vector") + except gs.ScriptError as e: GError(message=e.value) return False instr["name"] = info["fullname"] diff --git a/gui/wxpython/psmap/utils.py b/gui/wxpython/psmap/utils.py index f7e4cea1ad3..3e60ad6c2b6 100644 --- a/gui/wxpython/psmap/utils.py +++ b/gui/wxpython/psmap/utils.py @@ -26,7 +26,7 @@ except ImportError: havePILImage = False -import grass.script as grass +import grass.script as gs from core.gcmd import RunCommand, GError @@ -153,7 +153,7 @@ def convertRGB(rgb): or named color/r:g:b string to wx.Colour, depending on input""" # transform a wx.Colour tuple into an r:g:b string if isinstance(rgb, wx.Colour): - for name, color in grass.named_colors.items(): + for name, color in gs.named_colors.items(): if ( rgb.Red() == int(color[0] * 255) and rgb.Green() == int(color[1] * 255) @@ -164,9 +164,9 @@ def convertRGB(rgb): # transform a GRASS named color or an r:g:b string into a wx.Colour tuple else: color = ( - int(grass.parse_color(rgb)[0] * 255), - int(grass.parse_color(rgb)[1] * 255), - int(grass.parse_color(rgb)[2] * 255), + int(gs.parse_color(rgb)[0] * 255), + int(gs.parse_color(rgb)[1] * 255), + int(gs.parse_color(rgb)[2] * 255), ) color = wx.Colour(*color) if color.IsOk(): @@ -182,7 +182,7 @@ def PaperMapCoordinates(mapInstr, x, y, paperToMap=True, env=None): :param x,y: paper coords in inches or mapcoords in map units :param paperToMap: specify conversion direction """ - region = grass.region(env=env) + region = gs.region(env=env) mapWidthPaper = mapInstr["rect"].GetWidth() mapHeightPaper = mapInstr["rect"].GetHeight() mapWidthEN = region["e"] - region["w"] @@ -222,24 +222,22 @@ def AutoAdjust(self, scaleType, rect, env, map=None, mapType=None, region=None): res = "" if mapType == "raster": try: - res = grass.read_command( - "g.region", flags="gu", raster=map, env=env - ) - except grass.ScriptError: + res = gs.read_command("g.region", flags="gu", raster=map, env=env) + except gs.ScriptError: pass elif mapType == "vector": - res = grass.read_command("g.region", flags="gu", vector=map, env=env) - currRegionDict = grass.parse_key_val(res, val_type=float) + res = gs.read_command("g.region", flags="gu", vector=map, env=env) + currRegionDict = gs.parse_key_val(res, val_type=float) elif scaleType == 1 and region: # saved region - res = grass.read_command("g.region", flags="gu", region=region, env=env) - currRegionDict = grass.parse_key_val(res, val_type=float) + res = gs.read_command("g.region", flags="gu", region=region, env=env) + currRegionDict = gs.parse_key_val(res, val_type=float) elif scaleType == 2: # current region - currRegionDict = grass.region(env=None) + currRegionDict = gs.region(env=None) else: return None, None, None # fails after switching location - except (grass.ScriptError, grass.CalledModuleError): + except (gs.ScriptError, gs.CalledModuleError): pass if not currRegionDict: @@ -290,11 +288,11 @@ def SetResolution(dpi, width, height, env): :param width: map frame width :param height: map frame height """ - region = grass.region(env=env) + region = gs.region(env=env) if region["cols"] > width * dpi or region["rows"] > height * dpi: rows = height * dpi cols = width * dpi - env["GRASS_REGION"] = grass.region_env(rows=rows, cols=cols, env=env) + env["GRASS_REGION"] = gs.region_env(rows=rows, cols=cols, env=env) def ComputeSetRegion(self, mapDict, env): @@ -335,7 +333,7 @@ def ComputeSetRegion(self, mapDict, env): rasterId = None if rasterId: - env["GRASS_REGION"] = grass.region_env( + env["GRASS_REGION"] = gs.region_env( n=ceil(centerN + rectHalfMeter[1]), s=floor(centerN - rectHalfMeter[1]), e=ceil(centerE + rectHalfMeter[0]), @@ -344,7 +342,7 @@ def ComputeSetRegion(self, mapDict, env): env=env, ) else: - env["GRASS_REGION"] = grass.region_env( + env["GRASS_REGION"] = gs.region_env( n=ceil(centerN + rectHalfMeter[1]), s=floor(centerN - rectHalfMeter[1]), e=ceil(centerE + rectHalfMeter[0]), @@ -361,7 +359,7 @@ def projInfo(): "g.proj", flags="g", read=True, - parse=grass.parse_key_val, + parse=gs.parse_key_val, ) return ( @@ -384,7 +382,7 @@ def GetMapBounds(filename, env, portrait=True): bb = list( map( float, - grass.read_command( + gs.read_command( "ps.map", flags="b" + orient, quiet=True, input=filename, env=env ) .strip() @@ -392,7 +390,7 @@ def GetMapBounds(filename, env, portrait=True): .split(","), ) ) - except (grass.ScriptError, IndexError): + except (gs.ScriptError, IndexError): GError(message=_("Unable to run `ps.map -b`")) return None return Rect2D(bb[0], bb[3], bb[2] - bb[0], bb[1] - bb[3]) @@ -402,9 +400,9 @@ def getRasterType(map): """Returns type of raster map (CELL, FCELL, DCELL)""" if map is None: map = "" - file = grass.find_file(name=map, element="cell") + file = gs.find_file(name=map, element="cell") if file.get("file"): - rasterType = grass.raster_info(map)["datatype"] + rasterType = gs.raster_info(map)["datatype"] return rasterType else: return None diff --git a/gui/wxpython/rlisetup/g.gui.rlisetup.py b/gui/wxpython/rlisetup/g.gui.rlisetup.py index 9b24e98696f..bed4b030f04 100644 --- a/gui/wxpython/rlisetup/g.gui.rlisetup.py +++ b/gui/wxpython/rlisetup/g.gui.rlisetup.py @@ -26,11 +26,11 @@ # % keyword: landscape structure analysis # %end -import grass.script as gscript +import grass.script as gs def main(): - gscript.parser() + gs.parser() import wx diff --git a/gui/wxpython/timeline/frame.py b/gui/wxpython/timeline/frame.py index 48f23a0cbab..b8b4fa3c2fd 100644 --- a/gui/wxpython/timeline/frame.py +++ b/gui/wxpython/timeline/frame.py @@ -24,11 +24,11 @@ from functools import reduce try: - import matplotlib + import matplotlib as mpl # The recommended way to use wx with mpl is with the WXAgg # backend. - matplotlib.use("WXAgg") + mpl.use("WXAgg") from matplotlib import gridspec from matplotlib.figure import Figure from matplotlib.backends.backend_wxagg import ( @@ -45,7 +45,7 @@ ).format(e) ) -import grass.script as grass +import grass.script as gs import grass.temporal as tgis from core.gcmd import GError, GException, RunCommand @@ -60,7 +60,7 @@ def check_version(*version): """Checks if given version or newer is installed""" versionInstalled = [] - for i in matplotlib.__version__.split("."): + for i in mpl.__version__.split("."): try: v = int(i) versionInstalled.append(v) @@ -303,8 +303,8 @@ def _draw3dFigure(self): ) ) - params = grass.read_command("g.proj", flags="g") - params = grass.parse_key_val(params) + params = gs.read_command("g.proj", flags="g") + params = gs.parse_key_val(params) if "unit" in params: self.axes3d.set_xlabel(_("X [%s]") % params["unit"]) self.axes3d.set_ylabel(_("Y [%s]") % params["unit"]) diff --git a/gui/wxpython/timeline/g.gui.timeline.py b/gui/wxpython/timeline/g.gui.timeline.py index d3176736bca..161c6832a92 100755 --- a/gui/wxpython/timeline/g.gui.timeline.py +++ b/gui/wxpython/timeline/g.gui.timeline.py @@ -34,11 +34,11 @@ # % description: Show also 3D plot of spatio-temporal extents # %end -import grass.script as gscript +import grass.script as gs def main(): - options, flags = gscript.parser() + options, flags = gs.parser() import wx @@ -52,7 +52,7 @@ def main(): # TODO: why do we need this special check here, the reason of error # is wrong intallation or something, no need to report this to the # user in a nice way - gscript.fatal(str(e)) + gs.fatal(str(e)) datasets = options["inputs"].strip().split(",") datasets = [data for data in datasets if data] diff --git a/gui/wxpython/tplot/frame.py b/gui/wxpython/tplot/frame.py index 0750fc643cc..5a035657455 100755 --- a/gui/wxpython/tplot/frame.py +++ b/gui/wxpython/tplot/frame.py @@ -25,15 +25,15 @@ import wx from grass.pygrass.modules import Module -import grass.script as grass +import grass.script as gs from functools import reduce try: - import matplotlib + import matplotlib as mpl # The recommended way to use wx with mpl is with the WXAgg # backend. - matplotlib.use("WXAgg") + mpl.use("WXAgg") from matplotlib.figure import Figure from matplotlib.backends.backend_wxagg import ( FigureCanvasWxAgg as FigCanvas, @@ -77,7 +77,7 @@ def check_version(*version): """Checks if given version or newer is installed""" versionInstalled = [] - for i in matplotlib.__version__.split("."): + for i in mpl.__version__.split("."): try: v = int(i) versionInstalled.append(v) @@ -513,7 +513,7 @@ def _parseVDbConn(self, mapp, layerInp): def _getExistingCategories(self, mapp, cats): """Get a list of categories for a vector map""" - vdb = grass.read_command("v.category", input=mapp, option="print") + vdb = gs.read_command("v.category", input=mapp, option="print") categories = vdb.splitlines() if not cats: return categories @@ -613,7 +613,7 @@ def _getSTVDData(self, timeseries): self.plotNameListV.append(name) # TODO set an appropriate distance, right now a big one is set # to return the closer point to the selected one - out = grass.vector_what( + out = gs.vector_what( map="pois_srvds", coord=self.poi.coords(), distance=10000000000000000, @@ -673,7 +673,7 @@ def _getSTVDData(self, timeseries): ), ) return - vals = grass.vector_db_select( + vals = gs.vector_db_select( map=row["name"], layer=lay, where=wherequery.format(key=catkey), @@ -1306,7 +1306,7 @@ def OnVectorSelected(self, event): break if found: try: - vect_list = grass.read_command( + vect_list = gs.read_command( "t.vect.list", flags="u", input=dataset, column="name" ) except Exception: diff --git a/gui/wxpython/tplot/g.gui.tplot.py b/gui/wxpython/tplot/g.gui.tplot.py index a4b87326e03..2cb85a565f8 100755 --- a/gui/wxpython/tplot/g.gui.tplot.py +++ b/gui/wxpython/tplot/g.gui.tplot.py @@ -109,11 +109,11 @@ # % required: no # %end -import grass.script as gscript +import grass.script as gs def main(): - options, flags = gscript.parser() + options, flags = gs.parser() import wx @@ -126,7 +126,7 @@ def main(): try: from tplot.frame import TplotFrame except ImportError as e: - gscript.fatal(e.message) + gs.fatal(e.message) rasters = None if options["strds"]: rasters = options["strds"].strip().split(",") @@ -142,20 +142,18 @@ def main(): if options["stvds"]: vectors = options["stvds"].strip().split(",") if not options["attr"]: - gscript.fatal(_("With stvds you have to set 'attr' option")) + gs.fatal(_("With stvds you have to set 'attr' option")) else: attr = options["attr"] if coords and cats: - gscript.fatal( + gs.fatal( _( "With stvds it is not possible to use 'coordinates' " "and 'cats' options together" ) ) elif not coords and not cats: - gscript.warning( - _("With stvds you have to use 'coordinates' or 'cats' option") - ) + gs.warning(_("With stvds you have to use 'coordinates' or 'cats' option")) title = None if options["title"]: title = options["title"] @@ -188,7 +186,7 @@ def main(): ylabel, csvfile, flags["h"], - gscript.overwrite, + gs.overwrite, ) if output: frame.OnRedraw() diff --git a/gui/wxpython/vdigit/g.gui.vdigit.py b/gui/wxpython/vdigit/g.gui.vdigit.py index f66793176e5..ea09f207909 100644 --- a/gui/wxpython/vdigit/g.gui.vdigit.py +++ b/gui/wxpython/vdigit/g.gui.vdigit.py @@ -35,13 +35,13 @@ # %end import os -import grass.script as grass +import grass.script as gs def main(): - grass.set_raise_on_error(False) + gs.set_raise_on_error(False) - options, flags = grass.parser() + options, flags = gs.parser() # import wx only after running parser # to avoid issues with complex imports when only interface is needed @@ -113,13 +113,13 @@ def __init__(self, parent, vectorMap): parent.Layout() if not haveVDigit: - grass.fatal(_("Vector digitizer not available. %s") % errorMsg) + gs.fatal(_("Vector digitizer not available. %s") % errorMsg) - if not grass.find_file( - name=options["map"], element="vector", mapset=grass.gisenv()["MAPSET"] + if not gs.find_file( + name=options["map"], element="vector", mapset=gs.gisenv()["MAPSET"] )["fullname"]: if not flags["c"]: - grass.fatal( + gs.fatal( _( "Vector map <%s> not found in current mapset. " "New vector map can be created by providing '-c' flag." @@ -127,13 +127,11 @@ def __init__(self, parent, vectorMap): % options["map"] ) else: - grass.verbose(_("New vector map <%s> created") % options["map"]) + gs.verbose(_("New vector map <%s> created") % options["map"]) try: - grass.run_command( - "v.edit", map=options["map"], tool="create", quiet=True - ) + gs.run_command("v.edit", map=options["map"], tool="create", quiet=True) except CalledModuleError: - grass.fatal(_("Unable to create new vector map <%s>") % options["map"]) + gs.fatal(_("Unable to create new vector map <%s>") % options["map"]) # allow immediate rendering driver = UserSettings.Get(group="display", key="driver", subkey="type") diff --git a/gui/wxpython/vdigit/toolbars.py b/gui/wxpython/vdigit/toolbars.py index d72cc3dac3c..430f487245a 100644 --- a/gui/wxpython/vdigit/toolbars.py +++ b/gui/wxpython/vdigit/toolbars.py @@ -17,7 +17,7 @@ import wx -from grass import script as grass +from grass import script as gs from grass.pydispatch.signal import Signal from gui_core.toolbars import BaseToolbar, BaseIcons @@ -1002,7 +1002,7 @@ def OnSelectMap(self, event): if dlg and dlg.GetName(): # add layer to map layer tree/map display - mapName = dlg.GetName() + "@" + grass.gisenv()["MAPSET"] + mapName = dlg.GetName() + "@" + gs.gisenv()["MAPSET"] self._giface.GetLayerList().AddLayer( ltype="vector", name=mapName, @@ -1048,10 +1048,7 @@ def StartEditing(self, mapLayer): """ # check if topology is available (skip for hidden - temporary # maps, see iclass for details) - if ( - not mapLayer.IsHidden() - and grass.vector_info(mapLayer.GetName())["level"] != 2 - ): + if not mapLayer.IsHidden() and gs.vector_info(mapLayer.GetName())["level"] != 2: dlg = wx.MessageDialog( parent=self.MapWindow, message=_( @@ -1290,7 +1287,7 @@ def UpdateListOfLayers(self, updateTool=False): # select vector map layer in the current mapset layerNameList = [] self.layers = self.Map.GetListOfLayers( - ltype="vector", mapset=grass.gisenv()["MAPSET"] + ltype="vector", mapset=gs.gisenv()["MAPSET"] ) for layer in self.layers: diff --git a/gui/wxpython/web_services/dialogs.py b/gui/wxpython/web_services/dialogs.py index 3bfc1473121..904b2bb81c5 100644 --- a/gui/wxpython/web_services/dialogs.py +++ b/gui/wxpython/web_services/dialogs.py @@ -25,7 +25,7 @@ from copy import deepcopy -import grass.script as grass +import grass.script as gs from grass.script.task import cmdlist_to_tuple, cmdtuple_to_list from core import globalvar @@ -587,7 +587,7 @@ def OnAddLayer(self, event): active_ws = self.active_ws_panel.GetWebService() if "WMS" not in active_ws: cap_file = self.active_ws_panel.GetCapFile() - cmd_cap_file = grass.tempfile() + cmd_cap_file = gs.tempfile() shutil.copyfile(cap_file, cmd_cap_file) lcmd.append("capfile=" + cmd_cap_file) @@ -668,7 +668,7 @@ def __init__( self.revert_ws_cap_files[ws] = cmd[1]["capfile"] del ws_cap_files[ws] else: - self.revert_ws_cap_files[ws] = grass.tempfile() + self.revert_ws_cap_files[ws] = gs.tempfile() self._setRevertCapFiles(ws_cap_files) @@ -677,7 +677,7 @@ def __init__( def __del__(self): for f in self.revert_ws_cap_files.values(): - grass.try_remove(f) + gs.try_remove(f) def _setRevertCapFiles(self, ws_cap_files): for ws, f in ws_cap_files.items(): @@ -865,7 +865,7 @@ def _createWidgets(self): self.params["output"] = Select( parent=self, type="raster", - mapsets=[grass.gisenv()["MAPSET"]], + mapsets=[gs.gisenv()["MAPSET"]], size=globalvar.DIALOG_GSELECT_SIZE, ) @@ -1012,7 +1012,7 @@ def OnRegionType(self, event): def OnSave(self, event): """Import WMS raster data into GRASS as raster layer.""" self.thread.abort(abortall=True) - currmapset = grass.gisenv()["MAPSET"] + currmapset = gs.gisenv()["MAPSET"] self.output = self.params["output"].GetValue().strip() l_spl = self.output.strip().split("@") @@ -1027,7 +1027,7 @@ def OnSave(self, event): elif ( not self.overwrite.IsChecked() - and grass.find_file(self.output, "cell", ".")["fullname"] + and gs.find_file(self.output, "cell", ".")["fullname"] ): msg = _("Output map <%s> already exists" % self.output) @@ -1046,7 +1046,7 @@ def OnSave(self, event): reg_mapset = reg_spl[1] if self.region_types["named"].GetValue(): - if not grass.find_file(reg_spl[0], "windows", reg_mapset)["fullname"]: + if not gs.find_file(reg_spl[0], "windows", reg_mapset)["fullname"]: msg = _( "Region <%s> does not exist." % self.params["region"].GetValue() ) diff --git a/gui/wxpython/web_services/widgets.py b/gui/wxpython/web_services/widgets.py index 6e29e22e701..2da957ef948 100644 --- a/gui/wxpython/web_services/widgets.py +++ b/gui/wxpython/web_services/widgets.py @@ -59,7 +59,7 @@ TreeCtrl, ) -import grass.script as grass +import grass.script as gs rinwms_path = os.path.join(os.getenv("GISBASE"), "etc", "r.in.wms") if rinwms_path not in sys.path: @@ -131,7 +131,7 @@ def __init__(self, parent, web_service, **kwargs): self.cmdStdErr = GStderr(self) self.cmd_thread = CmdThread(self) - self.cap_file = grass.tempfile() + self.cap_file = gs.tempfile() reqDataBox = StaticBox(parent=self, label=_(" Requested data settings ")) self._nb_sizer = wx.StaticBoxSizer(reqDataBox, wx.VERTICAL) @@ -151,7 +151,7 @@ def __init__(self, parent, web_service, **kwargs): def __del__(self): self.cmd_thread.abort(abortall=True) - grass.try_remove(self.cap_file) + gs.try_remove(self.cap_file) def _layout(self): self._nb_sizer.Add(self.notebook, proportion=1, flag=wx.EXPAND) diff --git a/gui/wxpython/wxplot/base.py b/gui/wxpython/wxplot/base.py index 3eb43fd5f43..d52a8cde52e 100755 --- a/gui/wxpython/wxplot/base.py +++ b/gui/wxpython/wxplot/base.py @@ -29,7 +29,7 @@ from gui_core.toolbars import BaseIcons from gui_core.wrap import Menu -import grass.script as grass +import grass.script as gs PlotIcons = { "draw": MetaIcon(img="show", label=_("Draw/re-draw plot")), @@ -116,12 +116,12 @@ def _createColorDict(self): for assigning colors to images in imagery groups""" self.colorDict = {} - for clr in grass.named_colors.keys(): + for clr in gs.named_colors.keys(): if clr == "white": continue - r = int(grass.named_colors[clr][0] * 255) - g = int(grass.named_colors[clr][1] * 255) - b = int(grass.named_colors[clr][2] * 255) + r = int(gs.named_colors[clr][0] * 255) + g = int(gs.named_colors[clr][1] * 255) + b = int(gs.named_colors[clr][2] * 255) self.colorDict[clr] = (r, g, b, 255) def InitPlotOpts(self, plottype): @@ -203,7 +203,7 @@ def InitRasterOpts(self, rasterList, plottype): idx = rasterList.index(r) try: - ret = grass.raster_info(r) + ret = gs.raster_info(r) except: continue # if r.info cannot parse map, skip it @@ -267,8 +267,8 @@ def InitRasterPairs(self, rasterList, plottype): idx = rasterList.index(rpair) try: - ret0 = grass.raster_info(rpair[0]) - ret1 = grass.raster_info(rpair[1]) + ret0 = gs.raster_info(rpair[0]) + ret1 = gs.raster_info(rpair[1]) except: continue diff --git a/gui/wxpython/wxplot/histogram.py b/gui/wxpython/wxplot/histogram.py index 1c5c2b2de4f..bf86e1e8ff3 100644 --- a/gui/wxpython/wxplot/histogram.py +++ b/gui/wxpython/wxplot/histogram.py @@ -19,7 +19,7 @@ import wx -import grass.script as grass +import grass.script as gs from wx.lib import plot from gui_core.wrap import StockCursor from gui_core.toolbars import BaseToolbar, BaseIcons @@ -259,7 +259,7 @@ def OnStats(self, event): title = _("Statistics for Map(s) Histogrammed") for rast in self.rasterList: - ret = grass.read_command("r.univar", map=rast, flags="e", quiet=True) + ret = gs.read_command("r.univar", map=rast, flags="e", quiet=True) stats = _("Statistics for raster map <%s>") % rast + ":\n%s\n" % ret message.append(stats) diff --git a/gui/wxpython/wxplot/profile.py b/gui/wxpython/wxplot/profile.py index 6d49ea3fde1..1941022fb59 100644 --- a/gui/wxpython/wxplot/profile.py +++ b/gui/wxpython/wxplot/profile.py @@ -18,12 +18,12 @@ import os import sys import math -import numpy +import numpy as np import wx from wx.lib import plot -import grass.script as grass +import grass.script as gs from wxplot.base import BasePlotFrame, PlotIcons from gui_core.toolbars import BaseToolbar, BaseIcons from gui_core.wrap import StockCursor @@ -164,7 +164,7 @@ def SetupProfile(self): self.coordstr = "" lasteast = lastnorth = None - region = grass.region() + region = gs.region() insideRegion = True if len(self.transect) > 0: for point in self.transect: @@ -287,7 +287,7 @@ def CreateDatalist(self, raster, coords): # keep total number of transect points to 500 or less to avoid # freezing with large, high resolution maps - region = grass.region() + region = gs.region() curr_res = min(float(region["nsres"]), float(region["ewres"])) transect_rec = 0 if self.transect_length / curr_res > 500: @@ -472,19 +472,19 @@ def OnStats(self, event): statstr = "Profile of %s\n\n" % rast iterable = (i[1] for i in self.raster[r]["datalist"]) - a = numpy.fromiter(iterable, numpy.float) + a = np.fromiter(iterable, np.float) statstr += "n: %f\n" % a.size - statstr += "minimum: %f\n" % numpy.amin(a) - statstr += "maximum: %f\n" % numpy.amax(a) - statstr += "range: %f\n" % numpy.ptp(a) - statstr += "mean: %f\n" % numpy.mean(a) - statstr += "standard deviation: %f\n" % numpy.std(a) - statstr += "variance: %f\n" % numpy.var(a) - cv = numpy.std(a) / numpy.mean(a) + statstr += "minimum: %f\n" % np.amin(a) + statstr += "maximum: %f\n" % np.amax(a) + statstr += "range: %f\n" % np.ptp(a) + statstr += "mean: %f\n" % np.mean(a) + statstr += "standard deviation: %f\n" % np.std(a) + statstr += "variance: %f\n" % np.var(a) + cv = np.std(a) / np.mean(a) statstr += "coefficient of variation: %f\n" % cv - statstr += "sum: %f\n" % numpy.sum(a) - statstr += "median: %f\n" % numpy.median(a) + statstr += "sum: %f\n" % np.sum(a) + statstr += "median: %f\n" % np.median(a) statstr += "distance along transect: %f\n\n" % self.transect_length message.append(statstr) except: diff --git a/gui/wxpython/wxplot/scatter.py b/gui/wxpython/wxplot/scatter.py index b0063150560..c57a3e1fac9 100644 --- a/gui/wxpython/wxplot/scatter.py +++ b/gui/wxpython/wxplot/scatter.py @@ -19,7 +19,7 @@ import wx -import grass.script as grass +import grass.script as gs from wx.lib import plot from wxplot.base import BasePlotFrame, PlotIcons from gui_core.toolbars import BaseToolbar, BaseIcons @@ -275,13 +275,13 @@ def OnRegression(self, event): rast1, rast2 = rpair rast1 = rast1.split("@")[0] rast2 = rast2.split("@")[0] - ret = grass.parse_command( + ret = gs.parse_command( "r.regression.line", mapx=rast1, mapy=rast2, flags="g", quiet=True, - parse=(grass.parse_key_val, {"sep": "="}), + parse=(gs.parse_key_val, {"sep": "="}), ) eqtitle = _( "Regression equation for raster map <%(rast1)s> vs. <%(rast2)s>:\n\n" diff --git a/lib/imagery/testsuite/test_imagery_signature_management.py b/lib/imagery/testsuite/test_imagery_signature_management.py index 21f052372e2..7b1dc8bdc57 100644 --- a/lib/imagery/testsuite/test_imagery_signature_management.py +++ b/lib/imagery/testsuite/test_imagery_signature_management.py @@ -17,7 +17,7 @@ from grass.gunittest.main import test from grass.script.core import tempname -import grass.script as grass +import grass.script as gs from grass.pygrass import utils from grass.pygrass.gis import Mapset, make_mapset @@ -1036,13 +1036,13 @@ def test_multiple_sigs_multiple_mapsets(self): self.assertNotIn(golden[0], ret_list) I_free_signatures_list(ret, ctypes.byref(sig_list)) # Add temporary mapset to search path and re-run test - grass.run_command("g.mapsets", mapset=self.rnd_mapset_name, operation="add") + gs.run_command("g.mapsets", mapset=self.rnd_mapset_name, operation="add") # Search path is cached for this run => reset! G_reset_mapsets() ret = I_signatures_list_by_type( I_SIGFILE_TYPE_SIG, None, ctypes.byref(sig_list) ) - grass.run_command("g.mapsets", mapset=self.rnd_mapset_name, operation="remove") + gs.run_command("g.mapsets", mapset=self.rnd_mapset_name, operation="remove") G_reset_mapsets() shutil.rmtree(sig_dir1) shutil.rmtree(sig_dir2) @@ -1087,13 +1087,13 @@ def test_multiple_sigsets_multiple_mapsets(self): self.assertNotIn(golden[0], ret_list) I_free_signatures_list(ret, ctypes.byref(sig_list)) # Add temporary mapset to search path and re-run test - grass.run_command("g.mapsets", mapset=self.rnd_mapset_name, operation="add") + gs.run_command("g.mapsets", mapset=self.rnd_mapset_name, operation="add") # Search path is cached for this run => reset! G_reset_mapsets() ret = I_signatures_list_by_type( I_SIGFILE_TYPE_SIGSET, None, ctypes.byref(sig_list) ) - grass.run_command("g.mapsets", mapset=self.rnd_mapset_name, operation="remove") + gs.run_command("g.mapsets", mapset=self.rnd_mapset_name, operation="remove") G_reset_mapsets() shutil.rmtree(sig_dir1) shutil.rmtree(sig_dir2) @@ -1139,13 +1139,13 @@ def test_multiple_libsvms_multiple_mapsets(self): self.assertNotIn(golden[0], ret_list) I_free_signatures_list(ret, ctypes.byref(sig_list)) # Add temporary mapset to search path and re-run test - grass.run_command("g.mapsets", mapset=self.rnd_mapset_name, operation="add") + gs.run_command("g.mapsets", mapset=self.rnd_mapset_name, operation="add") # Search path is cached for this run => reset! G_reset_mapsets() ret = I_signatures_list_by_type( I_SIGFILE_TYPE_LIBSVM, None, ctypes.byref(sig_list) ) - grass.run_command("g.mapsets", mapset=self.rnd_mapset_name, operation="remove") + gs.run_command("g.mapsets", mapset=self.rnd_mapset_name, operation="remove") G_reset_mapsets() shutil.rmtree(sig_dir1) shutil.rmtree(sig_dir2) diff --git a/pyproject.toml b/pyproject.toml index e5d0c3b2240..a86c28d5eb0 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -180,7 +180,6 @@ ignore = [ "G002", # logging-percent-format "G003", # logging-string-concat "I001", # unsorted-imports - "ICN001", # unconventional-import-alias "ISC003", # explicit-string-concatenation "PERF102", # incorrect-dict-iterator "PERF203", # try-except-in-loop diff --git a/python/grass/benchmark/plots.py b/python/grass/benchmark/plots.py index 3cb66a84d45..9483fda9116 100644 --- a/python/grass/benchmark/plots.py +++ b/python/grass/benchmark/plots.py @@ -23,14 +23,14 @@ def get_pyplot(to_file): The *to_file* parameter can be set to True to avoid tkinter dependency if the interactive show method is not needed. """ - import matplotlib # pylint: disable=import-outside-toplevel + import matplotlib as mpl # pylint: disable=import-outside-toplevel if to_file: backend = "agg" else: backend = None if backend: - matplotlib.use(backend) + mpl.use(backend) import matplotlib.pyplot as plt # pylint: disable=import-outside-toplevel diff --git a/python/grass/gunittest/multireport.py b/python/grass/gunittest/multireport.py index 014d8296e4b..edeb98636ee 100644 --- a/python/grass/gunittest/multireport.py +++ b/python/grass/gunittest/multireport.py @@ -22,9 +22,9 @@ from grass.gunittest.reporters import success_to_html_percent # TODO: we should be able to work without matplotlib -import matplotlib +import matplotlib as mpl -matplotlib.use("Agg") +mpl.use("Agg") # This counts as code already, so silence "import not at top of file". # Perhaps in the future, switch_backend() could be used. import matplotlib.pyplot as plt # noqa: E402 diff --git a/python/grass/gunittest/reporters.py b/python/grass/gunittest/reporters.py index 4b8109ab622..e5455c33b39 100644 --- a/python/grass/gunittest/reporters.py +++ b/python/grass/gunittest/reporters.py @@ -78,9 +78,9 @@ def __init__(self, paths_to_remove, remove_gisbase=True, remove_gisdbase=False): if remove_gisdbase: # import only when really needed to avoid problems with # translations when environment is not set properly - import grass.script as gscript + import grass.script as gs - gisdbase = gscript.gisenv()["GISDBASE"] + gisdbase = gs.gisenv()["GISDBASE"] self._paths_to_remove.append(gisdbase) if paths_to_remove: self._paths_to_remove.extend(paths_to_remove) diff --git a/python/grass/imaging/images2avi.py b/python/grass/imaging/images2avi.py index 6dd590e858a..f0b1904823d 100644 --- a/python/grass/imaging/images2avi.py +++ b/python/grass/imaging/images2avi.py @@ -44,7 +44,7 @@ import shutil from grass.imaging import images2ims -import grass.script as gscript +import grass.script as gs def _cleanDir(tempDir): @@ -131,16 +131,16 @@ def writeAvi( _cleanDir(tempDir) if bg_task: return ( - gscript.decode(outPut) + gs.decode(outPut) + "\n" - + gscript.decode(S.stderr.read()) + + gs.decode(S.stderr.read()) + "\n" + _("Could not write avi.") ) else: # An error occurred, show - print(gscript.decode(outPut)) - print(gscript.decode(S.stderr.read())) + print(gs.decode(outPut)) + print(gs.decode(S.stderr.read())) raise RuntimeError(_("Could not write avi.")) else: try: diff --git a/python/grass/pygrass/gis/region.py b/python/grass/pygrass/gis/region.py index a4a1a1b5e03..0f736978026 100644 --- a/python/grass/pygrass/gis/region.py +++ b/python/grass/pygrass/gis/region.py @@ -7,7 +7,7 @@ import ctypes import grass.lib.gis as libgis import grass.lib.raster as libraster -import grass.script as grass +import grass.script as gs from grass.pygrass.errors import GrassError from grass.pygrass.shell.conversion import dict2html @@ -113,7 +113,7 @@ def byref(self): return ctypes.pointer(self.c_region) def _set_param(self, key, value): - grass.run_command("g.region", **{key: value}) + gs.run_command("g.region", **{key: value}) # ----------LIMITS---------- def _get_n(self): diff --git a/python/grass/pygrass/tests/benchmark.py b/python/grass/pygrass/tests/benchmark.py index c63dcb8d02e..c4871b34960 100644 --- a/python/grass/pygrass/tests/benchmark.py +++ b/python/grass/pygrass/tests/benchmark.py @@ -20,7 +20,7 @@ import grass.lib.gis as libgis import grass.lib.raster as libraster -import grass.script as core +import grass.script as gs import ctypes @@ -237,11 +237,11 @@ def test__RasterRow_row_access__if(): def test__mapcalc__add(): - core.mapcalc("test_c = test_a + test_b", quite=True, overwrite=True) + gs.mapcalc("test_c = test_a + test_b", quite=True, overwrite=True) def test__mapcalc__if(): - core.mapcalc("test_c = if(test_a > 50, 1, 0)", quite=True, overwrite=True) + gs.mapcalc("test_c = if(test_a > 50, 1, 0)", quite=True, overwrite=True) def mytimer(func, runs=1): @@ -260,10 +260,8 @@ def mytimer(func, runs=1): def run_benchmark(resolution_list, runs, testdict, profile): regions = [] for resolution in resolution_list: - core.use_temp_region() - core.run_command( - "g.region", e=50, w=-50, n=50, s=-50, res=resolution, flags="p" - ) + gs.use_temp_region() + gs.run_command("g.region", e=50, w=-50, n=50, s=-50, res=resolution, flags="p") # Adjust the computational region for this process region = libgis.Cell_head() @@ -281,8 +279,8 @@ def run_benchmark(resolution_list, runs, testdict, profile): libgis.G_set_window(ctypes.byref(region)) # Create two raster maps with random numbers - core.mapcalc("test_a = rand(0, 100)", quite=True, overwrite=True) - core.mapcalc("test_b = rand(0.0, 1.0)", quite=True, overwrite=True) + gs.mapcalc("test_a = rand(0, 100)", quite=True, overwrite=True) + gs.mapcalc("test_b = rand(0.0, 1.0)", quite=True, overwrite=True) result = collections.OrderedDict() result["res"] = resolution result["cols"] = region.cols @@ -305,7 +303,7 @@ def run_benchmark(resolution_list, runs, testdict, profile): del operdict["func"] regions.append(result) - core.del_temp_region() + gs.del_temp_region() return regions diff --git a/python/grass/script/array.py b/python/grass/script/array.py index c9abafbc24c..7358d397f32 100644 --- a/python/grass/script/array.py +++ b/python/grass/script/array.py @@ -109,7 +109,7 @@ .. sectionauthor:: Glynn Clements """ -import numpy +import numpy as np from .utils import try_remove from . import core as gcore @@ -130,8 +130,8 @@ def __del__(self): ############################################################################### -class array(numpy.memmap): - def __new__(cls, mapname=None, null=None, dtype=numpy.double, env=None): +class array(np.memmap): + def __new__(cls, mapname=None, null=None, dtype=np.double, env=None): """Define new numpy array :param cls: @@ -145,8 +145,8 @@ def __new__(cls, mapname=None, null=None, dtype=numpy.double, env=None): tempfile = _tempfile(env) if mapname: - kind = numpy.dtype(dtype).kind - size = numpy.dtype(dtype).itemsize + kind = np.dtype(dtype).kind + size = np.dtype(dtype).itemsize if kind == "f": flags = "f" @@ -170,7 +170,7 @@ def __new__(cls, mapname=None, null=None, dtype=numpy.double, env=None): env=env, ) - self = numpy.memmap.__new__( + self = np.memmap.__new__( cls, filename=tempfile.filename, dtype=dtype, mode="r+", shape=shape ) @@ -241,8 +241,8 @@ def write(self, mapname, title=None, null=None, overwrite=None, quiet=None): ############################################################################### -class array3d(numpy.memmap): - def __new__(cls, mapname=None, null=None, dtype=numpy.double, env=None): +class array3d(np.memmap): + def __new__(cls, mapname=None, null=None, dtype=np.double, env=None): """Define new 3d numpy array :param cls: @@ -257,8 +257,8 @@ def __new__(cls, mapname=None, null=None, dtype=numpy.double, env=None): tempfile = _tempfile() if mapname: - kind = numpy.dtype(dtype).kind - size = numpy.dtype(dtype).itemsize + kind = np.dtype(dtype).kind + size = np.dtype(dtype).itemsize if kind == "f": flags = None # default is double @@ -282,7 +282,7 @@ def __new__(cls, mapname=None, null=None, dtype=numpy.double, env=None): env=env, ) - self = numpy.memmap.__new__( + self = np.memmap.__new__( cls, filename=tempfile.filename, dtype=dtype, mode="r+", shape=shape ) diff --git a/python/grass/temporal/aggregation.py b/python/grass/temporal/aggregation.py index 64b2c44d845..1ea60eaeea1 100644 --- a/python/grass/temporal/aggregation.py +++ b/python/grass/temporal/aggregation.py @@ -19,7 +19,7 @@ :author: Soeren Gebbert """ -import grass.script as gscript +import grass.script as gs from grass.exceptions import CalledModuleError from .core import get_current_mapset, get_tgis_message_interface, init_dbif @@ -145,7 +145,7 @@ def aggregate_raster_maps( # Check if new map is in the temporal database if new_map.is_in_db(dbif): - if gscript.overwrite() is True: + if gs.overwrite() is True: # Remove the existing temporal database entry new_map.delete(dbif) new_map = RasterDataset(map_id) @@ -167,7 +167,7 @@ def aggregate_raster_maps( ) # Create the r.series input file - filename = gscript.tempfile(True) + filename = gs.tempfile(True) file = open(filename, "w") for name in inputs: @@ -178,20 +178,20 @@ def aggregate_raster_maps( # Run r.series try: if len(inputs) > 1000: - gscript.run_command( + gs.run_command( "r.series", flags="z", file=filename, output=output, - overwrite=gscript.overwrite(), + overwrite=gs.overwrite(), method=method, ) else: - gscript.run_command( + gs.run_command( "r.series", file=filename, output=output, - overwrite=gscript.overwrite(), + overwrite=gs.overwrite(), method=method, ) @@ -205,7 +205,7 @@ def aggregate_raster_maps( # In case of a null map continue, do not register null maps if new_map.metadata.get_min() is None and new_map.metadata.get_max() is None: if not register_null: - gscript.run_command("g.remove", flags="f", type="raster", name=output) + gs.run_command("g.remove", flags="f", type="raster", name=output) return None return new_map @@ -364,7 +364,7 @@ def aggregate_by_topology( if len(aggregation_list) > 1: # Create the r.series input file - filename = gscript.tempfile(True) + filename = gs.tempfile(True) file = open(filename, "w") for name in aggregation_list: string = "%s\n" % (name) diff --git a/python/grass/temporal/core.py b/python/grass/temporal/core.py index aad6fc4e2d4..85834df5d41 100644 --- a/python/grass/temporal/core.py +++ b/python/grass/temporal/core.py @@ -33,7 +33,7 @@ # import traceback import os -import grass.script as gscript +import grass.script as gs from grass.pygrass import messages from grass.script.utils import decode @@ -578,8 +578,8 @@ def init(raise_fatal_error=False, skip_db_version_check=False): # We must run t.connect at first to create the temporal database and to # get the environmental variables - gscript.run_command("t.connect", flags="c") - grassenv = gscript.gisenv() + gs.run_command("t.connect", flags="c") + grassenv = gs.gisenv() # Set the global variable for faster access current_mapset = grassenv["MAPSET"] @@ -595,7 +595,7 @@ def init(raise_fatal_error=False, skip_db_version_check=False): # Check if the script library raises on error, # if so we do the same - if gscript.get_raise_on_error() is True: + if gs.get_raise_on_error() is True: raise_on_error = True # Start the GRASS message interface server @@ -614,16 +614,16 @@ def init(raise_fatal_error=False, skip_db_version_check=False): # Set the mapset check and the timestamp write if "TGIS_DISABLE_MAPSET_CHECK" in grassenv: if ( - gscript.encode(grassenv["TGIS_DISABLE_MAPSET_CHECK"]) == "True" - or gscript.encode(grassenv["TGIS_DISABLE_MAPSET_CHECK"]) == "1" + gs.encode(grassenv["TGIS_DISABLE_MAPSET_CHECK"]) == "True" + or gs.encode(grassenv["TGIS_DISABLE_MAPSET_CHECK"]) == "1" ): enable_mapset_check = False msgr.warning("TGIS_DISABLE_MAPSET_CHECK is True") if "TGIS_DISABLE_TIMESTAMP_WRITE" in grassenv: if ( - gscript.encode(grassenv["TGIS_DISABLE_TIMESTAMP_WRITE"]) == "True" - or gscript.encode(grassenv["TGIS_DISABLE_TIMESTAMP_WRITE"]) == "1" + gs.encode(grassenv["TGIS_DISABLE_TIMESTAMP_WRITE"]) == "True" + or gs.encode(grassenv["TGIS_DISABLE_TIMESTAMP_WRITE"]) == "1" ): enable_timestamp_write = False msgr.warning("TGIS_DISABLE_TIMESTAMP_WRITE is True") @@ -662,7 +662,7 @@ def init(raise_fatal_error=False, skip_db_version_check=False): ) else: # Set the default sqlite3 connection in case nothing was defined - gscript.run_command("t.connect", flags="d") + gs.run_command("t.connect", flags="d") driver_string = ciface.get_driver_name() database_string = ciface.get_database_name() tgis_backend = driver_string diff --git a/python/grass/temporal/extract.py b/python/grass/temporal/extract.py index b96ce622540..eccfc9b6acc 100644 --- a/python/grass/temporal/extract.py +++ b/python/grass/temporal/extract.py @@ -12,7 +12,7 @@ import sys from multiprocessing import Process -import grass.script as gscript +import grass.script as gs from grass.exceptions import CalledModuleError from .abstract_map_dataset import AbstractMapDataset @@ -84,7 +84,7 @@ def extract_dataset( sp = open_old_stds(input, type, dbif) # Check the new stds - new_sp = check_new_stds(output, type, dbif, gscript.overwrite()) + new_sp = check_new_stds(output, type, dbif, gs.overwrite()) if type == "vector": rows = sp.get_registered_maps("id,name,mapset,layer", where, "start_time", dbif) else: @@ -140,7 +140,7 @@ def extract_dataset( # Check if new map is in the temporal database if new_map.is_in_db(dbif): - if gscript.overwrite(): + if gs.overwrite(): # Remove the existing temporal database entry new_map.delete(dbif) new_map = sp.get_new_map_instance(map_id) @@ -224,7 +224,7 @@ def extract_dataset( description, semantic_type, dbif, - gscript.overwrite(), + gs.overwrite(), ) # collect empty maps to remove them @@ -300,15 +300,15 @@ def extract_dataset( names += ",%s" % (map.get_name()) count += 1 if type == "raster": - gscript.run_command( + gs.run_command( "g.remove", flags="f", type="raster", name=names, quiet=True ) elif type == "raster3d": - gscript.run_command( + gs.run_command( "g.remove", flags="f", type="raster_3d", name=names, quiet=True ) elif type == "vector": - gscript.run_command( + gs.run_command( "g.remove", flags="f", type="vector", name=names, quiet=True ) @@ -321,8 +321,8 @@ def extract_dataset( def run_mapcalc2d(expr): """Helper function to run r.mapcalc in parallel""" try: - gscript.run_command( - "r.mapcalc", expression=expr, overwrite=gscript.overwrite(), quiet=True + gs.run_command( + "r.mapcalc", expression=expr, overwrite=gs.overwrite(), quiet=True ) except CalledModuleError: sys.exit(1) @@ -331,8 +331,8 @@ def run_mapcalc2d(expr): def run_mapcalc3d(expr): """Helper function to run r3.mapcalc in parallel""" try: - gscript.run_command( - "r3.mapcalc", expression=expr, overwrite=gscript.overwrite(), quiet=True + gs.run_command( + "r3.mapcalc", expression=expr, overwrite=gs.overwrite(), quiet=True ) except CalledModuleError: sys.exit(1) @@ -341,14 +341,14 @@ def run_mapcalc3d(expr): def run_vector_extraction(input, output, layer, type, where): """Helper function to run r.mapcalc in parallel""" try: - gscript.run_command( + gs.run_command( "v.extract", input=input, output=output, layer=layer, type=type, where=where, - overwrite=gscript.overwrite(), + overwrite=gs.overwrite(), quiet=True, ) except CalledModuleError: diff --git a/python/grass/temporal/gui_support.py b/python/grass/temporal/gui_support.py index aa4bf44c008..41f22edc6b7 100644 --- a/python/grass/temporal/gui_support.py +++ b/python/grass/temporal/gui_support.py @@ -10,7 +10,7 @@ :authors: Soeren Gebbert """ -import grass.script as gscript +import grass.script as gs from .core import get_available_temporal_mapsets, init_dbif from .factory import dataset_factory @@ -47,15 +47,15 @@ def tlist_grouped(type, group_type=False, dbif=None): for type in types: try: tlist_result = tlist(type=type, dbif=dbif) - except gscript.ScriptError as e: - gscript.warning(e) + except gs.ScriptError as e: + gs.warning(e) continue for line in tlist_result: try: name, mapset = line.split("@") except ValueError: - gscript.warning(_("Invalid element '%s'") % line) + gs.warning(_("Invalid element '%s'") % line) continue if mapset not in result: diff --git a/python/grass/temporal/mapcalc.py b/python/grass/temporal/mapcalc.py index 99f6d16670c..b3db20eef98 100644 --- a/python/grass/temporal/mapcalc.py +++ b/python/grass/temporal/mapcalc.py @@ -14,7 +14,7 @@ from datetime import datetime from multiprocessing import Process -import grass.script as gscript +import grass.script as gs from grass.exceptions import CalledModuleError from .core import ( @@ -127,7 +127,7 @@ def dataset_mapcalculator( sp = open_old_stds(input, type, dbif) input_list.append(copy.copy(sp)) - new_sp = check_new_stds(output, type, dbif, gscript.overwrite()) + new_sp = check_new_stds(output, type, dbif, gs.overwrite()) # Sample all inputs by the first input and create a sample matrix if spatial: @@ -241,7 +241,7 @@ def dataset_mapcalculator( # Create the r.mapcalc statement for the current time step map_name = "{base}_{suffix}".format( - base=base, suffix=gscript.get_num_suffix(count, num) + base=base, suffix=gs.get_num_suffix(count, num) ) # Remove spaces and new lines expr = expression.replace(" ", "") @@ -269,7 +269,7 @@ def dataset_mapcalculator( # Check if new map is in the temporal database if new_map.is_in_db(dbif): - if gscript.overwrite(): + if gs.overwrite(): # Remove the existing temporal database entry new_map.delete(dbif) new_map = first_input.get_new_map_instance(map_id) @@ -344,7 +344,7 @@ def dataset_mapcalculator( description, semantic_type, dbif, - gscript.overwrite(), + gs.overwrite(), ) count = 0 @@ -394,11 +394,11 @@ def dataset_mapcalculator( names += ",%s" % (map.get_name()) count += 1 if type == "raster": - gscript.run_command( + gs.run_command( "g.remove", flags="f", type="raster", name=names, quiet=True ) elif type == "raster3d": - gscript.run_command( + gs.run_command( "g.remove", flags="f", type="raster_3d", name=names, quiet=True ) @@ -411,8 +411,8 @@ def dataset_mapcalculator( def _run_mapcalc2d(expr): """Helper function to run r.mapcalc in parallel""" try: - gscript.run_command( - "r.mapcalc", expression=expr, overwrite=gscript.overwrite(), quiet=True + gs.run_command( + "r.mapcalc", expression=expr, overwrite=gs.overwrite(), quiet=True ) except CalledModuleError: sys.exit(1) @@ -424,8 +424,8 @@ def _run_mapcalc2d(expr): def _run_mapcalc3d(expr): """Helper function to run r3.mapcalc in parallel""" try: - gscript.run_command( - "r3.mapcalc", expression=expr, overwrite=gscript.overwrite(), quiet=True + gs.run_command( + "r3.mapcalc", expression=expr, overwrite=gs.overwrite(), quiet=True ) except CalledModuleError: sys.exit(1) diff --git a/python/grass/temporal/stds_export.py b/python/grass/temporal/stds_export.py index 0e2c7f7e216..7ef84710e76 100644 --- a/python/grass/temporal/stds_export.py +++ b/python/grass/temporal/stds_export.py @@ -30,7 +30,7 @@ import tarfile import tempfile -import grass.script as gscript +import grass.script as gs from grass.exceptions import CalledModuleError from .open_stds import open_old_stds @@ -82,7 +82,7 @@ def _export_raster_maps_as_gdal( gdal_type = "UInt32" else: gdal_type = "Int32" - gscript.run_command( + gs.run_command( "r.out.gdal", flags="c", input=name, @@ -93,7 +93,7 @@ def _export_raster_maps_as_gdal( **kwargs, ) elif type_: - gscript.run_command( + gs.run_command( "r.out.gdal", flags="cf", input=name, @@ -103,7 +103,7 @@ def _export_raster_maps_as_gdal( **kwargs, ) else: - gscript.run_command( + gs.run_command( "r.out.gdal", flags="c", input=name, @@ -114,7 +114,7 @@ def _export_raster_maps_as_gdal( elif format_ == "AAIGrid": # Export the raster map with r.out.gdal as Arc/Info ASCII Grid out_name = name + ".asc" - gscript.run_command( + gs.run_command( "r.out.gdal", flags="c", input=name, @@ -126,18 +126,18 @@ def _export_raster_maps_as_gdal( except CalledModuleError: shutil.rmtree(new_cwd) tar.close() - gscript.fatal(_("Unable to export raster map <%s>" % name)) + gs.fatal(_("Unable to export raster map <%s>" % name)) tar.add(out_name) # Export the color rules out_name = name + ".color" try: - gscript.run_command("r.colors.out", map=name, rules=out_name) + gs.run_command("r.colors.out", map=name, rules=out_name) except CalledModuleError: shutil.rmtree(new_cwd) tar.close() - gscript.fatal( + gs.fatal( _( "Unable to export color rules for raster " "map <%s> r.out.gdal" % name @@ -163,11 +163,11 @@ def _export_raster_maps(rows, tar, list_file, new_cwd, fs): list_file.write(string) # Export the raster map with r.pack try: - gscript.run_command("r.pack", input=name, flags="c") + gs.run_command("r.pack", input=name, flags="c") except CalledModuleError: shutil.rmtree(new_cwd) tar.close() - gscript.fatal(_("Unable to export raster map <%s> with r.pack" % name)) + gs.fatal(_("Unable to export raster map <%s> with r.pack" % name)) tar.add(name + ".pack") @@ -190,7 +190,7 @@ def _export_vector_maps_as_gml(rows, tar, list_file, new_cwd, fs): list_file.write(string) # Export the vector map with v.out.ogr try: - gscript.run_command( + gs.run_command( "v.out.ogr", input=name, output=(name + ".xml"), @@ -200,9 +200,7 @@ def _export_vector_maps_as_gml(rows, tar, list_file, new_cwd, fs): except CalledModuleError: shutil.rmtree(new_cwd) tar.close() - gscript.fatal( - _("Unable to export vector map <%s> as GML with v.out.ogr" % name) - ) + gs.fatal(_("Unable to export vector map <%s> as GML with v.out.ogr" % name)) tar.add(name + ".xml") tar.add(name + ".xsd") @@ -226,7 +224,7 @@ def _export_vector_maps_as_gpkg(rows, tar, list_file, new_cwd, fs): list_file.write(string) # Export the vector map with v.out.ogr try: - gscript.run_command( + gs.run_command( "v.out.ogr", input=name, output=(name + ".gpkg"), @@ -236,7 +234,7 @@ def _export_vector_maps_as_gpkg(rows, tar, list_file, new_cwd, fs): except CalledModuleError: shutil.rmtree(new_cwd) tar.close() - gscript.fatal( + gs.fatal( _("Unable to export vector map <%s> as GPKG with v.out.ogr" % name) ) @@ -266,11 +264,11 @@ def _export_vector_maps(rows, tar, list_file, new_cwd, fs): list_file.write(string) # Export the vector map with v.pack try: - gscript.run_command("v.pack", input=name, flags="c") + gs.run_command("v.pack", input=name, flags="c") except CalledModuleError: shutil.rmtree(new_cwd) tar.close() - gscript.fatal(_("Unable to export vector map <%s> with v.pack" % name)) + gs.fatal(_("Unable to export vector map <%s> with v.pack" % name)) tar.add(name + ".pack") @@ -292,11 +290,11 @@ def _export_raster3d_maps(rows, tar, list_file, new_cwd, fs): list_file.write(string) # Export the raster 3d map with r3.pack try: - gscript.run_command("r3.pack", input=name, flags="c") + gs.run_command("r3.pack", input=name, flags="c") except CalledModuleError: shutil.rmtree(new_cwd) tar.close() - gscript.fatal(_("Unable to export raster map <%s> with r3.pack" % name)) + gs.fatal(_("Unable to export raster map <%s> with r3.pack" % name)) tar.add(name + ".pack") @@ -402,7 +400,7 @@ def export_stds( list_file.close() # Write projection and metadata - proj = gscript.read_command("g.proj", flags="j") + proj = gs.read_command("g.proj", flags="j") proj_file = open(proj_file_name, "w") proj_file.write(proj) @@ -432,7 +430,7 @@ def export_stds( init_file.write(string) init_file.close() - metadata = gscript.read_command("t.info", type=type_, input=sp.get_id()) + metadata = gs.read_command("t.info", type=type_, input=sp.get_id()) metadata_file = open(metadata_file_name, "w") metadata_file.write(metadata) metadata_file.close() diff --git a/python/grass/temporal/stds_import.py b/python/grass/temporal/stds_import.py index 98a41518c1f..eb68838e798 100644 --- a/python/grass/temporal/stds_import.py +++ b/python/grass/temporal/stds_import.py @@ -33,7 +33,7 @@ import os.path import tarfile -import grass.script as gscript +import grass.script as gs from grass.exceptions import CalledModuleError from .core import get_current_mapset, get_tgis_message_interface @@ -71,25 +71,25 @@ def _import_raster_maps_from_gdal( try: if link: - gscript.run_command( + gs.run_command( "r.external", input=filename, output=name, flags=impflags, - overwrite=gscript.overwrite(), + overwrite=gs.overwrite(), ) else: - gscript.run_command( + gs.run_command( "r.in.gdal", input=filename, output=name, memory=memory, flags=impflags, - overwrite=gscript.overwrite(), + overwrite=gs.overwrite(), ) except CalledModuleError: - gscript.fatal( + gs.fatal( _("Unable to import/link raster map <%s> from file %s.") % (name, filename) ) @@ -98,17 +98,15 @@ def _import_raster_maps_from_gdal( filename = row["filename"] + ".color" if os.path.isfile(filename): try: - gscript.run_command( - "r.colors", map=name, rules=filename, overwrite=gscript.overwrite() + gs.run_command( + "r.colors", map=name, rules=filename, overwrite=gs.overwrite() ) except CalledModuleError: - gscript.fatal( - _("Unable to set the color rules for raster map <%s>.") % name - ) + gs.fatal(_("Unable to set the color rules for raster map <%s>.") % name) # Set the computational region from the last map imported if set_current_region is True: - gscript.run_command("g.region", raster=name) + gs.run_command("g.region", raster=name) ############################################################################ @@ -122,23 +120,23 @@ def _import_raster_maps(maplist, set_current_region=False): name = row["name"] filename = row["filename"] + ".pack" try: - gscript.run_command( + gs.run_command( "r.unpack", input=filename, output=name, flags=impflags, - overwrite=gscript.overwrite(), + overwrite=gs.overwrite(), verbose=True, ) except CalledModuleError: - gscript.fatal( + gs.fatal( _("Unable to unpack raster map <%s> from file %s.") % (name, filename) ) # Set the computational region from the last map imported if set_current_region is True: - gscript.run_command("g.region", raster=name) + gs.run_command("g.region", raster=name) ############################################################################ @@ -153,16 +151,16 @@ def _import_vector_maps_from_gml(maplist, overr, exp, location, link): filename = row["filename"] + ".xml" try: - gscript.run_command( + gs.run_command( "v.in.ogr", input=filename, output=name, flags=impflags, - overwrite=gscript.overwrite(), + overwrite=gs.overwrite(), ) except CalledModuleError: - gscript.fatal( + gs.fatal( _("Unable to import vector map <%s> from file %s.") % (name, filename) ) @@ -182,17 +180,17 @@ def _import_vector_maps(maplist): continue filename = row["filename"] + ".pack" try: - gscript.run_command( + gs.run_command( "v.unpack", input=filename, output=name, flags=impflags, - overwrite=gscript.overwrite(), + overwrite=gs.overwrite(), verbose=True, ) except CalledModuleError: - gscript.fatal( + gs.fatal( _("Unable to unpack vector map <%s> from file %s.") % (name, filename) ) @@ -241,14 +239,14 @@ def import_stds( :param memory: Cache size for raster rows, used in r.in.gdal """ - old_state = gscript.raise_on_error - gscript.set_raise_on_error(True) + old_state = gs.raise_on_error + gs.set_raise_on_error(True) # Check if input file and extraction directory exits if not os.path.exists(input): - gscript.fatal(_("Space time raster dataset archive <%s> not found") % input) + gs.fatal(_("Space time raster dataset archive <%s> not found") % input) if not create and not os.path.exists(directory): - gscript.fatal(_("Extraction directory <%s> not found") % directory) + gs.fatal(_("Extraction directory <%s> not found") % directory) tar = tarfile.open(name=input, mode="r") @@ -265,11 +263,11 @@ def import_stds( member_basenames = [os.path.basename(name) for name in members] if init_file_name not in member_basenames: - gscript.fatal(_("Unable to find init file <%s>") % init_file_name) + gs.fatal(_("Unable to find init file <%s>") % init_file_name) if list_file_name not in member_basenames: - gscript.fatal(_("Unable to find list file <%s>") % list_file_name) + gs.fatal(_("Unable to find list file <%s>") % list_file_name) if proj_file_name not in member_basenames: - gscript.fatal(_("Unable to find projection file <%s>") % proj_file_name) + gs.fatal(_("Unable to find projection file <%s>") % proj_file_name) msgr.message(_("Extracting data...")) # Extraction filters were added in Python 3.12, @@ -282,7 +280,7 @@ def import_stds( tar.extractall(path=directory, filter="data") else: # Remove this when no longer needed - gscript.warning(_("Extracting may be unsafe; consider updating Python")) + gs.warning(_("Extracting may be unsafe; consider updating Python")) tar.extractall(path=directory) tar.close() @@ -296,7 +294,7 @@ def import_stds( # Check projection information if not location: - temp_name = gscript.tempfile() + temp_name = gs.tempfile() temp_file = open(temp_name, "w") proj_name = os.path.abspath(proj_file_name) @@ -315,33 +313,31 @@ def import_stds( proj_file.write(proj_content) proj_file.close() - p = gscript.start_command("g.proj", flags="j", stdout=temp_file) + p = gs.start_command("g.proj", flags="j", stdout=temp_file) p.communicate() temp_file.close() - if not gscript.compare_key_value_text_files(temp_name, proj_name_tmp, sep="="): + if not gs.compare_key_value_text_files(temp_name, proj_name_tmp, sep="="): if overr: - gscript.warning( - _("Projection information does not match. Proceeding...") - ) + gs.warning(_("Projection information does not match. Proceeding...")) else: - diff = "".join(gscript.diff_files(temp_name, proj_name)) - gscript.warning( + diff = "".join(gs.diff_files(temp_name, proj_name)) + gs.warning( _( "Difference between PROJ_INFO file of " "imported map and of current location:" "\n{diff}" ).format(diff=diff) ) - gscript.fatal(_("Projection information does not match. Aborting.")) + gs.fatal(_("Projection information does not match. Aborting.")) # Create a new location based on the projection information and switch # into it - old_env = gscript.gisenv() + old_env = gs.gisenv() if location: try: proj4_string = open(proj_file_name, "r").read() - gscript.create_location( + gs.create_location( dbase=old_env["GISDBASE"], location=location, proj4=proj4_string ) # Just create a new location and return @@ -349,25 +345,25 @@ def import_stds( os.chdir(old_cwd) return except Exception as e: - gscript.fatal( + gs.fatal( _("Unable to create location %(l)s. Reason: %(e)s") % {"l": location, "e": str(e)} ) # Switch to the new created location try: - gscript.run_command( + gs.run_command( "g.mapset", mapset="PERMANENT", project=location, dbase=old_env["GISDBASE"], ) except CalledModuleError: - gscript.fatal(_("Unable to switch to location %s") % location) + gs.fatal(_("Unable to switch to location %s") % location) # create default database connection try: - gscript.run_command("t.connect", flags="d") + gs.run_command("t.connect", flags="d") except CalledModuleError: - gscript.fatal( + gs.fatal( _("Unable to create default temporal database in new location %s") % location ) @@ -406,7 +402,7 @@ def import_stds( if base: mapname = "%s_%s" % ( base, - gscript.get_num_suffix(line_count + 1, max_count), + gs.get_num_suffix(line_count + 1, max_count), ) mapid = "%s@%s" % (mapname, mapset) else: @@ -451,13 +447,13 @@ def import_stds( or "semantic_type" not in init or "number_of_maps" not in init ): - gscript.fatal( + gs.fatal( _("Key words %(t)s, %(s)s or %(n)s not found in init file.") % {"t": "temporal_type", "s": "semantic_type", "n": "number_of_maps"} ) if line_count != int(init["number_of_maps"]): - gscript.fatal(_("Number of maps mismatch in init and list file.")) + gs.fatal(_("Number of maps mismatch in init and list file.")) format_ = "GTiff" type_ = "strds" @@ -468,14 +464,14 @@ def import_stds( format_ = init["format"] if stds_type != type_: - gscript.fatal(_("The archive file is of wrong space time dataset type")) + gs.fatal(_("The archive file is of wrong space time dataset type")) # Check the existence of the files if format_ == "GTiff": for row in maplist: filename = row["filename"] + ".tif" if not os.path.exists(filename): - gscript.fatal( + gs.fatal( _("Unable to find GeoTIFF raster file <%s> in archive.") % filename ) @@ -483,7 +479,7 @@ def import_stds( for row in maplist: filename = row["filename"] + ".asc" if not os.path.exists(filename): - gscript.fatal( + gs.fatal( _("Unable to find AAIGrid raster file <%s> in archive.") % filename ) @@ -491,7 +487,7 @@ def import_stds( for row in maplist: filename = row["filename"] + ".xml" if not os.path.exists(filename): - gscript.fatal( + gs.fatal( _("Unable to find GML vector file <%s> in archive.") % filename ) elif format_ == "pack": @@ -501,18 +497,18 @@ def import_stds( else: filename = row["filename"] + ".pack" if not os.path.exists(filename): - gscript.fatal( + gs.fatal( _("Unable to find GRASS package file <%s> in archive.") % filename ) else: - gscript.fatal(_("Unsupported input format")) + gs.fatal(_("Unsupported input format")) # Check the space time dataset id = output + "@" + mapset sp = dataset_factory(type_, id) - if sp.is_in_db() and gscript.overwrite() is False: - gscript.fatal( + if sp.is_in_db() and gs.overwrite() is False: + gs.fatal( _( "Space time %(t)s dataset <%(sp)s> is already in" " the database. Use the overwrite flag." @@ -542,8 +538,8 @@ def import_stds( _import_vector_maps(maplist) # Create the space time dataset - if sp.is_in_db() and gscript.overwrite() is True: - gscript.info( + if sp.is_in_db() and gs.overwrite() is True: + gs.info( _( "Overwrite space time %(sp)s dataset " "<%(id)s> and unregister all maps." @@ -558,13 +554,13 @@ def import_stds( relative_time_unit = None if temporal_type == "relative": if "relative_time_unit" not in init: - gscript.fatal( + gs.fatal( _("Key word %s not found in init file.") % ("relative_time_unit") ) relative_time_unit = init["relative_time_unit"] sp.set_relative_time_unit(relative_time_unit) - gscript.verbose( + gs.verbose( _("Create space time %s dataset.") % sp.get_new_map_instance(None).get_type() ) @@ -597,13 +593,13 @@ def import_stds( if location: # Switch to the old location try: - gscript.run_command( + gs.run_command( "g.mapset", mapset=old_env["MAPSET"], project=old_env["LOCATION_NAME"], gisdbase=old_env["GISDBASE"], ) except CalledModuleError: - gscript.warning(_("Switching to original location failed")) + gs.warning(_("Switching to original location failed")) - gscript.set_raise_on_error(old_state) + gs.set_raise_on_error(old_state) diff --git a/python/grass/temporal/testsuite/test_register_function.py b/python/grass/temporal/testsuite/test_register_function.py index b1fb779684b..a58ec7d739a 100644 --- a/python/grass/temporal/testsuite/test_register_function.py +++ b/python/grass/temporal/testsuite/test_register_function.py @@ -12,7 +12,7 @@ import datetime import os -import grass.script as gscript +import grass.script as gs import grass.temporal as tgis from grass.gunittest.case import TestCase from grass.gunittest.main import test @@ -980,11 +980,11 @@ def tearDown(self): name="register_map_1,register_map_2", quiet=True, ) - grassenv = gscript.gisenv() + grassenv = gs.gisenv() mapset_path = os.path.join( grassenv["GISDBASE"], grassenv["LOCATION_NAME"], self.newmapset ) - gscript.try_rmdir(mapset_path) + gs.try_rmdir(mapset_path) def test_mapset_access_1(self): """Test the registration of maps from a different mapset.""" diff --git a/python/grass/temporal/testsuite/unittests_temporal_algebra_grs.py b/python/grass/temporal/testsuite/unittests_temporal_algebra_grs.py index a4f5b7f1f78..7e0db57a8ce 100644 --- a/python/grass/temporal/testsuite/unittests_temporal_algebra_grs.py +++ b/python/grass/temporal/testsuite/unittests_temporal_algebra_grs.py @@ -10,7 +10,6 @@ import datetime import os -import grass.script import grass.temporal as tgis from grass.gunittest.case import TestCase from grass.gunittest.main import test diff --git a/python/grass/temporal/testsuite/unittests_temporal_algebra_mixed_stds.py b/python/grass/temporal/testsuite/unittests_temporal_algebra_mixed_stds.py index b821a617df9..cf0e9c82bb7 100644 --- a/python/grass/temporal/testsuite/unittests_temporal_algebra_mixed_stds.py +++ b/python/grass/temporal/testsuite/unittests_temporal_algebra_mixed_stds.py @@ -10,7 +10,6 @@ import datetime import os -import grass.script import grass.temporal as tgis from grass.gunittest.case import TestCase from grass.gunittest.main import test diff --git a/python/grass/temporal/testsuite/unittests_temporal_conditionals.py b/python/grass/temporal/testsuite/unittests_temporal_conditionals.py index 0921b8eb063..ff0703aec1d 100644 --- a/python/grass/temporal/testsuite/unittests_temporal_conditionals.py +++ b/python/grass/temporal/testsuite/unittests_temporal_conditionals.py @@ -10,7 +10,6 @@ import datetime import os -import grass.script import grass.temporal as tgis from grass.gunittest.case import TestCase from grass.gunittest.main import test diff --git a/python/grass/temporal/testsuite/unittests_temporal_raster3d_algebra.py b/python/grass/temporal/testsuite/unittests_temporal_raster3d_algebra.py index 285da1955be..f2d8a215bdb 100644 --- a/python/grass/temporal/testsuite/unittests_temporal_raster3d_algebra.py +++ b/python/grass/temporal/testsuite/unittests_temporal_raster3d_algebra.py @@ -9,7 +9,7 @@ import datetime -import grass.script +import grass.script as gs import grass.temporal as tgis from grass.gunittest.case import TestCase from grass.gunittest.main import test @@ -21,7 +21,7 @@ def setUpClass(cls): """Initiate the temporal GIS and set the region""" tgis.init(True) # Raise on error instead of exit(1) cls.use_temp_region() - ret = grass.script.run_command( + ret = gs.run_command( "g.region", n=80.0, s=0.0, e=120.0, w=0.0, t=100.0, b=0.0, res=10.0 ) diff --git a/raster/r.solute.transport/seguin_verify.py b/raster/r.solute.transport/seguin_verify.py index fc1bdeba66f..745d254ad68 100755 --- a/raster/r.solute.transport/seguin_verify.py +++ b/raster/r.solute.transport/seguin_verify.py @@ -8,49 +8,47 @@ # year = "1996", # series = "Handbuch zur Erkundung des Untergrundes von Deponien und Altlasten" -import grass.script as grass +import grass.script as gs # Overwrite existing maps -grass.run_command("g.gisenv", set="OVERWRITE=1") +gs.run_command("g.gisenv", set="OVERWRITE=1") -grass.message(_("Set the region")) +gs.message(_("Set the region")) # The area is 2000m x 1000m with a cell size of 50m x 50m -grass.run_command("g.region", res=50, res3=50, t=25, b=0, n=1000, s=0, w=0, e=2000) +gs.run_command("g.region", res=50, res3=50, t=25, b=0, n=1000, s=0, w=0, e=2000) -grass.message(_("Create all the input maps needed for groundwater flow computation")) +gs.message(_("Create all the input maps needed for groundwater flow computation")) # Initial condition of the piezometric head, we have a huge gradient from 275m to 50m # over a distance of 2000m -grass.run_command("r.mapcalc", expression="phead_1=if(col() == 1 , 275, 50)") +gs.run_command("r.mapcalc", expression="phead_1=if(col() == 1 , 275, 50)") # Set the active cells and the dirichlet boundary condition, # the first and the last cells a dirichlet -grass.run_command( - "r.mapcalc", expression="status_1=if(col() == 1 || col() == 40 , 2, 1)" -) +gs.run_command("r.mapcalc", expression="status_1=if(col() == 1 || col() == 40 , 2, 1)") # We have a no wells -grass.run_command("r.mapcalc", expression="well_1=0") +gs.run_command("r.mapcalc", expression="well_1=0") # The hydraulic conductivity is 0.0001 m/s -grass.run_command("r.mapcalc", expression="hydcond_1=0.0001") +gs.run_command("r.mapcalc", expression="hydcond_1=0.0001") # The recharge, well we have no recharge at all -grass.run_command("r.mapcalc", expression="recharge_1=0") +gs.run_command("r.mapcalc", expression="recharge_1=0") # We have a confined aquifer with a height of 25m -grass.run_command("r.mapcalc", expression="top_conf_1=25") +gs.run_command("r.mapcalc", expression="top_conf_1=25") # Bottom of the aquifer starts at 0m -grass.run_command("r.mapcalc", expression="bottom_1=0") +gs.run_command("r.mapcalc", expression="bottom_1=0") # This porosity of sand aquifer is 0.17 in example 1.1 -grass.run_command("r.mapcalc", expression="poros_1=0.17") +gs.run_command("r.mapcalc", expression="poros_1=0.17") # The specific yield of a confined aquifer -grass.run_command("r.mapcalc", expression="syield_1=0.0001") -grass.run_command("r.mapcalc", expression="null_1=0.0") +gs.run_command("r.mapcalc", expression="syield_1=0.0001") +gs.run_command("r.mapcalc", expression="null_1=0.0") -grass.message( +gs.message( "First compute a steady state groundwater flow with a mean velocity" " of 5.88 m/d or 6.8*10^5m/s" ) # Compute the steady state groundwater flow -grass.run_command( +gs.run_command( "r.gwflow", solver="cg", top="top_conf_1", @@ -68,26 +66,22 @@ ) -grass.message(_("generate the transport data")) +gs.message(_("generate the transport data")) # The initial concentration is zero -grass.run_command( - "r.mapcalc", expression="c_1=if(col() == 10 && row() == 10 , 0.0, 0.0)" -) +gs.run_command("r.mapcalc", expression="c_1=if(col() == 10 && row() == 10 , 0.0, 0.0)") # One inner sources (result of chemical reaction) -grass.run_command( +gs.run_command( "r.mapcalc", expression="cs_1=if(col() == 10 && row() == 10 , 0.0013888, 0.0)" ) # No pollution by well -grass.run_command("r.mapcalc", expression="cin_1=0.0") +gs.run_command("r.mapcalc", expression="cin_1=0.0") # We have a transfer boundary condition -grass.run_command( - "r.mapcalc", expression="tstatus_1=if(col() == 1 || col() == 40 , 3, 1)" -) +gs.run_command("r.mapcalc", expression="tstatus_1=if(col() == 1 || col() == 40 , 3, 1)") # No diffusion coefficient known for the solution -grass.run_command("r.mapcalc", expression="diff_1=0.0") +gs.run_command("r.mapcalc", expression="diff_1=0.0") # Normal retardation -grass.run_command("r.mapcalc", expression="R_1=1.0") +gs.run_command("r.mapcalc", expression="R_1=1.0") # Longitudinal and transversal dispersivity length al = 100m, at = 10m AL = 100 @@ -95,7 +89,7 @@ # Compute the solute transport using the above defined dispersivity coefficients # for a timestep of 1000d -grass.run_command( +gs.run_command( "r.solute.transport", "c", error=0.000000000000001, @@ -124,14 +118,14 @@ ) # Get the maximum concentration -range = grass.parse_command("r.info", "r", map="stresult_conf_1") +range = gs.parse_command("r.info", "r", map="stresult_conf_1") # Normalize the result -grass.run_command( +gs.run_command( "r.mapcalc", expression="stresult_conf_1_norm = stresult_conf_1/" + str(range["max"]), ) # Create contour lines range from 0.7 to 0.1 in 0.1 steps -grass.run_command( +gs.run_command( "r.contour", input="stresult_conf_1_norm", output="stresult_conf_1_norm", @@ -144,11 +138,11 @@ # Used to compute a lower velocity, so the mean velocity is # about 1 m/d or 1.15*10^-5 m/s -grass.run_command("r.mapcalc", expression="poros_2=1") +gs.run_command("r.mapcalc", expression="poros_2=1") # Compute the solute transport using the above defined dispersivity coefficients for # a timestep of 1000d -grass.run_command( +gs.run_command( "r.solute.transport", "c", error=0.000000000000001, @@ -177,14 +171,14 @@ ) # Get the maximum concentration -range = grass.parse_command("r.info", "r", map="stresult_conf_2") +range = gs.parse_command("r.info", "r", map="stresult_conf_2") # Normalize the result -grass.run_command( +gs.run_command( "r.mapcalc", expression="stresult_conf_2_norm = stresult_conf_2/" + str(range["max"]), ) # Create contour lines range from 0.7 to 0.1 in 0.1 steps -grass.run_command( +gs.run_command( "r.contour", input="stresult_conf_2_norm", output="stresult_conf_2_norm", diff --git a/raster/r.solute.transport/seguin_verify_well.py b/raster/r.solute.transport/seguin_verify_well.py index 10ddc6a2dd5..85b82e53140 100755 --- a/raster/r.solute.transport/seguin_verify_well.py +++ b/raster/r.solute.transport/seguin_verify_well.py @@ -9,47 +9,45 @@ # series = "Handbuch zur Erkundung des Untergrundes von Deponien und Altlasten" # -import grass.script as grass +import grass.script as gs # Overwrite existing maps -grass.run_command("g.gisenv", set="OVERWRITE=1") +gs.run_command("g.gisenv", set="OVERWRITE=1") -grass.message(_("Set the region")) +gs.message(_("Set the region")) # The area is 2000m x 1000m with a cell size of 50m x 50m -grass.run_command("g.region", res=50, res3=50, t=25, b=0, n=1000, s=0, w=0, e=2000) +gs.run_command("g.region", res=50, res3=50, t=25, b=0, n=1000, s=0, w=0, e=2000) -grass.message(_("Create all the input maps needed for groundwater flow computation")) +gs.message(_("Create all the input maps needed for groundwater flow computation")) # Initial condition of the piezometric head, we have a huge gradient from 275m to 50m # over a distance of 2000m -grass.run_command("r.mapcalc", expression="phead_1=if(col() == 1 , 275, 50)") +gs.run_command("r.mapcalc", expression="phead_1=if(col() == 1 , 275, 50)") # Set the active cells and the dirichlet boundary condition -grass.run_command( - "r.mapcalc", expression="status_1=if(col() == 1 || col() == 40 , 2, 1)" -) +gs.run_command("r.mapcalc", expression="status_1=if(col() == 1 || col() == 40 , 2, 1)") # We have a single well with a small influent pumping rate -grass.run_command( +gs.run_command( "r.mapcalc", expression="well_1=if((row() == 10 && col() == 10), 0.000002818287, 0)" ) # The hydraulic conductivity -grass.run_command("r.mapcalc", expression="hydcond_1=0.0001") +gs.run_command("r.mapcalc", expression="hydcond_1=0.0001") # The recharge, well we have no recharge at all -grass.run_command("r.mapcalc", expression="recharge_1=0") +gs.run_command("r.mapcalc", expression="recharge_1=0") # We have a confined aquifer with a height of 25m -grass.run_command("r.mapcalc", expression="top_conf_1=25") +gs.run_command("r.mapcalc", expression="top_conf_1=25") # Bottom of the aquifer starts at 0m -grass.run_command("r.mapcalc", expression="bottom_1=0") +gs.run_command("r.mapcalc", expression="bottom_1=0") # This is the standard porosity of sand aquifer -grass.run_command("r.mapcalc", expression="poros_1=0.17") +gs.run_command("r.mapcalc", expression="poros_1=0.17") # The specific yield of a confined aquifer -grass.run_command("r.mapcalc", expression="syield_1=0.0001") -grass.run_command("r.mapcalc", expression="null_1=0.0") +gs.run_command("r.mapcalc", expression="syield_1=0.0001") +gs.run_command("r.mapcalc", expression="null_1=0.0") -grass.message("First compute a steady state groundwater flow") +gs.message("First compute a steady state groundwater flow") # Compute the steady state groundwater flow -grass.run_command( +gs.run_command( "r.gwflow", solver="cg", top="top_conf_1", @@ -66,27 +64,23 @@ type="confined", ) -grass.message(_("generate the transport data")) +gs.message(_("generate the transport data")) # The initial concentration is zero -grass.run_command( - "r.mapcalc", expression="c_1=if(col() == 10 && row() == 10 , 0.0, 0.0)" -) +gs.run_command("r.mapcalc", expression="c_1=if(col() == 10 && row() == 10 , 0.0, 0.0)") # No inner sources or sinks (result of chemical reaction) -grass.run_command("r.mapcalc", expression="cs_1=0.0") +gs.run_command("r.mapcalc", expression="cs_1=0.0") # The pollution is inserted by a well -grass.run_command( +gs.run_command( "r.mapcalc", expression="cin_1=if(col() == 10 && row() == 10 ," + str(0.2 / 86400) + ", 0.0)", ) # We have a transfer boundary condition -grass.run_command( - "r.mapcalc", expression="tstatus_1=if(col() == 1 || col() == 40 , 3, 1)" -) +gs.run_command("r.mapcalc", expression="tstatus_1=if(col() == 1 || col() == 40 , 3, 1)") # No diffusion coefficient known for the solution -grass.run_command("r.mapcalc", expression="diff_1=0.0") +gs.run_command("r.mapcalc", expression="diff_1=0.0") # Normal retardation -grass.run_command("r.mapcalc", expression="R_1=1.0") +gs.run_command("r.mapcalc", expression="R_1=1.0") # Longitudinal and transversal dispersivity length AL = 50 @@ -94,7 +88,7 @@ # Compute the solute transport using the above defined dispersivity coefficients # for a timestep of 250d -grass.run_command( +gs.run_command( "r.solute.transport", "c", error=0.000000000000001, @@ -121,14 +115,14 @@ ) # Get the maximum concentration -range = grass.parse_command("r.info", "r", map="stresult_conf_1") +range = gs.parse_command("r.info", "r", map="stresult_conf_1") # Normalize the result -grass.run_command( +gs.run_command( "r.mapcalc", expression="stresult_conf_1_norm = stresult_conf_1/" + str(range["max"]), ) # Create contour lines range from 0.7 to 0.1 in 0.1 steps -grass.run_command( +gs.run_command( "r.contour", input="stresult_conf_1_norm", output="stresult_conf_1_norm", @@ -143,7 +137,7 @@ # Compute the solute transport using the above defined dispersivity coefficients # for a timestep of 250d -grass.run_command( +gs.run_command( "r.solute.transport", "c", error=0.000000000000001, @@ -171,14 +165,14 @@ # Get the maximum concentration -range = grass.parse_command("r.info", "r", map="stresult_conf_2") +range = gs.parse_command("r.info", "r", map="stresult_conf_2") # Normalize the result -grass.run_command( +gs.run_command( "r.mapcalc", expression="stresult_conf_2_norm = stresult_conf_2/" + str(range["max"]), ) # Create contour lines range from 0.7 to 0.1 in 0.1 steps -grass.run_command( +gs.run_command( "r.contour", input="stresult_conf_2_norm", output="stresult_conf_2_norm", diff --git a/scripts/d.rast.edit/d.rast.edit.py b/scripts/d.rast.edit/d.rast.edit.py index 61f6a63cedc..6519d10c7a1 100755 --- a/scripts/d.rast.edit/d.rast.edit.py +++ b/scripts/d.rast.edit/d.rast.edit.py @@ -77,7 +77,7 @@ import sys import math import atexit -import grass.script as grass +import grass.script as gs from grass.script.setup import set_gui_path @@ -91,7 +91,7 @@ if len(sys.argv) == 2: arg = sys.argv[1] if arg[0:2] == "--" or arg in {"help", "-help"}: - grass.parser() + gs.parser() # Either we didn't call g.parser, or it returned # At this point, there's nothing to be done except re-raise the exception raise @@ -114,7 +114,7 @@ def run(cmd, **kwargs): - grass.run_command(cmd, quiet=True, **kwargs) + gs.run_command(cmd, quiet=True, **kwargs) def wxGUI(): @@ -137,7 +137,7 @@ def __init__(self, app, parent): run("r.out.ppm", input=app.inmap, output=app.tempfile) self.image = wx.Bitmap(wx.Image(app.tempfile)) - grass.try_remove(app.tempfile) + gs.try_remove(app.tempfile) app.force_window() @@ -475,19 +475,19 @@ def __init__(self, options): wx.App.__init__(self) def initialize(self): - grass.use_temp_region() + gs.use_temp_region() run("g.region", raster=self.inmap) - reg = grass.region() + reg = gs.region() for k, f in wind_keys.values(): self.total[k] = (f)(reg[k]) self.cols = min(self.cols, self.total["cols"]) self.rows = min(self.rows, self.total["rows"]) - tempbase = grass.tempfile() - grass.try_remove(tempbase) + tempbase = gs.tempfile() + gs.try_remove(tempbase) self.tempfile = tempbase + ".ppm" self.tempmap = "tmp.d.rast.edit" @@ -498,7 +498,7 @@ def initialize(self): run("r.colors", map=self.outmap, rast=self.inmap) def cleanup(self): - grass.try_remove(self.tempfile) + gs.try_remove(self.tempfile) run("g.remove", flags="f", type="raster", name=self.tempmap) def finalize(self): @@ -506,28 +506,28 @@ def finalize(self): sys.exit(0) def save_map(self): - p = grass.feed_command( + p = gs.feed_command( "r.in.ascii", input="-", output=self.tempmap, quiet=True, overwrite=True ) outf = p.stdin - outf.write(grass.encode("north: %f\n" % self.wind["n"])) - outf.write(grass.encode("south: %f\n" % self.wind["s"])) - outf.write(grass.encode("east: %f\n" % self.wind["e"])) - outf.write(grass.encode("west: %f\n" % self.wind["w"])) - outf.write(grass.encode("rows: %d\n" % self.wind["rows"])) - outf.write(grass.encode("cols: %d\n" % self.wind["cols"])) - outf.write(grass.encode("null: *\n")) + outf.write(gs.encode("north: %f\n" % self.wind["n"])) + outf.write(gs.encode("south: %f\n" % self.wind["s"])) + outf.write(gs.encode("east: %f\n" % self.wind["e"])) + outf.write(gs.encode("west: %f\n" % self.wind["w"])) + outf.write(gs.encode("rows: %d\n" % self.wind["rows"])) + outf.write(gs.encode("cols: %d\n" % self.wind["cols"])) + outf.write(gs.encode("null: *\n")) for row in range(self.wind["rows"]): for col in range(self.wind["cols"]): if col > 0: - outf.write(grass.encode(" ")) + outf.write(gs.encode(" ")) val = self.values[row][col] if val and self.changed[row][col]: - outf.write(grass.encode("%s" % val)) + outf.write(gs.encode("%s" % val)) else: - outf.write(grass.encode("*")) - outf.write(grass.encode("\n")) + outf.write(gs.encode("*")) + outf.write(gs.encode("\n")) outf.close() p.wait() @@ -545,7 +545,7 @@ def save_map(self): def read_header(self, infile): wind = {} for i in range(6): - line = grass.decode(infile.readline()).rstrip("\r\n") + line = gs.decode(infile.readline()).rstrip("\r\n") f = line.split(":") key = f[0] val = f[1].strip() @@ -556,14 +556,14 @@ def read_header(self, infile): def read_data(self, infile): values = [] for row in range(self.wind["rows"]): - line = grass.decode(infile.readline()).rstrip("\r\n") + line = gs.decode(infile.readline()).rstrip("\r\n") values.append(line.split()) return values def load_map(self): run("g.region", **self.wind) - p = grass.pipe_command("r.out.ascii", input=self.inmap, quiet=True) + p = gs.pipe_command("r.out.ascii", input=self.inmap, quiet=True) self.wind = self.read_header(p.stdout) self.values = self.read_data(p.stdout) self.changed = [[False for c in row] for row in self.values] @@ -573,7 +573,7 @@ def load_map(self): run("r.out.ppm", input=self.inmap, output=self.tempfile) colorimg = wx.Image(self.tempfile) - grass.try_remove(self.tempfile) + gs.try_remove(self.tempfile) for row in range(self.wind["rows"]): for col in range(self.wind["cols"]): @@ -592,7 +592,7 @@ def load_aspect(self): if not self.aspect: return - p = grass.pipe_command("r.out.ascii", input=self.aspect, quiet=True) + p = gs.pipe_command("r.out.ascii", input=self.aspect, quiet=True) self.read_header(p.stdout) self.angles = self.read_data(p.stdout) p.wait() @@ -653,7 +653,7 @@ def force_color(self, val): run("g.remove", flags="f", type="raster", name=self.tempmap) tempimg = wx.Image(self.tempfile) - grass.try_remove(self.tempfile) + gs.try_remove(self.tempfile) rgb = tempimg.get(0, 0) color = "#%02x%02x%02x" % rgb @@ -721,7 +721,7 @@ def OnInit(self): if __name__ == "__main__": - options, flags = grass.parser() + options, flags = gs.parser() from gui_core.wrap import ClientDC, Menu, Panel diff --git a/scripts/d.rast.leg/d.rast.leg.py b/scripts/d.rast.leg/d.rast.leg.py index 1ea93b8e467..46c46928d9b 100755 --- a/scripts/d.rast.leg/d.rast.leg.py +++ b/scripts/d.rast.leg/d.rast.leg.py @@ -63,7 +63,7 @@ import sys import os -import grass.script as grass +import grass.script as gs def make_frame(f, b, t, l, r): # noqa: E741 @@ -91,14 +91,14 @@ def main(): smooth = flags["s"] # for -n flag of d.legend - if not grass.find_file(map)["file"]: - grass.fatal(_("Raster map <%s> not found") % map) + if not gs.find_file(map)["file"]: + gs.fatal(_("Raster map <%s> not found") % map) # for rast= - if rast and not grass.find_file(rast)["file"]: - grass.fatal(_("Raster map <%s> not found") % rast) + if rast and not gs.find_file(rast)["file"]: + gs.fatal(_("Raster map <%s> not found") % rast) - s = grass.read_command("d.info", flags="f") + s = gs.read_command("d.info", flags="f") if not s: sys.exit(1) @@ -106,7 +106,7 @@ def main(): s = s.split(":")[1] f = tuple([float(x) for x in s.split()]) - grass.run_command("d.erase") + gs.run_command("d.erase") os.environ["GRASS_RENDER_FILE_READ"] = "TRUE" # draw title @@ -115,14 +115,12 @@ def main(): make_frame(f, 90, 100, 70, 100) # use map name without mapset suffix mapname = map.split("@")[0] - grass.run_command( - "d.text", color="black", size=5, at="5,97", align="cl", text=mapname - ) + gs.run_command("d.text", color="black", size=5, at="5,97", align="cl", text=mapname) # draw legend # set legend vertical position and size based on number of categories - cats = grass.read_command("r.describe", map=map, flags="1n") + cats = gs.read_command("r.describe", map=map, flags="1n") ncats = len(cats.strip().split("\n")) # Only need to adjust legend size if number of categories is between 1 and 10 @@ -139,7 +137,7 @@ def main(): else: lmap = map - kv = grass.raster_info(map=lmap) + kv = gs.raster_info(map=lmap) if kv["datatype"] == "CELL": leg_at = None else: @@ -161,13 +159,13 @@ def main(): # lflags += 'n' make_frame(f, 0, 90, 70, 100) - grass.run_command("d.legend", flags=lflags, raster=lmap, lines=nlines, at=leg_at) + gs.run_command("d.legend", flags=lflags, raster=lmap, lines=nlines, at=leg_at) # draw map make_frame(f, 0, 100, 0, 70) - grass.run_command("d.rast", map=map) + gs.run_command("d.rast", map=map) if __name__ == "__main__": - options, flags = grass.parser() + options, flags = gs.parser() main() diff --git a/scripts/db.dropcolumn/db.dropcolumn.py b/scripts/db.dropcolumn/db.dropcolumn.py index a097ec3314f..24681b18b23 100755 --- a/scripts/db.dropcolumn/db.dropcolumn.py +++ b/scripts/db.dropcolumn/db.dropcolumn.py @@ -46,7 +46,7 @@ import string from grass.exceptions import CalledModuleError -import grass.script as gscript +import grass.script as gs def main(): @@ -57,10 +57,10 @@ def main(): force = flags["f"] # check if DB parameters are set, and if not set them. - gscript.run_command("db.connect", flags="c") + gs.run_command("db.connect", flags="c") if not database or not driver: - kv = gscript.db_connection() + kv = gs.db_connection() if not database: database = kv["database"] if not driver: @@ -68,10 +68,10 @@ def main(): # schema needed for PG? if force: - gscript.message(_("Forcing ...")) + gs.message(_("Forcing ...")) if column == "cat": - gscript.warning( + gs.warning( _( "Deleting <%s> column which may be needed to keep " "table connected to a vector map" @@ -80,22 +80,21 @@ def main(): ) cols = [ - f[0] - for f in gscript.db_describe(table, database=database, driver=driver)["cols"] + f[0] for f in gs.db_describe(table, database=database, driver=driver)["cols"] ] if column not in cols: - gscript.fatal(_("Column <%s> not found in table") % column) + gs.fatal(_("Column <%s> not found in table") % column) if not force: - gscript.message(_("Column <%s> would be deleted.") % column) - gscript.message("") - gscript.message( + gs.message(_("Column <%s> would be deleted.") % column) + gs.message("") + gs.message( _("You must use the force flag (-f) to actually remove it. Exiting.") ) return 0 if driver == "sqlite": - sqlite3_version = gscript.read_command( + sqlite3_version = gs.read_command( "db.select", sql="SELECT sqlite_version();", flags="c", @@ -111,7 +110,7 @@ def main(): # for older sqlite3 versions, use old way to remove column colnames = [] coltypes = [] - for f in gscript.db_describe(table)["cols"]: + for f in gs.db_describe(table)["cols"]: if f[0] != column: colnames.append(f[0]) coltypes.append("%s %s" % (f[0], f[1])) @@ -135,15 +134,15 @@ def main(): sql = "ALTER TABLE %s DROP COLUMN %s" % (table, column) try: - gscript.write_command( + gs.write_command( "db.execute", input="-", database=database, driver=driver, stdin=sql ) except CalledModuleError: - gscript.fatal(_("Cannot continue (problem deleting column)")) + gs.fatal(_("Cannot continue (problem deleting column)")) return 0 if __name__ == "__main__": - options, flags = gscript.parser() + options, flags = gs.parser() sys.exit(main()) diff --git a/scripts/db.droptable/db.droptable.py b/scripts/db.droptable/db.droptable.py index 689185263fd..571638748cf 100755 --- a/scripts/db.droptable/db.droptable.py +++ b/scripts/db.droptable/db.droptable.py @@ -43,7 +43,7 @@ # %end import sys -import grass.script as grass +import grass.script as gs from grass.script.utils import encode @@ -53,9 +53,9 @@ def main(): if not options["driver"] or not options["database"]: # check if DB parameters are set, and if not set them. - grass.run_command("db.connect", flags="c", quiet=True) + gs.run_command("db.connect", flags="c", quiet=True) - kv = grass.db_connection() + kv = gs.db_connection() if options["database"]: database = options["database"] else: @@ -67,36 +67,36 @@ def main(): # schema needed for PG? if force: - grass.message(_("Forcing ...")) + gs.message(_("Forcing ...")) # check if table exists - if not grass.db_table_exist(table): - grass.warning(_("Table <%s> not found in database <%s>") % (table, database)) + if not gs.db_table_exist(table): + gs.warning(_("Table <%s> not found in database <%s>") % (table, database)) sys.exit(0) # check if table is used somewhere (connected to vector map) - used = grass.db.db_table_in_vector(table) + used = gs.db.db_table_in_vector(table) if used: - grass.warning( + gs.warning( _("Deleting table <%s> which is attached to following map(s):") % table ) for vect in used: - grass.warning("%s" % vect) + gs.warning("%s" % vect) if not force: - grass.message(_("The table <%s> would be deleted.") % table) - grass.message("") - grass.message(_("You must use the force flag to actually remove it. Exiting.")) + gs.message(_("The table <%s> would be deleted.") % table) + gs.message("") + gs.message(_("You must use the force flag to actually remove it. Exiting.")) sys.exit(0) - p = grass.feed_command("db.execute", input="-", database=database, driver=driver) + p = gs.feed_command("db.execute", input="-", database=database, driver=driver) p.stdin.write(encode("DROP TABLE " + table)) p.stdin.close() p.wait() if p.returncode != 0: - grass.fatal(_("Cannot continue (problem deleting table).")) + gs.fatal(_("Cannot continue (problem deleting table).")) if __name__ == "__main__": - options, flags = grass.parser() + options, flags = gs.parser() main() diff --git a/scripts/db.in.ogr/db.in.ogr.py b/scripts/db.in.ogr/db.in.ogr.py index 32b3815e68a..0137a41d62c 100755 --- a/scripts/db.in.ogr/db.in.ogr.py +++ b/scripts/db.in.ogr/db.in.ogr.py @@ -73,7 +73,7 @@ # %end import os -import grass.script as grass +import grass.script as gs from grass.script.utils import decode from grass.exceptions import CalledModuleError @@ -86,37 +86,37 @@ def main(): output = options["output"] key = options["key"] - mapset = grass.gisenv()["MAPSET"] + mapset = gs.gisenv()["MAPSET"] if db_table: input = db_table if not output: tmpname = input.replace(".", "_") - output = grass.basename(tmpname) + output = gs.basename(tmpname) # check if table exists try: nuldev = open(os.devnull, "w+") - s = grass.read_command("db.tables", flags="p", quiet=True, stderr=nuldev) + s = gs.read_command("db.tables", flags="p", quiet=True, stderr=nuldev) nuldev.close() except CalledModuleError: # check connection parameters, set if uninitialized - grass.read_command("db.connect", flags="c") - s = grass.read_command("db.tables", flags="p", quiet=True) + gs.read_command("db.connect", flags="c") + s = gs.read_command("db.tables", flags="p", quiet=True) for line in decode(s).splitlines(): if line == output: - if grass.overwrite(): - grass.warning( + if gs.overwrite(): + gs.warning( _("Table <%s> already exists and will be overwritten") % output ) - grass.write_command( + gs.write_command( "db.execute", input="-", stdin="DROP TABLE %s" % output ) break else: - grass.fatal(_("Table <%s> already exists") % output) + gs.fatal(_("Table <%s> already exists") % output) # treat DB as real vector map... layer = db_table if db_table else None @@ -126,7 +126,7 @@ def main(): vopts["encoding"] = options["encoding"] try: - grass.run_command( + gs.run_command( "v.in.ogr", flags="o", input=input, @@ -139,12 +139,12 @@ def main(): ) except CalledModuleError: if db_table: - grass.fatal(_("Input table <%s> not found or not readable") % input) + gs.fatal(_("Input table <%s> not found or not readable") % input) else: - grass.fatal(_("Input DSN <%s> not found or not readable") % input) + gs.fatal(_("Input DSN <%s> not found or not readable") % input) # save db connection settings of the output - f = grass.vector_layer_db(output, "1") + f = gs.vector_layer_db(output, "1") table = f["table"] database = f["database"] @@ -152,13 +152,13 @@ def main(): # rename ID col if requested from cat to new name if key: - grass.write_command( + gs.write_command( "db.execute", quiet=True, input="-", stdin="ALTER TABLE %s ADD COLUMN %s integer" % (output, key), ) - grass.write_command( + gs.write_command( "db.execute", quiet=True, input="-", @@ -166,17 +166,17 @@ def main(): ) # ... and immediately drop the empty geometry - vectfile = grass.find_file(output, element="vector", mapset=mapset)["file"] + vectfile = gs.find_file(output, element="vector", mapset=mapset)["file"] if not vectfile: - grass.fatal(_("Something went wrong. Should not happen")) + gs.fatal(_("Something went wrong. Should not happen")) else: # remove the vector part - grass.run_command("v.db.connect", quiet=True, map=output, layer="1", flags="d") - grass.run_command("g.remove", flags="f", quiet=True, type="vector", name=output) + gs.run_command("v.db.connect", quiet=True, map=output, layer="1", flags="d") + gs.run_command("g.remove", flags="f", quiet=True, type="vector", name=output) # get rid of superfluous auto-added cat column (and cat_ if present) nuldev = open(os.devnull, "w+") - grass.run_command( + gs.run_command( "db.dropcolumn", quiet=True, flags="f", @@ -189,10 +189,10 @@ def main(): ) nuldev.close() - records = grass.db_describe(table, database=database, driver=driver)["nrows"] - grass.message(_("Imported table <%s> with %d rows") % (output, records)) + records = gs.db_describe(table, database=database, driver=driver)["nrows"] + gs.message(_("Imported table <%s> with %d rows") % (output, records)) if __name__ == "__main__": - options, flags = grass.parser() + options, flags = gs.parser() main() diff --git a/scripts/db.univar/db.univar.py b/scripts/db.univar/db.univar.py index 8a91656d4b6..f941be42140 100755 --- a/scripts/db.univar/db.univar.py +++ b/scripts/db.univar/db.univar.py @@ -68,23 +68,23 @@ import json import math -import grass.script as gscript +import grass.script as gs def cleanup(): for ext in ["", ".sort"]: - gscript.try_remove(tmp + ext) + gs.try_remove(tmp + ext) def sortfile(infile, outfile): inf = open(infile, "r") outf = open(outfile, "w") - if gscript.find_program("sort", "--help"): - gscript.run_command("sort", flags="n", stdin=inf, stdout=outf) + if gs.find_program("sort", "--help"): + gs.run_command("sort", flags="n", stdin=inf, stdout=outf) else: # FIXME: we need a large-file sorting function - gscript.warning(_("'sort' not found: sorting in memory")) + gs.warning(_("'sort' not found: sorting in memory")) lines = inf.readlines() for i in range(len(lines)): lines[i] = float(lines[i].rstrip("\r\n")) @@ -103,7 +103,7 @@ def main(): # as well as pushing the limit of how long the function can be. # pylint: disable=too-many-branches global tmp - tmp = gscript.tempfile() + tmp = gs.tempfile() extend = flags["e"] shellstyle = flags["g"] @@ -125,25 +125,23 @@ def main(): elif shellstyle: # This can be a message or warning in future versions. # In version 9, -g may be removed. - gscript.verbose(_("The format option is used and -g flag ignored")) + gs.verbose(_("The format option is used and -g flag ignored")) - desc_table = gscript.db_describe(table, database=database, driver=driver) + desc_table = gs.db_describe(table, database=database, driver=driver) if not desc_table: - gscript.fatal(_("Unable to describe table <%s>") % table) + gs.fatal(_("Unable to describe table <%s>") % table) found = False for cname, ctype, cwidth in desc_table["cols"]: if cname == column: found = True if ctype not in {"INTEGER", "DOUBLE PRECISION"}: - gscript.fatal(_("Column <%s> is not numeric") % cname) + gs.fatal(_("Column <%s> is not numeric") % cname) if not found: - gscript.fatal(_("Column <%s> not found in table <%s>") % (column, table)) + gs.fatal(_("Column <%s> not found in table <%s>") % (column, table)) if output_format == "plain": - gscript.verbose( - _("Calculation for column <%s> of table <%s>...") % (column, table) - ) - gscript.message(_("Reading column values...")) + gs.verbose(_("Calculation for column <%s> of table <%s>...") % (column, table)) + gs.message(_("Reading column values...")) sql = "SELECT %s FROM %s" % (column, table) if where: @@ -156,7 +154,7 @@ def main(): driver = None tmpf = open(tmp, "w") - gscript.run_command( + gs.run_command( "db.select", flags="c", table=table, @@ -171,12 +169,12 @@ def main(): tmpf = open(tmp) if tmpf.read(1) == "": if output_format in {"plain", "shell"}: - gscript.fatal(_("Table <%s> contains no data.") % table) + gs.fatal(_("Table <%s> contains no data.") % table) tmpf.close() # calculate statistics if output_format == "plain": - gscript.verbose(_("Calculating statistics...")) + gs.verbose(_("Calculating statistics...")) N = 0 sum = 0.0 @@ -201,7 +199,7 @@ def main(): if N <= 0: if output_format in {"plain", "shell"}: - gscript.fatal(_("No non-null values found")) + gs.fatal(_("No non-null values found")) else: # We produce valid JSON with a value for n even when the query returned # no rows or when all values are nulls. @@ -379,6 +377,6 @@ def main(): if __name__ == "__main__": - options, flags = gscript.parser() + options, flags = gs.parser() atexit.register(cleanup) main() diff --git a/scripts/g.extension.all/g.extension.all.py b/scripts/g.extension.all/g.extension.all.py index 14a928ff9a1..8535dc06502 100644 --- a/scripts/g.extension.all/g.extension.all.py +++ b/scripts/g.extension.all/g.extension.all.py @@ -46,7 +46,7 @@ from urllib import request as urlrequest from urllib.error import HTTPError, URLError -import grass.script as gscript +import grass.script as gs from grass.exceptions import CalledModuleError HEADERS = { @@ -58,7 +58,7 @@ def get_extensions(): addon_base = os.getenv("GRASS_ADDON_BASE") if not addon_base: - gscript.fatal(_("%s not defined") % "GRASS_ADDON_BASE") + gs.fatal(_("%s not defined") % "GRASS_ADDON_BASE") fXML = os.path.join(addon_base, "modules.xml") if not os.path.exists(fXML): return [] @@ -68,13 +68,13 @@ def get_extensions(): try: tree = etree.fromstring(fo.read()) except Exception as e: - gscript.error(_("Unable to parse metadata file: %s") % e) + gs.error(_("Unable to parse metadata file: %s") % e) fo.close() return [] fo.close() - libgis_rev = gscript.version()["libgis_revision"] + libgis_rev = gs.version()["libgis_revision"] ret = [] for tnode in tree.findall("task"): gnode = tnode.find("libgis") @@ -107,7 +107,7 @@ def download_modules_xml_file(url, response_format, *args, **kwargs): if not response.code == 200: index = HTTP_STATUS_CODES.index(response.code) desc = HTTP_STATUS_CODES[index].description - gscript.fatal( + gs.fatal( _( "Download file from <{url}>, " "return status code {code}, " @@ -119,7 +119,7 @@ def download_modules_xml_file(url, response_format, *args, **kwargs): ), ) if response_format not in response.getheader("Content-Type"): - gscript.fatal( + gs.fatal( _( "Wrong file format downloaded. " "Check url <{url}>. Allowed file format is " @@ -133,7 +133,7 @@ def download_modules_xml_file(url, response_format, *args, **kwargs): except HTTPError as err: if err.code == 404: - gscript.fatal( + gs.fatal( _( "The download of the modules.xml file " "from the server was not successful. " @@ -147,7 +147,7 @@ def download_modules_xml_file(url, response_format, *args, **kwargs): response_format=response_format, ) except URLError: - gscript.fatal( + gs.fatal( _( "Download file from <{url}>, " "failed. Check internet connection.".format( @@ -176,7 +176,7 @@ def find_addon_name(addons): if grass_version != "unknown": major, minor, patch = grass_version.split(".") else: - gscript.fatal(_("Unable to get GRASS GIS version.")) + gs.fatal(_("Unable to get GRASS GIS version.")) url = "https://grass.osgeo.org/addons/grass{major}/modules.xml".format( major=major, ) @@ -196,7 +196,7 @@ def find_addon_name(addons): found = True break if not found: - gscript.warning( + gs.warning( _( "The <{}> addon cannot be reinstalled. " "Addon wasn't found among the official " @@ -209,36 +209,34 @@ def find_addon_name(addons): def main(): remove = options["operation"] == "remove" if remove or flags["f"]: - extensions = gscript.read_command( - "g.extension", quiet=True, flags="a" - ).splitlines() + extensions = gs.read_command("g.extension", quiet=True, flags="a").splitlines() else: extensions = get_extensions() if not extensions: if remove: - gscript.info(_("No extension found. Nothing to remove.")) + gs.info(_("No extension found. Nothing to remove.")) else: - gscript.info( + gs.info( _("Nothing to rebuild. Rebuilding process can be forced with -f flag.") ) return 0 if remove and not flags["f"]: - gscript.message(_("List of extensions to be removed:")) + gs.message(_("List of extensions to be removed:")) print(os.linesep.join(extensions)) - gscript.message( + gs.message( _("You must use the force flag (-f) to actually remove them. Exiting.") ) return 0 for ext in find_addon_name(addons=extensions): - gscript.message("-" * 60) + gs.message("-" * 60) if remove: - gscript.message(_("Removing extension <%s>...") % ext) + gs.message(_("Removing extension <%s>...") % ext) else: - gscript.message(_("Reinstalling extension <%s>...") % ext) - gscript.message("-" * 60) + gs.message(_("Reinstalling extension <%s>...") % ext) + gs.message("-" * 60) if remove: operation = "remove" operation_flags = "f" @@ -246,15 +244,15 @@ def main(): operation = "add" operation_flags = "" try: - gscript.run_command( + gs.run_command( "g.extension", flags=operation_flags, extension=ext, operation=operation ) except CalledModuleError: - gscript.error(_("Unable to process extension:%s") % ext) + gs.error(_("Unable to process extension:%s") % ext) return 0 if __name__ == "__main__": - options, flags = gscript.parser() + options, flags = gs.parser() sys.exit(main()) diff --git a/scripts/i.colors.enhance/i.colors.enhance.py b/scripts/i.colors.enhance/i.colors.enhance.py index c64406a51e2..68444007bd6 100755 --- a/scripts/i.colors.enhance/i.colors.enhance.py +++ b/scripts/i.colors.enhance/i.colors.enhance.py @@ -70,7 +70,7 @@ import sys import multiprocessing as mp -import grass.script as gscript +import grass.script as gs def get_percentile(map, percentiles): @@ -79,7 +79,7 @@ def get_percentile(map, percentiles): val2 = percentiles[1] values = "%s,%s" % (val1, val2) - s = gscript.read_command("r.quantile", input=map, percentiles=values, quiet=True) + s = gs.read_command("r.quantile", input=map, percentiles=values, quiet=True) val_str1 = s.splitlines()[0].split(":")[2] val_str2 = s.splitlines()[1].split(":")[2] @@ -97,7 +97,7 @@ def get_percentile_mp(map, percentiles, conn): output_pipe, input_pipe = conn input_pipe.close() result = get_percentile(map, percentiles) - gscript.debug("child (%s) (%.1f, %.1f)" % (map, result[0], result[1])) + gs.debug("child (%s) (%.1f, %.1f)" % (map, result[0], result[1])) output_pipe.send(result) output_pipe.close() @@ -106,7 +106,7 @@ def set_colors(map, v0, v1): rules = "".join( ["0% black\n", "%f black\n" % v0, "%f white\n" % v1, "100% white\n"] ) - gscript.write_command("r.colors", map=map, rules="-", stdin=rules, quiet=True) + gs.write_command("r.colors", map=map, rules="-", stdin=rules, quiet=True) def main(): @@ -124,29 +124,29 @@ def main(): check = True for m in [red, green, blue]: - ex = gscript.find_file(m) + ex = gs.find_file(m) if ex["name"] == "": check = False - gscript.warning("Raster map <{}> not found ".format(m)) + gs.warning("Raster map <{}> not found ".format(m)) if not check: - gscript.fatal("At least one of the input raster map was not found") + gs.fatal("At least one of the input raster map was not found") # 90 or 98? MAX value controls brightness # think of percent (0-100), must be positive or 0 # must be more than "2" ? if full: for i in [red, green, blue]: - gscript.run_command("r.colors", map=i, color="grey", quiet=True) + gs.run_command("r.colors", map=i, color="grey", quiet=True) sys.exit(0) if reset: for i in [red, green, blue]: - gscript.run_command("r.colors", map=i, color="grey255", quiet=True) + gs.run_command("r.colors", map=i, color="grey255", quiet=True) sys.exit(0) if not preserve: if do_mp: - gscript.message(_("Processing...")) + gs.message(_("Processing...")) # set up jobs and launch them proc = {} conn = {} @@ -161,22 +161,22 @@ def main(): ), ) proc[i].start() - gscript.percent(1, 2, 1) + gs.percent(1, 2, 1) # collect results and wait for jobs to finish for i in [red, green, blue]: output_pipe, input_pipe = conn[i] (v0, v1) = input_pipe.recv() - gscript.debug("parent (%s) (%.1f, %.1f)" % (i, v0, v1)) + gs.debug("parent (%s) (%.1f, %.1f)" % (i, v0, v1)) input_pipe.close() proc[i].join() set_colors(i, v0, v1) - gscript.percent(1, 1, 1) + gs.percent(1, 1, 1) else: for i in [red, green, blue]: - gscript.message(_("Processing...")) + gs.message(_("Processing...")) (v0, v1) = get_percentile(i, ["2", brightness]) - gscript.debug("<%s>: min=%f max=%f" % (i, v0, v1)) + gs.debug("<%s>: min=%f max=%f" % (i, v0, v1)) set_colors(i, v0, v1) else: @@ -184,7 +184,7 @@ def main(): all_min = 999999 if do_mp: - gscript.message(_("Processing...")) + gs.message(_("Processing...")) # set up jobs and launch jobs proc = {} conn = {} @@ -199,37 +199,37 @@ def main(): ), ) proc[i].start() - gscript.percent(1, 2, 1) + gs.percent(1, 2, 1) # collect results and wait for jobs to finish for i in [red, green, blue]: output_pipe, input_pipe = conn[i] (v0, v1) = input_pipe.recv() - gscript.debug("parent (%s) (%.1f, %.1f)" % (i, v0, v1)) + gs.debug("parent (%s) (%.1f, %.1f)" % (i, v0, v1)) input_pipe.close() proc[i].join() all_min = min(all_min, v0) all_max = max(all_max, v1) - gscript.percent(1, 1, 1) + gs.percent(1, 1, 1) else: for i in [red, green, blue]: - gscript.message(_("Processing...")) + gs.message(_("Processing...")) (v0, v1) = get_percentile(i, ["2", brightness]) - gscript.debug("<%s>: min=%f max=%f" % (i, v0, v1)) + gs.debug("<%s>: min=%f max=%f" % (i, v0, v1)) all_min = min(all_min, v0) all_max = max(all_max, v1) - gscript.debug("all_min=%f all_max=%f" % (all_min, all_max)) + gs.debug("all_min=%f all_max=%f" % (all_min, all_max)) for i in [red, green, blue]: set_colors(i, all_min, all_max) # write cmd history: - mapset = gscript.gisenv()["MAPSET"] + mapset = gs.gisenv()["MAPSET"] for i in [red, green, blue]: - if gscript.find_file(i)["mapset"] == mapset: - gscript.raster_history(i) + if gs.find_file(i)["mapset"] == mapset: + gs.raster_history(i) if __name__ == "__main__": - options, flags = gscript.parser() + options, flags = gs.parser() main() diff --git a/scripts/i.image.mosaic/i.image.mosaic.py b/scripts/i.image.mosaic/i.image.mosaic.py index a11edc14146..df194c49c8f 100755 --- a/scripts/i.image.mosaic/i.image.mosaic.py +++ b/scripts/i.image.mosaic/i.image.mosaic.py @@ -34,23 +34,23 @@ # %option G_OPT_R_OUTPUT # %end -import grass.script as gscript +import grass.script as gs def copy_colors(fh, map, offset): - p = gscript.pipe_command("r.colors.out", map=map) + p = gs.pipe_command("r.colors.out", map=map) for line in p.stdout: - f = gscript.decode(line).rstrip("\r\n").split(" ") + f = gs.decode(line).rstrip("\r\n").split(" ") if offset: if f[0] in {"nv", "default"}: continue f[0] = str(float(f[0]) + offset) - fh.write(gscript.encode(" ".join(f) + "\n")) + fh.write(gs.encode(" ".join(f) + "\n")) p.wait() def get_limit(map): - return gscript.raster_info(map)["max"] + return gs.raster_info(map)["max"] def make_expression(i, count): @@ -67,7 +67,7 @@ def main(): count = len(images) msg = _("Do not forget to set region properly to cover all images.") - gscript.warning(msg) + gs.warning(msg) offset = 0 offsets = [] @@ -78,24 +78,24 @@ def main(): parms["offset%d" % (n + 1)] = offset offset += get_limit(img) + 1 - gscript.message(_("Mosaicing %d images...") % count) + gs.message(_("Mosaicing %d images...") % count) - gscript.mapcalc("$output = " + make_expression(1, count), output=output, **parms) + gs.mapcalc("$output = " + make_expression(1, count), output=output, **parms) # modify the color table: - p = gscript.feed_command("r.colors", map=output, rules="-") + p = gs.feed_command("r.colors", map=output, rules="-") for img, offset in zip(images, offsets): print(img, offset) copy_colors(p.stdin, img, offset) p.stdin.close() p.wait() - gscript.message(_("Done. Raster map <%s> created.") % output) + gs.message(_("Done. Raster map <%s> created.") % output) # write cmd history: - gscript.raster_history(output) + gs.raster_history(output) if __name__ == "__main__": - options, flags = gscript.parser() + options, flags = gs.parser() main() diff --git a/scripts/i.in.spotvgt/i.in.spotvgt.py b/scripts/i.in.spotvgt/i.in.spotvgt.py index 61be75f8d49..cd744d4c252 100755 --- a/scripts/i.in.spotvgt/i.in.spotvgt.py +++ b/scripts/i.in.spotvgt/i.in.spotvgt.py @@ -50,7 +50,7 @@ import os import atexit import string -import grass.script as gscript +import grass.script as gs from grass.exceptions import CalledModuleError @@ -112,8 +112,8 @@ def create_VRT_file(projfile, vrtfile, infile): def cleanup(): # clean up the mess - gscript.try_remove(vrtfile) - gscript.try_remove(tmpfile) + gs.try_remove(vrtfile) + gs.try_remove(tmpfile) def main(): @@ -124,37 +124,37 @@ def main(): also = flags["a"] # check for gdalinfo (just to check if installation is complete) - if not gscript.find_program("gdalinfo", "--help"): - gscript.fatal( + if not gs.find_program("gdalinfo", "--help"): + gs.fatal( _("'gdalinfo' not found, install GDAL tools first (http://www.gdal.org)") ) pid = str(os.getpid()) - tmpfile = gscript.tempfile() + tmpfile = gs.tempfile() # let's go spotdir = os.path.dirname(infile) - spotname = gscript.basename(infile, "hdf") + spotname = gs.basename(infile, "hdf") if rast: name = rast else: name = spotname - if not gscript.overwrite() and gscript.find_file(name)["file"]: - gscript.fatal(_("<%s> already exists. Aborting.") % name) + if not gs.overwrite() and gs.find_file(name)["file"]: + gs.fatal(_("<%s> already exists. Aborting.") % name) # still a ZIP file? (is this portable?? see the r.in.srtm script for # ideas) if infile.lower().endswith(".zip"): - gscript.fatal(_("Please extract %s before import.") % infile) + gs.fatal(_("Please extract %s before import.") % infile) try: - p = gscript.Popen(["file", "-ib", infile], stdout=gscript.PIPE) + p = gs.Popen(["file", "-ib", infile], stdout=gs.PIPE) s = p.communicate()[0] if s == "application/x-zip": - gscript.fatal(_("Please extract %s before import.") % infile) + gs.fatal(_("Please extract %s before import.") % infile) except Exception: pass @@ -164,17 +164,17 @@ def main(): vrtfile = tmpfile + ".vrt" # first process the NDVI: - gscript.try_remove(vrtfile) + gs.try_remove(vrtfile) create_VRT_file(projfile, vrtfile, infile) # let's import the NDVI map... - gscript.message(_("Importing SPOT VGT NDVI map...")) + gs.message(_("Importing SPOT VGT NDVI map...")) try: - gscript.run_command("r.in.gdal", input=vrtfile, output=name) + gs.run_command("r.in.gdal", input=vrtfile, output=name) except CalledModuleError: - gscript.fatal(_("An error occurred. Stop.")) + gs.fatal(_("An error occurred. Stop.")) - gscript.message(_("Imported SPOT VEGETATION NDVI map <%s>.") % name) + gs.message(_("Imported SPOT VEGETATION NDVI map <%s>.") % name) ################# # http://www.vgt.vito.be/faq/FAQS/faq19.html @@ -187,21 +187,21 @@ def main(): # clone current region # switch to a temporary region - gscript.use_temp_region() + gs.use_temp_region() - gscript.run_command("g.region", raster=name, quiet=True) + gs.run_command("g.region", raster=name, quiet=True) - gscript.message(_("Remapping digital numbers to NDVI...")) + gs.message(_("Remapping digital numbers to NDVI...")) tmpname = "%s_%s" % (name, pid) - gscript.mapcalc("$tmpname = 0.004 * $name - 0.1", tmpname=tmpname, name=name) - gscript.run_command("g.remove", type="raster", name=name, quiet=True, flags="f") - gscript.run_command("g.rename", raster=(tmpname, name), quiet=True) + gs.mapcalc("$tmpname = 0.004 * $name - 0.1", tmpname=tmpname, name=name) + gs.run_command("g.remove", type="raster", name=name, quiet=True, flags="f") + gs.run_command("g.rename", raster=(tmpname, name), quiet=True) # write cmd history: - gscript.raster_history(name) + gs.raster_history(name) # apply color table: - gscript.run_command("r.colors", map=name, color="ndvi", quiet=True) + gs.run_command("r.colors", map=name, color="ndvi", quiet=True) ########################## # second, optionally process the SM quality map: @@ -232,8 +232,8 @@ def main(): # A good map threshold: >= 248 if also: - gscript.message(_("Importing SPOT VGT NDVI quality map...")) - gscript.try_remove(vrtfile) + gs.message(_("Importing SPOT VGT NDVI quality map...")) + gs.try_remove(vrtfile) qname = spotname.replace("NDV", "SM") qfile = os.path.join(spotdir, qname) create_VRT_file(projfile, vrtfile, qfile) @@ -241,9 +241,9 @@ def main(): # let's import the SM quality map... smfile = name + ".sm" try: - gscript.run_command("r.in.gdal", input=vrtfile, output=smfile) + gs.run_command("r.in.gdal", input=vrtfile, output=smfile) except CalledModuleError: - gscript.fatal(_("An error occurred. Stop.")) + gs.fatal(_("An error occurred. Stop.")) # some of the possible values: rules = [ @@ -262,38 +262,38 @@ def main(): "252 green", ] ] - gscript.write_command("r.colors", map=smfile, rules="-", stdin=rules) + gs.write_command("r.colors", map=smfile, rules="-", stdin=rules) - gscript.message(_("Imported SPOT VEGETATION SM quality map <%s>.") % smfile) - gscript.message( + gs.message(_("Imported SPOT VEGETATION SM quality map <%s>.") % smfile) + gs.message( _( "Note: A snow map can be extracted by category " "252 (d.rast %s cat=252)" ) % smfile ) - gscript.message("") - gscript.message(_("Filtering NDVI map by Status Map quality layer...")) + gs.message("") + gs.message(_("Filtering NDVI map by Status Map quality layer...")) filtfile = "%s_filt" % name - gscript.mapcalc( + gs.mapcalc( "$filtfile = if($smfile % 4 == 3 || " "($smfile / 16) % 16 == 0, null(), $name)", filtfile=filtfile, smfile=smfile, name=name, ) - gscript.run_command("r.colors", map=filtfile, color="ndvi", quiet=True) - gscript.message(_("Filtered SPOT VEGETATION NDVI map <%s>.") % filtfile) + gs.run_command("r.colors", map=filtfile, color="ndvi", quiet=True) + gs.message(_("Filtered SPOT VEGETATION NDVI map <%s>.") % filtfile) # write cmd history: - gscript.raster_history(smfile) - gscript.raster_history(filtfile) + gs.raster_history(smfile) + gs.raster_history(filtfile) - gscript.message(_("Done.")) + gs.message(_("Done.")) if __name__ == "__main__": - options, flags = gscript.parser() + options, flags = gs.parser() atexit.register(cleanup) main() diff --git a/scripts/i.pansharpen/i.pansharpen.py b/scripts/i.pansharpen/i.pansharpen.py index d0b06e53727..ff0146d7708 100755 --- a/scripts/i.pansharpen/i.pansharpen.py +++ b/scripts/i.pansharpen/i.pansharpen.py @@ -101,12 +101,12 @@ except ImportError: hasNumPy = False -import grass.script as grass +import grass.script as gs def main(): if not hasNumPy: - grass.fatal(_("Required dependency NumPy not found. Exiting.")) + gs.fatal(_("Required dependency NumPy not found. Exiting.")) sharpen = options["method"] # sharpening algorithm ms1_orig = options["blue"] # blue channel @@ -122,17 +122,17 @@ def main(): # Checking bit depth bits = float(bits) if bits < 2 or bits > 30: - grass.warning(_("Bit depth is outside acceptable range")) + gs.warning(_("Bit depth is outside acceptable range")) return - outb = grass.core.find_file("%s_blue" % out) - outg = grass.core.find_file("%s_green" % out) - outr = grass.core.find_file("%s_red" % out) + outb = gs.core.find_file("%s_blue" % out) + outg = gs.core.find_file("%s_green" % out) + outr = gs.core.find_file("%s_red" % out) if ( outb["name"] != "" or outg["name"] != "" or outr["name"] != "" - ) and not grass.overwrite(): - grass.warning( + ) and not gs.overwrite(): + gs.warning( _( "Maps with selected output prefix names already exist." " Delete them or use overwrite flag" @@ -150,28 +150,28 @@ def main(): if not rescale: if bits == 8: - grass.message(_("Using 8bit image channels")) + gs.message(_("Using 8bit image channels")) if sproc: # serial processing - grass.run_command( + gs.run_command( "g.copy", raster="%s,%s" % (ms1_orig, ms1), quiet=True, overwrite=True, ) - grass.run_command( + gs.run_command( "g.copy", raster="%s,%s" % (ms2_orig, ms2), quiet=True, overwrite=True, ) - grass.run_command( + gs.run_command( "g.copy", raster="%s,%s" % (ms3_orig, ms3), quiet=True, overwrite=True, ) - grass.run_command( + gs.run_command( "g.copy", raster="%s,%s" % (pan_orig, pan), quiet=True, @@ -179,25 +179,25 @@ def main(): ) else: # parallel processing - pb = grass.start_command( + pb = gs.start_command( "g.copy", raster="%s,%s" % (ms1_orig, ms1), quiet=True, overwrite=True, ) - pg = grass.start_command( + pg = gs.start_command( "g.copy", raster="%s,%s" % (ms2_orig, ms2), quiet=True, overwrite=True, ) - pr = grass.start_command( + pr = gs.start_command( "g.copy", raster="%s,%s" % (ms3_orig, ms3), quiet=True, overwrite=True, ) - pp = grass.start_command( + pp = gs.start_command( "g.copy", raster="%s,%s" % (pan_orig, pan), quiet=True, @@ -210,11 +210,11 @@ def main(): pp.wait() else: - grass.message(_("Converting image channels to 8bit for processing")) + gs.message(_("Converting image channels to 8bit for processing")) maxval = pow(2, bits) - 1 if sproc: # serial processing - grass.run_command( + gs.run_command( "r.rescale", input=ms1_orig, from_="0,%f" % maxval, @@ -223,7 +223,7 @@ def main(): quiet=True, overwrite=True, ) - grass.run_command( + gs.run_command( "r.rescale", input=ms2_orig, from_="0,%f" % maxval, @@ -232,7 +232,7 @@ def main(): quiet=True, overwrite=True, ) - grass.run_command( + gs.run_command( "r.rescale", input=ms3_orig, from_="0,%f" % maxval, @@ -241,7 +241,7 @@ def main(): quiet=True, overwrite=True, ) - grass.run_command( + gs.run_command( "r.rescale", input=pan_orig, from_="0,%f" % maxval, @@ -253,7 +253,7 @@ def main(): else: # parallel processing - pb = grass.start_command( + pb = gs.start_command( "r.rescale", input=ms1_orig, from_="0,%f" % maxval, @@ -262,7 +262,7 @@ def main(): quiet=True, overwrite=True, ) - pg = grass.start_command( + pg = gs.start_command( "r.rescale", input=ms2_orig, from_="0,%f" % maxval, @@ -271,7 +271,7 @@ def main(): quiet=True, overwrite=True, ) - pr = grass.start_command( + pr = gs.start_command( "r.rescale", input=ms3_orig, from_="0,%f" % maxval, @@ -280,7 +280,7 @@ def main(): quiet=True, overwrite=True, ) - pp = grass.start_command( + pp = gs.start_command( "r.rescale", input=pan_orig, from_="0,%f" % maxval, @@ -296,21 +296,21 @@ def main(): pp.wait() else: - grass.message(_("Rescaling image channels to 8bit for processing")) + gs.message(_("Rescaling image channels to 8bit for processing")) - min_ms1 = int(grass.raster_info(ms1_orig)["min"]) - max_ms1 = int(grass.raster_info(ms1_orig)["max"]) - min_ms2 = int(grass.raster_info(ms2_orig)["min"]) - max_ms2 = int(grass.raster_info(ms2_orig)["max"]) - min_ms3 = int(grass.raster_info(ms3_orig)["min"]) - max_ms3 = int(grass.raster_info(ms3_orig)["max"]) - min_pan = int(grass.raster_info(pan_orig)["min"]) - max_pan = int(grass.raster_info(pan_orig)["max"]) + min_ms1 = int(gs.raster_info(ms1_orig)["min"]) + max_ms1 = int(gs.raster_info(ms1_orig)["max"]) + min_ms2 = int(gs.raster_info(ms2_orig)["min"]) + max_ms2 = int(gs.raster_info(ms2_orig)["max"]) + min_ms3 = int(gs.raster_info(ms3_orig)["min"]) + max_ms3 = int(gs.raster_info(ms3_orig)["max"]) + min_pan = int(gs.raster_info(pan_orig)["min"]) + max_pan = int(gs.raster_info(pan_orig)["max"]) maxval = pow(2, bits) - 1 if sproc: # serial processing - grass.run_command( + gs.run_command( "r.rescale", input=ms1_orig, from_="%f,%f" % (min_ms1, max_ms1), @@ -319,7 +319,7 @@ def main(): quiet=True, overwrite=True, ) - grass.run_command( + gs.run_command( "r.rescale", input=ms2_orig, from_="%f,%f" % (min_ms2, max_ms2), @@ -328,7 +328,7 @@ def main(): quiet=True, overwrite=True, ) - grass.run_command( + gs.run_command( "r.rescale", input=ms3_orig, from_="%f,%f" % (min_ms3, max_ms3), @@ -337,7 +337,7 @@ def main(): quiet=True, overwrite=True, ) - grass.run_command( + gs.run_command( "r.rescale", input=pan_orig, from_="%f,%f" % (min_pan, max_pan), @@ -349,7 +349,7 @@ def main(): else: # parallel processing - pb = grass.start_command( + pb = gs.start_command( "r.rescale", input=ms1_orig, from_="%f,%f" % (min_ms1, max_ms1), @@ -358,7 +358,7 @@ def main(): quiet=True, overwrite=True, ) - pg = grass.start_command( + pg = gs.start_command( "r.rescale", input=ms2_orig, from_="%f,%f" % (min_ms2, max_ms2), @@ -367,7 +367,7 @@ def main(): quiet=True, overwrite=True, ) - pr = grass.start_command( + pr = gs.start_command( "r.rescale", input=ms3_orig, from_="%f,%f" % (min_ms3, max_ms3), @@ -376,7 +376,7 @@ def main(): quiet=True, overwrite=True, ) - pp = grass.start_command( + pp = gs.start_command( "r.rescale", input=pan_orig, from_="%f,%f" % (min_pan, max_pan), @@ -392,17 +392,17 @@ def main(): pp.wait() # get PAN resolution: - kv = grass.raster_info(map=pan) + kv = gs.raster_info(map=pan) nsres = kv["nsres"] ewres = kv["ewres"] panres = (nsres + ewres) / 2 # clone current region - grass.use_temp_region() - grass.run_command("g.region", res=panres, align=pan) + gs.use_temp_region() + gs.run_command("g.region", res=panres, align=pan) # Select sharpening method - grass.message(_("Performing pan sharpening with hi res pan image: %f" % panres)) + gs.message(_("Performing pan sharpening with hi res pan image: %f" % panres)) if sharpen == "brovey": brovey(pan, ms1, ms2, ms3, out, pid, sproc) elif sharpen == "ihs": @@ -411,51 +411,51 @@ def main(): pca(pan, ms1, ms2, ms3, out, pid, sproc) # Could add other sharpening algorithms here, e.g. wavelet transformation - grass.message(_("Assigning grey equalized color tables to output images...")) + gs.message(_("Assigning grey equalized color tables to output images...")) # equalized grey scales give best contrast - grass.message(_("setting pan-sharpened channels to equalized grey scale")) + gs.message(_("setting pan-sharpened channels to equalized grey scale")) for ch in ["red", "green", "blue"]: - grass.run_command( + gs.run_command( "r.colors", quiet=True, map="%s_%s" % (out, ch), flags="e", color="grey" ) # Landsat too blue-ish because panchromatic band less sensitive to blue # light, so output blue channed can be modified if bladjust: - grass.message(_("Adjusting blue channel color table...")) + gs.message(_("Adjusting blue channel color table...")) blue_colors = ["0 0 0 0\n5% 0 0 0\n67% 255 255 255\n100% 255 255 255"] # these previous colors are way too blue for landsat # blue_colors = ['0 0 0 0\n10% 0 0 0\n20% 200 200 200\n40% 230 230 230\n67% # 255 255 255\n100% 255 255 255'] - bc = grass.feed_command("r.colors", quiet=True, map="%s_blue" % out, rules="-") - bc.stdin.write(grass.encode("\n".join(blue_colors))) + bc = gs.feed_command("r.colors", quiet=True, map="%s_blue" % out, rules="-") + bc.stdin.write(gs.encode("\n".join(blue_colors))) bc.stdin.close() # output notice - grass.verbose(_("The following pan-sharpened output maps have been generated:")) + gs.verbose(_("The following pan-sharpened output maps have been generated:")) for ch in ["red", "green", "blue"]: - grass.verbose(_("%s_%s") % (out, ch)) + gs.verbose(_("%s_%s") % (out, ch)) - grass.verbose(_("To visualize output, run: g.region -p raster=%s_red" % out)) - grass.verbose(_("d.rgb r=%s_red g=%s_green b=%s_blue" % (out, out, out))) - grass.verbose( + gs.verbose(_("To visualize output, run: g.region -p raster=%s_red" % out)) + gs.verbose(_("d.rgb r=%s_red g=%s_green b=%s_blue" % (out, out, out))) + gs.verbose( _("If desired, combine channels into a single RGB map with 'r.composite'.") ) - grass.verbose(_("Channel colors can be rebalanced using i.colors.enhance.")) + gs.verbose(_("Channel colors can be rebalanced using i.colors.enhance.")) # write cmd history: for ch in ["red", "green", "blue"]: - grass.raster_history("%s_%s" % (out, ch)) + gs.raster_history("%s_%s" % (out, ch)) # create a group with the three outputs - # grass.run_command('i.group', group=out, + # gs.run_command('i.group', group=out, # input="{n}_red,{n}_blue,{n}_green".format(n=out)) # Cleanup - grass.message(_("cleaning up temp files")) + gs.message(_("cleaning up temp files")) try: - grass.run_command( + gs.run_command( "g.remove", flags="f", type="raster", pattern="tmp%s*" % pid, quiet=True ) except: @@ -463,10 +463,10 @@ def main(): def brovey(pan, ms1, ms2, ms3, out, pid, sproc): - grass.verbose(_("Using Brovey algorithm")) + gs.verbose(_("Using Brovey algorithm")) # pan/intensity histogram matching using linear regression - grass.message(_("Pan channel/intensity histogram matching using linear regression")) + gs.message(_("Pan channel/intensity histogram matching using linear regression")) outname = "tmp%s_pan1" % pid panmatch1 = matchhist(pan, ms1, outname) @@ -481,7 +481,7 @@ def brovey(pan, ms1, ms2, ms3, out, pid, sproc): outb = "%s_blue" % out # calculate brovey transformation - grass.message(_("Calculating Brovey transformation...")) + gs.message(_("Calculating Brovey transformation...")) if sproc: # serial processing @@ -489,7 +489,7 @@ def brovey(pan, ms1, ms2, ms3, out, pid, sproc): "$outr" = 1 * round("$ms3" * "$panmatch3" / k) "$outg" = 1 * round("$ms2" * "$panmatch2" / k) "$outb" = 1 * round("$ms1" * "$panmatch1" / k)""" - grass.mapcalc( + gs.mapcalc( e, outr=outr, outg=outg, @@ -504,17 +504,17 @@ def brovey(pan, ms1, ms2, ms3, out, pid, sproc): ) else: # parallel processing - pb = grass.mapcalc_start( + pb = gs.mapcalc_start( "%s_blue = 1 * round((%s * %s) / (%s + %s + %s))" % (out, ms1, panmatch1, ms1, ms2, ms3), overwrite=True, ) - pg = grass.mapcalc_start( + pg = gs.mapcalc_start( "%s_green = 1 * round((%s * %s) / (%s + %s + %s))" % (out, ms2, panmatch2, ms1, ms2, ms3), overwrite=True, ) - pr = grass.mapcalc_start( + pr = gs.mapcalc_start( "%s_red = 1 * round((%s * %s) / (%s + %s + %s))" % (out, ms3, panmatch3, ms1, ms2, ms3), overwrite=True, @@ -528,7 +528,7 @@ def brovey(pan, ms1, ms2, ms3, out, pid, sproc): # Cleanup try: - grass.run_command( + gs.run_command( "g.remove", flags="f", quiet=True, @@ -540,10 +540,10 @@ def brovey(pan, ms1, ms2, ms3, out, pid, sproc): def ihs(pan, ms1, ms2, ms3, out, pid, sproc): - grass.verbose(_("Using IHS<->RGB algorithm")) + gs.verbose(_("Using IHS<->RGB algorithm")) # transform RGB channels into IHS color space - grass.message(_("Transforming to IHS color space...")) - grass.run_command( + gs.message(_("Transforming to IHS color space...")) + gs.run_command( "i.rgb.his", overwrite=True, red=ms3, @@ -560,8 +560,8 @@ def ihs(pan, ms1, ms2, ms3, out, pid, sproc): panmatch = matchhist(pan, target, outname) # substitute pan for intensity channel and transform back to RGB color space - grass.message(_("Transforming back to RGB color space and sharpening...")) - grass.run_command( + gs.message(_("Transforming back to RGB color space and sharpening...")) + gs.run_command( "i.his.rgb", overwrite=True, hue="tmp%s_hue" % pid, @@ -574,19 +574,17 @@ def ihs(pan, ms1, ms2, ms3, out, pid, sproc): # Cleanup try: - grass.run_command( - "g.remove", flags="f", quiet=True, type="raster", name=panmatch - ) + gs.run_command("g.remove", flags="f", quiet=True, type="raster", name=panmatch) except: pass def pca(pan, ms1, ms2, ms3, out, pid, sproc): - grass.verbose(_("Using PCA/inverse PCA algorithm")) - grass.message(_("Creating PCA images and calculating eigenvectors...")) + gs.verbose(_("Using PCA/inverse PCA algorithm")) + gs.message(_("Creating PCA images and calculating eigenvectors...")) # initial PCA with RGB channels - pca_out = grass.read_command( + pca_out = gs.read_command( "i.pca", quiet=True, rescale="0,0", @@ -594,7 +592,7 @@ def pca(pan, ms1, ms2, ms3, out, pid, sproc): output="tmp%s.pca" % pid, ) if len(pca_out) < 1: - grass.fatal(_("Input has no data. Check region settings.")) + gs.fatal(_("Input has no data. Check region settings.")) b1evect = [] b2evect = [] @@ -627,17 +625,17 @@ def pca(pan, ms1, ms2, ms3, out, pid, sproc): outname = "tmp%s_pan3" % pid panmatch3 = matchhist(pan, ms3, outname) - grass.message(_("Performing inverse PCA ...")) + gs.message(_("Performing inverse PCA ...")) # Get mean value of each channel - stats1 = grass.parse_command( - "r.univar", map=ms1, flags="g", parse=(grass.parse_key_val, {"sep": "="}) + stats1 = gs.parse_command( + "r.univar", map=ms1, flags="g", parse=(gs.parse_key_val, {"sep": "="}) ) - stats2 = grass.parse_command( - "r.univar", map=ms2, flags="g", parse=(grass.parse_key_val, {"sep": "="}) + stats2 = gs.parse_command( + "r.univar", map=ms2, flags="g", parse=(gs.parse_key_val, {"sep": "="}) ) - stats3 = grass.parse_command( - "r.univar", map=ms3, flags="g", parse=(grass.parse_key_val, {"sep": "="}) + stats3 = gs.parse_command( + "r.univar", map=ms3, flags="g", parse=(gs.parse_key_val, {"sep": "="}) ) b1mean = float(stats1["mean"]) @@ -656,7 +654,7 @@ def pca(pan, ms1, ms2, ms3, out, pid, sproc): cmd = "\n".join([cmd1, cmd2, cmd3]) - grass.mapcalc( + gs.mapcalc( cmd, outb=outb, outg=outg, @@ -682,19 +680,19 @@ def pca(pan, ms1, ms2, ms3, out, pid, sproc): ) else: # parallel processing - pb = grass.mapcalc_start( + pb = gs.mapcalc_start( "%s_blue = 1 * round((%s * %f) + (%s * %f) + (%s * %f) + %f)" % (out, panmatch1, b1evect1, pca2, b1evect2, pca3, b1evect3, b1mean), overwrite=True, ) - pg = grass.mapcalc_start( + pg = gs.mapcalc_start( "%s_green = 1 * round((%s * %f) + (%s * %f) + (%s * %f) + %f)" % (out, panmatch2, b2evect1, pca2, b2evect2, pca3, b2evect3, b2mean), overwrite=True, ) - pr = grass.mapcalc_start( + pr = gs.mapcalc_start( "%s_red = 1 * round((%s * %f) + (%s * %f) + (%s * %f) + %f)" % (out, panmatch3, b3evect1, pca2, b3evect2, pca3, b3evect3, b3mean), overwrite=True, @@ -707,7 +705,7 @@ def pca(pan, ms1, ms2, ms3, out, pid, sproc): pass # Cleanup - grass.run_command( + gs.run_command( "g.remove", flags="f", quiet=True, @@ -718,7 +716,7 @@ def pca(pan, ms1, ms2, ms3, out, pid, sproc): def matchhist(original, target, matched): # pan/intensity histogram matching using numpy arrays - grass.message(_("Histogram matching...")) + gs.message(_("Histogram matching...")) # input images original = original.split("@")[0] @@ -730,8 +728,8 @@ def matchhist(original, target, matched): for img in images: # calculate number of cells for each grey value for for each image - stats_out = grass.pipe_command("r.stats", flags="cin", input=img, sep=":") - stats = grass.decode(stats_out.communicate()[0]).split("\n")[:-1] + stats_out = gs.pipe_command("r.stats", flags="cin", input=img, sep=":") + stats = gs.decode(stats_out.communicate()[0]).split("\n")[:-1] stats_dict = dict(s.split(":", 1) for s in stats) total_cells = 0 # total non-null cells for j in stats_dict: @@ -740,7 +738,7 @@ def matchhist(original, target, matched): total_cells += stats_dict[j] if total_cells < 1: - grass.fatal(_("Input has no data. Check region settings.")) + gs.fatal(_("Input has no data. Check region settings.")) # Make a 2x256 structured array for each image with a # cumulative distribution function (CDF) for each grey value. @@ -767,7 +765,7 @@ def matchhist(original, target, matched): arrays[img][n] = (n, cdf) # open file for reclass rules - outfile = open(grass.tempfile(), "w") + outfile = open(gs.tempfile(), "w") for i in arrays[original]: # for each grey value and corresponding cdf value in original, find the @@ -794,23 +792,21 @@ def matchhist(original, target, matched): outfile.close() # create reclass of target from reclass rules file - result = grass.core.find_file(matched, element="cell") + result = gs.core.find_file(matched, element="cell") if result["fullname"]: - grass.run_command( - "g.remove", flags="f", quiet=True, type="raster", name=matched - ) - grass.run_command("r.reclass", input=original, out=matched, rules=outfile.name) + gs.run_command("g.remove", flags="f", quiet=True, type="raster", name=matched) + gs.run_command("r.reclass", input=original, out=matched, rules=outfile.name) else: - grass.run_command("r.reclass", input=original, out=matched, rules=outfile.name) + gs.run_command("r.reclass", input=original, out=matched, rules=outfile.name) # Cleanup # remove the rules file - grass.try_remove(outfile.name) + gs.try_remove(outfile.name) # return reclass of target with histogram that matches original return matched if __name__ == "__main__": - options, flags = grass.parser() + options, flags = gs.parser() main() diff --git a/scripts/i.tasscap/i.tasscap.py b/scripts/i.tasscap/i.tasscap.py index c6fb6c3711b..4c68c234c73 100755 --- a/scripts/i.tasscap/i.tasscap.py +++ b/scripts/i.tasscap/i.tasscap.py @@ -82,7 +82,7 @@ # % options: landsat4_tm,landsat5_tm,landsat7_etm,landsat8_oli,modis,sentinel2,worldview2 # %end -import grass.script as grass +import grass.script as gs # weights for 6 Landsat bands: TM4, TM5, TM7, OLI @@ -236,7 +236,7 @@ def calc1bands6(out, bands, k1, k2, k3, k4, k5, k6, k0=0): "$out = $k1 * $in1band + $k2 * $in2band + $k3 * $in3band + " "$k4 * $in4band + $k5 * $in5band + $k6 * $in6band + $k0" ) - grass.mapcalc( + gs.mapcalc( equation, out=out, k1=k1, k2=k2, k3=k3, k4=k4, k5=k5, k6=k6, k0=k0, **bands ) @@ -250,7 +250,7 @@ def calc1bands7(out, bands, k1, k2, k3, k4, k5, k6, k7): "$k4 * $in4band + $k5 * $in5band + $k6 * $in6band + $k7 * " "$in7band" ) - grass.mapcalc( + gs.mapcalc( equation, out=out, k1=k1, k2=k2, k3=k3, k4=k4, k5=k5, k6=k6, k7=k7, **bands ) @@ -264,7 +264,7 @@ def calc1bands8(out, bands, k1, k2, k3, k4, k5, k6, k7, k8): "$k4 * $in4band + $k5 * $in5band + $k6 * $in6band + $k7 * " "$in7band + $k8 * $in8band" ) - grass.mapcalc( + gs.mapcalc( equation, out=out, k1=k1, @@ -289,7 +289,7 @@ def calc1bands13(out, bands, k1, k2, k3, k4, k5, k6, k7, k8, k9, k10, k11, k12, "$in7band + $k8 * $in8band + $k9 * $in9band + $k10 * $in10band + " "$k11 * $in11band + $k12 * $in12band + $k13 * $in13band" ) - grass.mapcalc( + gs.mapcalc( equation, out=out, k1=k1, @@ -314,7 +314,7 @@ def calcN(outpre, bands, satel): Calculating Tasseled Cap components """ i = satellites.index(satel) - grass.message(_("Satellite %s...") % satel) + gs.message(_("Satellite %s...") % satel) for j, p in enumerate(parms[i]): out = "%s.%d" % (outpre, j + 1) @@ -322,22 +322,22 @@ def calcN(outpre, bands, satel): name = " (%s)" % names[j] message = "Calculating {ordinal} TC component {outprefix}{outname} ..." message = message.format(ordinal=ord, outprefix=out, outname=name) - grass.message(_(message)) + gs.message(_(message)) bands_num = used_bands[i] # use combination function suitable for used number of bands eval("calc1bands%d(out, bands, *p)" % bands_num) - grass.run_command("r.colors", map=out, color="grey", quiet=True) + gs.run_command("r.colors", map=out, color="grey", quiet=True) def main(): - options, flags = grass.parser() + options, flags = gs.parser() satellite = options["sensor"] output_basename = options["output"] inputs = options["input"].split(",") num_of_bands = used_bands[satellites.index(satellite)] if len(inputs) != num_of_bands: - grass.fatal( + gs.fatal( _("The number of input raster maps (bands) should be %s") % num_of_bands ) @@ -345,7 +345,7 @@ def main(): for i, band in enumerate(inputs): band_num = i + 1 bands["in" + str(band_num) + "band"] = band - grass.debug(bands, 1) + gs.debug(bands, 1) # core tasseled cap components computation calcN(output_basename, bands, satellite) @@ -354,13 +354,13 @@ def main(): num_comp = len(parms[satellites.index(satellite)]) for i in range(0, num_comp): comp = names[i] - grass.run_command( + gs.run_command( "r.support", map="%s.%d" % (output_basename, i + 1), description="Tasseled Cap %d: %s" % (i + 1, comp), ) - grass.message(_("Tasseled Cap components calculated")) + gs.message(_("Tasseled Cap components calculated")) if __name__ == "__main__": diff --git a/scripts/r.blend/r.blend.py b/scripts/r.blend/r.blend.py index 66a7ac63cfb..4bda8be6d49 100755 --- a/scripts/r.blend/r.blend.py +++ b/scripts/r.blend/r.blend.py @@ -45,7 +45,7 @@ import os import string -import grass.script as gscript +import grass.script as gs def main(): @@ -54,13 +54,13 @@ def main(): output = options["output"] percent = options["percent"] - mapset = gscript.gisenv()["MAPSET"] + mapset = gs.gisenv()["MAPSET"] - if not gscript.overwrite(): + if not gs.overwrite(): for ch in ["r", "g", "b"]: map = "%s.%s" % (output, ch) - if gscript.find_file(map, element="cell", mapset=mapset)["file"]: - gscript.fatal(_("Raster map <%s> already exists.") % map) + if gs.find_file(map, element="cell", mapset=mapset)["file"]: + gs.fatal(_("Raster map <%s> already exists.") % map) percent = float(percent) perc_inv = 100.0 - percent @@ -68,7 +68,7 @@ def main(): frac1 = percent / 100.0 frac2 = perc_inv / 100.0 - gscript.message(_("Calculating the three component maps...")) + gs.message(_("Calculating the three component maps...")) template = string.Template( "$$output.$ch = " @@ -80,31 +80,29 @@ def main(): cmd = [template.substitute(ch=ch) for ch in ["r", "g", "b"]] cmd = ";".join(cmd) - gscript.mapcalc( - cmd, output=output, first=first, second=second, frac1=frac1, frac2=frac2 - ) + gs.mapcalc(cmd, output=output, first=first, second=second, frac1=frac1, frac2=frac2) for ch in ["r", "g", "b"]: map = "%s.%s" % (output, ch) - gscript.run_command("r.colors", map=map, color="grey255") - gscript.run_command( + gs.run_command("r.colors", map=map, color="grey255") + gs.run_command( "r.support", map=map, history="", title="Color blend of %s and %s" % (first, second), description="generated by r.blend", ) - gscript.run_command("r.support", map=map, history="r.blend %s channel." % ch) - gscript.run_command( + gs.run_command("r.support", map=map, history="r.blend %s channel." % ch) + gs.run_command( "r.support", map=map, history=" %d%% of %s, %d%% of %s" % (percent, first, perc_inv, second), ) - gscript.run_command("r.support", map=map, history="") - gscript.run_command("r.support", map=map, history=os.environ["CMDLINE"]) + gs.run_command("r.support", map=map, history="") + gs.run_command("r.support", map=map, history=os.environ["CMDLINE"]) if flags["c"]: - gscript.run_command( + gs.run_command( "r.composite", r="%s.r" % output, g="%s.g" % output, @@ -112,25 +110,25 @@ def main(): output=output, ) - gscript.run_command( + gs.run_command( "r.support", map=output, history="", title="Color blend of %s and %s" % (first, second), description="generated by r.blend", ) - gscript.run_command( + gs.run_command( "r.support", map=output, history=" %d%% of %s, %d%% of %s" % (percent, first, perc_inv, second), ) - gscript.run_command("r.support", map=output, history="") - gscript.run_command("r.support", map=output, history=os.environ["CMDLINE"]) + gs.run_command("r.support", map=output, history="") + gs.run_command("r.support", map=output, history=os.environ["CMDLINE"]) else: - gscript.message(_("Done. Use the following command to visualize the result:")) - gscript.message(_("d.rgb r=%s.r g=%s.g b=%s.b") % (output, output, output)) + gs.message(_("Done. Use the following command to visualize the result:")) + gs.message(_("d.rgb r=%s.r g=%s.g b=%s.b") % (output, output, output)) if __name__ == "__main__": - options, flags = gscript.parser() + options, flags = gs.parser() main() diff --git a/scripts/r.buffer.lowmem/r.buffer.lowmem.py b/scripts/r.buffer.lowmem/r.buffer.lowmem.py index 01e44973e91..2916ad95e7d 100755 --- a/scripts/r.buffer.lowmem/r.buffer.lowmem.py +++ b/scripts/r.buffer.lowmem/r.buffer.lowmem.py @@ -43,7 +43,7 @@ import os import atexit -import grass.script as grass +import grass.script as gs from grass.script.utils import encode @@ -59,12 +59,10 @@ def cleanup(): - if grass.find_file(temp_src)["file"]: - grass.run_command( - "g.remove", quiet=True, flags="fb", type="raster", name=temp_src - ) - if grass.find_file(temp_dist)["file"]: - grass.run_command( + if gs.find_file(temp_src)["file"]: + gs.run_command("g.remove", quiet=True, flags="fb", type="raster", name=temp_src) + if gs.find_file(temp_dist)["file"]: + gs.run_command( "g.remove", quiet=True, flags="fb", type="raster", name=temp_dist ) @@ -83,8 +81,8 @@ def main(): temp_src = "r.buffer.tmp.%s.src" % tmp # check if input file exists - if not grass.find_file(input)["file"]: - grass.fatal(_("Raster map <%s> not found") % input) + if not gs.find_file(input)["file"]: + gs.fatal(_("Raster map <%s> not found") % input) scale = scales[units] @@ -92,14 +90,14 @@ def main(): distances1 = [scale * float(d) for d in distances] distances2 = [d * d for d in distances1] - s = grass.read_command("g.proj", flags="j") - kv = grass.parse_key_val(s) + s = gs.read_command("g.proj", flags="j") + kv = gs.parse_key_val(s) if kv["+proj"] == "longlat": metric = "geodesic" else: metric = "squared" - grass.run_command( + gs.run_command( "r.grow.distance", input=input, metric=metric, distance=temp_dist, flags="m" ) @@ -108,8 +106,8 @@ def main(): else: exp = "$temp_src = if(isnull($input),null(),1)" - grass.message(_("Extracting buffers (1/2)...")) - grass.mapcalc(exp, temp_src=temp_src, input=input) + gs.message(_("Extracting buffers (1/2)...")) + gs.mapcalc(exp, temp_src=temp_src, input=input) exp = "$output = if(!isnull($input),$input,%s)" if metric == "squared": @@ -120,10 +118,10 @@ def main(): exp %= "if($dist <= %f,%d,%%s)" % (dist2, n + 2) exp %= "null()" - grass.message(_("Extracting buffers (2/2)...")) - grass.mapcalc(exp, output=output, input=temp_src, dist=temp_dist) + gs.message(_("Extracting buffers (2/2)...")) + gs.mapcalc(exp, output=output, input=temp_src, dist=temp_dist) - p = grass.feed_command("r.category", map=output, separator=":", rules="-") + p = gs.feed_command("r.category", map=output, separator=":", rules="-") msg = "1:distances calculated from these locations\n" p.stdin.write(encode(msg)) d0 = "0" @@ -134,13 +132,13 @@ def main(): p.stdin.close() p.wait() - grass.run_command("r.colors", map=output, color="rainbow") + gs.run_command("r.colors", map=output, color="rainbow") # write cmd history: - grass.raster_history(output) + gs.raster_history(output) if __name__ == "__main__": - options, flags = grass.parser() + options, flags = gs.parser() atexit.register(cleanup) main() diff --git a/scripts/r.colors.stddev/r.colors.stddev.py b/scripts/r.colors.stddev/r.colors.stddev.py index e8d4321939f..d8db41e427d 100755 --- a/scripts/r.colors.stddev/r.colors.stddev.py +++ b/scripts/r.colors.stddev/r.colors.stddev.py @@ -33,7 +33,7 @@ import os import atexit -import grass.script as gscript +import grass.script as gs from grass.script.utils import decode @@ -43,9 +43,7 @@ def z(n): def cleanup(): if tmpmap: - gscript.run_command( - "g.remove", flags="f", type="raster", name=tmpmap, quiet=True - ) + gs.run_command("g.remove", flags="f", type="raster", name=tmpmap, quiet=True) def main(): @@ -57,8 +55,8 @@ def main(): bands = flags["b"] if not zero: - s = gscript.read_command("r.univar", flags="g", map=map) - kv = gscript.parse_key_val(decode(s)) + s = gs.read_command("r.univar", flags="g", map=map) + kv = gs.parse_key_val(decode(s)) global mean, stddev mean = float(kv["mean"]) stddev = float(kv["stddev"]) @@ -103,17 +101,17 @@ def main(): ) else: tmpmap = "r_col_stdev_abs_%d" % os.getpid() - gscript.mapcalc("$tmp = abs($map)", tmp=tmpmap, map=map) + gs.mapcalc("$tmp = abs($map)", tmp=tmpmap, map=map) # data centered on 0 (e.g. map of deviations) - info = gscript.raster_info(tmpmap) + info = gs.raster_info(tmpmap) maxv = info["max"] # current r.univar truncates percentage to the base integer - s = gscript.read_command( + s = gs.read_command( "r.univar", flags="eg", map=map, percentile=[95.45, 68.2689, 99.7300] ) - kv = gscript.parse_key_val(decode(s)) + kv = gs.parse_key_val(decode(s)) stddev1 = float(kv["percentile_68_2689"]) stddev2 = float(kv["percentile_95_45"]) @@ -154,10 +152,10 @@ def main(): ] ) - gscript.write_command("r.colors", map=map, rules="-", stdin=rules) + gs.write_command("r.colors", map=map, rules="-", stdin=rules) if __name__ == "__main__": - options, flags = gscript.parser() + options, flags = gs.parser() atexit.register(cleanup) main() diff --git a/scripts/r.fillnulls/r.fillnulls.py b/scripts/r.fillnulls/r.fillnulls.py index b09ea17889d..2627bca9ffe 100755 --- a/scripts/r.fillnulls/r.fillnulls.py +++ b/scripts/r.fillnulls/r.fillnulls.py @@ -105,7 +105,7 @@ import atexit import subprocess -import grass.script as grass +import grass.script as gs from grass.exceptions import CalledModuleError tmp_rmaps = [] @@ -119,16 +119,16 @@ def cleanup(): # delete internal mask and any TMP files: if len(tmp_vmaps) > 0: - grass.run_command( + gs.run_command( "g.remove", quiet=True, flags="fb", type="vector", name=tmp_vmaps ) if len(tmp_rmaps) > 0: - grass.run_command( + gs.run_command( "g.remove", quiet=True, flags="fb", type="raster", name=tmp_rmaps ) if usermask and mapset: - if grass.find_file(usermask, mapset=mapset)["file"]: - grass.run_command( + if gs.find_file(usermask, mapset=mapset)["file"]: + gs.run_command( "g.rename", quiet=True, raster=(usermask, "MASK"), overwrite=True ) @@ -147,7 +147,7 @@ def main(): lambda_ = float(options["lambda"]) memory = options["memory"] quiet = True # FIXME - mapset = grass.gisenv()["MAPSET"] + mapset = gs.gisenv()["MAPSET"] unique = str(os.getpid()) # Shouldn't we use temp name? prefix = "r_fillnulls_%s_" % unique failed_list = ( @@ -155,19 +155,19 @@ def main(): ) # a list of failed holes. Caused by issues with v.surf.rst. Connected with #1813 # check if input file exists - if not grass.find_file(input)["file"]: - grass.fatal(_("Raster map <%s> not found") % input) + if not gs.find_file(input)["file"]: + gs.fatal(_("Raster map <%s> not found") % input) # save original region - reg_org = grass.region() + reg_org = gs.region() # check if a MASK is already present # and remove it to not interfere with NULL lookup part # as we don't fill MASKed parts! - if grass.find_file("MASK", mapset=mapset)["file"]: + if gs.find_file("MASK", mapset=mapset)["file"]: usermask = "usermask_mask." + unique - grass.message(_("A user raster mask (MASK) is present. Saving it...")) - grass.run_command("g.rename", quiet=quiet, raster=("MASK", usermask)) + gs.message(_("A user raster mask (MASK) is present. Saving it...")) + gs.run_command("g.rename", quiet=quiet, raster=("MASK", usermask)) # check if method is rst to use v.surf.rst if method == "rst": @@ -175,19 +175,19 @@ def main(): # interpolate from these surrounding 3 pixel edge filling = prefix + "filled" - grass.use_temp_region() - grass.run_command("g.region", align=input, quiet=quiet) - region = grass.region() + gs.use_temp_region() + gs.run_command("g.region", align=input, quiet=quiet) + region = gs.region() ns_res = region["nsres"] ew_res = region["ewres"] - grass.message(_("Using RST interpolation...")) - grass.message(_("Locating and isolating NULL areas...")) + gs.message(_("Using RST interpolation...")) + gs.message(_("Locating and isolating NULL areas...")) # creating binary (0/1) map if usermask: - grass.message(_("Skipping masked raster parts")) - grass.mapcalc( + gs.message(_("Skipping masked raster parts")) + gs.mapcalc( ( '$tmp1 = if(isnull("$input") && !($mask == 0 || isnull($mask)),1,' "null())" @@ -197,7 +197,7 @@ def main(): mask=usermask, ) else: - grass.mapcalc( + gs.mapcalc( '$tmp1 = if(isnull("$input"),1,null())', tmp1=prefix + "nulls", input=input, @@ -207,18 +207,18 @@ def main(): # restoring user's mask, if present # to ignore MASKed original values if usermask: - grass.message(_("Restoring user mask (MASK)...")) + gs.message(_("Restoring user mask (MASK)...")) try: - grass.run_command("g.rename", quiet=quiet, raster=(usermask, "MASK")) + gs.run_command("g.rename", quiet=quiet, raster=(usermask, "MASK")) except CalledModuleError: - grass.warning(_("Failed to restore user MASK!")) + gs.warning(_("Failed to restore user MASK!")) usermask = None # grow identified holes by X pixels - grass.message(_("Growing NULL areas")) + gs.message(_("Growing NULL areas")) tmp_rmaps.append(prefix + "grown") try: - grass.run_command( + gs.run_command( "r.grow", input=prefix + "nulls", radius=edge + 0.01, @@ -228,7 +228,7 @@ def main(): quiet=quiet, ) except CalledModuleError: - grass.fatal( + gs.fatal( _( "abandoned. Removing temporary map, restoring " "user mask if needed:" @@ -237,17 +237,17 @@ def main(): # assign unique IDs to each hole or hole system (holes closer than edge # distance) - grass.message(_("Assigning IDs to NULL areas")) + gs.message(_("Assigning IDs to NULL areas")) tmp_rmaps.append(prefix + "clumped") try: - grass.run_command( + gs.run_command( "r.clump", input=prefix + "grown", output=prefix + "clumped", quiet=quiet, ) except CalledModuleError: - grass.fatal( + gs.fatal( _( "abandoned. Removing temporary map, restoring " "user mask if needed:" @@ -255,7 +255,7 @@ def main(): ) # get a list of unique hole cat's - grass.mapcalc( + gs.mapcalc( "$out = if(isnull($inp), null(), $clumped)", out=prefix + "holes", inp=prefix + "nulls", @@ -265,7 +265,7 @@ def main(): # use new IDs to identify holes try: - grass.run_command( + gs.run_command( "r.to.vect", flags="v", input=prefix + "holes", @@ -274,7 +274,7 @@ def main(): quiet=quiet, ) except: - grass.fatal( + gs.fatal( _( "abandoned. Removing temporary maps, restoring " "user mask if needed:" @@ -283,8 +283,8 @@ def main(): tmp_vmaps.append(prefix + "holes") # get a list of unique hole cat's - cats_file_name = grass.tempfile(False) - grass.run_command( + cats_file_name = gs.tempfile(False) + gs.run_command( "v.db.select", flags="c", map=prefix + "holes", @@ -301,10 +301,10 @@ def main(): if len(cat_list) < 1: # no holes found in current region - grass.run_command( + gs.run_command( "g.copy", raster="%s,%sfilled" % (input, prefix), overwrite=True ) - grass.warning( + gs.warning( _( "Input map <%s> has no holes. Copying to output without " "modification." @@ -313,17 +313,17 @@ def main(): ) # GTC Hole is NULL area in a raster map - grass.message(_("Processing %d map holes") % len(cat_list)) + gs.message(_("Processing %d map holes") % len(cat_list)) first = True hole_n = 1 for cat in cat_list: holename = prefix + "hole_" + cat # GTC Hole is a NULL area in a raster map - grass.message(_("Filling hole %s of %s") % (hole_n, len(cat_list))) + gs.message(_("Filling hole %s of %s") % (hole_n, len(cat_list))) hole_n = hole_n + 1 # cut out only CAT hole for processing try: - grass.run_command( + gs.run_command( "v.extract", input=prefix + "holes", output=holename + "_pol", @@ -331,7 +331,7 @@ def main(): quiet=quiet, ) except CalledModuleError: - grass.fatal( + gs.fatal( _( "abandoned. Removing temporary maps, restoring " "user mask if needed:" @@ -342,7 +342,7 @@ def main(): # zoom to specific hole with a buffer of two cells around the hole to # remove rest of data try: - grass.run_command( + gs.run_command( "g.region", vector=holename + "_pol", align=input, @@ -353,7 +353,7 @@ def main(): quiet=quiet, ) except CalledModuleError: - grass.fatal( + gs.fatal( _( "abandoned. Removing temporary maps, restoring " "user mask if needed:" @@ -362,7 +362,7 @@ def main(): # remove temporary map to not overfill disk try: - grass.run_command( + gs.run_command( "g.remove", flags="fb", type="vector", @@ -370,7 +370,7 @@ def main(): quiet=quiet, ) except CalledModuleError: - grass.fatal( + gs.fatal( _( "abandoned. Removing temporary maps, restoring " "user mask if needed:" @@ -379,7 +379,7 @@ def main(): tmp_vmaps.remove(holename + "_pol") # copy only data around hole - grass.mapcalc( + gs.mapcalc( "$out = if($inp == $catn, $inp, null())", out=holename, inp=prefix + "holes", @@ -394,7 +394,7 @@ def main(): # grow hole border to get it's edge area tmp_rmaps.append(holename + "_grown") try: - grass.run_command( + gs.run_command( "r.grow", input=holename, radius=edge + 0.01, @@ -403,7 +403,7 @@ def main(): quiet=quiet, ) except CalledModuleError: - grass.fatal( + gs.fatal( _( "abandoned. Removing temporary map, restoring " "user mask if needed:" @@ -411,7 +411,7 @@ def main(): ) # no idea why r.grow old=-1 doesn't replace existing values with NULL - grass.mapcalc( + gs.mapcalc( '$out = if($inp == -1, null(), "$dem")', out=holename + "_edges", inp=holename + "_grown", @@ -422,7 +422,7 @@ def main(): # convert to points for interpolation tmp_vmaps.append(holename) try: - grass.run_command( + gs.run_command( "r.to.vect", input=holename + "_edges", output=holename, @@ -431,7 +431,7 @@ def main(): quiet=quiet, ) except CalledModuleError: - grass.fatal( + gs.fatal( _( "abandoned. Removing temporary maps, restoring " "user mask if needed:" @@ -439,11 +439,11 @@ def main(): ) # count number of points to control segmax parameter for interpolation: - pointsnumber = grass.vector_info_topo(map=holename)["points"] - grass.verbose(_("Interpolating %d points") % pointsnumber) + pointsnumber = gs.vector_info_topo(map=holename)["points"] + gs.verbose(_("Interpolating %d points") % pointsnumber) if pointsnumber < 2: - grass.verbose(_("No points to interpolate")) + gs.verbose(_("No points to interpolate")) failed_list.append(holename) continue @@ -458,7 +458,7 @@ def main(): # launch v.surf.rst tmp_rmaps.append(holename + "_dem") try: - grass.run_command( + gs.run_command( "v.surf.rst", quiet=quiet, input=holename, @@ -470,11 +470,11 @@ def main(): ) except CalledModuleError: # GTC Hole is NULL area in a raster map - grass.fatal(_("Failed to fill hole %s") % cat) + gs.fatal(_("Failed to fill hole %s") % cat) # v.surf.rst sometimes fails with exit code 0 # related bug #1813 - if not grass.find_file(holename + "_dem")["file"]: + if not gs.find_file(holename + "_dem")["file"]: try: tmp_rmaps.remove(holename) tmp_rmaps.remove(holename + "_grown") @@ -483,7 +483,7 @@ def main(): tmp_vmaps.remove(holename) except: pass - grass.warning( + gs.warning( _( "Filling has failed silently. Leaving temporary maps " "with prefix <%s> for debugging." @@ -497,10 +497,10 @@ def main(): # original DEM if first: tmp_rmaps.append(filling) - grass.run_command( + gs.run_command( "g.region", align=input, raster=holename + "_dem", quiet=quiet ) - grass.mapcalc( + gs.mapcalc( "$out = if(isnull($inp), null(), $dem)", out=filling, inp=holename, @@ -509,13 +509,13 @@ def main(): first = False else: tmp_rmaps.append(filling + "_tmp") - grass.run_command( + gs.run_command( "g.region", align=input, raster=(filling, holename + "_dem"), quiet=quiet, ) - grass.mapcalc( + gs.mapcalc( "$out = if(isnull($inp), if(isnull($fill), null(), $fill), $dem)", out=filling + "_tmp", inp=holename, @@ -523,14 +523,14 @@ def main(): fill=filling, ) try: - grass.run_command( + gs.run_command( "g.rename", raster=(filling + "_tmp", filling), overwrite=True, quiet=quiet, ) except CalledModuleError: - grass.fatal( + gs.fatal( _( "abandoned. Removing temporary maps, restoring user " "mask if needed:" @@ -548,7 +548,7 @@ def main(): except: pass try: - grass.run_command( + gs.run_command( "g.remove", quiet=quiet, flags="fb", @@ -561,7 +561,7 @@ def main(): ), ) except CalledModuleError: - grass.fatal( + gs.fatal( _( "abandoned. Removing temporary maps, restoring " "user mask if needed:" @@ -572,11 +572,11 @@ def main(): except: pass try: - grass.run_command( + gs.run_command( "g.remove", quiet=quiet, flags="fb", type="vector", name=holename ) except CalledModuleError: - grass.fatal( + gs.fatal( _( "abandoned. Removing temporary maps, restoring user mask if " "needed:" @@ -585,13 +585,13 @@ def main(): # check if method is different from rst to use r.resamp.bspline if method != "rst": - grass.message(_("Using %s bspline interpolation") % method) + gs.message(_("Using %s bspline interpolation") % method) # clone current region - grass.use_temp_region() - grass.run_command("g.region", align=input) + gs.use_temp_region() + gs.run_command("g.region", align=input) - reg = grass.region() + reg = gs.region() # launch r.resamp.bspline tmp_rmaps.append(prefix + "filled") # If there are no NULL cells, r.resamp.bslpine call @@ -601,7 +601,7 @@ def main(): new_env["LC_ALL"] = "C" if usermask: try: - p = grass.core.start_command( + p = gs.core.start_command( "r.resamp.bspline", input=input, mask=usermask, @@ -615,13 +615,13 @@ def main(): stderr=subprocess.PIPE, env=new_env, ) - stderr = grass.decode(p.communicate()[1]) + stderr = gs.decode(p.communicate()[1]) if "No NULL cells found" in stderr: - grass.run_command( + gs.run_command( "g.copy", raster="%s,%sfilled" % (input, prefix), overwrite=True ) p.returncode = 0 - grass.warning( + gs.warning( _( "Input map <%s> has no holes. Copying to output without " "modification." @@ -629,13 +629,13 @@ def main(): % (input,) ) except CalledModuleError: - grass.fatal( + gs.fatal( _("Failure during bspline interpolation. Error message: %s") % stderr ) else: try: - p = grass.core.start_command( + p = gs.core.start_command( "r.resamp.bspline", input=input, output=prefix + "filled", @@ -648,13 +648,13 @@ def main(): stderr=subprocess.PIPE, env=new_env, ) - stderr = grass.decode(p.communicate()[1]) + stderr = gs.decode(p.communicate()[1]) if "No NULL cells found" in stderr: - grass.run_command( + gs.run_command( "g.copy", raster="%s,%sfilled" % (input, prefix), overwrite=True ) p.returncode = 0 - grass.warning( + gs.warning( _( "Input map <%s> has no holes. Copying to output without " "modification." @@ -662,22 +662,22 @@ def main(): % (input,) ) except CalledModuleError: - grass.fatal( + gs.fatal( _("Failure during bspline interpolation. Error message: %s") % stderr ) # restoring user's mask, if present: if usermask: - grass.message(_("Restoring user mask (MASK)...")) + gs.message(_("Restoring user mask (MASK)...")) try: - grass.run_command("g.rename", quiet=quiet, raster=(usermask, "MASK")) + gs.run_command("g.rename", quiet=quiet, raster=(usermask, "MASK")) except CalledModuleError: - grass.warning(_("Failed to restore user MASK!")) + gs.warning(_("Failed to restore user MASK!")) usermask = None # set region to original extents, align to input - grass.run_command( + gs.run_command( "g.region", n=reg_org["n"], s=reg_org["s"], @@ -687,22 +687,22 @@ def main(): ) # patch orig and fill map - grass.message(_("Patching fill data into NULL areas...")) + gs.message(_("Patching fill data into NULL areas...")) # we can use --o here as g.parser already checks on startup - grass.run_command( + gs.run_command( "r.patch", input=(input, prefix + "filled"), output=output, overwrite=True ) # restore the real region - grass.del_temp_region() + gs.del_temp_region() - grass.message(_("Filled raster map is: %s") % output) + gs.message(_("Filled raster map is: %s") % output) # write cmd history: - grass.raster_history(output) + gs.raster_history(output) if len(failed_list) > 0: - grass.warning( + gs.warning( _( "Following holes where not filled. Temporary maps with are left " "in place to allow examination of unfilled holes" @@ -711,12 +711,12 @@ def main(): outlist = failed_list[0] for hole in failed_list[1:]: outlist = ", " + outlist - grass.message(outlist) + gs.message(outlist) - grass.message(_("Done.")) + gs.message(_("Done.")) if __name__ == "__main__": - options, flags = grass.parser() + options, flags = gs.parser() atexit.register(cleanup) main() diff --git a/scripts/r.grow/r.grow.py b/scripts/r.grow/r.grow.py index 72601d78ddb..86fdfd9ebc3 100755 --- a/scripts/r.grow/r.grow.py +++ b/scripts/r.grow/r.grow.py @@ -64,7 +64,7 @@ import atexit import math -import grass.script as grass +import grass.script as gs from grass.exceptions import CalledModuleError @@ -72,7 +72,7 @@ def cleanup(): for map in [temp_dist, temp_val]: if map: - grass.run_command("g.remove", flags="fb", quiet=True, type="rast", name=map) + gs.run_command("g.remove", flags="fb", quiet=True, type="rast", name=map) def main(): @@ -104,7 +104,7 @@ def main(): old = '"%s"' % input if not mapunits: - kv = grass.region() + kv = gs.region() scale = math.sqrt(float(kv["nsres"]) * float(kv["ewres"])) radius *= scale @@ -113,22 +113,22 @@ def main(): radius = radius * radius # check if input file exists - if not grass.find_file(input)["file"]: - grass.fatal(_("Raster map <%s> not found") % input) + if not gs.find_file(input)["file"]: + gs.fatal(_("Raster map <%s> not found") % input) # Workaround for r.mapcalc bug #3475 # Mapcalc will fail if output is a fully qualified map name out_name = options["output"].split("@") if len(out_name) == 2: - if out_name[1] != grass.gisenv()["MAPSET"]: - grass.fatal(_("Output can be written only to the current mapset")) + if out_name[1] != gs.gisenv()["MAPSET"]: + gs.fatal(_("Output can be written only to the current mapset")) output = out_name[0] else: output = out_name[0] if not shrink: try: - grass.run_command( + gs.run_command( "r.grow.distance", input=input, metric=metric, @@ -136,9 +136,9 @@ def main(): value=temp_val, ) except CalledModuleError: - grass.fatal(_("Growing failed. Removing temporary maps.")) + gs.fatal(_("Growing failed. Removing temporary maps.")) - grass.mapcalc( + gs.mapcalc( '$output = if(!isnull("$input"),$old,if($dist < $radius,$new,null()))', output=output, input=input, @@ -150,7 +150,7 @@ def main(): else: # shrink try: - grass.run_command( + gs.run_command( "r.grow.distance", input=input, metric=metric, @@ -159,9 +159,9 @@ def main(): flags="n", ) except CalledModuleError: - grass.fatal(_("Shrinking failed. Removing temporary maps.")) + gs.fatal(_("Shrinking failed. Removing temporary maps.")) - grass.mapcalc( + gs.mapcalc( "$output = if(isnull($dist), $old, if($dist < $radius,null(),$old))", output=output, radius=radius, @@ -169,13 +169,13 @@ def main(): dist=temp_dist, ) - grass.run_command("r.colors", map=output, raster=input) + gs.run_command("r.colors", map=output, raster=input) # write cmd history: - grass.raster_history(output) + gs.raster_history(output) if __name__ == "__main__": - options, flags = grass.parser() + options, flags = gs.parser() atexit.register(cleanup) main() diff --git a/scripts/r.import/r.import.py b/scripts/r.import/r.import.py index 195b7c79c31..a3f952c037b 100644 --- a/scripts/r.import/r.import.py +++ b/scripts/r.import/r.import.py @@ -118,7 +118,7 @@ import atexit import math -import grass.script as grass +import grass.script as gs from grass.exceptions import CalledModuleError @@ -132,16 +132,16 @@ def cleanup(): # remove temp location if TMPLOC: - grass.try_rmdir(os.path.join(GISDBASE, TMPLOC)) + gs.try_rmdir(os.path.join(GISDBASE, TMPLOC)) if SRCGISRC: - grass.try_remove(SRCGISRC) + gs.try_remove(SRCGISRC) if ( TMP_REG_NAME - and grass.find_file( - name=TMP_REG_NAME, element="vector", mapset=grass.gisenv()["MAPSET"] + and gs.find_file( + name=TMP_REG_NAME, element="vector", mapset=gs.gisenv()["MAPSET"] )["fullname"] ): - grass.run_command( + gs.run_command( "g.remove", type="vector", name=TMP_REG_NAME, flags="f", quiet=True ) @@ -150,7 +150,7 @@ def is_projection_matching(GDALdatasource): """Returns True if current location projection matches dataset projection, otherwise False""" try: - grass.run_command("r.in.gdal", input=GDALdatasource, flags="j", quiet=True) + gs.run_command("r.in.gdal", input=GDALdatasource, flags="j", quiet=True) return True except CalledModuleError: return False @@ -170,14 +170,14 @@ def main(): output = "rimport_tmp" # will be removed with the entire tmp location if options["resolution_value"]: if tgtres != "value": - grass.fatal( + gs.fatal( _("To set custom resolution value, select 'value' in resolution option") ) tgtres_value = float(options["resolution_value"]) if tgtres_value <= 0: - grass.fatal(_("Resolution value can't be smaller than 0")) + gs.fatal(_("Resolution value can't be smaller than 0")) elif tgtres == "value": - grass.fatal( + gs.fatal( _( "Please provide the resolution for the imported dataset or change to " "'estimated' resolution" @@ -201,21 +201,21 @@ def main(): if bands: parameters["band"] = bands try: - grass.run_command("r.in.gdal", **parameters) - grass.verbose( + gs.run_command("r.in.gdal", **parameters) + gs.verbose( _("Input <%s> successfully imported without reprojection") % GDALdatasource ) return 0 except CalledModuleError: - grass.fatal(_("Unable to import GDAL dataset <%s>") % GDALdatasource) + gs.fatal(_("Unable to import GDAL dataset <%s>") % GDALdatasource) - grassenv = grass.gisenv() + grassenv = gs.gisenv() tgtloc = grassenv["LOCATION_NAME"] # make sure target is not xy - if grass.parse_command("g.proj", flags="g")["name"] == "xy_location_unprojected": - grass.fatal( + if gs.parse_command("g.proj", flags="g")["name"] == "xy_location_unprojected": + gs.fatal( _("Coordinate reference system not available for current project <%s>") % tgtloc ) @@ -223,16 +223,16 @@ def main(): tgtmapset = grassenv["MAPSET"] GISDBASE = grassenv["GISDBASE"] - TMPLOC = grass.append_node_pid("tmp_r_import_location") - TMP_REG_NAME = grass.append_node_pid("tmp_r_import_region") + TMPLOC = gs.append_node_pid("tmp_r_import_location") + TMP_REG_NAME = gs.append_node_pid("tmp_r_import_region") - SRCGISRC, src_env = grass.create_environment(GISDBASE, TMPLOC, "PERMANENT") + SRCGISRC, src_env = gs.create_environment(GISDBASE, TMPLOC, "PERMANENT") # create temp location from input without import - grass.verbose(_("Creating temporary project for <%s>...") % GDALdatasource) + gs.verbose(_("Creating temporary project for <%s>...") % GDALdatasource) # creating a new location with r.in.gdal requires a sanitized env env = os.environ.copy() - env = grass.sanitize_mapset_environment(env) + env = gs.sanitize_mapset_environment(env) parameters = { "input": GDALdatasource, "output": output, @@ -245,34 +245,32 @@ def main(): if bands: parameters["band"] = bands try: - grass.run_command("r.in.gdal", env=env, **parameters) + gs.run_command("r.in.gdal", env=env, **parameters) except CalledModuleError: - grass.fatal(_("Unable to read GDAL dataset <%s>") % GDALdatasource) + gs.fatal(_("Unable to read GDAL dataset <%s>") % GDALdatasource) # prepare to set region in temp location if "r" in region_flag: tgtregion = TMP_REG_NAME - grass.run_command("v.in.region", output=tgtregion, flags="d") + gs.run_command("v.in.region", output=tgtregion, flags="d") # switch to temp location # print projection at verbose level - grass.verbose( - grass.read_command("g.proj", flags="p", env=src_env).rstrip(os.linesep) - ) + gs.verbose(gs.read_command("g.proj", flags="p", env=src_env).rstrip(os.linesep)) # make sure input is not xy if ( - grass.parse_command("g.proj", flags="g", env=src_env)["name"] + gs.parse_command("g.proj", flags="g", env=src_env)["name"] == "xy_location_unprojected" ): - grass.fatal( + gs.fatal( _("Coordinate reference system not available for input <%s>") % GDALdatasource ) # import into temp location - grass.verbose(_("Importing <%s> to temporary project...") % GDALdatasource) + gs.verbose(_("Importing <%s> to temporary project...") % GDALdatasource) parameters = { "input": GDALdatasource, "output": output, @@ -282,7 +280,7 @@ def main(): if bands: parameters["band"] = bands if "r" in region_flag: - grass.run_command( + gs.run_command( "v.proj", project=tgtloc, mapset=tgtmapset, @@ -290,14 +288,14 @@ def main(): output=tgtregion, env=src_env, ) - grass.run_command("g.region", vector=tgtregion, env=src_env) + gs.run_command("g.region", vector=tgtregion, env=src_env) parameters["flags"] = parameters["flags"] + region_flag try: - grass.run_command("r.in.gdal", env=src_env, **parameters) + gs.run_command("r.in.gdal", env=src_env, **parameters) except CalledModuleError: - grass.fatal(_("Unable to import GDAL dataset <%s>") % GDALdatasource) + gs.fatal(_("Unable to import GDAL dataset <%s>") % GDALdatasource) - outfiles = grass.list_grouped("raster", env=src_env)["PERMANENT"] + outfiles = gs.list_grouped("raster", env=src_env)["PERMANENT"] # is output a group? group = False @@ -306,17 +304,17 @@ def main(): group = True path = os.path.join(GISDBASE, TMPLOC, "group", output, "POINTS") if os.path.exists(path): - grass.fatal(_("Input contains GCPs, rectification is required")) + gs.fatal(_("Input contains GCPs, rectification is required")) if "r" in region_flag: - grass.run_command( + gs.run_command( "g.remove", type="vector", flags="f", name=tgtregion, env=src_env ) # switch to target location - grass.run_command("g.remove", type="vector", flags="f", name=tgtregion) + gs.run_command("g.remove", type="vector", flags="f", name=tgtregion) - region = grass.region() + region = gs.region() rflags = None if flags["n"]: @@ -334,7 +332,7 @@ def main(): if options["extent"] == "input": # r.proj -g try: - tgtextents = grass.read_command( + tgtextents = gs.read_command( "r.proj", project=TMPLOC, mapset="PERMANENT", @@ -344,37 +342,37 @@ def main(): quiet=True, ) except CalledModuleError: - grass.fatal(_("Unable to get reprojected map extent")) + gs.fatal(_("Unable to get reprojected map extent")) try: - srcregion = grass.parse_key_val(tgtextents, val_type=float, vsep=" ") + srcregion = gs.parse_key_val(tgtextents, val_type=float, vsep=" ") n = srcregion["n"] s = srcregion["s"] e = srcregion["e"] w = srcregion["w"] except ValueError: # import into latlong, expect 53:39:06.894826N - srcregion = grass.parse_key_val(tgtextents, vsep=" ") - n = grass.float_or_dms(srcregion["n"][:-1]) * ( + srcregion = gs.parse_key_val(tgtextents, vsep=" ") + n = gs.float_or_dms(srcregion["n"][:-1]) * ( -1 if srcregion["n"][-1] == "S" else 1 ) - s = grass.float_or_dms(srcregion["s"][:-1]) * ( + s = gs.float_or_dms(srcregion["s"][:-1]) * ( -1 if srcregion["s"][-1] == "S" else 1 ) - e = grass.float_or_dms(srcregion["e"][:-1]) * ( + e = gs.float_or_dms(srcregion["e"][:-1]) * ( -1 if srcregion["e"][-1] == "W" else 1 ) - w = grass.float_or_dms(srcregion["w"][:-1]) * ( + w = gs.float_or_dms(srcregion["w"][:-1]) * ( -1 if srcregion["w"][-1] == "W" else 1 ) - env["GRASS_REGION"] = grass.region_env(n=n, s=s, e=e, w=w) + env["GRASS_REGION"] = gs.region_env(n=n, s=s, e=e, w=w) # v.in.region in tgt - grass.run_command("v.in.region", output=vreg, quiet=True, env=env) + gs.run_command("v.in.region", output=vreg, quiet=True, env=env) # reproject to src # switch to temp location try: - grass.run_command( + gs.run_command( "v.proj", input=vreg, output=vreg, @@ -384,29 +382,29 @@ def main(): env=src_env, ) # test if v.proj created a valid area - if grass.vector_info_topo(vreg, env=src_env)["areas"] != 1: - grass.fatal(_("Please check the 'extent' parameter")) + if gs.vector_info_topo(vreg, env=src_env)["areas"] != 1: + gs.fatal(_("Please check the 'extent' parameter")) except CalledModuleError: - grass.fatal(_("Unable to reproject to source project")) + gs.fatal(_("Unable to reproject to source project")) # set region from region vector - grass.run_command("g.region", raster=outfile, env=src_env) - grass.run_command("g.region", vector=vreg, env=src_env) + gs.run_command("g.region", raster=outfile, env=src_env) + gs.run_command("g.region", vector=vreg, env=src_env) # align to first band - grass.run_command("g.region", align=outfile, env=src_env) + gs.run_command("g.region", align=outfile, env=src_env) # get number of cells - cells = grass.region(env=src_env)["cells"] + cells = gs.region(env=src_env)["cells"] estres = math.sqrt((n - s) * (e - w) / cells) # remove from source location for multi bands import - grass.run_command( + gs.run_command( "g.remove", type="vector", name=vreg, flags="f", quiet=True, env=src_env ) # switch to target location - grass.run_command("g.remove", type="vector", name=vreg, flags="f", quiet=True) + gs.run_command("g.remove", type="vector", name=vreg, flags="f", quiet=True) - grass.message( + gs.message( _("Estimated target resolution for input band <{out}>: {res}").format( out=outfile, res=estres ) @@ -417,23 +415,23 @@ def main(): env = os.environ.copy() if options["extent"] == "input": - env["GRASS_REGION"] = grass.region_env(n=n, s=s, e=e, w=w) + env["GRASS_REGION"] = gs.region_env(n=n, s=s, e=e, w=w) res = None if tgtres == "estimated": res = estres elif tgtres == "value": res = tgtres_value - grass.message( + gs.message( _("Using given resolution for input band <{out}>: {res}").format( out=outfile, res=res ) ) # align to requested resolution - env["GRASS_REGION"] = grass.region_env(res=res, flags="a", env=env) + env["GRASS_REGION"] = gs.region_env(res=res, flags="a", env=env) else: - curr_reg = grass.region() - grass.message( + curr_reg = gs.region() + gs.message( _( "Using current region resolution for input band " "<{out}>: nsres={ns}, ewres={ew}" @@ -441,9 +439,9 @@ def main(): ) # r.proj - grass.message(_("Reprojecting <%s>...") % outfile) + gs.message(_("Reprojecting <%s>...") % outfile) try: - grass.run_command( + gs.run_command( "r.proj", project=TMPLOC, mapset="PERMANENT", @@ -456,16 +454,16 @@ def main(): env=env, ) except CalledModuleError: - grass.fatal(_("Unable to to reproject raster <%s>") % outfile) + gs.fatal(_("Unable to to reproject raster <%s>") % outfile) - if grass.raster_info(outfile)["min"] is None: - grass.fatal(_("The reprojected raster <%s> is empty") % outfile) + if gs.raster_info(outfile)["min"] is None: + gs.fatal(_("The reprojected raster <%s> is empty") % outfile) if flags["e"]: return 0 if group: - grass.run_command("i.group", group=output, input=",".join(outfiles)) + gs.run_command("i.group", group=output, input=",".join(outfiles)) # TODO: write metadata with r.support @@ -473,6 +471,6 @@ def main(): if __name__ == "__main__": - options, flags = grass.parser() + options, flags = gs.parser() atexit.register(cleanup) sys.exit(main()) diff --git a/scripts/r.in.aster/r.in.aster.py b/scripts/r.in.aster/r.in.aster.py index 41f6f14810f..24722293dde 100755 --- a/scripts/r.in.aster/r.in.aster.py +++ b/scripts/r.in.aster/r.in.aster.py @@ -52,7 +52,7 @@ # %end import os -import grass.script as grass +import grass.script as gs bands = { "L1A": { @@ -115,18 +115,18 @@ def main(): band = options["band"] # check whether gdalwarp is in path and executable - if not grass.find_program("gdalwarp", "--help"): - grass.fatal(_("gdalwarp is not in the path and executable")) + if not gs.find_program("gdalwarp", "--help"): + gs.fatal(_("gdalwarp is not in the path and executable")) # create temporary file to hold gdalwarp output before importing to GRASS - tempfile = grass.read_command("g.tempfile", pid=os.getpid()).strip() + ".tif" + tempfile = gs.read_command("g.tempfile", pid=os.getpid()).strip() + ".tif" # get projection information for current GRASS location - proj = grass.read_command("g.proj", flags="jf").strip() + proj = gs.read_command("g.proj", flags="jf").strip() # currently only runs in projected location if "XY location" in proj: - grass.fatal( + gs.fatal( _("This module needs to be run in a projected location (found: %s)") % proj ) @@ -165,40 +165,40 @@ def main(): srcfile = "HDF4_EOS:EOS_SWATH:%s:%s" % (input, dataset) import_aster(proj, srcfile, tempfile, output, band) else: - grass.fatal(_("band %s is not an available Terra/ASTER band") % band) + gs.fatal(_("band %s is not an available Terra/ASTER band") % band) elif proctype == "DEM": srcfile = input import_aster(proj, srcfile, tempfile, output, "DEM") # cleanup - grass.message(_("Cleaning up ...")) - grass.try_remove(tempfile) - grass.message(_("Done.")) + gs.message(_("Cleaning up ...")) + gs.try_remove(tempfile) + gs.message(_("Done.")) def import_aster(proj, srcfile, tempfile, output, band): # run gdalwarp with selected options (must be in $PATH) # to translate aster image to geotiff - grass.message(_("Georeferencing aster image ...")) - grass.debug("gdalwarp -t_srs %s %s %s" % (proj, srcfile, tempfile)) + gs.message(_("Georeferencing aster image ...")) + gs.debug("gdalwarp -t_srs %s %s %s" % (proj, srcfile, tempfile)) # We assume gdal is build natively for the platform GRASS is running on. # see #3258 cmd = ["gdalwarp", "-t_srs", proj, srcfile, tempfile] - p = grass.call(cmd) + p = gs.call(cmd) if p != 0: # check to see if gdalwarp executed properly return # import geotiff to GRASS - grass.message(_("Importing into GRASS ...")) + gs.message(_("Importing into GRASS ...")) outfile = "%s.%s" % (output, band) - grass.run_command("r.in.gdal", input=tempfile, output=outfile) + gs.run_command("r.in.gdal", input=tempfile, output=outfile) # write cmd history - grass.raster_history(outfile) + gs.raster_history(outfile) if __name__ == "__main__": - options, flags = grass.parser() + options, flags = gs.parser() main() diff --git a/scripts/r.in.srtm/r.in.srtm.py b/scripts/r.in.srtm/r.in.srtm.py index 271ed7ad6ec..1e4c585ac02 100755 --- a/scripts/r.in.srtm/r.in.srtm.py +++ b/scripts/r.in.srtm/r.in.srtm.py @@ -74,7 +74,7 @@ import os import shutil import atexit -import grass.script as grass +import grass.script as gs import zipfile as zfile @@ -148,9 +148,9 @@ def cleanup(): if not in_temp: return for ext in [".bil", ".hdr", ".prj", ".hgt.zip"]: - grass.try_remove(tile + ext) + gs.try_remove(tile + ext) os.chdir("..") - grass.try_rmdir(tmpdir) + gs.try_rmdir(tmpdir) def main(): @@ -166,10 +166,10 @@ def main(): one = flags["1"] # are we in LatLong location? - s = grass.read_command("g.proj", flags="j") - kv = grass.parse_key_val(s) + s = gs.read_command("g.proj", flags="j") + kv = gs.parse_key_val(s) if "+proj" not in kv.keys() or kv["+proj"] != "longlat": - grass.fatal(_("This module only operates in LatLong locations")) + gs.fatal(_("This module only operates in LatLong locations")) # use these from now on: infile = input @@ -194,18 +194,18 @@ def main(): if os.path.isfile(zipfile): # really a ZIP file? if not zfile.is_zipfile(zipfile): - grass.fatal(_("'%s' does not appear to be a valid zip file.") % zipfile) + gs.fatal(_("'%s' does not appear to be a valid zip file.") % zipfile) is_zip = True elif os.path.isfile(hgtfile): # try and see if it's already unzipped is_zip = False else: - grass.fatal(_("File '%s' or '%s' not found") % (zipfile, hgtfile)) + gs.fatal(_("File '%s' or '%s' not found") % (zipfile, hgtfile)) # make a temporary directory - tmpdir = grass.tempfile() - grass.try_remove(tmpdir) + tmpdir = gs.tempfile() + gs.try_remove(tmpdir) os.mkdir(tmpdir) if is_zip: shutil.copyfile( @@ -226,14 +226,14 @@ def main(): if is_zip: # unzip & rename data file: - grass.message(_("Extracting '%s'...") % infile) + gs.message(_("Extracting '%s'...") % infile) try: zf = zfile.ZipFile(zipfile) zf.extractall() except: - grass.fatal(_("Unable to unzip file.")) + gs.fatal(_("Unable to unzip file.")) - grass.message(_("Converting input file to BIL...")) + gs.message(_("Converting input file to BIL...")) os.rename(hgtfile, bilfile) north = tile[0] @@ -257,10 +257,10 @@ def main(): if not one: tmpl = tmpl3sec elif swbd: - grass.message(_("Attempting to import 1-arcsec SWBD data")) + gs.message(_("Attempting to import 1-arcsec SWBD data")) tmpl = swbd1sec else: - grass.message(_("Attempting to import 1-arcsec data")) + gs.message(_("Attempting to import 1-arcsec data")) tmpl = tmpl1sec header = tmpl % (ulxmap, ulymap) @@ -276,24 +276,24 @@ def main(): outf.close() try: - grass.run_command("r.in.gdal", input=bilfile, out=tileout) + gs.run_command("r.in.gdal", input=bilfile, out=tileout) except: - grass.fatal(_("Unable to import data")) + gs.fatal(_("Unable to import data")) # nice color table if not swbd: - grass.run_command("r.colors", map=tileout, color="srtm") + gs.run_command("r.colors", map=tileout, color="srtm") # write cmd history: - grass.raster_history(tileout) + gs.raster_history(tileout) - grass.message(_("Done: generated map ") + tileout) - grass.message( + gs.message(_("Done: generated map ") + tileout) + gs.message( _("(Note: Holes in the data can be closed with 'r.fillnulls' using splines)") ) if __name__ == "__main__": - options, flags = grass.parser() + options, flags = gs.parser() atexit.register(cleanup) main() diff --git a/scripts/r.in.wms/r.in.wms.py b/scripts/r.in.wms/r.in.wms.py index cc571dbd878..71780d55842 100755 --- a/scripts/r.in.wms/r.in.wms.py +++ b/scripts/r.in.wms/r.in.wms.py @@ -207,7 +207,7 @@ import os import sys -import grass.script as grass +import grass.script as gs from grass.script.utils import decode @@ -219,16 +219,16 @@ def GetRegionParams(opt_region): if len(reg_spl) > 1: reg_mapset = reg_spl[1] - if not grass.find_file(name=reg_spl[0], element="windows", mapset=reg_mapset)[ + if not gs.find_file(name=reg_spl[0], element="windows", mapset=reg_mapset)[ "name" ]: - grass.fatal(_("Region <%s> not found") % opt_region) + gs.fatal(_("Region <%s> not found") % opt_region) if opt_region: - s = grass.read_command("g.region", quiet=True, flags="ug", region=opt_region) - region_params = grass.parse_key_val(decode(s), val_type=float) + s = gs.read_command("g.region", quiet=True, flags="ug", region=opt_region) + region_params = gs.parse_key_val(decode(s), val_type=float) else: - region_params = grass.region() + region_params = gs.region() return region_params @@ -237,12 +237,12 @@ def main(): sys.path.insert(1, os.path.join(os.path.dirname(sys.path[0]), "etc", "r.in.wms")) if "GRASS" in options["driver"]: - grass.debug("Using GRASS driver") + gs.debug("Using GRASS driver") from wms_drv import WMSDrv wms = WMSDrv() elif "GDAL" in options["driver"]: - grass.debug("Using GDAL WMS driver") + gs.debug("Using GDAL WMS driver") from wms_gdal_drv import WMSGdalDrv if options["gdal_createopt"]: @@ -262,7 +262,7 @@ def main(): if options["proxy"]: wms.setProxy(options["proxy"]) if "GRASS" in options["driver"]: - grass.warning( + gs.warning( _( "The proxy will be ignored by the chosen GRASS driver. It is " "only used with the GDAL driver." @@ -272,9 +272,9 @@ def main(): options["region"] = GetRegionParams(options["region"]) fetched_map = wms.GetMap(options, flags) - grass.message(_("Importing raster map into GRASS...")) + gs.message(_("Importing raster map into GRASS...")) if not fetched_map: - grass.warning( + gs.warning( _("Nothing to import.\nNo data has been downloaded from wms server.") ) return @@ -285,5 +285,5 @@ def main(): if __name__ == "__main__": - options, flags = grass.parser() + options, flags = gs.parser() sys.exit(main()) diff --git a/scripts/r.in.wms/wms_base.py b/scripts/r.in.wms/wms_base.py index b27abc74f97..1847ca05783 100644 --- a/scripts/r.in.wms/wms_base.py +++ b/scripts/r.in.wms/wms_base.py @@ -23,7 +23,7 @@ from urllib.error import HTTPError -import grass.script as grass +import grass.script as gs from grass.exceptions import CalledModuleError @@ -43,10 +43,10 @@ def __del__(self): # removed before, implemented just in case of unexpected # stop of module for temp_file in self.temp_files_to_cleanup: - grass.try_remove(temp_file) + gs.try_remove(temp_file) def _debug(self, fn, msg): - grass.debug("%s.%s: %s" % (self.__class__.__name__, fn, msg)) + gs.debug("%s.%s: %s" % (self.__class__.__name__, fn, msg)) def _initializeParameters(self, options, flags): self._debug("_initialize_parameters", "started") @@ -76,7 +76,7 @@ def _initializeParameters(self, options, flags): if (self.params["password"] and self.params["username"] == "") or ( self.params["password"] == "" and self.params["username"] ): - grass.fatal( + gs.fatal( _( "Please insert both %s and %s parameters or none of them." % ("password", "username") @@ -90,7 +90,7 @@ def _initializeParameters(self, options, flags): and "format" not in driver_props["ignored_params"] ): if not flags["o"] and "WMS" in self.params["driver"]: - grass.warning(_("JPEG format does not support transparency")) + gs.warning(_("JPEG format does not support transparency")) self.params["format"] = drv_info.GetFormat(options["format"]) if not self.params["format"]: @@ -99,7 +99,7 @@ def _initializeParameters(self, options, flags): # TODO: get srs from Tile Service file in OnEarth_GRASS driver self.params["srs"] = int(options["srs"]) if self.params["srs"] <= 0 and "srs" not in driver_props["ignored_params"]: - grass.fatal(_("Invalid EPSG code %d") % self.params["srs"]) + gs.fatal(_("Invalid EPSG code %d") % self.params["srs"]) self.params["wms_version"] = options["wms_version"] if ( @@ -107,7 +107,7 @@ def _initializeParameters(self, options, flags): and self.params["wms_version"] == "1.1.1" ): self.params["wms_version"] = "1.3.0" - grass.warning( + gs.warning( _( "WMS version <1.3.0> will be used, because version <1.1.1> does " "not support <%s>projection" @@ -121,16 +121,16 @@ def _initializeParameters(self, options, flags): self.params["proj_name"] = "SRS" # read projection info - self.proj_location = grass.read_command("g.proj", flags="jf").rstrip("\n") + self.proj_location = gs.read_command("g.proj", flags="jf").rstrip("\n") self.proj_location = self._modifyProj(self.proj_location) self.source_epsg = str(GetEpsg(self.params["srs"])) self.target_epsg = None - target_crs = grass.parse_command("g.proj", flags="g", delimiter="=") + target_crs = gs.parse_command("g.proj", flags="g", delimiter="=") if "epsg" in target_crs.keys(): self.target_epsg = target_crs["epsg"] if self.source_epsg != self.target_epsg: - grass.warning( + gs.warning( _( "SRS differences: WMS source EPSG %s != location EPSG %s (use " "srs=%s to adjust)" @@ -138,7 +138,7 @@ def _initializeParameters(self, options, flags): % (self.source_epsg, self.target_epsg, self.target_epsg) ) - self.proj_srs = grass.read_command( + self.proj_srs = gs.read_command( "g.proj", flags="jf", epsg=str(GetEpsg(self.params["srs"])) ) self.proj_srs = self.proj_srs.rstrip("\n") @@ -146,18 +146,18 @@ def _initializeParameters(self, options, flags): self.proj_srs = self._modifyProj(self.proj_srs) if not self.proj_srs or not self.proj_location: - grass.fatal(_("Unable to get projection info")) + gs.fatal(_("Unable to get projection info")) self.region = options["region"] min_tile_size = 100 maxcols = int(options["maxcols"]) if maxcols <= min_tile_size: - grass.fatal(_("Maxcols must be greater than 100")) + gs.fatal(_("Maxcols must be greater than 100")) maxrows = int(options["maxrows"]) if maxrows <= min_tile_size: - grass.fatal(_("Maxrows must be greater than 100")) + gs.fatal(_("Maxrows must be greater than 100")) # setting optimal tile size according to maxcols and maxrows constraint # and region cols and rows @@ -197,7 +197,7 @@ def _checkIgnoeredParams(self, options, flags, driver_props): not_relevant_params.append("<" + i_param + ">") if len(not_relevant_params) > 0: - grass.warning( + gs.warning( _( "These parameter are ignored: %s\n\ %s driver does not support the parameters." @@ -211,7 +211,7 @@ def _checkIgnoeredParams(self, options, flags, driver_props): not_relevant_flags.append("<" + i_flag + ">") if len(not_relevant_flags) > 0: - grass.warning( + gs.warning( _( "These flags are ignored: %s\n\ %s driver does not support the flags." @@ -255,7 +255,7 @@ def _fetchCapabilities(self, options): if options["urlparams"]: cap_url += "&" + options["urlparams"] - grass.debug("Fetching capabilities file.\n%s" % cap_url) + gs.debug("Fetching capabilities file.\n%s" % cap_url) try: cap = self._fetchDataFromServer( @@ -263,7 +263,7 @@ def _fetchCapabilities(self, options): ) except (OSError, HTTPException) as e: if isinstance(e, HTTPError) and e.code == 401: - grass.fatal( + gs.fatal( _("Authorization failed to <%s> when fetching capabilities") % options["url"] ) @@ -277,10 +277,10 @@ def _fetchCapabilities(self, options): else: msg += "{0}".format(e) - grass.fatal(msg) + gs.fatal(msg) - grass.debug("Fetching capabilities OK") - return grass.decode(cap.read()) + gs.debug("Fetching capabilities OK") + return gs.decode(cap.read()) def _fetchDataFromServer(self, url, username=None, password=None): """!Fetch data from server""" @@ -294,7 +294,7 @@ def _fetchDataFromServer(self, url, username=None, password=None): try: return urlopen(request) except ValueError as error: - grass.fatal("%s" % error) + gs.fatal("%s" % error) def GetCapabilities(self, options): """!Get capabilities from WMS server""" @@ -308,9 +308,7 @@ def GetCapabilities(self, options): temp.write(cap) return except OSError as error: - grass.fatal( - _("Unable to open file '%s'.\n%s\n" % (capfile_output, error)) - ) + gs.fatal(_("Unable to open file '%s'.\n%s\n" % (capfile_output, error))) # print to output print(cap) @@ -352,11 +350,11 @@ def _computeBbox(self): ) ) except OSError: - grass.fatal(_("Unable to write data into tempfile")) + gs.fatal(_("Unable to write data into tempfile")) finally: temp_region_opened.close() try: - points = grass.read_command( + points = gs.read_command( "m.proj", flags="d", proj_out=self.proj_srs, @@ -367,20 +365,20 @@ def _computeBbox(self): except CalledModuleError: points = None finally: - grass.try_remove(temp_region) + gs.try_remove(temp_region) if not points: - grass.fatal(_("Unable to determine region, %s failed") % "m.proj") + gs.fatal(_("Unable to determine region, %s failed") % "m.proj") points = points.splitlines() if len(points) != 4: - grass.fatal(_("Region definition: 4 points required")) + gs.fatal(_("Region definition: 4 points required")) for point in points: try: point = list(map(float, point.split("|"))) except ValueError: - grass.fatal(_("Reprojection of region using m.proj failed.")) + gs.fatal(_("Reprojection of region using m.proj failed.")) if not bbox["maxy"]: bbox["maxy"] = point[1] bbox["miny"] = point[1] @@ -420,8 +418,8 @@ def _reprojectMap(self): if do_reproject and self.proj_srs == self.proj_location: do_reproject = False if do_reproject: - grass.message(_("Reprojecting raster...")) - self.temp_warpmap = grass.tempfile() + ".tif" + gs.message(_("Reprojecting raster...")) + self.temp_warpmap = gs.tempfile() + ".tif" if int(os.getenv("GRASS_VERBOSE", "2")) <= 2: nuldev = open(os.devnull, "w+") @@ -438,7 +436,7 @@ def _reprojectMap(self): # RGB rasters - alpha layer is added for cropping edges of projected raster try: if self.temp_map_bands_num == 3: - ps = grass.Popen( + ps = gs.Popen( [ "gdalwarp", "-s_srs", @@ -455,7 +453,7 @@ def _reprojectMap(self): ) # RGBA rasters else: - ps = grass.Popen( + ps = gs.Popen( [ "gdalwarp", "-s_srs", @@ -471,7 +469,7 @@ def _reprojectMap(self): ) ps.wait() except OSError as e: - grass.fatal( + gs.fatal( "%s \nThis can be caused by missing %s utility. " % (e, "gdalwarp") ) @@ -479,8 +477,8 @@ def _reprojectMap(self): nuldev.close() if ps.returncode != 0: - grass.fatal(_("%s failed") % "gdalwarp") - grass.try_remove(self.temp_map) + gs.fatal(_("%s failed") % "gdalwarp") + gs.try_remove(self.temp_map) # raster projection is same as projection of location else: self.temp_warpmap = self.temp_map @@ -494,9 +492,9 @@ def _tempfile(self): @return string path to temp_file """ - temp_file = grass.tempfile() + temp_file = gs.tempfile() if temp_file is None: - grass.fatal(_("Unable to create temporary files")) + gs.fatal(_("Unable to create temporary files")) # list of created tempfiles for destructor self.temp_files_to_cleanup.append(temp_file) @@ -520,11 +518,11 @@ def __init__(self, opt_output, cleanup_bands): maps = [] for suffix in (".red", ".green", ".blue", ".alpha", self.original_mask_suffix): rast = self.opt_output + suffix - if grass.find_file(rast, element="cell", mapset=".")["file"]: + if gs.find_file(rast, element="cell", mapset=".")["file"]: maps.append(rast) if len(maps) != 0: - grass.fatal( + gs.fatal( _( "Please change output name, or change names of these rasters: %s, " "module needs to create this temporary maps during execution." @@ -537,34 +535,34 @@ def __del__(self): if self.cleanup_mask: # clear temporary mask, which was set by module try: - grass.run_command("r.mask", quiet=True, flags="r") + gs.run_command("r.mask", quiet=True, flags="r") except CalledModuleError: - grass.fatal(_("%s failed") % "r.mask") + gs.fatal(_("%s failed") % "r.mask") # restore original mask, if exists - if grass.find_file( + if gs.find_file( self.opt_output + self.original_mask_suffix, element="cell", mapset="." )["name"]: try: mask_copy = self.opt_output + self.original_mask_suffix - grass.run_command("g.copy", quiet=True, raster=mask_copy + ",MASK") + gs.run_command("g.copy", quiet=True, raster=mask_copy + ",MASK") except CalledModuleError: - grass.fatal(_("%s failed") % "g.copy") + gs.fatal(_("%s failed") % "g.copy") # remove temporary created rasters maps = [] rast = self.opt_output + ".alpha" - if grass.find_file(rast, element="cell", mapset=".")["file"]: + if gs.find_file(rast, element="cell", mapset=".")["file"]: maps.append(rast) if self.cleanup_bands: for suffix in (".red", ".green", ".blue", self.original_mask_suffix): rast = self.opt_output + suffix - if grass.find_file(rast, element="cell", mapset=".")["file"]: + if gs.find_file(rast, element="cell", mapset=".")["file"]: maps.append(rast) if maps: - grass.run_command( + gs.run_command( "g.remove", quiet=True, flags="fb", type="raster", name=",".join(maps) ) @@ -572,7 +570,7 @@ def __del__(self): if "GRASS_REGION" in os.environ.keys(): os.environ.pop("GRASS_REGION") - maplist = grass.read_command( + maplist = gs.read_command( "g.list", type="raster", pattern="%s*" % (self.opt_output), @@ -581,21 +579,21 @@ def __del__(self): ).rstrip("\n") if len(maplist) == 0: - grass.fatal(_("WMS import failed, nothing imported")) + gs.fatal(_("WMS import failed, nothing imported")) else: for raster in maplist.split(","): - grass.raster_history(raster, overwrite=True) - grass.run_command( + gs.raster_history(raster, overwrite=True) + gs.run_command( "r.support", map=raster, description="generated by r.in.wms" ) - grass.message(_("<%s> created.") % raster) + gs.message(_("<%s> created.") % raster) def ImportMapIntoGRASS(self, raster): """!Import raster into GRASS.""" # importing temp_map into GRASS try: # do not use -o flag ! - grass.run_command( + gs.run_command( "r.in.gdal", flags="o", quiet=True, @@ -604,38 +602,34 @@ def ImportMapIntoGRASS(self, raster): output=self.opt_output, ) except CalledModuleError: - grass.fatal(_("%s failed") % "r.in.gdal") + gs.fatal(_("%s failed") % "r.in.gdal") # information for destructor to cleanup temp_layers, created # with r.in.gdal # setting region for full extend of imported raster - if grass.find_file(self.opt_output + ".red", element="cell", mapset=".")[ - "file" - ]: + if gs.find_file(self.opt_output + ".red", element="cell", mapset=".")["file"]: region_map = self.opt_output + ".red" else: region_map = self.opt_output - os.environ["GRASS_REGION"] = grass.region_env(rast=region_map) + os.environ["GRASS_REGION"] = gs.region_env(rast=region_map) # mask created from alpha layer, which describes real extend # of warped layer (may not be a rectangle), also mask contains # transparent parts of raster - if grass.find_file(self.opt_output + ".alpha", element="cell", mapset=".")[ - "name" - ]: + if gs.find_file(self.opt_output + ".alpha", element="cell", mapset=".")["name"]: # saving current mask (if exists) into temp raster - if grass.find_file("MASK", element="cell", mapset=".")["name"]: + if gs.find_file("MASK", element="cell", mapset=".")["name"]: try: mask_copy = self.opt_output + self.original_mask_suffix - grass.run_command("g.copy", quiet=True, raster="MASK," + mask_copy) + gs.run_command("g.copy", quiet=True, raster="MASK," + mask_copy) except CalledModuleError: - grass.fatal(_("%s failed") % "g.copy") + gs.fatal(_("%s failed") % "g.copy") # info for destructor self.cleanup_mask = True try: - grass.run_command( + gs.run_command( "r.mask", quiet=True, overwrite=True, @@ -644,24 +638,24 @@ def ImportMapIntoGRASS(self, raster): raster=self.opt_output + ".alpha", ) except CalledModuleError: - grass.fatal(_("%s failed") % "r.mask") + gs.fatal(_("%s failed") % "r.mask") if not self.cleanup_bands: # use the MASK to set NULL values for suffix in (".red", ".green", ".blue"): rast = self.opt_output + suffix - if grass.find_file(rast, element="cell", mapset=".")["file"]: - grass.run_command( + if gs.find_file(rast, element="cell", mapset=".")["file"]: + gs.run_command( "g.rename", rast="%s,%s" % (rast, rast + "_null"), quiet=True, ) - grass.run_command( + gs.run_command( "r.mapcalc", expression="%s = %s" % (rast, rast + "_null"), quiet=True, ) - grass.run_command( + gs.run_command( "g.remove", type="raster", name="%s" % (rast + "_null"), @@ -671,13 +665,11 @@ def ImportMapIntoGRASS(self, raster): # TODO one band + alpha band? if ( - grass.find_file(self.opt_output + ".red", element="cell", mapset=".")[ - "file" - ] + gs.find_file(self.opt_output + ".red", element="cell", mapset=".")["file"] and self.cleanup_bands ): try: - grass.run_command( + gs.run_command( "r.composite", quiet=True, overwrite=True, @@ -687,7 +679,7 @@ def ImportMapIntoGRASS(self, raster): output=self.opt_output, ) except CalledModuleError: - grass.fatal(_("%s failed") % "r.composite") + gs.fatal(_("%s failed") % "r.composite") class WMSDriversInfo: diff --git a/scripts/r.in.wms/wms_cap_parsers.py b/scripts/r.in.wms/wms_cap_parsers.py index 4137c114deb..bf001d5d145 100644 --- a/scripts/r.in.wms/wms_cap_parsers.py +++ b/scripts/r.in.wms/wms_cap_parsers.py @@ -22,7 +22,7 @@ from xml.etree.ElementTree import ParseError import xml.etree.ElementTree as etree -import grass.script as grass +import grass.script as gs class BaseCapabilitiesTree(etree.ElementTree): @@ -99,7 +99,7 @@ def __init__(self, cap_file, force_version=None): BaseCapabilitiesTree.__init__(self, cap_file) self.xml_ns = WMSXMLNsHandler(self) - grass.debug("Checking WMS capabilities tree.", 4) + gs.debug("Checking WMS capabilities tree.", 4) if "version" not in self.getroot().attrib: raise ParseError( @@ -125,7 +125,7 @@ def __init__(self, cap_file, force_version=None): self._checkFormats(capability) self._checkLayerTree(root_layer) - grass.debug("Check of WMS capabilities tree was finished.", 4) + gs.debug("Check of WMS capabilities tree was finished.", 4) def _checkFormats(self, capability): """!Check if format element is defined.""" @@ -189,7 +189,7 @@ def _initLayer(self, layer, parent_layer): for s in styles: s_name = s.find(self.xml_ns.Ns("Name")) if s_name is None or not s_name.text: - grass.debug("Removed invalid