-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy path01_end_to_end_training.py
More file actions
3294 lines (2688 loc) · 150 KB
/
Copy path01_end_to_end_training.py
File metadata and controls
3294 lines (2688 loc) · 150 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 glob
import json
import time
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.utils.data import Dataset, DataLoader, random_split, Subset
from torch.utils.tensorboard import SummaryWriter
from loguru import logger
from tqdm import tqdm
import trimesh
from trimesh.smoothing import laplacian_calculation
from scipy.spatial.transform import Rotation
from scipy.spatial import KDTree
import scipy.sparse as sp
import viser
import viser.transforms as tf
from pymotion.io.bvh import BVH
from pymotion.ops.skeleton import fk
import pymotion.rotations.ortho6d as sixd
import pymotion.rotations.quat as quat
import pymotion.rotations.quat_torch as quat_torch
import pymotion.ops.skeleton as sk
# Quick class to calculate prisms volume
class PrismVolumeLoss(torch.nn.Module):
def __init__(self):
super().__init__()
# Gauss-Legendre Quadrature Constants
self.inv_sqrt3 = 0.5773502691896257
self.t1 = 0.5 * (1.0 - self.inv_sqrt3)
self.t2 = 0.5 * (1.0 + self.inv_sqrt3)
self.alpha = 1.0 / 3.0
self.beta = 1.0 / 3.0
self.gamma = 1.0 / 3.0
def compute_prism_volume(self, inner_verts, outer_verts, faces):
"""
Calculates exact prism volume using 2-point Gauss Quadrature.
inner_verts: (B, V, 3) or (V, 3) - e.g., Bone or Muscle
outer_verts: (B, V, 3) or (V, 3) - e.g., Muscle or Skin
faces: (F, 3) - Corresponding valid topology
"""
f0, f1, f2 = faces[:, 0], faces[:, 1], faces[:, 2]
# Gather vertices: (..., F, 3)
x1 = inner_verts[..., f0, :]
x2 = inner_verts[..., f1, :]
x3 = inner_verts[..., f2, :]
x4 = outer_verts[..., f0, :]
x5 = outer_verts[..., f1, :]
x6 = outer_verts[..., f2, :]
def compute_detJ(xi_scalar):
# 1. Derivatives wrt local coords (a, b)
dx_da = xi_scalar * (x1 - x3) + (1.0 - xi_scalar) * (x4 - x6)
dx_db = xi_scalar * (x2 - x3) + (1.0 - xi_scalar) * (x5 - x6)
# 2. Derivative wrt thickness (xi)
dx_dxi = self.alpha * (x1 - x4) + self.beta * (x2 - x5) + self.gamma * (x3 - x6)
# 3. Determinant of Jacobian via Scalar Triple Product
cross_prod = torch.cross(dx_db, dx_dxi, dim=-1)
return torch.sum(dx_da * cross_prod, dim=-1)
detJ_1 = compute_detJ(self.t1)
detJ_2 = compute_detJ(self.t2)
# No .abs() here. We want negative volume if inverted!
return 0.25 * (detJ_1 + detJ_2)
def forward(self, curr_inner_verts, curr_outer_verts, rest_volume, faces):
# 1. Compute current signed volume
curr_vol = self.compute_prism_volume(curr_inner_verts, curr_outer_verts, faces)
# Squeeze rest_volume to 1D (F,)
rest_vol_1d = rest_volume.squeeze()
# Safety mask: Ignore perfectly welded/flat geometry to prevent division by zero
valid_mask = rest_vol_1d.abs() > 1e-7
if valid_mask.sum() == 0:
return torch.tensor(0.0, device=curr_inner_verts.device)
curr_vol_valid = curr_vol[:, valid_mask]
rest_vol_valid = rest_vol_1d[valid_mask]
# 2. Calculate Absolute Volume Difference: (V - V0)
diff = curr_vol_valid - rest_vol_valid
# 3. Create a Numerically Safe Denominator
# We add 10% of the mean absolute volume to the denominator.
# For thick muscles, |V0| dominates (matching the paper perfectly).
# For paper-thin tissues, it prevents division by zero/singularity explosions.
mean_vol = rest_vol_valid.abs().mean().clamp(min=1e-8)
safe_denom = rest_vol_valid.abs() + (0.1 * mean_vol)
# 4. Final Energy Calculation: (V - V0)^2 / (|V0| + epsilon)
weighted_error = diff.pow(2) / safe_denom
# MEAN over the mesh, Mean over the batch
return weighted_error.mean()
# # 3. Create a Numerically Safe Denominator
# mean_vol = rest_vol_valid.abs().mean().clamp(min=1e-8)
# safe_denom = rest_vol_valid.abs() + (0.1 * mean_vol)
# # 4. Final Energy Calculation: Energy Density scaled for the optimizer
# # We multiply by 1e6 to bring the microscopic volumes into balance with data loss
# weighted_error = (diff.pow(2) / safe_denom) * 1e6
# return weighted_error.mean()
# --- VIZ FUNCTIONS ---
def visualize_output(p_bind, residuals_gt, p_pred, skin_layer, musc_layer, posed_joints, parents, current_m_final=None, current_s_final=None, d_muscle=None, rest_vol_skin=None):
"""
Visualizes the model output.
- If target_muscle_id is Set: Shows only that muscle (Red prediction, Colored GT).
- If target_muscle_id is None: Shows ALL muscles with unique palette colors.
- current_m_final: (V, 3) numpy array of the DEFORMED mesh. If None, shows static mesh.
"""
logger.info("--- LAUNCHING DEBUG VISUALIZATION ---")
print("\nOpen your browser to http://localhost:8080")
server = viser.ViserServer()
server.scene.add_grid("grid", plane="xz")
server.scene.set_up_direction("+y")
BLACK = [0, 0, 0]
RED = [255, 0, 0]
GRAY = [50, 50, 50]
GREEN = [0, 255, 0]
CYAN = [0, 255, 255]
BLUE = [0, 0, 255]
YELLOW = [255, 255, 0]
MAGENTA = [255, 0, 255]
# --- 1. Select Data (Deformed vs Rest) ---
if current_m_final is not None and current_s_final is not None:
logger.info("[VIZ] Visualizing DEFORMED state.")
m_verts = current_m_final
s_verts = current_s_final
# Topology comes from the bind layers
m_faces = musc_layer.faces
s_faces = skin_layer.faces
else:
logger.info("[VIZ] Visualizing REST/BIND state (Deformed data missing).")
m_verts = musc_layer.vertices
s_verts = skin_layer.vertices
m_faces = musc_layer.faces
s_faces = skin_layer.faces
# Muscle Layer (Inner) - Red Wireframe
server.scene.add_mesh_simple(
name="/bind/muscle_layer",
vertices=musc_layer.vertices,
faces=musc_layer.faces,
color=(200, 50, 50),
wireframe=True,
opacity=0.4
)
# Skin Layer (Outer) - Blue Wireframe
server.scene.add_mesh_simple(
name="/bind/skin_layer",
vertices=skin_layer.vertices,
faces=skin_layer.faces,
color=(50, 50, 200),
wireframe=True,
opacity=0.4
)
# Skeleton
bone_points = []
for i, p_idx in enumerate(parents):
if p_idx != -1:
bone_points.append([posed_joints[p_idx], posed_joints[i]])
server.scene.add_line_segments("/posed_skeleton/bones", np.array(bone_points), colors=(0, 0, 255))
# Colors
# gt_marker_colors = np.tile(BLACK, (len(p_bind), 1)).astype(np.uint8)
# pred_marker_colors = np.tile(BLACK, (len(p_bind), 1)).astype(np.uint8)
# Ground Truth Markers
p_gt = p_bind + residuals_gt
server.scene.add_point_cloud(
"/p_bind + residuals_gt",
points=p_gt,
colors=GREEN,
point_size=0.003
)
# Prediction
server.scene.add_point_cloud(
"/p_bind + delta_pred_tpose",
points=p_pred,
colors=BLACK,
point_size=0.003
)
if current_m_final is not None:
# Display the muscle mesh in the rest pose (Model Step 2)
server.scene.add_mesh_simple(
name="/current_m_final",
vertices=current_m_final,
faces=musc_layer.faces,
color=RED, # Red
wireframe = False
)
server.scene.add_mesh_simple(
name="/current_s_final",
vertices=current_s_final,
faces=skin_layer.faces,
color=GRAY,
wireframe = False
)
# =========================================================
# --- NEW: PRISM VISUALIZATION ---
# =========================================================
if rest_vol_skin is not None:
logger.info("[VIZ] Rendering Volume Prisms...")
# This matches the threshold inside PrismVolumeLoss
valid_prism_threshold = 1e-7
# 1. Determine Valid vs Invalid Faces based on Rest Volume
rest_vol_1d = rest_vol_skin.squeeze().cpu().numpy()
valid_face_mask = np.abs(rest_vol_1d) > valid_prism_threshold
faces_np = musc_layer.faces
valid_faces = faces_np[valid_face_mask]
invalid_faces = faces_np[~valid_face_mask]
# 2. Determine Valid vs Invalid Vertices for rendering connections
valid_vert_ids = np.unique(valid_faces)
all_vert_ids = np.arange(len(current_m_final))
invalid_vert_ids = np.setdiff1d(all_vert_ids, valid_vert_ids)
# 3. Draw Valid Connections (Green)
if len(valid_vert_ids) > 0:
m_valid = current_m_final[valid_vert_ids]
s_valid = current_s_final[valid_vert_ids]
lines_valid = np.stack([m_valid, s_valid], axis=1) # (N, 2, 3)
server.scene.add_line_segments(
name="/prisms/valid_tissue_connections",
points=lines_valid,
colors=(0, 255, 0), # Green = Healthy Volume
line_width=1.0,
)
# 4. Draw Invalid Connections (Red) - Ignored by volume loss
if len(invalid_vert_ids) > 0:
m_invalid = current_m_final[invalid_vert_ids]
s_invalid = current_s_final[invalid_vert_ids]
lines_invalid = np.stack([m_invalid, s_invalid], axis=1)
server.scene.add_line_segments(
name="/prisms/degenerate_connections",
points=lines_invalid,
colors=(255, 0, 0), # Red = Degenerate/Thin Volume
line_width=2.0,
)
# 5. Highlight specific prisms for close inspection
def draw_single_prism(f_idx, prefix, color_m, color_s, color_line):
face_indices = faces_np[f_idx]
m_v = current_m_final[face_indices]
s_v = current_s_final[face_indices]
single_face = np.array([[0, 1, 2]], dtype=np.int32)
# Muscle Base Triangle
server.scene.add_mesh_simple(
name=f"/prisms/inspect_{prefix}/muscle_base",
vertices=m_v, faces=single_face, color=color_m, opacity=1.0
)
# Skin Top Triangle
server.scene.add_mesh_simple(
name=f"/prisms/inspect_{prefix}/skin_top",
vertices=s_v, faces=single_face, color=color_s, opacity=1.0
)
# Vertical Connections
lines = np.stack([m_v, s_v], axis=1)
server.scene.add_line_segments(
name=f"/prisms/inspect_{prefix}/connections",
points=lines, colors=color_line, line_width=4.0
)
# Draw one random healthy prism and one random degenerate prism
if valid_faces.shape[0] > 0:
valid_f_idx = np.random.choice(np.nonzero(valid_face_mask)[0])
draw_single_prism(valid_f_idx, "valid", (0,200,0), (50,255,50), (255,255,0))
if invalid_faces.shape[0] > 0:
invalid_f_idx = np.random.choice(np.nonzero(~valid_face_mask)[0])
draw_single_prism(invalid_f_idx, "degenerate", (200,0,0), (255,50,50), (255,100,100))
while True:
time.sleep(0.1)
# --- MODEL FUNCTIONS ---
def lbs_working_batch_rotmat(vertices, rot_mats, weights, j_rest, parents, root_position):
"""
LBS given rotation matrices.
vertices: (B,V,3), rot_mats: (B,J,3,3), weights: (V,J), j_rest: (J,3), parents: (J,), root_position: (B,3)
"""
batch_size = vertices.shape[0]
num_joints = j_rest.shape[0]
device = vertices.device
# Align dtypes for numerical equivalence
weights = weights.to(vertices.dtype)
j_rest = j_rest.to(vertices.dtype)
root_position = root_position.to(vertices.dtype)
ident4 = torch.eye(4, device=device, dtype=vertices.dtype).unsqueeze(0).repeat(batch_size, 1, 1)
G_rest = torch.zeros(batch_size, num_joints, 4, 4, device=device, dtype=vertices.dtype)
for i in range(num_joints):
if parents[i] == -1:
T = ident4.clone()
T[:, :3, 3] = j_rest[i]
else:
off = (j_rest[i] - j_rest[parents[i]]).unsqueeze(0)
T_off = ident4.clone()
T_off[:, :3, 3] = off
T = G_rest[:, parents[i]] @ T_off
G_rest[:, i] = T
G_rest_inv = torch.inverse(G_rest)
G_posed = torch.zeros_like(G_rest)
for i in range(num_joints):
T_local = ident4.clone()
T_local[:, :3, :3] = rot_mats[:, i]
if parents[i] == -1:
T_local[:, :3, 3] = root_position
G_posed[:, i] = T_local
else:
T_local[:, :3, 3] = (j_rest[i] - j_rest[parents[i]]).unsqueeze(0)
G_posed[:, i] = G_posed[:, parents[i]] @ T_local
skinning = G_posed @ G_rest_inv
homo = torch.cat([vertices, torch.ones(batch_size, vertices.shape[1], 1, device=device, dtype=vertices.dtype)], dim=-1)
blended = torch.einsum('vj,bjmn->bvmn', weights, skinning)
out = blended @ homo.unsqueeze(-1)
return out[:, :, :3, 0]
def barycentric_interpolation_batch(deformed_vertices, bary_verts, bary_weights):
"""
Calculates the 3D positions of markers based on barycentric coordinates.
Args:
deformed_vertices (torch.Tensor): Deformed mesh vertices. Shape: (batch_size, num_vertices, 3)
bary_verts (torch.Tensor): Vertex indices for each marker. Shape: (num_markers, 3)
bary_weights (torch.Tensor): Barycentric weights for each marker. Shape: (num_markers, 3)
Returns:
torch.Tensor: Predicted 3D marker positions. Shape: (batch_size, num_markers, 3)
"""
# Gather the vertices for each marker's triangle
# bary_verts has shape (num_markers, 3). deformed_vertices has shape (batch_size, num_markers, 3).
# We want to select vertices along the Ns dimension.
v0 = deformed_vertices[:, bary_verts[:, 0], :] # Shape: (batch_size, num_markers, 3)
v1 = deformed_vertices[:, bary_verts[:, 1], :] # Shape: (batch_size, num_markers, 3)
v2 = deformed_vertices[:, bary_verts[:, 2], :] # Shape: (batch_size, num_markers, 3)
# Apply the barycentric weights to interpolate the marker positions
# bary_weights has shape (num_markers, 3). We broadcast it to (batch_size, num_markers, 3) for batch processing.
interpolated_positions = (
bary_weights[:, 0].unsqueeze(0).unsqueeze(-1) * v0 +
bary_weights[:, 1].unsqueeze(0).unsqueeze(-1) * v1 +
bary_weights[:, 2].unsqueeze(0).unsqueeze(-1) * v2
)
return interpolated_positions # Shape: (batch_size, num_markers, 3)
# --- TRANSFORMATION FUNCTIONS ---
def _rot_x(points, deg=0.0):
R = Rotation.from_euler('x', deg, degrees=True).as_matrix()
return (points @ R.T)
def _rot_y(points, deg=0.0):
R = Rotation.from_euler('y', deg, degrees=True).as_matrix()
return (points @ R.T)
def _rot_z(points, deg=0.0):
R = Rotation.from_euler('z', deg, degrees=True).as_matrix()
return (points @ R.T)
def rotate_points_x(points, angle_deg=-90):
"""Rotates points around X-axis."""
theta = np.radians(angle_deg)
c, s = np.cos(theta), np.sin(theta)
# Rotation Matrix for X-axis
R = np.array([
[1, 0, 0],
[0, c, -s],
[0, s, c]
], dtype=points.dtype)
return points @ R.T
def move_tensors_to_device(tensor_dict, device):
"""
Moves a dictionary of tensors to the specified device.
Gracefully handles None values and non-tensor types.
Args:
tensor_dict (dict): Dictionary of {name: tensor} pairs
device: PyTorch device (cuda, cpu, etc.)
Returns:
dict: Dictionary with all PyTorch tensors moved to device
Example:
tensors = {
'vertices': vertex_tensor,
'weights': weight_tensor,
'mask': None # Skipped
}
gpu_tensors = move_tensors_to_device(tensors, device)
"""
device_dict = {}
for key, value in tensor_dict.items():
if value is not None and isinstance(value, torch.Tensor):
device_dict[key] = value.to(device)
else:
device_dict[key] = value
return device_dict
def sixd_to_rotmat(sixd_reps):
"""
Converts 6D rotation representation to 3x3 rotation matrices.
Input: (B, J, 6)
Output: (B, J, 3, 3)
"""
x_raw = sixd_reps[..., 0:3]
y_raw = sixd_reps[..., 3:6]
x = F.normalize(x_raw, dim=-1)
z = torch.cross(x, y_raw, dim=-1)
z = F.normalize(z, dim=-1)
y = torch.cross(z, x, dim=-1)
# Stack columns to form matrix
matrix = torch.stack((x, y, z), dim=-1)
return matrix
# --- LBS FUNCTIONS ---
def convert_weights_to_npy(json_path, num_rows, output_path, bvh_joint_names, is_skin=True, canonical_ids=None):
"""
Generic function to convert skin or marker weights to a dense .npy matrix,
using bone names to ensure correct joint ordering.
"""
logger.debug(f"[LBS] Converting weights from {os.path.basename(json_path)} to .npy...")
with open(json_path, 'r') as f:
weights_data = json.load(f)
num_joints = len(bvh_joint_names)
# Create a lookup map from name to the correct index for this BVH
joint_name_to_index = {name: i for i, name in enumerate(bvh_joint_names)}
weights_matrix = np.zeros((num_rows, num_joints), dtype=np.float32)
data_source = weights_data if is_skin else weights_data.items()
if is_skin:
# Assuming the skin weights JSON is a list of dicts, ordered by vertex index
for v_idx, vertex_info in enumerate(weights_data):
if v_idx >= num_rows: continue
bone_names = vertex_info.get("bone_names", [])
weights = vertex_info.get("weights", [])
for bone_name, weight in zip(bone_names, weights):
if bone_name in joint_name_to_index:
correct_joint_idx = joint_name_to_index[bone_name]
weights_matrix[v_idx, correct_joint_idx] = weight
else: # Markers
marker_id_to_index = {marker_id: i for i, marker_id in enumerate(canonical_ids)}
for marker_id, data in data_source:
if marker_id in marker_id_to_index:
v_idx = marker_id_to_index[marker_id]
bone_names = data.get("bone_names", [])
weights = data.get("weights", [])
for bone_name, weight in zip(bone_names, weights):
if bone_name in joint_name_to_index:
correct_joint_idx = joint_name_to_index[bone_name]
weights_matrix[v_idx, correct_joint_idx] = weight
np.save(output_path, weights_matrix)
logger.debug(f"[LBS] Successfully converted and saved weights to {output_path}")
return weights_matrix
# --- SKELETON FUNCTIONS ---
def get_rest_joint_locations_zero_offset(bvh_obj, scale=1.0):
"""
Calculates the global joint positions for the rest pose from the BVH skeleton.
The root joint offset is set to zero, so the root pivot is at the origin.
"""
_, _, parents, offsets, _, _ = bvh_obj.get_data()
# Set root to -1
parents[0] = -1
for i, parent in enumerate(parents):
if parent == i:
raise ValueError(f"Joint {i} is its own parent!")
if parent >= len(parents):
raise ValueError(f"Invalid parent index {parent} for joint {i}!")
# Make a local copy of offsets and zero the root (hips) rest offset so the root pivot is at the origin
# This is done such as the hips has a zero offset in the rest pose
offsets = offsets.copy()
if offsets.shape[0] > 0:
offsets[0] = np.zeros(3, dtype=offsets.dtype)
offsets *= scale
j_rest = np.zeros_like(offsets)
for i in range(len(parents)):
if parents[i] == -1:
j_rest[i] = offsets[i]
# print("Joint", i, "is root offset", offsets[i], "rest pos", j_rest[i])
else:
j_rest[i] = j_rest[parents[i]] + offsets[i]
# print("Joint", i, "parent", parents[i], "offset", offsets[i], "rest pos", j_rest[i])
return j_rest, parents, offsets
def get_rest_joint_locations(bvh_obj, scale=1.0):
"""
Calculates the global joint positions for the rest pose from the BVH skeleton.
"""
_, _, parents, offsets, _, _ = bvh_obj.get_data()
# Set root to -1
parents[0] = -1
for i, parent in enumerate(parents):
if parent == i:
raise ValueError(f"Joint {i} is its own parent!")
if parent >= len(parents):
raise ValueError(f"Invalid parent index {parent} for joint {i}!")
offsets *= scale
j_rest = np.zeros_like(offsets)
for i in range(len(parents)):
if parents[i] == -1:
j_rest[i] = offsets[i]
# print("Joint", i, "is root offset", offsets[i], "rest pos", j_rest[i])
else:
j_rest[i] = j_rest[parents[i]] + offsets[i]
# print("Joint", i, "parent", parents[i], "offset", offsets[i], "rest pos", j_rest[i])
return j_rest, parents, offsets
# --- MESH FUNCTIONS ---
def compute_vertex_stability_mask(m_bind, s_bind, faces, threshold=1e-7):
"""
Creates a (V, 1) mask based on the exact prism volume.
1.0 = Vertex belongs to a thick area (Volume > threshold), allowed to deform.
0.0 = Vertex belongs to a thin/degenerate area (Volume <= threshold), PINNED.
"""
device = m_bind.device
# 1. Gather Prism Vertices
f0, f1, f2 = faces[:, 0], faces[:, 1], faces[:, 2]
x1 = m_bind[f0]; x2 = m_bind[f1]; x3 = m_bind[f2]
x4 = s_bind[f0]; x5 = s_bind[f1]; x6 = s_bind[f2]
# 2. Compute exact volume using 2-point Gauss Quadrature (syncs perfectly with loss)
inv_sqrt3 = 0.5773502691896257
t1 = 0.5 * (1.0 - inv_sqrt3)
t2 = 0.5 * (1.0 + inv_sqrt3)
alpha = beta = gamma = 1.0 / 3.0
def compute_detJ(xi_scalar):
dx_da = xi_scalar * (x1 - x3) + (1.0 - xi_scalar) * (x4 - x6)
dx_db = xi_scalar * (x2 - x3) + (1.0 - xi_scalar) * (x5 - x6)
dx_dxi = alpha * (x1 - x4) + beta * (x2 - x5) + gamma * (x3 - x6)
return torch.sum(dx_da * torch.cross(dx_db, dx_dxi, dim=-1), dim=-1)
# Calculate exact rest volume per face
face_volumes = 0.25 * (compute_detJ(t1) + compute_detJ(t2))
# 3. Identify Valid Prisms using your exact threshold
valid_prism_mask = face_volumes.abs() > threshold
# 4. Map Valid Prisms to Vertices
num_verts = m_bind.shape[0]
vertex_mask = torch.zeros(num_verts, 1, device=device)
# Get all unique vertex indices that belong to thick faces
valid_faces = faces[valid_prism_mask]
valid_indices = torch.unique(valid_faces)
# Set those vertices to 1.0 (allow deformation)
vertex_mask[valid_indices] = 1.0
return vertex_mask
def load_obj_simple(file_path):
"""
A simple, robust OBJ loader that only reads vertex positions and faces.
Guarantees vertex count matches the 'v' lines.
"""
vertices = []
faces = []
with open(file_path, 'r') as f:
for line in f:
if line.startswith('v '):
vertices.append([float(i) for i in line.strip().split()[1:]])
elif line.startswith('f '):
face = [int(i.split('/')[0]) - 1 for i in line.strip().split()[1:]]
faces.append(face)
return np.array(vertices, dtype=np.float32), np.array(faces, dtype=np.int32)
def load_and_stack_muscles(muscle_dir, file_pattern="*.obj"):
"""
Loads individual muscle meshes, stacks them into a single vertex/face array
for the model, and builds a Block-Diagonal Laplacian for regularization.
Returns:
merged_vertices (np.array): (Total_V, 3)
merged_faces (np.array): (Total_F, 3)
L_block_diag (scipy.sparse): (Total_V, Total_V) Block Diagonal Matrix
muscle_masks (dict): {muscle_name: (start_index, end_index)}
"""
mesh_files = sorted(glob.glob(os.path.join(muscle_dir, file_pattern)))
if not mesh_files:
raise ValueError(f"No muscle files found in {muscle_dir}")
all_vertices = []
all_faces = []
laplacians = []
muscle_vertex_ranges = {} # To store start/end indices for each muscle
muscle_face_ranges = {} # To store start/end indices for each muscle
vertex_offset = 0
face_offset = 0
logger.info(f"[MESH] FOUND {len(mesh_files)} INDEPENDENT MUSCLES. STACKING...")
for f_path in mesh_files:
muscle_name = os.path.basename(f_path).split('.')[0]
# Load individual mesh
# [FIX] We MUST merge vertices.
# Raw OBJs have duplicate vertices at UV seams. If we don't weld them,
# the NN lookup picks one, moves it, and leaves the duplicate behind, tearing the mesh.
mesh = trimesh.load(f_path, process=False)
mesh.merge_vertices()
# 1. Store Vertices
current_verts = mesh.vertices
all_vertices.append(current_verts)
# 2. Store Faces (offset by current vertex count to keep unique indices)
all_faces.append(mesh.faces + vertex_offset)
# 3. Calculate Independent Laplacian (Uniform is safer)
# This Laplacian ONLY knows about this specific muscle.
# [FIX] Use cotangent weights if possible for better physics, but uniform is stable
L_sub = laplacian_calculation(mesh, equal_weight=True)
laplacians.append(L_sub)
# 4. Store Ranges for VERTICES
num_verts = len(current_verts)
muscle_vertex_ranges[muscle_name] = (vertex_offset, vertex_offset + num_verts)
# 5. Store Ranges for FACES
num_faces = len(mesh.faces)
muscle_face_ranges[muscle_name] = (face_offset, face_offset + num_faces)
logger.debug(f"[MESH] Added {muscle_name}: vertices [{vertex_offset}, {vertex_offset + num_verts}]!")
vertex_offset += num_verts
face_offset += num_faces
# --- MERGE FOR MODEL ---
# Stack all vertices into (Total_V, 3)
merged_vertices = np.vstack(all_vertices).astype(np.float32)
# Stack all faces into (Total_F, 3)
merged_faces = np.vstack(all_faces).astype(np.int32)
# --- MERGE FOR REGULARIZATION ---
# Create a Block Diagonal Matrix
# [ L_1 0 0 ]
# [ 0 L_2 0 ]
# [ 0 0 L_3 ]
# This ensures smoothness can NEVER propagate between muscles.
L_block_diag = sp.block_diag(laplacians, format='coo')
return merged_vertices, merged_faces, L_block_diag, muscle_vertex_ranges, muscle_face_ranges
def calculate_vertex_mass(trimesh_mesh, device):
"""
Calculates the per-vertex area (Mass Matrix diagonal) for a Trimesh object.
Uses Barycentric Area (1/3 of incident face areas) for stability.
"""
# 1. Get Face Areas from Trimesh (make a copy to avoid read-only warning)
face_areas = torch.from_numpy(trimesh_mesh.area_faces.copy()).float().to(device) # (F,)
# 2. Get Faces
faces = torch.from_numpy(trimesh_mesh.faces).long().to(device) # (F, 3)
# 3. Scatter add face areas to vertices
num_verts = len(trimesh_mesh.vertices)
vertex_areas = torch.zeros(num_verts, device=device)
# Add 1/3 of face area to each of the 3 vertices
val = face_areas / 3.0
# Scatter for each column of the faces
vertex_areas.scatter_add_(0, faces[:, 0], val)
vertex_areas.scatter_add_(0, faces[:, 1], val)
vertex_areas.scatter_add_(0, faces[:, 2], val)
return vertex_areas
def compute_edge_weights(trimesh_mesh):
"""
Calculates area-based weights for edges to ensure discretization invariance.
Formula: weight_edge = (area_face_A + area_face_B) / 3
Args:
trimesh_mesh: The loaded Trimesh object.
device: Torch device.
Returns:
edge_weights: (Num_Edges,) float tensor, normalized to sum to 1.0 (optional but recommended).
"""
# 1. Get Face Areas (F,)
face_areas = trimesh_mesh.area_faces
# 2. Get the mapping from Faces to Unique Edges (F, 3)
# This gives us the 3 global edge indices for every face
face_edges = trimesh_mesh.faces_unique_edges
# 3. Accumulate Area to Edges
num_edges = len(trimesh_mesh.edges_unique)
edge_weights_np = np.zeros(num_edges, dtype=np.float32)
# Iterate over the 3 edges of every face
# We add area/3 to each incident edge.
# Since an internal edge is shared by 2 faces, it will sum (area_A/3 + area_B/3).
# This perfectly matches the paper formula.
val = face_areas / 3.0
# We use numpy.add.at for unbuffered summation (like scatter_add)
# Flatten face_edges to (F*3,) and repeat val 3 times
np.add.at(edge_weights_np, face_edges.flatten(), np.repeat(val, 3))
# 4. Normalize (Optional, but good for learning rate stability)
# We normalize so the sum of weights is 1.0 (or num_edges, depending on preference).
# Using Sum=1 makes the loss independent of mesh resolution.
sum_weights = np.sum(edge_weights_np) + 1e-8
edge_weights_np /= sum_weights
return torch.from_numpy(edge_weights_np).float()
def compute_edge_lengths(verts, edges):
"""Computes the length of every edge in the mesh."""
# Ensure edges is a writable array
if isinstance(edges, np.ndarray) and not edges.flags.writeable:
edges = edges.copy()
p1 = verts[:, edges[:, 0], :]
p2 = verts[:, edges[:, 1], :]
return torch.norm(p1 - p2, dim=-1)
def compute_mesh_properties(trimesh_obj, device):
"""
Computes all geometric properties for a mesh (edges, areas, normals, Laplacian).
Args:
trimesh_obj: Trimesh object
device: PyTorch device
Returns:
Dictionary containing:
- 'vertices_np': (V, 3) numpy vertices
- 'faces_np': (F, 3) numpy faces
- 'vertices': (V, 3) torch tensor
- 'faces': (F, 3) torch tensor
- 'edges': (E, 2) numpy edge indices
- 'edge_rest_lengths': (E,) numpy edge rest lengths
- 'edge_weights': (E,) torch normalized edge weights
- 'face_rest_areas': (F,) torch face areas
- 'normals': (V, 3) torch vertex normals
- 'vertex_mass': (V,) torch vertex areas
- 'laplacian_sp': scipy sparse Laplacian matrix
- 'laplacian': torch sparse Laplacian tensor
- 'laplacian_degree': (V,) torch Laplacian diagonal
"""
# --- BASIC GEOMETRY ---
vertices_np = trimesh_obj.vertices.astype(np.float32)
faces_np = trimesh_obj.faces.astype(np.int32)
vertices = torch.from_numpy(vertices_np).float()
faces = torch.from_numpy(faces_np).long()
# --- EDGES ---
edges_np = trimesh_obj.edges_unique # (E, 2)
# Calculate rest edge lengths
v0 = vertices_np[edges_np[:, 0]]
v1 = vertices_np[edges_np[:, 1]]
edge_rest_lengths = np.linalg.norm(v0 - v1, axis=1).astype(np.float32)
# Calculate edge weights (area-based)
edge_weights = compute_edge_weights(trimesh_obj)
# --- FACE AREAS ---
v0 = vertices[faces[:, 0]]
v1 = vertices[faces[:, 1]]
v2 = vertices[faces[:, 2]]
e1 = v1 - v0
e2 = v2 - v0
cross_prod = torch.cross(e1, e2, dim=1)
face_rest_areas = 0.5 * torch.norm(cross_prod, dim=1)
# --- VERTEX NORMALS ---
normals_np = trimesh_obj.vertex_normals.astype(np.float32)
normals = torch.from_numpy(normals_np).float()
# --- VERTEX MASS (Barycentric areas) ---
vertex_mass = calculate_vertex_mass(trimesh_obj, device)
# --- LAPLACIAN ---
laplacian_sp = laplacian_calculation(trimesh_obj, equal_weight=True)
# --- FACE ADJACENCY (For Normal Consistency) ---
face_adjacency_np = trimesh_obj.face_adjacency
face_adjacency = torch.from_numpy(face_adjacency_np).long()
# Convert to Sparse Torch Tensor
indices = np.vstack((laplacian_sp.tocoo().row, laplacian_sp.tocoo().col))
values = laplacian_sp.tocoo().data
laplacian = torch.sparse_coo_tensor(
torch.from_numpy(indices).long(),
torch.from_numpy(values).float(),
torch.Size(laplacian_sp.shape)
).coalesce()
# Extract diagonal (degree) with safety clamp
laplacian_degree_np = laplacian_sp.tocsr().diagonal()
laplacian_degree_np = np.maximum(laplacian_degree_np, 1.0) # Prevent division by zero
laplacian_degree = torch.from_numpy(laplacian_degree_np).float()
return {
'vertices_np': vertices_np,
'faces_np': faces_np,
'vertices': vertices,
'faces': faces,
'edges': edges_np,
'edge_rest_lengths': edge_rest_lengths,
'edge_weights': edge_weights,
'face_rest_areas': face_rest_areas,
'normals': normals,
'vertex_mass': vertex_mass,
'face_adjacency': face_adjacency,
'laplacian_sp': laplacian_sp,
'laplacian': laplacian,
'laplacian_degree': laplacian_degree
}
# --- CONFIGURATION ---
# Centralized config to keep parameters organized
CONFIG = {
"subject": "S1",
# Paths (We will build absolute paths dynamically below)
"base_path_suffix": r"static00",
# Training Hyperparameters
# "learning_rate": 1e-3,
"learning_rate": 1e-4,
"epochs": 20,
"batch_size": 128,
# "weight_decay": 1e-4,
"weight_decay": 0.0,
"train_split": 0.9,
"architecture": "mlp", # Options: "linear", "mlp", "unet"
# System
"device": "cuda" if torch.cuda.is_available() else "cpu",
"num_workers": 4, # Set to 0 if using RAM loading (faster), else 4
"preload_to_ram": False, # CRITICAL OPTIMIZATION: Load all .npy to RAM
"testing_dataset": False,
# Modes
"overfit_single": False, # Train on 1 frame only
"overfit_multiple": False, # Train on first 300 frames only
"viz_enabled": False, # Enable Viser visualization
"checkpoint_path": None # Path to the file just saved}
}
# --- LOSS WEIGHT PRESETS ---
# Add new presets here. Change ACTIVE_PRESET to switch between them.
# Keys: w_data, w_smooth_musc/skin, w_biharmonic_musc/skin, w_spring_musc/skin,
# w_tangent_musc/skin, w_vol_musc/skin
LAMBDAS_PRESETS = {
# All losses enabled at high weights
"full": {
"w_data": 50,
"w_smooth_musc": 100, "w_smooth_skin": 200,
"w_biharmonic_musc": 100, "w_biharmonic_skin": 200,
"w_spring_musc": 1000, "w_spring_skin": 1000,
"w_tangent_musc": 1, "w_tangent_skin": 0.1,
"w_vol_musc": 1000, "w_vol_skin": 1000,
},
# Ablation: remove vector losses (E_smooth, E_tan)
"no_smooth_tan": {
"w_data": 1,
"w_smooth_musc": 0, "w_smooth_skin": 0,
"w_biharmonic_musc": 1, "w_biharmonic_skin": 2.5,
"w_spring_musc": 1, "w_spring_skin": 1,
"w_tangent_musc": 0, "w_tangent_skin": 0,
"w_vol_musc": 10, "w_vol_skin": 10,
},
# Ablation: remove all physics losses (E_bi, E_spring, E_vol)
"no_physics": {
"w_data": 1,
"w_smooth_musc": 0.01, "w_smooth_skin": 0.05,
"w_biharmonic_musc": 0, "w_biharmonic_skin": 0,
"w_spring_musc": 0, "w_spring_skin": 0,
"w_tangent_musc": 1, "w_tangent_skin": 0.1,
"w_vol_musc": 0, "w_vol_skin": 0,
},
# Ablation: remove volume loss only
"no_vol": {
"w_data": 1,
"w_smooth_musc": 0.01, "w_smooth_skin": 0.05,
"w_biharmonic_musc": 1, "w_biharmonic_skin": 2.5,
"w_spring_musc": 1, "w_spring_skin": 1,
"w_tangent_musc": 1, "w_tangent_skin": 0.1,
"w_vol_musc": 0, "w_vol_skin": 0,
},
# Ablation: remove biharmonic and stretch losses (E_bi, E_spring)
"no_bi_stretch": {
"w_data": 1,
"w_smooth_musc": 0.01, "w_smooth_skin": 0.05,
"w_biharmonic_musc": 0, "w_biharmonic_skin": 0,
"w_spring_musc": 0, "w_spring_skin": 0,
"w_tangent_musc": 1, "w_tangent_skin": 0.1,
"w_vol_musc": 10, "w_vol_skin": 10,
},
}
# ------------------------------------------------------------------
ACTIVE_PRESET = "no_bi_stretch" # <-- Change this to switch presets
LAMBDAS = LAMBDAS_PRESETS[ACTIVE_PRESET]
# ------------------------------------------------------------------
# --- PATH SETUP ---
# Adjust this base path to match new directory structure
BASE_DIR = rf"/CT/SOMA/{CONFIG['base_path_suffix']}/{CONFIG['subject']}"
# The packed training frames live in the self-contained SKIM dataset under static00; the raw/layers/
# canonical inputs still read from BASE_DIR. Built by 05-Training/{preprocess_from_skim,pack_preprocessed}.py
# from the pure-Python SKIM residual dataset (/CT/SOMA/static00/SKIM_dataset/<S>/shot_*.npz). The loader
# (ProcessedMotionDataset) auto-detects the packed <shot>.npz layout.
PROCESSED_ROOT = rf"/CT/SOMA/static00/SKIM_dataset/{CONFIG['subject']}/preprocessed_vFinal_clean"
PATHS = {
"raw": os.path.join(BASE_DIR, "raw"),
"processed": PROCESSED_ROOT,
"layers_tpose": os.path.join(BASE_DIR, "layers", "tpose"),
"layers_apose": os.path.join(BASE_DIR, "layers", "apose"),
"canonical": os.path.join(BASE_DIR, "canonical_model"),
"checkpoints": os.path.join(os.getcwd(), "checkpoints"),
"logs": os.path.join(os.getcwd(), "runs")
}
# --- DATASET CLASS ---
class ProcessedMotionDataset(Dataset):
"""Loads the preprocessed training frames. Auto-detects two on-disk layouts:
* PACKED (default, light to distribute): one .npz per shot at the top of processed_dir
with arrays pose (F,J*6) / residuals (F,M,3) / masks (F,M). Loaded fully into RAM.
* LEGACY per-frame: pose_rotations/ residuals/ masks/ canonical_lbs/ dirs of *.npy.
Both yield the same 4-tuple (pose, residuals, masks, canonical_lbs); canonical_lbs is a zero
placeholder in packed mode (it is unused by the loss). `pose_rot_files` is a per-frame id list
used by the reproducible train/val split."""
def __init__(self, processed_dir, preload=True):
self.processed_dir = processed_dir
self.preload = preload
self.packed = (not os.path.isdir(os.path.join(processed_dir, 'pose_rotations'))