Skip to content

grass.script: Add available_cpus and resolve_nprocs helpers#7414

Open
petrasovaa wants to merge 1 commit into
OSGeo:mainfrom
petrasovaa:python-nprocs
Open

grass.script: Add available_cpus and resolve_nprocs helpers#7414
petrasovaa wants to merge 1 commit into
OSGeo:mainfrom
petrasovaa:python-nprocs

Conversation

@petrasovaa
Copy link
Copy Markdown
Contributor

We are using G_set_omp_num_threads that resolves nprocs <= 0, but in Python, we don't have equivalent, potentially resulting in bugs. This PR adds the function for resolving the nprocs and also function for getting available cpus that works better in containers.

  • available_cpus() — number of CPUs this process may actually use. Prefers affinity-aware sources
    (os.process_cpu_count on 3.13+, os.sched_getaffinity on Linux) over os.cpu_count, which reports the host total
    and overcounts in containers and cgroup-limited jobs.
  • resolve_nprocs(nprocs) — mirrors G_set_omp_num_threads() in lib/gis/omp_threads.c:
    • positive → used as-is
    • 0 → all available cores
    • negative → available + nprocs, clamped to at least 1

These functions are applied in the code base, resulting in some bug fixes:

t.rast.univar / t.rast3d.univar: nprocs=0 (documented as "use all available cores") was silently clamped to 1, so the tool ran serially. The tool entry points now apply gs.resolve_nprocs() so the documented G_OPT_M_NPROCS semantics take effect for 0 and negative values.

AI-assisted (Claude Code) — used for migration planning, edge case analysis, and drafting docstrings and tests.

  Affinity-aware CPU count and G_OPT_M_NPROCS resolution (positive
  as-is, 0 = all cores, negative reserves cores). Migrate ad-hoc
  cpu_count() sites in pygrass, jupyter, animation, and datacatalog
  GUI to the new helpers; all become container/cgroup aware.

  Fix t.rast.univar and t.rast3d.univar: nprocs=0 was silently
  clamped to 1 instead of using all available cores.

  New in grass.script public API in GRASS 8.6.
@github-actions github-actions Bot added GUI wxGUI related temporal Related to temporal data processing Python Related code is in Python libraries module tests Related to Test Suite notebook labels May 19, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

GUI wxGUI related libraries module notebook Python Related code is in Python temporal Related to temporal data processing tests Related to Test Suite

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant