diff --git a/python/grass/experimental/create.py b/python/grass/experimental/create.py index 8581691ac42..aeaf704928c 100644 --- a/python/grass/experimental/create.py +++ b/python/grass/experimental/create.py @@ -39,14 +39,13 @@ def require_create_ensure_mapset( ) exists = mapset_exists(path) if create and exists: - if overwrite: - delete_mapset(path.directory, path.location, path.mapset) - else: + if not overwrite: msg = ( f"Mapset '{path.mapset}' already exists, " "use a different name, overwrite, or ensure" ) raise ValueError(msg) + delete_mapset(path.directory, path.location, path.mapset) if create or (ensure and not exists): create_mapset(path.directory, path.location, path.mapset) elif not exists or not is_mapset_valid(path): diff --git a/python/grass/grassdb/history.py b/python/grass/grassdb/history.py index d168c0aa184..8c9bc2223b3 100644 --- a/python/grass/grassdb/history.py +++ b/python/grass/grassdb/history.py @@ -310,11 +310,10 @@ def add_entry(history_path, entry): :param str history_path: path to the history log file :param dict entry: entry consisting of 'command' and 'command_info' keys """ - if get_history_file_extension(history_path) == ".json": - _add_entry_to_JSON(history_path, entry) - else: + if get_history_file_extension(history_path) != ".json": msg = "Adding entries is supported only for JSON format." raise ValueError(msg) + _add_entry_to_JSON(history_path, entry) def _update_entry_in_JSON(history_path, command_info, index=None): @@ -358,11 +357,10 @@ def update_entry(history_path, command_info, index=None): :param dict command_info: command info entry for update :param int|None index: index of the command to be updated """ - if get_history_file_extension(history_path) == ".json": - _update_entry_in_JSON(history_path, command_info, index) - else: + if get_history_file_extension(history_path) != ".json": msg = "Updating entries is supported only for JSON format." raise ValueError(msg) + _update_entry_in_JSON(history_path, command_info, index) def copy(history_path, target_path): diff --git a/python/grass/gunittest/case.py b/python/grass/gunittest/case.py index 791217d13c1..18cab39e6df 100644 --- a/python/grass/gunittest/case.py +++ b/python/grass/gunittest/case.py @@ -258,12 +258,7 @@ def assertModuleKeyValue( " provided in reference" ": %s\n" % (module, ", ".join(missing)) ) - if mismatch: - stdMsg = "%s difference:\n" % module - stdMsg += "mismatch values" - stdMsg += " (key, reference, actual): %s\n" % mismatch - stdMsg += "command: %s %s" % (module, parameters) - else: + if not mismatch: # we can probably remove this once we have more tests # of keyvalue_equals and diff_keyvalue against each other msg = ( @@ -273,6 +268,11 @@ def assertModuleKeyValue( " (assertModuleKeyValue())" ) raise RuntimeError(msg) + stdMsg = "%s difference:\n" % module + stdMsg += "mismatch values" + stdMsg += " (key, reference, actual): %s\n" % mismatch + stdMsg += "command: %s %s" % (module, parameters) + self.fail(self._formatMessage(msg, stdMsg)) def assertRasterFitsUnivar(self, raster, reference, precision=None, msg=None): diff --git a/python/grass/gunittest/loader.py b/python/grass/gunittest/loader.py index 50fa368f62a..296529d8624 100644 --- a/python/grass/gunittest/loader.py +++ b/python/grass/gunittest/loader.py @@ -113,87 +113,88 @@ def discover_modules( for skip in to_skip: dirs.remove(skip) - if testsuite_dir in dirs: - dirs.remove(testsuite_dir) # do not recurse to testsuite - full = os.path.join(root, testsuite_dir) - - files = os.listdir(full) - if file_pattern: - files = fnmatch.filter(files, file_pattern) - if file_regexp: - files = [f for f in files if re.match(file_regexp, f)] - if exclude: - files = fnmatch_exclude_with_base(files, full, exclude) - files = sorted(files) - # get test/module name without .py - # expecting all files to end with .py - # this will not work for invoking bat files but it works fine - # as long as we handle only Python files (and using Python - # interpreter for invoking) - - # TODO: warning about no tests in a testsuite - # (in what way?) - for file_name in files: - # TODO: add also import if requested - # (see older versions of this file) - # TODO: check if there is some main in .py - # otherwise we can have successful test just because - # everything was loaded into Python - # TODO: check if there is set -e or exit !0 or ? - # otherwise we can have successful because nothing was reported - abspath = os.path.abspath(full) - abs_file_path = os.path.join(abspath, file_name) - if file_name.endswith(".py"): - if file_name == "__init__.py": - # we always ignore __init__.py - continue - file_type = "py" - name = file_name[:-3] - elif file_name.endswith(".sh"): - file_type = "sh" - name = file_name[:-3] + if testsuite_dir not in dirs: + continue + dirs.remove(testsuite_dir) # do not recurse to testsuite + full = os.path.join(root, testsuite_dir) + + files = os.listdir(full) + if file_pattern: + files = fnmatch.filter(files, file_pattern) + if file_regexp: + files = [f for f in files if re.match(file_regexp, f)] + if exclude: + files = fnmatch_exclude_with_base(files, full, exclude) + files = sorted(files) + # get test/module name without .py + # expecting all files to end with .py + # this will not work for invoking bat files but it works fine + # as long as we handle only Python files (and using Python + # interpreter for invoking) + + # TODO: warning about no tests in a testsuite + # (in what way?) + for file_name in files: + # TODO: add also import if requested + # (see older versions of this file) + # TODO: check if there is some main in .py + # otherwise we can have successful test just because + # everything was loaded into Python + # TODO: check if there is set -e or exit !0 or ? + # otherwise we can have successful because nothing was reported + abspath = os.path.abspath(full) + abs_file_path = os.path.join(abspath, file_name) + if file_name.endswith(".py"): + if file_name == "__init__.py": + # we always ignore __init__.py + continue + file_type = "py" + name = file_name[:-3] + elif file_name.endswith(".sh"): + file_type = "sh" + name = file_name[:-3] + else: + file_type = None # alternative would be '', now equivalent + name = file_name + + add = False + try: + if grass_location == all_locations_value: + add = True else: - file_type = None # alternative would be '', now equivalent - name = file_name - - add = False - try: - if grass_location == all_locations_value: - add = True - else: - try: - locations = ["nc", "stdmaps", "all"] - except AttributeError: - add = True # test is universal - else: - if universal_location_value in locations: - add = True # cases when it is explicit - if grass_location in locations: - add = True # standard case with given location - if not locations: - add = True # count not specified as universal - except ImportError as e: - if add_failed_imports: - add = True + try: + locations = ["nc", "stdmaps", "all"] + except AttributeError: + add = True # test is universal else: - raise ImportError( - "Cannot import module named" - " %s in %s (%s)" % (name, full, e.message) - ) - # alternative is to create TestClass which will raise - # see unittest.loader - if add: - modules.append( - GrassTestPythonModule( - name=name, - module=None, - tested_dir=root, - file_dir=full, - abs_file_path=abs_file_path, - file_path=os.path.join(full, file_name), - file_type=file_type, - ) + if universal_location_value in locations: + add = True # cases when it is explicit + if grass_location in locations: + add = True # standard case with given location + if not locations: + add = True # count not specified as universal + except ImportError as e: + if add_failed_imports: + add = True + else: + raise ImportError( + "Cannot import module named %s in %s (%s)" + % (name, full, e.message) + ) + # alternative is to create TestClass which will raise + # see unittest.loader + if add: + modules.append( + GrassTestPythonModule( + name=name, + module=None, + tested_dir=root, + file_dir=full, + abs_file_path=abs_file_path, + file_path=os.path.join(full, file_name), + file_type=file_type, ) + ) # in else with some verbose we could tell about skipped test return modules diff --git a/python/grass/gunittest/reporters.py b/python/grass/gunittest/reporters.py index 48d5392afe2..fc19b6086bb 100644 --- a/python/grass/gunittest/reporters.py +++ b/python/grass/gunittest/reporters.py @@ -527,10 +527,8 @@ def success_to_html_text(total, successes): def success_to_html_percent(total, successes): if total: pass_per = 100 * (float(successes) / total) - pass_per = percent_to_html(pass_per) - else: - pass_per = UNKNOWN_NUMBER_HTML - return pass_per + return percent_to_html(pass_per) + return UNKNOWN_NUMBER_HTML class GrassTestFilesHtmlReporter(GrassTestFilesCountingReporter): diff --git a/python/grass/imaging/images2gif.py b/python/grass/imaging/images2gif.py index b3ee3062719..215ef04af2f 100644 --- a/python/grass/imaging/images2gif.py +++ b/python/grass/imaging/images2gif.py @@ -285,13 +285,14 @@ def handleSubRectangles(self, images, subRectangles): # First make numpy arrays if required for i in range(len(images)): im = images[i] - if isinstance(im, Image.Image): - tmp = im.convert() # Make without palette - a = np.asarray(tmp) - if len(a.shape) == 0: - msg = "Too little memory to convert PIL image to array" - raise MemoryError(msg) - images[i] = a + if not isinstance(im, Image.Image): + continue + tmp = im.convert() # Make without palette + a = np.asarray(tmp) + if len(a.shape) == 0: + msg = "Too little memory to convert PIL image to array" + raise MemoryError(msg) + images[i] = a # Determine the sub rectangles images, xy = self.getSubRectangles(images) diff --git a/python/grass/imaging/images2ims.py b/python/grass/imaging/images2ims.py index b748ad975db..6324fffa3c5 100644 --- a/python/grass/imaging/images2ims.py +++ b/python/grass/imaging/images2ims.py @@ -120,10 +120,9 @@ def _getSequenceNumber(filename, part1, part2): # Get all numeric chars seq2 = "" for c in seq: - if c in digits: - seq2 += c - else: + if c not in digits: break + seq2 += c # Make int and return return int(seq2) diff --git a/python/grass/imaging/images2swf.py b/python/grass/imaging/images2swf.py index 858f9e819e5..8d470810d09 100644 --- a/python/grass/imaging/images2swf.py +++ b/python/grass/imaging/images2swf.py @@ -551,15 +551,14 @@ def __init__(self, im): # when storing RGB as ARGB). if len(im.shape) == 3: - if im.shape[2] in [3, 4]: - tmp = np.ones((im.shape[0], im.shape[1], 4), dtype=np.uint8) * 255 - for i in range(3): - tmp[:, :, i + 1] = im[:, :, i] - if im.shape[2] == 4: - tmp[:, :, 0] = im[:, :, 3] # swap channel where alpha is in - else: + if im.shape[2] not in {3, 4}: msg = "Invalid shape to be an image." raise ValueError(msg) + tmp = np.ones((im.shape[0], im.shape[1], 4), dtype=np.uint8) * 255 + for i in range(3): + tmp[:, :, i + 1] = im[:, :, i] + if im.shape[2] == 4: + tmp[:, :, 0] = im[:, :, 3] # swap channel where alpha is in elif len(im.shape) == 2: tmp = np.ones((im.shape[0], im.shape[1], 4), dtype=np.uint8) * 255 @@ -807,11 +806,11 @@ def writeSwf(filename, images, duration=0.1, repeat=True): # Check duration if hasattr(duration, "__len__"): - if len(duration) == len(images2): - duration = list(duration) - else: + if len(duration) != len(images2): msg = "len(duration) doesn't match amount of images." raise ValueError(msg) + duration = list(duration) + else: duration = [duration for im in images2] diff --git a/python/grass/jupyter/map.py b/python/grass/jupyter/map.py index dc78be31208..3b61372626d 100644 --- a/python/grass/jupyter/map.py +++ b/python/grass/jupyter/map.py @@ -158,13 +158,12 @@ def run(self, module, **kwargs): :param `**kwargs`: named arguments passed to run_command()""" # Check module is from display library then run - if module[0] == "d": - self._region_manager.set_region_from_command(module, **kwargs) - self._region_manager.adjust_rendering_size_from_region() - gs.run_command(module, env=self._env, **kwargs) - else: + if module[0] != "d": msg = "Module must begin with letter 'd'." raise ValueError(msg) + self._region_manager.set_region_from_command(module, **kwargs) + self._region_manager.adjust_rendering_size_from_region() + gs.run_command(module, env=self._env, **kwargs) def __getattr__(self, name): """Parse attribute to GRASS display module. Attribute should be in diff --git a/python/grass/pygrass/gis/__init__.py b/python/grass/pygrass/gis/__init__.py index e34abc405c4..b905626a0f8 100644 --- a/python/grass/pygrass/gis/__init__.py +++ b/python/grass/pygrass/gis/__init__.py @@ -383,12 +383,11 @@ def glist(self, type, pattern=None): elist = [] for el in clist: el_name = ct.cast(el, ct.c_char_p).value - if el_name: - elist.append(decode(el_name)) - else: + if not el_name: if pattern: return fnmatch.filter(elist, pattern) return elist + elist.append(decode(el_name)) def is_current(self): """Check if the MAPSET is the working MAPSET""" @@ -459,12 +458,11 @@ def add(self, mapset): :param mapset: a mapset's name :type mapset: str """ - if mapset not in self.read() and mapset in self.location: - with open(self.spath, "a+") as f: - f.write("%s\n" % mapset) - else: + if mapset in self.read() or mapset not in self.location: msg = "Mapset not found" raise TypeError(msg) + with open(self.spath, "a+") as f: + f.write("%s\n" % mapset) def remove(self, mapset): """Remove mapset to the search path diff --git a/python/grass/pygrass/modules/interface/flag.py b/python/grass/pygrass/modules/interface/flag.py index b6f00fdb744..c4014eb0b93 100644 --- a/python/grass/pygrass/modules/interface/flag.py +++ b/python/grass/pygrass/modules/interface/flag.py @@ -49,11 +49,11 @@ def get_bash(self): >>> flag.get_bash() '--o' """ - if self.value: - if self.special: - return "--%s" % self.name[0] - return "-%s" % self.name - return "" + if not self.value: + return "" + if self.special: + return "--%s" % self.name[0] + return "-%s" % self.name def get_python(self): """Return the python representation of a flag. diff --git a/python/grass/pygrass/modules/interface/module.py b/python/grass/pygrass/modules/interface/module.py index 10c38a12990..5c9fcd72a99 100644 --- a/python/grass/pygrass/modules/interface/module.py +++ b/python/grass/pygrass/modules/interface/module.py @@ -545,11 +545,10 @@ def f(*args, **kargs): """ # noqa: E501 def __init__(self, cmd, *args, **kargs): - if isinstance(cmd, str): - self.name = cmd - else: + if not isinstance(cmd, str): msg = "Problem initializing the module {s}".format(s=cmd) raise GrassError(msg) + self.name = cmd try: # call the command with --interface-description get_cmd_xml = Popen([cmd, "--interface-description"], stdout=PIPE) @@ -638,17 +637,13 @@ def __call__(self, *args, **kargs): self.update(*args, **kargs) - # # check if execute - # - if self.run_: - # - # check reqire parameters - # - if self.check_: - self.check() - return self.run() - return self + if not self.run_: + return self + # check required parameters + if self.check_: + self.check() + return self.run() def update(self, *args, **kargs): """Update module parameters and selected object attributes. diff --git a/python/grass/pygrass/modules/interface/parameter.py b/python/grass/pygrass/modules/interface/parameter.py index 4c9b8571250..78508a60c74 100644 --- a/python/grass/pygrass/modules/interface/parameter.py +++ b/python/grass/pygrass/modules/interface/parameter.py @@ -55,15 +55,14 @@ def check_string(value): if isinstance(value, tuple) else (value, value) ) - if param.multiple: - # everything looks fine, so check each value - try: - return [param.type(check_string(val)) for val in value], value - except Exception as exc: - raiseexcpet(exc, param, param.type, value) - else: + if not param.multiple: msg = "The Parameter <%s> does not accept multiple inputs" raise TypeError(msg % param.name) + # everything looks fine, so check each value + try: + return ([param.type(check_string(val)) for val in value], value) + except Exception as exc: + raiseexcpet(exc, param, param.type, value) if param.keydescvalues: msg = "The Parameter <%s> require multiple inputs in the form: %s" @@ -167,11 +166,10 @@ def __init__(self, xparameter=None, diz=None): self.required = diz["required"] == "yes" self.multiple = diz["multiple"] == "yes" # check the type - if diz["type"] in GETTYPE: - self.type = GETTYPE[diz["type"]] - self.typedesc = diz["type"] - else: + if diz["type"] not in GETTYPE: raise TypeError("New type: %s, ignored" % diz["type"]) + self.type = GETTYPE[diz["type"]] + self.typedesc = diz["type"] self.description = diz.get("description", None) self.keydesc, self.keydescvalues = diz.get("keydesc", (None, None)) diff --git a/python/grass/pygrass/modules/interface/typedict.py b/python/grass/pygrass/modules/interface/typedict.py index fb3ddb368eb..a2760d2c451 100644 --- a/python/grass/pygrass/modules/interface/typedict.py +++ b/python/grass/pygrass/modules/interface/typedict.py @@ -30,11 +30,10 @@ def __dir__(self): return self.keys() def __setitem__(self, key, value): - if isinstance(value, self._type): - super().__setitem__(key, value) - else: + if not isinstance(value, self._type): str_err = "The value: %r is not a %s instance." raise TypeError(str_err % (value, self._type.__name__)) + super().__setitem__(key, value) @docstring_property(__doc__) def __doc__(self): diff --git a/python/grass/pygrass/raster/__init__.py b/python/grass/pygrass/raster/__init__.py index cf3ab0f234d..8a21a5a2466 100644 --- a/python/grass/pygrass/raster/__init__.py +++ b/python/grass/pygrass/raster/__init__.py @@ -192,17 +192,16 @@ def open(self, mode=None, mtype=None, overwrite=None): self.overwrite = overwrite if overwrite is not None else self.overwrite if self.mode == "r": - if self.exist(): - self.info.read() - self.cats.mtype = self.mtype - self.cats.read() - self.hist.read() - self._fd = libraster.Rast_open_old(self.name, self.mapset) - self._gtype = libraster.Rast_get_map_type(self._fd) - self.mtype = RTYPE_STR[self._gtype] - else: + if not self.exist(): str_err = _("The map does not exist, I can't open in 'r' mode") raise OpenError(str_err) + self.info.read() + self.cats.mtype = self.mtype + self.cats.read() + self.hist.read() + self._fd = libraster.Rast_open_old(self.name, self.mapset) + self._gtype = libraster.Rast_get_map_type(self._fd) + self.mtype = RTYPE_STR[self._gtype] elif self.mode == "w": if self.exist(): if not self.overwrite: diff --git a/python/grass/pygrass/raster/abstract.py b/python/grass/pygrass/raster/abstract.py index a27350171f1..d5db9bb3b6e 100644 --- a/python/grass/pygrass/raster/abstract.py +++ b/python/grass/pygrass/raster/abstract.py @@ -427,13 +427,13 @@ def exist(self): >>> ele.exist() True """ - if self.name: - if self.mapset == "": - mapset = utils.get_mapset_raster(self.name, self.mapset) - self.mapset = mapset or "" - return bool(mapset) - return bool(utils.get_mapset_raster(self.name, self.mapset)) - return False + if not self.name: + return False + if self.mapset == "": + mapset = utils.get_mapset_raster(self.name, self.mapset) + self.mapset = mapset or "" + return bool(mapset) + return bool(utils.get_mapset_raster(self.name, self.mapset)) def is_open(self): """Return True if the map is open False otherwise. diff --git a/python/grass/pygrass/raster/category.py b/python/grass/pygrass/raster/category.py index 20fca524da5..e2168efa413 100644 --- a/python/grass/pygrass/raster/category.py +++ b/python/grass/pygrass/raster/category.py @@ -115,17 +115,16 @@ def _chk_index(self, index): return index def _chk_value(self, value): - if isinstance(value, tuple): - length = len(value) - if length == 2: - label, min_cat = value - value = (label, min_cat, None) - elif length < 2 or length > 3: - msg = "Tuple with a length that is not supported." - raise TypeError(msg) - else: + if not isinstance(value, tuple): msg = "Only tuples are supported." raise TypeError(msg) + length = len(value) + if length == 2: + label, min_cat = value + value = (label, min_cat, None) + elif length < 2 or length > 3: + msg = "Tuple with a length that is not supported." + raise TypeError(msg) return value def __getitem__(self, index): diff --git a/python/grass/pygrass/vector/__init__.py b/python/grass/pygrass/vector/__init__.py index b36fae9fa4f..ab37091a609 100644 --- a/python/grass/pygrass/vector/__init__.py +++ b/python/grass/pygrass/vector/__init__.py @@ -392,13 +392,13 @@ def number_of(self, vtype): .. """ - if vtype in _NUMOF.keys(): - if isinstance(_NUMOF[vtype], tuple): - fn, ptype = _NUMOF[vtype] - return fn(self.c_mapinfo, ptype) - return _NUMOF[vtype](self.c_mapinfo) - keys = "', '".join(sorted(_NUMOF.keys())) - raise ValueError("vtype not supported, use one of: '%s'" % keys) + if vtype not in _NUMOF.keys(): + keys = "', '".join(sorted(_NUMOF.keys())) + raise ValueError("vtype not supported, use one of: '%s'" % keys) + if isinstance(_NUMOF[vtype], tuple): + fn, ptype = _NUMOF[vtype] + return fn(self.c_mapinfo, ptype) + return _NUMOF[vtype](self.c_mapinfo) @must_be_open def num_primitives(self): @@ -450,24 +450,23 @@ def viter(self, vtype, idonly=False): >>> test_vect.close() """ is2D = not self.is_3D() - if vtype in _GEOOBJ.keys(): - if _GEOOBJ[vtype] is not None: - ids = (indx for indx in range(1, self.number_of(vtype) + 1)) - if idonly: - return ids - return ( - _GEOOBJ[vtype]( - v_id=indx, - c_mapinfo=self.c_mapinfo, - table=self.table, - writeable=self.writeable, - is2D=is2D, - ) - for indx in ids - ) - else: + if vtype not in _GEOOBJ.keys(): keys = "', '".join(sorted(_GEOOBJ.keys())) raise ValueError("vtype not supported, use one of: '%s'" % keys) + if _GEOOBJ[vtype] is not None: + ids = (indx for indx in range(1, self.number_of(vtype) + 1)) + if idonly: + return ids + return ( + _GEOOBJ[vtype]( + v_id=indx, + c_mapinfo=self.c_mapinfo, + table=self.table, + writeable=self.writeable, + is2D=is2D, + ) + for indx in ids + ) @must_be_open def rewind(self): @@ -666,16 +665,12 @@ def delete(self, feature_id): @must_be_open def restore(self, geo_obj): - if hasattr(geo_obj, "offset"): - if ( - libvect.Vect_restore_line(self.c_mapinfo, geo_obj.offset, geo_obj.id) - == -1 - ): - msg = "C function: Vect_restore_line." - raise GrassError(msg) - else: + if not hasattr(geo_obj, "offset"): msg = "The value have not an offset attribute." raise ValueError(msg) + if libvect.Vect_restore_line(self.c_mapinfo, geo_obj.offset, geo_obj.id) == -1: + msg = "C function: Vect_restore_line." + raise GrassError(msg) @must_be_open def bbox(self): @@ -720,27 +715,26 @@ def table_to_dict(self, where=None): """ - if self.table is not None: - table_dict = {} - # Get the category index - cat_index = self.table.columns.names().index("cat") - # Prepare a filter - if where is not None: - self.table.filters.where(where) - - self.table.filters.order_by("cat") + if self.table is None: + return None + table_dict = {} + # Get the category index + cat_index = self.table.columns.names().index("cat") + # Prepare a filter + if where is not None: + self.table.filters.where(where) - self.table.filters.select(",".join(self.table.columns.names())) - # Execute the query and fetch the result - cur = self.table.execute() - entries = cur.fetchall() - # Generate the dictionary - for entry in entries: - table_dict[entry[cat_index]] = list(entry) + self.table.filters.order_by("cat") - return table_dict + self.table.filters.select(",".join(self.table.columns.names())) + # Execute the query and fetch the result + cur = self.table.execute() + entries = cur.fetchall() + # Generate the dictionary + for entry in entries: + table_dict[entry[cat_index]] = list(entry) - return None + return table_dict @must_be_open def features_to_wkb_list(self, bbox=None, feature_type="point", field=1): @@ -841,42 +835,38 @@ def features_to_wkb_list(self, bbox=None, feature_type="point", field=1): bbox, type=feature_type.lower(), bboxlist_only=True ) - if bboxlist is not None and len(bboxlist) > 0: - wkb_list = [] - line_p = libvect.line_pnts() - line_c = libvect.line_cats() - size = ctypes.c_size_t() - cat = ctypes.c_int() - error = ctypes.c_int() - - for f_id in bboxlist.ids: - barray = libvect.Vect_read_line_to_wkb( - self.c_mapinfo, - ctypes.byref(line_p), - ctypes.byref(line_c), - f_id, - ctypes.byref(size), - ctypes.byref(error), - ) - if not barray: - if error == -1: - raise GrassError( - _("Unable to read line of feature %i") % (f_id) - ) - if error == -2: - print("Empty feature %i" % (f_id)) - continue - - ok = libvect.Vect_cat_get( - ctypes.byref(line_c), field, ctypes.byref(cat) - ) - pcat = None if ok < 1 else cat.value + if bboxlist is None or len(bboxlist) <= 0: + return None + + wkb_list = [] + line_p = libvect.line_pnts() + line_c = libvect.line_cats() + size = ctypes.c_size_t() + cat = ctypes.c_int() + error = ctypes.c_int() + + for f_id in bboxlist.ids: + barray = libvect.Vect_read_line_to_wkb( + self.c_mapinfo, + ctypes.byref(line_p), + ctypes.byref(line_c), + f_id, + ctypes.byref(size), + ctypes.byref(error), + ) + if not barray: + if error == -1: + raise GrassError(_("Unable to read line of feature %i") % f_id) + if error == -2: + print("Empty feature %i" % f_id) + continue + ok = libvect.Vect_cat_get(ctypes.byref(line_c), field, ctypes.byref(cat)) + pcat = None if ok < 1 else cat.value - wkb_list.append((f_id, pcat, ctypes.string_at(barray, size.value))) - libgis.G_free(barray) + wkb_list.append((f_id, pcat, ctypes.string_at(barray, size.value))) + libgis.G_free(barray) - return wkb_list - return None + return wkb_list @must_be_open def areas_to_wkb_list(self, bbox=None, field=1): @@ -939,35 +929,36 @@ def areas_to_wkb_list(self, bbox=None, field=1): bboxlist = self.find_by_bbox.areas(bbox, bboxlist_only=True) - if bboxlist is not None and len(bboxlist) > 0: - wkb_list = [] - line_c = libvect.line_cats() - size = ctypes.c_size_t() - cat = ctypes.c_int() + if bboxlist is None or len(bboxlist) <= 0: + return None - for a_id in bboxlist.ids: - barray = libvect.Vect_read_area_to_wkb( - self.c_mapinfo, a_id, ctypes.byref(size) - ) - if not barray: - raise GrassError(_("Unable to read area with id %i") % (a_id)) + wkb_list = [] + line_c = libvect.line_cats() + size = ctypes.c_size_t() + cat = ctypes.c_int() - pcat = None - c_ok = libvect.Vect_get_area_cats( - self.c_mapinfo, a_id, ctypes.byref(line_c) + for a_id in bboxlist.ids: + barray = libvect.Vect_read_area_to_wkb( + self.c_mapinfo, a_id, ctypes.byref(size) + ) + if not barray: + raise GrassError(_("Unable to read area with id %i") % a_id) + + pcat = None + c_ok = libvect.Vect_get_area_cats( + self.c_mapinfo, a_id, ctypes.byref(line_c) + ) + if c_ok == 0: # Centroid found + ok = libvect.Vect_cat_get( + ctypes.byref(line_c), field, ctypes.byref(cat) ) - if c_ok == 0: # Centroid found - ok = libvect.Vect_cat_get( - ctypes.byref(line_c), field, ctypes.byref(cat) - ) - if ok > 0: - pcat = cat.value - - wkb_list.append((a_id, pcat, ctypes.string_at(barray, size.value))) - libgis.G_free(barray) - - return wkb_list - return None + if ok > 0: + pcat = cat.value + + wkb_list.append((a_id, pcat, ctypes.string_at(barray, size.value))) + libgis.G_free(barray) + + return wkb_list if __name__ == "__main__": diff --git a/python/grass/pygrass/vector/abstract.py b/python/grass/pygrass/vector/abstract.py index 00bef3997f2..b1f38ea58da 100644 --- a/python/grass/pygrass/vector/abstract.py +++ b/python/grass/pygrass/vector/abstract.py @@ -281,11 +281,11 @@ def rename(self, newname): :type newname: str """ if self.exist(): - if not self.is_open(): - utils.rename(self.name, newname, "vect") - else: + if self.is_open(): msg = "The map is open, not able to rename it." raise GrassError(msg) + utils.rename(self.name, newname, "vect") + self._name = newname def is_3D(self): @@ -294,13 +294,13 @@ def is_3D(self): def exist(self): """Return if the Vector exists or not""" - if self.name: - if self.mapset == "": - mapset = utils.get_mapset_vector(self.name, self.mapset) - self.mapset = mapset or "" - return bool(mapset) - return bool(utils.get_mapset_vector(self.name, self.mapset)) - return False + if not self.name: + return False + if self.mapset == "": + mapset = utils.get_mapset_vector(self.name, self.mapset) + self.mapset = mapset or "" + return bool(mapset) + return bool(utils.get_mapset_vector(self.name, self.mapset)) def is_open(self): """Return if the Vector is open""" diff --git a/python/grass/pygrass/vector/geometry.py b/python/grass/pygrass/vector/geometry.py index 04d57d7a204..2d4c8e5d385 100644 --- a/python/grass/pygrass/vector/geometry.py +++ b/python/grass/pygrass/vector/geometry.py @@ -200,24 +200,23 @@ def __setitem__(self, keys, values): >>> test_vect.close() """ - if self.writeable: - if np.isscalar(keys): - keys, values = (keys,), (values,) - # check if key is a column of the table or not - for key in keys: - if key not in self.table.columns: - raise KeyError("Column: %s not in table" % key) - # prepare the string using as paramstyle: qmark - vals = ",".join(["%s=?" % k for k in keys]) - # "UPDATE {tname} SET {values} WHERE {condition};" - sqlcode = sql.UPDATE_WHERE.format( - tname=self.table.name, values=vals, condition=self.cond - ) - self.table.execute(sqlcode, values=values) - # self.table.conn.commit() - else: + if not self.writeable: str_err = "You can only read the attributes if the map is in another mapset" raise GrassError(str_err) + if np.isscalar(keys): + keys, values = ((keys,), (values,)) + # check if key is a column of the table or not + for key in keys: + if key not in self.table.columns: + raise KeyError("Column: %s not in table" % key) + # prepare the string using as paramstyle: qmark + vals = ",".join(["%s=?" % k for k in keys]) + # "UPDATE {tname} SET {values} WHERE {condition};" + sqlcode = sql.UPDATE_WHERE.format( + tname=self.table.name, values=vals, condition=self.cond + ) + self.table.execute(sqlcode, values=values) + # self.table.conn.commit() def __dict__(self): """Return a dict of the attribute table row.""" diff --git a/python/grass/pygrass/vector/table.py b/python/grass/pygrass/vector/table.py index ee972a5b634..ba3d1c3d2d5 100644 --- a/python/grass/pygrass/vector/table.py +++ b/python/grass/pygrass/vector/table.py @@ -552,18 +552,15 @@ def cast(self, col_name, new_type): It is not possible to cast a column with sqlite """ - if self.is_pg(): - cur = self.conn.cursor() - cur.execute( - sql.CAST_COL.format(tname=self.tname, col=col_name, ctype=new_type) - ) - self.conn.commit() - cur.close() - self.update_odict() - else: + if not self.is_pg(): # sqlite does not support rename columns: msg = "SQLite does not support to cast columns." raise DBError(msg) + cur = self.conn.cursor() + cur.execute(sql.CAST_COL.format(tname=self.tname, col=col_name, ctype=new_type)) + self.conn.commit() + cur.close() + self.update_odict() def drop(self, col_name): """Drop a column from the table. @@ -713,18 +710,17 @@ def _get_driver(self): return decode(self.c_fieldinfo.contents.driver) def _set_driver(self, driver): - if driver in DRIVERS: - self.c_fieldinfo.contents.driver = ReturnString(driver) - elif driver in UNSUPPORTED_DRIVERS: - raise NotImplementedError( - "The database driver %s is not supported by PyGRASS, " - "use: %s." % (driver, ", ".join(DRIVERS)) - ) - else: + if driver not in DRIVERS: + if driver in UNSUPPORTED_DRIVERS: + raise NotImplementedError( + "The database driver %s is not supported by PyGRASS, use: %s." + % (driver, ", ".join(DRIVERS)) + ) raise ValueError( - "The database driver %s is not known to PyGRASS, " - "use: %s." % (driver, ", ".join(DRIVERS)) + "The database driver %s is not known to PyGRASS, use: %s." + % (driver, ", ".join(DRIVERS)) ) + self.c_fieldinfo.contents.driver = ReturnString(driver) driver = property( fget=_get_driver, @@ -856,9 +852,9 @@ def connection(self): except ImportError: er = "You need to install psycopg2 to connect with this table." raise ImportError(er) - else: - str_err = "Driver is not supported yet, pleas use: sqlite or pg" - raise TypeError(str_err) + + str_err = "Driver is not supported yet, pleas use: sqlite or pg" + raise TypeError(str_err) def table(self): """Return a Table object. diff --git a/python/grass/script/core.py b/python/grass/script/core.py index a5f41696f34..ad7cca37050 100644 --- a/python/grass/script/core.py +++ b/python/grass/script/core.py @@ -1069,13 +1069,12 @@ def _text_to_key_value_dict( kvdict = KeyValue() for line in text: - if line.find(sep) >= 0: - key, value = line.split(sep) - key = key.strip() - value = value.strip() - else: + if line.find(sep) < 0: # Jump over empty values continue + key, value = line.split(sep) + key = key.strip() + value = value.strip() values = value.split(val_sep) value_list = [] diff --git a/python/grass/script/task.py b/python/grass/script/task.py index 5d7355efacb..cbf133c2f20 100644 --- a/python/grass/script/task.py +++ b/python/grass/script/task.py @@ -86,12 +86,12 @@ def get_error_msg(self): def get_name(self): """Get task name""" - if sys.platform == "win32": - name, ext = os.path.splitext(self.name) - if ext in {".py", ".sh"}: - return name + if sys.platform != "win32": return self.name + name, ext = os.path.splitext(self.name) + if ext in {".py", ".sh"}: + return name return self.name def get_description(self, full=True): @@ -99,11 +99,11 @@ def get_description(self, full=True): :param bool full: True for label + desc """ - if self.label: - if full: - return self.label + " " + self.description - return self.label - return self.description + if not self.label: + return self.description + if full: + return self.label + " " + self.description + return self.label def get_keywords(self): """Get module's keywords""" diff --git a/python/grass/temporal/abstract_map_dataset.py b/python/grass/temporal/abstract_map_dataset.py index 3b9cf272f0c..08452c612a0 100644 --- a/python/grass/temporal/abstract_map_dataset.py +++ b/python/grass/temporal/abstract_map_dataset.py @@ -943,33 +943,30 @@ def check_for_correct_time(self) -> bool: else: start, end, unit = self.get_relative_time() - if start is not None: - if end is not None: - if start >= end: - if self.get_layer() is not None: - self.msgr.error( - _( - "Map <%(id)s> with layer %(layer)s " - "has incorrect time interval, start " - "time is greater than end time" - ) - % {"id": self.get_map_id(), "layer": self.get_layer()} + if start is None: + self.msgr.error(_("Map <%s> has incorrect start time") % self.get_map_id()) + return False + if end is not None: + if start >= end: + if self.get_layer() is not None: + self.msgr.error( + _( + "Map <%(id)s> with layer %(layer)s " + "has incorrect time interval, start " + "time is greater than end time" ) - else: - self.msgr.error( - _( - "Map <%s> has incorrect time " - "interval, start time is greater " - "than end time" - ) - % (self.get_map_id()) + % {"id": self.get_map_id(), "layer": self.get_layer()} + ) + else: + self.msgr.error( + _( + "Map <%s> has incorrect time " + "interval, start time is greater " + "than end time" ) - return False - else: - self.msgr.error( - _("Map <%s> has incorrect start time") % (self.get_map_id()) - ) - return False + % (self.get_map_id()) + ) + return False return True diff --git a/python/grass/temporal/list_stds.py b/python/grass/temporal/list_stds.py index c8517545aeb..60938dbccef 100644 --- a/python/grass/temporal/list_stds.py +++ b/python/grass/temporal/list_stds.py @@ -286,17 +286,17 @@ def _get_get_registered_maps_as_objects_with_method(dataset, where, method, gran return dataset.get_registered_maps_as_objects( where=where, order="start_time", dbif=dbif ) - if method == "gran": - if where: - msg = f"The where parameter is not supported with method={method}" - raise ValueError(msg) - if gran is not None and gran != "": - return dataset.get_registered_maps_as_objects_by_granularity( - gran=gran, dbif=dbif - ) - return dataset.get_registered_maps_as_objects_by_granularity(dbif=dbif) - msg = f"Invalid method '{method}'" - raise ValueError(msg) + if method != "gran": + msg = f"Invalid method '{method}'" + raise ValueError(msg) + if where: + msg = f"The where parameter is not supported with method={method}" + raise ValueError(msg) + if gran is not None and gran != "": + return dataset.get_registered_maps_as_objects_by_granularity( + gran=gran, dbif=dbif + ) + return dataset.get_registered_maps_as_objects_by_granularity(dbif=dbif) def _get_get_registered_maps_as_objects_delta_gran( @@ -309,11 +309,10 @@ def _get_get_registered_maps_as_objects_delta_gran( return [] if isinstance(maps[0], list): - if len(maps[0]) > 0: - first_time, unused = maps[0][0].get_temporal_extent_as_tuple() - else: + if len(maps[0]) <= 0: msgr.warning(_("Empty map list")) return [] + first_time, unused = maps[0][0].get_temporal_extent_as_tuple() else: first_time, unused = maps[0].get_temporal_extent_as_tuple() diff --git a/python/grass/temporal/mapcalc.py b/python/grass/temporal/mapcalc.py index b1dbb5ce2db..c00040bbeb5 100644 --- a/python/grass/temporal/mapcalc.py +++ b/python/grass/temporal/mapcalc.py @@ -312,19 +312,20 @@ def dataset_mapcalculator( proc_list[proc_count].start() proc_count += 1 - if proc_count in {nprocs, num} or count == num: - proc_count = 0 - exitcodes = 0 - for proc in proc_list: - proc.join() - exitcodes += proc.exitcode - - if exitcodes != 0: - dbif.close() - msgr.fatal(_("Error while mapcalc computation")) - - # Empty process list - proc_list = [] + if proc_count not in {nprocs, num} and count != num: + continue + proc_count = 0 + exitcodes = 0 + for proc in proc_list: + proc.join() + exitcodes += proc.exitcode + + if exitcodes != 0: + dbif.close() + msgr.fatal(_("Error while mapcalc computation")) + + # Empty process list + proc_list = [] # Register the new maps in the output space time dataset msgr.message(_("Starting map registration in temporal database...")) diff --git a/python/grass/temporal/metadata.py b/python/grass/temporal/metadata.py index 8c85141e6aa..8fc3fe2047d 100644 --- a/python/grass/temporal/metadata.py +++ b/python/grass/temporal/metadata.py @@ -1430,20 +1430,20 @@ def get_semantic_labels(self): rows = dbif.fetchall(mapset=self.mapset) dbif.close() - if rows: - string = "" - count = 0 - for row in rows: - if row["semantic_label"]: - if count == 0: - string += row["semantic_label"] - else: - string += ",%s" % row["semantic_label"] - count += 1 - - if count > 0: - return string + if not rows: return None + string = "" + count = 0 + for row in rows: + if row["semantic_label"]: + if count == 0: + string += row["semantic_label"] + else: + string += ",%s" % row["semantic_label"] + count += 1 + + if count > 0: + return string return None raster_register = property(fget=get_raster_register, fset=set_raster_register) diff --git a/python/grass/temporal/space_time_datasets.py b/python/grass/temporal/space_time_datasets.py index 97678e5ce23..b2fe2c2404b 100644 --- a/python/grass/temporal/space_time_datasets.py +++ b/python/grass/temporal/space_time_datasets.py @@ -429,41 +429,37 @@ def load(self) -> bool: kvp = self.ciface.read_raster_info(self.get_name(), self.get_mapset()) - if kvp: - # Fill spatial extent - self.set_spatial_extent_from_values( - north=kvp["north"], - south=kvp["south"], - east=kvp["east"], - west=kvp["west"], - ) - - # Fill metadata - self.metadata.set_nsres(kvp["nsres"]) - self.metadata.set_ewres(kvp["ewres"]) - self.metadata.set_datatype(kvp["datatype"]) - self.metadata.set_min(kvp["min"]) - self.metadata.set_max(kvp["max"]) + if not kvp: + return False + # Fill spatial extent + self.set_spatial_extent_from_values( + north=kvp["north"], south=kvp["south"], east=kvp["east"], west=kvp["west"] + ) - rows = int(kvp["rows"]) - cols = int(kvp["cols"]) + # Fill metadata + self.metadata.set_nsres(kvp["nsres"]) + self.metadata.set_ewres(kvp["ewres"]) + self.metadata.set_datatype(kvp["datatype"]) + self.metadata.set_min(kvp["min"]) + self.metadata.set_max(kvp["max"]) - ncells = cols * rows + rows = int(kvp["rows"]) + cols = int(kvp["cols"]) - self.metadata.set_cols(cols) - self.metadata.set_rows(rows) - self.metadata.set_number_of_cells(ncells) + ncells = cols * rows - # Fill semantic label if defined - semantic_label = self.ciface.read_raster_semantic_label( - self.get_name(), self.get_mapset() - ) - if semantic_label: - self.metadata.set_semantic_label(semantic_label) + self.metadata.set_cols(cols) + self.metadata.set_rows(rows) + self.metadata.set_number_of_cells(ncells) - return True + # Fill semantic label if defined + semantic_label = self.ciface.read_raster_semantic_label( + self.get_name(), self.get_mapset() + ) + if semantic_label: + self.metadata.set_semantic_label(semantic_label) - return False + return True def set_semantic_label(self, semantic_label) -> None: """Set semantic label identifier @@ -828,38 +824,37 @@ def load(self) -> bool: # Fill spatial extent kvp = self.ciface.read_raster3d_info(self.get_name(), self.get_mapset()) - if kvp: - self.set_spatial_extent_from_values( - north=kvp["north"], - south=kvp["south"], - east=kvp["east"], - west=kvp["west"], - top=kvp["top"], - bottom=kvp["bottom"], - ) - - # Fill metadata - self.metadata.set_nsres(kvp["nsres"]) - self.metadata.set_ewres(kvp["ewres"]) - self.metadata.set_tbres(kvp["tbres"]) - self.metadata.set_datatype(kvp["datatype"]) - self.metadata.set_min(kvp["min"]) - self.metadata.set_max(kvp["max"]) + if not kvp: + return False + self.set_spatial_extent_from_values( + north=kvp["north"], + south=kvp["south"], + east=kvp["east"], + west=kvp["west"], + top=kvp["top"], + bottom=kvp["bottom"], + ) - rows = int(kvp["rows"]) - cols = int(kvp["cols"]) - depths = int(kvp["depths"]) + # Fill metadata + self.metadata.set_nsres(kvp["nsres"]) + self.metadata.set_ewres(kvp["ewres"]) + self.metadata.set_tbres(kvp["tbres"]) + self.metadata.set_datatype(kvp["datatype"]) + self.metadata.set_min(kvp["min"]) + self.metadata.set_max(kvp["max"]) - ncells = cols * rows * depths + rows = int(kvp["rows"]) + cols = int(kvp["cols"]) + depths = int(kvp["depths"]) - self.metadata.set_cols(cols) - self.metadata.set_rows(rows) - self.metadata.set_depths(depths) - self.metadata.set_number_of_cells(ncells) + ncells = cols * rows * depths - return True + self.metadata.set_cols(cols) + self.metadata.set_rows(rows) + self.metadata.set_depths(depths) + self.metadata.set_number_of_cells(ncells) - return False + return True ############################################################################### @@ -1167,35 +1162,34 @@ def load(self) -> bool: # Get the data from an existing vector map kvp = self.ciface.read_vector_info(self.get_name(), self.get_mapset()) - if kvp: - # Fill spatial extent - self.set_spatial_extent_from_values( - north=kvp["north"], - south=kvp["south"], - east=kvp["east"], - west=kvp["west"], - top=kvp["top"], - bottom=kvp["bottom"], - ) + if not kvp: + return False + # Fill spatial extent + self.set_spatial_extent_from_values( + north=kvp["north"], + south=kvp["south"], + east=kvp["east"], + west=kvp["west"], + top=kvp["top"], + bottom=kvp["bottom"], + ) - # Fill metadata - self.metadata.set_3d_info(kvp["map3d"]) - self.metadata.set_number_of_points(kvp["points"]) - self.metadata.set_number_of_lines(kvp["lines"]) - self.metadata.set_number_of_boundaries(kvp["boundaries"]) - self.metadata.set_number_of_centroids(kvp["centroids"]) - self.metadata.set_number_of_faces(kvp["faces"]) - self.metadata.set_number_of_kernels(kvp["kernels"]) - self.metadata.set_number_of_primitives(kvp["primitives"]) - self.metadata.set_number_of_nodes(kvp["nodes"]) - self.metadata.set_number_of_areas(kvp["areas"]) - self.metadata.set_number_of_islands(kvp["islands"]) - self.metadata.set_number_of_holes(kvp["holes"]) - self.metadata.set_number_of_volumes(kvp["volumes"]) - - return True + # Fill metadata + self.metadata.set_3d_info(kvp["map3d"]) + self.metadata.set_number_of_points(kvp["points"]) + self.metadata.set_number_of_lines(kvp["lines"]) + self.metadata.set_number_of_boundaries(kvp["boundaries"]) + self.metadata.set_number_of_centroids(kvp["centroids"]) + self.metadata.set_number_of_faces(kvp["faces"]) + self.metadata.set_number_of_kernels(kvp["kernels"]) + self.metadata.set_number_of_primitives(kvp["primitives"]) + self.metadata.set_number_of_nodes(kvp["nodes"]) + self.metadata.set_number_of_areas(kvp["areas"]) + self.metadata.set_number_of_islands(kvp["islands"]) + self.metadata.set_number_of_holes(kvp["holes"]) + self.metadata.set_number_of_volumes(kvp["volumes"]) - return False + return True ############################################################################### diff --git a/python/grass/temporal/temporal_raster_base_algebra.py b/python/grass/temporal/temporal_raster_base_algebra.py index b533d96e6f6..95a3c756ce6 100644 --- a/python/grass/temporal/temporal_raster_base_algebra.py +++ b/python/grass/temporal/temporal_raster_base_algebra.py @@ -332,26 +332,26 @@ def build_spatio_temporal_topology_list( spatial_relations = map_i.get_spatial_relations() for temporal_topology in temporal_topo_list: - if temporal_topology.upper() in temporal_relations.keys(): - if ( - self._check_spatial_topology_entries( - spatial_topo_list, spatial_relations - ) - is True - ): - if count_map: - relationmaplist = temporal_relations[ - temporal_topology.upper() - ] - gvar = GlobalTemporalVar() - gvar.td = len(relationmaplist) - if "map_value" in dir(map_i): - map_i.map_value.append(gvar) - else: - map_i.map_value = gvar - # Use unique identifier, since map names may be equal - resultdict[map_i.uid] = map_i - # map_i.print_info() + if temporal_topology.upper() not in temporal_relations.keys(): + continue + if ( + self._check_spatial_topology_entries( + spatial_topo_list, spatial_relations + ) + is not True + ): + continue + if count_map: + relationmaplist = temporal_relations[temporal_topology.upper()] + gvar = GlobalTemporalVar() + gvar.td = len(relationmaplist) + if "map_value" in dir(map_i): + map_i.map_value.append(gvar) + else: + map_i.map_value = gvar + # Use unique identifier, since map names may be equal + resultdict[map_i.uid] = map_i + # map_i.print_info() resultlist = resultdict.values() @@ -461,33 +461,36 @@ def compare_cmd_value( temporal_relations = map_i.get_temporal_relations() for topo in temporal_topo_list: - if topo.upper() in temporal_relations.keys(): - relationmaplist = temporal_relations[topo.upper()] - if count == 0 and "cmd_list" in dir(map_i): - cmd_value_list.extend((compop, "(")) - for relationmap in relationmaplist: - if ( - self._check_spatial_topology_relation( - spatial_topo_list, map_i, relationmap - ) - is True - ): - if convert and "condition_value" in dir(relationmap): - if relationmap.condition_value != []: - cmdstring = str(int(relationmap.condition_value[0])) - relationmap.cmd_list = cmdstring - if "cmd_list" in dir(relationmap): - if count > 0: - cmd_value_list.append(aggregate + aggregate) - cmd_value_list.append(relationmap.cmd_list) - count += 1 - if self.debug: - print( - "compare_cmd_value", - map_i.get_id(), - relationmap.get_id(), - relationmap.cmd_list, - ) + if topo.upper() not in temporal_relations.keys(): + continue + relationmaplist = temporal_relations[topo.upper()] + if count == 0 and "cmd_list" in dir(map_i): + cmd_value_list.extend((compop, "(")) + for relationmap in relationmaplist: + if ( + self._check_spatial_topology_relation( + spatial_topo_list, map_i, relationmap + ) + is not True + ): + continue + if convert and "condition_value" in dir(relationmap): + if relationmap.condition_value != []: + cmdstring = str(int(relationmap.condition_value[0])) + relationmap.cmd_list = cmdstring + if "cmd_list" in dir(relationmap): + if count > 0: + cmd_value_list.append(aggregate + aggregate) + cmd_value_list.append(relationmap.cmd_list) + count += 1 + if self.debug: + print( + "compare_cmd_value", + map_i.get_id(), + relationmap.get_id(), + relationmap.cmd_list, + ) + if count > 0: cmd_value_list.append(")") cmd_value_str = "".join(map(str, cmd_value_list)) @@ -519,28 +522,30 @@ def operator_cmd_value( leftcmd = map_i cmdstring = "" for topo in temporal_topo_list: - if topo.upper() in temporal_relations.keys(): - relationmaplist = temporal_relations[topo.upper()] - for relationmap in relationmaplist: - if ( - self._check_spatial_topology_relation( - spatial_topo_list, map_i, relationmap - ) - is True - ): - # Create r.mapcalc expression string for the operation. - cmdstring = self.build_command_string( - leftcmd, relationmap, operator=operator, cmd_type="operator" + if topo.upper() not in temporal_relations.keys(): + continue + relationmaplist = temporal_relations[topo.upper()] + for relationmap in relationmaplist: + if ( + self._check_spatial_topology_relation( + spatial_topo_list, map_i, relationmap + ) + is True + ): + # Create r.mapcalc expression string for the operation. + cmdstring = self.build_command_string( + leftcmd, relationmap, operator=operator, cmd_type="operator" + ) + leftcmd = cmdstring + + if self.debug: + print( + "operator_cmd_value", + map_i.get_id(), + operator, + relationmap.get_id(), ) - leftcmd = cmdstring - if self.debug: - print( - "operator_cmd_value", - map_i.get_id(), - operator, - relationmap.get_id(), - ) # Add command list to result map. map_i.cmd_list = cmdstring if self.debug: @@ -583,56 +588,54 @@ 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]: - if ( - self._check_spatial_topology_relation( - spatial_topo_list, map_i, map_j - ) - is True - ): - if temporal == "r": - # Generate an intermediate map for the result map list. - map_new = self.generate_new_map( - base_map=map_i, - bool_op="and", - copy=True, - rename=True, - ) - # Create overlaid map extent. - returncode = self.overlay_map_extent( - map_new, map_j, "and", temp_op=temporal - ) + if topo not in tbrelations.keys(): + continue + for map_j in tbrelations[topo]: + if ( + self._check_spatial_topology_relation( + spatial_topo_list, map_i, map_j + ) + is not True + ): + continue + if temporal == "r": + # Generate an intermediate map for the result map list. + map_new = self.generate_new_map( + base_map=map_i, + bool_op="and", + copy=True, + rename=True, + ) + # Create overlaid map extent. + returncode = self.overlay_map_extent( + map_new, map_j, "and", temp_op=temporal + ) - # Stop the loop if no temporal or spatial relationship - # exist. - if returncode == 0: - break - # Append map to result map list. - if returncode == 1: - # print(map_new.cmd_list) - # resultlist.append(map_new) - if cmd_bool: - # Create r.mapcalc expression string for the - # operation. - cmdstring = self.build_command_string( - map_i, - map_j, - operator=operator, - cmd_type=cmd_type, - ) - # Conditional append of module command. - map_new.cmd_list = cmdstring - # Write map object to result dictionary. - resultdict[map_new.uid] = map_new + # Stop the loop if no temporal or spatial relationship + # exist. if returncode == 0: break - # Append map to result map list. - # if returncode == 1: - # resultlist.append(map_new) + # Append map to result map list. + if returncode == 1: + # print(map_new.cmd_list) + # resultlist.append(map_new) + if cmd_bool: + # Create r.mapcalc expression string for the + # operation. + cmdstring = self.build_command_string( + map_i, + map_j, + operator=operator, + cmd_type=cmd_type, + ) + # Conditional append of module command. + map_new.cmd_list = cmdstring + # Write map object to result dictionary. + resultdict[map_new.uid] = map_new + if returncode == 0: + break # Get sorted map objects as values from result dictionary. resultlist = resultdict.values() return sorted(resultlist, key=AbstractDatasetComparisonKeyStartTime) diff --git a/python/grass/temporal/temporal_vector_algebra.py b/python/grass/temporal/temporal_vector_algebra.py index 099a56b89e5..f29c5e1a5a0 100644 --- a/python/grass/temporal/temporal_vector_algebra.py +++ b/python/grass/temporal/temporal_vector_algebra.py @@ -272,17 +272,18 @@ def build_spatio_temporal_topology_list( self.overlay_cmd_value(map_i, tbrelations, compop, topolist) for topo in topolist: - if topo.upper() in tbrelations.keys(): - if count_map: - relationmaplist = tbrelations[topo.upper()] - gvar = GlobalTemporalVar() - gvar.td = len(relationmaplist) - if "map_value" in dir(map_i): - map_i.map_value.append(gvar) - else: - map_i.map_value = gvar - # Use unique identifier, since map names may be equal - resultdict[map_i.uid] = map_i + if topo.upper() not in tbrelations.keys(): + continue + if count_map: + relationmaplist = tbrelations[topo.upper()] + gvar = GlobalTemporalVar() + gvar.td = len(relationmaplist) + if "map_value" in dir(map_i): + map_i.map_value.append(gvar) + else: + map_i.map_value = gvar + # Use unique identifier, since map names may be equal + resultdict[map_i.uid] = map_i resultlist = resultdict.values() # Sort list of maps chronological. @@ -311,41 +312,38 @@ def overlay_cmd_value(self, map_i, tbrelations, function, topolist=["EQUAL"]): if "cmd_list" in dir(map_i): resultlist += map_i.cmd_list for topo in topolist: - if topo.upper() in tbrelations.keys(): - relationmaplist = tbrelations[topo.upper()] - for relationmap in relationmaplist: - # Append command list of given map to result command list. - if "cmd_list" in dir(relationmap): - resultlist += relationmap.cmd_list - # Generate an intermediate name - name = self.generate_map_name() - # Put it into the removalbe map list - self.removable_maps[name] = VectorDataset( - name + "@%s" % (self.mapset) - ) - map_i.set_id(name + "@" + self.mapset) - # Set second input for overlay module. - mapbinput = relationmap.get_id() - # Create module command in PyGRASS for v.overlay and v.patch. - if operator != "disor": - m = copy.deepcopy(self.m_overlay) - m.run_ = False - m.inputs["operator"].value = operator - m.inputs["ainput"].value = str(mapainput) - m.inputs["binput"].value = str(mapbinput) - m.outputs["output"].value = name - m.flags["overwrite"].value = self.overwrite - else: - patchinput = str(mapainput) + "," + str(mapbinput) - m = copy.deepcopy(self.m_patch) - m.run_ = False - m.inputs["input"].value = patchinput - m.outputs["output"].value = name - m.flags["overwrite"].value = self.overwrite - # Conditional append of module command. - resultlist.append(m) - # Set new map name to temporary map name. - mapainput = name + if topo.upper() not in tbrelations.keys(): + continue + relationmaplist = tbrelations[topo.upper()] + for relationmap in relationmaplist: + # Append command list of given map to result command list. + if "cmd_list" in dir(relationmap): + resultlist += relationmap.cmd_list + # Generate an intermediate name + name = self.generate_map_name() + # Put it into the removalbe map list + self.removable_maps[name] = VectorDataset(name + "@%s" % (self.mapset)) + map_i.set_id(name + "@" + self.mapset) + # Set second input for overlay module. + mapbinput = relationmap.get_id() + # Create module command in PyGRASS for v.overlay and v.patch. + if operator != "disor": + m = copy.deepcopy(self.m_overlay) + m.run_ = False + m.inputs["operator"].value = operator + m.inputs["ainput"].value = str(mapainput) + m.inputs["binput"].value = str(mapbinput) + else: + patchinput = str(mapainput) + "," + str(mapbinput) + m = copy.deepcopy(self.m_patch) + m.run_ = False + m.inputs["input"].value = patchinput + m.outputs["output"].value = name + m.flags["overwrite"].value = self.overwrite + # Conditional append of module command. + resultlist.append(m) + # Set new map name to temporary map name. + mapainput = name # Add command list to result map. map_i.cmd_list = resultlist @@ -375,30 +373,31 @@ def set_temporal_extent_list(self, maplist, topolist=["EQUAL"], temporal="l"): ) # 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]: - if temporal == "r": - # Generate an intermediate map for the result map list. - map_new = self.generate_new_map( - base_map=map_i, - bool_op="and", - copy=True, - rename=False, - remove=True, - ) - # Create overlaid map extent. - returncode = self.overlay_map_extent( - map_new, map_j, "and", temp_op=temporal + if topo not in tbrelations.keys(): + continue + for map_j in tbrelations[topo]: + if temporal == "r": + # Generate an intermediate map for the result map list. + map_new = self.generate_new_map( + base_map=map_i, + bool_op="and", + copy=True, + rename=False, + remove=True, ) - # Stop the loop if no temporal or spatial relationship exist. - if returncode == 0: - break - # Append map to result map list. - if returncode == 1: - # resultlist.append(map_new) - resultdict[map_new.get_id()] = map_new + # Create overlaid map extent. + returncode = self.overlay_map_extent( + map_new, map_j, "and", temp_op=temporal + ) + # Stop the loop if no temporal or spatial relationship exist. if returncode == 0: break + # Append map to result map list. + if returncode == 1: + # resultlist.append(map_new) + resultdict[map_new.get_id()] = map_new + if returncode == 0: + break # Append map to result map list. # if returncode == 1: # resultlist.append(map_new) @@ -496,42 +495,43 @@ def p_statement_assign(self, t): map_i.set_id(newident + "@" + mapset) count += 1 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 - 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) - map_test_extent = map_test.get_temporal_extent_as_tuple() - if map_test_extent != map_i_extent: - # Create new map with basename - newident = self.basename + "_" + str(count).zfill(leadzero) - map_result = map_i.get_new_instance( - newident + "@" + self.mapset - ) - if map_test.map_exists() and self.overwrite is False: - self.msgr.fatal( - "Error raster maps with basename %s exist. " - "Use --o flag to overwrite existing file" - % (mapname) - ) + continue + + # Test if temporal extents have been changed by temporal + # 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) + map_test_extent = map_test.get_temporal_extent_as_tuple() + if map_test_extent != map_i_extent: + # Create new map with basename + newident = self.basename + "_" + str(count).zfill(leadzero) + map_result = map_i.get_new_instance( + newident + "@" + self.mapset + ) - map_result.set_temporal_extent(map_i.get_temporal_extent()) - map_result.set_spatial_extent(map_i.get_spatial_extent()) - # Attention we attach a new attribute - map_result.is_new = True - count += 1 - register_list.append(map_result) + if map_test.map_exists() and self.overwrite is False: + self.msgr.fatal( + "Error raster maps with basename %s exist. " + "Use --o flag to overwrite existing file" % (mapname) + ) - # Copy the map - m = copy.deepcopy(self.m_copy) - m.inputs["vector"].value = map_i.get_id(), newident - m.flags["overwrite"].value = self.overwrite - m.run() - else: - register_list.append(map_i) + map_result.set_temporal_extent(map_i.get_temporal_extent()) + map_result.set_spatial_extent(map_i.get_spatial_extent()) + # Attention we attach a new attribute + map_result.is_new = True + count += 1 + register_list.append(map_result) + + # Copy the map + m = copy.deepcopy(self.m_copy) + m.inputs["vector"].value = map_i.get_id(), newident + m.flags["overwrite"].value = self.overwrite + m.run() + else: + register_list.append(map_i) if len(register_list) > 0: # Create result space time dataset.