API Reference

This page contains the complete API reference for SOLWEIG-GPU, auto-generated from docstrings.

Main Entry Point

solweig_gpu.solweig_gpu.preprocess(base_path, selected_date_str, building_dsm_filename='Building_DSM.tif', dem_filename='DEM.tif', trees_filename='Trees.tif', landcover_filename=None, windcoeff_folder=None, tile_size=3600, overlap=20, use_own_met=True, start_time=None, end_time=None, data_source_type=None, data_folder=None, own_met_file=None, preprocess_dir=None, use_uhi=True)[source]

Run preprocessing only: validate rasters, create tiles, and prepare metfiles.

Use this when you want to run preprocessing once and then call run_walls_aspect() and run_utci_tiles() separately.

Parameters:
  • base_path (str) – Base directory; used to resolve relative raster paths.

  • selected_date_str (str) – Simulation date ‘YYYY-MM-DD’.

  • building_dsm_filename (str) – Raster paths or filenames. Relative paths are resolved against base_path.

  • dem_filename (str) – Raster paths or filenames. Relative paths are resolved against base_path.

  • trees_filename (str) – Raster paths or filenames. Relative paths are resolved against base_path.

  • landcover_filename (str | None) – Raster paths or filenames. Relative paths are resolved against base_path.

  • windcoeff_filename

    Wind coefficient input. Can be:
    • None: do not use wind coefficients

    • folder path containing WindCoeff_dir*.tif

    • glob pattern such as “WindCoeff_dir*.tif”

    • single legacy wind coefficient raster

    Relative paths are resolved against base_path.

    For directional wind coefficients, the expected files are:

    WindCoeff_dir000.tif WindCoeff_dir030.tif … WindCoeff_dir330.tif

  • tile_size (int) – Tile size in pixels.

  • overlap (int) – Overlap between tiles in pixels.

  • use_own_met (bool) – If True, use own_met_file; else use ERA5/WRF.

  • start_time (str | None) – Required for ERA5/WRF, in UTC format ‘YYYY-MM-DD HH:MM:SS’.

  • end_time (str | None) – Required for ERA5/WRF, in UTC format ‘YYYY-MM-DD HH:MM:SS’.

  • data_source_type (str | None) – ‘ERA5’ or ‘wrfout’ when use_own_met is False.

  • data_folder (str | None) – Folder with ERA5/WRF NetCDF files when use_own_met is False.

  • own_met_file (str | None) – Path to custom met file when use_own_met is True.

  • preprocess_dir (str | None) – Directory for preprocessing outputs. Defaults to ‘{base_path}/processed_inputs’.

  • use_uhi (bool) – If True, use UHI-aware ERA5 processing and write UHI_CYCLE/uhii into generated metfiles when available. If False, use standard ERA5 processing and write uhii = 0.0.

  • windcoeff_folder (str | None)

Returns:

The path to the preprocessing directory.

Return type:

str

solweig_gpu.solweig_gpu.build_inputs(lat, lon, city=None, km_buffer=8.0, km_reduced_lat=3.0, km_reduced_lon=1.0, base_folder=None, resolution=2.0)[source]

Build static and meteorological inputs for SOLWEIG-GPU at a given location.

Downloads and processes WorldCover, tree DSM, DEM, LCZ, OSM/GBA vectors, builds Building_DSM, Trees, DEM, Landuse rasters and meteorological NetCDF, and computes wind coefficient. Requires optional dependencies (e.g. earthengine-api, geemap, geopandas, osmnx); install them if you use this step.

Use the returned path as base_path for preprocess() (with raster filenames like Building_DSM.tif, DEM.tif, Trees.tif, Landuse.tif in that folder) and optionally set use_own_met=False with the generated NetCDF in data_folder.

Parameters:
  • lat (float) – Center of the area (degrees).

  • lon (float) – Center of the area (degrees).

  • city (str | None) – Name for the output folder. If None, derived from reverse geocoding.

  • km_buffer (float) – Half-size of initial bounding box in km.

  • km_reduced_lat (float) – Shrink (N/S and E/W) from bbox for SOLWEIG in km.

  • km_reduced_lon (float) – Shrink (N/S and E/W) from bbox for SOLWEIG in km.

  • year_start – Start/end year for meteorology (inclusive).

  • year_end – Start/end year for meteorology (inclusive).

  • base_folder (str | None) – Workspace root. Defaults to the create_inputs module default.

  • resolution (float) – Reference grid resolution in meters.

Returns:

Path to the output directory (e.g. {base_folder}/{city}_for_solweig) containing Building_DSM.tif, DEM.tif, Trees.tif, Landuse.tif and met NetCDF.

Return type:

str

solweig_gpu.solweig_gpu.build_wind_ext_coeff(input_dir, era5_dir, *, directions=(0, 30, 60, 90, 120, 150, 180, 210, 240, 270, 300, 330), z0_ref=0.03, hmin_b=1.0, hmin_t=1.0, z_eval=10.0, zref=10.0, LAI_t=2.0, a0_t=0.5, a1_t=0.4, alpha_min_t=0.2, alpha_max_t=2.5, coeff_min=0.1, coeff_max=1.0, lp_min_open=0.02, max_workers=None)[source]

Build full-domain wind-extension coefficient rasters for SOLWEIG-GPU.

Parameters:
  • input_dir (str | Path) –

    Directory containing the processed SOLWEIG raster inputs. The function searches this directory for:

    Buildings.tif or Building_DSM.tif Trees.tif

    The output WindCoeff_dir*.tif rasters are written into this same directory.

  • era5_dir (str | Path) –

    Directory containing the ERA5 NetCDF file:

    data_stream-oper_stepType-instant.nc

    The function extracts fsr at the midpoint of the building raster and averages it over all available times to use as the roughness length z0.

  • directions (Sequence[int])

  • z0_ref (float)

  • hmin_b (float)

  • hmin_t (float)

  • z_eval (float)

  • zref (float)

  • LAI_t (float)

  • a0_t (float)

  • a1_t (float)

  • alpha_min_t (float)

  • alpha_max_t (float)

  • coeff_min (float)

  • coeff_max (float)

  • lp_min_open (float)

  • max_workers (int | None)

Returns:

Path to the input/output directory.

Return type:

str

solweig_gpu.solweig_gpu.run_walls_aspect(preprocess_dir)[source]

Run wall height and aspect calculation for all tiles in the preprocessing directory.

Call this after preprocess(). Writes to {preprocess_dir}/walls and {preprocess_dir}/aspect.

Parameters:

preprocess_dir (str) – Path returned by preprocess() (contains Building_DSM/, DEM/, Trees/, etc.).

Return type:

None

solweig_gpu.solweig_gpu.calculate_svf(base_path, patch_option=2, overwrite=False)[source]

Calculate standalone Sky View Factor outputs for all raster tiles in a preprocessing directory.

Parameters:
  • base_path (str)

  • patch_option (int)

  • overwrite (bool)

Return type:

None

solweig_gpu.solweig_gpu.run_utci_tiles(base_path, preprocess_dir, selected_date_str, tile_keys=None, save_tmrt=True, save_svf=False, save_kup=False, save_kdown=False, save_lup=False, save_ldown=False, save_shadow=False, save_wbgt=False, save_ta=False, save_wind=False)[source]

Run UTCI (and optional outputs) for tiles in the preprocessing directory.

Call this after preprocess() and run_walls_aspect(). Writes GeoTIFFs to {base_path}/output_folder/{tile_key}/.

Parameters:
  • base_path (str) – Base directory; output_folder is created under this.

  • preprocess_dir (str) – Path returned by preprocess().

  • selected_date_str (str) – Simulation date ‘YYYY-MM-DD’.

  • tile_keys (List[str] | None) – If None, process all tiles. If a list, process only those tile keys.

  • save_tmrt (bool) – Which outputs to save (UTCI is always saved).

  • save_svf (bool) – Which outputs to save (UTCI is always saved).

  • save_kup (bool) – Which outputs to save (UTCI is always saved).

  • save_kdown (bool) – Which outputs to save (UTCI is always saved).

  • save_lup (bool) – Which outputs to save (UTCI is always saved).

  • save_ldown (bool) – Which outputs to save (UTCI is always saved).

  • save_shadow (bool) – Which outputs to save (UTCI is always saved).

  • save_ta (bool) – Save diagnostic Ta field.

  • save_wind (bool) – Save diagnostic wind field.

  • save_wbgt (bool)

Return type:

None

solweig_gpu.solweig_gpu.thermal_comfort(base_path, selected_date_str, building_dsm_filename='Building_DSM.tif', dem_filename='DEM.tif', trees_filename='Trees.tif', landcover_filename=None, ERA_5_z0_find=True, tile_size=3600, overlap=20, use_own_met=True, start_time=None, end_time=None, data_source_type=None, data_folder=None, own_met_file=None, use_uhi=True, save_tmrt=True, save_svf=False, save_kup=False, save_kdown=False, save_lup=False, save_ldown=False, save_shadow=False, save_wbgt=False, save_ta=False, save_wind=False)[source]

Main function to compute urban thermal comfort using the SOLWEIG-GPU model.

Parameters:
  • base_path – Base directory for outputs and relative raster paths.

  • selected_date_str – Simulation date in format ‘YYYY-MM-DD’.

  • building_dsm_filename – Building+terrain DSM path or filename.

  • dem_filename – DEM path or filename.

  • trees_filename – Vegetation DSM path or filename.

  • landcover_filename (str | None) – Optional land cover raster path or filename.

  • windcoeff_filename

    Optional wind coefficient input. Can be:

    • None:

      Do not use wind coefficients.

    • Folder path:

      Folder containing directional wind coefficient rasters: WindCoeff_dir000.tif WindCoeff_dir030.tif … WindCoeff_dir330.tif

    • Glob pattern:

      Example: “WindCoeff_dir*.tif”

    • Single legacy raster:

      Example: “WindCoeff.tif”

    Relative paths are resolved against base_path.

    If directional wind coefficients are provided, the metfile must contain wind direction column Wd. For ERA5 processing, Wd is generated from u10/v10 as meteorological wind-from direction:

    0=N, 90=E, 180=S, 270=W.

    During UTCI calculation, the model selects the nearest 30-degree wind coefficient raster for each timestep.

  • tile_size – Tile size in pixels.

  • overlap – Overlap between tiles in pixels.

  • use_own_met – Use custom meteorological file.

  • start_time – Start datetime ‘YYYY-MM-DD HH:MM:SS’.

  • end_time – End datetime ‘YYYY-MM-DD HH:MM:SS’.

  • data_source_type – ‘ERA5’ or ‘wrfout’.

  • data_folder – Folder containing ERA5/WRF NetCDF files.

  • own_met_file – Path to custom meteorological text file.

  • use_uhi – If True, use UHI-aware ERA5 processing and propagate UHI_CYCLE/uhii into generated metfiles. If False, disable it and write uhii = 0.0.

  • save_tmrt – Save mean radiant temperature output.

  • save_svf – Save sky view factor output.

  • save_kup – Save upward shortwave radiation.

  • save_kdown – Save downward shortwave radiation.

  • save_lup – Save upward longwave radiation.

  • save_ldown – Save downward longwave radiation.

  • save_shadow – Save shadow maps.

  • save_wbgt – Save WBGT output.

Returns:

None

Data Preprocessing

solweig_gpu.preprocessor.infer_timezone_from_grid(latitudes, longitudes)[source]

Infer timezone name from the center of the ERA5 grid.

solweig_gpu.preprocessor.utc_times_to_local_naive(times_utc, timezone_name)[source]

Convert UTC timestamps to local naive datetimes for local-day resampling and local-night detection.

solweig_gpu.preprocessor.compute_uhi_cycle_from_arrays(times, t2_k, swdown_wm2, u_wind_ms, v_wind_ms)[source]

Compute UHI_CYCLE from arrays already extracted from ERA5.

Parameters:
  • times (1D array-like of datetimes)

  • t2_k (ndarray (time, lat, lon), air temperature in K)

  • swdown_wm2 (ndarray (time, lat, lon), shortwave down radiation in W m-2)

  • u_wind_ms (ndarray (time, lat, lon), zonal wind speed in m s-1)

  • v_wind_ms (ndarray (time, lat, lon), meridional wind speed in m s-1)

Returns:

uhi_cycle

Return type:

ndarray (time, lat, lon), in K

solweig_gpu.preprocessor.extract_datetime_strict(filename)[source]

Return (datetime, domain_int) for strictly valid wrfout names. Raises ValueError for any non-matching filename.

solweig_gpu.preprocessor.check_rasters(files)[source]

Check that all provided raster files have matching dimensions, pixel size, and CRS.

Parameters:

files (list) – List of raster file paths.

Returns:

True if all checks pass, raises ValueError/FileNotFoundError otherwise.

Return type:

bool

solweig_gpu.preprocessor.find_windcoeff_files(base_path, windcoeff_filename)[source]
windcoeff_filename can be:
  • None: no wind coefficient

  • folder path: read WindCoeff_dir*.tif inside it

  • single file path: old behavior / fallback

  • glob pattern: e.g. ‘WindCoeff_dir*.tif’

solweig_gpu.preprocessor.create_tiles_to_folder(infile, tilesize, overlap, out_folder, tile_prefix, clear_folder=False)[source]

Tile a raster into a specified folder using a specified filename prefix.

Example output:

out_folder/WindCoeff_dir030_0_0.tif

solweig_gpu.preprocessor.create_windcoeff_tiles(windcoeff_files, tilesize, overlap, preprocess_dir)[source]

Tile all directional wind coefficient rasters into one folder:

preprocess_dir/WindCoeff/WindCoeff_dir000_i_j.tif preprocess_dir/WindCoeff/WindCoeff_dir030_i_j.tif …

solweig_gpu.preprocessor.create_tiles(infile, tilesize, overlap, tile_type, preprocess_dir)[source]

Tile a raster file into smaller chunks.

Normal rasters are written as:

preprocess_dir/DEM/DEM_i_j.tif preprocess_dir/Trees/Trees_i_j.tif etc.

solweig_gpu.preprocessor.process_era5_data(start_time, end_time, folder_path, output_file='Outfile.nc')[source]

Same numeric outputs as your original function, but time is taken from the files and sliced to [start_time, end_time] UTC. Variables written:

T2 (t2m, Kelvin), PSFC (sp, Pa), RH2 (%), WIND (m/s), SWDOWN (W/m^2 = ssrd/3600).

solweig_gpu.preprocessor.process_era5_data_uhi(start_time, end_time, folder_path, output_file='Outfile.nc')[source]

Same numeric outputs as your original function, but time is taken from the files and sliced to [start_time, end_time] UTC. Variables written:

T2 (t2m, Kelvin), PSFC (sp, Pa), RH2 (%), WIND (m/s), SWDOWN (W/m^2), UHI_CYCLE (K).

solweig_gpu.preprocessor.process_wrfout_data(start_time, end_time, folder_path, output_file='Outfile.nc')[source]

Process WRF output files to create meteorological forcing data.

Parameters:
  • start_time (str) – Start datetime string in format “%Y-%m-%d %H:%M:%S”.

  • end_time (str) – End datetime string in format “%Y-%m-%d %H:%M:%S”.

  • folder_path (str) – Directory containing wrfout files.

  • output_file (str) – Output NetCDF file name.

solweig_gpu.preprocessor.process_metfiles(netcdf_file, raster_folder, base_path, selected_date_str, preprocess_dir, use_uhi=True)[source]
solweig_gpu.preprocessor.create_met_files(base_path, source_met_file, preprocess_dir)[source]

Copy a given met file to multiple outputs based on the raster tile filenames.

Parameters:
  • base_path (str) – Base directory containing input rasters.

  • source_met_file (str) – Path to user-provided met file.

  • preprocess_dir (str) – Directory for preprocessing outputs (pre_processing_outputs).

solweig_gpu.preprocessor.ppr(base_path, building_dsm_filename, dem_filename, trees_filename, landcover_filename, windcoeff_filename, tile_size, overlap, selected_date_str, use_own_met, start_time=None, end_time=None, data_source_type=None, data_folder=None, own_met_file=None, preprocess_dir=None, use_uhi=True)[source]

Preprocessing routine to validate raster files, generate tiles, and prepare metfiles for SOLWEIG.

Parameters:
  • base_path (str) – Base working directory containing input rasters.

  • building_dsm_filename (str) – Filename of building DSM raster.

  • dem_filename (str) – Filename of DEM raster.

  • trees_filename (str) – Filename of trees raster.

  • landcover_filename (str) – Filename of landcover raster or None.

  • windcoeff_filename (str) – Filename of wind coefficient raster or None.

  • tile_size (int) – Tile size in pixels.

  • overlap (int) – Overlap between tiles in pixels.

  • selected_date_str (str) – Selected date (YYYY-MM-DD).

  • use_own_met (bool) – Whether to use a user-provided met file.

  • start_time (str) – Start datetime (required if not using own met file).

  • end_time (str) – End datetime (required if not using own met file).

  • data_source_type (str) – Either ‘ERA5’ or ‘wrfout’.

  • data_folder (str) – Folder containing input NetCDF files.

  • own_met_file (str) – Path to user-provided met file (used if use_own_met is True).

  • preprocess_dir (str) – Directory for preprocessing outputs.

  • use_uhi (bool) – Whether to use UHI-aware ERA5 preprocessing.

Radiation Calculations

solweig_gpu.solweig.ensure_tensor(x, device=None)[source]

Convert input to PyTorch tensor on specified device.

Parameters:
  • x – Input data (numpy array, list, or tensor)

  • device (torch.device, optional) – Target device

Returns:

Input as tensor on device

Return type:

torch.Tensor

solweig_gpu.solweig.daylen(DOY, XLAT)[source]

Calculate day length and solar declination for given day and latitude.

Parameters:
Returns:

(DAYL, DEC, SNDN, SNUP) where:
  • DAYL: Day length in hours

  • DEC: Solar declination in degrees

  • SNDN: Time of solar noon in hours

  • SNUP: Time of sunrise in hours

Return type:

tuple

solweig_gpu.solweig.sunonsurface_2018a(azimuthA, scale, buildings, shadow, sunwall, first, second, aspect, walls, Tg, Tgwall, Ta, emis_grid, ewall, alb_grid, SBC, albedo_b, Twater, lc_grid, landcover)[source]

Calculate solar radiation on surfaces with different orientations.

Determines radiation on walls and ground surfaces accounting for building geometry, shadows, and surface properties.

Parameters:
Returns:

Radiation components for different surfaces

Return type:

tuple

solweig_gpu.solweig.gvf_2018a(wallsun, walls, buildings, scale, shadow, first, second, dirwalls, Tg, Tgwall, Ta, emis_grid, ewall, alb_grid, SBC, albedo_b, rows, cols, Twater, lc_grid, landcover)[source]

Calculate ground view factors for radiation exchange between surfaces.

Computes how much ground surfaces “see” walls and other surfaces, accounting for shadows and multiple reflections.

Parameters:
Returns:

View factors and albedo components for different directions

Return type:

tuple

solweig_gpu.solweig.cylindric_wedge(zen, svfalfa, rows, cols)[source]

Calculate form factors for cylindrical geometry (human body model).

Parameters:
  • zen (torch.Tensor) – Solar zenith angle

  • svfalfa (torch.Tensor) – SVF alpha component

  • rows (int) – Grid dimensions

  • cols (int) – Grid dimensions

Returns:

(Fside, Fup, Fcyl) - Form factors for cylinder sides, top, and total

Return type:

tuple

solweig_gpu.solweig.TsWaveDelay_2015a(gvfLup, firstdaytime, timeadd, timestepdec, Tgmap1)[source]

Calculate surface temperature wave delay.

Models thermal inertia and temperature wave propagation in surfaces.

Parameters:
  • gvfLup – Ground view factor for upward longwave

  • firstdaytime – First time step flag

  • timeadd – Time addition parameter

  • timestepdec – Time step decimal

  • Tgmap1 – Previous ground temperature map

Returns:

Temperature with wave delay applied

Return type:

torch.Tensor

solweig_gpu.solweig.Kup_veg_2015a(radI, radD, radG, altitude, svfbuveg, albedo_b, F_sh, gvfalb, gvfalbE, gvfalbS, gvfalbW, gvfalbN, gvfalbnosh, gvfalbnoshE, gvfalbnoshS, gvfalbnoshW, gvfalbnoshN)[source]

Calculate upward shortwave radiation with vegetation effects.

Accounts for multiple reflections between ground, walls, and vegetation.

Returns:

Upward shortwave components for different directions

Return type:

tuple

solweig_gpu.solweig.Kvikt_veg(svf, svfveg, vikttot)[source]

Calculate shortwave weight factor accounting for vegetation.

solweig_gpu.solweig.shaded_or_sunlit(solar_altitude, solar_azimuth, patch_altitude, patch_azimuth, asvf)[source]

Determine if sky patches are shaded or sunlit.

Parameters:
  • solar_altitude (float) – Solar altitude angle

  • solar_azimuth (float) – Solar azimuth angle

  • patch_altitude (torch.Tensor) – Patch altitude angles

  • patch_azimuth (torch.Tensor) – Patch azimuth angles

  • asvf (torch.Tensor) – Anisotropic sky view factor

Returns:

Binary mask (1=sunlit, 0=shaded)

Return type:

torch.Tensor

solweig_gpu.solweig.Kside_veg_v2022a(radI, radD, radG, shadow, svfS, svfW, svfN, svfE, svfEveg, svfSveg, svfWveg, svfNveg, azimuth, altitude, psi, t, albedo, F_sh, KupE, KupS, KupW, KupN, cyl, lv, anisotropic_diffuse, diffsh, rows, cols, asvf, shmat, vegshmat, vbshvegshmat)[source]

Calculate shortwave radiation on vertical surfaces (walls) with vegetation effects.

Computes direct, diffuse, and reflected shortwave radiation on walls in the four cardinal directions, accounting for vegetation shading and ground reflections.

Parameters:
  • radI (float) – Direct, diffuse, and global radiation (W/m²)

  • radD (float) – Direct, diffuse, and global radiation (W/m²)

  • radG (float) – Direct, diffuse, and global radiation (W/m²)

  • shadow (torch.Tensor) – Shadow map

  • svfS (torch.Tensor) – Directional sky view factors

  • svfW (torch.Tensor) – Directional sky view factors

  • svfN (torch.Tensor) – Directional sky view factors

  • svfE (torch.Tensor) – Directional sky view factors

  • svf*veg (torch.Tensor) – Vegetation-obstructed SVFs

  • azimuth (float) – Solar angles (degrees)

  • altitude (float) – Solar angles (degrees)

  • psi (torch.Tensor) – Tilt angles

  • t (float) – Transmissivity factor

  • albedo (torch.Tensor) – Surface albedo

  • F_sh (torch.Tensor) – Form factor

  • KupE (torch.Tensor) – Upward shortwave per direction

  • KupS (torch.Tensor) – Upward shortwave per direction

  • KupW (torch.Tensor) – Upward shortwave per direction

  • KupN (torch.Tensor) – Upward shortwave per direction

  • cyl (torch.Tensor) – Cylindrical geometry factor

  • lv (float) – Leaf area index factor

  • anisotropic_diffuse (bool) – Use anisotropic diffuse model

  • diffsh (torch.Tensor) – Diffuse shadowing

  • rows (int) – Grid dimensions

  • cols (int) – Grid dimensions

  • asvf (torch.Tensor) – Anisotropic SVF

  • shmat (torch.Tensor) – Shadow matrices

  • vegshmat (torch.Tensor) – Shadow matrices

  • vbshvegshmat (torch.Tensor) – Shadow matrices

Returns:

(Keast, Ksouth, Kwest, Knorth, KsideI, KsideD, Kside) -

Shortwave radiation components for each direction

Return type:

tuple

solweig_gpu.solweig.sun_distance(jday)[source]

Calculate Earth-Sun distance correction factor for given day.

Parameters:

jday (torch.Tensor) – Julian day of year

Returns:

Distance correction factor (dimensionless)

Return type:

torch.Tensor

solweig_gpu.solweig.clearnessindex_2013b(zen, jday, Ta, RH, radG, location, P)[source]

Calculate atmospheric clearness index.

Parameters:
  • zen (torch.Tensor) – Solar zenith angle (radians)

  • jday (torch.Tensor) – Julian day

  • Ta (float) – Air temperature (°C)

  • RH (float) – Relative humidity (%)

  • radG (float) – Global radiation (W/m²)

  • location (dict) – Geographic location

  • P (float) – Atmospheric pressure (kPa)

Returns:

Clearness index (dimensionless, 0-1)

Return type:

torch.Tensor

solweig_gpu.solweig.diffusefraction(radG, altitude, Kt, Ta, RH)[source]

Calculate fraction of diffuse radiation from global radiation.

Uses empirical models to partition global radiation into direct and diffuse components.

Parameters:
  • radG (float) – Global horizontal radiation (W/m²)

  • altitude (torch.Tensor) – Solar altitude (degrees)

  • Kt (torch.Tensor) – Clearness index

  • Ta (float) – Air temperature (°C)

  • RH (float) – Relative humidity (%)

Returns:

(radD, radI) where:
  • radD: Diffuse radiation (W/m²)

  • radI: Direct beam radiation (W/m²)

Return type:

tuple

solweig_gpu.solweig.shadowingfunction_wallheight_13(a, azimuth, altitude, scale, walls, aspect)[source]

Calculate shadow patterns accounting for wall heights (method 1.3).

Determines which surfaces are in shadow cast by nearby walls based on solar angle, wall height, and wall orientation.

Returns:

(vegsh, sh, vbshvegsh, wallsh, wallsun, wallshve, facesh, facesun)

Return type:

tuple

solweig_gpu.solweig.shadowingfunction_wallheight_23(a, vegdem, vegdem2, azimuth, altitude, scale, amaxvalue, bush, walls, aspect)[source]

Calculate shadow patterns with vegetation and wall heights (method 2.3).

Extended shadow calculation including vegetation layers and building walls.

Returns:

Shadow components including vegetation effects

Return type:

tuple

solweig_gpu.solweig.Perez_v3(zen, azimuth, radD, radI, jday, patchchoice, patch_option)[source]

Calculate anisotropic diffuse radiation distribution using Perez model.

Implements the Perez all-weather sky model for anisotropic diffuse radiation, accounting for circumsolar brightening and horizon brightening.

Parameters:
  • zen (torch.Tensor) – Solar zenith angle (radians)

  • azimuth (torch.Tensor) – Solar azimuth (radians)

  • radD (float) – Diffuse radiation (W/m²)

  • radI (float) – Direct beam radiation (W/m²)

  • jday (torch.Tensor) – Julian day

  • patchchoice (int) – Patch selection

  • patch_option (int) – Sky discretization (144 or 2304)

Returns:

Patch-wise diffuse radiation distribution and anisotropic SVF

Return type:

tuple

Reference:

Perez et al. (1993). All-weather model for sky luminance distribution. Solar Energy, 50(3), 235-245.

solweig_gpu.solweig.model1(sky_patches, esky, Ta)[source]

Calculate longwave sky radiation using Model 1 (isotropic).

solweig_gpu.solweig.model2(sky_patches, esky, Ta)[source]

Calculate longwave sky radiation using Model 2 (simple anisotropic).

solweig_gpu.solweig.model3(sky_patches, esky, Ta)[source]

Calculate longwave sky radiation using Model 3 (advanced anisotropic).

solweig_gpu.solweig.define_patch_characteristics(solar_altitude, solar_azimuth, patch_altitude, patch_azimuth, steradian, asvf, shmat, vegshmat, vbshvegshmat, Lsky_down, Lsky_side, Lsky, Lup, Ta, Tgwall, ewall, rows, cols)[source]

Calculate longwave radiation from discretized sky hemisphere patches.

Computes downward and sideward longwave radiation by integrating contributions from individual sky patches, accounting for their position, solid angle, shadow state, and temperature.

Parameters:
Returns:

(Ldown, Lside, Lside_sky, Lside_veg, Lside_sh, Lside_sun,

Lside_ref, Least, Lwest, Lnorth, Lsouth) - Longwave components for downward, sideward (total and directional)

Return type:

tuple

Notes

  • Integrates over all sky patches using solid angle weighting

  • Accounts for patch visibility through shadow matrices

  • Distinguishes between sunlit and shaded patches

  • Computes directional components (E, S, W, N)

solweig_gpu.solweig.Lcyl_v2022a(esky, sky_patches, Ta, Tgwall, ewall, Lup, shmat, vegshmat, vbshvegshmat, solar_altitude, solar_azimuth, rows, cols, asvf)[source]

Calculate longwave radiation on cylindrical surface (human body model).

Computes longwave radiation received by a standing person from sky, ground, and wall surfaces, accounting for shadows and anisotropic effects.

Parameters:
  • esky (float) – Sky emissivity

  • sky_patches (torch.Tensor) – Sky hemisphere discretization

  • Ta (float) – Air temperature (°C)

  • Tgwall (torch.Tensor) – Wall/ground temperature (K)

  • ewall (float) – Wall emissivity

  • Lup (torch.Tensor) – Upward longwave radiation

  • shmat (torch.Tensor) – Shadow matrices

  • vegshmat (torch.Tensor) – Shadow matrices

  • vbshvegshmat (torch.Tensor) – Shadow matrices

  • solar_altitude (float) – Solar angles

  • solar_azimuth (float) – Solar angles

  • rows (int) – Grid dimensions

  • cols (int) – Grid dimensions

  • asvf (torch.Tensor) – Anisotropic SVF

Returns:

(Lsky, Lrefl) - Sky and reflected longwave components

Return type:

tuple

solweig_gpu.solweig.Lvikt_veg(svf, svfveg, svfaveg, vikttot)[source]

Calculate longwave radiation weight factors accounting for vegetation.

solweig_gpu.solweig.Lside_veg_v2022a(svfS, svfW, svfN, svfE, svfEveg, svfSveg, svfWveg, svfNveg, svfEaveg, svfSaveg, svfWaveg, svfNaveg, azimuth, altitude, Ta, Tw, SBC, ewall, Ldown, esky, t, F_sh, CI, LupE, LupS, LupW, LupN, anisotropic_longwave)[source]

Calculate longwave radiation on vertical surfaces (walls) with vegetation effects.

Computes longwave radiation received by walls in the four cardinal directions, accounting for sky emission, ground emission, wall-to-wall exchanges, and vegetation obstruction.

Parameters:
Returns:

(Ldown, Lside, Least, Lwest, Lnorth, Lsouth) - Longwave components

Return type:

tuple

solweig_gpu.solweig.Solweig_2022a_calc(i, dsm, scale, rows, cols, svf, svfN, svfW, svfE, svfS, svfveg, svfNveg, svfEveg, svfSveg, svfWveg, svfaveg, svfEaveg, svfSaveg, svfWaveg, svfNaveg, vegdem, vegdem2, albedo_b, absK, absL, ewall, Fside, Fup, Fcyl, altitude, azimuth, zen, jday, usevegdem, onlyglobal, buildings, location, psi, landcover, lc_grid, dectime, altmax, dirwalls, walls, cyl, elvis, Ta, RH, radG, radD, radI, P, amaxvalue, bush, Twater, TgK, Tstart, alb_grid, emis_grid, TgK_wall, Tstart_wall, TmaxLST, TmaxLST_wall, first, second, svfalfa, svfbuveg, firstdaytime, timeadd, timestepdec, Tgmap1, Tgmap1E, Tgmap1S, Tgmap1W, Tgmap1N, CI, TgOut1, diffsh, shmat, vegshmat, vbshvegshmat, anisotropic_sky, asvf, patch_option)[source]

Main SOLWEIG 2022a calculation kernel - integrates all radiation and temperature calculations.

This is the core GPU-accelerated function that computes: - Shortwave radiation (direct, diffuse, reflected) - Longwave radiation (sky, ground, wall emissions) - Surface energy balance - Ground and wall surface temperatures - Mean radiant temperature (Tmrt)

This function is called once per time step and performs the complete radiation budget calculation accounting for 3D urban geometry, vegetation, and surface-atmosphere interactions.

Parameters:
  • i (int) – Time step index

  • dsm (torch.Tensor) – Digital Surface Model

  • scale (float) – Grid resolution (pixels/meter)

  • rows (int) – Domain dimensions

  • cols (int) – Domain dimensions

  • svf* (torch.Tensor) – Sky view factors (multiple directional variants)

  • vegdem (torch.Tensor) – Vegetation layers

  • vegdem2 (torch.Tensor) – Vegetation layers

  • bush (torch.Tensor) – Vegetation layers

  • albedo_b (float) – Surface optical/thermal properties

  • absK (float) – Surface optical/thermal properties

  • absL (float) – Surface optical/thermal properties

  • ewall (float) – Surface optical/thermal properties

  • Fside (torch.Tensor) – Form factors for different geometries

  • Fup (torch.Tensor) – Form factors for different geometries

  • Fcyl (torch.Tensor) – Form factors for different geometries

  • altitude (torch.Tensor) – Solar geometry

  • azimuth (torch.Tensor) – Solar geometry

  • zen (torch.Tensor) – Solar geometry

  • jday (torch.Tensor) – Temporal parameters

  • dectime (torch.Tensor) – Temporal parameters

  • altmax (torch.Tensor) – Temporal parameters

  • usevegdem (bool) – Model configuration flags

  • onlyglobal (bool) – Model configuration flags

  • buildings (torch.Tensor) – Building footprint mask

  • location (dict) – Geographic coordinates

  • psi (torch.Tensor) – Tilt angles

  • landcover – Land cover classification

  • lc_grid – Land cover classification

  • dirwalls (torch.Tensor) – Wall geometry

  • walls (torch.Tensor) – Wall geometry

  • cyl (torch.Tensor) – Wall geometry

  • elvis (np.ndarray) – Elevation data

  • Ta (float) – Meteorological conditions (air temp, humidity, pressure)

  • RH (float) – Meteorological conditions (air temp, humidity, pressure)

  • P (float) – Meteorological conditions (air temp, humidity, pressure)

  • radG (float) – Incoming radiation components (global, diffuse, direct)

  • radD (float) – Incoming radiation components (global, diffuse, direct)

  • radI (float) – Incoming radiation components (global, diffuse, direct)

  • amaxvalue (float) – Maximum domain elevation

  • Twater (float) – Water surface temperature

  • TgK (torch.Tensor) – Temperature states

  • Tstart (torch.Tensor) – Temperature states

  • TgK_wall (torch.Tensor) – Temperature states

  • Tstart_wall (torch.Tensor) – Temperature states

  • TmaxLST (torch.Tensor) – Maximum temperatures

  • TmaxLST_wall (torch.Tensor) – Maximum temperatures

  • alb_grid (torch.Tensor) – Spatial albedo and emissivity

  • emis_grid (torch.Tensor) – Spatial albedo and emissivity

  • first (torch.Tensor) – Surface type classifications

  • second (torch.Tensor) – Surface type classifications

  • svfalfa (torch.Tensor) – Vegetation view factors

  • svfbuveg (torch.Tensor) – Vegetation view factors

  • firstdaytime (float) – Temporal parameters

  • timeadd (float) – Temporal parameters

  • timestepdec (float) – Temporal parameters

  • Tgmap1 (torch.Tensor) – Previous temperature maps

  • Tgmap1E (torch.Tensor) – Previous temperature maps

  • Tgmap1S (torch.Tensor) – Previous temperature maps

  • Tgmap1W (torch.Tensor) – Previous temperature maps

  • Tgmap1N (torch.Tensor) – Previous temperature maps

  • CI (torch.Tensor) – Clearness index and output temperature

  • TgOut1 (torch.Tensor) – Clearness index and output temperature

  • diffsh (torch.Tensor) – Shadow matrices

  • shmat (torch.Tensor) – Shadow matrices

  • vegshmat (torch.Tensor) – Shadow matrices

  • vbshvegshmat (torch.Tensor) – Shadow matrices

  • anisotropic_sky (bool) – Use anisotropic sky model

  • asvf (torch.Tensor) – Anisotropic SVF

  • patch_option (int) – Sky discretization option

Returns:

(KsideI, TgOut1, TgOut, radIout, radDout, Lside, Lsky_patch, CI_Tg, CI_TgG,

KsideD, dRad, Kside) - Comprehensive radiation and temperature outputs

Return type:

tuple

Notes

  • GPU-accelerated for performance

  • Most computationally intensive function in SOLWEIG

  • Implements surface energy balance with iteration

  • Accounts for multiple reflections and anisotropic effects

Solar Position Algorithm

solweig_gpu.sun_position.sun_position(time, location)[source]

Calculate solar position (zenith and azimuth) using SPA algorithm.

Implements the Solar Position Algorithm (SPA) as described in: Reda, I. and Andreas, A. (2004). Solar position algorithm for solar radiation applications. Solar Energy, 76(5), 577-589.

Parameters:
  • time (dict) – Time information with keys: - ‘year’ (int): Year - ‘month’ (int): Month (1-12) - ‘day’ (int): Day of month - ‘hour’ (int): Hour (0-23) - ‘min’ (int): Minute (0-59) - ‘sec’ (int): Second (0-59) - ‘UTC’ (float): UTC offset in hours (e.g., -5 for EST)

  • location (dict) – Geographic location with keys: - ‘latitude’ (float): Latitude in degrees (-90 to 90) - ‘longitude’ (float): Longitude in degrees (-180 to 180) - ‘altitude’ (float): Elevation above sea level in meters

Returns:

Solar position containing:
  • ’zenith’ (float): Solar zenith angle in degrees (0=directly overhead, 90=horizon)

  • ’azimuth’ (float): Solar azimuth in degrees (0=North, 90=East, 180=South, 270=West)

Return type:

dict

Notes

  • Accounts for atmospheric refraction

  • Accuracy: ~0.0003° for years 2000-6000

  • All angles in degrees unless otherwise specified

Example

>>> time = {'year': 2020, 'month': 7, 'day': 18, 'hour': 12, 'min': 0, 'sec': 0, 'UTC': -5}
>>> location = {'latitude': 30.27, 'longitude': -97.74, 'altitude': 0}
>>> sun = sun_position(time, location)
>>> print(f"Zenith: {sun['zenith']:.2f}°, Azimuth: {sun['azimuth']:.2f}°")
solweig_gpu.sun_position.julian_calculation(t_input)[source]

Calculate Julian day and related time parameters.

Parameters:

t_input (dict) – Time dictionary with year, month, day, hour, min, sec, UTC

Returns:

Julian day, century, ephemeris day/century/millennium

Return type:

dict

solweig_gpu.sun_position.earth_heliocentric_position_calculation(julian)[source]

Calculate Earth’s heliocentric position (longitude, latitude, radius).

Parameters:

julian (dict) – Julian day parameters

Returns:

Earth heliocentric position (longitude, latitude, radius in AU)

Return type:

dict

solweig_gpu.sun_position.sun_geocentric_position_calculation(earth_heliocentric_position)[source]

Calculate geocentric sun position from Earth heliocentric position. SPA Step 3.

solweig_gpu.sun_position.nutation_calculation(julian)[source]

Calculate nutation in longitude and obliquity.

Parameters:

julian (dict) – Julian parameters

Returns:

Nutation in longitude and obliquity (degrees)

Return type:

dict

solweig_gpu.sun_position.true_obliquity_calculation(julian, nutation)[source]

Calculate true obliquity of the ecliptic. SPA Step 5.

solweig_gpu.sun_position.abberation_correction_calculation(earth_heliocentric_position)[source]

Calculate aberration correction. SPA Step 6.

solweig_gpu.sun_position.apparent_sun_longitude_calculation(sun_geocentric_position, nutation, aberration_correction)[source]

Calculate apparent sun longitude. SPA Step 7.

solweig_gpu.sun_position.apparent_stime_at_greenwich_calculation(julian, nutation, true_obliquity)[source]

Calculate apparent sidereal time at Greenwich. SPA Step 8.

solweig_gpu.sun_position.sun_rigth_ascension_calculation(apparent_sun_longitude, true_obliquity, sun_geocentric_position)[source]

Calculate sun right ascension. SPA Step 9.

solweig_gpu.sun_position.sun_geocentric_declination_calculation(apparent_sun_longitude, true_obliquity, sun_geocentric_position)[source]

Calculate geocentric sun declination. SPA Step 10.

solweig_gpu.sun_position.observer_local_hour_calculation(apparent_stime_at_greenwich, location, sun_rigth_ascension)[source]

Calculate observer local hour angle. SPA Step 11.

solweig_gpu.sun_position.topocentric_sun_position_calculate(earth_heliocentric_position, location, observer_local_hour, sun_rigth_ascension, sun_geocentric_declination)[source]

Calculate topocentric sun position. SPA Step 12.

solweig_gpu.sun_position.topocentric_local_hour_calculate(observer_local_hour, topocentric_sun_position)[source]

Calculate topocentric local hour angle. SPA Step 13.

solweig_gpu.sun_position.sun_topocentric_zenith_angle_calculate(location, topocentric_sun_position, topocentric_local_hour)[source]

Calculate topocentric zenith and azimuth angles with atmospheric refraction. SPA Step 14.

solweig_gpu.sun_position.set_to_range(var, min_interval, max_interval)[source]

Normalize angle to specified range.

Parameters:
  • var – Angle value

  • min_interval – Minimum value (typically 0)

  • max_interval – Maximum value (typically 360)

Returns:

Normalized angle in [min_interval, max_interval)

solweig_gpu.sun_position.Solweig_2015a_metdata_noload(inputdata, location, UTC)[source]

Process meteorological data and calculate solar geometry for each time step.

Computes solar position (altitude, azimuth) for all hours in the met data and organizes the data for SOLWEIG calculations.

Parameters:
  • inputdata (np.ndarray) – Meteorological data array

  • location (dict) – Geographic location (latitude, longitude, altitude)

  • UTC (float) – UTC offset in hours

Returns:

(Met, altitude, azimuth, zen, jday, I0, CI, Twater, TgK, Tstart,

TgK_wall, Tstart_wall, firstdaytime, timeadd, timestepdec) containing processed meteorological forcing and solar geometry

Return type:

tuple

Notes

  • Calculates solar position for every time step

  • Prepares data for SOLWEIG radiation calculations

  • Handles multiple time steps efficiently

Shadow and Sky View Factor

solweig_gpu.shadow.load_raster_to_tensor(dem_path, device=torch.device)[source]
solweig_gpu.shadow.ensure_tensor(x, device=None)[source]

Convert input to PyTorch tensor on specified device.

Parameters:
  • x – Input data (can be numpy array, list, or torch tensor)

  • device (torch.device, optional) – Target device. Auto-detects GPU if available.

Returns:

Input converted to tensor on specified device

Return type:

torch.Tensor

solweig_gpu.shadow.tensor_to_numpy(x)[source]

Move GPU/CPU torch tensor to CPU NumPy array before writing.

solweig_gpu.shadow.save_raster_like_gdal(gdal_template, output_path, array)[source]

Save a 2D array as GeoTIFF using geotransform/projection from the input DSM raster.

solweig_gpu.shadow.save_svf_zip_npz_outputs(output_dir, gdal_dsm, svf, svfE, svfS, svfW, svfN, svfveg, svfEveg, svfSveg, svfWveg, svfNveg, svfaveg, svfEaveg, svfSaveg, svfWaveg, svfNaveg, shmat, vegshmat, vbshvegshmat, svftotal, number=None)[source]
  • svfs.zip containing SVF GeoTIFFs

  • shadowmats.npz containing shadow matrices

  • SkyViewFactor.tif or SkyViewFactor_<number>.tif

solweig_gpu.shadow.shadow(amaxvalue, a, vegdem, vegdem2, bush, azimuth, altitude, scale)[source]

Calculate shadow patterns from buildings and vegetation using GPU-accelerated ray tracing.

This function performs GPU-accelerated shadow calculations by tracing sun rays across the Digital Surface Model (DSM) accounting for buildings and vegetation.

Parameters:
  • amaxvalue (torch.Tensor) – Maximum elevation value in the domain

  • a (torch.Tensor) – Digital Surface Model (DSM) array

  • vegdem (torch.Tensor) – Vegetation canopy DSM

  • vegdem2 (torch.Tensor) – Vegetation trunk zone DSM

  • bush (torch.Tensor) – Bush/shrub layer DSM

  • azimuth (float) – Solar azimuth angle (degrees, 0=North, clockwise)

  • altitude (float) – Solar altitude angle (degrees above horizon)

  • scale (float) – Grid resolution in pixels per meter

Returns:

(sh, vegsh, vbshvegsh) where:
  • sh: Shadow map (0=shadow, 1=sunlit)

  • vegsh: Vegetation shadow influence

  • vbshvegsh: Combined vegetation and building shadow

Return type:

tuple

Notes

  • Automatically uses GPU if available, otherwise CPU

  • Implements anisotropic shadow casting

  • Accounts for vegetation transmittance

solweig_gpu.shadow.annulus_weight(altitude, aziinterval, device=None)[source]

Calculate annulus weights for sky view factor computation.

Computes weights for different altitude bands used in SVF calculation based on the solid angle subtended by each annular ring.

Parameters:
  • altitude (float or torch.Tensor) – Solar altitude angle (degrees)

  • aziinterval (int) – Azimuthal interval for discretization

  • device (torch.device, optional) – PyTorch device. Auto-detects if None.

Returns:

Array of annulus weights

Return type:

torch.Tensor

solweig_gpu.shadow.create_patches(patch_option)[source]

Create patch configuration for sky hemisphere discretization.

Generates the angular resolution and patch geometry for sky view factor calculations by dividing the sky hemisphere into discrete patches.

Parameters:

patch_option (int) – Number of patches (144 or 2304) - 144: Coarser resolution (faster) - 2304: Finer resolution (more accurate)

Returns:

Configuration containing:
  • ’azimuthinterval’: Number of azimuth bins

  • ’altitudeinterval’: Number of altitude bins

  • ’patchnorm’: Normalization factor

Return type:

dict

Raises:

ValueError – If patch_option is not 144 or 2304

solweig_gpu.shadow.svf_calculator(patch_option, amaxvalue=None, a=None, vegdem=None, vegdem2=None, bush=None, scale=None, save_rasters=False, building_dsm_path=None, tree_path=None, dem_path=None, output_dir=None, number=None, gdal_dsm=None)[source]

Calculate Sky View Factor (SVF) using GPU-accelerated hemisphere sampling.

SVF represents the portion of visible sky from each point, accounting for obstructions from buildings and vegetation. Directional SVFs are also computed for cardinal directions (N, E, S, W).

Parameters:
  • patch_option (int) – Sky discretization option (144 or 2304 patches)

  • amaxvalue (torch.Tensor) – Maximum elevation in domain

  • a (torch.Tensor) – Digital Surface Model

  • vegdem (torch.Tensor) – Vegetation canopy DSM

  • vegdem2 (torch.Tensor) – Vegetation trunk zone DSM

  • bush (torch.Tensor) – Bush layer DSM

  • scale (float) – Grid resolution (pixels per meter)

Returns:

(svf, svfE, svfS, svfW, svfN, svfveg, svfEveg, svfSveg, svfWveg, svfNveg,

svfaveg, svfEaveg, svfSaveg, svfWaveg, svfNaveg) where:

  • svf: Total sky view factor [0-1]

  • svfE/S/W/N: Directional SVFs for East/South/West/North

  • svf*veg: Vegetation-obstructed SVFs

  • svf*aveg: Vegetation-adjusted SVFs

Return type:

tuple

Notes

  • Uses GPU if available for fast computation

  • Higher patch_option gives more accurate but slower results

  • Directional SVFs useful for anisotropic radiation modeling

UTCI Calculations

solweig_gpu.calculate_utci.utci_polynomial(D_Tmrt, Ta, va, Pa)[source]

Calculate UTCI using 6th order polynomial approximation.

This function implements the UTCI polynomial approximation formula as defined in the UTCI documentation.

Parameters:
Returns:

UTCI approximation value (°C)

Return type:

torch.Tensor

References

Bröde P, Fiala D, Błażejczyk K, et al. (2012). Deriving the operational procedure for the Universal Thermal Climate Index (UTCI). Int J Biometeorol 56:481-494.

solweig_gpu.calculate_utci.utci_calculator(Ta, RH, Tmrt, va10m)[source]

Calculate Universal Thermal Climate Index (UTCI) for given meteorological conditions.

UTCI is an international standard for assessing thermal comfort in outdoor environments. It combines air temperature, mean radiant temperature, wind speed, and humidity into a single index value that represents the “feels like” temperature.

Parameters:
  • Ta (torch.Tensor) – Air temperature (°C). Can be scalar or multi-dimensional array.

  • RH (torch.Tensor) – Relative humidity (%). Range: 0-100.

  • Tmrt (torch.Tensor) – Mean radiant temperature (°C). Accounts for solar and thermal radiation.

  • va10m (torch.Tensor) – Wind speed at 10m height (m/s).

Returns:

UTCI value (°C). Same shape as input tensors.

Returns -999 for invalid input values (Ta, RH, va10m, or Tmrt <= -999).

Return type:

torch.Tensor

Notes

  • UTCI interpretation: * < 9°C: Strong cold stress * 9-26°C: Comfortable * 26-32°C: Moderate heat stress * > 32°C: Strong heat stress

  • All inputs must be torch tensors of the same shape

  • Invalid/missing data should be marked as -999

Examples

>>> import torch
>>> ta = torch.tensor([25.0])
>>> rh = torch.tensor([50.0])
>>> tmrt = torch.tensor([30.0])
>>> wind = torch.tensor([1.0])
>>> utci = utci_calculator(ta, rh, tmrt, wind)
>>> print(f"UTCI: {utci.item():.1f}°C")

References

Bröde P, Fiala D, Błażejczyk K, et al. (2012). Deriving the operational procedure for the Universal Thermal Climate Index (UTCI). Int J Biometeorol 56:481-494.

UTCI Processing

Wall Geometry

solweig_gpu.walls_aspect.findwalls(dem_array, walllimit)[source]

Identify walls in a Digital Surface Model (DSM) based on height threshold.

Walls are detected by comparing each cell to its immediate neighbors. A wall exists where the elevation difference exceeds the threshold.

Parameters:
  • dem_array (np.ndarray) – 2D array of elevation values (DSM)

  • walllimit (float) – Minimum height difference (m) to be considered a wall

Returns:

2D array of wall heights. Zero where no wall exists.

Return type:

np.ndarray

solweig_gpu.walls_aspect.cart2pol(x, y, units='deg')[source]

Convert Cartesian coordinates to polar coordinates.

Parameters:
  • x (np.ndarray or float) – X coordinate(s)

  • y (np.ndarray or float) – Y coordinate(s)

  • units (str) – Output angle units (‘deg’ or ‘rad’). Default: ‘deg’

Returns:

(theta, radius) where theta is angle and radius is distance

Return type:

tuple

solweig_gpu.walls_aspect.get_ders(dsm, scale)[source]

Calculate slope derivatives (aspect and gradient) from DSM.

Parameters:
  • dsm (np.ndarray) – Digital Surface Model array

  • scale (float) – Pixel size in meters

Returns:

(aspect, gradient) where:
  • aspect: slope orientation in radians

  • gradient: slope magnitude

Return type:

tuple

solweig_gpu.walls_aspect.filter1Goodwin_as_aspect_v3(walls, scale, a)[source]

Calculate wall aspect (orientation) using directional filtering.

This function determines the orientation of walls by rotating a directional filter and finding the direction with maximum wall presence.

Parameters:
  • walls (np.ndarray) – Binary array indicating wall locations

  • scale (float) – Pixel size in meters

  • a (np.ndarray) – Aspect array from DSM derivatives

Returns:

Wall aspect in degrees [0-360], where 0=North, 90=East, 180=South, 270=West

Return type:

np.ndarray

solweig_gpu.walls_aspect.process_file_parallel(args)[source]

Process a single DEM tile to calculate walls and aspect (parallel worker function).

This function is designed to be called by parallel processing workers.

Parameters:

args (tuple) – (filename, dem_folder_path, wall_output_path, aspect_output_path)

Returns:

Filename of processed tile

Return type:

str

solweig_gpu.walls_aspect.run_parallel_processing(dem_folder_path, wall_output_path, aspect_output_path)[source]

Process all DEM tiles in parallel to calculate walls and aspects.

This is the main entry point for wall and aspect calculation. It uses multiprocessing to process multiple tiles simultaneously for efficiency.

Parameters:
  • dem_folder_path (str) – Path to folder containing DEM tile GeoTIFFs

  • wall_output_path (str) – Output path for wall height rasters

  • aspect_output_path (str) – Output path for wall aspect rasters

Notes

  • Uses multiple CPU cores for parallel processing

  • On Windows, uses fewer workers (max 8 or half of CPU cores) to avoid file locking issues

  • Progress bar shows processing status

  • Creates output directories if they don’t exist

  • Skips tiles that cannot be opened or have invalid data

Command-Line Interface

solweig_gpu.cli.str2bool(v)[source]

Convert string to boolean for argparse.

Parameters:

v – Input value (str or bool)

Returns:

Converted boolean value

Return type:

bool

Raises:

argparse.ArgumentTypeError – If value cannot be converted to boolean

solweig_gpu.cli.main()[source]

Command-line interface for SOLWEIG-GPU thermal comfort modeling.

Parses command-line arguments and runs the thermal_comfort function. This is the entry point for the ‘thermal_comfort’ console script.

Usage:

thermal_comfort –base_path /path/to/input –date 2020-08-13 [options]

For full help:

thermal_comfort –help

Surface Properties

solweig_gpu.Tgmaps_v1.Tgmaps_v1(lc_grid, lc_class)[source]

Populate surface property grids from land cover classification.

Maps land cover classes to their corresponding thermal and optical properties for ground temperature wave calculations.

Parameters:
  • lc_grid (np.ndarray) – Land cover classification grid

  • lc_class (np.ndarray) – Land cover lookup table with columns: [class_id, albedo, emissivity, TgK, Tstart, TmaxLST]

Returns:

(TgK, Tstart, alb_grid, emis_grid, TgK_wall, Tstart_wall,

TmaxLST, TmaxLST_wall) - Surface property grids and wall parameters

Return type:

tuple