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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 13 additions & 1 deletion beratools/__init__.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,21 @@
import os as _os

# numba (cache=True, as in xarray-spatial) caches compiled functions in __pycache__ beside their code
# and first checks it can write a temporary file there. Under Program Files (the Windows installer)
# it can't, and on Windows Python's tempfile takes the PermissionError for a name already taken and
# retries up to TMP_MAX (2**31 - 1) times, so a tool hangs while importing. Cache in the user's
# folder instead. Here, as every tool, the GUI and the CLI import beratools before numba.
if _os.name == "nt" and "NUMBA_CACHE_DIR" not in _os.environ:
_os.environ["NUMBA_CACHE_DIR"] = _os.path.join(
_os.environ.get("LOCALAPPDATA") or _os.path.expanduser("~"), "BERA Tools", "numba_cache"
)

__author__ = """Applied Geospatial Research Group"""
__email__ = '[email protected]'
# The one place the version is set: the packages, the GUI's About box and each module's
# requires_frame check read it. Bump it for each release (see the maintainer guide), and set
# "version" in every module's tools.json to the same (tests/test_registry.py checks it).
__version__ = "0.7.0"
__version__ = "0.7.1"
__license__ = "GPL-3.0-or-later"
__copyright__ = "Copyright (c) AppliedGRG"
__status__ = "Pre-Alpha"
Expand Down
12 changes: 11 additions & 1 deletion beratools/core/pipeline.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,15 @@
PIPELINE_FORMAT = 2
PACKAGE_ROOT = Path(__file__).resolve().parents[2]

# Python options a tool process starts with. Options, not PYTHONUTF8 or PYTHONUNBUFFERED: the
# Windows installer's Python has a ._pth file, which makes it ignore the PYTHON* environment variables.
# -u: write output at once. To a pipe (the GUI reads one) Python otherwise holds back what isn't
# flushed, and a tool shows nothing for minutes while it works.
# -X utf8: the tools print symbols such as ✓; a Python outside conda (the installer's) writes to a
# pipe in the Windows code page (cp1252), which can't encode them, and the tool stops with
# UnicodeEncodeError.
TOOL_PYTHON_OPTIONS = ["-u", "-X", "utf8"]


@functools.lru_cache(maxsize=None)
def _tool_params():
Expand Down Expand Up @@ -235,7 +244,8 @@ def run_pipeline(steps, processes=0):
print(f"Step {i + 1}/{len(steps)}: {step['tool_api']}")
print("-" * 50, flush=True)
args = resolve_step_args(steps, i)
result = subprocess.run([sys.executable] + tool_command(step["tool_api"], args, processes), env=env)
command = [sys.executable, *TOOL_PYTHON_OPTIONS, *tool_command(step["tool_api"], args, processes)]
result = subprocess.run(command, env=env)
if result.returncode != 0:
raise RuntimeError(f"Step {i + 1} ({step['tool_api']}) failed with exit code {result.returncode}")

Expand Down
2 changes: 2 additions & 0 deletions beratools/gui/bt_data.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
import pyogrio

import beratools.core.constants as bt_const
from beratools.core.pipeline import TOOL_PYTHON_OPTIONS
from beratools.core.registry import get_registry, tool_script
from beratools.gui.geometry_types import (
format_expected_families,
Expand Down Expand Up @@ -450,6 +451,7 @@ def prepare_tool_run(self, tool_api, args, callback=None):

if tool_type == "python":
tool_args = [
*TOOL_PYTHON_OPTIONS,
tool_script(tool_api).as_posix(),
"-i", args_string,
"-p", str(self.get_selected_cpu_cores()),
Expand Down
5 changes: 5 additions & 0 deletions beratools/gui/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,11 @@

put_conda_dlls_on_path()

# GDAL before Qt. The PyQt5 wheel ships its own, older msvcp140.dll (PyQt5/Qt5/bin); loaded first,
# it is the one GDAL gets, and the GDAL wheel of the Windows installer then crashes on import
# (access violation, 0xC0000005). Loaded first, GDAL gets the system's current runtime.
from osgeo import gdal # noqa: E402, F401

# Import after environment variables are set
from beratools.gui.bt_gui_main import runner # noqa: E402

Expand Down
2 changes: 1 addition & 1 deletion beratools/modules/mapping/tools.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"$schema": "../../gui/assets/module.schema.json",
"module": "mapping",
"version": "0.7.0",
"version": "0.7.1",
"requires_frame": ">=0.7",
"category": "Mapping",
"description": "Tools used to map centerlines and footprint polygons of linear disturbances in forests using a Canopy Height Model (CHM) as reference.",
Expand Down
33 changes: 28 additions & 5 deletions beratools/modules/pc2products/r_common.py
Original file line number Diff line number Diff line change
Expand Up @@ -304,6 +304,31 @@ def check_las_out_folder_existence(folder):
OPTIONAL_WORKER_PACKAGES = ['future.mirai']


def r_install_library():
"""
The R library the tools install missing R packages into.

An R inside the conda/pixi environment: that R's own library, which keeps the packages in the
environment. A standalone R (one from CRAN, as the Windows installer users have): the user's
library (R_LIBS_USER, such as %LOCALAPPDATA%/R/win-library/4.5), as R itself does, since a user
can't write to an R in Program Files. It is created if missing and put first in .libPaths(),
as R only adds it at startup when it exists.
"""
initialize_r()
from beratools.modules.pc2products import r_interface

if r_interface.R_IN_ENV:
return str(r('normalizePath(file.path(R.home(), "library"), winslash = "/")')[0])
return str(r(
"""local({
lib <- path.expand(strsplit(Sys.getenv("R_LIBS_USER"), .Platform$path.sep)[[1]][1])
dir.create(lib, recursive = TRUE, showWarnings = FALSE)
.libPaths(c(lib, .libPaths()))
normalizePath(lib, winslash = "/")
})"""
)[0])


def check_r_packages_installation(packages, optional=()):
"""
Install the R packages in packages that are missing, stopping if one can't be installed.
Expand Down Expand Up @@ -331,9 +356,7 @@ def check_r_packages_installation(packages, optional=()):

utils.chooseCRANmirror(ind=12) # select the 12th mirror in the list: Canada

# The environment only provides R itself, so install into that R's own library
# (not a user library) to keep the packages inside the conda/pixi environment.
r_lib = str(r('normalizePath(file.path(R.home(), "library"), winslash = "/")')[0])
r_lib = r_install_library()
print(f"Installing missing R packages into {r_lib}: {', '.join(cran_names_to_install)}")

need_fasterRaster = False
Expand All @@ -359,11 +382,11 @@ def check_r_packages_installation(packages, optional=()):


def _install_optional_r_packages(packages):
"""Install optional R packages into the environment's R library, only warning on failure."""
"""Install optional R packages (see r_install_library), only warning on failure."""
from rpy2.robjects import StrVector
from rpy2.robjects.packages import importr, isinstalled

r_lib = str(r('normalizePath(file.path(R.home(), "library"), winslash = "/")')[0])
r_lib = r_install_library()
print(f"Installing optional R packages into {r_lib}: {', '.join(packages)}")
try:
utils = importr('utils')
Expand Down
81 changes: 68 additions & 13 deletions beratools/modules/pc2products/r_interface.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,65 @@
os.environ.setdefault("OMP_NUM_THREADS", "1")


def _version_key(r_home):
"""(4, 5, 10) for R-4.5.10, so that 4.5.10 sorts after 4.5.3."""
parts = Path(r_home).name.removeprefix("R-").split(".")
return tuple(int(part) if part.isdigit() else -1 for part in parts)


def _registry_r_homes():
"""The InstallPath of each R that R's Windows installer registered, for all users or this one."""
if os.name != "nt":
return []
import winreg

homes = []
for hive in (winreg.HKEY_LOCAL_MACHINE, winreg.HKEY_CURRENT_USER):
for base in (r"SOFTWARE\R-core\R", r"SOFTWARE\R-core\R64"):
try:
key = winreg.OpenKey(hive, base, 0, winreg.KEY_READ | winreg.KEY_WOW64_64KEY)
except OSError:
continue
# the current version's InstallPath, and one subkey per installed version
keys = [key]
i = 0
while True:
try:
keys.append(winreg.OpenKey(key, winreg.EnumKey(key, i)))
except OSError:
break
i += 1
for k in keys:
with k:
try:
homes.append(winreg.QueryValueEx(k, "InstallPath")[0])
except OSError:
pass
return homes


def windows_r_homes():
"""
The R installs from CRAN's Windows installer, newest first.

From the registry, and from the installer's default folders: Program Files for all users, and
%LOCALAPPDATA%/Programs for one user (installed without administrator rights).
"""
candidates = [Path(home) for home in _registry_r_homes()]
roots = [Path(os.environ.get("ProgramFiles", r"C:\Program Files")) / "R"]
if os.environ.get("LOCALAPPDATA"):
roots.append(Path(os.environ["LOCALAPPDATA"]) / "Programs" / "R")
for root in roots:
if root.is_dir():
candidates.extend(root.glob("R-*"))

homes = {}
for candidate in candidates:
if (candidate / "bin" / "R.exe").exists():
homes.setdefault(os.path.normcase(str(candidate.resolve())), candidate)
return sorted(homes.values(), key=_version_key, reverse=True)


def configure_r_environment():
"""Locate and configure R before importing rpy2."""
# --------------------------------------------------
Expand Down Expand Up @@ -85,17 +144,12 @@ def configure_r_environment():
return str(candidate)

# --------------------------------------------------
# 4. Standard Windows install
# 4. R from CRAN's Windows installer, newest first
# --------------------------------------------------
r_root = Path(r"C:\Program Files\R")

if r_root.exists():
versions = sorted(r_root.glob("R-*"), reverse=True)
for r_home in windows_r_homes():
os.environ["R_HOME"] = str(r_home)
return str(r_home)

for version in versions:
if (version / "bin" / "R.exe").exists():
os.environ["R_HOME"] = str(version)
return str(version)
# --------------------------------------------------
# 5. Diagnostics
# --------------------------------------------------
Expand All @@ -108,10 +162,11 @@ def configure_r_environment():
raise RuntimeError(
"\n"
"R installation not found.\n\n"
"Install R from:\n"
"https://cran.r-project.org/\n\n"
"Or install in conda:\n"
"conda install -c conda-forge r-base rpy2\n"
"The PC2Products (LiDAR) tools need R 4.5:\n"
"- Windows: install R 4.5 from https://cran.r-project.org/bin/windows/base/ with the default\n"
" options, then start BERA Tools again.\n"
"- Other systems: install R 4.5 from https://cran.r-project.org/\n"
"- In a conda or pixi environment: conda install -c conda-forge r-base rpy2\n"
)


Expand Down
42 changes: 42 additions & 0 deletions beratools/modules/pc2products/tests/test_r_environment.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
"""Verify R environment is available."""

import os

import pytest

# Union of the packages the rpy_* tools check for.
Expand Down Expand Up @@ -31,3 +33,43 @@ def test_r_packages():
assert not missing, (
f"Missing R packages: {', '.join(missing)}"
)


INSTALL_LIBRARY = """
import os, sys
from beratools.modules.pc2products import r_common, r_interface
standalone = sys.argv[1] == "standalone"
if standalone:
# as for an R outside the environment: R starts with the user's library, here a test folder
os.environ["R_LIBS_USER"] = sys.argv[2]
r_interface.R_IN_ENV = False
lib = r_common.r_install_library()
print("LIB", lib)
print("FIRST", str(r_common.r(".libPaths()[1]")[0]))
"""


def _install_library(*args):
import subprocess
import sys

result = subprocess.run(
[sys.executable, "-c", INSTALL_LIBRARY, *args], capture_output=True, text=True, timeout=300
)
assert result.returncode == 0, result.stderr
lines = dict(line.split(" ", 1) for line in result.stdout.splitlines() if line[:4] in ("LIB ", "FIRS"))
return lines["LIB"], lines["FIRST"]


def test_r_install_library_of_environment_r_is_its_own():
lib, _ = _install_library("environment")
assert lib.endswith("/library")


def test_r_install_library_of_standalone_r_is_the_user_library(tmp_path):
"""A user can't write to an R in Program Files: install into the user's library, as R does."""
user_lib = tmp_path / "win-library" / "4.5"
lib, first = _install_library("standalone", str(user_lib))
assert user_lib.is_dir()
assert os.path.samefile(lib, user_lib)
assert os.path.samefile(first, user_lib)
48 changes: 48 additions & 0 deletions beratools/modules/pc2products/tests/test_r_interface.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
"""How the R tools find an R installed with CRAN's Windows installer."""

from pathlib import Path

from beratools.modules.pc2products import r_interface


def _r(root, version):
home = Path(root) / f"R-{version}"
(home / "bin").mkdir(parents=True)
(home / "bin" / "R.exe").touch()
return home


def test_windows_r_homes_finds_program_files_user_folder_and_registry(tmp_path, monkeypatch):
program_files = tmp_path / "Program Files"
local_app_data = tmp_path / "Local"
elsewhere = tmp_path / "D" / "R"
for_all = _r(program_files / "R", "4.5.3")
for_user = _r(local_app_data / "Programs" / "R", "4.5.10")
registered = _r(elsewhere, "4.4.1")
(program_files / "R" / "R-4.6.0").mkdir() # no bin/R.exe: left out
monkeypatch.setenv("ProgramFiles", str(program_files))
monkeypatch.setenv("LOCALAPPDATA", str(local_app_data))
# registered twice (HKLM and HKCU), and one also found in Program Files
monkeypatch.setattr(
r_interface, "_registry_r_homes", lambda: [str(registered), str(registered), str(for_all)]
)

homes = r_interface.windows_r_homes()

# newest first, by number: 4.5.10 after 4.5.3
assert [h.name for h in homes] == ["R-4.5.10", "R-4.5.3", "R-4.4.1"]
assert homes[0] == for_user


def test_windows_r_homes_is_empty_without_r(tmp_path, monkeypatch):
monkeypatch.setenv("ProgramFiles", str(tmp_path / "Program Files"))
monkeypatch.setenv("LOCALAPPDATA", str(tmp_path / "Local"))
monkeypatch.setattr(r_interface, "_registry_r_homes", lambda: [])
assert r_interface.windows_r_homes() == []


def test_registry_r_homes_returns_paths():
"""On Windows reads the registry; elsewhere there is none. Either way, a list of strings."""
homes = r_interface._registry_r_homes()
assert isinstance(homes, list)
assert all(isinstance(home, str) for home in homes)
2 changes: 1 addition & 1 deletion beratools/modules/pc2products/tools.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"$schema": "../../gui/assets/module.schema.json",
"module": "pc2products",
"version": "0.7.0",
"version": "0.7.1",
"requires_frame": ">=0.7",
"category": "PC2Products",
"description": "Tools used to work with LiDAR point cloud data to produce different results. e.g. DTM, DSM and CHM.",
Expand Down
2 changes: 1 addition & 1 deletion beratools/modules/raster2products/tools.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"$schema": "../../gui/assets/module.schema.json",
"module": "raster2products",
"version": "0.7.0",
"version": "0.7.1",
"requires_frame": ">=0.7",
"category": "Raster2Products",
"description": "Tools used to work with raster data, such as a DTM, to produce other rasters, e.g. a normalized DTM.",
Expand Down
Loading
Loading