-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprocess_reference_single_obj.py
More file actions
2053 lines (1737 loc) · 90.9 KB
/
Copy pathprocess_reference_single_obj.py
File metadata and controls
2053 lines (1737 loc) · 90.9 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
import os
import csv
import argparse
import json
import math
import pandas as pd
import numpy as np
import traceback
import open3d as o3d
import open3d.core as o3c
o3d.utility.set_verbosity_level(o3d.utility.VerbosityLevel.Error)
import datetime as dt
from typing import Optional
import sys
from tqdm import tqdm
import psutil
import gc
from functools import partial
import joblib
from joblib import Parallel, delayed, Memory
import trimesh
import contextlib
import subprocess
import pyvista as pv
from typing import List, Tuple, Union, Optional
from pathlib import Path
from numba import njit, prange
global _CUDA_DEVICE_ID
temp_dir = os.getenv('TMPDIR', 'tmp')
# temp_dir = "/scratch/project/veg3d/uqjrivor/Raja_Tumba_Test/tmp"
if not os.path.exists(temp_dir):
os.makedirs(temp_dir, exist_ok=True)
memory = Memory(location=temp_dir, verbose=1)
def get_memory_usage():
job_id = os.getenv('SLURM_JOB_ID', 'local')
try:
result = subprocess.run([
'scontrol', 'show', 'job', job_id
], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
output = result.stdout.decode()
for line in output.split('\n'):
if 'maxRSS' in line:
print(f"Slurm... Used memory: {line}")
except Exception as e:
used_memory = psutil.virtual_memory().used / (1024 ** 2) # Convert to MB
print(f"Not Slurm... Used memory: {used_memory:.2f} MB")
def calculate_wood_volume(wood_mesh: trimesh.Trimesh, voxel_size: float=0.01, threshold: int=4, cache_size=10000) -> str:
"""
Calculate the wood volume of a mesh by voxelizing it.
"""
if wood_mesh.is_empty:
print("Wood mesh is empty, cannot calculate volume.")
return None
start_time = dt.datetime.now()
# Convert to open3d
o3d_wood_mesh = o3d.geometry.TriangleMesh()
o3d_wood_mesh.vertices = o3d.utility.Vector3dVector(wood_mesh.vertices)
o3d_wood_mesh.triangles = o3d.utility.Vector3iVector(wood_mesh.faces)
o3d_wood_mesh.compute_vertex_normals()
o3d_wood_mesh.remove_duplicated_vertices()
o3d_wood_mesh.remove_duplicated_triangles()
o3d_wood_mesh.remove_degenerate_triangles()
# Get bounding box of the mesh
aabb = o3d_wood_mesh.get_axis_aligned_bounding_box()
print (f"Bounding box of wood mesh: {aabb}")
offset = voxel_size * 0.01
# Create grid coordinates
x = np.arange(aabb.min_bound[0] - offset, aabb.max_bound[0] + offset, voxel_size)
y = np.arange(aabb.min_bound[1] - offset, aabb.max_bound[1] + offset, voxel_size)
z = np.arange(aabb.min_bound[2] - offset, aabb.max_bound[2] + offset, voxel_size)
total_points = len(x) * len(y) * len(z)
print(f"Grid dimensions: {len(x)} x {len(y)} x {len(z)} = {total_points} points.")
# Setup raycasting scene
scene = o3d.t.geometry.RaycastingScene()
mesh_t = o3d.t.geometry.TriangleMesh.from_legacy(o3d_wood_mesh)
scene.add_triangles(mesh_t)
# Prepare rays
directions = np.array([
[1.0001, 0.0001, 0.0001],
[-1.0001, 0.0001, 0.0001],
[0.0001, 1.0001, 0.0001],
[0.0001, -1.0001, 0.0001],
[0.0001, 0.0001, 1.0001],
[0.0001, 0.0001, -1.0001]
], dtype=np.float32)
inside_points = []
for xi, x_val in enumerate(tqdm(x, desc="Processing X-slices")):
slice_points = []
slice_indices = []
for yi, y_val in enumerate(y):
for zi, z_val in enumerate(z):
point = np.array([x_val, y_val, z_val], dtype=np.float32)
slice_points.append(point)
slice_indices.append((xi, yi, zi))
for i in range(0, len(slice_points), cache_size):
end_idx = min(i + cache_size, len(slice_points))
chunk_points = slice_points[i:end_idx]
# Check each direction for each point
for direction in directions:
# Create rays for all points in this direction
rays = []
for point in chunk_points:
ray = np.concatenate([point, direction])
rays.append(ray)
# Convert to tensor for batch processing
rays_tensor = o3d.core.Tensor(np.array(rays), dtype=o3d.core.Dtype.Float32)
# Get intersection counts for all rays at once
intersection_counts = scene.count_intersections(rays_tensor).numpy()
# Update inside counts for each point
if 'inside_counts' not in locals():
inside_counts = np.zeros(len(chunk_points), dtype=np.int32)
# Add odd intersections (indicates inside)
inside_counts += (intersection_counts % 2).astype(np.int32)
# Identify inside points based on threshold
for j in range(len(chunk_points)):
if inside_counts[j] >= threshold:
inside_points.append(chunk_points[j])
# Reset for next batch
if 'inside_counts' in locals():
del inside_counts
# Print progress every 10 x-slices
if xi % 10 == 0 and xi > 0:
elapsed = dt.datetime.now() - start_time
percent_complete = (xi + 1) / len(x) * 100
est_total_time = elapsed / percent_complete * 100
remaining = (est_total_time - elapsed).total_seconds()
print(f"Progress: {percent_complete:.1f}% complete, " +
f"ETA: {remaining/60:.1f} minutes, " +
f"Found {len(inside_points)} inside points so far")
# Convert to numpy array
inside_points = np.array(inside_points)
if len(inside_points) == 0:
print(f"No inside points found. Try a different threshold or check mesh.")
return
return inside_points
def process_wood_volume_file(scene_file: str, wood_mesh: str, wood_voxel_size: float=0.01, threshold: int=4) -> Optional[np.ndarray]:
wood_inside_points = calculate_wood_volume(wood_mesh, voxel_size=wood_voxel_size, threshold=threshold)
if wood_inside_points is not None:
try:
np.savetxt(wood_volume_file, wood_inside_points, fmt='%.3f')
print(f"Wood volume file saved at {wood_volume_file}.")
return np.round(wood_inside_points, 3)
except Exception as e:
print(f"Error saving wood volume file {wood_volume_file}: {e}")
return None
print(f"No wood volume file found at {wood_volume_file}.")
return None
@memory.cache
def load_wood_volume_file(wood_volume_file: str, wood_voxel_size: float=0.01, threshold: int=4) -> Optional[np.ndarray]:
"""
Load the wood volume file if it exists.
The file is expected to be in the same directory as the scene file.
"""
if os.path.exists(wood_volume_file):
try:
return np.loadtxt(wood_volume_file)
except Exception as e:
print(f"Error loading wood volume file {wood_volume_file}: {e}")
return None
else:
return None
def process_leaf_area_file(scene_file: str, leaf_mesh: trimesh.Trimesh) -> None:
"""
Process the leaf area file and save it as a CSV.
The leaf area is calculated from the mesh and saved in a CSV file.
"""
if leaf_mesh.is_empty:
print("Leaf mesh is empty, cannot calculate area.")
return
# Find triangle clusters that are connected (i.e. a leaf)
leaf_mesh = leaf_mesh.copy()
# Use trimesh to compute connected components and their areas
components = leaf_mesh.split(only_watertight=False)
areas = [comp.area for comp in components if comp.faces.shape[0] > 0]
if not areas:
avg_area, min_area, max_area, num_leaves, total_leaf_area = 0.0, 0.0, 0.0, 0, 0.0
else:
avg_area = float(np.mean(areas))
min_area = float(np.min(areas))
max_area = float(np.max(areas))
num_leaves = len(areas)
total_leaf_area = float(np.nansum(areas))
print(f"Leaf area stats: avg={avg_area:.3f}, min={min_area:.3f}, max={max_area:.3f}, num_leaves={num_leaves}, total_leaf_area={total_leaf_area}")
output_path = os.path.join(os.path.dirname(scene_file), os.path.basename(scene_file).replace(".obj", "_leaf_area.csv"))
df = pd.DataFrame({
'tree_id': [os.path.basename(scene_file).replace(".obj", "")],
'avg_leaf_area': [avg_area],
'min_leaf_area': [min_area],
'max_leaf_area': [max_area],
'num_leaves': [num_leaves],
'total_leaf_area': [total_leaf_area]
})
df.to_csv(output_path, index=False)
print(f"Leaf area saved to {output_path}.")
return avg_area, min_area, max_area, num_leaves, total_leaf_area
@contextlib.contextmanager
def tqdm_joblib(tqdm_object):
"""
Context manager to patch joblib to report progress updates to a tqdm bar.
This is necessary because joblib.Parallel doesn't have a built-in progress bar.
"""
class TqdmBatchCompletionCallback(joblib.parallel.BatchCompletionCallBack):
def __call__(self, *args, **kwargs):
tqdm_object.update(n=self.batch_size)
return super().__call__(*args, **kwargs)
old_callback = joblib.parallel.BatchCompletionCallBack
joblib.parallel.BatchCompletionCallBack = TqdmBatchCompletionCallback
try:
yield
finally:
joblib.parallel.BatchCompletionCallBack = old_callback
tqdm_object.close()
@memory.cache
def load_mesh_trimesh(file_path: str) -> Optional[trimesh.Trimesh]:
"""
Load a mesh using trimesh, returning None if the mesh is empty or invalid.
"""
try:
mesh = trimesh.load_mesh(file_path)
if isinstance(mesh, trimesh.Trimesh):
return mesh
else:
print(f"Invalid or empty mesh found in {file_path}.")
return None
except Exception as e:
print(f"Error loading mesh from {file_path}: {e}")
return None
# Global leaf and wood mesh cache
_LEAF_MESH = None
_WOOD_MESH = None
_LEAF_TREE = None
_WOOD_TREE = None
_LEAF_TRI_MIN = None
_LEAF_TRI_MAX = None
_WOOD_TRI_MIN = None
_WOOD_TRI_MAX = None
def _ensure_clip_worker_meshes(leaf_mesh_path: str, wood_mesh_path: str, build_tree: bool=True):
"""Ensure that the global leaf and wood meshes are loaded in the worker process.
"""
global _LEAF_MESH, _WOOD_MESH
global _LEAF_TREE, _WOOD_TREE
global _LEAF_TRI_MIN, _LEAF_TRI_MAX
global _WOOD_TRI_MIN, _WOOD_TRI_MAX
if _LEAF_MESH is None:
_LEAF_MESH = load_mesh_trimesh(leaf_mesh_path)
if _LEAF_MESH is not None and not _LEAF_MESH.is_empty:
tris = _LEAF_MESH.triangles # (N, 3, 3)
_LEAF_TRI_MIN = tris.min(axis=1)
_LEAF_TRI_MAX = tris.max(axis=1)
if build_tree:
_LEAF_TREE = _LEAF_MESH.triangles_tree # built once per worker
if _WOOD_MESH is None:
_WOOD_MESH = load_mesh_trimesh(wood_mesh_path)
if _WOOD_MESH is not None and not _WOOD_MESH.is_empty:
tris = _WOOD_MESH.triangles
_WOOD_TRI_MIN = tris.min(axis=1)
_WOOD_TRI_MAX = tris.max(axis=1)
if build_tree:
_WOOD_TREE = _WOOD_MESH.triangles_tree
def _clip_one_mesh_with_aabb(mesh, tri_min, tri_max, voxel_center, voxel_size):
"""Fast candidate selection via triangle AABB overlap; then clip via PyVista."""
if mesh is None or mesh.is_empty:
return (np.empty((0, 3), np.float64), np.empty((0, 3), np.int64))
half = voxel_size / 2.0
min_bound = np.asarray(voxel_center) - half
max_bound = np.asarray(voxel_center) + half
bounds6 = (min_bound[0], max_bound[0], min_bound[1], max_bound[1], min_bound[2], max_bound[2])
overlap = (tri_max >= min_bound).all(axis=1) & (tri_min <= max_bound).all(axis=1)
idx = np.flatnonzero(overlap)
if idx.size == 0:
return (np.empty((0, 3), np.float64), np.empty((0, 3), np.int64))
submesh = mesh.submesh([idx], append=True)
p_sub = pv.wrap(submesh)
# Prefer bounds param to avoid constructing a cube dataset
try:
clipped = p_sub.clip_box(bounds=bounds6, invert=False)
except TypeError:
cube = pv.Cube(center=voxel_center, x_length=voxel_size, y_length=voxel_size, z_length=voxel_size)
clipped = p_sub.clip_box(cube, invert=False)
if isinstance(clipped, pv.UnstructuredGrid):
clipped = clipped.extract_geometry()
if not clipped.is_all_triangles:
clipped = clipped.triangulate()
vertices = np.asarray(clipped.points)
faces = np.asarray(clipped.faces.reshape((-1, 4))[:, 1:])
return (vertices, faces)
def _faces_to_poly(vertices, faces):
"""Convert trimesh faces to a format compatible with PyVista.
"""
if not faces:
return None
faces_arr = np.asarray(faces, dtype=np.int64)
n_per_face = np.full((faces_arr.shape[0], 1), faces_arr.shape[1], np.int64)
faces_flat = np.hstack([n_per_face, faces_arr])
return pv.PolyData(vertices, faces_flat)
def get_clipped_meshes(
leaf_mesh,
wood_mesh,
voxel_center,
voxel_size) -> trimesh.Trimesh:
"""
Roughly clip a mesh using a bounding box defined by the voxel center and size.
This function uses a KDTree for efficient point querying.
"""
half_size = voxel_size / 2.0
min_bound = np.array(voxel_center) - half_size
max_bound = np.array(voxel_center) + half_size
voxel_bounds = np.stack([min_bound, max_bound], axis=0)
if leaf_mesh is None or leaf_mesh.is_empty:
print(f"Leaf mesh is empty or None at voxel center {voxel_center}.")
clipped_leaf_faces = np.empty((0, 3), dtype=np.int64)
clipped_leaf_vertices = np.empty((0, 3), dtype=np.float64)
leaf_mesh = None
else:
leaf_tree = leaf_mesh.triangles_tree
candidate_triangle_indices = list(leaf_tree.intersection(voxel_bounds.flatten()))
if not candidate_triangle_indices:
# print(f"No triangles found within voxel bounds {voxel_bounds}.")
del leaf_mesh, leaf_tree
gc.collect()
clipped_leaf_faces = np.empty((0, 3), dtype=np.int64)
clipped_leaf_vertices = np.empty((0, 3), dtype=np.float64)
else:
# Extract triangles within the voxel bounds
sub_mesh = leaf_mesh.submesh([candidate_triangle_indices], append=True)
del leaf_mesh, leaf_tree
# Create a PyVista mesh from the trimesh submesh
sub_mesh = pv.wrap(sub_mesh)
voxel = pv.Cube(center=voxel_center, x_length=voxel_size, y_length=voxel_size, z_length=voxel_size)
clipped_leaf_mesh = sub_mesh.clip_box(voxel, invert=False)
if isinstance(clipped_leaf_mesh, pv.UnstructuredGrid):
clipped_leaf_mesh = clipped_leaf_mesh.extract_geometry()
if not clipped_leaf_mesh.is_all_triangles:
clipped_leaf_mesh = clipped_leaf_mesh.triangulate()
clipped_leaf_vertices = np.asarray(clipped_leaf_mesh.points)
clipped_leaf_faces = np.asarray(clipped_leaf_mesh.faces.reshape((-1, 4))[:, 1:])
# print(f"No valid mesh found after clipping for voxel at {voxel_center}.")
### DEBUG ###
# Save .ply files for debugging
# cube = pv.Cube(center=voxel_center, x_length=voxel_size, y_length=voxel_size, z_length=voxel_size)
# cube.save(f"voxel_cube_{voxel_center[0]:.2f}_{voxel_center[1]:.2f}_{voxel_center[2]:.2f}.ply")
# clipped_leaf_mesh.save(f"clipped_leaf_{voxel_center[0]:.2f}_{voxel_center[1]:.2f}_{voxel_center[2]:.2f}.ply")
del sub_mesh, clipped_leaf_mesh
gc.collect()
# ### DEBUG ####
# # Save .ply files for debugging
# project_dir = os.path.dirname(leaf_mesh_path)
# surface_area = clipped_leaf_mesh.area if hasattr(clipped_leaf_mesh, 'area') else 0.0
# debug_leaf_path = os.path.join(project_dir, f"clipped_leaf_{voxel_center[0]:.2f}_{voxel_center[1]:.2f}_{voxel_center[2]:.2f}_{surface_area}.ply")
# debug_wood_path = os.path.join(project_dir, f"clipped_wood_{voxel_center[0]:.2f}_{voxel_center[1]:.2f}_{voxel_center[2]:.2f}.ply")
# clipped_leaf_mesh.save(debug_leaf_path)
if wood_mesh is None or wood_mesh.is_empty:
clipped_wood_faces = np.empty((0, 3), dtype=np.int64)
clipped_wood_vertices = np.empty((0, 3), dtype=np.float64)
wood_mesh = None
else:
wood_tree = wood_mesh.triangles_tree
candidate_triangle_indices = list(wood_tree.intersection(voxel_bounds.flatten()))
if not candidate_triangle_indices:
# print(f"No triangles found within voxel bounds {voxel_bounds}.")
del wood_mesh, wood_tree
gc.collect()
clipped_wood_faces = np.empty((0, 3), dtype=np.int64)
clipped_wood_vertices = np.empty((0, 3), dtype=np.float64)
else:
# Extract triangles within the voxel bounds
sub_mesh = wood_mesh.submesh([candidate_triangle_indices], append=True)
del wood_mesh, wood_tree
# Create a PyVista mesh from the trimesh submesh
sub_mesh = pv.wrap(sub_mesh)
voxel = pv.Cube(center=voxel_center, x_length=voxel_size, y_length=voxel_size, z_length=voxel_size)
clipped_wood_mesh = sub_mesh.clip_box(voxel, invert=False)
if isinstance(clipped_wood_mesh, pv.UnstructuredGrid):
clipped_wood_mesh = clipped_wood_mesh.extract_geometry()
if not clipped_wood_mesh.is_all_triangles:
clipped_wood_mesh = clipped_wood_mesh.triangulate()
clipped_wood_vertices = np.asarray(clipped_wood_mesh.points)
clipped_wood_faces = np.asarray(clipped_wood_mesh.faces.reshape((-1, 4))[:, 1:])
### DEBUG ###
# clipped_wood_mesh.save(f"clipped_wood_{voxel_center[0]:.2f}_{voxel_center[1]:.2f}_{voxel_center[2]:.2f}.ply")
return voxel_center, clipped_leaf_vertices, clipped_leaf_faces, clipped_wood_vertices, clipped_wood_faces
def build_voxel_scene(o3d_leaf, o3d_wood):
"""Return (scene, leaf_id, wood_id) either id may be None."""
_load_leaf = True if o3d_leaf is not None and len(o3d_leaf.triangles) > 0 and LEAF_OFF is False else False
_load_wood = True if o3d_wood is not None and len(o3d_wood.triangles) > 0 else False
leaf_id = wood_id = None
try:
dev = o3d.core.Device(f"SYCL:{_CUDA_DEVICE_ID}" if _CUDA_DEVICE_ID is not None else "SYCL:0")
scene = o3d.t.geometry.RaycastingScene(device=dev)
if _load_leaf:
leaves = o3d.t.geometry.TriangleMesh.from_legacy(o3d_leaf)
leaves = leaves.to(dev)
leaf_id = scene.add_triangles(leaves)
if _load_wood:
wood = o3d.t.geometry.TriangleMesh.from_legacy(o3d_wood)
wood = wood.to(dev)
wood_id = scene.add_triangles(wood)
# print("[INFO] Using CUDA for raycasting.")
except Exception as e:
# Fallback to CPU
dev = o3d.core.Device("CPU:0")
scene = o3d.t.geometry.RaycastingScene(device=dev)
if _load_leaf:
leaves = o3d.t.geometry.TriangleMesh.from_legacy(o3d_leaf)
leaf_id = scene.add_triangles(leaves)
if _load_wood:
wood = o3d.t.geometry.TriangleMesh.from_legacy(o3d_wood)
wood_id = scene.add_triangles(wood)
# print(f"[INFO] CUDA unavailable, falling back to CPU: {e}.")
return scene, leaf_id, wood_id
def compute_wood_volume_in_voxel(wood_volume, voxel_center, voxel_size, small_voxel_size=0.01):
"""
Return estimates the volume of wood points within a voxel.
This function assumes wood_volume_file is a numpy array of shape (N, 3).
"""
if wood_volume is None or wood_volume.shape[0] == 0:
return 0.0
# Calculate number of points within the voxel
half_size = voxel_size / 2.0
min_bound = np.array(voxel_center) - half_size
max_bound = np.array(voxel_center) + half_size
in_voxel = np.all((wood_volume >= min_bound) & (wood_volume <= max_bound), axis=1)
num_points_in_voxel = np.sum(in_voxel)
wood_volume = small_voxel_size ** 3 * num_points_in_voxel
# print(f"Computed wood volume in voxel centered at {voxel_center}: {wood_volume} (with {num_points_in_voxel} points).")
return wood_volume
def compute_LIAD_from_mesh(o3d_mesh, num_bins=18):
"""
Compute area-weighted leaf inclination distribution.
Returns: (bin centers, LIAD, mean angle)
"""
if (o3d_mesh is None) or (len(o3d_mesh.triangles) == 0):
return np.array([]), np.array([]), np.nan
verts = np.asarray(o3d_mesh.vertices)
tris = np.asarray(o3d_mesh.triangles)
v0 = verts[tris[:, 1]] - verts[tris[:, 0]]
v1 = verts[tris[:, 2]] - verts[tris[:, 0]]
cross_prod = np.cross(v0, v1)
areas = 0.5 * np.linalg.norm(cross_prod, axis=1)
norms = np.linalg.norm(cross_prod, axis=1, keepdims=True)
normals = np.divide(cross_prod, norms, where=(norms != 0))
angle_facets = np.degrees(np.arccos(np.clip(normals[:, 2], -1, 1)))
angle_facets = np.where(angle_facets > 90, 180 - angle_facets, angle_facets)
mean_angle = angle_facets.mean() if angle_facets.size > 0 else np.nan
bin_edges = np.linspace(0, 90, num_bins + 1)
idx = np.digitize(angle_facets, bin_edges) - 1
idx = np.clip(idx, 0, num_bins - 1)
bin_counts = np.bincount(idx, weights=areas, minlength=num_bins)
total_area = areas.sum()
liad = bin_counts / total_area if total_area > 0 else np.zeros(num_bins)
bin_centers = 0.5 * (bin_edges[:-1] + bin_edges[1:])
return bin_centers, liad, mean_angle
def ray_box_intersection_vectorized(orig, dirs, bmin, bmax, eps=1e-12):
safe = np.where(np.abs(dirs) < eps,
np.where(dirs >= 0, eps, -eps),
dirs)
t1 = (bmin - orig) / safe
t2 = (bmax - orig) / safe
t_near = np.maximum.reduce(np.minimum(t1, t2), axis=1)
t_far = np.minimum.reduce(np.maximum(t1, t2), axis=1)
return t_near, t_far
def compute_efpl_array(d_arr, lambda_1):
d_arr = np.asarray(d_arr)
out = np.zeros_like(d_arr)
mask = d_arr > 0
# Avoid division by zero for lambda_1 == 0
if lambda_1 == 0:
out[mask] = d_arr[mask]
else:
out[mask] = -np.log(1.0 - lambda_1 * d_arr[mask]) / lambda_1
return out
### Ray tracing functions ###
def _grid(voxel_size, ray_spacing):
"""
Generate a grid covering a square of size `face_len` centered at the origin.
For full coverage when rotating the voxel, use face_len = voxel_size * sqrt(2).
This ensures the grid covers the diagonal of the voxel after rotation.
"""
face_len = voxel_size * np.sqrt(2)
s = np.arange(-face_len / 2, face_len / 2 + ray_spacing, ray_spacing)
return np.meshgrid(s, s, indexing='xy')
def generate_face_rays_bottom(vc, vs, grid):
# XX, YY = _grid(vs * 2, spc)
XX, YY = grid
zface = vc[2] - vs * 2
org = np.column_stack([vc[0] + XX.ravel(),
vc[1] + YY.ravel(),
np.full(XX.size, zface)])
return org, np.tile([0, 0, 1], (len(org), 1))
def generate_face_rays_top(vc, vs, grid):
# XX, YY = _grid(vs * 2, spc)
XX, YY = grid
zface = vc[2] + vs * 2
org = np.column_stack([vc[0] + XX.ravel(),
vc[1] + YY.ravel(),
np.full(XX.size, zface)])
return org, np.tile([0, 0, -1], (len(org), 1))
def generate_side_rays_xplus(vc, vs, grid):
# YY, ZZ = _grid(vs * 2, spc)
YY, ZZ = grid
xface = vc[0] + vs * 2
org = np.column_stack([np.full(YY.size, xface),
vc[1] + YY.ravel(),
vc[2] + ZZ.ravel()])
return org, np.tile([-1, 0, 0], (len(org), 1))
def generate_side_rays_xminus(vc, vs, grid):
# YY, ZZ = _grid(vs * 2, spc)
YY, ZZ = grid
xface = vc[0] - vs * 2
org = np.column_stack([np.full(YY.size, xface),
vc[1] + YY.ravel(),
vc[2] + ZZ.ravel()])
return org, np.tile([1, 0, 0], (len(org), 1))
def generate_side_rays_yplus(vc, vs, grid):
# XX, ZZ = _grid(vs * 2, spc)
XX, ZZ = grid
yface = vc[1] + vs * 2
org = np.column_stack([vc[0] + XX.ravel(),
np.full(XX.size, yface),
vc[2] + ZZ.ravel()])
return org, np.tile([0, -1, 0], (len(org), 1))
def generate_side_rays_yminus(vc, vs, grid):
# XX, ZZ = _grid(vs * 2, spc)
XX, ZZ = grid
yface = vc[1] - vs * 2
org = np.column_stack([vc[0] + XX.ravel(),
np.full(XX.size, yface),
vc[2] + ZZ.ravel()])
return org, np.tile([0, 1, 0], (len(org), 1))
def rotate_rays(orig, dirs, angle_deg, vc, axis="x"):
ang = np.radians(angle_deg)
if axis == "x":
R = np.array([[1, 0, 0],
[0, np.cos(ang), -np.sin(ang)],
[0, np.sin(ang), np.cos(ang)]])
else: # yaxis
R = np.array([[ np.cos(ang), 0, np.sin(ang)],
[ 0, 1, 0 ],
[-np.sin(ang), 0, np.cos(ang)]])
o = (orig - vc) @ R.T + vc
d = dirs @ R.T
return o, d
def simulate_combined_mesh_with_points(scene, leaf_gid, wood_gid,
voxel_center, voxel_size,
ray_origins, ray_dirs, lambda_1):
hit_details = []
voxel_center = np.asarray(voxel_center, dtype=np.float32)
bmin = voxel_center - 0.5 * voxel_size
bmax = voxel_center + 0.5 * voxel_size
t_near, t_far = ray_box_intersection_vectorized(
ray_origins, ray_dirs, bmin, bmax)
valid_rays_mask = (t_near <= t_far) & (t_far >= 0)
N = int(valid_rays_mask.sum())
if N == 0:
return {k: 0.0 for k in (
"N","n_hits","I","delta_bar","sum_delta","sum_z","mean_z",
"mean_delta_e","var_delta_e","sum_z_e","sum_hits_z_e",
"mean_efpl_free","var_efpl_free"
)}, hit_details
rays_np = np.hstack([ray_origins, ray_dirs]).astype(np.float32)
# print(f"Simulating {N} rays for voxel at {voxel_center} with size {voxel_size}.")
hits = scene.cast_rays(o3c.Tensor(rays_np, dtype=o3c.float32))
# print(f"Ray casting completed for voxel at {voxel_center}.")
gids = hits["geometry_ids"].numpy()
dists = hits["t_hit"].numpy()
# Mask infinite t_hits
valid_hits_mask = np.isfinite(dists) & (dists >= t_near) & (dists <= t_far) & (dists >= 0) & valid_rays_mask
dist_leaf = np.full_like(dists, np.inf)
dist_wood = np.full_like(dists, np.inf)
if leaf_gid is not None:
m = (gids == leaf_gid) & valid_hits_mask
dist_leaf[m] = dists[m]
if wood_gid is not None:
m = (gids == wood_gid) & valid_hits_mask
dist_wood[m] = dists[m]
comb_dist = np.minimum(dist_leaf, dist_wood)
hit_any = np.isfinite(comb_dist) # & (comb_dist < np.inf)
n_hits_lw = int(hit_any.sum())
hit_leaf = np.isfinite(dist_leaf)
n_hits_leaf = int(hit_leaf.sum())
delta = np.zeros_like(dists)
delta[valid_rays_mask] = t_far[valid_rays_mask] - t_near[valid_rays_mask]
z_arr = delta.copy()
z_arr[hit_any] = comb_dist[hit_any] - t_near[hit_any]
efpl_d = compute_efpl_array(delta[valid_rays_mask], lambda_1)
efpl_f = compute_efpl_array(z_arr[valid_rays_mask], lambda_1)
stats_lw = dict(
N=N,
n_hits=n_hits_lw,
I=n_hits_lw / N if N else 0.0,
delta_bar=delta[valid_rays_mask].mean() if N else 0.0,
sum_delta=delta[valid_rays_mask].sum(),
sum_z=z_arr[valid_rays_mask].sum(),
mean_z=z_arr[valid_rays_mask].mean() if N else 0.0,
mean_delta_e=efpl_d.mean() if N else 0.0,
var_delta_e=efpl_d.var(ddof=1) if N > 1 else 0.0,
sum_z_e=efpl_f.sum(),
sum_hits_z_e=efpl_f[hit_any[valid_rays_mask]].sum() if n_hits_lw else 0.0,
mean_efpl_free=efpl_f.mean() if N else 0.0,
var_efpl_free=efpl_f.var(ddof=1) if N > 1 else 0.0,
)
delta = np.zeros_like(dists)
delta[valid_rays_mask] = t_far[valid_rays_mask] - t_near[valid_rays_mask]
z_arr = delta.copy()
z_arr[hit_leaf] = dists[hit_leaf] - t_near[hit_leaf]
efpl_d = compute_efpl_array(delta[valid_rays_mask], lambda_1)
efpl_f = compute_efpl_array(z_arr[valid_rays_mask], lambda_1)
stats_leaf = dict(
N=N,
n_hits=n_hits_leaf,
I=n_hits_leaf / N if N else 0.0,
delta_bar=delta[valid_rays_mask].mean() if N else 0.0,
sum_delta=delta[valid_rays_mask].sum(),
sum_z=z_arr[valid_rays_mask].sum(),
mean_z=z_arr[valid_rays_mask].mean() if N else 0.0,
mean_delta_e=efpl_d.mean() if N else 0.0,
var_delta_e=efpl_d.var(ddof=1) if N > 1 else 0.0,
sum_z_e=efpl_f.sum(),
sum_hits_z_e=efpl_f[hit_leaf[valid_rays_mask]].sum() if n_hits_leaf else 0.0,
mean_efpl_free=efpl_f.mean() if N else 0.0,
var_efpl_free=efpl_f.var(ddof=1) if N > 1 else 0.0,
)
return stats_lw, stats_leaf, hit_details
def simulate_voxel_grouped(scene, leaf_gids, wood_gids,
voxel_center, voxel_size,
rays_FAR6, # shape (Faces,Angles,Rays,6), float32
lambda_1,
scene_name="scene"):
"""
Vectorized per-(face, angle) aggregation that matches your stats dictionaries.
Returns:
stats_lw[F][A], stats_leaf[F][A], each a dict like your original.
"""
F, A, R, _ = rays_FAR6.shape
vc = np.asarray(voxel_center, dtype=np.float32)
bmin = vc - 0.5 * voxel_size
bmax = vc + 0.5 * voxel_size
O = rays_FAR6[..., 0:3] # (F,A,R,3)
D = rays_FAR6[..., 3:6] # (F,A,R,3)
# Compute t_near, t_far for ray-box intersection
t_near, t_far = ray_box_intersection_vectorized(
O.reshape(-1, 3), D.reshape(-1, 3), bmin, bmax
)
t_near = t_near.reshape(F, A, R)
t_far = t_far.reshape(F, A, R)
valid_rays_mask = (t_near <= t_far) & (t_far >= 0.0) # (F,A,R)
# Single cast_rays call
hits = scene.cast_rays(o3c.Tensor(rays_FAR6, dtype=o3c.float32))
# Each field returns with leading dims (F,A,R)
gids = hits["geometry_ids"].numpy() # (F,A,R), uint32 or int64
dists = hits["t_hit"].numpy() # (F,A,R), float32; inf for miss
# If debugging, save xyz to ASCII .xyz, with scalar for Face, Angle, and Leaf/Wood hit
if DEBUG_MODE:
# Filter to valid hits before computing points to avoid NaN from inf * direction
hit_mask = valid_rays_mask & np.isfinite(dists)
if np.any(hit_mask):
f_idx, a_idx, r_idx = np.nonzero(hit_mask)
O_hits = O[f_idx, a_idx, r_idx] # (N_hits, 3)
D_hits = D[f_idx, a_idx, r_idx] # (N_hits, 3)
dists_hits = dists[f_idx, a_idx, r_idx] # (N_hits,)
pts = O_hits + D_hits * dists_hits[:, np.newaxis] # (N_hits, 3)
gids_hits = gids[f_idx, a_idx, r_idx] # (N_hits,)
leaf_hit = (np.isin(gids_hits, leaf_gids))
wood_hit = (np.isin(gids_hits, wood_gids))
classes = np.zeros(pts.shape[0], dtype=np.int8)
classes[leaf_hit] = 1
classes[wood_hit] = 0
data = np.column_stack((pts, f_idx, a_idx, classes)) # (N_hits, 6)
debug_dir = os.path.join(DEBUG_PATH, f"voxel_size={voxel_size}", f"voxel_{voxel_center[0]:.2f}_{voxel_center[1]:.2f}_{voxel_center[2]:.2f}")
os.makedirs(debug_dir, exist_ok=True)
out_path = os.path.join(debug_dir, f"{scene_name}_hits_{voxel_center[0]:.2f}_{voxel_center[1]:.2f}_{voxel_center[2]:.2f}.xyz")
# Write separate class mapping file
class_map_path = os.path.join(debug_dir, "class_mapping.txt")
face_idx_to_label = {i: label for i, label in enumerate(FACE_ORDER)}
angle_idx_to_label = {i: label for i, label in enumerate(ANGLE_ORDER)}
with open(class_map_path, 'w') as f:
f.write(f"# face_idx mapping: {','.join([f'{i}={label}' for i, label in face_idx_to_label.items()])}\n")
f.write(f"# angle_idx mapping: {','.join([f'{i}={label}' for i, label in angle_idx_to_label.items()])}\n")
f.write(f"# class: 0=wood, 1=leaf\n")
# Write hits to .xyz file in chunks to avoid large memory usage
header_text = f"x y z face_idx angle_idx class\n"
df = pd.DataFrame(data, columns=["x", "y", "z", "face_idx", "angle_idx", "class"])
chunk_size = 200000 # 200 thousand rows per chunk
with open(out_path, 'w', buffering=4*1024*1024) as f:
f.write(header_text)
for start in range(0, df.shape[0], chunk_size):
end = start + chunk_size
df.iloc[start:end].to_csv(f, sep=' ', header=False, index=False, float_format='%.2f')
# Valid hits inside the voxel slab
valid_hits_mask = np.isfinite(dists) & (dists >= t_near) & (dists <= t_far) & (dists >= 0) & valid_rays_mask
# Separate leaf vs wood by geometry_id
# Open3D returns INVALID_ID (typically 0xFFFFFFFF) on miss.
# We only consider valid_hits_mask anyway.
dist_leaf = np.full_like(dists, np.inf, dtype=np.float32)
dist_wood = np.full_like(dists, np.inf, dtype=np.float32)
if leaf_gids is not None:
m_leaf = np.isin(gids, leaf_gids) & valid_hits_mask
dist_leaf[m_leaf] = dists[m_leaf]
_is_leaf = True
else:
# No leaf in voxel scene
_is_leaf = False
if wood_gids is not None:
m_wood = np.isin(gids, wood_gids) & valid_hits_mask
dist_wood[m_wood] = dists[m_wood]
_is_wood = True
else:
# No wood in voxel scene
_is_wood = False
### Combined Stats First ###
# Use some shared variables later for leaf and wood statistics if present
# eff_free_path_length means/vars (ddof=1); compute sums and sums of squares
def mean_var_ddof1(x, N):
mx = x.sum(axis=2)
mean = np.divide(mx, N, out=np.zeros_like(mx), where=(N > 0))
mx2 = (x**2).sum(axis=2)
# var = (sum(x^2) - sum(x)^2 / N) / (N-1)
numer = mx2 - (mx * mx) / np.maximum(N, 1)
denom = np.maximum(N - 1, 1)
var = numer / denom
var[(N <= 1)] = 0.0
return mean, var
# Combined (leaf+wood): first hit distance among the two
if _is_leaf is True or _is_wood is True:
comb_dist = np.minimum(dist_leaf, dist_wood) # (F,A,R)
else:
comb_dist = np.full_like(dists, np.inf, dtype=np.float32)
comb_dist[valid_hits_mask] = dists[valid_hits_mask]
N = valid_rays_mask.sum(axis=2).astype(np.int32) # (F,A)
hit_any = np.isfinite(comb_dist) # (F,A,R)
n_hits_lw = hit_any.sum(axis=2).astype(np.int32) # (F,A)
path_lengths = np.zeros_like(dists, dtype=np.float32)
path_lengths[valid_rays_mask] = (t_far[valid_rays_mask] - t_near[valid_rays_mask])
mean_path_length = np.divide(path_lengths.sum(axis=2), N, out=np.zeros_like(path_lengths.sum(axis=2)), where=(N > 0)) # (F,A)
sum_path_length = path_lengths.sum(axis=2) # (F,A)
free_path_length_comb = path_lengths.copy()
free_path_length_comb[hit_any] = comb_dist[hit_any] - t_near[hit_any]
eff_free_path_length_comb = np.zeros_like(free_path_length_comb, dtype=np.float32)
eff_free_path_length_comb[valid_rays_mask] = compute_efpl_array(free_path_length_comb[valid_rays_mask], lambda_1).astype(np.float32)
sum_eff_free_path_length_comb = np.sum(eff_free_path_length_comb, axis=2)
sum_path_lengths = path_lengths.sum(axis=2) # (F,A)
sum_free_path_length_comb = free_path_length_comb.sum(axis=2) # (F,A)
mean_free_path_length_comb = np.divide(sum_free_path_length_comb, N, out=np.zeros_like(sum_free_path_length_comb), where=(N > 0)) # (F,A)
mean_eff_free_path_length_comb, var_eff_free_path_length_comb = mean_var_ddof1(eff_free_path_length_comb, N)
sum_hits_eff_free_path_length_comb = (eff_free_path_length_comb * hit_any).sum(axis=2)
stats_comb = [[None for _ in range(A)] for _ in range(F)]
for f in range(F):
for a in range(A):
stats_comb[f][a] = dict(
N=int(N[f, a]),
n_hits=int(n_hits_lw[f, a]),
I=(float(n_hits_lw[f, a]) / float(N[f, a])) if N[f, a] else 0.0,
mean_path_length=float(mean_path_length[f, a]),
sum_path_length=float(sum_path_length[f, a]),
sum_free_path_length=float(sum_free_path_length_comb[f, a]),
mean_free_path_length=float(mean_free_path_length_comb[f, a]),
mean_eff_free_path_length=float(mean_eff_free_path_length_comb[f, a]),
var_eff_free_path_length=float(var_eff_free_path_length_comb[f, a]),
sum_eff_free_path_length=float(sum_eff_free_path_length_comb[f, a]),
sum_hits_eff_free_path_length=float(sum_hits_eff_free_path_length_comb[f, a]),
)
### Leaf-only Stats ###
if _is_leaf:
hit_leaf = np.isfinite(dist_leaf) # (F,A,R)
free_path_length_leaf = path_lengths.copy()
free_path_length_leaf[hit_leaf] = dists[hit_leaf] - t_near[hit_leaf]
sum_free_path_length_leaf = free_path_length_leaf.sum(axis=2)
eff_free_path_length_leaf = np.zeros_like(free_path_length_leaf, dtype=np.float32)
eff_free_path_length_leaf[valid_rays_mask] = compute_efpl_array(free_path_length_leaf[valid_rays_mask], lambda_1).astype(np.float32)
sum_eff_free_path_length_leaf = np.sum(eff_free_path_length_leaf, axis=2)
n_hits_leaf = hit_leaf.sum(axis=2).astype(np.int32)
mean_free_path_length_leaf = np.nanmean(free_path_length_leaf, axis=2)
mean_eff_free_path_length_leaf, var_eff_free_path_length_leaf = mean_var_ddof1(eff_free_path_length_leaf, N)
sum_hits_eff_free_path_length_leaf = (eff_free_path_length_leaf * hit_leaf).sum(axis=2)
stats_leaf = [[None for _ in range(A)] for _ in range(F)]
for f in range(F):
for a in range(A):
stats_leaf[f][a] = dict(
N=int(N[f, a]),
n_hits=int(n_hits_leaf[f, a]),
I=(float(n_hits_leaf[f, a]) / float(N[f, a])) if N[f, a] else 0.0,
mean_path_length=float(mean_path_length[f, a]),
sum_path_length=float(sum_path_length[f, a]),
sum_free_path_length=float(sum_free_path_length_leaf[f, a]),
mean_free_path_length=float(mean_free_path_length_leaf[f, a]),
mean_eff_free_path_length=float(mean_eff_free_path_length_leaf[f, a]),
var_eff_free_path_length=float(var_eff_free_path_length_leaf[f, a]),
sum_eff_free_path_length=float(sum_eff_free_path_length_leaf[f, a]),
sum_hits_eff_free_path_length=float(sum_hits_eff_free_path_length_leaf[f, a]),
)
else:
stats_leaf = [[None for _ in range(A)] for _ in range(F)]
for f in range(F):
for a in range(A):
stats_leaf[f][a] = dict(
N=0,
n_hits=0,
I=0.0,
mean_path_length=0.0,
sum_path_length=0.0,
sum_free_path_length=0.0,
mean_free_path_length=0.0,
mean_eff_free_path_length=0.0,
var_eff_free_path_length=0.0,
sum_eff_free_path_length=0.0,
sum_hits_eff_free_path_length=0.0,
)
### Wood-only Stats ###
if _is_wood:
hit_wood = np.isfinite(dist_wood) # (F,A,R)
# free_path_length for wood-only: distance from t_near to wood intersection
free_path_length_wood = path_lengths.copy()
free_path_length_wood[hit_wood] = dists[hit_wood] - t_near[hit_wood]
# Effective free path length transforms (you already have compute_efpl_array)
# Compute only on valid rays to avoid NaNs
eff_free_path_length_path = np.zeros_like(path_lengths, dtype=np.float32)
eff_free_path_length_wood = np.zeros_like(free_path_length_wood, dtype=np.float32)
eff_free_path_length_wood[valid_rays_mask] = compute_efpl_array(free_path_length_wood[valid_rays_mask], lambda_1).astype(np.float32)
n_hits_wood = hit_wood.sum(axis=2).astype(np.int32) # (F,A)
sum_free_path_length_wood = free_path_length_wood.sum(axis=2) # (F,A)
mean_free_path_length_wood = np.divide(sum_free_path_length_wood, N, out=np.zeros_like(sum_free_path_length_wood), where=(N > 0))
mean_eff_free_path_length_wood, var_eff_free_path_length_wood = mean_var_ddof1(eff_free_path_length_wood, N)
sum_hits_eff_free_path_length_wood = (eff_free_path_length_wood * hit_wood).sum(axis=2)
stats_wood= [[None for _ in range(A)] for _ in range(F)]
for f in range(F):
for a in range(A):
stats_wood[f][a] = dict(
N=int(N[f, a]),
n_hits=int(n_hits_wood[f, a]),
I=(float(n_hits_wood[f, a]) / float(N[f, a])) if N[f, a] else 0.0,
mean_path_length=float(mean_path_length[f, a]),
sum_path_length=float(sum_path_length[f, a]),
sum_free_path_length=float(sum_free_path_length_wood[f, a]),
mean_free_path_length=float(mean_free_path_length_wood[f, a]),
mean_eff_free_path_length=float(mean_eff_free_path_length_wood[f, a]),
var_eff_free_path_length=float(var_eff_free_path_length_wood[f, a]),
sum_eff_free_path_length=float((eff_free_path_length_wood).sum(axis=2)[f, a]),
sum_hits_eff_free_path_length=float(sum_hits_eff_free_path_length_wood[f, a]),
mean_eff_free_path_length_free=float(mean_eff_free_path_length_wood[f, a]),
var_eff_free_path_length_free=float(var_eff_free_path_length_wood[f, a])