-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutils.py
More file actions
4894 lines (4091 loc) · 196 KB
/
Copy pathutils.py
File metadata and controls
4894 lines (4091 loc) · 196 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from __future__ import annotations
"""
A Python script of commonly shared utilities for other scripts.
Includes schemas for i/o data, functions, and helpers.
"""
import os
import gc
import glob
import json
import math
import time
import shutil
import tempfile
from typing import Dict, List, Tuple, Optional
from collections import defaultdict
import numpy as np
import pandas as pd
import pyarrow as pa
import pyarrow.parquet as pq
from fnvhash import fnv1a_32
from sklearn.neighbors import NearestNeighbors
from tqdm import tqdm
from joblib import Parallel, delayed
from numba import njit, prange, set_num_threads, get_num_threads
import dask
import dask.dataframe as dd
from dask.distributed import get_client
import tqdm_joblib
try:
import psutil # type: ignore
except Exception: # pragma: no cover
psutil = None
### Module Initialization: Configure Numba threading from HPC environment ###
def _setup_numba_threads():
"""
Configure Numba threading on module load based on HPC environment.
Respects SLURM_CPUS_PER_TASK, OMP_NUM_THREADS, or falls back to cpu_count.
"""
# Detect number of CPUs from environment
nthreads = 1
if 'SLURM_CPUS_PER_TASK' in os.environ:
try:
n = int(os.environ['SLURM_CPUS_PER_TASK'])
if n > 0:
nthreads = n
except (ValueError, TypeError):
pass
elif 'OMP_NUM_THREADS' in os.environ:
try:
n = int(os.environ['OMP_NUM_THREADS'])
if n > 0:
nthreads = n
except (ValueError, TypeError):
pass
else:
# Fall back to os.cpu_count()
n = os.cpu_count()
if n and n > 0:
nthreads = n
# Clamp to Numba's actual maximum (e.g. physical cores, not hyperthreads)
numba_max = get_num_threads()
if nthreads > numba_max:
nthreads = numba_max
# Set OMP_NUM_THREADS environment variable (Numba respects this)
os.environ['OMP_NUM_THREADS'] = str(nthreads)
# Also explicitly set Numba threads
set_num_threads(nthreads)
_setup_numba_threads()
# Per-process cache for warmup signatures to avoid repeated first-call warmups.
_VOXEL_RI_WARMED_KERNELS = set()
def _configure_pyarrow_worker_threads() -> tuple[int, int]:
"""Configure pyarrow CPU/IO thread pools for worker processes."""
cpu_raw = os.environ.get("VOXEL_RI_ARROW_CPU_THREADS", "1")
io_raw = os.environ.get("VOXEL_RI_ARROW_IO_THREADS", "1")
try:
cpu_threads = max(1, int(cpu_raw))
except (TypeError, ValueError):
cpu_threads = 1
try:
io_threads = max(1, int(io_raw))
except (TypeError, ValueError):
io_threads = 1
try:
pa.set_cpu_count(cpu_threads)
except Exception:
pass
try:
pa.set_io_thread_count(io_threads)
except Exception:
pass
return cpu_threads, io_threads
### CONSTANTS ###
beam_divergence = np.float32(0.001) # Beam divergence in radians
### SCHEMAS ###
# Voxel Ray Intersection Schema
"""
This schema is used to store ray intersections for each voxel.
It leverages the pyarrow library to maximise efficiency of dask, pandas, and parquet.
It is saved in the format:
leg_{scan_id}_voxel_{voxel_size}_ray_intersections.parquet
And contains the information outlined in the following schema.
Each index corresponds to a ray that intersects a voxel.
"""
voxel_ray_intersection_schema = pa.schema([
pa.field('voxel_size', pa.float32()),
pa.field('voxel_id', pa.uint64()),
pa.field('voxel_cx', pa.float64()),
pa.field('voxel_cy', pa.float64()),
pa.field('voxel_cz', pa.float64()),
pa.field('scan_id', pa.uint64()),
pa.field('ray_id', pa.uint64()),
pa.field('t_entry_x', pa.float64()),
pa.field('t_entry_y', pa.float64()),
pa.field('t_entry_z', pa.float64()),
pa.field('t_exit_x', pa.float64()),
pa.field('t_exit_y', pa.float64()),
pa.field('t_exit_z', pa.float64()),
pa.field('distance_to_centre', pa.float64()),
pa.field('point_x', pa.float64()),
pa.field('point_y', pa.float64()),
pa.field('point_z', pa.float64()),
pa.field('echo_intensity', pa.float64()),
pa.field('return_number', pa.int32()),
pa.field('number_of_returns', pa.int32()),
pa.field('viewing_angle', pa.float64()),
pa.field('hit_type', pa.int32()),
pa.field('is_leaf', pa.bool_())
])
# Voxel Metrics Schema
"""
This schema is used to store the metrics for each voxel, based on the selected legs and voxel size.
Since this one is only used to store to a csv file (for final output), it is not as important to be efficient.
"""
voxel_metrics_schema_singlereturn = pa.schema([
pa.field('voxel_id', pa.uint64()),
pa.field('voxel_cx', pa.float64()),
pa.field('voxel_cy', pa.float64()),
pa.field('voxel_cz', pa.float64()),
pa.field('voxel_size', pa.float32()),
pa.field('num_rays', pa.uint32()),
pa.field('num_hits', pa.uint32()),
pa.field('num_leaf_hits', pa.uint32()),
pa.field('pgap_lw', pa.float64()),
pa.field('pgap_leaf', pa.float64()),
pa.field('pgap_wood', pa.float64()),
pa.field('I_lw', pa.float64()), # num_hits / num_rays (i.e. leaf and wood)
pa.field('I_leaf', pa.float64()), # num_leaf_hits / num_rays (i.e. leaf only)
pa.field('I_wood', pa.float64()), # num_wood_hits / num_rays (i.e. wood only)
pa.field('G_leaf', pa.float64()), # G function calculated from leaf hits only
pa.field('G_wood', pa.float64()), # G function calculated from wood hits only
pa.field('G_lw', pa.float64()), # G function calculated from all hits
pa.field('bins_json', pa.string()), # Angle distribution bin centres as a JSON string
pa.field('liad_json', pa.string()), # LIAD histogram as JSON string
pa.field('liad_dewit', pa.string()), # LIAD De Wit classification
pa.field('liad_dewit_rmse', pa.float64()), # De Wit rmse for designated label
pa.field('liad_dewit_l1', pa.float64()), # De Wit l1 for designated label
pa.field('wiad_json', pa.string()), # WIAD histogram as JSON string
pa.field('wiad_dewit', pa.string()), # WIAD De Wit classification
pa.field('wiad_dewit_rmse', pa.float64()), # De Wit rmse for designated label
pa.field('wiad_dewit_l1', pa.float64()), # De Wit l1 for designated label
pa.field('piad_json', pa.string()), # PIAD histogram as JSON string
pa.field('piad_dewit', pa.string()), # PIAD De Wit classification
pa.field('piad_dewit_rmse', pa.float64()), # De Wit rmse for designated label
pa.field('piad_dewit_l1', pa.float64()), # De Wit l1 for designated label
pa.field('lambda_1', pa.float64()),
pa.field('mean_angle_leaf', pa.float32()), # Mean angle of leaf hits only
pa.field('mean_angle_lw', pa.float32()), # Mean angle of all hits
pa.field('mean_path_length', pa.float64()),
pa.field('sum_path_length', pa.float64()),
pa.field('mean_free_path_length', pa.float64()),
pa.field('sum_free_path_length', pa.float64()),
pa.field('sum_free_path_length_hit', pa.float64()),
pa.field('sum_free_path_length_hit_leaf', pa.float64()),
pa.field('mean_eff_path_length', pa.float64()),
pa.field('var_eff_path_length', pa.float64()),
pa.field('sum_eff_path_length', pa.float64()),
pa.field('mean_eff_free_path_length', pa.float64()),
pa.field('mean_eff_free_path_length', pa.float64()),
pa.field('var_eff_free_path_length', pa.float64()),
pa.field('sum_eff_free_path_length', pa.float64()),
pa.field('sum_eff_free_path_length_hit', pa.float64()), # Sum of z for all hits
pa.field('sum_eff_free_path_length_hit_leaf', pa.float64()) # Sum of z for leaf hits only
])
voxel_metrics_schema_multireturn = pa.schema([
pa.field('voxel_id', pa.uint64()),
pa.field('voxel_cx', pa.float64()),
pa.field('voxel_cy', pa.float64()),
pa.field('voxel_cz', pa.float64()),
pa.field('voxel_size', pa.float32()),
pa.field('num_rays', pa.uint32()),
pa.field('num_hits', pa.uint32()),
pa.field('num_leaf_hits', pa.uint32()),
pa.field('pgap_lw', pa.float64()),
pa.field('pgap_leaf', pa.float64()),
pa.field('pgap_wood', pa.float64()),
pa.field('I_lw', pa.float64()), # num_hits / num_rays (i.e. leaf and wood)
pa.field('I_leaf', pa.float64()), # num_leaf_hits / num_rays (i.e. leaf only)
pa.field('I_wood', pa.float64()), # num_wood_hits / num_rays (i.e. wood only)
pa.field('G_leaf', pa.float64()), # G function calculated from leaf hits only
pa.field('G_wood', pa.float64()), # G function calculated from wood hits only
pa.field('G_lw', pa.float64()), # G function calculated from all hits
pa.field('bins_json', pa.string()), # Angle distribution bin centres as a JSON string
pa.field('liad_json', pa.string()), # LIAD histogram as JSON string
pa.field('liad_dewit', pa.string()), # LIAD de Wit classification as string
pa.field('liad_dewit_rmse', pa.float64()), # de Wit classification RMSE for chosen label
pa.field('liad_dewit_l1', pa.float64()), # de Wit l1 for chosen label
pa.field('wiad_json', pa.string()), # WIAD histogram as JSON string
pa.field('wiad_dewit', pa.string()), # WIAD de Wit classification as string
pa.field('wiad_dewit_rmse', pa.float64()), # de Wit classification RMSE for chosen label
pa.field('wiad_dewit_l1', pa.float64()), # de Wit l1 for chosen label
pa.field('piad_json', pa.string()), # PIAD histogram as JSON string
pa.field('piad_dewit', pa.string()), # PIAD de Wit classification as string
pa.field('piad_dewit_rmse', pa.float64()), # De Wit classification RMSE for chosen label
pa.field('piad_dewit_l1', pa.float64()), # De Wit l1 for chosen label
pa.field('lambda_1', pa.float64()),
pa.field('P_first', pa.float64()),
pa.field('P_equal', pa.float64()),
pa.field('P_intensity', pa.float64()),
pa.field('P_first_leaf', pa.float64()),
pa.field('P_equal_leaf', pa.float64()),
pa.field('P_intensity_leaf', pa.float64()),
pa.field('LAD_BL_first', pa.float64()),
pa.field('LAD_BL_equal', pa.float64()),
pa.field('LAD_BL_intensity', pa.float64()),
pa.field('LAD_MLE_nocorr', pa.float64()),
pa.field('LAD_MLE_lambda1', pa.float64()),
pa.field('LAD_MLE_bias', pa.float64()),
pa.field('LAD_MLE_lambda1_bias', pa.float64()),
pa.field('mean_angle_leaf', pa.float32()), # Mean angle of leaf hits only
pa.field('mean_angle_lw', pa.float32()), # Mean angle of all hits
pa.field('mean_path_length', pa.float64()),
pa.field('sum_path_length', pa.float64()),
pa.field('mean_free_path_length', pa.float64()),
pa.field('sum_free_path_length', pa.float64()),
pa.field('sum_free_path_length_hit', pa.float64()),
pa.field('sum_free_path_length_hit_leaf', pa.float64()),
pa.field('mean_eff_path_length', pa.float64()),
pa.field('var_eff_path_length', pa.float64()),
pa.field('sum_eff_path_length', pa.float64()),
pa.field('mean_eff_free_path_length', pa.float64()),
pa.field('var_eff_free_path_length', pa.float64()),
pa.field('sum_eff_free_path_length', pa.float64()),
pa.field('sum_eff_free_path_length_hit', pa.float64()), # Sum of z for all hits
pa.field('sum_eff_free_path_length_hit_leaf', pa.float64()) # Sum of z for leaf hits only
])
# Occlusion metrics schema
"""
This schema is used to store the occlusion metrics for each voxel.
TEST ONLY at this stage.
"""
# Create occlusion metrics dataframe
voxel_occ_schema = pa.schema([
pa.field('voxel_id', pa.uint64()),
pa.field('voxel_cx', pa.float64()),
pa.field('voxel_cy', pa.float64()),
pa.field('voxel_cz', pa.float64()),
pa.field('theoretical_volume', pa.float64()),
pa.field('actual_volume', pa.float64()),
pa.field('volume_coverage', pa.float64()),
pa.field('weighted_theoretical_volume', pa.float64()),
pa.field('weighted_actual_volume', pa.float64()),
pa.field('weighted_volume_coverage', pa.float64()),
pa.field('theoretical_coverage_west', pa.float64()),
pa.field('theoretical_coverage_east', pa.float64()),
pa.field('theoretical_coverage_south', pa.float64()),
pa.field('theoretical_coverage_north', pa.float64()),
pa.field('theoretical_coverage_bottom', pa.float64()),
pa.field('theoretical_coverage_top', pa.float64()),
pa.field('actual_coverage_west', pa.float64()),
pa.field('actual_coverage_east', pa.float64()),
pa.field('actual_coverage_south', pa.float64()),
pa.field('actual_coverage_north', pa.float64()),
pa.field('actual_coverage_bottom', pa.float64()),
pa.field('actual_coverage_top', pa.float64()),
pa.field('weighted_theoretical_coverage_west', pa.float64()),
pa.field('weighted_theoretical_coverage_east', pa.float64()),
pa.field('weighted_theoretical_coverage_south', pa.float64()),
pa.field('weighted_theoretical_coverage_north', pa.float64()),
pa.field('weighted_theoretical_coverage_bottom', pa.float64()),
pa.field('weighted_theoretical_coverage_top', pa.float64()),
pa.field('weighted_actual_coverage_west', pa.float64()),
pa.field('weighted_actual_coverage_east', pa.float64()),
pa.field('weighted_actual_coverage_south', pa.float64()),
pa.field('weighted_actual_coverage_north', pa.float64()),
pa.field('weighted_actual_coverage_bottom', pa.float64()),
pa.field('weighted_actual_coverage_top', pa.float64()),
])
# Reference Schema
"""
This schema is used to store the reference data for each voxel.
"""
reference_schema = pa.schema([
pa.field('voxel_id', pa.uint64()),
pa.field('voxel_size', pa.float32()),
pa.field('CI', pa.float32()),
pa.field('woody_vol_proportion', pa.float32()),
pa.field('G', pa.float32()),
pa.field('G_leaf', pa.float32()),
pa.field('LAD', pa.float32()),
pa.field('PAD', pa.float32()),
])
# Valid Rays Schema
valid_rays_schema = pa.schema([
pa.field('scan_id', pa.uint64()),
pa.field('ray_id', pa.uint64()),
pa.field('origin_x', pa.float64()),
pa.field('origin_y', pa.float64()),
pa.field('origin_z', pa.float64()),
pa.field('direction_x', pa.float64()),
pa.field('direction_y', pa.float64()),
pa.field('direction_z', pa.float64()),
pa.field('point_x', pa.float64()),
pa.field('point_y', pa.float64()),
pa.field('point_z', pa.float64()),
pa.field('echo_intensity', pa.float64()),
pa.field('return_number', pa.int32()),
pa.field('number_of_returns', pa.int32()),
pa.field('is_leaf', pa.bool_())
])
### HELPER FUNCTIONS ###
# Commonly used functions that offer small utilities for components of other scripts.
DEWIT_LABELS = np.array([
"planophile", # mostly horizontal
"erectophile", # mostly vertical
"plagiophile", # around 45°
"uniform", # flat
"spherical", # sin(2θ)
"extremophile" # steeper than erectophile
])
DASK_CLIENT = None
def _gen_dataframe(schema):
fields = []
for field in schema:
dtype = field.type.to_pandas_dtype()
if np.issubdtype(dtype, np.integer):
dtype = 'Int64'
fields.append((field.name, dtype))
df = pd.DataFrame({name: pd.Series(dtype=dtype) for name, dtype in fields})
return df
def _canonical_curves(theta_deg: np.ndarray, categories: list = ["planophile", "erectophile", "plagiophile", "uniform", "spherical", "extremophile"]) -> np.ndarray:
"""
Build discretized, normalized canonical PDFs for the six de Wit categories at
the provided bin centers (theta_deg in degrees).
Inputs:
- theta_deg: (n_bins,) array of bin centers in degrees (e.g., 2.5, 7.5, ..., 87.5)
- categories: list of category names to generate (default to the classical 6 de Wit classes)
"""
th = np.deg2rad(theta_deg) # convert to radians
# Raw (unnormalized) shapes
raw = []
for name in categories:
if name == "planophile":
y = (2.0 / np.pi) * (1.0 + np.cos(2.0 * th)) # ∝ (2/π)(1 + cos(2θ))
elif name == "erectophile":
y = (2.0 / np.pi) * (1.0 - np.cos(2.0 * th)) # ∝ (2/π)(1 - cos(2θ))
elif name == "plagiophile":
y = (2.0 / np.pi) * (1.0 - np.cos(4.0 * th)) # ∝ (2/π)(1 - cos(4θ))
elif name == "uniform":
y = (2.0 / np.pi) * np.ones_like(th) # constant (uniform distribution)
elif name == "spherical":
y = np.sin(th) # ∝ sin(θ)
elif name == "extremophile":
y = (2.0 / np.pi) * (1.0 + np.cos(4.0 * th)) # ∝ (2/π)(1 + cos(4θ))
else:
raise ValueError(f"Unknown category: {name}")
# clamp negatives (e.g., sin(2θ) can be tiny negative due to float noise near 0/90)
y = np.maximum(y, 0.0)
raw.append(y)
raw = np.vstack(raw) # (n_cat, n_bins)
# Discrete normalization across bins so each shape sums to 1
raw_sum = raw.sum(axis=1, keepdims=True)
# If any shape sums ~0 (shouldn't happen), make it uniform as fallback
raw_norm = np.divide(raw, np.maximum(raw_sum, 1e-12))
return raw_norm # (n_cat, n_bins)
def classify_liad_to_dewit(
liad: np.ndarray,
bin_centres_deg: np.ndarray = None,
return_scores: bool = False
) -> Tuple[np.ndarray, np.ndarray]:
"""
Classify each voxel's LIAD histogram to the closest de Wit category
by RMSE to canonical curves evaluated at the provided bin centers.
Parameters
----------
liad : (n_voxels, n_bins) array
Each row is a LIAD histogram over 0–90° (not necessarily normalized).
bin_centres_deg : (n_bins,) array, optional
Bin centers in degrees. If None, equal-width centers over [0,90] are assumed.
return_scores : bool
If True, also return the RMSE scores per voxel for the chosen label
Returns
-------
labels : (n_voxels,) array of str
Best-fit de Wit class for each voxel.
scores : (n_voxels, ) array
RMSE per voxel for best category (only if return_scores=True).
NOTE: If only one voxel, just return floats
"""
liad = np.atleast_2d(np.asarray(liad, dtype=float))
if liad.ndim != 2:
raise ValueError("liad must be a 1D or 2D array")
if liad.shape[0] == 0 or liad.shape[1] == 0:
raise ValueError("liad array cannot be empty")
n_vox, n_bins = liad.shape
if bin_centres_deg is None:
edges = np.linspace(0, 90, n_bins + 1)
bin_centres_deg = 0.5 * (edges[:-1] + edges[1:])
else:
bin_centres_deg = np.asarray(bin_centres_deg, dtype=float)
if bin_centres_deg.shape != (n_bins,):
raise ValueError("bin_centres_deg must have shape (n_bins,)")
# Normalize LIAD rows (so comparisons are shape-only)
# liad_norm = liad / (np.linalg.norm(liad, axis=1, keepdims=True) + 1e-10) # (n_vox, n_bins)
# Build canonical curves
canon = _canonical_curves(bin_centres_deg) # (6, n_bins)
# print(f"canon row sums:", canon.sum(axis=1))
# print(f"canon distinct rows:", np.linalg.matrix_rank(canon))
row_sum = liad.sum(axis=1, keepdims=True)
liad_norm = liad / np.maximum(row_sum, 1e-12)
# Compute RMSE between each voxel and each canonical category
# Expand dims for broadcasting: (n_vox, 1, n_bins) vs (1, n_cat, n_bins)
diff = np.abs(liad_norm[:, None, :] - canon[None, :, :])
rmse = np.sqrt(np.mean(diff ** 2, axis=2)) # (n_vox, n_cat)
l1 = diff.sum(axis=2)
# Best category = argmin RMSE
best_idx = np.argmin(abs(l1), axis=1) # (n_vox,)
best_idx_r = np.argmin(abs(rmse), axis=1)
rmse_best = rmse[np.arange(n_vox), best_idx] # (n_vox,)
l1_best = l1[np.arange(n_vox), best_idx]
labels = DEWIT_LABELS[best_idx]
if return_scores:
if labels.size == 1 and rmse_best.size == 1:
labels = labels[0]
rmse_best = rmse_best[0]
l1_best = l1_best[0]
return labels, rmse_best, l1_best
return labels, None, None
# ---- normals_weights.py (can live alongside your metrics code) ----
import numpy as np
from joblib import Parallel, delayed
from scipy.spatial import cKDTree
from numba import njit
def compute_normals_weights_from_points_parallel(
points: np.ndarray,
*,
voxel_size: float = 20.0,
knn: int = 10,
n_jobs: int = -1,
eps: float = 1e-9
) -> tuple[np.ndarray, np.ndarray]:
"""
Parallel, memory-friendly version of your plane-fitting step.
- Bins points by coarse 'normal-voxel' of size `voxel_size`
- In each bin: build cKDTree, KNN, Numba PCA normals, weights = 1/(kth_distance+eps)
- Parallelizes over bins (joblib); inside each bin cKDTree runs single-threaded to avoid oversubscription
points: (N,3) float64; returns (normals(N,3), weights(N,))
"""
points = np.asarray(points, dtype=np.float64)
N = len(points)
if N == 0:
print("[compute_normals_weights] Empty input; returning empty arrays")
return np.zeros((0,3), dtype=np.float64), np.zeros((0,), dtype=np.float64)
if N < knn:
print(f"[compute_normals_weights] Only {N} points (< knn={knn}); returning default normals/weights")
return np.zeros((N,3), dtype=np.float64), np.ones((N,), dtype=np.float64)
print(f"[compute_normals_weights] Processing {N:,} points with voxel_size={voxel_size}, knn={knn}")
# Grid keys
vox = np.floor(points / voxel_size).astype(np.int64)
keys = (vox[:,0] * 73856093) ^ (vox[:,1] * 19349663) ^ (vox[:,2] * 83492791) # simple hash
order = np.argsort(keys, kind="stable")
keys_sorted = keys[order]
splits = np.flatnonzero(np.diff(keys_sorted)) + 1
starts = np.r_[0, splits]; ends = np.r_[splits, N]
num_bins = len(starts)
print(f" ✓ Partitioned into {num_bins} spatial bins")
# Output buffers
normals = np.zeros((N,3), dtype=np.float64)
weights = np.ones((N,), dtype=np.float64)
def _process_bin(s: int, e: int):
idx = order[s:e]
pts = points[idx]
if len(pts) < knn:
# leave zeros/ones defaults
return idx, np.zeros((len(pts),3), dtype=np.float64), np.ones((len(pts),), dtype=np.float64)
tree = cKDTree(pts)
k = min(knn, len(pts))
dists, nb = tree.query(pts, k=k, workers=1)
# nb is (M, k) indices *within* pts; compute normals in this local frame
nb = nb.astype(np.int64, copy=False)
loc_normals, loc_confidences = _compute_normals_vectorized(pts, nb)
# weight based on area-proportional weight for planar surfaces
r_k = np.maximum(dists[:, -1], eps) # distance to kth neighbor
w = r_k**2
conf = np.clip(loc_confidences, 0.0, 1.0)
w *= conf # downweight points with low confidence (e.g., near edges)
# Remove extreme weights to avoid outliers dominating metrics
w = np.clip(w, 0.0, np.percentile(w, 99.5))
return idx, loc_normals, w
# Run bins in parallel with progress bar
if n_jobs == -1:
n_jobs = max(1, num_bins // 4) # Use 1/4 of bins per job for better parallelization
print(f" Computing normals & weights (n_jobs={n_jobs}):")
jobs = [delayed(_process_bin)(s, e) for s, e in zip(starts, ends)]
chunks = Parallel(n_jobs=n_jobs, prefer="processes", batch_size="auto", verbose=0, env_var='LOKY_DISABLE_RESOURCE_TRACKER=1')(
tqdm(jobs, total=num_bins, desc=" Bins", unit=" bin", ncols=80, leave=True)
)
print(f" ✓ Computed {len(chunks)} bins; assembling output...")
for idx, nrm, w in chunks:
normals[idx] = nrm
weights[idx] = w
print(f" ✓ Normals & weights complete: {N:,} points processed")
return normals, weights
@njit(parallel=False)
def _compute_normals_vectorized(points, neighbor_indices):
"""
Compute normals using PCA on neighboring points.
Numba JIT compiled for speed.
INPUTS:
points: Points array (N, 3)
neighbor_indices: KNN neighbor indices (N, K)
OUTPUTS:
normals: Unit normal vectors (N, 3)
confidences: Surface variation confidence (N,)
"""
n_points = points.shape[0]
normals = np.zeros((n_points, 3), dtype=np.float64)
confidences = np.zeros(n_points, dtype=np.float64)
for i in range(n_points):
# Get neighbor points
neighbor_pts = points[neighbor_indices[i]]
# Compute centroid
centroid = np.zeros(3)
for j in range(neighbor_pts.shape[0]):
for k in range(3):
centroid[k] += neighbor_pts[j, k]
for k in range(3):
centroid[k] /= neighbor_pts.shape[0]
# Center points
centered = neighbor_pts - centroid
# Compute covariance matrix (3x3)
cov = np.zeros((3, 3))
for j in range(centered.shape[0]):
for a in range(3):
for b in range(3):
cov[a, b] += centered[j, a] * centered[j, b]
cov /= centered.shape[0]
# Compute normal (smallest eigenvector)
normal, confidence = _compute_smallest_eigenvector_3x3(cov)
# Ensure normal orientation is consistent: point outward from centroid to point
direction = points[i] - centroid
dot = 0.0
for k in range(3):
dot += normal[k] * direction[k]
if dot < 0:
for k in range(3):
normal[k] = -normal[k]
# Normalize the normal vector to ensure unit length (important for all axes)
norm = 0.0
for k in range(3):
norm += normal[k] * normal[k]
norm = np.sqrt(norm)
if norm > 0:
for k in range(3):
normal[k] /= norm
# Assign
for k in range(3):
normals[i, k] = normal[k]
confidences[i] = confidence
return normals, confidences
@njit
def _compute_smallest_eigenvector_3x3(cov, eps=1e-12):
"""
Compute the eigenvector of the smallest eigenvalue for a 3x3 matrix using direct eigen-decomposition.
Returns:
normal: The eigenvector corresponding to the smallest eigenvalue (unit vector)
confidence: 1 - surface_variation in [0,1] as a measure of how planar the neighborhood is
"""
# Symmetrize to remove numerical skew
cov_s = 0.5 * (cov + cov.T)
# Use numpy.linalg.eigh for symmetric matrices (guaranteed real eigenvalues)
eigvals, eigvecs = np.linalg.eigh(cov_s)
min_idx = np.argmin(eigvals)
v = eigvecs[:, min_idx]
# Normalize the normal vector
norm = np.sqrt(v[0]**2 + v[1]**2 + v[2]**2)
if norm > 0.0:
v = v / norm
else:
v = np.array([1.0, 0.0, 0.0])
# Calculate the confidence of the surface planes used to attenuate the weights later on
lam3 = eigvals[min_idx]
trace = cov_s[0, 0] + cov_s[1, 1] + cov_s[2, 2]
surf_var = 0.0
if trace > 0.0 and lam3 >= 0.0:
surf_var = lam3 / trace
confidence = 1.0 - min(1.0, max(0.0, surf_var)) # Invert so that more planar = higher confidence
return v, confidence
# Create a unique ID for a voxel
def create_voxel_id(voxel_size, x, y, z):
"""
Create a unique ID for a voxel.
INPUTS:
nd_array: containing [voxel_size, x, y, z]
OUTPUTS:
voxel_id: A unique ID for the voxel
"""
# Create a string representation of the voxel parameters
voxel_string = f'{voxel_size}_{x}_{y}_{z}'
# Encode the string and hash it using FNV-1a
voxel_id = fnv1a_32(voxel_string.encode())
# print(f"Created unique voxel_id: {voxel_id} for voxel {voxel_string}")
return voxel_id
# Create a pandas dataframe from a pyarrow schema
# Calculate lambda_1
def calculate_lambda_1(average_leaf_area, voxel_size):
"""
Calculate lambda_1 for a given voxel size.
"""
lambda_1 = float(average_leaf_area) / (float(voxel_size) ** 3)
return lambda_1
# Calculate the effective path length z
def calculate_inclination_angle_distribution_weighted_points(normals, weights, num_bins=18):
"""
Calculate the Leaf Angle Distribution (LAD) for a set of normals and weights.
INPUTS:
normals: A numpy array of normals
weights: A numpy array of weights
num_bins: The number of bins to use for the histogram
OUTPUTS:
bin_centres_deg: The bin centres
LIAD_values: The LIAD values
angles: The angles
"""
# Normalise normals
normals = normals / np.linalg.norm(normals, axis=1, keepdims=True)
# Compute inclination angle
angles = np.arccos(np.dot(normals, np.array([0, 0, 1])))
angles = np.where(angles > np.pi / 2, np.pi - angles, angles)
angles = np.degrees(angles)
# Compute LIAD for each voxel
if len(angles) == 0 or np.all(np.isnan(angles)):
return np.array([]), np.array([]), np.array([])
if len(weights) == 0:
weights = np.ones_like(angles)
# Remove NaN angles and align weights
valid_mask = ~np.isnan(angles)
angles = angles[valid_mask]
weights = weights[valid_mask].flatten()
if len(angles) == 0:
return np.array([]), np.array([]), np.array([])
# Compute the histogram
hist, bin_edges = np.histogram(angles, bins=num_bins, range=(0, 90), weights=weights)
total_weight = np.sum(hist)
if total_weight > 0:
LIAD_values = hist / total_weight
else:
LIAD_values = np.zeros(num_bins)
# Compute the bin centres
bin_centres_deg = (bin_edges[:-1] + bin_edges[1:]) / 2
return bin_centres_deg, LIAD_values, angles
# Calculate the G function mean
def calculate_G(viewing_angles, bin_centres_deg, LIAD_values, epsilon=1e-9):
"""
Calculate the G function mean.
INPUTS:
viewing_angle: The viewing angles
bin_centres_deg: The bin centres
LIAD_values: The LIAD values
OUTPUTS:
G_mean: The G function mean
"""
# Check for empty arrays
if len(viewing_angles) == 0 or len(bin_centres_deg) == 0 or len(LIAD_values) == 0:
return np.nan
# # Normalise LIAD
# total_LIAD = LIAD_values.sum()
# LIAD_norm = LIAD_values / total_LIAD if total_LIAD > 0 else LIAD_values
LIAD_norm = LIAD_values
# Ensure angles are clipped
viewing_angles = np.clip(viewing_angles, epsilon, 90)
bin_centres_deg = np.clip(bin_centres_deg, epsilon, 90)
### A(angle, leaf_angle) ####
theta_a = np.radians(viewing_angles)
theta_b = np.radians(bin_centres_deg)
# Calculate the cotangent of the angles
cos_theta_a = np.cos(theta_a)
cot_theta_a = 1 / np.tan(theta_a)
cos_theta_b = np.cos(theta_b)
cot_theta_b = 1 / np.tan(theta_b)
#
cos_outer = np.outer(cos_theta_a, cos_theta_b)
cot_outer = np.outer(cot_theta_a, cot_theta_b)
A = np.zeros_like(cos_outer)
mask_greater_1 = np.abs(cot_outer) > 1
A[mask_greater_1] = cos_outer[mask_greater_1]
inside = np.clip(cot_outer[~mask_greater_1], -1, 1)
psi = np.arccos(inside)
factor = 1.0 + (2.0 / np.pi) * (np.tan(psi) - psi)
A[~mask_greater_1] = factor * cos_outer[~mask_greater_1]
# Calculate the G function mean for all angles
delta_bin = np.radians(bin_centres_deg[1] - bin_centres_deg[0])
G = A @ LIAD_norm # (LIAD_norm * delta_bin)
return G
### LAD/PAD Functions ###
def CI_adjusted(AD, CI):
"""
This function takes an ADeff and CI and returns the AD.
Where, AD = ADeff/CI
"""
AD = AD/CI
return AD
def nan_zero_to_default_G_CI(G, CI):
"""
This function takes an array and a default value and returns the array with nans replaced by the default value.
"""
if isinstance(G, np.ndarray):
G = np.where(np.logical_or(np.isnan(G), G==0), 0.5, G)
if isinstance(CI, np.ndarray):
CI = np.where(np.logical_or(np.isnan(CI), CI==0), 1.0, CI)
return G, CI
# Beer-Lambert Pimont et al. 2018, eq. 5
def BL_pimont_2018(P, mean_path_length, G=0.5, CI=1.0, epsilon=1e-9):
"""
Calculate density using Beer-Lambert (Pimont et al. 2018), equation 5.
BL = -log(P) / δ̄
Calculate PAD by passing I/G values that use all hits,
and LAD by passing I/G values that use leaf hits only
INPUTS:
P: Pgap (probability gap fraction). Can be calculated in various methods.
G: A provided G_mean value or default 0.5
CI: A provided CI value or default 1.0
mean_path_length: Provided mean path length of voxel
epsilon: A condition to avoid issues with zero division
OUTPUTS:
ADeff: The calculated Leaf/Plant Area Density without corrected for CI
"""
### CI IS NOT CURRENTLY USED, BUT COULD BE LATER ###
try:
G, CI = nan_zero_to_default_G_CI(G, CI)
ADeff = np.where(
(~np.isnan(P) & ~np.isnan(mean_path_length)),
-(np.log(P) / (G * mean_path_length)),
np.nan
)
AD = np.where(
(~np.isnan(ADeff) & (CI != 0)),
ADeff / CI,
np.nan
)
except Exception as e:
print(f"Error: {e}")
return np.nan
return AD
def BL_EPL_UEPL_pimont_2018(I, mean_eff_path_length, var_eff_path_length, num_rays, G=0.5, epsilon=1e-9, CI=1.0):
"""
Calculate density using Beer-Lambert (Pimont et al. 2018) with Effective Path Length, equation 25.
Λ̂ = {
-1 / δ̄ₑ * (log(1 - I) + I / (2N(1 - I))) when I < 1
log(2N + 2) / δ̄ₑ when I = 1
}
&
Calculate the unbiased effective path length (UEPL) (Pimont et al. 2018, eq. 27), based on the shared EPL value before G correction
Λ̅₂ = 1 / aₑ * (1 - sqrt(1 - 2 * aₑ * Λ̅))
where:
Λ̅₂ is the second Lambda with a bar over it
aₑ is a subscripted 'a' with 'e'
sqrt represents the square root
Calculate PAD by passing I values that use all hits,
and LAD by passing I values that use leaf hits only
INPUTS:
I: A numpy array of Relative Density Indexes (num_hits/num_rays)
mean_eff_path_length: A numpy array of mean_eff_path_length
num_rays: A numpy array of num_rays
epsilon: A condition to avoid issues with zero division
OUTPUTS:
ADeff_EPL: The calculated density, without correcting for CI from EPL
ADeff_UEPL: The calculated density, without correcting for CI from UEPL
"""
try:
G, CI = nan_zero_to_default_G_CI(G, CI)
# Check for nans in inputs
valid_mask = (
~np.isnan(I) &
~np.isnan(mean_eff_path_length) &
np.logical_and(~np.isnan(num_rays), num_rays > 0)
)
# Split I < 1 and I == 1 values to handle separate calculations
I_lt_1_mask = I < 1
I_eq_1_mask = I == 1
# Calculate ADeff_EPL (L or P depending on inputs)
ADeff_EPL = np.where(
np.logical_and(I_lt_1_mask, valid_mask), # I < 1
-(1 / mean_eff_path_length) * (np.log(1 - I) + (I / (2 * num_rays * (1 - I)))),
np.where(
np.logical_and(I_eq_1_mask, valid_mask), # I == 1
np.log(2 * num_rays + 2) / mean_eff_path_length,
np.nan # Other
)
)
# Calculate ADeff_UEPL (L or P depending on inputs)
valid_UEPL_mask = (
np.logical_and(~np.isnan(ADeff_EPL), (ADeff_EPL > 0)) &
(mean_eff_path_length > 0) &
(var_eff_path_length > 0)
)
a_e = np.where(
valid_UEPL_mask,
var_eff_path_length / mean_eff_path_length,
np.nan
)
ADeff_UEPL = np.where(
valid_UEPL_mask,
1 / a_e * (1 - np.sqrt(1 - 2 * a_e * ADeff_EPL)),
np.nan
)
# Correct both ADeff values with G
ADeff_EPL = np.where(
~np.isnan(ADeff_EPL) & (G > 0),
ADeff_EPL / G,
np.nan
)
ADeff_UEPL = np.where(
~np.isnan(ADeff_UEPL) & (G > 0),
ADeff_UEPL / G,
np.nan
)
AD_EPL = ADeff_EPL / CI
AD_UEPL = ADeff_UEPL / CI
except Exception as e:
print(f"Error: {e}")
return np.nan, np.nan
return AD_EPL, AD_UEPL
def MCF_beland_2011(I, mean_free_path_length, G=0.5, CI=1.0, epsilon=1e-9):
"""
Calculate the Modified Contact Frequency (MCF) using the formula from Pimont et al. 2018 (eq. 8).
λ̃ = I / z̅ (See paper for more details about this simplification)