API Reference

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

Main Entry Point

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, 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, save_tmrt=True, save_svf=False, save_kup=False, save_kdown=False, save_lup=False, save_ldown=False, save_shadow=False)[source]

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

This function orchestrates the complete workflow: 1. Preprocesses input rasters (tiling, validation) 2. Processes meteorological data (ERA5, WRF, or custom) 3. Calculates wall heights and aspects (parallel CPU) 4. Computes shadows, radiation, and SVF (GPU-accelerated) 5. Calculates UTCI thermal comfort index 6. Saves outputs as georeferenced rasters

Parameters:
  • base_path (str) – Base directory for output_folder/ and processed_inputs/; also used to resolve relative raster paths. For outputs elsewhere, set this to the desired output directory and pass complete paths for the raster arguments.

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

  • building_dsm_filename (str) – Building+terrain DSM path or filename (relative to base_path). Default: ‘Building_DSM.tif’. Can be a complete path if rasters live elsewhere.

  • dem_filename (str) – DEM path or filename (relative to base_path). Default: ‘DEM.tif’

  • trees_filename (str) – Vegetation DSM path or filename (relative to base_path). Default: ‘Trees.tif’

  • landcover_filename (str, optional) – Land cover raster path or filename. Default: None

  • tile_size (int) – Tile size in pixels. Default: 3600. Adjust based on GPU RAM.

  • overlap (int) – Overlap between tiles in pixels. Default: 20. Used for shadow transfer.

  • use_own_met (bool) – Use custom meteorological file. Default: True

  • start_time (str, optional) – Start datetime ‘YYYY-MM-DD HH:MM:SS’ (UTC for ERA5/WRF)

  • end_time (str, optional) – End datetime ‘YYYY-MM-DD HH:MM:SS’ (UTC for ERA5/WRF)

  • data_source_type (str, optional) – ‘ERA5’ or ‘wrfout’ if not using own met file

  • data_folder (str, optional) – Folder containing ERA5/WRF NetCDF files

  • own_met_file (str, optional) – Path to custom meteorological text file

  • save_tmrt (bool) – Save mean radiant temperature output. Default: True

  • save_svf (bool) – Save sky view factor output. Default: False

  • save_kup (bool) – Save upward shortwave radiation. Default: False

  • save_kdown (bool) – Save downward shortwave radiation. Default: False

  • save_lup (bool) – Save upward longwave radiation. Default: False

  • save_ldown (bool) – Save downward longwave radiation. Default: False

  • save_shadow (bool) – Save shadow maps. Default: False

Returns:

Outputs are saved to {base_path}/output_folder/ directory

Return type:

None

Output Structure:
  • {base_path}/processed_inputs/ - All preprocessing files - Building_DSM/ - Preprocessing tiles - DEM/ - Preprocessing tiles - Trees/ - Preprocessing tiles - metfiles/ - Meteorological files - walls/ - Wall height rasters - aspect/ - Wall aspect rasters - Outfile.nc - Processed NetCDF (if using ERA5/WRF)

  • output_folder/{tile_key}/ - One folder per tile (tile_key e.g. “0_0”, “1000_0”) - UTCI_{tile_key}.tif - Universal Thermal Climate Index (always saved) - TMRT_{tile_key}.tif - Mean radiant temperature (if save_tmrt=True) - SVF_{tile_key}.tif - Sky view factor (if save_svf=True) - Kup_{tile_key}.tif - Upward shortwave (if save_kup=True) - Kdown_{tile_key}.tif - Downward shortwave (if save_kdown=True) - Lup_{tile_key}.tif - Upward longwave (if save_lup=True) - Ldown_{tile_key}.tif - Downward longwave (if save_ldown=True) - Shadow_{tile_key}.tif - Shadow maps (if save_shadow=True)

Notes

  • Automatically uses GPU if available, falls back to CPU

  • Processes tiles in parallel for large domains

  • UTC to local time conversion handled automatically

  • Multi-band rasters: one band per hour

Example

>>> from solweig_gpu import thermal_comfort
>>> thermal_comfort(
...     base_path='/path/to/input',
...     selected_date_str='2020-08-13',
...     tile_size=1000,
...     overlap=100,
...     use_own_met=True,
...     own_met_file='/path/to/met.txt'
... )
Raises:
  • ValueError – If input rasters have mismatched dimensions, CRS, or pixel sizes

  • FileNotFoundError – If the required input files are missing

Parameters:

landcover_filename (str | None)

Data Preprocessing

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.create_tiles(infile, tilesize, overlap, tile_type, preprocess_dir)[source]

Tile a raster file into smaller chunks.

Parameters:
  • infile (str) – Path to input raster.

  • tilesize (int) – Size of each tile in pixels.

  • overlap (int) – Number of pixels to overlap between tiles.

  • tile_type (str) – Label to use for naming output tiles.

  • preprocess_dir (str) – Directory to save tiles in the pre_processing_outputs folder.

Raises:
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_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)[source]

Minimal-edits, curvilinear-safe version of your function.

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, 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)[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.

  • 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 (pre_processing_outputs folder).

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.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.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, a, vegdem, vegdem2, bush, scale)[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

solweig_gpu.utci_process.load_raster_to_tensor(dem_path)[source]

Load a GeoTIFF raster file into a PyTorch tensor.

Parameters:

dem_path (str) – Path to GeoTIFF file

Returns:

(tensor, dataset) where:
  • tensor: PyTorch tensor on GPU/CPU with raster data

  • dataset: GDAL dataset object (for accessing metadata)

Return type:

tuple

solweig_gpu.utci_process.extract_key(filename, is_metfile=False)[source]

Extract numerical key from filename for tile matching.

Parameters:
  • filename (str) – Filename to parse

  • is_metfile (bool) – True if filename is a metfile, False if raster tile

Returns:

Extracted key (e.g., “0_0” from “Building_DSM_0_0.tif”)

Return type:

str

solweig_gpu.utci_process.get_matching_files(directory, extension)[source]

Get sorted list of files with given extension from directory.

Parameters:
  • directory (str) – Directory path to search

  • extension (str) – File extension to filter (e.g., ‘.tif’)

Returns:

Sorted list of filenames matching extension

Return type:

list

solweig_gpu.utci_process.map_files_by_key(directory, extension, is_metfile=False)[source]

Create mapping of tile keys to filenames.

Groups files by their tile coordinates (e.g., “0_0”, “1000_0”) to match corresponding raster tiles with their meteorological files.

Parameters:
  • directory (str) – Directory containing files

  • extension (str) – File extension to filter

  • is_metfile (bool) – True if files are metfiles

Returns:

Dictionary mapping keys to filenames

Return type:

dict

solweig_gpu.utci_process.extract_number_from_filename(filename)[source]

Extract tile number from Building_DSM filename.

Parameters:

filename (str) – Filename in format “Building_DSM_X_Y.tif”

Returns:

Extracted number portion (e.g., “0_0”)

Return type:

str

solweig_gpu.utci_process.compute_utci(building_dsm_path, tree_path, dem_path, walls_path, aspect_path, landcover_path, met_file, output_path, number, selected_date_str, save_tmrt=False, save_svf=False, save_kup=False, save_kdown=False, save_lup=False, save_ldown=False, save_shadow=False)[source]

Compute UTCI and related thermal comfort outputs for a single tile.

This is the main computation function that integrates shadow modeling, radiation calculations, and UTCI computation for urban microclimate analysis.

Parameters:
  • building_dsm_path (str) – Path to Building DSM raster

  • tree_path (str) – Path to tree/vegetation DSM raster

  • dem_path (str) – Path to Digital Elevation Model raster

  • walls_path (str) – Path to wall height raster

  • aspect_path (str) – Path to wall aspect raster

  • landcover_path (str) – Path to land cover raster (can be None)

  • met_file (str) – Path to meteorological forcing file

  • output_path (str) – Directory for saving output rasters

  • number (str) – Tile identifier (e.g., “0_0”)

  • selected_date_str (str) – Date string (YYYY-MM-DD)

  • save_tmrt (bool) – Save mean radiant temperature output

  • save_svf (bool) – Save sky view factor output

  • save_kup (bool) – Save upward shortwave radiation

  • save_kdown (bool) – Save downward shortwave radiation

  • save_lup (bool) – Save upward longwave radiation

  • save_ldown (bool) – Save downward longwave radiation

  • save_shadow (bool) – Save shadow maps

Returns:

Outputs are saved as GeoTIFF files in output_path

Return type:

None

Notes

  • Automatically uses GPU if available

  • Outputs are multi-band rasters (one band per hour)

  • UTCI is always computed and saved

  • Other outputs are optional based on save_* flags

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