-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpathlengthdistribution.py
More file actions
1430 lines (1162 loc) · 47.1 KB
/
Copy pathpathlengthdistribution.py
File metadata and controls
1430 lines (1162 loc) · 47.1 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
"""Radiative path-length distributions and geometric radiation interception.
This module computes the distribution of radiative path lengths through 3D plant
crown shapes (sphere/ellipsoid, cylinder, rectangular prism, or an arbitrary
triangular mesh) and, from those distributions, the geometric radiation
interception and absorption quantities described by:
* Bailey, Ponce de Leon & Krayenhoff (2020), Geosci. Model Dev. 13, 4789-4808
-- path-length distributions, the canopy-level binomial interception model,
and hemispherical diffuse integration.
* Ponce de Leon et al. (2025), Agric. For. Meteorol. 373, 110706
-- three-mode scattering (leaf reflectance/transmittance + ground reflection).
* Ponce de Leon et al. (2026), J. Geophys. Res. Biogeosciences
-- ellipsoidal crowns with diffuse radiation and scattering.
Conventions
-----------
* ``ray_zenith`` and ``ray_azimuth`` are in **radians** by default. Pass
``degrees=True`` to the public functions to supply them in degrees instead.
* Shapes: ``'ellipsoid'`` (equal scales give a sphere), ``'cylinder'``,
``'prism'`` (rectangular prism), and ``'polymesh'`` (triangular mesh from a
PLY file). Aliases ``'sphere'`` -> ``'ellipsoid'`` and ``'cone'`` ->
``'polymesh'`` are accepted.
* The ray grid is a deterministic ``N x N`` lattice (``N = ceil(sqrt(nrays))``);
there is no random sampling, so results are fully reproducible.
Performance
-----------
The ray-marching and ray/triangle intersection kernels are JIT-compiled with
numba. The pure-Python reference implementations are retained (suffixed
``_ref``) for regression testing and readability.
"""
import os
import numpy as np
from numpy import sqrt, sin, cos, exp, pi, ceil
try:
from numba import njit
_HAVE_NUMBA = True
except ImportError: # pragma: no cover - numba is a listed dependency
_HAVE_NUMBA = False
def njit(*args, **kwargs):
"""Fallback no-op decorator if numba is unavailable."""
def _decorate(func):
return func
if len(args) == 1 and callable(args[0]) and not kwargs:
return args[0]
return _decorate
from plyfile import PlyData, PlyElement
# ---------------------------------------------------------------------------
# Shape-name / unit helpers
# ---------------------------------------------------------------------------
_SHAPE_ALIASES = {
'ellipsoid': 'ellipsoid',
'sphere': 'ellipsoid',
'cylinder': 'cylinder',
'prism': 'prism',
'box': 'prism',
'rectangular_prism': 'prism',
'polymesh': 'polymesh',
'mesh': 'polymesh',
'cone': 'polymesh',
}
def _normalize_shape(shape):
"""Map a user-facing shape name/alias to an internal shape key.
Accepted (case-insensitive): 'sphere'/'ellipsoid', 'cylinder',
'prism'/'box'/'rectangular_prism', 'polymesh'/'mesh'/'cone'.
``'sphere'`` is an ellipsoid with equal scales; ``'cone'`` is handled via a
triangular mesh (there is no analytic cone primitive), so it maps to
'polymesh' and requires a ``plyfile``.
"""
key = str(shape).strip().lower()
if key not in _SHAPE_ALIASES:
raise ValueError(
"Invalid shape '{}'. Options: prism, ellipsoid (alias sphere), "
"cylinder, polymesh (alias cone).".format(shape))
return _SHAPE_ALIASES[key]
def _to_radians(angle, degrees):
"""Return ``angle`` in radians, converting from degrees if requested."""
return np.radians(angle) if degrees else float(angle)
# ===========================================================================
# Numba-accelerated numerical kernels
# ===========================================================================
#
# These are faithful ports of the pure-Python reference functions further down
# in this file. They operate only on plain float64/int64 scalars and arrays
# (numba cannot consume the structured record arrays returned by plyfile), so
# mesh geometry is pre-extracted into a contiguous (Nfaces, 3, 3) float64 array
# once in ``pathlengths`` before these kernels are called.
#
# A BVH / spatial acceleration structure is intentionally not used: brute-force
# ray/triangle testing under numba is fast enough for meshes up to ~1e5 faces.
# For much larger meshes a BVH would be the natural next step.
@njit(cache=True, fastmath=False)
def _intersect_bbox(ox, oy, oz, dx, dy, dz, sizex, sizey, sizez):
"""Ray/axis-aligned-box slab intersection (Suffern 2007, Listing 19.1).
Returns ``(dr, xe, ye, ze)`` where ``dr`` is the segment length inside the
box and ``(xe, ye, ze)`` is the exit point.
"""
x0 = -0.5 * sizex
x1 = 0.5 * sizex
y0 = -0.5 * sizey
y1 = 0.5 * sizey
z0 = -1e-6
z1 = sizez
if dx == 0.0:
a = 1e6
else:
a = 1.0 / dx
if a >= 0.0:
tx_min = (x0 - ox) * a
tx_max = (x1 - ox) * a
else:
tx_min = (x1 - ox) * a
tx_max = (x0 - ox) * a
if dy == 0.0:
b = 1e6
else:
b = 1.0 / dy
if b >= 0.0:
ty_min = (y0 - oy) * b
ty_max = (y1 - oy) * b
else:
ty_min = (y1 - oy) * b
ty_max = (y0 - oy) * b
if dz == 0.0:
c = 1e6
else:
c = 1.0 / dz
if c >= 0.0:
tz_min = (z0 - oz) * c
tz_max = (z1 - oz) * c
else:
tz_min = (z1 - oz) * c
tz_max = (z0 - oz) * c
if tx_min > ty_min:
t0 = tx_min
else:
t0 = ty_min
if tz_min > t0:
t0 = tz_min
if tx_max < ty_max:
t1 = tx_max
else:
t1 = ty_max
if tz_max < t1:
t1 = tz_max
if t0 < t1 and t1 > 1e-6:
if t0 > 1e-6:
dr = t1 - t0
else:
dr = t1
else:
dr = 0.0
xe = ox + t1 * dx
ye = oy + t1 * dy
ze = oz + t1 * dz
return dr, xe, ye, ze
@njit(cache=True, fastmath=False)
def _intersect_ellipsoid(ox, oy, oz, dx, dy, dz, sizex, sizey, sizez):
"""Path length through an ellipsoid centered at height ``sizez/2``."""
tempx = ox / sizex
tempy = oy / sizey
tempz = (oz - 0.5) / sizez
ddx = dx / sizex
ddy = dy / sizey
ddz = dz / sizez
a = ddx * ddx + ddy * ddy + ddz * ddz
b = 2.0 * (tempx * ddx + tempy * ddy + tempz * ddz)
c = (tempx * tempx + tempy * tempy + tempz * tempz) - 0.25
disc = b * b - 4.0 * a * c
if disc < 0.0:
return 0.0
e = sqrt(disc)
denom = 2.0 * a
t_small = (-b - e) / denom
t_big = (-b + e) / denom
if t_small > 1e-6 or t_big > 1e-6:
return abs(t_big - t_small)
return 0.0
@njit(cache=True, fastmath=False)
def _intersect_cylinder(ox, oy, oz, dx, dy, dz, sizex, sizey, sizez):
"""Path length through an upright cylinder (Suffern 2007, 19.5.3)."""
tempx = ox / sizex
tempy = oy / sizey
tempz = oz / sizez
ddx = dx / sizex
ddy = dy / sizey
ddz = dz / sizez
a = ddx * ddx + ddy * ddy
b = 2.0 * (tempx * ddx + tempy * ddy)
c = (tempx * tempx + tempy * tempy) - 0.25
disc = b * b - 4.0 * a * c
if disc >= 0.0 and a != 0.0:
t0 = (-b + sqrt(disc)) / (2.0 * a)
t1 = (-b - sqrt(disc)) / (2.0 * a)
else:
t0 = -1.0
t1 = -1.0
# Candidate intersection parameters (side x2, top, bottom); -1 = no hit.
c0 = -1.0
c1 = -1.0
c2 = -1.0
c3 = -1.0
z0 = tempz + t0 * ddz
if t0 > 1e-6 and 0.0 <= z0 <= 1.0:
c0 = t0
z1 = tempz + t1 * ddz
if t1 > 1e-6 and 0.0 <= z1 <= 1.0:
c1 = t1
if ddz != 0.0:
t_top = (1.0 - tempz) / ddz
hx = tempx + t_top * ddx
hy = tempy + t_top * ddy
if t_top > 0.0 and hx * hx + hy * hy <= 0.25:
c2 = t_top
t_bot = (0.0 - tempz) / ddz
hx = tempx + t_bot * ddx
hy = tempy + t_bot * ddy
if t_bot > 0.0 and hx * hx + hy * hy <= 0.25:
c3 = t_bot
# Smallest non-negative entry and overall largest, matching the reference
# (Tin = min over non-negative candidates, Tout = max over all four).
tin = 1e30
have_in = False
for cval in (c0, c1, c2, c3):
if cval >= 0.0 and cval < tin:
tin = cval
have_in = True
if not have_in:
return 0.0
tout = c0
if c1 > tout:
tout = c1
if c2 > tout:
tout = c2
if c3 > tout:
tout = c3
if 0.0 < tin < tout and tout > 0.0:
return tout - tin
return 0.0
@njit(cache=True, fastmath=False)
def _intersect_triangle(ox, oy, oz, dx, dy, dz, v0x, v0y, v0z,
v1x, v1y, v1z, v2x, v2y, v2z):
"""Ray/triangle intersection parameter ``t`` (0 if no hit)."""
kEpsilon = 1e-6
a = v0x - v1x
b = v0x - v2x
c = dx
d = v0x - ox
e = v0y - v1y
f = v0y - v2y
g = dy
h = v0y - oy
i = v0z - v1z
j = v0z - v2z
k = dz
l = v0z - oz
m = f * k - g * j
n = h * k - g * l
p = f * l - h * j
q = g * i - e * k
s = e * j - f * i
denom = a * m + b * q + c * s
if denom == 0.0:
inv_denom = 1e8
else:
inv_denom = 1.0 / denom
e1 = d * m - b * n - c * p
beta = e1 * inv_denom
if beta < 0.0:
return 0.0
r = e * l - h * i
e2 = a * n + d * q + c * r
gamma = e2 * inv_denom
if gamma < 0.0:
return 0.0
if beta + gamma > 1.0:
return 0.0
e3 = a * p - b * r + d * s
t = e3 * inv_denom
if t < kEpsilon:
return 0.0
return t
@njit(cache=True, fastmath=False)
def _intersect_polymesh(ox, oy, oz, dx, dy, dz, sizex, sizey, sizez, faces):
"""Path length through a closed triangular mesh (first two hits)."""
ox = ox / sizex
oy = oy / sizey
oz = oz / sizez
dx = dx / sizex
dy = dy / sizey
dz = dz / sizez
t0 = 0.0
t1 = 0.0
for kf in range(faces.shape[0]):
t = _intersect_triangle(
ox, oy, oz, dx, dy, dz,
faces[kf, 0, 0], faces[kf, 0, 1], faces[kf, 0, 2],
faces[kf, 1, 0], faces[kf, 1, 1], faces[kf, 1, 2],
faces[kf, 2, 0], faces[kf, 2, 1], faces[kf, 2, 2])
if t > 0.0:
if t0 > 0.0:
t1 = t
else:
t0 = t
if t0 > 0.0 and t1 > 0.0:
return abs(t0 - t1)
return 0.0
@njit(cache=True, fastmath=False)
def _march_kernel(shape_code, faces, N, dx, dy, dz,
bbox_sizex, bbox_sizey, z_min, z_max,
scale_x, scale_y, scale_z, kEpsilon):
"""March the full N x N ray grid and return recorded path-length segments.
``shape_code``: 0=prism, 1=ellipsoid, 2=cylinder, 3=polymesh. Mirrors the
reference ``pathlengths`` marcher exactly, including the periodic wall
cycling and the append pattern (one ``dr`` per march step plus one trailing
``dr`` per ray).
"""
sx = bbox_sizex / N
sy = bbox_sizey / N
# Upper bound on recorded segments; grown-safe preallocation. Each ray
# records at least one trailing value plus one per z-slab crossing.
out = np.empty(N * N * 64, dtype=np.float64)
count = 0
for j in range(N):
for i in range(N):
ox = -0.5 * bbox_sizex + (i + 0.5) * sx
oy = -0.5 * bbox_sizey + (j + 0.5) * sy
oz = z_min - kEpsilon
ze = 0.0
dr = 0.0
while ze <= z_max:
if shape_code == 0:
dr, _, _, _ = _intersect_bbox(
ox, oy, oz, dx, dy, dz, scale_x, scale_y, scale_z)
elif shape_code == 1:
dr = _intersect_ellipsoid(
ox, oy, oz, dx, dy, dz, scale_x, scale_y, scale_z)
elif shape_code == 2:
dr = _intersect_cylinder(
ox, oy, oz, dx, dy, dz, scale_x, scale_y, scale_z)
else:
dr = _intersect_polymesh(
ox, oy, oz, dx, dy, dz, scale_x, scale_y, scale_z, faces)
_, xe, ye, ze = _intersect_bbox(
ox, oy, oz, dx, dy, dz, bbox_sizex, bbox_sizey, 1e6)
if ze <= z_max:
if count >= out.shape[0]:
tmp = np.empty(out.shape[0] * 2, dtype=np.float64)
tmp[:count] = out[:count]
out = tmp
out[count] = dr
count += 1
ox = xe
oy = ye
oz = ze
if abs(ox - 0.5 * bbox_sizex) < kEpsilon:
ox = ox - bbox_sizex + kEpsilon
elif abs(ox + 0.5 * bbox_sizex) < kEpsilon:
ox = ox + bbox_sizex - kEpsilon
if abs(oy - 0.5 * bbox_sizey) < kEpsilon:
oy = oy - bbox_sizey + kEpsilon
elif abs(oy + 0.5 * bbox_sizey) < kEpsilon:
oy = oy + bbox_sizey - kEpsilon
if count >= out.shape[0]:
tmp = np.empty(out.shape[0] * 2, dtype=np.float64)
tmp[:count] = out[:count]
out = tmp
out[count] = dr
count += 1
return out[:count]
@njit(cache=True, fastmath=False)
def _silhouette_shadow_kernel(shape_code, faces, N, dx, dy, dz,
bbox_sizex, bbox_sizey, z_launch,
scale_x, scale_y, scale_z):
"""Fraction of an N x N launch grid whose ray hits the crown (no periodicity).
Rays are launched over a bounding box (which the caller enlarges so the
tilted crown shadow fits), and each ray is counted at most once. The single
crown's horizontal shadow area is ``fraction * bbox_sizex * bbox_sizey`` and
the beam-normal silhouette is that divided by ``cos(theta)``.
"""
sx = bbox_sizex / N
sy = bbox_sizey / N
hits = 0
for j in range(N):
for i in range(N):
ox = -0.5 * bbox_sizex + (i + 0.5) * sx
oy = -0.5 * bbox_sizey + (j + 0.5) * sy
oz = z_launch
if shape_code == 0:
dr, _, _, _ = _intersect_bbox(
ox, oy, oz, dx, dy, dz, scale_x, scale_y, scale_z)
elif shape_code == 1:
dr = _intersect_ellipsoid(
ox, oy, oz, dx, dy, dz, scale_x, scale_y, scale_z)
elif shape_code == 2:
dr = _intersect_cylinder(
ox, oy, oz, dx, dy, dz, scale_x, scale_y, scale_z)
else:
dr = _intersect_polymesh(
ox, oy, oz, dx, dy, dz, scale_x, scale_y, scale_z, faces)
if dr > 1e-6:
hits += 1
return hits / (N * N)
# ===========================================================================
# Pure-Python reference implementations (retained for testing / clarity)
# ===========================================================================
def intersectBBox(ox, oy, oz, dx, dy, dz, sizex, sizey, sizez):
# Intersection code below is adapted from Suffern (2007) Listing 19.1
x0 = -0.5*sizex
x1 = 0.5*sizex
y0 = -0.5 * sizey
y1 = 0.5 * sizey
z0 = -1e-6
z1 = sizez
if dx == 0:
a = 1e6
else:
a = 1.0 / dx
if a >= 0:
tx_min = (x0 - ox) * a
tx_max = (x1 - ox) * a
else:
tx_min = (x1 - ox) * a
tx_max = (x0 - ox) * a
if dy == 0:
b = 1e6
else:
b = 1.0 / dy
if b >= 0:
ty_min = (y0 - oy) * b
ty_max = (y1 - oy) * b
else:
ty_min = (y1 - oy) * b
ty_max = (y0 - oy) * b
if dz == 0:
c = 1e6
else:
c = 1.0 / dz
if c >= 0:
tz_min = (z0 - oz) * c
tz_max = (z1 - oz) * c
else:
tz_min = (z1 - oz) * c
tz_max = (z0 - oz) * c
# find largest entering t value
if tx_min > ty_min:
t0 = tx_min
else:
t0 = ty_min
if tz_min > t0:
t0 = tz_min
# find smallest exiting t value
if tx_max < ty_max:
t1 = tx_max
else:
t1 = ty_max
if tz_max < t1:
t1 = tz_max
if t0 < t1 and t1 > 1e-6:
if t0 > 1e-6:
dr = t1-t0
else:
dr = t1
else:
dr = 0
xe = ox + t1 * dx
ye = oy + t1 * dy
ze = oz + t1 * dz
if dr == 0:
raise Exception('Shouldnt be here')
return dr, xe, ye, ze
def intersectEllipsoid(ox, oy, oz, dx, dy, dz, sizex, sizey, sizez):
tempx = ox/sizex
tempy = oy/sizey
tempz = (oz - 0.5)/sizez
dx = dx/sizex
dy = dy/sizey
dz = dz/sizez
a = dx*dx + dy*dy + dz*dz
b = 2.0 * (tempx*dx+tempy*dy+tempz*dz)
c = (tempx*tempx+tempy*tempy+tempz*tempz) - 0.5*0.5
disc = b * b - 4.0 * a * c
if disc < 0.0:
return 0
else:
e = sqrt(disc)
denom = 2.0 * a
t_small = (-b - e) / denom # smaller root
t_big = (-b + e) / denom # larger root
if t_small > 1e-6 or t_big > 1e-6:
dr = abs(t_big-t_small)
return dr
return 0
def intersectCylinder(ox, oy, oz, dx, dy, dz, sizex, sizey, sizez):
tempx = ox / sizex
tempy = oy / sizey
tempz = oz / sizez
dx = dx / sizex
dy = dy / sizey
dz = dz / sizez
#19.5.3 of Suffern
a = dx * dx + dy * dy
b = 2.0 * (tempx * dx + tempy * dy)
c = (tempx * tempx + tempy * tempy) - 0.5 * 0.5
disc = b*b - 4 * a * c
if disc >= 0 and a != 0:
t0 = (-b + sqrt(disc)) / (2 * a)
t1 = (-b - sqrt(disc)) / (2 * a)
else:
t0 = -1
t1 = -1
T = np.array([-1., -1., -1., -1.])
# check if hit side surface of cylinder
z0 = tempz + t0 * dz
if t0 > 1e-6 and 1 >= z0 >= 0:
T[0] = t0
z1 = tempz + t1 * dz
if t1 > 1e-6 and 1 >= z1 >= 0:
T[1] = t1
# check if it hits top of cylinder
t_top = (1 - tempz) / dz
hx = tempx + t_top * dx
hy = tempy + t_top * dy
if t_top > 0 and hx*hx + hy*hy <= 0.25: # hits top
T[2] = t_top
# check if it hits bottom of cylinder
t_bot = (0 - tempz) / dz
hx = tempx + t_bot * dx
hy = tempy + t_bot * dy
if t_bot > 0 and hx*hx + hy*hy <= 0.25: # hits bottom
T[3] = t_bot
t_int = T[T >= 0.0]
if np.size(t_int) == 0:
return 0
Tin = np.min(t_int)
Tout = np.max(T)
if 0 < Tin < Tout and Tout > 0:
dr = Tout-Tin
else:
dr = 0
return dr
def importPLY(file):
plydata = PlyData.read(file)
return plydata
def intersectTriangle(ox, oy, oz, dx, dy, dz, vertices):
kEpsilon = 1e-6
a = vertices[0][0] - vertices[1][0]
b = vertices[0][0] - vertices[2][0]
c = dx
d = vertices[0][0] - ox
e = vertices[0][1] - vertices[1][1]
f = vertices[0][1] - vertices[2][1]
g = dy
h = vertices[0][1] - oy
i = vertices[0][2] - vertices[1][2]
j = vertices[0][2] - vertices[2][2]
k = dz
l = vertices[0][2] - oz
m = f * k - g * j
n = h * k - g * l
p = f * l - h * j
q = g * i - e * k
s = e * j - f * i
if (a * m + b * q + c * s) == 0:
inv_denom = 1e8
else:
inv_denom = 1.0 / (a * m + b * q + c * s)
e1 = d * m - b * n - c * p
beta = e1 * inv_denom
if beta < 0.0:
return 0
r = e * l - h * i
e2 = a * n + d * q + c * r
gamma = e2 * inv_denom
if gamma < 0.0:
return 0
if beta + gamma > 1.0:
return 0
e3 = a * p - b * r + d * s
t = e3 * inv_denom
if t < kEpsilon:
return 0
return t
def intersectPolymesh(ox, oy, oz, dx, dy, dz, sizex, sizey, sizez, plydata):
ox = ox / sizex
oy = oy / sizey
oz = oz / sizez
dx = dx / sizex
dy = dy / sizey
dz = dz / sizez
vertices = plydata.elements[0].data
faces = plydata.elements[1].data
Nfaces = len(faces)
face_verts = np.empty((3, 3))
T = [0, 0]
for face in range(0, Nfaces):
f = faces[face][0]
Nv = len(f)
if Nv != 3:
raise Exception('ERROR: only triangular elements are supported in PLY file geometry.')
for v in range(0, 3):
face_verts[0, v] = vertices[f[0]][v]
face_verts[1, v] = vertices[f[1]][v]
face_verts[2, v] = vertices[f[2]][v]
t = intersectTriangle(ox, oy, oz, dx, dy, dz, face_verts)
if t > 0:
if T[0] > 0:
T[1] = t
else:
T[0] = t
if T[0] > 0 and T[1] > 0:
return abs(T[0]-T[1])
else:
return 0
# ===========================================================================
# Mesh loading helper
# ===========================================================================
def _extract_faces(plydata):
"""Return a contiguous ``(Nfaces, 3, 3)`` float64 array of triangle verts.
Raises if any face is not a triangle.
"""
vertices = plydata.elements[0].data
faces = plydata.elements[1].data
verts = np.stack(
[np.asarray(vertices['x'], dtype=np.float64),
np.asarray(vertices['y'], dtype=np.float64),
np.asarray(vertices['z'], dtype=np.float64)], axis=1)
idx = np.empty((len(faces), 3), dtype=np.int64)
for fi in range(len(faces)):
f = faces[fi][0]
if len(f) != 3:
raise Exception(
'ERROR: only triangular elements are supported in PLY file geometry.')
idx[fi, 0] = f[0]
idx[fi, 1] = f[1]
idx[fi, 2] = f[2]
return np.ascontiguousarray(verts[idx])
_SHAPE_CODE = {'prism': 0, 'ellipsoid': 1, 'cylinder': 2, 'polymesh': 3}
# ===========================================================================
# Public path-length API
# ===========================================================================
def pathlengths(shape, scale_x, scale_y, scale_z, ray_zenith, ray_azimuth,
nrays, plyfile='', outputfile='', degrees=False):
"""Compute the radiative path lengths through a shape for a beam direction.
Launches a deterministic ``N x N`` grid of rays (``N = ceil(sqrt(nrays))``)
from below the bounding box in the beam direction, using periodic side
boundaries, and records the path length through the shape for each crossing.
Parameters
----------
shape : str
'prism', 'ellipsoid' (alias 'sphere'), 'cylinder', or 'polymesh'
(alias 'cone'). For a true sphere pass equal scales to 'ellipsoid'.
scale_x, scale_y, scale_z : float
Shape dimensions (m). For ellipsoid these are the full axis lengths
(semi-axes are scale/2); for cylinder scale_x/2 is the radius and
scale_z the height; for prism they are the box side lengths.
ray_zenith, ray_azimuth : float
Beam zenith and azimuth. Radians by default; degrees if ``degrees``.
nrays : int
Approximate number of rays; the actual grid is ``ceil(sqrt(nrays))**2``.
plyfile : str, optional
Path to a triangular-mesh PLY file (required for 'polymesh'/'cone').
outputfile : str, optional
If given, write all recorded path lengths to this file.
degrees : bool, optional
Interpret ``ray_zenith``/``ray_azimuth`` in degrees (default radians).
Returns
-------
path_length : ndarray
Path lengths of the rays that intersected the shape (m).
projected_area : float
Beam-normal silhouette area ``S(theta)`` of the crown (m^2). At
``theta = 0`` this equals the true silhouette (e.g. ``pi R^2`` for a
sphere). At oblique angles the periodic side boundaries let a ray cross
the tiled crown more than once, so this value is inflated relative to a
single isolated crown; use :func:`silhouette_area` for the isolated
``S(theta)`` needed by the canopy binomial model.
"""
shape = _normalize_shape(shape)
ray_zenith = _to_radians(ray_zenith, degrees)
ray_azimuth = _to_radians(ray_azimuth, degrees)
kEpsilon = 1e-5
N = int(ceil(sqrt(nrays)))
# Ray direction Cartesian unit vector
dx = sin(ray_zenith) * cos(ray_azimuth)
dy = sin(ray_zenith) * sin(ray_azimuth)
dz = cos(ray_zenith)
faces = np.empty((0, 3, 3), dtype=np.float64)
if shape == 'polymesh':
if len(plyfile) == 0:
raise Exception('Path to PLY file must be provided for polymesh intersection.')
elif not os.path.exists(plyfile):
raise Exception('PLY file does not exist.')
plydata = PlyData.read(plyfile)
faces = _extract_faces(plydata)
vertices = plydata.elements[0].data
Nvertices = len(vertices)
bx_min = 1e6
bx_max = -1e6
by_min = 1e6
by_max = -1e6
z_min = 1e6
z_max = -1e6
for vert in range(0, Nvertices):
vx = vertices[vert][0] * scale_x
vy = vertices[vert][1] * scale_y
vz = vertices[vert][2] * scale_z
if vx < bx_min:
bx_min = vx
if vx > bx_max:
bx_max = vx
if vy < by_min:
by_min = vy
if vy > by_max:
by_max = vy
if vz < z_min:
z_min = vz
if vz > z_max:
z_max = vz
bbox_sizex = 2*max(abs(bx_max), abs(bx_min)) * (1.0 + kEpsilon)
bbox_sizey = 2*max(abs(by_max), abs(by_min)) * (1.0 + kEpsilon)
z_min = z_min
z_max = z_max * (1.0 + kEpsilon)
else:
bbox_sizex = scale_x * (1.0 + kEpsilon)
bbox_sizey = scale_y * (1.0 + kEpsilon)
z_min = 0
z_max = scale_z * (1.0 + kEpsilon)
path_length = _march_kernel(
_SHAPE_CODE[shape], faces, N, dx, dy, dz,
float(bbox_sizex), float(bbox_sizey), float(z_min), float(z_max),
float(scale_x), float(scale_y), float(scale_z), kEpsilon)
path_length = np.asarray(path_length, dtype=float)
projected_area = np.sum(path_length > kEpsilon) / (N * N) \
* bbox_sizex * bbox_sizey * cos(ray_zenith)
if outputfile != '':
np.savetxt(outputfile, path_length, delimiter=',')
return path_length[path_length > kEpsilon], projected_area
def pathlengthdistribution(shape, scale_x, scale_y, scale_z, ray_zenith,
ray_azimuth, nrays, plyfile='', bins=10,
normalize=True, degrees=False):
"""Probability density (or histogram) of path lengths through a shape."""
path_lengths, _ = pathlengths(shape, scale_x, scale_y, scale_z, ray_zenith,
ray_azimuth, nrays, plyfile, degrees=degrees)
hist, bin_edges = np.histogram(path_lengths, bins=bins, density=normalize)
return hist, bin_edges
# ===========================================================================
# Crown-level interception and absorption
# ===========================================================================
def crown_interception(Gtheta, LAD, shape, scale_x, scale_y, scale_z,
ray_zenith, ray_azimuth, nrays,
path_multiplier=1.0, absorptivity=1.0,
plyfile='', degrees=False):
r"""Per-crown probability of intercepting a leaf (Bailey et al. 2020).
Monte-Carlo estimate of
.. math::
P_{\mathrm{leaf}}(\theta) = \int p(r|\theta)\,
[1 - e^{-m\,\zeta\,G\,a\,r}]\,dr
\approx \frac{1}{M}\sum_i [1 - e^{-m\,\zeta\,G\,a\,r_i}]
over the ``M`` path lengths that intersect the crown, where ``m`` is
``path_multiplier`` and ``zeta`` is ``absorptivity``.
Parameters
----------
Gtheta : float
Fraction of leaf area projected in the beam direction (Ross G).
LAD : float
Leaf area density ``a`` (m^2 m^-3).
path_multiplier : float, optional
Path-length multiplier ``m``. Use 1.0 for the direct (single-pass)
term and 2.0 for the mode-2 scattering approximation of Ponce de Leon
et al. (2025).
absorptivity : float, optional
Leaf absorptivity ``zeta = 1 - rho_l - tau_l``. Use 1.0 for total
interception (no scattering).
Returns
-------
float
Interception probability in [0, 1].
"""
path_length, _ = pathlengths(shape, scale_x, scale_y, scale_z, ray_zenith,
ray_azimuth, nrays, plyfile, degrees=degrees)
if path_length.size == 0:
return 0.0
k = path_multiplier * absorptivity * Gtheta * LAD
return float(np.mean(1.0 - np.exp(-k * path_length)))
def crownabsorptionfraction(Gtheta, LAD, shape, scale_x, scale_y, scale_z,
ray_zenith, ray_azimuth, nrays, plyfile='',
degrees=False):
"""Per-crown interception probability P_leaf (Bailey et al. 2020).
This is the corrected form of the crown-scale interception probability and
is equivalent to :func:`crown_interception` with unit multiplier and
absorptivity. (Earlier versions of this function erroneously divided by the
projected area; that has been fixed so the return value is a probability in
[0, 1].)
"""
return crown_interception(Gtheta, LAD, shape, scale_x, scale_y, scale_z,
ray_zenith, ray_azimuth, nrays, plyfile=plyfile,
degrees=degrees)