Repository navigation
Expand file tree
/
Copy pathmodel.py
More file actions
4633 lines (4276 loc) · 183 KB
/
Copy pathmodel.py
File metadata and controls
4633 lines (4276 loc) · 183 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from __future__ import annotations
from dataclasses import dataclass, field, replace
import math
import torch
from torch import nn
import torch.nn.functional as F
from dtypes import torch_float_hi, numpy_float_hi
import fit_data
@dataclass(frozen=True)
class ModelParams3D:
mesh_step: int # height step in fullres voxels
winding_step: int # radial step per winding in fullres voxels
subsample_mesh: int # HR height subsample factor
subsample_winding: int # HR width subsample factor
scaledown: float # data xy downscale factor
z_step_eff: int # effective z spacing in fullres voxels
volume_extent: tuple[float, float, float, float, float, float] | None # (x0,y0,z0,x1,y1,z1) fullres bbox
pyramid_d: bool # whether depth axis participates in pyramid
model_w: float | None = None
model_h: float | None = None
depth_windings: tuple[int, ...] = field(default_factory=tuple)
flatten_output_step: float | None = None
def _normalize_depth_windings(raw, *, depth: int, where: str) -> tuple[int, ...]:
if not isinstance(raw, (list, tuple)):
raise ValueError(f"{where}: missing required depth_windings list")
out = tuple(int(v) for v in raw)
if len(out) != int(depth):
raise ValueError(f"{where}: depth_windings length {len(out)} must match depth {int(depth)}")
if len(set(out)) != len(out):
raise ValueError(f"{where}: depth_windings must not contain duplicates")
if any(b <= a for a, b in zip(out, out[1:])):
raise ValueError(f"{where}: depth_windings must be strictly increasing")
return out
def _frozen_channels(channels: set[str] | frozenset[str] | tuple[str, ...] | list[str] | None) -> frozenset[str]:
return frozenset(str(ch) for ch in (channels or ()))
@dataclass(frozen=True)
class ModelForwardNeeds:
"""Request object for optional `Model3D.forward` artifacts.
`xyz_lr`, `data`, and `params` are always produced. Everything else is
requested by optimizer-owned callers from the active loss set. Channel
sets ending in `_grad_channels` require position gradients; other channel
requests are sampled from detached positions.
"""
xyz_hr: bool = False
xyz_hr_grad: bool = False
hr_data_channels: frozenset[str] = field(default_factory=frozenset)
hr_data_grad_channels: frozenset[str] = field(default_factory=frozenset)
hr_prefetch_channels: frozenset[str] = field(default_factory=frozenset)
hr_prefetch_grad_channels: frozenset[str] = field(default_factory=frozenset)
lr_data_channels: frozenset[str] = field(default_factory=frozenset)
lr_data_grad_channels: frozenset[str] = field(default_factory=frozenset)
lr_prefetch_channels: frozenset[str] = field(default_factory=frozenset)
lr_prefetch_grad_channels: frozenset[str] = field(default_factory=frozenset)
target: bool = False
mesh_conn: bool = False
mesh_normals: bool = False
ext_conn: bool = False
ext_surfaces: bool = False
cyl_samples: bool = False
cyl_normals: bool = False
cyl_centers_axes: bool = False
cyl_shell_fields: bool = False
prefetch_pred_dt_loss: bool = False
prefetch_pred_dt_flow: bool = False
prefetch_cyl_gt_normals: bool = False
prefetch_cyl_grad_mask: bool = False
prefetch_ext_offset: bool = False
prefetch_corr_points: bool = False
prefetch_snap_surf_map: bool = False
flatten: bool = False
def __post_init__(self) -> None:
hr_data_grad = _frozen_channels(self.hr_data_grad_channels)
hr_prefetch_grad = _frozen_channels(self.hr_prefetch_grad_channels)
lr_data_grad = _frozen_channels(self.lr_data_grad_channels)
lr_prefetch_grad = _frozen_channels(self.lr_prefetch_grad_channels)
object.__setattr__(self, "hr_data_grad_channels", hr_data_grad)
object.__setattr__(self, "hr_prefetch_grad_channels", hr_prefetch_grad)
object.__setattr__(self, "lr_data_grad_channels", lr_data_grad)
object.__setattr__(self, "lr_prefetch_grad_channels", lr_prefetch_grad)
object.__setattr__(self, "hr_data_channels", _frozen_channels(self.hr_data_channels) | hr_data_grad)
object.__setattr__(self, "hr_prefetch_channels", _frozen_channels(self.hr_prefetch_channels) | hr_prefetch_grad)
object.__setattr__(self, "lr_data_channels", _frozen_channels(self.lr_data_channels) | lr_data_grad)
object.__setattr__(self, "lr_prefetch_channels", _frozen_channels(self.lr_prefetch_channels) | lr_prefetch_grad)
if self.xyz_hr_grad or hr_data_grad or hr_prefetch_grad:
object.__setattr__(self, "xyz_hr_grad", True)
object.__setattr__(self, "xyz_hr", True)
@classmethod
def full(cls, data: fit_data.FitData3D) -> "ModelForwardNeeds":
hr_channels = {"grad_mag"}
if data.has_channel("pred_dt"):
hr_channels.add("pred_dt")
return cls(
xyz_hr=True,
xyz_hr_grad=True,
hr_data_channels=frozenset(hr_channels),
lr_data_channels=frozenset({"grad_mag", "nx", "ny"}),
target=True,
mesh_conn=True,
mesh_normals=True,
ext_conn=True,
ext_surfaces=True,
cyl_samples=True,
cyl_normals=True,
cyl_centers_axes=True,
cyl_shell_fields=True,
)
def merged(self, *others: "ModelForwardNeeds") -> "ModelForwardNeeds":
out = self
for other in others:
out = ModelForwardNeeds(
xyz_hr=out.xyz_hr or other.xyz_hr,
xyz_hr_grad=out.xyz_hr_grad or other.xyz_hr_grad,
hr_data_channels=out.hr_data_channels | other.hr_data_channels,
hr_data_grad_channels=out.hr_data_grad_channels | other.hr_data_grad_channels,
hr_prefetch_channels=out.hr_prefetch_channels | other.hr_prefetch_channels,
hr_prefetch_grad_channels=out.hr_prefetch_grad_channels | other.hr_prefetch_grad_channels,
lr_data_channels=out.lr_data_channels | other.lr_data_channels,
lr_data_grad_channels=out.lr_data_grad_channels | other.lr_data_grad_channels,
lr_prefetch_channels=out.lr_prefetch_channels | other.lr_prefetch_channels,
lr_prefetch_grad_channels=out.lr_prefetch_grad_channels | other.lr_prefetch_grad_channels,
target=out.target or other.target,
mesh_conn=out.mesh_conn or other.mesh_conn,
mesh_normals=out.mesh_normals or other.mesh_normals,
ext_conn=out.ext_conn or other.ext_conn,
ext_surfaces=out.ext_surfaces or other.ext_surfaces,
cyl_samples=out.cyl_samples or other.cyl_samples,
cyl_normals=out.cyl_normals or other.cyl_normals,
cyl_centers_axes=out.cyl_centers_axes or other.cyl_centers_axes,
cyl_shell_fields=out.cyl_shell_fields or other.cyl_shell_fields,
prefetch_pred_dt_loss=out.prefetch_pred_dt_loss or other.prefetch_pred_dt_loss,
prefetch_pred_dt_flow=out.prefetch_pred_dt_flow or other.prefetch_pred_dt_flow,
prefetch_cyl_gt_normals=out.prefetch_cyl_gt_normals or other.prefetch_cyl_gt_normals,
prefetch_cyl_grad_mask=out.prefetch_cyl_grad_mask or other.prefetch_cyl_grad_mask,
prefetch_ext_offset=out.prefetch_ext_offset or other.prefetch_ext_offset,
prefetch_corr_points=out.prefetch_corr_points or other.prefetch_corr_points,
prefetch_snap_surf_map=out.prefetch_snap_surf_map or other.prefetch_snap_surf_map,
flatten=out.flatten or other.flatten,
)
return out
def prefetch_channels_by_position_grad(self) -> tuple[frozenset[str], frozenset[str]]:
grad_channels = set(self.hr_data_grad_channels)
grad_channels.update(self.hr_prefetch_grad_channels)
grad_channels.update(self.lr_data_grad_channels)
grad_channels.update(self.lr_prefetch_grad_channels)
nograd_channels = set(self.hr_data_channels - self.hr_data_grad_channels)
nograd_channels.update(self.hr_prefetch_channels - self.hr_prefetch_grad_channels)
nograd_channels.update(self.lr_data_channels - self.lr_data_grad_channels)
nograd_channels.update(self.lr_prefetch_channels - self.lr_prefetch_grad_channels)
if self.mesh_conn or self.prefetch_ext_offset:
nograd_channels.add("grad_mag")
if self.prefetch_pred_dt_loss:
grad_channels.add("pred_dt")
if self.prefetch_pred_dt_flow:
nograd_channels.add("pred_dt")
nograd_channels.update({"nx", "ny"})
if self.prefetch_cyl_gt_normals:
nograd_channels.update({"grad_mag", "nx", "ny"})
if self.prefetch_cyl_grad_mask:
nograd_channels.add("grad_mag")
if self.prefetch_corr_points:
nograd_channels.update({"grad_mag", "nx", "ny"})
if self.prefetch_snap_surf_map:
nograd_channels.add("grad_mag")
return frozenset(grad_channels), frozenset(nograd_channels)
def prefetch_channels(self) -> frozenset[str]:
grad_channels, nograd_channels = self.prefetch_channels_by_position_grad()
return frozenset(set(grad_channels) | set(nograd_channels))
def summary(self) -> str:
parts: list[str] = []
if self.xyz_hr:
parts.append("xyz_hr_grad" if self.xyz_hr_grad else "xyz_hr_nograd")
hr_data_nograd = self.hr_data_channels - self.hr_data_grad_channels
hr_prefetch_nograd = self.hr_prefetch_channels - self.hr_prefetch_grad_channels
lr_data_nograd = self.lr_data_channels - self.lr_data_grad_channels
lr_prefetch_nograd = self.lr_prefetch_channels - self.lr_prefetch_grad_channels
for label, channels in (
("hr_grad", self.hr_data_grad_channels),
("hr_nograd", hr_data_nograd),
("hr_pf_grad", self.hr_prefetch_grad_channels),
("hr_pf_nograd", hr_prefetch_nograd),
("lr_grad", self.lr_data_grad_channels),
("lr_nograd", lr_data_nograd),
("lr_pf_grad", self.lr_prefetch_grad_channels),
("lr_pf_nograd", lr_prefetch_nograd),
):
if channels:
parts.append(f"{label}={','.join(sorted(channels))}")
for name, enabled in (
("target", self.target),
("mesh_conn", self.mesh_conn),
("mesh_normals", self.mesh_normals),
("ext_conn", self.ext_conn),
("ext_surfaces", self.ext_surfaces),
("cyl", self.cyl_samples),
("cyl_normals", self.cyl_normals),
("cyl_axes", self.cyl_centers_axes),
("cyl_shell", self.cyl_shell_fields),
("pred_dt_loss_pf", self.prefetch_pred_dt_loss),
("pred_dt_flow_pf", self.prefetch_pred_dt_flow),
("cyl_gt_pf", self.prefetch_cyl_gt_normals),
("cyl_grad_pf", self.prefetch_cyl_grad_mask),
("ext_pf", self.prefetch_ext_offset),
("corr_pf", self.prefetch_corr_points),
("flatten", self.flatten),
):
if enabled:
parts.append(name)
if not parts:
return "xyz_lr,data,params"
return "xyz_lr,data,params+" + "+".join(parts)
@dataclass(frozen=True)
class SeedShellMetrics:
classification: str
signed_distance: float
abs_distance: float
tolerance: float
row_index: int
@dataclass(frozen=True)
class _SeedCrossSection:
xy_segments: torch.Tensor
param_segments: torch.Tensor
row_index: int
tolerance: float
@dataclass(frozen=True)
class FitResult3D:
xyz_lr: torch.Tensor # (D, Hm, Wm, 3) LR mesh in fullres voxels
xyz_hr: torch.Tensor | None # (D, He, We, 3) HR mesh
data: fit_data.FitData3D # full volume data
data_s: fit_data.FitData3D | None # sampled at HR positions
data_lr: fit_data.FitData3D | None # sampled at LR positions
target_plain: torch.Tensor | None # (D, 1, He, We)
target_mod: torch.Tensor | None # (D, 1, He, We)
amp_lr: torch.Tensor # (D, 1, Hm, Wm)
bias_lr: torch.Tensor # (D, 1, Hm, Wm)
mask_hr: torch.Tensor | None # (D, 1, He, We)
mask_lr: torch.Tensor | None # (D, 1, Hm, Wm)
normals: torch.Tensor | None # (D, Hm, Wm, 3) detached unit normals
xy_conn: torch.Tensor | None # (D, Hm, Wm, 3, 3) — [prev, self, next], each 3D fullres
mask_conn: torch.Tensor | None # (D, 1, Hm, Wm, 3) — validity per connection point
sign_conn: torch.Tensor | None # (D, 1, Hm, Wm, 2) — ray param sign [prev, next]
params: ModelParams3D
gt_normal_lr: torch.Tensor | None = None # (D, Hm, Wm, 3) GT unit normals at LR mesh positions
ext_conn: list | None = None
ext_surfaces: list | None = None # per surface: (xyz, corner_valid, normals, quad_valid, offset), detached
cyl_xyz: torch.Tensor | None = None # (N*D, Hm, Wm, 3) analytic cylinder samples
cyl_normals: torch.Tensor | None = None # (N*D, Hm, Wm, 3) analytic cylinder normals
cyl_centers: torch.Tensor | None = None # (N, 3) cylinder axis anchor [cx, cy, zc]
cyl_axes: torch.Tensor | None = None # (N, 3) unit cylinder axis direction
cyl_params: torch.Tensor | None = None # analytic: (N, 6); shell losses use cyl_shell_delta_xyz
cyl_count: int = 0
cyl_shell_mode: bool = False
cyl_shell_step: float = 500.0
cyl_shell_width_step: float = 0.0
cyl_shell_height_step: float = 0.0
cyl_seed_z: float = 0.0
cyl_seed_signed_distance: float | None = None
cyl_z_center_target: float = 0.0
cyl_shell_base_xyz: torch.Tensor | None = None
cyl_shell_dirs: torch.Tensor | None = None
cyl_shell_w_offsets: torch.Tensor | None = None
cyl_shell_delta_xyz: torch.Tensor | None = None
cyl_shell_index: int = 0
cyl_outside_volume: torch.Tensor | None = None # (1, Z, Y, X) uint8 previous-shell violation depth
cyl_outside_origin: tuple[float, float, float] | None = None
cyl_outside_spacing: tuple[float, float, float] | None = None
cyl_outside_shape: tuple[int, int, int] | None = None # (Z, Y, X)
cyl_outside_depth_max: float = 0.0
cyl_outside_sample_factor: int = 2
cyl_outside_model_step: float | None = None
flatten_map: torch.Tensor | None = None # (Hout, Wout, 2) source grid coords (row, col)
flatten_xyz: torch.Tensor | None = None # (1, Hout, Wout, 3) sampled frozen source surface
flatten_point_mask: torch.Tensor | None = None # (Hout, Wout) bool
flatten_quad_mask: torch.Tensor | None = None # (1, Hout-1, Wout-1) bool
flatten_target_step: torch.Tensor | None = None # scalar requested output spacing
flatten_map_step: torch.Tensor | None = None # scalar map increment per grid edge
flatten_avg_offset_mask: torch.Tensor | None = None # (Hout, Wout) bool fixed init-valid anchor mask
flatten_initial_avg_offset: torch.Tensor | None = None # (2,) initial mean map offset over anchor mask
flatten_direction: str = "inverse" # inverse: output->source, forward: source->output UV
flatten_source_xyz: torch.Tensor | None = None # (Hs, Ws, 3) frozen source surface
flatten_source_valid: torch.Tensor | None = None # (Hs, Ws) bool frozen source vertices
flatten_source_cell_valid: torch.Tensor | None = None # (Hs-1, Ws-1) bool frozen source quads
flatten_source_metric: torch.Tensor | None = None # (Hs-1, Ws-1, 3) frozen g00,g01,g11
flatten_identity_y: torch.Tensor | None = None # (Hmap,) frozen canonical row coordinates
flatten_identity_x: torch.Tensor | None = None # (Wmap,) frozen canonical column coordinates
# Per ext surface: (mask, offset, ext_P, ext_N, full_h, full_w)
# ext_P/ext_N = ext corner pos/normal (detached), full_h/full_w = model grid position (row+u, col+v)
# Shapes: (D, H_ext, W_ext, ...). Model quad corners are re-gathered from xyz_lr in the loss.
class Model3D(nn.Module):
def __init__(
self,
*,
device: torch.device,
depth: int,
mesh_h: int,
mesh_w: int,
mesh_step: int,
winding_step: int,
subsample_mesh: int = 4,
subsample_winding: int = 4,
scaledown: float = 1.0,
z_step_eff: int = 1,
z_center: float = 0.0,
arc_cx: float = 0.0,
arc_cy: float = 0.0,
arc_radius: float = 1000.0,
arc_angle0: float = -0.5,
arc_angle1: float = 0.5,
straight_cx: float = 0.0,
straight_cy: float = 0.0,
straight_angle: float = 0.0,
straight_half_w: float = 100.0,
init_mode: str = "cylinder_seed",
volume_extent: tuple[float, float, float, float, float, float] | None = None,
pyramid_d: bool = True,
) -> None:
super().__init__()
self.depth = max(1, int(depth))
self.mesh_h = max(2, int(mesh_h))
self.mesh_w = max(2, int(mesh_w))
self.z_center = float(z_center)
self.init_mode = str(init_mode)
self.cylinder_enabled = self.init_mode == "cylinder_seed"
self.cyl_best_idx = 0
self.arc_enabled = False
self.straight_enabled = False
self.pyramid_d = bool(pyramid_d) and self.depth > 1
self.params = ModelParams3D(
mesh_step=int(mesh_step),
winding_step=int(winding_step),
subsample_mesh=int(subsample_mesh),
subsample_winding=int(subsample_winding),
scaledown=float(scaledown),
z_step_eff=max(1, int(z_step_eff)),
volume_extent=volume_extent,
pyramid_d=self.pyramid_d,
depth_windings=tuple(range(self.depth)),
)
# Arc parameters (fullres coordinates)
self.arc_cx = nn.Parameter(torch.tensor(float(arc_cx), device=device, dtype=torch.float32))
self.arc_cy = nn.Parameter(torch.tensor(float(arc_cy), device=device, dtype=torch.float32))
self.arc_radius = nn.Parameter(torch.tensor(float(arc_radius), device=device, dtype=torch.float32))
self.arc_angle0 = nn.Parameter(torch.tensor(float(arc_angle0), device=device, dtype=torch.float32))
self.arc_angle1 = nn.Parameter(torch.tensor(float(arc_angle1), device=device, dtype=torch.float32))
# Straight parameters (fullres coordinates)
self.straight_cx = nn.Parameter(torch.tensor(float(straight_cx), device=device, dtype=torch.float32))
self.straight_cy = nn.Parameter(torch.tensor(float(straight_cy), device=device, dtype=torch.float32))
self.straight_angle = nn.Parameter(torch.tensor(float(straight_angle), device=device, dtype=torch.float32))
self.straight_half_w = nn.Parameter(torch.tensor(float(straight_half_w), device=device, dtype=torch.float32))
# Multi-start analytic cylinder seed params:
# [radius, ellipse_k, seed_phase, tilt_x, tilt_y, roll]. The center is
# derived so q=0 stays on the seed point, and height is centered
# at the seed along the optimized cylinder axis.
self.cyl_params = nn.Parameter(self._default_cylinder_params(device=device))
self.cyl_shell_delta_ms = nn.ParameterList()
self.cyl_shell_w_offsets = nn.Parameter(
torch.empty(0, device=device, dtype=torch.float32)
if self.init_mode == "flatten"
else torch.zeros(self.mesh_h, self.mesh_w, device=device, dtype=torch.float32)
)
self.cyl_seed_xyz = torch.zeros(3, device=device, dtype=torch.float32)
self.cyl_shell_mode = False
self.cyl_shell_n_scales = 5
self.cyl_shell_target_count = 4
self.cyl_shell_initial_radius = 2000.0
self.cyl_shell_target_radius = self.cyl_shell_initial_radius
self.cyl_shell_step = 500.0
self.cyl_shell_initial_step = 10.0
self.cyl_shell_growth_factor = 1.5
self.cyl_shell_optimize_resampled = False
self.cyl_shell_use_conn_offsets = False
self.cyl_shell_z_step = 1000.0
self.cyl_shell_current_height_step = self.cyl_shell_z_step
self.cyl_shell_width_target_step = 1000.0
self.cyl_shell_current_width_step = self.cyl_shell_width_target_step
self.cyl_shell_current_radius = self.cyl_shell_initial_radius
self.cyl_shell_seed_z = float(z_center)
self.cyl_shell_z_center_target = float(z_center)
self.cyl_shell_model_h: float | None = None
self.cyl_shell_z: torch.Tensor | None = None
self.cyl_shell_base: torch.Tensor | None = None
self.cyl_shell_dirs: torch.Tensor | None = None
self.cyl_shell_completed: list[torch.Tensor] = []
self.cyl_grow_reference_width_count: int | None = None
self.cyl_grow_reference_circumference: float | None = None
self.cyl_shell_current_index = 0
self.cyl_shell_active = False
self.cyl_shell_search_max_shells = 16
self.cyl_shell_search_direction = 1
self.cyl_shell_search_initial_class: str | None = None
self.cyl_shell_search_last_class: str | None = None
self.cyl_shell_search_initial_signed_distance: float | None = None
self.cyl_shell_search_last_signed_distance: float | None = None
self.cyl_shell_search_crossed = False
self.cyl_shell_search_done = False
self.cyl_outside_volume: torch.Tensor | None = None
self.cyl_outside_origin: tuple[float, float, float] | None = None
self.cyl_outside_spacing: tuple[float, float, float] | None = None
self.cyl_outside_shape: tuple[int, int, int] | None = None
self.cyl_outside_depth_max: float = 0.0
self.cyl_outside_sample_factor: int = 2
self.cyl_outside_model_step: float | None = None
# Flattening owns a separate UV pyramid and never reads the generic XYZ
# mesh. Avoid materialising the full generic pyramid for that mode.
if self.init_mode == "flatten":
self.mesh_ms = nn.ParameterList()
else:
n_scales = int(self.cyl_shell_n_scales)
self.mesh_ms = self._build_zero_pyramid(
n_scales=n_scales, channels=3, d=self.depth, h=self.mesh_h, w=self.mesh_w, device=device,
pyramid_d=self.pyramid_d,
)
# Connection offsets buffer: (4, D, Hm, Wm) — [prev_h, prev_w, next_h, next_w]
# Not gradient-optimized; updated by update_conn_offsets() after each step.
self.register_buffer(
"conn_offsets",
torch.empty(0, device=device, dtype=torch.float32)
if self.init_mode == "flatten"
else torch.zeros(4, self.depth, self.mesh_h, self.mesh_w, device=device, dtype=torch.float32),
)
# External reference surfaces: frozen meshes for offset optimization
self._ext_surfaces: list[torch.Tensor] = [] # each (H_ext, W_ext, 3)
self._ext_valid: list[torch.Tensor] = [] # each (H_ext, W_ext) bool
self._ext_conn_offsets: list[torch.Tensor] = [] # each (2, D, H_ext, W_ext) — [h_off, w_off]
self._ext_conn_params: list[dict] = [] # cached intersection params per ext surface
self._ext_normals: list[torch.Tensor] = [] # each (H_ext, W_ext, 3) precomputed unit normals
self._ext_offsets: list[float] = [] # target integral offset per ext surface
# Flatten-only mode: optimized inverse map from an output grid to one
# frozen tifxyz source surface. These buffers are unused outside
# flatten mode and are intentionally separate from external offset
# surfaces.
self.flatten_enabled = False
self.flatten_direction = "inverse"
self.flatten_output_shape: tuple[int, int] = (0, 0)
self.flatten_output_margin = 0.10
self.flatten_map_ms = nn.ParameterList()
self.register_buffer("flatten_source_xyz", torch.empty(0, 0, 3, device=device, dtype=torch.float32))
self.register_buffer("flatten_source_valid", torch.empty(0, 0, device=device, dtype=torch.bool))
self.register_buffer("flatten_source_cell_valid", torch.empty(0, 0, device=device, dtype=torch.bool))
self.register_buffer("flatten_target_step", torch.tensor(float(mesh_step), device=device, dtype=torch.float32))
self.register_buffer("flatten_map_step", torch.tensor(1.0, device=device, dtype=torch.float32))
self.register_buffer("flatten_measured_source_step", torch.tensor(float(mesh_step), device=device, dtype=torch.float32))
self.register_buffer("flatten_avg_offset_mask", torch.empty(0, 0, device=device, dtype=torch.bool))
self.register_buffer("flatten_initial_avg_offset", torch.zeros(2, device=device, dtype=torch.float32))
self.register_buffer(
"flatten_source_metric",
torch.empty(0, 0, 3, device=device, dtype=torch.float32),
persistent=False,
)
self.register_buffer(
"flatten_identity_y",
torch.empty(0, device=device, dtype=torch.float32),
persistent=False,
)
self.register_buffer(
"flatten_identity_x",
torch.empty(0, device=device, dtype=torch.float32),
persistent=False,
)
self.flatten_source_filter_stats: dict[str, float] = {}
# Amplitude and bias are irrelevant to the flatten-only objective. Keep
# empty parameters so checkpoint/module structure remains predictable.
if self.init_mode == "flatten":
amp_init = torch.empty(0, device=device, dtype=torch.float32)
bias_init = torch.empty(0, device=device, dtype=torch.float32)
else:
amp_init = torch.full((self.depth, 1, self.mesh_h, self.mesh_w), 1.0, device=device, dtype=torch.float32)
bias_init = torch.full((self.depth, 1, self.mesh_h, self.mesh_w), 0.5, device=device, dtype=torch.float32)
self.amp = nn.Parameter(amp_init)
self.bias = nn.Parameter(bias_init)
@staticmethod
def _build_zero_pyramid(*, n_scales: int, channels: int, d: int, h: int, w: int, device: torch.device, pyramid_d: bool) -> nn.ParameterList:
shapes: list[tuple[int, int, int]] = [(d, h, w)]
for _ in range(1, max(1, n_scales)):
dp, hp, wp = shapes[-1]
if pyramid_d:
shapes.append((max(2, (dp + 1) // 2), max(2, (hp + 1) // 2), max(2, (wp + 1) // 2)))
else:
shapes.append((dp, max(2, (hp + 1) // 2), max(2, (wp + 1) // 2)))
print(f"[model] pyramid levels (C={channels}, pyramid_d={pyramid_d}): {' -> '.join(f'{d}x{h}x{w}' for d,h,w in shapes)}")
return nn.ParameterList([
nn.Parameter(torch.zeros(channels, di, hi, wi, device=device, dtype=torch.float32))
for di, hi, wi in shapes
])
@staticmethod
def _default_cylinder_params(*, device: torch.device) -> torch.Tensor:
return torch.zeros(1, 6, device=device, dtype=torch.float32)
# --- 3D pyramid operations ---
@staticmethod
def _upsample_crop(src: torch.Tensor, d_t: int, h_t: int, w_t: int, *, pyramid_d: bool) -> torch.Tensor:
if pyramid_d:
return F.interpolate(src.unsqueeze(0), size=(d_t, h_t, w_t),
mode='trilinear', align_corners=True).squeeze(0)
else:
return F.interpolate(src, size=(h_t, w_t),
mode='bilinear', align_corners=True)
@staticmethod
def _integrate_pyramid_3d(src: nn.ParameterList, *, pyramid_d: bool) -> torch.Tensor:
v = src[-1]
for d in reversed(list(src[:-1])):
v = Model3D._upsample_crop(v, d.shape[1], d.shape[2], d.shape[3], pyramid_d=pyramid_d) + d
return v
@staticmethod
def _construct_pyramid_from_flat_3d(flat: torch.Tensor, n_scales: int, *, pyramid_d: bool) -> nn.ParameterList:
shapes: list[tuple[int, int, int]] = [(int(flat.shape[1]), int(flat.shape[2]), int(flat.shape[3]))]
for _ in range(1, n_scales):
d, h, w = shapes[-1]
if pyramid_d:
shapes.append((max(2, (d + 1) // 2), max(2, (h + 1) // 2), max(2, (w + 1) // 2)))
else:
shapes.append((d, max(2, (h + 1) // 2), max(2, (w + 1) // 2)))
targets: list[torch.Tensor] = [flat]
for (d, h, w) in shapes[1:]:
if pyramid_d:
t = F.interpolate(targets[-1].unsqueeze(0), size=(d, h, w),
mode='trilinear', align_corners=True).squeeze(0)
else:
t = F.interpolate(targets[-1], size=(h, w),
mode='bilinear', align_corners=True)
targets.append(t)
residuals: list[torch.Tensor | None] = [None] * len(targets)
recon = targets[-1]
residuals[-1] = targets[-1]
for i in range(len(targets) - 2, -1, -1):
up = Model3D._upsample_crop(recon, *targets[i].shape[1:], pyramid_d=pyramid_d)
residuals[i] = targets[i] - up
recon = up + residuals[i]
return nn.ParameterList([nn.Parameter(r) for r in residuals])
@staticmethod
def _scale_count_to_longer_dim_2(h: int, w: int) -> int:
longer = max(2, int(h), int(w))
count = 1
while longer > 2:
longer = max(2, (longer + 1) // 2)
count += 1
return count
@staticmethod
def _flatten_output_shape_for_source(
h: int,
w: int,
*,
source_step: float,
output_step: float,
) -> tuple[int, int]:
"""Derive vertex counts from physical span and requested density."""
if not math.isfinite(float(source_step)) or float(source_step) <= 0.0:
raise ValueError("flatten source_step must be finite and positive")
if not math.isfinite(float(output_step)) or float(output_step) <= 0.0:
raise ValueError("flatten output_step must be finite and positive")
def _vertex_count(n: int) -> int:
# N vertices contain N-1 physical intervals.
if int(n) < 1:
raise ValueError("flatten source dimensions must be positive")
intervals = int(n) - 1
physical_span = float(intervals) * float(source_step)
return int(math.ceil(physical_span / float(output_step))) + 1
return _vertex_count(h), _vertex_count(w)
@staticmethod
def _centered_flatten_source_map(
*,
source_h: int,
source_w: int,
out_h: int,
out_w: int,
source_step: float,
output_step: float,
device: torch.device,
dtype: torch.dtype,
) -> torch.Tensor:
map_yx = Model3D._identity_flatten_map(h=out_h, w=out_w, device=device, dtype=dtype)
source_per_output = float(output_step) / float(source_step)
output_center = torch.tensor(
[0.5 * float(out_h - 1), 0.5 * float(out_w - 1)],
device=device,
dtype=dtype,
)
source_center = torch.tensor(
[0.5 * float(source_h - 1), 0.5 * float(source_w - 1)],
device=device,
dtype=dtype,
)
return (
(map_yx - output_center.reshape(1, 1, 2)) * source_per_output
+ source_center.reshape(1, 1, 2)
).contiguous()
@staticmethod
def _normalize_flatten_direction(raw: str | None) -> str:
value = str(raw or "inverse").strip().lower().replace("-", "_")
if value in {"torch", "bilin", "bilinear", "inverse", "inverse_adam"}:
return "inverse"
if value in {"forward", "forward_adam", "uv", "source_uv"}:
return "forward"
raise ValueError(f"unsupported flatten solver/direction {raw!r} (expected inverse/torch or forward)")
@staticmethod
def _centered_flatten_forward_uv_map(
*,
source_h: int,
source_w: int,
out_h: int,
out_w: int,
source_step: float,
output_step: float,
device: torch.device,
dtype: torch.dtype,
) -> torch.Tensor:
uv_yx = Model3D._identity_flatten_map(h=source_h, w=source_w, device=device, dtype=dtype)
output_per_source = float(source_step) / float(output_step)
source_center = torch.tensor(
[0.5 * float(source_h - 1), 0.5 * float(source_w - 1)],
device=device,
dtype=dtype,
)
output_center = torch.tensor(
[0.5 * float(out_h - 1), 0.5 * float(out_w - 1)],
device=device,
dtype=dtype,
)
return (
(uv_yx - source_center.reshape(1, 1, 2)) * output_per_source
+ output_center.reshape(1, 1, 2)
).contiguous()
def _shell_delta_scale_count(self) -> int:
return max(1, int(getattr(self, "cyl_shell_n_scales", 5)))
@staticmethod
def _shell_delta_to_pyramid_flat(delta_xyz: torch.Tensor) -> torch.Tensor:
if delta_xyz.ndim != 3 or int(delta_xyz.shape[-1]) != 3:
raise ValueError(f"shell delta must have shape (H, W, 3), got {tuple(delta_xyz.shape)}")
return delta_xyz.permute(2, 0, 1).unsqueeze(1).contiguous()
@staticmethod
def _shell_delta_from_pyramid_flat(flat: torch.Tensor) -> torch.Tensor:
if flat.ndim != 4 or int(flat.shape[0]) != 3 or int(flat.shape[1]) != 1:
raise ValueError(f"shell delta pyramid must integrate to shape (3, 1, H, W), got {tuple(flat.shape)}")
return flat[:, 0].permute(1, 2, 0).contiguous()
def _construct_shell_delta_pyramid(self, delta_xyz: torch.Tensor) -> nn.ParameterList:
flat = self._shell_delta_to_pyramid_flat(delta_xyz)
return self._construct_pyramid_from_flat_3d(
flat,
self._shell_delta_scale_count(),
pyramid_d=False,
)
def _set_shell_delta_xyz_params(self, delta_xyz: torch.Tensor) -> None:
delta_xyz = delta_xyz.detach().contiguous()
self.cyl_shell_delta_ms = self._construct_shell_delta_pyramid(delta_xyz)
self.cyl_params = nn.Parameter(delta_xyz.clone(), requires_grad=False)
def cyl_param_scale_count(self) -> int:
if self.cyl_shell_mode and len(self.cyl_shell_delta_ms) > 0:
return len(self.cyl_shell_delta_ms)
return 0
@staticmethod
def _construct_pyramid_from_flat_3d_masked(
flat: torch.Tensor, valid: torch.Tensor, n_scales: int, *, pyramid_d: bool,
) -> nn.ParameterList:
"""Build residual pyramid with validity-aware downsampling.
flat: (C, D, H, W), valid: (H, W) bool.
Invalid regions get residual=0 so integration naturally inpaints them
from coarser (valid) structure.
"""
C = flat.shape[0]
D = int(flat.shape[1])
# Compute enough scales to reach 1×1
shapes: list[tuple[int, int, int]] = [(D, int(flat.shape[2]), int(flat.shape[3]))]
for _ in range(1, n_scales):
d, h, w = shapes[-1]
if pyramid_d:
shapes.append((max(1, (d + 1) // 2), max(1, (h + 1) // 2), max(1, (w + 1) // 2)))
else:
shapes.append((d, max(1, (h + 1) // 2), max(1, (w + 1) // 2)))
# Build validity mask pyramid: (1, D, H, W) float
valid_4d = valid.float().unsqueeze(0).unsqueeze(0).expand(1, D, -1, -1) # (1, D, H, W)
# Masked downsampling: weighted average excluding invalid
targets: list[torch.Tensor] = [flat]
valids: list[torch.Tensor] = [valid_4d]
for (d_t, h_t, w_t) in shapes[1:]:
prev_data = targets[-1] * valids[-1] # zero out invalid before pooling
prev_valid = valids[-1]
if pyramid_d:
data_down = F.interpolate(
(prev_data).unsqueeze(0), size=(d_t, h_t, w_t),
mode='trilinear', align_corners=True).squeeze(0)
valid_down = F.interpolate(
prev_valid.unsqueeze(0), size=(d_t, h_t, w_t),
mode='trilinear', align_corners=True).squeeze(0)
else:
# (C, D, H, W) → treat D as batch: (C*D, 1, H, W) for 2D interpolate
CD = C * D
data_down = F.interpolate(
prev_data.reshape(CD, 1, prev_data.shape[2], prev_data.shape[3]),
size=(h_t, w_t), mode='bilinear', align_corners=True
).reshape(C, D, h_t, w_t)
valid_down = F.interpolate(
prev_valid.reshape(D, 1, prev_valid.shape[2], prev_valid.shape[3]),
size=(h_t, w_t), mode='bilinear', align_corners=True
).reshape(1, D, h_t, w_t)
# Normalize by valid weight
target = data_down / valid_down.clamp(min=1e-6)
valid_mask = (valid_down > 0.01).float()
targets.append(target)
valids.append(valid_mask)
# Build residuals: masked so invalid regions contribute zero
residuals: list[torch.Tensor | None] = [None] * len(targets)
recon = targets[-1]
residuals[-1] = targets[-1]
for i in range(len(targets) - 2, -1, -1):
up = Model3D._upsample_crop(recon, *targets[i].shape[1:], pyramid_d=pyramid_d)
residuals[i] = (targets[i] - up) * valids[i]
recon = up + residuals[i]
return nn.ParameterList([nn.Parameter(r) for r in residuals])
# --- Analytic cylinder seed ---
def init_cylinder_seed(
self,
*,
seed: tuple[float, float, float],
model_w: float,
model_h: float,
volume_extent_fullres: tuple[int, int, int] | None,
exact_z_range: tuple[float, float] | None = None,
) -> None:
"""Initialize the experimental umbilicus tube grower from seed z.
The shell geometry is built lazily once FitData3D has supplied the
umbilicus lookup. The final regular mesh bake uses model_w/model_h as a
seed-centered patch size.
"""
device = self.cyl_params.device
with torch.no_grad():
self.cyl_seed_xyz = torch.tensor([float(seed[0]), float(seed[1]), float(seed[2])],
device=device, dtype=torch.float32)
self.cyl_params = nn.Parameter(torch.zeros(self.mesh_h, self.mesh_w, 3, device=device, dtype=torch.float32))
self.cyl_shell_delta_ms = nn.ParameterList()
self.cyl_shell_w_offsets = nn.Parameter(torch.zeros(self.mesh_h, self.mesh_w, device=device, dtype=torch.float32))
requested_model_h = max(1.0, float(model_h))
if exact_z_range is None:
init_half_h = 2.0 * requested_model_h
init_z0 = float(seed[2]) - init_half_h
init_z1 = float(seed[2]) + init_half_h
if volume_extent_fullres is not None and len(volume_extent_fullres) >= 3:
z_max = max(0.0, float(volume_extent_fullres[2]) - 1.0)
init_z0 = max(0.0, init_z0)
init_z1 = min(z_max, init_z1)
params_model_h = float(model_h)
else:
init_z0 = float(exact_z_range[0])
init_z1 = float(exact_z_range[1])
params_model_h = float(init_z1 - init_z0)
if init_z1 <= init_z0:
raise ValueError(
f"invalid cylinder seed z extent: "
f"z0={init_z0:.3f} z1={init_z1:.3f} seed_z={float(seed[2]):.3f}"
)
self.params = replace(
self.params,
model_w=(float(model_w) if float(model_w) > 0.0 else None),
model_h=params_model_h,
)
self.cyl_shell_mode = True
self.cyl_shell_seed_z = float(seed[2])
self.cyl_shell_z_center_target = 0.5 * (init_z0 + init_z1)
self.z_center = float(self.cyl_shell_z_center_target)
self.cyl_shell_model_h = float(init_z1 - init_z0)
self.cyl_shell_z = None
self.cyl_shell_base = None
self.cyl_shell_dirs = None
self.cyl_shell_completed = []
self.cyl_shell_current_index = 0
self.cyl_shell_active = False
self.cyl_shell_search_direction = 1
self.cyl_shell_search_initial_class = None
self.cyl_shell_search_last_class = None
self.cyl_shell_search_initial_signed_distance = None
self.cyl_shell_search_last_signed_distance = None
self.cyl_shell_search_crossed = False
self.cyl_shell_search_done = False
self.clear_cyl_outside_volume()
self.cylinder_enabled = True
self.cyl_best_idx = 0
self.arc_enabled = False
self.straight_enabled = False
self.init_mode = "cylinder_seed"
def clear_cyl_outside_volume(self) -> None:
self.cyl_outside_volume = None
self.cyl_outside_origin = None
self.cyl_outside_spacing = None
self.cyl_outside_shape = None
self.cyl_outside_depth_max = 0.0
self.cyl_outside_model_step = None
def set_cyl_outside_volume(self, field: object, *, sample_factor: int = 2, model_step: float | None = None) -> None:
volume = getattr(field, "volume", None)
origin = getattr(field, "origin", None)
spacing = getattr(field, "spacing", None)
shape = getattr(field, "shape", None)
depth_max = float(getattr(field, "depth_max", 0.0))
if volume is None or origin is None or spacing is None or shape is None:
raise ValueError("cyl_outside field must expose volume, origin, spacing, shape, and depth_max")
self.cyl_outside_volume = volume.detach().contiguous()
self.cyl_outside_origin = tuple(float(v) for v in origin)
self.cyl_outside_spacing = tuple(float(v) for v in spacing)
self.cyl_outside_shape = tuple(int(v) for v in shape)
self.cyl_outside_depth_max = depth_max
self.cyl_outside_sample_factor = max(1, int(sample_factor))
self.cyl_outside_model_step = (
None if model_step is None else max(1.0e-6, float(model_step))
)
def _set_shell_grid_shape(self, *, h: int, w: int) -> None:
h = max(2, int(h))
w = max(3, int(w))
device = self.cyl_params.device
self.depth = 1
self.mesh_h = h
self.mesh_w = w
self.conn_offsets = torch.zeros(4, 1, h, w, device=device, dtype=torch.float32)
self.amp = nn.Parameter(torch.ones(1, 1, h, w, device=device, dtype=torch.float32))
self.bias = nn.Parameter(torch.full((1, 1, h, w), 0.5, device=device, dtype=torch.float32))
def _set_fused_grid_shape(self, *, d: int, h: int, w: int) -> None:
d = max(1, int(d))
h = max(2, int(h))
w = max(3, int(w))
device = self.cyl_params.device
self.depth = d
self.mesh_h = h
self.mesh_w = w
self.conn_offsets = torch.zeros(4, d, h, w, device=device, dtype=torch.float32)
self.amp = nn.Parameter(torch.ones(d, 1, h, w, device=device, dtype=torch.float32))
self.bias = nn.Parameter(torch.full((d, 1, h, w), 0.5, device=device, dtype=torch.float32))
def prepare_umbilicus_tube_init(self, data: fit_data.FitData3D) -> None:
"""Build the first pending shell from the umbilicus lookup."""
if not self.cyl_shell_mode or self.cyl_shell_base is not None:
return
if self.cyl_shell_model_h is None:
raise ValueError("cylinder shell init missing model_h")
device = self.cyl_params.device
dtype = self.cyl_params.dtype
z_step = max(1.0, float(self.cyl_shell_z_step))
model_h = max(1.0, float(self.cyl_shell_model_h))
z0 = float(self.cyl_shell_z_center_target) - 0.5 * model_h
z1 = float(self.cyl_shell_z_center_target) + 0.5 * model_h
z, actual_h_step = self._umbilicus_arclength_z_values(
data=data,
z0=z0,
z1=z1,
target_step=z_step,
device=device,
dtype=dtype,
)
H = int(z.shape[0])
radius_target = self._first_shell_radius()
self.cyl_shell_target_radius = float(radius_target)
W = self._shell_width_for_radius(radius_target)
radius0 = radius_target
self.cyl_shell_current_radius = float(radius0)
self._set_shell_grid_shape(h=H, w=W)
base, dirs = self._umbilicus_base_shell(data=data, z=z, w=W)
if H > 1:
self.cyl_shell_current_height_step = float((base[1:, 0] - base[:-1, 0]).norm(dim=-1).mean().detach().cpu())
else:
self.cyl_shell_current_height_step = float(actual_h_step)
self.cyl_shell_z = z.detach()
self.cyl_shell_base = base.detach()
self.cyl_shell_dirs = dirs.detach()
self._set_shell_delta_xyz_params(
self._initial_shell_delta_xyz(dirs, target_step=radius0).to(device=device, dtype=dtype)
)
self.cyl_shell_w_offsets = nn.Parameter(torch.zeros(H, W, device=device, dtype=dtype))
print(f"[model] umbilicus tube init: search_max_shells={self.cyl_shell_search_max_shells} "
f"H={H} W={W} seed_z={self.cyl_shell_seed_z:.1f} "
f"z_center_target={self.cyl_shell_z_center_target:.1f} "
f"model_h={model_h:.1f} h_step={float(self.cyl_shell_current_height_step):.1f} "
f"z_step_target={z_step:.1f} target_radius={radius_target:.1f} "
f"initial_radius={radius0:.1f} "
f"step_growth={float(getattr(self, 'cyl_shell_growth_factor', 1.5)):.3g} "
f"width_target_step={self.cyl_shell_width_target_step:.1f}",
flush=True)
def _shell_z_values(self, *, device: torch.device, dtype: torch.dtype, h: int) -> torch.Tensor:
model_h = (
float(self.cyl_shell_model_h)
if self.cyl_shell_model_h is not None
else float(self.params.mesh_step) * float(max(1, h - 1))
)
if h <= 1:
return torch.full((1,), float(self.cyl_shell_z_center_target), device=device, dtype=dtype)
t = torch.linspace(-0.5, 0.5, h, device=device, dtype=dtype)
return float(self.cyl_shell_z_center_target) + t * float(model_h)
def _umbilicus_arclength_z_values(
self,
*,
data: fit_data.FitData3D,
z0: float,
z1: float,
target_step: float,
device: torch.device,
dtype: torch.dtype,
) -> tuple[torch.Tensor, float]:
z0 = float(z0)
z1 = float(z1)
target_step = max(1.0, float(target_step))
z_span = abs(z1 - z0)
if z_span <= 1.0e-6:
z = torch.tensor([z0, z1], device=device, dtype=dtype)
return z, 1.0
dense_step = max(1.0, target_step * 0.25)
n_dense = max(2, int(math.ceil(z_span / dense_step)) + 1)
z_dense = torch.linspace(z0, z1, n_dense, device=device, dtype=dtype)
umb_xy = data.umbilicus_xy_at_z(z_dense).to(device=device, dtype=dtype)
pts = torch.cat([umb_xy, z_dense[:, None]], dim=-1)
seg = (pts[1:] - pts[:-1]).norm(dim=-1)
cum = torch.cat([seg.new_zeros(1), seg.cumsum(dim=0)], dim=0)
total = float(cum[-1].detach().cpu())
if total <= 1.0e-6:
z = torch.tensor([z0, z1], device=device, dtype=dtype)
return z, 1.0
H = max(2, int(math.ceil(total / target_step)) + 1)
s_target = torch.linspace(0.0, total, H, device=device, dtype=dtype)
idx = torch.searchsorted(cum, s_target).clamp(min=1, max=n_dense - 1)
s0 = cum[idx - 1]
s1 = cum[idx]
z_lo = z_dense[idx - 1]
z_hi = z_dense[idx]
alpha = (s_target - s0) / (s1 - s0).clamp(min=1.0e-8)
z = z_lo + alpha * (z_hi - z_lo)
z[0] = z_dense[0]
z[-1] = z_dense[-1]
return z, total / float(max(1, H - 1))
def _shell_width_for_radius(self, radius: float) -> int:
radius = max(1.0, float(radius))
target_step = max(1.0, float(self.cyl_shell_width_target_step))
max_step = 2.0 * radius * math.sin(math.pi / 3.0)
if target_step >= max_step:
return 3
ratio = min(max(target_step / (2.0 * radius), 1.0e-12), math.sin(math.pi / 3.0))
continuous_w = math.pi / math.asin(ratio)
near = int(round(continuous_w))
candidates = {3}
for w in range(max(3, near - 3), max(3, near + 3) + 1):
candidates.add(w)