Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions python/grass/gunittest/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,11 @@ def do_doctest_gettext_workaround() -> None:
This should be considered for the future. The second option is to define
dummy underscore function and one other function which creates the right
environment to satisfy all. This is done by this function.

The default display hook assigns the last printed value to ``_`` in builtins,
replacing the gettext function. The display hook is replaced both in
``sys.displayhook`` and in ``sys.__displayhook__`` because doctest sets
``sys.displayhook`` to ``sys.__displayhook__`` before running each example.
"""

def new_displayhook(string: str | None) -> None:
Expand All @@ -67,6 +72,7 @@ def new_translator(string: str) -> str:
return string

sys.displayhook = new_displayhook
sys.__displayhook__ = new_displayhook

import builtins

Expand Down
20 changes: 8 additions & 12 deletions python/grass/script/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -202,8 +202,8 @@ def get_commands(*, env=None):

>>> cmds = list(get_commands()[0])
>>> cmds.sort()
>>> cmds[:5]
['d.barscale', 'd.colorlist', 'd.colortable', 'd.correlate', 'd.erase']
>>> "g.region" in cmds
True
"""
if not env:
env = os.environ
Expand Down Expand Up @@ -520,7 +520,7 @@ def start_command(

>>> p = start_command("g.gisenv", stdout=subprocess.PIPE)
>>> print(p) # doctest: +ELLIPSIS
<...Popen object at 0x...>
<...Popen...>
>>> print(p.communicate()[0]) # doctest: +SKIP
GISDBASE='/opt/grass-data';
LOCATION_NAME='spearfish60';
Expand Down Expand Up @@ -627,7 +627,7 @@ def pipe_command(*args, **kwargs):

>>> p = pipe_command("g.gisenv")
>>> print(p) # doctest: +ELLIPSIS
<....Popen object at 0x...>
<...Popen...>
>>> print(p.communicate()[0]) # doctest: +SKIP
GISDBASE='/opt/grass-data';
LOCATION_NAME='spearfish60';
Expand Down Expand Up @@ -761,7 +761,6 @@ def write_command(*args, **kwargs):
... stdin="%s|%s" % (635818.8, 221342.4),
... output="view_point",
... )
0

See :func:`start_command()` for details about parameters and usage.

Expand Down Expand Up @@ -1147,8 +1146,8 @@ def tempname(length: int, lowercase: bool = False) -> str:
:Example:
.. code-block:: pycon

>>> tempname(12)
'tmp_MxMa1kAS13s9'
>>> tempname(12) # doctest: +ELLIPSIS
'tmp_...'

.. seealso:: functions :func:`~grass.script.utils.append_uuid()`,
:func:`~grass.script.utils.append_random()`,
Expand Down Expand Up @@ -2282,11 +2281,8 @@ def version():

.. code-block:: pycon

>>> print(version())
{'proj4': '4.8.0', 'geos': '3.3.5', 'libgis_revision': '52468',
'libgis_date': '2012-07-27 22:53:30 +0200 (Fri, 27 Jul 2012)',
'version': '7.0.svn', 'date': '2012', 'gdal': '2.0dev',
'revision': '53670'}
>>> print(version()) # doctest: +ELLIPSIS
{'version': '...', 'date': '...', 'revision': '...', ...}

"""
data = parse_command("g.version", flags="rge", errors="ignore")
Expand Down
18 changes: 5 additions & 13 deletions python/grass/script/db.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,11 +37,9 @@ def db_describe(table, env=None, **args):
.. code-block:: pycon

>>> run_command("g.copy", vector="firestations,myfirestations")
0
>>> db_describe("myfirestations") # doctest: +ELLIPSIS
{'nrows': 71, 'cols': [['cat', 'INTEGER', '20'], ... 'ncols': 22}
{'ncols': 22, 'nrows': 71, 'cols': [['cat', 'INTEGER', '20'], ...]}
>>> run_command("g.remove", flags="f", type="vector", name="myfirestations")
0

:param str table: table name
:param list args:
Expand Down Expand Up @@ -83,11 +81,9 @@ def db_table_exist(table, env=None, **args):
(check db_connection()).

>>> run_command("g.copy", vector="firestations,myfirestations")
0
>>> db_table_exist("myfirestations")
True
>>> run_command("g.remove", flags="f", type="vector", name="myfirestations")
0

:param str table: table name
:param args:
Expand Down Expand Up @@ -119,8 +115,8 @@ def db_connection(force=False, env=None):
:Example:
.. code-block:: pycon

>>> db_connection()
{'group': '', 'schema': '', 'driver': 'sqlite', 'database': '$GISDBASE/$LOCATION_NAME/$MAPSET/sqlite/sqlite.db'}
>>> db_connection(force=True)
{'driver': 'sqlite', 'database': '$GISDBASE/$LOCATION_NAME/$MAPSET/sqlite/sqlite.db', 'schema': '', 'group': ''}

:param force: True to set up default DB connection if not defined
:param env: environment
Expand Down Expand Up @@ -150,7 +146,6 @@ def db_select(sql=None, filename=None, table=None, env=None, **args):
.. code-block:: pycon

>>> run_command("g.copy", vector="firestations,myfirestations")
0
>>> db_select(sql="SELECT cat,CITY FROM myfirestations WHERE cat < 4")
(('1', 'Morrisville'), ('2', 'Morrisville'), ('3', 'Apex'))

Expand All @@ -161,7 +156,6 @@ def db_select(sql=None, filename=None, table=None, env=None, **args):
>>> db_select(table="myfirestations") # doctest: +ELLIPSIS
(('1', '24', 'Morrisville #3', ... 'HS2A', '1.37'))
>>> run_command("g.remove", flags="f", type="vector", name="myfirestations")
0

:param str sql: SQL statement to perform (or None)
:param str filename: name of file with SQL statements (or None)
Expand Down Expand Up @@ -208,12 +202,10 @@ def db_table_in_vector(table, mapset=".", env=None):
It returns None if no vectors are connected to the table.

>>> run_command("g.copy", vector="firestations,myfirestations")
0
>>> db_table_in_vector("myfirestations")
['myfirestations@user1']
>>> db_table_in_vector("myfirestations") # doctest: +ELLIPSIS
['myfirestations@...']
>>> db_table_in_vector("mfirestations")
>>> run_command("g.remove", flags="f", type="vector", name="myfirestations")
0

:param str table: name of table to query
:param env: environment
Expand Down
32 changes: 20 additions & 12 deletions python/grass/script/imagery.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,19 +46,27 @@ def group_to_dict(
:Example:
.. code-block:: pycon

>>> run_command("g.copy", raster="lsat7_2000_10,lsat7_2000_10")
>>> run_command("r.support", raster="lsat7_2000_10", semantic_label="L8_1")
>>> run_command("g.copy", raster="lsat7_2000_20,lsat7_2000_20")
>>> run_command("r.support", raster="lsat7_2000_20", semantic_label="L8_2")
>>> run_command("g.copy", raster="lsat7_2000_30,lsat7_2000_30")
>>> run_command("r.support", raster="lsat7_2000_30", semantic_label="L8_3")
>>> run_command("i.group", group="L8_group",
>>> input="lsat7_2000_10,lsat7_2000_20,lsat7_2000_30")
>>> import grass.script as gs
>>> gs.run_command("g.copy", raster="lsat7_2002_10,lsat7_2002_10")
>>> gs.run_command("r.support", map="lsat7_2002_10", semantic_label="L8_1")
>>> gs.run_command("g.copy", raster="lsat7_2002_20,lsat7_2002_20")
>>> gs.run_command("r.support", map="lsat7_2002_20", semantic_label="L8_2")
>>> gs.run_command("g.copy", raster="lsat7_2002_30,lsat7_2002_30")
>>> gs.run_command("r.support", map="lsat7_2002_30", semantic_label="L8_3")
>>> gs.run_command(
... "i.group",
... group="L8_group",
... input="lsat7_2002_10,lsat7_2002_20,lsat7_2002_30",
... )
>>> group_to_dict("L8_group") # doctest: +ELLIPSIS
{"L8_1": "lsat7_2000_10", ... "L8_3": "lsat7_2000_30"}
>>> run_command("g.remove", flags="f", type="group", name="L8_group")
>>> run_command("g.remove", flags="f", type="raster",
>>> name="lsat7_2000_10,lsat7_2000_20,lsat7_2000_30")
{'L8_1': 'lsat7_2002_10@...', ... 'L8_3': 'lsat7_2002_30@...'}
>>> gs.run_command("g.remove", flags="f", type="group", name="L8_group")
>>> gs.run_command(
... "g.remove",
... flags="f",
... type="raster",
... name="lsat7_2002_10,lsat7_2002_20,lsat7_2002_30",
... )

:param str imagery_group_name: Name of the imagery group to process (or None)
:param str subgroup: Name of the imagery sub-group to process (or None)
Expand Down
86 changes: 56 additions & 30 deletions python/grass/script/raster.py
Original file line number Diff line number Diff line change
Expand Up @@ -84,8 +84,9 @@ def raster_info(map, env=None):
:Example:
.. code-block:: pycon

>>> raster_info("elevation") # doctest: +ELLIPSIS
{'creator': '"helena"', 'cols': '1500' ... 'south': 215000.0}
>>> raster_info("elevation") # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE
{'north': 228500.0, 'south': 215000.0, ... 'cols': '1500', ... 'creator':
'"helena"', ...}

:param str map: map name
:param env: environment
Expand Down Expand Up @@ -246,7 +247,7 @@ def raster_what(map, coord, env=None, localized=False):
"""Interface to r.what

>>> raster_what("elevation", [[640000, 228000]])
[{'elevation': {'color': '255:214:000', 'label': '', 'value': '102.479'}}]
[{'elevation': {'value': '102.479', 'label': '', 'color': '255:214:000'}}]

:param str map: the map name
:param list coord: a list of list containing all the point that you want to query
Expand Down Expand Up @@ -302,9 +303,12 @@ class MaskManager:
raster which represents the mask. The mask is deactivated at the end of the
context by the context manager and the raster is removed.

>>> import grass.script as gs
>>> gs.run_command("g.region", raster="elevation")
>>> with gs.MaskManager():
... gs.run_command("r.mask", raster="state_boundary")
... gs.parse_command("r.univar", map="elevation", format="json")
... gs.run_command("r.mask", raster="lakes")
Comment on lines -306 to +309

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Find more about the old raster. I don't really like changing layers like that

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

state_boundary was added in OSGeo#2392 (Feb 2025) as an illustrative name. It is not in nc_spm_full_v2beta1, nc_spm_08_grass7, or anywhere else in the repository, so the example could never run. The closest real raster is ncmask_500m, but it covers the whole elevation region, so the mask would change nothing (n stays 2025000). lakes does mask cells (n = 36011), so the example shows an effect. Happy to switch to ncmask_500m if you prefer keeping the state-wide idea.


Generated by Claude Code

... gs.parse_command("r.univar", map="elevation", format="json")["n"]
36011

The *mask_name* can be a name of an existing raster map and in that case,
that raster map is used directly as is. If the raster map does not exist,
Expand All @@ -314,19 +318,22 @@ class MaskManager:
The mask is disabled at the end of the context, but the raster map is not
removed.

>>> with gs.MaskManager(mask_name="state_boundary"):
... gs.parse_command("r.univar", map="elevation", format="json")
>>> with gs.MaskManager(mask_name="lakes@PERMANENT"):
... gs.parse_command("r.univar", map="elevation", format="json")["n"]
36011

Example using explicit activate and deactivate:

>>> manager = gs.MaskManager()
>>> manager.activate()
>>> manager.activate() # doctest: +ELLIPSIS
<...MaskManager object at ...>
>>> try:
... # Create mask with r.mask
... gs.run_command("r.mask", raster="state_boundary")
... gs.parse_command("r.univar", map="elevation", format="json")
... gs.run_command("r.mask", raster="lakes")
... gs.parse_command("r.univar", map="elevation", format="json")["n"]
... finally:
... manager.deactivate()
36011


Note the difference between using the name of an existing raster map directly
Expand All @@ -353,11 +360,9 @@ class MaskManager:

>>> with gs.MaskManager() as manager:
... gs.run_command(
"r.mapcalc", expression=f"{manager.mask_name} = row() < col()"
)
... gs.run_command(
"r.mapcalc", expression=f"masked_elevation = elevation"
)
... "r.mapcalc", expression=f"{manager.mask_name} = row() < col()"
... )
... gs.run_command("r.mapcalc", expression="masked_elevation = elevation")

In the background, this class manages the `GRASS_MASK` environment variable.
It modifies the current system environment or the one provided. It does not
Expand All @@ -375,7 +380,9 @@ class MaskManager:
... env=manager.env,
... )
... gs.run_command(
... "r.mapcalc", expression=f"masked_elevation = elevation", env=manager.env
... "r.mapcalc",
... expression="masked_elevation_env = elevation",
... env=manager.env,
... )
"""

Expand Down Expand Up @@ -471,8 +478,11 @@ class RegionManager:

Example with explicit region parameters:

>>> import grass.script as gs
>>> gs.run_command("g.region", raster="elevation")
>>> with gs.RegionManager(n=226000, s=222000, w=634000, e=638000):
... gs.parse_command("r.univar", map="elevation", format="json")
... gs.parse_command("r.univar", map="elevation", format="json")["cells"]
160000

Example matching a raster map's region:

Expand All @@ -483,19 +493,22 @@ class RegionManager:

>>> with gs.RegionManager():
... gs.run_command("g.region", n=226000, s=222000, w=634000, e=638000)
... gs.parse_command("r.univar", map="elevation", format="json")
... gs.parse_command("r.univar", map="elevation", format="json")["cells"]
160000

Example using a saved region:

>>> gs.run_command("g.region", save="study_area", s=1000, n=1100, w=1000, e=1100)
>>> with gs.RegionManager(region="study_area"):
... gs.parse_command("r.univar", map="elevation", format="json")
... gs.parse_command("r.univar", map="elevation", format="json")["cells"]
100

Example using :py:meth:`~grass.script.raster.RegionManager.set_region`:

>>> with gs.RegionManager() as manager:
... manager.set_region(n=226000, s=222000, w=634000, e=638000)
... gs.parse_command("r.univar", map="elevation", format="json")
... gs.parse_command("r.univar", map="elevation", format="json")["cells"]
160000

Example using :py:meth:`~grass.script.raster.RegionManager.save` to store the temporarily
modified region under a persistent name so it can be reused after the context exits:
Expand All @@ -506,9 +519,12 @@ class RegionManager:
Example using explicit activate and deactivate:

>>> manager = gs.RegionManager(raster="elevation")
>>> manager.activate()
>>> manager.activate() # doctest: +ELLIPSIS
<...RegionManager object at ...>
>>> try:
... gs.run_command("r.slope.aspect", elevation="elevation", slope="slope")
... gs.run_command(
... "r.slope.aspect", elevation="elevation", slope="slope_activated"
... )
... finally:
... manager.deactivate()

Expand Down Expand Up @@ -614,26 +630,34 @@ class RegionManagerEnv:

Example with explicit region parameters:

>>> import grass.script as gs
>>> gs.run_command("g.region", raster="elevation")
>>> with gs.RegionManagerEnv(n=226000, s=222000, w=634000, e=638000):
... gs.parse_command("r.univar", map="elevation", format="json")
... gs.parse_command("r.univar", map="elevation", format="json")["cells"]
160000

Example using a saved region:

>>> gs.run_command("g.region", save="study_area", s=1000, n=1100, w=1000, e=1100)
>>> with gs.RegionManagerEnv(region="study_area"):
... gs.parse_command("r.univar", map="elevation", format="json")
>>> gs.run_command(
... "g.region", save="study_area_env", s=1000, n=1100, w=1000, e=1100
... )
>>> with gs.RegionManagerEnv(region="study_area_env"):
... gs.parse_command("r.univar", map="elevation", format="json")["cells"]
100

Example with :py:meth:`.set_region`:

>>> with gs.RegionManagerEnv() as manager:
... manager.set_region(n=226000, s=222000, w=634000, e=638000)
... gs.parse_command("r.univar", map="elevation", format="json")
... gs.parse_command("r.univar", map="elevation", format="json")["cells"]
64

This is identical to:

>>> with gs.RegionManagerEnv() as manager:
... manager.env["GRASS_REGION"] = gs.region_env()
... gs.parse_command("r.univar", map="elevation", format="json")
... gs.parse_command("r.univar", map="elevation", format="json")["cells"]
1010600

Example using :py:meth:`.save`: to store the temporarily modified region under
a persistent name so it can be reused after the context exits:
Expand All @@ -644,12 +668,14 @@ class RegionManagerEnv:
Example using explicit activate and deactivate:

>>> manager = gs.RegionManagerEnv(raster="elevation")
>>> manager.activate()
>>> manager.activate() # doctest: +ELLIPSIS
<...RegionManagerEnv object at ...>
>>> try:
... manager.set_region(n=226000, s=222000, w=634000, e=638000)
... gs.parse_command("r.univar", map="elevation", format="json")
... gs.parse_command("r.univar", map="elevation", format="json")["cells"]
... finally:
... manager.deactivate()
160000

.. caution::

Expand Down
Loading
Loading