diff --git a/.flake8 b/.flake8 index f340bac1ac9..84c3826b32c 100644 --- a/.flake8 +++ b/.flake8 @@ -20,8 +20,8 @@ per-file-ignores = # F841 local variable assigned to but never used # E741 ambiguous variable name 'l' __init__.py: F401, F403 - lib/init/grass.py: E501, E722, F821, F841, W605 - utils/mkrest.py: E501, W605 + lib/init/grass.py: E722, F821, F841, W605 + utils/mkrest.py: W605 utils/gitlog2changelog.py: E722, E712, W605 utils/g.html2man/ggroff.py: W605 man/build_check_rest.py: F403, F405 @@ -36,98 +36,87 @@ per-file-ignores = man/build_keywords.py: F403, F405, E722 man/build_topics.py: F403, F405, E722 man/build_html.py: E501 - man/build_rest.py: E501 - imagery/i.atcorr/create_iwave.py: E501, F632, F821, W293 + imagery/i.atcorr/create_iwave.py: F632, F821, W293 doc/python/raster_example_ctypes.py: F403, F405 doc/python/vector_example_ctypes.py: F403, F405 doc/python/m.distance.py: F403, F405, E501 doc/gui/wxpython/example/dialogs.py: F401 - doc/gui/wxpython/example/g.gui.example.py: E501 - locale/grass_po_stats.py: E122, E128, E231, E401, E501, E722, E741 - gui/scripts/d.rast3d.py: E501 + locale/grass_po_stats.py: E122, E128, E231, E401, E722, E741 gui/scripts/d.wms.py: E501 - gui/wxpython/core/debug.py: E501 - gui/wxpython/core/gcmd.py: E402, E501 - gui/wxpython/core/giface.py: E501 + gui/wxpython/core/gcmd.py: E402 gui/wxpython/core/gthread.py: F841 gui/wxpython/core/gconsole.py: E722, W605 gui/wxpython/core/globalvar.py: W605 - gui/wxpython/core/toolboxes.py: E722, E501 + gui/wxpython/core/toolboxes.py: E722 gui/wxpython/core/utils.py: E722, F841, W605 - gui/wxpython/core/workspace.py: E722, E501 - gui/wxpython/core/render.py: E722, F841, E501 - gui/wxpython/core/ws.py: F841, E501 + gui/wxpython/core/workspace.py: E722 + gui/wxpython/core/render.py: E722, F841 + gui/wxpython/core/ws.py: F841 gui/wxpython/core/settings.py: E722 gui/wxpython/core/watchdog.py: E402 - gui/wxpython/datacatalog/tree.py: E731, E402, E501 - gui/wxpython/dbmgr/base.py: E501, E722, F841 - gui/wxpython/dbmgr/dialogs.py: E501, F841, E722 - gui/wxpython/dbmgr/sqlbuilder.py: E501, E722, F841 - gui/wxpython/dbmgr/manager.py: E501, E722 + gui/wxpython/datacatalog/tree.py: E731, E402 + gui/wxpython/dbmgr/base.py: E722, F841 + gui/wxpython/dbmgr/dialogs.py: F841, E722 + gui/wxpython/dbmgr/sqlbuilder.py: E722, F841 + gui/wxpython/dbmgr/manager.py: E722 gui/wxpython/dbmgr/vinfo.py: F841 - gui/wxpython/docs/wxgui_sphinx/conf.py: E402, E501 + gui/wxpython/docs/wxgui_sphinx/conf.py: E402, W291 gui/wxpython/gcp/g.gui.gcp.py: F841 - gui/wxpython/gcp/manager.py: E501, F841, E722 + gui/wxpython/gcp/manager.py: F841, E722 gui/wxpython/gcp/mapdisplay.py: F841 - gui/wxpython/gmodeler/*: E501 gui/wxpython/gui_core/*: F841, E266, E722, W605 - gui/wxpython/gui_core/dialogs.py: E501, E722, F841, W605 - gui/wxpython/gui_core/forms.py: E501, E722, F841 - gui/wxpython/gui_core/ghelp.py: E501, E722 - gui/wxpython/gui_core/gselect.py: E501, F841, E266, E722 - gui/wxpython/gui_core/preferences.py: E501, E266, F841 - gui/wxpython/gui_core/treeview.py: E501, F841 - gui/wxpython/gui_core/widgets.py: E501, F841, E722, E266 - gui/wxpython/image2target/*: F841, E722, E265, E501 - gui/wxpython/iscatt/*: F841, E722, E741, F405, F403, E501 - gui/wxpython/lmgr/giface.py: E501, E741 - gui/wxpython/lmgr/frame.py: F841, E722, W605, E501 + gui/wxpython/gui_core/dialogs.py: E722, F841, W605 + gui/wxpython/gui_core/forms.py: E722, F841 + gui/wxpython/gui_core/ghelp.py: E722 + gui/wxpython/gui_core/gselect.py: F841, E266, E722 + gui/wxpython/gui_core/preferences.py: E266, F841 + gui/wxpython/gui_core/treeview.py: F841 + gui/wxpython/gui_core/widgets.py: F841, E722, E266 + gui/wxpython/image2target/*: F841, E722, E265 + gui/wxpython/image2target/g.gui.image2target.py: E501, E265, F841 + gui/wxpython/iscatt/*: F841, E722, E741, F405, F403 + gui/wxpython/lmgr/giface.py: E741 + gui/wxpython/lmgr/frame.py: F841, E722, W605 # layertree still includes some formatting issues (it is ignored by Black) - gui/wxpython/lmgr/layertree.py: E722, E266, W504, E225, E501 + gui/wxpython/lmgr/layertree.py: E722, E266, W504, E225 gui/wxpython/lmgr/workspace.py: F841 - gui/wxpython/modules/*: F841, E722, W605, E501 - gui/wxpython/nviz/*: F841, E266, E722, W605, F403, F405, E501 - gui/wxpython/photo2image/*: F841, E722, E265, E501 - gui/wxpython/psmap/*: F841, E266, E722, F405, F403, E501 - gui/wxpython/vdigit/*: F841, E722, E741, F405, F403, E501 - gui/wxpython/vnet/*: F841, E501 + gui/wxpython/modules/*: F841, E722, W605 + gui/wxpython/nviz/*: F841, E266, E722, W605, F403, F405 + gui/wxpython/photo2image/*: F841, E722, E265 + gui/wxpython/photo2image/g.gui.photo2image.py: E501, F841 + gui/wxpython/psmap/*: F841, E266, E722, F405, F403 + gui/wxpython/vdigit/*: F841, E722, E741, F405, F403 + gui/wxpython/vnet/*: F841 gui/wxpython/wxgui.py: F841 gui/wxpython/animation/g.gui.animation.py: E501 gui/wxpython/animation/mapwindow.py: F841 - gui/wxpython/animation/provider.py: F841, E501 - gui/wxpython/animation/temporal_manager.py: E501 - gui/wxpython/tplot/frame.py: F841, E722 + gui/wxpython/animation/provider.py: F841 + gui/wxpython/tplot/frame.py: F841, E722, E741 gui/wxpython/tplot/g.gui.tplot.py: E501 gui/wxpython/rdigit/g.gui.rdigit.py: F841 - gui/wxpython/rdigit/toolbars.py: E501 - gui/wxpython/iclass/dialogs.py: E741, E501 + gui/wxpython/iclass/dialogs.py: E741 gui/wxpython/iclass/digit.py: F405, F403 - gui/wxpython/iclass/frame.py: F405, F403, E501 + gui/wxpython/iclass/frame.py: F405, F403 gui/wxpython/iclass/g.gui.iclass.py: E501 gui/wxpython/iclass/statistics.py: F841, F405, F403 - gui/wxpython/wxplot/dialogs.py: E501 gui/wxpython/wxplot/histogram.py: E722 gui/wxpython/wxplot/profile.py: F841, E722 gui/wxpython/wxplot/base.py: F841, E722 - gui/wxpython/wxplot/scatter.py: E501 - gui/wxpython/location_wizard/dialogs.py: F841, E501 + gui/wxpython/location_wizard/dialogs.py: F841 gui/wxpython/location_wizard/wizard.py: E722 - gui/wxpython/mapdisp/frame.py: E501 - gui/wxpython/mapdisp/main.py: E722, E501 + gui/wxpython/mapdisp/main.py: E722 gui/wxpython/mapdisp/test_mapdisp.py: E501 - gui/wxpython/mapdisp/toolbars.py: E501 - gui/wxpython/mapdisp/statusbar.py: F841, E501 + gui/wxpython/mapdisp/statusbar.py: F841 gui/wxpython/mapswipe/g.gui.mapswipe.py: E501 - gui/wxpython/mapwin/base.py: E722, E501 - gui/wxpython/mapwin/buffered.py: E722, E501 - gui/wxpython/mapwin/decorations.py: E501 + gui/wxpython/mapwin/base.py: E722 + gui/wxpython/mapwin/buffered.py: E722 gui/wxpython/mapwin/graphics.py: E722 - gui/wxpython/startup/locdownload.py: E722, E402, E501 - gui/wxpython/timeline/g.gui.timeline.py: E501 - gui/wxpython/tools/build_modules_xml.py: E722, E501 + gui/wxpython/startup/locdownload.py: E722, E402 + gui/wxpython/timeline/g.gui.timeline.py: E501, E741 + gui/wxpython/timeline/frame.py: E741 + gui/wxpython/tools/build_modules_xml.py: E722 gui/wxpython/web_services/cap_interface.py: E501 - gui/wxpython/web_services/dialogs.py: E501 - gui/wxpython/web_services/widgets.py: F841, E741, W605, E402, E501 + gui/wxpython/web_services/widgets.py: F841, E741, W605, E402 gui/wxpython/rlisetup/frame.py: E741 gui/wxpython/rlisetup/sampling_frame.py: F841 gui/wxpython/rlisetup/wizard.py: E722, E741 @@ -138,57 +127,43 @@ per-file-ignores = python/grass/pydispatch/saferef.py: F821 # C wrappers call libgis.G_gisinit before importing other modules. # TODO: Is this really needed? - python/grass/pygrass/vector/__init__.py: E402, - python/grass/pygrass/raster/__init__.py: E402, - python/grass/gunittest/*.py: E501 # These are mainly just todo comments - python/grass/gunittest/gmodules.py: E501, W605 + python/grass/pygrass/vector/__init__.py: E402 + python/grass/pygrass/raster/__init__.py: E402 + python/grass/gunittest/gmodules.py: W605 + python/grass/gunittest/invoker.py: E721 python/grass/pygrass/vector/geometry.py: W605 - python/grass/pygrass/vector/table.py: E501 - python/grass/pygrass/vector/__init__.py: E501, E402 - python/grass/pygrass/modules/interface/*.py: E501, F401 - python/grass/pygrass/modules/interface/module.py: E501, W605 - python/grass/pygrass/modules/interface/parameter.py: E501, W605 - python/grass/pygrass/modules/grid/*.py: E501, F401 - python/grass/pygrass/raster/*.py: E501 + python/grass/pygrass/vector/__init__.py: E402 + python/grass/pygrass/modules/interface/*.py: F401 + python/grass/pygrass/modules/interface/module.py: W605 + python/grass/pygrass/modules/interface/parameter.py: W605 + python/grass/pygrass/modules/grid/*.py: F401 python/grass/pygrass/raster/rowio.py: E741 - python/grass/pygrass/rpc/__init__.py: E501, F401, F403 - python/grass/pygrass/utils.py: E402, E501 - python/grass/script/db.py: E501 + python/grass/pygrass/raster/category.py: E721 + python/grass/pygrass/rpc/__init__.py: F401, F403 + python/grass/pygrass/utils.py: E402 python/grass/script/task.py: W605 - python/grass/script/vector.py: E501 # Long doctest lines which need review anyway - python/grass/temporal/abstract_map_dataset.py: E501 - python/grass/temporal/abstract_space_time_dataset.py: W605, E501, F841, E722 - python/grass/temporal/aggregation.py: E501 - python/grass/temporal/base.py: E501 - python/grass/temporal/c_libraries_interface.py: E501, F841, E722 - python/grass/temporal/core.py: E501, E722 - python/grass/temporal/datetime_math.py: E501, F841, E722 - python/grass/temporal/list_stds.py: E501 - python/grass/temporal/metadata.py: E501 + python/grass/temporal/abstract_space_time_dataset.py: W605, F841, E722 + python/grass/temporal/c_libraries_interface.py: F841, E722 + python/grass/temporal/core.py: E722 + python/grass/temporal/datetime_math.py: F841, E722 python/grass/temporal/open_stds.py: F841 - python/grass/temporal/register.py: E501 - python/grass/temporal/space_time_datasets.py: E501 - python/grass/temporal/spatial_extent.py: E501 - python/grass/temporal/spatial_topology_dataset_connector.py: E501, E722 - python/grass/temporal/spatio_temporal_relationships.py: E501 - python/grass/temporal/temporal_algebra.py: E741, E501, F841, E722 - python/grass/temporal/temporal_extent.py: E501 - python/grass/temporal/temporal_granularity.py: E501, F841, E722 - python/grass/temporal/temporal_operator.py: E501 + python/grass/temporal/spatial_topology_dataset_connector.py: E722 + python/grass/temporal/temporal_algebra.py: E741, 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: E501, F841, E722 + 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: E501, E722 - python/grass/temporal/temporal_vector_algebra.py: E741, E501, F841 - python/grass/temporal/univar_statistics.py: E501 + python/grass/temporal/temporal_topology_dataset_connector.py: E722 + python/grass/temporal/temporal_vector_algebra.py: E741, 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. - python/grass/pygrass/tests/benchmark.py: E501, E402, F401, F821 + python/grass/pygrass/tests/benchmark.py: E402, F401, F821 # Configuration file for Sphinx: # Ignoring import/code mix and line length. - python/grass/docs/conf.py: E402, E501, + python/grass/docs/conf.py: E402 # Files not managed by Black - python/grass/imaging/images2gif.py: E226, E501 + python/grass/imaging/images2gif.py: E226 # Unused imports in init files # F401 imported but unused # F403 star import used; unable to detect undefined names @@ -196,27 +171,25 @@ per-file-ignores = python/grass/*/*/__init__.py: F401, F403 python/grass/*/*/*/__init__.py: F401, F403 # E402 module level import not at top of file - scripts/d.polar/d.polar.py: F841, E501 - scripts/r.in.wms/wms_gdal_drv.py: F841, E722, E501 - scripts/r.in.wms/wms_cap_parsers.py: F841, E741, E501 - scripts/r.in.wms/wms_drv.py: E402, E722, E501 - scripts/r.in.wms/srs.py: E722, E501 + 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_drv.py: E402, E722 + scripts/r.in.wms/srs.py: E722 scripts/r.semantic.label/r.semantic.label.py: F841, E501 - scripts/v.report/v.report.py: F841, E501 + scripts/v.report/v.report.py: F841, E721 scripts/db.out.ogr/db.out.ogr.py: F841 scripts/g.extension/g.extension.py: F841, E722, E501 - scripts/r.unpack/r.unpack.py: 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/d.frame/d.frame.py: E722, 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, E501 - scripts/r.fillnulls/r.fillnulls.py: E722, E501 - scripts/d.rast.edit/d.rast.edit.py: E722, E501 + scripts/r.in.srtm/r.in.srtm.py: E722 + scripts/r.fillnulls/r.fillnulls.py: E722 + scripts/d.rast.edit/d.rast.edit.py: E722 scripts/v.what.strds/v.what.strds.py: E722, E501 - scripts/i.in.spotvgt/i.in.spotvgt.py: E501 # Line too long (esp. module interface definitions) scripts/*/*.py: E501 # local variable 'column' is assigned to but never used diff --git a/gui/wxpython/animation/provider.py b/gui/wxpython/animation/provider.py index 978c18e90cb..c23cede79ef 100644 --- a/gui/wxpython/animation/provider.py +++ b/gui/wxpython/animation/provider.py @@ -93,9 +93,9 @@ def SetCmds(self, cmdsForComposition, opacities, regions=None): Applies to 2D mode. :param cmdsForComposition: list of lists of command lists - [[['d.rast', 'map=elev_2001'], ['d.vect', 'map=points']], # g.pnmcomp - [['d.rast', 'map=elev_2002'], ['d.vect', 'map=points']], - ...] + [[['d.rast', 'map=elev_2001'], ['d.vect', 'map=points']], # g.pnmcomp + [['d.rast', 'map=elev_2002'], ['d.vect', 'map=points']], + ...] :param opacities: list of opacity values :param regions: list of regions """ diff --git a/gui/wxpython/animation/temporal_manager.py b/gui/wxpython/animation/temporal_manager.py index a111edc81cb..e5ee593415a 100644 --- a/gui/wxpython/animation/temporal_manager.py +++ b/gui/wxpython/animation/temporal_manager.py @@ -135,7 +135,8 @@ def _setTemporalState(self): message = _( "You are going to display data with different " "temporal types of maps (interval and point)." - " It is recommended to use data of one temporal type to avoid confusion." + " It is recommended to use data of one temporal type to avoid " + "confusion." ) return True, message # warning diff --git a/gui/wxpython/core/debug.py b/gui/wxpython/core/debug.py index 090cd9c60d3..86bb006d603 100644 --- a/gui/wxpython/core/debug.py +++ b/gui/wxpython/core/debug.py @@ -48,8 +48,9 @@ def SetLevel(self): self.debuglevel = 0 sys.stderr.write( _( - "WARNING: Ignoring unsupported wx debug level (must be >=0 and <=5). {0}\n" - ).format(e) + "WARNING: Ignoring unsupported wx debug level (must be >=0 and " + "<=5). {0}\n".format(e) + ) ) def msg(self, level, message, *args): diff --git a/gui/wxpython/core/gcmd.py b/gui/wxpython/core/gcmd.py index eca7ef05898..138936fb4f5 100644 --- a/gui/wxpython/core/gcmd.py +++ b/gui/wxpython/core/gcmd.py @@ -688,7 +688,8 @@ def RunCommand( :param env: environment (optional, uses os.environ if not provided) :param kwargs: program parameters - The environment passed to the function (env or os.environ) is not modified (a copy is used internally). + The environment passed to the function (env or os.environ) is not modified + (a copy is used internally). :return: returncode (read == False and getErrorMsg == False) :return: returncode, messages (read == False and getErrorMsg == True) diff --git a/gui/wxpython/core/giface.py b/gui/wxpython/core/giface.py index 8cb430d7650..951c9cb42dd 100644 --- a/gui/wxpython/core/giface.py +++ b/gui/wxpython/core/giface.py @@ -218,10 +218,12 @@ def __init__(self): # Signal for communicating something in current grassdb has changed. # Parameters: # action: required, is one of 'new', 'rename', 'delete' - # element: required, can be one of 'grassdb', 'location', 'mapset', 'raster', 'vector' and 'raster_3d' + # element: required, can be one of 'grassdb', 'location', 'mapset', 'raster', + # 'vector' and 'raster_3d' # grassdb: path to grass db, required # location: location name, required - # mapset: mapset name, required when element is 'mapset', 'raster', 'vector' or 'raster_3d' + # mapset: mapset name, required when element is 'mapset', 'raster', + # 'vector' or 'raster_3d' # map: map name, required when element is 'raster', 'vector' or 'raster_3d' # newname: new name (of mapset, map), required with action='rename' self.grassdbChanged = Signal("StandaloneGrassInterface.grassdbChanged") diff --git a/gui/wxpython/core/render.py b/gui/wxpython/core/render.py index 2bab7806bab..6e658252bbd 100644 --- a/gui/wxpython/core/render.py +++ b/gui/wxpython/core/render.py @@ -1049,7 +1049,8 @@ def GetRegion( :param rast: list of raster maps :param zoom: zoom to raster map (ignore NULLs) :param vect: list of vector maps - :param rast3d: 3d raster map (not list, no support of multiple 3d rasters in g.region) + :param rast3d: 3d raster map (not list, no support of multiple 3d rasters in + g.region) :param regionName: named region or None :param n,s,e,w: force extent :param default: force default region settings @@ -1256,7 +1257,8 @@ def GetListOfLayers( """Returns list of layers of selected properties or list of all layers. - :param ltype: layer type, e.g. raster/vector/wms/overlay (value or tuple of values) + :param ltype: layer type, e.g. raster/vector/wms/overlay (value or tuple of + values) :param mapset: all layers from given mapset (only for maplayers) :param name: all layers with given name :param active: only layers with 'active' attribute set to True or False diff --git a/gui/wxpython/core/toolboxes.py b/gui/wxpython/core/toolboxes.py index 8c8c380295c..1d58d59f867 100644 --- a/gui/wxpython/core/toolboxes.py +++ b/gui/wxpython/core/toolboxes.py @@ -135,7 +135,10 @@ def getMenudataFile(userRootFile, newFile, fallback): os.remove(menudataFile) _debug( 2, - "toolboxes.getMenudataFile: no user defined files, menudata deleted", + ( + "toolboxes.getMenudataFile: no user defined files, " + "menudata deleted" + ), ) return fallback @@ -144,7 +147,11 @@ def getMenudataFile(userRootFile, newFile, fallback): # any change generateNew = True _debug( - 2, "toolboxes.getMenudataFile: only one of the user defined files" + 2, + ( + "toolboxes.getMenudataFile: only one of the user " + "defined files" + ), ) else: # if newer files -> generate new @@ -153,14 +160,20 @@ def getMenudataFile(userRootFile, newFile, fallback): if os.path.getmtime(_getUserToolboxesFile()) > menudataTime: _debug( 2, - "toolboxes.getMenudataFile: user toolboxes is newer than menudata", + ( + "toolboxes.getMenudataFile: user toolboxes is newer " + "than menudata" + ), ) generateNew = True if userRootFile: if os.path.getmtime(userRootFile) > menudataTime: _debug( 2, - "toolboxes.getMenudataFile: user root file is newer than menudata", + ( + "toolboxes.getMenudataFile: user root file is " + "newer than menudata" + ), ) generateNew = True elif _getUserToolboxesFile() or userRootFile: @@ -198,7 +211,10 @@ def getMenudataFile(userRootFile, newFile, fallback): except: _debug( 2, - "toolboxes.getMenudataFile: writing menudata failed, returning fallback file", + ( + "toolboxes.getMenudataFile: writing menudata failed, " + "returning fallback file" + ), ) return fallback else: @@ -432,12 +448,16 @@ def _expandUserToolboxesItem(node, toolboxes): Include all user toolboxes. - >>> tree = etree.fromstring('') - >>> toolboxes = etree.fromstring('') + >>> tree = etree.fromstring( + ... "" + ... ) + >>> toolboxes = etree.fromstring( + ... '' + ... ) >>> _expandUserToolboxesItem(tree, toolboxes) >>> etree.tostring(tree) b'' - """ + """ # noqa: E501 tboxes = toolboxes.findall(".//toolbox") for n in node.findall("./items/user-toolboxes-list"): @@ -456,7 +476,9 @@ def _expandUserToolboxesItem(node, toolboxes): def _removeUserToolboxesItem(root): """Removes tag 'user-toolboxes-list' if there are no user toolboxes. - >>> tree = etree.fromstring('') + >>> tree = etree.fromstring( + ... "" + ... ) >>> _removeUserToolboxesItem(tree) >>> etree.tostring(tree) b'' @@ -545,12 +567,16 @@ def _expandAddonsItem(node): def _expandItems(node, items, itemTag): """Expand items from file - >>> tree = etree.fromstring('') - >>> items = etree.fromstring('g.regionGRASS region management') - >>> _expandItems(tree, items, 'module-item') + >>> tree = etree.fromstring( + ... '' + ... ) + >>> items = etree.fromstring( + ... 'g.regionGRASS region management' + ... ) + >>> _expandItems(tree, items, "module-item") >>> etree.tostring(tree) b'g.regionGRASS region management' - """ + """ # noqa: E501 for moduleItem in node.findall(".//" + itemTag): itemName = moduleItem.get("name") moduleNode = items.find('.//%s[@name="%s"]' % (itemTag, itemName)) @@ -569,19 +595,19 @@ def _expandRuntimeModules(node, loadMetadata=True): If loadMetadata is False, modules are not called, useful for incompatible addons. - >>> tree = etree.fromstring('' - ... '' - ... '') + >>> tree = etree.fromstring( + ... "" '' "" + ... ) >>> _expandRuntimeModules(tree) >>> etree.tostring(tree) b'g.regionManages the boundary definitions for the geographic region.general,settings,computational region,extent,resolution,level1' - >>> tree = etree.fromstring('' - ... '' - ... '') + >>> tree = etree.fromstring( + ... "" '' "" + ... ) >>> _expandRuntimeModules(tree) >>> etree.tostring(tree) b'm.projConverts coordinates from one projection to another (cs2cs frontend).miscellaneous,projection,transformation' - """ + """ # noqa: E501 hasErrors = False modules = node.findall(".//module-item") for module in modules: @@ -621,7 +647,7 @@ def _escapeXML(text): Duplicate function in core/toolboxes and probably also in man compilation and some existing Python package. - >>> _escapeXML('<>&') + >>> _escapeXML("<>&") '&lt;>&' """ return text.replace("<", "<").replace("&", "&").replace(">", ">") @@ -659,9 +685,11 @@ def _addHandlers(node): def _convertTag(node, old, new): """Converts tag name. - >>> tree = etree.fromstring('') - >>> _convertTag(tree, 'toolbox', 'menu') - >>> _convertTag(tree, 'module-item', 'menuitem') + >>> tree = etree.fromstring( + ... "" + ... ) + >>> _convertTag(tree, "toolbox", "menu") + >>> _convertTag(tree, "module-item", "menuitem") >>> etree.tostring(tree) b'' """ @@ -672,12 +700,14 @@ def _convertTag(node, old, new): def _convertTagAndRemoveAttrib(node, old, new): """Converts tag name and removes attributes. - >>> tree = etree.fromstring('') - >>> _convertTagAndRemoveAttrib(tree, 'toolbox', 'menu') - >>> _convertTagAndRemoveAttrib(tree, 'module-item', 'menuitem') + >>> tree = etree.fromstring( + ... '' + ... ) + >>> _convertTagAndRemoveAttrib(tree, "toolbox", "menu") + >>> _convertTagAndRemoveAttrib(tree, "module-item", "menuitem") >>> etree.tostring(tree) b'' - """ + """ # noqa: E501 for n in node.findall(".//%s" % old): n.tag = new n.attrib = {} @@ -686,11 +716,13 @@ def _convertTagAndRemoveAttrib(node, old, new): def _convertTree(root): """Converts tree to be the form readable by core/menutree.py. - >>> tree = etree.fromstring('g.region') + >>> tree = etree.fromstring( + ... 'g.region' + ... ) >>> _convertTree(tree) >>> etree.tostring(tree) b'g.region' - """ + """ # noqa: E501 root.attrib = {} label = root.find("label") # must check because of inconsistent XML menudata file diff --git a/gui/wxpython/core/workspace.py b/gui/wxpython/core/workspace.py index 82d05d89342..6ff1345c884 100644 --- a/gui/wxpython/core/workspace.py +++ b/gui/wxpython/core/workspace.py @@ -1768,8 +1768,8 @@ def read(self, parent): parent=parent, message=_( "Some lines were skipped when reading settings " - "from file <%(file)s>.\nSee 'Command output' window for details.\n\n" - "Number of skipped lines: %(line)d" + "from file <%(file)s>.\nSee 'Command output' window for details." + "\n\nNumber of skipped lines: %(line)d" ) % {"file": self.filename, "line": self.num_error}, caption=_("Warning"), diff --git a/gui/wxpython/core/ws.py b/gui/wxpython/core/ws.py index fc88772ff36..f705962f9b2 100644 --- a/gui/wxpython/core/ws.py +++ b/gui/wxpython/core/ws.py @@ -228,7 +228,8 @@ def _getRegionDict(self, env): return region def _createRegionStr(self, region): - """Create string for GRASS_REGION env variable from dict created by _getRegionDict.""" + """Create string for GRASS_REGION env variable from dict created + by _getRegionDict.""" regionStr = "" for k, v in region.items(): item = k + ": " + str(v) diff --git a/gui/wxpython/datacatalog/tree.py b/gui/wxpython/datacatalog/tree.py index bd479e69bc5..cfe7fe7a43c 100644 --- a/gui/wxpython/datacatalog/tree.py +++ b/gui/wxpython/datacatalog/tree.py @@ -581,9 +581,11 @@ def _reloadTreeItems(self, full=False): """Updates grass databases, locations, mapsets and layers in the tree. It runs in thread, so it should not directly interact with GUI. - In case of any errors it returns the errors as a list of strings, otherwise None. + In case of any errors it returns the errors as a list of strings, otherwise + None. - Option full=True forces full reload, full=False will behave based on user settings. + Option full=True forces full reload, full=False will behave based on user + settings. """ errors = [] for grassdatabase in self.grassdatabases: @@ -870,10 +872,10 @@ def OnDoubleClick(self, node): dlg = wx.MessageDialog( parent=self, message=_( - "Map <{map_name}@{map_mapset}> is not in the current project. " - "To be able to display it you need to switch to <{map_location}> " - "project. Note that if you switch there all current " - "Map Displays will be closed.\n\n" + "Map <{map_name}@{map_mapset}> is not in the current " + "project. To be able to display it you need to switch to " + "<{map_location}> project. Note that if you switch there " + "all current Map Displays will be closed.\n\n" "Do you want to switch anyway?" ).format( map_name=selected_layer.data["name"], @@ -1676,7 +1678,8 @@ def DisplayLayer(self): ) names[self.selected_layer[i].data["type"]].append(name) all_names.append(name) - # if self.selected_location[0].data['name'] == gisenv()['LOCATION_NAME'] and self.selected_mapset[0]: + # if self.selected_location[0].data['name'] == gisenv()['LOCATION_NAME'] and + # self.selected_mapset[0]: for ltype in names: if names[ltype]: self._giface.lmgr.AddMaps(list(reversed(names[ltype])), ltype, True) @@ -1712,7 +1715,8 @@ def OnEndDrag(self, node, event): ): GMessage( _( - "To move or copy maps to other mapsets, unlock editing of other mapsets" + "To move or copy maps to other mapsets, unlock editing of " + "other mapsets" ), parent=self, ) diff --git a/gui/wxpython/dbmgr/base.py b/gui/wxpython/dbmgr/base.py index 7538ee8a450..482c3ccf7db 100644 --- a/gui/wxpython/dbmgr/base.py +++ b/gui/wxpython/dbmgr/base.py @@ -26,7 +26,8 @@ @author Jachym Cepicky @author Martin Landa -@author Refactoring by Stepan Turek (GSoC 2012, mentor: Martin Landa) +@author Refactoring by Stepan Turek + (GSoC 2012, mentor: Martin Landa) """ import os @@ -301,8 +302,8 @@ def LoadData(self, layer, columns=None, where=None, sql=None): GWarning( parent=self, message=_( - "Incorrect encoding {enc} used. Set encoding in GUI Settings" - " or set GRASS_DB_ENCODING variable." + "Incorrect encoding {enc} used. Set encoding in GUI " + "Settings or set GRASS_DB_ENCODING variable." ).format(enc=enc), ) @@ -317,13 +318,16 @@ def LoadData(self, layer, columns=None, where=None, sql=None): if len(record) > show_max: record = record[:show_max] # TODO: The real fix here is to use JSON output from v.db.select or - # proper CSV output and real CSV reader here (Python csv and json packages). + # proper CSV output and real CSV reader here (Python csv and json + # packages). raise GException( _( "Unable to read the table <{table}> from the database due" - " to seemingly inconsistent number of columns in the data transfer." + " to seemingly inconsistent number of columns in the data" + " transfer." " Check row: {row}..." - " Likely, a newline character is present in the attribute value starting with: '{value}'" + " Likely, a newline character is present in the attribute value" + " starting with: '{value}'" " Use the v.db.select module to investigate." ).format(table=tableName, row=" | ".join(record), value=last) ) @@ -404,8 +408,8 @@ def AddDataRow(self, i, record, columns, keyId): parent=self, message=_( "Error loading attribute data. " - "Record number: %(rec)d. Unable to convert value '%(val)s' in " - "key column (%(key)s) to integer.\n\n" + "Record number: %(rec)d. Unable to convert value '%(val)s' " + "in key column (%(key)s) to integer.\n\n" "Details: %(detail)s" ) % {"rec": i + 1, "val": value, "key": keyColumn, "detail": e}, @@ -856,9 +860,11 @@ def UpdateDialog(self, layer): if layer in self.dbMgrData["mapDBInfo"].layers.keys(): # delete page # dragging pages disallowed - # if self.browsePage.GetPageText(page).replace('Layer ', '').strip() == str(layer): - # self.browsePage.DeletePage(page) - # break + # if self.browsePage.GetPageText(page).replace("Layer ", "").strip() == str( + # layer + # ): + # self.browsePage.DeletePage(page) + # break if self.pages["browse"]: self.pages["browse"].DeletePage(layer) if self.pages["manageTable"]: @@ -2319,7 +2325,8 @@ def AddLayer(self, layer, pos=-1): :param pos: position of tab, if -1 it is added to end :return: True if layer was added - :return: False if layer was not added - layer has been already added or does not exist + :return: False if layer was not added - layer has been already added or does + not exist """ if layer in self.layers or layer not in self.parentDbMgrBase.GetVectorLayers(): return False @@ -2839,7 +2846,8 @@ def _updateTableColumnWidgetChoices(self, table): self.FindWindowById( self.pages["browse"].layerPage[self.selLayer]["whereColumn"] ).SetItems(cols) - # Browse data page SQL Query Builder page SQL builder frame ListBox column names widget + # Browse data page SQL Query Builder page SQL builder frame ListBox column + # names widget if self.pages["browse"].builder: self.pages["browse"].builder.list_columns.Set(cols) # Browse data page column Field calculator frame ListBox column names widget @@ -3135,7 +3143,8 @@ def __init__(self, parent, id, parentDialog, style=wx.BK_DEFAULT): # len(self.defaultConnect['database']) == 0: # GWarning(parent = self.parent, # message = _("Unknown default DB connection. " - # "Please define DB connection using db.connect module.")) + # "Please define DB connection using db.connect" + # "module.")) self.defaultTables = self._getTables( self.defaultConnect["driver"], self.defaultConnect["database"] @@ -3536,9 +3545,11 @@ def _createModifyPage(self): # events self.modifyLayerWidgets["layer"][1].Bind(wx.EVT_COMBOBOX, self.OnChangeLayer) - # self.modifyLayerWidgets['driver'][1].Bind(wx.EVT_CHOICE, self.OnDriverChanged) - # self.modifyLayerWidgets['database'][1].Bind(wx.EVT_TEXT_ENTER, self.OnDatabaseChanged) - # self.modifyLayerWidgets['table'][1].Bind(wx.EVT_CHOICE, self.OnTableChanged) + # self.modifyLayerWidgets["driver"][1].Bind(wx.EVT_CHOICE, self.OnDriverChanged) + # self.modifyLayerWidgets["database"][1].Bind( + # wx.EVT_TEXT_ENTER, self.OnDatabaseChanged + # ) + # self.modifyLayerWidgets["table"][1].Bind(wx.EVT_CHOICE, self.OnTableChanged) btnModify = Button( self.modifyPanel, wx.ID_DELETE, _("&Modify layer"), size=(125, -1) diff --git a/gui/wxpython/dbmgr/dialogs.py b/gui/wxpython/dbmgr/dialogs.py index 5778c8a0fcd..1a3c3af6ee2 100644 --- a/gui/wxpython/dbmgr/dialogs.py +++ b/gui/wxpython/dbmgr/dialogs.py @@ -14,7 +14,8 @@ (>=v2). Read the file COPYING that comes with GRASS for details. @author Martin Landa -@author Refactoring by Stepan Turek (GSoC 2012, mentor: Martin Landa) +@author Refactoring by Stepan Turek + (GSoC 2012, mentor: Martin Landa) """ import wx @@ -237,7 +238,8 @@ def GetSQLString(self, updateValues=False): GError( parent=self, message=_( - "Column <%(col)s>: Value '%(value)s' needs to be entered as %(type)s." + "Column <%(col)s>: Value '%(value)s' needs to be " + "entered as %(type)s." ) % { "col": name, diff --git a/gui/wxpython/dbmgr/manager.py b/gui/wxpython/dbmgr/manager.py index 40f879a1e55..c866bd55650 100644 --- a/gui/wxpython/dbmgr/manager.py +++ b/gui/wxpython/dbmgr/manager.py @@ -19,7 +19,8 @@ @author Jachym Cepicky @author Martin Landa -@author Refactoring by Stepan Turek (GSoC 2012, mentor: Martin Landa) +@author Refactoring by Stepan Turek + (GSoC 2012, mentor: Martin Landa) """ import os diff --git a/gui/wxpython/dbmgr/sqlbuilder.py b/gui/wxpython/dbmgr/sqlbuilder.py index d69a6cace62..a4bc926463c 100644 --- a/gui/wxpython/dbmgr/sqlbuilder.py +++ b/gui/wxpython/dbmgr/sqlbuilder.py @@ -21,7 +21,8 @@ @author Jachym Cepicky (original author) @author Martin Landa @author Hamish Bowman -@author Refactoring, SQLBUilderUpdate by Stepan Turek (GSoC 2012, mentor: Martin Landa) +@author Refactoring, SQLBUilderUpdate by Stepan Turek + (GSoC 2012, mentor: Martin Landa) """ import os diff --git a/gui/wxpython/docs/wxgui_sphinx/conf.py b/gui/wxpython/docs/wxgui_sphinx/conf.py index ba3d4c4c6e8..ef2a4a3849f 100644 --- a/gui/wxpython/docs/wxgui_sphinx/conf.py +++ b/gui/wxpython/docs/wxgui_sphinx/conf.py @@ -30,8 +30,11 @@ footer_tmpl = string.Template( r""" {% block footer %}
-

Help Index | Topics Index | Keywords Index | Full Index

-

© 2003-${year} GRASS Development Team, GRASS GIS ${grass_version} Reference Manual

+

Help Index | Topics Index +| Keywords Index +| Full Index

+

© 2003-${year} GRASS Development Team, +GRASS GIS ${grass_version} Reference Manual

{% endblock %} """ ) diff --git a/gui/wxpython/gcp/manager.py b/gui/wxpython/gcp/manager.py index 451f3c2c833..3e948dc3c91 100644 --- a/gui/wxpython/gcp/manager.py +++ b/gui/wxpython/gcp/manager.py @@ -1549,7 +1549,7 @@ def SaveGCPs(self, event): f.write("#\tsource\t\ttarget\t\tstatus\n") f.write("#\teast\tnorth\teast\tnorth\t(1=ok, 0=ignore)\n") f.write( - "#----------------------- ----------------------- ---------------\n" + "#----------------------- ----------------------- ---------------\n" # noqa: E501 ) for index in range(self.list.GetItemCount()): @@ -1694,7 +1694,8 @@ def ReloadGCPs(self, event): targetMapWin.UpdateMap(render=False, renderVector=False) def OnFocus(self, event): - # TODO: it is here just to remove old or obsolete beavior of base class gcp/MapPanel? + # TODO: it is here just to remove old or obsolete beavior of base class + # gcp/MapPanel? # self.grwiz.SwitchEnv('source') pass @@ -2033,16 +2034,19 @@ def OnGROrder(self, event): if self.gr_order == 1: minNumOfItems = 3 - # self.SetStatusText(_('Insufficient points, 3+ points needed for 1st order')) + # self.SetStatusText( + # _('Insufficient points, 3+ points needed for 1st order')) elif self.gr_order == 2: minNumOfItems = 6 diff = 6 - numOfItems - # self.SetStatusText(_('Insufficient points, 6+ points needed for 2nd order')) + # self.SetStatusText( + # _('Insufficient points, 6+ points needed for 2nd order')) elif self.gr_order == 3: minNumOfItems = 10 - # self.SetStatusText(_('Insufficient points, 10+ points needed for 3rd order')) + # self.SetStatusText( + # _('Insufficient points, 10+ points needed for 3rd order')) for i in range(minNumOfItems - numOfItems): self.AddGCP(None) @@ -2972,7 +2976,8 @@ def __init__( btnSave.Bind(wx.EVT_BUTTON, self.OnSave) btnSave.SetToolTip( _( - "Apply and save changes to user settings file (default for next sessions)" + "Apply and save changes to user settings file (default for next " + "sessions)" ) ) btnClose.Bind(wx.EVT_BUTTON, self.OnClose) diff --git a/gui/wxpython/gmodeler/model.py b/gui/wxpython/gmodeler/model.py index 6b4e84a2681..b33c5b6d4e4 100644 --- a/gui/wxpython/gmodeler/model.py +++ b/gui/wxpython/gmodeler/model.py @@ -2783,7 +2783,7 @@ def __init__(self): inputs = list() outputs = list() -""" +""" # noqa: E501 ) for item in self.model.GetItems(): diff --git a/gui/wxpython/gui_core/dialogs.py b/gui/wxpython/gui_core/dialogs.py index 4d292854a11..e4c9cd50081 100644 --- a/gui/wxpython/gui_core/dialogs.py +++ b/gui/wxpython/gui_core/dialogs.py @@ -107,7 +107,8 @@ def __layout(self): self.sizer.Add(self.dataSizer, proportion=1, flag=wx.EXPAND | wx.ALL, border=5) - # self.sizer.Add(item = self.informLabel, proportion = 0, flag = wx.ALL, border = 5) + # self.sizer.Add(item = self.informLabel, proportion = 0, + # flag = wx.ALL, border = 5) self.sizer.Add(btnSizer, proportion=0, flag=wx.EXPAND | wx.ALL, border=5) def ValidatorCallback(self, win): @@ -304,7 +305,8 @@ def __init__( :param title: window title :param disableAdd: disable 'add layer' checkbox :param disableTable: disable 'create table' checkbox - :param showType: True to show feature type selector (used for creating new empty OGR layers) + :param showType: True to show feature type selector (used for creating new + empty OGR layers) :return: dialog instance """ @@ -2599,7 +2601,8 @@ def GetFonts(self): return fontdict, fontdict_reverse, fontlist def RenderText(self, font, text, size): - """Renders an example text with the selected font and resets the bitmap widget""" + """Renders an example text with the selected font and resets the bitmap + widget""" env = os.environ.copy() driver = UserSettings.Get(group="display", key="driver", subkey="type") if driver == "png": diff --git a/gui/wxpython/gui_core/forms.py b/gui/wxpython/gui_core/forms.py index 87d10c81815..937b31321a9 100644 --- a/gui/wxpython/gui_core/forms.py +++ b/gui/wxpython/gui_core/forms.py @@ -1548,8 +1548,8 @@ def __init__(self, parent, giface, task, id=wx.ID_ANY, frame=None, *args, **kwar selection.SetValue(value) formatSelector = True - # A gselect.Select is a combobox with two children: a textctl and a popupwindow; - # we target the textctl here + # A gselect.Select is a combobox with two children: a textctl + # and a popupwindow; we target the textctl here textWin = selection.GetTextCtrl() if globalvar.CheckWxVersion([3]): p["wxId"] = [ @@ -1572,44 +1572,63 @@ def __init__(self, parent, giface, task, id=wx.ID_ANY, frame=None, *args, **kwar win.Bind(wx.EVT_TEXT, self.OnUpdateSelection) win.Bind(wx.EVT_TEXT, self.OnSetValue) - # if formatSelector and p.get('age', 'old') == 'old': + # if formatSelector and p.get("age", "old") == "old": # # OGR supported (read-only) # self.hsizer = wx.BoxSizer(wx.HORIZONTAL) - - # self.hsizer.Add(item = selection, - # flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT | wx.RIGHT | wx.TOP | wx.ALIGN_TOP, - # border = 5) - + # + # self.hsizer.Add( + # item=selection, + # flag=wx.ADJUST_MINSIZE + # | wx.BOTTOM + # | wx.LEFT + # | wx.RIGHT + # | wx.TOP + # | wx.ALIGN_TOP, + # border=5, + # ) + # # # format (native / ogr) - # rbox = wx.RadioBox(parent = which_panel, id = wx.ID_ANY, - # label = " %s " % _("Format"), - # style = wx.RA_SPECIFY_ROWS, - # choices = [_("Native / Linked OGR"), _("Direct OGR")]) - # if p.get('value', '').lower().rfind('@ogr') > -1: + # rbox = wx.RadioBox( + # parent=which_panel, + # id=wx.ID_ANY, + # label=" %s " % _("Format"), + # style=wx.RA_SPECIFY_ROWS, + # choices=[_("Native / Linked OGR"), _("Direct OGR")], + # ) + # if p.get("value", "").lower().rfind("@ogr") > -1: # rbox.SetSelection(1) - # rbox.SetName('VectorFormat') + # rbox.SetName("VectorFormat") # rbox.Bind(wx.EVT_RADIOBOX, self.OnVectorFormat) - - # self.hsizer.Add(item = rbox, - # flag = wx.ADJUST_MINSIZE | wx.BOTTOM | wx.LEFT | - # wx.RIGHT | wx.ALIGN_TOP, - # border = 5) - - # ogrSelection = gselect.GdalSelect(parent = self, panel = which_panel, ogr = True, - # default = 'dir', - # exclude = ['file']) + # + # self.hsizer.Add( + # item=rbox, + # flag=wx.ADJUST_MINSIZE + # | wx.BOTTOM + # | wx.LEFT + # | wx.RIGHT + # | wx.ALIGN_TOP, + # border=5, + # ) + # + # ogrSelection = gselect.GdalSelect( + # parent=self, + # panel=which_panel, + # ogr=True, + # default="dir", + # exclude=["file"], + # ) # self.Bind(gselect.EVT_GDALSELECT, self.OnUpdateSelection) # self.Bind(gselect.EVT_GDALSELECT, self.OnSetValue) - # ogrSelection.SetName('OgrSelect') + # ogrSelection.SetName("OgrSelect") # ogrSelection.Hide() # which_sizer.Add(item = self.hsizer, proportion = 0) - # p['wxId'].append(rbox.GetId()) - # p['wxId'].append(ogrSelection.GetId()) + # p["wxId"].append(rbox.GetId()) + # p["wxId"].append(ogrSelection.GetId()) # for win in ogrSelection.GetDsnWin(): - # p['wxId'].append(win.GetId()) + # p["wxId"].append(win.GetId()) # else: which_sizer.Add( selection, @@ -1660,7 +1679,8 @@ def __init__(self, parent, giface, task, id=wx.ID_ANY, frame=None, *args, **kwar bb.Bind(wx.EVT_BUTTON, self.OnTimelineTool) bb.SetToolTip( _( - "Show graphical representation of temporal extent of dataset(s) ." + "Show graphical representation of temporal extent " + "of dataset(s)." ) ) p["wxId"].append(bb.GetId()) @@ -1935,9 +1955,9 @@ def __init__(self, parent, giface, task, id=wx.ID_ANY, frame=None, *args, **kwar else: this_sizer = which_sizer colorSize = 150 - # For color selectors, this is a three-member array, holding the IDs of - # the color picker, the text control for multiple colors (or None), - # and either a "transparent" checkbox or None + # For color selectors, this is a three-member array, holding the + # IDs of the color picker, the text control for multiple colors + # (or None), and either a "transparent" checkbox or None p["wxId"] = [None] * 3 if p.get("multiple", False): txt = TextCtrl(parent=which_panel, id=wx.ID_ANY) @@ -2063,7 +2083,8 @@ def __init__(self, parent, giface, task, id=wx.ID_ANY, frame=None, *args, **kwar try: ifbb.AppendText(line) except UnicodeDecodeError: - # remove non-ascii characters on encoding mismatch (file vs OS) + # remove non-ascii characters on encoding + # mismatch (file vs OS) ifbb.AppendText(line.translate(None, nonascii)) ifbb.SetInsertionPoint(0) @@ -2818,8 +2839,8 @@ def OnColorChange(self, event): else: colorchooser = wx.FindWindowById(p["wxId"][0]) new_color = colorchooser.GetValue()[:] - # This is weird: new_color is a 4-tuple and new_color[:] is a 3-tuple - # under wx2.8.1 + # This is weird: new_color is a 4-tuple and new_color[:] is + # a 3-tuple under wx2.8.1 new_label = utils.rgb2str.get( new_color, ":".join(list(map(str, new_color))) ) @@ -3306,7 +3327,8 @@ def OnInit(self): task.params = [ { "name": "text", - "description": "Descriptions go into tooltips if labels are present, like this one", + "description": "Descriptions go into tooltips if labels are present, " + "like this one", "label": "Enter some text", "key_desc": ["value"], "values_desc": [], @@ -3334,7 +3356,8 @@ def OnInit(self): }, { "name": "plain_color", - "description": "This is a plain color, and it is a compulsory parameter", + "description": "This is a plain color, and it is a compulsory " + "parameter", "required": False, "gisprompt": True, "prompt": "color", @@ -3400,7 +3423,8 @@ def OnInit(self): }, { "name": "b", - "description": "pre-filled flag, will appear in options since it is not required", + "description": "pre-filled flag, will appear in options since it is " + "not required", "value": True, "suppress_required": False, }, diff --git a/gui/wxpython/gui_core/ghelp.py b/gui/wxpython/gui_core/ghelp.py index 1ac64bb6609..6c87b444081 100644 --- a/gui/wxpython/gui_core/ghelp.py +++ b/gui/wxpython/gui_core/ghelp.py @@ -188,16 +188,26 @@ def _pageInfo(self): # show only basic info # row += 1 - # infoGridSizer.Add(item = wx.StaticText(parent = infoTxt, id = wx.ID_ANY, - # label = '%s:' % _('GIS Library Revision')), - # pos = (row, 0), - # flag = wx.ALIGN_RIGHT) - - # infoGridSizer.Add(item = wx.StaticText(parent = infoTxt, id = wx.ID_ANY, - # label = vInfo['libgis_revision'] + ' (' + - # vInfo['libgis_date'].split(' ')[0] + ')'), - # pos = (row, 1), - # flag = wx.ALIGN_LEFT) + # infoGridSizer.Add( + # item=wx.StaticText( + # parent=infoTxt, id=wx.ID_ANY, label="%s:" % _("GIS Library Revision") + # ), + # pos=(row, 0), + # flag=wx.ALIGN_RIGHT, + # ) + # + # infoGridSizer.Add( + # item=wx.StaticText( + # parent=infoTxt, + # id=wx.ID_ANY, + # label=vInfo["libgis_revision"] + # + " (" + # + vInfo["libgis_date"].split(" ")[0] + # + ")", + # ), + # pos=(row, 1), + # flag=wx.ALIGN_LEFT, + # ) row += 2 infoGridSizer.Add( @@ -751,7 +761,8 @@ def __init__(self, parent, command, text, skipDescription, **kwargs): self.history.append(url) self.loaded = True else: - # FIXME: calling LoadPage() is strangely time-consuming (only first call) + # FIXME: calling LoadPage() is strangely time-consuming + # (only first call) # self.LoadPage(self.fspath + command + ".html") self.loaded = False else: diff --git a/gui/wxpython/gui_core/gselect.py b/gui/wxpython/gui_core/gselect.py index 859be0e132f..12773f1c449 100644 --- a/gui/wxpython/gui_core/gselect.py +++ b/gui/wxpython/gui_core/gselect.py @@ -117,7 +117,8 @@ def __init__( :param updateOnPopup: True for updating list of elements on popup :param onPopup: function to be called on Popup :param fullyQualified: True to provide fully qualified names (map@mapset) - :param extraItems: extra items to add (given as dictionary) - see gmodeler for usage + :param extraItems: extra items to add (given as dictionary) + - see gmodeler for usage :param layerTree: show only elements from given layer tree if not None :param validator: validator for TextCtrl """ @@ -2284,8 +2285,8 @@ def hasRastSameProjAsLocation(dsn, table=None): "r.external", quiet=True, read=True, flags="t", input=dsn ) - # v.external returns info for individual bands, however projection is shared by all bands -> - # (it is possible to take first line) + # v.external returns info for individual bands, however projection is + # shared by all bands -> (it is possible to take first line) lines = ret.splitlines() projectionMatch = "0" @@ -2983,7 +2984,8 @@ def _isMapSelected(self): return True def _chckMap(self): - """Check if selected map in 'input' widget is the same as selected map in lmgr""" + """Check if selected map in 'input' widget is the same as selected map in + lmgr""" if self._isMapSelected(): layerList = self.giface.GetLayerList() layerSelected = layerList.GetSelectedLayer() @@ -2997,8 +2999,8 @@ def _chckMap(self): return False GWarning( _( - "Input vector map <%s> and selected map <%s> in layer manager are different. " - "Operation canceled." + "Input vector map <%s> and selected map <%s> in layer manager " + "are different. Operation canceled." ) % (inputName["value"], str(layerSelected)) ) diff --git a/gui/wxpython/gui_core/preferences.py b/gui/wxpython/gui_core/preferences.py index 95d16a2c996..96b7d339664 100644 --- a/gui/wxpython/gui_core/preferences.py +++ b/gui/wxpython/gui_core/preferences.py @@ -113,7 +113,8 @@ def __init__( self.btnSave.Bind(wx.EVT_BUTTON, self.OnSave) self.btnSave.SetToolTip( _( - "Apply and save changes to user settings file (default for next sessions)" + "Apply and save changes to user settings file (default for next " + "sessions)" ) ) self.btnSave.SetDefault() diff --git a/gui/wxpython/gui_core/treeview.py b/gui/wxpython/gui_core/treeview.py index 53f5852dff9..01bbe87d493 100644 --- a/gui/wxpython/gui_core/treeview.py +++ b/gui/wxpython/gui_core/treeview.py @@ -279,8 +279,8 @@ def __init__(self, model=None): wx.Frame.__init__(self, None, title="Test tree") panel = wx.Panel(self) - # self.tree = TreeListView(model=model, parent=panel, columns=['col1', 'xxx']) - # self.tree = TreeView(model=model, parent=panel) + # self.tree = TreeListView(model=model, parent=panel, columns=["col1", "xxx"]) + # self.tree = TreeView(model=model, parent=panel) self.tree = CTreeView(model=model, parent=panel) self.tree.selectionChanged.connect(self.OnSelChanged) self.tree.itemActivated.connect(self.OnItemActivated) diff --git a/gui/wxpython/gui_core/widgets.py b/gui/wxpython/gui_core/widgets.py index 3ced80291ce..7630c6f03ad 100644 --- a/gui/wxpython/gui_core/widgets.py +++ b/gui/wxpython/gui_core/widgets.py @@ -43,10 +43,11 @@ @author Martin Landa (Google SoC 2008/2010) @author Enhancements by Michael Barton @author Anna Kratochvilova (Google SoC 2011) -@author Stepan Turek (ManageSettingsWidget - created from GdalSelect) -@author Matej Krejci (Google GSoC 2014; EmailValidator, TimeISOValidator) -@author Tomas Zigo (LayersListValidator, -PlacementValidator) +@author Stepan Turek (ManageSettingsWidget - created from + GdalSelect) +@author Matej Krejci (Google GSoC 2014; EmailValidator, + TimeISOValidator) +@author Tomas Zigo (LayersListValidator, PlacementValidator) """ import os diff --git a/gui/wxpython/iclass/dialogs.py b/gui/wxpython/iclass/dialogs.py index 868928efc89..48537c10548 100644 --- a/gui/wxpython/iclass/dialogs.py +++ b/gui/wxpython/iclass/dialogs.py @@ -180,9 +180,9 @@ def GetSelectedGroup(self): return self.groupSelect.GetValue().split("@")[0] def GetGroupBandsErr(self, parent): - """Get list of raster bands which are in the soubgroup of group with both having same name. - If the group does not exists or it does not contain any bands in subgoup with same name, - error dialog is shown. + """Get list of raster bands which are in the subgroup of group with both + having same name. If the group does not exist, or it does not contain any bands + in subgroup with same name, error dialog is shown. """ gr, s = self.GetData() @@ -220,7 +220,8 @@ def GetGroupBandsErr(self, parent): return bands def GetGroupBands(self, group, subgroup): - """Get list of raster bands which are in the soubgroup of group with both having same name.""" + """Get list of raster bands which are in the subgroup of group with both having + same name.""" kwargs = {} if subgroup: @@ -384,7 +385,8 @@ class CategoryListCtrl(ListCtrl, listmix.ListCtrlAutoWidthMixin, listmix.TextEdi def __init__(self, parent, mapwindow, stats_data, id=wx.ID_ANY): """ :param parent: gui parent - :param mapwindow: mapwindow instance with iclass toolbar and remove raster method + :param mapwindow: mapwindow instance with iclass toolbar and remove raster + method :param stats_data: StatisticsData instance (defined in statistics.py) :param id: wx id """ diff --git a/gui/wxpython/iclass/frame.py b/gui/wxpython/iclass/frame.py index 9a53317694c..f041f84e892 100644 --- a/gui/wxpython/iclass/frame.py +++ b/gui/wxpython/iclass/frame.py @@ -94,7 +94,8 @@ def __init__( """ :param parent: (no parent is expected) :param title: window title - :param toolbars: dictionary of active toolbars (default value represents all toolbars) + :param toolbars: dictionary of active toolbars (default value represents all + toolbars) :param size: default size """ DoubleMapPanel.__init__( @@ -1445,7 +1446,8 @@ def AddLayer(self, name, alias=None, resultsLayer=False): """Adds layer to Map and update toolbar :param str name: layer (raster) name - :param str resultsLayer: True if layer is temp. raster showing the results of computation + :param str resultsLayer: True if layer is temp. raster showing the results of + computation """ if resultsLayer and name in [ layer.GetName() for layer in self.map.GetListOfLayers(name=name) diff --git a/gui/wxpython/image2target/g.gui.image2target.py b/gui/wxpython/image2target/g.gui.image2target.py index 706a0e6a133..d78ff78ae95 100755 --- a/gui/wxpython/image2target/g.gui.image2target.py +++ b/gui/wxpython/image2target/g.gui.image2target.py @@ -129,43 +129,45 @@ def main(): else: os.environ["GRASS_RENDER_IMMEDIATE"] = "cairo" - # if options['source_location']: - # src_loc = options['source_location'] + # if options["source_location"]: + # src_loc = options["source_location"] # else: # gscript.fatal(_("No georeferenced source location provided")) - # if options['source_mapset']: - # src_mpt = options['source_mapset'] + # if options["source_mapset"]: + # src_mpt = options["source_mapset"] # else: # gscript.fatal(_("No georeferenced source mapset provided")) - # if options['source_group']: - # src_grp = options['source_group'] + # if options["source_group"]: + # src_grp = options["source_group"] # else: # gscript.fatal(_("Please provide a source group name to process")) # if options['source_image']: - # src_ras = options['source_image'] + # src_ras = options["source_image"] # else: # gscript.fatal(_("Please provide a source image map name to process")) - # if options['target_image']: - # tgt_ras = options['target_image'] + # if options["target_image"]: + # tgt_ras = options["target_image"] # else: # gscript.fatal(_("No georeferenced target map provided")) - # if options['camera']: - # camera = options['camera'] + # if options["camera"]: + # camera = options["camera"] # else: - # gscript.fatal(_("Please provide a camera name (generated by i.ortho.camera)")) + # gscript.fatal(_( + # "Please provide a camera name (generated by i.ortho.camera)" + # )) - # if options['order']: - # order = options['order'] + # if options["order"]: + # order = options["order"] # else: # gscript.fatal(_("Please provive an order value")) - # if options['extension']: - # extension = options['extension'] + # if options["extension"]: + # extension = options["extension"] # else: # gscript.fatal(_("Please provide an output file extension")) diff --git a/gui/wxpython/image2target/ii2t_gis_set.py b/gui/wxpython/image2target/ii2t_gis_set.py index 641ff2671d5..12ee5938849 100644 --- a/gui/wxpython/image2target/ii2t_gis_set.py +++ b/gui/wxpython/image2target/ii2t_gis_set.py @@ -132,7 +132,8 @@ def __init__(self, parent=None, id=wx.ID_ANY, style=wx.DEFAULT_FRAME_STYLE): self.lmessage = StaticText(parent=self.panel) # It is not clear if all wx versions supports color, so try-except. # The color itself may not be correct for all platforms/system settings - # but in http://xoomer.virgilio.it/infinity77/wxPython/Widgets/wx.SystemSettings.html + # but in + # http://xoomer.virgilio.it/infinity77/wxPython/Widgets/wx.SystemSettings.html # there is no 'warning' color. try: self.lmessage.SetForegroundColour(wx.Colour(255, 0, 0)) diff --git a/gui/wxpython/image2target/ii2t_manager.py b/gui/wxpython/image2target/ii2t_manager.py index f15b89d986f..2828a3b0a58 100644 --- a/gui/wxpython/image2target/ii2t_manager.py +++ b/gui/wxpython/image2target/ii2t_manager.py @@ -112,27 +112,40 @@ class GCPWizard: Start wizard here and finish wizard here """ - # def __init__(self, parent, giface, srcloc, srcmpt, srcgrp, srcras, tgtras, camera, order, extension): - # global maptype - # global src_map - # global tgt_map - # maptype = 'raster' - # rendertype = 'raster' - # self.parent = parent # GMFrame - # self._giface = giface - # self.srcloc = srcloc - # self.srcmpt = srcmpt - # self.group = srcgrp - # self.src_map = srcras - # self.tgt_map = tgtras - # self.camera = camera - # self.order = int(order) - # self.extension = extension - # self.src_maps = self.src_map - # # location for xy map to georectify - # self.newlocation = self.srcloc - # # mapset for xy map to georectify - # self.newmapset = self.srcmpt + # def __init__( + # self, + # parent, + # giface, + # srcloc, + # srcmpt, + # srcgrp, + # srcras, + # tgtras, + # camera, + # order, + # extension, + # ): + # global maptype + # global src_map + # global tgt_map + # maptype = "raster" + # rendertype = "raster" + # self.parent = parent # GMFrame + # self._giface = giface + # self.srcloc = srcloc + # self.srcmpt = srcmpt + # self.group = srcgrp + # self.src_map = srcras + # self.tgt_map = tgtras + # self.camera = camera + # self.order = int(order) + # self.extension = extension + # self.src_maps = self.src_map + # # location for xy map to georectify + # self.newlocation = self.srcloc + # # mapset for xy map to georectify + # self.newmapset = self.srcmpt + def __init__(self, parent, giface): self.parent = parent # GMFrame self._giface = giface @@ -1552,7 +1565,7 @@ def SaveGCPs(self, event): f.write("#\tsource\t\t\ttarget\t\t\tstatus\n") f.write("#\teast\tnorth\theight\teast\tnorth\theight\t(1=ok, 0=ignore)\n") f.write( - "#---------------------------- --------------------------- ---------------\n" + "#---------------------------- --------------------------- ---------------\n" # noqa: E501 ) for index in range(self.list.GetItemCount()): @@ -1707,7 +1720,8 @@ def ReloadGCPs(self, event): targetMapWin.UpdateMap(render=False, renderVector=False) def OnFocus(self, event): - # TODO: it is here just to remove old or obsolete beavior of base class gcp/MapPanel? + # TODO: it is here just to remove old or obsolete beavior of base class + # gcp/MapPanel? # self.grwiz.SwitchEnv('source') pass @@ -1962,16 +1976,19 @@ def OnGROrder(self, event): if self.gr_order == 1: minNumOfItems = 3 - # self.SetStatusText(_('Insufficient points, 3+ points needed for 1st order')) + # self.SetStatusText(_( + # "Insufficient points, 3+ points needed for 1st order")) elif self.gr_order == 2: minNumOfItems = 6 diff = 6 - numOfItems - # self.SetStatusText(_('Insufficient points, 6+ points needed for 2nd order')) + # self.SetStatusText(_( + # "Insufficient points, 6+ points needed for 2nd order")) elif self.gr_order == 3: minNumOfItems = 10 - # self.SetStatusText(_('Insufficient points, 10+ points needed for 3rd order')) + # self.SetStatusText(_( + # "Insufficient points, 10+ points needed for 3rd order")) for i in range(minNumOfItems - numOfItems): self.AddGCP(None) @@ -2907,7 +2924,8 @@ def __init__( btnSave.Bind(wx.EVT_BUTTON, self.OnSave) btnSave.SetToolTip( _( - "Apply and save changes to user settings file (default for next sessions)" + "Apply and save changes to user settings file (default for next " + "sessions)" ) ) btnClose.Bind(wx.EVT_BUTTON, self.OnClose) diff --git a/gui/wxpython/iscatt/controllers.py b/gui/wxpython/iscatt/controllers.py index c526a4bf28d..d823dfb6e1a 100644 --- a/gui/wxpython/iscatt/controllers.py +++ b/gui/wxpython/iscatt/controllers.py @@ -233,8 +233,8 @@ def AddScattPlot(self): "Interactive Scatter Plot Tool can not be used.\n" "Number of cells (rows*cols) <%d> in current region" "is higher than maximum limit <%d>.\n\n" - "You can reduce number of cells in current region using command." - % (ncells, MAX_NCELLS) + "You can reduce number of cells in current region using " + " command." % (ncells, MAX_NCELLS) ), ) ) diff --git a/gui/wxpython/iscatt/dialogs.py b/gui/wxpython/iscatt/dialogs.py index 20787867f04..5fad1990875 100644 --- a/gui/wxpython/iscatt/dialogs.py +++ b/gui/wxpython/iscatt/dialogs.py @@ -406,7 +406,8 @@ def __init__( self.btnSave.Bind(wx.EVT_BUTTON, self.OnSave) self.btnSave.SetToolTip( _( - "Apply and save changes to user settings file (default for next sessions)" + "Apply and save changes to user settings file (default for next " + "sessions)" ) ) self.btnClose.Bind(wx.EVT_BUTTON, self.OnClose) diff --git a/gui/wxpython/iscatt/plots.py b/gui/wxpython/iscatt/plots.py index 661da107754..a955250db10 100644 --- a/gui/wxpython/iscatt/plots.py +++ b/gui/wxpython/iscatt/plots.py @@ -517,27 +517,37 @@ def MergeImg(cats_order, scatts, styles, rend_dt, output_queue): MergeArrays(merged_img, rend_dt[cat_id]["dt"], styles[cat_id]["opacity"]) """ - #c_img_a = np.memmap(grass.tempfile(), dtype="uint16", mode='w+', shape = shape) - c_img_a = colored_cat.astype('uint16')[:,:,3] * styles[cat_id]['opacity'] - - #TODO apply strides and there will be no need for loop - #b = as_strided(a, strides=(0, a.strides[3], a.strides[3], a.strides[3]), shape=(3, a.shape[0], a.shape[1])) - - for i in range(3): - merged_img[:,:,i] = (merged_img[:,:,i] * (255 - c_img_a) + colored_cat[:,:,i] * c_img_a) / 255; - merged_img[:,:,3] = (merged_img[:,:,3] * (255 - c_img_a) + 255 * c_img_a) / 255; - - del c_img_a - """ - + # c_img_a = np.memmap( + # grass.tempfile(), dtype="uint16", mode="w+", shape=shape + # ) + c_img_a = colored_cat.astype("uint16")[:, :, 3] * styles[cat_id]["opacity"] + + # TODO apply strides and there will be no need for loop + # b = as_strided( + # a, + # strides=(0, a.strides[3], a.strides[3], a.strides[3]), + # shape=(3, a.shape[0], a.shape[1]), + # ) + + for i in range(3): + merged_img[:, :, i] = ( + merged_img[:, :, i] * (255 - c_img_a) + + colored_cat[:, :, i] * c_img_a + ) / 255 + merged_img[:, :, 3] = ( + merged_img[:, :, 3] * (255 - c_img_a) + 255 * c_img_a + ) / 255 + + del c_img_a + """ _rendDtMemmapsToFiles(rend_dt) merged_img = {"dt": merged_img.filename, "sh": merged_img.shape} output_queue.put((merged_img, full_extend, rend_dt)) -# _rendDtMemmapsToFiles and _rendDtFilesToMemmaps are workarounds for older numpy versions, -# where memmap objects are not pickable +# _rendDtMemmapsToFiles and _rendDtFilesToMemmaps are workarounds for older numpy +# versions, where memmap objects are not pickable def _rendDtMemmapsToFiles(rend_dt): @@ -630,7 +640,8 @@ class PolygonDrawer: def __init__(self, ax, pol, empty_pol): if pol.figure is None: raise RuntimeError( - "You must first add the polygon to a figure or canvas before defining the interactor" + "You must first add the polygon to a figure or canvas before defining " + "the interactor" ) self.ax = ax self.canvas = pol.figure.canvas diff --git a/gui/wxpython/iscatt/toolbars.py b/gui/wxpython/iscatt/toolbars.py index 6c5ab3947d6..30d9869f861 100644 --- a/gui/wxpython/iscatt/toolbars.py +++ b/gui/wxpython/iscatt/toolbars.py @@ -69,7 +69,8 @@ def _toolbarData(self): "zoomExtent": MetaIcon( img="zoom-extent", label=_( - "Zoom to scatter plot data extend mode (click on scatter plot for zooming to extend)" + "Zoom to scatter plot data extend mode (click on scatter plot for " + "zooming to extend)" ), ), "cats_mgr": MetaIcon( diff --git a/gui/wxpython/lmgr/frame.py b/gui/wxpython/lmgr/frame.py index 2f863103424..c24ee04ab8e 100644 --- a/gui/wxpython/lmgr/frame.py +++ b/gui/wxpython/lmgr/frame.py @@ -595,8 +595,8 @@ def CanCloseDisplay(askIfSaveWorkspace): ) mapdisplay.starting3dMode.connect( - lambda firstTime, mapDisplayPage=self.currentPage: self._onMapDisplayStarting3dMode( - mapDisplayPage + lambda firstTime, mapDisplayPage=self.currentPage: ( + self._onMapDisplayStarting3dMode(mapDisplayPage) ) ) mapdisplay.starting3dMode.connect(self.AddNvizTools) @@ -2129,8 +2129,13 @@ def OnAddRasterNum(self, event): dlg.Destroy() # region = tree.GetMap().GetCurrentRegion() - # if region['cells'] > 10000: - # GMessage(message = "Cell values can only be displayed for regions of < 10,000 cells.", parent = self) + # if region["cells"] > 10000: + # GMessage( + # message=( + # "Cell values can only be displayed for regions of < 10,000 cells." + # ), + # parent=self, + # ) self.GetLayerTree().AddLayer("rastnum") def OnAddCommand(self, event): diff --git a/gui/wxpython/lmgr/giface.py b/gui/wxpython/lmgr/giface.py index 7a2cce9223a..1c347d35a0f 100644 --- a/gui/wxpython/lmgr/giface.py +++ b/gui/wxpython/lmgr/giface.py @@ -198,10 +198,12 @@ def __init__(self, lmgr): # Signal for communicating something in current grassdb has changed. # Parameters: # action: required, is one of 'new', 'rename', 'delete' - # element: required, can be one of 'grassdb', 'location', 'mapset', 'raster', 'vector' and 'raster_3d' + # element: required, can be one of 'grassdb', 'location', 'mapset', 'raster', + # 'vector' and 'raster_3d' # grassdb: path to grass db, required # location: location name, required - # mapset: mapset name, required when element is 'mapset', 'raster', 'vector' or 'raster_3d' + # mapset: mapset name, required when element is 'mapset', 'raster', + # 'vector' or 'raster_3d' # map: map name, required when element is 'raster', 'vector' or 'raster_3d' # newname: new name (of mapset, map), required with action='rename' self.grassdbChanged = Signal("LayerManagerGrassInterface.grassdbChanged") diff --git a/gui/wxpython/lmgr/layertree.py b/gui/wxpython/lmgr/layertree.py index eb9e2aa7d48..03ae921b2ec 100644 --- a/gui/wxpython/lmgr/layertree.py +++ b/gui/wxpython/lmgr/layertree.py @@ -710,29 +710,40 @@ def OnLayerContextMenu(self, event): # removed from layer tree # if digitToolbar: # background vector map - # self.popupMenu.Append(self.popupID['bgmap'], - # text = _("Use as background vector map for digitizer"), - # kind = wx.ITEM_CHECK) - # self.Bind(wx.EVT_MENU, self.OnSetBgMap, id = self.popupID['bgmap']) - # if UserSettings.Get(group = 'vdigit', key = 'bgmap', subkey = 'value', - # internal = True) == layer.GetName(): - # self.popupMenu.Check(self.popupID['bgmap'], True) + # self.popupMenu.Append( + # self.popupID["bgmap"], + # text=_("Use as background vector map for digitizer"), + # kind=wx.ITEM_CHECK, + # ) + # self.Bind(wx.EVT_MENU, self.OnSetBgMap, id = self.popupID["bgmap"]) + # if ( + # UserSettings.Get( + # group="vdigit", key="bgmap", subkey="value", internal=True + # ) + # == layer.GetName() + # ): + # self.popupMenu.Check(self.popupID["bgmap"], True) self.popupMenu.Append(self.popupID["topo"], _("Rebuild topology")) self.Bind(wx.EVT_MENU, self.OnTopology, id=self.popupID["topo"]) # determine format - # if layer and layer.GetType() == 'vector': - # if 'info' not in self.GetLayerInfo(self.layer_selected): - # info = grass.parse_command('v.info', - # flags = 'e', - # map = layer.GetName()) - # self.SetLayerInfo(self.layer_selected, key = 'info', value = info) - # info = self.GetLayerInfo(self.layer_selected, key = 'info') - # if info and info['format'] != 'native' and \ - # info['format'].split(',')[1] == 'PostgreSQL': - # self.popupMenu.Append(self.popupID['sql'], text = _("SQL Spatial Query")) - # self.Bind(wx.EVT_MENU, self.OnSqlQuery, id = self.popupID['sql']) + # if layer and layer.GetType() == "vector": + # if "info" not in self.GetLayerInfo(self.layer_selected): + # info = grass.parse_command( + # "v.info", flags="e", map=layer.GetName() + # ) + # self.SetLayerInfo(self.layer_selected, key="info", value=info) + # info = self.GetLayerInfo(self.layer_selected, key="info") + # if ( + # info + # and info["format"] != "native" + # and info["format"].split(",")[1] == "PostgreSQL" + # ): + # self.popupMenu.Append( + # self.popupID["sql"], text=_("SQL Spatial Query") + # ) + # self.Bind(wx.EVT_MENU, self.OnSqlQuery, id=self.popupID["sql"]) if layer.GetMapset() != currentMapset: # only vector map in current mapset can be edited diff --git a/gui/wxpython/location_wizard/dialogs.py b/gui/wxpython/location_wizard/dialogs.py index 236913c211b..8c48d75cf18 100644 --- a/gui/wxpython/location_wizard/dialogs.py +++ b/gui/wxpython/location_wizard/dialogs.py @@ -239,10 +239,12 @@ def MakeSettings3DPaneContent(self, pane): self.ttbres = TextCtrl( parent=pane, id=wx.ID_ANY, value=str(self.tbres), size=(150, -1) ) - # self.tnsres3 = wx.TextCtrl(parent = pane, id = wx.ID_ANY, value = str(self.nsres3), - # size = (150, -1)) - # self.tewres3 = wx.TextCtrl(parent = pane, id = wx.ID_ANY, value = str(self.ewres3), - # size = (150, -1)) + # self.tnsres3 = wx.TextCtrl( + # parent=pane, id=wx.ID_ANY, value=str(self.nsres3), size=(150, -1) + # ) + # self.tewres3 = wx.TextCtrl( + # parent=pane, id=wx.ID_ANY, value=str(self.ewres3), size=(150, -1) + # ) # labels self.ldepth = StaticText(parent=pane, label=_("Depth: %d") % self.depth) @@ -280,20 +282,30 @@ def MakeSettings3DPaneContent(self, pane): ) # res - # gridSizer.Add(item = wx.StaticText(parent = pane, label = _("3D N-S resolution")), - # flag = wx.ALIGN_CENTER | - # wx.LEFT | wx.RIGHT | wx.TOP, border = 5, - # pos = (2, 1)) - # gridSizer.Add(item = self.tnsres3, - # flag = wx.ALIGN_CENTER_HORIZONTAL | - # wx.ALL, border = 5, pos = (3, 1)) - # gridSizer.Add(item = wx.StaticText(parent = pane, label = _("3D E-W resolution")), - # flag = wx.ALIGN_CENTER | - # wx.LEFT | wx.RIGHT | wx.TOP, border = 5, - # pos = (2, 3)) - # gridSizer.Add(item = self.tewres3, - # flag = wx.ALIGN_CENTER_HORIZONTAL | - # wx.ALL, border = 5, pos = (3, 3)) + # gridSizer.Add( + # item=wx.StaticText(parent=pane, label=_("3D N-S resolution")), + # flag=wx.ALIGN_CENTER | wx.LEFT | wx.RIGHT | wx.TOP, + # border=5, + # pos=(2, 1), + # ) + # gridSizer.Add( + # item=self.tnsres3, + # flag=wx.ALIGN_CENTER_HORIZONTAL | wx.ALL, + # border=5, + # pos=(3, 1), + # ) + # gridSizer.Add( + # item=wx.StaticText(parent=pane, label=_("3D E-W resolution")), + # flag=wx.ALIGN_CENTER | wx.LEFT | wx.RIGHT | wx.TOP, + # border=5, + # pos=(2, 3), + # ) + # gridSizer.Add( + # item=self.tewres3, + # flag=wx.ALIGN_CENTER_HORIZONTAL | wx.ALL, + # border=5, + # pos=(3, 3), + # ) # rows/cols/cells gridSizer.Add( @@ -527,10 +539,10 @@ def OnValue(self, event): self.top = float(event.GetString()) elif event.GetId() == self.tbottom.GetId(): self.bottom = float(event.GetString()) - # elif event.GetId() == self.tnsres3.GetId(): - # self.nsres3 = float(event.GetString()) - # elif event.GetId() == self.tewres3.GetId(): - # self.ewres3 = float(event.GetString()) + # elif event.GetId() == self.tnsres3.GetId(): + # self.nsres3 = float(event.GetString()) + # elif event.GetId() == self.tewres3.GetId(): + # self.ewres3 = float(event.GetString()) elif event.GetId() == self.ttbres.GetId(): self.tbres = float(event.GetString()) diff --git a/gui/wxpython/main_window/frame.py b/gui/wxpython/main_window/frame.py index 2494077e7e9..3f005defc18 100644 --- a/gui/wxpython/main_window/frame.py +++ b/gui/wxpython/main_window/frame.py @@ -1043,9 +1043,9 @@ def _renamePageNoEvent(self, pgnum_dict, is_docked, text): ) def _closePageNoEvent(self, pgnum_dict, is_docked): - """If map display is docked, close page and destroy map display without generating - layer notebook page closing event. If map display is undocked, close only - layer notebook page, not map notebook page. + """If map display is docked, close page and destroy map display without + generating layer notebook page closing event. If map display is undocked, + close only layer notebook page, not map notebook page. :param dict pgnum_dict: dict "layers" key represent map display notebook layers tree page index and diff --git a/gui/wxpython/mapdisp/frame.py b/gui/wxpython/mapdisp/frame.py index 6e10937ec6d..c9aeb6f07db 100644 --- a/gui/wxpython/mapdisp/frame.py +++ b/gui/wxpython/mapdisp/frame.py @@ -1237,7 +1237,8 @@ def OnMeasureArea(self, event): def _onMeasure(self, controller): """Starts measurement mode. - :param controller: measurement class (MeasureDistanceController, MeasureAreaController) + :param controller: measurement class (MeasureDistanceController, + MeasureAreaController) """ self.measureController = controller(self._giface, mapWindow=self.GetMapWindow()) # assure that the mode is ended and lines are cleared whenever other @@ -1303,8 +1304,8 @@ def OnScatterplot(self, event): win.CentreOnParent() win.Show() - # Open raster select dialog to make sure that at least 2 rasters (and the desired rasters) - # are selected to be plotted + # Open raster select dialog to make sure that at least 2 rasters (and the + # desired rasters) are selected to be plotted win.OnSelectRaster(None) def OnHistogram(self, event): diff --git a/gui/wxpython/mapdisp/main.py b/gui/wxpython/mapdisp/main.py index 6b6256a915a..9a26378eb1e 100644 --- a/gui/wxpython/mapdisp/main.py +++ b/gui/wxpython/mapdisp/main.py @@ -25,7 +25,7 @@ @author Martin Landa @author Vaclav Petras (MapPanelBase) @author Anna Kratochvilova (MapPanelBase) -""" +""" # noqa: E501 import os import sys @@ -227,7 +227,8 @@ def GetLayersFromCmdFile(self): if layersOrder[i] == -1: layersOrder[i] = next_layer next_layer += 1 - # layer must be put higher in render order (same cmd was insered more times) + # layer must be put higher in render order (same cmd was + # insered more times) # TODO delete rendurant cmds from cmd file? else: for j, l_order in enumerate(layersOrder): diff --git a/gui/wxpython/mapdisp/statusbar.py b/gui/wxpython/mapdisp/statusbar.py index fb8bb4d6528..43211341147 100644 --- a/gui/wxpython/mapdisp/statusbar.py +++ b/gui/wxpython/mapdisp/statusbar.py @@ -53,10 +53,10 @@ class SbManager: Statusbar manager manages items added by AddStatusbarItem method. Provides progress bar (SbProgress). - Items with position 0 are shown according to selection in Map Display settings dialog. - Only one item of the same class is supposed to be in statusbar. - Manager user have to create statusbar on his own, add items to manager - and call Update method to show particular widgets. + Items with position 0 are shown according to selection in Map Display settings + dialog. Only one item of the same class is supposed to be in statusbar. Manager + user have to create statusbar on his own, add items to manager and call Update + method to show particular widgets. User settings (group = 'display', key = 'statusbarMode', subkey = 'selection') are taken into account. @@ -286,7 +286,8 @@ def SetProgress(self, range, value, text): self.statusbar.SetStatusText(text) def OnContextMenu(self, event): - """Popup context menu enabling to choose a widget that will be shown in statusbar.""" + """Popup context menu enabling to choose a widget that will be shown in + statusbar.""" def setSbItemProperty(idx): self.mapFrame.mapWindowProperties.sbItem = idx @@ -381,7 +382,8 @@ def _update(self, longHelp): self.mapFrame.StatusbarEnableLongHelp(longHelp) def Update(self): - """Called when statusbar action is activated (e.g. through Map Display settings).""" + """Called when statusbar action is activated (e.g. through Map Display + settings).""" self._update(longHelp=False) @@ -533,7 +535,8 @@ def ReprojectENToMap(self, e, n, useDefinedProjection): :param e,n: coordinate (for DMS string, else float or string) :param useDefinedProjection: projection defined by user in settings dialog - @throws SbException if useDefinedProjection is True and projection is not defined in UserSettings + @throws SbException if useDefinedProjection is True and projection is not + defined in UserSettings """ if useDefinedProjection: settings = UserSettings.Get( @@ -788,7 +791,8 @@ def ReprojectENFromMap(self, e, n, useDefinedProjection, precision, format): :param e,n: coordinate - @throws SbException if useDefinedProjection is True and projection is not defined in UserSettings + @throws SbException if useDefinedProjection is True and projection is not + defined in UserSettings """ if useDefinedProjection: settings = UserSettings.Get( @@ -867,7 +871,8 @@ def ReprojectRegionFromMap(self, region, useDefinedProjection, precision, format """Reproject region values .. todo:: - reorganize this method to remove code useful only for derived class SbCompRegionExtent + reorganize this method to remove code useful only for derived class + SbCompRegionExtent """ if useDefinedProjection: settings = UserSettings.Get( diff --git a/gui/wxpython/mapdisp/test_mapdisp.py b/gui/wxpython/mapdisp/test_mapdisp.py index 5fb13857a4e..71a1a81f985 100755 --- a/gui/wxpython/mapdisp/test_mapdisp.py +++ b/gui/wxpython/mapdisp/test_mapdisp.py @@ -161,8 +161,10 @@ def testMapDisplay(self, giface, map_): from mapdisp.frame import MapFrame # known issues (should be similar with d.mon): - # * opening map in digitizer ends with: vdigit/toolbars.py:723: 'selection' referenced before assignment - # * nviz start fails (closes window? segfaults?) after mapdisp/frame.py:306: 'NoneType' object has no attribute 'GetLayerNotebook' + # * opening map in digitizer ends with: vdigit/toolbars.py:723: 'selection' + # referenced before assignment + # * nviz start fails (closes window? segfaults?) after mapdisp/frame.py:306: + # 'NoneType' object has no attribute 'GetLayerNotebook' frame = MapFrame( parent=None, title=_("Map display test"), giface=giface, Map=map_ ) diff --git a/gui/wxpython/mapdisp/toolbars.py b/gui/wxpython/mapdisp/toolbars.py index 3da61d60398..3589c7fd5de 100644 --- a/gui/wxpython/mapdisp/toolbars.py +++ b/gui/wxpython/mapdisp/toolbars.py @@ -120,7 +120,8 @@ def __init__(self, parent, toolSwitcher, giface): self._giface.WriteWarning(_("Reason: %s") % errorMsg) self._giface.WriteLog( _( - "Note that the wxGUI's vector digitizer is disabled in this installation. " + "Note that the wxGUI's vector digitizer is disabled in this " + "installation." "Please keep an eye out for updated versions of GRASS. " 'In the meantime you can use "v.edit" for non-interactive editing ' "from the Develop vector map menu." diff --git a/gui/wxpython/mapwin/base.py b/gui/wxpython/mapwin/base.py index 6e179b6aa00..3a27713dfd9 100644 --- a/gui/wxpython/mapwin/base.py +++ b/gui/wxpython/mapwin/base.py @@ -255,8 +255,9 @@ def OnButton(self, event): # current map display's map window # expects LayerManager to be the parent self.mapwin = self.parent.GetLayerTree().GetMapDisplay().GetWindow() - if self.mapwin.RegisterEventHandler(wx.EVT_LEFT_DOWN, self.OnMouseAction, - 'cross'): + if self.mapwin.RegisterEventHandler( + wx.EVT_LEFT_DOWN, self.OnMouseAction, "cross" + ): self.parent.GetLayerTree().GetMapDisplay().Raise() else: # handle that you cannot get coordinates @@ -264,8 +265,10 @@ def OnButton(self, event): def OnMouseAction(self, event): # get real world coordinates of mouse click coor = self.mapwin.Pixel2Cell(event.GetPositionTuple()[:]) - self.text.SetLabel('Coor: ' + str(coor)) - self.mapwin.UnregisterMouseEventHandler(wx.EVT_LEFT_DOWN, self.OnMouseAction) + self.text.SetLabel("Coor: " + str(coor)) + self.mapwin.UnregisterMouseEventHandler( + wx.EVT_LEFT_DOWN, self.OnMouseAction + ) event.Skip() @@ -390,7 +393,8 @@ def OnMotion(self, event): def GetLastEN(self): """Returns last coordinates of mouse cursor. - @deprecated This method is deprecated. Use Signal with coordinates as parameters. + @deprecated This method is deprecated. Use Signal with coordinates as + parameters. :func:`OnMotion` """ diff --git a/gui/wxpython/mapwin/buffered.py b/gui/wxpython/mapwin/buffered.py index 6f7f918af3e..23989ae865f 100644 --- a/gui/wxpython/mapwin/buffered.py +++ b/gui/wxpython/mapwin/buffered.py @@ -866,7 +866,8 @@ def UpdateMap(self, render=True, renderVector=True, delay=0.0): giface :param render: re-render map composition - :param renderVector: re-render vector map layer enabled for editing (used for digitizer) + :param renderVector: re-render vector map layer enabled for editing (used for + digitizer) :param delay: defines time threshold in seconds for postponing rendering to merge more update requests. @@ -2254,7 +2255,8 @@ def RegisterGraphicsToDraw( is not defined DrawCross method is used for type "point", DrawLines method for type "line", DrawRectangle for "rectangle". - :param mapCoords: True if map coordinates should be set by user, otherwise pixels + :param mapCoords: True if map coordinates should be set by user, otherwise + pixels :return: reference to GraphicsSet, which was added. """ diff --git a/gui/wxpython/mapwin/decorations.py b/gui/wxpython/mapwin/decorations.py index 2eb5abe6075..9e2051a435d 100644 --- a/gui/wxpython/mapwin/decorations.py +++ b/gui/wxpython/mapwin/decorations.py @@ -299,7 +299,8 @@ def GetPlacement(self, screensize): for param in self._cmd: if not param.startswith("at"): continue - # if the at= is the default, we will move the legend from the center to bottom left + # if the at= is the default, we will move the legend from the center to + # bottom left if param == self._defaultAt: b, t, l, r = 5, 50, 7, 10 else: diff --git a/gui/wxpython/modules/colorrules.py b/gui/wxpython/modules/colorrules.py index 96606fb0653..626c0ea93d5 100644 --- a/gui/wxpython/modules/colorrules.py +++ b/gui/wxpython/modules/colorrules.py @@ -1403,8 +1403,8 @@ def AddTemporaryColumn(self, type): :param type: type of column (e.g. vachar(11))""" if not self.CheckMapset(): return - # because more than one dialog with the same map can be opened we must test column name and - # create another one + # because more than one dialog with the same map can be opened we must test + # column name and create another one while ( self.properties["tmpColumn"] in self.dbInfo.GetTableDesc(self.properties["table"]).keys() diff --git a/gui/wxpython/modules/import_export.py b/gui/wxpython/modules/import_export.py index 97a646037ed..da082feb68d 100644 --- a/gui/wxpython/modules/import_export.py +++ b/gui/wxpython/modules/import_export.py @@ -959,7 +959,8 @@ def __init__( parent=self.panel, id=wx.ID_ANY, label=_( - "Projection of following layers do not match with projection of current location. " + "Projection of following layers do not match with projection of " + "current location. " ), ) diff --git a/gui/wxpython/nviz/mapwindow.py b/gui/wxpython/nviz/mapwindow.py index fa9f51207da..52548983f58 100644 --- a/gui/wxpython/nviz/mapwindow.py +++ b/gui/wxpython/nviz/mapwindow.py @@ -2370,7 +2370,8 @@ def GetLayerId(self, type, name, vsubtyp=None): return -1 def ReloadLayersData(self): - """Delete nviz data of all loaded layers and reload them from current settings""" + """Delete nviz data of all loaded layers and reload them from current + settings""" for item in self.layers: type = self.tree.GetLayerInfo(item, key="type") layer = self.tree.GetLayerInfo(item, key="maplayer") diff --git a/gui/wxpython/nviz/tools.py b/gui/wxpython/nviz/tools.py index 5d65f38c6b8..686be2e98ef 100644 --- a/gui/wxpython/nviz/tools.py +++ b/gui/wxpython/nviz/tools.py @@ -329,7 +329,8 @@ def _createViewPage(self): gridSizer.Add(posSizer, pos=(0, 0)) # perspective - # set initial defaults here (or perhaps in a default values file), not in user settings + # set initial defaults here (or perhaps in a default values file), not in user + # settings # todo: consider setting an absolute max at 360 instead of undefined. # (leave the default max value at pi) tooltip = _( @@ -488,7 +489,8 @@ def _createViewPage(self): top.SetName("top") top.SetToolTip( _( - "Sets the viewer directly over the scene's center position. This top view orients approximately north south." + "Sets the viewer directly over the scene's center position. This top " + "view orients approximately north south." ) ) viewSizer.Add(top, flag=wx.TOP | wx.BOTTOM | wx.ALIGN_CENTER_VERTICAL, border=5) @@ -685,7 +687,8 @@ def _createAnimationPage(self): ) prefixCtrl.SetToolTip( _( - "Generated files names will look like this: prefix_1.ppm, prefix_2.ppm, ..." + "Generated files names will look like this: prefix_1.ppm, " + "prefix_2.ppm, ..." ) ) fileTypeLabel = StaticText(parent=panel, id=wx.ID_ANY, label=_("File format:")) @@ -1425,7 +1428,8 @@ def _createCPlanePage(self, parent): flag=wx.ALIGN_CENTER_VERTICAL, ) tooltip = _( - "Sets the Z coordinate of the current cutting plane (only meaningful when tilt is not 0)" + "Sets the Z coordinate of the current cutting plane (only meaningful when " + "tilt is not 0)" ) self._createControl( panel, @@ -2678,7 +2682,8 @@ def OnRecord(self, event): if not anim.IsPaused(): if anim.Exists() and not anim.IsSaved(): msg = _( - "Do you want to record new animation without saving the previous one?" + "Do you want to record new animation without saving the previous " + "one?" ) dlg = wx.MessageDialog( parent=self, @@ -4295,7 +4300,7 @@ def OnVectorPoints(self, event): marker = self.FindWindowById( self.win["vector"]["points"]["marker"] ).GetSelection() - # width = self.FindWindowById(self.win['vector']['points']['width']).GetValue() + # width = self.FindWindowById(self.win['vector']['points']['width']).GetValue() for attrb in ("size", "marker"): data["vector"]["points"][attrb]["update"] = None diff --git a/gui/wxpython/photo2image/ip2i_manager.py b/gui/wxpython/photo2image/ip2i_manager.py index 7af883ccf6a..fc89994607a 100644 --- a/gui/wxpython/photo2image/ip2i_manager.py +++ b/gui/wxpython/photo2image/ip2i_manager.py @@ -22,7 +22,8 @@ @author Original version improved by Martin Landa @author Rewritten by Markus Metz redesign georectfier -> GCP Manage @author Support for GraphicsSet added by Stepan Turek (2012) -@author Yann modified: graphical replacement of i.photo.2image (was in v6 using Vask lib) +@author Yann modified: graphical replacement of i.photo.2image + (was in v6 using Vask lib) """ import os @@ -473,7 +474,7 @@ def __init__( f.write("#\tsource\t\ttarget\t\tstatus\n") f.write("#\teast\tnorth\teast\tnorth\t(1=ok, 0=ignore)\n") f.write( - "#----------------------- ----------------------- ---------------\n" + "#----------------------- ----------------------- ---------------\n" # noqa: E501 ) check = "0" @@ -894,7 +895,7 @@ def SaveGCPs(self, event): f.write("#\tsource\t\ttarget\t\tstatus\n") f.write("#\teast\tnorth\teast\tnorth\t(1=ok, 0=ignore)\n") f.write( - "#----------------------- ----------------------- ---------------\n" + "#----------------------- ----------------------- ---------------\n" # noqa: E501 ) for index in range(self.list.GetItemCount()): @@ -1040,7 +1041,8 @@ def ReloadGCPs(self, event): targetMapWin.UpdateMap(render=False) def OnFocus(self, event): - # TODO: it is here just to remove old or obsolete beavior of base class gcp/MapPanel? + # TODO: it is here just to remove old or obsolete beavior of base class + # gcp/MapPanel? # self.grwiz.SwitchEnv('source') pass @@ -1251,16 +1253,19 @@ def OnGROrder(self, event): if self.gr_order == 1: minNumOfItems = 3 - # self.SetStatusText(_('Insufficient points, 3+ points needed for 1st order')) + # self.SetStatusText(_( + # "Insufficient points, 3+ points needed for 1st order")) elif self.gr_order == 2: minNumOfItems = 6 diff = 6 - numOfItems - # self.SetStatusText(_('Insufficient points, 6+ points needed for 2nd order')) + # self.SetStatusText(_( + # "Insufficient points, 6+ points needed for 2nd order")) elif self.gr_order == 3: minNumOfItems = 10 - # self.SetStatusText(_('Insufficient points, 10+ points needed for 3rd order')) + # self.SetStatusText(_( + # "Insufficient points, 10+ points needed for 3rd order")) for i in range(minNumOfItems - numOfItems): self.AddGCP(None) @@ -2039,7 +2044,8 @@ def __init__( btnSave.Bind(wx.EVT_BUTTON, self.OnSave) btnSave.SetToolTip( _( - "Apply and save changes to user settings file (default for next sessions)" + "Apply and save changes to user settings file (default for next " + "sessions)" ) ) btnClose.Bind(wx.EVT_BUTTON, self.OnClose) diff --git a/gui/wxpython/psmap/dialogs.py b/gui/wxpython/psmap/dialogs.py index 88c2f5abc98..ce10ad3ba96 100644 --- a/gui/wxpython/psmap/dialogs.py +++ b/gui/wxpython/psmap/dialogs.py @@ -436,19 +436,28 @@ def AddExtendedPosition(self, panel, gridBagSizer, dialogDict): def AddFont(self, parent, dialogDict, color=True): parent.font = dict() - ## parent.font['fontLabel'] = wx.StaticText(parent, id = wx.ID_ANY, label = _("Choose font:")) - ## parent.font['fontCtrl'] = wx.FontPickerCtrl(parent, id = wx.ID_ANY) - ## - # parent.font['fontCtrl'].SetSelectedFont( - # wx.FontFromNativeInfoString(dialogDict['font'] + " " + str(dialogDict['fontsize']))) - # parent.font['fontCtrl'].SetMaxPointSize(50) - ## + # parent.font["fontLabel"] = wx.StaticText( + # parent, id=wx.ID_ANY, label=_("Choose font:") + # ) + # parent.font["fontCtrl"] = wx.FontPickerCtrl(parent, id=wx.ID_ANY) + # + # parent.font["fontCtrl"].SetSelectedFont( + # wx.FontFromNativeInfoString( + # dialogDict["font"] + " " + str(dialogDict["fontsize"]) + # ) + # ) + # parent.font["fontCtrl"].SetMaxPointSize(50) + # # if color: - ## parent.font['colorLabel'] = wx.StaticText(parent, id = wx.ID_ANY, label = _("Choose color:")) - ## parent.font['colorCtrl'] = ColourPickerCtrl(parent, id = wx.ID_ANY, style=wx.FNTP_FONTDESC_AS_LABEL) - # parent.font['colorCtrl'].SetColour(dialogDict['color']) - - # parent.font['colorCtrl'].SetColour(convertRGB(dialogDict['color'])) + # parent.font["colorLabel"] = wx.StaticText( + # parent, id=wx.ID_ANY, label=_("Choose color:") + # ) + # parent.font["colorCtrl"] = ColourPickerCtrl( + # parent, id=wx.ID_ANY, style=wx.FNTP_FONTDESC_AS_LABEL + # ) + # parent.font["colorCtrl"].SetColour(dialogDict["color"]) + # + # parent.font["colorCtrl"].SetColour(convertRGB(dialogDict["color"])) parent.font["fontLabel"] = StaticText(parent, id=wx.ID_ANY, label=_("Font:")) parent.font["fontSizeLabel"] = StaticText( @@ -485,13 +494,30 @@ def AddFont(self, parent, dialogDict, color=True): parent.font["colorCtrl"] = ColourPickerCtrl(parent, id=wx.ID_ANY) parent.font["colorCtrl"].SetColour(convertRGB(dialogDict["color"])) - ## parent.font['colorLabel'] = wx.StaticText(parent, id = wx.ID_ANY, label = _("Color:")) - # colorChoices = [ 'aqua', 'black', 'blue', 'brown', 'cyan', 'gray', 'green', 'indigo', 'magenta',\ - # 'orange', 'purple', 'red', 'violet', 'white', 'yellow'] - ## parent.colorCtrl = Choice(parent, id = wx.ID_ANY, choices = colorChoices) - # parent.colorCtrl.SetStringSelection(parent.rLegendDict['color']) - ## parent.font['colorCtrl'] = ColourPickerCtrl(parent, id = wx.ID_ANY) - # parent.font['colorCtrl'].SetColour(dialogDict['color']) + # parent.font["colorLabel"] = wx.StaticText( + # parent, id=wx.ID_ANY, label=_("Color:") + # ) + # colorChoices = [ + # "aqua", + # "black", + # "blue", + # "brown", + # "cyan", + # "gray", + # "green", + # "indigo", + # "magenta", + # "orange", + # "purple", + # "red", + # "violet", + # "white", + # "yellow", + # ] + # parent.colorCtrl = Choice(parent, id=wx.ID_ANY, choices=colorChoices) + # parent.colorCtrl.SetStringSelection(parent.rLegendDict["color"]) + # parent.font["colorCtrl"] = ColourPickerCtrl(parent, id=wx.ID_ANY) + # parent.font["colorCtrl"].SetColour(dialogDict["color"]) def OnApply(self, event): ok = self.update() @@ -1257,7 +1283,8 @@ def OnScaleChoice(self, event): self.mapText.SetLabel(self.mapOrRegionText[0]) self.select.SetToolTip( _( - "Region is set to match this map,\nraster or vector map must be added later" + "Region is set to match this map,\nraster or vector map must " + "be added later" ) ) @@ -2082,11 +2109,15 @@ def updateDialog(self): pass -# if 'map' in self.parent.openDialogs: -# if self.parent.openDialogs['map'].mPanel.rasterTypeRadio.GetValue()\ -# and self.parent.openDialogs['map'].mPanel.select.GetValue(): -# if self.parent.openDialogs['map'].mPanel.drawMap.IsChecked(): -# self.rPanel.rasterSelect.SetValue(self.parent.openDialogs['map'].mPanel.select.GetValue()) +# if "map" in self.parent.openDialogs: +# if ( +# self.parent.openDialogs["map"].mPanel.rasterTypeRadio.GetValue() +# and self.parent.openDialogs["map"].mPanel.select.GetValue() +# ): +# if self.parent.openDialogs["map"].mPanel.drawMap.IsChecked(): +# self.rPanel.rasterSelect.SetValue( +# self.parent.openDialogs["map"].mPanel.select.GetValue() +# ) class MainVectorDialog(PsmapDialog): @@ -2941,13 +2972,21 @@ def _StyleLinePanel(self, notebook): styleText = StaticText(panel, id=wx.ID_ANY, label=_("Choose line style:")) penStyles = ["solid", "dashed", "dotted", "dashdotted"] self.styleCombo = PenStyleComboBox(panel, choices=penStyles) - # self.styleCombo = wx.ComboBox(panel, id = wx.ID_ANY, - ## choices = ["solid", "dashed", "dotted", "dashdotted"], - # validator = TCValidator(flag = 'ZERO_AND_ONE_ONLY')) - # self.styleCombo.SetToolTipString(_("It's possible to enter a series of 0's and 1's too. "\ - ## "The first block of repeated zeros or ones represents 'draw', "\ - ## "the second block represents 'blank'. An even number of blocks "\ - # "will repeat the pattern, an odd number of blocks will alternate the pattern.")) + # self.styleCombo = wx.ComboBox( + # panel, + # id=wx.ID_ANY, + # choices=["solid", "dashed", "dotted", "dashdotted"], + # validator=TCValidator(flag="ZERO_AND_ONE_ONLY"), + # ) + # self.styleCombo.SetToolTipString( + # _( + # "It's possible to enter a series of 0's and 1's too. " + # "The first block of repeated zeros or ones represents 'draw', " + # "the second block represents 'blank'. An even number of blocks " + # "will repeat the pattern, an odd number of blocks will alternate " + # "the pattern." + # ) + # ) linecapText = StaticText(panel, id=wx.ID_ANY, label=_("Choose linecap:")) self.linecapChoice = Choice( panel, id=wx.ID_ANY, choices=["butt", "round", "extended_butt"] @@ -3763,8 +3802,10 @@ def sizePositionFont(self, legendType, parent, mainSizer): ) if legendType == "raster": - ## panel.defaultSize = wx.CheckBox(panel, id = wx.ID_ANY, label = _("Use default size")) - # panel.defaultSize.SetValue(legendDict['defaultSize']) + # panel.defaultSize = wx.CheckBox( + # panel, id=wx.ID_ANY, label=_("Use default size") + # ) + # panel.defaultSize.SetValue(legendDict["defaultSize"]) panel.heightOrColumnsLabel = StaticText( panel, id=wx.ID_ANY, label=_("Height:") @@ -3782,7 +3823,13 @@ def sizePositionFont(self, legendType, parent, mainSizer): ) self.rSizeGBSizer = wx.GridBagSizer(hgap=5, vgap=5) - ## self.rSizeGBSizer.Add(panel.defaultSize, pos = (0,0), span = (1,2), flag = wx.ALIGN_CENTER_VERTICAL, border = 0) + # self.rSizeGBSizer.Add( + # panel.defaultSize, + # pos=(0, 0), + # span=(1, 2), + # flag=wx.ALIGN_CENTER_VERTICAL, + # border=0, + # ) self.rSizeGBSizer.Add( width, pos=(0, 0), flag=wx.ALIGN_CENTER_VERTICAL, border=0 ) @@ -3926,7 +3973,8 @@ def sizePositionFont(self, legendType, parent, mainSizer): # some enable/disable methods def OnIsLegend(self, event): - """Enables and disables controls, it depends if raster or vector legend is checked""" + """Enables and disables controls, it depends if raster or vector legend is + checked""" page = self.notebook.GetSelection() if page == 0 or event is None: children = self.panelRaster.GetChildren() @@ -4096,8 +4144,9 @@ def OnSpan(self, event): self.panelVector.spanTextCtrl.Enable(self.panelVector.spanRadio.GetValue()) def OnFont(self, event): - """Changes default width according to fontsize, width [inch] = fontsize[pt]/24""" - ## fontsize = self.panelVector.font['fontCtrl'].GetSelectedFont().GetPointSize() + """Changes default width according to fontsize, + width [inch] = fontsize[pt]/24""" + # fontsize = self.panelVector.font["fontCtrl"].GetSelectedFont().GetPointSize() fontsize = self.panelVector.font["fontSizeCtrl"].GetValue() unit = self.unitConv.findUnit( self.panelVector.units["unitsCtrl"].GetStringSelection() @@ -4928,7 +4977,11 @@ def _scalebarPanel(self): else: bitmap = wx.Bitmap(path) self.sbCombo.Append(item="", bitmap=bitmap, clientData=item[0]) - # self.sbCombo.Append(item = 'simple', bitmap = wx.Bitmap("./images/scalebar-simple.png"), clientData = 's') + # self.sbCombo.Append( + # item="simple", + # bitmap=wx.Bitmap("./images/scalebar-simple.png"), + # clientData="s", + # ) if self.scalebarDict["scalebar"] == "f": self.sbCombo.SetSelection(0) elif self.scalebarDict["scalebar"] == "s": diff --git a/gui/wxpython/psmap/frame.py b/gui/wxpython/psmap/frame.py index 88a4ad08dd5..ef6bc17f59b 100644 --- a/gui/wxpython/psmap/frame.py +++ b/gui/wxpython/psmap/frame.py @@ -317,7 +317,8 @@ def OnPDFFile(self, event): GMessage( parent=self, message=_( - "Program ps2pdf is not available. Please install it first to create PDF." + "Program ps2pdf is not available. Please install it first to " + "create PDF." ), ) return @@ -505,7 +506,8 @@ def OnCmdDone(self, event): self, title=_("Preview not available"), message=_( - "Preview is not available probably because Ghostscript is not installed or not on PATH." + "Preview is not available probably because Ghostscript is not " + "installed or not on PATH." ), hyperlink="https://www.ghostscript.com/releases/gsdnld.html", hyperlinkLabel=_( @@ -1062,7 +1064,8 @@ def getTextExtent(self, textDict): return (0, 0) def getInitMap(self): - """Create default map frame when no map is selected, needed for coordinates in map units""" + """Create default map frame when no map is selected, needed for coordinates in + map units""" instrFile = grass.tempfile() instrFileFd = open(instrFile, mode="wb") content = self.InstructionFile() @@ -1457,7 +1460,8 @@ def Clear(self): self.SetPage() def CanvasPaperCoordinates(self, rect, canvasToPaper=True): - """Converts canvas (pixel) -> paper (inch) coordinates and size and vice versa""" + """Converts canvas (pixel) -> paper (inch) coordinates and size and + vice versa""" units = UnitConversion(self) @@ -1524,7 +1528,8 @@ def modifyRectangle(self, r): return r def RecalculateEN(self): - """Recalculate east and north for texts (eps, points) after their or map's movement""" + """Recalculate east and north for texts (eps, points) after their or map's + movement""" try: mapId = self.instruction.FindInstructionByType("map").id except AttributeError: @@ -2528,12 +2533,16 @@ def DrawRotText(self, pdc, drawId, textDict, coords, bounds): pdc.BeginDrawing() # border is not redrawn when zoom changes, why? - # if textDict['border'] != 'none' and not rot: - ## units = UnitConversion(self) - # borderWidth = units.convert(value = textDict['width'], - # fromUnit = 'point', toUnit = 'pixel' ) * self.currScale - ## pdc.SetPen(wx.Pen(colour = convertRGB(textDict['border']), width = borderWidth)) - # pdc.DrawRectangle(*bounds) + # if textDict["border"] != "none" and not rot: + # units = UnitConversion(self) + # borderWidth = ( + # units.convert( + # value=textDict["width"], fromUnit="point", toUnit="pixel") + # * self.currScale + # ) + # pdc.SetPen(wx.Pen(colour=convertRGB( + # textDict["border"]), width=borderWidth)) + # pdc.DrawRectangle(*bounds) if background: pdc.SetTextBackground(convertRGB(background)) diff --git a/gui/wxpython/psmap/instructions.py b/gui/wxpython/psmap/instructions.py index 0b36a2ae7ab..c527fe65df0 100644 --- a/gui/wxpython/psmap/instructions.py +++ b/gui/wxpython/psmap/instructions.py @@ -738,7 +738,8 @@ def Read(self, instruction, text, **kwargs): ): GWarning( _( - "Map frame position changed, old value: %(old1)s %(old2)s\nnew value: %(new1)s %(new2)s" + "Map frame position changed, old value: %(old1)s %(old2)s\n" + "new value: %(new1)s %(new2)s" ) % { "old1": maploc[0], @@ -748,7 +749,12 @@ def Read(self, instruction, text, **kwargs): } ) - # instr['rect'] = wx.Rect2D(float(maploc[0]), float(maploc[1]), self.instruction['rect'][2], self.instruction['rect'][3]) + # instr["rect"] = wx.Rect2D( + # float(maploc[0]), + # float(maploc[1]), + # self.instruction["rect"][2], + # self.instruction["rect"][3], + # ) if len(maploc) == 4: if ( abs(self.instruction["rect"].Get()[2] - float(maploc[2])) > 0.5 @@ -756,7 +762,8 @@ def Read(self, instruction, text, **kwargs): ): GWarning( _( - "Map frame size changed, old value: %(old1)s %(old2)s\nnew value: %(new1)s %(new2)s" + "Map frame size changed, old value: %(old1)s %(old2)s\n" + "new value: %(new1)s %(new2)s" ) % { "old1": maploc[2], @@ -799,7 +806,8 @@ def __str__(self): else: instr = string.Template("paper $Format\n").substitute(self.instruction) instr += string.Template( - " left $Left\n right $Right\n bottom $Bottom\n top $Top\n end" + " left $Left\n right $Right\n bottom $Bottom\n top $Top\n" + " end" ).substitute(self.instruction) return instr @@ -829,7 +837,8 @@ def Read(self, instruction, text, **kwargs): except KeyError: GError( _( - "Failed to read instruction %(file)s.\nUnknown format %(for)s" + "Failed to read instruction %(file)s.\n" + "Unknown format %(for)s" ) % {"file": instruction, "for": format} ) diff --git a/gui/wxpython/rdigit/toolbars.py b/gui/wxpython/rdigit/toolbars.py index ec18102fbdf..277e4c11ff6 100644 --- a/gui/wxpython/rdigit/toolbars.py +++ b/gui/wxpython/rdigit/toolbars.py @@ -83,7 +83,8 @@ def __init__(self, parent, giface, controller, toolSwitcher): self._widthValueChanged() self._widthValue.SetToolTip( _( - "Width of currently digitized line or diameter of a digitized point in map units." + "Width of currently digitized line or diameter of a digitized point " + "in map units." ) ) labelWidth = StaticText(self, label=" %s" % _("Width:")) diff --git a/gui/wxpython/startup/locdownload.py b/gui/wxpython/startup/locdownload.py index 887e38b918b..588d30960d0 100644 --- a/gui/wxpython/startup/locdownload.py +++ b/gui/wxpython/startup/locdownload.py @@ -41,11 +41,11 @@ LOCATIONS = [ { "label": "Complete North Carolina dataset", - "url": "https://grass.osgeo.org/sampledata/north_carolina/nc_spm_08_grass7.tar.gz", + "url": "https://grass.osgeo.org/sampledata/north_carolina/nc_spm_08_grass7.tar.gz", # noqa: E501 }, { "label": "Basic North Carolina dataset", - "url": "https://grass.osgeo.org/sampledata/north_carolina/nc_basic_spm_grass7.tar.gz", + "url": "https://grass.osgeo.org/sampledata/north_carolina/nc_basic_spm_grass7.tar.gz", # noqa: E501 }, { "label": "World dataset in LatLong/WGS84", @@ -57,7 +57,7 @@ }, { "label": "Piemonte, Italy dataset", - "url": "https://grass.osgeo.org/sampledata/grassdata_piemonte_utm32n_wgs84_grass7.tar.gz", + "url": "https://grass.osgeo.org/sampledata/grassdata_piemonte_utm32n_wgs84_grass7.tar.gz", # noqa: E501 }, { "label": "Slovakia 3D precipitation voxel dataset", @@ -137,7 +137,9 @@ def _resize(self, heigth=-1): ) -# based on https://blog.shichao.io/2012/10/04/progress_speed_indicator_for_urlretrieve_in_python.html +# based on +# https://blog.shichao.io/2012/10/04/ +# progress_speed_indicator_for_urlretrieve_in_python.html def reporthook(count, block_size, total_size): global start_time if count == 0: @@ -243,7 +245,8 @@ def __init__(self, parent, database, locations=LOCATIONS): # It is not clear if all wx versions supports color, so try-except. # The color itself may not be correct for all platforms/system settings - # but in http://xoomer.virgilio.it/infinity77/wxPython/Widgets/wx.SystemSettings.html + # but in + # http://xoomer.virgilio.it/infinity77/wxPython/Widgets/wx.SystemSettings.html # there is no 'warning' color. try: self.message.SetForegroundColour(wx.Colour(255, 0, 0)) diff --git a/gui/wxpython/tools/build_modules_xml.py b/gui/wxpython/tools/build_modules_xml.py index 96ec07a7e5b..8dc341d7c75 100644 --- a/gui/wxpython/tools/build_modules_xml.py +++ b/gui/wxpython/tools/build_modules_xml.py @@ -22,7 +22,7 @@ def escapeXML(text): """This is a duplicate of function in core/toolboxes. - >>> escapeXML('<>&') + >>> escapeXML("<>&") '&lt;>&' """ return text.replace("<", "<").replace("&", "&").replace(">", ">") @@ -72,11 +72,11 @@ def parse_modules(fd): def get_module_metadata(name): """ - >>> get_module_metadata('g.region') + >>> get_module_metadata("g.region") ('Manages the boundary definitions for the geographic region.', ['general', 'settings']) - >>> get_module_metadata('m.proj') + >>> get_module_metadata("m.proj") ('Converts coordinates from one projection to another (cs2cs frontend).', ['miscellaneous', 'projection']) - """ + """ # noqa: E501 try: task = gtask.parse_interface(name) except ScriptError as exc: diff --git a/gui/wxpython/vdigit/preferences.py b/gui/wxpython/vdigit/preferences.py index b9eb12f38a3..cdd88f6b6d5 100644 --- a/gui/wxpython/vdigit/preferences.py +++ b/gui/wxpython/vdigit/preferences.py @@ -302,7 +302,8 @@ def _createGeneralPage(self, notebook): ) self.selectIn.SetToolTip( _( - "By default are selected all features overlapping selection bounding box " + "By default are selected all features overlapping selection bounding " + "box " ) ) @@ -631,7 +632,8 @@ def _createAttributesPage(self, notebook): check = CheckBox( parent=panel, id=wx.ID_ANY, label=self.geomAttrb[attrb]["label"] ) - # self.deleteRecord.SetValue(UserSettings.Get(group='vdigit', key="delRecord", subkey='enabled')) + # self.deleteRecord.SetValue(UserSettings.Get( + # group='vdigit', key="delRecord", subkey='enabled')) check.Bind(wx.EVT_CHECKBOX, self.OnGeomAttrb) # column (only numeric) column = ColumnSelect(parent=panel, size=(200, -1)) diff --git a/gui/wxpython/vdigit/toolbars.py b/gui/wxpython/vdigit/toolbars.py index fb461118d2a..e1af771c4d8 100644 --- a/gui/wxpython/vdigit/toolbars.py +++ b/gui/wxpython/vdigit/toolbars.py @@ -183,7 +183,8 @@ def _toolbarData(self): "deleteLine": MetaIcon( img="line-delete", label=_( - "Delete selected point(s), line(s), boundary(ies) or centroid(s) (Ctrl+D)" + "Delete selected point(s), line(s), boundary(ies) or " + "centroid(s) (Ctrl+D)" ), desc=_("Left: Select; Ctrl+Left: Unselect; Right: Confirm"), ), @@ -212,7 +213,8 @@ def _toolbarData(self): "moveLine": MetaIcon( img="line-move", label=_( - "Move selected point(s), line(s), boundary(ies) or centroid(s) (Ctrl+M)" + "Move selected point(s), line(s), boundary(ies) or " + "centroid(s) (Ctrl+M)" ), desc=_("Left: Select; Ctrl+Left: Unselect; Right: Confirm"), ), diff --git a/gui/wxpython/vdigit/wxdigit.py b/gui/wxpython/vdigit/wxdigit.py index 0c36100e561..ac95eb32131 100644 --- a/gui/wxpython/vdigit/wxdigit.py +++ b/gui/wxpython/vdigit/wxdigit.py @@ -200,7 +200,8 @@ def __init__(self, giface, mapwindow, driver=DisplayDriver): # signals parameter description: # old_bboxs - list of bboxes of boundary features, which covers changed areas # it is bbox of old state (before edit) - # old_areas_cats - list of area categories of boundary features of old state (before edit) + # old_areas_cats - + # list of area categories of boundary features of old state (before edit) # same position in both lists corresponds to same feature # new_bboxs = list of bboxes of created features / after edit @@ -237,7 +238,8 @@ def __del__(self): del self.bgMapInfo def EmitSignals(self, emit): - """Activate/deactivate signals which describes features changes during digitization.""" + """Activate/deactivate signals which describes features changes during + digitization.""" self.emit_signals = emit def CloseBackgroundMap(self): @@ -434,7 +436,8 @@ def _applyChangeset(self, changeset, undo): if Vect_line_alive(self.poMapInfo, line): Debug.msg( 3, - "IVDigit._applyChangeset(): changeset=%d, action=add, line=%d -> deleted", + "IVDigit._applyChangeset(): " + "changeset=%d, action=add, line=%d -> deleted", changeset, line, ) @@ -444,7 +447,8 @@ def _applyChangeset(self, changeset, undo): else: Debug.msg( 3, - "Digit.ApplyChangeset(): changeset=%d, action=add, line=%d dead", + "Digit.ApplyChangeset(): " + "changeset=%d, action=add, line=%d dead", changeset, line, ) @@ -455,7 +459,8 @@ def _applyChangeset(self, changeset, undo): if not Vect_line_alive(self.poMapInfo, line): Debug.msg( 3, - "Digit.ApplyChangeset(): changeset=%d, action=delete, line=%d -> added", + "Digit.ApplyChangeset(): " + "changeset=%d, action=delete, line=%d -> added", changeset, line, ) @@ -466,7 +471,8 @@ def _applyChangeset(self, changeset, undo): else: Debug.msg( 3, - "Digit.ApplyChangeset(): changeset=%d, action=delete, line=%d alive", + "Digit.ApplyChangeset(): " + "changeset=%d, action=delete, line=%d alive", changeset, line, ) diff --git a/gui/wxpython/vdigit/wxdisplay.py b/gui/wxpython/vdigit/wxdisplay.py index 988afc481ac..c44859c976b 100644 --- a/gui/wxpython/vdigit/wxdisplay.py +++ b/gui/wxpython/vdigit/wxdisplay.py @@ -818,7 +818,8 @@ def SetSelected(self, ids, layer=-1): self.selected["cats"] = ids self.selected["ids"] = list() # cidx is not up-to-date - # Vect_cidx_find_all(self.poMapInfo, layer, GV_POINTS | GV_LINES, lid, ilist) + # Vect_cidx_find_all(self.poMapInfo, + # layer, GV_POINTS | GV_LINES, lid, ilist) nlines = Vect_get_num_lines(self.poMapInfo) for line in range(1, nlines + 1): if not Vect_line_alive(self.poMapInfo, line): diff --git a/gui/wxpython/vnet/dialogs.py b/gui/wxpython/vnet/dialogs.py index 2d6ed76e44a..03b48b698bb 100644 --- a/gui/wxpython/vnet/dialogs.py +++ b/gui/wxpython/vnet/dialogs.py @@ -100,8 +100,8 @@ def __init__( self.mapWin = giface.GetMapWindow() self.giface = giface - # contains current analysis result (do not have to be last one, when history is browsed), - # it is instance of VectMap class + # contains current analysis result (do not have to be last one, when history + # is browsed), it is instance of VectMap class self.tmp_result = None self.defIsecTurnsHndlrReg = False @@ -388,7 +388,8 @@ def _createParametersPage(self): ["arc_layer", "Arc layer number or name:", LayerSelect], ["node_layer", "Node layer number or name:", LayerSelect], # ['turn_layer', "Layer with turntable:", LayerSelect], - # ['turn_cat_layer', "Layer with unique categories for turntable:", LayerSelect], + # ['turn_cat_layer', + # "Layer with unique categories for turntable:", LayerSelect], ["arc_column", "", ColumnSelect], ["arc_backward_column", "", ColumnSelect], ["node_column", "", ColumnSelect], @@ -737,7 +738,8 @@ def TtbCreated(self): self.stBar.RemoveStatusItem("ttb") def OnVectSel(self, event): - """When vector map is selected it populates other comboboxes in Parameters tab (layer selects, columns selects)""" + """When vector map is selected it populates other comboboxes in Parameters + tab (layer selects, columns selects)""" if self.vnet_mgr.IsSnappingActive(): # TODO should be in vnet_mgr self.vnet_mgr.Snapping(activate=True) @@ -798,7 +800,8 @@ def _updateParamsTab(self, params, flags): self.inputData[k].SetValue(params[k]) def OnALayerSel(self, event): - """When arc layer from vector map is selected, populates corespondent columns selects""" + """When arc layer from vector map is selected, populates corespondent columns + selects""" self.inputData["arc_column"].InsertColumns( vector=self.inputData["input"].GetValue(), layer=self.inputData["arc_layer"].GetValue(), @@ -813,7 +816,8 @@ def OnALayerSel(self, event): self._setInputData() def OnNLayerSel(self, event): - """When node layer from vector map is selected, populates corespondent column select""" + """When node layer from vector map is selected, populates corespondent column + select""" if self.vnet_mgr.IsSnappingActive(): self.vnet_mgr.Snapping(activate=True) @@ -898,7 +902,10 @@ def OnDefIsecTurnCost(self, event): # TODO move to vnet mgr? if ["turn_layer", "turn_cat_layer"] in err_params: GMessage( parent=self, - message="Please choose existing turntable layer and unique categories layer in Parameters tab.", + message=( + "Please choose existing turntable layer and unique " + "categories layer in Parameters tab." + ), ) cat = GetNearestNodeCat( @@ -1322,7 +1329,8 @@ def __init__( self.btnSave.Bind(wx.EVT_BUTTON, self.OnSave) self.btnSave.SetToolTip( _( - "Apply and save changes to user settings file (default for next sessions)" + "Apply and save changes to user settings file " + "(default for next sessions)" ) ) self.btnClose.Bind(wx.EVT_BUTTON, self.OnClose) @@ -1619,7 +1627,8 @@ def _doSelLayout(self, title, sel, btn=None): return selSizer def InputSel(self): - """When vector map is selected it populates other comboboxes in Parameters tab (layer selects, columns selects)""" + """When vector map is selected it populates other comboboxes in Parameters tab + (layer selects, columns selects)""" vectMapName, mapSet = self._parseMapStr(self.inputData["input"].GetValue()) vectorMap = vectMapName + "@" + mapSet @@ -1711,7 +1720,8 @@ def _layout(self): class VnetStatusbar(wx.StatusBar): - """Extends wx.StatusBar class with functionality to show multiple messages with the highest priority""" + """Extends wx.StatusBar class with functionality to show multiple messages with + the highest priority""" def __init__(self, parent, style, id=wx.ID_ANY, **kwargs): wx.StatusBar.__init__(self, parent, id, style, **kwargs) diff --git a/gui/wxpython/vnet/vnet_core.py b/gui/wxpython/vnet/vnet_core.py index ea5e329e319..ff0e2fd7fe6 100644 --- a/gui/wxpython/vnet/vnet_core.py +++ b/gui/wxpython/vnet/vnet_core.py @@ -127,7 +127,8 @@ def RunAnalysis(self): return False # for case there is some map with same name - # (when analysis does not produce any map, this map would have been shown as result) + # (when analysis does not produce any map, this map would have been shown + # as result) RunCommand( "g.remove", flags="f", @@ -604,10 +605,11 @@ def _updateTtbByGlobalCosts(self, vectMapName, tlayer): # if angle < from_angle: # angle = math.pi * 2 + angle - where = " WHERE (((angle < {0}) AND ({2} + angle >= {0} AND {2} + angle < {1})) OR \ - ((angle >= {0}) AND (angle >= {0} AND angle < {1}))) AND cost==0.0 ".format( - str(from_angle), str(to_angle), str(math.pi * 2) - ) + where = ( + " WHERE (((angle < {0}) AND ({2} + angle >= {0} AND {2} + angle < {1}))" + " OR ((angle >= {0}) AND (angle >= {0} AND angle < {1})))" + " AND cost==0.0 " + ).format(str(from_angle), str(to_angle), str(math.pi * 2)) stm = ("UPDATE %s SET cost=%f " % (table, cost)) + where + ";\n" sqlFile_f.write(stm) @@ -753,7 +755,8 @@ def _runAnDone(self, event): def _setInputParams(self, analysis, params, flags): """Return list of chosen values (vector map, layers). - The list items are in form to be used in command for analysis e.g. 'arc_layer=1'. + The list items are in form to be used in command for analysis + e.g. 'arc_layer=1'. """ inParams = [] diff --git a/gui/wxpython/vnet/vnet_data.py b/gui/wxpython/vnet/vnet_data.py index 528efa0a6c2..edf17a7fc8b 100644 --- a/gui/wxpython/vnet/vnet_data.py +++ b/gui/wxpython/vnet/vnet_data.py @@ -143,7 +143,8 @@ def GetLayerStyle(self): def InputsErrorMsgs( self, msg, analysis, params, flags, inv_params, relevant_params ): - """Checks input data in Parameters tab and shows messages if some value is not valid + """Checks input data in Parameters tab and shows messages if some value is + not valid :param str msg: message added to start of message string :return: True if checked inputs are OK @@ -193,7 +194,8 @@ def InputsErrorMsgs( for col in ["arc_column", "arc_backward_column", "node_column"]: if params[col] and col in inv_params and col in relevant_params: errColStr += _( - "Chosen column '%s' does not exist in attribute table of layer '%s' of vector map '%s'.\n" + "Chosen column '%s' does not exist in attribute table of layer " + "'%s' of vector map '%s'.\n" ) % (params[col], params[layer], params["input"]) if errColStr: @@ -408,7 +410,8 @@ def ParametersChanged(self, method, kwargs): self._vnetPathUpdateUsePoints(None) def _updateTypeCol(self): - """Rename category values when module is changed. Expample: Start point -> Sink point""" + """Rename category values when module is changed. Example: Start point + -> Sink point""" colValues = [""] analysis, valid = self.an_params.GetParam("analysis") anParamsCats = self.an_data[analysis]["cmdParams"]["cats"] @@ -737,7 +740,8 @@ def __init__(self): }, "resultProps": { "singleColor": None, - "dbMgr": True, # TODO delete this property, this information can be get from result + "dbMgr": True, # TODO delete this property, this information can + # be get from result }, "turns_support": True, }, @@ -1084,7 +1088,8 @@ def GetLastModified(self): class History: - """Class which reads and saves history data (based on gui.core.settings Settings class file save/load) + """Class which reads and saves history data (based on gui.core.settings Settings + class file save/load) .. todo:: Maybe it could be useful for other GRASS wxGUI tools. diff --git a/gui/wxpython/vnet/widgets.py b/gui/wxpython/vnet/widgets.py index ba0d35048bf..44e88cf3df0 100644 --- a/gui/wxpython/vnet/widgets.py +++ b/gui/wxpython/vnet/widgets.py @@ -15,7 +15,8 @@ @author Original author Michael Barton @author Original version improved by Martin Landa @author Rewritten by Markus Metz redesign georectfier -> GCP Manage -@author Stepan Turek (Created PointsList from GCPList) (GSoC 2012, mentor: Martin Landa) +@author Stepan Turek (Created PointsList from GCPList) + (GSoC 2012, mentor: Martin Landa) """ import os @@ -64,13 +65,13 @@ def __init__( Structure of list item must be this: -1. item: column name -2. item: column label - -3. item: If column is editable by user, it must contain convert function to convert - inserted string to it's type for sorting. Use None for not editable - columns. Values for insertion can be in list. This allows insert - just values in the list. - -4. item: Default value for column cell. Value should be given in it's type - in order to sorting would work properly. If 3. item is list, it must be index - of some item in the list. + -3. item: If column is editable by user, it must contain convert + function to convert inserted string to it's type for sorting. + Use None for not editable columns. Values for insertion can be + in list. This allows insert just values in the list. + -4. item: Default value for column cell. Value should be given in it's + type in order to sorting would work properly. If 3. item is + list, it must be index of some item in the list. Example of cols parameter: column name, column label, convert function, default val @@ -82,8 +83,9 @@ def __init__( ['N', _('target N'), float, 0.0], ['F_Err', _('Forward error'), None, 0], ['B_Err', _(Backward error'), None, 0] - ['type', _('type'), [_(""), _("Start point"), _("End point")], 0] # Select from 3 choices ("Start point", "End point"), - # Choice with index 0 ("") is default. + # Select from 3 choices ("Start point", "End point"), + # Choice with index 0 ("") is default. + ['type', _('type'), [_(""), _("Start point"), _("End point")], 0] ] @endcode """ @@ -281,7 +283,8 @@ def _findIndex(self, key): return -1 def ChangeColEditable(self, colName, colType): - """Change 3. item in constructor parameter cols (see the class constructor hint)""" + """Change 3. item in constructor parameter cols (see the class constructor + hint)""" colNum = self._getColumnNum(colName) iColEd = self.dataTypes["colEditable"] self.colsData[colNum][iColEd] = colType @@ -504,7 +507,8 @@ def ShowColumn(self, colName, pos): :param colName: name of column :type colName: str - :param pos: zero based index of position among showed columns (including added 'use' column) + :param pos: zero based index of position among showed columns (including added + 'use' column) :return: True if column was shown :return: False if position is not valid or column is not hidden diff --git a/gui/wxpython/web_services/cap_interface.py b/gui/wxpython/web_services/cap_interface.py index 44de7b6056a..d73cdb5bc84 100644 --- a/gui/wxpython/web_services/cap_interface.py +++ b/gui/wxpython/web_services/cap_interface.py @@ -1,7 +1,8 @@ """ @package web_services.cap_interface -@brief Provides common interface for GUI web_services.widgets to capabilities data of web services. +@brief Provides common interface for GUI web_services.widgets to capabilities data of + web services. List of classes: - cap_interface::CapabilitiesBase diff --git a/gui/wxpython/web_services/dialogs.py b/gui/wxpython/web_services/dialogs.py index f6f76103585..7ad21f824a8 100644 --- a/gui/wxpython/web_services/dialogs.py +++ b/gui/wxpython/web_services/dialogs.py @@ -414,7 +414,8 @@ def OnPanelCapParsed(self, error_msg): def _getConnectedWS(self): """ - :return: list of found web services on server (identified as keys in self.ws_panels) + :return: list of found web services on server (identified as keys in + self.ws_panels) """ conn_ws = [] for ws, data in self.ws_panels.items(): @@ -424,7 +425,8 @@ def _getConnectedWS(self): return conn_ws def UpdateDialogAfterConnection(self): - """Update dialog after all web service panels downloaded and parsed capabilities data.""" + """Update dialog after all web service panels downloaded and parsed + capabilities data.""" avail_ws = {} conn_ws = self._getConnectedWS() diff --git a/gui/wxpython/web_services/widgets.py b/gui/wxpython/web_services/widgets.py index e1cf5e84dd8..1a4b4c5501f 100644 --- a/gui/wxpython/web_services/widgets.py +++ b/gui/wxpython/web_services/widgets.py @@ -558,8 +558,8 @@ def _parseCapFile(self, cap_file): self.cap = self.ws_drvs[self.ws]["cap_parser"](cap_file) except (OSError, ParseError) as error: error_msg = _( - "%s web service was not found in fetched capabilities file from <%s>:\n%s\n" - % (self.ws, self.conn["url"], str(error)) + "%s web service was not found in fetched capabilities file from " + "<%s>:\n%s\n" % (self.ws, self.conn["url"], str(error)) ) if Debug.GetLevel() != 0: Debug.msg(1, error_msg) @@ -980,7 +980,8 @@ def addlayer(layer, item): item, { "type": "layer", # is it layer or style? - "layer": layer, # Layer instance from web_services.cap_interface + # Layer instance from web_services.cap_interface + "layer": layer, "style": def_st, }, ) # layer can have assigned default style diff --git a/gui/wxpython/wxplot/dialogs.py b/gui/wxpython/wxplot/dialogs.py index 7fbf0b9f9bb..ac23bb61547 100755 --- a/gui/wxpython/wxplot/dialogs.py +++ b/gui/wxpython/wxplot/dialogs.py @@ -814,7 +814,8 @@ def _do_layout(self): btnSave.Bind(wx.EVT_BUTTON, self.OnSave) btnSave.SetToolTip( _( - "Apply and save changes to user settings file (default for next sessions)" + "Apply and save changes to user settings file (default for next " + "sessions)" ) ) btnCancel.SetToolTip(_("Close dialog and ignore changes")) @@ -1209,7 +1210,8 @@ def _do_layout(self): type.SetStringSelection(prop["type"]) type.SetToolTip( _( - "Automatic axis scaling, custom max and min, or scale matches data range (min)" + "Automatic axis scaling, custom max and min, or scale matches data " + "range (min)" ) ) self.wxId[atype]["type"] = type.GetId() @@ -1323,7 +1325,8 @@ def _do_layout(self): btnOk.SetToolTip(_("Apply changes for the current session and close dialog")) btnSave.SetToolTip( _( - "Apply and save changes to user settings file (default for next sessions)" + "Apply and save changes to user settings file (default for next " + "sessions)" ) ) btnCancel.SetToolTip(_("Close dialog and ignore changes")) @@ -1470,8 +1473,8 @@ def UpdateSettings(self): self.wxId["grid"]["enabled"] ).IsChecked() - # this makes more sense in the text properties, including for settings update. But will need to change - # layout for controls to text dialog too. + # this makes more sense in the text properties, including for settings update. + # But will need to change layout for controls to text dialog too. self.properties["font"]["prop"]["legendSize"] = self.FindWindowById( self.wxId["font"]["legendSize"] ).GetValue() diff --git a/gui/wxpython/wxplot/scatter.py b/gui/wxpython/wxplot/scatter.py index 0b53a1fe138..6022f7add4b 100644 --- a/gui/wxpython/wxplot/scatter.py +++ b/gui/wxpython/wxplot/scatter.py @@ -29,7 +29,8 @@ class ScatterFrame(BasePlotFrame): - """Mainframe for displaying bivariate scatter plot of two raster maps. Uses wx.lib.plot.""" + """Mainframe for displaying bivariate scatter plot of two raster maps. Uses + wx.lib.plot.""" def __init__( self, diff --git a/imagery/i.atcorr/create_iwave.py b/imagery/i.atcorr/create_iwave.py index eb79602dd0d..863b4416a84 100644 --- a/imagery/i.atcorr/create_iwave.py +++ b/imagery/i.atcorr/create_iwave.py @@ -20,8 +20,10 @@ Updated by: Anne Ghisla, 2010 Bug fix (9/12/2010) by Daniel: - 1) function interpolate_band was not generating the spectral response for the last value in the filter function. Fixed - 2) function pretty_print was not printing the 8th value of every line, cutting the filter function short. + 1) function interpolate_band was not generating the spectral response for the last + value in the filter function. Fixed + 2) function pretty_print was not printing the 8th value of every line, cutting the + filter function short. """ import os @@ -141,9 +143,10 @@ def interpolate_band(values, step=2.5): # how many spectral responses? expected = np.ceil((stop - start) / step) - assert ( - len(filter_f) == expected - ), "Number of interpolated spectral responses not equal to expected number of interpolations" + assert len(filter_f) == expected, ( + "Number of interpolated spectral responses not equal to expected number of " + "interpolations" + ) # convert limits from nanometers to micrometers lowerlimit = start / 1000 diff --git a/lib/init/grass.py b/lib/init/grass.py index b306f31d94d..6d9d8b3b3e1 100755 --- a/lib/init/grass.py +++ b/lib/init/grass.py @@ -380,7 +380,8 @@ def help_message(default_gui): gui_detail=_("and set as default"), config=_("print GRASS configuration parameters"), config_detail=_( - "options: arch,build,compiler,date,path,python_path,revision,svn_revision,version" + "options: arch,build,compiler,date,path,python_path,revision," + "svn_revision,version" ), params=_("Parameters"), gisdbase=_("initial GRASS database directory"), @@ -1492,8 +1493,10 @@ def set_language(grass_config_dir): # If we got so far, attempts to set up language and locale have # failed on this system. sys.stderr.write( - "Failed to enforce user specified language '%s' with error: '%s'\n" - % (language, e) + ( + "Failed to enforce user specified language " + f"'{language}' with error: '{e}'\n" + ) ) sys.stderr.write( "A LANGUAGE environmental variable has been set.\n" diff --git a/man/build_rest.py b/man/build_rest.py index 37eaab80b94..ef684fd2de6 100644 --- a/man/build_rest.py +++ b/man/build_rest.py @@ -170,7 +170,7 @@ :doc:`Manual main page ` \| :doc:`Full Index ` 2003-2024 `GRASS Development Team `_, GRASS GIS ${grass_version} Reference Manual -""" +""" # noqa: E501 ) cmd1_tmpl = string.Template(r"""*`$cmd.\* <${cmd}>` *""") diff --git a/python/grass/docs/conf.py b/python/grass/docs/conf.py index 991c54be8ef..2d6a564cac0 100644 --- a/python/grass/docs/conf.py +++ b/python/grass/docs/conf.py @@ -73,13 +73,17 @@ ), ) -from grass.script import core +from grass.script import core # noqa: E402 footer_tmpl = string.Template( r""" {% block footer %}
-

Help Index | Topics Index | Keywords Index | Full Index

-

© 2003-${year} GRASS Development Team, GRASS GIS ${grass_version} Reference Manual

+

Help Index + | Topics Index + | Keywords Index + | Full Index

+

© 2003-${year} +GRASS Development Team, GRASS GIS ${grass_version} Reference Manual

{% endblock %} """ ) diff --git a/python/grass/gunittest/case.py b/python/grass/gunittest/case.py index a6c89cbcaa8..3f67f729d14 100644 --- a/python/grass/gunittest/case.py +++ b/python/grass/gunittest/case.py @@ -1270,11 +1270,14 @@ def assertVectorAsciiEqualsVectorAscii( # a difference (always a iterator object is returned) if i > 0: # do HTML diff only if there is not too many lines - # TODO: this might be tough to do with some more sophisticated way of reports + # TODO: this might be tough to do with some more sophisticated way of + # reports if self.html_reports and i < maxlines: - # TODO: this might be here and somehow stored as file or done in reporter again if right information is stored + # TODO: this might be here and somehow stored as file or done in + # reporter again if right information is stored # i.e., files not deleted or the whole strings passed - # alternative is make_table() which is the same but creates just a table not a whole document + # alternative is make_table() which is the same but creates just a table + # not a whole document # TODO: all HTML files might be collected by the main reporter # TODO: standardize the format of name of HTML file # for one test id there is only one possible file of this name @@ -1357,7 +1360,8 @@ def runModule(cls, module, expecting_stdout=False, **kwargs): # should be done by some other function # TODO: this should be the function used for valgrind or profiling or debug # TODO: it asserts the rc but it does much more, so testModule? - # TODO: do we need special function for testing module failures or just add parameter returncode=0? + # TODO: do we need special function for testing module failures or just add + # parameter returncode=0? # TODO: consider not allowing to call this method more than once # the original idea was to run this method just once for test method # but for "integration" tests (script-like tests with more than one module) diff --git a/python/grass/gunittest/checkers.py b/python/grass/gunittest/checkers.py index 669bb03d9ed..cc0cdc0020d 100644 --- a/python/grass/gunittest/checkers.py +++ b/python/grass/gunittest/checkers.py @@ -23,7 +23,8 @@ # TODO: we are silent about the error and use a object with different # interface, should be replaced by central keyvalue module # this can happen when translations are not available - # TODO: grass should survive are give better error when tranlsations are not available + # TODO: grass should survive and give better errors when translations are not + # available # even the lazy loading after first _ call would be interesting # File "...grass/script/core.py", line 40, in # AttributeError: 'NoneType' object has no attribute 'endswith' @@ -41,7 +42,7 @@ def unify_projection(dic): Example of common typo in UTM replaced by correct spelling:: - >>> unify_projection({'name': ['Universe Transverse Mercator']}) + >>> unify_projection({"name": ["Universe Transverse Mercator"]}) {'name': ['Universal Transverse Mercator']} :param dic: The dictionary containing information about projection @@ -67,7 +68,7 @@ def unify_units(dic): Example of British English spelling replaced by US English spelling:: - >>> unify_units({'units': ['metres'], 'unit': ['metre']}) # doctest: +SKIP + >>> unify_units({"units": ["metres"], "unit": ["metre"]}) # doctest: +SKIP {'units': ['meters'], 'unit': ['meter']} :param dic: The dictionary containing information about units @@ -111,13 +112,13 @@ def value_from_string(value): Type conversions are applied in order ``int``, ``float``, ``string`` where string is no conversion. - >>> value_from_string('1') + >>> value_from_string("1") 1 - >>> value_from_string('5.6') + >>> value_from_string("5.6") 5.6 - >>> value_from_string(' 5.6\t ') + >>> value_from_string(" 5.6\t ") 5.6 - >>> value_from_string('hello') + >>> value_from_string("hello") 'hello' """ not_float = False @@ -178,10 +179,14 @@ def text_to_keyvalue( And example of converting text with text, floats, integers and list to a dictionary:: - >>> sorted(text_to_keyvalue('''a: Hello + >>> sorted( + ... text_to_keyvalue( + ... '''a: Hello ... b: 1.0 ... c: 1,2,3,4,5 - ... d : hello,8,0.1''').items()) # sorted items from the dictionary + ... d : hello,8,0.1''' + ... ).items() + ... ) # sorted items from the dictionary [('a', 'Hello'), ('b', 1.0), ('c', [1, 2, 3, 4, 5]), ('d', ['hello', 8, 0.1])] .. warning:: @@ -260,7 +265,7 @@ def values_equal(value_a, value_b, precision=0.000001): True >>> values_equal(1, 5.9, precision=10) True - >>> values_equal('Hello', 'hello') + >>> values_equal("Hello", "hello") False """ # each if body needs to handle only not equal state @@ -325,14 +330,21 @@ def keyvalue_equals( An example of key-value texts comparison:: - >>> keyvalue_equals(text_to_keyvalue('''a: Hello + >>> keyvalue_equals( + ... text_to_keyvalue( + ... '''a: Hello ... b: 1.0 ... c: 1,2,3,4,5 - ... d: hello,8,0.1'''), - ... text_to_keyvalue('''a: Hello + ... d: hello,8,0.1''' + ... ), + ... text_to_keyvalue( + ... '''a: Hello ... b: 1.1 ... c: 1,22,3,4,5 - ... d: hello,8,0.1'''), precision=0.1) + ... d: hello,8,0.1''' + ... ), + ... precision=0.1, + ... ) False :param dict_a: first dictionary @@ -381,8 +393,8 @@ def diff_keyvalue( The function returns missing keys and different values for common keys:: - >>> a = {'c': 2, 'b': 3, 'a': 4} - >>> b = {'c': 1, 'b': 3, 'd': 5} + >>> a = {"c": 2, "b": 3, "a": 4} + >>> b = {"c": 1, "b": 3, "d": 5} >>> diff_keyvalue(a, b, precision=0) (['d'], ['a'], [('c', 2, 1)]) @@ -486,32 +498,31 @@ def lowercase_equals(string_a, string_b, precision=None): # TODO: the behavior with last \n is strange but now using DOTALL and $ def check_text_ellipsis(reference, actual): r""" - >>> check_text_ellipsis("Vector map <...> contains ... points.", - ... "Vector map contains 5268 points.") + >>> check_text_ellipsis( + ... "Vector map <...> contains ... points.", + ... "Vector map contains 5268 points.", + ... ) True - >>> check_text_ellipsis("user: ...\\nname: elevation", - ... "user: some_user\\nname: elevation") + >>> check_text_ellipsis( + ... "user: ...\\nname: elevation", "user: some_user\\nname: elevation" + ... ) True - >>> check_text_ellipsis("user: ...\\nname: elevation", - ... "user: \\nname: elevation") + >>> check_text_ellipsis("user: ...\\nname: elevation", "user: \\nname: elevation") False The ellipsis is always considered even if it is followed by another dots. Consequently, a dot at the end of the sentence with preceding ellipsis will work as well as a line filled with undefined number of dots. - >>> check_text_ellipsis("The result is ....", - ... "The result is 25.") + >>> check_text_ellipsis("The result is ....", "The result is 25.") True - >>> check_text_ellipsis("max ..... ...", - ... "max ....... 6") + >>> check_text_ellipsis("max ..... ...", "max ....... 6") True However, there is no way how to express that the dot should be in the beginning and the ellipsis is at the end of the group of dots. - >>> check_text_ellipsis("The result is ....", - ... "The result is .25") + >>> check_text_ellipsis("The result is ....", "The result is .25") False The matching goes over lines (TODO: should this be changed?): @@ -521,8 +532,7 @@ def check_text_ellipsis(reference, actual): This function is based on regular expression containing .+ but no other regular expression matching will be done. - >>> check_text_ellipsis("Result: [569] (...)", - ... "Result: 9 (too high)") + >>> check_text_ellipsis("Result: [569] (...)", "Result: 9 (too high)") False """ ref_escaped = re.escape(reference) @@ -536,43 +546,55 @@ def check_text_ellipsis(reference, actual): def check_text_ellipsis_doctest(reference, actual): """ - >>> check_text_ellipsis_doctest("user: ...\\nname: elevation", - ... "user: some_user\\nname: elevation") + >>> check_text_ellipsis_doctest( + ... "user: ...\\nname: elevation", "user: some_user\\nname: elevation" + ... ) True - >>> check_text_ellipsis_doctest("user: ...\\nname: elevation", - ... "user: \\nname: elevation") + >>> check_text_ellipsis_doctest( + ... "user: ...\\nname: elevation", "user: \\nname: elevation" + ... ) True This function is using doctest's function to check the result, so we will discuss here how the underlying function behaves. >>> checker = doctest.OutputChecker() - >>> checker.check_output("user: some_user\\nname: elevation", - ... "user: some_user\\nname: elevation", - ... optionflags=None) + >>> checker.check_output( + ... "user: some_user\\nname: elevation", + ... "user: some_user\\nname: elevation", + ... optionflags=None, + ... ) True - >>> checker.check_output("user: user1\\nname: elevation", - ... "user: some_user\\nname: elevation", - ... optionflags=doctest.ELLIPSIS) + >>> checker.check_output( + ... "user: user1\\nname: elevation", + ... "user: some_user\\nname: elevation", + ... optionflags=doctest.ELLIPSIS, + ... ) False - >>> checker.check_output("user: ...\\nname: elevation", - ... "user: some_user\\nname: elevation", - ... optionflags=doctest.ELLIPSIS) + >>> checker.check_output( + ... "user: ...\\nname: elevation", + ... "user: some_user\\nname: elevation", + ... optionflags=doctest.ELLIPSIS, + ... ) True The ellipsis matches also an empty string, so the following matches: - >>> checker.check_output("user: ...\\nname: elevation", - ... "user: \\nname: elevation", - ... optionflags=doctest.ELLIPSIS) + >>> checker.check_output( + ... "user: ...\\nname: elevation", + ... "user: \\nname: elevation", + ... optionflags=doctest.ELLIPSIS, + ... ) True It is robust concerning misspelled matching string but does not allow ellipsis followed by a dot, e.g. at the end of the sentence: - >>> checker.check_output("user: ....\\nname: elevation", - ... "user: some_user\\nname: elevation", - ... optionflags=doctest.ELLIPSIS) + >>> checker.check_output( + ... "user: ....\\nname: elevation", + ... "user: some_user\\nname: elevation", + ... optionflags=doctest.ELLIPSIS, + ... ) False """ # this can be also global diff --git a/python/grass/gunittest/gmodules.py b/python/grass/gunittest/gmodules.py index c105fcfa12d..20d8bd2daed 100644 --- a/python/grass/gunittest/gmodules.py +++ b/python/grass/gunittest/gmodules.py @@ -22,15 +22,13 @@ class SimpleModule(Module): r"""Simple wrapper around pygrass.modules.Module to make sure that run\_, finish\_, stdout and stderr are set correctly. - >>> mapcalc = SimpleModule('r.mapcalc', expression='test_a = 1', - ... overwrite=True) + >>> mapcalc = SimpleModule("r.mapcalc", expression="test_a = 1", overwrite=True) >>> mapcalc.run() Module('r.mapcalc') >>> mapcalc.returncode 0 - >>> colors = SimpleModule('r.colors', - ... map='test_a', rules='-', stdin_='1 red') + >>> colors = SimpleModule("r.colors", map="test_a", rules="-", stdin_="1 red") >>> colors.run() Module('r.colors') >>> colors.returncode @@ -67,15 +65,17 @@ def call_module( ): r"""Run module with parameters given in `kwargs` and return its output. - >>> print (call_module('g.region', flags='pg')) # doctest: +ELLIPSIS + >>> print(call_module("g.region", flags="pg")) # doctest: +ELLIPSIS projection=... zone=... n=... s=... w=... - >>> call_module('m.proj', flags='i', input='-', stdin="50.0 41.5") + >>> call_module("m.proj", flags="i", input="-", stdin="50.0 41.5") '8642890.65|6965155.61|0.00\n' - >>> call_module('g.region', aabbbccc='notexist') # doctest: +IGNORE_EXCEPTION_DETAIL + >>> call_module( + ... "g.region", aabbbccc="notexist" + ... ) # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... CalledModuleError: Module run g.region ... ended with error @@ -103,7 +103,7 @@ def call_module( .. note:: The data read is buffered in memory, so do not use this method if the data size is large or unlimited. - """ + """ # noqa: E501 # TODO: remove this: do_doctest_gettext_workaround() # implementation inspired by subprocess.check_output() function diff --git a/python/grass/gunittest/invoker.py b/python/grass/gunittest/invoker.py index c57df91960a..681fad5ff14 100644 --- a/python/grass/gunittest/invoker.py +++ b/python/grass/gunittest/invoker.py @@ -127,7 +127,8 @@ def _create_mapset(self, gisdbase, location, module): os.mkdir(mapset_dir) # TODO: default region in mapset will be what? # copy DEFAULT_WIND file from PERMANENT to WIND - # TODO: this should be a function in grass.script (used also in gis_set.py, PyGRASS also has its way with Mapset) + # TODO: this should be a function in grass.script (used also in gis_set.py, + # PyGRASS also has its way with Mapset) shutil.copy( os.path.join(gisdbase, location, "PERMANENT", "DEFAULT_WIND"), os.path.join(mapset_dir, "WIND"), @@ -212,7 +213,10 @@ def _run_test_module(self, module, results_dir, gisdbase, location, timeout): if stdout is None: stdout = "" if stderr is None: - stderr = f"Process has timed out in {timeout}s and produced no error output.\n" + stderr = ( + f"Process has timed out in {timeout}s and produced no error " + "output.\n" + ) # Return code is None if the process times out. # Rest of the code expects success to evaluate as False. # So, we assign a failing return code. diff --git a/python/grass/gunittest/main.py b/python/grass/gunittest/main.py index 18b2dfab5d1..631d0ee3116 100644 --- a/python/grass/gunittest/main.py +++ b/python/grass/gunittest/main.py @@ -82,7 +82,8 @@ def test(): """Run a test of a module.""" # TODO: put the link to to the report only if available # TODO: how to disable Python code coverage for module and C tests? - # TODO: we probably need to have different test functions for C, Python modules, and Python code + # TODO: we probably need to have different test functions for C, Python modules, + # and Python code # TODO: combine the results using python -m coverage --help | grep combine # TODO: function to anonymize/beautify file names (in content and actual filenames) # TODO: implement coverage but only when requested by invoker and only if diff --git a/python/grass/gunittest/reporters.py b/python/grass/gunittest/reporters.py index 312a8fd6b89..252331840d2 100644 --- a/python/grass/gunittest/reporters.py +++ b/python/grass/gunittest/reporters.py @@ -1234,7 +1234,8 @@ def report_for_dir(self, root, directory, test_files): return row def report_for_dirs(self, root, directories): - # TODO: this will need chanages according to potential changes in absolute/relative paths + # TODO: this will need changes according to potential changes in + # absolute/relative paths page_name = os.path.join(root, self.main_page_name) page = open(page_name, "w") diff --git a/python/grass/imaging/images2gif.py b/python/grass/imaging/images2gif.py index f67bbed2a16..95d72add09a 100644 --- a/python/grass/imaging/images2gif.py +++ b/python/grass/imaging/images2gif.py @@ -891,7 +891,8 @@ def alterneigh(self, alpha, rad, i, b, g, r): # """ Search for biased BGR values # Finds closest neuron (min dist) and updates self.freq # finds best neuron (min dist-self.bias) and returns position - # for frequently chosen neurons, self.freq[i] is high and self.bias[i] is negative + # for frequently chosen neurons, self.freq[i] is high and self.bias[i] + # is negative # self.bias[i] = self.GAMMA * ((1/self.NETSIZE)-self.freq[i])""" # # i, j = self.SPECIALS, self.NETSIZE diff --git a/python/grass/pygrass/gis/region.py b/python/grass/pygrass/gis/region.py index 453c2c84f5f..a4a1a1b5e03 100644 --- a/python/grass/pygrass/gis/region.py +++ b/python/grass/pygrass/gis/region.py @@ -346,7 +346,7 @@ def keys(self): """Return a list of valid keys. :: >>> reg = Region() - >>> reg.keys() # doctest: +ELLIPSIS + >>> reg.keys() # doctest: +ELLIPSIS ['proj', 'zone', ..., 'cols', 'cells'] .. @@ -459,7 +459,8 @@ def from_rast(self, raster_name): libraster.Rast_get_cellhd(raster_name, mapset, self.byref()) def set_raster_region(self): - """Set the computational region (window) for all raster maps in the current process. + """Set the computational region (window) for all raster maps in the current + process. Attention: All raster objects must be closed or the process will be terminated. diff --git a/python/grass/pygrass/modules/grid/split.py b/python/grass/pygrass/modules/grid/split.py index 5ff56a3e737..ea20a216e8e 100644 --- a/python/grass/pygrass/modules/grid/split.py +++ b/python/grass/pygrass/modules/grid/split.py @@ -82,10 +82,14 @@ def split_region_in_overlapping_tiles(region=None, width=100, height=100, overla 1500 >>> reg.rows 1350 - >>> split_region_in_overlapping_tiles(region=reg, width=1000, height=700, overlap=0) # doctest: +NORMALIZE_WHITESPACE + >>> split_region_in_overlapping_tiles( + ... region=reg, width=1000, height=700, overlap=0 + ... ) # doctest: +NORMALIZE_WHITESPACE [[Bbox(1350.0, 650.0, 1000.0, 0.0), Bbox(1350.0, 650.0, 1500.0, 1000.0)], [Bbox(650.0, 0.0, 1000.0, 0.0), Bbox(650.0, 0.0, 1500.0, 1000.0)]] - >>> split_region_in_overlapping_tiles(region=reg, width=1000, height=700, overlap=10) # doctest: +NORMALIZE_WHITESPACE + >>> split_region_in_overlapping_tiles( + ... region=reg, width=1000, height=700, overlap=10 + ... ) # doctest: +NORMALIZE_WHITESPACE [[Bbox(1350.0, 640.0, 1010.0, 0.0), Bbox(1350.0, 640.0, 1500.0, 990.0)], [Bbox(660.0, 0.0, 1010.0, 0.0), Bbox(660.0, 0.0, 1500.0, 990.0)]] """ @@ -104,7 +108,8 @@ def split_region_in_overlapping_tiles(region=None, width=100, height=100, overla def split_region_tiles(region=None, width=100, height=100): - """Split a region into a list of tiles defined as (start_row, end_row, start_col, end_col). + """Split a region into a list of tiles defined as (start_row, end_row, start_col, + end_col). :param region: a Region object to split :type region: Region object diff --git a/python/grass/pygrass/modules/interface/module.py b/python/grass/pygrass/modules/interface/module.py index 57b4c235302..9f0c911a4b1 100644 --- a/python/grass/pygrass/modules/interface/module.py +++ b/python/grass/pygrass/modules/interface/module.py @@ -20,8 +20,8 @@ def _get_bash(self, *args, **kargs): class ParallelModuleQueue: - """This class is designed to run an arbitrary number of pygrass Module or MultiModule - processes in parallel. + """This class is designed to run an arbitrary number of pygrass Module or + MultiModule processes in parallel. Objects of type grass.pygrass.modules.Module or grass.pygrass.modules.MultiModule can be put into the @@ -55,8 +55,9 @@ class ParallelModuleQueue: >>> for i in range(5): ... new_mapcalc = copy.deepcopy(mapcalc) ... mapcalc_list.append(new_mapcalc) - ... m = new_mapcalc(expression="test_pygrass_%i = %i"%(i, i)) + ... m = new_mapcalc(expression="test_pygrass_%i = %i" % (i, i)) ... queue.put(m) + ... >>> queue.wait() >>> mapcalc_list = queue.get_finished_modules() >>> queue.get_num_run_procs() @@ -65,6 +66,7 @@ class ParallelModuleQueue: 3 >>> for mapcalc in mapcalc_list: ... print(mapcalc.returncode) + ... 0 0 0 @@ -78,8 +80,9 @@ class ParallelModuleQueue: >>> for i in range(5): ... new_mapcalc = copy.deepcopy(mapcalc) ... mapcalc_list.append(new_mapcalc) - ... m = new_mapcalc(expression="test_pygrass_%i = %i"%(i, i)) + ... m = new_mapcalc(expression="test_pygrass_%i = %i" % (i, i)) ... queue.put(m) + ... >>> queue.wait() >>> mapcalc_list = queue.get_finished_modules() >>> queue.get_num_run_procs() @@ -88,6 +91,7 @@ class ParallelModuleQueue: 8 >>> for mapcalc in mapcalc_list: ... print(mapcalc.returncode) + ... 0 0 0 @@ -103,10 +107,13 @@ class ParallelModuleQueue: ... new_gregion = copy.deepcopy(gregion) ... proc_list.append(new_gregion) ... new_mapcalc = copy.deepcopy(mapcalc) - ... m = new_mapcalc(expression="test_pygrass_%i = %i"%(i, i)) + ... m = new_mapcalc(expression="test_pygrass_%i = %i" % (i, i)) ... proc_list.append(new_mapcalc) - ... mm = MultiModule(module_list=[new_gregion, new_mapcalc], sync=False, set_temp_region=True) + ... mm = MultiModule( + ... module_list=[new_gregion, new_mapcalc], sync=False, set_temp_region=True + ... ) ... queue.put(mm) + ... >>> queue.wait() >>> proc_list = queue.get_finished_modules() >>> queue.get_num_run_procs() @@ -115,6 +122,7 @@ class ParallelModuleQueue: 3 >>> for proc in proc_list: ... print(proc.returncode) + ... 0 0 0 @@ -158,6 +166,7 @@ class ParallelModuleQueue: 8 >>> for mapcalc in mapcalc_list: ... print(mapcalc.returncode) + ... 0 0 0 @@ -182,12 +191,14 @@ class ParallelModuleQueue: >>> new_mapcalc = copy.deepcopy(mapcalc) >>> mapcalc_list.append(new_mapcalc) >>> m = new_mapcalc(expression="test_pygrass_3 =3") - >>> queue.put(m) # Now it will wait until all procs finish and set the counter back to 0 + >>> queue.put( + ... m + ... ) # Now it will wait until all procs finish and set the counter back to 0 >>> queue.get_num_run_procs() 0 >>> new_mapcalc = copy.deepcopy(mapcalc) >>> mapcalc_list.append(new_mapcalc) - >>> m = new_mapcalc(expression="test_pygrass_%i = %i"%(i, i)) + >>> m = new_mapcalc(expression="test_pygrass_%i = %i" % (i, i)) >>> queue.put(m) >>> queue.get_num_run_procs() 1 @@ -199,12 +210,13 @@ class ParallelModuleQueue: 3 >>> for mapcalc in mapcalc_list: ... print(mapcalc.returncode) + ... 0 0 0 0 - """ + """ # noqa: E501 def __init__(self, nprocs=1): """Constructor @@ -245,7 +257,8 @@ def get(self, num): :param num: the number of the object in queue :type num: int - :returns: the Module object or list of Module objects or None if num is not in the queue + :returns: the Module object or list of Module objects or None if num is not in + the queue """ if num < self._num_procs: return self._list[num] @@ -358,15 +371,21 @@ class Module: >>> new_neighbors3.get_bash() 'r.neighbors input=mapA size=3 method=average weighting_function=none nprocs=1 memory=300 output=mapB' - >>> mapcalc = Module("r.mapcalc", expression="test_a = 1", - ... overwrite=True, run_=False) + >>> mapcalc = Module( + ... "r.mapcalc", expression="test_a = 1", overwrite=True, run_=False + ... ) >>> mapcalc.run() Module('r.mapcalc') >>> mapcalc.returncode 0 - >>> mapcalc = Module("r.mapcalc", expression="test_a = 1", - ... overwrite=True, run_=False, finish_=False) + >>> mapcalc = Module( + ... "r.mapcalc", + ... expression="test_a = 1", + ... overwrite=True, + ... run_=False, + ... finish_=False, + ... ) >>> mapcalc.run() Module('r.mapcalc') >>> p = mapcalc.wait() @@ -378,9 +397,15 @@ class Module: >>> p.returncode 0 - >>> colors = Module("r.colors", map="test_a", rules="-", - ... run_=False, stdout_=PIPE, - ... stderr_=PIPE, stdin_="1 red") + >>> colors = Module( + ... "r.colors", + ... map="test_a", + ... rules="-", + ... run_=False, + ... stdout_=PIPE, + ... stderr_=PIPE, + ... stdin_="1 red", + ... ) >>> colors.run() Module('r.colors') >>> p = mapcalc.wait() @@ -393,8 +418,9 @@ class Module: >>> colors.outputs["stderr"].value.strip() "Color table for raster map set to 'rules'" - >>> colors = Module("r.colors", map="test_a", rules="-", - ... run_=False, finish_=False, stdin_=PIPE) + >>> colors = Module( + ... "r.colors", map="test_a", rules="-", run_=False, finish_=False, stdin_=PIPE + ... ) >>> colors.inputs["stdin"].value = "1 red" >>> colors.run() Module('r.colors') @@ -403,9 +429,15 @@ class Module: >>> colors.returncode 0 - >>> colors = Module("r.colors", map="test_a", rules="-", - ... run_=False, finish_=False, - ... stdin_=PIPE, stderr_=PIPE) + >>> colors = Module( + ... "r.colors", + ... map="test_a", + ... rules="-", + ... run_=False, + ... finish_=False, + ... stdin_=PIPE, + ... stderr_=PIPE, + ... ) >>> colors.inputs["stdin"].value = "1 red" >>> colors.run() Module('r.colors') @@ -466,15 +498,15 @@ def f(*args): therefore if we call the function like: - >>> f('grass', 'gis', 'modules') # doctest: +SKIP + >>> f("grass", "gis", "modules") # doctest: +SKIP grass gis modules or we can define a new list: - >>> words = ['grass', 'gis', 'modules'] # doctest: +SKIP - >>> f(*words) # doctest: +SKIP + >>> words = ["grass", "gis", "modules"] # doctest: +SKIP + >>> f(*words) # doctest: +SKIP grass gis modules @@ -489,8 +521,8 @@ def f(*args, **kargs): now we can use the new function, with: - >>> f('grass', 'gis', 'modules', os = 'linux', language = 'python') - ... # doctest: +SKIP + >>> f("grass", "gis", "modules", os="linux", language="python") + ... # doctest: +SKIP grass gis modules @@ -500,8 +532,8 @@ def f(*args, **kargs): or, as before we can, define a dictionary and give the dictionary to the function, like: - >>> keywords = {'os' : 'linux', 'language' : 'python'} # doctest: +SKIP - >>> f(*words, **keywords) # doctest: +SKIP + >>> keywords = {"os": "linux", "language": "python"} # doctest: +SKIP + >>> f(*words, **keywords) # doctest: +SKIP grass gis modules @@ -510,7 +542,7 @@ def f(*args, **kargs): In the Module class we heavily use this language feature to pass arguments and keyword arguments to the grass module. - """ + """ # noqa: E501 def __init__(self, cmd, *args, **kargs): if isinstance(cmd, str): @@ -842,20 +874,22 @@ class MultiModule: Module can be run in serial synchronously or asynchronously. - Synchronously: When calling run() all modules will run in serial order - until they are finished, The run() method will return until all modules finished. - The modules objects can be accessed by calling get_modules() to check their return - values. - - Asynchronously: When calling run() all modules will run in serial order in a background process. - Method run() will return after starting the modules without waiting for them to finish. - The user must call the wait() method to wait for the modules to finish. - Asynchronously called module can be optionally run in a temporary region - environment, hence invokeing g.region will not alter the current - region or the region of other MultiModule runs. + until they are finished, The run() method will return until all + modules finished. The modules objects can be accessed by calling + get_modules() to check their return values. + - Asynchronously: When calling run() all modules will run in serial order in a + background process. Method run() will return after starting the + modules without waiting for them to finish. The user must call + the wait() method to wait for the modules to finish. + Asynchronously called module can be optionally run in a temporary + region environment, hence invoking g.region will not alter the + current region or the region of other MultiModule runs. Note: - Modules run in asynchronous mode can only be accessed via the wait() method. - The wait() method will return all finished module objects as list. + Modules run in asynchronous mode can only be accessed via the + wait() method. The wait() method will return all finished + module objects as list. Objects of this class can be passed to the ParallelModuleQueue to run serial stacks of modules in parallel. This is meaningful if region settings must be applied @@ -892,8 +926,9 @@ class MultiModule: >>> region_4.flags.p = True >>> region_5 = copy.deepcopy(region_1) >>> region_5.flags.p = True - >>> mm = MultiModule(module_list=[region_1, region_2, region_3, region_4, region_5], - ... sync=False) + >>> mm = MultiModule( + ... module_list=[region_1, region_2, region_3, region_4, region_5], sync=False + ... ) >>> t = mm.run() >>> isinstance(t, Process) True @@ -911,8 +946,11 @@ class MultiModule: Asynchronous module run, setting finish = False and using temporary region - >>> mm = MultiModule(module_list=[region_1, region_2, region_3, region_4, region_5], - ... sync=False, set_temp_region=True) + >>> mm = MultiModule( + ... module_list=[region_1, region_2, region_3, region_4, region_5], + ... sync=False, + ... set_temp_region=True, + ... ) >>> str(mm) 'g.region -p ; g.region -p ; g.region -p ; g.region -p ; g.region -p' >>> t = mm.run() @@ -936,12 +974,14 @@ def __init__(self, module_list, sync=True, set_temp_region=False): """Constructor of the multi module class :param module_list: A list of pre-configured Module objects that should be run - :param sync: If set True the run() method will wait for all processes to finish -> synchronously run. - If set False, the run() method will return after starting the processes -> asynchronously run. - The wait() method must be called to finish the modules. - :param set_temp_region: Set a temporary region in which the modules should be run, hence - region settings in the process list will not affect the current - computation region. + :param sync: If set True the run() method will wait for all processes to finish + -> synchronously run. + If set False, the run() method will return after starting the + processes -> asynchronously run. The wait() method must be called + to finish the modules. + :param set_temp_region: Set a temporary region in which the modules should be + run, hence region settings in the process list will not + affect the current computation region. Note: diff --git a/python/grass/pygrass/modules/interface/parameter.py b/python/grass/pygrass/modules/interface/parameter.py index 161640e638e..4d769972e10 100644 --- a/python/grass/pygrass/modules/interface/parameter.py +++ b/python/grass/pygrass/modules/interface/parameter.py @@ -115,8 +115,8 @@ def check_string(value): break if not good: raise ValueError( - f"The Parameter <{param.name}>, must be one of the following values:" - f" {param.values!r} not '{newvalue}'" + f"The Parameter <{param.name}>, must be one of the following " + f"values: {param.values!r} not '{newvalue}'" ) return ( ( @@ -135,9 +135,15 @@ class Parameter: """The Parameter object store all information about a parameter of a GRASS GIS module. :: - >>> param = Parameter(diz=dict(name='int_number', required='yes', - ... multiple='no', type='integer', - ... values=[2, 4, 6, 8])) + >>> param = Parameter( + ... diz=dict( + ... name="int_number", + ... required="yes", + ... multiple="no", + ... type="integer", + ... values=[2, 4, 6, 8], + ... ) + ... ) >>> param.value = 2 >>> param.value 2 @@ -147,7 +153,7 @@ class Parameter: ValueError: The Parameter , must be one of the following values: [2, 4, 6, 8] not '3' ... - """ + """ # noqa: E501 def __init__(self, xparameter=None, diz=None): self._value = None @@ -238,9 +244,16 @@ def rawvalue(self): def get_bash(self): """Return the BASH representation of the parameter. :: - >>> param = Parameter(diz=dict(name='int_number', required='yes', - ... multiple='no', type='integer', - ... values=[2, 4, 6, 8], default=8)) + >>> param = Parameter( + ... diz=dict( + ... name="int_number", + ... required="yes", + ... multiple="no", + ... type="integer", + ... values=[2, 4, 6, 8], + ... default=8, + ... ) + ... ) >>> param.get_bash() 'int_number=8' @@ -265,9 +278,16 @@ def get_bash(self): def get_python(self): """Return a string with the Python representation of the parameter. :: - >>> param = Parameter(diz=dict(name='int_number', required='yes', - ... multiple='no', type='integer', - ... values=[2, 4, 6, 8], default=8)) + >>> param = Parameter( + ... diz=dict( + ... name="int_number", + ... required="yes", + ... multiple="no", + ... type="integer", + ... values=[2, 4, 6, 8], + ... default=8, + ... ) + ... ) >>> param.get_python() 'int_number=8' @@ -301,11 +321,17 @@ def __doc__(self): :: - >>> param = Parameter(diz=dict(name='int_number', - ... description="Set an number", - ... required='yes', - ... multiple='no', type='integer', - ... values=[2, 4, 6, 8], default=8)) + >>> param = Parameter( + ... diz=dict( + ... name="int_number", + ... description="Set an number", + ... required="yes", + ... multiple="no", + ... type="integer", + ... values=[2, 4, 6, 8], + ... default=8, + ... ) + ... ) >>> print(param.__doc__) int_number: 8, required, integer Set an number diff --git a/python/grass/pygrass/raster/__init__.py b/python/grass/pygrass/raster/__init__.py index a151e1d35e3..448d4e3b1db 100644 --- a/python/grass/pygrass/raster/__init__.py +++ b/python/grass/pygrass/raster/__init__.py @@ -13,16 +13,12 @@ libgis.G_gisinit("") -# # import pygrass modules -# from grass.pygrass.errors import must_be_open from grass.pygrass.gis.region import Region from grass.pygrass import utils -# # import raster classes -# from grass.pygrass.raster.abstract import RasterAbstractBase from grass.pygrass.raster.raster_type import TYPE as RTYPE, RTYPE_STR from grass.pygrass.raster.buffer import Buffer diff --git a/python/grass/pygrass/raster/abstract.py b/python/grass/pygrass/raster/abstract.py index 6969154b7fb..4967dc6487b 100644 --- a/python/grass/pygrass/raster/abstract.py +++ b/python/grass/pygrass/raster/abstract.py @@ -49,7 +49,7 @@ def __init__(self, name, mapset=""): >>> info = Info(test_raster_name) >>> info.read() - >>> info # doctest: +ELLIPSIS +NORMALIZE_WHITESPACE + >>> info # doctest: +ELLIPSIS +NORMALIZE_WHITESPACE abstract_test_map@ rows: 4 cols: 4 @@ -539,7 +539,8 @@ def _set_raster_window(self, region): def get_value(self, point, region=None): """This method returns the pixel value of a given pair of coordinates: - :param point: pair of coordinates in tuple object or class object with coords() method + :param point: pair of coordinates in tuple object or class object with coords() + method """ # Check for tuple if not isinstance(point, list) and not isinstance(point, tuple): diff --git a/python/grass/pygrass/rpc/__init__.py b/python/grass/pygrass/rpc/__init__.py index c5797c19caa..07cbfe6503a 100644 --- a/python/grass/pygrass/rpc/__init__.py +++ b/python/grass/pygrass/rpc/__init__.py @@ -273,30 +273,38 @@ def get_raster_image_as_np(self, name, mapset=None, extent=None, color="RGB"): >>> len(ret) 64 - >>> extent = {"north":30, "south":10, "east":30, "west":10, - ... "rows":2, "cols":2} - >>> ret = provider.get_raster_image_as_np(name=test_raster_name, - ... extent=extent) + >>> extent = { + ... "north": 30, + ... "south": 10, + ... "east": 30, + ... "west": 10, + ... "rows": 2, + ... "cols": 2, + ... } + >>> ret = provider.get_raster_image_as_np(name=test_raster_name, extent=extent) >>> len(ret) 16 - >>> extent = {"rows":3, "cols":1} - >>> ret = provider.get_raster_image_as_np(name=test_raster_name, - ... extent=extent) + >>> extent = {"rows": 3, "cols": 1} + >>> ret = provider.get_raster_image_as_np(name=test_raster_name, extent=extent) >>> len(ret) 12 - >>> extent = {"north":100, "south":10, "east":30, "west":10, - ... "rows":2, "cols":2} - >>> ret = provider.get_raster_image_as_np(name=test_raster_name, - ... extent=extent) + >>> extent = { + ... "north": 100, + ... "south": 10, + ... "east": 30, + ... "west": 10, + ... "rows": 2, + ... "cols": 2, + ... } + >>> ret = provider.get_raster_image_as_np(name=test_raster_name, extent=extent) >>> provider.stop() >>> time.sleep(1) - >>> extent = {"rows":3, "cols":1} - >>> ret = provider.get_raster_image_as_np(name=test_raster_name, - ... extent=extent) + >>> extent = {"rows": 3, "cols": 1} + >>> ret = provider.get_raster_image_as_np(name=test_raster_name, extent=extent) >>> len(ret) 12 @@ -325,18 +333,18 @@ def get_vector_table_as_dict(self, name, mapset=None, where=None): {1: [1, 'point', 1.0], 2: [2, 'line', 2.0], 3: [3, 'centroid', 3.0]} >>> ret["columns"] Columns([('cat', 'INTEGER'), ('name', 'varchar(50)'), ('value', 'double precision')]) - >>> ret = provider.get_vector_table_as_dict(name=test_vector_name, - ... where="value > 1") + >>> ret = provider.get_vector_table_as_dict( + ... name=test_vector_name, where="value > 1" + ... ) >>> ret["table"] {2: [2, 'line', 2.0], 3: [3, 'centroid', 3.0]} >>> ret["columns"] Columns([('cat', 'INTEGER'), ('name', 'varchar(50)'), ('value', 'double precision')]) - >>> provider.get_vector_table_as_dict(name="no_map", - ... where="value > 1") + >>> provider.get_vector_table_as_dict(name="no_map", where="value > 1") >>> provider.stop() .. - """ + """ # noqa: E501 self.check_server() self.client_conn.send([RPCDefs.GET_VECTOR_TABLE_AS_DICT, name, mapset, where]) return self.safe_receive("get_vector_table_as_dict") @@ -360,64 +368,70 @@ def get_vector_features_as_wkb_list( >>> from grass.pygrass.rpc import DataProvider >>> provider = DataProvider() - >>> wkb = provider.get_vector_features_as_wkb_list(name=test_vector_name, - ... extent=None, - ... feature_type="point") + >>> wkb = provider.get_vector_features_as_wkb_list( + ... name=test_vector_name, extent=None, feature_type="point" + ... ) >>> for entry in wkb: ... f_id, cat, string = entry ... print(f_id, cat, len(string)) + ... 1 1 21 2 1 21 3 1 21 - >>> extent = {"north":6.6, "south":5.5, "east":14.5, "west":13.5} - >>> wkb = provider.get_vector_features_as_wkb_list(name=test_vector_name, - ... extent=extent, - ... feature_type="point") + >>> extent = {"north": 6.6, "south": 5.5, "east": 14.5, "west": 13.5} + >>> wkb = provider.get_vector_features_as_wkb_list( + ... name=test_vector_name, extent=extent, feature_type="point" + ... ) >>> for entry in wkb: ... f_id, cat, string = entry ... print(f_id, cat, len(string)) + ... 3 1 21 - >>> wkb = provider.get_vector_features_as_wkb_list(name=test_vector_name, - ... extent=None, - ... feature_type="line") + >>> wkb = provider.get_vector_features_as_wkb_list( + ... name=test_vector_name, extent=None, feature_type="line" + ... ) >>> for entry in wkb: ... f_id, cat, string = entry ... print(f_id, cat, len(string)) + ... 4 2 57 5 2 57 6 2 57 - >>> wkb = provider.get_vector_features_as_wkb_list(name=test_vector_name, - ... extent=None, - ... feature_type="centroid") + >>> wkb = provider.get_vector_features_as_wkb_list( + ... name=test_vector_name, extent=None, feature_type="centroid" + ... ) >>> for entry in wkb: ... f_id, cat, string = entry ... print(f_id, cat, len(string)) + ... 19 3 21 18 3 21 20 3 21 21 3 21 - >>> wkb = provider.get_vector_features_as_wkb_list(name=test_vector_name, - ... extent=None, - ... feature_type="area") + >>> wkb = provider.get_vector_features_as_wkb_list( + ... name=test_vector_name, extent=None, feature_type="area" + ... ) >>> for entry in wkb: ... f_id, cat, string = entry ... print(f_id, cat, len(string)) + ... 1 3 225 2 3 141 3 3 93 4 3 141 - >>> wkb = provider.get_vector_features_as_wkb_list(name=test_vector_name, - ... extent=None, - ... feature_type="boundary") + >>> wkb = provider.get_vector_features_as_wkb_list( + ... name=test_vector_name, extent=None, feature_type="boundary" + ... ) >>> for entry in wkb: ... f_id, cat, string = entry ... print(f_id, cat, len(string)) + ... 10 None 41 7 None 41 8 None 41 diff --git a/python/grass/pygrass/tests/benchmark.py b/python/grass/pygrass/tests/benchmark.py index 422feb0eec9..c63dcb8d02e 100644 --- a/python/grass/pygrass/tests/benchmark.py +++ b/python/grass/pygrass/tests/benchmark.py @@ -343,7 +343,7 @@ def print_test(testdict): TXT = """ {% for region in regions %} {{ '#'*60 }} -### Benchmark cols = {{ region.cols }} rows = {{ region.rows}} cells = {{ region.cells }} +# Benchmark cols = {{ region.cols }} rows = {{ region.rows }} cells = {{ region.cells }} {{ '#'*60 }} # equation: c = a + b diff --git a/python/grass/pygrass/utils.py b/python/grass/pygrass/utils.py index 96fe731ee3d..38a78277dd0 100644 --- a/python/grass/pygrass/utils.py +++ b/python/grass/pygrass/utils.py @@ -6,6 +6,7 @@ import grass.lib.gis as libgis libgis.G_gisinit("") + import grass.lib.raster as libraster from grass.lib.ctypes_preamble import String from grass.script import core as grasscore @@ -21,7 +22,7 @@ def looking(obj, filter_string): """ >>> import grass.lib.vector as libvect - >>> sorted(looking(libvect, '*by_box*')) # doctest: +NORMALIZE_WHITESPACE + >>> sorted(looking(libvect, "*by_box*")) # doctest: +NORMALIZE_WHITESPACE ['Vect_select_areas_by_box', 'Vect_select_isles_by_box', 'Vect_select_lines_by_box', 'Vect_select_nodes_by_box'] @@ -120,9 +121,9 @@ def rename(oldname, newname, maptype, **kwargs): def copy(existingmap, newmap, maptype, **kwargs): """Copy a map - >>> copy(test_vector_name, 'mycensus', 'vector') - >>> rename('mycensus', 'mynewcensus', 'vector') - >>> remove('mynewcensus', 'vector') + >>> copy(test_vector_name, "mycensus", "vector") + >>> rename("mycensus", "mynewcensus", "vector") + >>> remove("mynewcensus", "vector") """ kwargs.update({maptype: "{old},{new}".format(old=existingmap, new=newmap)}) @@ -176,13 +177,13 @@ def get_mapset_vector(mapname, mapset=""): def is_clean_name(name): """Return if the name is valid - >>> is_clean_name('census') + >>> is_clean_name("census") True - >>> is_clean_name('0census') + >>> is_clean_name("0census") True - >>> is_clean_name('census?') + >>> is_clean_name("census?") True - >>> is_clean_name('cénsus') + >>> is_clean_name("cénsus") False """ @@ -239,14 +240,30 @@ def get_raster_for_points(poi_vector, raster, column=None, region=None): Create a vector map - >>> cols = [(u'cat', 'INTEGER PRIMARY KEY'), - ... (u'value', 'double precision')] + >>> cols = [("cat", "INTEGER PRIMARY KEY"), ("value", "double precision")] >>> vect = VectorTopo("test_vect_2") - >>> vect.open("w",tab_name="test_vect_2", - ... tab_cols=cols) - >>> vect.write(Point(10, 6), cat=1, attrs=[10, ]) - >>> vect.write(Point(12, 6), cat=2, attrs=[12, ]) - >>> vect.write(Point(14, 6), cat=3, attrs=[14, ]) + >>> vect.open("w", tab_name="test_vect_2", tab_cols=cols) + >>> vect.write( + ... Point(10, 6), + ... cat=1, + ... attrs=[ + ... 10, + ... ], + ... ) + >>> vect.write( + ... Point(12, 6), + ... cat=2, + ... attrs=[ + ... 12, + ... ], + ... ) + >>> vect.write( + ... Point(14, 6), + ... cat=3, + ... attrs=[ + ... 14, + ... ], + ... ) >>> vect.table.conn.commit() >>> vect.close() @@ -260,38 +277,40 @@ def get_raster_for_points(poi_vector, raster, column=None, region=None): Sample the raster layer at the given points, return a list of values >>> l = get_raster_for_points(vect, ele, region=region) - >>> l[0] # doctest: +ELLIPSIS + >>> l[0] # doctest: +ELLIPSIS (1, 10.0, 6.0, 1) - >>> l[1] # doctest: +ELLIPSIS + >>> l[1] # doctest: +ELLIPSIS (2, 12.0, 6.0, 1) Add a new column and sample again >>> vect.open("r") - >>> vect.table.columns.add(test_raster_name,'double precision') + >>> vect.table.columns.add(test_raster_name, "double precision") >>> vect.table.conn.commit() >>> test_raster_name in vect.table.columns True >>> get_raster_for_points(vect, ele, column=test_raster_name, region=region) True - >>> vect.table.filters.select('value', test_raster_name) + >>> vect.table.filters.select("value", test_raster_name) Filters('SELECT value, Utils_test_raster FROM test_vect_2;') >>> cur = vect.table.execute() >>> r = cur.fetchall() - >>> r[0] # doctest: +ELLIPSIS + >>> r[0] # doctest: +ELLIPSIS (10.0, 1.0) - >>> r[1] # doctest: +ELLIPSIS + >>> r[1] # doctest: +ELLIPSIS (12.0, 1.0) - >>> remove('test_vect_2','vect') + >>> remove("test_vect_2", "vect") :param poi_vector: A VectorTopo object that contains points :param raster: raster object :param str column: column name to update in the attrinute table, if set to None a list of sampled values will be returned - :param region: The region to work with, if not set the current computational region will be used + :param region: The region to work with, if not set the current computational region + will be used :return: True in case of success and a specified column for update, - if column name for update was not set a list of (id, x, y, value) is returned + if column name for update was not set a list of (id, x, y, value) is + returned """ from math import isnan @@ -372,11 +391,15 @@ def set_path(modulename, dirname=None, path="."): def split_in_chunk(iterable, length=10): """Split a list in chunk. - >>> for chunk in split_in_chunk(range(25)): print (chunk) + >>> for chunk in split_in_chunk(range(25)): + ... print(chunk) + ... (0, 1, 2, 3, 4, 5, 6, 7, 8, 9) (10, 11, 12, 13, 14, 15, 16, 17, 18, 19) (20, 21, 22, 23, 24) - >>> for chunk in split_in_chunk(range(25), 3): print (chunk) + >>> for chunk in split_in_chunk(range(25), 3): + ... print(chunk) + ... (0, 1, 2) (3, 4, 5) (6, 7, 8) diff --git a/python/grass/pygrass/vector/__init__.py b/python/grass/pygrass/vector/__init__.py index 4016fe34dd5..44baff75300 100644 --- a/python/grass/pygrass/vector/__init__.py +++ b/python/grass/pygrass/vector/__init__.py @@ -2,12 +2,11 @@ import grass.lib.gis as libgis libgis.G_gisinit("") + import grass.lib.vector as libvect import ctypes -# # import pygrass modules -# from grass.pygrass.vector.vector_type import VTYPE from grass.pygrass.errors import GrassError, must_be_open from grass.pygrass.gis import Location @@ -78,14 +77,14 @@ def __iter__(self): """:: >>> test_vect = Vector(test_vector_name) - >>> test_vect.open(mode='r') + >>> test_vect.open(mode="r") >>> features = [feature for feature in test_vect] >>> features[:3] [Point(10.000000, 6.000000), Point(12.000000, 6.000000), Point(14.000000, 6.000000)] >>> test_vect.close() .. - """ + """ # noqa: E501 # return (self.read(f_id) for f_id in xrange(self.num_of_features())) return self @@ -94,7 +93,7 @@ def __next__(self): """:: >>> test_vect = Vector(test_vector_name) - >>> test_vect.open(mode='r') + >>> test_vect.open(mode="r") >>> test_vect.next() Point(10.000000, 6.000000) >>> test_vect.next() @@ -133,18 +132,17 @@ def write(self, geo_obj, cat=None, attrs=None): Open a new vector map :: - >>> new = VectorTopo('newvect') + >>> new = VectorTopo("newvect") >>> new.exist() False define the new columns of the attribute table :: - >>> cols = [(u'cat', 'INTEGER PRIMARY KEY'), - ... (u'name', 'TEXT')] + >>> cols = [("cat", "INTEGER PRIMARY KEY"), ("name", "TEXT")] open the vector map in write mode - >>> new.open('w', tab_name='newvect', tab_cols=cols) + >>> new.open("w", tab_name="newvect", tab_cols=cols) import a geometry feature :: @@ -157,8 +155,8 @@ def write(self, geo_obj, cat=None, attrs=None): then write the two points on the map, with :: - >>> new.write(point0, cat=1, attrs=('pub',)) - >>> new.write(point1, cat=2, attrs=('resturant',)) + >>> new.write(point0, cat=1, attrs=("pub",)) + >>> new.write(point1, cat=2, attrs=("resturant",)) commit the db changes :: @@ -174,14 +172,14 @@ def write(self, geo_obj, cat=None, attrs=None): then play with the map :: - >>> new.open(mode='r') + >>> new.open(mode="r") >>> new.read(1) Point(0.000000, 0.000000) >>> new.read(2) Point(1.000000, 1.000000) - >>> new.read(1).attrs['name'] + >>> new.read(1).attrs["name"] 'pub' - >>> new.read(2).attrs['name'] + >>> new.read(2).attrs["name"] 'resturant' >>> new.close() >>> new.remove() @@ -241,22 +239,22 @@ def has_color_table(self): Color table stored in the vector's attribute table well be not checked >>> test_vect = Vector(test_vector_name) - >>> test_vect.open(mode='r') + >>> test_vect.open(mode="r") >>> test_vect.has_color_table() False >>> test_vect.close() >>> from grass.pygrass.utils import copy, remove - >>> copy(test_vector_name,'mytest_vect','vect') + >>> copy(test_vector_name, "mytest_vect", "vect") >>> from grass.pygrass.modules.shortcuts import vector as v - >>> v.colors(map='mytest_vect', color='population', column='value') + >>> v.colors(map="mytest_vect", color="population", column="value") Module('v.colors') - >>> mytest_vect = Vector('mytest_vect') - >>> mytest_vect.open(mode='r') + >>> mytest_vect = Vector("mytest_vect") + >>> mytest_vect.open(mode="r") >>> mytest_vect.has_color_table() True >>> mytest_vect.close() - >>> remove('mytest_vect', 'vect') + >>> remove("mytest_vect", "vect") """ loc = Location() path = join(loc.path(), self.mapset, "vector", self.name, "colr") @@ -273,9 +271,9 @@ class VectorTopo(Vector): Open a vector map using the *with statement*: :: - >>> with VectorTopo(test_vector_name, mode='r') as test_vect: + >>> with VectorTopo(test_vector_name, mode="r") as test_vect: ... for feature in test_vect[:7]: - ... print(feature.attrs['name']) + ... print(feature.attrs["name"]) ... point point @@ -301,13 +299,13 @@ def __getitem__(self, key): """:: >>> test_vect = VectorTopo(test_vector_name) - >>> test_vect.open(mode='r') + >>> test_vect.open(mode="r") >>> test_vect[:4] [Point(10.000000, 6.000000), Point(12.000000, 6.000000), Point(14.000000, 6.000000)] >>> test_vect.close() .. - """ + """ # noqa: E501 if isinstance(key, slice): return [ self.read(indx) @@ -342,14 +340,14 @@ def num_primitive_of(self, primitive): :: >>> test_vect = VectorTopo(test_vector_name) - >>> test_vect.open(mode='r') - >>> test_vect.num_primitive_of('point') + >>> test_vect.open(mode="r") + >>> test_vect.num_primitive_of("point") 3 - >>> test_vect.num_primitive_of('line') + >>> test_vect.num_primitive_of("line") 3 - >>> test_vect.num_primitive_of('centroid') + >>> test_vect.num_primitive_of("centroid") 4 - >>> test_vect.num_primitive_of('boundary') + >>> test_vect.num_primitive_of("boundary") 11 >>> test_vect.close() @@ -369,7 +367,7 @@ def number_of(self, vtype): :type vtype: str >>> test_vect = VectorTopo(test_vector_name) - >>> test_vect.open(mode='r') + >>> test_vect.open(mode="r") >>> test_vect.number_of("areas") 4 >>> test_vect.number_of("islands") @@ -381,7 +379,7 @@ def number_of(self, vtype): >>> test_vect.number_of("nodes") 15 >>> test_vect.number_of("pizza") - ... # doctest: +ELLIPSIS +NORMALIZE_WHITESPACE + ... # doctest: +ELLIPSIS +NORMALIZE_WHITESPACE Traceback (most recent call last): ... ValueError: vtype not supported, use one of: 'areas', ... @@ -421,9 +419,9 @@ def viter(self, vtype, idonly=False): full features :type idonly: bool - >>> test_vect = VectorTopo(test_vector_name, mode='r') - >>> test_vect.open(mode='r') - >>> areas = [area for area in test_vect.viter('areas')] + >>> test_vect = VectorTopo(test_vector_name, mode="r") + >>> test_vect.open(mode="r") + >>> areas = [area for area in test_vect.viter("areas")] >>> areas[:3] [Area(1), Area(2), Area(3)] @@ -431,16 +429,17 @@ def viter(self, vtype, idonly=False): to sort the result in a efficient way, use: :: >>> from operator import methodcaller as method - >>> areas.sort(key=method('area'), reverse=True) # sort the list + >>> areas.sort(key=method("area"), reverse=True) # sort the list >>> for area in areas[:3]: ... print(area, area.area()) Area(1) 12.0 Area(2) 8.0 Area(4) 8.0 - >>> areas = [area for area in test_vect.viter('areas')] + >>> areas = [area for area in test_vect.viter("areas")] >>> for area in areas: ... print(area.centroid().cat) + ... 3 3 3 @@ -473,7 +472,7 @@ def rewind(self): """Rewind vector map to cause reads to start at beginning. :: >>> test_vect = VectorTopo(test_vector_name) - >>> test_vect.open(mode='r') + >>> test_vect.open(mode="r") >>> test_vect.next() Point(10.000000, 6.000000) >>> test_vect.next() @@ -546,8 +545,8 @@ def read(self, feature_id): :param int feature_id: the id of feature to obtain >>> test_vect = VectorTopo(test_vector_name) - >>> test_vect.open(mode='r') - >>> feature1 = test_vect.read(0) #doctest: +ELLIPSIS + >>> test_vect.open(mode="r") + >>> feature1 = test_vect.read(0) # doctest: +ELLIPSIS Traceback (most recent call last): ... ValueError: The index must be >0, 0 given. @@ -562,13 +561,13 @@ def read(self, feature_id): 21 >>> test_vect.read(21) Centroid(7.500000, 3.500000) - >>> test_vect.read(22) #doctest: +ELLIPSIS + >>> test_vect.read(22) # doctest: +ELLIPSIS Traceback (most recent call last): ... IndexError: Index out of range >>> test_vect.close() - """ + """ # noqa: E501 return read_line( feature_id, self.c_mapinfo, @@ -592,14 +591,12 @@ def is_empty(self): def rewrite(self, geo_obj, cat, attrs=None, **kargs): """Rewrite a geometry features - >>> cols = [(u'cat', 'INTEGER PRIMARY KEY'), - ... (u'name', 'TEXT')] + >>> cols = [("cat", "INTEGER PRIMARY KEY"), ("name", "TEXT")] Generate a new vector map - >>> test_vect = VectorTopo('newvect_2') - >>> test_vect.open('w', tab_name='newvect_2', tab_cols=cols, - ... overwrite=True) + >>> test_vect = VectorTopo("newvect_2") + >>> test_vect.open("w", tab_name="newvect_2", tab_cols=cols, overwrite=True) import a geometry feature :: @@ -613,8 +610,8 @@ def rewrite(self, geo_obj, cat, attrs=None, **kargs): then write the two points on the map, with :: - >>> test_vect.write(point0, cat=1, attrs=('pub',)) - >>> test_vect.write(point1, cat=2, attrs=('resturant',)) + >>> test_vect.write(point0, cat=1, attrs=("pub",)) + >>> test_vect.write(point1, cat=2, attrs=("resturant",)) >>> test_vect.table.conn.commit() # save changes in the DB >>> test_vect.table_to_dict() {1: [1, 'pub'], 2: [2, 'resturant']} @@ -622,17 +619,17 @@ def rewrite(self, geo_obj, cat, attrs=None, **kargs): Now rewrite one point of the vector map: :: - >>> test_vect.open('rw') - >>> test_vect.rewrite(point2, cat=1, attrs=('Irish Pub',)) + >>> test_vect.open("rw") + >>> test_vect.rewrite(point2, cat=1, attrs=("Irish Pub",)) >>> test_vect.table.conn.commit() # save changes in the DB >>> test_vect.close() Check the output: - >>> test_vect.open('r') + >>> test_vect.open("r") >>> test_vect[1] == point2 True - >>> test_vect[1].attrs['name'] == 'Irish Pub' + >>> test_vect[1].attrs["name"] == "Irish Pub" True >>> test_vect.close() >>> test_vect.remove() @@ -701,7 +698,7 @@ def table_to_dict(self, where=None): >>> from grass.pygrass.vector import VectorTopo >>> from grass.pygrass.vector.basic import Bbox >>> test_vect = VectorTopo(test_vector_name) - >>> test_vect.open('r') + >>> test_vect.open("r") >>> test_vect.table_to_dict() {1: [1, 'point', 1.0], 2: [2, 'line', 2.0], 3: [3, 'centroid', 3.0]} @@ -772,58 +769,56 @@ def features_to_wkb_list(self, bbox=None, feature_type="point", field=1): >>> from grass.pygrass.vector import VectorTopo >>> from grass.pygrass.vector.basic import Bbox >>> test_vect = VectorTopo(test_vector_name) - >>> test_vect.open('r') + >>> test_vect.open("r") >>> bbox = Bbox(north=20, south=-1, east=20, west=-1) - >>> result = test_vect.features_to_wkb_list(bbox=bbox, - ... feature_type="point") + >>> result = test_vect.features_to_wkb_list(bbox=bbox, feature_type="point") >>> len(result) 3 >>> for entry in result: ... f_id, cat, wkb = entry ... print((f_id, cat, len(wkb))) + ... (1, 1, 21) (2, 1, 21) (3, 1, 21) - >>> result = test_vect.features_to_wkb_list(bbox=None, - ... feature_type="line") + >>> result = test_vect.features_to_wkb_list(bbox=None, feature_type="line") >>> len(result) 3 >>> for entry in result: ... f_id, cat, wkb = entry ... print((f_id, cat, len(wkb))) + ... (4, 2, 57) (5, 2, 57) (6, 2, 57) - >>> result = test_vect.features_to_wkb_list(bbox=bbox, - ... feature_type="boundary") + >>> result = test_vect.features_to_wkb_list(bbox=bbox, feature_type="boundary") >>> len(result) 11 - >>> result = test_vect.features_to_wkb_list(bbox=None, - ... feature_type="centroid") + >>> result = test_vect.features_to_wkb_list(bbox=None, feature_type="centroid") >>> len(result) 4 >>> for entry in result: ... f_id, cat, wkb = entry ... print((f_id, cat, len(wkb))) + ... (19, 3, 21) (18, 3, 21) (20, 3, 21) (21, 3, 21) - >>> result = test_vect.features_to_wkb_list(bbox=bbox, - ... feature_type="blub") + >>> result = test_vect.features_to_wkb_list(bbox=bbox, feature_type="blub") Traceback (most recent call last): ... grass.exceptions.GrassError: Unsupported feature type , supported are >>> test_vect.close() - """ + """ # noqa: E501 supported = ["point", "line", "boundary", "centroid"] @@ -905,7 +900,7 @@ def areas_to_wkb_list(self, bbox=None, field=1): >>> from grass.pygrass.vector import VectorTopo >>> from grass.pygrass.vector.basic import Bbox >>> test_vect = VectorTopo(test_vector_name) - >>> test_vect.open('r') + >>> test_vect.open("r") >>> bbox = Bbox(north=20, south=-1, east=20, west=-1) >>> result = test_vect.areas_to_wkb_list(bbox=bbox) @@ -914,6 +909,7 @@ def areas_to_wkb_list(self, bbox=None, field=1): >>> for entry in result: ... a_id, cat, wkb = entry ... print((a_id, cat, len(wkb))) + ... (1, 3, 225) (2, 3, 141) (3, 3, 93) @@ -925,6 +921,7 @@ def areas_to_wkb_list(self, bbox=None, field=1): >>> for entry in result: ... a_id, cat, wkb = entry ... print((a_id, cat, len(wkb))) + ... (1, 3, 225) (2, 3, 141) (3, 3, 93) diff --git a/python/grass/pygrass/vector/table.py b/python/grass/pygrass/vector/table.py index e4f6de52ab4..48badee09f0 100644 --- a/python/grass/pygrass/vector/table.py +++ b/python/grass/pygrass/vector/table.py @@ -38,17 +38,28 @@ def get_path(path, vect_name=None): >>> from grass.script.core import gisenv >>> import os - >>> path = '$GISDBASE/$LOCATION_NAME/$MAPSET/sqlite/sqlite.db' + >>> path = "$GISDBASE/$LOCATION_NAME/$MAPSET/sqlite/sqlite.db" >>> new_path = get_path(path) - >>> new_path2 = os.path.join(gisenv()['GISDBASE'], gisenv()['LOCATION_NAME'], - ... gisenv()['MAPSET'], 'sqlite', 'sqlite.db') - >>> new_path.replace("//","/") == new_path2.replace("//","/") + >>> new_path2 = os.path.join( + ... gisenv()["GISDBASE"], + ... gisenv()["LOCATION_NAME"], + ... gisenv()["MAPSET"], + ... "sqlite", + ... "sqlite.db", + ... ) + >>> new_path.replace("//", "/") == new_path2.replace("//", "/") True - >>> path = '$GISDBASE/$LOCATION_NAME/$MAPSET/vector/$MAP/sqlite.db' + >>> path = "$GISDBASE/$LOCATION_NAME/$MAPSET/vector/$MAP/sqlite.db" >>> new_path = get_path(path, "test") - >>> new_path2 = os.path.join(gisenv()['GISDBASE'], gisenv()['LOCATION_NAME'], - ... gisenv()['MAPSET'], 'vector', 'test', 'sqlite.db') - >>> new_path.replace("//","/") == new_path2.replace("//","/") + >>> new_path2 = os.path.join( + ... gisenv()["GISDBASE"], + ... gisenv()["LOCATION_NAME"], + ... gisenv()["MAPSET"], + ... "vector", + ... "test", + ... "sqlite.db", + ... ) + >>> new_path.replace("//", "/") == new_path2.replace("//", "/") True """ @@ -67,7 +78,7 @@ def get_path(path, vect_name=None): class Filters: """Help user to build a simple sql query. - >>> filter = Filters('table') + >>> filter = Filters("table") >>> filter.get_sql() 'SELECT * FROM table;' >>> filter.where("area<10000").get_sql() @@ -172,18 +183,18 @@ class Columns: For a sqlite table: >>> import sqlite3 - >>> path = '$GISDBASE/$LOCATION_NAME/$MAPSET/sqlite/sqlite.db' - >>> cols_sqlite = Columns(test_vector_name, - ... sqlite3.connect(get_path(path))) + >>> path = "$GISDBASE/$LOCATION_NAME/$MAPSET/sqlite/sqlite.db" + >>> cols_sqlite = Columns(test_vector_name, sqlite3.connect(get_path(path))) >>> cols_sqlite.tname 'table_doctest_map' For a postgreSQL table: - >>> import psycopg2 as pg #doctest: +SKIP - >>> cols_pg = Columns(test_vector_name, - ... pg.connect('host=localhost dbname=grassdb')) #doctest: +SKIP - >>> cols_pg.tname #doctest: +SKIP + >>> import psycopg2 as pg # doctest: +SKIP + >>> cols_pg = Columns( + ... test_vector_name, pg.connect("host=localhost dbname=grassdb") + ... ) # doctest: +SKIP + >>> cols_pg.tname # doctest: +SKIP 'table_doctest_map' #doctest: +SKIP """ @@ -218,7 +229,7 @@ def __eq__(self, obj): """Return True if two table have the same columns. >>> import sqlite3 - >>> path = '$GISDBASE/$LOCATION_NAME/$MAPSET/sqlite/sqlite.db' + >>> path = "$GISDBASE/$LOCATION_NAME/$MAPSET/sqlite/sqlite.db" >>> connection = sqlite3.connect(get_path(path)) >>> cols0 = Columns(test_vector_name, connection) >>> cols1 = Columns(test_vector_name, connection) @@ -237,15 +248,15 @@ def is_pg(self): """Return True if is a psycopg connection. >>> import sqlite3 - >>> path = '$GISDBASE/$LOCATION_NAME/$MAPSET/sqlite/sqlite.db' - >>> cols_sqlite = Columns(test_vector_name, - ... sqlite3.connect(get_path(path))) + >>> path = "$GISDBASE/$LOCATION_NAME/$MAPSET/sqlite/sqlite.db" + >>> cols_sqlite = Columns(test_vector_name, sqlite3.connect(get_path(path))) >>> cols_sqlite.is_pg() False - >>> import psycopg2 as pg #doctest: +SKIP - >>> cols_pg = Columns(test_vector_name, - ... pg.connect('host=localhost dbname=grassdb')) #doctest: +SKIP - >>> cols_pg.is_pg() #doctest: +SKIP + >>> import psycopg2 as pg # doctest: +SKIP + >>> cols_pg = Columns( + ... test_vector_name, pg.connect("host=localhost dbname=grassdb") + ... ) # doctest: +SKIP + >>> cols_pg.is_pg() # doctest: +SKIP True """ @@ -300,15 +311,15 @@ def sql_descr(self, remove=None): Remove it is used to remove a columns. >>> import sqlite3 - >>> path = '$GISDBASE/$LOCATION_NAME/$MAPSET/sqlite/sqlite.db' - >>> cols_sqlite = Columns(test_vector_name, - ... sqlite3.connect(get_path(path))) - >>> cols_sqlite.sql_descr() # doctest: +ELLIPSIS + >>> path = "$GISDBASE/$LOCATION_NAME/$MAPSET/sqlite/sqlite.db" + >>> cols_sqlite = Columns(test_vector_name, sqlite3.connect(get_path(path))) + >>> cols_sqlite.sql_descr() # doctest: +ELLIPSIS 'cat INTEGER, name varchar(50), value double precision' - >>> import psycopg2 as pg # doctest: +SKIP - >>> cols_pg = Columns(test_vector_name, - ... pg.connect('host=localhost dbname=grassdb')) # doctest: +SKIP - >>> cols_pg.sql_descr() # doctest: +ELLIPSIS +SKIP + >>> import psycopg2 as pg # doctest: +SKIP + >>> cols_pg = Columns( + ... test_vector_name, pg.connect("host=localhost dbname=grassdb") + ... ) # doctest: +SKIP + >>> cols_pg.sql_descr() # doctest: +ELLIPSIS +SKIP 'cat INTEGER, name varchar(50), value double precision' """ if remove: @@ -322,15 +333,15 @@ def types(self): """Return a list with the column types. >>> import sqlite3 - >>> path = '$GISDBASE/$LOCATION_NAME/$MAPSET/sqlite/sqlite.db' - >>> cols_sqlite = Columns(test_vector_name, - ... sqlite3.connect(get_path(path))) - >>> cols_sqlite.types() # doctest: +ELLIPSIS + >>> path = "$GISDBASE/$LOCATION_NAME/$MAPSET/sqlite/sqlite.db" + >>> cols_sqlite = Columns(test_vector_name, sqlite3.connect(get_path(path))) + >>> cols_sqlite.types() # doctest: +ELLIPSIS ['INTEGER', 'varchar(50)', 'double precision'] - >>> import psycopg2 as pg # doctest: +SKIP - >>> cols_pg = Columns(test_vector_name, - ... pg.connect('host=localhost dbname=grassdb')) # doctest: +SKIP - >>> cols_pg.types() # doctest: +ELLIPSIS +SKIP + >>> import psycopg2 as pg # doctest: +SKIP + >>> cols_pg = Columns( + ... test_vector_name, pg.connect("host=localhost dbname=grassdb") + ... ) # doctest: +SKIP + >>> cols_pg.types() # doctest: +ELLIPSIS +SKIP ['INTEGER', 'varchar(50)', 'double precision'] """ @@ -341,15 +352,16 @@ def names(self, remove=None, unicod=True): Remove it is used to remove a columns. >>> import sqlite3 - >>> path = '$GISDBASE/$LOCATION_NAME/$MAPSET/sqlite/sqlite.db' - >>> cols_sqlite = Columns(test_vector_name, - ... sqlite3.connect(get_path(path))) - >>> cols_sqlite.names() # doctest: +ELLIPSIS + >>> path = "$GISDBASE/$LOCATION_NAME/$MAPSET/sqlite/sqlite.db" + >>> cols_sqlite = Columns(test_vector_name, sqlite3.connect(get_path(path))) + >>> cols_sqlite.names() # doctest: +ELLIPSIS ['cat', 'name', 'value'] - >>> import psycopg2 as pg # doctest: +SKIP - >>> cols_pg = Columns(test_vector_name, # doctest: +SKIP - ... pg.connect('host=localhost dbname=grassdb')) - >>> cols_pg.names() # doctest: +ELLIPSIS +SKIP + >>> import psycopg2 as pg # doctest: +SKIP + >>> cols_pg = Columns( + ... test_vector_name, # doctest: +SKIP + ... pg.connect("host=localhost dbname=grassdb"), + ... ) + >>> cols_pg.names() # doctest: +ELLIPSIS +SKIP ['cat', 'name', 'value'] """ @@ -367,15 +379,15 @@ def items(self): """Return a list of tuple with column name and column type. >>> import sqlite3 - >>> path = '$GISDBASE/$LOCATION_NAME/$MAPSET/sqlite/sqlite.db' - >>> cols_sqlite = Columns(test_vector_name, - ... sqlite3.connect(get_path(path))) - >>> cols_sqlite.items() # doctest: +ELLIPSIS + >>> path = "$GISDBASE/$LOCATION_NAME/$MAPSET/sqlite/sqlite.db" + >>> cols_sqlite = Columns(test_vector_name, sqlite3.connect(get_path(path))) + >>> cols_sqlite.items() # doctest: +ELLIPSIS [('cat', 'INTEGER'), ('name', 'varchar(50)'), ('value', 'double precision')] - >>> import psycopg2 as pg # doctest: +SKIP - >>> cols_pg = Columns(test_vector_name, - ... pg.connect('host=localhost dbname=grassdb')) # doctest: +SKIP - >>> cols_pg.items() # doctest: +ELLIPSIS +SKIP + >>> import psycopg2 as pg # doctest: +SKIP + >>> cols_pg = Columns( + ... test_vector_name, pg.connect("host=localhost dbname=grassdb") + ... ) # doctest: +SKIP + >>> cols_pg.items() # doctest: +ELLIPSIS +SKIP [('cat', 'INTEGER'), ('name', 'varchar(50)'), ('value', 'double precision')] """ @@ -390,21 +402,21 @@ def add(self, col_name, col_type): :type col_type: str >>> import sqlite3 - >>> path = '$GISDBASE/$LOCATION_NAME/$MAPSET/sqlite/sqlite.db' + >>> path = "$GISDBASE/$LOCATION_NAME/$MAPSET/sqlite/sqlite.db" >>> from grass.pygrass.utils import copy, remove - >>> copy(test_vector_name,'mycensus','vect') - >>> cols_sqlite = Columns('mycensus', - ... sqlite3.connect(get_path(path))) - >>> cols_sqlite.add(['n_pizza'], ['INT']) - >>> 'n_pizza' in cols_sqlite + >>> copy(test_vector_name, "mycensus", "vect") + >>> cols_sqlite = Columns("mycensus", sqlite3.connect(get_path(path))) + >>> cols_sqlite.add(["n_pizza"], ["INT"]) + >>> "n_pizza" in cols_sqlite True - >>> import psycopg2 as pg # doctest: +SKIP - >>> cols_pg = Columns('boundary_municp_pg', - ... pg.connect('host=localhost dbname=grassdb')) #doctest: +SKIP - >>> cols_pg.add('n_pizza', 'INT') # doctest: +SKIP - >>> 'n_pizza' in cols_pg # doctest: +SKIP + >>> import psycopg2 as pg # doctest: +SKIP + >>> cols_pg = Columns( + ... "boundary_municp_pg", pg.connect("host=localhost dbname=grassdb") + ... ) # doctest: +SKIP + >>> cols_pg.add("n_pizza", "INT") # doctest: +SKIP + >>> "n_pizza" in cols_pg # doctest: +SKIP True - >>> remove('mycensus', 'vect') + >>> remove("mycensus", "vect") """ @@ -462,29 +474,29 @@ def rename(self, old_name, new_name): :type new_name: str >>> import sqlite3 - >>> path = '$GISDBASE/$LOCATION_NAME/$MAPSET/sqlite/sqlite.db' + >>> path = "$GISDBASE/$LOCATION_NAME/$MAPSET/sqlite/sqlite.db" >>> from grass.pygrass.utils import copy, remove - >>> copy(test_vector_name,'mycensus','vect') - >>> cols_sqlite = Columns('mycensus', - ... sqlite3.connect(get_path(path))) - >>> cols_sqlite.add(['n_pizza'], ['INT']) - >>> 'n_pizza' in cols_sqlite + >>> copy(test_vector_name, "mycensus", "vect") + >>> cols_sqlite = Columns("mycensus", sqlite3.connect(get_path(path))) + >>> cols_sqlite.add(["n_pizza"], ["INT"]) + >>> "n_pizza" in cols_sqlite True - >>> cols_sqlite.rename('n_pizza', 'n_pizzas') # doctest: +ELLIPSIS - >>> 'n_pizza' in cols_sqlite + >>> cols_sqlite.rename("n_pizza", "n_pizzas") # doctest: +ELLIPSIS + >>> "n_pizza" in cols_sqlite False - >>> 'n_pizzas' in cols_sqlite + >>> "n_pizzas" in cols_sqlite True - >>> import psycopg2 as pg # doctest: +SKIP - >>> cols_pg = Columns(test_vector_name, - ... pg.connect('host=localhost dbname=grassdb')) # doctest: +SKIP - >>> cols_pg.rename('n_pizza', 'n_pizzas') # doctest: +SKIP - >>> 'n_pizza' in cols_pg # doctest: +SKIP + >>> import psycopg2 as pg # doctest: +SKIP + >>> cols_pg = Columns( + ... test_vector_name, pg.connect("host=localhost dbname=grassdb") + ... ) # doctest: +SKIP + >>> cols_pg.rename("n_pizza", "n_pizzas") # doctest: +SKIP + >>> "n_pizza" in cols_pg # doctest: +SKIP False - >>> 'n_pizzas' in cols_pg # doctest: +SKIP + >>> "n_pizzas" in cols_pg # doctest: +SKIP True - >>> remove('mycensus', 'vect') + >>> remove("mycensus", "vect") """ cur = self.conn.cursor() @@ -520,23 +532,23 @@ def cast(self, col_name, new_type): :type new_type: str >>> import sqlite3 - >>> path = '$GISDBASE/$LOCATION_NAME/$MAPSET/sqlite/sqlite.db' + >>> path = "$GISDBASE/$LOCATION_NAME/$MAPSET/sqlite/sqlite.db" >>> from grass.pygrass.utils import copy, remove - >>> copy(test_vector_name,'mycensus','vect') - >>> cols_sqlite = Columns('mycensus', - ... sqlite3.connect(get_path(path))) - >>> cols_sqlite.add(['n_pizzas'], ['INT']) - >>> cols_sqlite.cast('n_pizzas', 'float8') # doctest: +ELLIPSIS + >>> copy(test_vector_name, "mycensus", "vect") + >>> cols_sqlite = Columns("mycensus", sqlite3.connect(get_path(path))) + >>> cols_sqlite.add(["n_pizzas"], ["INT"]) + >>> cols_sqlite.cast("n_pizzas", "float8") # doctest: +ELLIPSIS Traceback (most recent call last): ... grass.exceptions.DBError: SQLite does not support to cast columns. - >>> import psycopg2 as pg # doctest: +SKIP - >>> cols_pg = Columns(test_vector_name, - ... pg.connect('host=localhost dbname=grassdb')) # doctest: +SKIP - >>> cols_pg.cast('n_pizzas', 'float8') # doctest: +SKIP - >>> cols_pg['n_pizzas'] # doctest: +SKIP + >>> import psycopg2 as pg # doctest: +SKIP + >>> cols_pg = Columns( + ... test_vector_name, pg.connect("host=localhost dbname=grassdb") + ... ) # doctest: +SKIP + >>> cols_pg.cast("n_pizzas", "float8") # doctest: +SKIP + >>> cols_pg["n_pizzas"] # doctest: +SKIP 'float8' - >>> remove('mycensus', 'vect') + >>> remove("mycensus", "vect") .. warning :: @@ -562,22 +574,22 @@ def drop(self, col_name): :type col_name: str >>> import sqlite3 - >>> path = '$GISDBASE/$LOCATION_NAME/$MAPSET/sqlite/sqlite.db' + >>> path = "$GISDBASE/$LOCATION_NAME/$MAPSET/sqlite/sqlite.db" >>> from grass.pygrass.utils import copy, remove - >>> copy(test_vector_name,'mycensus','vect') - >>> cols_sqlite = Columns('mycensus', - ... sqlite3.connect(get_path(path))) - >>> cols_sqlite.drop('name') # doctest: +ELLIPSIS - >>> 'name' in cols_sqlite + >>> copy(test_vector_name, "mycensus", "vect") + >>> cols_sqlite = Columns("mycensus", sqlite3.connect(get_path(path))) + >>> cols_sqlite.drop("name") # doctest: +ELLIPSIS + >>> "name" in cols_sqlite False - >>> import psycopg2 as pg # doctest: +SKIP - >>> cols_pg = Columns(test_vector_name, - ... pg.connect('host=localhost dbname=grassdb')) # doctest: +SKIP - >>> cols_pg.drop('name') # doctest: +SKIP - >>> 'name' in cols_pg # doctest: +SKIP + >>> import psycopg2 as pg # doctest: +SKIP + >>> cols_pg = Columns( + ... test_vector_name, pg.connect("host=localhost dbname=grassdb") + ... ) # doctest: +SKIP + >>> cols_pg.drop("name") # doctest: +SKIP + >>> "name" in cols_pg # doctest: +SKIP False - >>> remove('mycensus','vect') + >>> remove("mycensus", "vect") """ cur = self.conn.cursor() @@ -602,8 +614,14 @@ class Link: It is possible to define a Link object or given all the information (layer, name, table name, key, database, driver): - >>> link = Link(1, 'link0', test_vector_name, 'cat', - ... '$GISDBASE/$LOCATION_NAME/$MAPSET/sqlite/sqlite.db', 'sqlite') + >>> link = Link( + ... 1, + ... "link0", + ... test_vector_name, + ... "cat", + ... "$GISDBASE/$LOCATION_NAME/$MAPSET/sqlite/sqlite.db", + ... "sqlite", + ... ) >>> link.layer 1 >>> link.name @@ -622,16 +640,16 @@ class Link: It is possible to change parameters with: - >>> link.driver = 'pg' # doctest: +SKIP - >>> link.driver # doctest: +SKIP + >>> link.driver = "pg" # doctest: +SKIP + >>> link.driver # doctest: +SKIP 'pg' - >>> link.driver = 'postgres' # doctest: +ELLIPSIS +SKIP + >>> link.driver = "postgres" # doctest: +ELLIPSIS +SKIP Traceback (most recent call last): ... TypeError: Driver not supported, use: sqlite, pg. - >>> link.driver # doctest: +SKIP + >>> link.driver # doctest: +SKIP 'pg' - >>> link.number = 0 # doctest: +ELLIPSIS +SKIP + >>> link.number = 0 # doctest: +ELLIPSIS +SKIP Traceback (most recent call last): ... TypeError: Number must be positive and greater than 0. @@ -640,7 +658,7 @@ class Link: Or given a c_fieldinfo object that is a ctypes pointer to the field_info C struct. :: - >>> link = Link(c_fieldinfo = ctypes.pointer(libvect.field_info())) + >>> link = Link(c_fieldinfo=ctypes.pointer(libvect.field_info())) """ @@ -743,12 +761,30 @@ def __repr__(self): def __eq__(self, link): """Return True if two Link instance have the same parameters. - >>> l0 = Link(1, 'link0', test_vector_name, 'cat', - ... '$GISDBASE/$LOCATION_NAME/$MAPSET/sqlite/sqlite.db', 'sqlite') - >>> l1 = Link(1, 'link0', test_vector_name, 'cat', - ... '$GISDBASE/$LOCATION_NAME/$MAPSET/sqlite/sqlite.db', 'sqlite') - >>> l2 = Link(2, 'link0', test_vector_name, 'cat', - ... '$GISDBASE/$LOCATION_NAME/PERMANENT/sqlite/sqlite.db', 'sqlite') + >>> l0 = Link( + ... 1, + ... "link0", + ... test_vector_name, + ... "cat", + ... "$GISDBASE/$LOCATION_NAME/$MAPSET/sqlite/sqlite.db", + ... "sqlite", + ... ) + >>> l1 = Link( + ... 1, + ... "link0", + ... test_vector_name, + ... "cat", + ... "$GISDBASE/$LOCATION_NAME/$MAPSET/sqlite/sqlite.db", + ... "sqlite", + ... ) + >>> l2 = Link( + ... 2, + ... "link0", + ... test_vector_name, + ... "cat", + ... "$GISDBASE/$LOCATION_NAME/PERMANENT/sqlite/sqlite.db", + ... "sqlite", + ... ) >>> l0 == l1 True >>> l1 == l2 @@ -769,17 +805,23 @@ def __ne__(self, other): def connection(self): """Return a connection object. - >>> link = Link(1, 'link0', test_vector_name, 'cat', - ... '$GISDBASE/$LOCATION_NAME/$MAPSET/sqlite/sqlite.db', - ... 'sqlite') + >>> link = Link( + ... 1, + ... "link0", + ... test_vector_name, + ... "cat", + ... "$GISDBASE/$LOCATION_NAME/$MAPSET/sqlite/sqlite.db", + ... "sqlite", + ... ) >>> conn = link.connection() >>> cur = conn.cursor() >>> link.table_name 'table_doctest_map' - >>> cur.execute("SELECT cat, name, value from %s" % - ... link.table_name) # doctest: +ELLIPSIS + >>> cur.execute( + ... "SELECT cat, name, value from %s" % link.table_name + ... ) # doctest: +ELLIPSIS - >>> cur.fetchone() #doctest: +ELLIPSIS +NORMALIZE_WHITESPACE + >>> cur.fetchone() # doctest: +ELLIPSIS +NORMALIZE_WHITESPACE (1, 'point', 1.0) >>> cur.close() >>> conn.close() @@ -825,11 +867,16 @@ def connection(self): def table(self): """Return a Table object. - >>> link = Link(1, 'link0', test_vector_name, 'cat', - ... '$GISDBASE/$LOCATION_NAME/$MAPSET/sqlite/sqlite.db', - ... 'sqlite') + >>> link = Link( + ... 1, + ... "link0", + ... test_vector_name, + ... "cat", + ... "$GISDBASE/$LOCATION_NAME/$MAPSET/sqlite/sqlite.db", + ... "sqlite", + ... ) >>> table = link.table() - >>> table.filters.select('cat', 'name', 'value') + >>> table.filters.select("cat", "name", "value") Filters('SELECT cat, name, value FROM table_doctest_map;') >>> cur = table.execute() >>> cur.fetchone() @@ -842,9 +889,14 @@ def table(self): def info(self): """Print information of the link. - >>> link = Link(1, 'link0', test_vector_name, 'cat', - ... '$GISDBASE/$LOCATION_NAME/$MAPSET/sqlite/sqlite.db', - ... 'sqlite') + >>> link = Link( + ... 1, + ... "link0", + ... test_vector_name, + ... "cat", + ... "$GISDBASE/$LOCATION_NAME/$MAPSET/sqlite/sqlite.db", + ... "sqlite", + ... ) >>> link.info() layer: 1 name: link0 @@ -867,7 +919,7 @@ class DBlinks: >>> from grass.pygrass.vector import VectorTopo >>> cens = VectorTopo(test_vector_name) - >>> cens.open(mode='r') + >>> cens.open(mode="r") >>> dblinks = DBlinks(cens.c_mapinfo) >>> dblinks DBlinks([Link(1, table_doctest_map, sqlite)]) @@ -943,14 +995,20 @@ def add(self, link): >>> from grass.pygrass.vector import VectorTopo >>> test_vect = VectorTopo(test_vector_name) - >>> test_vect.open(mode='r') + >>> test_vect.open(mode="r") >>> dblinks = DBlinks(test_vect.c_mapinfo) >>> dblinks DBlinks([Link(1, table_doctest_map, sqlite)]) - >>> link = Link(2, 'pg_link', test_vector_name, 'cat', - ... 'host=localhost dbname=grassdb', 'pg') # doctest: +SKIP - >>> dblinks.add(link) # doctest: +SKIP - >>> dblinks # doctest: +SKIP + >>> link = Link( + ... 2, + ... "pg_link", + ... test_vector_name, + ... "cat", + ... "host=localhost dbname=grassdb", + ... "pg", + ... ) # doctest: +SKIP + >>> dblinks.add(link) # doctest: +SKIP + >>> dblinks # doctest: +SKIP DBlinks([Link(1, table_doctest_map, sqlite)]) """ @@ -976,15 +1034,14 @@ def remove(self, key, force=False): >>> from grass.pygrass.vector import VectorTopo >>> test_vect = VectorTopo(test_vector_name) - >>> test_vect.open(mode='r') + >>> test_vect.open(mode="r") >>> dblinks = DBlinks(test_vect.c_mapinfo) >>> dblinks DBlinks([Link(1, table_doctest_map, sqlite)]) - >>> dblinks.remove('pg_link') # doctest: +SKIP + >>> dblinks.remove("pg_link") # doctest: +SKIP >>> dblinks # need to open vector map in write mode DBlinks([Link(1, table_doctest_map, sqlite)]) - """ if force: link = self.by_name(key) @@ -1005,16 +1062,17 @@ class Table: """ >>> import sqlite3 - >>> path = '$GISDBASE/$LOCATION_NAME/PERMANENT/sqlite/sqlite.db' - >>> tab_sqlite = Table(name=test_vector_name, - ... connection=sqlite3.connect(get_path(path))) + >>> path = "$GISDBASE/$LOCATION_NAME/PERMANENT/sqlite/sqlite.db" + >>> tab_sqlite = Table( + ... name=test_vector_name, connection=sqlite3.connect(get_path(path)) + ... ) >>> tab_sqlite.name 'table_doctest_map' - >>> import psycopg2 # doctest: +SKIP - >>> tab_pg = Table(test_vector_name, - ... psycopg2.connect('host=localhost dbname=grassdb', - ... 'pg')) # doctest: +SKIP - >>> tab_pg.columns # doctest: +ELLIPSIS +SKIP + >>> import psycopg2 # doctest: +SKIP + >>> tab_pg = Table( + ... test_vector_name, psycopg2.connect("host=localhost dbname=grassdb", "pg") + ... ) # doctest: +SKIP + >>> tab_pg.columns # doctest: +ELLIPSIS +SKIP Columns([('cat', 'int4'), ...]) """ @@ -1048,9 +1106,10 @@ def __repr__(self): """ >>> import sqlite3 - >>> path = '$GISDBASE/$LOCATION_NAME/PERMANENT/sqlite/sqlite.db' - >>> tab_sqlite = Table(name=test_vector_name, - ... connection=sqlite3.connect(get_path(path))) + >>> path = "$GISDBASE/$LOCATION_NAME/PERMANENT/sqlite/sqlite.db" + >>> tab_sqlite = Table( + ... name=test_vector_name, connection=sqlite3.connect(get_path(path)) + ... ) >>> tab_sqlite Table('table_doctest_map') @@ -1096,9 +1155,10 @@ def n_rows(self): """Return the number of rows >>> import sqlite3 - >>> path = '$GISDBASE/$LOCATION_NAME/$MAPSET/sqlite/sqlite.db' - >>> tab_sqlite = Table(name=test_vector_name, - ... connection=sqlite3.connect(get_path(path))) + >>> path = "$GISDBASE/$LOCATION_NAME/$MAPSET/sqlite/sqlite.db" + >>> tab_sqlite = Table( + ... name=test_vector_name, connection=sqlite3.connect(get_path(path)) + ... ) >>> tab_sqlite.n_rows() 3 """ @@ -1124,13 +1184,14 @@ def execute(self, sql_code=None, cursor=None, many=False, values=None): :type values: list of tuple >>> import sqlite3 - >>> path = '$GISDBASE/$LOCATION_NAME/$MAPSET/sqlite/sqlite.db' - >>> tab_sqlite = Table(name=test_vector_name, - ... connection=sqlite3.connect(get_path(path))) - >>> tab_sqlite.filters.select('cat', 'name').order_by('value') + >>> path = "$GISDBASE/$LOCATION_NAME/$MAPSET/sqlite/sqlite.db" + >>> tab_sqlite = Table( + ... name=test_vector_name, connection=sqlite3.connect(get_path(path)) + ... ) + >>> tab_sqlite.filters.select("cat", "name").order_by("value") Filters('SELECT cat, name FROM table_doctest_map ORDER BY value;') >>> cur = tab_sqlite.execute() - >>> cur.fetchone() #doctest: +ELLIPSIS +NORMALIZE_WHITESPACE + >>> cur.fetchone() # doctest: +ELLIPSIS +NORMALIZE_WHITESPACE (1, 'point') """ diff --git a/python/grass/script/db.py b/python/grass/script/db.py index 2aa2e983c78..abb7ad1764b 100644 --- a/python/grass/script/db.py +++ b/python/grass/script/db.py @@ -36,11 +36,11 @@ def db_describe(table, env=None, **args): """Return the list of columns for a database table (interface to `db.describe -c`). Example: - >>> run_command('g.copy', vector='firestations,myfirestations') + >>> run_command("g.copy", vector="firestations,myfirestations") 0 - >>> db_describe('myfirestations') # doctest: +ELLIPSIS + >>> db_describe("myfirestations") # doctest: +ELLIPSIS {'nrows': 71, 'cols': [['cat', 'INTEGER', '20'], ... 'ncols': 22} - >>> run_command('g.remove', flags='f', type='vector', name='myfirestations') + >>> run_command("g.remove", flags="f", type="vector", name="myfirestations") 0 :param str table: table name @@ -81,11 +81,11 @@ def db_table_exist(table, env=None, **args): If no driver or database are given, then default settings is used (check db_connection()). - >>> run_command('g.copy', vector='firestations,myfirestations') + >>> run_command("g.copy", vector="firestations,myfirestations") 0 - >>> db_table_exist('myfirestations') + >>> db_table_exist("myfirestations") True - >>> run_command('g.remove', flags='f', type='vector', name='myfirestations') + >>> run_command("g.remove", flags="f", type="vector", name="myfirestations") 0 :param str table: table name @@ -125,7 +125,7 @@ def db_connection(force=False, env=None): :param env: environment :return: parsed output of db.connect - """ + """ # noqa: E501 try: nuldev = open(os.devnull, "w") conn = parse_command("db.connect", flags="g", stderr=nuldev, env=env) @@ -148,16 +148,16 @@ def db_select(sql=None, filename=None, table=None, env=None, **args): Examples: - >>> run_command('g.copy', vector='firestations,myfirestations') + >>> run_command("g.copy", vector="firestations,myfirestations") 0 - >>> db_select(sql = 'SELECT cat,CITY FROM myfirestations WHERE cat < 4') + >>> db_select(sql="SELECT cat,CITY FROM myfirestations WHERE cat < 4") (('1', 'Morrisville'), ('2', 'Morrisville'), ('3', 'Apex')) Simplyfied usage (it performs SELECT * FROM myfirestations.) - >>> db_select(table = 'myfirestations') # doctest: +ELLIPSIS + >>> db_select(table="myfirestations") # doctest: +ELLIPSIS (('1', '24', 'Morrisville #3', ... 'HS2A', '1.37')) - >>> run_command('g.remove', flags='f', type='vector', name='myfirestations') + >>> run_command("g.remove", flags="f", type="vector", name="myfirestations") 0 :param str sql: SQL statement to perform (or None) @@ -176,7 +176,8 @@ def db_select(sql=None, filename=None, table=None, env=None, **args): else: fatal( _( - "Programmer error: '%(sql)s', '%(filename)s', or '%(table)s' must be provided" + "Programmer error: '%(sql)s', '%(filename)s', or '%(table)s' must be \ + provided" ) % {"sql": "sql", "filename": "filename", "table": "table"} ) @@ -203,12 +204,12 @@ def db_table_in_vector(table, mapset=".", env=None): name could be used also in other mapset by other vector. It returns None if no vectors are connected to the table. - >>> run_command('g.copy', vector='firestations,myfirestations') + >>> run_command("g.copy", vector="firestations,myfirestations") 0 - >>> db_table_in_vector('myfirestations') + >>> db_table_in_vector("myfirestations") ['myfirestations@user1'] - >>> db_table_in_vector('mfirestations') - >>> run_command('g.remove', flags='f', type='vector', name='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 diff --git a/python/grass/script/vector.py b/python/grass/script/vector.py index 4297fa0171f..131a872b1d4 100644 --- a/python/grass/script/vector.py +++ b/python/grass/script/vector.py @@ -35,7 +35,7 @@ def vector_db(map, env=None, **kwargs): """Return the database connection details for a vector map (interface to `v.db.connect -g`). Example: - >>> vector_db('geology') # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE + >>> vector_db("geology") # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE {1: {'layer': 1, ... 'table': 'geology'}} :param str map: vector map @@ -99,7 +99,7 @@ def vector_columns(map, layer=None, getDict=True, env=None, **kwargs): """Return a dictionary (or a list) of the columns for the database table connected to a vector map (interface to `v.info -c`). - >>> vector_columns('geology', getDict=True) # doctest: +NORMALIZE_WHITESPACE + >>> vector_columns("geology", getDict=True) # doctest: +NORMALIZE_WHITESPACE {'PERIMETER': {'index': 2, 'type': 'DOUBLE PRECISION'}, 'GEOL250_': {'index': 3, 'type': 'INTEGER'}, 'SHAPE_area': {'index': 6, 'type': 'DOUBLE PRECISION'}, 'onemap_pro': {'index': 1, 'type': 'DOUBLE @@ -107,7 +107,7 @@ def vector_columns(map, layer=None, getDict=True, env=None, **kwargs): 'cat': {'index': 0, 'type': 'INTEGER'}, 'GEOL250_ID': {'index': 4, 'type': 'INTEGER'}, 'GEO_NAME': {'index': 5, 'type': 'CHARACTER'}} - >>> vector_columns('geology', getDict=False) # doctest: +NORMALIZE_WHITESPACE + >>> vector_columns("geology", getDict=False) # doctest: +NORMALIZE_WHITESPACE ['cat', 'onemap_pro', 'PERIMETER', @@ -168,7 +168,7 @@ def vector_info_topo(map, layer=1, env=None): """Return information about a vector map (interface to `v.info -t`). Example: - >>> vector_info_topo('geology') # doctest: +NORMALIZE_WHITESPACE + >>> vector_info_topo("geology") # doctest: +NORMALIZE_WHITESPACE {'lines': 0, 'centroids': 1832, 'boundaries': 3649, 'points': 0, 'primitives': 5481, 'islands': 907, 'nodes': 2724, 'map3d': False, 'areas': 1832} @@ -191,7 +191,7 @@ def vector_info(map, layer=1, env=None): """Return information about a vector map (interface to `v.info`). Example: - >>> vector_info('geology') # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE + >>> vector_info("geology") # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE {'comment': '', 'projection': 'Lambert Conformal Conic' ... 'south': 10875.8272320917} :param str map: map name @@ -199,7 +199,7 @@ def vector_info(map, layer=1, env=None): :param env: environment :return: parsed vector info - """ + """ # noqa: E501 s = read_command("v.info", flags="get", layer=layer, map=map, env=env) @@ -234,11 +234,11 @@ def vector_db_select(map, layer=1, env=None, **kwargs): Function returns list of columns and dictionary of values ordered by key column value. Example: - >>> print vector_db_select('geology')['columns'] + >>> print(vector_db_select("geology")["columns"]) ['cat', 'onemap_pro', 'PERIMETER', 'GEOL250_', 'GEOL250_ID', 'GEO_NAME', 'SHAPE_area', 'SHAPE_len'] - >>> print vector_db_select('geology')['values'][3] + >>> print(vector_db_select("geology")["values"][3]) ['3', '579286.875', '3335.55835', '4', '3', 'Zml', '579286.829631', '3335.557182'] - >>> print vector_db_select('geology', columns = 'GEO_NAME')['values'][3] + >>> print(vector_db_select("geology", columns="GEO_NAME")["values"][3]) ['Zml'] :param str map: map name @@ -247,7 +247,7 @@ def vector_db_select(map, layer=1, env=None, **kwargs): :param env: environment :return: dictionary ('columns' and 'values') - """ + """ # noqa: E501 try: key = vector_db(map=map, env=env)[layer]["key"] except KeyError: diff --git a/python/grass/temporal/abstract_map_dataset.py b/python/grass/temporal/abstract_map_dataset.py index 7306133251b..70d325c87b4 100644 --- a/python/grass/temporal/abstract_map_dataset.py +++ b/python/grass/temporal/abstract_map_dataset.py @@ -177,8 +177,8 @@ def split_name(name, layer=None, mapset=None): layer exists :param mapset: The mapset in which the map is located - :return: tuple of three elements name, layer, mapset e(:layer)@mapset" while layer is - optional + :return: tuple of three elements name, layer, mapset e(:layer)@mapset" while + layer is optional """ # Check if the name includes any mapset @@ -223,7 +223,8 @@ def build_id_from_search_path(name, element): else: gs.fatal( _( - "Map <{map_name}> of element tpye '{element}' not found on search path" + "Map <{map_name}> of element tpye '{element}' not found on \ + search path" ).format(element=element, map_name=name) ) @@ -277,25 +278,25 @@ def print_info(self): """Print information about this object in human readable style""" if self.get_type() == "raster": - # 1 2 3 4 5 6 7 - # 0123456789012345678901234567890123456789012345678901234567890123456789012345678 + # 1 2 3 4 5 6 7 # noqa: E501 + # 0123456789012345678901234567890123456789012345678901234567890123456789012345678 # noqa: E501 print( - " +-------------------- Raster Dataset ----------------------------------------+" + " +-------------------- Raster Dataset ----------------------------------------+" # noqa: E501 ) if self.get_type() == "raster3d": - # 1 2 3 4 5 6 7 - # 0123456789012345678901234567890123456789012345678901234567890123456789012345678 + # 1 2 3 4 5 6 7 # noqa: E501 + # 0123456789012345678901234567890123456789012345678901234567890123456789012345678 # noqa: E501 print( - " +-------------------- 3D Raster Dataset -------------------------------------+" + " +-------------------- 3D Raster Dataset -------------------------------------+" # noqa: E501 ) if self.get_type() == "vector": - # 1 2 3 4 5 6 7 - # 0123456789012345678901234567890123456789012345678901234567890123456789012345678 + # 1 2 3 4 5 6 7 # noqa: E501 + # 0123456789012345678901234567890123456789012345678901234567890123456789012345678 # noqa: E501 print( - " +-------------------- Vector Dataset ----------------------------------------+" + " +-------------------- Vector Dataset ----------------------------------------+" # noqa: E501 ) print( - " | |" + " | |" # noqa: E501 ) self.base.print_info() self.temporal_extent.print_info() @@ -318,7 +319,7 @@ def print_info(self): count += 1 print(" | Registered datasets ........ " + string) print( - " +----------------------------------------------------------------------------+" + " +----------------------------------------------------------------------------+" # noqa: E501 ) def print_shell_info(self): @@ -684,24 +685,32 @@ def set_temporal_extent(self, extent): >>> import datetime >>> import grass.temporal as tgis - >>> map = tgis.RasterDataset(None) - >>> temp_ext = tgis.RasterRelativeTime(start_time=1, end_time=2, unit="years") + >>> map = tgis.RasterDataset(None) + >>> temp_ext = tgis.RasterRelativeTime( + ... start_time=1, end_time=2, unit="years" + ... ) >>> map.set_temporal_extent(temp_ext) >>> print(map.get_temporal_extent_as_tuple()) (1, 2) - >>> map = tgis.VectorDataset(None) - >>> temp_ext = tgis.VectorAbsoluteTime(start_time=datetime.datetime(2000, 1, 1), - ... end_time=datetime.datetime(2001, 1, 1)) + >>> map = tgis.VectorDataset(None) + >>> temp_ext = tgis.VectorAbsoluteTime( + ... start_time=datetime.datetime(2000, 1, 1), + ... end_time=datetime.datetime(2001, 1, 1), + ... ) >>> map.set_temporal_extent(temp_ext) >>> print(map.get_temporal_extent_as_tuple()) (datetime.datetime(2000, 1, 1, 0, 0), datetime.datetime(2001, 1, 1, 0, 0)) >>> map1 = tgis.VectorDataset("A@P") - >>> check = map1.set_absolute_time(datetime.datetime(2000,5,5), datetime.datetime(2005,6,6)) + >>> check = map1.set_absolute_time( + ... datetime.datetime(2000, 5, 5), datetime.datetime(2005, 6, 6) + ... ) >>> print(map1.get_temporal_extent_as_tuple()) (datetime.datetime(2000, 5, 5, 0, 0), datetime.datetime(2005, 6, 6, 0, 0)) >>> map2 = tgis.RasterDataset("B@P") - >>> check = map2.set_absolute_time(datetime.datetime(1990,1,1), datetime.datetime(1999,8,1)) + >>> check = map2.set_absolute_time( + ... datetime.datetime(1990, 1, 1), datetime.datetime(1999, 8, 1) + ... ) >>> print(map2.get_temporal_extent_as_tuple()) (datetime.datetime(1990, 1, 1, 0, 0), datetime.datetime(1999, 8, 1, 0, 0)) >>> map2.set_temporal_extent(map1.get_temporal_extent()) @@ -744,15 +753,17 @@ def temporal_buffer(self, increment, update=False, dbif=None): >>> import grass.temporal as tgis >>> maps = [] >>> for i in range(5): - ... map = tgis.RasterDataset(None) - ... if i%2 == 0: - ... check = map.set_relative_time(i, i + 1, 'years') - ... else: - ... check = map.set_relative_time(i, None, 'years') - ... map.temporal_buffer(3) - ... maps.append(map) + ... map = tgis.RasterDataset(None) + ... if i % 2 == 0: + ... check = map.set_relative_time(i, i + 1, "years") + ... else: + ... check = map.set_relative_time(i, None, "years") + ... map.temporal_buffer(3) + ... maps.append(map) + ... >>> for map in maps: - ... map.temporal_extent.print_info() + ... map.temporal_extent.print_info() + ... +-------------------- Relative time -----------------------------------------+ | Start time:................. -3 | End time:................... 4 @@ -774,16 +785,20 @@ def temporal_buffer(self, increment, update=False, dbif=None): | End time:................... 8 | Relative time unit:......... years >>> maps = [] - >>> for i in range(1,5): - ... map = tgis.RasterDataset(None) - ... if i%2 == 0: - ... check = map.set_absolute_time(datetime(2001,i,1), datetime(2001, i + 1, 1)) - ... else: - ... check = map.set_absolute_time(datetime(2001,i,1), None) - ... map.temporal_buffer("7 days") - ... maps.append(map) + >>> for i in range(1, 5): + ... map = tgis.RasterDataset(None) + ... if i % 2 == 0: + ... check = map.set_absolute_time( + ... datetime(2001, i, 1), datetime(2001, i + 1, 1) + ... ) + ... else: + ... check = map.set_absolute_time(datetime(2001, i, 1), None) + ... map.temporal_buffer("7 days") + ... maps.append(map) + ... >>> for map in maps: - ... map.temporal_extent.print_info() + ... map.temporal_extent.print_info() + ... +-------------------- Absolute time -----------------------------------------+ | Start time:................. 2000-12-25 00:00:00 | End time:................... 2001-01-08 00:00:00 @@ -797,7 +812,7 @@ def temporal_buffer(self, increment, update=False, dbif=None): | Start time:................. 2001-03-25 00:00:00 | End time:................... 2001-05-08 00:00:00 - """ + """ # noqa: E501 if self.is_time_absolute(): start, end = self.get_absolute_time() @@ -855,8 +870,10 @@ def set_spatial_extent(self, spatial_extent): >>> import datetime >>> import grass.temporal as tgis - >>> map = tgis.RasterDataset(None) - >>> spat_ext = tgis.SpatialExtent(north=10, south=-10, east=20, west=-20, top=5, bottom=-5) + >>> map = tgis.RasterDataset(None) + >>> spat_ext = tgis.SpatialExtent( + ... north=10, south=-10, east=20, west=-20, top=5, bottom=-5 + ... ) >>> map.set_spatial_extent(spat_ext) >>> print(map.get_spatial_extent_as_tuple()) (10.0, -10.0, 20.0, -20.0, 5.0, -5.0) @@ -877,7 +894,9 @@ def spatial_buffer(self, size, update=False, dbif=None): >>> import grass.temporal as tgis >>> map = tgis.RasterDataset(None) - >>> spat_ext = tgis.SpatialExtent(north=10, south=-10, east=20, west=-20, top=5, bottom=-5) + >>> spat_ext = tgis.SpatialExtent( + ... north=10, south=-10, east=20, west=-20, top=5, bottom=-5 + ... ) >>> map.set_spatial_extent(spat_ext) >>> map.spatial_buffer(10) >>> print(map.get_spatial_extent_as_tuple()) @@ -907,7 +926,9 @@ def spatial_buffer_2d(self, size, update=False, dbif=None): >>> import grass.temporal as tgis >>> map = tgis.RasterDataset(None) - >>> spat_ext = tgis.SpatialExtent(north=10, south=-10, east=20, west=-20, top=5, bottom=-5) + >>> spat_ext = tgis.SpatialExtent( + ... north=10, south=-10, east=20, west=-20, top=5, bottom=-5 + ... ) >>> map.set_spatial_extent(spat_ext) >>> map.spatial_buffer_2d(10) >>> print(map.get_spatial_extent_as_tuple()) diff --git a/python/grass/temporal/abstract_space_time_dataset.py b/python/grass/temporal/abstract_space_time_dataset.py index b4812361174..38d154c9f11 100644 --- a/python/grass/temporal/abstract_space_time_dataset.py +++ b/python/grass/temporal/abstract_space_time_dataset.py @@ -143,32 +143,32 @@ def print_info(self): """Print information about this class in human readable style""" if self.get_type() == "strds": - # 1 2 3 4 5 6 7 - # 0123456789012345678901234567890123456789012345678901234567890123456789012345678 + # 1 2 3 4 5 6 7 # noqa: E501 + # 0123456789012345678901234567890123456789012345678901234567890123456789012345678 # noqa: E501 print( - " +-------------------- Space Time Raster Dataset -----------------------------+" + " +-------------------- Space Time Raster Dataset -----------------------------+" # noqa: E501 ) if self.get_type() == "str3ds": - # 1 2 3 4 5 6 7 - # 0123456789012345678901234567890123456789012345678901234567890123456789012345678 + # 1 2 3 4 5 6 7 # noqa: E501 + # 0123456789012345678901234567890123456789012345678901234567890123456789012345678 # noqa: E501 print( - " +-------------------- Space Time 3D Raster Dataset --------------------------+" + " +-------------------- Space Time 3D Raster Dataset --------------------------+" # noqa: E501 ) if self.get_type() == "stvds": - # 1 2 3 4 5 6 7 - # 0123456789012345678901234567890123456789012345678901234567890123456789012345678 + # 1 2 3 4 5 6 7 # noqa: E501 + # 0123456789012345678901234567890123456789012345678901234567890123456789012345678 # noqa: E501 print( - " +-------------------- Space Time Vector Dataset -----------------------------+" + " +-------------------- Space Time Vector Dataset -----------------------------+" # noqa: E501 ) print( - " | |" + " | |" # noqa: E501 ) self.base.print_info() self.temporal_extent.print_info() self.spatial_extent.print_info() self.metadata.print_info() print( - " +----------------------------------------------------------------------------+" + " +----------------------------------------------------------------------------+" # noqa: E501 ) def print_shell_info(self): @@ -396,7 +396,8 @@ def insert(self, dbif=None, execute=True): # Create table name stds_register_table = self.create_map_register_name() # Assure that the table and index do not exist - # dbif.execute_transaction("DROP INDEX IF EXISTS %s; DROP TABLE IF EXISTS %s;"%(stds_register_table + "_index", stds_register_table)) + # dbif.execute_transaction("DROP INDEX IF EXISTS %s; DROP TABLE IF EXISTS + # %s;"%(stds_register_table + "_index", stds_register_table)) # Read the SQL template sql = open( @@ -454,7 +455,8 @@ def count_temporal_types(self, maps=None, dbif=None): - interval -> start and end time - invalid -> No valid time point or interval found - :param maps: A sorted (start_time) list of AbstractDataset objects or database rows + :param maps: A sorted (start_time) list of AbstractDataset objects or database + rows :param dbif: The database interface to be used """ @@ -636,8 +638,9 @@ def sample_by_dataset(self, stds, method=None, spatial=False, dbif=None): .. code-block:: python - list = self.sample_by_dataset(stds=sampler, method=[ - "during","overlap","contains","equal"]) + list = self.sample_by_dataset( + stds=sampler, method=["during", "overlap", "contains", "equal"] + ) for entry in list: granule = entry["granule"] maplist = entry["samples"] @@ -851,8 +854,9 @@ def sample_by_dataset_sql(self, stds, method=None, spatial=False, dbif=None): .. code-block:: python - list = self.sample_by_dataset(stds=sampler, method=[ - "during","overlap","contain","equal"]) + list = self.sample_by_dataset( + stds=sampler, method=["during", "overlap", "contain", "equal"] + ) for entry in list: granule = entry["granule"] maplist = entry["samples"] @@ -1200,12 +1204,19 @@ def resample_maplist_by_granularity(maps, start, end, gran): >>> import grass.temporal as tgis >>> maps = [] >>> for i in range(3): - ... map = tgis.RasterDataset("map%i@PERMANENT"%i) + ... map = tgis.RasterDataset("map%i@PERMANENT" % i) ... check = map.set_relative_time(i + 2, i + 3, "days") ... maps.append(map) - >>> grans = tgis.AbstractSpaceTimeDataset.resample_maplist_by_granularity(maps,0,8,1) + ... + >>> grans = tgis.AbstractSpaceTimeDataset.resample_maplist_by_granularity( + ... maps, 0, 8, 1 + ... ) >>> for map_list in grans: - ... print(map_list[0].get_id(), map_list[0].get_temporal_extent_as_tuple()) + ... print( + ... map_list[0].get_id(), + ... map_list[0].get_temporal_extent_as_tuple(), + ... ) + ... None (0, 1) None (1, 2) map0@PERMANENT (2, 3) @@ -1222,9 +1233,15 @@ def resample_maplist_by_granularity(maps, start, end, gran): >>> map2 = tgis.RasterDataset("map2@PERMANENT") >>> check = map2.set_relative_time(7, 13, "days") >>> maps.append(map2) - >>> grans = tgis.AbstractSpaceTimeDataset.resample_maplist_by_granularity(maps,0,16,2) + >>> grans = tgis.AbstractSpaceTimeDataset.resample_maplist_by_granularity( + ... maps, 0, 16, 2 + ... ) >>> for map_list in grans: - ... print(map_list[0].get_id(), map_list[0].get_temporal_extent_as_tuple()) + ... print( + ... map_list[0].get_id(), + ... map_list[0].get_temporal_extent_as_tuple(), + ... ) + ... None (0, 2) map1@PERMANENT (2, 4) map1@PERMANENT (4, 6) @@ -1241,9 +1258,15 @@ def resample_maplist_by_granularity(maps, start, end, gran): >>> map2 = tgis.RasterDataset("map2@PERMANENT") >>> check = map2.set_relative_time(7, None, "days") >>> maps.append(map2) - >>> grans = tgis.AbstractSpaceTimeDataset.resample_maplist_by_granularity(maps,0,16,2) + >>> grans = tgis.AbstractSpaceTimeDataset.resample_maplist_by_granularity( + ... maps, 0, 16, 2 + ... ) >>> for map_list in grans: - ... print(map_list[0].get_id(), map_list[0].get_temporal_extent_as_tuple()) + ... print( + ... map_list[0].get_id(), + ... map_list[0].get_temporal_extent_as_tuple(), + ... ) + ... None (0, 2) map1@PERMANENT (2, 4) None (4, 6) @@ -1255,14 +1278,24 @@ def resample_maplist_by_granularity(maps, start, end, gran): >>> maps = [] >>> map1 = tgis.RasterDataset("map1@PERMANENT") - >>> check = map1.set_absolute_time(datetime(2000, 4,1), datetime(2000, 6, 1)) + >>> check = map1.set_absolute_time( + ... datetime(2000, 4, 1), datetime(2000, 6, 1) + ... ) >>> maps.append(map1) >>> map2 = tgis.RasterDataset("map2@PERMANENT") - >>> check = map2.set_absolute_time(datetime(2000, 8,1), datetime(2000, 12, 1)) + >>> check = map2.set_absolute_time( + ... datetime(2000, 8, 1), datetime(2000, 12, 1) + ... ) >>> maps.append(map2) - >>> grans = tgis.AbstractSpaceTimeDataset.resample_maplist_by_granularity(maps,datetime(2000,1,1),datetime(2001,4,1),"1 month") + >>> grans = tgis.AbstractSpaceTimeDataset.resample_maplist_by_granularity( + ... maps, datetime(2000, 1, 1), datetime(2001, 4, 1), "1 month" + ... ) >>> for map_list in grans: - ... print(map_list[0].get_id(), map_list[0].get_temporal_extent_as_tuple()) + ... print( + ... map_list[0].get_id(), + ... map_list[0].get_temporal_extent_as_tuple(), + ... ) + ... None (datetime.datetime(2000, 1, 1, 0, 0), datetime.datetime(2000, 2, 1, 0, 0)) None (datetime.datetime(2000, 2, 1, 0, 0), datetime.datetime(2000, 3, 1, 0, 0)) None (datetime.datetime(2000, 3, 1, 0, 0), datetime.datetime(2000, 4, 1, 0, 0)) @@ -1279,7 +1312,7 @@ def resample_maplist_by_granularity(maps, start, end, gran): None (datetime.datetime(2001, 2, 1, 0, 0), datetime.datetime(2001, 3, 1, 0, 0)) None (datetime.datetime(2001, 3, 1, 0, 0), datetime.datetime(2001, 4, 1, 0, 0)) - """ + """ # noqa: E501 if not maps: return None @@ -1632,7 +1665,8 @@ def leading_zero(value): if shortcut_identifier: where += ( "{br} LIKE '{si}\\_%' {esc} OR {br} LIKE '%\\_{si}' {esc} OR " - "{br} LIKE '{orig}\\_%' {esc} OR {br} LIKE '%\\_{orig}' {esc}".format( + "{br} LIKE '{orig}\\_%' {esc} OR " + "{br} LIKE '%\\_{orig}' {esc}".format( br="semantic_label", si=shortcut_identifier, orig=self.semantic_label.upper(), @@ -1675,7 +1709,9 @@ def _update_where_statement_by_spatial_extent( >>> import grass.script as gs >>> where = None >>> spatial_extent = gs.parse_command("g.region", flags="ug3") - >>> _update_where_statement_by_spatial_extent(where, spatial_extent, "overlaps") + >>> _update_where_statement_by_spatial_extent( + ... where, spatial_extent, "overlaps" + ... ) ((north > 0 AND south < 1 AND east > 0 AND west < 1)) """ @@ -1691,7 +1727,8 @@ def _update_where_statement_by_spatial_extent( self.msgr.error( _( "Invalid spatial relation <{}> requested." - "Only values 'overlaps', 'is_contained', and 'contains' are allowed." + "Only values 'overlaps', 'is_contained', and 'contains' are \ + allowed." ).format(spatial_relation) ) raise @@ -1858,14 +1895,16 @@ def shift_map_list(maps, gran): >>> import grass.temporal as tgis >>> maps = [] >>> for i in range(5): - ... map = tgis.RasterDataset(None) - ... if i%2 == 0: - ... check = map.set_relative_time(i, i + 1, 'years') - ... else: - ... check = map.set_relative_time(i, None, 'years') - ... maps.append(map) + ... map = tgis.RasterDataset(None) + ... if i % 2 == 0: + ... check = map.set_relative_time(i, i + 1, "years") + ... else: + ... check = map.set_relative_time(i, None, "years") + ... maps.append(map) + ... >>> for map in maps: - ... map.temporal_extent.print_info() + ... map.temporal_extent.print_info() + ... +-------------------- Relative time -----------------------------------------+ | Start time:................. 0 | End time:................... 1 @@ -1888,7 +1927,8 @@ def shift_map_list(maps, gran): | Relative time unit:......... years >>> maps = tgis.AbstractSpaceTimeDataset.shift_map_list(maps, 5) >>> for map in maps: - ... map.temporal_extent.print_info() + ... map.temporal_extent.print_info() + ... +-------------------- Relative time -----------------------------------------+ | Start time:................. 5 | End time:................... 6 @@ -1910,7 +1950,7 @@ def shift_map_list(maps, gran): | End time:................... 10 | Relative time unit:......... years - """ + """ # noqa: E501 if maps is None: return None @@ -2010,14 +2050,16 @@ def snap_map_list(maps): >>> import grass.temporal as tgis >>> maps = [] >>> for i in range(5): - ... map = tgis.RasterDataset(None) - ... if i%2 == 0: - ... check = map.set_relative_time(i, i + 1, 'years') - ... else: - ... check = map.set_relative_time(i, None, 'years') - ... maps.append(map) + ... map = tgis.RasterDataset(None) + ... if i % 2 == 0: + ... check = map.set_relative_time(i, i + 1, "years") + ... else: + ... check = map.set_relative_time(i, None, "years") + ... maps.append(map) + ... >>> for map in maps: - ... map.temporal_extent.print_info() + ... map.temporal_extent.print_info() + ... +-------------------- Relative time -----------------------------------------+ | Start time:................. 0 | End time:................... 1 @@ -2040,7 +2082,8 @@ def snap_map_list(maps): | Relative time unit:......... years >>> maps = tgis.AbstractSpaceTimeDataset.snap_map_list(maps) >>> for map in maps: - ... map.temporal_extent.print_info() + ... map.temporal_extent.print_info() + ... +-------------------- Relative time -----------------------------------------+ | Start time:................. 0 | End time:................... 1 @@ -2062,7 +2105,7 @@ def snap_map_list(maps): | End time:................... 5 | Relative time unit:......... years - """ + """ # noqa: E501 if maps is None or len(maps) == 0: return None diff --git a/python/grass/temporal/aggregation.py b/python/grass/temporal/aggregation.py index 22b2d772afb..223dcfa29f5 100644 --- a/python/grass/temporal/aggregation.py +++ b/python/grass/temporal/aggregation.py @@ -7,7 +7,9 @@ import grass.temporal as tgis - tgis.aggregate_raster_maps(dataset, mapset, inputs, base, start, end, count, method, register_null, dbif) + tgis.aggregate_raster_maps( + dataset, mapset, inputs, base, start, end, count, method, register_null, dbif + ) (C) 2012-2013 by the GRASS Development Team This program is free software under the GNU General Public diff --git a/python/grass/temporal/base.py b/python/grass/temporal/base.py index 84d247449ff..d11f8a081ac 100644 --- a/python/grass/temporal/base.py +++ b/python/grass/temporal/base.py @@ -56,8 +56,8 @@ def serialize(self, type, table, where=None): >>> t.D["name"] = "soil" >>> t.D["mapset"] = "PERMANENT" >>> t.D["creator"] = "soeren" - >>> t.D["creation_time"] = datetime(2001,1,1) - >>> t.D["modification_time"] = datetime(2001,1,1) + >>> t.D["creation_time"] = datetime(2001, 1, 1) + >>> t.D["modification_time"] = datetime(2001, 1, 1) >>> t.serialize(type="SELECT", table="raster_base") ('SELECT name , creator , creation_time , modification_time , mapset , id FROM raster_base ;\\n', ()) >>> t.serialize(type="INSERT", table="raster_base") @@ -72,7 +72,7 @@ def serialize(self, type, table, where=None): :param where: The optional where statement :return: a tuple containing the SQL string and the arguments - """ + """ # noqa: E501 sql = "" args = [] @@ -219,7 +219,7 @@ class SQLDatabaseInterface(DictSQLSerializer): >>> t.D["name"] = "soil" >>> t.D["mapset"] = "PERMANENT" >>> t.D["creator"] = "soeren" - >>> t.D["creation_time"] = datetime(2001,1,1) + >>> t.D["creation_time"] = datetime(2001, 1, 1) >>> t.get_delete_statement() "DELETE FROM raster WHERE id = 'soil@PERMANENT';\\n" >>> t.get_is_in_db_statement() @@ -241,7 +241,7 @@ class SQLDatabaseInterface(DictSQLSerializer): >>> t.get_update_all_statement_mogrified() "UPDATE raster SET creation_time = '2001-01-01 00:00:00' ,mapset = 'PERMANENT' ,name = 'soil' ,creator = 'soeren' WHERE id = 'soil@PERMANENT';\\n" - """ + """ # noqa: E501 def __init__(self, table=None, ident=None): """Constructor of this class @@ -591,7 +591,13 @@ class DatasetBase(SQLDatabaseInterface): .. code-block:: python >>> init() - >>> t = DatasetBase("raster", "soil@PERMANENT", creator="soeren", ctime=datetime(2001,1,1), ttype="absolute") + >>> t = DatasetBase( + ... "raster", + ... "soil@PERMANENT", + ... creator="soeren", + ... ctime=datetime(2001, 1, 1), + ... ttype="absolute", + ... ) >>> t.id 'soil@PERMANENT' >>> t.name @@ -830,7 +836,7 @@ def print_info(self): """Print information about this class in human readable style""" # 0123456789012345678901234567890 print( - " +-------------------- Basic information -------------------------------------+" + " +-------------------- Basic information -------------------------------------+" # noqa: E501 ) print(" | Id: ........................ " + str(self.get_id())) print(" | Name: ...................... " + str(self.get_name())) @@ -955,7 +961,15 @@ class STDSBase(DatasetBase): .. code-block:: python >>> init() - >>> t = STDSBase("stds", "soil@PERMANENT", semantic_type="average", creator="soeren", ctime=datetime(2001,1,1), ttype="absolute", mtime=datetime(2001,1,1)) + >>> t = STDSBase( + ... "stds", + ... "soil@PERMANENT", + ... semantic_type="average", + ... creator="soeren", + ... ctime=datetime(2001, 1, 1), + ... ttype="absolute", + ... mtime=datetime(2001, 1, 1), + ... ) >>> t.semantic_type 'average' >>> t.print_info() diff --git a/python/grass/temporal/c_libraries_interface.py b/python/grass/temporal/c_libraries_interface.py index 646ccfdd492..ab564df2312 100644 --- a/python/grass/temporal/c_libraries_interface.py +++ b/python/grass/temporal/c_libraries_interface.py @@ -1297,21 +1297,54 @@ class CLibrariesInterface(RPCServerBase): >>> import grass.script as gscript >>> import grass.temporal as tgis >>> gscript.use_temp_region() - >>> gscript.run_command("g.region", n=80.0, s=0.0, e=120.0, w=0.0, - ... t=1.0, b=0.0, res=10.0, res3=10.0) + >>> gscript.run_command( + ... "g.region", + ... n=80.0, + ... s=0.0, + ... e=120.0, + ... w=0.0, + ... t=1.0, + ... b=0.0, + ... res=10.0, + ... res3=10.0, + ... ) 0 >>> tgis.init() - >>> gscript.run_command("r.mapcalc", expression="test = 1", overwrite=True, quiet=True) + >>> gscript.run_command( + ... "r.mapcalc", expression="test = 1", overwrite=True, quiet=True + ... ) 0 - >>> gscript.run_command("r3.mapcalc", expression="test = 1", overwrite=True, quiet=True) + >>> gscript.run_command( + ... "r3.mapcalc", expression="test = 1", overwrite=True, quiet=True + ... ) 0 - >>> gscript.run_command("v.random", output="test", n=10, overwrite=True, quiet=True) + >>> gscript.run_command( + ... "v.random", output="test", n=10, overwrite=True, quiet=True + ... ) 0 - >>> gscript.run_command("r.timestamp", map="test", date='12 Mar 1995 10:34:40', overwrite=True, quiet=True) + >>> gscript.run_command( + ... "r.timestamp", + ... map="test", + ... date="12 Mar 1995 10:34:40", + ... overwrite=True, + ... quiet=True, + ... ) 0 - >>> gscript.run_command("r3.timestamp", map="test", date='12 Mar 1995 10:34:40', overwrite=True, quiet=True) + >>> gscript.run_command( + ... "r3.timestamp", + ... map="test", + ... date="12 Mar 1995 10:34:40", + ... overwrite=True, + ... quiet=True, + ... ) 0 - >>> gscript.run_command("v.timestamp", map="test", date='12 Mar 1995 10:34:40', overwrite=True, quiet=True) + >>> gscript.run_command( + ... "v.timestamp", + ... map="test", + ... date="12 Mar 1995 10:34:40", + ... overwrite=True, + ... quiet=True, + ... ) 0 # Check mapsets @@ -1323,13 +1356,13 @@ class CLibrariesInterface(RPCServerBase): # Raster map >>> ciface = tgis.CLibrariesInterface() >>> check = ciface.raster_map_exists("test", tgis.get_current_mapset()) - >>> print check + >>> print(check) True >>> ciface.read_raster_info("test", tgis.get_current_mapset()) {'rows': 12, 'north': 80.0, 'min': 1, 'datatype': 'CELL', 'max': 1, 'ewres': 10.0, 'cols': 8, 'west': 0.0, 'east': 120.0, 'nsres': 10.0, 'south': 0.0} >>> info = ciface.read_raster_full_info("test", tgis.get_current_mapset()) - >>> info # doctest: +ELLIPSIS +NORMALIZE_WHITESPACE + >>> info # doctest: +ELLIPSIS +NORMALIZE_WHITESPACE {u'tbres': 1.0, ... 'keyword': 'generated by r.mapcalc', u'bottom': 0.0, 'end_time': None, 'title': 'test', u'south': 0.0} @@ -1338,18 +1371,21 @@ class CLibrariesInterface(RPCServerBase): >>> info["end_time"] >>> check = ciface.has_raster_timestamp("test", tgis.get_current_mapset()) - >>> print check + >>> print(check) True >>> if check: ... res = ciface.read_raster_timestamp("test", tgis.get_current_mapset()) ... if res[0]: - ... print str(res[1][0]), str(res[1][0]) + ... print(str(res[1][0]), str(res[1][0])) ... ciface.remove_raster_timestamp("test", tgis.get_current_mapset()) + ... 1995-03-12 10:34:40 1995-03-12 10:34:40 1 >>> ciface.has_raster_timestamp("test", tgis.get_current_mapset()) False - >>> ciface.write_raster_timestamp("test", tgis.get_current_mapset(), "13 Jan 1999 14:30:05") + >>> ciface.write_raster_timestamp( + ... "test", tgis.get_current_mapset(), "13 Jan 1999 14:30:05" + ... ) 1 >>> ciface.has_raster_timestamp("test", tgis.get_current_mapset()) True @@ -1357,23 +1393,26 @@ class CLibrariesInterface(RPCServerBase): # 3D raster map >>> check = ciface.raster3d_map_exists("test", tgis.get_current_mapset()) - >>> print check + >>> print(check) True >>> ciface.read_raster3d_info("test", tgis.get_current_mapset()) {'tbres': 1.0, 'rows': 12, 'north': 80.0, 'bottom': 0.0, 'datatype': 'DCELL', 'max': 1.0, 'top': 1.0, 'min': 1.0, 'cols': 8, 'depths': 1, 'west': 0.0, 'ewres': 10.0, 'east': 120.0, 'nsres': 10.0, 'south': 0.0} >>> check = ciface.has_raster3d_timestamp("test", tgis.get_current_mapset()) - >>> print check + >>> print(check) True >>> if check: ... res = ciface.read_raster3d_timestamp("test", tgis.get_current_mapset()) ... if res[0]: - ... print str(res[1][0]), str(res[1][0]) + ... print(str(res[1][0]), str(res[1][0])) ... ciface.remove_raster3d_timestamp("test", tgis.get_current_mapset()) + ... 1995-03-12 10:34:40 1995-03-12 10:34:40 1 >>> ciface.has_raster3d_timestamp("test", tgis.get_current_mapset()) False - >>> ciface.write_raster3d_timestamp("test", tgis.get_current_mapset(), "13 Jan 1999 14:30:05") + >>> ciface.write_raster3d_timestamp( + ... "test", tgis.get_current_mapset(), "13 Jan 1999 14:30:05" + ... ) 1 >>> ciface.has_raster3d_timestamp("test", tgis.get_current_mapset()) True @@ -1381,42 +1420,45 @@ class CLibrariesInterface(RPCServerBase): # Vector map >>> check = ciface.vector_map_exists("test", tgis.get_current_mapset()) - >>> print check + >>> print(check) True >>> kvp = ciface.read_vector_info("test", tgis.get_current_mapset()) - >>> kvp['points'] + >>> kvp["points"] 10 >>> kvp = ciface.read_vector_full_info("test", tgis.get_current_mapset()) - >>> print kvp['points'] + >>> print(kvp["points"]) 10 - >>> kvp['point'] + >>> kvp["point"] 10 - >>> kvp['area'] + >>> kvp["area"] 0 - >>> kvp['lines'] + >>> kvp["lines"] 0 - >>> kvp['line'] + >>> kvp["line"] 0 - >>> 'columns' in kvp + >>> "columns" in kvp False >>> kvp["start_time"] datetime.datetime(1995, 3, 12, 10, 34, 40) >>> kvp["end_time"] >>> check = ciface.has_vector_timestamp("test", tgis.get_current_mapset(), None) - >>> print check + >>> print(check) True >>> if check: ... res = ciface.read_vector_timestamp("test", tgis.get_current_mapset()) ... if res[0]: - ... print str(res[1][0]), str(res[1][0]) + ... print(str(res[1][0]), str(res[1][0])) ... ciface.remove_vector_timestamp("test", tgis.get_current_mapset()) + ... 1995-03-12 10:34:40 1995-03-12 10:34:40 1 >>> ciface.has_vector_timestamp("test", tgis.get_current_mapset()) False - >>> ciface.write_vector_timestamp("test", tgis.get_current_mapset(), "13 Jan 1999 14:30:05") + >>> ciface.write_vector_timestamp( + ... "test", tgis.get_current_mapset(), "13 Jan 1999 14:30:05" + ... ) 1 >>> ciface.has_vector_timestamp("test", tgis.get_current_mapset()) True @@ -1430,22 +1472,22 @@ class CLibrariesInterface(RPCServerBase): >>> location = ciface.get_location() >>> gisdbase = ciface.get_gisdbase() - >>> ciface.fatal_error() # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE + >>> ciface.fatal_error() # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE Traceback (most recent call last): raise FatalError("Exception raised: " + str(e) + " Message: " + message) FatalError: Exception raised: ... - >>> ciface.fatal_error() # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE + >>> ciface.fatal_error() # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE Traceback (most recent call last): raise FatalError("Exception raised: " + str(e) + " Message: " + message) FatalError: Exception raised: ... - >>> ciface.fatal_error() # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE + >>> ciface.fatal_error() # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE Traceback (most recent call last): raise FatalError("Exception raised: " + str(e) + " Message: " + message) FatalError: Exception raised: ... - >>> ciface.fatal_error() # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE + >>> ciface.fatal_error() # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE Traceback (most recent call last): raise FatalError("Exception raised: " + str(e) + " Message: " + message) FatalError: Exception raised: ... @@ -1454,7 +1496,7 @@ class CLibrariesInterface(RPCServerBase): >>> gscript.del_temp_region() - """ + """ # noqa: E501 def __init__(self): RPCServerBase.__init__(self) diff --git a/python/grass/temporal/core.py b/python/grass/temporal/core.py index 56d3b4cb77e..68db2716ae5 100644 --- a/python/grass/temporal/core.py +++ b/python/grass/temporal/core.py @@ -15,8 +15,9 @@ >>> # Execute a SQL statement >>> dbif.execute_transaction("SELECT datetime(0, 'unixepoch', 'localtime');") >>> # Mogrify an SQL statement - >>> dbif.mogrify_sql_statement(["SELECT name from raster_base where name = ?", - ... ("precipitation",)]) + >>> dbif.mogrify_sql_statement( + ... ["SELECT name from raster_base where name = ?", ("precipitation",)] + ... ) "SELECT name from raster_base where name = 'precipitation'" >>> dbif.close() @@ -490,7 +491,8 @@ def get_available_temporal_mapsets(): ) if driver and database: # Check if the temporal sqlite database exists - # We need to set non-existing databases in case the mapset is the current mapset + # We need to set non-existing databases in case the mapset is the current + # mapset # to create it if ( driver == "sqlite" and os.path.exists(database) @@ -1394,8 +1396,14 @@ def mogrify_sql_statement(self, content): >>> init() >>> dbif = SQLDatabaseInterfaceConnection() - >>> dbif.mogrify_sql_statement(["SELECT ctime FROM raster_base WHERE id = ?", - ... ["soil@PERMANENT",]]) + >>> dbif.mogrify_sql_statement( + ... [ + ... "SELECT ctime FROM raster_base WHERE id = ?", + ... [ + ... "soil@PERMANENT", + ... ], + ... ] + ... ) "SELECT ctime FROM raster_base WHERE id = 'soil@PERMANENT'" """ @@ -1602,8 +1610,9 @@ def init_dbif(dbif): dbif, connection_state_changed = tgis.init_dbif(None) - sql = dbif.mogrify_sql_statement(["SELECT * FROM raster_base WHERE ? = ?"], - ["id", "soil@PERMANENT"]) + sql = dbif.mogrify_sql_statement( + ["SELECT * FROM raster_base WHERE ? = ?"], ["id", "soil@PERMANENT"] + ) dbif.execute_transaction(sql) if connection_state_changed: diff --git a/python/grass/temporal/datetime_math.py b/python/grass/temporal/datetime_math.py index 3cd30120788..29bcc8907de 100644 --- a/python/grass/temporal/datetime_math.py +++ b/python/grass/temporal/datetime_math.py @@ -157,7 +157,9 @@ def increment_datetime_by_string(mydate, increment, mult=1): .. code-block:: python >>> dt = datetime(2001, 9, 1, 0, 0, 0) - >>> string = "60 seconds, 4 minutes, 12 hours, 10 days, 1 weeks, 5 months, 1 years" + >>> string = ( + ... "60 seconds, 4 minutes, 12 hours, 10 days, 1 weeks, 5 months, 1 years" + ... ) >>> increment_datetime_by_string(dt, string) datetime.datetime(2003, 2, 18, 12, 5) @@ -389,7 +391,7 @@ def adjust_datetime_to_granularity(mydate, granularity): .. code-block:: python - >>> dt = datetime(2001, 8, 8, 12,30,30) + >>> dt = datetime(2001, 8, 8, 12, 30, 30) >>> adjust_datetime_to_granularity(dt, "5 seconds") datetime.datetime(2001, 8, 8, 12, 30, 30) @@ -414,7 +416,9 @@ def adjust_datetime_to_granularity(mydate, granularity): >>> adjust_datetime_to_granularity(dt, "2 years") datetime.datetime(2001, 1, 1, 0, 0) - >>> adjust_datetime_to_granularity(dt, "2 years, 3 months, 5 days, 3 hours, 3 minutes, 2 seconds") + >>> adjust_datetime_to_granularity( + ... dt, "2 years, 3 months, 5 days, 3 hours, 3 minutes, 2 seconds" + ... ) datetime.datetime(2001, 8, 8, 12, 30, 30) >>> adjust_datetime_to_granularity(dt, "3 months, 5 days, 3 minutes") @@ -521,129 +525,129 @@ def compute_datetime_delta(start, end): .. code-block:: python - >>> start = datetime(2001, 1, 1, 00,00,00) - >>> end = datetime(2001, 1, 1, 00,00,00) + >>> start = datetime(2001, 1, 1, 0, 0, 0) + >>> end = datetime(2001, 1, 1, 0, 0, 0) >>> compute_datetime_delta(start, end) {'hour': 0, 'month': 0, 'second': 0, 'max_days': 0, 'year': 0, 'day': 0, 'minute': 0} - >>> start = datetime(2001, 1, 1, 00,00,14) - >>> end = datetime(2001, 1, 1, 00,00,44) + >>> start = datetime(2001, 1, 1, 0, 0, 14) + >>> end = datetime(2001, 1, 1, 0, 0, 44) >>> compute_datetime_delta(start, end) {'hour': 0, 'month': 0, 'second': 30, 'max_days': 0, 'year': 0, 'day': 0, 'minute': 0} - >>> start = datetime(2001, 1, 1, 00,00,44) - >>> end = datetime(2001, 1, 1, 00,01,14) + >>> start = datetime(2001, 1, 1, 0, 0, 44) + >>> end = datetime(2001, 1, 1, 0, 1, 14) >>> compute_datetime_delta(start, end) {'hour': 0, 'month': 0, 'second': 30, 'max_days': 0, 'year': 0, 'day': 0, 'minute': 1} - >>> start = datetime(2001, 1, 1, 00,00,30) - >>> end = datetime(2001, 1, 1, 00,05,30) + >>> start = datetime(2001, 1, 1, 0, 0, 30) + >>> end = datetime(2001, 1, 1, 0, 5, 30) >>> compute_datetime_delta(start, end) {'hour': 0, 'month': 0, 'second': 300, 'max_days': 0, 'year': 0, 'day': 0, 'minute': 5} - >>> start = datetime(2001, 1, 1, 00,00,00) - >>> end = datetime(2001, 1, 1, 00,01,00) + >>> start = datetime(2001, 1, 1, 0, 0, 0) + >>> end = datetime(2001, 1, 1, 0, 1, 0) >>> compute_datetime_delta(start, end) {'hour': 0, 'month': 0, 'second': 0, 'max_days': 0, 'year': 0, 'day': 0, 'minute': 1} - >>> start = datetime(2011,10,31, 00,45,00) - >>> end = datetime(2011,10,31, 01,45,00) + >>> start = datetime(2011, 10, 31, 0, 45, 0) + >>> end = datetime(2011, 10, 31, 1, 45, 0) >>> compute_datetime_delta(start, end) {'hour': 1, 'second': 0, 'max_days': 0, 'year': 0, 'day': 0, 'minute': 60} - >>> start = datetime(2011,10,31, 00,45,00) - >>> end = datetime(2011,10,31, 01,15,00) + >>> start = datetime(2011, 10, 31, 0, 45, 0) + >>> end = datetime(2011, 10, 31, 1, 15, 0) >>> compute_datetime_delta(start, end) {'hour': 1, 'second': 0, 'max_days': 0, 'year': 0, 'day': 0, 'minute': 30} - >>> start = datetime(2011,10,31, 00,45,00) - >>> end = datetime(2011,10,31, 12,15,00) + >>> start = datetime(2011, 10, 31, 0, 45, 0) + >>> end = datetime(2011, 10, 31, 12, 15, 0) >>> compute_datetime_delta(start, end) {'hour': 12, 'second': 0, 'max_days': 0, 'year': 0, 'day': 0, 'minute': 690} - >>> start = datetime(2011,10,31, 00,00,00) - >>> end = datetime(2011,10,31, 01,00,00) + >>> start = datetime(2011, 10, 31, 0, 0, 0) + >>> end = datetime(2011, 10, 31, 1, 0, 0) >>> compute_datetime_delta(start, end) {'hour': 1, 'second': 0, 'max_days': 0, 'year': 0, 'day': 0, 'minute': 0} - >>> start = datetime(2011,10,31, 00,00,00) - >>> end = datetime(2011,11,01, 01,00,00) + >>> start = datetime(2011, 10, 31, 0, 0, 0) + >>> end = datetime(2011, 11, 1, 1, 0, 0) >>> compute_datetime_delta(start, end) {'hour': 25, 'second': 0, 'max_days': 1, 'year': 0, 'day': 1, 'minute': 0} - >>> start = datetime(2011,10,31, 12,00,00) - >>> end = datetime(2011,11,01, 06,00,00) + >>> start = datetime(2011, 10, 31, 12, 0, 0) + >>> end = datetime(2011, 11, 1, 6, 0, 0) >>> compute_datetime_delta(start, end) {'hour': 18, 'second': 0, 'max_days': 0, 'year': 0, 'day': 0, 'minute': 0} - >>> start = datetime(2011,11,01, 00,00,00) - >>> end = datetime(2011,12,01, 01,00,00) + >>> start = datetime(2011, 11, 1, 0, 0, 0) + >>> end = datetime(2011, 12, 1, 1, 0, 0) >>> compute_datetime_delta(start, end) {'hour': 721, 'month': 1, 'second': 0, 'max_days': 30, 'year': 0, 'day': 0, 'minute': 0} - >>> start = datetime(2011,11,01, 00,00,00) - >>> end = datetime(2011,11,05, 00,00,00) + >>> start = datetime(2011, 11, 1, 0, 0, 0) + >>> end = datetime(2011, 11, 5, 0, 0, 0) >>> compute_datetime_delta(start, end) {'hour': 0, 'second': 0, 'max_days': 4, 'year': 0, 'day': 4, 'minute': 0} - >>> start = datetime(2011,10,06, 00,00,00) - >>> end = datetime(2011,11,05, 00,00,00) + >>> start = datetime(2011, 10, 6, 0, 0, 0) + >>> end = datetime(2011, 11, 5, 0, 0, 0) >>> compute_datetime_delta(start, end) {'hour': 0, 'second': 0, 'max_days': 30, 'year': 0, 'day': 30, 'minute': 0} - >>> start = datetime(2011,12,02, 00,00,00) - >>> end = datetime(2012,01,01, 00,00,00) + >>> start = datetime(2011, 12, 2, 0, 0, 0) + >>> end = datetime(2012, 1, 1, 0, 0, 0) >>> compute_datetime_delta(start, end) {'hour': 0, 'second': 0, 'max_days': 30, 'year': 1, 'day': 30, 'minute': 0} - >>> start = datetime(2011,01,01, 00,00,00) - >>> end = datetime(2011,02,01, 00,00,00) + >>> start = datetime(2011, 1, 1, 0, 0, 0) + >>> end = datetime(2011, 2, 1, 0, 0, 0) >>> compute_datetime_delta(start, end) {'hour': 0, 'month': 1, 'second': 0, 'max_days': 31, 'year': 0, 'day': 0, 'minute': 0} - >>> start = datetime(2011,12,01, 00,00,00) - >>> end = datetime(2012,01,01, 00,00,00) + >>> start = datetime(2011, 12, 1, 0, 0, 0) + >>> end = datetime(2012, 1, 1, 0, 0, 0) >>> compute_datetime_delta(start, end) {'hour': 0, 'month': 1, 'second': 0, 'max_days': 31, 'year': 1, 'day': 0, 'minute': 0} - >>> start = datetime(2011,12,01, 00,00,00) - >>> end = datetime(2012,06,01, 00,00,00) + >>> start = datetime(2011, 12, 1, 0, 0, 0) + >>> end = datetime(2012, 6, 1, 0, 0, 0) >>> compute_datetime_delta(start, end) {'hour': 0, 'month': 6, 'second': 0, 'max_days': 183, 'year': 1, 'day': 0, 'minute': 0} - >>> start = datetime(2011,06,01, 00,00,00) - >>> end = datetime(2021,06,01, 00,00,00) + >>> start = datetime(2011, 6, 1, 0, 0, 0) + >>> end = datetime(2021, 6, 1, 0, 0, 0) >>> compute_datetime_delta(start, end) {'hour': 0, 'month': 120, 'second': 0, 'max_days': 3653, 'year': 10, 'day': 0, 'minute': 0} - >>> start = datetime(2011,06,01, 00,00,00) - >>> end = datetime(2012,06,01, 12,00,00) + >>> start = datetime(2011, 6, 1, 0, 0, 0) + >>> end = datetime(2012, 6, 1, 12, 0, 0) >>> compute_datetime_delta(start, end) {'hour': 8796, 'month': 12, 'second': 0, 'max_days': 366, 'year': 1, 'day': 0, 'minute': 0} - >>> start = datetime(2011,06,01, 00,00,00) - >>> end = datetime(2012,06,01, 12,30,00) + >>> start = datetime(2011, 6, 1, 0, 0, 0) + >>> end = datetime(2012, 6, 1, 12, 30, 0) >>> compute_datetime_delta(start, end) {'hour': 8796, 'month': 12, 'second': 0, 'max_days': 366, 'year': 1, 'day': 0, 'minute': 527790} - >>> start = datetime(2011,06,01, 00,00,00) - >>> end = datetime(2012,06,01, 12,00,05) + >>> start = datetime(2011, 6, 1, 0, 0, 0) + >>> end = datetime(2012, 6, 1, 12, 0, 5) >>> compute_datetime_delta(start, end) {'hour': 8796, 'month': 12, 'second': 31665605, 'max_days': 366, 'year': 1, 'day': 0, 'minute': 0} - >>> start = datetime(2011,06,01, 00,00,00) - >>> end = datetime(2012,06,01, 00,30,00) + >>> start = datetime(2011, 6, 1, 0, 0, 0) + >>> end = datetime(2012, 6, 1, 0, 30, 0) >>> compute_datetime_delta(start, end) {'hour': 0, 'month': 12, 'second': 0, 'max_days': 366, 'year': 1, 'day': 0, 'minute': 527070} - >>> start = datetime(2011,06,01, 00,00,00) - >>> end = datetime(2012,06,01, 00,00,05) + >>> start = datetime(2011, 12, 1, 0, 0, 0) + >>> end = datetime(2012, 6, 1, 0, 0, 0) >>> compute_datetime_delta(start, end) {'hour': 0, 'month': 12, 'second': 31622405, 'max_days': 366, 'year': 1, 'day': 0, 'minute': 0} :return: A dictionary with year, month, day, hour, minute and second as keys() - """ + """ # noqa: E501 comp = {} day_diff = (end - start).days @@ -993,7 +997,8 @@ def create_numeric_suffix(base, count, zeros): :param base: the basename for new map :param count: a number - :param zeros: a string containing the expected number, coming from suffix option like "%05" + :param zeros: a string containing the expected number, coming from suffix option + like "%05" """ spli = zeros.split("%") if len(spli) == 2: diff --git a/python/grass/temporal/list_stds.py b/python/grass/temporal/list_stds.py index 0a216bedcd2..e913409fd60 100644 --- a/python/grass/temporal/list_stds.py +++ b/python/grass/temporal/list_stds.py @@ -60,21 +60,37 @@ def get_dataset_list( >>> import grass.temporal as tgis >>> tgis.core.init() >>> name = "list_stds_test" - >>> sp = tgis.open_stds.open_new_stds(name=name, type="strds", - ... temporaltype="absolute", title="title", descr="descr", - ... semantic="mean", dbif=None, overwrite=True) + >>> sp = tgis.open_stds.open_new_stds( + ... name=name, + ... type="strds", + ... temporaltype="absolute", + ... title="title", + ... descr="descr", + ... semantic="mean", + ... dbif=None, + ... overwrite=True, + ... ) >>> mapset = tgis.get_current_mapset() - >>> stds_list = tgis.list_stds.get_dataset_list("strds", "absolute", columns="name") - >>> rows = stds_list[mapset] + >>> stds_list = tgis.list_stds.get_dataset_list( + ... "strds", "absolute", columns="name" + ... ) + >>> rows = stds_list[mapset] >>> for row in rows: ... if row["name"] == name: ... print(True) + ... True - >>> stds_list = tgis.list_stds.get_dataset_list("strds", "absolute", columns="name,mapset", where="mapset = '%s'"%(mapset)) - >>> rows = stds_list[mapset] + >>> stds_list = tgis.list_stds.get_dataset_list( + ... "strds", + ... "absolute", + ... columns="name,mapset", + ... where="mapset = '%s'" % (mapset), + ... ) + >>> rows = stds_list[mapset] >>> for row in rows: ... if row["name"] == name and row["mapset"] == mapset: ... print(True) + ... True >>> check = sp.delete() @@ -249,7 +265,8 @@ def _write_table(rows, column_names, output_format, separator, file): elif output_format == "yaml": _write_yaml(rows=rows, column_names=column_names, file=file) elif output_format == "plain": - # No particular reason for this separator expect that this is the original behavior. + # No particular reason for this separator except that this is the original + # behavior. if not separator: separator = "\t" _write_plain(rows=rows, header=column_names, separator=separator, file=file) @@ -445,7 +462,8 @@ def check_columns(column_names, output_format, element_type): element_type=element_type, detail=( _( - "Dataset is empty or where clause is too constrained or incorrect" + "Dataset is empty or where clause is too constrained or " + "incorrect" ) if where else _("Dataset is empty") diff --git a/python/grass/temporal/metadata.py b/python/grass/temporal/metadata.py index a77c16b9850..6094bbbe146 100644 --- a/python/grass/temporal/metadata.py +++ b/python/grass/temporal/metadata.py @@ -36,9 +36,18 @@ class RasterMetadataBase(SQLDatabaseInterface): .. code-block:: python >>> init() - >>> meta = RasterMetadataBase(table="metadata", ident="soil@PERMANENT", - ... datatype="CELL", cols=100, rows=100, number_of_cells=10000, nsres=0.1, - ... ewres=0.1, min=0, max=100) + >>> meta = RasterMetadataBase( + ... table="metadata", + ... ident="soil@PERMANENT", + ... datatype="CELL", + ... cols=100, + ... rows=100, + ... number_of_cells=10000, + ... nsres=0.1, + ... ewres=0.1, + ... min=0, + ... max=100, + ... ) >>> meta.datatype 'CELL' >>> meta.cols @@ -285,9 +294,17 @@ class RasterMetadata(RasterMetadataBase): .. code-block:: python >>> init() - >>> meta = RasterMetadata(ident="soil@PERMANENT", - ... datatype="CELL", cols=100, rows=100, number_of_cells=10000, nsres=0.1, - ... ewres=0.1, min=0, max=100) + >>> meta = RasterMetadata( + ... ident="soil@PERMANENT", + ... datatype="CELL", + ... cols=100, + ... rows=100, + ... number_of_cells=10000, + ... nsres=0.1, + ... ewres=0.1, + ... min=0, + ... max=100, + ... ) >>> meta.datatype 'CELL' >>> meta.cols @@ -399,10 +416,19 @@ class Raster3DMetadata(RasterMetadataBase): .. code-block:: python >>> init() - >>> meta = Raster3DMetadata(ident="soil@PERMANENT", - ... datatype="FCELL", cols=100, rows=100, depths=100, - ... number_of_cells=1000000, nsres=0.1, ewres=0.1, tbres=0.1, - ... min=0, max=100) + >>> meta = Raster3DMetadata( + ... ident="soil@PERMANENT", + ... datatype="FCELL", + ... cols=100, + ... rows=100, + ... depths=100, + ... number_of_cells=1000000, + ... nsres=0.1, + ... ewres=0.1, + ... tbres=0.1, + ... min=0, + ... max=100, + ... ) >>> meta.datatype 'FCELL' >>> meta.cols @@ -542,11 +568,22 @@ class VectorMetadata(SQLDatabaseInterface): .. code-block:: python >>> init() - >>> meta = VectorMetadata(ident="lidar@PERMANENT", is_3d=True, - ... number_of_points=1, number_of_lines=2, number_of_boundaries=3, - ... number_of_centroids=4, number_of_faces=5, number_of_kernels=6, - ... number_of_primitives=7, number_of_nodes=8, number_of_areas=9, - ... number_of_islands=10, number_of_holes=11, number_of_volumes=12) + >>> meta = VectorMetadata( + ... ident="lidar@PERMANENT", + ... is_3d=True, + ... number_of_points=1, + ... number_of_lines=2, + ... number_of_boundaries=3, + ... number_of_centroids=4, + ... number_of_faces=5, + ... number_of_kernels=6, + ... number_of_primitives=7, + ... number_of_nodes=8, + ... number_of_areas=9, + ... number_of_islands=10, + ... number_of_holes=11, + ... number_of_volumes=12, + ... ) >>> meta.id 'lidar@PERMANENT' >>> meta.is_3d @@ -895,8 +932,9 @@ class STDSMetadataBase(SQLDatabaseInterface): .. code-block:: python >>> init() - >>> meta = STDSMetadataBase(ident="soils@PERMANENT", - ... title="Soils", description="Soils 1950 - 2010") + >>> meta = STDSMetadataBase( + ... ident="soils@PERMANENT", title="Soils", description="Soils 1950 - 2010" + ... ) >>> meta.id 'soils@PERMANENT' >>> meta.title @@ -1015,7 +1053,7 @@ def _print_info_head(self, shell=False): """ if not shell: print( - " +-------------------- Metadata information ----------------------------------+" + " +-------------------- Metadata information ----------------------------------+" # noqa: E501 ) def _print_info_tail(self, shell=False): @@ -1086,8 +1124,9 @@ class for strds and str3ds datasets .. code-block:: python >>> init() - >>> meta = STDSRasterMetadataBase(ident="soils@PERMANENT", - ... title="Soils", description="Soils 1950 - 2010") + >>> meta = STDSRasterMetadataBase( + ... ident="soils@PERMANENT", title="Soils", description="Soils 1950 - 2010" + ... ) >>> meta.id 'soils@PERMANENT' >>> meta.title @@ -1304,8 +1343,9 @@ class STRDSMetadata(STDSRasterMetadataBase): .. code-block:: python >>> init() - >>> meta = STRDSMetadata(ident="soils@PERMANENT", - ... title="Soils", description="Soils 1950 - 2010") + >>> meta = STRDSMetadata( + ... ident="soils@PERMANENT", title="Soils", description="Soils 1950 - 2010" + ... ) >>> meta.id 'soils@PERMANENT' >>> meta.title @@ -1478,8 +1518,9 @@ class STR3DSMetadata(STDSRasterMetadataBase): .. code-block:: python >>> init() - >>> meta = STR3DSMetadata(ident="soils@PERMANENT", - ... title="Soils", description="Soils 1950 - 2010") + >>> meta = STR3DSMetadata( + ... ident="soils@PERMANENT", title="Soils", description="Soils 1950 - 2010" + ... ) >>> meta.id 'soils@PERMANENT' >>> meta.title @@ -1620,8 +1661,11 @@ class STVDSMetadata(STDSMetadataBase): .. code-block:: python >>> init() - >>> meta = STVDSMetadata(ident="lidars@PERMANENT", - ... title="LIDARS", description="LIDARS 2008 - 2010") + >>> meta = STVDSMetadata( + ... ident="lidars@PERMANENT", + ... title="LIDARS", + ... description="LIDARS 2008 - 2010", + ... ) >>> meta.id 'lidars@PERMANENT' >>> meta.title diff --git a/python/grass/temporal/register.py b/python/grass/temporal/register.py index d0ccbc7aa0c..149a304f628 100644 --- a/python/grass/temporal/register.py +++ b/python/grass/temporal/register.py @@ -215,7 +215,8 @@ def register_maps_in_space_time_dataset( increment = None msgr.warning( _( - "The increment option will be ignored because of time stamps in input file" + "The increment option will be ignored because of time stamps in " + "input file" ) ) @@ -223,7 +224,8 @@ def register_maps_in_space_time_dataset( increment = None msgr.warning( _( - "The interval flag will be ignored because of time stamps in input file" + "The interval flag will be ignored because of time stamps in input " + "file" ) ) fd.close() @@ -373,7 +375,8 @@ def register_maps_in_space_time_dataset( # Try to read an existing time stamp from the grass spatial database # in case this map wasn't already registered in the temporal database - # Read the spatial database time stamp only, if no time stamp was provided for this map + # Read the spatial database time stamp only, if no time stamp was provided for + # this map # as method argument or in the input file if not is_in_db and not start: map_object.read_timestamp_from_grass() @@ -534,7 +537,8 @@ def assign_valid_time_to_map( msgr.debug( 1, _( - "Set absolute valid time for map <{mid}> to {start_time} - {end_time}" + "Set absolute valid time for map <{mid}> to " + "{start_time} - {end_time}" ).format( mid=map_object.get_map_id(), start_time=str(start_time), @@ -573,7 +577,8 @@ def assign_valid_time_to_map( msgr.debug( 1, _( - "Set relative valid time for map <{mid}> to {start} - {end} with unit {unit}" + "Set relative valid time for map <{mid}> to " + "{start} - {end} with unit {unit}" ).format( mid=map_object.get_map_id(), start=start_time, diff --git a/python/grass/temporal/space_time_datasets.py b/python/grass/temporal/space_time_datasets.py index c6acca67358..a32cb2d2fac 100644 --- a/python/grass/temporal/space_time_datasets.py +++ b/python/grass/temporal/space_time_datasets.py @@ -76,14 +76,20 @@ class RasterDataset(AbstractMapDataset): >>> import grass.temporal as tgis >>> init() >>> gs.use_temp_region() - >>> gs.run_command("g.region", n=80.0, s=0.0, e=120.0, w=0.0, - ... t=1.0, b=0.0, res=10.0) + >>> gs.run_command( + ... "g.region", n=80.0, s=0.0, e=120.0, w=0.0, t=1.0, b=0.0, res=10.0 + ... ) 0 - >>> gs.run_command("r.mapcalc", overwrite=True, quiet=True, - ... expression="strds_map_test_case = 1") + >>> gs.run_command( + ... "r.mapcalc", + ... overwrite=True, + ... quiet=True, + ... expression="strds_map_test_case = 1", + ... ) 0 - >>> gs.run_command("r.timestamp", map="strds_map_test_case", - ... date="15 jan 1999", quiet=True) + >>> gs.run_command( + ... "r.timestamp", map="strds_map_test_case", date="15 jan 1999", quiet=True + ... ) 0 >>> mapset = tgis.get_current_mapset() >>> name = "strds_map_test_case" @@ -120,8 +126,9 @@ class RasterDataset(AbstractMapDataset): | Minimum value:.............. 1.0 | Maximum value:.............. 1.0 - >>> gs.run_command("r.timestamp", map="strds_map_test_case", - ... date="2 years", quiet=True) + >>> gs.run_command( + ... "r.timestamp", map="strds_map_test_case", date="2 years", quiet=True + ... ) 0 >>> rmap.read_timestamp_from_grass() True @@ -142,8 +149,9 @@ class RasterDataset(AbstractMapDataset): True >>> rmap.get_type() 'raster' - >>> rmap.set_absolute_time(start_time=datetime(2001,1,1), - ... end_time=datetime(2012,1,1)) + >>> rmap.set_absolute_time( + ... start_time=datetime(2001, 1, 1), end_time=datetime(2012, 1, 1) + ... ) True >>> rmap.get_absolute_time() (datetime.datetime(2001, 1, 1, 0, 0), datetime.datetime(2012, 1, 1, 0, 0)) @@ -229,7 +237,7 @@ def get_np_array(self): """Return this raster map as memmap numpy style array to access the raster values in numpy style without loading the whole map in the RAM. - In case this raster map does exists in the grass spatial database, + In case this raster map does exist in the grass spatial database, the map will be exported using r.out.bin to a temporary location and assigned to the memmap object that is returned by this function. @@ -263,7 +271,7 @@ def has_grass_timestamp(self): def read_timestamp_from_grass(self): """Read the timestamp of this map from the map metadata in the grass file system based spatial database and - set the internal time stamp that should be insert/updated + set the internal time stamp that should be inserted/updated in the temporal database. :return: True if success, False on error @@ -350,7 +358,7 @@ def remove_timestamp_from_grass(self): def read_semantic_label_from_grass(self): """Read the semantic label of this map from the map metadata in the GRASS file system based spatial database and - set the internal semantic label that should be insert/updated + set the internal semantic label that should be inserted/updated in the temporal database. :return: True if success, False if semantic labels could not be @@ -491,14 +499,31 @@ class Raster3DDataset(AbstractMapDataset): >>> import grass.script as gs >>> init() >>> gs.use_temp_region() - >>> 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, res3=10.0) + >>> 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, + ... res3=10.0, + ... ) 0 - >>> gs.run_command("r3.mapcalc", overwrite=True, quiet=True, - ... expression="str3ds_map_test_case = 1") + >>> gs.run_command( + ... "r3.mapcalc", + ... overwrite=True, + ... quiet=True, + ... expression="str3ds_map_test_case = 1", + ... ) 0 - >>> gs.run_command("r3.timestamp", map="str3ds_map_test_case", - ... date="15 jan 1999", quiet=True) + >>> gs.run_command( + ... "r3.timestamp", + ... map="str3ds_map_test_case", + ... date="15 jan 1999", + ... quiet=True, + ... ) 0 >>> mapset = get_current_mapset() >>> name = "str3ds_map_test_case" @@ -537,8 +562,9 @@ class Raster3DDataset(AbstractMapDataset): | Number of depths:........... 10 | Top-Bottom resolution:...... 10.0 - >>> gs.run_command("r3.timestamp", map="str3ds_map_test_case", - ... date="2 years", quiet=True) + >>> gs.run_command( + ... "r3.timestamp", map="str3ds_map_test_case", date="2 years", quiet=True + ... ) 0 >>> r3map.read_timestamp_from_grass() True @@ -559,8 +585,9 @@ class Raster3DDataset(AbstractMapDataset): True >>> r3map.get_type() 'raster3d' - >>> r3map.set_absolute_time(start_time=datetime(2001,1,1), - ... end_time=datetime(2012,1,1)) + >>> r3map.set_absolute_time( + ... start_time=datetime(2001, 1, 1), end_time=datetime(2012, 1, 1) + ... ) True >>> r3map.get_absolute_time() (datetime.datetime(2001, 1, 1, 0, 0), datetime.datetime(2012, 1, 1, 0, 0)) @@ -578,7 +605,9 @@ class Raster3DDataset(AbstractMapDataset): True >>> r3map.is_time_relative() False - >>> gs.run_command("g.remove", flags="f", type="raster_3d", name=name, quiet=True) + >>> gs.run_command( + ... "g.remove", flags="f", type="raster_3d", name=name, quiet=True + ... ) 0 >>> gs.del_temp_region() @@ -661,7 +690,7 @@ def get_np_array(self): 3D raster values in numpy style without loading the whole map in the RAM. - In case this 3D raster map does exists in the grass spatial database, + In case this 3D raster map does exist in the grass spatial database, the map will be exported using r3.out.bin to a temporary location and assigned to the memmap object that is returned by this function. @@ -695,7 +724,7 @@ def has_grass_timestamp(self): def read_timestamp_from_grass(self): """Read the timestamp of this map from the map metadata in the grass file system based spatial database and - set the internal time stamp that should be insert/updated + set the internal time stamp that should be inserted/updated in the temporal database. :return: True if success, False on error @@ -867,14 +896,25 @@ class VectorDataset(AbstractMapDataset): >>> import grass.script as gs >>> init() >>> gs.use_temp_region() - >>> gs.run_command("g.region", n=80.0, s=0.0, e=120.0, w=0.0, - ... t=1.0, b=0.0, res=10.0) + >>> gs.run_command( + ... "g.region", n=80.0, s=0.0, e=120.0, w=0.0, t=1.0, b=0.0, res=10.0 + ... ) 0 - >>> gs.run_command("v.random", overwrite=True, output="stvds_map_test_case", - ... n=100, zmin=0, zmax=100, flags="z", column="elevation", quiet=True) + >>> gs.run_command( + ... "v.random", + ... overwrite=True, + ... output="stvds_map_test_case", + ... n=100, + ... zmin=0, + ... zmax=100, + ... flags="z", + ... column="elevation", + ... quiet=True, + ... ) 0 - >>> gs.run_command("v.timestamp", map="stvds_map_test_case", - ... date="15 jan 1999", quiet=True) + >>> gs.run_command( + ... "v.timestamp", map="stvds_map_test_case", date="15 jan 1999", quiet=True + ... ) 0 >>> mapset = get_current_mapset() >>> name = "stvds_map_test_case" @@ -908,8 +948,9 @@ class VectorDataset(AbstractMapDataset): | Number of holes ............ 0 | Number of volumes .......... 0 - >>> gs.run_command("v.timestamp", map="stvds_map_test_case", - ... date="2 years", quiet=True) + >>> gs.run_command( + ... "v.timestamp", map="stvds_map_test_case", date="2 years", quiet=True + ... ) 0 >>> vmap.read_timestamp_from_grass() True @@ -930,8 +971,9 @@ class VectorDataset(AbstractMapDataset): True >>> vmap.get_type() 'vector' - >>> vmap.set_absolute_time(start_time=datetime(2001,1,1), - ... end_time=datetime(2012,1,1)) + >>> vmap.set_absolute_time( + ... start_time=datetime(2001, 1, 1), end_time=datetime(2012, 1, 1) + ... ) True >>> vmap.get_absolute_time() (datetime.datetime(2001, 1, 1, 0, 0), datetime.datetime(2012, 1, 1, 0, 0)) @@ -1034,7 +1076,7 @@ def has_grass_timestamp(self): def read_timestamp_from_grass(self): """Read the timestamp of this map from the map metadata in the grass file system based spatial database and - set the internal time stamp that should be insert/updated + set the internal time stamp that should be inserted/updated in the temporal database. """ @@ -1192,20 +1234,20 @@ class SpaceTimeRasterDataset(AbstractSpaceTimeDataset): >>> import grass.temporal as tgis >>> tgis.init() >>> mapset = tgis.get_current_mapset() - >>> strds = tgis.SpaceTimeRasterDataset("old@%s"%mapset) + >>> strds = tgis.SpaceTimeRasterDataset("old@%s" % mapset) >>> strds.is_in_db() False >>> strds.is_stds() True >>> strds.get_type() 'strds' - >>> newstrds = strds.get_new_instance("newstrds@%s"%mapset) + >>> newstrds = strds.get_new_instance("newstrds@%s" % mapset) >>> isinstance(newstrds, SpaceTimeRasterDataset) True - >>> newmap = strds.get_new_map_instance("newmap@%s"%mapset) + >>> newmap = strds.get_new_map_instance("newmap@%s" % mapset) >>> isinstance(newmap, RasterDataset) True - >>> strds.reset("new@%s"%mapset) + >>> strds.reset("new@%s" % mapset) >>> strds.is_in_db() False >>> strds.reset(None) @@ -1308,20 +1350,20 @@ class SpaceTimeRaster3DDataset(AbstractSpaceTimeDataset): >>> import grass.temporal as tgis >>> tgis.init() >>> mapset = tgis.get_current_mapset() - >>> str3ds = tgis.SpaceTimeRaster3DDataset("old@%s"%mapset) + >>> str3ds = tgis.SpaceTimeRaster3DDataset("old@%s" % mapset) >>> str3ds.is_in_db() False >>> str3ds.is_stds() True >>> str3ds.get_type() 'str3ds' - >>> newstrds = str3ds.get_new_instance("newstrds@%s"%mapset) + >>> newstrds = str3ds.get_new_instance("newstrds@%s" % mapset) >>> isinstance(newstrds, SpaceTimeRaster3DDataset) True - >>> newmap = str3ds.get_new_map_instance("newmap@%s"%mapset) + >>> newmap = str3ds.get_new_map_instance("newmap@%s" % mapset) >>> isinstance(newmap, Raster3DDataset) True - >>> str3ds.reset("new@%s"%mapset) + >>> str3ds.reset("new@%s" % mapset) >>> str3ds.is_in_db() False >>> str3ds.reset(None) @@ -1434,20 +1476,20 @@ class SpaceTimeVectorDataset(AbstractSpaceTimeDataset): >>> import grass.temporal as tgis >>> tgis.init() >>> mapset = tgis.get_current_mapset() - >>> stvds = tgis.SpaceTimeVectorDataset("old@%s"%mapset) + >>> stvds = tgis.SpaceTimeVectorDataset("old@%s" % mapset) >>> stvds.is_in_db() False >>> stvds.is_stds() True >>> stvds.get_type() 'stvds' - >>> newstvds = stvds.get_new_instance("newstvds@%s"%mapset) + >>> newstvds = stvds.get_new_instance("newstvds@%s" % mapset) >>> isinstance(newstvds, SpaceTimeVectorDataset) True - >>> newmap = stvds.get_new_map_instance("newmap@%s"%mapset) + >>> newmap = stvds.get_new_map_instance("newmap@%s" % mapset) >>> isinstance(newmap, VectorDataset) True - >>> stvds.reset("new@%s"%mapset) + >>> stvds.reset("new@%s" % mapset) >>> stvds.is_in_db() False >>> stvds.reset(None) diff --git a/python/grass/temporal/spatial_extent.py b/python/grass/temporal/spatial_extent.py index ced1f88a9a1..7e026cf76eb 100644 --- a/python/grass/temporal/spatial_extent.py +++ b/python/grass/temporal/spatial_extent.py @@ -8,23 +8,59 @@ >>> import grass.temporal as tgis >>> tgis.init() >>> extent = tgis.RasterSpatialExtent( - ... ident="raster@PERMANENT", north=90, south=90, east=180, west=180, - ... top=100, bottom=-20) + ... ident="raster@PERMANENT", + ... north=90, + ... south=90, + ... east=180, + ... west=180, + ... top=100, + ... bottom=-20, + ... ) >>> extent = tgis.Raster3DSpatialExtent( - ... ident="raster3d@PERMANENT", north=90, south=90, east=180, west=180, - ... top=100, bottom=-20) + ... ident="raster3d@PERMANENT", + ... north=90, + ... south=90, + ... east=180, + ... west=180, + ... top=100, + ... bottom=-20, + ... ) >>> extent = tgis.VectorSpatialExtent( - ... ident="vector@PERMANENT", north=90, south=90, east=180, west=180, - ... top=100, bottom=-20) + ... ident="vector@PERMANENT", + ... north=90, + ... south=90, + ... east=180, + ... west=180, + ... top=100, + ... bottom=-20, + ... ) >>> extent = tgis.STRDSSpatialExtent( - ... ident="strds@PERMANENT", north=90, south=90, east=180, west=180, - ... top=100, bottom=-20) + ... ident="strds@PERMANENT", + ... north=90, + ... south=90, + ... east=180, + ... west=180, + ... top=100, + ... bottom=-20, + ... ) >>> extent = tgis.STR3DSSpatialExtent( - ... ident="str3ds@PERMANENT", north=90, south=90, east=180, west=180, - ... top=100, bottom=-20) + ... ident="str3ds@PERMANENT", + ... north=90, + ... south=90, + ... east=180, + ... west=180, + ... top=100, + ... bottom=-20, + ... ) >>> extent = tgis.STVDSSpatialExtent( - ... ident="stvds@PERMANENT", north=90, south=90, east=180, west=180, - ... top=100, bottom=-20) + ... ident="stvds@PERMANENT", + ... north=90, + ... south=90, + ... east=180, + ... west=180, + ... top=100, + ... bottom=-20, + ... ) (C) 2012-2013 by the GRASS Development Team This program is free software under the GNU General Public @@ -48,9 +84,16 @@ class SpatialExtent(SQLDatabaseInterface): .. code-block:: python >>> init() - >>> extent = SpatialExtent(table="raster_spatial_extent", - ... ident="soil@PERMANENT", north=90, south=90, east=180, west=180, - ... top=100, bottom=-20) + >>> extent = SpatialExtent( + ... table="raster_spatial_extent", + ... ident="soil@PERMANENT", + ... north=90, + ... south=90, + ... east=180, + ... west=180, + ... top=100, + ... bottom=-20, + ... ) >>> extent.id 'soil@PERMANENT' >>> extent.north @@ -178,8 +221,12 @@ def overlapping(self, extent): .. code-block:: python - >>> A = SpatialExtent(north=80, south=20, east=60, west=10, bottom=-50, top=50) - >>> B = SpatialExtent(north=80, south=20, east=60, west=10, bottom=-50, top=50) + >>> A = SpatialExtent( + ... north=80, south=20, east=60, west=10, bottom=-50, top=50 + ... ) + >>> B = SpatialExtent( + ... north=80, south=20, east=60, west=10, bottom=-50, top=50 + ... ) >>> A.overlapping(B) True @@ -266,10 +313,12 @@ def intersect(self, extent): .. code-block:: python - >>> A = SpatialExtent(north=80, south=20, east=60, west=10, - ... bottom=-50, top=50) - >>> B = SpatialExtent(north=80, south=20, east=60, west=10, - ... bottom=-50, top=50) + >>> A = SpatialExtent( + ... north=80, south=20, east=60, west=10, bottom=-50, top=50 + ... ) + >>> B = SpatialExtent( + ... north=80, south=20, east=60, west=10, bottom=-50, top=50 + ... ) >>> C = A.intersect(B) >>> C.print_info() +-------------------- Spatial extent ----------------------------------------+ @@ -279,8 +328,9 @@ def intersect(self, extent): | West:....................... 10.0 | Top:........................ 50.0 | Bottom:..................... -50.0 - >>> B = SpatialExtent(north=40, south=30, east=60, west=10, - ... bottom=-50, top=50) + >>> B = SpatialExtent( + ... north=40, south=30, east=60, west=10, bottom=-50, top=50 + ... ) >>> C = A.intersect(B) >>> C.print_info() +-------------------- Spatial extent ----------------------------------------+ @@ -290,8 +340,9 @@ def intersect(self, extent): | West:....................... 10.0 | Top:........................ 50.0 | Bottom:..................... -50.0 - >>> B = SpatialExtent(north=40, south=30, east=60, west=30, - ... bottom=-50, top=50) + >>> B = SpatialExtent( + ... north=40, south=30, east=60, west=30, bottom=-50, top=50 + ... ) >>> C = A.intersect(B) >>> C.print_info() +-------------------- Spatial extent ----------------------------------------+ @@ -301,8 +352,9 @@ def intersect(self, extent): | West:....................... 30.0 | Top:........................ 50.0 | Bottom:..................... -50.0 - >>> B = SpatialExtent(north=40, south=30, east=60, west=30, - ... bottom=-30, top=50) + >>> B = SpatialExtent( + ... north=40, south=30, east=60, west=30, bottom=-30, top=50 + ... ) >>> C = A.intersect(B) >>> C.print_info() +-------------------- Spatial extent ----------------------------------------+ @@ -312,8 +364,9 @@ def intersect(self, extent): | West:....................... 30.0 | Top:........................ 50.0 | Bottom:..................... -30.0 - >>> B = SpatialExtent(north=40, south=30, east=60, west=30, - ... bottom=-30, top=30) + >>> B = SpatialExtent( + ... north=40, south=30, east=60, west=30, bottom=-30, top=30 + ... ) >>> C = A.intersect(B) >>> C.print_info() +-------------------- Spatial extent ----------------------------------------+ @@ -327,7 +380,7 @@ def intersect(self, extent): :param extent: The spatial extent to intersect with :return: The intersection spatial extent - """ + """ # noqa: E501 if not self.overlapping(extent): return None @@ -436,10 +489,12 @@ def disjoint_union(self, extent): .. code-block:: python - >>> A = SpatialExtent(north=80, south=20, east=60, west=10, - ... bottom=-50, top=50) - >>> B = SpatialExtent(north=80, south=20, east=60, west=10, - ... bottom=-50, top=50) + >>> A = SpatialExtent( + ... north=80, south=20, east=60, west=10, bottom=-50, top=50 + ... ) + >>> B = SpatialExtent( + ... north=80, south=20, east=60, west=10, bottom=-50, top=50 + ... ) >>> C = A.disjoint_union(B) >>> C.print_info() +-------------------- Spatial extent ----------------------------------------+ @@ -449,8 +504,9 @@ def disjoint_union(self, extent): | West:....................... 10.0 | Top:........................ 50.0 | Bottom:..................... -50.0 - >>> B = SpatialExtent(north=40, south=30, east=60, west=10, - ... bottom=-50, top=50) + >>> B = SpatialExtent( + ... north=40, south=30, east=60, west=10, bottom=-50, top=50 + ... ) >>> C = A.disjoint_union(B) >>> C.print_info() +-------------------- Spatial extent ----------------------------------------+ @@ -460,8 +516,9 @@ def disjoint_union(self, extent): | West:....................... 10.0 | Top:........................ 50.0 | Bottom:..................... -50.0 - >>> B = SpatialExtent(north=40, south=30, east=60, west=30, - ... bottom=-50, top=50) + >>> B = SpatialExtent( + ... north=40, south=30, east=60, west=30, bottom=-50, top=50 + ... ) >>> C = A.disjoint_union(B) >>> C.print_info() +-------------------- Spatial extent ----------------------------------------+ @@ -471,8 +528,9 @@ def disjoint_union(self, extent): | West:....................... 10.0 | Top:........................ 50.0 | Bottom:..................... -50.0 - >>> B = SpatialExtent(north=40, south=30, east=60, west=30, - ... bottom=-30, top=50) + >>> B = SpatialExtent( + ... north=40, south=30, east=60, west=30, bottom=-30, top=50 + ... ) >>> C = A.disjoint_union(B) >>> C.print_info() +-------------------- Spatial extent ----------------------------------------+ @@ -482,8 +540,9 @@ def disjoint_union(self, extent): | West:....................... 10.0 | Top:........................ 50.0 | Bottom:..................... -50.0 - >>> B = SpatialExtent(north=40, south=30, east=60, west=30, - ... bottom=-30, top=30) + >>> B = SpatialExtent( + ... north=40, south=30, east=60, west=30, bottom=-30, top=30 + ... ) >>> C = A.disjoint_union(B) >>> C.print_info() +-------------------- Spatial extent ----------------------------------------+ @@ -493,10 +552,12 @@ def disjoint_union(self, extent): | West:....................... 10.0 | Top:........................ 50.0 | Bottom:..................... -50.0 - >>> A = SpatialExtent(north=80, south=20, east=60, west=10, - ... bottom=-50, top=50) - >>> B = SpatialExtent(north=90, south=80, east=70, west=20, - ... bottom=-30, top=60) + >>> A = SpatialExtent( + ... north=80, south=20, east=60, west=10, bottom=-50, top=50 + ... ) + >>> B = SpatialExtent( + ... north=90, south=80, east=70, west=20, bottom=-30, top=60 + ... ) >>> C = A.disjoint_union(B) >>> C.print_info() +-------------------- Spatial extent ----------------------------------------+ @@ -510,7 +571,7 @@ def disjoint_union(self, extent): :param extent: The spatial extent to create a disjoint union with :return: The union spatial extent - """ + """ # noqa: E501 new = self.disjoint_union_2d(extent) @@ -596,10 +657,12 @@ def is_in(self, extent): .. code-block:: python - >>> A = SpatialExtent(north=79, south=21, east=59, west=11, - ... bottom=-49, top=49) - >>> B = SpatialExtent(north=80, south=20, east=60, west=10, - ... bottom=-50, top=50) + >>> A = SpatialExtent( + ... north=79, south=21, east=59, west=11, bottom=-49, top=49 + ... ) + >>> B = SpatialExtent( + ... north=80, south=20, east=60, west=10, bottom=-50, top=50 + ... ) >>> A.is_in(B) True >>> B.is_in(A) @@ -652,10 +715,12 @@ def contain(self, extent): .. code-block:: python - >>> A = SpatialExtent(north=80, south=20, east=60, west=10, - ... bottom=-50, top=50) - >>> B = SpatialExtent(north=79, south=21, east=59, west=11, - ... bottom=-49, top=49) + >>> A = SpatialExtent( + ... north=80, south=20, east=60, west=10, bottom=-50, top=50 + ... ) + >>> B = SpatialExtent( + ... north=79, south=21, east=59, west=11, bottom=-49, top=49 + ... ) >>> A.contain(B) True >>> B.contain(A) @@ -732,10 +797,12 @@ def equivalent(self, extent): .. code-block:: python - >>> A = SpatialExtent(north=80, south=20, east=60, west=10, - ... bottom=-50, top=50) - >>> B = SpatialExtent(north=80, south=20, east=60, west=10, - ... bottom=-50, top=50) + >>> A = SpatialExtent( + ... north=80, south=20, east=60, west=10, bottom=-50, top=50 + ... ) + >>> B = SpatialExtent( + ... north=80, south=20, east=60, west=10, bottom=-50, top=50 + ... ) >>> A.equivalent(B) True >>> B.equivalent(A) @@ -1414,18 +1481,26 @@ def spatial_relation(self, extent): .. code-block:: python - >>> A = SpatialExtent(north=80, south=20, east=60, west=10, bottom=-50, top=50) - >>> B = SpatialExtent(north=80, south=20, east=60, west=10, bottom=-50, top=50) + >>> A = SpatialExtent( + ... north=80, south=20, east=60, west=10, bottom=-50, top=50 + ... ) + >>> B = SpatialExtent( + ... north=80, south=20, east=60, west=10, bottom=-50, top=50 + ... ) >>> A.spatial_relation(B) 'equivalent' >>> B.spatial_relation(A) 'equivalent' - >>> B = SpatialExtent(north=70, south=20, east=60, west=10, bottom=-50, top=50) + >>> B = SpatialExtent( + ... north=70, south=20, east=60, west=10, bottom=-50, top=50 + ... ) >>> A.spatial_relation_2d(B) 'cover' >>> A.spatial_relation(B) 'cover' - >>> B = SpatialExtent(north=70, south=30, east=60, west=10, bottom=-50, top=50) + >>> B = SpatialExtent( + ... north=70, south=30, east=60, west=10, bottom=-50, top=50 + ... ) >>> A.spatial_relation_2d(B) 'cover' >>> A.spatial_relation(B) @@ -1434,141 +1509,243 @@ def spatial_relation(self, extent): 'covered' >>> B.spatial_relation(A) 'covered' - >>> B = SpatialExtent(north=70, south=30, east=50, west=10, bottom=-50, top=50) + >>> B = SpatialExtent( + ... north=70, south=30, east=50, west=10, bottom=-50, top=50 + ... ) >>> A.spatial_relation_2d(B) 'cover' >>> B.spatial_relation_2d(A) 'covered' >>> A.spatial_relation(B) 'cover' - >>> B = SpatialExtent(north=70, south=30, east=50, west=20, bottom=-50, top=50) + >>> B = SpatialExtent( + ... north=70, south=30, east=50, west=20, bottom=-50, top=50 + ... ) >>> B.spatial_relation(A) 'covered' - >>> B = SpatialExtent(north=70, south=30, east=50, west=20, bottom=-50, top=50) + >>> B = SpatialExtent( + ... north=70, south=30, east=50, west=20, bottom=-50, top=50 + ... ) >>> A.spatial_relation_2d(B) 'contain' >>> A.spatial_relation(B) 'cover' - >>> B = SpatialExtent(north=70, south=30, east=50, west=20, bottom=-40, top=50) + >>> B = SpatialExtent( + ... north=70, south=30, east=50, west=20, bottom=-40, top=50 + ... ) >>> A.spatial_relation(B) 'cover' - >>> B = SpatialExtent(north=70, south=30, east=50, west=20, bottom=-40, top=40) + >>> B = SpatialExtent( + ... north=70, south=30, east=50, west=20, bottom=-40, top=40 + ... ) >>> A.spatial_relation(B) 'contain' >>> B.spatial_relation(A) 'in' - >>> B = SpatialExtent(north=90, south=30, east=50, west=20, bottom=-40, top=40) + >>> B = SpatialExtent( + ... north=90, south=30, east=50, west=20, bottom=-40, top=40 + ... ) >>> A.spatial_relation_2d(B) 'overlap' >>> A.spatial_relation(B) 'overlap' - >>> B = SpatialExtent(north=90, south=5, east=70, west=5, bottom=-40, top=40) + >>> B = SpatialExtent( + ... north=90, south=5, east=70, west=5, bottom=-40, top=40 + ... ) >>> A.spatial_relation_2d(B) 'in' >>> A.spatial_relation(B) 'overlap' - >>> B = SpatialExtent(north=90, south=5, east=70, west=5, bottom=-40, top=60) + >>> B = SpatialExtent( + ... north=90, south=5, east=70, west=5, bottom=-40, top=60 + ... ) >>> A.spatial_relation(B) 'overlap' - >>> B = SpatialExtent(north=90, south=5, east=70, west=5, bottom=-60, top=60) + >>> B = SpatialExtent( + ... north=90, south=5, east=70, west=5, bottom=-60, top=60 + ... ) >>> A.spatial_relation(B) 'in' - >>> A = SpatialExtent(north=80, south=60, east=60, west=10, bottom=-50, top=50) - >>> B = SpatialExtent(north=60, south=20, east=60, west=10, bottom=-50, top=50) + >>> A = SpatialExtent( + ... north=80, south=60, east=60, west=10, bottom=-50, top=50 + ... ) + >>> B = SpatialExtent( + ... north=60, south=20, east=60, west=10, bottom=-50, top=50 + ... ) >>> A.spatial_relation_2d(B) 'meet' >>> A.spatial_relation(B) 'meet' - >>> A = SpatialExtent(north=60, south=40, east=60, west=10, bottom=-50, top=50) - >>> B = SpatialExtent(north=80, south=60, east=60, west=10, bottom=-50, top=50) + >>> A = SpatialExtent( + ... north=60, south=40, east=60, west=10, bottom=-50, top=50 + ... ) + >>> B = SpatialExtent( + ... north=80, south=60, east=60, west=10, bottom=-50, top=50 + ... ) >>> A.spatial_relation_2d(B) 'meet' >>> A.spatial_relation(B) 'meet' - >>> A = SpatialExtent(north=80, south=40, east=60, west=40, bottom=-50, top=50) - >>> B = SpatialExtent(north=80, south=40, east=40, west=20, bottom=-50, top=50) + >>> A = SpatialExtent( + ... north=80, south=40, east=60, west=40, bottom=-50, top=50 + ... ) + >>> B = SpatialExtent( + ... north=80, south=40, east=40, west=20, bottom=-50, top=50 + ... ) >>> A.spatial_relation_2d(B) 'meet' >>> A.spatial_relation(B) 'meet' - >>> A = SpatialExtent(north=80, south=40, east=40, west=20, bottom=-50, top=50) - >>> B = SpatialExtent(north=90, south=30, east=60, west=40, bottom=-50, top=50) + >>> A = SpatialExtent( + ... north=80, south=40, east=40, west=20, bottom=-50, top=50 + ... ) + >>> B = SpatialExtent( + ... north=90, south=30, east=60, west=40, bottom=-50, top=50 + ... ) >>> A.spatial_relation_2d(B) 'meet' >>> A.spatial_relation(B) 'meet' - >>> A = SpatialExtent(north=80, south=40, east=40, west=20, bottom=-50, top=50) - >>> B = SpatialExtent(north=70, south=50, east=60, west=40, bottom=-50, top=50) + >>> A = SpatialExtent( + ... north=80, south=40, east=40, west=20, bottom=-50, top=50 + ... ) + >>> B = SpatialExtent( + ... north=70, south=50, east=60, west=40, bottom=-50, top=50 + ... ) >>> A.spatial_relation_2d(B) 'meet' >>> A.spatial_relation(B) 'meet' - >>> A = SpatialExtent(north=80, south=40, east=40, west=20, bottom=-50, top=50) - >>> B = SpatialExtent(north=60, south=20, east=60, west=40, bottom=-50, top=50) + >>> A = SpatialExtent( + ... north=80, south=40, east=40, west=20, bottom=-50, top=50 + ... ) + >>> B = SpatialExtent( + ... north=60, south=20, east=60, west=40, bottom=-50, top=50 + ... ) >>> A.spatial_relation_2d(B) 'meet' >>> A.spatial_relation(B) 'meet' - >>> A = SpatialExtent(north=80, south=40, east=40, west=20, bottom=-50, top=50) - >>> B = SpatialExtent(north=40, south=20, east=60, west=40, bottom=-50, top=50) + >>> A = SpatialExtent( + ... north=80, south=40, east=40, west=20, bottom=-50, top=50 + ... ) + >>> B = SpatialExtent( + ... north=40, south=20, east=60, west=40, bottom=-50, top=50 + ... ) >>> A.spatial_relation_2d(B) 'disjoint' >>> A.spatial_relation(B) 'disjoint' - >>> A = SpatialExtent(north=80, south=40, east=40, west=20, bottom=-50, top=50) - >>> B = SpatialExtent(north=60, south=20, east=60, west=40, bottom=-60, top=60) + >>> A = SpatialExtent( + ... north=80, south=40, east=40, west=20, bottom=-50, top=50 + ... ) + >>> B = SpatialExtent( + ... north=60, south=20, east=60, west=40, bottom=-60, top=60 + ... ) >>> A.spatial_relation(B) 'meet' - >>> A = SpatialExtent(north=80, south=40, east=40, west=20, bottom=-50, top=50) - >>> B = SpatialExtent(north=90, south=30, east=60, west=40, bottom=-40, top=40) + >>> A = SpatialExtent( + ... north=80, south=40, east=40, west=20, bottom=-50, top=50 + ... ) + >>> B = SpatialExtent( + ... north=90, south=30, east=60, west=40, bottom=-40, top=40 + ... ) >>> A.spatial_relation(B) 'meet' - >>> A = SpatialExtent(north=80, south=40, east=60, west=20, bottom=0, top=50) - >>> B = SpatialExtent(north=80, south=40, east=60, west=20, bottom=-50, top=0) + >>> A = SpatialExtent( + ... north=80, south=40, east=60, west=20, bottom=0, top=50 + ... ) + >>> B = SpatialExtent( + ... north=80, south=40, east=60, west=20, bottom=-50, top=0 + ... ) >>> A.spatial_relation(B) 'meet' - >>> A = SpatialExtent(north=80, south=40, east=60, west=20, bottom=0, top=50) - >>> B = SpatialExtent(north=80, south=50, east=60, west=30, bottom=-50, top=0) + >>> A = SpatialExtent( + ... north=80, south=40, east=60, west=20, bottom=0, top=50 + ... ) + >>> B = SpatialExtent( + ... north=80, south=50, east=60, west=30, bottom=-50, top=0 + ... ) >>> A.spatial_relation(B) 'meet' - >>> A = SpatialExtent(north=80, south=40, east=60, west=20, bottom=0, top=50) - >>> B = SpatialExtent(north=70, south=50, east=50, west=30, bottom=-50, top=0) + >>> A = SpatialExtent( + ... north=80, south=40, east=60, west=20, bottom=0, top=50 + ... ) + >>> B = SpatialExtent( + ... north=70, south=50, east=50, west=30, bottom=-50, top=0 + ... ) >>> A.spatial_relation(B) 'meet' - >>> A = SpatialExtent(north=80, south=40, east=60, west=20, bottom=0, top=50) - >>> B = SpatialExtent(north=90, south=30, east=70, west=10, bottom=-50, top=0) + >>> A = SpatialExtent( + ... north=80, south=40, east=60, west=20, bottom=0, top=50 + ... ) + >>> B = SpatialExtent( + ... north=90, south=30, east=70, west=10, bottom=-50, top=0 + ... ) >>> A.spatial_relation(B) 'meet' - >>> A = SpatialExtent(north=80, south=40, east=60, west=20, bottom=0, top=50) - >>> B = SpatialExtent(north=70, south=30, east=50, west=10, bottom=-50, top=0) + >>> A = SpatialExtent( + ... north=80, south=40, east=60, west=20, bottom=0, top=50 + ... ) + >>> B = SpatialExtent( + ... north=70, south=30, east=50, west=10, bottom=-50, top=0 + ... ) >>> A.spatial_relation(B) 'meet' - >>> A = SpatialExtent(north=80, south=40, east=60, west=20, bottom=-50, top=0) - >>> B = SpatialExtent(north=80, south=40, east=60, west=20, bottom=0, top=50) + >>> A = SpatialExtent( + ... north=80, south=40, east=60, west=20, bottom=-50, top=0 + ... ) + >>> B = SpatialExtent( + ... north=80, south=40, east=60, west=20, bottom=0, top=50 + ... ) >>> A.spatial_relation(B) 'meet' - >>> A = SpatialExtent(north=80, south=40, east=60, west=20, bottom=-50, top=0) - >>> B = SpatialExtent(north=80, south=50, east=60, west=30, bottom=0, top=50) + >>> A = SpatialExtent( + ... north=80, south=40, east=60, west=20, bottom=-50, top=0 + ... ) + >>> B = SpatialExtent( + ... north=80, south=50, east=60, west=30, bottom=0, top=50 + ... ) >>> A.spatial_relation(B) 'meet' - >>> A = SpatialExtent(north=80, south=40, east=60, west=20, bottom=-50, top=0) - >>> B = SpatialExtent(north=70, south=50, east=50, west=30, bottom=0, top=50) + >>> A = SpatialExtent( + ... north=80, south=40, east=60, west=20, bottom=-50, top=0 + ... ) + >>> B = SpatialExtent( + ... north=70, south=50, east=50, west=30, bottom=0, top=50 + ... ) >>> A.spatial_relation(B) 'meet' - >>> A = SpatialExtent(north=80, south=40, east=60, west=20, bottom=-50, top=0) - >>> B = SpatialExtent(north=90, south=30, east=70, west=10, bottom=0, top=50) + >>> A = SpatialExtent( + ... north=80, south=40, east=60, west=20, bottom=-50, top=0 + ... ) + >>> B = SpatialExtent( + ... north=90, south=30, east=70, west=10, bottom=0, top=50 + ... ) >>> A.spatial_relation(B) 'meet' - >>> A = SpatialExtent(north=80, south=40, east=60, west=20, bottom=-50, top=0) - >>> B = SpatialExtent(north=70, south=30, east=50, west=10, bottom=0, top=50) + >>> A = SpatialExtent( + ... north=80, south=40, east=60, west=20, bottom=-50, top=0 + ... ) + >>> B = SpatialExtent( + ... north=70, south=30, east=50, west=10, bottom=0, top=50 + ... ) >>> A.spatial_relation(B) 'meet' - >>> A = SpatialExtent(north=80, south=20, east=60, west=10, bottom=-50, top=50) - >>> B = SpatialExtent(north=90, south=81, east=60, west=10, bottom=-50, top=50) + >>> A = SpatialExtent( + ... north=80, south=20, east=60, west=10, bottom=-50, top=50 + ... ) + >>> B = SpatialExtent( + ... north=90, south=81, east=60, west=10, bottom=-50, top=50 + ... ) >>> A.spatial_relation(B) 'disjoint' - >>> A = SpatialExtent(north=80, south=20, east=60, west=10, bottom=-50, top=50) - >>> B = SpatialExtent(north=90, south=80, east=60, west=10, bottom=-50, top=50) + >>> A = SpatialExtent( + ... north=80, south=20, east=60, west=10, bottom=-50, top=50 + ... ) + >>> B = SpatialExtent( + ... north=90, south=80, east=60, west=10, bottom=-50, top=50 + ... ) >>> A.spatial_relation(B) 'meet' @@ -1825,7 +2002,7 @@ def print_info(self): """Print information about this class in human readable style""" # 0123456789012345678901234567890 print( - " +-------------------- Spatial extent ----------------------------------------+" + " +-------------------- Spatial extent ----------------------------------------+" # noqa: E501 ) print(" | North:...................... " + str(self.get_north())) print(" | South:...................... " + str(self.get_south())) diff --git a/python/grass/temporal/spatial_topology_dataset_connector.py b/python/grass/temporal/spatial_topology_dataset_connector.py index 0f303e5e663..93fe3270c43 100644 --- a/python/grass/temporal/spatial_topology_dataset_connector.py +++ b/python/grass/temporal/spatial_topology_dataset_connector.py @@ -68,7 +68,8 @@ class SpatialTopologyDatasetConnector: meet=a@P >>> rlist = tmr.get_spatial_relations() >>> if "COVER" in rlist.keys(): - ... print(rlist["COVER"][0].get_id()) + ... print(rlist["COVER"][0].get_id()) + ... a@P """ @@ -319,7 +320,7 @@ def print_spatial_topology_info(self): """Print information about this class in human readable style""" print( - " +-------------------- Spatial Topology --------------------------------------+" + " +-------------------- Spatial Topology --------------------------------------+" # noqa: E501 ) # 0123456789012345678901234567890 if self.equivalent is not None: diff --git a/python/grass/temporal/spatio_temporal_relationships.py b/python/grass/temporal/spatio_temporal_relationships.py index 14b81ed40d4..ab876d45ede 100644 --- a/python/grass/temporal/spatio_temporal_relationships.py +++ b/python/grass/temporal/spatio_temporal_relationships.py @@ -38,8 +38,6 @@ class SpatioTemporalTopologyBuilder: Example: - .. code-block:: python - # We have a space time raster dataset and build a map list # from all registered maps ordered by start time maps = strds.get_registered_maps_as_objects() @@ -74,6 +72,8 @@ class SpatioTemporalTopologyBuilder: # Dictionary like accessed map = tb["name@mapset"] + .. code-block:: python + >>> # Example with two lists of maps >>> import grass.temporal as tgis >>> import datetime @@ -81,14 +81,15 @@ class SpatioTemporalTopologyBuilder: >>> mapsA = [] >>> mapsB = [] >>> for i in range(4): - ... idA = "a%i@B"%(i) + ... idA = "a%i@B" % (i) ... mapA = tgis.RasterDataset(idA) - ... idB = "b%i@B"%(i) + ... idB = "b%i@B" % (i) ... mapB = tgis.RasterDataset(idB) ... check = mapA.set_relative_time(i, i + 1, "months") ... check = mapB.set_relative_time(i, i + 1, "months") ... mapsA.append(mapA) ... mapsB.append(mapB) + ... >>> # Build the topology between the two map lists >>> tb = SpatioTemporalTopologyBuilder() >>> tb.build(mapsA, mapsB, None) @@ -96,8 +97,11 @@ class SpatioTemporalTopologyBuilder: >>> for map in mapsA: ... if map.get_equal(): ... relations = map.get_equal() - ... print("Map %s has equal relation to map %s"%(map.get_name(), - ... relations[0].get_name())) + ... print( + ... "Map %s has equal relation to map %s" + ... % (map.get_name(), relations[0].get_name()) + ... ) + ... Map a0 has equal relation to map b0 Map a1 has equal relation to map b1 Map a2 has equal relation to map b2 @@ -106,8 +110,11 @@ class SpatioTemporalTopologyBuilder: >>> for map in mapsB: ... if map.get_equal(): ... relations = map.get_equal() - ... print("Map %s has equal relation to map %s"%(map.get_name(), - ... relations[0].get_name())) + ... print( + ... "Map %s has equal relation to map %s" + ... % (map.get_name(), relations[0].get_name()) + ... ) + ... Map b0 has equal relation to map a0 Map b1 has equal relation to map a1 Map b2 has equal relation to map a2 @@ -117,14 +124,15 @@ class SpatioTemporalTopologyBuilder: >>> mapsA = [] >>> mapsB = [] >>> for i in range(4): - ... idA = "a%i@B"%(i) + ... idA = "a%i@B" % (i) ... mapA = tgis.RasterDataset(idA) - ... idB = "b%i@B"%(i) + ... idB = "b%i@B" % (i) ... mapB = tgis.RasterDataset(idB) ... check = mapA.set_relative_time(i, i + 1, "months") ... check = mapB.set_relative_time(i + 1, i + 2, "months") ... mapsA.append(mapA) ... mapsB.append(mapB) + ... >>> # Build the topology between the two map lists >>> tb = SpatioTemporalTopologyBuilder() >>> tb.build(mapsA, mapsB, None) @@ -135,6 +143,7 @@ class SpatioTemporalTopologyBuilder: ... for key in m.keys(): ... if key not in ["NEXT", "PREV"]: ... print((key, m[key][0].get_temporal_extent_as_tuple())) + ... (0, 1) ('PRECEDES', (1, 2)) (1, 2) @@ -152,9 +161,9 @@ class SpatioTemporalTopologyBuilder: >>> mapsA = [] >>> mapsB = [] >>> for i in range(4): - ... idA = "a%i@B"%(i) + ... idA = "a%i@B" % (i) ... mapA = tgis.RasterDataset(idA) - ... idB = "b%i@B"%(i) + ... idB = "b%i@B" % (i) ... mapB = tgis.RasterDataset(idB) ... start = datetime.datetime(2000 + i, 1, 1) ... end = datetime.datetime(2000 + i + 1, 1, 1) @@ -164,6 +173,7 @@ class SpatioTemporalTopologyBuilder: ... check = mapB.set_absolute_time(start, end) ... mapsA.append(mapA) ... mapsB.append(mapB) + ... >>> # Build the topology between the two map lists >>> tb = SpatioTemporalTopologyBuilder() >>> tb.build(mapsA, mapsB, None) @@ -174,6 +184,7 @@ class SpatioTemporalTopologyBuilder: ... for key in m.keys(): ... if key not in ["NEXT", "PREV"]: ... print((key, m[key][0].get_temporal_extent_as_tuple())) + ... (datetime.datetime(2000, 1, 1, 0, 0), datetime.datetime(2001, 1, 1, 0, 0)) ('PRECEDES', (datetime.datetime(2001, 1, 1, 0, 0), datetime.datetime(2002, 1, 1, 0, 0))) (datetime.datetime(2001, 1, 1, 0, 0), datetime.datetime(2002, 1, 1, 0, 0)) @@ -191,9 +202,9 @@ class SpatioTemporalTopologyBuilder: >>> mapsA = [] >>> mapsB = [] >>> for i in range(4): - ... idA = "a%i@B"%(i) + ... idA = "a%i@B" % (i) ... mapA = tgis.RasterDataset(idA) - ... idB = "b%i@B"%(i) + ... idB = "b%i@B" % (i) ... mapB = tgis.RasterDataset(idB) ... start = datetime.datetime(2000 + i, 1, 1) ... end = datetime.datetime(2000 + i + 1, 1, 1) @@ -203,6 +214,7 @@ class SpatioTemporalTopologyBuilder: ... check = mapB.set_absolute_time(start, end) ... mapsA.append(mapA) ... mapsB.append(mapB) + ... >>> # Build the topology between the two map lists >>> tb = SpatioTemporalTopologyBuilder() >>> tb.build(mapsA, mapsB, None) @@ -213,6 +225,7 @@ class SpatioTemporalTopologyBuilder: ... for key in m.keys(): ... if key not in ["NEXT", "PREV"]: ... print((key, m[key][0].get_temporal_extent_as_tuple())) + ... (datetime.datetime(2000, 1, 1, 0, 0), datetime.datetime(2001, 1, 1, 0, 0)) ('DURING', (datetime.datetime(2000, 1, 1, 0, 0), datetime.datetime(2003, 1, 1, 0, 0))) ('STARTS', (datetime.datetime(2000, 1, 1, 0, 0), datetime.datetime(2003, 1, 1, 0, 0))) @@ -235,9 +248,9 @@ class SpatioTemporalTopologyBuilder: >>> mapsA = [] >>> mapsB = [] >>> for i in range(4): - ... idA = "a%i@B"%(i) + ... idA = "a%i@B" % (i) ... mapA = tgis.RasterDataset(idA) - ... idB = "b%i@B"%(i) + ... idB = "b%i@B" % (i) ... mapB = tgis.RasterDataset(idB) ... start = datetime.datetime(2000 + i, 1, 1) ... end = datetime.datetime(2000 + i + 2, 1, 1) @@ -247,6 +260,7 @@ class SpatioTemporalTopologyBuilder: ... check = mapB.set_absolute_time(start, end) ... mapsA.append(mapA) ... mapsB.append(mapB) + ... >>> # Build the topology between the two map lists >>> tb = SpatioTemporalTopologyBuilder() >>> tb.build(mapsA, mapsB, None) @@ -257,6 +271,7 @@ class SpatioTemporalTopologyBuilder: ... for key in m.keys(): ... if key not in ["NEXT", "PREV"]: ... print((key, m[key][0].get_temporal_extent_as_tuple())) + ... (datetime.datetime(2000, 1, 1, 0, 0), datetime.datetime(2002, 1, 1, 0, 0)) ('OVERLAPS', (datetime.datetime(2001, 1, 1, 0, 0), datetime.datetime(2004, 1, 1, 0, 0))) ('DURING', (datetime.datetime(2000, 1, 1, 0, 0), datetime.datetime(2003, 1, 1, 0, 0))) @@ -284,9 +299,9 @@ class SpatioTemporalTopologyBuilder: >>> mapsA = [] >>> mapsB = [] >>> for i in range(4): - ... idA = "a%i@B"%(i) + ... idA = "a%i@B" % (i) ... mapA = tgis.RasterDataset(idA) - ... idB = "b%i@B"%(i) + ... idB = "b%i@B" % (i) ... mapB = tgis.RasterDataset(idB) ... start = datetime.datetime(2000, 1, 1, 0, 0, i) ... end = datetime.datetime(2000, 1, 1, 0, 0, i + 2) @@ -296,6 +311,7 @@ class SpatioTemporalTopologyBuilder: ... check = mapB.set_absolute_time(start, end) ... mapsA.append(mapA) ... mapsB.append(mapB) + ... >>> # Build the topology between the two map lists >>> tb = SpatioTemporalTopologyBuilder() >>> tb.build(mapsA, mapsB, None) @@ -306,6 +322,7 @@ class SpatioTemporalTopologyBuilder: ... for key in m.keys(): ... if key not in ["NEXT", "PREV"]: ... print((key, m[key][0].get_temporal_extent_as_tuple())) + ... (datetime.datetime(2000, 1, 1, 0, 0), datetime.datetime(2000, 1, 1, 0, 0, 2)) ('OVERLAPS', (datetime.datetime(2000, 1, 1, 0, 0, 1), datetime.datetime(2000, 1, 1, 0, 0, 3))) ('PRECEDES', (datetime.datetime(2000, 1, 1, 0, 0, 2), datetime.datetime(2000, 1, 1, 0, 0, 4))) @@ -326,12 +343,13 @@ class SpatioTemporalTopologyBuilder: >>> mapsA = [] >>> for i in range(4): - ... idA = "a%i@B"%(i) + ... idA = "a%i@B" % (i) ... mapA = tgis.RasterDataset(idA) ... start = datetime.datetime(2000, 1, 1, 0, 0, i) ... end = datetime.datetime(2000, 1, 1, 0, 0, i + 2) ... check = mapA.set_absolute_time(start, end) ... mapsA.append(mapA) + ... >>> tb = SpatioTemporalTopologyBuilder() >>> tb.build(mapsA) >>> # Check relations of mapsA @@ -341,6 +359,7 @@ class SpatioTemporalTopologyBuilder: ... for key in m.keys(): ... if key not in ["NEXT", "PREV"]: ... print((key, m[key][0].get_temporal_extent_as_tuple())) + ... (datetime.datetime(2000, 1, 1, 0, 0), datetime.datetime(2000, 1, 1, 0, 0, 2)) ('OVERLAPS', (datetime.datetime(2000, 1, 1, 0, 0, 1), datetime.datetime(2000, 1, 1, 0, 0, 3))) ('PRECEDES', (datetime.datetime(2000, 1, 1, 0, 0, 2), datetime.datetime(2000, 1, 1, 0, 0, 4))) @@ -356,7 +375,7 @@ class SpatioTemporalTopologyBuilder: ('FOLLOWS', (datetime.datetime(2000, 1, 1, 0, 0, 1), datetime.datetime(2000, 1, 1, 0, 0, 3))) ('OVERLAPPED', (datetime.datetime(2000, 1, 1, 0, 0, 2), datetime.datetime(2000, 1, 1, 0, 0, 4))) - """ + """ # noqa: E501 def __init__(self): self._reset() @@ -889,70 +908,94 @@ def create_temporal_relation_sql_where_statement( >>> # Relative time >>> start = 1 >>> end = 2 - >>> create_temporal_relation_sql_where_statement(start, end, - ... use_start=False) + >>> create_temporal_relation_sql_where_statement(start, end, use_start=False) >>> create_temporal_relation_sql_where_statement(start, end) '((start_time >= 1 and start_time < 2) )' - >>> create_temporal_relation_sql_where_statement(start, end, - ... use_start=True) + >>> create_temporal_relation_sql_where_statement(start, end, use_start=True) '((start_time >= 1 and start_time < 2) )' - >>> create_temporal_relation_sql_where_statement(start, end, - ... use_start=False, use_during=True) + >>> create_temporal_relation_sql_where_statement( + ... start, end, use_start=False, use_during=True + ... ) '(((start_time > 1 and end_time < 2) OR (start_time >= 1 and end_time < 2) OR (start_time > 1 and end_time <= 2)))' - >>> create_temporal_relation_sql_where_statement(start, end, - ... use_start=False, use_overlap=True) + >>> create_temporal_relation_sql_where_statement( + ... start, end, use_start=False, use_overlap=True + ... ) '(((start_time < 1 and end_time > 1 and end_time < 2) OR (start_time < 2 and start_time > 1 and end_time > 2)))' - >>> create_temporal_relation_sql_where_statement(start, end, - ... use_start=False, use_contain=True) + >>> create_temporal_relation_sql_where_statement( + ... start, end, use_start=False, use_contain=True + ... ) '(((start_time < 1 and end_time > 2) OR (start_time <= 1 and end_time > 2) OR (start_time < 1 and end_time >= 2)))' - >>> create_temporal_relation_sql_where_statement(start, end, - ... use_start=False, use_equal=True) + >>> create_temporal_relation_sql_where_statement( + ... start, end, use_start=False, use_equal=True + ... ) '((start_time = 1 and end_time = 2))' - >>> create_temporal_relation_sql_where_statement(start, end, - ... use_start=False, use_follows=True) + >>> create_temporal_relation_sql_where_statement( + ... start, end, use_start=False, use_follows=True + ... ) '((start_time = 2))' - >>> create_temporal_relation_sql_where_statement(start, end, - ... use_start=False, use_precedes=True) + >>> create_temporal_relation_sql_where_statement( + ... start, end, use_start=False, use_precedes=True + ... ) '((end_time = 1))' - >>> create_temporal_relation_sql_where_statement(start, end, - ... use_start=True, use_during=True, use_overlap=True, use_contain=True, - ... use_equal=True, use_follows=True, use_precedes=True) + >>> create_temporal_relation_sql_where_statement( + ... start, + ... end, + ... use_start=True, + ... use_during=True, + ... use_overlap=True, + ... use_contain=True, + ... use_equal=True, + ... use_follows=True, + ... use_precedes=True, + ... ) '((start_time >= 1 and start_time < 2) OR ((start_time > 1 and end_time < 2) OR (start_time >= 1 and end_time < 2) OR (start_time > 1 and end_time <= 2)) OR ((start_time < 1 and end_time > 1 and end_time < 2) OR (start_time < 2 and start_time > 1 and end_time > 2)) OR ((start_time < 1 and end_time > 2) OR (start_time <= 1 and end_time > 2) OR (start_time < 1 and end_time >= 2)) OR (start_time = 1 and end_time = 2) OR (start_time = 2) OR (end_time = 1))' >>> # Absolute time >>> start = datetime(2001, 1, 1, 12, 30) >>> end = datetime(2001, 3, 31, 14, 30) - >>> create_temporal_relation_sql_where_statement(start, end, - ... use_start=False) + >>> create_temporal_relation_sql_where_statement(start, end, use_start=False) >>> create_temporal_relation_sql_where_statement(start, end) "((start_time >= '2001-01-01 12:30:00' and start_time < '2001-03-31 14:30:00') )" - >>> create_temporal_relation_sql_where_statement(start, end, - ... use_start=True) + >>> create_temporal_relation_sql_where_statement(start, end, use_start=True) "((start_time >= '2001-01-01 12:30:00' and start_time < '2001-03-31 14:30:00') )" - >>> create_temporal_relation_sql_where_statement(start, end, - ... use_start=False, use_during=True) + >>> create_temporal_relation_sql_where_statement( + ... start, end, use_start=False, use_during=True + ... ) "(((start_time > '2001-01-01 12:30:00' and end_time < '2001-03-31 14:30:00') OR (start_time >= '2001-01-01 12:30:00' and end_time < '2001-03-31 14:30:00') OR (start_time > '2001-01-01 12:30:00' and end_time <= '2001-03-31 14:30:00')))" - >>> create_temporal_relation_sql_where_statement(start, end, - ... use_start=False, use_overlap=True) + >>> create_temporal_relation_sql_where_statement( + ... start, end, use_start=False, use_overlap=True + ... ) "(((start_time < '2001-01-01 12:30:00' and end_time > '2001-01-01 12:30:00' and end_time < '2001-03-31 14:30:00') OR (start_time < '2001-03-31 14:30:00' and start_time > '2001-01-01 12:30:00' and end_time > '2001-03-31 14:30:00')))" - >>> create_temporal_relation_sql_where_statement(start, end, - ... use_start=False, use_contain=True) + >>> create_temporal_relation_sql_where_statement( + ... start, end, use_start=False, use_contain=True + ... ) "(((start_time < '2001-01-01 12:30:00' and end_time > '2001-03-31 14:30:00') OR (start_time <= '2001-01-01 12:30:00' and end_time > '2001-03-31 14:30:00') OR (start_time < '2001-01-01 12:30:00' and end_time >= '2001-03-31 14:30:00')))" - >>> create_temporal_relation_sql_where_statement(start, end, - ... use_start=False, use_equal=True) + >>> create_temporal_relation_sql_where_statement( + ... start, end, use_start=False, use_equal=True + ... ) "((start_time = '2001-01-01 12:30:00' and end_time = '2001-03-31 14:30:00'))" - >>> create_temporal_relation_sql_where_statement(start, end, - ... use_start=False, use_follows=True) + >>> create_temporal_relation_sql_where_statement( + ... start, end, use_start=False, use_follows=True + ... ) "((start_time = '2001-03-31 14:30:00'))" - >>> create_temporal_relation_sql_where_statement(start, end, - ... use_start=False, use_precedes=True) + >>> create_temporal_relation_sql_where_statement( + ... start, end, use_start=False, use_precedes=True + ... ) "((end_time = '2001-01-01 12:30:00'))" - >>> create_temporal_relation_sql_where_statement(start, end, - ... use_start=True, use_during=True, use_overlap=True, use_contain=True, - ... use_equal=True, use_follows=True, use_precedes=True) + >>> create_temporal_relation_sql_where_statement( + ... start, + ... end, + ... use_start=True, + ... use_during=True, + ... use_overlap=True, + ... use_contain=True, + ... use_equal=True, + ... use_follows=True, + ... use_precedes=True, + ... ) "((start_time >= '2001-01-01 12:30:00' and start_time < '2001-03-31 14:30:00') OR ((start_time > '2001-01-01 12:30:00' and end_time < '2001-03-31 14:30:00') OR (start_time >= '2001-01-01 12:30:00' and end_time < '2001-03-31 14:30:00') OR (start_time > '2001-01-01 12:30:00' and end_time <= '2001-03-31 14:30:00')) OR ((start_time < '2001-01-01 12:30:00' and end_time > '2001-01-01 12:30:00' and end_time < '2001-03-31 14:30:00') OR (start_time < '2001-03-31 14:30:00' and start_time > '2001-01-01 12:30:00' and end_time > '2001-03-31 14:30:00')) OR ((start_time < '2001-01-01 12:30:00' and end_time > '2001-03-31 14:30:00') OR (start_time <= '2001-01-01 12:30:00' and end_time > '2001-03-31 14:30:00') OR (start_time < '2001-01-01 12:30:00' and end_time >= '2001-03-31 14:30:00')) OR (start_time = '2001-01-01 12:30:00' and end_time = '2001-03-31 14:30:00') OR (start_time = '2001-03-31 14:30:00') OR (end_time = '2001-01-01 12:30:00'))" - """ + """ # noqa: E501 where = "(" diff --git a/python/grass/temporal/temporal_algebra.py b/python/grass/temporal/temporal_algebra.py index b8f71ff0655..db35f03f071 100644 --- a/python/grass/temporal/temporal_algebra.py +++ b/python/grass/temporal/temporal_algebra.py @@ -16,7 +16,7 @@ >>> p = tgis.TemporalAlgebraLexer() >>> p.build() >>> p.debug = True - >>> expression = "C = A : B" + >>> expression = "C = A : B" >>> p.test(expression) C = A : B LexToken(NAME,'C',1,0) @@ -24,7 +24,7 @@ LexToken(NAME,'A',1,4) LexToken(T_SELECT,':',1,6) LexToken(NAME,'B',1,8) - >>> expression = "C = test1 !: test2" + >>> expression = "C = test1 !: test2" >>> p.test(expression) C = test1 !: test2 LexToken(NAME,'C',1,0) @@ -32,7 +32,7 @@ LexToken(NAME,'test1',1,4) LexToken(T_NOT_SELECT,'!:',1,10) LexToken(NAME,'test2',1,13) - >>> expression = "C = test1 {:,equal} test2" + >>> expression = "C = test1 {:,equal} test2" >>> p.test(expression) C = test1 {:,equal} test2 LexToken(NAME,'C',1,0) @@ -40,7 +40,7 @@ LexToken(NAME,'test1',1,4) LexToken(T_SELECT_OPERATOR,'{:,equal}',1,10) LexToken(NAME,'test2',1,20) - >>> expression = "C = test1 {!:,equal} test2" + >>> expression = "C = test1 {!:,equal} test2" >>> p.test(expression) C = test1 {!:,equal} test2 LexToken(NAME,'C',1,0) @@ -48,7 +48,7 @@ LexToken(NAME,'test1',1,4) LexToken(T_SELECT_OPERATOR,'{!:,equal}',1,10) LexToken(NAME,'test2',1,21) - >>> expression = "C = test1 # test2" + >>> expression = "C = test1 # test2" >>> p.test(expression) C = test1 # test2 LexToken(NAME,'C',1,0) @@ -56,7 +56,7 @@ LexToken(NAME,'test1',1,4) LexToken(HASH,'#',1,10) LexToken(NAME,'test2',1,12) - >>> expression = "C = test1 {#} test2" + >>> expression = "C = test1 {#} test2" >>> p.test(expression) C = test1 {#} test2 LexToken(NAME,'C',1,0) @@ -64,7 +64,7 @@ LexToken(NAME,'test1',1,4) LexToken(T_HASH_OPERATOR,'{#}',1,10) LexToken(NAME,'test2',1,14) - >>> expression = "C = test1 {#,equal} test2" + >>> expression = "C = test1 {#,equal} test2" >>> p.test(expression) C = test1 {#,equal} test2 LexToken(NAME,'C',1,0) @@ -72,7 +72,7 @@ LexToken(NAME,'test1',1,4) LexToken(T_HASH_OPERATOR,'{#,equal}',1,10) LexToken(NAME,'test2',1,20) - >>> expression = "C = test1 {#,equal|during} test2" + >>> expression = "C = test1 {#,equal|during} test2" >>> p.test(expression) C = test1 {#,equal|during} test2 LexToken(NAME,'C',1,0) @@ -80,7 +80,7 @@ LexToken(NAME,'test1',1,4) LexToken(T_HASH_OPERATOR,'{#,equal|during}',1,10) LexToken(NAME,'test2',1,27) - >>> expression = "E = test1 : test2 !: test1" + >>> expression = "E = test1 : test2 !: test1" >>> p.test(expression) E = test1 : test2 !: test1 LexToken(NAME,'E',1,0) @@ -90,7 +90,7 @@ LexToken(NAME,'test2',1,12) LexToken(T_NOT_SELECT,'!:',1,18) LexToken(NAME,'test1',1,21) - >>> expression = 'D = buff_t(test1,"10 months")' + >>> expression = 'D = buff_t(test1,"10 months")' >>> p.test(expression) D = buff_t(test1,"10 months") LexToken(NAME,'D',1,0) @@ -104,7 +104,7 @@ LexToken(NAME,'months',1,21) LexToken(QUOTE,'"',1,27) LexToken(RPAREN,')',1,28) - >>> expression = 'H = tsnap(test1)' + >>> expression = "H = tsnap(test1)" >>> p.test(expression) H = tsnap(test1) LexToken(NAME,'H',1,0) @@ -113,7 +113,7 @@ LexToken(LPAREN,'(',1,9) LexToken(NAME,'test1',1,10) LexToken(RPAREN,')',1,15) - >>> expression = 'H = tsnap(test2 {:,during} buff_t(test1, "1 days"))' + >>> expression = 'H = tsnap(test2 {:,during} buff_t(test1, "1 days"))' >>> p.test(expression) H = tsnap(test2 {:,during} buff_t(test1, "1 days")) LexToken(NAME,'H',1,0) @@ -132,7 +132,7 @@ LexToken(QUOTE,'"',1,48) LexToken(RPAREN,')',1,49) LexToken(RPAREN,')',1,50) - >>> expression = 'H = tshift(test2 {:,during} buff_t(test1, "1 days"), "1 months")' + >>> expression = 'H = tshift(test2 {:,during} buff_t(test1, "1 days"), "1 months")' >>> p.test(expression) H = tshift(test2 {:,during} buff_t(test1, "1 days"), "1 months") LexToken(NAME,'H',1,0) @@ -156,7 +156,7 @@ LexToken(NAME,'months',1,56) LexToken(QUOTE,'"',1,62) LexToken(RPAREN,')',1,63) - >>> expression = 'H = tshift(A , 10)' + >>> expression = "H = tshift(A , 10)" >>> p.test(expression) H = tshift(A , 10) LexToken(NAME,'H',1,0) @@ -167,7 +167,7 @@ LexToken(COMMA,',',1,13) LexToken(INT,10,1,15) LexToken(RPAREN,')',1,17) - >>> expression = 'H = if(td(A) > 10, A)' + >>> expression = "H = if(td(A) > 10, A)" >>> p.test(expression) H = if(td(A) > 10, A) LexToken(NAME,'H',1,0) @@ -183,7 +183,7 @@ LexToken(COMMA,',',1,17) LexToken(NAME,'A',1,19) LexToken(RPAREN,')',1,20) - >>> expression = 'H = if(td(A) > 10, A, B)' + >>> expression = "H = if(td(A) > 10, A, B)" >>> p.test(expression) H = if(td(A) > 10, A, B) LexToken(NAME,'H',1,0) @@ -201,7 +201,7 @@ LexToken(COMMA,',',1,20) LexToken(NAME,'B',1,22) LexToken(RPAREN,')',1,23) - >>> expression = 'I = if(equals,td(A) > 10 {||,equals} td(B) < 10, A)' + >>> expression = "I = if(equals,td(A) > 10 {||,equals} td(B) < 10, A)" >>> p.test(expression) I = if(equals,td(A) > 10 {||,equals} td(B) < 10, A) LexToken(NAME,'I',1,0) @@ -226,7 +226,7 @@ LexToken(COMMA,',',1,47) LexToken(NAME,'A',1,49) LexToken(RPAREN,')',1,50) - >>> expression = 'I = if(equals,td(A) > 10 || start_day() < 10, A)' + >>> expression = "I = if(equals,td(A) > 10 || start_day() < 10, A)" >>> p.test(expression) I = if(equals,td(A) > 10 || start_day() < 10, A) LexToken(NAME,'I',1,0) @@ -251,7 +251,7 @@ LexToken(COMMA,',',1,44) LexToken(NAME,'A',1,46) LexToken(RPAREN,')',1,47) - >>> expression = 'E = if({equals},td(A) >= 4 {&&,contain} td(B) == 2, C : D)' + >>> expression = "E = if({equals},td(A) >= 4 {&&,contain} td(B) == 2, C : D)" >>> p.test(expression) E = if({equals},td(A) >= 4 {&&,contain} td(B) == 2, C : D) LexToken(NAME,'E',1,0) @@ -278,7 +278,7 @@ LexToken(T_SELECT,':',1,54) LexToken(NAME,'D',1,56) LexToken(RPAREN,')',1,57) - >>> expression = 'F = if({equals},A {#,equal}, B, C : D)' + >>> expression = "F = if({equals},A {#,equal}, B, C : D)" >>> p.test(expression) F = if({equals},A {#,equal}, B, C : D) LexToken(NAME,'F',1,0) @@ -299,14 +299,14 @@ >>> p = tgis.TemporalAlgebraParser() >>> p.run = False >>> p.debug = True - >>> expression = "D = A {!:} B {:,during} C" + >>> expression = "D = A {!:} B {:,during} C" >>> print(expression) D = A {!:} B {:,during} C >>> ret = p.parse(expression) A* = A {!:} B A** = A* {:,during} C D = A** - >>> expression = "D = A {:} B {!:,during} C" + >>> expression = "D = A {:} B {!:,during} C" >>> print(expression) D = A {:} B {!:,during} C >>> ret = p.parse(expression) @@ -315,52 +315,52 @@ D = A** >>> p.run = False >>> p.debug = False - >>> expression = "C = test1 : test2" + >>> expression = "C = test1 : test2" >>> print(expression) C = test1 : test2 - >>> ret = p.parse(expression, 'stvds') - >>> expression = 'D = buff_t(test1,"10 months")' + >>> ret = p.parse(expression, "stvds") + >>> expression = 'D = buff_t(test1,"10 months")' >>> print(expression) D = buff_t(test1,"10 months") - >>> ret = p.parse(expression, 'stvds') - >>> expression = 'E = test2 {:,during} buff_t(test1,"1 days")' + >>> ret = p.parse(expression, "stvds") + >>> expression = 'E = test2 {:,during} buff_t(test1,"1 days")' >>> print(expression) E = test2 {:,during} buff_t(test1,"1 days") - >>> ret = p.parse(expression, 'stvds') - >>> expression = 'F = test2 {:,equal} buff_t(test1,"1 days")' + >>> ret = p.parse(expression, "stvds") + >>> expression = 'F = test2 {:,equal} buff_t(test1,"1 days")' >>> print(expression) F = test2 {:,equal} buff_t(test1,"1 days") - >>> ret = p.parse(expression, 'stvds') + >>> ret = p.parse(expression, "stvds") >>> p.debug = True - >>> expression = 'H = tsnap(test2 {:,during} buff_t(test1, "1 days"))' - >>> ret = p.parse(expression, 'stvds') + >>> expression = 'H = tsnap(test2 {:,during} buff_t(test1, "1 days"))' + >>> ret = p.parse(expression, "stvds") test1* = buff_t( test1 , " 1 days " ) test2* = test2 {:,during} test1* test2** = tsnap( test2* ) H = test2** - >>> expression = 'H = tshift(test2 {:,during} test1, "1 days")' - >>> ret = p.parse(expression, 'stvds') + >>> expression = 'H = tshift(test2 {:,during} test1, "1 days")' + >>> ret = p.parse(expression, "stvds") test2* = test2 {:,during} test1 test2** = tshift( test2* , " 1 days " ) H = test2** - >>> expression = 'H = tshift(H, 3)' - >>> ret = p.parse(expression, 'stvds') + >>> expression = "H = tshift(H, 3)" + >>> ret = p.parse(expression, "stvds") H* = tshift( H , 3 ) H = H* - >>> expression = 'C = if(td(A) == 2, A)' - >>> ret = p.parse(expression, 'stvds') + >>> expression = "C = if(td(A) == 2, A)" + >>> ret = p.parse(expression, "stvds") td(A) td(A) == 2 A* = if condition None then A C = A* - >>> expression = 'C = if(td(A) == 5, A, B)' - >>> ret = p.parse(expression, 'stvds') + >>> expression = "C = if(td(A) == 5, A, B)" + >>> ret = p.parse(expression, "stvds") td(A) td(A) == 5 A* = if condition None then A else B C = A* - >>> expression = 'C = if(td(A) == 5 || start_date(A) > "2010-01-01", A, B)' - >>> ret = p.parse(expression, 'stvds') + >>> expression = 'C = if(td(A) == 5 || start_date(A) > "2010-01-01", A, B)' + >>> ret = p.parse(expression, "stvds") td(A) td(A) == 5 start_date A > "2010-01-01" @@ -371,7 +371,7 @@ >>> p = tgis.TemporalAlgebraLexer() >>> p.build() >>> p.debug = True - >>> expression = "D = strds(A) : stvds(B) : str3ds(C)" + >>> expression = "D = strds(A) : stvds(B) : str3ds(C)" >>> p.test(expression) D = strds(A) : stvds(B) : str3ds(C) LexToken(NAME,'D',1,0) @@ -394,7 +394,7 @@ >>> p = tgis.TemporalAlgebraLexer() >>> p.build() >>> p.debug = True - >>> expression = "R = if(A {#,during} stvds(C) == 1, A)" + >>> expression = "R = if(A {#,during} stvds(C) == 1, A)" >>> p.test(expression) R = if(A {#,during} stvds(C) == 1, A) LexToken(NAME,'R',1,0) @@ -416,7 +416,7 @@ >>> p = tgis.TemporalAlgebraLexer() >>> p.build() >>> p.debug = True - >>> expression = "R = if({during}, stvds(C) {#,contains} A == 2, A)" + >>> expression = "R = if({during}, stvds(C) {#,contains} A == 2, A)" >>> p.test(expression) R = if({during}, stvds(C) {#,contains} A == 2, A) LexToken(NAME,'R',1,0) @@ -525,7 +525,8 @@ class TemporalAlgebraLexer: # and in relative units in case of relative time. # The end_time() will be represented by null() in case of a time instance. "start_doy": "START_DOY", # Day of year (doy) from the start time [1 - 366] - "start_dow": "START_DOW", # Day of week (dow) from the start time [1 - 7], the start of the week is Monday == 1 + "start_dow": "START_DOW", # Day of week (dow) from the start time [1 - 7], + # the start of the week is Monday == 1 "start_year": "START_YEAR", # The year of the start time [0 - 9999] "start_month": "START_MONTH", # The month of the start time [1 - 12] "start_week": "START_WEEK", # Week of year of the start time [1 - 54] @@ -534,7 +535,8 @@ class TemporalAlgebraLexer: "start_minute": "START_MINUTE", # The minute of the start time [0 - 59] "start_second": "START_SECOND", # The second of the start time [0 - 59] "end_doy": "END_DOY", # Day of year (doy) from the end time [1 - 366] - "end_dow": "END_DOW", # Day of week (dow) from the end time [1 - 7], the start of the week is Monday == 1 + "end_dow": "END_DOW", # Day of week (dow) from the end time [1 - 7], the + # start of the week is Monday == 1 "end_year": "END_YEAR", # The year of the end time [0 - 9999] "end_month": "END_MONTH", # The month of the end time [1 - 12] "end_week": "END_WEEK", # Week of year of the end time [1 - 54] @@ -583,11 +585,9 @@ class TemporalAlgebraLexer: ) # Regular expression rules for simple tokens - t_T_SELECT_OPERATOR = r"\{[!]?[:][,]?[a-zA-Z\| ]*([,])?([lrudi]|left|right|union|disjoint|intersect)?\}" - t_T_HASH_OPERATOR = ( - r"\{[#][,]?[a-zA-Z\| ]*([,])?([lrudi]|left|right|union|disjoint|intersect)?\}" - ) - t_T_COMP_OPERATOR = r"\{(\|\||&&)[,][a-zA-Z\| ]*[,]?[\|&]?([,])?([lrudi]|left|right|union|disjoint|intersect)?\}" + t_T_SELECT_OPERATOR = r"\{[!]?[:][,]?[a-zA-Z\| ]*([,])?([lrudi]|left|right|union|disjoint|intersect)?\}" # noqa: E501 + t_T_HASH_OPERATOR = r"\{[#][,]?[a-zA-Z\| ]*([,])?([lrudi]|left|right|union|disjoint|intersect)?\}" # noqa: E501 + t_T_COMP_OPERATOR = r"\{(\|\||&&)[,][a-zA-Z\| ]*[,]?[\|&]?([,])?([lrudi]|left|right|union|disjoint|intersect)?\}" # noqa: E501 t_T_REL_OPERATOR = r"\{([a-zA-Z\| ])+\}" t_T_SELECT = r":" t_T_NOT_SELECT = r"!:" @@ -611,7 +611,7 @@ class TemporalAlgebraLexer: # Read time string and convert it into a date object def t_DATETIME(self, t): - r'"\d\d\d\d-(0[1-9]|1[012])-(0[1-9]|[12][0-9]|3[01])[ T](0[0-9]|1(0-9)|2[0-4]):(0[0-9]|[1-5][0-9]|60):(0[0-9]|[1-5][0-9]|60)"' + r'"\d\d\d\d-(0[1-9]|1[012])-(0[1-9]|[12][0-9]|3[01])[ T](0[0-9]|1(0-9)|2[0-4]):(0[0-9]|[1-5][0-9]|60):(0[0-9]|[1-5][0-9]|60)"' # noqa: E501 # t.value = int(t.value) return t @@ -790,18 +790,15 @@ def __init__( time_suffix=None, ): self.run = run - self.dry_run = ( - dry_run # Compute the processes and output but Do not start the processes - ) - self.process_chain_dict = ( - {} - ) # This dictionary stores all processes, as well as the maps to register and remove - self.process_chain_dict["processes"] = ( - [] - ) # The mapcalc and v.patch module calls - self.process_chain_dict["register"] = ( - [] - ) # Maps that must be registered/updated or inserted in a new STDS + # Compute the processes and output but Do not start the processes + self.dry_run = dry_run + # This dictionary stores all processes, as well as the maps to register and + # remove + self.process_chain_dict = {} + # The mapcalc and v.patch module calls + self.process_chain_dict["processes"] = [] + # Maps that must be registered/updated or inserted in a new STDS + self.process_chain_dict["register"] = [] self.process_chain_dict["remove"] = [] # The g.remove module calls self.process_chain_dict["STDS"] = {} # The STDS that must be created @@ -856,7 +853,8 @@ def setup_common_granularity(self, expression, stdstype="strds", lexer=None): space time datasets in the expression to generate the map lists. This function will analyze the expression to detect space time datasets - and computes the common granularity from all granularities of the input space time datasets. + and computes the common granularity from all granularities of the input space + time datasets. This granularity is then be used to generate the map lists. Hence, all maps from all STDS will have equidistant temporal extents. The only meaningful @@ -864,8 +862,9 @@ def setup_common_granularity(self, expression, stdstype="strds", lexer=None): :param expression: The algebra expression to analyze - :param lexer: The temporal algebra lexer (select, raster, voxel, vector) that should be used to - parse the expression, default is TemporalAlgebraLexer + :param lexer: The temporal algebra lexer (select, raster, voxel, vector) that + should be used to parse the expression, default is + TemporalAlgebraLexer :return: True if successful, False otherwise """ @@ -921,7 +920,8 @@ def setup_common_granularity(self, expression, stdstype="strds", lexer=None): if stds.check_temporal_topology() is False: self.msgr.error( _( - "All input space time datasets must have a valid temporal topology." + "All input space time datasets must have a valid temporal " + "topology." ) ) return False @@ -1010,7 +1010,8 @@ def generate_new_map( copied to mapA :param rename: Specifies if the generated map get a random name or get the id from the base map. - :param remove: Set this True if this map is an intermediate or empty map that should be removed + :param remove: Set this True if this map is an intermediate or empty map that + should be removed :return: Map object """ # Generate an intermediate name for the result map list. @@ -1126,7 +1127,8 @@ def set_temporal_extent_list(self, maplist, topolist=["EQUAL"], temporal="l"): map_new = self.generate_new_map( base_map=map_i, bool_op="and", copy=True, rename=True ) - # Combine temporal and spatial extents of intermediate map with related maps. + # Combine temporal and spatial extents of intermediate map with related + # maps. for topo in topolist: if topo in tbrelations.keys(): for map_j in tbrelations[topo]: @@ -1150,21 +1152,22 @@ def set_temporal_extent_list(self, maplist, topolist=["EQUAL"], temporal="l"): ) if self.debug: print(map_new.get_id(), map_j.get_id()) - # Stop the loop if no temporal or spatial relationship exist. + # Stop the loop if no temporal or spatial relationship + # exist. if returncode == 0: break # Append map to result map list. elif returncode == 1: - # print(map_new.get_id() + " " + str(map_new.get_temporal_extent_as_tuple())) + # print(map_new.get_id() + " " + + # str(map_new.get_temporal_extent_as_tuple())) # print(map_new.condition_value) # print(map_new.cmd_list) # resultlist.append(map_new) resultdict[map_new.get_id()] = map_new # Create r.mapcalc expression string for the operation. - # cmdstring = self.build_command_string(s_expr_a = map_new, - # s_expr_b = map_j, - # operator = function) + # cmdstring = self.build_command_string( + # s_expr_a = map_new, s_expr_b = map_j, operator = function) # Conditional append of module command. # map_new.cmd_list = cmdstring if returncode == 0: @@ -1221,9 +1224,10 @@ def check_stds(self, input, clear=False, stds_type=None, check_type=True): :param input: Name of space time data set as string or list of maps. :param clear: Reset the stored conditional values to empty list. - :param check_type: Check the type of the space time dataset to match the global stds type - :param stds_type: The type of the space time dataset to be opened, if not provided - then self.stdstype will be used + :param check_type: Check the type of the space time dataset to match the global + stds type + :param stds_type: The type of the space time dataset to be opened, if not + provided then self.stdstype will be used :return: List of maps. """ @@ -1273,16 +1277,16 @@ def check_stds(self, input, clear=False, stds_type=None, check_type=True): elif map_i.is_time_absolute() and self.temporaltype == "relative": self.msgr.fatal( _( - "Wrong temporal type of space time dataset <%s> \ - <%s> time is required" + "Wrong temporal type of space time dataset " + "<%s> <%s> time is required" ) % (id_input, self.temporaltype) ) elif map_i.is_time_relative() and self.temporaltype == "absolute": self.msgr.fatal( _( - "Wrong temporal type of space time dataset <%s> \ - <%s> time is required" + "Wrong temporal type of space time dataset " + "<%s> <%s> time is required" ) % (id_input, self.temporaltype) ) @@ -1321,7 +1325,8 @@ def _check_spatial_topology_entries(self, spatial_topo_list, spatial_relations): Return True if no spatial relation list is provided or if one spatial relation was found - :param spatial_topo_list: The spatial relations that were defined in the expression + :param spatial_topo_list: The spatial relations that were defined in the + expression :param spatial_relations: The spatial relations of a single map object :return: True if a spatial topological relation was found, False if not @@ -1342,8 +1347,8 @@ def _check_spatial_topology_entries(self, spatial_topo_list, spatial_relations): return spatial_topo_check def _check_spatial_topology_relation(self, spatial_topo_list, map_a, map_b): - """Check if map_b has one of the spatial topological relations to map_a that is defined - in spatial_topo_list + """Check if map_b has one of the spatial topological relations to map_a that is + defined in spatial_topo_list :param spatial_topo_list: :param map_a: @@ -1373,9 +1378,11 @@ def _check_topology(self, topolist): :param topolist: List of strings of temporal and spatial relations. - :return: A tuple of spatial and temporal topology lists (temporal_topo_list, spatial_topo_list) + :return: A tuple of spatial and temporal topology lists + (temporal_topo_list, spatial_topo_list) - :raises: This method will raise a syntax error in case the topology name is unknown + :raises: This method will raise a syntax error in case the topology name is + unknown """ temporal_topo_list = [] spatial_topo_list = [] @@ -1429,7 +1436,7 @@ def build_spatio_temporal_topology_list( .. code-block:: python - # Example with two lists of maps + >>> # Example with two lists of maps >>> import grass.temporal as tgis >>> tgis.init(True) >>> l = tgis.TemporalAlgebraParser() @@ -1437,22 +1444,28 @@ def build_spatio_temporal_topology_list( >>> mapsA = [] >>> mapsB = [] >>> for i in range(10): - ... idA = "a%i@B"%(i) + ... idA = "a%i@B" % (i) ... mapA = tgis.RasterDataset(idA) ... mapA.uid = idA - ... idB = "b%i@B"%(i) + ... idB = "b%i@B" % (i) ... mapB = tgis.RasterDataset(idB) ... mapB.uid = idB ... check = mapA.set_relative_time(i, i + 1, "months") ... check = mapB.set_relative_time(i, i + 1, "months") ... mapsA.append(mapA) ... mapsB.append(mapB) - >>> resultlist = l.build_spatio_temporal_topology_list(mapsA, mapsB, ['EQUAL']) + ... + >>> resultlist = l.build_spatio_temporal_topology_list( + ... mapsA, mapsB, ["EQUAL"] + ... ) >>> for map in resultlist: ... if map.get_equal(): ... relations = map.get_equal() - ... print("Map %s has equal relation to map %s"%(map.get_name(), - ... relations[0].get_name())) + ... print( + ... "Map %s has equal relation to map %s" + ... % (map.get_name(), relations[0].get_name()) + ... ) + ... Map a0 has equal relation to map b0 Map a1 has equal relation to map b1 Map a2 has equal relation to map b2 @@ -1463,29 +1476,37 @@ def build_spatio_temporal_topology_list( Map a7 has equal relation to map b7 Map a8 has equal relation to map b8 Map a9 has equal relation to map b9 - >>> resultlist = l.build_spatio_temporal_topology_list(mapsA, mapsB, ['DURING']) + >>> resultlist = l.build_spatio_temporal_topology_list( + ... mapsA, mapsB, ["DURING"] + ... ) >>> print(resultlist) [] >>> # Create two list of maps with equal time stamps >>> mapsA = [] >>> mapsB = [] >>> for i in range(10): - ... idA = "a%i@B"%(i) + ... idA = "a%i@B" % (i) ... mapA = tgis.RasterDataset(idA) ... mapA.uid = idA - ... idB = "b%i@B"%(i) + ... idB = "b%i@B" % (i) ... mapB = tgis.RasterDataset(idB) ... mapB.uid = idB ... check = mapA.set_relative_time(i, i + 1, "months") ... check = mapB.set_relative_time(i, i + 2, "months") ... mapsA.append(mapA) ... mapsB.append(mapB) - >>> resultlist = l.build_spatio_temporal_topology_list(mapsA, mapsB, ['starts','during']) + ... + >>> resultlist = l.build_spatio_temporal_topology_list( + ... mapsA, mapsB, ["starts", "during"] + ... ) >>> for map in resultlist: ... if map.get_starts(): ... relations = map.get_starts() - ... print("Map %s has start relation to map %s"%(map.get_name(), - ... relations[0].get_name())) + ... print( + ... "Map %s has start relation to map %s" + ... % (map.get_name(), relations[0].get_name()) + ... ) + ... Map a0 has start relation to map b0 Map a1 has start relation to map b1 Map a2 has start relation to map b2 @@ -1499,8 +1520,11 @@ def build_spatio_temporal_topology_list( >>> for map in resultlist: ... if map.get_during(): ... relations = map.get_during() - ... print("Map %s has during relation to map %s"%(map.get_name(), - ... relations[0].get_name())) + ... print( + ... "Map %s has during relation to map %s" + ... % (map.get_name(), relations[0].get_name()) + ... ) + ... Map a0 has during relation to map b0 Map a1 has during relation to map b0 Map a2 has during relation to map b1 @@ -1515,10 +1539,10 @@ def build_spatio_temporal_topology_list( >>> mapsA = [] >>> mapsB = [] >>> for i in range(10): - ... idA = "a%i@B"%(i) + ... idA = "a%i@B" % (i) ... mapA = tgis.RasterDataset(idA) ... mapA.uid = idA - ... idB = "b%i@B"%(i) + ... idB = "b%i@B" % (i) ... mapB = tgis.RasterDataset(idB) ... mapB.uid = idB ... check = mapA.set_relative_time(i, i + 1, "months") @@ -1526,35 +1550,43 @@ def build_spatio_temporal_topology_list( ... mapB.map_value = True ... mapsA.append(mapA) ... mapsB.append(mapB) + ... >>> # Create two list of maps with equal time stamps >>> mapsA = [] >>> mapsB = [] >>> for i in range(10): - ... idA = "a%i@B"%(i) + ... idA = "a%i@B" % (i) ... mapA = tgis.RasterDataset(idA) ... mapA.uid = idA ... mapA.map_value = True - ... idB = "b%i@B"%(i) + ... idB = "b%i@B" % (i) ... mapB = tgis.RasterDataset(idB) ... mapB.uid = idB ... mapB.map_value = False - ... check = mapA.set_absolute_time(datetime(2000,1,i+1), - ... datetime(2000,1,i + 2)) - ... check = mapB.set_absolute_time(datetime(2000,1,i+6), - ... datetime(2000,1,i + 7)) + ... check = mapA.set_absolute_time( + ... datetime(2000, 1, i + 1), datetime(2000, 1, i + 2) + ... ) + ... check = mapB.set_absolute_time( + ... datetime(2000, 1, i + 6), datetime(2000, 1, i + 7) + ... ) ... mapsA.append(mapA) ... mapsB.append(mapB) + ... >>> resultlist = l.build_spatio_temporal_topology_list(mapsA, mapsB) >>> for map in resultlist: ... print(map.get_id()) + ... a5@B a6@B a7@B a8@B a9@B - >>> resultlist = l.build_spatio_temporal_topology_list(mapsA, mapsB, ['during']) + >>> resultlist = l.build_spatio_temporal_topology_list( + ... mapsA, mapsB, ["during"] + ... ) >>> for map in resultlist: ... print(map.get_id()) + ... """ # Check the topology definitions and return the list of temporal and spatial @@ -1678,7 +1710,8 @@ def compare_bool_value( temporal_relations = map_i.get_temporal_relations() - # Build conditional list with elements from related maps and given relation operator. + # Build conditional list with elements from related maps and given relation + # operator. leftbool = map_i.condition_value[0] condition_value_list = [leftbool] count = 0 @@ -1737,7 +1770,7 @@ def eval_toperator(self, operator, optype="relation"): >>> tgis.init() >>> p = tgis.TemporalOperatorParser() >>> operator = "{+, during}" - >>> p.parse(operator, optype = 'raster') + >>> p.parse(operator, optype="raster") >>> print((p.relations, p.temporal, p.function)) (['during'], 'l', '+') @@ -1776,33 +1809,41 @@ def perform_temporal_selection( >>> mapsA = [] >>> mapsB = [] >>> for i in range(10): - ... idA = "a%i@B"%(i) + ... idA = "a%i@B" % (i) ... mapA = tgis.RasterDataset(idA) ... mapA.uid = idA - ... idB = "b%i@B"%(i) + ... idB = "b%i@B" % (i) ... mapB = tgis.RasterDataset(idB) ... mapB.uid = idB ... check = mapA.set_relative_time(i, i + 1, "months") ... check = mapB.set_relative_time(i + 5, i + 6, "months") ... mapsA.append(mapA) ... mapsB.append(mapB) - >>> resultlist = l.perform_temporal_selection(mapsA, mapsB, ['EQUAL'], - ... False) + ... + >>> resultlist = l.perform_temporal_selection( + ... mapsA, mapsB, ["EQUAL"], False + ... ) >>> for map in resultlist: ... if map.get_equal(): ... relations = map.get_equal() - ... print("Map %s has equal relation to map %s"%(map.get_name(), - ... relations[0].get_name())) + ... print( + ... "Map %s has equal relation to map %s" + ... % (map.get_name(), relations[0].get_name()) + ... ) + ... Map a5 has equal relation to map b0 Map a6 has equal relation to map b1 Map a7 has equal relation to map b2 Map a8 has equal relation to map b3 Map a9 has equal relation to map b4 - >>> resultlist = l.perform_temporal_selection(mapsA, mapsB, ['EQUAL'], - ... True) + >>> resultlist = l.perform_temporal_selection(mapsA, mapsB, ["EQUAL"], True) >>> for map in resultlist: ... if not map.get_equal(): - ... print("Map %s has no equal relation to mapset mapsB"%(map.get_name())) + ... print( + ... "Map %s has no equal relation to mapset mapsB" + ... % (map.get_name()) + ... ) + ... Map a0 has no equal relation to mapset mapsB Map a1 has no equal relation to mapset mapsB Map a2 has no equal relation to mapset mapsB @@ -1852,20 +1893,26 @@ def set_granularity(self, maplistA, maplistB, toperator="l", topolist=["EQUAL"]) >>> mapsA = [] >>> mapsB = [] >>> for i in range(10): - ... idA = "a%i@B"%(i) + ... idA = "a%i@B" % (i) ... mapA = tgis.RasterDataset(idA) ... mapA.uid = idA - ... idB = "b%i@B"%(i) + ... idB = "b%i@B" % (i) ... mapB = tgis.RasterDataset(idB) ... mapB.uid = idB ... check = mapA.set_relative_time(i, i + 1, "months") - ... check = mapB.set_relative_time(i*2, i*2 + 2, "months") + ... check = mapB.set_relative_time(i * 2, i * 2 + 2, "months") ... mapsA.append(mapA) ... mapsB.append(mapB) - >>> resultlist = p.set_granularity(mapsA, mapsB, toperator = "u", topolist = ["during"]) + ... + >>> resultlist = p.set_granularity( + ... mapsA, mapsB, toperator="u", topolist=["during"] + ... ) >>> for map in resultlist: - ... start,end,unit = map.get_relative_time() - ... print(map.get_id() + ' - start: ' + str(start) + ' end: ' + str(end)) + ... start, end, unit = map.get_relative_time() + ... print( + ... map.get_id() + " - start: " + str(start) + " end: " + str(end) + ... ) + ... a1@B - start: 0 end: 2 a0@B - start: 0 end: 2 a3@B - start: 2 end: 4 @@ -1933,7 +1980,8 @@ def set_granularity(self, maplistA, maplistB, toperator="l", topolist=["EQUAL"]) if newextent is not None: start = newextent.get_start_time() end = newextent.get_end_time() - # print(map_i.get_id() + ' - start: ' + str(start) + ' end: ' + str(end)) + # print(map_i.get_id() + " - start: " + str(start) + # + " end: " + str(end)) # Track changes in temporal extents of maps. if map_start != start or map_end != end: unchanged = False @@ -1982,12 +2030,14 @@ def get_temporal_func_dict(self, map): >>> # Example with one list of maps >>> # Create one list of maps with equal time stamps >>> for i in range(1): - ... idA = "a%i@B"%(i) + ... idA = "a%i@B" % (i) ... mapA = tgis.RasterDataset(idA) ... mapA.uid = idA - ... check = mapA.set_absolute_time(datetime.datetime(2000,1,1), - ... datetime.datetime(2000,10,1)) + ... check = mapA.set_absolute_time( + ... datetime.datetime(2000, 1, 1), datetime.datetime(2000, 10, 1) + ... ) ... tfuncdict = l.get_temporal_func_dict(mapA) + ... >>> print(tfuncdict["START_YEAR"]) 2000 >>> print(tfuncdict["START_TIME"]) @@ -2161,16 +2211,16 @@ def eval_map_list(self, maplist, thenlist, topolist=["EQUAL"]): def build_condition_list(self, tvarexpr, thenlist, topolist=["EQUAL"]): """This function evaluates temporal variable expressions of a conditional expression in two steps. - At first it combines stepwise the single conditions by their relations with LALR. - In this process sub condition map lists will be created which will include - information of the underlying single conditions. Important: The temporal - relations between conditions are evaluated by implicit aggregation. + At first it combines stepwise the single conditions by their relations with + LALR. In this process sub condition map lists will be created which will + include information of the underlying single conditions. Important: The + temporal relations between conditions are evaluated by implicit aggregation. In the second step the aggregated condition map list will be compared with the map list of conclusion statements by the given temporal relation. - The result is written as 'condition_value' attribute to the resulting map objects. - These attribute consists of boolean expressions and operators which can be - evaluated with the eval_condition_list function. + The result is written as 'condition_value' attribute to the resulting map + objects. These attribute consists of boolean expressions and operators which + can be evaluated with the eval_condition_list function. [True, '||', False, '&&', True] For example: td(A) == 1 && start_day() > 5 --> [True || False] @@ -2315,7 +2365,8 @@ def recurse_compare(conditionlist): def p_statement_assign(self, t): # The expression should always return a list of maps - # This function starts all the work and is the last one that is called from the parser + # This function starts all the work and is the last one that is called from the + # parser """ statement : stds EQUALS expr @@ -2353,8 +2404,8 @@ def p_statement_assign(self, t): if maps_stds_type != self.stdstype: self.msgr.warning( _( - "The resulting space time dataset type <%(a)s> is " - "different from the requested type <%(b)s>" + "The resulting space time dataset type <%(a)s> " + "is different from the requested type <%(b)s>" % ({"a": maps_stds_type, "b": self.stdstype}) ) ) @@ -2364,7 +2415,8 @@ def p_statement_assign(self, t): self.msgr.fatal( _( "Maps that should be registered in the " - "resulting space time dataset have different types." + "resulting space time dataset have different " + "types." ) ) count += 1 @@ -2490,7 +2542,8 @@ def p_statement_assign(self, t): if self.dry_run is False: map_i.update_all(dbif) elif map_i.is_in_db(dbif) and self.overwrite is False: - # Raise error if map exists and no overwrite flag is given. + # Raise error if map exists and no overwrite flag is + # given. self.msgr.fatal( "Error map %s exist in temporal database. " "Use overwrite flag." % map_i.get_map_id() @@ -2669,14 +2722,16 @@ def p_expr_tmerge_function(self, t): elif len(maplistA) == 0: self.msgr.message( _( - "First Map list is empty, can't merge it. Return only last map list" + "First Map list is empty, can't merge it. " + "Return only last map list" ) ) resultlist = maplistB elif len(maplistB) == 0: self.msgr.message( _( - "Second Map list is empty, can't merge it. Return only first map list" + "Second Map list is empty, can't merge it. " + "Return only first map list" ) ) resultlist = maplistA @@ -2688,7 +2743,8 @@ def p_expr_tmerge_function(self, t): if typeA != typeB: raise FatalError( _( - "Space time datasets to merge must have the same temporal type" + "Space time datasets to merge must have " + "the same temporal type" ) ) @@ -2832,7 +2888,8 @@ def p_t_var_expr_td_hash(self, t): map_i.condition_value = boolname except: self.msgr.fatal( - "Error: the given expression does not contain a correct time difference object." + "Error: the given expression does not contain a correct time " + "difference object." ) t[0] = maplist @@ -3028,10 +3085,13 @@ def p_expr_t_select_operator(self, t): # Examples: # A {!:} B # Select the part of A that is temporally unequal to B # A { :} B # Select the part of A that is temporally equal B - # A {!:, equals} B # Select the part of A that is temporally unequal to B - # A {!:, during} B # Select the part of A that is temporally not during B + # A {!:, equals} B # Select the part of A that is temporally unequal + # # to B + # A {!:, during} B # Select the part of A that is temporally not + # # during B # A {:, overlaps} B # Select the part of A that temporally overlaps B - # A {:, overlaps|equals} B # Select the part of A that temporally overlaps or equals B + # A {:, overlaps|equals} B # Select the part of A that temporally overlaps + # # or equals B """ expr : stds T_SELECT_OPERATOR stds | expr T_SELECT_OPERATOR stds @@ -3164,7 +3224,8 @@ def p_expr_condition_elif(self, t): def p_expr_condition_elif_relation(self, t): # Examples - # if({equal}, start_date() < "2005-06-01", if(start_time() < "12:30:00", A:B), A!:B) + # if({equal}, start_date() < "2005-06-01", + # if(start_time() < "12:30:00", A:B), A!:B) # The then and else statement using the same topological relationships. # Feature request: Independent relationships for then and else to conditions. """ @@ -3225,7 +3286,8 @@ def p_expr_condition_elif_relation(self, t): def p_expr_t_buff(self, t): # Examples # buff_t(A : B, "10 minutes") # Select the part of A that is temporally - # equal to B and create a buffer of 10 minutes around + # equal to B and create a buffer of 10 minutes + # around """ expr : BUFF_T LPAREN stds COMMA QUOTE number NAME QUOTE RPAREN | BUFF_T LPAREN expr COMMA QUOTE number NAME QUOTE RPAREN @@ -3366,8 +3428,8 @@ def p_error(self, t): # Handle errors. if t: raise SyntaxError( - "syntax error on line %d, position %i token %s near '%s' expression '%s'" - % (t.lineno, t.lexpos, t.type, t.value, self.expression) + "syntax error on line %d, position %i token %s near '%s' expression " + "'%s'" % (t.lineno, t.lexpos, t.type, t.value, self.expression) ) else: raise SyntaxError("Unexpected syntax error") diff --git a/python/grass/temporal/temporal_extent.py b/python/grass/temporal/temporal_extent.py index 066f1697462..b3ce5714c3b 100644 --- a/python/grass/temporal/temporal_extent.py +++ b/python/grass/temporal/temporal_extent.py @@ -41,9 +41,12 @@ class TemporalExtent(SQLDatabaseInterface): .. code-block:: python >>> init() - >>> A = TemporalExtent(table="raster_absolute_time", - ... ident="soil@PERMANENT", start_time=datetime(2001, 01, 01), - ... end_time=datetime(2005,01,01) ) + >>> A = TemporalExtent( + ... table="raster_absolute_time", + ... ident="soil@PERMANENT", + ... start_time=datetime(2001, 1, 1), + ... end_time=datetime(2005, 1, 1), + ... ) >>> A.id 'soil@PERMANENT' >>> A.start_time @@ -57,8 +60,12 @@ class TemporalExtent(SQLDatabaseInterface): start_time='2001-01-01 00:00:00' end_time='2005-01-01 00:00:00' >>> # relative time - >>> A = TemporalExtent(table="raster_absolute_time", - ... ident="soil@PERMANENT", start_time=0, end_time=1 ) + >>> A = TemporalExtent( + ... table="raster_absolute_time", + ... ident="soil@PERMANENT", + ... start_time=0, + ... end_time=1, + ... ) >>> A.id 'soil@PERMANENT' >>> A.start_time @@ -93,14 +100,14 @@ def intersect(self, extent): .. code-block:: python - >>> A = TemporalExtent(start_time=5, end_time=6 ) + >>> A = TemporalExtent(start_time=5, end_time=6) >>> inter = A.intersect(A) >>> inter.print_info() | Start time:................. 5 | End time:................... 6 - >>> A = TemporalExtent(start_time=5, end_time=6 ) - >>> B = TemporalExtent(start_time=5, end_time=7 ) + >>> A = TemporalExtent(start_time=5, end_time=6) + >>> B = TemporalExtent(start_time=5, end_time=7) >>> inter = A.intersect(B) >>> inter.print_info() | Start time:................. 5 @@ -110,8 +117,8 @@ def intersect(self, extent): | Start time:................. 5 | End time:................... 6 - >>> A = TemporalExtent(start_time=3, end_time=6 ) - >>> B = TemporalExtent(start_time=5, end_time=7 ) + >>> A = TemporalExtent(start_time=3, end_time=6) + >>> B = TemporalExtent(start_time=5, end_time=7) >>> inter = A.intersect(B) >>> inter.print_info() | Start time:................. 5 @@ -121,8 +128,8 @@ def intersect(self, extent): | Start time:................. 5 | End time:................... 6 - >>> A = TemporalExtent(start_time=3, end_time=8 ) - >>> B = TemporalExtent(start_time=5, end_time=6 ) + >>> A = TemporalExtent(start_time=3, end_time=8) + >>> B = TemporalExtent(start_time=5, end_time=6) >>> inter = A.intersect(B) >>> inter.print_info() | Start time:................. 5 @@ -132,8 +139,8 @@ def intersect(self, extent): | Start time:................. 5 | End time:................... 6 - >>> A = TemporalExtent(start_time=5, end_time=8 ) - >>> B = TemporalExtent(start_time=3, end_time=6 ) + >>> A = TemporalExtent(start_time=5, end_time=8) + >>> B = TemporalExtent(start_time=3, end_time=6) >>> inter = A.intersect(B) >>> inter.print_info() | Start time:................. 5 @@ -143,8 +150,8 @@ def intersect(self, extent): | Start time:................. 5 | End time:................... 6 - >>> A = TemporalExtent(start_time=5, end_time=None ) - >>> B = TemporalExtent(start_time=3, end_time=6 ) + >>> A = TemporalExtent(start_time=5, end_time=None) + >>> B = TemporalExtent(start_time=3, end_time=6) >>> inter = A.intersect(B) >>> inter.print_info() | Start time:................. 5 @@ -154,14 +161,14 @@ def intersect(self, extent): | Start time:................. 5 | End time:................... None - >>> A = TemporalExtent(start_time=5, end_time=8 ) - >>> B = TemporalExtent(start_time=3, end_time=4 ) + >>> A = TemporalExtent(start_time=5, end_time=8) + >>> B = TemporalExtent(start_time=3, end_time=4) >>> inter = A.intersect(B) >>> print(inter) None - >>> A = TemporalExtent(start_time=5, end_time=8 ) - >>> B = TemporalExtent(start_time=3, end_time=None ) + >>> A = TemporalExtent(start_time=5, end_time=8) + >>> B = TemporalExtent(start_time=3, end_time=None) >>> inter = A.intersect(B) >>> print(inter) None @@ -211,14 +218,14 @@ def disjoint_union(self, extent): .. code-block:: python - >>> A = TemporalExtent(start_time=5, end_time=6 ) + >>> A = TemporalExtent(start_time=5, end_time=6) >>> inter = A.intersect(A) >>> inter.print_info() | Start time:................. 5 | End time:................... 6 - >>> A = TemporalExtent(start_time=5, end_time=6 ) - >>> B = TemporalExtent(start_time=5, end_time=7 ) + >>> A = TemporalExtent(start_time=5, end_time=6) + >>> B = TemporalExtent(start_time=5, end_time=7) >>> inter = A.disjoint_union(B) >>> inter.print_info() | Start time:................. 5 @@ -228,8 +235,8 @@ def disjoint_union(self, extent): | Start time:................. 5 | End time:................... 7 - >>> A = TemporalExtent(start_time=3, end_time=6 ) - >>> B = TemporalExtent(start_time=5, end_time=7 ) + >>> A = TemporalExtent(start_time=3, end_time=6) + >>> B = TemporalExtent(start_time=5, end_time=7) >>> inter = A.disjoint_union(B) >>> inter.print_info() | Start time:................. 3 @@ -239,8 +246,8 @@ def disjoint_union(self, extent): | Start time:................. 3 | End time:................... 7 - >>> A = TemporalExtent(start_time=3, end_time=8 ) - >>> B = TemporalExtent(start_time=5, end_time=6 ) + >>> A = TemporalExtent(start_time=3, end_time=8) + >>> B = TemporalExtent(start_time=5, end_time=6) >>> inter = A.disjoint_union(B) >>> inter.print_info() | Start time:................. 3 @@ -250,8 +257,8 @@ def disjoint_union(self, extent): | Start time:................. 3 | End time:................... 8 - >>> A = TemporalExtent(start_time=5, end_time=8 ) - >>> B = TemporalExtent(start_time=3, end_time=6 ) + >>> A = TemporalExtent(start_time=5, end_time=8) + >>> B = TemporalExtent(start_time=3, end_time=6) >>> inter = A.disjoint_union(B) >>> inter.print_info() | Start time:................. 3 @@ -261,8 +268,8 @@ def disjoint_union(self, extent): | Start time:................. 3 | End time:................... 8 - >>> A = TemporalExtent(start_time=5, end_time=None ) - >>> B = TemporalExtent(start_time=3, end_time=6 ) + >>> A = TemporalExtent(start_time=5, end_time=None) + >>> B = TemporalExtent(start_time=3, end_time=6) >>> inter = A.disjoint_union(B) >>> inter.print_info() | Start time:................. 3 @@ -272,8 +279,8 @@ def disjoint_union(self, extent): | Start time:................. 3 | End time:................... 6 - >>> A = TemporalExtent(start_time=5, end_time=8 ) - >>> B = TemporalExtent(start_time=3, end_time=4 ) + >>> A = TemporalExtent(start_time=5, end_time=8) + >>> B = TemporalExtent(start_time=3, end_time=4) >>> inter = A.disjoint_union(B) >>> inter.print_info() | Start time:................. 3 @@ -282,8 +289,8 @@ def disjoint_union(self, extent): >>> inter.print_info() | Start time:................. 3 | End time:................... 8 - >>> A = TemporalExtent(start_time=5, end_time=8 ) - >>> B = TemporalExtent(start_time=3, end_time=None ) + >>> A = TemporalExtent(start_time=5, end_time=8) + >>> B = TemporalExtent(start_time=3, end_time=None) >>> inter = A.disjoint_union(B) >>> inter.print_info() | Start time:................. 3 @@ -292,8 +299,8 @@ def disjoint_union(self, extent): >>> inter.print_info() | Start time:................. 3 | End time:................... 8 - >>> A = TemporalExtent(start_time=5, end_time=None ) - >>> B = TemporalExtent(start_time=3, end_time=8 ) + >>> A = TemporalExtent(start_time=5, end_time=None) + >>> B = TemporalExtent(start_time=3, end_time=8) >>> inter = A.disjoint_union(B) >>> inter.print_info() | Start time:................. 3 @@ -302,8 +309,8 @@ def disjoint_union(self, extent): >>> inter.print_info() | Start time:................. 3 | End time:................... 8 - >>> A = TemporalExtent(start_time=5, end_time=None ) - >>> B = TemporalExtent(start_time=3, end_time=None ) + >>> A = TemporalExtent(start_time=5, end_time=None) + >>> B = TemporalExtent(start_time=3, end_time=None) >>> inter = A.disjoint_union(B) >>> inter.print_info() | Start time:................. 3 @@ -313,8 +320,8 @@ def disjoint_union(self, extent): | Start time:................. 3 | End time:................... 5 - >>> A = RelativeTemporalExtent(start_time=5, end_time=None, unit="years" ) - >>> B = RelativeTemporalExtent(start_time=3, end_time=None, unit="years" ) + >>> A = RelativeTemporalExtent(start_time=5, end_time=None, unit="years") + >>> B = RelativeTemporalExtent(start_time=3, end_time=None, unit="years") >>> inter = A.disjoint_union(B) >>> inter.print_info() +-------------------- Relative time -----------------------------------------+ @@ -331,8 +338,12 @@ def disjoint_union(self, extent): >>> from datetime import datetime as dt - >>> A = AbsoluteTemporalExtent(start_time=dt(2001,1,10), end_time=dt(2003,1,1)) - >>> B = AbsoluteTemporalExtent(start_time=dt(2005,1,10), end_time=dt(2008,1,1)) + >>> A = AbsoluteTemporalExtent( + ... start_time=dt(2001, 1, 10), end_time=dt(2003, 1, 1) + ... ) + >>> B = AbsoluteTemporalExtent( + ... start_time=dt(2005, 1, 10), end_time=dt(2008, 1, 1) + ... ) >>> inter = A.disjoint_union(B) >>> inter.print_info() +-------------------- Absolute time -----------------------------------------+ @@ -345,7 +356,7 @@ def disjoint_union(self, extent): | Start time:................. 2001-01-10 00:00:00 | End time:................... 2008-01-01 00:00:00 - """ + """ # noqa: E501 start = None end = None @@ -396,14 +407,14 @@ def union(self, extent): .. code-block:: python - >>> A = TemporalExtent(start_time=5, end_time=8 ) - >>> B = TemporalExtent(start_time=3, end_time=4 ) + >>> A = TemporalExtent(start_time=5, end_time=8) + >>> B = TemporalExtent(start_time=3, end_time=4) >>> inter = A.intersect(B) >>> print(inter) None - >>> A = TemporalExtent(start_time=5, end_time=8 ) - >>> B = TemporalExtent(start_time=3, end_time=None ) + >>> A = TemporalExtent(start_time=5, end_time=8) + >>> B = TemporalExtent(start_time=3, end_time=None) >>> inter = A.intersect(B) >>> print(inter) None @@ -433,8 +444,8 @@ def starts(self, extent): .. code-block:: python - >>> A = TemporalExtent(start_time=5, end_time=6 ) - >>> B = TemporalExtent(start_time=5, end_time=7 ) + >>> A = TemporalExtent(start_time=5, end_time=6) + >>> B = TemporalExtent(start_time=5, end_time=7) >>> A.starts(B) True >>> B.starts(A) @@ -467,8 +478,8 @@ def started(self, extent): .. code-block:: python - >>> A = TemporalExtent(start_time=5, end_time=7 ) - >>> B = TemporalExtent(start_time=5, end_time=6 ) + >>> A = TemporalExtent(start_time=5, end_time=7) + >>> B = TemporalExtent(start_time=5, end_time=6) >>> A.started(B) True >>> B.started(A) @@ -501,8 +512,8 @@ def finishes(self, extent): .. code-block:: python - >>> A = TemporalExtent(start_time=6, end_time=7 ) - >>> B = TemporalExtent(start_time=5, end_time=7 ) + >>> A = TemporalExtent(start_time=6, end_time=7) + >>> B = TemporalExtent(start_time=5, end_time=7) >>> A.finishes(B) True >>> B.finishes(A) @@ -535,8 +546,8 @@ def finished(self, extent): .. code-block:: python - >>> A = TemporalExtent(start_time=5, end_time=7 ) - >>> B = TemporalExtent(start_time=6, end_time=7 ) + >>> A = TemporalExtent(start_time=5, end_time=7) + >>> B = TemporalExtent(start_time=6, end_time=7) >>> A.finished(B) True >>> B.finished(A) @@ -569,8 +580,8 @@ def after(self, extent): .. code-block:: python - >>> A = TemporalExtent(start_time=8, end_time=9 ) - >>> B = TemporalExtent(start_time=6, end_time=7 ) + >>> A = TemporalExtent(start_time=8, end_time=9) + >>> B = TemporalExtent(start_time=6, end_time=7) >>> A.after(B) True >>> B.after(A) @@ -603,8 +614,8 @@ def before(self, extent): .. code-block:: python - >>> A = TemporalExtent(start_time=6, end_time=7 ) - >>> B = TemporalExtent(start_time=8, end_time=9 ) + >>> A = TemporalExtent(start_time=6, end_time=7) + >>> B = TemporalExtent(start_time=8, end_time=9) >>> A.before(B) True >>> B.before(A) @@ -639,14 +650,14 @@ def adjacent(self, extent): .. code-block:: python - >>> A = TemporalExtent(start_time=5, end_time=7 ) - >>> B = TemporalExtent(start_time=7, end_time=9 ) + >>> A = TemporalExtent(start_time=5, end_time=7) + >>> B = TemporalExtent(start_time=7, end_time=9) >>> A.adjacent(B) True >>> B.adjacent(A) True - >>> A = TemporalExtent(start_time=5, end_time=7 ) - >>> B = TemporalExtent(start_time=3, end_time=5 ) + >>> A = TemporalExtent(start_time=5, end_time=7) + >>> B = TemporalExtent(start_time=3, end_time=5) >>> A.adjacent(B) True >>> B.adjacent(A) @@ -678,8 +689,8 @@ def follows(self, extent): .. code-block:: python - >>> A = TemporalExtent(start_time=5, end_time=7 ) - >>> B = TemporalExtent(start_time=3, end_time=5 ) + >>> A = TemporalExtent(start_time=5, end_time=7) + >>> B = TemporalExtent(start_time=3, end_time=5) >>> A.follows(B) True >>> B.follows(A) @@ -710,8 +721,8 @@ def precedes(self, extent): .. code-block:: python - >>> A = TemporalExtent(start_time=5, end_time=7 ) - >>> B = TemporalExtent(start_time=7, end_time=9 ) + >>> A = TemporalExtent(start_time=5, end_time=7) + >>> B = TemporalExtent(start_time=7, end_time=9) >>> A.precedes(B) True >>> B.precedes(A) @@ -741,8 +752,8 @@ def during(self, extent): .. code-block:: python - >>> A = TemporalExtent(start_time=5, end_time=7 ) - >>> B = TemporalExtent(start_time=4, end_time=9 ) + >>> A = TemporalExtent(start_time=5, end_time=7) + >>> B = TemporalExtent(start_time=4, end_time=9) >>> A.during(B) True >>> B.during(A) @@ -786,8 +797,8 @@ def contains(self, extent): .. code-block:: python - >>> A = TemporalExtent(start_time=4, end_time=9 ) - >>> B = TemporalExtent(start_time=5, end_time=8 ) + >>> A = TemporalExtent(start_time=4, end_time=9) + >>> B = TemporalExtent(start_time=5, end_time=8) >>> A.contains(B) True >>> B.contains(A) @@ -831,8 +842,8 @@ def equal(self, extent): .. code-block:: python - >>> A = TemporalExtent(start_time=5, end_time=6 ) - >>> B = TemporalExtent(start_time=5, end_time=6 ) + >>> A = TemporalExtent(start_time=5, end_time=6) + >>> B = TemporalExtent(start_time=5, end_time=6) >>> A.equal(B) True >>> B.equal(A) @@ -871,15 +882,15 @@ def overlaps(self, extent): .. code-block:: python - >>> A = TemporalExtent(start_time=5, end_time=7 ) - >>> B = TemporalExtent(start_time=6, end_time=8 ) + >>> A = TemporalExtent(start_time=5, end_time=7) + >>> B = TemporalExtent(start_time=6, end_time=8) >>> A.overlaps(B) True >>> B.overlaps(A) False - >>> A = TemporalExtent(start_time=5, end_time=6 ) - >>> B = TemporalExtent(start_time=6, end_time=8 ) + >>> A = TemporalExtent(start_time=5, end_time=6) + >>> B = TemporalExtent(start_time=6, end_time=8) >>> A.overlaps(B) False >>> B.overlaps(A) @@ -914,15 +925,15 @@ def overlapped(self, extent): .. code-block:: python - >>> A = TemporalExtent(start_time=6, end_time=8 ) - >>> B = TemporalExtent(start_time=5, end_time=7 ) + >>> A = TemporalExtent(start_time=6, end_time=8) + >>> B = TemporalExtent(start_time=5, end_time=7) >>> A.overlapped(B) True >>> B.overlapped(A) False - >>> A = TemporalExtent(start_time=6, end_time=8 ) - >>> B = TemporalExtent(start_time=5, end_time=6 ) + >>> A = TemporalExtent(start_time=6, end_time=8) + >>> B = TemporalExtent(start_time=5, end_time=6) >>> A.overlapped(B) False >>> B.overlapped(A) @@ -1079,7 +1090,7 @@ def print_info(self): """Print information about this class in human readable style""" # 0123456789012345678901234567890 print( - " +-------------------- Absolute time -----------------------------------------+" + " +-------------------- Absolute time -----------------------------------------+" # noqa: E501 ) TemporalExtent.print_info(self) @@ -1126,10 +1137,14 @@ class STDSAbsoluteTime(AbsoluteTemporalExtent): .. code-block:: python >>> init() - >>> A = STDSAbsoluteTime(table="strds_absolute_time", - ... ident="strds@PERMANENT", start_time=datetime(2001, 01, 01), - ... end_time=datetime(2005,01,01), granularity="1 days", - ... map_time="interval") + >>> A = STDSAbsoluteTime( + ... table="strds_absolute_time", + ... ident="strds@PERMANENT", + ... start_time=datetime(2001, 1, 1), + ... end_time=datetime(2005, 1, 1), + ... granularity="1 days", + ... map_time="interval", + ... ) >>> A.id 'strds@PERMANENT' >>> A.start_time @@ -1264,8 +1279,13 @@ class RelativeTemporalExtent(TemporalExtent): .. code-block:: python >>> init() - >>> A = RelativeTemporalExtent(table="raster_relative_time", - ... ident="soil@PERMANENT", start_time=0, end_time=1, unit="years") + >>> A = RelativeTemporalExtent( + ... table="raster_relative_time", + ... ident="soil@PERMANENT", + ... start_time=0, + ... end_time=1, + ... unit="years", + ... ) >>> A.id 'soil@PERMANENT' >>> A.start_time @@ -1337,7 +1357,7 @@ def print_info(self): """Print information about this class in human readable style""" # 0123456789012345678901234567890 print( - " +-------------------- Relative time -----------------------------------------+" + " +-------------------- Relative time -----------------------------------------+" # noqa: E501 ) TemporalExtent.print_info(self) print(" | Relative time unit:......... " + str(self.get_unit())) @@ -1385,9 +1405,15 @@ class STDSRelativeTime(RelativeTemporalExtent): .. code-block:: python >>> init() - >>> A = STDSRelativeTime(table="strds_relative_time", - ... ident="strds@PERMANENT", start_time=0, end_time=1, unit="years", - ... granularity=5, map_time="interval") + >>> A = STDSRelativeTime( + ... table="strds_relative_time", + ... ident="strds@PERMANENT", + ... start_time=0, + ... end_time=1, + ... unit="years", + ... granularity=5, + ... map_time="interval", + ... ) >>> A.id 'strds@PERMANENT' >>> A.start_time diff --git a/python/grass/temporal/temporal_granularity.py b/python/grass/temporal/temporal_granularity.py index a7c47c045d2..3b1b005d533 100644 --- a/python/grass/temporal/temporal_granularity.py +++ b/python/grass/temporal/temporal_granularity.py @@ -205,94 +205,102 @@ def compute_relative_time_granularity(maps): >>> tgis.init() >>> maps = [] >>> for i in range(5): - ... map = tgis.RasterDataset("a%i@P"%i) - ... check = map.set_relative_time(i,i + 1,"seconds") - ... if check: - ... maps.append(map) + ... map = tgis.RasterDataset("a%i@P" % i) + ... check = map.set_relative_time(i, i + 1, "seconds") + ... if check: + ... maps.append(map) + ... >>> tgis.compute_relative_time_granularity(maps) 1 >>> maps = [] >>> count = 0 - >>> timelist = ((0,3), (3,6), (6,9)) + >>> timelist = ((0, 3), (3, 6), (6, 9)) >>> for t in timelist: - ... map = tgis.RasterDataset("a%i@P"%count) - ... check = map.set_relative_time(t[0],t[1],"years") - ... if check: - ... maps.append(map) - ... count += 1 + ... map = tgis.RasterDataset("a%i@P" % count) + ... check = map.set_relative_time(t[0], t[1], "years") + ... if check: + ... maps.append(map) + ... count += 1 + ... >>> tgis.compute_relative_time_granularity(maps) 3 >>> maps = [] >>> count = 0 - >>> timelist = ((0,3), (4,6), (8,11)) + >>> timelist = ((0, 3), (4, 6), (8, 11)) >>> for t in timelist: - ... map = tgis.RasterDataset("a%i@P"%count) - ... check = map.set_relative_time(t[0],t[1],"years") - ... if check: - ... maps.append(map) - ... count += 1 + ... map = tgis.RasterDataset("a%i@P" % count) + ... check = map.set_relative_time(t[0], t[1], "years") + ... if check: + ... maps.append(map) + ... count += 1 + ... >>> tgis.compute_relative_time_granularity(maps) 1 >>> maps = [] >>> count = 0 - >>> timelist = ((0,8), (2,6), (5,9)) + >>> timelist = ((0, 8), (2, 6), (5, 9)) >>> for t in timelist: - ... map = tgis.RasterDataset("a%i@P"%count) - ... check = map.set_relative_time(t[0],t[1],"months") - ... if check: - ... maps.append(map) - ... count += 1 + ... map = tgis.RasterDataset("a%i@P" % count) + ... check = map.set_relative_time(t[0], t[1], "months") + ... if check: + ... maps.append(map) + ... count += 1 + ... >>> tgis.compute_relative_time_granularity(maps) 4 >>> maps = [] >>> count = 0 - >>> timelist = ((0,8), (8,12), (12,18)) + >>> timelist = ((0, 8), (8, 12), (12, 18)) >>> for t in timelist: - ... map = tgis.RasterDataset("a%i@P"%count) - ... check = map.set_relative_time(t[0],t[1],"days") - ... if check: - ... maps.append(map) - ... count += 1 + ... map = tgis.RasterDataset("a%i@P" % count) + ... check = map.set_relative_time(t[0], t[1], "days") + ... if check: + ... maps.append(map) + ... count += 1 + ... >>> tgis.compute_relative_time_granularity(maps) 2 >>> maps = [] >>> count = 0 - >>> timelist = ((0,None), (8,None), (12,None), (24,None)) + >>> timelist = ((0, None), (8, None), (12, None), (24, None)) >>> for t in timelist: - ... map = tgis.RasterDataset("a%i@P"%count) - ... check = map.set_relative_time(t[0],t[1],"minutes") - ... if check: - ... maps.append(map) - ... count += 1 + ... map = tgis.RasterDataset("a%i@P" % count) + ... check = map.set_relative_time(t[0], t[1], "minutes") + ... if check: + ... maps.append(map) + ... count += 1 + ... >>> tgis.compute_relative_time_granularity(maps) 4 >>> maps = [] >>> count = 0 - >>> timelist = ((0,None), (8,14), (18,None), (24,None)) + >>> timelist = ((0, None), (8, 14), (18, None), (24, None)) >>> for t in timelist: - ... map = tgis.RasterDataset("a%i@P"%count) - ... check = map.set_relative_time(t[0],t[1],"hours") - ... if check: - ... maps.append(map) - ... count += 1 + ... map = tgis.RasterDataset("a%i@P" % count) + ... check = map.set_relative_time(t[0], t[1], "hours") + ... if check: + ... maps.append(map) + ... count += 1 + ... >>> tgis.compute_relative_time_granularity(maps) 2 >>> maps = [] >>> count = 0 - >>> timelist = ((0,21),) + >>> timelist = ((0, 21),) >>> for t in timelist: - ... map = tgis.RasterDataset("a%i@P"%count) - ... check = map.set_relative_time(t[0],t[1],"hours") - ... if check: - ... maps.append(map) - ... count += 1 + ... map = tgis.RasterDataset("a%i@P" % count) + ... check = map.set_relative_time(t[0], t[1], "hours") + ... if check: + ... maps.append(map) + ... count += 1 + ... >>> tgis.compute_relative_time_granularity(maps) 21 @@ -364,61 +372,77 @@ def compute_absolute_time_granularity(maps): >>> tgis.init() >>> maps = [] >>> count = 0 - >>> timelist = ((dt(2000,01,01),None), (dt(2000,02,01),None)) + >>> timelist = ((dt(2000, 1, 1), None), (dt(2000, 2, 1), None)) >>> for t in timelist: - ... map = tgis.RasterDataset("a%i@P"%count) - ... check = map.set_absolute_time(t[0],t[1]) - ... if check: - ... maps.append(map) - ... count += 1 + ... map = tgis.RasterDataset("a%i@P" % count) + ... check = map.set_absolute_time(t[0], t[1]) + ... if check: + ... maps.append(map) + ... count += 1 + ... >>> tgis.compute_absolute_time_granularity(maps) '1 month' >>> maps = [] >>> count = 0 - >>> timelist = ((dt(2000,01,01),None), (dt(2000,01,02),None), (dt(2000,01,03),None)) + >>> timelist = ( + ... (dt(2000, 1, 1), None), + ... (dt(2000, 1, 2), None), + ... (dt(2000, 1, 3), None), + ... ) >>> for t in timelist: - ... map = tgis.RasterDataset("a%i@P"%count) - ... check = map.set_absolute_time(t[0],t[1]) - ... if check: - ... maps.append(map) - ... count += 1 + ... map = tgis.RasterDataset("a%i@P" % count) + ... check = map.set_absolute_time(t[0], t[1]) + ... if check: + ... maps.append(map) + ... count += 1 + ... >>> tgis.compute_absolute_time_granularity(maps) '1 day' >>> maps = [] >>> count = 0 - >>> timelist = ((dt(2000,01,01),None), (dt(2000,01,02),None), (dt(2000,05,04,0,5,30),None)) + >>> timelist = ( + ... (dt(2000, 1, 1), None), + ... (dt(2000, 1, 2), None), + ... (dt(2000, 5, 4, 0, 5, 30), None), + ... ) >>> for t in timelist: - ... map = tgis.RasterDataset("a%i@P"%count) - ... check = map.set_absolute_time(t[0],t[1]) - ... if check: - ... maps.append(map) - ... count += 1 + ... map = tgis.RasterDataset("a%i@P" % count) + ... check = map.set_absolute_time(t[0], t[1]) + ... if check: + ... maps.append(map) + ... count += 1 + ... >>> tgis.compute_absolute_time_granularity(maps) '30 seconds' >>> maps = [] >>> count = 0 - >>> timelist = ((dt(2000,01,01),dt(2000,05,02)), (dt(2000,05,04,2),None)) + >>> timelist = ((dt(2000, 1, 1), dt(2000, 5, 2)), (dt(2000, 5, 4, 2), None)) >>> for t in timelist: - ... map = tgis.RasterDataset("a%i@P"%count) - ... check = map.set_absolute_time(t[0],t[1]) - ... if check: - ... maps.append(map) - ... count += 1 + ... map = tgis.RasterDataset("a%i@P" % count) + ... check = map.set_absolute_time(t[0], t[1]) + ... if check: + ... maps.append(map) + ... count += 1 + ... >>> tgis.compute_absolute_time_granularity(maps) '2 hours' >>> maps = [] >>> count = 0 - >>> timelist = ((dt(2000,01,01),dt(2000,02,01)), (dt(2005,05,04,12),dt(2007,05,20,6))) + >>> timelist = ( + ... (dt(2000, 1, 1), dt(2000, 2, 1)), + ... (dt(2005, 5, 4, 12), dt(2007, 5, 20, 6)), + ... ) >>> for t in timelist: - ... map = tgis.RasterDataset("a%i@P"%count) - ... check = map.set_absolute_time(t[0],t[1]) - ... if check: - ... maps.append(map) - ... count += 1 + ... map = tgis.RasterDataset("a%i@P" % count) + ... check = map.set_absolute_time(t[0], t[1]) + ... if check: + ... maps.append(map) + ... count += 1 + ... >>> tgis.compute_absolute_time_granularity(maps) '6 hours' @@ -538,13 +562,13 @@ def compute_common_relative_time_granularity(gran_list): >>> import grass.temporal as tgis >>> tgis.init() - >>> grans = [1,2,30] + >>> grans = [1, 2, 30] >>> tgis.compute_common_relative_time_granularity(grans) 1 >>> import grass.temporal as tgis >>> tgis.init() - >>> grans = [10,20,30] + >>> grans = [10, 20, 30] >>> tgis.compute_common_relative_time_granularity(grans) 10 """ @@ -573,130 +597,168 @@ def compute_common_absolute_time_granularity(gran_list, start_date_list=None): >>> import grass.temporal as tgis >>> tgis.init() >>> grans = ["20 second", "10 minutes", "2 hours"] - >>> dates = [datetime(2001,1,1,0,0,0), - ... datetime(2001,1,1,0,0,0), - ... datetime(2001,1,1,0,0,0),] + >>> dates = [ + ... datetime(2001, 1, 1, 0, 0, 0), + ... datetime(2001, 1, 1, 0, 0, 0), + ... datetime(2001, 1, 1, 0, 0, 0), + ... ] >>> tgis.compute_common_absolute_time_granularity(grans, dates) '20 seconds' >>> grans = ["20 second", "10 minutes", "2 hours"] - >>> dates = [datetime(2001,1,1,0,0,20), - ... datetime(2001,1,1,0,0,0), - ... datetime(2001,1,1,0,0,0),] + >>> dates = [ + ... datetime(2001, 1, 1, 0, 0, 20), + ... datetime(2001, 1, 1, 0, 0, 0), + ... datetime(2001, 1, 1, 0, 0, 0), + ... ] >>> tgis.compute_common_absolute_time_granularity(grans, dates) '1 second' >>> grans = ["7200 second", "240 minutes", "1 year"] - >>> dates = [datetime(2001,1,1,0,0,10), - ... datetime(2001,1,1,0,0,0), - ... datetime(2001,1,1,0,0,0),] + >>> dates = [ + ... datetime(2001, 1, 1, 0, 0, 10), + ... datetime(2001, 1, 1, 0, 0, 0), + ... datetime(2001, 1, 1, 0, 0, 0), + ... ] >>> tgis.compute_common_absolute_time_granularity(grans, dates) '1 second' >>> grans = ["7200 second", "89 minutes", "1 year"] - >>> dates = [datetime(2001,1,1,0,0,0), - ... datetime(2001,1,1,0,0,0), - ... datetime(2001,1,1,0,0,0),] + >>> dates = [ + ... datetime(2001, 1, 1, 0, 0, 0), + ... datetime(2001, 1, 1, 0, 0, 0), + ... datetime(2001, 1, 1, 0, 0, 0), + ... ] >>> tgis.compute_common_absolute_time_granularity(grans, dates) '60 seconds' >>> grans = ["120 minutes", "2 hours"] - >>> dates = [datetime(2001,1,1,0,0,0), - ... datetime(2001,1,1,0,0,0),] + >>> dates = [ + ... datetime(2001, 1, 1, 0, 0, 0), + ... datetime(2001, 1, 1, 0, 0, 0), + ... ] >>> tgis.compute_common_absolute_time_granularity(grans, dates) '60 minutes' >>> grans = ["120 minutes", "2 hours"] - >>> dates = [datetime(2001,1,1,0,30,0), - ... datetime(2001,1,1,0,0,0),] + >>> dates = [ + ... datetime(2001, 1, 1, 0, 30, 0), + ... datetime(2001, 1, 1, 0, 0, 0), + ... ] >>> tgis.compute_common_absolute_time_granularity(grans, dates) '1 minute' >>> grans = ["360 minutes", "3 hours"] - >>> dates = [datetime(2001,1,1,0,0,0), - ... datetime(2001,1,1,0,0,0),] + >>> dates = [ + ... datetime(2001, 1, 1, 0, 0, 0), + ... datetime(2001, 1, 1, 0, 0, 0), + ... ] >>> tgis.compute_common_absolute_time_granularity(grans, dates) '60 minutes' >>> grans = ["2 hours", "4 hours", "8 hours"] - >>> dates = [datetime(2001,1,1,0,0,0), - ... datetime(2001,1,1,0,0,0), - ... datetime(2001,1,1,0,0,0),] + >>> dates = [ + ... datetime(2001, 1, 1, 0, 0, 0), + ... datetime(2001, 1, 1, 0, 0, 0), + ... datetime(2001, 1, 1, 0, 0, 0), + ... ] >>> tgis.compute_common_absolute_time_granularity(grans, dates) '2 hours' >>> grans = ["2 hours", "4 hours", "8 hours"] - >>> dates = [datetime(2001,1,1,2,0,0), - ... datetime(2001,1,1,4,0,0), - ... datetime(2001,1,1,8,0,0),] + >>> dates = [ + ... datetime(2001, 1, 1, 2, 0, 0), + ... datetime(2001, 1, 1, 4, 0, 0), + ... datetime(2001, 1, 1, 8, 0, 0), + ... ] >>> tgis.compute_common_absolute_time_granularity(grans, dates) '1 hour' >>> grans = ["8 hours", "2 days"] - >>> dates = [datetime(2001,1,1,0,0,0), - ... datetime(2001,1,1,0,0,0),] + >>> dates = [ + ... datetime(2001, 1, 1, 0, 0, 0), + ... datetime(2001, 1, 1, 0, 0, 0), + ... ] >>> tgis.compute_common_absolute_time_granularity(grans, dates) '8 hours' >>> grans = ["8 hours", "2 days"] - >>> dates = [datetime(2001,1,1,10,0,0), - ... datetime(2001,1,1,0,0,0),] + >>> dates = [ + ... datetime(2001, 1, 1, 10, 0, 0), + ... datetime(2001, 1, 1, 0, 0, 0), + ... ] >>> tgis.compute_common_absolute_time_granularity(grans, dates) '1 hour' >>> grans = ["120 months", "360 months", "4 years"] - >>> dates = [datetime(2001,1,1,0,0,0), - ... datetime(2001,1,1,0,0,0), - ... datetime(2001,1,1,0,0,0),] + >>> dates = [ + ... datetime(2001, 1, 1, 0, 0, 0), + ... datetime(2001, 1, 1, 0, 0, 0), + ... datetime(2001, 1, 1, 0, 0, 0), + ... ] >>> tgis.compute_common_absolute_time_granularity(grans, dates) '12 months' >>> grans = ["30 days", "10 days", "5 days"] - >>> dates = [datetime(2001,2,1,0,0,0), - ... datetime(2001,1,1,0,0,0), - ... datetime(2001,1,1,0,0,0),] + >>> dates = [ + ... datetime(2001, 2, 1, 0, 0, 0), + ... datetime(2001, 1, 1, 0, 0, 0), + ... datetime(2001, 1, 1, 0, 0, 0), + ... ] >>> tgis.compute_common_absolute_time_granularity(grans, dates) '5 days' >>> grans = ["30 days", "10 days", "5 days"] - >>> dates = [datetime(2001,2,2,0,0,0), - ... datetime(2001,1,1,0,0,0), - ... datetime(2001,1,1,0,0,0),] + >>> dates = [ + ... datetime(2001, 2, 2, 0, 0, 0), + ... datetime(2001, 1, 1, 0, 0, 0), + ... datetime(2001, 1, 1, 0, 0, 0), + ... ] >>> tgis.compute_common_absolute_time_granularity(grans, dates) '1 day' >>> grans = ["2 days", "360 months", "4 years"] - >>> dates = [datetime(2001,1,1,0,0,0), - ... datetime(2001,1,1,0,0,0), - ... datetime(2001,1,1,0,0,0),] + >>> dates = [ + ... datetime(2001, 1, 1, 0, 0, 0), + ... datetime(2001, 1, 1, 0, 0, 0), + ... datetime(2001, 1, 1, 0, 0, 0), + ... ] >>> tgis.compute_common_absolute_time_granularity(grans, dates) '2 days' >>> grans = ["2 days", "360 months", "4 years"] - >>> dates = [datetime(2001,1,2,0,0,0), - ... datetime(2001,1,1,0,0,0), - ... datetime(2001,1,1,0,0,0),] + >>> dates = [ + ... datetime(2001, 1, 2, 0, 0, 0), + ... datetime(2001, 1, 1, 0, 0, 0), + ... datetime(2001, 1, 1, 0, 0, 0), + ... ] >>> tgis.compute_common_absolute_time_granularity(grans, dates) '1 day' >>> grans = ["120 months", "360 months", "4 years"] - >>> dates = [datetime(2001,2,1,0,0,0), - ... datetime(2001,1,1,0,0,0), - ... datetime(2001,1,1,0,0,0),] + >>> dates = [ + ... datetime(2001, 2, 1, 0, 0, 0), + ... datetime(2001, 1, 1, 0, 0, 0), + ... datetime(2001, 1, 1, 0, 0, 0), + ... ] >>> tgis.compute_common_absolute_time_granularity(grans, dates) '1 month' >>> grans = ["120 months", "361 months", "4 years"] - >>> dates = [datetime(2001,1,1,0,0,0), - ... datetime(2001,1,1,0,0,0), - ... datetime(2001,1,1,0,0,0),] + >>> dates = [ + ... datetime(2001, 1, 1, 0, 0, 0), + ... datetime(2001, 1, 1, 0, 0, 0), + ... datetime(2001, 1, 1, 0, 0, 0), + ... ] >>> tgis.compute_common_absolute_time_granularity(grans, dates) '1 month' >>> grans = ["120 months", "360 months", "4 years"] - >>> dates = [datetime(2001,1,1,0,0,0), - ... datetime(2001,1,1,0,0,0), - ... datetime(2001,1,1,0,0,0),] + >>> dates = [ + ... datetime(2001, 1, 1, 0, 0, 0), + ... datetime(2001, 1, 1, 0, 0, 0), + ... datetime(2001, 1, 1, 0, 0, 0), + ... ] >>> tgis.compute_common_absolute_time_granularity(grans, dates) '12 months' @@ -1056,16 +1118,16 @@ def gran_singular_unit(gran): >>> import grass.temporal as tgis >>> tgis.init() - >>> tgis.gran_singular_unit('1 month') + >>> tgis.gran_singular_unit("1 month") 'month' - >>> tgis.gran_singular_unit('2 months') + >>> tgis.gran_singular_unit("2 months") 'month' - >>> tgis.gran_singular_unit('6 seconds') + >>> tgis.gran_singular_unit("6 seconds") 'second' - >>> tgis.gran_singular_unit('1 year') + >>> tgis.gran_singular_unit("1 year") 'year' """ if check_granularity_string(gran, "absolute"): @@ -1101,16 +1163,16 @@ def gran_plural_unit(gran): >>> import grass.temporal as tgis >>> tgis.init() - >>> tgis.gran_singular_unit('1 month') + >>> tgis.gran_singular_unit("1 month") 'month' - >>> tgis.gran_singular_unit('2 months') + >>> tgis.gran_singular_unit("2 months") 'month' - >>> tgis.gran_singular_unit('6 seconds') + >>> tgis.gran_singular_unit("6 seconds") 'second' - >>> tgis.gran_singular_unit('1 year') + >>> tgis.gran_singular_unit("1 year") 'year' """ if check_granularity_string(gran, "absolute"): @@ -1149,28 +1211,28 @@ def gran_to_gran(from_gran, to_gran="days", shell=False): >>> import grass.temporal as tgis >>> tgis.init() - >>> tgis.gran_to_gran('1 month', '1 day') + >>> tgis.gran_to_gran("1 month", "1 day") '30.436875 days' - >>> tgis.gran_to_gran('1 month', '1 day', True) + >>> tgis.gran_to_gran("1 month", "1 day", True) 30.436875 - >>> tgis.gran_to_gran('10 year', '1 hour') + >>> tgis.gran_to_gran("10 year", "1 hour") '87658.2 hours' - >>> tgis.gran_to_gran('10 year', '1 minute') + >>> tgis.gran_to_gran("10 year", "1 minute") '5259492.0 minutes' - >>> tgis.gran_to_gran('6 months', '1 day') + >>> tgis.gran_to_gran("6 months", "1 day") '182.62125 days' - >>> tgis.gran_to_gran('1 months', '1 second') + >>> tgis.gran_to_gran("1 months", "1 second") '2629746.0 seconds' - >>> tgis.gran_to_gran('1 month', '1 second', True) + >>> tgis.gran_to_gran("1 month", "1 second", True) 2629746.0 - >>> tgis.gran_to_gran('30 month', '1 month', True) + >>> tgis.gran_to_gran("30 month", "1 month", True) 30 """ diff --git a/python/grass/temporal/temporal_operator.py b/python/grass/temporal/temporal_operator.py index d86aab8adbd..0bf001ee0c5 100644 --- a/python/grass/temporal/temporal_operator.py +++ b/python/grass/temporal/temporal_operator.py @@ -12,133 +12,133 @@ .. code-block:: python >>> p = TemporalOperatorParser() - >>> expression = "{equal|equivalent|cover|in|meet|contain|overlap}" - >>> p.parse(expression, optype = 'relation') + >>> expression = "{equal|equivalent|cover|in|meet|contain|overlap}" + >>> p.parse(expression, optype="relation") >>> print((p.relations, p.temporal, p.function)) (['equal', 'equivalent', 'cover', 'in', 'meet', 'contain', 'overlap'], None, None) >>> p = TemporalOperatorParser() - >>> expression = "{equal| during}" - >>> p.parse(expression, optype = 'relation') + >>> expression = "{equal| during}" + >>> p.parse(expression, optype="relation") >>> print((p.relations, p.temporal, p.function)) (['equal', 'during'], None, None) >>> p = TemporalOperatorParser() - >>> expression = "{contains | starts}" + >>> expression = "{contains | starts}" >>> p.parse(expression) >>> print((p.relations, p.temporal, p.function)) (['contains', 'starts'], None, None) >>> p = TemporalOperatorParser() - >>> expression = "{&&, during}" - >>> p.parse(expression, optype = 'boolean') + >>> expression = "{&&, during}" + >>> p.parse(expression, optype="boolean") >>> print((p.relations, p.temporal, p.function, p.aggregate)) (['during'], 'l', '&&', '&') >>> p = TemporalOperatorParser() - >>> expression = "{||, equal | during}" - >>> p.parse(expression, optype = 'boolean') + >>> expression = "{||, equal | during}" + >>> p.parse(expression, optype="boolean") >>> print((p.relations, p.temporal, p.function, p.aggregate)) (['equal', 'during'], 'l', '||', '|') >>> p = TemporalOperatorParser() - >>> expression = "{||, equal | during, &}" - >>> p.parse(expression, optype = 'boolean') + >>> expression = "{||, equal | during, &}" + >>> p.parse(expression, optype="boolean") >>> print((p.relations, p.temporal, p.function, p.aggregate)) (['equal', 'during'], 'l', '||', '&') >>> p = TemporalOperatorParser() - >>> expression = "{&&, during, |}" - >>> p.parse(expression, optype = 'boolean') + >>> expression = "{&&, during, |}" + >>> p.parse(expression, optype="boolean") >>> print((p.relations, p.temporal, p.function, p.aggregate)) (['during'], 'l', '&&', '|') >>> p = TemporalOperatorParser() - >>> expression = "{&&, during, |, r}" - >>> p.parse(expression, optype = 'boolean') + >>> expression = "{&&, during, |, r}" + >>> p.parse(expression, optype="boolean") >>> print((p.relations, p.temporal, p.function, p.aggregate)) (['during'], 'r', '&&', '|') >>> p = TemporalOperatorParser() - >>> expression = "{&&, during, u}" - >>> p.parse(expression, optype = 'boolean') + >>> expression = "{&&, during, u}" + >>> p.parse(expression, optype="boolean") >>> print((p.relations, p.temporal, p.function, p.aggregate)) (['during'], 'u', '&&', '&') >>> p = TemporalOperatorParser() - >>> expression = "{:, during, r}" - >>> p.parse(expression, optype = 'select') + >>> expression = "{:, during, r}" + >>> p.parse(expression, optype="select") >>> print((p.relations, p.temporal, p.function)) (['during'], 'r', ':') >>> p = TemporalOperatorParser() - >>> expression = "{!:, equal | contains, d}" - >>> p.parse(expression, optype = 'select') + >>> expression = "{!:, equal | contains, d}" + >>> p.parse(expression, optype="select") >>> print((p.relations, p.temporal, p.function)) (['equal', 'contains'], 'd', '!:') >>> p = TemporalOperatorParser() - >>> expression = "{#, during, r}" - >>> p.parse(expression, optype = 'hash') + >>> expression = "{#, during, r}" + >>> p.parse(expression, optype="hash") >>> print((p.relations, p.temporal, p.function)) (['during'], 'r', '#') >>> p = TemporalOperatorParser() - >>> expression = "{#, equal | contains}" - >>> p.parse(expression, optype = 'hash') + >>> expression = "{#, equal | contains}" + >>> p.parse(expression, optype="hash") >>> print((p.relations, p.temporal, p.function)) (['equal', 'contains'], 'l', '#') >>> p = TemporalOperatorParser() - >>> expression = "{+, during, r}" - >>> p.parse(expression, optype = 'raster') + >>> expression = "{+, during, r}" + >>> p.parse(expression, optype="raster") >>> print((p.relations, p.temporal, p.function)) (['during'], 'r', '+') >>> p = TemporalOperatorParser() - >>> expression = "{/, equal | contains}" - >>> p.parse(expression, optype = 'raster') + >>> expression = "{/, equal | contains}" + >>> p.parse(expression, optype="raster") >>> print((p.relations, p.temporal, p.function)) (['equal', 'contains'], 'l', '/') >>> p = TemporalOperatorParser() - >>> expression = "{+, equal | contains,intersect}" - >>> p.parse(expression, optype = 'raster') + >>> expression = "{+, equal | contains,intersect}" + >>> p.parse(expression, optype="raster") >>> print((p.relations, p.temporal, p.function)) (['equal', 'contains'], 'i', '+') >>> p = TemporalOperatorParser() - >>> expression = "{*, contains,disjoint}" - >>> p.parse(expression, optype = 'raster') + >>> expression = "{*, contains,disjoint}" + >>> p.parse(expression, optype="raster") >>> print((p.relations, p.temporal, p.function)) (['contains'], 'd', '*') >>> p = TemporalOperatorParser() - >>> expression = "{~, equal,left}" - >>> p.parse(expression, optype = 'overlay') + >>> expression = "{~, equal,left}" + >>> p.parse(expression, optype="overlay") >>> print((p.relations, p.temporal, p.function)) (['equal'], 'l', '~') >>> p = TemporalOperatorParser() - >>> expression = "{^, over,right}" - >>> p.parse(expression, optype = 'overlay') + >>> expression = "{^, over,right}" + >>> p.parse(expression, optype="overlay") >>> print((p.relations, p.temporal, p.function)) (['overlaps', 'overlapped'], 'r', '^') >>> p = TemporalOperatorParser() - >>> expression = "{&&, equal | during | contains | starts, &}" - >>> p.parse(expression, optype = 'boolean') + >>> expression = "{&&, equal | during | contains | starts, &}" + >>> p.parse(expression, optype="boolean") >>> print((p.relations, p.temporal, p.function, p.aggregate)) (['equal', 'during', 'contains', 'starts'], 'l', '&&', '&') >>> p = TemporalOperatorParser() - >>> expression = "{&&, equal | during | contains | starts, &&&&&}" - >>> p.parse(expression, optype = 'boolean') + >>> expression = "{&&, equal | during | contains | starts, &&&&&}" + >>> p.parse(expression, optype="boolean") Traceback (most recent call last): SyntaxError: Unexpected syntax error in expression "{&&, equal | during | contains | starts, &&&&&}" at position 42 near & >>> p = TemporalOperatorParser() - >>> expression = "{+, starting}" + >>> expression = "{+, starting}" >>> p.parse(expression) Traceback (most recent call last): SyntaxError: syntax error on line 1 position 4 near 'starting' >>> p = TemporalOperatorParser() - >>> expression = "{nope, start, |, l}" + >>> expression = "{nope, start, |, l}" >>> p.parse(expression) Traceback (most recent call last): SyntaxError: syntax error on line 1 position 1 near 'nope' >>> p = TemporalOperatorParser() - >>> expression = "{++, start, |, l}" + >>> expression = "{++, start, |, l}" >>> p.parse(expression) Traceback (most recent call last): SyntaxError: Unexpected syntax error in expression "{++, start, |, l}" at position 2 near + >>> p = TemporalOperatorParser() - >>> expression = "{^, over, right}" - >>> p.parse(expression, optype='rter') + >>> expression = "{^, over, right}" + >>> p.parse(expression, optype="rter") Traceback (most recent call last): SyntaxError: Unknown optype rter, must be one of ['select', 'boolean', 'raster', 'hash', 'relation', 'overlay'] -""" +""" # noqa: E501 try: import ply.lex as lex diff --git a/python/grass/temporal/temporal_raster_base_algebra.py b/python/grass/temporal/temporal_raster_base_algebra.py index 3fb3d31ad2a..dfae8f86863 100644 --- a/python/grass/temporal/temporal_raster_base_algebra.py +++ b/python/grass/temporal/temporal_raster_base_algebra.py @@ -14,7 +14,7 @@ >>> p = TemporalRasterAlgebraLexer() >>> p.build() >>> p.debug = True - >>> expression = 'R = A {+,equal,l} B' + >>> expression = "R = A {+,equal,l} B" >>> p.test(expression) R = A {+,equal,l} B LexToken(NAME,'R',1,0) @@ -22,7 +22,7 @@ LexToken(NAME,'A',1,4) LexToken(T_ARITH2_OPERATOR,'{+,equal,l}',1,6) LexToken(NAME,'B',1,18) - >>> expression = 'R = A {*,equal|during,r} B' + >>> expression = "R = A {*,equal|during,r} B" >>> p.test(expression) R = A {*,equal|during,r} B LexToken(NAME,'R',1,0) @@ -30,7 +30,7 @@ LexToken(NAME,'A',1,4) LexToken(T_ARITH1_OPERATOR,'{*,equal|during,r}',1,6) LexToken(NAME,'B',1,25) - >>> expression = 'R = A {+,equal|during} B' + >>> expression = "R = A {+,equal|during} B" >>> p.test(expression) R = A {+,equal|during} B LexToken(NAME,'R',1,0) @@ -119,7 +119,7 @@ def __init__(self): t_MULT = r"[\*]" t_ADD = r"[\+]" t_SUB = r"[-]" - t_T_ARITH1_OPERATOR = r"\{[\%\*\/][,]?[a-zA-Z\| ]*([,])?([lrudi]|left|right|union|disjoint|intersect)?\}" + t_T_ARITH1_OPERATOR = r"\{[\%\*\/][,]?[a-zA-Z\| ]*([,])?([lrudi]|left|right|union|disjoint|intersect)?\}" # noqa: E501 t_T_ARITH2_OPERATOR = ( r"\{[+-][,]?[a-zA-Z\| ]*([,])?([lrudi]|left|right|union|disjoint|intersect)?\}" ) @@ -245,23 +245,27 @@ def build_spatio_temporal_topology_list( >>> mapsA = [] >>> mapsB = [] >>> for i in range(10): - ... idA = "a%i@B"%(i) + ... idA = "a%i@B" % (i) ... mapA = tgis.RasterDataset(idA) ... mapA.uid = idA ... mapA.map_value = True - ... idB = "b%i@B"%(i) + ... idB = "b%i@B" % (i) ... mapB = tgis.RasterDataset(idB) ... mapB.uid = idB ... mapB.map_value = False - ... check = mapA.set_absolute_time(datetime(2000,1,i+1), - ... datetime(2000,1,i + 2)) - ... check = mapB.set_absolute_time(datetime(2000,1,i+6), - ... datetime(2000,1,i + 7)) + ... check = mapA.set_absolute_time( + ... datetime(2000, 1, i + 1), datetime(2000, 1, i + 2) + ... ) + ... check = mapB.set_absolute_time( + ... datetime(2000, 1, i + 6), datetime(2000, 1, i + 7) + ... ) ... mapsA.append(mapA) ... mapsB.append(mapB) + ... >>> resultlist = l.build_spatio_temporal_topology_list(mapsA, mapsB) >>> for map in resultlist: ... print(map.get_id()) + ... a5@B a6@B a7@B @@ -441,7 +445,8 @@ def compare_cmd_value( :return: Map object with conditional value that has been evaluated by comparison operators. """ - # Build command list list with elements from related maps and given relation operator. + # Build command list list with elements from related maps and given relation + # operator. if convert and "condition_value" in dir(map_i): if map_i.condition_value != []: cmdstring = str(int(map_i.condition_value[0])) @@ -509,7 +514,8 @@ def operator_cmd_value( temporal_relations = map_i.get_temporal_relations() spatial_relations = map_i.get_spatial_relations() - # Build comandlist list with elements from related maps and given relation operator. + # Build comandlist list with elements from related maps and given relation + # operator. leftcmd = map_i cmdstring = "" for topo in temporal_topo_list: @@ -577,7 +583,8 @@ def set_temporal_extent_list( base_map=map_i, bool_op="and", copy=True, rename=True ) - # Combine temporal and spatial extents of intermediate map with related maps. + # Combine temporal and spatial extents of intermediate map with related + # maps. for topo in topolist: if topo in tbrelations.keys(): for map_j in tbrelations[topo]: @@ -600,7 +607,8 @@ def set_temporal_extent_list( map_new, map_j, "and", temp_op=temporal ) - # Stop the loop if no temporal or spatial relationship exist. + # Stop the loop if no temporal or spatial relationship + # exist. if returncode == 0: break # Append map to result map list. @@ -608,7 +616,8 @@ def set_temporal_extent_list( # print(map_new.cmd_list) # resultlist.append(map_new) if cmd_bool: - # Create r.mapcalc expression string for the operation. + # Create r.mapcalc expression string for the + # operation. cmdstring = self.build_command_string( map_i, map_j, @@ -644,8 +653,10 @@ def build_condition_cmd_list( For Example: 'if(a1 == 1, b1, c2)' :param iflist: Map list with temporal extents and command list. - :param thenlist: Map list with temporal extents and command list or numeric string. - :param elselist: Map list with temporal extents and command list or numeric string. + :param thenlist: Map list with temporal extents and command list or numeric + string. + :param elselist: Map list with temporal extents and command list or numeric + string. :param condition_topolist: List of strings for given temporal relations between conditions and conclusions. :param conclusion_topolist: List of strings for given temporal relations between @@ -1784,7 +1795,7 @@ def p_s_numeric_condition_elif(self, t): | IF LPAREN ts_var_expr COMMA NULL LPAREN RPAREN COMMA number RPAREN | IF LPAREN ts_var_expr COMMA number COMMA NULL LPAREN RPAREN RPAREN | IF LPAREN ts_var_expr COMMA NULL LPAREN RPAREN COMMA NULL LPAREN RPAREN RPAREN - """ + """ # noqa: E501 ifmaplist = self.check_stds(t[3]) # Select input for r.mapcalc expression based on length of PLY object. if len(t) == 9: @@ -1895,7 +1906,7 @@ def p_s_numeric_expr_condition_elif_relation(self, t): | IF LPAREN T_REL_OPERATOR COMMA ts_var_expr COMMA stds COMMA NULL LPAREN RPAREN RPAREN | IF LPAREN T_REL_OPERATOR COMMA ts_var_expr COMMA expr COMMA number RPAREN | IF LPAREN T_REL_OPERATOR COMMA ts_var_expr COMMA expr COMMA NULL LPAREN RPAREN RPAREN - """ + """ # noqa: E501 relations, temporal, function, aggregation = self.eval_toperator( t[3], optype="relation" ) diff --git a/python/grass/temporal/temporal_topology_dataset_connector.py b/python/grass/temporal/temporal_topology_dataset_connector.py index a75a13ef54f..fddf478ad71 100644 --- a/python/grass/temporal/temporal_topology_dataset_connector.py +++ b/python/grass/temporal/temporal_topology_dataset_connector.py @@ -56,6 +56,8 @@ class TemporalTopologyDatasetConnector: start = start.next() + .. code-block:: python + >>> import grass.temporal as tgis >>> tgis.init() >>> map = tgis.RasterDataset("a@P") @@ -104,7 +106,8 @@ class TemporalTopologyDatasetConnector: finished=a@P >>> rlist = tmr.get_temporal_relations() >>> if "FINISHED" in rlist.keys(): - ... print(rlist["FINISHED"][0].get_id()) + ... print(rlist["FINISHED"][0].get_id()) + ... a@P """ @@ -504,7 +507,7 @@ def print_temporal_topology_info(self): """Print information about this class in human readable style""" print( - " +-------------------- Temporal Topology -------------------------------------+" + " +-------------------- Temporal Topology -------------------------------------+" # noqa: E501 ) # 0123456789012345678901234567890 if self.next() is not None: diff --git a/python/grass/temporal/temporal_vector_algebra.py b/python/grass/temporal/temporal_vector_algebra.py index 87341fb2c58..7b3f838d461 100644 --- a/python/grass/temporal/temporal_vector_algebra.py +++ b/python/grass/temporal/temporal_vector_algebra.py @@ -16,7 +16,7 @@ >>> p = tgis.TemporalVectorAlgebraLexer() >>> p.build() >>> p.debug = True - >>> expression = 'E = A : B ^ C : D' + >>> expression = "E = A : B ^ C : D" >>> p.test(expression) E = A : B ^ C : D LexToken(NAME,'E',1,0) @@ -28,7 +28,7 @@ LexToken(NAME,'C',1,12) LexToken(T_SELECT,':',1,14) LexToken(NAME,'D',1,16) - >>> expression = 'E = buff_a(A, 10)' + >>> expression = "E = buff_a(A, 10)" >>> p.test(expression) E = buff_a(A, 10) LexToken(NAME,'E',1,0) @@ -95,7 +95,7 @@ def __init__(self): t_XOR = r"\^" t_NOT = r"\~" # t_T_OVERLAY_OPERATOR = r'\{([a-zA-Z\|]+[,])?([\|&+=]?[\|&+=\^\~])\}' - t_T_OVERLAY_OPERATOR = r"\{[\|&+\^\~][,]?[a-zA-Z\| ]*([,])?([lrudi]|left|right|union|disjoint|intersect)?\}" + t_T_OVERLAY_OPERATOR = r"\{[\|&+\^\~][,]?[a-zA-Z\| ]*([,])?([lrudi]|left|right|union|disjoint|intersect)?\}" # noqa: E501 # Parse symbols def temporal_symbol(self, t): @@ -305,7 +305,8 @@ def overlay_cmd_value(self, map_i, tbrelations, function, topolist=["EQUAL"]): :return: Map object with command list with operators that has been evaluated by implicit aggregration. """ - # Build comandlist list with elements from related maps and given relation operator. + # Build comandlist list with elements from related maps and given relation + # operator. resultlist = [] # Define overlay operation dictionary. overlaydict = {"&": "and", "|": "or", "^": "xor", "~": "not", "+": "disor"} @@ -378,7 +379,7 @@ def set_temporal_extent_list(self, maplist, topolist=["EQUAL"], temporal="l"): map_new = self.generate_new_map( base_map=map_i, bool_op="and", copy=True, rename=False, remove=True ) - # Combine temporal and spatial extents of intermediate map with related maps. + # Combine temporal and spatial extents of intermediate map with related maps for topo in topolist: if topo in tbrelations.keys(): for map_j in tbrelations[topo]: @@ -445,20 +446,22 @@ def p_statement_assign(self, t): # Execute command list. for cmd in map_i.cmd_list: try: - # We need to check if the input maps have areas in case of v.overlay - # otherwise v.overlay will break + # We need to check if the input maps have areas in case + # of v.overlay. Otherwise v.overlay will break. if cmd.name == "v.overlay": for name in ( cmd.inputs["ainput"].value, cmd.inputs["binput"].value, ): - # self.msgr.message("Check if map <" + name + "> exists") + # self.msgr.message("Check if map <" + name + + # "> exists") if name.find("@") < 0: name = name + "@" + get_current_mapset() tmp_map = map_i.get_new_instance(name) if not tmp_map.map_exists(): raise Exception - # self.msgr.message("Check if map <" + name + "> has areas") + # self.msgr.message("Check if map <" + name + + # "> has areas") tmp_map.load() if tmp_map.metadata.get_number_of_areas() == 0: raise Exception @@ -502,7 +505,8 @@ def p_statement_assign(self, t): register_list.append(map_i) else: # Test if temporal extents have been changed by temporal - # relation operators (i|r). This is a code copy from temporal_algebra.py + # relation operators (i|r). This is a code copy from + # temporal_algebra.py map_i_extent = map_i.get_temporal_extent_as_tuple() map_test = map_i.get_new_instance(map_i.get_id()) map_test.select(dbif) @@ -557,11 +561,12 @@ def p_statement_assign(self, t): # Update map in temporal database. map_i.update_all(dbif=dbif) elif map_i.is_in_db(dbif=dbif) and self.overwrite is False: - # Raise error if map exists and no overwrite flag is given. + # Raise error if map exists and no overwrite flag is + # given. self.msgr.fatal( _( - "Error vector map %s exist in temporal database. " - "Use overwrite flag. : \n%s" + "Error vector map %s exist in temporal " + "database. Use overwrite flag. : \n%s" ) % (map_i.get_map_id(), cmd.outputs.stderr) ) diff --git a/python/grass/temporal/univar_statistics.py b/python/grass/temporal/univar_statistics.py index bb5475aec1e..5ae6f255d1b 100755 --- a/python/grass/temporal/univar_statistics.py +++ b/python/grass/temporal/univar_statistics.py @@ -7,7 +7,9 @@ import grass.temporal as tgis - tgis.print_gridded_dataset_univar_statistics(type, input, output, where, extended, no_header, fs, rast_region) + tgis.print_gridded_dataset_univar_statistics( + type, input, output, where, extended, no_header, fs, rast_region + ) .. @@ -33,10 +35,12 @@ def compute_univar_stats(registered_map_info, stats_module, fs, rast_region=False): - """Compute univariate statistics for a map of a space time raster or raster3d dataset + """Compute univariate statistics for a map of a space time raster or raster3d + dataset :param registered_map_info: dict or db row with tgis info for a registered map - :param stats_module: Pre-configured PyGRASS Module to compute univariate statistics with + :param stats_module: Pre-configured PyGRASS Module to compute univariate statistics + with :param fs: Field separator :param rast_region: If set True ignore the current region settings and use the raster map regions for univar statistical calculation. @@ -101,7 +105,8 @@ def compute_univar_stats(registered_map_info, stats_module, fs, rast_region=Fals if stats_module.inputs.percentile: for perc in stats_module.inputs.percentile: perc_value = stats[ - f"percentile_{str(perc).rstrip('0').rstrip('.').replace('.','_')}" + "percentile_" + f"{str(perc).rstrip('0').rstrip('.').replace('.','_')}" ] string += f"{fs}{perc_value}" string += eol @@ -217,7 +222,8 @@ def print_gridded_dataset_univar_statistics( if percentile: cols.extend( [ - f"percentile_{str(perc).rstrip('0').rstrip('.').replace('.','_')}" + "percentile_" + f"{str(perc).rstrip('0').rstrip('.').replace('.','_')}" for perc in percentile ] ) diff --git a/scripts/d.frame/d.frame.py b/scripts/d.frame/d.frame.py index 9459dfdbbaa..2d75457bee0 100755 --- a/scripts/d.frame/d.frame.py +++ b/scripts/d.frame/d.frame.py @@ -188,11 +188,11 @@ def calculate_frame(frame, at, width, height): This function does also the necessary formatting. - >>> calculate_frame('apple', "0,49.8,0,50.2", 500, 500) + >>> calculate_frame("apple", "0,49.8,0,50.2", 500, 500) 'GRASS_RENDER_FRAME=251,500,0,251 # apple\\n' - >>> calculate_frame('orange', "50.2,0,49.8,100", 500, 500) + >>> calculate_frame("orange", "50.2,0,49.8,100", 500, 500) 'GRASS_RENDER_FRAME=500,249,249,500 # orange\\n' - >>> calculate_frame('odd_number', "0,49.8,0,50.2", 367, 367) + >>> calculate_frame("odd_number", "0,49.8,0,50.2", 367, 367) 'GRASS_RENDER_FRAME=184,367,0,184 # odd_number\\n' The following would give 182,367,0,184 if we would be truncating @@ -201,7 +201,7 @@ def calculate_frame(frame, at, width, height): 0.502 times 367 is 184.234 which fits with the (correct) width of the frame which is 184. - >>> calculate_frame('test_truncating_bug', "0,50.2,0,50.2", 367, 367) + >>> calculate_frame("test_truncating_bug", "0,50.2,0,50.2", 367, 367) 'GRASS_RENDER_FRAME=183,367,0,184 # test_truncating_bug\\n' """ try: @@ -322,7 +322,8 @@ def main(): if options["at"]: warning( _( - "Frame <%s> already found. An existing frame can be overwritten by '%s' flag." + "Frame <%s> already found. An existing frame can be " + "overwritten by '%s' flag." ) % (options["frame"], "--overwrite") ) diff --git a/scripts/d.polar/d.polar.py b/scripts/d.polar/d.polar.py index 051b958de1d..c1c35080cc8 100755 --- a/scripts/d.polar/d.polar.py +++ b/scripts/d.polar/d.polar.py @@ -275,7 +275,7 @@ def plot_eps(psout): newpath %% coordinates of rescaled, translated outer circle follow %% first point moveto, then lineto -""" +""" # noqa: E501 ) s = t.substitute( AXESLINEWIDTH=axeslinewidth, @@ -322,7 +322,7 @@ def plot_eps(psout): newpath %% coordinates of rescaled, translated diagram follow %% first point moveto, then lineto -""" +""" # noqa: E501 ) s = t.substitute( AXESFONTSIZE=axesfontsize, @@ -364,7 +364,7 @@ def plot_eps(psout): newpath %% coordinates of rescaled, translated average direction follow %% first point moveto, second lineto -""" +""" # noqa: E501 ) s = t.substitute(DIAGRAMLINEWIDTH=diagramlinewidth) outf.write(s) @@ -396,7 +396,7 @@ def plot_eps(psout): col1 %% colAVERAGE-DIRECTION-COLOR %% Line below: (AVERAGE-DIRECTION-STRING) LEGENDS-X AVERAGE-DIRECTION-LEGEND-Y 4 just-string ($AVERAGEDIRECTIONSTRING) $LEGENDSX $AVERAGEDIRECTIONLEGENDY 4 just-string -""" +""" # noqa: E501 ) s = t.substitute( ALLDATALEGENDY=alldatalegendy, diff --git a/scripts/d.rast.edit/d.rast.edit.py b/scripts/d.rast.edit/d.rast.edit.py index a3e311079f6..4824a17a81c 100755 --- a/scripts/d.rast.edit/d.rast.edit.py +++ b/scripts/d.rast.edit/d.rast.edit.py @@ -107,7 +107,10 @@ "cols": ("cols", int), } -gray12_bits = b"\x00\x00\x22\x22\x00\x00\x88\x88\x00\x00\x22\x22\x00\x00\x88\x88\x00\x00\x22\x22\x00\x00\x88\x88\x00\x00\x22\x22\x00\x00\x88\x88" +gray12_bits = ( + b"\x00\x00\x22\x22\x00\x00\x88\x88\x00\x00\x22\x22\x00\x00\x88\x88\x00" + b"\x00\x22\x22\x00\x00\x88\x88\x00\x00\x22\x22\x00\x00\x88\x88" +) def run(cmd, **kwargs): diff --git a/scripts/g.extension/g.extension.py b/scripts/g.extension/g.extension.py index 36362928c1d..3fd497d78cd 100644 --- a/scripts/g.extension/g.extension.py +++ b/scripts/g.extension/g.extension.py @@ -16,8 +16,8 @@ # # TODO: - update temporary workaround of using grass7 subdir of addon-repo, see # https://github.com/OSGeo/grass-addons/issues/528 -# - add sudo support where needed (i.e. check first permission to write into -# $GISBASE directory) +# - add sudo support where needed (i.e. check first permission to write +# into $GISBASE directory) # - fix toolbox support in install_private_extension_xml() ############################################################################# @@ -224,9 +224,11 @@ def __init__( #: Attribute containing the URL to the online repository self.url = url self.major_grass_version = major_grass_version - #: Attribute flagging if the repository is structured like the official addons repository + #: Attribute flagging if the repository is structured like the official addons + # repository self.official_repository_structure = official_repository_structure - #: Attribute containing the path to the working directory where the repo is cloned out to + #: Attribute containing the path to the working directory where the repo is + # cloned out to if working_directory: self.working_directory = Path(working_directory).absolute() else: @@ -247,7 +249,8 @@ def __init__( self.default_branch = self._get_default_branch() #: Attribute containing the branch used for checkout self.branch = self._set_branch(branch) - #: Attribute containing list of addons in the repository with path to directories + #: Attribute containing list of addons in the repository with path to + # directories self.addons = self._get_addons_list() def _get_version(self): @@ -350,7 +353,8 @@ def _get_version_branch(self): def _set_branch(self, branch_name): """Set the branch to check out to either: a) a user defined branch - b) a version branch for repositories following the official addons repository structure + b) a version branch for repositories following the official addons repository + structure c) the default branch of the repository """ checkout_branch = None @@ -547,12 +551,12 @@ def get_default_branch(full_url): # Construct API call and retrieve default branch api_calls = { "github.com": f"https://api.github.com/repos/{organization}/{repository}", - "gitlab.com": f"https://gitlab.com/api/v4/projects/{organization}%2F{repository}", - "bitbucket.org": f"https://api.bitbucket.org/2.0/repositories/{organization}/{repository}/branching-model?", + "gitlab.com": f"https://gitlab.com/api/v4/projects/{organization}%2F{repository}", # noqa: E501 + "bitbucket.org": f"https://api.bitbucket.org/2.0/repositories/{organization}/{repository}/branching-model?", # noqa: E501 } - # Try to get default branch via API. The API call is known to fail a) if the full_url - # does not belong to an implemented hosting service or b) if the rate limit of the - # API is exceeded + # Try to get default branch via API. The API call is known to fail a) if the + # full_url does not belong to an implemented hosting service or b) if the rate + # limit of the API is exceeded try: req = urlrequest.urlopen(api_calls.get(url_parts.netloc)) content = json.loads(req.read()) @@ -606,9 +610,9 @@ def expand_module_class_name(class_letters): The letter or letters are used in module names, e.g. r.slope.aspect. The names are used in directories in Addons but also in the source code. - >>> expand_module_class_name('r') + >>> expand_module_class_name("r") 'raster' - >>> expand_module_class_name('v') + >>> expand_module_class_name("v") 'vector' """ name = { @@ -635,9 +639,9 @@ def get_module_class_name(module_name): The names are used in directories in Addons but also in the source code. - >>> get_module_class_name('r.slope.aspect') + >>> get_module_class_name("r.slope.aspect") 'raster' - >>> get_module_class_name('v.to.rast') + >>> get_module_class_name("v.to.rast") 'vector' """ classchar = module_name.split(".", 1)[0] @@ -1590,7 +1594,8 @@ def install_module_xml(mlist): tree.append(tnode) else: gs.verbose( - "Extension module already listed in metadata file; metadata not updated!" + "Extension module already listed in metadata file; metadata not " + "updated!" ) write_xml_modules(xml_file, tree) @@ -2503,9 +2508,9 @@ def resolve_xmlurl_prefix(url, source=None): It ensures that there is a single slash at the end of URL, so we can attach file name easily: - >>> resolve_xmlurl_prefix('https://grass.osgeo.org/addons') + >>> resolve_xmlurl_prefix("https://grass.osgeo.org/addons") 'https://grass.osgeo.org/addons/' - >>> resolve_xmlurl_prefix('https://grass.osgeo.org/addons/') + >>> resolve_xmlurl_prefix("https://grass.osgeo.org/addons/") 'https://grass.osgeo.org/addons/' """ gs.debug("resolve_xmlurl_prefix(url={0}, source={1})".format(url, source)) @@ -2655,58 +2660,62 @@ def resolve_source_code(url=None, name=None, branch=None, fork=False): Official repository: - >>> resolve_source_code(name='g.example') # doctest: +SKIP + >>> resolve_source_code(name="g.example") # doctest: +SKIP ('official', 'https://trac.osgeo.org/.../general/g.example') Subversion: - >>> resolve_source_code('https://svn.osgeo.org/grass/grass-addons/grass7') + >>> resolve_source_code("https://svn.osgeo.org/grass/grass-addons/grass7") ('svn', 'https://svn.osgeo.org/grass/grass-addons/grass7') ZIP files online: - >>> resolve_source_code('https://trac.osgeo.org/.../r.modis?format=zip') # doctest: +SKIP + >>> resolve_source_code( + ... "https://trac.osgeo.org/.../r.modis?format=zip" + ... ) # doctest: +SKIP ('remote_zip', 'https://trac.osgeo.org/.../r.modis?format=zip') Local directories and ZIP files: - >>> resolve_source_code(os.path.expanduser("~")) # doctest: +ELLIPSIS + >>> resolve_source_code(os.path.expanduser("~")) # doctest: +ELLIPSIS ('dir', '...') - >>> resolve_source_code('/local/directory/downloaded.zip') # doctest: +SKIP + >>> resolve_source_code("/local/directory/downloaded.zip") # doctest: +SKIP ('zip', '/local/directory/downloaded.zip') OSGeo Trac: - >>> resolve_source_code('trac.osgeo.org/.../r.agent.aco') # doctest: +SKIP + >>> resolve_source_code("trac.osgeo.org/.../r.agent.aco") # doctest: +SKIP ('remote_zip', 'https://trac.osgeo.org/.../r.agent.aco?format=zip') - >>> resolve_source_code('https://trac.osgeo.org/.../r.agent.aco') # doctest: +SKIP + >>> resolve_source_code("https://trac.osgeo.org/.../r.agent.aco") # doctest: +SKIP ('remote_zip', 'https://trac.osgeo.org/.../r.agent.aco?format=zip') GitHub: - >>> resolve_source_code('github.com/user/g.example') # doctest: +SKIP + >>> resolve_source_code("github.com/user/g.example") # doctest: +SKIP ('remote_zip', 'https://github.com/user/g.example/archive/master.zip') - >>> resolve_source_code('github.com/user/g.example/') # doctest: +SKIP + >>> resolve_source_code("github.com/user/g.example/") # doctest: +SKIP ('remote_zip', 'https://github.com/user/g.example/archive/master.zip') - >>> resolve_source_code('https://github.com/user/g.example') # doctest: +SKIP + >>> resolve_source_code("https://github.com/user/g.example") # doctest: +SKIP ('remote_zip', 'https://github.com/user/g.example/archive/master.zip') - >>> resolve_source_code('https://github.com/user/g.example/') # doctest: +SKIP + >>> resolve_source_code("https://github.com/user/g.example/") # doctest: +SKIP ('remote_zip', 'https://github.com/user/g.example/archive/master.zip') GitLab: - >>> resolve_source_code('gitlab.com/JoeUser/GrassModule') # doctest: +SKIP + >>> resolve_source_code("gitlab.com/JoeUser/GrassModule") # doctest: +SKIP ('remote_zip', 'https://gitlab.com/JoeUser/GrassModule/-/archive/master/GrassModule-master.zip') - >>> resolve_source_code('https://gitlab.com/JoeUser/GrassModule') # doctest: +SKIP + >>> resolve_source_code("https://gitlab.com/JoeUser/GrassModule") # doctest: +SKIP ('remote_zip', 'https://gitlab.com/JoeUser/GrassModule/-/archive/master/GrassModule-master.zip') Bitbucket: - >>> resolve_source_code('bitbucket.org/joe-user/grass-module') # doctest: +SKIP + >>> resolve_source_code("bitbucket.org/joe-user/grass-module") # doctest: +SKIP ('remote_zip', 'https://bitbucket.org/joe-user/grass-module/get/default.zip') - >>> resolve_source_code('https://bitbucket.org/joe-user/grass-module') # doctest: +SKIP + >>> resolve_source_code( + ... "https://bitbucket.org/joe-user/grass-module" + ... ) # doctest: +SKIP ('remote_zip', 'https://bitbucket.org/joe-user/grass-module/get/default.zip') - """ + """ # noqa: E501 # Handle URL for the official repo if not url or url == GIT_URL: return "official", GIT_URL diff --git a/scripts/i.image.mosaic/i.image.mosaic.py b/scripts/i.image.mosaic/i.image.mosaic.py index ddd89553b22..65ac5f2e38c 100755 --- a/scripts/i.image.mosaic/i.image.mosaic.py +++ b/scripts/i.image.mosaic/i.image.mosaic.py @@ -12,8 +12,9 @@ # License (>=v2). Read the file COPYING that comes with GRASS # for details. # -# TODO: - implement g.findfile for 3 and 4 maps (currently only current mapset supported) -# [done for 2 maps] +# TODO: - implement g.findfile for 3 and 4 maps (currently only current mapset +# supported) +# [done for 2 maps] # - fix isnull() in r.mapcalc for 3 and 4 maps composites # [done for 2 maps] # - fix color table length (currently only 256 cols supported, make diff --git a/scripts/i.in.spotvgt/i.in.spotvgt.py b/scripts/i.in.spotvgt/i.in.spotvgt.py index e0e0911c81a..1ee52d11c40 100755 --- a/scripts/i.in.spotvgt/i.in.spotvgt.py +++ b/scripts/i.in.spotvgt/i.in.spotvgt.py @@ -67,7 +67,7 @@ -""" +""" # noqa: E501 # a function for writing VRT files diff --git a/scripts/i.pansharpen/i.pansharpen.py b/scripts/i.pansharpen/i.pansharpen.py index dc6f15bcb5e..d0b06e53727 100755 --- a/scripts/i.pansharpen/i.pansharpen.py +++ b/scripts/i.pansharpen/i.pansharpen.py @@ -426,7 +426,8 @@ def main(): grass.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'] + # 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.stdin.close() @@ -649,9 +650,9 @@ def pca(pan, ms1, ms2, ms3, out, pid, sproc): outg = "%s_green" % out outb = "%s_blue" % out - cmd1 = "$outb = 1 * round(($panmatch1 * $b1evect1) + ($pca2 * $b1evect2) + ($pca3 * $b1evect3) + $b1mean)" - cmd2 = "$outg = 1 * round(($panmatch2 * $b2evect1) + ($pca2 * $b2evect2) + ($pca3 * $b2evect3) + $b2mean)" - cmd3 = "$outr = 1 * round(($panmatch3 * $b3evect1) + ($pca2 * $b3evect2) + ($pca3 * $b3evect3) + $b3mean)" + cmd1 = "$outb = 1 * round(($panmatch1 * $b1evect1) + ($pca2 * $b1evect2) + ($pca3 * $b1evect3) + $b1mean)" # noqa: E501 + cmd2 = "$outg = 1 * round(($panmatch2 * $b2evect1) + ($pca2 * $b2evect2) + ($pca3 * $b2evect3) + $b2mean)" # noqa: E501 + cmd3 = "$outr = 1 * round(($panmatch3 * $b3evect1) + ($pca2 * $b3evect2) + ($pca3 * $b3evect3) + $b3mean)" # noqa: E501 cmd = "\n".join([cmd1, cmd2, cmd3]) diff --git a/scripts/r.colors.stddev/r.colors.stddev.py b/scripts/r.colors.stddev/r.colors.stddev.py index c7ff5a51770..e8d4321939f 100755 --- a/scripts/r.colors.stddev/r.colors.stddev.py +++ b/scripts/r.colors.stddev/r.colors.stddev.py @@ -81,7 +81,8 @@ def main(): # r.reclass input="$GIS_OPT_MAP" output="${GIS_OPT_MAP}.stdevs" << # EOF - # >3 S.D. outliers colored black so they show up in d.histogram w/ white background + # >3 S.D. outliers colored black so they show up in d.histogram w/ white + # background rules = "\n".join( [ "0% black", @@ -132,7 +133,8 @@ def main(): else: # zero centered banded black/red/yellow/green/yellow/red/black - # >3 S.D. outliers colored black so they show up in d.histogram w/ white background + # >3 S.D. outliers colored black so they show up in d.histogram w/ white + # background rules = "\n".join( [ "%f black" % -maxv, diff --git a/scripts/r.fillnulls/r.fillnulls.py b/scripts/r.fillnulls/r.fillnulls.py index 219f9dafa07..7744d01ca25 100755 --- a/scripts/r.fillnulls/r.fillnulls.py +++ b/scripts/r.fillnulls/r.fillnulls.py @@ -188,7 +188,10 @@ def main(): if usermask: grass.message(_("Skipping masked raster parts")) grass.mapcalc( - '$tmp1 = if(isnull("$input") && !($mask == 0 || isnull($mask)),1,null())', + ( + '$tmp1 = if(isnull("$input") && !($mask == 0 || isnull($mask)),1,' + "null())" + ), tmp1=prefix + "nulls", input=input, mask=usermask, @@ -232,7 +235,8 @@ def main(): ) ) - # assign unique IDs to each hole or hole system (holes closer than edge distance) + # assign unique IDs to each hole or hole system (holes closer than edge + # distance) grass.message(_("Assigning IDs to NULL areas")) tmp_rmaps.append(prefix + "clumped") try: @@ -302,7 +306,8 @@ def main(): ) grass.warning( _( - "Input map <%s> has no holes. Copying to output without modification." + "Input map <%s> has no holes. Copying to output without " + "modification." ) % (input,) ) @@ -488,7 +493,8 @@ def main(): failed_list.append(holename) continue - # append hole result to interpolated version later used to patch into original DEM + # append hole result to interpolated version later used to patch into + # original DEM if first: tmp_rmaps.append(filling) grass.run_command( @@ -572,7 +578,8 @@ def main(): except CalledModuleError: grass.fatal( _( - "abandoned. Removing temporary maps, restoring user mask if needed:" + "abandoned. Removing temporary maps, restoring user mask if " + "needed:" ) ) @@ -616,7 +623,8 @@ def main(): p.returncode = 0 grass.warning( _( - "Input map <%s> has no holes. Copying to output without modification." + "Input map <%s> has no holes. Copying to output without " + "modification." ) % (input,) ) @@ -648,7 +656,8 @@ def main(): p.returncode = 0 grass.warning( _( - "Input map <%s> has no holes. Copying to output without modification." + "Input map <%s> has no holes. Copying to output without " + "modification." ) % (input,) ) diff --git a/scripts/r.import/r.import.py b/scripts/r.import/r.import.py index b49fdb2439a..f9f2db56b75 100644 --- a/scripts/r.import/r.import.py +++ b/scripts/r.import/r.import.py @@ -179,7 +179,8 @@ def main(): elif tgtres == "value": grass.fatal( _( - "Please provide the resolution for the imported dataset or change to 'estimated' resolution" + "Please provide the resolution for the imported dataset or change to " + "'estimated' resolution" ) ) diff --git a/scripts/r.in.srtm/r.in.srtm.py b/scripts/r.in.srtm/r.in.srtm.py index d88a560d49c..3aa4db4f6be 100755 --- a/scripts/r.in.srtm/r.in.srtm.py +++ b/scripts/r.in.srtm/r.in.srtm.py @@ -133,7 +133,10 @@ [ "GEOGCS[", '"wgs84",', - 'DATUM["WGS_1984",SPHEROID["wgs84",6378137,298.257223563],TOWGS84[0.000000,0.000000,0.000000]],', + ( + 'DATUM["WGS_1984",SPHEROID["wgs84",6378137,298.257223563],TOWGS84[0.000000,' + "0.000000,0.000000]]," + ), 'PRIMEM["Greenwich",0],', 'UNIT["degree",0.0174532925199433]', "]", diff --git a/scripts/r.in.wms/r.in.wms.py b/scripts/r.in.wms/r.in.wms.py index dccfc8e3517..cc571dbd878 100755 --- a/scripts/r.in.wms/r.in.wms.py +++ b/scripts/r.in.wms/r.in.wms.py @@ -264,7 +264,8 @@ def main(): if "GRASS" in options["driver"]: grass.warning( _( - "The proxy will be ignored by the chosen GRASS driver. It is only used with the GDAL driver." + "The proxy will be ignored by the chosen GRASS driver. It is " + "only used with the GDAL driver." ) ) diff --git a/scripts/r.in.wms/srs.py b/scripts/r.in.wms/srs.py index 6840e72dca5..460e3c14fc1 100644 --- a/scripts/r.in.wms/srs.py +++ b/scripts/r.in.wms/srs.py @@ -1,5 +1,6 @@ """! -@brief WMS, WMTS and NASA OnEarth drivers implemented in GRASS using GDAL Python bindings. +@brief WMS, WMTS and NASA OnEarth drivers implemented in GRASS using GDAL Python +bindings. List of classes: - srs.py::Srs @@ -9,7 +10,8 @@ This program is free software under the GNU General Public License (>=v2). Read the file COPYING that comes with GRASS for details. -@author Stepan Turek (Based on code from OWSLib - Copyright below) +@author Stepan Turek (Based on code from OWSLib - Copyright + below) """ # -*- coding: ISO-8859-15 -*- diff --git a/scripts/r.in.wms/wms_base.py b/scripts/r.in.wms/wms_base.py index cf2a9c1c38f..b2b74e3e6c6 100644 --- a/scripts/r.in.wms/wms_base.py +++ b/scripts/r.in.wms/wms_base.py @@ -1,5 +1,6 @@ """! -@brief Preparation of parameters for drivers, which download it, and managing downloaded data. +@brief Preparation of parameters for drivers, which download it, and managing + downloaded data. List of classes: - wms_base::WMSBase @@ -108,7 +109,8 @@ def _initializeParameters(self, options, flags): self.params["wms_version"] = "1.3.0" grass.warning( _( - "WMS version <1.3.0> will be used, because version <1.1.1> does not support <%s>projection" + "WMS version <1.3.0> will be used, because version <1.1.1> does " + "not support <%s>projection" ) % GetSRSParamVal(self.params["srs"]) ) @@ -130,7 +132,8 @@ def _initializeParameters(self, options, flags): if self.source_epsg != self.target_epsg: grass.warning( _( - "SRS differences: WMS source EPSG %s != location EPSG %s (use srs=%s to adjust)" + "SRS differences: WMS source EPSG %s != location EPSG %s (use " + "srs=%s to adjust)" ) % (self.source_epsg, self.target_epsg, self.target_epsg) ) @@ -173,14 +176,16 @@ def _initializeParameters(self, options, flags): def _modifyProj(self, proj): """!Modify proj.4 string for usage in this module""" - # add +wktext parameter to avoid dropping of +nadgrids parameter (if presented) in gdalwarp + # add +wktext parameter to avoid dropping of +nadgrids parameter (if presented) + # in gdalwarp if "+nadgrids=" in proj and " +wktext" not in proj: proj += " +wktext" return proj def _checkIgnoeredParams(self, options, flags, driver_props): - """!Write warnings for set parameters and flags, which chosen driver does not use.""" + """!Write warnings for set parameters and flags, which chosen driver does not + use.""" not_relevant_params = [] for i_param in driver_props["ignored_params"]: diff --git a/scripts/r.in.wms/wms_cap_parsers.py b/scripts/r.in.wms/wms_cap_parsers.py index 8418bbdbbe6..40a7d63d3af 100644 --- a/scripts/r.in.wms/wms_cap_parsers.py +++ b/scripts/r.in.wms/wms_cap_parsers.py @@ -85,7 +85,8 @@ def Ns(self, tag_name): class WMSCapabilitiesTree(BaseCapabilitiesTree): def __init__(self, cap_file, force_version=None): """!Parses WMS capabilities file. - If the capabilities file cannot be parsed if it raises xml.etree.ElementTree.ParseError. + If the capabilities file cannot be parsed if it raises + xml.etree.ElementTree.ParseError. The class manges inheritance in 'Layer' elements. Inherited elements are added to 'Layer' element. @@ -201,8 +202,10 @@ def _inhNotSame(self, element_name, cmp_type, layer, parent_layer, add_arg=None) @param element_name - name of inherited element @param cmp_type - 'element_content' - compared value is text of element - @param cmp_type - 'child_element_content' - compared value is text of a child of the element - @param cmp_type - 'attribute' - compared value is text of the element attribute + @param cmp_type - 'child_element_content' - compared value is text of a child + of the element + @param cmp_type - 'attribute' - compared value is text of the element + attribute @param layer - element which inherits @param parent_layer - element which is inherited from @param add_arg - name of child element or attribute @@ -310,10 +313,12 @@ def NsOws(self, tag): class WMTSCapabilitiesTree(BaseCapabilitiesTree): def __init__(self, cap_file): """!Parses WMTS capabilities file. - If the capabilities file cannot be parsed it raises xml.etree.ElementTree.ParseError. + If the capabilities file cannot be parsed it raises + xml.etree.ElementTree.ParseError. The class also removes elements which are in invalid form and are needed - by wxGUI capabilities dialog or for creation of GetTile request by GRASS WMS library. + by wxGUI capabilities dialog or for creation of GetTile request by GRASS WMS + library. @param cap_file - capabilities file """ @@ -551,7 +556,8 @@ def __init__(self, cap_file): If the file cannot be parsed it raises xml.etree.ElementTree.ParseError. The class also removes elements which are in invalid form and are needed - by wxGUI capabilities dialog or for creation of GetMap request by GRASS WMS library. + by wxGUI capabilities dialog or for creation of GetMap request by GRASS WMS + library. @param cap_file - capabilities file """ diff --git a/scripts/r.in.wms/wms_drv.py b/scripts/r.in.wms/wms_drv.py index df592624031..51c9f2037c4 100644 --- a/scripts/r.in.wms/wms_drv.py +++ b/scripts/r.in.wms/wms_drv.py @@ -1,5 +1,6 @@ """! -@brief WMS, WMTS and NASA OnEarth drivers implemented in GRASS using GDAL Python bindings. +@brief WMS, WMTS and NASA OnEarth drivers implemented in GRASS using GDAL Python +bindings. List of classes: - wms_drv::WMSDrv @@ -26,7 +27,8 @@ except: grass.fatal( _( - "Unable to load GDAL Python bindings (requires package 'python-gdal' being installed)" + "Unable to load GDAL Python bindings (requires package 'python-gdal' " + "being installed)" ) ) @@ -103,7 +105,8 @@ def _download(self): # url for request the tile query_url = tile[0] - # the tile size and offset in pixels for placing it into raster where tiles are joined + # the tile size and offset in pixels for placing it into raster where tiles + # are joined tile_ref = tile[1] grass.debug(query_url, 2) try: @@ -129,8 +132,9 @@ def _download(self): temp_tile_opened = open(temp_tile, "wb") temp_tile_opened.write(wms_data.read()) except OSError as e: - # some servers are not happy with many subsequent requests for tiles done immediately, - # if immediate request was unsuccessful, try to repeat the request after 5s and 30s breaks + # some servers are not happy with many subsequent requests for tiles + # done immediately, if immediate request was unsuccessful, try to + # repeat the request after 5s and 30s breaks # TODO probably servers can return more kinds of errors related to this # problem (not only 104) if isinstance(e, socket.error) and e[0] == 104 and fetch_try < 2: @@ -143,7 +147,8 @@ def _download(self): grass.warning( _( - "Server refused to send data for a tile.\nRequest will be repeated after %d s." + "Server refused to send data for a tile.\nRequest will be " + "repeated after %d s." ) % sleep_time ) @@ -177,7 +182,8 @@ def _download(self): if tile_dataset_info.RasterCount < 1: grass.fatal( _( - "WMS server error: no band(s) received. Is server URL correct? <%s>" + "WMS server error: no band(s) received. Is server URL correct? " + "<%s>" ) % server_url ) @@ -268,7 +274,8 @@ def _download(self): return temp_map def _pct2rgb(self, src_filename, dst_filename): - """!Create new dataset with data in dst_filename with bands according to src_filename + """!Create new dataset with data in dst_filename with bands according to + src_filename raster color table - modified code from gdal utility pct2rgb @return new dataset @@ -321,7 +328,8 @@ class BaseRequestMgr: """!Base class for request managers.""" def _computeRequestData(self, bbox, tl_corner, tile_span, tile_size, mat_num_bbox): - """!Initialize data needed for iteration through tiles. Used by WMTS_GRASS and OnEarth_GRASS drivers.""" + """!Initialize data needed for iteration through tiles. Used by WMTS_GRASS and + OnEarth_GRASS drivers.""" epsilon = 1e-15 # request data bbox specified in row and col number @@ -446,7 +454,8 @@ def __init__(self, params, bbox, region, tile_size, proj_srs, cap_file=None): proj = params["proj_name"] + "=" + GetSRSParamVal(params["srs"]) self.url = params["url"] + ( - "SERVICE=WMS&REQUEST=GetMap&VERSION=%s&LAYERS=%s&WIDTH=%s&HEIGHT=%s&STYLES=%s&TRANSPARENT=%s" + "SERVICE=WMS&REQUEST=GetMap&VERSION=%s&LAYERS=%s&WIDTH=%s&HEIGHT=%s&" + "STYLES=%s&TRANSPARENT=%s" % ( params["wms_version"], params["layers"], @@ -511,11 +520,13 @@ def __init__(self, params, bbox, region, tile_size, proj_srs, cap_file=None): self.map_region["rows"] = rows def GetMapRegion(self): - """!Get size in pixels and bounding box of raster where all tiles will be merged.""" + """!Get size in pixels and bounding box of raster where all tiles will be + merged.""" return self.map_region def GetNextTile(self): - """!Get url for tile request from server and information for merging the tile with other tiles""" + """!Get url for tile request from server and information for merging the tile + with other tiles""" tile_ref = {} @@ -636,7 +647,8 @@ def __init__(self, params, bbox, region, proj_srs, cap_file=None): mat_set.findall(self.xml_ns.NsWmts("TileMatrix")), region, bbox ) - # get extend of data available on server expressed in max/min rows and cols of tile matrix + # get extend of data available on server expressed in max/min rows and cols of + # tile matrix mat_num_bbox = self._getMatSize(tile_mat, mat_set_link) # initialize data needed for iteration through tiles @@ -645,11 +657,13 @@ def __init__(self, params, bbox, region, proj_srs, cap_file=None): ) def GetMapRegion(self): - """!Get size in pixels and bounding box of raster where all tiles will be merged.""" + """!Get size in pixels and bounding box of raster where all tiles will be + merged.""" return self.map_region def _getMatSets(self, root, layer_name, srs): - """!Get matrix sets which are available for chosen layer and have required EPSG.""" + """!Get matrix sets which are available for chosen layer and have required + EPSG.""" contents = root.find(self.xml_ns.NsWmts("Contents")) layers = contents.findall(self.xml_ns.NsWmts("Layer")) @@ -731,7 +745,8 @@ def _findTileMats(self, tile_mats, region, bbox): return best_t_mat def _getMetersPerUnit(self): - """!Get coefficient which allows converting units of request projection into meters.""" + """!Get coefficient which allows converting units of request projection into + meters.""" if self.meters_per_unit: return self.meters_per_unit @@ -760,7 +775,8 @@ def _getMetersPerUnit(self): return self.meters_per_unit def _getMatSize(self, tile_mat, mat_set_link): - """!Get rows and cols extend of data available on server for chosen layer and tile matrix.""" + """!Get rows and cols extend of data available on server for chosen layer and + tile matrix.""" # general tile matrix size mat_num_bbox = {} @@ -817,7 +833,8 @@ def _computeRequestData(self, tile_mat, params, bbox, mat_num_bbox, mat_set_srs) tl_corner["minx"] = float(tl_str[0]) tl_corner["maxy"] = float(tl_str[1]) - # TODO do it more generally WMS cap parser may use it in future(not needed now)??? + # TODO do it more generally WMS cap parser may use it in future(not needed + # now)??? s = Srs( mat_set_srs ) # NOTE not used params['srs'], it is just number, encoding needed @@ -858,7 +875,8 @@ def _computeRequestData(self, tile_mat, params, bbox, mat_num_bbox, mat_set_srs) ) def GetNextTile(self): - """!Get url for tile request from server and information for merging the tile with other tiles.""" + """!Get url for tile request from server and information for merging the tile + with other tiles.""" if not self.intersects or self.i_col > self.t_num_bbox["max_col"]: return None @@ -905,7 +923,8 @@ def __init__(self, params, bbox, region, proj_srs, tile_service): self._computeRequestData(bbox, t_patt_bbox, self.tile_span, self.tile_size) def GetMapRegion(self): - """!Get size in pixels and bounding box of raster where all tiles will be merged.""" + """!Get size in pixels and bounding box of raster where all tiles will be + merged.""" return self.map_region def _parseTileService(self, root, bbox, region, params): @@ -1011,7 +1030,8 @@ def _parseTilePattern(self, group_t_patts, bbox, region): def _insTimeToTilePatternUrl(self, url_params, urls): """!Time can be variable in some urls in OnEarth TMS. - Insert requested time from 'urlparams' into the variable if any url of urls contains the variable. + Insert requested time from 'urlparams' into the variable if any url of urls + contains the variable. """ url = None not_sup_params = [] @@ -1055,7 +1075,8 @@ def _insTimeToTilePatternUrl(self, url_params, urls): if not_sup_params: grass.warning( _( - "%s driver supports only '%s' parameter in '%s'. Other parameters are ignored." + "%s driver supports only '%s' parameter in '%s'. Other parameters " + "are ignored." ) % ("OnEarth GRASS", "time", "urlparams") ) @@ -1080,7 +1101,8 @@ def _computeRequestData(self, bbox, t_patt_bbox, tile_span, tile_size): ) def GetNextTile(self): - """!Get url for tile request from server and information for merging the tile with other tiles""" + """!Get url for tile request from server and information for merging the tile + with other tiles""" if self.i_col > self.t_num_bbox["max_col"]: return None diff --git a/scripts/r.in.wms/wms_gdal_drv.py b/scripts/r.in.wms/wms_gdal_drv.py index 479318e4f4f..353de1a679c 100644 --- a/scripts/r.in.wms/wms_gdal_drv.py +++ b/scripts/r.in.wms/wms_gdal_drv.py @@ -20,7 +20,8 @@ except: grass.fatal( _( - "Unable to load GDAL Python bindings (requires package 'python-gdal' being installed)" + "Unable to load GDAL Python bindings (requires package 'python-gdal' being " + "installed)" ) ) @@ -144,7 +145,8 @@ def _download(self): grass.warning( _( "If module will not be able to fetch the data in this " - + "geographic projection, \n try 'WMS_GRASS' driver or use WMS version 1.1.1." + "geographic projection, \n try 'WMS_GRASS' driver or use WMS " + "version 1.1.1." ) ) diff --git a/scripts/r.mask/r.mask.py b/scripts/r.mask/r.mask.py index e33788dffc1..969c35ad9d4 100755 --- a/scripts/r.mask/r.mask.py +++ b/scripts/r.mask/r.mask.py @@ -122,7 +122,8 @@ def main(): if not grass.overwrite(): grass.fatal( _( - "MASK already found in current mapset. Delete first or overwrite." + "MASK already found in current mapset. Delete first or " + "overwrite." ) ) else: diff --git a/scripts/r.reclass.area/r.reclass.area.py b/scripts/r.reclass.area/r.reclass.area.py index 8809ccb042e..9e579eb5f10 100755 --- a/scripts/r.reclass.area/r.reclass.area.py +++ b/scripts/r.reclass.area/r.reclass.area.py @@ -180,7 +180,8 @@ def reclass(inf, outf, lim, clump, diag, les): def rmarea(infile, outfile, thresh, coef): # transform user input from hectares to map units (kept this for future) # thresh = thresh * 10000.0 / (float(coef)**2) - # grass.debug("Threshold: %d, coeff linear: %s, coef squared: %d" % (thresh, coef, (float(coef)**2)), 0) + # grass.debug("Threshold: %d, coeff linear: %s, coef squared: %d" % + # (thresh, coef, (float(coef)**2)), 0) # transform user input from hectares to meters because currently v.clean # rmarea accept only meters as threshold diff --git a/scripts/r.tileset/r.tileset.py b/scripts/r.tileset/r.tileset.py index 240a0911d58..13e970aeaab 100644 --- a/scripts/r.tileset/r.tileset.py +++ b/scripts/r.tileset/r.tileset.py @@ -333,15 +333,17 @@ def main(): # Find the skewedness of the two directions. # Define it to be greater than one - # In the direction (x or y) in which the world is least skewed (ie north south in lat long) - # Divide the world into strips. These strips are as big as possible constrained by max_ + # In the direction (x or y) in which the world is least skewed (ie north south in + # lat long) + # Divide the world into strips. These strips are as big as possible constrained by + # max_ # In the other direction do the same thing. # There's some recomputation of the size of the world that's got to come in # here somewhere. - # For now, however, we are going to go ahead and request more data than is necessary. - # For small regions far from the critical areas of projections this makes very little difference - # in the amount of data gotten. + # For now, however, we are going to go ahead and request more data than is + # necessary. For small regions far from the critical areas of projections this + # makes very little difference in the amount of data gotten. # We can make this efficient for big regions or regions near critical # points later. diff --git a/scripts/r.unpack/r.unpack.py b/scripts/r.unpack/r.unpack.py index 63b66ad65d9..a19123b28f0 100644 --- a/scripts/r.unpack/r.unpack.py +++ b/scripts/r.unpack/r.unpack.py @@ -153,7 +153,8 @@ def main(): if os.path.exists(proj_info_file_2): grass.fatal( _( - "PROJ_INFO file is missing, unpack raster map in XY (unprojected) project." + "PROJ_INFO file is missing, unpack raster map in XY " + "(unprojected) project." ) ) skip_projection_check = True # XY location diff --git a/scripts/v.db.renamecolumn/v.db.renamecolumn.py b/scripts/v.db.renamecolumn/v.db.renamecolumn.py index 87f1850a57c..edcd89c0935 100755 --- a/scripts/v.db.renamecolumn/v.db.renamecolumn.py +++ b/scripts/v.db.renamecolumn/v.db.renamecolumn.py @@ -63,7 +63,8 @@ def main(): if not table: grass.fatal( _( - "There is no table connected to the input vector map. Cannot rename any column" + "There is no table connected to the input vector map. Cannot rename " + "any column" ) ) @@ -75,7 +76,8 @@ def main(): if len(newcol) > 10: grass.fatal( _( - "Column name <%s> too long. The DBF driver supports column names not longer than 10 characters" + "Column name <%s> too long. The DBF driver supports column names " + "not longer than 10 characters" ) % newcol ) @@ -83,7 +85,8 @@ def main(): if oldcol == keycol: grass.fatal( _( - "Cannot rename column <%s> as it is needed to keep table <%s> connected to the input vector map" + "Cannot rename column <%s> as it is needed to keep table <%s> " + "connected to the input vector map" ) % (oldcol, table) ) diff --git a/scripts/v.dissolve/v.dissolve.py b/scripts/v.dissolve/v.dissolve.py index c0700c4eebf..b5e030ad573 100755 --- a/scripts/v.dissolve/v.dissolve.py +++ b/scripts/v.dissolve/v.dissolve.py @@ -362,7 +362,8 @@ def create_or_check_result_columns_or_fatal( "Result column '{column}' needs a type " "specified (using the syntax: 'name type') " "when no methods are provided with the " - "{option_name} option and aggregation backend is '{backend}'" + "{option_name} option and aggregation backend is " + "'{backend}'" ).format( column=column, option_name="aggregate_methods", @@ -586,7 +587,8 @@ def main(): if not column: gs.warning( _( - "No '%s' option specified. Dissolving based on category values from layer <%s>." + "No '%s' option specified. Dissolving based on category values from " + "layer <%s>." ) % ("column", layer) ) diff --git a/scripts/v.import/v.import.py b/scripts/v.import/v.import.py index 809c18243bd..8bb95fa8737 100755 --- a/scripts/v.import/v.import.py +++ b/scripts/v.import/v.import.py @@ -269,7 +269,8 @@ def main(): except: grass.fatal( _( - "Unable to load GDAL Python bindings (requires package 'python-gdal' being installed)" + "Unable to load GDAL Python bindings (requires package " + "'python-gdal' being installed)" ) ) if int(gdal.VersionInfo("VERSION_NUM")) < GDAL_COMPUTE_VERSION(2, 4, 1): @@ -345,7 +346,8 @@ def main(): except: grass.fatal( _( - "Unable to load GDAL Python bindings (requires package 'python-gdal' being installed)" + "Unable to load GDAL Python bindings (requires package " + "'python-gdal' being installed)" ) ) if int(gdal.VersionInfo("VERSION_NUM")) < GDAL_COMPUTE_VERSION(2, 4, 1): diff --git a/scripts/v.in.geonames/v.in.geonames.py b/scripts/v.in.geonames/v.in.geonames.py index 401cca5c134..5a5653c2157 100755 --- a/scripts/v.in.geonames/v.in.geonames.py +++ b/scripts/v.in.geonames/v.in.geonames.py @@ -59,7 +59,8 @@ def main(): if dbfdriver: grass.warning( _( - "Since DBF driver is used, the content of the 'alternatenames' column might be cut with respect to the original Geonames.org column content" + "Since DBF driver is used, the content of the 'alternatenames' column " + "might be cut with respect to the original Geonames.org column content" ) ) diff --git a/scripts/v.rast.stats/v.rast.stats.py b/scripts/v.rast.stats/v.rast.stats.py index cea37e38cca..c5a288a749d 100644 --- a/scripts/v.rast.stats/v.rast.stats.py +++ b/scripts/v.rast.stats/v.rast.stats.py @@ -133,7 +133,8 @@ def main(): except KeyError: grass.fatal( _( - "There is no table connected to this map. Run v.db.connect or v.db.addtable first." + "There is no table connected to this map. Run v.db.connect or " + "v.db.addtable first." ) ) # we need this for non-DBF driver: diff --git a/scripts/v.report/v.report.py b/scripts/v.report/v.report.py index f5284f97bf7..80ece04aeb5 100755 --- a/scripts/v.report/v.report.py +++ b/scripts/v.report/v.report.py @@ -141,8 +141,8 @@ def main(): grass.fatal( _( "There is a table connected to input vector map '%s', but " - "there are no categories present in the key column '%s'. Consider using " - "v.to.db to correct this." + "there are no categories present in the key column '%s'. " + "Consider using v.to.db to correct this." ) % (mapname, f["key"]) ) diff --git a/scripts/v.unpack/v.unpack.py b/scripts/v.unpack/v.unpack.py index 04070770ec9..bd350676444 100644 --- a/scripts/v.unpack/v.unpack.py +++ b/scripts/v.unpack/v.unpack.py @@ -154,7 +154,8 @@ def main(): if os.path.exists(loc_proj): grass.fatal( _( - "PROJ_INFO file is missing, unpack vector map in XY (unprojected) project." + "PROJ_INFO file is missing, unpack vector map in XY (unprojected) " + "project." ) ) skip_projection_check = True # XY location diff --git a/temporal/t.info/t.info.py b/temporal/t.info/t.info.py index 24faee35940..dd86e8123ef 100755 --- a/temporal/t.info/t.info.py +++ b/temporal/t.info/t.info.py @@ -79,7 +79,7 @@ def main(): if system and not shellstyle and not history: # 0123456789012345678901234567890 print( - " +------------------- Temporal DBMI backend information ----------------------+" + " +------------------- Temporal DBMI backend information ----------------------+" # noqa: E501 ) print(" | DBMI Python interface:...... " + str(dbif.get_dbmi().__name__)) print(" | Temporal database string:... " + str(tgis.get_tgis_database_string())) @@ -88,7 +88,7 @@ def main(): for row in rows: print(" | %s .......... %s" % (row[0], row[1])) print( - " +----------------------------------------------------------------------------+" + " +----------------------------------------------------------------------------+" # noqa: E501 ) return elif system and not history: diff --git a/temporal/t.list/t.list.py b/temporal/t.list/t.list.py index 26be3c9b453..7f8de190a45 100755 --- a/temporal/t.list/t.list.py +++ b/temporal/t.list/t.list.py @@ -143,14 +143,16 @@ def main(): if issubclass(sp.__class__, tgis.AbstractMapDataset): sys.stderr.write( _( - "Time stamped %s maps with %s available in mapset <%s>:\n" + "Time stamped %s maps with %s available in mapset " + "<%s>:\n" ) % (sp.get_type(), time, key) ) else: sys.stderr.write( _( - "Space time %s datasets with %s available in mapset <%s>:\n" + "Space time %s datasets with %s available in " + "mapset <%s>:\n" ) % (sp.get_new_map_instance(None).get_type(), time, key) ) diff --git a/temporal/t.rast.accdetect/t.rast.accdetect.py b/temporal/t.rast.accdetect/t.rast.accdetect.py index 39d9826b6ad..b8cee70fda4 100644 --- a/temporal/t.rast.accdetect/t.rast.accdetect.py +++ b/temporal/t.rast.accdetect/t.rast.accdetect.py @@ -429,14 +429,18 @@ def main(): elif i > 0 and i < num_maps - 1: prev_map = occurrence_maps[map.next().get_id()].get_name() next_map = occurrence_maps[map.prev().get_id()].get_name() - # In case the previous map is null() set null() or the start indicator + # In case the previous map is null() set null() or the start + # indicator subexpr1 = "if(isnull(%s), null(), %i)" % ( curr_map, indicator_start, ) - # In case the previous map was not null() if the current map is null() set null() - # if the current map is not null() and the next map is not null() set - # intermediate indicator, if the next map is null set the end indicator + # In case the previous map was not null() if the current map is + # null() set null() + # if the current map is not null() and the next map is not + # null() set + # intermediate indicator, if the next map is null set the end + # indicator subexpr2 = "if(isnull(%s), %i, %i)" % ( next_map, indicator_end, @@ -467,14 +471,18 @@ def main(): elif i > 0 and i < num_maps - 1: prev_map = occurrence_maps[map.prev().get_id()].get_name() next_map = occurrence_maps[map.next().get_id()].get_name() - # In case the previous map is null() set null() or the start indicator + # In case the previous map is null() set null() or the start + # indicator subexpr1 = "if(isnull(%s), null(), %i)" % ( curr_map, indicator_start, ) - # In case the previous map was not null() if the current map is null() set null() - # if the current map is not null() and the next map is not null() set - # intermediate indicator, if the next map is null set the end indicator + # In case the previous map was not null() if the current map + # is null() set null() + # if the current map is not null() and the next map is not + # null() set + # intermediate indicator, if the next map is null set the end + # indicator subexpr2 = "if(isnull(%s), %i, %i)" % ( next_map, indicator_end, diff --git a/temporal/t.rast.algebra/t.rast.algebra.py b/temporal/t.rast.algebra/t.rast.algebra.py index 8f1718f6795..0bb81453f0a 100644 --- a/temporal/t.rast.algebra/t.rast.algebra.py +++ b/temporal/t.rast.algebra/t.rast.algebra.py @@ -108,9 +108,10 @@ def main(): except ImportError: grass.script.fatal( _( - "Please install PLY (Lex and Yacc Python implementation) to use the temporal algebra modules. " - "You can use t.rast.mapcalc that provides a limited but useful alternative to " - "t.rast.algebra without PLY requirement." + "Please install PLY (Lex and Yacc Python implementation) to use the " + "temporal algebra modules. You can use t.rast.mapcalc that provides a " + "limited but useful alternative to t.rast.algebra without PLY " + "requirement." ) ) diff --git a/temporal/t.rast.list/t.rast.list.py b/temporal/t.rast.list/t.rast.list.py index a28a80f5455..5278cc60f82 100755 --- a/temporal/t.rast.list/t.rast.list.py +++ b/temporal/t.rast.list/t.rast.list.py @@ -155,7 +155,8 @@ def main(): excluded_option_name="separator", excluded_option_value=separator, reason=_( - "A standard CSV separator (delimiter) is only one character long" + "A standard CSV separator (delimiter) is only one character " + "long" ), ) ) @@ -221,7 +222,8 @@ def main(): excluded_option_name="columns", excluded_option_value=columns, reason=_( - "Column '{name}' is not available with the method '{method}'" + "Column '{name}' is not available with the method " + "'{method}'" ).format(name=column, method=method), ) ) @@ -236,7 +238,8 @@ def main(): excluded_option_name="columns", excluded_option_value=columns, reason=_( - "Column '{name}' is not available with the method '{method}'" + "Column '{name}' is not available with the method " + "'{method}'" ).format(name=column, method=method), ) ) diff --git a/temporal/t.rast.series/t.rast.series.py b/temporal/t.rast.series/t.rast.series.py index f78f71b5ab6..2ec781dfab8 100755 --- a/temporal/t.rast.series/t.rast.series.py +++ b/temporal/t.rast.series/t.rast.series.py @@ -148,9 +148,8 @@ def main(): if len(rows) > max_files_open: grass.warning( _( - "Processing over {} maps: activating -z flag of r.series which slows down processing.".format( - max_files_open - ) + "Processing over {} maps: activating -z flag of r.series which " + "slows down processing.".format(max_files_open) ) ) flag += "z" diff --git a/temporal/t.rast.what/t.rast.what.py b/temporal/t.rast.what/t.rast.what.py index 45a0c9347b2..ffb1c884893 100755 --- a/temporal/t.rast.what/t.rast.what.py +++ b/temporal/t.rast.what/t.rast.what.py @@ -160,7 +160,9 @@ def main(options, flags): if not coordinates and not points and not use_stdin: gscript.fatal( _( - "Please specify the coordinates, the points option or use the 'i' flag to pipe coordinate positions to t.rast.what from stdin, to provide the sampling coordinates" + "Please specify the coordinates, the points option or use the 'i' flag " + "to pipe coordinate positions to t.rast.what from stdin, to provide " + "the sampling coordinates" ) ) @@ -552,7 +554,7 @@ def one_point_per_timerow_output( x|y|1991-01-01 00:00:00;1991-01-02 00:00:00|1991-01-02 00:00:00;1991-01-03 00:00:00|1991-01-03 00:00:00;1991-01-04 00:00:00|1991-01-04 00:00:00;1991-01-05 00:00:00 3730731.49590371|5642483.51236521|6|8|7|7 3581249.04638104|5634411.97526282|5|8|7|7 - """ + """ # noqa: E501 out_file = open(output, "w") if output != "-" else sys.stdout matrix = [] diff --git a/temporal/t.rast3d.algebra/t.rast3d.algebra.py b/temporal/t.rast3d.algebra/t.rast3d.algebra.py index 0e39bb45a59..2d80e90a9db 100644 --- a/temporal/t.rast3d.algebra/t.rast3d.algebra.py +++ b/temporal/t.rast3d.algebra/t.rast3d.algebra.py @@ -94,9 +94,10 @@ def main(): except ImportError: grass.script.fatal( _( - "Please install PLY (Lex and Yacc Python implementation) to use the temporal algebra modules. " - "You can use t.rast3d.mapcalc that provides a limited but useful alternative to " - "t.rast3d.mapcalc2 without PLY requirement." + "Please install PLY (Lex and Yacc Python implementation) to use the " + "temporal algebra modules. You can use t.rast3d.mapcalc that provides " + "a limited but useful alternative to t.rast3d.mapcalc2 without PLY " + "requirement." ) ) diff --git a/temporal/t.select/t.select.py b/temporal/t.select/t.select.py index 030aba99c7e..bf7d0f0e53a 100644 --- a/temporal/t.select/t.select.py +++ b/temporal/t.select/t.select.py @@ -75,7 +75,8 @@ def main(): except ImportError: grass.fatal( _( - "Please install PLY (Lex and Yacc Python implementation) to use the temporal algebra modules." + "Please install PLY (Lex and Yacc Python implementation) to use the " + "temporal algebra modules." ) ) diff --git a/temporal/t.topology/t.topology.py b/temporal/t.topology/t.topology.py index f531e096099..9f795aa0840 100755 --- a/temporal/t.topology/t.topology.py +++ b/temporal/t.topology/t.topology.py @@ -88,7 +88,7 @@ def main(): # 0123456789012345678901234567890 print( - " +-------------------- Temporal topology -------------------------------------+" + " +-------------------- Temporal topology -------------------------------------+" # noqa: E501 ) if where: print(" | Is subset of dataset: ...... True") @@ -124,7 +124,7 @@ def main(): print(" | Granularity: ............... %s" % str(gran)) print( - " +-------------------- Topological relations ---------------------------------+" + " +-------------------- Topological relations ---------------------------------+" # noqa: E501 ) dict_ = sp.count_temporal_relations(maps) @@ -158,7 +158,7 @@ def main(): if key == "precedes": print(" | Precedes: .................. %s" % (dict_[key])) print( - " +----------------------------------------------------------------------------+" + "+----------------------------------------------------------------------------+" # noqa: E501 ) diff --git a/temporal/t.vect.algebra/t.vect.algebra.py b/temporal/t.vect.algebra/t.vect.algebra.py index 763a50ef6e9..b68ef19f9a1 100644 --- a/temporal/t.vect.algebra/t.vect.algebra.py +++ b/temporal/t.vect.algebra/t.vect.algebra.py @@ -73,7 +73,8 @@ def main(): except ImportError: grass.script.fatal( _( - "Please install PLY (Lex and Yacc Python implementation) to use the temporal algebra modules." + "Please install PLY (Lex and Yacc Python implementation) to use the " + "temporal algebra modules." ) ) diff --git a/temporal/t.vect.observe.strds/t.vect.observe.strds.py b/temporal/t.vect.observe.strds/t.vect.observe.strds.py index 996392239ae..9b01ca08cef 100755 --- a/temporal/t.vect.observe.strds/t.vect.observe.strds.py +++ b/temporal/t.vect.observe.strds/t.vect.observe.strds.py @@ -104,7 +104,8 @@ def main(): if len(strds_names) != len(column_names): grass.fatal( _( - "The number of columns must be equal to the number of space time raster datasets" + "The number of columns must be equal to the number of space time " + "raster datasets" ) ) @@ -149,7 +150,8 @@ def main(): grass.fatal( _( "Temporal type of space time raster datasets must be equal\n" - "<%(a)s> of type %(type_a)s do not match <%(b)s> of type %(type_b)s" + "<%(a)s> of type %(type_a)s do not match <%(b)s> of type " + "%(type_b)s" % { "a": first_strds.get_id(), "type_a": first_strds.get_temporal_type(), diff --git a/utils/mkrest.py b/utils/mkrest.py index a5320ef2d01..ca04c173f51 100755 --- a/utils/mkrest.py +++ b/utils/mkrest.py @@ -36,7 +36,7 @@ :doc:`Main Page ` - :doc:`${INDEXNAMECAP} index <${INDEXNAME}>` - :doc:`Full index ` 2003-${YEAR} `GRASS Development Team `_ -""" +""" # noqa: E501 ) footer_noindex = string.Template(