OccPy tutorial notebook for Terrestrial Laser Scanning (TLS) data¶
This notebook gives a brief overview over TLS occlusion mapping using OccPy.
The data used for this analysis were acquired using a Riegl VZ400i laser scanner at the Rameren forest close to the WSL in Birmensdorf, Switzerland. The forest plot is characterized as a mixed temperate forest and the data was acquired under leaf-on conditions. The data has been heavily filtered to reduce storage needs and reduce processing time. The tutorial data is the same as used for the manuscript currently under revision in RSE and available as pre-print here: (TODO!)
First, we download the test data and configure paths
import json
import os
import shutil
from pathlib import Path
import pooch
from occpy import OccPy
RIEGL RDBlib is not available RIEGL RiVlib is not available Jupyter environment detected. Enabling Open3D WebVisualizer. [Open3D INFO] WebRTC GUI backend enabled. [Open3D INFO] WebRTCWindowSystem: HTTP handshake server disabled.
# Download test data once to cache and mirror it into the repository for stable relative paths
repo_root = Path('..', '..').resolve()
data_notebooks = repo_root / 'data_notebooks'
tls_data_dir = data_notebooks / 'TLS_demo'
data_notebooks.mkdir(parents=True, exist_ok=True)
p = pooch.create(
path=pooch.os_cache('occpy_test_data'),
base_url='https://zenodo.org/records/21281997/files/',
registry={'TLS_demo.zip': 'md5:ad0fda9108224b9335715cdc517a8f12'},
)
p.fetch('TLS_demo.zip', processor=pooch.Unzip(members=['TLS_demo']), progressbar=True)
cache_data_dir = Path(p.path) / 'TLS_demo.zip.unzip' / 'TLS_demo'
if not tls_data_dir.exists():
shutil.copytree(cache_data_dir, tls_data_dir)
print(f'Notebook data folder: {tls_data_dir}')
config_file = str(repo_root / 'config' / 'settings_TLS_tutorial.JSON')
Notebook data folder: /home/wcherlet/occlusion/OccPy/data_notebooks/TLS_demo
OccPy configurations are saved in JSON files.
There are a few minimal requirements for a run:
- laz_in: input laz file or directory containing laz files. If given multiple las files, will assume multi-position TLS. If given single las file, will assume single-position TLS unless is_mobile is set.
- plot_dim: grid for occlusion mapping: [minX, minY, minZ, maxX, maxY, maxZ]
- vox_dim: voxel size - currently this applies to x, y, and z dimension. Non-cubic voxels are on the list of features to be added
Optional arguments:
- is_mobile: whether the acquisition is mobile (MLS/ULS) or static (TLS) (default: False)
- single_return: whether the data is single return or multi return data (default: False)
- out_dir: output directory (default: ./output)
- verbose: set logging level (default: False)
- debug: set logging level (default: False)
- lower_threshold: lower threshold above ground to exclude from occlusion mapping in voxels (default: 0)
- points_per_iter: number of points read in from laz file in each iteration (default: 10000000)
- delimiter: csv delimiter for scan position file (default: ",")
- root_folder: if given, will assume other paths are relative to this root folder and will prepend it to the paths (default: None)
- str_idxs_ScanPosID: string indices of where the scan position identifier is written in the laz file name. If not given, will use file name as ID (without extension) (default: None)
- output_voxels: whether to export .ply voxel grids (large files, slow) (default: False)
Additionally, we use the config file to save paths to other files, such as the positions file, DSM and DTM.
# Load config and resolve all relative paths once for downstream plotting/normalization calls
with open(config_file, 'r') as file:
config = json.load(file)
config
{'root_folder': '../..',
'laz_in': 'data_notebooks/TLS_demo/LAZ/',
'out_dir': 'output/TLS',
'vox_dim': 0.1,
'lower_threshold': 1,
'points_per_iter': 1000000,
'plot_dim': [2676515, 1246063, 545, 2676525, 1246113, 590],
'output_voxels': False,
'single_return': False,
'is_mobile': False,
'str_idxs_ScanPosID': [0, 10],
'debug': False,
'verbose': True,
'tif_in': {'DTM': 'data_notebooks/TLS_demo/Grids/Ramerenwald_DTM_20250305.tif',
'DSM': 'data_notebooks/TLS_demo/Grids/Ramerenwald_DSM_20250305.tif'},
'ScanPos': 'data_notebooks/TLS_demo/ScanPos/ScanPositions.txt'}
Running OccPy¶
First step is to create an OccPy object with the config file.
test = OccPy(config=config)
2026-08-31 11:49:08,349 - INFO - Prepending root folder /home/wcherlet/occlusion/OccPy to input and output paths.
INFO: optional arguments: ['out_dir', 'is_mobile', 'output_voxels', 'verbose', 'debug', 'lower_threshold', 'points_per_iter', 'delimiter', 'root_folder', 'single_return', 'str_idxs_ScanPosID', 'cleanup_incomplete_pulses', 'move_senspos_to_collinearity', 'check_returns_all_files']
Then, define the sensor positions.
The linking between IDs in the sensor position file and the LAZ files can be controlled with str_idx_ScanPosID in the config. If this is not given, we use the scan filename (w/o extension) to try to link.
test.define_sensor_pos(path2file=config['ScanPos'], # Path to csv file with scanner positions
delimiter=',', # Delimiter used in the csv file
hdr_scanpos_id='#Name', # Header for the scan position ID [expected a substring or integer that should be linkable to the laz file - substring or number should be in the laz file name]
hdr_x='X', # Header for the x coordinate
hdr_y='Y', # Header for the y coordinate
hdr_z='Z', # Header for the z coordinate
sens_pos_id_offset=0 # very specific case, where there is an offset between scan position id in the file name and on the ID of the file. will only work if scanpos names are integer
)
2026-08-31 11:49:08,431 - INFO - Provided path to sensor position file data_notebooks/TLS_demo/ScanPos/ScanPositions.txt is not absolute. Resolving relative to root folder /home/wcherlet/occlusion/OccPy. 2026-08-31 11:49:08,432 - INFO - Defining sensor positions for static acquisition.
Now we can start the raytracing and save the outputs.
Note: An alternative approach is shown in TLS_notebook_individualLAZ.ipynb. There OccPy is run separately for each scan, which could be useful for insights into individual scan contribution to the overall occlusion.
import time
tic = time.time()
test.do_raytracing()
toc = time.time()
print(f"Raytracing took {toc - tic:.2f} seconds.")
2026-08-31 11:49:08,440 - INFO - Linked 5 TLS LAS/LAZ files to scan positions. 2026-08-31 11:49:08,441 - INFO - Probing the return mode on ScanPos033_sort_filtered.laz only and applying it to all 5 files. Set check_returns_all_files=True to probe every file. 2026-08-31 11:49:08,442 - INFO - ScanPos033_sort_filtered.laz: return mode multi (from header) -- number_of_points_by_return reports 1239414 echoes beyond return 1 (max return index 5) 2026-08-31 11:49:08,442 - INFO - Ray tracing 5 scan(s). 2026-08-31 11:49:08,442 - INFO - ===== Processing ScanPos033_sort_filtered.laz ===== [1/5] ScanPos033_sort_filtered.laz: 100%|██████████| 4.62M/4.62M [00:10<00:00, 426kpts/s] 2026-08-31 11:49:19,424 - INFO - Reading and tracing ScanPos033_sort_filtered.laz: 10.98 seconds 2026-08-31 11:49:19,426 - INFO - ScanPos033_sort_filtered.laz: ray traced 5 chunk(s) in 4.00 seconds. 2026-08-31 11:49:19,427 - INFO - ===== Processing ScanPos035_sort_filtered.laz ===== [2/5] ScanPos035_sort_filtered.laz: 100%|██████████| 4.71M/4.71M [00:10<00:00, 429kpts/s] 2026-08-31 11:49:30,424 - INFO - Reading and tracing ScanPos035_sort_filtered.laz: 11.00 seconds 2026-08-31 11:49:30,582 - INFO - ScanPos035_sort_filtered.laz: ray traced 5 chunk(s) in 3.21 seconds. 2026-08-31 11:49:30,584 - INFO - ===== Processing ScanPos045_sort_filtered.laz ===== [3/5] ScanPos045_sort_filtered.laz: 100%|██████████| 5.39M/5.39M [00:13<00:00, 394kpts/s] 2026-08-31 11:49:44,381 - INFO - Reading and tracing ScanPos045_sort_filtered.laz: 13.80 seconds 2026-08-31 11:49:44,383 - INFO - ScanPos045_sort_filtered.laz: ray traced 6 chunk(s) in 4.51 seconds. 2026-08-31 11:49:44,384 - INFO - ===== Processing ScanPos047_sort_filtered.laz ===== [4/5] ScanPos047_sort_filtered.laz: 100%|██████████| 4.83M/4.83M [00:12<00:00, 385kpts/s] 2026-08-31 11:49:56,946 - INFO - Reading and tracing ScanPos047_sort_filtered.laz: 12.56 seconds 2026-08-31 11:49:57,117 - INFO - ScanPos047_sort_filtered.laz: ray traced 5 chunk(s) in 4.33 seconds. 2026-08-31 11:49:57,118 - INFO - ===== Processing ScanPos061_sort_filtered.laz ===== [5/5] ScanPos061_sort_filtered.laz: 100%|██████████| 4.98M/4.98M [00:12<00:00, 386kpts/s] 2026-08-31 11:50:10,038 - INFO - Reading and tracing ScanPos061_sort_filtered.laz: 12.92 seconds 2026-08-31 11:50:10,204 - INFO - ScanPos061_sort_filtered.laz: ray traced 5 chunk(s) in 4.49 seconds. 2026-08-31 11:50:10,206 - INFO - Reading and ray tracing all input: 61.76 seconds 2026-08-31 11:50:10,208 - WARNING - 5,291 returns were missed during traversal: they did not fall in a voxel crossed by their own pulse, which means the returns are not collinear with the sensor position. Setting move_senspos_to_collinearity=True can recover them, with the caveats noted in the config documentation. 2026-08-31 11:50:10,209 - INFO - Extracting Nhit
==================== Occlusion mapping report ==================== Pulses traversed 14,220,463 of 15,172,862 (93.7%) Pulses missing the grid 952,399 (6.3%) Returns registered 7,468,005 Returns outside the grid 12,041,054 Returns missed 5,291 Ray tracing time 61.77 s ==================================================================
2026-08-31 11:50:10,937 - INFO - Elapsed Time: 0.73 seconds 2026-08-31 11:50:10,940 - INFO - Extracting Nocc 2026-08-31 11:50:11,672 - INFO - Elapsed Time: 0.73 seconds 2026-08-31 11:50:11,675 - INFO - Extracting Nmiss 2026-08-31 11:50:12,320 - INFO - Elapsed Time: 0.64 seconds 2026-08-31 11:50:12,322 - INFO - Saving Occlusion Outputs As .npy 2026-08-31 11:50:12,417 - INFO - Elapsed Time: 0.09 seconds 2026-08-31 11:50:12,418 - INFO - Classify Grid 2026-08-31 11:50:12,710 - INFO - Elapsed Time: 0.2904326915740967 seconds 2026-08-31 11:50:12,711 - INFO - Wrote run summary to /home/wcherlet/occlusion/OccPy/output/TLS/run_summary.json
Raytracing took 64.27 seconds.
We can now height normalize the outputs using the provided DTM and DSM file. The DSM file is only to define the upper bounds of the canopy. Function 'normalize_occlusion_output' will also store the normalized voxel grids as npy files in the specified output folder
from occpy.util import normalize_occlusion_output
Nhit_norm, Nmiss_norm, Nocc_norm, Classification_norm, chm = normalize_occlusion_output(input_folder=os.path.join(config["root_folder"], config['out_dir']),
PlotDim=config['plot_dim'],
vox_dim=config['vox_dim'],
dtm_file=os.path.join(config["root_folder"], config['tif_in']['DTM']),
dsm_file=os.path.join(config["root_folder"], config['tif_in']['DSM']),
lower_threshold=config['lower_threshold'],
output_voxels=config['output_voxels'])
# If instead of a binary voxel grid classification, you are intereded in a fraction of occluded pulses per voxel, you can use the following function:
EPS = 1e-6 # small value to avoid division by zero
OcclFrac_norm = Nocc_norm.astype(float) / (Nhit_norm.astype(float) + Nmiss_norm.astype(float) + Nocc_norm.astype(float) + EPS)
Saving normalized output files into directory as .npy...
We can also visualize the results. Note that the amount of occlusion shown here is very high. This is due to the heavy filtering of the input data consisting of only 20% of the original data. The same figure based on the original data can be seen in the paper Kükenbrink et al. (under revision) [Preprint available here: https://doi.org/10.31223/X5N16X]
from occpy.visualization import plot_transect, plot_profile
# first define figure properties
fig_prop = dict(fig_size=(3.5, 3.2), # figure size in inches
label_size=8, # label size in pts. for e.g. axis labels
label_size_ticks=6, # label size in pts. for e.g. axis ticks
label_size_tiny=5, # label size in pts. for e.g. ticks in colorbar
out_format='png',) # output format of the figure, can be 'png', 'pdf', 'svg', etc.
%matplotlib inline
plot_transect(Nhit_norm, Classification_norm, plot_dim=config['plot_dim'], vox_dim=config['vox_dim'],
out_dir=os.path.join(config["root_folder"], config['out_dir']), axis=0, start_ind=0, end_ind=100, chm=chm, vertBuffer=10, fig_prop=fig_prop, show_plots=True)
# define other figure properties for the smaller figure
fig_prop = dict(fig_size=(1.75, 3.2),
label_size=8,
label_size_ticks=6,
label_size_tiny=5,
out_format='png', )
plot_profile(Classification_norm, plot_dim=config['plot_dim'], vox_dim=config['vox_dim'], out_dir=os.path.join(config["root_folder"], config['out_dir']), low_thresh=0, vertBuffer=10, max_percentage=100, fig_prop=fig_prop, show_plots=True)
The missing part in the middle of the transect close to top of canopy is unobserved volume. This is caused by the few selected Scan stations for the purpose of this tutorial, where all scan stations were setup as vertical scans with the Riegl scanner (no tilted scans). This can lead to unobserved volumes in the canopy. Please see Figure 4 in Kükenbrink et al. (under revision) [Preprint available here: https://doi.org/10.31223/X5N16X] to see how the occlusion map looks like when all scan positions were used.