Source code for temporal.univar_statistics

"""
Univariate statistic function for space time datasets

Usage:

.. code-block:: python

    import grass.temporal as tgis

    tgis.print_gridded_dataset_univar_statistics(
        type, input, output, where, extended, no_header, fs, rast_region
    )

..

(C) 2012-2024 by the GRASS Development Team
This program is free software under the GNU General Public
License (>=v2). Read the file COPYING that comes with GRASS
for details.

:authors: Soeren Gebbert
"""

from multiprocessing import Pool
from subprocess import PIPE
import json

import grass.script as gs
from grass.pygrass.modules import Module

from .core import SQLDatabaseInterfaceConnection, get_current_mapset
from .factory import dataset_factory
from .open_stds import open_old_stds

###############################################################################


[docs] def compute_univar_stats( registered_map_info, stats_module, fs, rast_region: bool = False, output_format: str | None = None, ): """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 fs: Field separator :param rast_region: If set True ignore the current region settings and use the raster map regions for univar statistical calculation. Only available for strds. :param output_format: Output format specification """ string = "" id = registered_map_info["id"] start = registered_map_info["start_time"] end = registered_map_info["end_time"] semantic_label = ( "" if stats_module.name == "r3.univar" or not registered_map_info["semantic_label"] else registered_map_info["semantic_label"] ) stats_module.inputs.map = id if rast_region and (stats_module.inputs.zones or stats_module.name == "r3.univar"): stats_module.env = gs.region_env(raster=id) stats_module.run() univar_stats = stats_module.outputs.stdout if not univar_stats: gs.warning( _("Unable to get statistics for raster map <%s>") % id if stats_module.name == "r.univar" else _("Unable to get statistics for 3d raster map <%s>") % id ) return None if output_format == "json": try: stats = json.loads(univar_stats) except ValueError: gs.warning(_("Unable to parse JSON output for map <%s>") % id) return None if isinstance(stats, dict): stats = [stats] processed_stats = [] for s in stats: new_s = { "id": id, "semantic_label": semantic_label if stats_module.name == "r.univar" and semantic_label else None, "start": str(start) if start else None, "end": str(end) if end else None, } new_s.update(s) processed_stats.append(new_s) return processed_stats eol = "" for idx, stats_kv in enumerate(univar_stats.split(";")): stats = gs.utils.parse_key_val(stats_kv) string += ( f"{id}{fs}{semantic_label}{fs}{start}{fs}{end}" if stats_module.name == "r.univar" else f"{id}{fs}{start}{fs}{end}" ) if stats_module.inputs.zones: if idx == 0: zone = str(stats["zone"]) string = "" continue string += f"{fs}{zone}" if "zone" in stats: zone = str(stats["zone"]) eol = "\n" else: eol = "" string += f"{fs}{stats['mean']}{fs}{stats['min']}" string += f"{fs}{stats['max']}{fs}{stats['mean_of_abs']}" string += f"{fs}{stats['stddev']}{fs}{stats['variance']}" string += f"{fs}{stats['coeff_var']}{fs}{stats['sum']}" string += f"{fs}{stats['null_cells']}{fs}{stats['n']}" string += f"{fs}{stats['n']}" if "median" in stats: string += f"{fs}{stats['first_quartile']}{fs}{stats['median']}" string += f"{fs}{stats['third_quartile']}" if stats_module.inputs.percentile: for perc in stats_module.inputs.percentile: perc_value = stats[ "percentile_" f"{str(perc).rstrip('0').rstrip('.').replace('.', '_')}" ] string += f"{fs}{perc_value}" string += eol return string
###############################################################################