diff --git a/.gitattributes b/.gitattributes index 044d07637c9de322d67cbfd68a5c2f1659774a7a..52a99b6b5ba32ee62a3865a0ee4e6fe6349f2367 100644 --- a/.gitattributes +++ b/.gitattributes @@ -11422,13 +11422,4 @@ cfd_workflow_20261012/**/wallShearStress filter=lfs diff=lfs merge=lfs -text cfd_workflow_20261012/**/wallShearStressMean filter=lfs diff=lfs merge=lfs -text cfd_workflow_20261012/**/yPlus filter=lfs diff=lfs merge=lfs -text cfd_workflow_20261012/**/yPlusMean filter=lfs diff=lfs merge=lfs -text -cfd_workflow_20261012/anchorgen_side60_20260923_v1/results/pair0342_source057/initial/prepared/constant/triSurface/car.stl filter=lfs diff=lfs merge=lfs -text -cfd_workflow_20261012/anchorgen_side60_20260923_v1/results/pair0342_source057/target/prepared/constant/triSurface/car.stl filter=lfs diff=lfs merge=lfs -text -cfd_workflow_20261012/anchorgen_side60_20260923_v1/results/pair0428_source071/final60/prepared/constant/triSurface/car.stl filter=lfs diff=lfs merge=lfs -text -cfd_workflow_20261012/anchorgen_side60_20260923_v1/results/pair0428_source071/initial/prepared/constant/triSurface/car.stl filter=lfs diff=lfs merge=lfs -text -cfd_workflow_20261012/anchorgen_side60_20260923_v1/results/pair0428_source071/target/prepared/constant/triSurface/car.stl filter=lfs diff=lfs merge=lfs -text -cfd_workflow_20261012/anchorgen_side60_20260923_v1/results/pair0478_source079/final60/prepared/constant/triSurface/car.stl filter=lfs diff=lfs merge=lfs -text -cfd_workflow_20261012/anchorgen_side60_20260923_v1/results/pair0478_source079/initial/prepared/constant/triSurface/car.stl filter=lfs diff=lfs merge=lfs -text -cfd_workflow_20261012/anchorgen_side60_20260923_v1/results/pair0478_source079/target/prepared/constant/triSurface/car.stl filter=lfs diff=lfs merge=lfs -text -cfd_workflow_20261012/anchorgen_side60_20260923_v1/results/pair0503_source083/final60/prepared/constant/triSurface/car.stl filter=lfs diff=lfs merge=lfs -text -cfd_workflow_20261012/anchorgen_side60_20260923_v1/results/pair0503_source083/initial/prepared/constant/triSurface/car.stl filter=lfs diff=lfs merge=lfs -text +cfd_workflow_20261012/_seiler_ref/example_INIT_30_sim/constant/triSurface/car.stl.ori filter=lfs diff=lfs merge=lfs -text diff --git a/cfd_workflow_20261012/_seiler_ref/example_INIT_30_sim/0/U b/cfd_workflow_20261012/_seiler_ref/example_INIT_30_sim/0/U index 5769e79855336fd3cfd9be718253e66f5c745dd8..dae421d1f90f0d263c09b7c97262271a363540dd 100644 --- a/cfd_workflow_20261012/_seiler_ref/example_INIT_30_sim/0/U +++ b/cfd_workflow_20261012/_seiler_ref/example_INIT_30_sim/0/U @@ -1,88 +1,3 @@ -/*--------------------------------*- C++ -*----------------------------------*\ -| ========= | | -| \\ / F ield | OpenFOAM: The Open Source CFD Toolbox | -| \\ / O peration | Version: 7 | -| \\ / A nd | Web: www.OpenFOAM.com | -| \\/ M anipulation | | -\*---------------------------------------------------------------------------*/ -FoamFile -{ - version 2.0; - format ascii; - class volVectorField; - object U; -} -// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // - -dimensions [ 0 1 -1 0 0 0 0 ]; -internalField uniform (30 0.0 0.0); - -boundaryField -{ - #includeEtc "caseDicts/setConstraintTypes" - inlet - { - - type fixedValue; - value uniform ( 30.0 0.0 0.0 ); - -/* - type uniformFixedValue; - uniformValue table - ( - (0 (5 0 0)) - //(20 (10 0 0)) - //(40 (15 0 0)) - //(60 (20 0 0)) - //(80 (25 0 0)) - (100 (30 0 0)) - ); -*/ - - } - - outlet - { - //type zeroGradient; - //value uniform ( 0.0 0.0 0.0 ); - - type inletOutlet; - inletValue uniform (30 0 0); - value uniform (30 0 0); - } - - sides - { - type slip; - } - - ground - { - type fixedValue; - value uniform ( 30.0 0.0 0.0 ); - -/* - type uniformFixedValue; - uniformValue table - ( - (0 (5 0 0)) - //(20 (10 0 0)) - //(40 (15 0 0)) - //(60 (20 0 0)) - //(80 (25 0 0)) - (100 (30 0 0)) - ); -*/ - } - - top - { - type slip; - } - - car - { - type fixedValue; - value uniform ( 0 0 0); - } -} +version https://git-lfs.github.com/spec/v1 +oid sha256:562432c8ef08dd9d7a5c4aaa55e256f8c8c996c414fc0d50ac67bad22fb40f95 +size 1907 diff --git a/cfd_workflow_20261012/_seiler_ref/example_INIT_30_sim/0/k b/cfd_workflow_20261012/_seiler_ref/example_INIT_30_sim/0/k index 3fbd5f6027c8e931e018cc02da50c2bbd0831fc1..751cf632bc059b6a53e1567050fda8329b702db7 100644 --- a/cfd_workflow_20261012/_seiler_ref/example_INIT_30_sim/0/k +++ b/cfd_workflow_20261012/_seiler_ref/example_INIT_30_sim/0/k @@ -1,60 +1,3 @@ -/*--------------------------------*- C++ -*----------------------------------*\ -| ========= | | -| \\ / F ield | OpenFOAM: The Open Source CFD Toolbox | -| \\ / O peration | Version: 7 | -| \\ / A nd | Web: www.OpenFOAM.com | -| \\/ M anipulation | | -\*---------------------------------------------------------------------------*/ -FoamFile -{ - version 2.0; - format ascii; - class volScalarField; - object k; -} -// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // - -dimensions [ 0 2 -2 0 0 0 0 ]; -internalField uniform 3.375; - -boundaryField -{ - #includeEtc "caseDicts/setConstraintTypes" - inlet - { - type fixedValue; - value uniform 3.375; - } - - outlet - { - type zeroGradient; - } - - sides - { - //type kqRWallFunction; - //value uniform 1e-20; - type slip; - } - - ground - { - type kqRWallFunction; - value uniform 3.375; - } - - top - { - //type kqRWallFunction; - //value uniform 1e-20; - type slip; - } - - car - { - type kqRWallFunction; - value uniform 3.375; - } - -} +version https://git-lfs.github.com/spec/v1 +oid sha256:b599768ea2ecec8b6d2f699ceea9336af32b3aba20826ec502df66fb0f175b7e +size 1367 diff --git a/cfd_workflow_20261012/_seiler_ref/example_INIT_30_sim/0/nut b/cfd_workflow_20261012/_seiler_ref/example_INIT_30_sim/0/nut index 7cc736fd68245464e1f551f416639189b1d2c3ee..5f6c83c0b2c744735689d51ff997f05844120fb1 100644 --- a/cfd_workflow_20261012/_seiler_ref/example_INIT_30_sim/0/nut +++ b/cfd_workflow_20261012/_seiler_ref/example_INIT_30_sim/0/nut @@ -1,59 +1,3 @@ -/*--------------------------------*- C++ -*----------------------------------*\ -| ========= | | -| \\ / F ield | OpenFOAM: The Open Source CFD Toolbox | -| \\ / O peration | Version: 7 | -| \\ / A nd | Web: www.OpenFOAM.com | -| \\/ M anipulation | | -\*---------------------------------------------------------------------------*/ -FoamFile -{ - version 2.0; - format ascii; - class volScalarField; - object nut; -} -// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // - -dimensions [ 0 2 -1 0 0 0 0 ]; -internalField uniform 0.0001; - -boundaryField -{ - #includeEtc "caseDicts/setConstraintTypes" - inlet - { - type zeroGradient; - } - - outlet - { - type zeroGradient; - } - - sides - { - //type nutUSpaldingWallFunction; - //value uniform 0.001; - type slip; - } - - ground - { - type nutUSpaldingWallFunction; - value uniform 0.0001; - } - - top - { - //type nutUSpaldingWallFunction; - //value uniform 0.001; - type slip; - } - - car - { - type nutUSpaldingWallFunction; - value uniform 0.0001; - } - -} +version https://git-lfs.github.com/spec/v1 +oid sha256:e29a89f75f157ff99c42b2f5338511921f757a91452575b5b1dc7a2366f289f7 +size 1388 diff --git a/cfd_workflow_20261012/_seiler_ref/example_INIT_30_sim/0/omega b/cfd_workflow_20261012/_seiler_ref/example_INIT_30_sim/0/omega index abb9403abbbecb24411e3e29e7e9ae75c9b5b779..a4c57757c20d60cd577a2d9806fd71d0d63b4e78 100644 --- a/cfd_workflow_20261012/_seiler_ref/example_INIT_30_sim/0/omega +++ b/cfd_workflow_20261012/_seiler_ref/example_INIT_30_sim/0/omega @@ -1,62 +1,3 @@ -/*--------------------------------*- C++ -*----------------------------------*\ -| ========= | | -| \\ / F ield | OpenFOAM: The Open Source CFD Toolbox | -| \\ / O peration | Version: 7 | -| \\ / A nd | Web: www.OpenFOAM.com | -| \\/ M anipulation | | -\*---------------------------------------------------------------------------*/ -FoamFile -{ - version 2.0; - format ascii; - class volScalarField; - object omega; -} -// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // - -dimensions [ 0 0 -1 0 0 0 0 ]; -internalField uniform 9000; - -boundaryField -{ - #includeEtc "caseDicts/setConstraintTypes" - inlet - { - type fixedValue; - value uniform 9000; - } - - outlet - { - type zeroGradient; - } - - sides - { - //type omegaWallFunction; - //value uniform 1; - type slip; - } - - ground - { - type omegaWallFunction; - //value uniform 9000; - value uniform 500000; - } - - top - { - //type omegaWallFunction; - //value uniform 1; - type slip; - } - - car - { - type omegaWallFunction; - //value uniform 9000; - value uniform 500000; - } - -} +version https://git-lfs.github.com/spec/v1 +oid sha256:cbe61f8b4dd72db7cd569310c1810f959328b0797ecbbcc3469ea58b67e6798c +size 1442 diff --git a/cfd_workflow_20261012/_seiler_ref/example_INIT_30_sim/0/p b/cfd_workflow_20261012/_seiler_ref/example_INIT_30_sim/0/p index fc09297236df88eb7bd8fd91833cb28a6bad8464..db51b7a99e33c54dd5e97f1b355f95a0aa45e420 100644 --- a/cfd_workflow_20261012/_seiler_ref/example_INIT_30_sim/0/p +++ b/cfd_workflow_20261012/_seiler_ref/example_INIT_30_sim/0/p @@ -1,56 +1,3 @@ -/*--------------------------------*- C++ -*----------------------------------*\ -| ========= | | -| \\ / F ield | OpenFOAM: The Open Source CFD Toolbox | -| \\ / O peration | Version: 7 | -| \\ / A nd | Web: www.OpenFOAM.com | -| \\/ M anipulation | | -\*---------------------------------------------------------------------------*/ -FoamFile -{ - version 2.0; - format ascii; - class volScalarField; - object p; -} -// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // - -dimensions [ 0 2 -2 0 0 0 0 ]; -internalField uniform 0.0; - -boundaryField -{ - #includeEtc "caseDicts/setConstraintTypes" - inlet - { - type zeroGradient; - } - - outlet - { - type fixedValue; - value uniform 0.0; - } - - sides - { - //type zeroGradient; - type slip; - } - - ground - { - type zeroGradient; - } - - top - { - //type zeroGradient; - type slip; - } - - car - { - type zeroGradient; - } - -} +version https://git-lfs.github.com/spec/v1 +oid sha256:b2c076ebfbd5801985fc179c56b02dafab1b1bc1043a9d5286aaf549b25a3088 +size 1238 diff --git a/cfd_workflow_20261012/_seiler_ref/example_INIT_30_sim/0_org/U b/cfd_workflow_20261012/_seiler_ref/example_INIT_30_sim/0_org/U index 5769e79855336fd3cfd9be718253e66f5c745dd8..dae421d1f90f0d263c09b7c97262271a363540dd 100644 --- a/cfd_workflow_20261012/_seiler_ref/example_INIT_30_sim/0_org/U +++ b/cfd_workflow_20261012/_seiler_ref/example_INIT_30_sim/0_org/U @@ -1,88 +1,3 @@ -/*--------------------------------*- C++ -*----------------------------------*\ -| ========= | | -| \\ / F ield | OpenFOAM: The Open Source CFD Toolbox | -| \\ / O peration | Version: 7 | -| \\ / A nd | Web: www.OpenFOAM.com | -| \\/ M anipulation | | -\*---------------------------------------------------------------------------*/ -FoamFile -{ - version 2.0; - format ascii; - class volVectorField; - object U; -} -// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // - -dimensions [ 0 1 -1 0 0 0 0 ]; -internalField uniform (30 0.0 0.0); - -boundaryField -{ - #includeEtc "caseDicts/setConstraintTypes" - inlet - { - - type fixedValue; - value uniform ( 30.0 0.0 0.0 ); - -/* - type uniformFixedValue; - uniformValue table - ( - (0 (5 0 0)) - //(20 (10 0 0)) - //(40 (15 0 0)) - //(60 (20 0 0)) - //(80 (25 0 0)) - (100 (30 0 0)) - ); -*/ - - } - - outlet - { - //type zeroGradient; - //value uniform ( 0.0 0.0 0.0 ); - - type inletOutlet; - inletValue uniform (30 0 0); - value uniform (30 0 0); - } - - sides - { - type slip; - } - - ground - { - type fixedValue; - value uniform ( 30.0 0.0 0.0 ); - -/* - type uniformFixedValue; - uniformValue table - ( - (0 (5 0 0)) - //(20 (10 0 0)) - //(40 (15 0 0)) - //(60 (20 0 0)) - //(80 (25 0 0)) - (100 (30 0 0)) - ); -*/ - } - - top - { - type slip; - } - - car - { - type fixedValue; - value uniform ( 0 0 0); - } -} +version https://git-lfs.github.com/spec/v1 +oid sha256:562432c8ef08dd9d7a5c4aaa55e256f8c8c996c414fc0d50ac67bad22fb40f95 +size 1907 diff --git a/cfd_workflow_20261012/_seiler_ref/example_INIT_30_sim/0_org/k b/cfd_workflow_20261012/_seiler_ref/example_INIT_30_sim/0_org/k index 3fbd5f6027c8e931e018cc02da50c2bbd0831fc1..751cf632bc059b6a53e1567050fda8329b702db7 100644 --- a/cfd_workflow_20261012/_seiler_ref/example_INIT_30_sim/0_org/k +++ b/cfd_workflow_20261012/_seiler_ref/example_INIT_30_sim/0_org/k @@ -1,60 +1,3 @@ -/*--------------------------------*- C++ -*----------------------------------*\ -| ========= | | -| \\ / F ield | OpenFOAM: The Open Source CFD Toolbox | -| \\ / O peration | Version: 7 | -| \\ / A nd | Web: www.OpenFOAM.com | -| \\/ M anipulation | | -\*---------------------------------------------------------------------------*/ -FoamFile -{ - version 2.0; - format ascii; - class volScalarField; - object k; -} -// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // - -dimensions [ 0 2 -2 0 0 0 0 ]; -internalField uniform 3.375; - -boundaryField -{ - #includeEtc "caseDicts/setConstraintTypes" - inlet - { - type fixedValue; - value uniform 3.375; - } - - outlet - { - type zeroGradient; - } - - sides - { - //type kqRWallFunction; - //value uniform 1e-20; - type slip; - } - - ground - { - type kqRWallFunction; - value uniform 3.375; - } - - top - { - //type kqRWallFunction; - //value uniform 1e-20; - type slip; - } - - car - { - type kqRWallFunction; - value uniform 3.375; - } - -} +version https://git-lfs.github.com/spec/v1 +oid sha256:b599768ea2ecec8b6d2f699ceea9336af32b3aba20826ec502df66fb0f175b7e +size 1367 diff --git a/cfd_workflow_20261012/_seiler_ref/example_INIT_30_sim/0_org/nut b/cfd_workflow_20261012/_seiler_ref/example_INIT_30_sim/0_org/nut index 7cc736fd68245464e1f551f416639189b1d2c3ee..5f6c83c0b2c744735689d51ff997f05844120fb1 100644 --- a/cfd_workflow_20261012/_seiler_ref/example_INIT_30_sim/0_org/nut +++ b/cfd_workflow_20261012/_seiler_ref/example_INIT_30_sim/0_org/nut @@ -1,59 +1,3 @@ -/*--------------------------------*- C++ -*----------------------------------*\ -| ========= | | -| \\ / F ield | OpenFOAM: The Open Source CFD Toolbox | -| \\ / O peration | Version: 7 | -| \\ / A nd | Web: www.OpenFOAM.com | -| \\/ M anipulation | | -\*---------------------------------------------------------------------------*/ -FoamFile -{ - version 2.0; - format ascii; - class volScalarField; - object nut; -} -// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // - -dimensions [ 0 2 -1 0 0 0 0 ]; -internalField uniform 0.0001; - -boundaryField -{ - #includeEtc "caseDicts/setConstraintTypes" - inlet - { - type zeroGradient; - } - - outlet - { - type zeroGradient; - } - - sides - { - //type nutUSpaldingWallFunction; - //value uniform 0.001; - type slip; - } - - ground - { - type nutUSpaldingWallFunction; - value uniform 0.0001; - } - - top - { - //type nutUSpaldingWallFunction; - //value uniform 0.001; - type slip; - } - - car - { - type nutUSpaldingWallFunction; - value uniform 0.0001; - } - -} +version https://git-lfs.github.com/spec/v1 +oid sha256:e29a89f75f157ff99c42b2f5338511921f757a91452575b5b1dc7a2366f289f7 +size 1388 diff --git a/cfd_workflow_20261012/_seiler_ref/example_INIT_30_sim/0_org/omega b/cfd_workflow_20261012/_seiler_ref/example_INIT_30_sim/0_org/omega index abb9403abbbecb24411e3e29e7e9ae75c9b5b779..a4c57757c20d60cd577a2d9806fd71d0d63b4e78 100644 --- a/cfd_workflow_20261012/_seiler_ref/example_INIT_30_sim/0_org/omega +++ b/cfd_workflow_20261012/_seiler_ref/example_INIT_30_sim/0_org/omega @@ -1,62 +1,3 @@ -/*--------------------------------*- C++ -*----------------------------------*\ -| ========= | | -| \\ / F ield | OpenFOAM: The Open Source CFD Toolbox | -| \\ / O peration | Version: 7 | -| \\ / A nd | Web: www.OpenFOAM.com | -| \\/ M anipulation | | -\*---------------------------------------------------------------------------*/ -FoamFile -{ - version 2.0; - format ascii; - class volScalarField; - object omega; -} -// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // - -dimensions [ 0 0 -1 0 0 0 0 ]; -internalField uniform 9000; - -boundaryField -{ - #includeEtc "caseDicts/setConstraintTypes" - inlet - { - type fixedValue; - value uniform 9000; - } - - outlet - { - type zeroGradient; - } - - sides - { - //type omegaWallFunction; - //value uniform 1; - type slip; - } - - ground - { - type omegaWallFunction; - //value uniform 9000; - value uniform 500000; - } - - top - { - //type omegaWallFunction; - //value uniform 1; - type slip; - } - - car - { - type omegaWallFunction; - //value uniform 9000; - value uniform 500000; - } - -} +version https://git-lfs.github.com/spec/v1 +oid sha256:cbe61f8b4dd72db7cd569310c1810f959328b0797ecbbcc3469ea58b67e6798c +size 1442 diff --git a/cfd_workflow_20261012/_seiler_ref/example_INIT_30_sim/0_org/p b/cfd_workflow_20261012/_seiler_ref/example_INIT_30_sim/0_org/p index a6c6175f19ff93896acbb705f2185d1e873fb459..c319ebf11ffbb4343997194ce5ffd58800e69c77 100644 --- a/cfd_workflow_20261012/_seiler_ref/example_INIT_30_sim/0_org/p +++ b/cfd_workflow_20261012/_seiler_ref/example_INIT_30_sim/0_org/p @@ -1,55 +1,3 @@ -/*--------------------------------*- C++ -*----------------------------------*\ -| ========= | | -| \\ / F ield | OpenFOAM: The Open Source CFD Toolbox | -| \\ / O peration | Version: 7 | -| \\ / A nd | Web: www.OpenFOAM.com | -| \\/ M anipulation | | -\*---------------------------------------------------------------------------*/ -FoamFile -{ - version 2.0; - format ascii; - class volScalarField; - object p; -} -// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // - -dimensions [ 0 2 -2 0 0 0 0 ]; -internalField uniform 0.0; - -boundaryField -{ - inlet - { - type zeroGradient; - } - - outlet - { - type fixedValue; - value uniform 0.0; - } - - sides - { - //type zeroGradient; - type slip; - } - - ground - { - type zeroGradient; - } - - top - { - //type zeroGradient; - type slip; - } - - car - { - type zeroGradient; - } - -} +version https://git-lfs.github.com/spec/v1 +oid sha256:a9933435039a1b90677edd393878dabf3c809b34703fb0fd42d30260c2c68999 +size 1191 diff --git a/cfd_workflow_20261012/_seiler_ref/example_INIT_30_sim/constant/extendedFeatureEdgeMesh/car.extendedFeatureEdgeMesh b/cfd_workflow_20261012/_seiler_ref/example_INIT_30_sim/constant/extendedFeatureEdgeMesh/car.extendedFeatureEdgeMesh new file mode 100644 index 0000000000000000000000000000000000000000..7bb682e9a3e3a502999f6667b3938922575e0d6b --- /dev/null +++ b/cfd_workflow_20261012/_seiler_ref/example_INIT_30_sim/constant/extendedFeatureEdgeMesh/car.extendedFeatureEdgeMesh @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:09a7e990bf7cd605eeec3173c7f4f94649a58498d99427c2e177de8850b27a57 +size 214444 diff --git a/cfd_workflow_20261012/_seiler_ref/example_INIT_30_sim/constant/transportProperties b/cfd_workflow_20261012/_seiler_ref/example_INIT_30_sim/constant/transportProperties new file mode 100644 index 0000000000000000000000000000000000000000..c96a5beb6a77b30738b977bcdf55adcc2961c822 --- /dev/null +++ b/cfd_workflow_20261012/_seiler_ref/example_INIT_30_sim/constant/transportProperties @@ -0,0 +1,20 @@ +/*--------------------------------*- C++ -*----------------------------------*\ +| ========= | | +| \\ / F ield | OpenFOAM: The Open Source CFD Toolbox | +| \\ / O peration | Version: 7 | +| \\ / A nd | Web: www.OpenFOAM.com | +| \\/ M anipulation | | +\*---------------------------------------------------------------------------*/ +FoamFile +{ + version 2.0; + format ascii; + class dictionary; + object transportProperties; +} +// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // + +transportModel Newtonian; + +nu nu [0 2 -1 0 0 0 0 ] 1.5881327800829875E-5; + diff --git a/cfd_workflow_20261012/_seiler_ref/example_INIT_30_sim/constant/triSurface/car.stl.ori b/cfd_workflow_20261012/_seiler_ref/example_INIT_30_sim/constant/triSurface/car.stl.ori new file mode 100644 index 0000000000000000000000000000000000000000..ecc30d8b0b33bc6aa118a683e9cce0e7a76bfd64 --- /dev/null +++ b/cfd_workflow_20261012/_seiler_ref/example_INIT_30_sim/constant/triSurface/car.stl.ori @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:75cee1fd8f57047f8d7879a10c62f84245c2b7855d00b0ab02ba1020ccecc743 +size 2193184 diff --git a/cfd_workflow_20261012/_seiler_ref/example_INIT_30_sim/constant/turbulenceProperties b/cfd_workflow_20261012/_seiler_ref/example_INIT_30_sim/constant/turbulenceProperties new file mode 100644 index 0000000000000000000000000000000000000000..a87c7f8a8999fb5a479f5b06c843aac5bbb0d19e --- /dev/null +++ b/cfd_workflow_20261012/_seiler_ref/example_INIT_30_sim/constant/turbulenceProperties @@ -0,0 +1,24 @@ +/*--------------------------------*- C++ -*----------------------------------*\ +| ========= | | +| \\ / F ield | OpenFOAM: The Open Source CFD Toolbox | +| \\ / O peration | Version: 7 | +| \\ / A nd | Web: www.OpenFOAM.com | +| \\/ M anipulation | | +\*---------------------------------------------------------------------------*/ +FoamFile +{ + version 2.0; + format ascii; + class dictionary; + object turbulenceProperties; +} +// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // + +simulationType RAS; + +RAS +{ + RASModel kOmegaSST; + turbulence on; + printCoeffs on; +} diff --git a/cfd_workflow_20261012/_seiler_ref/example_INIT_30_sim/forceCoeffs_car b/cfd_workflow_20261012/_seiler_ref/example_INIT_30_sim/forceCoeffs_car new file mode 100644 index 0000000000000000000000000000000000000000..234e0644650ef54d23efc83dcba928ac7b1d792d --- /dev/null +++ b/cfd_workflow_20261012/_seiler_ref/example_INIT_30_sim/forceCoeffs_car @@ -0,0 +1,20 @@ +#set yr [0:0.25] +set term pngcairo +set output "./images/forceCoeffs.png" +#set xr [0:3000] +set yr [0:2.0] +set key bottom right +set xlabel "Simulation time [s]" +set ylabel "forceCoeff [-]" +set title "Plot of forceCoeffs over simulationtime" +set grid + + +#plot "./postProcessing/car/0/forceCoeffs_0.dat" using ($1):($4) with lines title "lift_{coeff}",\ + "./postProcessing/car/0/forceCoeffs_0.dat" using ($1):($3) with lines title "drag_{coeff}" + +plot "./postProcessing/car/0/forceCoeffs.dat" using ($1):($4) with lines title "lift_{coeff}",\ + "./postProcessing/car/0/forceCoeffs.dat" using ($1):($3) with lines title "drag_{coeff}" + +#pause -1 +#reread \ No newline at end of file diff --git a/cfd_workflow_20261012/_seiler_ref/example_INIT_30_sim/forces b/cfd_workflow_20261012/_seiler_ref/example_INIT_30_sim/forces new file mode 100644 index 0000000000000000000000000000000000000000..771e29e3bd1e38aae30c12dfa0ddaf94d07bb37d --- /dev/null +++ b/cfd_workflow_20261012/_seiler_ref/example_INIT_30_sim/forces @@ -0,0 +1,18 @@ +#set yr [0:0.25] +set term pngcairo +set output "./images/forces.png" +#set xr [0:2000] +set yr [0:500] +set key bottom right +set xlabel "Simulation time [s]" +set ylabel "forces [N]" +set title "Plot of forces over simulationtime" +set grid + +#plot "./postProcessing/forces/0/forces_0.dat" using ($1):($4) with lines title "lift",\ + "./postProcessing/forces/0/forces_0.dat" using ($1):($3) with lines title "drag" + +plot "./postProcessing/forces/0/forces.dat" using ($1):($4) with lines title "lift",\ + "./postProcessing/forces/0/forces.dat" using ($1):($3) with lines title "drag" +#pause -1 +#reread diff --git a/cfd_workflow_20261012/_seiler_ref/example_INIT_30_sim/include/.DS_Store b/cfd_workflow_20261012/_seiler_ref/example_INIT_30_sim/include/.DS_Store new file mode 100644 index 0000000000000000000000000000000000000000..5008ddfcf53c02e82d7eee2e57c38e5672ef89f6 Binary files /dev/null and b/cfd_workflow_20261012/_seiler_ref/example_INIT_30_sim/include/.DS_Store differ diff --git a/cfd_workflow_20261012/_seiler_ref/example_INIT_30_sim/include/config b/cfd_workflow_20261012/_seiler_ref/example_INIT_30_sim/include/config new file mode 100644 index 0000000000000000000000000000000000000000..74deddf7924c12ba1e528c97ab6f04d4b2011156 --- /dev/null +++ b/cfd_workflow_20261012/_seiler_ref/example_INIT_30_sim/include/config @@ -0,0 +1,38 @@ +/*--------------------------------*- C++ -*----------------------------------*\ + ========= | + \\ / F ield | OpenFOAM: The Open Source CFD Toolbox + \\ / O peration | Website: https://openfoam.org + \\ / A nd | Version: 9 + \\/ M anipulation | +\*---------------------------------------------------------------------------*/ +FoamFile +{ + version 2.0; + format ascii; + class dictionary; + object config; +} +// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // + +config +{ + /* controlDict */ + // Area of reference (projected area in x) + Aref 2.303064; + + /* snappyHexMeshDict */ + // Refinement regions + vr1_min ( -7.50 -3.00 -0.30 ); + vr1_max ( 25.00 3.00 3.70 ); + + vr2_min ( -2.13 -1.99 -0.30 ); + vr2_max ( 8.88 1.99 1.79 ); + + vr3_min ( 1.29 -1.49 -0.30 ); + vr3_max ( 7.38 1.49 1.49 ); + + vr4_min ( 1.29 -0.99 -0.30 ); + vr4_max ( 6.08 0.99 1.19 ); +} + +// ************************************************************************* // diff --git a/cfd_workflow_20261012/_seiler_ref/example_INIT_30_sim/include/geometry b/cfd_workflow_20261012/_seiler_ref/example_INIT_30_sim/include/geometry new file mode 100644 index 0000000000000000000000000000000000000000..7dc3dec0ded7efcdede4d9ec4e2a126f3bbace52 --- /dev/null +++ b/cfd_workflow_20261012/_seiler_ref/example_INIT_30_sim/include/geometry @@ -0,0 +1,56 @@ +/*--------------------------------*- C++ -*----------------------------------*\ +| ========= | | +| \\ / F ield | OpenFOAM: The Open Source CFD Toolbox | +| \\ / O peration | Version: 5 | +| \\ / A nd | Web: www.OpenFOAM.org | +| \\/ M anipulation | | +\*---------------------------------------------------------------------------*/ + +//Name of .stl +name_stl car.stl; + +// Computational domain coordinates +x_min -15.0; +x_max 25.0; + +y_min -15.0; +y_max 15.0; + +z_min -0.3; +z_max 14.7; + +cell_division (80 60 30); +// Refinement box coordinates + +//fine box close to the car +x_min_ref -1.25; +x_max_ref 2.0; + +y_min_ref -1.25; +y_max_ref 1.25; + +z_min_ref -0.3; +z_max_ref 1.75; + +//medium box further away +x_min_ref_medium -2.0; +x_max_ref_medium 10.0; + +y_min_ref_medium -1.75; +y_max_ref_medium 1.75; + +z_min_ref_medium -0.3; +z_max_ref_medium 2.25; + +//coarse box just before far field +x_min_ref_coarse -3.0; +x_max_ref_coarse 15.0; + +y_min_ref_coarse -2.75; +y_max_ref_coarse 2.75; + +z_min_ref_coarse -0.3; +z_max_ref_coarse 2.75; + + +// ************************************************************************* // \ No newline at end of file diff --git a/cfd_workflow_20261012/_seiler_ref/example_INIT_30_sim/plots.sh b/cfd_workflow_20261012/_seiler_ref/example_INIT_30_sim/plots.sh new file mode 100644 index 0000000000000000000000000000000000000000..a89c1d1acc01d5ceddb69a4b128297788893e044 --- /dev/null +++ b/cfd_workflow_20261012/_seiler_ref/example_INIT_30_sim/plots.sh @@ -0,0 +1,6 @@ +#!/bin/bash +dict=$1 +mkdir -p ./images +#gnuplot $dict/forces +gnuplot $dict/forceCoeffs_car +gnuplot $dict/residuals \ No newline at end of file diff --git a/cfd_workflow_20261012/_seiler_ref/example_INIT_30_sim/residuals b/cfd_workflow_20261012/_seiler_ref/example_INIT_30_sim/residuals new file mode 100644 index 0000000000000000000000000000000000000000..14e42308536cb9041ca8938686d419d1806d3c57 --- /dev/null +++ b/cfd_workflow_20261012/_seiler_ref/example_INIT_30_sim/residuals @@ -0,0 +1,15 @@ +set term pngcairo +set output "./images/residuals.png" +set logscale y +set yr [0.0000001:1] +set title "Residuals" +set ylabel 'Residual' +set xlabel 'Iteration' +plot "< cat logs/log.solver | grep 'Solving for Ux' | cut -d' ' -f9 | tr -d ','" title 'Ux' with lines,\ + "< cat logs/log.solver | grep 'Solving for Uy' | cut -d' ' -f9 | tr -d ','" title 'Uy' with lines,\ + "< cat logs/log.solver | grep 'Solving for Uz' | cut -d' ' -f9 | tr -d ','" title 'Uz' with lines,\ + "< cat logs/log.solver | grep 'Solving for omega' | cut -d' ' -f9 | tr -d ','" title 'omega' with lines,\ + "< cat logs/log.solver | grep 'Solving for k' | cut -d' ' -f9 | tr -d ','" title 'k' with lines,\ + #"< cat logs/log.solver | grep 'Solving for p' | cut -d' ' -f9 | tr -d ','" title 'p' with lines +#pause -1 +#reread diff --git a/cfd_workflow_20261012/_seiler_ref/example_INIT_30_sim/run_all_shm.sh b/cfd_workflow_20261012/_seiler_ref/example_INIT_30_sim/run_all_shm.sh new file mode 100644 index 0000000000000000000000000000000000000000..8323dc482e8d1aa0918e980aa2dab6ca81ec4d7c --- /dev/null +++ b/cfd_workflow_20261012/_seiler_ref/example_INIT_30_sim/run_all_shm.sh @@ -0,0 +1,72 @@ +#!/bin/bash + +# Verify if already finished by checking the plotting folder +ITERMAX=$(grep -o "endTime *[0-9]* *;" system/controlDict | grep -o "[0-9]*") +if [[ -d images ]] && [[ -d $ITERMAX ]] && [[ -f simulation.done ]]; then + echo "Experiment at $(pwd) is already finished! Passing..." + exit 0 +fi + +mkdir -p logs + +# Following tries to recover automatically the numberOfSubdomains from system/decomposeParDict +procs=$(grep -o "numberOfSubdomains *[0-9]* *;" system/decomposeParDict | grep -o "[0-9]*") +# If doesn't work, set it manually here +if [ -z $procs ]; then + echo "Couldn't read 'numberOfSubdomains' from 'system/decomposeParDict'." + procs=12 +fi +echo "procs set to $procs." +MAXITER=2500 # max iter of the simulations + +# If car.foam exists, then must have at least meshed -> skip +if [[ ! -f car.foam ]]; then + foamCleanTutorials + #rm -rf 0 > /dev/null 2>&1 + + #PART DEDICATED TO MESHING + surfaceFeatures | tee logs/log.surfaceFeatures + blockMesh | tee logs/log.blockMesh + + decomposePar + (time (mpirun -np $procs snappyHexMesh -parallel -overwrite)) 2>&1 | tee logs/log.shm + mpirun -np $procs checkMesh -parallel | tee logs/log.checkMesh + + reconstructParMesh -constant + rm -r ./processor* + + touch car.foam +fi + +#PART DEDICATED TO SOLVER +# If processor0 exists -> must have been doing solver (assuming not already finished and removed!) +if [[ ! -d processor0 ]]; then + decomposePar -force -copyZero + + mpirun -np $procs renumberMesh -parallel -overwrite | tee logs/log.renumber + mpirun -np $procs potentialFoam -parallel -writep | tee logs/log.potential +fi +(time (mpirun -np $procs simpleFoam -parallel)) 2>&1 | tee logs/log.solver + +# If solver has finished, do rest +ENDTIME=$(grep -o "endTime *[0-9]* *;" system/controlDict | grep -o "[0-9]*") +if [[ -d processor0/$ENDTIME ]]; then + reconstructPar -latestTime + + rm -r ./processor* + + ./plots.sh . + + touch car.foam + + touch simulation.done +fi + +# # Copy UMean as U to compute vorticity on UMean automatically +# cp $MAXITER/UMean $MAXITER/U + +# # Compute vorticity +# postProcess -func vorticity -latestTime + +# # Remove copied U (ignore if non-existent) +# rm -f $MAXITER/U diff --git a/cfd_workflow_20261012/_seiler_ref/example_INIT_30_sim/run_mesh_shm.sh b/cfd_workflow_20261012/_seiler_ref/example_INIT_30_sim/run_mesh_shm.sh new file mode 100644 index 0000000000000000000000000000000000000000..361eddfe77dd51d99c455e3553de1889b2508139 --- /dev/null +++ b/cfd_workflow_20261012/_seiler_ref/example_INIT_30_sim/run_mesh_shm.sh @@ -0,0 +1,30 @@ +#!/bin/bash + +# Following tries to recover automatically the numberOfSubdomains from system/decomposeParDict +procs=$(grep -o "numberOfSubdomains *[0-9]* *;" system/decomposeParDict | grep -o "[0-9]*") +# If doesn't work, set it manually here +if [ -z $procs ]; then + echo "Couldn't read 'numberOfSubdomains' from 'system/decomposeParDict'." + procs=12 +fi +echo "procs set to $procs." + +# If car.foam, then must have at least meshed -> skip +if [[ ! -f car.foam ]]; then + foamCleanTutorials + #rm -rf 0 > /dev/null 2>&1 + + surfaceFeatures | tee logs/log.surfaceFeatures + blockMesh | tee logs/log.blockMesh + + decomposePar + (time (mpirun -np $procs snappyHexMesh -parallel -overwrite)) 2>&1 | tee logs/log.shm + mpirun -np $procs checkMesh -parallel | tee logs/log.checkMesh + + reconstructParMesh -constant + # rm -rf 0 > /dev/null 2>&1 + # cp -r 0_org 0 > /dev/null 2>&1 + rm -r ./processor* + + touch car.foam +fi diff --git a/cfd_workflow_20261012/_seiler_ref/example_INIT_30_sim/run_solver_shm.sh b/cfd_workflow_20261012/_seiler_ref/example_INIT_30_sim/run_solver_shm.sh new file mode 100644 index 0000000000000000000000000000000000000000..872d05bd12b28bdf790fe66e148ee13dfd28a118 --- /dev/null +++ b/cfd_workflow_20261012/_seiler_ref/example_INIT_30_sim/run_solver_shm.sh @@ -0,0 +1,32 @@ +#!/bin/bash + +# Following tries to recover automatically the numberOfSubdomains from system/decomposeParDict +procs=$(grep -o "numberOfSubdomains *[0-9]* *;" system/decomposeParDict | grep -o "[0-9]*") +# If doesn't work, set it manually here +if [ -z $procs ]; then + echo "Couldn't read 'numberOfSubdomains' from 'system/decomposeParDict'." + procs=12 +fi +echo "procs set to $procs." + +#PART DEDICATED TO SOLVER +# If processor0 -> must have been doing solver (assuming not already finished and removed!) +if [[ ! -d processor0 ]]; then + decomposePar -force -copyZero + + mpirun -np $procs renumberMesh -parallel -overwrite | tee logs/log.renumber + mpirun -np $procs potentialFoam -parallel -writep | tee logs/log.potential +fi +(time (mpirun -np $procs simpleFoam -parallel)) 2>&1 | tee logs/log.solver + +# If solver has finished, do rest +ENDTIME=$(grep -o "endTime *[0-9]* *;" system/controlDict | grep -o "[0-9]*") +if [[ -d processor0/$ENDTIME ]]; then + reconstructPar -latestTime + + rm -r ./processor* + + ./plots.sh . + + touch car.foam +fi diff --git a/cfd_workflow_20261012/_seiler_ref/example_INIT_30_sim/simulation.done b/cfd_workflow_20261012/_seiler_ref/example_INIT_30_sim/simulation.done new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/cfd_workflow_20261012/_seiler_ref/example_INIT_30_sim/system/.DS_Store b/cfd_workflow_20261012/_seiler_ref/example_INIT_30_sim/system/.DS_Store new file mode 100644 index 0000000000000000000000000000000000000000..5008ddfcf53c02e82d7eee2e57c38e5672ef89f6 Binary files /dev/null and b/cfd_workflow_20261012/_seiler_ref/example_INIT_30_sim/system/.DS_Store differ diff --git a/cfd_workflow_20261012/_seiler_ref/example_INIT_30_sim/system/._snappyHexMeshDict b/cfd_workflow_20261012/_seiler_ref/example_INIT_30_sim/system/._snappyHexMeshDict new file mode 100644 index 0000000000000000000000000000000000000000..2d8c802c5694d932033382b968937ccdc9ccb25f Binary files /dev/null and b/cfd_workflow_20261012/_seiler_ref/example_INIT_30_sim/system/._snappyHexMeshDict differ diff --git a/cfd_workflow_20261012/_seiler_ref/example_INIT_30_sim/system/blockMeshDict b/cfd_workflow_20261012/_seiler_ref/example_INIT_30_sim/system/blockMeshDict new file mode 100644 index 0000000000000000000000000000000000000000..5652745415ba1f9aef73769b9ec8c8e4a479ef8c --- /dev/null +++ b/cfd_workflow_20261012/_seiler_ref/example_INIT_30_sim/system/blockMeshDict @@ -0,0 +1,121 @@ +/*--------------------------------*- C++ -*----------------------------------*\ + ========= | + \\ / F ield | OpenFOAM: The Open Source CFD Toolbox + \\ / O peration | Website: https://openfoam.org + \\ / A nd | Version: 9 + \\/ M anipulation | +\*---------------------------------------------------------------------------*/ +FoamFile +{ + format ascii; + class dictionary; + object blockMeshDict; +} +// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // + +convertToMeters 1; + +x_min -12; +x_max 32; +y_min -4; +y_max 4; +z_min -0.3; +z_max 6.4; + +//xcells 22; +//ycells 4; +//zcells 4; + + +//deltax 0.2; //0.05 +//deltay 0.2; //0.05 +//deltaz 0.2; //0.05 +// +//lx #calc "($xmax) - ($xmin)"; +//ly #calc "($ymax) - ($ymin)"; +//lz #calc "($zmax) - ($zmin)"; +// +//xcells #calc "round(($lx)/($deltax))"; +//ycells #calc "round(($ly)/($deltay))"; +//zcells #calc "round(($lz)/($deltaz))"; + + +xcells 220; // MANUALLY CALCULATED BECAUSE WMAKE FAILED +ycells 40; +zcells 34; + +vertices +( + ($x_min $y_min $z_min) + ($x_max $y_min $z_min) + ($x_max $y_max $z_min) + ($x_min $y_max $z_min) + ($x_min $y_min $z_max) + ($x_max $y_min $z_max) + ($x_max $y_max $z_max) + ($x_min $y_max $z_max) +); + +blocks +( + hex (0 1 2 3 4 5 6 7) ($xcells $ycells $zcells) simpleGrading (1 1 1) +); + +edges +( +); + +boundary +( + inlet + { + type patch; + faces + ( + (0 4 7 3) + ); + } + + outlet + { + type patch; + faces + ( + (2 6 5 1) + ); + } + + sides + { + type patch; + faces + ( + (3 7 6 2) + (0 1 5 4) + ); + } + + ground + { + type wall; + faces + ( + (0 3 2 1) + ); + } + + top + { + type patch; + faces + ( + (4 5 6 7) + ); + } +); + +mergePatchPairs +( +); + +// ************************************************************************* // diff --git a/cfd_workflow_20261012/_seiler_ref/example_INIT_30_sim/system/controlDict b/cfd_workflow_20261012/_seiler_ref/example_INIT_30_sim/system/controlDict new file mode 100644 index 0000000000000000000000000000000000000000..0df518e2872176077cd578ac16072e5bbdf68e64 --- /dev/null +++ b/cfd_workflow_20261012/_seiler_ref/example_INIT_30_sim/system/controlDict @@ -0,0 +1,319 @@ +/*--------------------------------*- C++ -*----------------------------------*\ +| ========= | | +| \\ / F ield | OpenFOAM: The Open Source CFD Toolbox | +| \\ / O peration | Version: 7 | +| \\ / A nd | Web: www.OpenFOAM.com | +| \\/ M anipulation | | +\*---------------------------------------------------------------------------*/ +FoamFile +{ + version 2.0; + format ascii; + class dictionary; + object controlDict; +} +// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // +#include "../include/config" + + +application simpleFoam; + +// startFrom startTime; +startFrom latestTime; + +startTime 0; + +stopAt endTime; + +endTime 2500; //1000-3000-5000 +averageStart 1500; // 1K iters before the end + +deltaT 1; + +writeControl timeStep; + +writeInterval 100; + +/* +secondaryWriteControl cpuTime; +secondaryWriteInterval 1000; +secondaryPurgeWrite 1; +*/ + +purgeWrite 2; + +writeFormat binary; + +writePrecision 12; + +writeCompression off; //uncompressed + +timeFormat general; + +timePrecision 6; + +runTimeModifiable yes; + + + + +// ************************************************************************* // + +functions +{ + +/////////////////////////////////////////////////////////////////////////// +car +{ + log yes; + enabled yes; + + type forceCoeffs; + functionObjectLibs ( "libforces.so"); + + patches ( "car"); + + rho rhoInf; + rhoInf 1.205; + + CofR ( 0 0 0); + liftDir ( 0 0 1); + dragDir ( 1 0 0); + pitchAxis ( 0 1 0); + magUInf 30; + lRef 1; //length in x //1; + Aref $!config/Aref; //projected area in x //drivAer=2.146952 + writeControl timeStep; + writeInterval 1; +} + +/////////////////////////////////////////////////////////////////////////// + + +/////////////////////////////////////////////////////////////////////////// + +yplus +{ + type yPlus; + functionObjectLibs ("libfieldFunctionObjects.so"); + + enabled true; + + writeControl outputTime; + //writeControl timeStep; + writeInterval 25; + + log true; +} + +/////////////////////////////////////////////////////////////////////////// + + +/////////////////////////////////////////////////////////////////////////// +Q +{ + type Q; + functionObjectLibs ("libutilityFunctionObjects.so"); + + enabled true; + + writeControl outputTime; + //writeControl timeStep; + //writeInterval 1; + + //log true; +} +/////////////////////////////////////////////////////////////////////////// + + +/////////////////////////////////////////////////////////////////////////// + +minmaxdomain_scalar +{ + type volFieldValue; + libs ("libfieldFunctionObjects.so"); + + enabled true; //true or false + log true; //write to screen + + //writeControl writeTime; + writeControl timeStep; + writeInterval 1; + + writeFields false; //write solution to field value - Not needed when only reporting value to screen + + writeLocation true; //write location in the output file + + //mode component; + + regionType all; + + operation none; + + fields + ( + p k omega nut + ); +} + +/////////////////////////////////////////////////////////////////////////// + + +/////////////////////////////////////////////////////////////////////////// + +wallShearStress1 +{ + type wallShearStress; + functionObjectLibs ("libutilityFunctionObjects.so"); + + enabled true; + + writeControl outputTime; + //writeControl timeStep; + //writeInterval 1; + + //log true; +} + +/////////////////////////////////////////////////////////////////////////// + + +/////////////////////////////////////////////////////////////////////////// + + fieldAverage + { + type fieldAverage; + functionObjectLibs ("libfieldFunctionObjects.so"); + enabled true; + writeControl outputTime; + + //writeControl timeStep; + //writeInterval 100; + + //cleanRestart true; + + timeStart $!averageStart; // see top of file, should be 1K iters before endTime + //timeEnd 1000; + + fields + ( + U + { + mean on; + prime2Mean on; + base time; + } + + p + { + mean on; + prime2Mean on; + base time; + } + + nut + { + mean on; + prime2Mean on; + base time; + } + + k + { + mean on; + prime2Mean off; + base time; + } + + omega + { + mean on; + prime2Mean off; + base time; + } + + Q + { + mean on; + prime2Mean off; + base time; + } + + yPlus + { + mean on; + prime2Mean off; + base time; + } + + wallShearStress + { + mean on; + prime2Mean off; + base time; + } + + ); + } + +/////////////////////////////////////////////////////////////////////////// + + +/////////////////////////////////////////////////////////////////////////// + +minmaxdomain_vector +{ + type volFieldValue; + libs ("libfieldFunctionObjects.so"); + + enabled true; //true or false + log true; //write to screen + + //writeControl writeTime; + writeControl timeStep; + writeInterval 1; + + writeFields false; //write solution to field value - Not needed when only reporting value to screen + + writeLocation true; //write location in the output file + + //mode component; + + regionType all; + + operation none; + + fields + ( + U + ); +} + +mindomain_scalar +{ + $minmaxdomain_scalar + operation min; +} + +mindomain_vector +{ + $minmaxdomain_vector + operation minMag; +} + +maxdomain_scalar +{ + $minmaxdomain_scalar + operation max; +} + +maxdomain_vector +{ + $minmaxdomain_vector + operation maxMag; +} + +/////////////////////////////////////////////////////////////////////////// + + +}; diff --git a/cfd_workflow_20261012/_seiler_ref/example_INIT_30_sim/system/decomposeParDict b/cfd_workflow_20261012/_seiler_ref/example_INIT_30_sim/system/decomposeParDict new file mode 100644 index 0000000000000000000000000000000000000000..00f514fbd0580aab4e4f2d1558b52cb2263c082d --- /dev/null +++ b/cfd_workflow_20261012/_seiler_ref/example_INIT_30_sim/system/decomposeParDict @@ -0,0 +1,19 @@ +/*--------------------------------*- C++ -*----------------------------------*\ +| ========= | | +| \\ / F ield | OpenFOAM: The Open Source CFD Toolbox | +| \\ / O peration | Version: 7 | +| \\ / A nd | Web: www.OpenFOAM.com | +| \\/ M anipulation | | +\*---------------------------------------------------------------------------*/ +FoamFile +{ + version 2.0; + format ascii; + class dictionary; + object decomposeParDict; +} +// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // + + numberOfSubdomains 12; + method scotch; + diff --git a/cfd_workflow_20261012/_seiler_ref/example_INIT_30_sim/system/fvConstraints b/cfd_workflow_20261012/_seiler_ref/example_INIT_30_sim/system/fvConstraints new file mode 100644 index 0000000000000000000000000000000000000000..f118edd9bdd5683dca879a301623ed4143299b9f --- /dev/null +++ b/cfd_workflow_20261012/_seiler_ref/example_INIT_30_sim/system/fvConstraints @@ -0,0 +1,28 @@ +/*--------------------------------*- C++ -*----------------------------------*\ + ========= | + \\ / F ield | OpenFOAM: The Open Source CFD Toolbox + \\ / O peration | Website: https://openfoam.org + \\ / A nd | Version: 9 + \\/ M anipulation | +\*---------------------------------------------------------------------------*/ +FoamFile +{ + format ascii; + class dictionary; + object fvConstraints; +} +// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // + +//To control on/off just modify the value. +//In this case a large value is like off +//Use from the begining so the object it is created + +limitU +{ + type limitVelocity; + selectionMode all; + max 200; //100 - 10000 (large value is off) +} + +//************************************************************************** // + diff --git a/cfd_workflow_20261012/_seiler_ref/example_INIT_30_sim/system/fvSchemes b/cfd_workflow_20261012/_seiler_ref/example_INIT_30_sim/system/fvSchemes new file mode 100644 index 0000000000000000000000000000000000000000..7a9c59cdd42076680fbe1bb63b998855aed1cf67 --- /dev/null +++ b/cfd_workflow_20261012/_seiler_ref/example_INIT_30_sim/system/fvSchemes @@ -0,0 +1,69 @@ +/*--------------------------------*- C++ -*----------------------------------*\ + ========= | + \\ / F ield | OpenFOAM: The Open Source CFD Toolbox + \\ / O peration | Website: https://openfoam.org + \\ / A nd | Version: 9 + \\/ M anipulation | +\*---------------------------------------------------------------------------*/ +FoamFile +{ + format ascii; + class dictionary; + object fvSchemes; +} +// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // + + ddtSchemes + { + default steadyState; + } + + gradSchemes + { + //default Gauss linear; + default cellLimited Gauss linear 1; + grad(U) cellLimited Gauss linear 1; + grad(k) cellLimited Gauss linear 1; + grad(omega) cellLimited Gauss linear 1; + grad(p) cellLimited Gauss linear 0.333; + } + + divSchemes + { + default none; + + //div(phi,U) bounded Gauss linearUpwindV grad(U); + div(phi,U) bounded Gauss linearUpwind grad(U); + + //div(phi,k) bounded Gauss linearUpwind grad(k); + //div(phi,omega) bounded Gauss linearUpwind grad(omega); + div(phi,k) bounded Gauss upwind; + div(phi,omega) bounded Gauss upwind; + + div((nuEff*dev2(T(grad(U))))) Gauss linear; + +//For potentialFoam + div(div(phi,U)) Gauss linear; + + } + + interpolationSchemes + { + //default linear; + default skewCorrected linear; + } + + laplacianSchemes + { + default Gauss linear limited 0.5; + } + + snGradSchemes + { + default limited 0.5; + } + + wallDist + { + method meshWave; + } diff --git a/cfd_workflow_20261012/_seiler_ref/example_INIT_30_sim/system/fvSolution b/cfd_workflow_20261012/_seiler_ref/example_INIT_30_sim/system/fvSolution new file mode 100644 index 0000000000000000000000000000000000000000..4aa7bb6ebab56df1247323c121661d4bd7988950 --- /dev/null +++ b/cfd_workflow_20261012/_seiler_ref/example_INIT_30_sim/system/fvSolution @@ -0,0 +1,181 @@ +/*--------------------------------*- C++ -*----------------------------------*\ + ========= | + \\ / F ield | OpenFOAM: The Open Source CFD Toolbox + \\ / O peration | Website: https://openfoam.org + \\ / A nd | Version: 9 + \\/ M anipulation | +\*---------------------------------------------------------------------------*/ +FoamFile +{ + format ascii; + class dictionary; + object fvSolution; +} +// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // + + solvers + { + p + { + + solver GAMG; + tolerance 1e-06; + relTol 0.01; + smoother GaussSeidel; + nPreSweeps 0; + nPostSweeps 2; + nFinestSweeps 2; + cacheAgglomeration on; + nCellsInCoarsestLevel 10; + agglomerator faceAreaPair; + mergeLevels 1; +/* + + solver PCG; + preconditioner + { + preconditioner GAMG; + tolerance 1e-06; //1e-06 1e-08 + relTol 0.0; //0.01 0 + nVcycles 2; + smoother GaussSeidel; + nPreSweeps 0; + nPostSweeps 2; + nFinestSweeps 2; + cacheAgglomeration false; + nCellsInCoarsestLevel 10; + agglomerator faceAreaPair; + mergeLevels 1; + } + + tolerance 1e-06; + relTol 0.01; + //maxIter 20; + + + solver PCG; + preconditioner DIC; + tolerance 1e-6; + relTol 0.01; +*/ + + minIter 3; + } + + U + { + solver PBiCGStab; + preconditioner DILU; + tolerance 1e-08; //1e-08 + relTol 0.001; //0.1 0.01 + + minIter 3; + } + + k + { + solver PBiCGStab; + preconditioner DILU; + tolerance 1e-08; //1e-08 + relTol 0.001; //0.1 0.01 + + minIter 3; + } + + omega + { + solver PBiCGStab; + preconditioner DILU; + tolerance 1e-08; //1e-08 + relTol 0.001; //0.1 0.01 + + minIter 3; + } + +/* + Phi + { + $p; + } +*/ + + Phi + { + solver GAMG; + agglomerator faceAreaPair; + mergeLevels 1; + cacheAgglomeration true; + nCellsInCoarsestLevel 200; + tolerance 1e-8; + relTol 0.001; + smoother GaussSeidel; + nPreSweeps 0; + nPostSweeps 2; + nFinestSweeps 2; + minIter 3; + } + + } + + potentialFlow + { + nNonOrthogonalCorrectors 10; + } + + SIMPLE + { + consistent yes; + nNonOrthogonalCorrectors 2; + + pRefCell 0; + pRefValue 0; + + residualControl + { + p 1.0e-4; + U 1.0e-4; + k 1.0e-4; + omega 1.0e-4; + } + + } + +//SIMPLE +/* + relaxationFactors + { + fields + { + p 0.3; + } + + equations + { + U 0.7; + k 0.5; + omega 0.5; + } + + } +*/ + +//SIMPLEC + + relaxationFactors + { + fields + { + //".*" 0.7; + p 0.9; + } + equations + { + //".*" 0.7; + p 0.9; + U 0.7; + k 0.7; + omega 0.7; + } + } + + diff --git a/cfd_workflow_20261012/_seiler_ref/example_INIT_30_sim/system/meshQualityDict b/cfd_workflow_20261012/_seiler_ref/example_INIT_30_sim/system/meshQualityDict new file mode 100644 index 0000000000000000000000000000000000000000..485ffbf78a759b69fa33e50f8ecb96245a82bfa5 --- /dev/null +++ b/cfd_workflow_20261012/_seiler_ref/example_INIT_30_sim/system/meshQualityDict @@ -0,0 +1,48 @@ +/*--------------------------------*- C++ -*----------------------------------*\ + ========= | + \\ / F ield | OpenFOAM: The Open Source CFD Toolbox + \\ / O peration | Website: https://openfoam.org + \\ / A nd | Version: 9 + \\/ M anipulation | +\*---------------------------------------------------------------------------*/ +FoamFile +{ + format ascii; + class dictionary; + object meshQualityDict; +} +// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // + + +maxNonOrtho 75; +maxBoundarySkewness 4; //Original 20 for better quality 4 +maxInternalSkewness 4; + +/* +maxNonOrtho 180; +maxBoundarySkewness -1; +maxInternalSkewness -1; +*/ + +maxConcave 80; + +minVol 1e-13; + +minTetQuality -1e+30; + +minArea -1; + +minTwist 0.02; + +minDeterminant 0.001; + +minFaceWeight 0.05; +//minFaceWeight 0.02; + +minVolRatio 0.01; + +minTriangleTwist -1; + +//minFlatness 0.5; + +// ************************************************************************* // diff --git a/cfd_workflow_20261012/_seiler_ref/example_INIT_30_sim/system/snappyHexMeshDict b/cfd_workflow_20261012/_seiler_ref/example_INIT_30_sim/system/snappyHexMeshDict new file mode 100644 index 0000000000000000000000000000000000000000..a4c34526ab1098437a9dc2076065f0ef5064d0cb --- /dev/null +++ b/cfd_workflow_20261012/_seiler_ref/example_INIT_30_sim/system/snappyHexMeshDict @@ -0,0 +1,322 @@ +/*--------------------------------*- C++ -*----------------------------------*\ +| ========= | | +| \\ / F ield | OpenFOAM: The Open Source CFD Toolbox | +| \\ / O peration | Version: 7 | +| \\ / A nd | Web: www.OpenFOAM.com | +| \\/ M anipulation | | +\*---------------------------------------------------------------------------*/ +FoamFile +{ + version 2.0; + format ascii; + class dictionary; + object snappyHexMeshDict; +} +// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // +#include "../include/config" + +/***************************************************/ +castellatedMesh true; +snap true; +addLayers true; +/***************************************************/ + + + +/***************************************************/ + +geometry +{ + + car.stl + { + type triSurfaceMesh; + name car; + } + + + vr1 + { + type searchableBox; + min $!config/vr1_min; + max $!config/vr1_max; + } + + vr2 + { + type searchableBox; + min $!config/vr2_min; + max $!config/vr2_max; + } + + vr3 + { + type searchableBox; + min $!config/vr3_min; + max $!config/vr3_max; + } + + vr4 + { + type searchableBox; + min $!config/vr4_min; + max $!config/vr4_max; + } + + + /* + vr1 + { + type searchableBox; + min ( -7.5 -3.0 -0.3 ); + max ( 25.0 3.0 3.7 ); + } + + vr2 + { + type searchableBox; + //min ( -3.0 0.0 0.0 ); + //max ( 15.0 2.0 3.0 ); + min ( -2.0 -2.0 -0.3 ); + max ( 9.0 2.0 1.7 ); // 6.0 2.0 1.7 + } + + vr3 + { + type searchableBox; + min ( 2.5 -1.5 -0.3 ); + max ( 7.5 1.5 1.4 ); // 6.5 1.5 1.4 + } + + vr4 + { + type searchableBox; + min ( 3.2 -1 -0.3 ); + max ( 6.2 1.0 1.0 ); // 5.2 1.0 1.0 + } + */ +} + +/***************************************************/ + + + +/***************************************************/ + +castellatedMeshControls +{ + + maxLocalCells 5000000; + maxGlobalCells 30000000; //******* + minRefinementCells 0; + nCellsBetweenLevels 10; // 5 + resolveFeatureAngle 30.0; //curvature + allowFreeStandingZoneFaces true; + planarAngle 30.0; + maxLoadUnbalance 0.1; + + locationInMesh (10.0 1.0 1.0 ); + + +////////////////////////////////////// + features + ( + + { + file "car.eMesh"; + levels ((0.025 0)); + //level 0; + } + + ); +////////////////////////////////////// + + +////////////////////////////////////// + refinementSurfaces + { + car + { + level ( 4 5 ); // 2 4 - 4 4 + } + + } +////////////////////////////////////// + + +////////////////////////////////////// + refinementRegions + { + + vr1 + { + mode inside; + levels (( 1E5 1 )); + } + + vr2 + { + mode inside; + levels (( 1E5 2 )); + } + + vr3 + { + mode inside; + levels (( 1E5 3 )); + } + + vr4 + { + mode inside; + levels (( 1E5 4 )); // 1E5 4 + } + + } +////////////////////////////////////// + +} + +/***************************************************/ + + + +/***************************************************/ + +snapControls +{ + +// Number of patch smoothing iterations before finding correspondence +// to surface +nSmoothPatch 3; //recommended +//nSmoothPatch 10; //improved + +tolerance 2.0; +//tolerance 1.0; + +nSolveIter 30; //recommended +//nSolveIter 100; //improved + +nRelaxIter 5; //default +//nRelaxIter 10; //improved 10-20-50 + +// Feature snapping + + // Number of feature edge snapping iterations. + // Leave out altogether to disable. + nFeatureSnapIter 10; //recommended + //nFeatureSnapIter 100; //improved 20-50-100 + + // Detect (geometric only) features by sampling the surface + // (default=false). + implicitFeatureSnap false; + + // Use castellatedMeshControls::features (default = true) + explicitFeatureSnap true; + + // Detect features between multiple surfaces + // (only for explicitFeatureSnap, default = false) + multiRegionFeatureSnap false; + +} + +/***************************************************/ + + + + +/***************************************************/ + +addLayersControls +{ + +///////////////////////////////////////////// + relativeSizes true; + + expansionRatio 1.2; //1.0; + finalLayerThickness 0.3; + minThickness 0.01; //0.1 0.25 +///////////////////////////////////////////// + + + layers + { + + car + { + nSurfaceLayers 6; + expansionRatio 1.1; + finalLayerThickness 0.3; + minThickness 0.01; + } + + ground + { + nSurfaceLayers 6; + expansionRatio 1.2; + finalLayerThickness 0.3; + minThickness 0.01; + } + + } + + +///////////////////////////////////////////// + nGrow 0; + + featureAngle 130.0; + + maxFaceThicknessRatio 0.5; + + nSmoothSurfaceNormals 1; + nSmoothNormals 3; + nSmoothThickness 10; + + slipFeatureAngle 30.0; + nRelaxIter 5; + + maxThicknessToMedialRatio 0.3; + + minMedialAxisAngle 90; + minMedianAxisAngle 90; + + nBufferCellsNoExtrude 0; + nLayerIter 50; + nRelaxedIter 20; + + //writeVTK false; + //noErrors false; + //layerRecovery 1; + //growZoneLayers false; + //projectGrownUp 0.0; +///////////////////////////////////////////// + +} + +/***************************************************/ + + + + +/***************************************************/ + +meshQualityControls +{ + #include "meshQualityDict" + + nSmoothScale 4; + errorReduction 0.75; + + relaxed + { + maxNonOrtho 75; + } + +} + +/***************************************************/ + + +debug 0; +mergeTolerance 1.0E-6; +//autoBlockMesh false; diff --git a/cfd_workflow_20261012/_seiler_ref/example_INIT_30_sim/system/surfaceFeaturesDict b/cfd_workflow_20261012/_seiler_ref/example_INIT_30_sim/system/surfaceFeaturesDict new file mode 100644 index 0000000000000000000000000000000000000000..b98166722df51048ec84e897563c807290f7b37c --- /dev/null +++ b/cfd_workflow_20261012/_seiler_ref/example_INIT_30_sim/system/surfaceFeaturesDict @@ -0,0 +1,34 @@ +/*--------------------------------*- C++ -*----------------------------------*\ + ========= | + \\ / F ield | OpenFOAM: The Open Source CFD Toolbox + \\ / O peration | Website: https://openfoam.org + \\ / A nd | Version: 9 + \\/ M anipulation | +\*---------------------------------------------------------------------------*/ +FoamFile +{ + format ascii; + class dictionary; + object surfaceFeatureExtractDict; +} +// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // + +surfaces ("car.stl"); + +extractionMethod extractFromSurface; + +includedAngle 150; + +subsetFeatures +{ + // Keep nonManifold edges (edges with >2 connected faces) + nonManifoldEdges yes; + + // Keep open edges (edges with 1 connected face) + openEdges yes; +} + +// Write features to obj format for postprocessing +writeObj yes; + +// ************************************************************************* // diff --git a/cfd_workflow_20261012/_seiler_ref/physiopt_new_scripts/compute_force_chair.py b/cfd_workflow_20261012/_seiler_ref/physiopt_new_scripts/compute_force_chair.py new file mode 100644 index 0000000000000000000000000000000000000000..777e4b7722aeb84a3a443b7cd0a1636db8cfced4 --- /dev/null +++ b/cfd_workflow_20261012/_seiler_ref/physiopt_new_scripts/compute_force_chair.py @@ -0,0 +1,259 @@ +import argparse +import trimesh +import numpy as np +import matplotlib.pyplot as plt +from mpl_toolkits.mplot3d.art3d import Poly3DCollection +import os +import json + + +def detect_seat_bbox_auto(mesh_path, up_axis=1, shrink_factor=0.60): + """ + Détecte la Bounding Box de l'assise d'une chaise avec calcul automatique de l'épaisseur. + - shrink_factor: Réduit la taille (X, Z) pour analyser uniquement le "cœur" de l'assise + et éviter de prendre en compte les pieds sur les côtés. (0.60 = 60% du centre) + """ + # 1. Charger le mesh + mesh = trimesh.load(mesh_path, force='mesh') + up_vector = np.zeros(3) + up_vector[up_axis] = 1.0 + bounds_min, bounds_max = mesh.bounds + mesh.vertices = (mesh.vertices - bounds_min) / (bounds_max - bounds_min) + + # 2. Filtrer les faces horizontales + dot_products = np.dot(mesh.face_normals, up_vector) + horizontal_faces_mask = dot_products > 0.85 + + if not np.any(horizontal_faces_mask): + return None, None, mesh + + horizontal_faces = mesh.faces[horizontal_faces_mask] + horizontal_vertices = mesh.vertices[np.unique(horizontal_faces.flatten())] + + # 3. Trouver la hauteur principale de l'assise + heights = horizontal_vertices[:, up_axis] + hist, bin_edges = np.histogram(heights, bins=30, range=(0, 1)) + peak_bin = np.argmax(hist) + seat_height_center = (bin_edges[peak_bin] + bin_edges[peak_bin + 1]) / 2.0 + + # 4. Isoler les sommets de la surface de l'assise + seat_vertices = horizontal_vertices[np.abs(horizontal_vertices[:, up_axis] - seat_height_center) < 0.05] + if len(seat_vertices) == 0: + return None, None, mesh + + # Bounding Box de base de la surface + min_bounds = np.min(seat_vertices, axis=0) + max_bounds = np.max(seat_vertices, axis=0) + + # 5. Réduire vers le centre sur les axes horizontaux + axes_horizontaux = [i for i in range(3) if i != up_axis] + for axis in axes_horizontaux: + center = (max_bounds[axis] + min_bounds[axis]) / 2.0 + length = max_bounds[axis] - min_bounds[axis] + min_bounds[axis] = center - (length * shrink_factor / 2.0) + max_bounds[axis] = center + (length * shrink_factor / 2.0) + + # --- 6. CALCUL AUTOMATIQUE DE L'ÉPAISSEUR --- + + # On récupère les limites X et Z de notre "colonne" centrale + min_h1, min_h2 = min_bounds[axes_horizontaux[0]], min_bounds[axes_horizontaux[1]] + max_h1, max_h2 = max_bounds[axes_horizontaux[0]], max_bounds[axes_horizontaux[1]] + + # On sélectionne tous les points du mesh complet qui sont dans cette colonne + col_mask = (mesh.vertices[:, axes_horizontaux[0]] >= min_h1) & \ + (mesh.vertices[:, axes_horizontaux[0]] <= max_h1) & \ + (mesh.vertices[:, axes_horizontaux[1]] >= min_h2) & \ + (mesh.vertices[:, axes_horizontaux[1]] <= max_h2) + column_vertices = mesh.vertices[col_mask] + + y_values = column_vertices[:, up_axis] + + def find_boundary(y_array, direction, gap_threshold=0.04): + # direction: -1 pour chercher vers le bas, 1 pour chercher vers le haut + if len(y_array) == 0: + return seat_height_center + + # Trier les hauteurs (décroissant si on va vers le bas, croissant si on va vers le haut) + if direction == -1: + y_sorted = np.sort(y_array[y_array <= seat_height_center + 0.01])[::-1] + else: + y_sorted = np.sort(y_array[y_array >= seat_height_center - 0.01]) + + if len(y_sorted) < 2: + return y_sorted[0] if len(y_sorted)>0 else seat_height_center + + # Calculer l'espace (gap) entre chaque point consécutif + gaps = np.abs(y_sorted[:-1] - y_sorted[1:]) + + # Trouver le premier endroit où le trou est plus grand que notre seuil + large_gaps = np.where(gaps > gap_threshold)[0] + + if len(large_gaps) > 0: + return y_sorted[large_gaps[0]] # On renvoie le point juste avant le vide + return y_sorted[-1] # Si c'est un bloc plein jusqu'au bout, on prend la fin + + # 1. Calculer le bas et le haut EXACTS de l'assise + # (Attention, j'ai remis gap_threshold=0.04 pour le bottom, tu avais mis 0.4 dans ton message, + # ce qui risquait de faire descendre la boîte jusqu'au sol !) + seat_bottom_exact = find_boundary(y_values, direction=-1, gap_threshold=0.4) + seat_top_exact = find_boundary(y_values, direction=1, gap_threshold=0.04) + + # 2. Définir tes marges (ex: 0.02 = 2% de la hauteur totale de la chaise) + margin_bottom = 0.02 + margin_top = 0.02 + + # 3. Appliquer les marges tout en restant dans les limites normalisées (0.0 à 1.0) + seat_bottom = max(0.0, seat_bottom_exact - margin_bottom) + seat_top = min(1.0, seat_top_exact + margin_top) + + min_bounds[up_axis] = seat_bottom + max_bounds[up_axis] = seat_top + + return min_bounds, max_bounds, mesh + + +def get_box_faces(min_b, max_b): + """Génère les 6 faces d'une Bounding Box 3D pour matplotlib.""" + x0, y0, z0 = min_b + x1, y1, z1 = max_b + verts = [ + [x0, y0, z0], [x1, y0, z0], [x1, y1, z0], [x0, y1, z0], + [x0, y0, z1], [x1, y0, z1], [x1, y1, z1], [x0, y1, z1] + ] + faces = [ + [verts[0], verts[1], verts[2], verts[3]], + [verts[4], verts[5], verts[6], verts[7]], + [verts[0], verts[1], verts[5], verts[4]], + [verts[2], verts[3], verts[7], verts[6]], + [verts[1], verts[2], verts[6], verts[5]], + [verts[0], verts[3], verts[7], verts[4]] + ] + return faces + + +def render_chair_bbox(mesh, min_bound, max_bound, output_filename): + """Génère 1 seule image contenant les 3 rendus avec correction de l'axe vertical (Y -> Z).""" + + # 1. Échantillonner le mesh + num_vertices = len(mesh.vertices) + step = max(1, num_vertices // 5000) + sampled_vertices = mesh.vertices[::step] + + # --- L'ASTUCE EST ICI --- + # On isole les axes et on échange Y et Z pour l'affichage matplotlib + x_plot = sampled_vertices[:, 0] + y_plot = sampled_vertices[:, 2] # La profondeur du mesh devient l'axe Y de matplotlib + z_plot = sampled_vertices[:, 1] # La hauteur du mesh (Y) devient l'axe vertical Z de matplotlib + + # 2. Récupérer les faces de la boîte et échanger aussi Y et Z + box_faces = get_box_faces(min_bound, max_bound) + box_faces_z_up = [] + for face in box_faces: + # Pour chaque point [x, y, z], on crée [x, z, y] + new_face = [[v[0], v[2], v[1]] for v in face] + box_faces_z_up.append(new_face) + + # 3. Récupérer les limites et échanger Y et Z + b = mesh.bounds + min_x, max_x = b[0][0], b[1][0] + min_y, max_y = b[0][2], b[1][2] # Ancien Z + min_z, max_z = b[0][1], b[1][1] # Ancien Y + + # 4. Définir les vues adaptées (Maintenant que Z est bien en haut) + views = [ + {"name": "Isométrique", "elev": 20, "azim": -45}, + {"name": "Face", "elev": 0, "azim": -90}, # Regarde l'avant de la chaise + {"name": "Profil", "elev": 0, "azim": 0} # Regarde le côté + ] + + fig = plt.figure(figsize=(18, 6)) + + for i, view in enumerate(views, start=1): + ax = fig.add_subplot(1, 3, i, projection='3d') + + # A. Dessiner la chaise avec nos axes modifiés + ax.scatter( + x_plot, y_plot, z_plot, + c='gray', s=2, alpha=0.4, marker='.' + ) + + # B. Dessiner la Bounding Box avec nos axes modifiés + box_col = Poly3DCollection(box_faces_z_up, alpha=0.4, facecolors='red', edgecolors='darkred') + ax.add_collection3d(box_col) + + # C. Cadrage de la caméra + ax.set_xlim(min_x, max_x) + ax.set_ylim(min_y, max_y) + ax.set_zlim(min_z, max_z) + + # Conserver les proportions + try: + ax.set_box_aspect((max_x-min_x, max_y-min_y, max_z-min_z)) + except AttributeError: + pass + + # Appliquer l'angle de vue + ax.view_init(elev=view["elev"], azim=view["azim"]) + ax.set_title(f"Vue : {view['name']}") + ax.set_axis_off() + + plt.tight_layout() + plt.savefig(output_filename, dpi=150, bbox_inches='tight') + plt.close(fig) + + +def main(): + parser = argparse.ArgumentParser(description="Batch process chair meshes to extract seat bbox.") + parser.add_argument("--folder", required=True, help="Input directory containing chair folders.") + parser.add_argument("--instance-file", required=True, help="File with instance to optimize") + parser.add_argument("-s", "--shrink", type=float, default=0.60, help="Shrink factor for bbox (default: 0.60).") + parser.add_argument("-r", "--rotation", choices=['none', 'x_up', 'y_up'], default='y_up', help="Rotation fix (default: y_up).") + args = parser.parse_args() + + # Chemins ajustés + input_folder = f"/scratch/cvlab/home/seiler/physiopt_new/output/hunyuan_gen/{args.folder}" + output_folder = f"/scratch/cvlab/home/seiler/physiopt_new/output_force/hunyuan_gen/{args.folder}" + os.makedirs(output_folder, exist_ok=True) + print(f"Processing folders in: {input_folder}") + + with open(os.path.join("file_for_exp", args.instance_file), "r") as f: + instance_optimize = json.load(f) + count = 0 + + for folder_name in os.listdir(input_folder): + if folder_name in instance_optimize: + input_subdir = os.path.join(input_folder, folder_name) + mesh_file = os.path.join(input_subdir, "generated_mesh.obj") + + if os.path.isdir(input_subdir) and os.path.exists(mesh_file): + out_subdir = os.path.join(output_folder, folder_name) + os.makedirs(out_subdir, exist_ok=True) + + try: + # Traitement de la chaise + min_bounds, max_bounds, mesh = detect_seat_bbox_auto(mesh_file) + # Construction de l'output force [x_min, x_max, y_min, y_max, z_min, z_max] + config = { + "force": [0.0, -300000.0, 0.0], + "force_region_mode": "bbox", + "force_bbox_ratio": [ + float(min_bounds[0]), float(max_bounds[0]), + float(min_bounds[1]), float(max_bounds[1]), + float(min_bounds[2]), float(max_bounds[2]) + ] + } + + with open(os.path.join(out_subdir, "force_config.json"), 'w') as f: + json.dump(config, f, indent=2) + + render_chair_bbox(mesh, min_bounds, max_bounds, os.path.join(out_subdir, "plot.png")) + print(f"✅ Success: {folder_name}") + count += 1 + + except Exception as e: + print(f"❌ Failed: {folder_name} | Error: {e}") + + print(f"🎉 Batch processing complete for {count} shapes") + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/cfd_workflow_20261012/_seiler_ref/physiopt_new_scripts/compute_force_table.py b/cfd_workflow_20261012/_seiler_ref/physiopt_new_scripts/compute_force_table.py new file mode 100644 index 0000000000000000000000000000000000000000..e0f2cb0ea1f1e045be9e99a28a9d658d9b4aea8d --- /dev/null +++ b/cfd_workflow_20261012/_seiler_ref/physiopt_new_scripts/compute_force_table.py @@ -0,0 +1,154 @@ +import argparse +import trimesh +import numpy as np + +import matplotlib.pyplot as plt +from mpl_toolkits.mplot3d.art3d import Poly3DCollection +import os +import json + +def process_mesh(mesh_path, rot_fix, margin): + """Loads mesh, fixes orientation, normalizes Z, and calculates t_final.""" + mesh = trimesh.load(mesh_path, force='mesh') + + # Fix orientation + if rot_fix == 'y_up': + q = trimesh.transformations.quaternion_about_axis(np.radians(90), [1, 0, 0]) + mesh.apply_transform(trimesh.transformations.quaternion_matrix(q)) + elif rot_fix == 'x_up': + q = trimesh.transformations.quaternion_about_axis(np.radians(-90), [1, 0, 0]) + mesh.apply_transform(trimesh.transformations.quaternion_matrix(q)) + + # Normalize Z axis between 0 and 1 + z_min, z_max = mesh.vertices[:, 2].min(), mesh.vertices[:, 2].max() + mesh.vertices[:, 2] = (mesh.vertices[:, 2] - z_min) / (z_max - z_min) + + # Find downward-facing faces in the upper half of the mesh + mask = (mesh.face_normals[:, 2] < -0.8) & (mesh.triangles_center[:, 2] > 0.5) + z_vals = np.round(mesh.triangles_center[mask, 2], decimals=3) + areas = mesh.area_faces[mask] + + # Find the Z level with the largest flat area + unique_z = np.unique(z_vals) + t_exact = unique_z[np.argmax([np.sum(areas[z_vals == z]) for z in unique_z])] + + # Calculate t_final with the adaptive margin + t_final = float(t_exact - ((1.0 - t_exact) * margin)) + return mesh, t_final + + +def save_plot(mesh, t, save_path): + """Saves a 3D PNG plot instantly using a point cloud for the mesh.""" + fig = plt.figure(figsize=(18, 6)) + + # 1. Obtenir les limites pour la taille du plan + b = mesh.bounds + mx, my = (b[1] - b[0])[:2] * 0.2 + min_x, max_x = b[0][0] - mx, b[1][0] + mx + min_y, max_y = b[0][1] - my, b[1][1] + my + + plane_verts = [[ + (min_x, min_y, t), (max_x, min_y, t), + (max_x, max_y, t), (min_x, max_y, t) + ]] + + # --- L'ASTUCE EST ICI --- + # Au lieu d'extraire les faces, on prend juste les sommets (vertices). + # On calcule un 'step' pour ne garder qu'environ 5000 points maximum. + # C'est largement suffisant pour voir la forme de la table sans faire ramer le PC. + num_vertices = len(mesh.vertices) + step = max(1, num_vertices // 5000) + sampled_vertices = mesh.vertices[::step] + # ------------------------ + + views = [ + {"title": "Vue Isométrique", "elev": 30, "azim": 45}, + {"title": "Vue de Profil (Z)", "elev": 0, "azim": 0}, + {"title": "Vue de Dessous", "elev": -90, "azim": 0} + ] + + for i, view in enumerate(views, start=1): + ax = fig.add_subplot(1, 3, i, projection='3d') + + # Afficher la table comme un nuage de points (ultra rapide) + ax.scatter( + sampled_vertices[:, 0], sampled_vertices[:, 1], sampled_vertices[:, 2], + c='gray', s=1, alpha=0.3, marker='.' + ) + + # Le plan reste un polygone (il n'a que 4 sommets, donc c'est instantané) + plane_col = Poly3DCollection(plane_verts, alpha=0.5, facecolors='red') + ax.add_collection3d(plane_col) + + ax.set_xlim(min_x, max_x) + ax.set_ylim(min_y, max_y) + ax.set_zlim(b[0][2], b[1][2]) + + try: + ax.set_box_aspect((max_x-min_x, max_y-min_y, b[1][2]-b[0][2])) + except AttributeError: + pass + + ax.view_init(elev=view["elev"], azim=view["azim"]) + ax.set_title(view["title"]) + ax.set_xlabel('X') + ax.set_ylabel('Y') + ax.set_zlabel('Z') + + plt.suptitle(f"Table Bottom Z = {t:.3f}", fontsize=16) + + plt.tight_layout() + plt.savefig(save_path, dpi=150, bbox_inches='tight') + plt.close(fig) + + +def main(): + # --- Parse Command Line Arguments --- + parser = argparse.ArgumentParser(description="Batch process table meshes to extract bottom T value.") + parser.add_argument("--folder", required=True, help="Input directory containing table folders.") + parser.add_argument("--instance-file", required=True, help="File with instance to optimize") + parser.add_argument("-m", "--margin", type=float, default=0.5, help="Margin percentage (default: 0.5).") + parser.add_argument("-r", "--rotation", choices=['none', 'x_up', 'y_up'], default='y_up', help="Rotation fix (default: y_up).") + args = parser.parse_args() + + input_folder = "/scratch/cvlab/home/seiler/physiopt_new/output/hunyuan_gen" + f"/{args.folder}" + output_folder = "/scratch/cvlab/home/seiler/physiopt_new/output_force/hunyuan_gen" + f"/{args.folder}" + os.makedirs(output_folder, exist_ok=True) + print(f"Processing folders in: {input_folder}") + + with open(os.path.join("file_for_exp", args.instance_file), "r") as f: + instance_optimize = json.load(f) + count = 0 + + # --- Batch Processing Loop --- + for folder_name in os.listdir(input_folder): + if folder_name in instance_optimize: + input_subdir = os.path.join(input_folder, folder_name) + mesh_file = os.path.join(input_subdir, "generated_mesh.obj") + + if os.path.isdir(input_subdir) and os.path.exists(mesh_file): + out_subdir = os.path.join(output_folder, folder_name) + os.makedirs(out_subdir, exist_ok=True) + + try: + mesh, t_final = process_mesh(mesh_file, args.rotation, args.margin) + + config = { + "force": [0.0, -100000.0, 0.0], + "force_region_mode": "bbox", + "force_bbox_ratio": [0.0, 1.0, 1.0, t_final, 0.0, 1.0] + } + with open(os.path.join(out_subdir, "force_config.json"), 'w') as f: + json.dump(config, f, indent=2) + + save_plot(mesh, t_final, os.path.join(out_subdir, "plot.png")) + print(f"✅ Success: {folder_name} (t_final={t_final:.3f})") + count += 1 + + except Exception as e: + print(f"❌ Failed: {folder_name} | Error: {e}") + + print(f"🎉 Batch processing complete for {count} shape") + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/cfd_workflow_20261012/_seiler_ref/physiopt_new_scripts/compute_metrics.py b/cfd_workflow_20261012/_seiler_ref/physiopt_new_scripts/compute_metrics.py new file mode 100644 index 0000000000000000000000000000000000000000..0eb7b23e4dfe4d10fafa4095ef4f6ea2efb7d831 --- /dev/null +++ b/cfd_workflow_20261012/_seiler_ref/physiopt_new_scripts/compute_metrics.py @@ -0,0 +1,169 @@ +import os +import argparse +import logging +import json +import torch +import trimesh +from tqdm.auto import tqdm + +# Custom imports (ensure these are available in your PYTHONPATH) +import sys +sys.path.append("../smoothSDF") +from src_optimization.global_metrics import compute_final_distribution_metrics +from src_optimization.features_extractor import PointNetExtractor, DINOv2Extractor, InceptionV3Extractor +from src_optimization.features_extractor import extract_features_step + +def setup_logging(): + """Sets up the logging configuration to output to the console.""" + logging.basicConfig( + level=logging.INFO, + format="%(asctime)s [%(levelname)s] %(message)s", + datefmt="%Y-%m-%d %H:%M:%S", + handlers=[logging.StreamHandler()] + ) + +def parse_args(): + """Parses command-line arguments.""" + parser = argparse.ArgumentParser(description="Extract features and compute distribution metrics for optimized 3D meshes.") + + # Paths and folders + parser.add_argument("--base_dir", type=str, default="/scratch/cvlab/home/seiler/physiopt_new", help="Base directory of the project") + parser.add_argument("--experiment_folder", type=str, default="table_experiment", help="Name of the experiment folder") + parser.add_argument("--model_folder", type=str, default="gd_physiopt_64_180", help="Name of the subfolder containing optimized meshes") + + # Extraction parameters + parser.add_argument("--max_meshes", type=int, default=9, help="Maximum number of 'decrease' meshes per instance to process") + parser.add_argument("--num_points", type=int, default=2048, help="Number of sample points for PointNet extraction") + parser.add_argument("--seed", type=int, default=42, help="Random seed for reproducibility") + + # Debug/Testing + parser.add_argument("--test_mode", action="store_true", help="If set, only runs on hardcoded test instances instead of the full folder") + + return parser.parse_args() + +def main(): + args = parse_args() + setup_logging() + + logging.info("Starting feature extraction and metric computation...") + logging.info(f"Experiment: {args.experiment_folder} | Model Folder: {args.model_folder}") + + # Set random seeds + torch.manual_seed(args.seed) + torch.cuda.manual_seed(args.seed) + + # Initialize models + logging.info("Loading feature extraction models...") + device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') + logging.info(f"Using device: {device}") + + model_point = PointNetExtractor().to(device) + model_dino = DINOv2Extractor().to(device) + model_inception = InceptionV3Extractor().to(device) + + models = { + "pointE": model_point, + "inception": model_inception, + "dino": model_dino + } + + # Setup paths + path_folder_experiment = os.path.join(args.base_dir, "output", "hunyuan_gen", args.experiment_folder) + metrics_path_dir = os.path.join(args.base_dir, "metrics", "hunyuan_gen", args.experiment_folder) + + os.makedirs(metrics_path_dir, exist_ok=True) + + # Determine instances to process + if args.test_mode: + logging.info("Running in TEST MODE. Only processing specific test instances.") + instance_list = ["table_0_test", "table_1_test"] + else: + if not os.path.exists(path_folder_experiment): + logging.error(f"Experiment folder not found: {path_folder_experiment}") + return + instance_list = sorted([d for d in os.listdir(path_folder_experiment) if os.path.isdir(os.path.join(path_folder_experiment, d))]) + + logging.info(f"Found {len(instance_list)} instances to process.") + + # Data structures to hold features + global_features = {"pointE": [], "inception": [], "dino": []} + number_data = [0 for _ in range(args.max_meshes)] + + # Feature Extraction Loop + for instance in tqdm(instance_list, desc="Processing instances"): + mesh_folder = os.path.join(path_folder_experiment, instance, args.model_folder) + + if not os.path.exists(mesh_folder): + logging.warning(f"Mesh folder missing for instance {instance}. Skipping...") + continue + + instance_features = {"pointE": [], "inception": [], "dino": []} + + # Get sorted list of decrease meshes + decrease_meshes = sorted([m for m in os.listdir(mesh_folder) if m.startswith('decrease') and m.endswith('.obj')]) + + for i, mesh_filename in enumerate(decrease_meshes): + if i >= args.max_meshes: + break # Do not exceed max expected meshes + + mesh_path = os.path.join(mesh_folder, mesh_filename) + mesh = trimesh.load(mesh_path) + number_data[i] += 1 + + with torch.no_grad(): + features = extract_features_step(mesh, models, {"SamplePoints": args.num_points}, device) + instance_features["pointE"].append(features["pointE"]) + instance_features["inception"].append(features["inception"]) + instance_features["dino"].append(features["dino"]) + + # Padding with zeros if fewer meshes were found than expected + for k in ["pointE", "inception", "dino"]: + if len(instance_features[k]) == 0: + logging.warning(f"No features extracted for {k} in instance {instance}.") + continue + + dim = instance_features[k][0].shape + while len(instance_features[k]) < args.max_meshes: + instance_features[k].append(torch.zeros(dim, dtype=torch.float32).to(device)) + + # Stack features for this instance and append to global tracking + instance_features[k] = torch.stack(instance_features[k]) + global_features[k].append(instance_features[k]) + + # Computing Global Metrics + distribution_metrics = {} + metric_map = [ + ("pointE", os.path.join(metrics_path_dir, "pointnetE_features.npy")), + ("inception", os.path.join(metrics_path_dir, "inceptionv3_features.npy")), + ("dino", os.path.join(metrics_path_dir, "dinov2_vits14_features.npy")) + ] + + logging.info("Starting global metrics computation...") + for feat_name, spec_key_path in metric_map: + if not global_features[feat_name]: + logging.warning(f"No global features collected for {feat_name}. Skipping metrics.") + continue + + logging.info(f"Computing global metrics for {feat_name}...") + try: + res = compute_final_distribution_metrics( + global_features[feat_name], + spec_key_path, + feat_name + ) + distribution_metrics.update(res) + except Exception as e: + logging.error(f"Failed to compute metrics for {feat_name}: {e}") + + # Save Results + distribution_metrics["number_data"] = number_data + output_json = os.path.join(metrics_path_dir, "metrics.json") + + with open(output_json, "w") as f: + json.dump(distribution_metrics, f, indent=4) + + logging.info(f"Successfully saved metrics to: {output_json}") + logging.info("Done!") + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/cfd_workflow_20261012/_seiler_ref/physiopt_new_scripts/force_web_ui.py b/cfd_workflow_20261012/_seiler_ref/physiopt_new_scripts/force_web_ui.py new file mode 100644 index 0000000000000000000000000000000000000000..5bb3f15a92b5789ec0fc40198c707b261acd45ca --- /dev/null +++ b/cfd_workflow_20261012/_seiler_ref/physiopt_new_scripts/force_web_ui.py @@ -0,0 +1,733 @@ +import argparse +import hashlib +import json +import os +import re +import shutil + +import numpy as np +import gradio as gr +import trimesh + +POINT_PREVIEW_MAX = 12000 +POINT_PREVIEW_SIZE_RATIO = 0.004 +ROTATE_X_CCW_90 = trimesh.transformations.rotation_matrix( + np.deg2rad(270.0), [1.0, 0.0, 0.0] +) + + +def _normalize_out_path(out_path: str) -> str: + out_path = (out_path or "").strip() + if not out_path: + out_path = "force_config.json" + if out_path.endswith(os.sep) or os.path.isdir(out_path): + out_path = os.path.join(out_path, "force_config.json") + return out_path + + +def _parse_force_lines(text: str): + forces = [] + for raw_line in (text or "").splitlines(): + line = raw_line.strip() + if not line or line.startswith("#"): + continue + parts = [p for p in re.split(r"[,\s]+", line) if p] + if len(parts) != 3: + continue + try: + vec = [float(v) for v in parts] + except Exception: + continue + forces.append(vec) + return forces + + +def _save_config( + out_path: str, + fx: float, + fy: float, + fz: float, + extra_forces_text: str, + mode: str, + top_percent: float, + hr_min: float, + hr_max: float, + bx0: float, + bx1: float, + by0: float, + by1: float, + bz0: float, + bz1: float, + brx0: float, + brx1: float, + bry0: float, + bry1: float, + brz0: float, + brz1: float, + force_entries, +): + out_path = _normalize_out_path(out_path) + os.makedirs(os.path.dirname(out_path) or ".", exist_ok=True) + + force_entries = list(force_entries or []) + if force_entries: + entries = force_entries + else: + entries = [ + _build_force_entry( + fx, + fy, + fz, + extra_forces_text, + mode, + top_percent, + hr_min, + hr_max, + bx0, + bx1, + by0, + by1, + bz0, + bz1, + brx0, + brx1, + bry0, + bry1, + brz0, + brz1, + ) + ] + + all_forces = _flatten_entry_forces(entries) + + if len(entries) == 1: + cfg = dict(entries[0]) + else: + cfg = {"force_entries": entries} + if len(all_forces) > 1: + cfg["forces"] = all_forces + cfg["force"] = [float(sum(v[i] for v in all_forces)) for i in range(3)] + elif len(all_forces) == 1: + cfg["force"] = all_forces[0] + + with open(out_path, "w") as f: + json.dump(cfg, f, indent=2) + + cmd = f"python scripts/viewer_hunyuan_web_alternate.py --latents --use_physics --force_config {out_path}" + return f"Saved to {out_path}", json.dumps(cfg, indent=2), cmd + + +def _toggle_groups(mode: str): + return ( + gr.update(visible=mode == "top_percent"), + gr.update(visible=mode == "height_ratio"), + gr.update(visible=mode == "bbox_abs"), + gr.update(visible=mode == "bbox_ratio"), + ) + + +def _build_force_entry( + fx: float, + fy: float, + fz: float, + extra_forces_text: str, + mode: str, + top_percent: float, + hr_min: float, + hr_max: float, + bx0: float, + bx1: float, + by0: float, + by1: float, + bz0: float, + bz1: float, + brx0: float, + brx1: float, + bry0: float, + bry1: float, + brz0: float, + brz1: float, +): + base_force = [float(fx), float(fy), float(fz)] + extra_forces = _parse_force_lines(extra_forces_text) + forces = [] + base_nonzero = any(abs(v) > 0 for v in base_force) + if base_nonzero or not extra_forces: + forces.append(base_force) + forces.extend(extra_forces) + + entry = {} + if len(forces) > 1: + entry["forces"] = forces + entry["force"] = [float(sum(v[i] for v in forces)) for i in range(3)] + else: + entry["force"] = forces[0] + + if mode == "global": + entry["force_region_mode"] = "global" + entry["global_loading"] = True + elif mode == "top_percent": + entry["force_region_mode"] = "top_percent" + entry["force_top_percent"] = float(top_percent) + elif mode == "height_ratio": + entry["force_region_mode"] = "height_ratio" + entry["seat_height_min_ratio"] = float(hr_min) + entry["seat_height_max_ratio"] = float(hr_max) + elif mode == "bbox_abs": + entry["force_region_mode"] = "bbox" + entry["force_bbox"] = [ + float(bx0), + float(bx1), + float(by0), + float(by1), + float(bz0), + float(bz1), + ] + elif mode == "bbox_ratio": + entry["force_region_mode"] = "bbox" + entry["force_bbox_ratio"] = [ + float(brx0), + float(brx1), + float(bry0), + float(bry1), + float(brz0), + float(brz1), + ] + return entry + + +def _flatten_entry_forces(entries): + all_forces = [] + for entry in entries: + if not isinstance(entry, dict): + continue + if "forces" in entry and isinstance(entry["forces"], list): + all_forces.extend(entry["forces"]) + elif "force" in entry: + all_forces.append(entry["force"]) + return all_forces + + +def _add_force_entry( + force_entries, + fx: float, + fy: float, + fz: float, + extra_forces_text: str, + mode: str, + top_percent: float, + hr_min: float, + hr_max: float, + bx0: float, + bx1: float, + by0: float, + by1: float, + bz0: float, + bz1: float, + brx0: float, + brx1: float, + bry0: float, + bry1: float, + brz0: float, + brz1: float, +): + entries = list(force_entries or []) + entry = _build_force_entry( + fx, + fy, + fz, + extra_forces_text, + mode, + top_percent, + hr_min, + hr_max, + bx0, + bx1, + by0, + by1, + bz0, + bz1, + brx0, + brx1, + bry0, + bry1, + brz0, + brz1, + ) + entries.append(entry) + preview = json.dumps(entries, indent=2) + status = f"✅ Added load location #{len(entries)}" + return entries, preview, status + + +def _clear_force_entries(): + return [], "[]", "🧹 Cleared all load locations" + + +def _copy_to_tmp(mesh_path: str) -> str: + abs_path = os.path.abspath(os.path.expanduser(mesh_path)) + stat = os.stat(abs_path) + key = f"{abs_path}|{stat.st_size}|{stat.st_mtime_ns}" + digest = hashlib.sha256(key.encode("utf-8")).hexdigest()[:16] + tmp_dir = os.path.join("./tmp", "force_web_ui_cache") + os.makedirs(tmp_dir, exist_ok=True) + dst_name = f"{digest}_{os.path.basename(abs_path)}" + dst_path = os.path.join(tmp_dir, dst_name) + if not os.path.exists(dst_path): + shutil.copy2(abs_path, dst_path) + return dst_path + + +def _prepare_preview_mesh(mesh, mesh_path: str, rotated: bool): + """Export preview mesh to ./tmp as GLB (fallback to original file).""" + abs_path = os.path.abspath(os.path.expanduser(mesh_path)) + stat = os.stat(abs_path) + key = f"{abs_path}|{stat.st_size}|{stat.st_mtime_ns}|rotated={int(bool(rotated))}|preview_v1" + digest = hashlib.sha256(key.encode("utf-8")).hexdigest()[:16] + tmp_dir = os.path.join("./tmp", "force_web_ui_cache") + os.makedirs(tmp_dir, exist_ok=True) + glb_path = os.path.join(tmp_dir, f"{digest}.glb") + if not os.path.exists(glb_path): + try: + mesh_to_export = mesh + if isinstance(mesh, trimesh.Scene): + geoms = [g for g in mesh.dump() if isinstance(g, trimesh.Trimesh)] + if len(geoms) > 0: + mesh_to_export = trimesh.util.concatenate(geoms) + mesh_to_export.export(glb_path) + except Exception: + return _copy_to_tmp(mesh_path), "⚠️ Preview GLB export failed; using the original file instead" + return glb_path, None + + +def _reduce_faces(mesh: trimesh.Trimesh, target_faces: int) -> trimesh.Trimesh: + if not isinstance(mesh, trimesh.Trimesh) or mesh.faces is None: + return mesh + face_count = int(mesh.faces.shape[0]) + if face_count <= target_faces: + return mesh + idx = np.linspace(0, face_count - 1, target_faces, dtype=np.int64) + faces = mesh.faces[idx] + mesh_small = trimesh.Trimesh(vertices=mesh.vertices, faces=faces, process=False) + try: + mesh_small.remove_unreferenced_vertices() + except Exception: + pass + return mesh_small + + +def _extract_points_and_mesh(loaded): + if loaded is None: + return None, None + if isinstance(loaded, trimesh.Trimesh): + pts = loaded.vertices if hasattr(loaded, "vertices") else None + return (np.asarray(pts) if pts is not None else None), loaded + if isinstance(loaded, trimesh.points.PointCloud): + pts = loaded.vertices if hasattr(loaded, "vertices") else loaded.points + return (np.asarray(pts) if pts is not None else None), None + if isinstance(loaded, trimesh.Scene): + meshes = [] + points = [] + for geom in loaded.dump(): + if isinstance(geom, trimesh.Trimesh): + meshes.append(geom) + elif isinstance(geom, trimesh.points.PointCloud): + pts = geom.vertices if hasattr(geom, "vertices") else geom.points + if pts is not None: + points.append(np.asarray(pts)) + if meshes: + mesh = trimesh.util.concatenate(meshes) + pts = mesh.vertices if hasattr(mesh, "vertices") else None + return (np.asarray(pts) if pts is not None else None), mesh + if points: + return np.concatenate(points, axis=0), None + return None, None + + +def _rotate_points_and_mesh(points, mesh, enable_rotation: bool): + if not enable_rotation: + return points, mesh + + rot = np.asarray(ROTATE_X_CCW_90, dtype=np.float64) + + rotated_points = None + if points is not None: + rotated_points = trimesh.transform_points(np.asarray(points, dtype=np.float64), rot) + + rotated_mesh = None + if mesh is not None: + rotated_mesh = mesh.copy() + rotated_mesh.apply_transform(rot) + + return rotated_points, rotated_mesh + + +def _make_preview_mesh_from_points(points: np.ndarray): + if points is None or len(points) == 0: + return None, "⚠️ The point cloud is empty and cannot be previewed" + points = np.asarray(points, dtype=np.float32) + total = int(points.shape[0]) + if total > POINT_PREVIEW_MAX: + idx = np.linspace(0, total - 1, POINT_PREVIEW_MAX, dtype=np.int64) + pts = points[idx] + sample_note = f" (sampled {POINT_PREVIEW_MAX}/{total})" + else: + pts = points + sample_note = f" ({total} pts)" + min_b = points.min(axis=0) + max_b = points.max(axis=0) + max_range = float(np.max(max_b - min_b)) + if not np.isfinite(max_range) or max_range <= 0: + max_range = 1.0 + point_size = max(max_range * POINT_PREVIEW_SIZE_RATIO, 1e-4) + try: + base = trimesh.creation.box(extents=[point_size, point_size, point_size]) + v = base.vertices + f = base.faces + num = int(pts.shape[0]) + verts = (v[None, :, :] + pts[:, None, :]).reshape(-1, 3) + faces = (f[None, :, :] + (np.arange(num) * len(v))[:, None, None]).reshape(-1, 3) + cloud_mesh = trimesh.Trimesh(vertices=verts, faces=faces, process=False) + cloud_mesh.visual.face_colors = [120, 120, 120, 100] + return cloud_mesh, f"✅ Point-cloud preview{sample_note}, point size≈{point_size:.4f}" + except Exception as e: + extents = np.maximum(max_b - min_b, 1e-6) + center = (min_b + max_b) * 0.5 + transform = trimesh.transformations.translation_matrix(center) + box = trimesh.creation.box(extents=extents, transform=transform) + box.visual.face_colors = [160, 160, 160, 60] + return box, f"⚠️ Point-cloud preview failed; using a bounding box instead: {e}" + + +def _load_mesh(mesh_path: str, z_up: bool): + mesh_path = (mesh_path or "").strip() + if not mesh_path: + return "⚠️ Please enter a mesh path", "", None, None, None + if not os.path.exists(mesh_path): + return f"⚠️ Path does not exist: {mesh_path}", "", None, None, None + try: + loaded = trimesh.load(mesh_path, force="scene") + points, mesh = _extract_points_and_mesh(loaded) + if points is None or len(points) == 0: + return "⚠️ The mesh is empty or failed to load", "", None, None, None + points, mesh = _rotate_points_and_mesh(points, mesh, enable_rotation=bool(z_up)) + status_prefix = "✅ Mesh loaded" + preview_note = None + target_faces = 100000 + if isinstance(mesh, trimesh.Trimesh) and mesh.faces is not None: + face_count = int(mesh.faces.shape[0]) + if face_count == 0: + preview_mesh, preview_note = _make_preview_mesh_from_points(points) + mesh = preview_mesh + status_prefix = "✅ Point cloud loaded" + elif face_count > target_faces: + try: + mesh = mesh.simplify_quadratic_decimation(target_faces) + status_prefix += f" (simplified: {face_count} -> {mesh.faces.shape[0]} faces)" + except Exception: + mesh = _reduce_faces(mesh, target_faces) + if hasattr(mesh, "faces") and mesh.faces is not None: + status_prefix += f" (sample-based reduction: {face_count} -> {mesh.faces.shape[0]} faces)" + else: + status_prefix += f" (⚠️ simplification failed, faces={face_count})" + elif mesh is None: + preview_mesh, preview_note = _make_preview_mesh_from_points(points) + mesh = preview_mesh + status_prefix = "✅ Point cloud loaded" + + min_b = points.min(axis=0) + max_b = points.max(axis=0) + size = max_b - min_b + info = ( + f"min: [{min_b[0]:.4f}, {min_b[1]:.4f}, {min_b[2]:.4f}]\n" + f"max: [{max_b[0]:.4f}, {max_b[1]:.4f}, {max_b[2]:.4f}]\n" + f"size: [{size[0]:.4f}, {size[1]:.4f}, {size[2]:.4f}]" + ) + bbox = [float(min_b[0]), float(max_b[0]), float(min_b[1]), float(max_b[1]), float(min_b[2]), float(max_b[2])] + preview_path, warn = _prepare_preview_mesh(mesh, mesh_path, rotated=bool(z_up)) + status_parts = [status_prefix] + if z_up: + status_parts.append("↻ Rotated 90 degrees counterclockwise around the +X axis") + if warn is not None: + status_parts.append(warn) + if preview_note is not None: + status_parts.append(preview_note) + status = "\n".join(status_parts) + return status, info, preview_path, bbox, preview_path + except Exception as e: + return f"⚠️ Load failed: {e}", "", None, None, None + + +def _set_bbox_abs_from_bounds(bounds): + if not bounds or len(bounds) != 6: + return [gr.update() for _ in range(6)] + return [bounds[0], bounds[1], bounds[2], bounds[3], bounds[4], bounds[5]] + + +def _bbox_from_ratio(bounds, ratio): + if not bounds or len(bounds) != 6 or not ratio or len(ratio) != 6: + return None + x0, x1, y0, y1, z0, z1 = [float(v) for v in bounds] + rx0, rx1, ry0, ry1, rz0, rz1 = [float(v) for v in ratio] + return [ + x0 + rx0 * (x1 - x0), + x0 + rx1 * (x1 - x0), + y0 + ry0 * (y1 - y0), + y0 + ry1 * (y1 - y0), + z0 + rz0 * (z1 - z0), + z0 + rz1 * (z1 - z0), + ] + + +def _preview_bbox( + preview_path: str, + bounds, + mode: str, + bx0: float, + bx1: float, + by0: float, + by1: float, + bz0: float, + bz1: float, + brx0: float, + brx1: float, + bry0: float, + bry1: float, + brz0: float, + brz1: float, +): + if not preview_path or not os.path.exists(preview_path): + return gr.update(), "⚠️ Please load a mesh first" + mode = (mode or "").lower() + if mode not in ("bbox_abs", "bbox_ratio"): + return gr.update(), "⚠️ Preview is only available in bbox mode" + if mode == "bbox_ratio": + bbox = _bbox_from_ratio(bounds, [brx0, brx1, bry0, bry1, brz0, brz1]) + if bbox is None: + return gr.update(), "⚠️ bbox_ratio is missing bounds or parameters" + else: + bbox = [bx0, bx1, by0, by1, bz0, bz1] + x0, x1 = sorted([float(bbox[0]), float(bbox[1])]) + y0, y1 = sorted([float(bbox[2]), float(bbox[3])]) + z0, z1 = sorted([float(bbox[4]), float(bbox[5])]) + if x1 - x0 <= 0 or y1 - y0 <= 0 or z1 - z0 <= 0: + return gr.update(), "⚠️ Invalid bbox size" + + try: + base = trimesh.load(preview_path, force="scene") + scene = base if isinstance(base, trimesh.Scene) else trimesh.Scene(base) + center = np.array([(x0 + x1) / 2, (y0 + y1) / 2, (z0 + z1) / 2], dtype=np.float64) + extents = np.array([x1 - x0, y1 - y0, z1 - z0], dtype=np.float64) + transform = trimesh.transformations.translation_matrix(center) + box = trimesh.creation.box(extents=extents, transform=transform) + box.visual.face_colors = [255, 0, 0, 60] + scene.add_geometry(box, node_name="bbox") + + stat = os.stat(preview_path) + key = f"{preview_path}|{stat.st_size}|{stat.st_mtime_ns}|{x0},{x1},{y0},{y1},{z0},{z1}" + digest = hashlib.sha256(key.encode("utf-8")).hexdigest()[:16] + tmp_dir = os.path.join("./tmp", "force_web_ui_cache") + os.makedirs(tmp_dir, exist_ok=True) + out_path = os.path.join(tmp_dir, f"bbox_{digest}.glb") + scene.export(out_path) + return out_path, "✅ Updated bbox preview" + except Exception as e: + return gr.update(), f"⚠️ Bbox preview failed: {e}" + + +def build_ui(default_out: str, z_up: bool): + with gr.Blocks(title="Force Config UI") as demo: + gr.Markdown( + "Set force vector(s) (Y-up) and region. " + "Use 'Add Force Entry' to create multiple locations; " + "Save JSON will use entries if any exist." + ) + + mesh_bounds_state = gr.State(None) + mesh_preview_state = gr.State(None) + force_entries_state = gr.State([]) + + out_path = gr.Textbox(label="Output JSON Path", value=default_out) + mesh_path = gr.Textbox(label="Mesh Path (server)", placeholder="/path/to/mesh.obj") + with gr.Row(): + load_mesh_btn = gr.Button("Load Mesh") + fill_bbox_btn = gr.Button("Use Mesh Bounds for BBox") + mesh_status = gr.Textbox(label="Mesh Status", interactive=False) + mesh_bounds = gr.Textbox(label="Mesh Bounds", interactive=False) + mesh_view = gr.Model3D(label="Mesh Preview") + bbox_status = gr.Textbox(label="BBox Preview Status", interactive=False) + + if z_up: + with gr.Row(): + fx = gr.Number(label="Fx (N)", value=0.0) + fy = gr.Number(label="Fy (N)", value=0.0) + fz = gr.Number(label="Fz (N)", value=-100000.0) + else: + with gr.Row(): + fx = gr.Number(label="Fx (N)", value=0.0) + fy = gr.Number(label="Fy (N)", value=-100000.0) + fz = gr.Number(label="Fz (N)", value=0.0) + extra_forces = gr.Textbox( + label="Extra Forces (one per line: fx fy fz)", + placeholder="0 0 -500\n100 0 0", + lines=3, + ) + + mode = gr.Radio( + ["global", "top_percent", "height_ratio", "bbox_abs", "bbox_ratio"], + value="top_percent", + label="Region Mode", + ) + + with gr.Group(visible=True) as top_group: + top_percent = gr.Slider(0.01, 0.5, value=0.05, step=0.01, label="Top Percent") + + with gr.Group(visible=False) as height_group: + hr_min = gr.Slider(0.0, 1.0, value=0.3, step=0.01, label="Height Min Ratio") + hr_max = gr.Slider(0.0, 1.0, value=0.5, step=0.01, label="Height Max Ratio") + + with gr.Group(visible=False) as bbox_abs_group: + gr.Markdown("BBox (abs) order: x_min, x_max, y_min, y_max, z_min, z_max") + with gr.Row(): + bx0 = gr.Number(label="x_min", value=-0.2) + bx1 = gr.Number(label="x_max", value=0.2) + by0 = gr.Number(label="y_min", value=0.2) + by1 = gr.Number(label="y_max", value=0.4) + bz0 = gr.Number(label="z_min", value=-0.2) + bz1 = gr.Number(label="z_max", value=0.2) + + with gr.Group(visible=False) as bbox_ratio_group: + gr.Markdown("BBox (ratio 0-1) order: x_min, x_max, y_min, y_max, z_min, z_max") + with gr.Row(): + brx0 = gr.Slider(0.0, 1.0, value=0.4, step=0.01, label="x_min") + brx1 = gr.Slider(0.0, 1.0, value=0.6, step=0.01, label="x_max") + bry0 = gr.Slider(0.0, 1.0, value=0.4, step=0.01, label="y_min") + bry1 = gr.Slider(0.0, 1.0, value=0.6, step=0.01, label="y_max") + brz0 = gr.Slider(0.0, 1.0, value=0.4, step=0.01, label="z_min") + brz1 = gr.Slider(0.0, 1.0, value=0.6, step=0.01, label="z_max") + + save_btn = gr.Button("Save JSON", variant="primary") + add_force_btn = gr.Button("Add Force Entry") + clear_force_btn = gr.Button("Clear Force Entries") + preview_bbox_btn = gr.Button("Preview BBox") + status = gr.Textbox(label="Status") + force_entries_preview = gr.Code(label="Force Entries", language="json", value="[]") + preview = gr.Code(label="JSON Preview", language="json") + cmd = gr.Textbox(label="Command Preview") + + mode.change( + _toggle_groups, + inputs=mode, + outputs=[top_group, height_group, bbox_abs_group, bbox_ratio_group], + ) + load_mesh_btn.click( + _load_mesh, + inputs=[mesh_path, gr.State(z_up)], + outputs=[mesh_status, mesh_bounds, mesh_view, mesh_bounds_state, mesh_preview_state], + ) + fill_bbox_btn.click( + _set_bbox_abs_from_bounds, + inputs=[mesh_bounds_state], + outputs=[bx0, bx1, by0, by1, bz0, bz1], + ) + preview_bbox_btn.click( + _preview_bbox, + inputs=[ + mesh_preview_state, + mesh_bounds_state, + mode, + bx0, + bx1, + by0, + by1, + bz0, + bz1, + brx0, + brx1, + bry0, + bry1, + brz0, + brz1, + ], + outputs=[mesh_view, bbox_status], + ) + + add_force_btn.click( + _add_force_entry, + inputs=[ + force_entries_state, + fx, + fy, + fz, + extra_forces, + mode, + top_percent, + hr_min, + hr_max, + bx0, + bx1, + by0, + by1, + bz0, + bz1, + brx0, + brx1, + bry0, + bry1, + brz0, + brz1, + ], + outputs=[force_entries_state, force_entries_preview, status], + ) + clear_force_btn.click( + _clear_force_entries, + inputs=[], + outputs=[force_entries_state, force_entries_preview, status], + ) + + save_btn.click( + _save_config, + inputs=[ + out_path, + fx, + fy, + fz, + extra_forces, + mode, + top_percent, + hr_min, + hr_max, + bx0, + bx1, + by0, + by1, + bz0, + bz1, + brx0, + brx1, + bry0, + bry1, + brz0, + brz1, + force_entries_state, + ], + outputs=[status, preview, cmd], + ) + return demo + + +def main(): + parser = argparse.ArgumentParser(description="Force config web UI") + parser.add_argument("--out", type=str, default="force_config.json", help="Output JSON path") + parser.add_argument("--server_name", type=str, default="0.0.0.0", help="Gradio server name") + parser.add_argument("--server_port", type=int, default=7860, help="Gradio server port") + parser.add_argument("--share", action="store_true", help="Enable Gradio share link") + parser.add_argument("--z_up", action="store_true", help="Enable z_up mode") + args = parser.parse_args() + + demo = build_ui(args.out, args.z_up) + demo.launch(server_name=args.server_name, server_port=args.server_port, share=args.share) + + +if __name__ == "__main__": + main() diff --git a/cfd_workflow_20261012/_seiler_ref/physiopt_new_scripts/hunyuan_alternate_me.py b/cfd_workflow_20261012/_seiler_ref/physiopt_new_scripts/hunyuan_alternate_me.py new file mode 100644 index 0000000000000000000000000000000000000000..8e20cab3b0edb5a68f3883587d1e153e67611a0b --- /dev/null +++ b/cfd_workflow_20261012/_seiler_ref/physiopt_new_scripts/hunyuan_alternate_me.py @@ -0,0 +1,3420 @@ +""" +Hunyuan3D-2.1 physical optimization + shape-prior optimization. +""" + +import os +import copy +# os.environ['TORCH_HOME'] = '/mnt/cvlab/scratch/cvlab/home/hantzhan/.torch' +import sys +import shutil + +# Add Hunyuan3D-2.1 to the Python path. +hunyuan_path = os.path.abspath(os.path.join(os.path.dirname(__file__), "../../Hunyuan3D-2.1")) +# Note: logging is not imported yet, so use print here if needed. +# Basic logging is configured near the top of the file after import. + +sys.path.append("..") + +from matplotlib import pyplot as plt +import torch +import torch.nn.functional as F +import trimesh +import numpy as np +from PIL import Image +import argparse +import json +from typing import Tuple, Optional, List +from dataclasses import dataclass, field +import traceback +import logging + +# Configure logging here only conceptually; main() will reconfigure it to +# log to both the console and a file. +# Do not call basicConfig here so the main() configuration remains effective. +# logging.basicConfig(level=logging.INFO, format='%(levelname)s: %(message)s') + +# Physical-simulation imports. +PHYSIOPT_AVAILABLE = False +try: + from physiopt.utils.phys_utils import generate_hex + from physiopt.utils.grid_utils import filter_one_component + from physiopt.opt.field import occ_kernel + from physiopt.opt.forces import ForceConfig + PHYSIOPT_AVAILABLE = True + logging.info("✅ physics simulation moduleimportsucceeded") +except ImportError as e: + logging.warning(f"⚠️ warning: physics simulation moduleimportfailed: {e}") + logging.warning(" if you only run SDS optimization, you can ignore this warning") + PHYSIOPT_AVAILABLE = False + + def generate_hex(res, limits=[(-0.5, 0.5), (-0.5, 0.5), (-0.5, 0.5)], device="cuda", return_coords=False): + """Placeholder for hexahedral grid generation. + + Returns tensors in the same format as the real function. + """ + logging.warning(f"⚠️ warning: using placeholdergenerate_hex, please install the physiopt module") + return None, None + + def filter_one_component(mask, res): + """Placeholder for connected-component filtering. + + Args: + mask: Element mask [res*res*res] + res: Voxel resolution + """ + return mask + + def occ_kernel(sdf, res, beta): + """Placeholder for SDF-to-occupancy conversion.""" + return torch.sigmoid(-sdf * beta) + +# Warp physics-engine import. +try: + import warp as wp + wp.init() + WARP_AVAILABLE = True + logging.info("✅ Warp physics engineInitializationsucceeded") +except ImportError: + WARP_AVAILABLE = False + logging.warning("⚠️ warning: Warp physics enginenot installed, physics simulationwill be unavailable") + logging.warning(" Install: pip install warp-lang") + +# Hunyuan3D imports +try: + from hy3dgen.shapegen.models.autoencoders import ShapeVAE + from hy3dgen.shapegen import Hunyuan3DDiTFlowMatchingPipeline + from hy3dgen.shapegen.pipelines import export_to_trimesh +except ImportError as e: + logging.error(f"❌ failed to import Hunyuan3D modules: {e}") + logging.error(f"\nplease follow these steps to set upHunyuan3D-2.1:") + logging.error(f"1. cd {os.path.dirname(hunyuan_path)}") + logging.error(f"2. git clone https://github.com/Tencent/Hunyuan3D-2.git Hunyuan3D-2.1") + logging.error(f"3. cd Hunyuan3D-2.1") + logging.error(f"4. pip install -e .") + sys.exit(1) + + +@dataclass +class OptimizationConfig: + """Optimization config for physics + SDS.""" + # Physical-simulation parameters. + res: int = 32 # Voxel resolution (16/32/64), matching the reference code. + # Restored physical settings from the stable v90 configuration. + p_exponent: float = 1.0 # SIMP penalty exponent. + alpha_min: float = 0.01 # Minimum density, restored from v90. + volume_term: float = 1000000.0 # Volume-constraint weight, currently disabled. + occ_sdf_beta: float = 2.0 # Sigmoid-kernel beta, restored from v90. + one_cc_only: bool = False # Keep only the largest connected component. + + # SDS parameters. + # Use dynamic SDS weights so physics dominates early and aesthetics enters later. + sds_timestep: float = 0.1 # SDS timestep; smaller values preserve more detail. + sds_weight: float = 1.0 # SDS weight relative to the physical gradient. + sds_weight_start: float = 1e5 # 0.1 # 0.0001 # Initial SDS weight. + sds_weight_end: float = 1e5 # 1.0 # 0.001 # Final SDS weight. + guidance_scale: float = 7.5 # Standard CFG guidance scale for stronger image conditioning. + sds_projection_max_rel: float = 0.0 # Max relative target_z0 projection offset (0 = unlimited). + sds_use_uncond: bool = False # Use the unconditional branch when guidance_scale <= 1. + sds_target_z0_update_interval: int = 10 # target_z0 update interval; tied to phys_steps_per_cycle. + sds_target_z0_ema_beta: float = 0.9 # EMA smoothing coefficient; larger is smoother. + + lagrange_max: float = 50.0 # Max lambda. + compliance_threshold: float = 200.0 # Compliance threshold used for normalization. + alm_rho_init: float = 1.0 # Initial rho. + alm_rho_max: float = 1000.0 # Max rho. + alm_rho_increase_factor: float = 2.0 # Rho growth factor. + alm_rho_increase_patience: int = 5 # Number of consecutive violations before increasing rho. + alm_scale_guard_ratio: float = 0.95 # ALM scaling guard to stay below gradient clipping. + + # Topology control. + re_extract_interval: int = 5 # Re-extract the solid every N steps; 0 disables it. + + # Material properties. Values are aligned with the reference setup. + # youngs_modulus is already specified directly in Pa, so no unit conversion is needed. + youngs_modulus: float = 5e8 # 1e9 # Pa (= 1 GPa), restored from v90. + youngs_modulus_scale: float = 2.0 # Final multiplier after the last projection in alternating mode. + poissons_ratio: float = 0.3 # Poisson's ratio (dimensionless). + density: float = 650.0 # Material density (kg/m^3). + + ## Wood + # youngs_modulus: float = 9e9 # Pa (= 1 GPa), aligned with the reference code. + # poissons_ratio: float = 0.35 # Poisson's ratio (dimensionless), matches the reference. + # density: float = 400.0 # Material density (kg/m^3), matches the reference. + + ## PVG + # youngs_modulus: float = 3.25e9 # Pa (= 1 GPa), aligned with the reference code. + # poissons_ratio: float = 0.38 # Poisson's ratio (dimensionless), matches the reference. + # density: float = 1380.0 # Material density (kg/m^3), matches the reference. + + # Load conditions; supports multiple forces like config.json. + forces: List = None # List of ForceConfig objects. + # Multiple localized load entries, each with its own force and region settings. + force_entries: Optional[List[dict]] = None + + # Local-loading settings, e.g. to mimic a person sitting on a chair. + use_local_loading: bool = True # Use local loading instead of global uniform loading. + seat_height_min_ratio: float = 0.3 # Lower bound of the seat band as a height ratio. + seat_height_max_ratio: float = 0.5 # Upper bound of the seat band as a height ratio. + force_region_mode: str = "top_percent" # Load-region mode: top_percent / height_ratio / bbox. + force_top_percent: float = 0.05 # In top_percent mode, use the highest-Y fraction of nodes. + force_bbox: Optional[List[float]] = None # bbox mode: x_min x_max y_min y_max z_min z_max. + force_bbox_ratio: Optional[List[float]] = None # bbox mode in normalized node bounds [0, 1]. + + # Optimization parameters, restored from the stable v90 configuration. + lr: float = 0.001 # Learning rate. + num_steps: int = 100 # Number of optimization steps. + use_sgd: bool = False # Use SGD instead of Adam. + grad_clip_enabled: bool = False # Enable gradient clipping; off by default. + save_every: int = 10 # Save interval in steps. + deformed_mesh_interval: int = 10 # Save interval for deformed meshes. + deformed_mesh_disp_min: float = 0.0 # Minimum displacement for deformed-mesh color mapping. + deformed_mesh_disp_max: float = 0.2 # Maximum displacement for deformed-mesh color mapping. + + # Output path. + out_folder: str = "../out/hunyuan_opt" # Output directory. + + # Device. + device: str = "cuda" # Compute device. + + # Whether to enable physics optimization. + use_physics: bool = True # Enable physical-constraint optimization. + + def __post_init__(self): + # Set default loads in the Hunyuan Y-up coordinate system: + # X = right, Y = up, Z = forward. + if self.forces is None: + try: + from physiopt.opt.forces import ForceConfig + self.forces = [ + ForceConfig(external_force=[0.0, -100000.0, 0.0]) # 100 kN downward along Y. + # ForceConfig(external_force=[0.0, 0.0, -500.0]), # 500 N backward along Z. + ] + except ImportError: + # Fallback format if physiopt is unavailable; keep only the force vectors. + self.forces = [ + {'external_force': [0.0, -100000.0, 0.0]} # 100 kN downward along Y. + # {'external_force': [0.0, 0.0, -500.0]}, # Backward along Z. + ] + + +class HunyuanSDSOptimizer: + """Hunyuan3D SDS optimizer with differentiable physics support.""" + + def __init__( + self, + latents: torch.Tensor, + cond: dict, # Condition dict containing positive and negative branches. + vae: ShapeVAE, + flow_model: torch.nn.Module, + config: OptimizationConfig, + scheduler=None, + device: str = 'cuda' + ): + """ + Args: + latents: Initial latent tokens [1, N, D]. + cond: Condition dict returned by pipeline.encode_cond. + vae: Hunyuan3D VAE model. + flow_model: Hunyuan3D Flow Matching model. + scheduler: Hunyuan3D Flow Matching scheduler used to align target_z0. + config: Optimization config. + device: Compute device. + """ + self.device = device + self.config = config + + # Models. + self.vae = vae.to(device).eval() + self.flow_model = flow_model.to(device).eval() + if scheduler is not None: + try: + self.sds_scheduler = copy.deepcopy(scheduler) + except Exception: + self.sds_scheduler = scheduler + logging.warning("⚠️ Scheduler deepcopyfailed, already fallback to originalscheduler") + else: + self.sds_scheduler = None + + # Create a differentiable SDF query helper. + from hy3dgen.shapegen.models.autoencoders.differentiable_sdf_query import DifferentiableSDFQuery + self.sdf_query = DifferentiableSDFQuery( + vae=self.vae, + bounds=0.8, # Our coordinate range is [-0.8, 0.8]. + chunk_size=8192 # Batch query size. + ) + logging.info(f"✅ created differentiable SDF query helper") + + # Latent tokens are the variables being optimized. + # Use float32 instead of float16 to avoid numeric overflow. + self.latents = latents.clone().to(device).to(torch.float32).requires_grad_(True) + + logging.info(f" ⚠️ note: Latentsfloat32FP16value") + + # Move conditioning data to the target device recursively. + def to_device_recursive(obj): + if isinstance(obj, torch.Tensor): + return obj.to(device) + elif isinstance(obj, dict): + return {k: to_device_recursive(v) for k, v in obj.items()} + elif isinstance(obj, (list, tuple)): + return type(obj)(to_device_recursive(item) for item in obj) + else: + return obj + + self.cond = to_device_recursive(cond) + self._cond_warned_cfg_repeat = False + self._cond_warned_nocfg_slice = False + + # Optimizer selection. + if config.use_sgd: + self.optimizer = torch.optim.SGD([self.latents], lr=config.lr, momentum=0.0) + opt_name = "SGD" + else: + self.optimizer = torch.optim.Adam([self.latents], lr=config.lr, betas=(0.9, 0.999), eps=1e-8) + opt_name = "Adam" + + logging.info(f"✅ HunyuanSDSOptimizerInitializationcompleted (with differentiable physics support) ") + logging.info(f" - Latents shape: {self.latents.shape}") + logging.info(f" - Latents dtype: {self.latents.dtype} (optimized in float32)") + logging.info(f" - Device: {device}") + logging.info(f" - Optimizer: {opt_name}") + logging.info(f" - Learning rate: {config.lr}") + + # target_z0 EMA cache. + self.target_z0_ema = None + self.target_z0_last_velocity = None + self.target_z0_last_update = None + + def get_field(self, x: torch.Tensor, latents: torch.Tensor = None) -> torch.Tensor: + """Differentiable SDF query through the VAE geo_decoder. + + Args: + x: Query points [N, 3] in the range [-0.8, 0.8]^3. + latents: Optional latent tokens; defaults to self.latents. + + Returns: + sdf: SDF values [N] with gradient support. + """ + if latents is None: + latents = self.latents + + # Match the official pipeline: divide by scale_factor before decoding. + scale_factor = getattr(self.vae, "scale_factor", 1.0) + latents_scaled = latents / scale_factor + + # Convert to FP16 because the VAE expects FP16 inputs. + latents_fp16 = latents_scaled.to(torch.float16) + + # Decode with the VAE decoder while preserving gradients. + decoded_latents = self.vae.decode(latents_fp16) + + # Query the SDF through the differentiable helper. + # sdf_query calls geo_decoder internally, so keep FP16 to match VAE weights. + sdf = self.sdf_query( + decoded_latents, # Keep FP16 and let sdf_query handle the rest. + x, + return_occupancy=False # Return SDF instead of occupancy. + ) # [N] + + return sdf + + def _cond_batch_size(self, cond) -> Optional[int]: + if isinstance(cond, torch.Tensor): + return cond.shape[0] if cond.dim() >= 1 else None + if isinstance(cond, dict): + for v in cond.values(): + bsz = self._cond_batch_size(v) + if bsz is not None: + return bsz + if isinstance(cond, (list, tuple)): + for v in cond: + bsz = self._cond_batch_size(v) + if bsz is not None: + return bsz + return None + + def _cond_slice(self, cond, batch_slice: slice): + if isinstance(cond, torch.Tensor): + if cond.dim() >= 1 and cond.shape[0] >= batch_slice.stop: + return cond[batch_slice] + return cond + if isinstance(cond, dict): + return {k: self._cond_slice(v, batch_slice) for k, v in cond.items()} + if isinstance(cond, (list, tuple)): + return type(cond)(self._cond_slice(v, batch_slice) for v in cond) + return cond + + def _cond_repeat(self, cond, repeats: int): + if isinstance(cond, torch.Tensor): + if cond.dim() >= 1: + rep_shape = (repeats,) + (1,) * (cond.dim() - 1) + return cond.repeat(rep_shape) + return cond + if isinstance(cond, dict): + return {k: self._cond_repeat(v, repeats) for k, v in cond.items()} + if isinstance(cond, (list, tuple)): + return type(cond)(self._cond_repeat(v, repeats) for v in cond) + return cond + + def _get_cond_for_guidance(self, use_cfg: bool): + cond = self.cond + bsz = self._cond_batch_size(cond) + if use_cfg: + if bsz == 1: + if not self._cond_warned_cfg_repeat: + logging.warning("⚠️ guidance_scale>1 cond batch=1, already condCFG") + self._cond_warned_cfg_repeat = True + return self._cond_repeat(cond, 2) + if bsz is not None and bsz > 2: + return self._cond_slice(cond, slice(0, 2)) + return cond + # no-CFG + if bsz is not None and bsz >= 2: + if self.config.sds_use_uncond: + if not self._cond_warned_nocfg_slice: + logging.info("ℹ️ guidance_scale<=1, useno conditioncond[1:2]") + self._cond_warned_nocfg_slice = True + return self._cond_slice(cond, slice(1, 2)) + if not self._cond_warned_nocfg_slice: + logging.info("ℹ️ guidance_scale<=1, already usecond[0:1]batch") + self._cond_warned_nocfg_slice = True + return self._cond_slice(cond, slice(0, 1)) + if self.config.sds_use_uncond and bsz == 1 and not self._cond_warned_nocfg_slice: + logging.warning("⚠️ sds_use_uncond=1 cond batch=1, already fallback to conditself") + self._cond_warned_nocfg_slice = True + return cond + + def latents_to_mesh(self, latents: torch.Tensor, octree_res: int = 128) -> Optional[trimesh.Trimesh]: + """Decode latent tokens into a mesh. + + Args: + latents: Latent tokens [1, N, D] (float32). + octree_res: Octree resolution. 128 is faster; 256 is higher quality. + + Returns: + A trimesh.Trimesh object, or None on failure. + """ + with torch.no_grad(): + # Skip invalid latent tensors early. + if torch.isnan(latents).any() or torch.isinf(latents).any(): + logging.warning(" latents_to_mesh: latentscontains NaN or Inf, skip") + return None + + # Match the official pipeline by dividing by scale_factor first. + scale_factor = getattr(self.vae, "scale_factor", 1.0) + latents_scaled = latents / scale_factor + + # Decode in FP16 because the VAE expects FP16 inputs. + latents_fp16 = latents_scaled.to(torch.float16) + + try: + # VAE decode. + decoded_latents = self.vae.decode(latents_fp16) + + # Skip invalid decoded latents. + if torch.isnan(decoded_latents).any() or torch.isinf(decoded_latents).any(): + logging.warning(" latents_to_mesh: decoded_latentscontains NaN or Inf, skip") + return None + except Exception as e: + logging.debug(f" latents_to_mesh: VAE decodingfailed: {e}") + return None + + # Use an adaptive mc_level fallback if the default level fails. + try: + # First try the standard mc_level=0.0. + mesh = self.vae.latents2mesh( + decoded_latents, + output_type='trimesh', + bounds=1.01, + mc_level=0.0, + num_chunks=20000, + octree_resolution=octree_res, + mc_algo='mc', + enable_pbar=False + ) + mesh = export_to_trimesh(mesh)[0] + return mesh + + except ValueError as e: + error_msg = str(e) + if "Surface level must be within volume data range" in error_msg: + # Estimate a better mc_level from sampled SDF statistics. + logging.debug(f" latents_to_mesh: mc_level=0.0 failed, try an adaptive level...") + + try: + # Sample a coarse grid to estimate the SDF range. + grid_size = 32 + x = torch.linspace(-1.0, 1.0, grid_size, device=decoded_latents.device) + y = torch.linspace(-1.0, 1.0, grid_size, device=decoded_latents.device) + z = torch.linspace(-1.0, 1.0, grid_size, device=decoded_latents.device) + xx, yy, zz = torch.meshgrid(x, y, z, indexing='ij') + points = torch.stack([xx, yy, zz], dim=-1).reshape(-1, 3) # [N, 3] + + # query the SDF values. + sdf_values = self.get_field(points, latents=latents) + + # Compute basic statistics. + sdf_median = torch.median(sdf_values).item() + sdf_min = sdf_values.min().item() + sdf_max = sdf_values.max().item() + sdf_mean = sdf_values.mean().item() + + logging.debug(f" SDFstatistics: min={sdf_min:.4f}, max={sdf_max:.4f}, median={sdf_median:.4f}, mean={sdf_mean:.4f}") + + # No clear surface can be extracted if the SDF range is too small. + if abs(sdf_max - sdf_min) < 1e-4: + logging.debug(f" SDFrange is too small to extract a surface") + return None + + # Try several plausible candidate levels. + candidate_levels = [ + sdf_median, # Median. + sdf_mean, # Mean. + (sdf_min + sdf_max) / 2, # Midpoint of the range. + sdf_min + (sdf_max - sdf_min) * 0.3, # 30% point. + sdf_min + (sdf_max - sdf_min) * 0.7, # 70% point. + ] + + # Clamp all levels to the valid range. + valid_levels = [ + max(sdf_min + 0.001, min(sdf_max - 0.001, level)) + for level in candidate_levels + ] + + # Remove duplicates. + valid_levels = list(set(valid_levels)) + + logging.debug(f" try {len(valid_levels)} candidate levels: {[f'{l:.4f}' for l in valid_levels[:3]]}...") + + # Try each candidate level in order. + for i, adaptive_level in enumerate(valid_levels): + try: + mesh = self.vae.latents2mesh( + decoded_latents, + output_type='trimesh', + bounds=1.01, + mc_level=adaptive_level, + num_chunks=20000, + octree_resolution=octree_res, + mc_algo='mc', + enable_pbar=False + ) + mesh = export_to_trimesh(mesh)[0] + logging.info(f" ✅ uselevelsucceeded (level={adaptive_level:.4f}, attempt {i+1})") + return mesh + except (ValueError, RuntimeError) as level_error: + # Try the next level if this one fails. + if i < len(valid_levels) - 1: + continue + else: + # All candidate levels failed. + logging.debug(f" all candidate levels failed") + return None + + # No candidate succeeded. + return None + + except Exception as adaptive_error: + logging.debug(f" adaptive extraction failed: {type(adaptive_error).__name__}: {str(adaptive_error)[:50]}") + return None + + elif "No surface found" in error_msg: + logging.debug(f" latents_to_mesh: Marching cubesno surface found, skip") + return None + else: + logging.warning(f" latents_to_mesh: unknown ValueError: {error_msg}") + return None + + except RuntimeError as e: + error_msg = str(e) + if "No surface found" in error_msg or "Surface level" in error_msg: + logging.debug(f" latents_to_mesh: Marching cubesfailed, skip") + return None + else: + logging.warning(f" latents_to_mesh: RuntimeError: {error_msg}") + return None + + except Exception as e: + # Catch any other unexpected failure. + logging.warning(f" latents_to_mesh: unexpected exception: {type(e).__name__}: {e}") + return None + + def _filter_floating_components(self, mesh: trimesh.Trimesh) -> trimesh.Trimesh: + """Remove small floating fragments and keep only the largest component.""" + try: + components = mesh.split(only_watertight=False) + if len(components) <= 1: + return mesh + + face_counts = [len(comp.faces) for comp in components] + max_idx = int(np.argmax(face_counts)) + filtered = components[max_idx] + dropped = len(components) - 1 + + logging.info(f" 🧹 filter floating fragments: kept{len(filtered.faces)} faces, discarded{dropped} small components") + return filtered + except Exception as e: + logging.warning(f" failed to filter floating fragments: {type(e).__name__}: {str(e)[:100]}") + return mesh + + def _sample_displacement_to_vertices( + self, + vertices: np.ndarray, + nodes: np.ndarray, + displacement: np.ndarray, + ) -> np.ndarray: + """Sample the voxel-node displacement field onto mesh vertices by nearest neighbor.""" + try: + from scipy.spatial import cKDTree + tree = cKDTree(nodes) + _, idx = tree.query(vertices, k=1) + return displacement[idx] + except Exception as e: + try: + from sklearn.neighbors import NearestNeighbors + nn = NearestNeighbors(n_neighbors=1, algorithm="auto") + nn.fit(nodes) + idx = nn.kneighbors(vertices, return_distance=False).squeeze(1) + return displacement[idx] + except Exception as e2: + logging.warning(f" displacement sampling failed, fallback to zero displacement: {type(e).__name__}: {str(e)[:100]}") + logging.debug(f" secondaryError: {type(e2).__name__}: {str(e2)[:100]}") + return np.zeros_like(vertices) + + def _normalize_displacement_magnitude( + self, disp_mag: np.ndarray + ) -> Tuple[np.ndarray, float, float, bool]: + """Normalize displacement magnitude, optionally with a fixed range.""" + mag_max_cfg = getattr(self.config, "deformed_mesh_disp_max", None) + mag_min_cfg = getattr(self.config, "deformed_mesh_disp_min", None) + use_fixed = mag_max_cfg is not None and mag_max_cfg > 0.0 + if use_fixed: + mag_min = 0.0 if mag_min_cfg is None else float(mag_min_cfg) + mag_max = float(mag_max_cfg) + if mag_max <= mag_min: + use_fixed = False + if not use_fixed: + mag_min = float(disp_mag.min()) + mag_max = float(disp_mag.max()) + denom = max(1e-12, mag_max - mag_min) + norm = (disp_mag - mag_min) / denom + if use_fixed: + norm = np.clip(norm, 0.0, 1.0) + return norm, mag_min, mag_max, use_fixed + + def _make_displacement_colors(self, displacement: np.ndarray) -> np.ndarray: + """Map displacement magnitude to vertex colors (blue -> red).""" + disp_mag = np.linalg.norm(displacement, axis=1) + norm, _, _, _ = self._normalize_displacement_magnitude(disp_mag) + colors = np.stack([norm, np.zeros_like(norm), 1.0 - norm], axis=1) + return (colors * 255).astype(np.uint8) + + def _log_physical_quantities( + self, + u: torch.Tensor, + sigma: Optional[torch.Tensor], + ) -> None: + """Log displacement and von Mises stress statistics.""" + with torch.no_grad(): + u_max = None + u_avg = None + try: + u_mag = torch.norm(u, dim=1) + u_max = u_mag.max().item() + u_avg = u_mag.mean().item() + except Exception as e: + logging.warning( + f" ⚠️ displacement statistics failed: {type(e).__name__}: {str(e)[:100]}" + ) + + sigma_vm_max = None + sigma_vm_avg = None + if sigma is not None: + try: + if sigma.dim() == 2 and sigma.shape[1] >= 6: + s_xx = sigma[:, 0] + s_yy = sigma[:, 1] + s_zz = sigma[:, 2] + s_yz = sigma[:, 3] + s_xz = sigma[:, 4] + s_xy = sigma[:, 5] + mises_sq = 0.5 * ( + (s_xx - s_yy) ** 2 + + (s_yy - s_zz) ** 2 + + (s_zz - s_xx) ** 2 + + 6.0 * (s_xy ** 2 + s_yz ** 2 + s_xz ** 2) + ) + mises = torch.sqrt(torch.clamp(mises_sq, min=0.0)) + sigma_vm_max = mises.max().item() + sigma_vm_avg = mises.mean().item() + else: + logging.warning( + f" ⚠️ sigmashape does not match expectations, skip von Mises statistics: {tuple(sigma.shape)}" + ) + except Exception as e: + logging.warning( + f" ⚠️ von Mises statistics failed: {type(e).__name__}: {str(e)[:100]}" + ) + + if u_max is not None and u_avg is not None: + if sigma_vm_max is not None and sigma_vm_avg is not None: + logging.info( + f" physical metrics: u_max={u_max:.3e}, u_avg={u_avg:.3e}, " + f"sigma_vm_max={sigma_vm_max:.3e}, sigma_vm_avg={sigma_vm_avg:.3e}" + ) + else: + logging.info( + f" physical metrics: u_max={u_max:.3e}, u_avg={u_avg:.3e}" + ) + + def backward_step(self, sensitivity_density: torch.Tensor): + """Backpropagate with VJP, aligned with the reference code. + + Reference: viewer_deepsdf.py Line 148-183. + This uses torch.autograd.functional.vjp to propagate sensitivity to latents. + """ + def f(latents: torch.Tensor): + """ + Compute occupancy from a given latent tensor. + Aligned with viewer_deepsdf.py Line 155-173. + """ + # Query the SDF. + sdf = self.get_field(self.nodes, latents) + + # SDF → occupancy + from physiopt.opt.field import occ_kernel + occ = occ_kernel(sdf, self.config.res, self.config.occ_sdf_beta) + + # Element occupancy is the average over the 8 nodes. + occ_elem = occ[self.elements].mean(1) + + # Clamp by alpha_min if requested. + if self.config.alpha_min > 0.0: + occ_elem = torch.clamp(occ_elem, self.config.alpha_min) + + return occ_elem + + # VJP computations d occ / d latents^T times the sensitivity vector. + # Aligned with viewer_deepsdf.py Line 175-180. + try: + grad_latent = torch.autograd.functional.vjp( + f, + self.latents.clone().requires_grad_(True), + sensitivity_density, + )[1] + + # Validate the returned gradient. + if grad_latent is None: + logging.error(" ❌ VJP returned None!") + return + + grad_norm = torch.norm(grad_latent).item() + logging.info(f" VJP gradient: norm={grad_norm:.2e}") + + # Assign the gradient manually, matching the reference implementation. + self.latents.grad = grad_latent + + except Exception as e: + logging.error(f" ❌ VJP failed: {e}") + import traceback + traceback.print_exc() + + def prepare_physical_simulation(self): + """Prepare the physical simulation and FEM solver state. + + Initialization includes: + 1. Material properties + 2. Boundary conditions + 3. External forces + """ + if not WARP_AVAILABLE: + logging.warning("Warpnot installed, skipphysics simulation preparation") + return + + if not hasattr(self, 'nodes') or not hasattr(self, 'elements'): + logging.error("please call extract_solid() to extract the solid first") + return + + logging.info("prepare physical simulation...") + + # Initialize Warp. + wp.init() + + # Normalize device names such as "cuda" and "cuda:0". + if 'cuda' in self.device: + # Extract the device id when needed. + if ':' in self.device: + device_id = self.device.split(':')[-1] + warp_device = f"cuda:{device_id}" + else: + warp_device = "cuda:0" # default to cuda:0 + else: + warp_device = "cpu" + + wp.set_device(warp_device) + logging.info(f"Warpdevice: {warp_device}") + + # Material properties. + self.E = self.config.youngs_modulus # Young's modulus. + self.nu = self.config.poissons_ratio # Poisson's ratio. + self.rho = self.config.density # Density. + + # Boundary condition: fix bottom nodes using Hunyuan's Y-up frame. + y_coords = self.nodes[:, 1] + y_min = y_coords.min() + boundary_threshold = y_min + 0.05 # 0.2 # 0.05 # Bottom 5% band. + self.boundary_mask = y_coords < boundary_threshold + + logging.info(f" coordinate system: Y-up (Hunyuan-native), fix Y < {boundary_threshold:.3f}nodes") + + # Apply load locally instead of spreading it across all nodes. + # The default heuristic targets a seat-like region in the Y-up frame. + + # Compute the total force, giving priority to force_entries. + total_force = np.zeros(3, dtype=np.float32) + force_entries = getattr(self.config, "force_entries", None) + valid_force_entries = None + if force_entries: + valid_force_entries = [] + for entry in force_entries: + if not isinstance(entry, dict): + continue + entry_force = None + if "force" in entry: + try: + entry_force = np.array(entry["force"], dtype=np.float32) + except Exception: + entry_force = None + elif "forces" in entry and isinstance(entry["forces"], list): + try: + entry_force = np.sum( + np.array(entry["forces"], dtype=np.float32), axis=0 + ) + except Exception: + entry_force = None + if entry_force is None or entry_force.shape != (3,): + continue + valid_force_entries.append(entry) + total_force += entry_force + if valid_force_entries: + self.force_entries_preset = valid_force_entries + logging.info(f" force entries: {len(valid_force_entries)}") + else: + logging.warning(" ⚠️ force_entries has no valid entries, fallback to forces") + valid_force_entries = None + + if valid_force_entries is None: + for force_config in self.config.forces: + if hasattr(force_config, 'get_total_force'): + # ForceConfig object. + total_force += force_config.get_total_force() + elif isinstance(force_config, dict) and 'external_force' in force_config: + # Compatibility format using a plain dict. + total_force += np.array(force_config['external_force'], dtype=np.float32) + else: + logging.warning(f"unknown force format: {type(force_config)}") + + logging.info(f" sum of external forces (Y-up coordinates): {total_force}") + + # Choose the loading strategy from the config. + if valid_force_entries is not None: + # Multiple localized loads, each with its own region. + self._setup_local_loading(total_force) + elif self.config.use_local_loading: + # Preferred mode: local loading. + self._setup_local_loading(total_force) + else: + # Fallback mode: global uniform loading. + logging.info(f" ℹ️ using global uniform loading mode") + total_force_tensor = torch.from_numpy(total_force).float().to(self.device) + num_nodes = self.nodes.shape[0] + self.forces = total_force_tensor[None, :].repeat(num_nodes, 1) + logging.info(f" 💨 distributed the total force uniformly to{num_nodes}nodes") + + logging.info(f"boundary conditions: {self.boundary_mask.sum().item()}fixed nodes") + logging.info(f"material properties: E={self.E:.2e}, ν={self.nu}, ρ={self.rho}") + + def _setup_local_loading(self, total_force: np.ndarray): + """Set up local loading on the selected seat/contact region. + + The total force is distributed uniformly across the selected nodes so + that sum(forces) equals total_force. + + Args: + total_force: Total force vector [3] in the Y-up frame, in Newtons. + """ + # Cache the total force for later updates. + self.total_force_preset = torch.from_numpy(total_force).float().to(self.device) + + # Reuse the generic update routine for the initial setup. + self._update_forces(initial_setup=True) + + def _update_forces(self, initial_setup: bool = False): + """Update the force distribution for the current mesh state. + + Core logic: + 1. Re-identify contact nodes + 2. Spread the preset total force uniformly over those nodes + 3. Keep total force conserved + + Args: + initial_setup: Whether this is the first setup pass. + """ + if not hasattr(self, 'total_force_preset'): + logging.warning("No preset total force is set, so the force distribution cannot be updated") + return + + # Step 1: inspect the Y-coordinate distribution. + y_coords = self.nodes[:, 1] + num_nodes = self.nodes.shape[0] + + force_entries = getattr(self, "force_entries_preset", None) + if force_entries: + def _select_nodes_for_mode(mode, top_percent, min_ratio, max_ratio, bbox, bbox_ratio): + seat_mask = torch.zeros(num_nodes, dtype=torch.bool, device=self.device) + mode_used = mode + bbox_desc = None + + if mode_used not in ("top_percent", "height_ratio", "bbox", "global"): + logging.warning(f" ⚠️ invalid force_region_mode: {mode_used}, fallback to top_percent") + mode_used = "top_percent" + + if mode_used == "global": + seat_mask[:] = True + return seat_mask, mode_used, bbox_desc + + if mode_used == "bbox": + bbox_vals = None + if bbox is not None and len(bbox) == 6: + bbox_vals = [float(v) for v in bbox] + bbox_desc = "abs" + elif bbox_ratio is not None and len(bbox_ratio) == 6: + bbox_ratio_vals = [float(v) for v in bbox_ratio] + bounds_min = self.nodes.min(dim=0).values + bounds_max = self.nodes.max(dim=0).values + bbox_vals = [ + bounds_min[0].item() + bbox_ratio_vals[0] * (bounds_max[0] - bounds_min[0]).item(), + bounds_min[0].item() + bbox_ratio_vals[1] * (bounds_max[0] - bounds_min[0]).item(), + bounds_min[1].item() + bbox_ratio_vals[2] * (bounds_max[1] - bounds_min[1]).item(), + bounds_min[1].item() + bbox_ratio_vals[3] * (bounds_max[1] - bounds_min[1]).item(), + bounds_min[2].item() + bbox_ratio_vals[4] * (bounds_max[2] - bounds_min[2]).item(), + bounds_min[2].item() + bbox_ratio_vals[5] * (bounds_max[2] - bounds_min[2]).item(), + ] + bbox_desc = "ratio" + else: + logging.warning(" ⚠️ bbox mode did not provide a valid bbox, fallback to top_percent") + mode_used = "top_percent" + + if mode_used == "bbox" and bbox_vals is not None: + x0, x1 = sorted([bbox_vals[0], bbox_vals[1]]) + y0, y1 = sorted([bbox_vals[2], bbox_vals[3]]) + z0, z1 = sorted([bbox_vals[4], bbox_vals[5]]) + seat_mask = ( + (self.nodes[:, 0] >= x0) & (self.nodes[:, 0] <= x1) + & (self.nodes[:, 1] >= y0) & (self.nodes[:, 1] <= y1) + & (self.nodes[:, 2] >= z0) & (self.nodes[:, 2] <= z1) + ) + if seat_mask.sum().item() < 1: + logging.warning(" ⚠️ bbox region matched no nodes, fallback to top_percent") + mode_used = "top_percent" + else: + bbox_desc = f"{bbox_desc}: [{x0:.3f},{x1:.3f}]x[{y0:.3f},{y1:.3f}]x[{z0:.3f},{z1:.3f}]" + + if mode_used == "height_ratio": + y_min = y_coords.min().item() + y_max = y_coords.max().item() + y_range = max(1e-8, y_max - y_min) + if not (0.0 <= min_ratio < max_ratio <= 1.0): + logging.warning( + f" ⚠️ invalid height_ratio: min={min_ratio}, max={max_ratio}, fallback to top_percent" + ) + mode_used = "top_percent" + else: + seat_y_min = y_min + y_range * min_ratio + seat_y_max = y_min + y_range * max_ratio + seat_mask = (y_coords >= seat_y_min) & (y_coords <= seat_y_max) + if seat_mask.sum().item() < 1: + logging.warning(" ⚠️ height_ratio matched no nodes, fallback to top_percent") + mode_used = "top_percent" + + if mode_used == "top_percent": + top_percent = float(top_percent) + top_percent = max(0.0, min(1.0, top_percent)) + if top_percent <= 0.0: + top_percent = 0.05 + num_seat_nodes = max(1, int(num_nodes * top_percent)) + _, top_indices = torch.topk(y_coords, k=num_seat_nodes, largest=True) + seat_mask = torch.zeros(num_nodes, dtype=torch.bool, device=self.device) + seat_mask[top_indices] = True + + return seat_mask, mode_used, bbox_desc + + self.forces = torch.zeros((num_nodes, 3), dtype=torch.float32, device=self.device) + combined_mask = torch.zeros(num_nodes, dtype=torch.bool, device=self.device) + total_force = torch.zeros(3, dtype=torch.float32, device=self.device) + + for idx, entry in enumerate(force_entries): + if not isinstance(entry, dict): + continue + entry_label = entry.get("label") or entry.get("name") or f"{idx+1}" + entry_force = None + if "forces" in entry and isinstance(entry["forces"], list): + try: + entry_force = np.sum(np.array(entry["forces"], dtype=np.float32), axis=0) + except Exception: + entry_force = None + if entry_force is None and "force" in entry: + try: + entry_force = np.array(entry["force"], dtype=np.float32) + except Exception: + entry_force = None + if entry_force is None or entry_force.shape != (3,): + logging.warning(f" ⚠️ invalid force entry[{entry_label}], skip") + continue + + entry_force_tensor = torch.from_numpy(entry_force).float().to(self.device) + total_force += entry_force_tensor + + mode = str(entry.get("force_region_mode", self.config.force_region_mode)).lower() + if entry.get("global_loading") is True: + mode = "global" + + top_percent = entry.get("force_top_percent", self.config.force_top_percent) + min_ratio = entry.get("seat_height_min_ratio", self.config.seat_height_min_ratio) + max_ratio = entry.get("seat_height_max_ratio", self.config.seat_height_max_ratio) + bbox = entry.get("force_bbox", self.config.force_bbox) + bbox_ratio = entry.get("force_bbox_ratio", self.config.force_bbox_ratio) + + seat_nodes_mask, mode_used, bbox_desc = _select_nodes_for_mode( + mode, top_percent, min_ratio, max_ratio, bbox, bbox_ratio + ) + + num_seat_nodes = int(seat_nodes_mask.sum().item()) + if num_seat_nodes < 1: + logging.warning(f" ⚠️ entry[{entry_label}]matched no nodes, skip") + continue + + force_per_node = entry_force_tensor / num_seat_nodes + self.forces[seat_nodes_mask] += force_per_node + combined_mask |= seat_nodes_mask + + seat_y_values = y_coords[seat_nodes_mask] + seat_y_min = seat_y_values.min().item() + seat_y_max = seat_y_values.max().item() + seat_y_mean = seat_y_values.mean().item() + + if initial_setup: + if mode_used == "bbox": + logging.info(f" 🪑 contact surface[{entry_label}]: bbox ({bbox_desc})") + elif mode_used == "height_ratio": + logging.info( + f" 🪑 contact surface[{entry_label}]: height_ratio " + f"[{min_ratio:.2f}, {max_ratio:.2f}]" + ) + elif mode_used == "global": + logging.info(f" 🪑 contact surface[{entry_label}]: global") + else: + logging.info( + f" 🪑 contact surface[{entry_label}]: highest-Y {float(top_percent):.1%} nodes" + ) + logging.info( + f" 🪑 seat-node count[{entry_label}]: {num_seat_nodes}/{num_nodes} " + f"({num_seat_nodes/num_nodes:.1%})" + ) + logging.info( + f" 🪑 Y range[{entry_label}]: [{seat_y_min:.3f}, {seat_y_max:.3f}], " + f"mean: {seat_y_mean:.3f}" + ) + logging.info(f" 💺 force[{entry_label}]: {entry_force}") + logging.info(f" 💺 per node[{entry_label}]: {force_per_node.cpu().numpy()}") + + self.total_force_preset = total_force + actual_total_force = self.forces.sum(dim=0) + force_error = torch.norm(actual_total_force - total_force).item() + force_error_percent = (force_error / (torch.norm(total_force).item() + 1e-10)) * 100 + + if initial_setup: + logging.info( + f" ✅ total-force check: {actual_total_force.cpu().numpy()} " + f"(error: {force_error:.2e}, {force_error_percent:.3f}%)" + ) + if combined_mask.any(): + self._save_force_visualization( + combined_mask, total_force.cpu().numpy() + ) + else: + logging.debug( + f" 🔄 force update: loaded nodes {int(combined_mask.sum().item())}, " + f"total force error {force_error:.2e}" + ) + + self._last_num_seat_nodes = int(combined_mask.sum().item()) + return + + # Contact-region selection supports top_percent / height_ratio / bbox. + mode = str(getattr(self.config, "force_region_mode", "top_percent")).lower() + seat_nodes_mask = torch.zeros(num_nodes, dtype=torch.bool, device=self.device) + mode_used = mode + bbox_desc = None + if mode_used not in ("top_percent", "height_ratio", "bbox"): + logging.warning(f" ⚠️ invalid force_region_mode: {mode_used}, fallback to top_percent") + mode_used = "top_percent" + + if mode_used == "bbox": + bbox = getattr(self.config, "force_bbox", None) + bbox_ratio = getattr(self.config, "force_bbox_ratio", None) + bbox_vals = None + if bbox is not None and len(bbox) == 6: + bbox_vals = [float(v) for v in bbox] + bbox_desc = "abs" + elif bbox_ratio is not None and len(bbox_ratio) == 6: + bbox_ratio_vals = [float(v) for v in bbox_ratio] + bounds_min = self.nodes.min(dim=0).values + bounds_max = self.nodes.max(dim=0).values + bbox_vals = [ + bounds_min[0].item() + bbox_ratio_vals[0] * (bounds_max[0] - bounds_min[0]).item(), + bounds_min[0].item() + bbox_ratio_vals[1] * (bounds_max[0] - bounds_min[0]).item(), + bounds_min[1].item() + bbox_ratio_vals[2] * (bounds_max[1] - bounds_min[1]).item(), + bounds_min[1].item() + bbox_ratio_vals[3] * (bounds_max[1] - bounds_min[1]).item(), + bounds_min[2].item() + bbox_ratio_vals[4] * (bounds_max[2] - bounds_min[2]).item(), + bounds_min[2].item() + bbox_ratio_vals[5] * (bounds_max[2] - bounds_min[2]).item(), + ] + bbox_desc = "ratio" + else: + logging.warning(" ⚠️ bbox mode did not provide a valid bbox, fallback to top_percent") + mode_used = "top_percent" + + if mode_used == "bbox" and bbox_vals is not None: + x0, x1 = sorted([bbox_vals[0], bbox_vals[1]]) + y0, y1 = sorted([bbox_vals[2], bbox_vals[3]]) + z0, z1 = sorted([bbox_vals[4], bbox_vals[5]]) + seat_nodes_mask = ( + (self.nodes[:, 0] >= x0) & (self.nodes[:, 0] <= x1) + & (self.nodes[:, 1] >= y0) & (self.nodes[:, 1] <= y1) + & (self.nodes[:, 2] >= z0) & (self.nodes[:, 2] <= z1) + ) + if seat_nodes_mask.sum().item() < 1: + logging.warning(" ⚠️ bbox region matched no nodes, fallback to top_percent") + mode_used = "top_percent" + else: + bbox_desc = f"{bbox_desc}: [{x0:.3f},{x1:.3f}]x[{y0:.3f},{y1:.3f}]x[{z0:.3f},{z1:.3f}]" + + if mode_used == "height_ratio": + y_min = y_coords.min().item() + y_max = y_coords.max().item() + y_range = max(1e-8, y_max - y_min) + min_ratio = float(self.config.seat_height_min_ratio) + max_ratio = float(self.config.seat_height_max_ratio) + if not (0.0 <= min_ratio < max_ratio <= 1.0): + logging.warning( + f" ⚠️ invalid height_ratio: min={min_ratio}, max={max_ratio}, fallback to top_percent" + ) + mode_used = "top_percent" + else: + seat_y_min = y_min + y_range * min_ratio + seat_y_max = y_min + y_range * max_ratio + seat_nodes_mask = (y_coords >= seat_y_min) & (y_coords <= seat_y_max) + if seat_nodes_mask.sum().item() < 1: + logging.warning(" ⚠️ height_ratio matched no nodes, fallback to top_percent") + mode_used = "top_percent" + + if mode_used == "top_percent": + top_percent = float(getattr(self.config, "force_top_percent", 0.05)) + top_percent = max(0.0, min(1.0, top_percent)) + if top_percent <= 0.0: + top_percent = 0.05 + num_seat_nodes = max(1, int(num_nodes * top_percent)) + _, top_indices = torch.topk(y_coords, k=num_seat_nodes, largest=True) + seat_nodes_mask = torch.zeros(num_nodes, dtype=torch.bool, device=self.device) + seat_nodes_mask[top_indices] = True + + num_seat_nodes = int(seat_nodes_mask.sum().item()) + + # Step 3: gather region statistics. + seat_y_values = y_coords[seat_nodes_mask] + seat_y_min = seat_y_values.min().item() + seat_y_max = seat_y_values.max().item() + seat_y_mean = seat_y_values.mean().item() + + # Step 4: computation the per-node load with uniform distribution. + force_per_node = self.total_force_preset / num_seat_nodes + + # Initialize all node forces to zero. + self.forces = torch.zeros((num_nodes, 3), dtype=torch.float32, device=self.device) + + # Apply force only to the selected seat/contact nodes. + self.forces[seat_nodes_mask] = force_per_node + + # Step 5: verify total-force conservation. + actual_total_force = self.forces.sum(dim=0) + force_error = torch.norm(actual_total_force - self.total_force_preset).item() + force_error_percent = (force_error / torch.norm(self.total_force_preset).item()) * 100 + + # Logging. + if initial_setup: + if mode_used == "bbox": + logging.info(f" 🪑 contact-surface setup: bbox ({bbox_desc})") + elif mode_used == "height_ratio": + logging.info( + f" 🪑 contact-surface setup: height_ratio " + f"[{self.config.seat_height_min_ratio:.2f}, {self.config.seat_height_max_ratio:.2f}]" + ) + else: + logging.info( + f" 🪑 contact-surface setup: highest-Y {float(getattr(self.config, 'force_top_percent', 0.05)):.1%} nodes" + ) + logging.info(f" 🪑 seat-node count: {num_seat_nodes}/{num_nodes} ({num_seat_nodes/num_nodes:.1%})") + logging.info(f" 🪑 Y-coordinate range: [{seat_y_min:.3f}, {seat_y_max:.3f}], mean: {seat_y_mean:.3f}") + logging.info(f" 💺 preset total force: {self.total_force_preset.cpu().numpy()}") + logging.info(f" 💺 force per node: {force_per_node.cpu().numpy()}") + logging.info(f" ✅ total-force check: {actual_total_force.cpu().numpy()} (error: {force_error:.2e}, {force_error_percent:.3f}%)") + + # Estimate the equivalent pressure. + y_range = y_coords.max().item() - y_coords.min().item() + grid_spacing = y_range / self.config.res if y_range > 0 else 0.01 + estimated_area = num_seat_nodes * (grid_spacing ** 2) + if estimated_area > 0 and abs(self.total_force_preset[1].item()) > 0: + pressure_kpa = abs(self.total_force_preset[1].item()) / estimated_area / 1000 + logging.info(f" 📏 equivalent pressure: {pressure_kpa:.1f} kPa (contact area≈{estimated_area:.4f} m²)") + + if pressure_kpa < 5: + logging.warning(f" ⚠️ pressure is too small ({pressure_kpa:.1f} kPa < 5 kPa)") + elif pressure_kpa > 50: + logging.warning(f" ⚠️ pressure is too large ({pressure_kpa:.1f} kPa > 50 kPa)") + + # Save visualization data. + self._save_force_visualization(seat_nodes_mask, self.total_force_preset.cpu().numpy()) + else: + # Shorter logging during optimization. + logging.debug(f" 🔄 force update: seat nodes {num_seat_nodes}, per node {force_per_node.cpu().numpy()}, " + f"total force error {force_error:.2e}") + + # Watch for changes in the number of loaded nodes. + if hasattr(self, '_last_num_seat_nodes') and self._last_num_seat_nodes != num_seat_nodes: + logging.info(f" ⚠️ seat-node count changed: {self._last_num_seat_nodes} → {num_seat_nodes}") + + # Cache the current state for the next comparison. + self._last_num_seat_nodes = num_seat_nodes + + def extract_solid(self, step: int = -1): + """Extract the physical solid by querying the node SDF directly. + + This method rebuilds the FEM mesh from the current latents so topology + changes in the SDF field can be reflected by the simulation mesh. + + Args: + step: Current optimization step, used for logging. + """ + if not WARP_AVAILABLE: + logging.warning("Warpnot installed, unable toperformphysics simulation") + return + + # Re-check physiopt availability at runtime. + try: + from physiopt.utils.phys_utils import generate_hex as _generate_hex + from physiopt.utils.grid_utils import filter_one_component as _filter_one_component + from physiopt.opt.field import occ_kernel as _occ_kernel + generate_hex_func = _generate_hex + filter_one_component_func = _filter_one_component + occ_kernel_func = _occ_kernel + logging.info("✅ physioptmoduleruntime check succeeded") + except ImportError as e: + logging.error(f"physioptmodulenot installed: {e}") + logging.error("please make sure physiopt is installed correctly: cd /mnt/cvlab/scratch/cvlab/home/hantzhan/physiopt && pip install -e .") + return + + res = self.config.res + step_label = f"Step {step}" if step >= 0 else "Initialization" + logging.info(f"{'🔄' if step >= 0 else '🆕'} [{step_label}] generate/update a mesh at resolution {res} hexahedral mesh...") + + # Keep the previous mesh size for comparison. + old_num_nodes = len(self.nodes) if hasattr(self, 'nodes') else 0 + old_num_elements = len(self.elements) if hasattr(self, 'elements') else 0 + + # 1. Generate the full hexahedral grid. + full_nodes, full_elements = generate_hex_func( + res=res, + limits=[(-0.8, 0.8), (-0.8, 0.8), (-0.8, 0.8)], + device=self.device, + return_coords=False + ) + + if full_nodes is None or full_elements is None: + logging.error("failed to generate the hexahedral mesh") + return + + full_nodes = full_nodes.to(self.device).float() + full_elements = full_elements.to(self.device).long() + + logging.info(f"hexahedral mesh generated successfully: {full_nodes.shape[0]}nodes, {full_elements.shape[0]}elements") + + # 2. Query the SDF directly through get_field. + logging.info("query node SDF values...") + sdf = self.get_field(full_nodes) + + # Make sure the SDF is a 1D tensor [N]. + if sdf.dim() > 1: + logging.warning(f"⚠️ SDFYesmulti-dimensional tensor: {sdf.shape}, will be flattened to 1D") + sdf = sdf.squeeze() # remove all size-1 dimensions + if sdf.dim() > 1: + sdf = sdf.reshape(-1) # force-flatten to 1D + + logging.info(f" ✅ SDF query succeeded: range=[{sdf.min():.3f}, {sdf.max():.3f}]") + logging.info(f" nodescount: {full_nodes.shape[0]}, SDF count: {sdf.shape[0]}") + + # Verify that the SDF count matches the node count. + if sdf.shape[0] != full_nodes.shape[0]: + logging.error(f"❌ SDF count({sdf.shape[0]}) vs. node count ({full_nodes.shape[0]})do not match!") + return + + # 3. Convert SDF values to occupancy. + logging.info("convert the SDF into an occupancy field...") + occ = occ_kernel_func(sdf, res, self.config.occ_sdf_beta) + + # 4. Select solid elements using an SDF threshold instead of an + # occupancy threshold. The threshold is intentionally relaxed so thin + # structures such as chair legs are kept. + SDF_FILTER_VALUE = 2.0 / res + nodewise_mask = sdf <= SDF_FILTER_VALUE + + # Diagnostic SDF statistics. + sdf_inside = sdf[nodewise_mask] + sdf_outside = sdf[~nodewise_mask] + logging.info(f" SDF threshold: {SDF_FILTER_VALUE:.4f}") + logging.info(f" interior nodes: {nodewise_mask.sum().item()}/{len(sdf)} ({100*nodewise_mask.sum().item()/len(sdf):.1f}%)") + if len(sdf_inside) > 0: + logging.info(f" inner SDF range: [{sdf_inside.min():.4f}, {sdf_inside.max():.4f}]") + if len(sdf_outside) > 0: + logging.info(f" outside-SDF range: [{sdf_outside.min():.4f}, {sdf_outside.max():.4f}]") + + # Debug the element-index range. + max_elem_idx = full_elements.max().item() + num_nodes = full_nodes.shape[0] + logging.info(f" elementsindex range: [0, {max_elem_idx}], nodescount: {num_nodes}") + + if max_elem_idx >= num_nodes: + logging.error(f"❌ index out of bounds!maximum element index({max_elem_idx}) >= nodescount({num_nodes})") + logging.error(f" this may be a problem with generate_hex") + # Clamp indices to the valid range. + valid_mask = (full_elements >= 0) & (full_elements < num_nodes) + if not valid_mask.all(): + logging.warning(f" found{(~valid_mask).sum().item()} invalid indices; filtering elements") + # Keep only elements whose node indices are all valid. + valid_elements_mask = valid_mask.all(dim=1) + full_elements = full_elements[valid_elements_mask] + logging.info(f" element count after filtering: {full_elements.shape[0]}") + + # Keep an element if any of its nodes passes the threshold. + elementwise_mask = torch.any(nodewise_mask[full_elements], dim=1) + + num_solid_elements = elementwise_mask.sum().item() + logging.info(f"SDF thresholdfiltering: {num_solid_elements}/{len(elementwise_mask)} solid elements") + + if num_solid_elements == 0: + logging.error("No solid elements were found; please check the SDF or adjust the threshold") + return + + # 5. Optionally keep only one connected component. + if self.config.one_cc_only: + element_res = res - 1 + try: + num_before_filter = elementwise_mask.sum().item() + elementwise_mask = filter_one_component_func(elementwise_mask, element_res) + num_filtered_elements = elementwise_mask.sum().item() + num_removed = num_before_filter - num_filtered_elements + logging.info(f"connectivity filtering: {num_filtered_elements} elements kept (removed{num_removed} small components)") + if num_removed > num_filtered_elements * 0.1: + logging.warning(f" ⚠️ removed{num_removed}elements({100*num_removed/num_before_filter:.1f}%), may have filtered out important parts (such as chair legs) ") + logging.warning(f" Suggestion: check the SDF threshold or consider disabling one_cc_only") + except IndexError as e: + logging.warning(f"connectivity filteringfailed: {e}, using the original mask") + else: + logging.info("connectivity filteringdisabled, keep all connected components") + + # 6. Select the active elements and nodes. + selected_elements = full_elements[elementwise_mask] + selected_node_indices, selected_elements = torch.unique( + selected_elements, return_inverse=True + ) + + self.elements = selected_elements + self.nodes = full_nodes[selected_node_indices] + + # 7. Compute occupancy for the selected nodes used in the simulation. + coarse_sdf = sdf[selected_node_indices] + coarse_occ_nodes = occ_kernel_func( + coarse_sdf, self.config.res, self.config.occ_sdf_beta + ) + # Each element occupancy is the mean over its 8 nodes. + self.coarse_occ = coarse_occ_nodes[self.elements].mean(1) + + # Diagnostic statistics for mesh-size changes. + new_num_nodes = len(self.nodes) + new_num_elements = len(self.elements) + + if old_num_nodes > 0: + node_change = new_num_nodes - old_num_nodes + element_change = new_num_elements - old_num_elements + node_change_pct = (node_change / old_num_nodes) * 100 + element_change_pct = (element_change / old_num_elements) * 100 + + logging.info(f"✅ solid extraction completed:") + logging.info(f" nodes: {old_num_nodes} → {new_num_nodes} ({node_change:+d}, {node_change_pct:+.1f}%)") + logging.info(f" elements: {old_num_elements} → {new_num_elements} ({element_change:+d}, {element_change_pct:+.1f}%)") + + if node_change > 0: + logging.info(f" ✅ mesh expanded!added{node_change}nodes (chair legs may have thickened) ") + elif node_change < 0: + logging.warning(f" ⚠️ mesh shrank!removed{-node_change}nodes (chair legs may have become thinner) ") + else: + logging.info(f"✅ solid extraction succeeded: {new_num_nodes}nodes, {new_num_elements}elements") + + # 8. Recomputation the boundary mask because the node count may change. + y_coords = self.nodes[:, 1] + y_min = y_coords.min() + boundary_threshold = y_min + 0.05 # bottom 5% region + self.boundary_mask = y_coords < boundary_threshold + + num_boundary = self.boundary_mask.sum().item() + logging.debug(f" 🔧 boundary conditionsupdated: {num_boundary}fixed nodes (Y < {boundary_threshold:.3f})") + + def get_current_sds_weight(self, step: int) -> float: + """Return the current SDS weight by linear interpolation. + + Args: + step: Current optimization step. + + Returns: + The SDS weight interpolated from sds_weight_start to sds_weight_end. + """ + # Linear interpolation from sds_weight_start to sds_weight_end. + progress = min(1.0, step / max(1, self.config.num_steps - 1)) + current_weight = self.config.sds_weight_start + progress * (self.config.sds_weight_end - self.config.sds_weight_start) + return current_weight + + def _computation_target_z0_current(self, step: int) -> Tuple[torch.Tensor, torch.Tensor]: + """Compute the current target_z0 for one update.""" + noise_level = float(self.config.sds_timestep) + t = 1.0 - noise_level # Hunyuan3D-2.1 uses t=0 for noise and t=1 for data. + epsilon = torch.randn_like(self.latents) + + self.sds_scheduler.config.num_train_timesteps = 100 + if self.sds_scheduler is not None: + # Match the official Flow Matching noise process: + # x_t = (1 - sigma) * x0 + sigma * eps. + sigma_step = 1.0 / float(self.sds_scheduler.config.num_train_timesteps) + total_span = max(0.0, 1.0 - t) + num_steps = int(np.ceil(total_span / sigma_step)) + sigmas = np.linspace(t, 1.0, num_steps + 1, dtype=np.float32) + self.sds_scheduler.set_timesteps(sigmas=sigmas, device=self.device) + t_scheds = self.sds_scheduler.timesteps + t_sched0 = t_scheds[0] + t_model0 = (t_sched0 / self.sds_scheduler.config.num_train_timesteps).to(self.latents.dtype) + if step % max(1, int(self.config.sds_target_z0_update_interval)) == 0: + logging.info( + f" 🎯 target_z0/sigmaalign: noise={noise_level:.4f}, t_start={t:.4f}, " + f"t_sched={t_sched0.item():.2f}, t_model={t_model0.item():.6f}, " + f"steps={num_steps}, sigma_step={sigma_step:.4g}" + ) + else: + t_sched = None + z_t = (1 - t) * epsilon + t * self.latents + t_model = torch.tensor([t], device=self.device, dtype=self.latents.dtype) + + with torch.no_grad(): + if self.sds_scheduler is not None: + # Integrate over multiple small sigma steps from sigma=t to 0. + cond_for_model = self._get_cond_for_guidance(self.config.guidance_scale > 1.0) + t_sched0 = t_scheds[0] + t_sched_batch = t_sched0.reshape(1).expand(self.latents.shape[0]) + # Hunyuan3D convention: t=0 is noise and t=1 is data. + z_t = self.sds_scheduler.scale_noise(epsilon, t_sched_batch, noise=self.latents) + + z_curr = z_t + velocity = None + for i in range(len(t_scheds) - 1): + t_sched = t_scheds[i] + t_model = (t_sched / self.sds_scheduler.config.num_train_timesteps).to(self.latents.dtype) + z_t_fp16 = z_curr.to(torch.float16) + t_tensor = t_model.to(device=self.device, dtype=z_t_fp16.dtype) + + if self.config.guidance_scale > 1.0: + latent_model_input = torch.cat([z_t_fp16, z_t_fp16]) + timestep_input = t_tensor.expand(latent_model_input.shape[0]) + + velocity_pred_fp16 = self.flow_model( + latent_model_input, + timestep_input, + cond_for_model, + guidance=None, + ) + + velocity_cond_fp16, velocity_uncond_fp16 = velocity_pred_fp16.chunk(2) + velocity_fp16 = velocity_uncond_fp16 + self.config.guidance_scale * (velocity_cond_fp16 - velocity_uncond_fp16) + + if step % 10 == 0 and i == 0: + logging.debug( + f" CFG (SDS): guidance_scale={self.config.guidance_scale:.1f}, " + f"||v_cond||={torch.norm(velocity_cond_fp16).item():.3e}, " + f"||v_uncond||={torch.norm(velocity_uncond_fp16).item():.3e}" + ) + else: + velocity_fp16 = self.flow_model( + z_t_fp16, + t_tensor.expand(z_t_fp16.shape[0]), + cond_for_model, + guidance=None, + ) + + velocity = velocity_fp16.to(torch.float32) + z_curr = self.sds_scheduler.step(velocity, t_sched, z_curr).prev_sample + + target_z0_current = z_curr + else: + cond_for_model = self._get_cond_for_guidance(self.config.guidance_scale > 1.0) + z_t_fp16 = z_t.to(torch.float16) + t_tensor = t_model.to(device=self.device, dtype=z_t_fp16.dtype) + + if self.config.guidance_scale > 1.0: + latent_model_input = torch.cat([z_t_fp16, z_t_fp16]) + timestep_input = t_tensor.expand(latent_model_input.shape[0]) + + velocity_pred_fp16 = self.flow_model( + latent_model_input, + timestep_input, + cond_for_model, + guidance=None, + ) + + velocity_cond_fp16, velocity_uncond_fp16 = velocity_pred_fp16.chunk(2) + velocity_fp16 = velocity_uncond_fp16 + self.config.guidance_scale * (velocity_cond_fp16 - velocity_uncond_fp16) + + if step % 10 == 0: + logging.debug( + f" CFG (SDS): guidance_scale={self.config.guidance_scale:.1f}, " + f"||v_cond||={torch.norm(velocity_cond_fp16).item():.3e}, " + f"||v_uncond||={torch.norm(velocity_uncond_fp16).item():.3e}" + ) + else: + velocity_fp16 = self.flow_model( + z_t_fp16, + t_tensor.expand(z_t_fp16.shape[0]), + cond_for_model, + guidance=None, + ) + + velocity = velocity_fp16.to(torch.float32) + # Fallback: one forward-Euler step to t=1. + target_z0_current = z_t + (1.0 - t) * velocity + + # Optional trust region to keep target_z0 from moving too far away. + max_rel = float(getattr(self.config, "sds_projection_max_rel", 0.0)) + if max_rel > 0.0: + with torch.no_grad(): + diff = target_z0_current - self.latents + diff_norm = torch.norm(diff).item() + latents_norm = torch.norm(self.latents).item() + max_norm = max_rel * (latents_norm + 1e-8) + if diff_norm > max_norm and max_norm > 0.0: + scale = max_norm / (diff_norm + 1e-8) + target_z0_current = self.latents + diff * scale + if step % max(1, int(self.config.sds_target_z0_update_interval)) == 0: + logging.info( + f" 🧱 target_z0 projection limit: diff={diff_norm:.3e} → {max_norm:.3e} " + f"(rel={max_rel:.2f})" + ) + return target_z0_current, velocity + + def _get_target_z0(self, step: int) -> Tuple[torch.Tensor, Optional[torch.Tensor], bool]: + """Update target_z0 on schedule and smooth it with EMA.""" + update_interval = max(1, int(self.config.sds_target_z0_update_interval)) + do_update = self.target_z0_ema is None or step % update_interval == 0 + + if do_update: + target_z0_current, velocity = self._computation_target_z0_current(step) + target_z0_current = target_z0_current.detach() + + if self.target_z0_ema is None: + self.target_z0_ema = target_z0_current.clone() + diff_norm = 0.0 + else: + diff = target_z0_current - self.target_z0_ema + diff_norm = torch.norm(diff).item() + alpha = 1.0 - self.config.sds_target_z0_ema_beta + self.target_z0_ema = self.target_z0_ema + alpha * diff + + self.target_z0_last_velocity = velocity + self.target_z0_last_update = step + + if step % update_interval == 0: + logging.info( + f" 🧭 target_z0 EMAupdate: interval={update_interval}, " + f"beta={self.config.sds_target_z0_ema_beta:.2f}, diff_norm={diff_norm:.3e}" + ) + else: + velocity = self.target_z0_last_velocity + + return self.target_z0_ema, velocity, do_update + + def project_to_manifold(self, step: int) -> bool: + """Project the current latents back to the manifold by replacing them with target_z0.""" + with torch.no_grad(): + target_z0, _ = self._computation_target_z0_current(step) + if torch.isnan(target_z0).any() or torch.isinf(target_z0).any(): + logging.warning(" ⚠️ projection failed: target_z0 contains NaN/Inf") + return False + deviation = torch.norm(target_z0 - self.latents).item() + latents_norm = torch.norm(self.latents).item() + rel = deviation / (latents_norm + 1e-8) + logging.info(f" 🧭 projection deviation: {deviation:.3e} (rel={rel:.2%})") + self.latents.data.copy_(target_z0) + if self.latents.grad is not None: + self.latents.grad.zero_() + # Reset optimizer state to avoid stale momentum. + self.optimizer.state.clear() + # Sync the EMA cache with the projected state. + self.target_z0_ema = target_z0.detach().clone() + self.target_z0_last_velocity = None + self.target_z0_last_update = step + return True + + def training_step_sds(self, step: int) -> Tuple[float]: + """Run one SDS optimization step. + + Returns: + (recon_loss,) + """ + self.optimizer.zero_grad() + + # ==================== SDS loss (Rectified Flow) ==================== + t = self.config.sds_timestep + target_z0, velocity, _ = self._get_target_z0(step) + + # SDS gradient: grad = z_0 - target_z0. + # This pulls the current z_0 (self.latents) toward target_z0. + sds_gradient = self.latents - target_z0.detach() + recon_loss = torch.mean(sds_gradient ** 2) / 2 + + # Debug information. + with torch.no_grad(): + target_norm = torch.norm(target_z0).item() + current_norm = torch.norm(self.latents).item() + grad_norm = torch.norm(sds_gradient).item() + velocity_norm = torch.norm(velocity).item() if velocity is not None else 0.0 + + logging.info(f"📐 Step {step:3d} | SDS: ||z_0||={current_norm:.2e}, " + f"||target_z_0||={target_norm:.2e}, " + f"||v||={velocity_norm:.2e}, " + f"||∇||={grad_norm:.2e}, t={t:.2f}, loss={recon_loss.item():.6e}") + + # Backpropagation. + sds_gradient_scaled = self.config.sds_weight * sds_gradient + + # Guard against invalid gradients. + if torch.isnan(sds_gradient_scaled).any() or torch.isinf(sds_gradient_scaled).any(): + logging.error(f"❌ Error: SDS gradient contains NaN or Inf!") + logging.error(f" ||sds_gradient||: {grad_norm:.2e}") + logging.error(f" sds_weight: {self.config.sds_weight}") + logging.error(f" target_z0 range: [{target_z0.min().item():.2e}, {target_z0.max().item():.2e}]") + logging.error(f" latents range: [{self.latents.min().item():.2e}, {self.latents.max().item():.2e}]") + if velocity is not None: + logging.error(f" velocity range: [{velocity.min().item():.2e}, {velocity.max().item():.2e}]") + return (recon_loss.item(),) + + if self.latents.grad is not None: + self.latents.grad.zero_() + + self.latents.grad = sds_gradient_scaled + + # Optional gradient clipping. + if self.config.grad_clip_enabled: + grad_norm_total = torch.norm(self.latents.grad).item() + max_grad_norm = 100.0 # 1e5lower to100 + if grad_norm_total > max_grad_norm: + clip_factor = max_grad_norm / grad_norm_total + self.latents.grad *= clip_factor + logging.warning(f"⚠️ gradient clipping: {grad_norm_total:.4e} -> {max_grad_norm:.4e}") + + # Save the pre-update latents for diagnostics. + old_latents = self.latents.data.clone() + + # Re-check the gradient before the optimizer step. + if torch.isnan(self.latents.grad).any(): + logging.error(f"❌ Error: gradient contains NaN (optimizerupdatefront) !") + return (recon_loss.item(),) + + # Optimizer update. + self.optimizer.step() + + # Measure parameter change after the update. + param_change = torch.norm(self.latents.data - old_latents).item() + + # Validate the updated latents. + if torch.isnan(self.latents).any(): + logging.error(f"❌ Error: latents contain NaN (optimizerupdateback) !") + logging.error(f" gradient norm: {grad_norm_total:.4e}") + logging.error(f" Learning rate: {self.config.lr}") + logging.error(f" Param change: {param_change:.4e}") + logging.error(f" suggestion: this may be caused by Adam optimizer momentum") + logging.error(f" : 1) reset optimizer 2) Use SGD instead of Adam") + # Restore the previous value. + self.latents.data.copy_(old_latents) + # Clear optimizer momentum/state before retrying. + self.optimizer.state.clear() + logging.info(f" ✅ already reset optimizerStatus, will retry on the next step") + return (recon_loss.item(),) + + # Sanity-check the latent magnitude. + latents_max = torch.abs(self.latents).max().item() + if latents_max > 1000: + logging.warning(f"⚠️ warning: latent values are too large (max={latents_max:.2e})") + logging.warning(f" you may need to lower the learning rate or SDS timestep") + + logging.info(f"✏️ Step {step:3d} | Param change: {param_change:.4e}, max|z|: {latents_max:.2e}") + + return (recon_loss.item(),) + + def training_step( + self, + step: int, + lagrange: float, + rho: float, + use_sds: bool = True, + save_step: Optional[int] = None, + ) -> Tuple[float, float, float]: + """Physics optimization. + + This follows the computation_phys_loss_grad flow from viewer_base.py: + 1. optimizer.zero_grad() + 2. with torch.no_grad(): prepare_solid() + solve() + 3. Compute sensitivities with the reference-style formula + 4. backward_step() via VJP + 5. Apply ALM weighting (lambda + rho[g]_+) + 6. optimizer.step() + + Reference: + physiopt/src/physiopt/vis/viewer_base.py Line 1297-1430 + """ + save_step_id = step if save_step is None else int(save_step) + + # ==================== Step 1: zero gradients ==================== + self.optimizer.zero_grad() + + # ==================== Step 2: update occupancy on the fixed topology ==================== + if step > 0: + logging.info(f"🔄 [Step {step}] update occupancy (mesh topology fixed) ...") + # Keep the previous occupancy for diagnostics. + old_occ = self.coarse_occ.clone() + + # Re-query the SDF and occupancy on the fixed mesh. + sdf = self.get_field(self.nodes) + from physiopt.opt.field import occ_kernel + occ = occ_kernel(sdf, self.config.res, self.config.occ_sdf_beta) + self.coarse_occ = occ[self.elements].mean(1) + + # Diagnose occupancy changes. + occ_change = self.coarse_occ - old_occ + occ_mean_change = occ_change.mean().item() + occ_increase_ratio = (occ_change > 0).float().mean().item() + + logging.info(f" occupancy range: [{self.coarse_occ.min():.3f}, {self.coarse_occ.max():.3f}]") + logging.info(f" occupancy change: mean={occ_mean_change:+.3e}, increase ratio={occ_increase_ratio:.1%}") + + # ==================== Step 3: physics simulation (with torch.no_grad) ==================== + # Aligned with the reference flow around Line 1317-1356. + with torch.no_grad(): + # 3.1 prepare_solid: apply SIMP scaling and build SolidGrid. + if self.config.alpha_min > 0.0: + self.coarse_occ = torch.clamp(self.coarse_occ, self.config.alpha_min) + + # Material SIMP scaling. + from torchfem.materials import IsotropicElasticity3D + from physiopt.opt.solid_grid import SolidGrid + + vectorized_material = IsotropicElasticity3D( + E=self.config.youngs_modulus, + nu=self.config.poissons_ratio, + rho=self.config.density, + ).vectorize(self.elements.shape[0]) + + vectorized_material.C *= ( + self.coarse_occ[:, None, None] ** self.config.p_exponent + ) + + # Create the SolidGrid solver state. + solid = SolidGrid(self.nodes, self.elements, vectorized_material) + solid.constraints[self.boundary_mask, :] = True + solid.forces = self.forces + + # 3.2 FEM solve. + logging.info(f"Step {step}: FEM solve...") + u, f_int, f_ext, sigma, _, _ = solid.solve(max_iter=1) + u_mean = torch.abs(u).mean().item() + logging.info(f" |u|_mean={u_mean}") + self._log_physical_quantities(u, sigma) + + # Save the deformed mesh every N steps. + # if self.config.deformed_mesh_interval > 0 and save_step_id % self.config.deformed_mesh_interval == 0: + # try: + # self.save_deformed_mesh(save_step_id, u) + # except Exception as e: + # logging.warning(f" ⚠️ error while saving the deformed mesh: {e}") + + # ==================== Step 4: sensitivity computation ==================== + # Strictly aligned with the reference flow around Line 1368-1399. + + # 4.1 Compute strain energy. We recover the unweighted energy by + # dividing out occ^p and keep strong numerical guards. + k0 = solid.k0() # occ^p * K_base after stiffness scaling. + u_j = u[self.elements].reshape(solid.n_elem, -1) + w_k_scaled = torch.einsum("...i, ...ij, ...j", u_j, k0, u_j) + + # Remove occ^p scaling to recover the base energy. + occ_power = torch.clamp( + self.coarse_occ ** self.config.p_exponent, + min=1e-6, # Avoid division by zero. + max=1.0 # Avoid overflow. + ) + + # Check again before division. + if torch.any(occ_power < 1e-6): + n_small = (occ_power < 1e-6).sum().item() + logging.warning(f" ⚠️ {n_small} elements have extremely small occ^p and were clamped to 1e-6") + + w_k_base = w_k_scaled / occ_power + + # Fall back if the recovered energy becomes invalid. + if torch.isnan(w_k_base).any() or torch.isinf(w_k_base).any(): + n_nan = torch.isnan(w_k_base).sum().item() + n_inf = torch.isinf(w_k_base).sum().item() + logging.error(f" ❌ w_k_baseabnormal: {n_nan} NaN, {n_inf} Inf") + logging.error(f" fall back to SIMP weightingw_k") + w_k_base = w_k_scaled + + # Use the recovered energy downstream. + compliance_mean = w_k_base.mean().item() + w_k = w_k_base # Downstream sensitivity uses the recovered energy. + + # Diagnostics. + logging.info(f" Compliance (true) ={compliance_mean:.2e}") + logging.info(f" w_k_base: max={w_k.max():.2e}, stress concentration={w_k.max()/(w_k.mean() + 1e-10):.1f}x") + + # ALM normalized constraint: g = D / D_thr - 1. + compliance_threshold = self.config.compliance_threshold if self.config.compliance_threshold is not None else 1.0 + g_raw = compliance_mean / (compliance_threshold + 1e-8) - 1.0 + g_pos = max(0.0, g_raw) + logging.info(f" constraint normalization: g={g_raw:+.3e}, [g]+={g_pos:.3e}, D_thr={compliance_threshold:.2e}") + + # Dynamic clip limit used by the ALM scaling guard. + base_max_grad = 1000.0 + lagrange_bonus = min((lagrange + rho * g_pos) * 10.0, 1000.0) + max_grad_norm = base_max_grad + lagrange_bonus + + # 4.3 Sensitivity formula aligned with the reference code: + # sensitivity = -p * occ^(p-1) * w_k + self.sensitivity_density = ( + -self.config.p_exponent + * self.coarse_occ ** (self.config.p_exponent - 1) + * w_k + ) + + # 4.4 Volume regularization is intentionally disabled here so the pure + # physics signal can be validated first. + if False and self.config.volume_term > 0.0: # Temporarily forced off. + # Initialize the reference volume on first use. + if not hasattr(self, 'init_volume'): + self.init_volume = self.coarse_occ.clone() + logging.info(f" record initial volume: sum={self.init_volume.sum().item():.2f}") + + # Volume sensitivity term. + sensitivity_volume = ( + self.config.volume_term + * (1.0 / self.config.res) ** 3 + * torch.ones_like(self.sensitivity_density) + ) + + # Choose the sign from the current volume change. + volume_sign = 1.0 if self.coarse_occ.sum() >= self.init_volume.sum() else -1.0 + sensitivity_volume *= volume_sign + + self.sensitivity_density += sensitivity_volume + + volume_ratio = self.coarse_occ.sum() / self.init_volume.sum() + logging.info(f" volume constraint: ratio={volume_ratio.item():.3f}, " + f"{'penalize' if volume_sign > 0 else 'encourage'}") + else: + logging.info(f" volume constraint: disabled (physicsoptimizationdominates) ") + + # Sensitivity diagnostics. + sens_norm = torch.norm(self.sensitivity_density).item() + sens_min = self.sensitivity_density.min().item() + sens_max = self.sensitivity_density.max().item() + logging.info(f" sensitivity: norm={sens_norm:.2e}, range=[{sens_min:.2e}, {sens_max:.2e}]") + + # ==================== Step 5: backward pass via VJP ==================== + self.backward_step(self.sensitivity_density) + + # ==================== Step 6: apply ALM weighting (lambda + rho[g]+) ==================== + if self.latents.grad is not None: + phys_grad_norm = torch.norm(self.latents.grad).item() + phys_grad_unscaled = self.latents.grad.clone() # Unscaled physics gradient for SDS comparisons. + + if g_pos > 0.0: + alm_scale_raw = (lagrange + rho * g_pos) / (compliance_threshold + 1e-8) + alm_scale = alm_scale_raw + guard_ratio = min(max(self.config.alm_scale_guard_ratio, 0.0), 1.0) + if phys_grad_norm > 0.0 and max_grad_norm > 0.0 and guard_ratio > 0.0: + alm_scale_guard = (max_grad_norm * guard_ratio) / (phys_grad_norm + 1e-8) + if alm_scale > alm_scale_guard: + logging.info( + f" 🔧 ALMscaling limit: raw={alm_scale_raw:.3e} -> {alm_scale_guard:.3e} " + f"(guard={guard_ratio:.2f}, max_grad={max_grad_norm:.1f})" + ) + alm_scale = alm_scale_guard + self.latents.grad *= alm_scale + else: + alm_scale = 0.0 + self.latents.grad.zero_() + + scaled_grad_norm = torch.norm(self.latents.grad).item() + logging.info( + f" physics gradient(ALM): {phys_grad_norm:.2e} → {scaled_grad_norm:.2e} " + f"(×scale={alm_scale:.3e}, λ={lagrange:.2f}, ρ={rho:.2f})" + ) + else: + phys_grad_unscaled = None + alm_scale = 0.0 + + # ==================== Step 7: shape loss toward target_z0 ==================== + + # 7.1 Compute the denoised target_z0. + import math + if use_sds: + target_z0, _, _ = self._get_target_z0(step) + else: + target_z0 = self.latents.detach() + + # Optionally validate and save a target_z0 mesh every 10 steps. + if use_sds: + self._maybe_save_target_z0_mesh(target_z0, save_step_id) + + # Shape loss is a simple MSE pulling latents toward target_z0. + shape_loss = torch.nn.functional.mse_loss(self.latents, target_z0.detach()) + + # 7.2 Decide whether shape loss is active this step. + current_sds_weight = self.get_current_sds_weight(step) if use_sds else 0.0 + use_sds_this_step = current_sds_weight > 0.0 + + if not use_sds_this_step: + logging.info(f" 🚫 Shape Loss disabled (physicsoptimizationmode) ") + weighted_sds = 0.0 + shape_grad_norm = 0.0 + else: + # Weighted shape loss. + weighted_shape_loss = current_sds_weight * shape_loss + + # Validate shape loss before backpropagating it. + if torch.isnan(shape_loss) or torch.isinf(shape_loss): + logging.error(f" ❌ Shape Loss contains NaN or Inf; skipping the shape constraint") + weighted_sds = 0.0 + shape_grad_norm = 0.0 + else: + # Backpropagate the shape loss into latents.grad. + weighted_shape_loss.backward() + + # Measure the shape-gradient norm for logging. + if self.latents.grad is not None and phys_grad_unscaled is not None: + # Isolate the shape part from the combined gradient. + shape_gradient = self.latents.grad - phys_grad_unscaled * alm_scale + shape_grad_norm = torch.norm(shape_gradient).item() + phys_grad_norm_current = torch.norm(phys_grad_unscaled * alm_scale).item() + shape_phys_ratio = shape_grad_norm / (phys_grad_norm_current + 1e-10) + + if shape_phys_ratio > 100.0: + logging.error(f" ❌ Shape gradient is too large (Shape/physics={shape_phys_ratio:.1f}x)!") + logging.error(f" consider lowering sds_weight_end: {self.config.sds_weight_end} → {self.config.sds_weight_end/100:.4f}") + elif shape_phys_ratio > 10.0: + logging.warning(f" ⚠️ Shape gradient is relatively large (Shape/physics={shape_phys_ratio:.1f}x)") + + # Compare the directions of physics and shape gradients. + cos_angle = (phys_grad_unscaled * shape_gradient).sum() / ( + torch.norm(phys_grad_unscaled) * torch.norm(shape_gradient) + 1e-10 + ) + angle_deg = torch.acos(torch.clamp(cos_angle, -1, 1)) * 180 / math.pi + direction = "same direction✅" if angle_deg < 90 else "opposite direction⚠️" + + logging.info(f" Shapegradient: norm={shape_grad_norm:.4e}, weight={current_sds_weight:.6f}") + logging.info(f" gradient direction: physics vs Shape = {angle_deg:.1f}° ({direction})") + elif self.latents.grad is not None: + shape_grad_norm = torch.norm(self.latents.grad).item() + logging.info(f" Shapegradient: norm={shape_grad_norm:.4e} (no physics gradient)") + else: + shape_grad_norm = 0.0 + + weighted_sds = weighted_shape_loss.item() + + # ==================== Step 8: combine losses and clip if needed ==================== + compliance_loss_item = compliance_mean + alm_penalty = lagrange * g_pos + 0.5 * rho * (g_pos ** 2) + total_loss = alm_penalty + weighted_sds + + # Log the combined loss terms. + if use_sds_this_step: + logging.info( + f" 📊 weighted loss: Compliance={compliance_loss_item:.4e}, g={g_raw:+.3e}, " + f"ALM={alm_penalty:.4e} (λ={lagrange:.2f}, ρ={rho:.2f}), " + f"Shape={weighted_sds:.4e} (×w={current_sds_weight:.6f}), Total={total_loss:.4e}" + ) + else: + logging.info( + f" 📊 weighted loss: Compliance={compliance_loss_item:.4e}, g={g_raw:+.3e}, " + f"ALM={alm_penalty:.4e} (λ={lagrange:.2f}, ρ={rho:.2f}), " + f"Shape=0.00e+00 (disabled), Total={total_loss:.4e}" + ) + + # Log gradient composition details. + if self.latents.grad is not None: + grad_norm = torch.norm(self.latents.grad).item() + + # Report each gradient contribution. + if phys_grad_unscaled is not None: + weighted_phys_grad_norm = torch.norm(phys_grad_unscaled * alm_scale).item() + logging.info(f" 🔍 gradient composition: Weighted Compliance Grad={weighted_phys_grad_norm:.4e} (ALM scale={alm_scale:.3e})") + + if use_sds_this_step and shape_grad_norm > 0: + logging.info(f" Scaled Shape Grad={shape_grad_norm:.4e} (Shape×w={current_sds_weight:.6f})") + if phys_grad_unscaled is not None: + grad_ratio = shape_grad_norm / (weighted_phys_grad_norm + 1e-10) + logging.info(f" ratio: Shape/Compliance = {grad_ratio:.4f} ({grad_ratio*100:.2f}%)") + + logging.info(f" Total Grad={grad_norm:.4e}") + + # Optional gradient clipping. + if self.latents.grad is not None: + grad_norm = torch.norm(self.latents.grad).item() + + if torch.isnan(self.latents.grad).any() or torch.isinf(self.latents.grad).any(): + logging.error(f"❌ the final gradient contains NaN or Inf!skip this steps") + return (compliance_loss_item, u_mean, shape_loss.item(), total_loss) + + if self.config.grad_clip_enabled: + if grad_norm > max_grad_norm: + clip_factor = max_grad_norm / grad_norm + self.latents.grad = self.latents.grad * clip_factor + logging.info(f" ✂️ gradient clipping: {grad_norm:.4e} -> {max_grad_norm:.1f} (×{clip_factor:.3f})") + else: + logging.info(f" ✅ gradient not clipped: {grad_norm:.4e} (max={max_grad_norm:.1f})") + + # ==================== Step 9: optimizer step ==================== + + # Save the previous latents for diagnostics. + old_latents = self.latents.data.clone() + + self.optimizer.step() + + # Diagnose latent changes after the optimizer step. + with torch.no_grad(): + latents_change = torch.norm(self.latents.data - old_latents).item() + latents_norm = torch.norm(old_latents).item() + latents_change_percent = (latents_change / (latents_norm + 1e-10)) * 100 + max_latents_change = torch.abs(self.latents.data - old_latents).max().item() + + logging.info(f" 🔄 Latentschange: L2={latents_change:.4e} ({latents_change_percent:.3f}%), max={max_latents_change:.4e}") + + if latents_change < 1e-6: + logging.warning(f" ⚠️ latents almost did not change!the learning rate may be too small or the gradient may be too weak") + + # Return the scalar loss values. + return (compliance_loss_item, u_mean, shape_loss.item(), total_loss) + + def save_mesh(self, step: int, output_dir: str = "results/hunyuan_meshes", high_quality: bool = False, suffix="step"): + """Save frontlatentsmesh + + Args: + step: front steps + output_dir: outputdirectory + high_quality: YesNouse (Resolution) , Trueuse256resolution + """ + os.makedirs(output_dir, exist_ok=True) + + try: + # finalSave use256resolution, Stepuse128resolution + octree_res = 256 if high_quality else 128 + mesh = self.latents_to_mesh(self.latents, octree_res=octree_res) + if mesh is None: + logging.warning(f" ⚠️ warning: Step {step} - Marching cubesno surface found, skipSave ") + return + + # finalSave filterfloating + if high_quality: + mesh = self._filter_floating_components(mesh) + + mesh_path = os.path.join(output_dir, f"{suffix}_{step:04d}.obj") + mesh.export(mesh_path) + quality_label = "256resolution" if high_quality else "128resolution" + logging.info(f" 💾 Save mesh ({quality_label}): {mesh_path}") + except Exception as e: + logging.warning(f" ⚠️ warning: Step {step} - Save meshfailed: {e}") + + + def _maybe_save_target_z0_mesh(self, target_z0: torch.Tensor, step_id: int, force: bool = False): + """Save a mesh decoded from target_z0 for diagnostics.""" + if (not force) and (step_id % 10 != 0): + return + + with torch.no_grad(): + deviation = torch.norm(target_z0 - self.latents).item() + latents_norm = torch.norm(self.latents).item() + relative_deviation = deviation / (latents_norm + 1e-8) + + if relative_deviation > 0.5: + logging.warning( + f" ⚠️ target_z0 deviation is too large: {relative_deviation:.1%} " + f"(||target_z0 - latents||={deviation:.3e}, ||latents||={latents_norm:.3e})" + ) + logging.warning(f" thismaySave target meshshape is abnormal") + + try: + target_norm = torch.norm(target_z0).item() + target_max = torch.abs(target_z0).max().item() + target_has_nan = torch.isnan(target_z0).any().item() + target_has_inf = torch.isinf(target_z0).any().item() + + # Save only when target_z0 looks numerically healthy. + if (not target_has_nan and not target_has_inf and + target_max < 100.0 and relative_deviation < 1.0): + target_z0_clean = target_z0.detach().clone() + + logging.info(f" 📊 target_z0 statistics:") + logging.info(f" - shape: {target_z0_clean.shape}") + logging.info(f" - range: [{target_z0_clean.min():.3e}, {target_z0_clean.max():.3e}]") + logging.info(f" - mean: {target_z0_clean.mean():.3e}, Std: {target_z0_clean.std():.3e}") + logging.info(f" - deviation from latents: {relative_deviation:.1%}") + + target_mesh = self.latents_to_mesh(target_z0_clean, octree_res=128) + if target_mesh is not None: + target_mesh_dir = os.path.join( + self.config.out_folder if hasattr(self.config, 'out_folder') + else "results/hunyuan_meshes", + "target_z0_meshes" + ) + os.makedirs(target_mesh_dir, exist_ok=True) + target_mesh_path = os.path.join(target_mesh_dir, f"target_z0_step_{step_id:04d}.obj") + target_mesh.export(target_mesh_path) + logging.info(f" 💾 Save target_z0 mesh (||z||={target_norm:.2e}): {target_mesh_path}") + else: + logging.debug(f" skipSave target_z0: marching cubesno surface found") + else: + logging.warning( + f" ⚠️ skipSave target_z0: containsabnormal values " + f"(nan={target_has_nan}, inf={target_has_inf}, max={target_max:.2e})" + ) + except (ValueError, RuntimeError) as e: + error_msg = str(e) + if "Surface level must be within volume data range" in error_msg or "No surface found" in error_msg: + logging.debug(f" skipSave target_z0: SDFvalueoutside the valid range or has no surface") + else: + logging.warning(f" Save target_z0 meshfailed: {type(e).__name__}: {error_msg[:100]}") + except Exception as e: + logging.warning(f" Save target_z0 meshfailed: {type(e).__name__}: {str(e)[:100]}") + + def save_final_target_z0_mesh(self, step_id: int): + """Force-save a target_z0 mesh at the final step.""" + try: + if self.target_z0_ema is not None: + target_z0 = self.target_z0_ema.detach().clone() + else: + target_z0, _ = self._computation_target_z0_current(step_id) + self._maybe_save_target_z0_mesh(target_z0, step_id, force=True) + except Exception as e: + logging.warning(f" ⚠️ failed to save the final target_z0: {type(e).__name__}: {str(e)[:100]}") + + def save_deformed_mesh(self, step: int, displacement: torch.Tensor, output_dir: str = None, suffix="step"): + """Save FEM solvebackdeformed mesh + + Args: + step: front steps + displacement: FEM solve [num_nodes, 3] + output_dir: outputdirectory, useconfig.out_folder/deformed_meshes + """ + if output_dir is None: + if hasattr(self.config, 'out_folder'): + output_dir = os.path.join(self.config.out_folder, "deformed_meshes") + else: + output_dir = "results/deformed_meshes" + + os.makedirs(output_dir, exist_ok=True) + + try: + # originalnodespositionandbackposition + original_nodes = self.nodes.detach().cpu().numpy() # [num_nodes, 3] + displacement_np = displacement.detach().cpu().numpy() # [num_nodes, 3] + deformed_nodes = original_nodes + displacement_np + + # elements + elements_np = self.elements.detach().cpu().numpy() # [num_elements, 8] + + # # Save VTK format (ParaView, contains) + # vtk_path = os.path.join(output_dir, f"deformed_step_{step:04d}.vtk") + # self._save_hex_mesh_vtk(deformed_nodes, elements_np, displacement_np, vtk_path, step) + + # Save OBJ/PLY (usedecodemesh, ) + decoded_mesh = self.latents_to_mesh(self.latents, octree_res=128) + if decoded_mesh is not None: + disp_vertices = self._sample_displacement_to_vertices( + decoded_mesh.vertices, original_nodes, displacement_np + ) + deformed_vertices = decoded_mesh.vertices + disp_vertices + colors = self._make_displacement_colors(disp_vertices) + + deformed_mesh = trimesh.Trimesh( + vertices=deformed_vertices, + faces=decoded_mesh.faces, + process=False, + ) + deformed_mesh.visual.vertex_colors = colors + + obj_path = os.path.join(output_dir, f"deformed_{suffix}_{step:04d}.obj") + # ply_path = os.path.join(output_dir, f"deformed_step_{step:04d}.ply") + deformed_mesh.export(obj_path) + # deformed_mesh.export(ply_path) + else: + # fallback: usemesh + obj_path = os.path.join(output_dir, f"deformed_{suffix}_{step:04d}.obj") + # ply_path = os.path.join(output_dir, f"deformed_step_{step:04d}.ply") + self._save_surface_mesh_obj(deformed_nodes, elements_np, obj_path) + # self._save_surface_mesh_ply(deformed_nodes, elements_np, displacement_np, ply_path) + + # displacement statistics + disp_mean = np.abs(displacement_np).mean() + disp_max = np.abs(displacement_np).max() + logging.info(f" 💾 saved deformed mesh : OBJ={obj_path.split('/')[-1]}") + logging.debug(f" : mean={disp_mean:.4e}, max={disp_max:.4e}") + + except Exception as e: + logging.warning(f" ⚠️ Save deformed meshfailed (Step {step}): {e}") + + def save_final_deformed_mesh(self, step_id: int, suffix="step"): + """force at the final step toSave deformed mesh (re-solveFEM) """ + if not hasattr(self, 'nodes') or not hasattr(self, 'elements'): + logging.warning(" ⚠️ unable to save the finaldeformed mesh: missingnodes/elements") + return + if not hasattr(self, 'forces') or not hasattr(self, 'boundary_mask'): + logging.warning(" ⚠️ unable to save the finaldeformed mesh: missingforces/boundary_mask") + return + + try: + from torchfem.materials import IsotropicElasticity3D + from physiopt.opt.solid_grid import SolidGrid + from physiopt.opt.field import occ_kernel + + with torch.no_grad(): + # update occupancyalignfrontlatents + sdf = self.get_field(self.nodes) + occ = occ_kernel(sdf, self.config.res, self.config.occ_sdf_beta) + self.coarse_occ = occ[self.elements].mean(1) + + if self.config.alpha_min > 0.0: + self.coarse_occ = torch.clamp(self.coarse_occ, self.config.alpha_min) + + vectorized_material = IsotropicElasticity3D( + E=self.config.youngs_modulus, + nu=self.config.poissons_ratio, + rho=self.config.density, + ).vectorize(self.elements.shape[0]) + + vectorized_material.C *= ( + self.coarse_occ[:, None, None] ** self.config.p_exponent + ) + + solid = SolidGrid(self.nodes, self.elements, vectorized_material) + solid.constraints[self.boundary_mask, :] = True + solid.forces = self.forces + + logging.info(" 🧱 final deformed mesh: re-solve the FEM system to save ") + u, _, _, _, _, _ = solid.solve(max_iter=1) + self.save_deformed_mesh(step_id, u, suffix=suffix) + except Exception as e: + logging.warning(f" ⚠️ final deformed meshSave failed: {type(e).__name__}: {str(e)[:100]}") + + def _save_surface_mesh_obj(self, nodes: np.ndarray, elements: np.ndarray, filename: str): + """Extract the surface from a hexahedral mesh and save it as OBJ.""" + # The six faces of a hexahedron. + hex_faces = [ + [0, 1, 2, 3], [4, 5, 6, 7], # Bottom, top. + [0, 1, 5, 4], [2, 3, 7, 6], # Front, back. + [0, 3, 7, 4], [1, 2, 6, 5], # Left, right. + ] + + # Collect faces that appear only once, i.e. surface faces. + face_count = {} + for elem in elements: + for face_indices in hex_faces: + face_nodes = tuple(sorted([elem[i] for i in face_indices])) + if face_nodes in face_count: + face_count[face_nodes] += 1 + else: + face_count[face_nodes] = 1 + + # Keep only surface faces. + surface_faces = [face for face, count in face_count.items() if count == 1] + + # Save OBJ. + with open(filename, 'w') as f: + f.write("# Deformed mesh surface\n") + for node in nodes: + f.write(f"v {node[0]:.6f} {node[1]:.6f} {node[2]:.6f}\n") + for face in surface_faces: + # OBJ indices are 1-based. + f.write(f"f {face[0]+1} {face[1]+1} {face[2]+1} {face[3]+1}\n") + + def _save_force_visualization(self, seat_nodes_mask: torch.Tensor, total_force: np.ndarray): + """Save voxel-level load data for visualization and validation. + + This exports: + 1. NumPy (.npz) with full node/load data + 2. OBJ point clouds for quick inspection + 3. Optional VTK data for ParaView + + Args: + seat_nodes_mask: Mask of seat/contact nodes [num_nodes]. + total_force: Total force vector [3]. + """ + if not hasattr(self.config, 'out_folder'): + logging.warning(" out_folder is not set, skipSave loaded voxel") + return + + # Create the force_visualization subdirectory. + vis_dir = os.path.join(self.config.out_folder, "force_visualization") + os.makedirs(vis_dir, exist_ok=True) + + # ==================== 1. Save NumPy data (most complete format) ==================== + all_nodes_cpu = self.nodes.cpu().numpy() + all_forces_cpu = self.forces.cpu().numpy() + seat_mask_cpu = seat_nodes_mask.cpu().numpy() + + # Extract loaded nodes. + seat_nodes = all_nodes_cpu[seat_mask_cpu] + seat_forces = all_forces_cpu[seat_mask_cpu] + + npz_path = os.path.join(vis_dir, "force_nodes.npz") + np.savez( + npz_path, + # All node data. + all_nodes=all_nodes_cpu, + all_forces=all_forces_cpu, + # Loaded-node data. + seat_nodes=seat_nodes, + seat_forces=seat_forces, + seat_mask=seat_mask_cpu, + # Boundary-node data. + boundary_mask=self.boundary_mask.cpu().numpy() if hasattr(self, 'boundary_mask') else None, + # Metadata. + total_force=total_force, + num_seat_nodes=len(seat_nodes), + num_all_nodes=len(all_nodes_cpu), + ) + logging.info(f" 💾 Save load data (NumPy format) : {npz_path}") + + # ==================== 2. Save OBJ point clouds ==================== + # 2a. Loaded nodes (red point cloud). + seat_obj_path = os.path.join(vis_dir, "seat_nodes.obj") + with open(seat_obj_path, 'w') as f: + f.write("# Seat nodes (loaded area)\n") + f.write(f"# Total: {len(seat_nodes)} nodes\n") + f.write(f"# Force per node: {seat_forces[0] if len(seat_forces) > 0 else [0,0,0]}\n") + for node in seat_nodes: + f.write(f"v {node[0]:.6f} {node[1]:.6f} {node[2]:.6f}\n") + logging.info(f" 💾 Save seat nodes (OBJpoint cloud) : {seat_obj_path}") + + # 2b. Boundary nodes (blue point cloud). + if hasattr(self, 'boundary_mask'): + boundary_nodes = all_nodes_cpu[self.boundary_mask.cpu().numpy()] + boundary_obj_path = os.path.join(vis_dir, "boundary_nodes.obj") + with open(boundary_obj_path, 'w') as f: + f.write("# Boundary nodes (fixed area)\n") + f.write(f"# Total: {len(boundary_nodes)} nodes\n") + for node in boundary_nodes: + f.write(f"v {node[0]:.6f} {node[1]:.6f} {node[2]:.6f}\n") + logging.info(f" 💾 Save boundary nodes (OBJpoint cloud) : {boundary_obj_path}") + + # 2c. All nodes (gray point cloud) for comparison. + all_obj_path = os.path.join(vis_dir, "all_nodes.obj") + with open(all_obj_path, 'w') as f: + f.write("# All nodes\n") + f.write(f"# Total: {len(all_nodes_cpu)} nodes\n") + for node in all_nodes_cpu: + f.write(f"v {node[0]:.6f} {node[1]:.6f} {node[2]:.6f}\n") + logging.info(f" 💾 Save all nodes (OBJpoint cloud) : {all_obj_path}") + + # ==================== 3. Save VTK data for ParaView ==================== + try: + vtk_path = os.path.join(vis_dir, "force_field.vtk") + with open(vtk_path, 'w') as f: + # VTK Header + f.write("# vtk DataFile Version 3.0\n") + f.write("Force field visualization\n") + f.write("ASCII\n") + f.write("DATASET UNSTRUCTURED_GRID\n") + + # Points + f.write(f"POINTS {len(all_nodes_cpu)} float\n") + for node in all_nodes_cpu: + f.write(f"{node[0]:.6f} {node[1]:.6f} {node[2]:.6f}\n") + + # Cells (vertices) + f.write(f"\nCELLS {len(all_nodes_cpu)} {len(all_nodes_cpu)*2}\n") + for i in range(len(all_nodes_cpu)): + f.write(f"1 {i}\n") + + # Cell types (1 = vertex) + f.write(f"\nCELL_TYPES {len(all_nodes_cpu)}\n") + for _ in range(len(all_nodes_cpu)): + f.write("1\n") + + # Point data (force vectors) + f.write(f"\nPOINT_DATA {len(all_nodes_cpu)}\n") + f.write("VECTORS force float\n") + for force in all_forces_cpu: + f.write(f"{force[0]:.6e} {force[1]:.6e} {force[2]:.6e}\n") + + # Scalar field: force magnitude + f.write("\nSCALARS force_magnitude float 1\n") + f.write("LOOKUP_TABLE default\n") + for force in all_forces_cpu: + mag = np.linalg.norm(force) + f.write(f"{mag:.6e}\n") + + # Scalar field: is_seat (0 or 1) + f.write("\nSCALARS is_seat int 1\n") + f.write("LOOKUP_TABLE default\n") + for is_seat in seat_mask_cpu: + f.write(f"{int(is_seat)}\n") + + logging.info(f" 💾 Save force field (VTK format, ParaView) : {vtk_path}") + except Exception as e: + logging.warning(f" ⚠️ Save VTK formatfailed: {e}") + + # ==================== 4. Generate a Python visualization script ==================== + vis_script_path = os.path.join(vis_dir, "visualize_forces.py") + with open(vis_script_path, 'w') as f: + f.write("""#!/usr/bin/env python3 +\"""Visualize voxel load data + +Usage: + python visualize_forces.py + +Requirements: + pip install numpy matplotlib + +\""" +import numpy as np +import matplotlib.pyplot as plt +from mpl_toolkits.mplot3d import Axes3D + +# Load data. +data = np.load('force_nodes.npz') +all_nodes = data['all_nodes'] +seat_nodes = data['seat_nodes'] +seat_forces = data['seat_forces'] +total_force = data['total_force'] + +# Create the 3D figure. +fig = plt.figure(figsize=(15, 5)) + +# Subplot 1: all nodes (gray) + loaded nodes (red). +ax1 = fig.add_subplot(131, projection='3d') +ax1.scatter(all_nodes[:, 0], all_nodes[:, 1], all_nodes[:, 2], + c='lightgray', s=0.5, alpha=0.3, label='All nodes') +ax1.scatter(seat_nodes[:, 0], seat_nodes[:, 1], seat_nodes[:, 2], + c='red', s=5, alpha=1.0, label='Seat nodes (loaded)') +ax1.set_xlabel('X') +ax1.set_ylabel('Y (up)') +ax1.set_zlabel('Z') +ax1.set_title(f'Loaded Nodes\\n({len(seat_nodes)}/{len(all_nodes)} nodes)') +ax1.legend() + +# Subplot 2: Y distribution of loaded nodes. +ax2 = fig.add_subplot(132) +y_coords = seat_nodes[:, 1] +ax2.hist(y_coords, bins=30, color='red', alpha=0.7, edgecolor='black') +ax2.axvline(y_coords.min(), color='blue', linestyle='--', label=f'Y_min={y_coords.min():.3f}') +ax2.axvline(y_coords.max(), color='green', linestyle='--', label=f'Y_max={y_coords.max():.3f}') +ax2.set_xlabel('Y coordinate (height)') +ax2.set_ylabel('Number of nodes') +ax2.set_title('Seat Node Y Distribution') +ax2.legend() +ax2.grid(True, alpha=0.3) + +# Subplot 3: XZ force-vector layout in top view. +ax3 = fig.add_subplot(133) +ax3.scatter(seat_nodes[:, 0], seat_nodes[:, 2], c='red', s=10, alpha=0.5) +# Draw a sparse subset of force vectors to avoid clutter. +step = max(1, len(seat_nodes) // 50) +for i in range(0, len(seat_nodes), step): + node = seat_nodes[i] + force = seat_forces[i] + # Scale force vectors for visualization. + scale = 0.01 + ax3.arrow(node[0], node[2], force[0]*scale, force[2]*scale, + head_width=0.02, head_length=0.01, fc='blue', ec='blue', alpha=0.7) +ax3.set_xlabel('X') +ax3.set_ylabel('Z') +ax3.set_title(f'Top View (XZ plane)\\nForce: {total_force}') +ax3.axis('equal') +ax3.grid(True, alpha=0.3) + +plt.tight_layout() +plt.savefig('force_visualization.png', dpi=150, bbox_inches='tight') +logging.info("✅ image saved : force_visualization.png") +plt.show() + +# Print summary statistics. +logging.info("\\n" + "="*60) +logging.info("force voxel statistics") +logging.info("="*60) +logging.info(f"total node count: {len(all_nodes)}") +logging.info(f"loaded node count: {len(seat_nodes)} ({len(seat_nodes)/len(all_nodes)*100:.1f}%)") +logging.info(f"total: {total_force}") +logging.info(f"per nodeaverage force per node: {seat_forces.mean(axis=0)}") +logging.info(f"\\nY-coordinate range:") +logging.info(f" - min: {y_coords.min():.3f}") +logging.info(f" - max: {y_coords.max():.3f}") +logging.info(f" - mean: {y_coords.mean():.3f}") +logging.info(f" - height span: {y_coords.max() - y_coords.min():.3f}") +logging.info("="*60) +""") + os.chmod(vis_script_path, 0o755) # Add execute permission. + logging.info(f" 💾 Save visualization script: {vis_script_path}") + + # ==================== 5. Generate a README document ==================== + readme_path = os.path.join(vis_dir, "README.md") + with open(readme_path, 'w') as f: + f.write(f"""# Load Voxel Visualization Data + +Generated at: {np.datetime64('now')} + +## Statistics + +- **Total nodes**: {len(all_nodes_cpu)} +- **Loaded nodes**: {len(seat_nodes)} ({len(seat_nodes)/len(all_nodes_cpu)*100:.1f}%) +- **Total force**: {total_force} +- **Force per node**: {seat_forces[0] if len(seat_forces) > 0 else [0,0,0]} + +## Files + +### 1. NumPy format (recommended for analysis) + +- `force_nodes.npz`: contains the full dataset + - `all_nodes`: coordinates of all nodes [{len(all_nodes_cpu)}, 3] + - `all_forces`: force vectors on all nodes [{len(all_nodes_cpu)}, 3] + - `seat_nodes`: coordinates of loaded nodes [{len(seat_nodes)}, 3] + - `seat_forces`: force vectors on loaded nodes [{len(seat_nodes)}, 3] + - `seat_mask`: mask of loaded nodes [{len(all_nodes_cpu)}] + - `boundary_mask`: mask of boundary nodes [{len(all_nodes_cpu)}] + +**Example**: +```python +import numpy as np +data = np.load('force_nodes.npz') +seat_nodes = data['seat_nodes'] +print(f"Loaded nodes: {{len(seat_nodes)}}") +``` + +### 2. OBJ format (recommended for quick inspection) + +- `seat_nodes.obj`: loaded nodes (red point cloud) +- `boundary_nodes.obj`: boundary nodes (blue point cloud) +- `all_nodes.obj`: all nodes (gray point cloud) + +**Usage**: +1. Open in Meshlab: `meshlab seat_nodes.obj` +2. Or import the OBJ files into Blender +3. You can load multiple OBJ files together for comparison + +### 3. VTK format (recommended for professional visualization) + +- `force_field.vtk`: force-field data with vector information + +**Usage**: +1. Open in ParaView: `paraview force_field.vtk` +2. In ParaView: + - Use `Glyph` to visualize force vectors + - Color by `force_magnitude` to inspect strength + - Filter by `is_seat` to isolate the loaded region + +### 4. Visualization script + +- `visualize_forces.py`: Python visualization script + +**Usage**: +```bash +python visualize_forces.py +``` +""") + logging.info(f" 💾 Save README document: {readme_path}") + + # Print a short summary. + logging.info(f" ✅ force voxel data saved successfully!") + logging.info(f" - view directory: {vis_dir}") + logging.info(f" - quick visualization: cd {vis_dir} && python visualize_forces.py") + logging.info(f" - view in Meshlab: meshlab {os.path.join(vis_dir, 'seat_nodes.obj')}") + + +def load_hunyuan_models(model_path: str = "tencent/Hunyuan3D-2.1", + subfolder: str = "hunyuan3d-shapegen", + use_safetensors: bool = True): + """Load the Hunyuan3D models (VAE, Flow Model, and Scheduler). + + Args: + model_path: Model path, either a Hugging Face ID or a local directory. + subfolder: Model subfolder name. + use_safetensors: Whether to load safetensors checkpoints. + + Returns: + (vae, flow_model, scheduler): the VAE, Flow Matching model, and scheduler. + """ + logging.info(f"🔧 loading Hunyuan3D-2.1model...") + logging.info(f" modelpath: {model_path}") + logging.info(f" subfolder: {subfolder}") + logging.info(f" modelformat: {'safetensors' if use_safetensors else 'checkpoint'}") + + try: + pipeline = Hunyuan3DDiTFlowMatchingPipeline.from_pretrained( + model_path, + subfolder=subfolder, + torch_dtype=torch.float16, + use_safetensors=use_safetensors + ) + + if pipeline is None: + raise ValueError("pipeline loading failed and returned None") + + logging.info(" ✅ pipeline loaded successfully") + + pipeline.to('cuda') + logging.info(" ✅ modelmoved to CUDA (dtype: fp16)") + + vae = pipeline.vae + flow_model = pipeline.model + scheduler = pipeline.scheduler + + return vae, flow_model, scheduler + + except Exception as e: + logging.error(f"\n❌ modelloadfailed: {e}") + logging.error(f"\nPossible fixes:") + logging.error(f"1. make sure Hunyuan3D is installed-2.1: cd Hunyuan3D-2.1 && pip install -e .") + logging.error(f"2. check network connectivity to huggingface.co") + logging.error(f"3. or download manually: git clone https://huggingface.co/tencent/Hunyuan3D-2") + import traceback + traceback.print_exc() + sys.exit(1) + + +def plot_history(history: dict, save_dir: str, filename: str = "optimization_metrics.png"): + + epochs = list(range(1, len(history["compliance"]) + 1)) + + # 2. Create the figure with a 2x2 grid + fig, axs = plt.subplots(2, 2, figsize=(14, 10)) + fig.suptitle("Optimization Metrics Evolution", fontsize=16, fontweight='bold') + + # --- Plot 1: Compliance --- + axs[0, 0].plot(epochs, history["compliance"], marker='o', color='#1f77b4', linewidth=2) + axs[0, 0].set_title("Compliance (Strain Energy)") + axs[0, 0].set_xlabel("Epoch") + axs[0, 0].grid(True, linestyle='--', alpha=0.7) + + # --- Plot 2: u_mean --- + axs[0, 1].plot(epochs, history["u_mean"], marker='s', color='#2ca02c', linewidth=2) + axs[0, 1].set_title("Mean Displacement (|u|_mean)") + axs[0, 1].set_xlabel("Epoch") + axs[0, 1].grid(True, linestyle='--', alpha=0.7) + + # --- Plot 3: c_relative_decrease --- + axs[1, 0].plot(epochs, history["c_relative_decrease"], marker='^', color='#d62728', linewidth=2) + axs[1, 0].set_title("Relative Compliance Decrease") + axs[1, 0].set_xlabel("Epoch") + axs[1, 0].grid(True, linestyle='--', alpha=0.7) + + # --- Plot 4: u_relative_decrease --- + axs[1, 1].plot(epochs, history["u_relative_decrease"], marker='v', color='#9467bd', linewidth=2) + axs[1, 1].set_title("Relative Displacement Decrease") + axs[1, 1].set_xlabel("Epoch") + axs[1, 1].grid(True, linestyle='--', alpha=0.7) + + # 3. Adjust layout to prevent text from overlapping + plt.tight_layout() + fig.subplots_adjust(top=0.92) # Leave space for the main super-title + + # 4. Save the figure + os.makedirs(save_dir, exist_ok=True) + full_path = os.path.join(save_dir, filename) + + plt.savefig(full_path, dpi=300, bbox_inches='tight') + plt.close(fig) + + logging.info(f" 📊 Plot successfully saved to: {full_path}") + + +def main(): + """Parse CLI arguments and run the optimization.""" + import argparse + + parser = argparse.ArgumentParser(description="Hunyuan3D physics optimization + shape-prior optimization") + + # Required arguments. + parser.add_argument("--latents", type=str, required=True, + help="Input latents file path (.pt)") + parser.add_argument("--out_folder", type=str, default="../out/hunyuan_opt", + help="Output folder path") + parser.add_argument("--not_use_threshold", action="store_true") + + # Model arguments. + parser.add_argument("--model_path", type=str, default="tencent/Hunyuan3D-2.1", + help="Model path (using v2.1)") + parser.add_argument("--subfolder", type=str, default="hunyuan3d-dit-v2-1", + help="Model subfolder") + parser.add_argument("--use_safetensors", action="store_true", + help="Use safetensors format (default: ckpt)") + + # Physical-simulation arguments. + parser.add_argument("--use_physics", action="store_true", + help="Enable physics-constrained optimization") + parser.add_argument("--res", type=int, default=16, + help="Voxel resolution (16/32/64)") + parser.add_argument("--youngs_modulus_scale", type=float, default=2.0, + help="Final Young's modulus multiplier (default 2x after the last projection)") + parser.add_argument("--compliance_threshold", type=float, default=None, + help="Target compliance threshold (None = automatic)") + parser.add_argument("--compliance_threshold_ratio", type=float, default=0.3, + help="Automatic threshold ratio (threshold = initial value × ratio)") + + # Optimization arguments. + parser.add_argument("--num_steps", type=int, default=300, + help="Number of optimization steps (pure SDS only; in physics mode it becomes outer_cycles * phys_steps_per_cycle automatically)") + parser.add_argument("--outer_cycles", type=int, default=100, + help="Number of outer cycles (each cycle = physics optimization + projection)") + parser.add_argument("--phys_steps_per_cycle", type=int, default=5, + help="Number of physics-optimization steps per outer cycle") + parser.add_argument("--lr", type=float, default=5e-3, + help="Learning rate (increase to 0.005 to help the mesh thicken faster) ") + parser.add_argument("--lagrange_max", type=float, default=10.0, + help="Maximum Lagrange multiplier (recommended: 5-20)") + parser.add_argument("--alm_rho_init", type=float, default=1.0, + help="ALM rhoinitial value") + parser.add_argument("--alm_rho_max", type=float, default=1000.0, + help="ALM rhoMax") + parser.add_argument("--alm_rho_increase_factor", type=float, default=2.0, + help="ALM rhogrowth factor") + parser.add_argument("--alm_rho_increase_patience", type=int, default=5, + help="ALM rhonumber of consecutive violation steps required before increasing") + parser.add_argument("--alm_scale_guard_ratio", type=float, default=0.95, + help="ALMscaling guard ratio(<=1), control the upper bound of the physics-gradient target=this ratio x clipping-threshold value") + parser.add_argument("--grad_clip_enabled", action="store_true", + help="Enable gradient clipping (disabled by default; otherwise only NaN/Inf checks are kept)") + parser.add_argument("--use_sgd", action="store_true", + help="Use SGD instead of Adam") + parser.add_argument("--force_config", type=str, default=None, + help="Path to the external-force JSON config (generated by the web UI)") + parser.add_argument("--force", type=float, nargs=3, action="append", default=None, + help="External force vector [fx fy fz] (N, Y-up coordinates; can be specified multiple times)") + parser.add_argument("--global_loading", action="store_true", + help="Use global uniform loading (disable local loading)") + parser.add_argument("--force_region_mode", type=str, default="top_percent", + choices=["top_percent", "height_ratio", "bbox"], + help="How to choose the local loading region") + parser.add_argument("--force_top_percent", type=float, default=0.05, + help="top_percent mode: select the highest-Y fraction") + parser.add_argument("--force_bbox", type=float, nargs=6, default=None, + help="bbox mode: x_min x_max y_min y_max z_min z_max (absolute coordinates)") + parser.add_argument("--force_bbox_ratio", type=float, nargs=6, default=None, + help="bbox mode (0-1): bbox relative to the node bounds") + parser.add_argument("--seat_height_min_ratio", type=float, default=0.3, + help="height_ratio mode: lower seat boundary (0-1)") + parser.add_argument("--seat_height_max_ratio", type=float, default=0.5, + help="height_ratio mode: upper seat boundary (0-1)") + + # SDS arguments. + parser.add_argument("--sds_weight", type=float, default=1.0, + help="SDS gradient weight (deprecated; use sds_weight_start and sds_weight_end instead)") + parser.add_argument("--sds_weight_start", type=float, default=10.0, + help="Initial SDS weight (linearly increased; 0.0001 is recommended to avoid disturbing physics optimization)") + parser.add_argument("--sds_weight_end", type=float, default=10.0, + help="Final SDS weight (linearly increased; 0.001 is recommended, about 1/10 of the physics gradient)") + parser.add_argument("--sds_timestep", type=float, default=0.1, + help="SDS timestep (recommended: 0.05-0.2)") + parser.add_argument("--sds_target_z0_ema_beta", type=float, default=0.9, + help="target_z0 EMA smoothing factor (larger means smoother)") + parser.add_argument("--deformed_mesh_interval", type=int, default=10, + help="Interval for saving deformed meshes (steps)") + parser.add_argument("--deformed_mesh_disp_min", type=float, default=0.0, + help="Minimum displacement for deformed-mesh color mapping (default 0.0)") + parser.add_argument("--deformed_mesh_disp_max", type=float, default=0.2, + help="Maximum displacement for deformed-mesh color mapping (<=0 enables per-step auto scaling)") + parser.add_argument("--guidance_scale", type=float, default=7.5, + help="CFG guidance scale (standard value: 7.5; larger means stronger image conditioning)") + parser.add_argument("--sds_projection_max_rel", type=float, default=0.0, + help="Maximum relative target_z0 projection deviation (0 = unlimited)") + parser.add_argument("--sds_use_uncond", action="store_true", + help="Use the unconditional branch (only takes effect when guidance_scale <= 1)") + + # Topology control. + parser.add_argument("--keep_all_components", action="store_true", + help="Keep all connected components (to avoid disappearing chair legs)") + parser.add_argument("--re_extract_interval", type=int, default=1, + help="Solid re-extraction interval (0 = disabled)") + + args = parser.parse_args() + + def _normalize_force_vectors(value): + if value is None: + return None + if isinstance(value, (list, tuple)) and len(value) > 0: + if isinstance(value[0], (list, tuple)): + candidates = value + else: + candidates = [value] + else: + return None + normalized = [] + for vec in candidates: + if not isinstance(vec, (list, tuple)) or len(vec) != 3: + continue + try: + normalized.append([float(v) for v in vec]) + except Exception: + continue + return normalized if normalized else None + + def _normalize_force_entry(entry): + if not isinstance(entry, dict): + return None + forces = _normalize_force_vectors(entry.get("forces")) + if forces is None: + forces = _normalize_force_vectors(entry.get("force")) + if forces is None: + return None + out = dict(entry) + if len(forces) > 1: + out["forces"] = forces + out["force"] = [float(sum(v[i] for v in forces)) for i in range(3)] + else: + out["force"] = forces[0] + out.pop("forces", None) + if "force_region_mode" in out: + out["force_region_mode"] = str(out["force_region_mode"]) + if "global_loading" in out: + out["global_loading"] = bool(out["global_loading"]) + if "force_top_percent" in out: + out["force_top_percent"] = float(out["force_top_percent"]) + if "seat_height_min_ratio" in out: + out["seat_height_min_ratio"] = float(out["seat_height_min_ratio"]) + if "seat_height_max_ratio" in out: + out["seat_height_max_ratio"] = float(out["seat_height_max_ratio"]) + if "force_bbox" in out and isinstance(out["force_bbox"], (list, tuple)) and len(out["force_bbox"]) == 6: + out["force_bbox"] = [float(v) for v in out["force_bbox"]] + elif "force_bbox" in out: + out.pop("force_bbox", None) + if "force_bbox_ratio" in out and isinstance(out["force_bbox_ratio"], (list, tuple)) and len(out["force_bbox_ratio"]) == 6: + out["force_bbox_ratio"] = [float(v) for v in out["force_bbox_ratio"]] + elif "force_bbox_ratio" in out: + out.pop("force_bbox_ratio", None) + return out + + # Load force configuration from JSON, typically exported from the web UI. + force_config_loaded = False + force_config_error = None + force_entries = None + if args.force_config: + raw_force_config = args.force_config + candidates = [] + if os.path.isabs(raw_force_config): + candidates.append(raw_force_config) + else: + candidates.append(raw_force_config) + script_dir = os.path.dirname(os.path.abspath(__file__)) + candidates.append(os.path.join(script_dir, raw_force_config)) + candidates.append(os.path.join(os.path.dirname(script_dir), raw_force_config)) + force_config_path = next((p for p in candidates if os.path.exists(p)), None) + if force_config_path is None: + force_config_error = f"Path does not exist; tried: {candidates}" + else: + args.force_config = force_config_path + try: + with open(force_config_path, "r") as f: + force_cfg = json.load(f) + if isinstance(force_cfg, dict): + cfg_forces = _normalize_force_vectors(force_cfg.get("forces")) + if cfg_forces is not None: + args.force = cfg_forces + else: + cfg_force = _normalize_force_vectors(force_cfg.get("force")) + if cfg_force is not None: + args.force = cfg_force + elif "force" in force_cfg or "forces" in force_cfg: + force_config_error = "force/forcesinvalid format" + if "global_loading" in force_cfg: + args.global_loading = bool(force_cfg["global_loading"]) + if "force_region_mode" in force_cfg: + args.force_region_mode = str(force_cfg["force_region_mode"]) + if "force_top_percent" in force_cfg: + args.force_top_percent = float(force_cfg["force_top_percent"]) + if "seat_height_min_ratio" in force_cfg: + args.seat_height_min_ratio = float(force_cfg["seat_height_min_ratio"]) + if "seat_height_max_ratio" in force_cfg: + args.seat_height_max_ratio = float(force_cfg["seat_height_max_ratio"]) + if "force_bbox" in force_cfg: + args.force_bbox = force_cfg["force_bbox"] + if "force_bbox_ratio" in force_cfg: + args.force_bbox_ratio = force_cfg["force_bbox_ratio"] + if "force_entries" in force_cfg: + raw_entries = force_cfg["force_entries"] + if isinstance(raw_entries, list): + normalized_entries = [] + for entry in raw_entries: + norm_entry = _normalize_force_entry(entry) + if norm_entry is not None: + normalized_entries.append(norm_entry) + if normalized_entries: + force_entries = normalized_entries + else: + force_config_error = "force_entries has no valid entries" + else: + force_config_error = "force_entriesinvalid format" + force_config_loaded = True + else: + force_config_error = f"force_configis not a dict: {type(force_cfg)}" + except Exception as e: + force_config_error = f"read failed: {e}" + + # Configure logging. force=True ensures this replaces any prior setup. + os.makedirs(args.out_folder, exist_ok=True) + log_file = os.path.join(args.out_folder, "optimization.log") + + # Remove any existing handlers. + for handler in logging.root.handlers[:]: + logging.root.removeHandler(handler) + + # Reconfigure logging. + logging.basicConfig( + level=logging.INFO, + format='%(asctime)s - %(levelname)s - %(message)s', + handlers=[ + logging.FileHandler(log_file, mode='w'), # Rewrite the log on each run. + logging.StreamHandler() + ], + force=True # Python 3.8+: force a full reconfiguration. + ) + + logging.info(f"🔧 logging configuration completed") + logging.info(f" - log file: {log_file}") + logging.info(f" - output mode: file + console") + if args.force_config: + if force_config_loaded: + logging.info(" ✅ force_configloaded") + logging.info(f" - path: {args.force_config}") + logging.info(f" - forces: {args.force}") + if force_entries: + logging.info(f" - force_entries: {len(force_entries)}") + logging.info(f" - global_loading: {args.global_loading}") + logging.info(f" - force_region_mode: {args.force_region_mode}") + logging.info(f" - force_top_percent: {args.force_top_percent}") + logging.info(f" - seat_height_min_ratio: {args.seat_height_min_ratio}") + logging.info(f" - seat_height_max_ratio: {args.seat_height_max_ratio}") + logging.info(f" - force_bbox: {args.force_bbox}") + logging.info(f" - force_bbox_ratio: {args.force_bbox_ratio}") + if force_config_error: + logging.warning(f" ⚠️ force_configsome fields are invalid: {force_config_error}") + else: + logging.warning(f" ⚠️ force_configloadfailed: {force_config_error}") + + # In physics mode, derive num_steps from outer_cycles and phys_steps_per_cycle. + if args.use_physics: + outer_cycles = max(1, int(args.outer_cycles)) + phys_steps_per_cycle = max(1, int(args.phys_steps_per_cycle)) + derived_num_steps = outer_cycles * phys_steps_per_cycle + if args.num_steps != derived_num_steps: + logging.info( + f" - num_stepsautomatically set: {args.num_steps} → {derived_num_steps} " + f"(outer_cycles={outer_cycles}, phys_steps_per_cycle={phys_steps_per_cycle})" + ) + args.num_steps = derived_num_steps + + # ==================== Save run metadata ==================== + # 1. Save the command line. + command_file = os.path.join(args.out_folder, "run_command.txt") + try: + with open(command_file, 'w') as f: + f.write("=" * 80 + "\n") + f.write("Command used (Command Used)\n") + f.write("=" * 80 + "\n\n") + f.write("Full command:\n") + f.write("python " + " ".join(sys.argv) + "\n\n") + + f.write("=" * 80 + "\n") + f.write("Arguments (Arguments)\n") + f.write("=" * 80 + "\n\n") + for arg, value in vars(args).items(): + f.write(f"{arg}: {value}\n") + + f.write("\n" + "=" * 80 + "\n") + f.write("Environment (Environment)\n") + f.write("=" * 80 + "\n\n") + f.write(f"Python: {sys.version}\n") + f.write(f"PyTorch: {torch.__version__}\n") + f.write(f"CUDA Available: {torch.cuda.is_available()}\n") + if torch.cuda.is_available(): + f.write(f"CUDA Version: {torch.version.cuda}\n") + f.write(f"GPU Count: {torch.cuda.device_count()}\n") + + logging.info(f" - saved command used : {command_file}") + except Exception as e: + logging.warning(f" ⚠️ Save Command usedfailed: {e}") + + # 2. Save a copy of the current script. + script_backup = os.path.join(args.out_folder, "viewer_hunyuan_web_alternate.py") + try: + current_script = os.path.abspath(__file__) + shutil.copy2(current_script, script_backup) + logging.info(f" - saved script copy : {script_backup}") + except Exception as e: + logging.warning(f" ⚠️ Save failed to save script copy: {e}") + + # Load latents and conditioning data. + logging.info(f"\n📂 loading input data...") + logging.info(f" - Latents: {args.latents}") + + data = torch.load(args.latents, map_location='cpu') + + # Extract latents. + if isinstance(data, dict) and 'latents' in data: + latents = data['latents'] + else: + latents = data + + logging.info(f" ✅ Latents shape: {latents.shape}") + + # Check conditioning data (image_embeds or image). + need_encode_cond = False + image_embeds = None + image = None + + if isinstance(data, dict): + if 'image' in data: + # New format: only the image was saved, so we need to re-encode it. + logging.info(f" - detected image data; re-encoding as conditional embeds") + image_array = data['image'] + image = Image.fromarray(image_array) + need_encode_cond = True + elif 'image_embeds' in data: + # Legacy format: embeddings are already saved. + logging.info(f" - using the saved conditional embeds") + image_embeds = data['image_embeds'] + need_encode_cond = False + elif 'cond' in data: + # Alternate format using a saved cond dict. + logging.info(f" - using the saved cond") + image_embeds = data['cond'] + need_encode_cond = False + else: + raise ValueError("latents.ptis missingimage, image_embedsor cond data") + else: + raise ValueError("latentsmust be a dictionary containing'latents'andconditioninformation dict") + + if image_embeds is not None: + if isinstance(image_embeds, dict): + logging.info(f" ✅ Cond keys: {list(image_embeds.keys())}") + else: + logging.info(f" ✅ Image embeds shape: {image_embeds.shape}") + + # Load models. + logging.info(f"\n🔧 loading Hunyuan3Dmodel...") + vae, flow_model, scheduler = load_hunyuan_models( + model_path=args.model_path, + subfolder=args.subfolder, + use_safetensors=args.use_safetensors + ) + + # ==================== Encode conditioning data if needed ==================== + if need_encode_cond: + logging.info("🎨 encoding conditional embeds from the image...") + + # Reload the full pipeline for condition encoding. + from hy3dgen.shapegen import Hunyuan3DDiTFlowMatchingPipeline + + pipeline = Hunyuan3DDiTFlowMatchingPipeline.from_pretrained( + args.model_path, + subfolder=args.subfolder, + torch_dtype=torch.float16, + use_safetensors=args.use_safetensors + ) + pipeline.to('cuda') + + with torch.no_grad(): + # Prepare the image. + cond_inputs = pipeline.prepare_image(image) + image_tensor = cond_inputs.pop('image') + + # Enable CFG so the encoded condition contains both branches. + cond_dict = pipeline.encode_cond( + image=image_tensor, + additional_cond_inputs=cond_inputs, + do_classifier_free_guidance=True, # Enable CFG. + dual_guidance=False, + ) + + # Save the condition dict. + image_embeds = cond_dict + + logging.info(f" ✅ condition encoding completed (CFG mode) ") + logging.info(f" - Cond keys: {list(cond_dict.keys()) if isinstance(cond_dict, dict) else 'tensor'}") + + # Resolve the compliance threshold. + if args.compliance_threshold is None: + compliance_threshold = 200.0 + logging.info(f" using the default compliance threshold: {compliance_threshold}") + else: + compliance_threshold = args.compliance_threshold + logging.info(f" using the custom compliance threshold: {compliance_threshold}") + + target_z0_update_interval = max(1, int(args.phys_steps_per_cycle)) + forces = None + normalized_forces = _normalize_force_vectors(args.force) + if normalized_forces: + forces = [{'external_force': vec} for vec in normalized_forces] + elif args.force is not None: + logging.warning(f" ⚠️ invalid external force vector; ignoring: {args.force}") + # Build the optimization config. + config = OptimizationConfig( + num_steps=args.num_steps, + lr=args.lr, + sds_timestep=args.sds_timestep, + sds_weight=args.sds_weight if args.use_physics else 1.0, # Keep backward compatibility. + sds_weight_start=args.sds_weight_start, # Dynamic weight schedule start. + sds_weight_end=args.sds_weight_end, # Dynamic weight schedule end. + guidance_scale=args.guidance_scale, # CFG guidance scale. + sds_projection_max_rel=args.sds_projection_max_rel, + sds_use_uncond=args.sds_use_uncond, + sds_target_z0_update_interval=target_z0_update_interval, + sds_target_z0_ema_beta=args.sds_target_z0_ema_beta, + deformed_mesh_interval=args.deformed_mesh_interval, + deformed_mesh_disp_min=args.deformed_mesh_disp_min, + deformed_mesh_disp_max=args.deformed_mesh_disp_max, + use_sgd=args.use_sgd, + grad_clip_enabled=args.grad_clip_enabled, + # Physical parameters. + res=args.res, + lagrange_max=args.lagrange_max, + compliance_threshold=compliance_threshold, + alm_rho_init=args.alm_rho_init, + alm_rho_max=args.alm_rho_max, + alm_rho_increase_factor=args.alm_rho_increase_factor, + alm_rho_increase_patience=args.alm_rho_increase_patience, + alm_scale_guard_ratio=args.alm_scale_guard_ratio, + youngs_modulus_scale=args.youngs_modulus_scale, + # Topology control. + one_cc_only=not args.keep_all_components, + re_extract_interval=args.re_extract_interval, + # Loads and load-region settings. + forces=forces, + force_entries=force_entries, + use_local_loading=not args.global_loading, + seat_height_min_ratio=args.seat_height_min_ratio, + seat_height_max_ratio=args.seat_height_max_ratio, + force_region_mode=args.force_region_mode, + force_top_percent=args.force_top_percent, + force_bbox=args.force_bbox, + force_bbox_ratio=args.force_bbox_ratio, + # Output path. + out_folder=args.out_folder, + ) + + # Create the optimizer. + optimizer = HunyuanSDSOptimizer( + latents=latents, + cond=image_embeds, + vae=vae, + flow_model=flow_model, + scheduler=scheduler, + config=config, + device='cuda' + ) + + # Prepare physics if requested. + final_step = args.num_steps + if args.use_physics: + logging.info(f"\n🔬 enable physics optimization mode") + logging.info(f" - Voxel resolution: {args.res}") + logging.info(f" - physics steps/cycle: {args.phys_steps_per_cycle}, outer cycles: {args.outer_cycles}") + logging.info(f" - projection noise: sds_timestep={args.sds_timestep}") + logging.info(f" - target_z0update interval: {target_z0_update_interval} (consistent with phys_steps_per_cycle)") + logging.info(f" - LagrangeMax: {args.lagrange_max}") + + try: + optimizer.extract_solid(step=-1) # Initial extraction. + optimizer.prepare_physical_simulation() + logging.info(f" ✅ physics simulationInitializationsucceeded") + except Exception as e: + logging.warning(f" ⚠️ warning: initial mesh extraction failed (this is normal, optimizationbe repaired during the optimization process) ") + logging.warning(f" error information: {str(e)[:100]}") + # Continue anyway: the key physical state is the occupancy field, not the mesh. + else: + logging.info(f"\n🎨 using pure SDS optimization mode") + + # Optimization loop. + optimization_mode = "Alternating Phys/Projection" if args.use_physics else "Pure SDS" + total_steps_hint = ( + int(args.outer_cycles) * (int(args.phys_steps_per_cycle) + 1) + if args.use_physics + else args.num_steps + ) + logging.info(f"\n🚀 start{optimization_mode}optimization ({total_steps_hint} steps)...") + + if args.use_physics: + lagrange_multiplier = 0.0 + rho = config.alm_rho_init + violation_count = 0 + + # Automatically set the compliance threshold when needed. + if config.compliance_threshold is None or config.compliance_threshold == 200.0: + logging.info(f" 📊 computationinitialcompliancethreshold value...") + try: + initial_compliance, _, _, _ = optimizer.training_step( + 0, 0.0, 0.0, use_sds=False + ) + # Auto threshold: initial compliance times the requested ratio. + auto_threshold = initial_compliance * args.compliance_threshold_ratio + auto_threshold = min(auto_threshold, 100000.0) # Upper bound only. + compliance_threshold = auto_threshold + config.compliance_threshold = auto_threshold + logging.info( + f" ✅ Automatically set the threshold: {initial_compliance:.2e} × {args.compliance_threshold_ratio:.2f} " + f"= {compliance_threshold:.2e}" + ) + + # Warn when the structure already looks extremely stiff or too soft. + if initial_compliance < 0.01: # Already very stiff. + logging.warning(f" ⚠️ initial compliance is very small ({initial_compliance:.2e}), the structure may already be stiff enough!") + logging.warning(f" consider increasing the external force or using a softer material to create visible deformation") + logging.warning(f" current material: E={config.youngs_modulus:.2e} Pa, ν={config.poissons_ratio}") + elif initial_compliance > 1000.0: # Likely too soft. + logging.warning(f" ⚠️ initial compliance is very large ({initial_compliance:.2e}), the structure may be too soft!") + logging.warning(f" consider using a stiffer material or reducing the external force") + except Exception as e: + logging.warning(f" ⚠️ automatic computation failed, usethreshold value200: {e}") + compliance_threshold = 200.0 + else: + compliance_threshold = config.compliance_threshold + + logging.info(f"🎯 parameters:") + logging.info(f" - initial lambda: {lagrange_multiplier}") + logging.info(f" - initial rho: {rho}") + logging.info(f" - Compliancethreshold value: {compliance_threshold:.2e}") + logging.info(f" - λMax: {args.lagrange_max}") + logging.info(f" - ρMax: {config.alm_rho_max:.1e}") + logging.info(f" - rho growth: ×{config.alm_rho_increase_factor:.1f} (continuous violations{config.alm_rho_increase_patience} steps)") + logging.info(f" - ALMscaling guard ratio: {config.alm_scale_guard_ratio:.2f}") + logging.info(f" - gradient clipping: {'enabled' if config.grad_clip_enabled else 'disabled'}") + + outer_cycles = max(1, int(args.outer_cycles)) + phys_steps_per_cycle = max(1, int(args.phys_steps_per_cycle)) + total_steps = outer_cycles * (phys_steps_per_cycle + 1) + logging.info( + f"🔁 Alternating optimization: outer cycles={outer_cycles}, physics steps/cycle={phys_steps_per_cycle}, " + f"total steps(including projections)≈{total_steps}" + ) + base_youngs_modulus = float(config.youngs_modulus) + youngs_modulus_scale = float(config.youngs_modulus_scale) + youngs_modulus_target = base_youngs_modulus * youngs_modulus_scale + youngs_modulus_delta = (youngs_modulus_target - base_youngs_modulus) / outer_cycles + projection_count = 0 + logging.info( + f" - linearly increase Young's modulus: E0={base_youngs_modulus:.2e}, " + f"Δ/projection={youngs_modulus_delta:.2e}, E_final={youngs_modulus_target:.2e} " + f"(scale={youngs_modulus_scale:.2f}x)" + ) + global_step = 0 + phys_step_count = 0 + + history = {"compliance": [], + "u_mean": [], + "c_relative_decrease": [], + "u_relative_decrease": [], + "epoch": []} + + # thresholds = [0, 30, 40, 50, 60, 65, 70, 75, 80] + thresholds = [0, 20, 30, 40, 50, 55, 60] + thresh_idx = 0 + latents_dir = os.path.join(args.out_folder, "latents") + os.makedirs(latents_dir, exist_ok=True) + finish = False + for cycle in range(outer_cycles): + if finish: + break + logging.info(f"\n{'='*60}") + logging.info(f"Outer Cycle {cycle+1}/{outer_cycles}") + logging.info(f"{'='*60}") + + for inner in range(phys_steps_per_cycle): + step_id = global_step + phys_step = phys_step_count + + # Physics optimization step with ALM. + compliance_loss, u_mean, sds_loss, total_loss = optimizer.training_step( + phys_step, lagrange_multiplier, rho, use_sds=True, save_step=step_id + ) + + # Update history + history["compliance"].append(compliance_loss) + history["u_mean"].append(u_mean) + + # Calculate relative decreases using current variables + c_decrease = (history["compliance"][0] - compliance_loss) / history["compliance"][0] * 100 + u_decrease = (history["u_mean"][0] - u_mean) / history["u_mean"][0] * 100 + history["c_relative_decrease"].append(c_decrease) + history["u_relative_decrease"].append(u_decrease) + logging.info( + f" 📉 Metrics | Comp: {compliance_loss:.3e} (↓ {c_decrease:.1f}%) | u_mean: {u_mean:.3e} (↓ {u_decrease:.1f}%)" + ) + + if not args.not_use_threshold: + if thresh_idx < len(thresholds): + current_threshold = thresholds[thresh_idx] + if (c_decrease > current_threshold) or (c_decrease == current_threshold) : + logging.info(f"\n✅ Threshold reached: {current_threshold}") + optimizer.save_mesh(current_threshold, args.out_folder, suffix="decrease", high_quality=True) + + latent_path = os.path.join(latents_dir, f"latent_{current_threshold}.pt") + torch.save({ + 'latents': optimizer.latents.detach().cpu(), + 'cond': optimizer.cond, + }, latent_path) + + optimizer.save_final_deformed_mesh(current_threshold, suffix="decrease") + + history["epoch"].append(phys_step) + thresh_idx += 1 + else: + finish = True + break + else: + is_first_phys_step = inner == 0 + is_last_phys_step = inner == phys_steps_per_cycle - 1 + if is_first_phys_step or is_last_phys_step: + optimizer.save_mesh(step_id, args.out_folder, high_quality=True) + latent_path = os.path.join(latents_dir, f"latent_{step_id}.pt") + torch.save({ + 'latents': optimizer.latents.detach().cpu(), + 'cond': optimizer.cond, + }, latent_path) + optimizer.save_final_deformed_mesh(step_id) + + # Normalized constraint: g = D / D_thr - 1. + violation = (compliance_loss / (compliance_threshold + 1e-8)) - 1.0 + g_pos = max(0.0, violation) + + # Update lambda and project it to the non-negative range. + lagrange_multiplier = max(0.0, lagrange_multiplier + rho * violation) + lagrange_multiplier = min(lagrange_multiplier, args.lagrange_max) + + # Increase rho after persistent violations. + if g_pos > 0.0: + violation_count += 1 + if violation_count >= config.alm_rho_increase_patience: + new_rho = min(rho * config.alm_rho_increase_factor, config.alm_rho_max) + if new_rho > rho: + rho = new_rho + logging.info(f" 🔧 rho increased: {rho:.2e} (continuous violations{config.alm_rho_increase_patience} steps)") + violation_count = 0 + else: + violation_count = 0 + + status = "❌ violating" if violation > 0 else "✅ within threshold" + + # Log a compact ALM summary. + logging.info( + f" 📊 Compliance (true) : {compliance_loss:.2e} vs threshold value{compliance_threshold:.2e} " + f"(g={violation:+.3e}, [g]+={g_pos:.3e}) {status}" + ) + logging.info(f" ⚖️ ALMStatus: λ={lagrange_multiplier:.4f} (max={args.lagrange_max}), ρ={rho:.2e}") + current_sds_weight = optimizer.get_current_sds_weight(phys_step) + if current_sds_weight > 0.0: + sds_percentage = (current_sds_weight * sds_loss) / (total_loss + 1e-10) * 100 + logging.info( + f" 🎨 Shape Loss: weight={current_sds_weight:.6f}, " + f"loss={sds_loss:.4e}, ratio={sds_percentage:.2f}%" + ) + else: + logging.info(f" 🎨 Shape Loss: disabled (weight is 0)") + + # Save only the first and last physics step of each outer cycle. + # is_first_phys_step = inner == 0 + # is_last_phys_step = inner == phys_steps_per_cycle - 1 + # if is_first_phys_step or is_last_phys_step: + # optimizer.save_mesh(step_id, args.out_folder) + + global_step += 1 + phys_step_count += 1 + + # Project back to the manifold by replacing latents with target_z0. + logging.info(f"\nStep {global_step} | Projection (E={optimizer.config.youngs_modulus:.2e} Pa)") + logging.info(" 🔮 manifold projection: add noise and compute target_z0, backreplace directlylatents") + projected = optimizer.project_to_manifold(step=global_step) + if not projected: + logging.warning(" ⚠️ projection failed, keep the physical result for this cycle") + else: + projection_count += 1 + new_E = base_youngs_modulus + youngs_modulus_delta * projection_count + new_E = min(new_E, youngs_modulus_target) + optimizer.config.youngs_modulus = new_E + if hasattr(optimizer, "E"): + optimizer.E = new_E + logging.info( + f" 🧱 Young's modulusupdate: E={new_E:.2e} " + f"(projection {projection_count}/{outer_cycles})" + ) + # if global_step % 20 == 0: + # projection_dir = os.path.join(args.out_folder, "projection_meshes") + # os.makedirs(projection_dir, exist_ok=True) + # optimizer.save_mesh(global_step, projection_dir) + global_step += 1 + + final_step = global_step + else: + # Pure SDS optimization. + for step in range(args.num_steps): + logging.info(f"\nStep {step}/{args.num_steps}") + optimizer.training_step_sds(step) + if step % 20 == 0: + optimizer.save_mesh(step, args.out_folder) + + # Save final results. + logging.info("\n✅ Optimization finished!save final results...") + optimizer.save_mesh(final_step, args.out_folder, high_quality=True) + if args.use_physics: + optimizer.save_final_target_z0_mesh(final_step) + optimizer.save_final_deformed_mesh(final_step) + + final_latents_path = os.path.join(args.out_folder, "optimized_latents.pt") + torch.save({ + 'latents': optimizer.latents.detach().cpu(), + 'cond': optimizer.cond, + }, final_latents_path) + logging.info(f"💾 save optimized latents: {final_latents_path}") + logging.info(f"\n✅ all files saved to: {args.out_folder}") + + history_path = os.path.join(args.out_folder, "history.json") + with open(history_path, "w", encoding="utf-8") as f: + json.dump(history, f, indent=4) + plot_history(history, save_dir=args.out_folder, filename="optimization_metrics.png") + + if args.use_physics: + logging.info(f"\n📊 force visualization data:") + logging.info(f" - directory: {os.path.join(args.out_folder, 'force_visualization')}") + logging.info(f" - quick view: cd {os.path.join(args.out_folder, 'force_visualization')} && python visualize_forces.py") + + +if __name__ == "__main__": + main() diff --git a/cfd_workflow_20261012/_seiler_ref/physiopt_new_scripts/hunyuan_alternate_me_better.py b/cfd_workflow_20261012/_seiler_ref/physiopt_new_scripts/hunyuan_alternate_me_better.py new file mode 100644 index 0000000000000000000000000000000000000000..50b53da2169171f156f3db97fe04f8e7ebfb3b34 --- /dev/null +++ b/cfd_workflow_20261012/_seiler_ref/physiopt_new_scripts/hunyuan_alternate_me_better.py @@ -0,0 +1,3404 @@ +""" +Hunyuan3D-2.1 physical optimization + shape-prior optimization. +""" + +import os +import copy +# os.environ['TORCH_HOME'] = '/mnt/cvlab/scratch/cvlab/home/hantzhan/.torch' +import sys +import shutil + +# Add Hunyuan3D-2.1 to the Python path. +hunyuan_path = os.path.abspath(os.path.join(os.path.dirname(__file__), "../../Hunyuan3D-2.1")) +# Note: logging is not imported yet, so use print here if needed. +# Basic logging is configured near the top of the file after import. + +sys.path.append("..") + +from matplotlib import pyplot as plt +import torch +import torch.nn.functional as F +import trimesh +import numpy as np +from PIL import Image +import argparse +import json +from typing import Tuple, Optional, List +from dataclasses import dataclass, field +import traceback +import logging + +# Configure logging here only conceptually; main() will reconfigure it to +# log to both the console and a file. +# Do not call basicConfig here so the main() configuration remains effective. +# logging.basicConfig(level=logging.INFO, format='%(levelname)s: %(message)s') + +# Physical-simulation imports. +PHYSIOPT_AVAILABLE = False +try: + from physiopt.utils.phys_utils import generate_hex + from physiopt.utils.grid_utils import filter_one_component + from physiopt.opt.field import occ_kernel + from physiopt.opt.forces import ForceConfig + PHYSIOPT_AVAILABLE = True + logging.info("✅ physics simulation moduleimportsucceeded") +except ImportError as e: + logging.warning(f"⚠️ warning: physics simulation moduleimportfailed: {e}") + logging.warning(" if you only run SDS optimization, you can ignore this warning") + PHYSIOPT_AVAILABLE = False + + def generate_hex(res, limits=[(-0.5, 0.5), (-0.5, 0.5), (-0.5, 0.5)], device="cuda", return_coords=False): + """Placeholder for hexahedral grid generation. + + Returns tensors in the same format as the real function. + """ + logging.warning(f"⚠️ warning: using placeholdergenerate_hex, please install the physiopt module") + return None, None + + def filter_one_component(mask, res): + """Placeholder for connected-component filtering. + + Args: + mask: Element mask [res*res*res] + res: Voxel resolution + """ + return mask + + def occ_kernel(sdf, res, beta): + """Placeholder for SDF-to-occupancy conversion.""" + return torch.sigmoid(-sdf * beta) + +# Warp physics-engine import. +try: + import warp as wp + wp.init() + WARP_AVAILABLE = True + logging.info("✅ Warp physics engineInitializationsucceeded") +except ImportError: + WARP_AVAILABLE = False + logging.warning("⚠️ warning: Warp physics enginenot installed, physics simulationwill be unavailable") + logging.warning(" Install: pip install warp-lang") + +# Hunyuan3D imports +try: + from hy3dgen.shapegen.models.autoencoders import ShapeVAE + from hy3dgen.shapegen import Hunyuan3DDiTFlowMatchingPipeline + from hy3dgen.shapegen.pipelines import export_to_trimesh +except ImportError as e: + logging.error(f"❌ failed to import Hunyuan3D modules: {e}") + logging.error(f"\nplease follow these steps to set upHunyuan3D-2.1:") + logging.error(f"1. cd {os.path.dirname(hunyuan_path)}") + logging.error(f"2. git clone https://github.com/Tencent/Hunyuan3D-2.git Hunyuan3D-2.1") + logging.error(f"3. cd Hunyuan3D-2.1") + logging.error(f"4. pip install -e .") + sys.exit(1) + + +@dataclass +class OptimizationConfig: + """Optimization config for physics + SDS.""" + # Physical-simulation parameters. + res: int = 32 # Voxel resolution (16/32/64), matching the reference code. + # Restored physical settings from the stable v90 configuration. + p_exponent: float = 1.0 # SIMP penalty exponent. + alpha_min: float = 0.01 # Minimum density, restored from v90. + volume_term: float = 1000000.0 # Volume-constraint weight, currently disabled. + occ_sdf_beta: float = 2.0 # Sigmoid-kernel beta, restored from v90. + one_cc_only: bool = False # Keep only the largest connected component. + + # SDS parameters. + # Use dynamic SDS weights so physics dominates early and aesthetics enters later. + sds_timestep: float = 0.1 # SDS timestep; smaller values preserve more detail. + sds_weight: float = 1.0 # SDS weight relative to the physical gradient. + sds_weight_start: float = 1e5 # 0.1 # 0.0001 # Initial SDS weight. + sds_weight_end: float = 1e5 # 1.0 # 0.001 # Final SDS weight. + guidance_scale: float = 7.5 # Standard CFG guidance scale for stronger image conditioning. + sds_projection_max_rel: float = 0.0 # Max relative target_z0 projection offset (0 = unlimited). + sds_use_uncond: bool = False # Use the unconditional branch when guidance_scale <= 1. + sds_target_z0_update_interval: int = 10 # target_z0 update interval; tied to phys_steps_per_cycle. + sds_target_z0_ema_beta: float = 0.9 # EMA smoothing coefficient; larger is smoother. + + lagrange_max: float = 50.0 # Max lambda. + compliance_threshold: float = 200.0 # Compliance threshold used for normalization. + alm_rho_init: float = 1.0 # Initial rho. + alm_rho_max: float = 1000.0 # Max rho. + alm_rho_increase_factor: float = 2.0 # Rho growth factor. + alm_rho_increase_patience: int = 5 # Number of consecutive violations before increasing rho. + alm_scale_guard_ratio: float = 0.95 # ALM scaling guard to stay below gradient clipping. + + # Topology control. + re_extract_interval: int = 5 # Re-extract the solid every N steps; 0 disables it. + + # Material properties. Values are aligned with the reference setup. + # youngs_modulus is already specified directly in Pa, so no unit conversion is needed. + youngs_modulus: float = 5e8 # 1e9 # Pa (= 1 GPa), restored from v90. + youngs_modulus_scale: float = 2.0 # Final multiplier after the last projection in alternating mode. + poissons_ratio: float = 0.3 # Poisson's ratio (dimensionless). + density: float = 650.0 # Material density (kg/m^3). + + ## Wood + # youngs_modulus: float = 9e9 # Pa (= 1 GPa), aligned with the reference code. + # poissons_ratio: float = 0.35 # Poisson's ratio (dimensionless), matches the reference. + # density: float = 400.0 # Material density (kg/m^3), matches the reference. + + ## PVG + # youngs_modulus: float = 3.25e9 # Pa (= 1 GPa), aligned with the reference code. + # poissons_ratio: float = 0.38 # Poisson's ratio (dimensionless), matches the reference. + # density: float = 1380.0 # Material density (kg/m^3), matches the reference. + + # Load conditions; supports multiple forces like config.json. + forces: List = None # List of ForceConfig objects. + # Multiple localized load entries, each with its own force and region settings. + force_entries: Optional[List[dict]] = None + + # Local-loading settings, e.g. to mimic a person sitting on a chair. + use_local_loading: bool = True # Use local loading instead of global uniform loading. + seat_height_min_ratio: float = 0.3 # Lower bound of the seat band as a height ratio. + seat_height_max_ratio: float = 0.5 # Upper bound of the seat band as a height ratio. + force_region_mode: str = "top_percent" # Load-region mode: top_percent / height_ratio / bbox. + force_top_percent: float = 0.05 # In top_percent mode, use the highest-Y fraction of nodes. + force_bbox: Optional[List[float]] = None # bbox mode: x_min x_max y_min y_max z_min z_max. + force_bbox_ratio: Optional[List[float]] = None # bbox mode in normalized node bounds [0, 1]. + + # Optimization parameters, restored from the stable v90 configuration. + lr: float = 0.001 # Learning rate. + num_steps: int = 100 # Number of optimization steps. + use_sgd: bool = False # Use SGD instead of Adam. + grad_clip_enabled: bool = False # Enable gradient clipping; off by default. + save_every: int = 10 # Save interval in steps. + deformed_mesh_interval: int = 10 # Save interval for deformed meshes. + deformed_mesh_disp_min: float = 0.0 # Minimum displacement for deformed-mesh color mapping. + deformed_mesh_disp_max: float = 0.2 # Maximum displacement for deformed-mesh color mapping. + + # Output path. + out_folder: str = "../out/hunyuan_opt" # Output directory. + + # Device. + device: str = "cuda" # Compute device. + + # Whether to enable physics optimization. + use_physics: bool = True # Enable physical-constraint optimization. + + def __post_init__(self): + # Set default loads in the Hunyuan Y-up coordinate system: + # X = right, Y = up, Z = forward. + if self.forces is None: + try: + from physiopt.opt.forces import ForceConfig + self.forces = [ + ForceConfig(external_force=[0.0, -100000.0, 0.0]) # 100 kN downward along Y. + # ForceConfig(external_force=[0.0, 0.0, -500.0]), # 500 N backward along Z. + ] + except ImportError: + # Fallback format if physiopt is unavailable; keep only the force vectors. + self.forces = [ + {'external_force': [0.0, -100000.0, 0.0]} # 100 kN downward along Y. + # {'external_force': [0.0, 0.0, -500.0]}, # Backward along Z. + ] + + +class HunyuanSDSOptimizer: + """Hunyuan3D SDS optimizer with differentiable physics support.""" + + def __init__( + self, + latents: torch.Tensor, + cond: dict, # Condition dict containing positive and negative branches. + vae: ShapeVAE, + flow_model: torch.nn.Module, + config: OptimizationConfig, + scheduler=None, + device: str = 'cuda' + ): + """ + Args: + latents: Initial latent tokens [1, N, D]. + cond: Condition dict returned by pipeline.encode_cond. + vae: Hunyuan3D VAE model. + flow_model: Hunyuan3D Flow Matching model. + scheduler: Hunyuan3D Flow Matching scheduler used to align target_z0. + config: Optimization config. + device: Compute device. + """ + self.device = device + self.config = config + + # Models. + self.vae = vae.to(device).eval() + self.flow_model = flow_model.to(device).eval() + if scheduler is not None: + try: + self.sds_scheduler = copy.deepcopy(scheduler) + except Exception: + self.sds_scheduler = scheduler + logging.warning("⚠️ Scheduler deepcopyfailed, already fallback to originalscheduler") + else: + self.sds_scheduler = None + + # Create a differentiable SDF query helper. + from hy3dgen.shapegen.models.autoencoders.differentiable_sdf_query import DifferentiableSDFQuery + self.sdf_query = DifferentiableSDFQuery( + vae=self.vae, + bounds=0.8, # Our coordinate range is [-0.8, 0.8]. + chunk_size=8192 # Batch query size. + ) + logging.info(f"✅ created differentiable SDF query helper") + + # Latent tokens are the variables being optimized. + # Use float32 instead of float16 to avoid numeric overflow. + self.latents = latents.clone().to(device).to(torch.float32).requires_grad_(True) + + logging.info(f" ⚠️ note: Latentsfloat32FP16value") + + # Move conditioning data to the target device recursively. + def to_device_recursive(obj): + if isinstance(obj, torch.Tensor): + return obj.to(device) + elif isinstance(obj, dict): + return {k: to_device_recursive(v) for k, v in obj.items()} + elif isinstance(obj, (list, tuple)): + return type(obj)(to_device_recursive(item) for item in obj) + else: + return obj + + self.cond = to_device_recursive(cond) + self._cond_warned_cfg_repeat = False + self._cond_warned_nocfg_slice = False + + # Optimizer selection. + if config.use_sgd: + self.optimizer = torch.optim.SGD([self.latents], lr=config.lr, momentum=0.0) + opt_name = "SGD" + else: + self.optimizer = torch.optim.Adam([self.latents], lr=config.lr, betas=(0.9, 0.999), eps=1e-8) + opt_name = "Adam" + + logging.info(f"✅ HunyuanSDSOptimizerInitializationcompleted (with differentiable physics support) ") + logging.info(f" - Latents shape: {self.latents.shape}") + logging.info(f" - Latents dtype: {self.latents.dtype} (optimized in float32)") + logging.info(f" - Device: {device}") + logging.info(f" - Optimizer: {opt_name}") + logging.info(f" - Learning rate: {config.lr}") + + # target_z0 EMA cache. + self.target_z0_ema = None + self.target_z0_last_velocity = None + self.target_z0_last_update = None + + def get_field(self, x: torch.Tensor, latents: torch.Tensor = None) -> torch.Tensor: + """Differentiable SDF query through the VAE geo_decoder. + + Args: + x: Query points [N, 3] in the range [-0.8, 0.8]^3. + latents: Optional latent tokens; defaults to self.latents. + + Returns: + sdf: SDF values [N] with gradient support. + """ + if latents is None: + latents = self.latents + + # Match the official pipeline: divide by scale_factor before decoding. + scale_factor = getattr(self.vae, "scale_factor", 1.0) + latents_scaled = latents / scale_factor + + # Convert to FP16 because the VAE expects FP16 inputs. + latents_fp16 = latents_scaled.to(torch.float16) + + # Decode with the VAE decoder while preserving gradients. + decoded_latents = self.vae.decode(latents_fp16) + + # Query the SDF through the differentiable helper. + # sdf_query calls geo_decoder internally, so keep FP16 to match VAE weights. + sdf = self.sdf_query( + decoded_latents, # Keep FP16 and let sdf_query handle the rest. + x, + return_occupancy=False # Return SDF instead of occupancy. + ) # [N] + + return sdf + + def _cond_batch_size(self, cond) -> Optional[int]: + if isinstance(cond, torch.Tensor): + return cond.shape[0] if cond.dim() >= 1 else None + if isinstance(cond, dict): + for v in cond.values(): + bsz = self._cond_batch_size(v) + if bsz is not None: + return bsz + if isinstance(cond, (list, tuple)): + for v in cond: + bsz = self._cond_batch_size(v) + if bsz is not None: + return bsz + return None + + def _cond_slice(self, cond, batch_slice: slice): + if isinstance(cond, torch.Tensor): + if cond.dim() >= 1 and cond.shape[0] >= batch_slice.stop: + return cond[batch_slice] + return cond + if isinstance(cond, dict): + return {k: self._cond_slice(v, batch_slice) for k, v in cond.items()} + if isinstance(cond, (list, tuple)): + return type(cond)(self._cond_slice(v, batch_slice) for v in cond) + return cond + + def _cond_repeat(self, cond, repeats: int): + if isinstance(cond, torch.Tensor): + if cond.dim() >= 1: + rep_shape = (repeats,) + (1,) * (cond.dim() - 1) + return cond.repeat(rep_shape) + return cond + if isinstance(cond, dict): + return {k: self._cond_repeat(v, repeats) for k, v in cond.items()} + if isinstance(cond, (list, tuple)): + return type(cond)(self._cond_repeat(v, repeats) for v in cond) + return cond + + def _get_cond_for_guidance(self, use_cfg: bool): + cond = self.cond + bsz = self._cond_batch_size(cond) + if use_cfg: + if bsz == 1: + if not self._cond_warned_cfg_repeat: + logging.warning("⚠️ guidance_scale>1 cond batch=1, already condCFG") + self._cond_warned_cfg_repeat = True + return self._cond_repeat(cond, 2) + if bsz is not None and bsz > 2: + return self._cond_slice(cond, slice(0, 2)) + return cond + # no-CFG + if bsz is not None and bsz >= 2: + if self.config.sds_use_uncond: + if not self._cond_warned_nocfg_slice: + logging.info("ℹ️ guidance_scale<=1, useno conditioncond[1:2]") + self._cond_warned_nocfg_slice = True + return self._cond_slice(cond, slice(1, 2)) + if not self._cond_warned_nocfg_slice: + logging.info("ℹ️ guidance_scale<=1, already usecond[0:1]batch") + self._cond_warned_nocfg_slice = True + return self._cond_slice(cond, slice(0, 1)) + if self.config.sds_use_uncond and bsz == 1 and not self._cond_warned_nocfg_slice: + logging.warning("⚠️ sds_use_uncond=1 cond batch=1, already fallback to conditself") + self._cond_warned_nocfg_slice = True + return cond + + def latents_to_mesh(self, latents: torch.Tensor, octree_res: int = 128) -> Optional[trimesh.Trimesh]: + """Decode latent tokens into a mesh. + + Args: + latents: Latent tokens [1, N, D] (float32). + octree_res: Octree resolution. 128 is faster; 256 is higher quality. + + Returns: + A trimesh.Trimesh object, or None on failure. + """ + with torch.no_grad(): + # Skip invalid latent tensors early. + if torch.isnan(latents).any() or torch.isinf(latents).any(): + logging.warning(" latents_to_mesh: latentscontains NaN or Inf, skip") + return None + + # Match the official pipeline by dividing by scale_factor first. + scale_factor = getattr(self.vae, "scale_factor", 1.0) + latents_scaled = latents / scale_factor + + # Decode in FP16 because the VAE expects FP16 inputs. + latents_fp16 = latents_scaled.to(torch.float16) + + try: + # VAE decode. + decoded_latents = self.vae.decode(latents_fp16) + + # Skip invalid decoded latents. + if torch.isnan(decoded_latents).any() or torch.isinf(decoded_latents).any(): + logging.warning(" latents_to_mesh: decoded_latentscontains NaN or Inf, skip") + return None + except Exception as e: + logging.debug(f" latents_to_mesh: VAE decodingfailed: {e}") + return None + + # Use an adaptive mc_level fallback if the default level fails. + try: + # First try the standard mc_level=0.0. + mesh = self.vae.latents2mesh( + decoded_latents, + output_type='trimesh', + bounds=1.01, + mc_level=0.0, + num_chunks=20000, + octree_resolution=octree_res, + mc_algo='mc', + enable_pbar=False + ) + mesh = export_to_trimesh(mesh)[0] + return mesh + + except ValueError as e: + error_msg = str(e) + if "Surface level must be within volume data range" in error_msg: + # Estimate a better mc_level from sampled SDF statistics. + logging.debug(f" latents_to_mesh: mc_level=0.0 failed, try an adaptive level...") + + try: + # Sample a coarse grid to estimate the SDF range. + grid_size = 32 + x = torch.linspace(-1.0, 1.0, grid_size, device=decoded_latents.device) + y = torch.linspace(-1.0, 1.0, grid_size, device=decoded_latents.device) + z = torch.linspace(-1.0, 1.0, grid_size, device=decoded_latents.device) + xx, yy, zz = torch.meshgrid(x, y, z, indexing='ij') + points = torch.stack([xx, yy, zz], dim=-1).reshape(-1, 3) # [N, 3] + + # query the SDF values. + sdf_values = self.get_field(points, latents=latents) + + # Compute basic statistics. + sdf_median = torch.median(sdf_values).item() + sdf_min = sdf_values.min().item() + sdf_max = sdf_values.max().item() + sdf_mean = sdf_values.mean().item() + + logging.debug(f" SDFstatistics: min={sdf_min:.4f}, max={sdf_max:.4f}, median={sdf_median:.4f}, mean={sdf_mean:.4f}") + + # No clear surface can be extracted if the SDF range is too small. + if abs(sdf_max - sdf_min) < 1e-4: + logging.debug(f" SDFrange is too small to extract a surface") + return None + + # Try several plausible candidate levels. + candidate_levels = [ + sdf_median, # Median. + sdf_mean, # Mean. + (sdf_min + sdf_max) / 2, # Midpoint of the range. + sdf_min + (sdf_max - sdf_min) * 0.3, # 30% point. + sdf_min + (sdf_max - sdf_min) * 0.7, # 70% point. + ] + + # Clamp all levels to the valid range. + valid_levels = [ + max(sdf_min + 0.001, min(sdf_max - 0.001, level)) + for level in candidate_levels + ] + + # Remove duplicates. + valid_levels = list(set(valid_levels)) + + logging.debug(f" try {len(valid_levels)} candidate levels: {[f'{l:.4f}' for l in valid_levels[:3]]}...") + + # Try each candidate level in order. + for i, adaptive_level in enumerate(valid_levels): + try: + mesh = self.vae.latents2mesh( + decoded_latents, + output_type='trimesh', + bounds=1.01, + mc_level=adaptive_level, + num_chunks=20000, + octree_resolution=octree_res, + mc_algo='mc', + enable_pbar=False + ) + mesh = export_to_trimesh(mesh)[0] + logging.info(f" ✅ uselevelsucceeded (level={adaptive_level:.4f}, attempt {i+1})") + return mesh + except (ValueError, RuntimeError) as level_error: + # Try the next level if this one fails. + if i < len(valid_levels) - 1: + continue + else: + # All candidate levels failed. + logging.debug(f" all candidate levels failed") + return None + + # No candidate succeeded. + return None + + except Exception as adaptive_error: + logging.debug(f" adaptive extraction failed: {type(adaptive_error).__name__}: {str(adaptive_error)[:50]}") + return None + + elif "No surface found" in error_msg: + logging.debug(f" latents_to_mesh: Marching cubesno surface found, skip") + return None + else: + logging.warning(f" latents_to_mesh: unknown ValueError: {error_msg}") + return None + + except RuntimeError as e: + error_msg = str(e) + if "No surface found" in error_msg or "Surface level" in error_msg: + logging.debug(f" latents_to_mesh: Marching cubesfailed, skip") + return None + else: + logging.warning(f" latents_to_mesh: RuntimeError: {error_msg}") + return None + + except Exception as e: + # Catch any other unexpected failure. + logging.warning(f" latents_to_mesh: unexpected exception: {type(e).__name__}: {e}") + return None + + def _filter_floating_components(self, mesh: trimesh.Trimesh) -> trimesh.Trimesh: + """Remove small floating fragments and keep only the largest component.""" + try: + components = mesh.split(only_watertight=False) + if len(components) <= 1: + return mesh + + face_counts = [len(comp.faces) for comp in components] + max_idx = int(np.argmax(face_counts)) + filtered = components[max_idx] + dropped = len(components) - 1 + + logging.info(f" 🧹 filter floating fragments: kept{len(filtered.faces)} faces, discarded{dropped} small components") + return filtered + except Exception as e: + logging.warning(f" failed to filter floating fragments: {type(e).__name__}: {str(e)[:100]}") + return mesh + + def _sample_displacement_to_vertices( + self, + vertices: np.ndarray, + nodes: np.ndarray, + displacement: np.ndarray, + ) -> np.ndarray: + """Sample the voxel-node displacement field onto mesh vertices by nearest neighbor.""" + try: + from scipy.spatial import cKDTree + tree = cKDTree(nodes) + _, idx = tree.query(vertices, k=1) + return displacement[idx] + except Exception as e: + try: + from sklearn.neighbors import NearestNeighbors + nn = NearestNeighbors(n_neighbors=1, algorithm="auto") + nn.fit(nodes) + idx = nn.kneighbors(vertices, return_distance=False).squeeze(1) + return displacement[idx] + except Exception as e2: + logging.warning(f" displacement sampling failed, fallback to zero displacement: {type(e).__name__}: {str(e)[:100]}") + logging.debug(f" secondaryError: {type(e2).__name__}: {str(e2)[:100]}") + return np.zeros_like(vertices) + + def _normalize_displacement_magnitude( + self, disp_mag: np.ndarray + ) -> Tuple[np.ndarray, float, float, bool]: + """Normalize displacement magnitude, optionally with a fixed range.""" + mag_max_cfg = getattr(self.config, "deformed_mesh_disp_max", None) + mag_min_cfg = getattr(self.config, "deformed_mesh_disp_min", None) + use_fixed = mag_max_cfg is not None and mag_max_cfg > 0.0 + if use_fixed: + mag_min = 0.0 if mag_min_cfg is None else float(mag_min_cfg) + mag_max = float(mag_max_cfg) + if mag_max <= mag_min: + use_fixed = False + if not use_fixed: + mag_min = float(disp_mag.min()) + mag_max = float(disp_mag.max()) + denom = max(1e-12, mag_max - mag_min) + norm = (disp_mag - mag_min) / denom + if use_fixed: + norm = np.clip(norm, 0.0, 1.0) + return norm, mag_min, mag_max, use_fixed + + def _make_displacement_colors(self, displacement: np.ndarray) -> np.ndarray: + """Map displacement magnitude to vertex colors (blue -> red).""" + disp_mag = np.linalg.norm(displacement, axis=1) + norm, _, _, _ = self._normalize_displacement_magnitude(disp_mag) + colors = np.stack([norm, np.zeros_like(norm), 1.0 - norm], axis=1) + return (colors * 255).astype(np.uint8) + + def _log_physical_quantities( + self, + u: torch.Tensor, + sigma: Optional[torch.Tensor], + ) -> None: + """Log displacement and von Mises stress statistics.""" + with torch.no_grad(): + u_max = None + u_avg = None + try: + u_mag = torch.norm(u, dim=1) + u_max = u_mag.max().item() + u_avg = u_mag.mean().item() + except Exception as e: + logging.warning( + f" ⚠️ displacement statistics failed: {type(e).__name__}: {str(e)[:100]}" + ) + + sigma_vm_max = None + sigma_vm_avg = None + if sigma is not None: + try: + if sigma.dim() == 2 and sigma.shape[1] >= 6: + s_xx = sigma[:, 0] + s_yy = sigma[:, 1] + s_zz = sigma[:, 2] + s_yz = sigma[:, 3] + s_xz = sigma[:, 4] + s_xy = sigma[:, 5] + mises_sq = 0.5 * ( + (s_xx - s_yy) ** 2 + + (s_yy - s_zz) ** 2 + + (s_zz - s_xx) ** 2 + + 6.0 * (s_xy ** 2 + s_yz ** 2 + s_xz ** 2) + ) + mises = torch.sqrt(torch.clamp(mises_sq, min=0.0)) + sigma_vm_max = mises.max().item() + sigma_vm_avg = mises.mean().item() + else: + logging.warning( + f" ⚠️ sigmashape does not match expectations, skip von Mises statistics: {tuple(sigma.shape)}" + ) + except Exception as e: + logging.warning( + f" ⚠️ von Mises statistics failed: {type(e).__name__}: {str(e)[:100]}" + ) + + if u_max is not None and u_avg is not None: + if sigma_vm_max is not None and sigma_vm_avg is not None: + logging.info( + f" physical metrics: u_max={u_max:.3e}, u_avg={u_avg:.3e}, " + f"sigma_vm_max={sigma_vm_max:.3e}, sigma_vm_avg={sigma_vm_avg:.3e}" + ) + else: + logging.info( + f" physical metrics: u_max={u_max:.3e}, u_avg={u_avg:.3e}" + ) + + def backward_step(self, sensitivity_density: torch.Tensor): + """Backpropagate with VJP, aligned with the reference code. + + Reference: viewer_deepsdf.py Line 148-183. + This uses torch.autograd.functional.vjp to propagate sensitivity to latents. + """ + def f(latents: torch.Tensor): + """ + Compute occupancy from a given latent tensor. + Aligned with viewer_deepsdf.py Line 155-173. + """ + # Query the SDF. + sdf = self.get_field(self.nodes, latents) + + # SDF → occupancy + from physiopt.opt.field import occ_kernel + occ = occ_kernel(sdf, self.config.res, self.config.occ_sdf_beta) + + # Element occupancy is the average over the 8 nodes. + occ_elem = occ[self.elements].mean(1) + + # Clamp by alpha_min if requested. + if self.config.alpha_min > 0.0: + occ_elem = torch.clamp(occ_elem, self.config.alpha_min) + + return occ_elem + + # VJP computations d occ / d latents^T times the sensitivity vector. + # Aligned with viewer_deepsdf.py Line 175-180. + try: + grad_latent = torch.autograd.functional.vjp( + f, + self.latents.clone().requires_grad_(True), + sensitivity_density, + )[1] + + # Validate the returned gradient. + if grad_latent is None: + logging.error(" ❌ VJP returned None!") + return + + grad_norm = torch.norm(grad_latent).item() + logging.info(f" VJP gradient: norm={grad_norm:.2e}") + + # Assign the gradient manually, matching the reference implementation. + self.latents.grad = grad_latent + + except Exception as e: + logging.error(f" ❌ VJP failed: {e}") + import traceback + traceback.print_exc() + + def prepare_physical_simulation(self): + """Prepare the physical simulation and FEM solver state. + + Initialization includes: + 1. Material properties + 2. Boundary conditions + 3. External forces + """ + if not WARP_AVAILABLE: + logging.warning("Warpnot installed, skipphysics simulation preparation") + return + + if not hasattr(self, 'nodes') or not hasattr(self, 'elements'): + logging.error("please call extract_solid() to extract the solid first") + return + + logging.info("prepare physical simulation...") + + # Initialize Warp. + wp.init() + + # Normalize device names such as "cuda" and "cuda:0". + if 'cuda' in self.device: + # Extract the device id when needed. + if ':' in self.device: + device_id = self.device.split(':')[-1] + warp_device = f"cuda:{device_id}" + else: + warp_device = "cuda:0" # default to cuda:0 + else: + warp_device = "cpu" + + wp.set_device(warp_device) + logging.info(f"Warpdevice: {warp_device}") + + # Material properties. + self.E = self.config.youngs_modulus # Young's modulus. + self.nu = self.config.poissons_ratio # Poisson's ratio. + self.rho = self.config.density # Density. + + # Boundary condition: fix bottom nodes using Hunyuan's Y-up frame. + y_coords = self.nodes[:, 1] + y_min = y_coords.min() + boundary_threshold = y_min + 0.05 # 0.2 # 0.05 # Bottom 5% band. + self.boundary_mask = y_coords < boundary_threshold + + logging.info(f" coordinate system: Y-up (Hunyuan-native), fix Y < {boundary_threshold:.3f}nodes") + + # Apply load locally instead of spreading it across all nodes. + # The default heuristic targets a seat-like region in the Y-up frame. + + # Compute the total force, giving priority to force_entries. + total_force = np.zeros(3, dtype=np.float32) + force_entries = getattr(self.config, "force_entries", None) + valid_force_entries = None + if force_entries: + valid_force_entries = [] + for entry in force_entries: + if not isinstance(entry, dict): + continue + entry_force = None + if "force" in entry: + try: + entry_force = np.array(entry["force"], dtype=np.float32) + except Exception: + entry_force = None + elif "forces" in entry and isinstance(entry["forces"], list): + try: + entry_force = np.sum( + np.array(entry["forces"], dtype=np.float32), axis=0 + ) + except Exception: + entry_force = None + if entry_force is None or entry_force.shape != (3,): + continue + valid_force_entries.append(entry) + total_force += entry_force + if valid_force_entries: + self.force_entries_preset = valid_force_entries + logging.info(f" force entries: {len(valid_force_entries)}") + else: + logging.warning(" ⚠️ force_entries has no valid entries, fallback to forces") + valid_force_entries = None + + if valid_force_entries is None: + for force_config in self.config.forces: + if hasattr(force_config, 'get_total_force'): + # ForceConfig object. + total_force += force_config.get_total_force() + elif isinstance(force_config, dict) and 'external_force' in force_config: + # Compatibility format using a plain dict. + total_force += np.array(force_config['external_force'], dtype=np.float32) + else: + logging.warning(f"unknown force format: {type(force_config)}") + + logging.info(f" sum of external forces (Y-up coordinates): {total_force}") + + # Choose the loading strategy from the config. + if valid_force_entries is not None: + # Multiple localized loads, each with its own region. + self._setup_local_loading(total_force) + elif self.config.use_local_loading: + # Preferred mode: local loading. + self._setup_local_loading(total_force) + else: + # Fallback mode: global uniform loading. + logging.info(f" ℹ️ using global uniform loading mode") + total_force_tensor = torch.from_numpy(total_force).float().to(self.device) + num_nodes = self.nodes.shape[0] + self.forces = total_force_tensor[None, :].repeat(num_nodes, 1) + logging.info(f" 💨 distributed the total force uniformly to{num_nodes}nodes") + + logging.info(f"boundary conditions: {self.boundary_mask.sum().item()}fixed nodes") + logging.info(f"material properties: E={self.E:.2e}, ν={self.nu}, ρ={self.rho}") + + def _setup_local_loading(self, total_force: np.ndarray): + """Set up local loading on the selected seat/contact region. + + The total force is distributed uniformly across the selected nodes so + that sum(forces) equals total_force. + + Args: + total_force: Total force vector [3] in the Y-up frame, in Newtons. + """ + # Cache the total force for later updates. + self.total_force_preset = torch.from_numpy(total_force).float().to(self.device) + + # Reuse the generic update routine for the initial setup. + self._update_forces(initial_setup=True) + + def _update_forces(self, initial_setup: bool = False): + """Update the force distribution for the current mesh state. + + Core logic: + 1. Re-identify contact nodes + 2. Spread the preset total force uniformly over those nodes + 3. Keep total force conserved + + Args: + initial_setup: Whether this is the first setup pass. + """ + if not hasattr(self, 'total_force_preset'): + logging.warning("No preset total force is set, so the force distribution cannot be updated") + return + + # Step 1: inspect the Y-coordinate distribution. + y_coords = self.nodes[:, 1] + num_nodes = self.nodes.shape[0] + + force_entries = getattr(self, "force_entries_preset", None) + if force_entries: + def _select_nodes_for_mode(mode, top_percent, min_ratio, max_ratio, bbox, bbox_ratio): + seat_mask = torch.zeros(num_nodes, dtype=torch.bool, device=self.device) + mode_used = mode + bbox_desc = None + + if mode_used not in ("top_percent", "height_ratio", "bbox", "global"): + logging.warning(f" ⚠️ invalid force_region_mode: {mode_used}, fallback to top_percent") + mode_used = "top_percent" + + if mode_used == "global": + seat_mask[:] = True + return seat_mask, mode_used, bbox_desc + + if mode_used == "bbox": + bbox_vals = None + if bbox is not None and len(bbox) == 6: + bbox_vals = [float(v) for v in bbox] + bbox_desc = "abs" + elif bbox_ratio is not None and len(bbox_ratio) == 6: + bbox_ratio_vals = [float(v) for v in bbox_ratio] + bounds_min = self.nodes.min(dim=0).values + bounds_max = self.nodes.max(dim=0).values + bbox_vals = [ + bounds_min[0].item() + bbox_ratio_vals[0] * (bounds_max[0] - bounds_min[0]).item(), + bounds_min[0].item() + bbox_ratio_vals[1] * (bounds_max[0] - bounds_min[0]).item(), + bounds_min[1].item() + bbox_ratio_vals[2] * (bounds_max[1] - bounds_min[1]).item(), + bounds_min[1].item() + bbox_ratio_vals[3] * (bounds_max[1] - bounds_min[1]).item(), + bounds_min[2].item() + bbox_ratio_vals[4] * (bounds_max[2] - bounds_min[2]).item(), + bounds_min[2].item() + bbox_ratio_vals[5] * (bounds_max[2] - bounds_min[2]).item(), + ] + bbox_desc = "ratio" + else: + logging.warning(" ⚠️ bbox mode did not provide a valid bbox, fallback to top_percent") + mode_used = "top_percent" + + if mode_used == "bbox" and bbox_vals is not None: + x0, x1 = sorted([bbox_vals[0], bbox_vals[1]]) + y0, y1 = sorted([bbox_vals[2], bbox_vals[3]]) + z0, z1 = sorted([bbox_vals[4], bbox_vals[5]]) + seat_mask = ( + (self.nodes[:, 0] >= x0) & (self.nodes[:, 0] <= x1) + & (self.nodes[:, 1] >= y0) & (self.nodes[:, 1] <= y1) + & (self.nodes[:, 2] >= z0) & (self.nodes[:, 2] <= z1) + ) + if seat_mask.sum().item() < 1: + logging.warning(" ⚠️ bbox region matched no nodes, fallback to top_percent") + mode_used = "top_percent" + else: + bbox_desc = f"{bbox_desc}: [{x0:.3f},{x1:.3f}]x[{y0:.3f},{y1:.3f}]x[{z0:.3f},{z1:.3f}]" + + if mode_used == "height_ratio": + y_min = y_coords.min().item() + y_max = y_coords.max().item() + y_range = max(1e-8, y_max - y_min) + if not (0.0 <= min_ratio < max_ratio <= 1.0): + logging.warning( + f" ⚠️ invalid height_ratio: min={min_ratio}, max={max_ratio}, fallback to top_percent" + ) + mode_used = "top_percent" + else: + seat_y_min = y_min + y_range * min_ratio + seat_y_max = y_min + y_range * max_ratio + seat_mask = (y_coords >= seat_y_min) & (y_coords <= seat_y_max) + if seat_mask.sum().item() < 1: + logging.warning(" ⚠️ height_ratio matched no nodes, fallback to top_percent") + mode_used = "top_percent" + + if mode_used == "top_percent": + top_percent = float(top_percent) + top_percent = max(0.0, min(1.0, top_percent)) + if top_percent <= 0.0: + top_percent = 0.05 + num_seat_nodes = max(1, int(num_nodes * top_percent)) + _, top_indices = torch.topk(y_coords, k=num_seat_nodes, largest=True) + seat_mask = torch.zeros(num_nodes, dtype=torch.bool, device=self.device) + seat_mask[top_indices] = True + + return seat_mask, mode_used, bbox_desc + + self.forces = torch.zeros((num_nodes, 3), dtype=torch.float32, device=self.device) + combined_mask = torch.zeros(num_nodes, dtype=torch.bool, device=self.device) + total_force = torch.zeros(3, dtype=torch.float32, device=self.device) + + for idx, entry in enumerate(force_entries): + if not isinstance(entry, dict): + continue + entry_label = entry.get("label") or entry.get("name") or f"{idx+1}" + entry_force = None + if "forces" in entry and isinstance(entry["forces"], list): + try: + entry_force = np.sum(np.array(entry["forces"], dtype=np.float32), axis=0) + except Exception: + entry_force = None + if entry_force is None and "force" in entry: + try: + entry_force = np.array(entry["force"], dtype=np.float32) + except Exception: + entry_force = None + if entry_force is None or entry_force.shape != (3,): + logging.warning(f" ⚠️ invalid force entry[{entry_label}], skip") + continue + + entry_force_tensor = torch.from_numpy(entry_force).float().to(self.device) + total_force += entry_force_tensor + + mode = str(entry.get("force_region_mode", self.config.force_region_mode)).lower() + if entry.get("global_loading") is True: + mode = "global" + + top_percent = entry.get("force_top_percent", self.config.force_top_percent) + min_ratio = entry.get("seat_height_min_ratio", self.config.seat_height_min_ratio) + max_ratio = entry.get("seat_height_max_ratio", self.config.seat_height_max_ratio) + bbox = entry.get("force_bbox", self.config.force_bbox) + bbox_ratio = entry.get("force_bbox_ratio", self.config.force_bbox_ratio) + + seat_nodes_mask, mode_used, bbox_desc = _select_nodes_for_mode( + mode, top_percent, min_ratio, max_ratio, bbox, bbox_ratio + ) + + num_seat_nodes = int(seat_nodes_mask.sum().item()) + if num_seat_nodes < 1: + logging.warning(f" ⚠️ entry[{entry_label}]matched no nodes, skip") + continue + + force_per_node = entry_force_tensor / num_seat_nodes + self.forces[seat_nodes_mask] += force_per_node + combined_mask |= seat_nodes_mask + + seat_y_values = y_coords[seat_nodes_mask] + seat_y_min = seat_y_values.min().item() + seat_y_max = seat_y_values.max().item() + seat_y_mean = seat_y_values.mean().item() + + if initial_setup: + if mode_used == "bbox": + logging.info(f" 🪑 contact surface[{entry_label}]: bbox ({bbox_desc})") + elif mode_used == "height_ratio": + logging.info( + f" 🪑 contact surface[{entry_label}]: height_ratio " + f"[{min_ratio:.2f}, {max_ratio:.2f}]" + ) + elif mode_used == "global": + logging.info(f" 🪑 contact surface[{entry_label}]: global") + else: + logging.info( + f" 🪑 contact surface[{entry_label}]: highest-Y {float(top_percent):.1%} nodes" + ) + logging.info( + f" 🪑 seat-node count[{entry_label}]: {num_seat_nodes}/{num_nodes} " + f"({num_seat_nodes/num_nodes:.1%})" + ) + logging.info( + f" 🪑 Y range[{entry_label}]: [{seat_y_min:.3f}, {seat_y_max:.3f}], " + f"mean: {seat_y_mean:.3f}" + ) + logging.info(f" 💺 force[{entry_label}]: {entry_force}") + logging.info(f" 💺 per node[{entry_label}]: {force_per_node.cpu().numpy()}") + + self.total_force_preset = total_force + actual_total_force = self.forces.sum(dim=0) + force_error = torch.norm(actual_total_force - total_force).item() + force_error_percent = (force_error / (torch.norm(total_force).item() + 1e-10)) * 100 + + if initial_setup: + logging.info( + f" ✅ total-force check: {actual_total_force.cpu().numpy()} " + f"(error: {force_error:.2e}, {force_error_percent:.3f}%)" + ) + if combined_mask.any(): + self._save_force_visualization( + combined_mask, total_force.cpu().numpy() + ) + else: + logging.debug( + f" 🔄 force update: loaded nodes {int(combined_mask.sum().item())}, " + f"total force error {force_error:.2e}" + ) + + self._last_num_seat_nodes = int(combined_mask.sum().item()) + return + + # Contact-region selection supports top_percent / height_ratio / bbox. + mode = str(getattr(self.config, "force_region_mode", "top_percent")).lower() + seat_nodes_mask = torch.zeros(num_nodes, dtype=torch.bool, device=self.device) + mode_used = mode + bbox_desc = None + if mode_used not in ("top_percent", "height_ratio", "bbox"): + logging.warning(f" ⚠️ invalid force_region_mode: {mode_used}, fallback to top_percent") + mode_used = "top_percent" + + if mode_used == "bbox": + bbox = getattr(self.config, "force_bbox", None) + bbox_ratio = getattr(self.config, "force_bbox_ratio", None) + bbox_vals = None + if bbox is not None and len(bbox) == 6: + bbox_vals = [float(v) for v in bbox] + bbox_desc = "abs" + elif bbox_ratio is not None and len(bbox_ratio) == 6: + bbox_ratio_vals = [float(v) for v in bbox_ratio] + bounds_min = self.nodes.min(dim=0).values + bounds_max = self.nodes.max(dim=0).values + bbox_vals = [ + bounds_min[0].item() + bbox_ratio_vals[0] * (bounds_max[0] - bounds_min[0]).item(), + bounds_min[0].item() + bbox_ratio_vals[1] * (bounds_max[0] - bounds_min[0]).item(), + bounds_min[1].item() + bbox_ratio_vals[2] * (bounds_max[1] - bounds_min[1]).item(), + bounds_min[1].item() + bbox_ratio_vals[3] * (bounds_max[1] - bounds_min[1]).item(), + bounds_min[2].item() + bbox_ratio_vals[4] * (bounds_max[2] - bounds_min[2]).item(), + bounds_min[2].item() + bbox_ratio_vals[5] * (bounds_max[2] - bounds_min[2]).item(), + ] + bbox_desc = "ratio" + else: + logging.warning(" ⚠️ bbox mode did not provide a valid bbox, fallback to top_percent") + mode_used = "top_percent" + + if mode_used == "bbox" and bbox_vals is not None: + x0, x1 = sorted([bbox_vals[0], bbox_vals[1]]) + y0, y1 = sorted([bbox_vals[2], bbox_vals[3]]) + z0, z1 = sorted([bbox_vals[4], bbox_vals[5]]) + seat_nodes_mask = ( + (self.nodes[:, 0] >= x0) & (self.nodes[:, 0] <= x1) + & (self.nodes[:, 1] >= y0) & (self.nodes[:, 1] <= y1) + & (self.nodes[:, 2] >= z0) & (self.nodes[:, 2] <= z1) + ) + if seat_nodes_mask.sum().item() < 1: + logging.warning(" ⚠️ bbox region matched no nodes, fallback to top_percent") + mode_used = "top_percent" + else: + bbox_desc = f"{bbox_desc}: [{x0:.3f},{x1:.3f}]x[{y0:.3f},{y1:.3f}]x[{z0:.3f},{z1:.3f}]" + + if mode_used == "height_ratio": + y_min = y_coords.min().item() + y_max = y_coords.max().item() + y_range = max(1e-8, y_max - y_min) + min_ratio = float(self.config.seat_height_min_ratio) + max_ratio = float(self.config.seat_height_max_ratio) + if not (0.0 <= min_ratio < max_ratio <= 1.0): + logging.warning( + f" ⚠️ invalid height_ratio: min={min_ratio}, max={max_ratio}, fallback to top_percent" + ) + mode_used = "top_percent" + else: + seat_y_min = y_min + y_range * min_ratio + seat_y_max = y_min + y_range * max_ratio + seat_nodes_mask = (y_coords >= seat_y_min) & (y_coords <= seat_y_max) + if seat_nodes_mask.sum().item() < 1: + logging.warning(" ⚠️ height_ratio matched no nodes, fallback to top_percent") + mode_used = "top_percent" + + if mode_used == "top_percent": + top_percent = float(getattr(self.config, "force_top_percent", 0.05)) + top_percent = max(0.0, min(1.0, top_percent)) + if top_percent <= 0.0: + top_percent = 0.05 + num_seat_nodes = max(1, int(num_nodes * top_percent)) + _, top_indices = torch.topk(y_coords, k=num_seat_nodes, largest=True) + seat_nodes_mask = torch.zeros(num_nodes, dtype=torch.bool, device=self.device) + seat_nodes_mask[top_indices] = True + + num_seat_nodes = int(seat_nodes_mask.sum().item()) + + # Step 3: gather region statistics. + seat_y_values = y_coords[seat_nodes_mask] + seat_y_min = seat_y_values.min().item() + seat_y_max = seat_y_values.max().item() + seat_y_mean = seat_y_values.mean().item() + + # Step 4: computation the per-node load with uniform distribution. + force_per_node = self.total_force_preset / num_seat_nodes + + # Initialize all node forces to zero. + self.forces = torch.zeros((num_nodes, 3), dtype=torch.float32, device=self.device) + + # Apply force only to the selected seat/contact nodes. + self.forces[seat_nodes_mask] = force_per_node + + # Step 5: verify total-force conservation. + actual_total_force = self.forces.sum(dim=0) + force_error = torch.norm(actual_total_force - self.total_force_preset).item() + force_error_percent = (force_error / torch.norm(self.total_force_preset).item()) * 100 + + # Logging. + if initial_setup: + if mode_used == "bbox": + logging.info(f" 🪑 contact-surface setup: bbox ({bbox_desc})") + elif mode_used == "height_ratio": + logging.info( + f" 🪑 contact-surface setup: height_ratio " + f"[{self.config.seat_height_min_ratio:.2f}, {self.config.seat_height_max_ratio:.2f}]" + ) + else: + logging.info( + f" 🪑 contact-surface setup: highest-Y {float(getattr(self.config, 'force_top_percent', 0.05)):.1%} nodes" + ) + logging.info(f" 🪑 seat-node count: {num_seat_nodes}/{num_nodes} ({num_seat_nodes/num_nodes:.1%})") + logging.info(f" 🪑 Y-coordinate range: [{seat_y_min:.3f}, {seat_y_max:.3f}], mean: {seat_y_mean:.3f}") + logging.info(f" 💺 preset total force: {self.total_force_preset.cpu().numpy()}") + logging.info(f" 💺 force per node: {force_per_node.cpu().numpy()}") + logging.info(f" ✅ total-force check: {actual_total_force.cpu().numpy()} (error: {force_error:.2e}, {force_error_percent:.3f}%)") + + # Estimate the equivalent pressure. + y_range = y_coords.max().item() - y_coords.min().item() + grid_spacing = y_range / self.config.res if y_range > 0 else 0.01 + estimated_area = num_seat_nodes * (grid_spacing ** 2) + if estimated_area > 0 and abs(self.total_force_preset[1].item()) > 0: + pressure_kpa = abs(self.total_force_preset[1].item()) / estimated_area / 1000 + logging.info(f" 📏 equivalent pressure: {pressure_kpa:.1f} kPa (contact area≈{estimated_area:.4f} m²)") + + if pressure_kpa < 5: + logging.warning(f" ⚠️ pressure is too small ({pressure_kpa:.1f} kPa < 5 kPa)") + elif pressure_kpa > 50: + logging.warning(f" ⚠️ pressure is too large ({pressure_kpa:.1f} kPa > 50 kPa)") + + # Save visualization data. + self._save_force_visualization(seat_nodes_mask, self.total_force_preset.cpu().numpy()) + else: + # Shorter logging during optimization. + logging.debug(f" 🔄 force update: seat nodes {num_seat_nodes}, per node {force_per_node.cpu().numpy()}, " + f"total force error {force_error:.2e}") + + # Watch for changes in the number of loaded nodes. + if hasattr(self, '_last_num_seat_nodes') and self._last_num_seat_nodes != num_seat_nodes: + logging.info(f" ⚠️ seat-node count changed: {self._last_num_seat_nodes} → {num_seat_nodes}") + + # Cache the current state for the next comparison. + self._last_num_seat_nodes = num_seat_nodes + + def extract_solid(self, step: int = -1): + """Extract the physical solid by querying the node SDF directly. + + This method rebuilds the FEM mesh from the current latents so topology + changes in the SDF field can be reflected by the simulation mesh. + + Args: + step: Current optimization step, used for logging. + """ + if not WARP_AVAILABLE: + logging.warning("Warpnot installed, unable toperformphysics simulation") + return + + # Re-check physiopt availability at runtime. + try: + from physiopt.utils.phys_utils import generate_hex as _generate_hex + from physiopt.utils.grid_utils import filter_one_component as _filter_one_component + from physiopt.opt.field import occ_kernel as _occ_kernel + generate_hex_func = _generate_hex + filter_one_component_func = _filter_one_component + occ_kernel_func = _occ_kernel + logging.info("✅ physioptmoduleruntime check succeeded") + except ImportError as e: + logging.error(f"physioptmodulenot installed: {e}") + logging.error("please make sure physiopt is installed correctly: cd /mnt/cvlab/scratch/cvlab/home/hantzhan/physiopt && pip install -e .") + return + + res = self.config.res + step_label = f"Step {step}" if step >= 0 else "Initialization" + logging.info(f"{'🔄' if step >= 0 else '🆕'} [{step_label}] generate/update a mesh at resolution {res} hexahedral mesh...") + + # Keep the previous mesh size for comparison. + old_num_nodes = len(self.nodes) if hasattr(self, 'nodes') else 0 + old_num_elements = len(self.elements) if hasattr(self, 'elements') else 0 + + # 1. Generate the full hexahedral grid. + full_nodes, full_elements = generate_hex_func( + res=res, + limits=[(-0.8, 0.8), (-0.8, 0.8), (-0.8, 0.8)], + device=self.device, + return_coords=False + ) + + if full_nodes is None or full_elements is None: + logging.error("failed to generate the hexahedral mesh") + return + + full_nodes = full_nodes.to(self.device).float() + full_elements = full_elements.to(self.device).long() + + logging.info(f"hexahedral mesh generated successfully: {full_nodes.shape[0]}nodes, {full_elements.shape[0]}elements") + + # 2. Query the SDF directly through get_field. + logging.info("query node SDF values...") + sdf = self.get_field(full_nodes) + + # Make sure the SDF is a 1D tensor [N]. + if sdf.dim() > 1: + logging.warning(f"⚠️ SDFYesmulti-dimensional tensor: {sdf.shape}, will be flattened to 1D") + sdf = sdf.squeeze() # remove all size-1 dimensions + if sdf.dim() > 1: + sdf = sdf.reshape(-1) # force-flatten to 1D + + logging.info(f" ✅ SDF query succeeded: range=[{sdf.min():.3f}, {sdf.max():.3f}]") + logging.info(f" nodescount: {full_nodes.shape[0]}, SDF count: {sdf.shape[0]}") + + # Verify that the SDF count matches the node count. + if sdf.shape[0] != full_nodes.shape[0]: + logging.error(f"❌ SDF count({sdf.shape[0]}) vs. node count ({full_nodes.shape[0]})do not match!") + return + + # 3. Convert SDF values to occupancy. + logging.info("convert the SDF into an occupancy field...") + occ = occ_kernel_func(sdf, res, self.config.occ_sdf_beta) + + # 4. Select solid elements using an SDF threshold instead of an + # occupancy threshold. The threshold is intentionally relaxed so thin + # structures such as chair legs are kept. + SDF_FILTER_VALUE = 2.0 / res + nodewise_mask = sdf <= SDF_FILTER_VALUE + + # Diagnostic SDF statistics. + sdf_inside = sdf[nodewise_mask] + sdf_outside = sdf[~nodewise_mask] + logging.info(f" SDF threshold: {SDF_FILTER_VALUE:.4f}") + logging.info(f" interior nodes: {nodewise_mask.sum().item()}/{len(sdf)} ({100*nodewise_mask.sum().item()/len(sdf):.1f}%)") + if len(sdf_inside) > 0: + logging.info(f" inner SDF range: [{sdf_inside.min():.4f}, {sdf_inside.max():.4f}]") + if len(sdf_outside) > 0: + logging.info(f" outside-SDF range: [{sdf_outside.min():.4f}, {sdf_outside.max():.4f}]") + + # Debug the element-index range. + max_elem_idx = full_elements.max().item() + num_nodes = full_nodes.shape[0] + logging.info(f" elementsindex range: [0, {max_elem_idx}], nodescount: {num_nodes}") + + if max_elem_idx >= num_nodes: + logging.error(f"❌ index out of bounds!maximum element index({max_elem_idx}) >= nodescount({num_nodes})") + logging.error(f" this may be a problem with generate_hex") + # Clamp indices to the valid range. + valid_mask = (full_elements >= 0) & (full_elements < num_nodes) + if not valid_mask.all(): + logging.warning(f" found{(~valid_mask).sum().item()} invalid indices; filtering elements") + # Keep only elements whose node indices are all valid. + valid_elements_mask = valid_mask.all(dim=1) + full_elements = full_elements[valid_elements_mask] + logging.info(f" element count after filtering: {full_elements.shape[0]}") + + # Keep an element if any of its nodes passes the threshold. + elementwise_mask = torch.any(nodewise_mask[full_elements], dim=1) + + num_solid_elements = elementwise_mask.sum().item() + logging.info(f"SDF thresholdfiltering: {num_solid_elements}/{len(elementwise_mask)} solid elements") + + if num_solid_elements == 0: + logging.error("No solid elements were found; please check the SDF or adjust the threshold") + return + + # 5. Optionally keep only one connected component. + if self.config.one_cc_only: + element_res = res - 1 + try: + num_before_filter = elementwise_mask.sum().item() + elementwise_mask = filter_one_component_func(elementwise_mask, element_res) + num_filtered_elements = elementwise_mask.sum().item() + num_removed = num_before_filter - num_filtered_elements + logging.info(f"connectivity filtering: {num_filtered_elements} elements kept (removed{num_removed} small components)") + if num_removed > num_filtered_elements * 0.1: + logging.warning(f" ⚠️ removed{num_removed}elements({100*num_removed/num_before_filter:.1f}%), may have filtered out important parts (such as chair legs) ") + logging.warning(f" Suggestion: check the SDF threshold or consider disabling one_cc_only") + except IndexError as e: + logging.warning(f"connectivity filteringfailed: {e}, using the original mask") + else: + logging.info("connectivity filteringdisabled, keep all connected components") + + # 6. Select the active elements and nodes. + selected_elements = full_elements[elementwise_mask] + selected_node_indices, selected_elements = torch.unique( + selected_elements, return_inverse=True + ) + + self.elements = selected_elements + self.nodes = full_nodes[selected_node_indices] + + # 7. Compute occupancy for the selected nodes used in the simulation. + coarse_sdf = sdf[selected_node_indices] + coarse_occ_nodes = occ_kernel_func( + coarse_sdf, self.config.res, self.config.occ_sdf_beta + ) + # Each element occupancy is the mean over its 8 nodes. + self.coarse_occ = coarse_occ_nodes[self.elements].mean(1) + + # Diagnostic statistics for mesh-size changes. + new_num_nodes = len(self.nodes) + new_num_elements = len(self.elements) + + if old_num_nodes > 0: + node_change = new_num_nodes - old_num_nodes + element_change = new_num_elements - old_num_elements + node_change_pct = (node_change / old_num_nodes) * 100 + element_change_pct = (element_change / old_num_elements) * 100 + + logging.info(f"✅ solid extraction completed:") + logging.info(f" nodes: {old_num_nodes} → {new_num_nodes} ({node_change:+d}, {node_change_pct:+.1f}%)") + logging.info(f" elements: {old_num_elements} → {new_num_elements} ({element_change:+d}, {element_change_pct:+.1f}%)") + + if node_change > 0: + logging.info(f" ✅ mesh expanded!added{node_change}nodes (chair legs may have thickened) ") + elif node_change < 0: + logging.warning(f" ⚠️ mesh shrank!removed{-node_change}nodes (chair legs may have become thinner) ") + else: + logging.info(f"✅ solid extraction succeeded: {new_num_nodes}nodes, {new_num_elements}elements") + + # 8. Recomputation the boundary mask because the node count may change. + y_coords = self.nodes[:, 1] + y_min = y_coords.min() + boundary_threshold = y_min + 0.05 # bottom 5% region + self.boundary_mask = y_coords < boundary_threshold + + num_boundary = self.boundary_mask.sum().item() + logging.debug(f" 🔧 boundary conditionsupdated: {num_boundary}fixed nodes (Y < {boundary_threshold:.3f})") + + def get_current_sds_weight(self, step: int) -> float: + """Return the current SDS weight by linear interpolation. + + Args: + step: Current optimization step. + + Returns: + The SDS weight interpolated from sds_weight_start to sds_weight_end. + """ + # Linear interpolation from sds_weight_start to sds_weight_end. + progress = min(1.0, step / max(1, self.config.num_steps - 1)) + current_weight = self.config.sds_weight_start + progress * (self.config.sds_weight_end - self.config.sds_weight_start) + return current_weight + + def _computation_target_z0_current(self, step: int) -> Tuple[torch.Tensor, torch.Tensor]: + """Compute the current target_z0 for one update.""" + noise_level = float(self.config.sds_timestep) + t = 1.0 - noise_level # Hunyuan3D-2.1 uses t=0 for noise and t=1 for data. + epsilon = torch.randn_like(self.latents) + + self.sds_scheduler.config.num_train_timesteps = 100 + if self.sds_scheduler is not None: + # Match the official Flow Matching noise process: + # x_t = (1 - sigma) * x0 + sigma * eps. + sigma_step = 1.0 / float(self.sds_scheduler.config.num_train_timesteps) + total_span = max(0.0, 1.0 - t) + num_steps = int(np.ceil(total_span / sigma_step)) + sigmas = np.linspace(t, 1.0, num_steps + 1, dtype=np.float32) + self.sds_scheduler.set_timesteps(sigmas=sigmas, device=self.device) + t_scheds = self.sds_scheduler.timesteps + t_sched0 = t_scheds[0] + t_model0 = (t_sched0 / self.sds_scheduler.config.num_train_timesteps).to(self.latents.dtype) + if step % max(1, int(self.config.sds_target_z0_update_interval)) == 0: + logging.info( + f" 🎯 target_z0/sigmaalign: noise={noise_level:.4f}, t_start={t:.4f}, " + f"t_sched={t_sched0.item():.2f}, t_model={t_model0.item():.6f}, " + f"steps={num_steps}, sigma_step={sigma_step:.4g}" + ) + else: + t_sched = None + z_t = (1 - t) * epsilon + t * self.latents + t_model = torch.tensor([t], device=self.device, dtype=self.latents.dtype) + + with torch.no_grad(): + if self.sds_scheduler is not None: + # Integrate over multiple small sigma steps from sigma=t to 0. + cond_for_model = self._get_cond_for_guidance(self.config.guidance_scale > 1.0) + t_sched0 = t_scheds[0] + t_sched_batch = t_sched0.reshape(1).expand(self.latents.shape[0]) + # Hunyuan3D convention: t=0 is noise and t=1 is data. + z_t = self.sds_scheduler.scale_noise(epsilon, t_sched_batch, noise=self.latents) + + z_curr = z_t + velocity = None + for i in range(len(t_scheds) - 1): + t_sched = t_scheds[i] + t_model = (t_sched / self.sds_scheduler.config.num_train_timesteps).to(self.latents.dtype) + z_t_fp16 = z_curr.to(torch.float16) + t_tensor = t_model.to(device=self.device, dtype=z_t_fp16.dtype) + + if self.config.guidance_scale > 1.0: + latent_model_input = torch.cat([z_t_fp16, z_t_fp16]) + timestep_input = t_tensor.expand(latent_model_input.shape[0]) + + velocity_pred_fp16 = self.flow_model( + latent_model_input, + timestep_input, + cond_for_model, + guidance=None, + ) + + velocity_cond_fp16, velocity_uncond_fp16 = velocity_pred_fp16.chunk(2) + velocity_fp16 = velocity_uncond_fp16 + self.config.guidance_scale * (velocity_cond_fp16 - velocity_uncond_fp16) + + if step % 10 == 0 and i == 0: + logging.debug( + f" CFG (SDS): guidance_scale={self.config.guidance_scale:.1f}, " + f"||v_cond||={torch.norm(velocity_cond_fp16).item():.3e}, " + f"||v_uncond||={torch.norm(velocity_uncond_fp16).item():.3e}" + ) + else: + velocity_fp16 = self.flow_model( + z_t_fp16, + t_tensor.expand(z_t_fp16.shape[0]), + cond_for_model, + guidance=None, + ) + + velocity = velocity_fp16.to(torch.float32) + z_curr = self.sds_scheduler.step(velocity, t_sched, z_curr).prev_sample + + target_z0_current = z_curr + else: + cond_for_model = self._get_cond_for_guidance(self.config.guidance_scale > 1.0) + z_t_fp16 = z_t.to(torch.float16) + t_tensor = t_model.to(device=self.device, dtype=z_t_fp16.dtype) + + if self.config.guidance_scale > 1.0: + latent_model_input = torch.cat([z_t_fp16, z_t_fp16]) + timestep_input = t_tensor.expand(latent_model_input.shape[0]) + + velocity_pred_fp16 = self.flow_model( + latent_model_input, + timestep_input, + cond_for_model, + guidance=None, + ) + + velocity_cond_fp16, velocity_uncond_fp16 = velocity_pred_fp16.chunk(2) + velocity_fp16 = velocity_uncond_fp16 + self.config.guidance_scale * (velocity_cond_fp16 - velocity_uncond_fp16) + + if step % 10 == 0: + logging.debug( + f" CFG (SDS): guidance_scale={self.config.guidance_scale:.1f}, " + f"||v_cond||={torch.norm(velocity_cond_fp16).item():.3e}, " + f"||v_uncond||={torch.norm(velocity_uncond_fp16).item():.3e}" + ) + else: + velocity_fp16 = self.flow_model( + z_t_fp16, + t_tensor.expand(z_t_fp16.shape[0]), + cond_for_model, + guidance=None, + ) + + velocity = velocity_fp16.to(torch.float32) + # Fallback: one forward-Euler step to t=1. + target_z0_current = z_t + (1.0 - t) * velocity + + # Optional trust region to keep target_z0 from moving too far away. + max_rel = float(getattr(self.config, "sds_projection_max_rel", 0.0)) + if max_rel > 0.0: + with torch.no_grad(): + diff = target_z0_current - self.latents + diff_norm = torch.norm(diff).item() + latents_norm = torch.norm(self.latents).item() + max_norm = max_rel * (latents_norm + 1e-8) + if diff_norm > max_norm and max_norm > 0.0: + scale = max_norm / (diff_norm + 1e-8) + target_z0_current = self.latents + diff * scale + if step % max(1, int(self.config.sds_target_z0_update_interval)) == 0: + logging.info( + f" 🧱 target_z0 projection limit: diff={diff_norm:.3e} → {max_norm:.3e} " + f"(rel={max_rel:.2f})" + ) + return target_z0_current, velocity + + def _get_target_z0(self, step: int) -> Tuple[torch.Tensor, Optional[torch.Tensor], bool]: + """Update target_z0 on schedule and smooth it with EMA.""" + update_interval = max(1, int(self.config.sds_target_z0_update_interval)) + do_update = self.target_z0_ema is None or step % update_interval == 0 + + if do_update: + target_z0_current, velocity = self._computation_target_z0_current(step) + target_z0_current = target_z0_current.detach() + + if self.target_z0_ema is None: + self.target_z0_ema = target_z0_current.clone() + diff_norm = 0.0 + else: + diff = target_z0_current - self.target_z0_ema + diff_norm = torch.norm(diff).item() + alpha = 1.0 - self.config.sds_target_z0_ema_beta + self.target_z0_ema = self.target_z0_ema + alpha * diff + + self.target_z0_last_velocity = velocity + self.target_z0_last_update = step + + if step % update_interval == 0: + logging.info( + f" 🧭 target_z0 EMAupdate: interval={update_interval}, " + f"beta={self.config.sds_target_z0_ema_beta:.2f}, diff_norm={diff_norm:.3e}" + ) + else: + velocity = self.target_z0_last_velocity + + return self.target_z0_ema, velocity, do_update + + def project_to_manifold(self, step: int) -> bool: + """Project the current latents back to the manifold by replacing them with target_z0.""" + with torch.no_grad(): + target_z0, _ = self._computation_target_z0_current(step) + if torch.isnan(target_z0).any() or torch.isinf(target_z0).any(): + logging.warning(" ⚠️ projection failed: target_z0 contains NaN/Inf") + return False + deviation = torch.norm(target_z0 - self.latents).item() + latents_norm = torch.norm(self.latents).item() + rel = deviation / (latents_norm + 1e-8) + logging.info(f" 🧭 projection deviation: {deviation:.3e} (rel={rel:.2%})") + self.latents.data.copy_(target_z0) + if self.latents.grad is not None: + self.latents.grad.zero_() + # Reset optimizer state to avoid stale momentum. + self.optimizer.state.clear() + # Sync the EMA cache with the projected state. + self.target_z0_ema = target_z0.detach().clone() + self.target_z0_last_velocity = None + self.target_z0_last_update = step + return True + + def training_step_sds(self, step: int) -> Tuple[float]: + """Run one SDS optimization step. + + Returns: + (recon_loss,) + """ + self.optimizer.zero_grad() + + # ==================== SDS loss (Rectified Flow) ==================== + t = self.config.sds_timestep + target_z0, velocity, _ = self._get_target_z0(step) + + # SDS gradient: grad = z_0 - target_z0. + # This pulls the current z_0 (self.latents) toward target_z0. + sds_gradient = self.latents - target_z0.detach() + recon_loss = torch.mean(sds_gradient ** 2) / 2 + + # Debug information. + with torch.no_grad(): + target_norm = torch.norm(target_z0).item() + current_norm = torch.norm(self.latents).item() + grad_norm = torch.norm(sds_gradient).item() + velocity_norm = torch.norm(velocity).item() if velocity is not None else 0.0 + + logging.info(f"📐 Step {step:3d} | SDS: ||z_0||={current_norm:.2e}, " + f"||target_z_0||={target_norm:.2e}, " + f"||v||={velocity_norm:.2e}, " + f"||∇||={grad_norm:.2e}, t={t:.2f}, loss={recon_loss.item():.6e}") + + # Backpropagation. + sds_gradient_scaled = self.config.sds_weight * sds_gradient + + # Guard against invalid gradients. + if torch.isnan(sds_gradient_scaled).any() or torch.isinf(sds_gradient_scaled).any(): + logging.error(f"❌ Error: SDS gradient contains NaN or Inf!") + logging.error(f" ||sds_gradient||: {grad_norm:.2e}") + logging.error(f" sds_weight: {self.config.sds_weight}") + logging.error(f" target_z0 range: [{target_z0.min().item():.2e}, {target_z0.max().item():.2e}]") + logging.error(f" latents range: [{self.latents.min().item():.2e}, {self.latents.max().item():.2e}]") + if velocity is not None: + logging.error(f" velocity range: [{velocity.min().item():.2e}, {velocity.max().item():.2e}]") + return (recon_loss.item(),) + + if self.latents.grad is not None: + self.latents.grad.zero_() + + self.latents.grad = sds_gradient_scaled + + # Optional gradient clipping. + if self.config.grad_clip_enabled: + grad_norm_total = torch.norm(self.latents.grad).item() + max_grad_norm = 100.0 # 1e5lower to100 + if grad_norm_total > max_grad_norm: + clip_factor = max_grad_norm / grad_norm_total + self.latents.grad *= clip_factor + logging.warning(f"⚠️ gradient clipping: {grad_norm_total:.4e} -> {max_grad_norm:.4e}") + + # Save the pre-update latents for diagnostics. + old_latents = self.latents.data.clone() + + # Re-check the gradient before the optimizer step. + if torch.isnan(self.latents.grad).any(): + logging.error(f"❌ Error: gradient contains NaN (optimizerupdatefront) !") + return (recon_loss.item(),) + + # Optimizer update. + self.optimizer.step() + + # Measure parameter change after the update. + param_change = torch.norm(self.latents.data - old_latents).item() + + # Validate the updated latents. + if torch.isnan(self.latents).any(): + logging.error(f"❌ Error: latents contain NaN (optimizerupdateback) !") + logging.error(f" gradient norm: {grad_norm_total:.4e}") + logging.error(f" Learning rate: {self.config.lr}") + logging.error(f" Param change: {param_change:.4e}") + logging.error(f" suggestion: this may be caused by Adam optimizer momentum") + logging.error(f" : 1) reset optimizer 2) Use SGD instead of Adam") + # Restore the previous value. + self.latents.data.copy_(old_latents) + # Clear optimizer momentum/state before retrying. + self.optimizer.state.clear() + logging.info(f" ✅ already reset optimizerStatus, will retry on the next step") + return (recon_loss.item(),) + + # Sanity-check the latent magnitude. + latents_max = torch.abs(self.latents).max().item() + if latents_max > 1000: + logging.warning(f"⚠️ warning: latent values are too large (max={latents_max:.2e})") + logging.warning(f" you may need to lower the learning rate or SDS timestep") + + logging.info(f"✏️ Step {step:3d} | Param change: {param_change:.4e}, max|z|: {latents_max:.2e}") + + return (recon_loss.item(),) + + def training_step( + self, + step: int, + lagrange: float, + rho: float, + use_sds: bool = True, + save_step: Optional[int] = None, + ) -> Tuple[float, float, float]: + """Physics optimization. + + This follows the computation_phys_loss_grad flow from viewer_base.py: + 1. optimizer.zero_grad() + 2. with torch.no_grad(): prepare_solid() + solve() + 3. Compute sensitivities with the reference-style formula + 4. backward_step() via VJP + 5. Apply ALM weighting (lambda + rho[g]_+) + 6. optimizer.step() + + Reference: + physiopt/src/physiopt/vis/viewer_base.py Line 1297-1430 + """ + save_step_id = step if save_step is None else int(save_step) + + # ==================== Step 1: zero gradients ==================== + self.optimizer.zero_grad() + + # ==================== Step 2: update occupancy on the fixed topology ==================== + if step > 0: + logging.info(f"🔄 [Step {step}] update occupancy (mesh topology fixed) ...") + # Keep the previous occupancy for diagnostics. + old_occ = self.coarse_occ.clone() + + # Re-query the SDF and occupancy on the fixed mesh. + sdf = self.get_field(self.nodes) + from physiopt.opt.field import occ_kernel + occ = occ_kernel(sdf, self.config.res, self.config.occ_sdf_beta) + self.coarse_occ = occ[self.elements].mean(1) + + # Diagnose occupancy changes. + occ_change = self.coarse_occ - old_occ + occ_mean_change = occ_change.mean().item() + occ_increase_ratio = (occ_change > 0).float().mean().item() + + logging.info(f" occupancy range: [{self.coarse_occ.min():.3f}, {self.coarse_occ.max():.3f}]") + logging.info(f" occupancy change: mean={occ_mean_change:+.3e}, increase ratio={occ_increase_ratio:.1%}") + + # ==================== Step 3: physics simulation (with torch.no_grad) ==================== + # Aligned with the reference flow around Line 1317-1356. + with torch.no_grad(): + # 3.1 prepare_solid: apply SIMP scaling and build SolidGrid. + if self.config.alpha_min > 0.0: + self.coarse_occ = torch.clamp(self.coarse_occ, self.config.alpha_min) + + # Material SIMP scaling. + from torchfem.materials import IsotropicElasticity3D + from physiopt.opt.solid_grid import SolidGrid + + vectorized_material = IsotropicElasticity3D( + E=self.config.youngs_modulus, + nu=self.config.poissons_ratio, + rho=self.config.density, + ).vectorize(self.elements.shape[0]) + + vectorized_material.C *= ( + self.coarse_occ[:, None, None] ** self.config.p_exponent + ) + + # Create the SolidGrid solver state. + solid = SolidGrid(self.nodes, self.elements, vectorized_material) + solid.constraints[self.boundary_mask, :] = True + solid.forces = self.forces + + # 3.2 FEM solve. + logging.info(f"Step {step}: FEM solve...") + u, f_int, f_ext, sigma, _, _ = solid.solve(max_iter=1) + u_mean = torch.abs(u).mean().item() + logging.info(f" |u|_mean={u_mean}") + self._log_physical_quantities(u, sigma) + + # Save the deformed mesh every N steps. + # if self.config.deformed_mesh_interval > 0 and save_step_id % self.config.deformed_mesh_interval == 0: + # try: + # self.save_deformed_mesh(save_step_id, u) + # except Exception as e: + # logging.warning(f" ⚠️ error while saving the deformed mesh: {e}") + + # ==================== Step 4: sensitivity computation ==================== + # Strictly aligned with the reference flow around Line 1368-1399. + + # 4.1 Compute strain energy. We recover the unweighted energy by + # dividing out occ^p and keep strong numerical guards. + k0 = solid.k0() # occ^p * K_base after stiffness scaling. + u_j = u[self.elements].reshape(solid.n_elem, -1) + w_k_scaled = torch.einsum("...i, ...ij, ...j", u_j, k0, u_j) + + # Remove occ^p scaling to recover the base energy. + occ_power = torch.clamp( + self.coarse_occ ** self.config.p_exponent, + min=1e-6, # Avoid division by zero. + max=1.0 # Avoid overflow. + ) + + # Check again before division. + if torch.any(occ_power < 1e-6): + n_small = (occ_power < 1e-6).sum().item() + logging.warning(f" ⚠️ {n_small} elements have extremely small occ^p and were clamped to 1e-6") + + w_k_base = w_k_scaled / occ_power + + # Fall back if the recovered energy becomes invalid. + if torch.isnan(w_k_base).any() or torch.isinf(w_k_base).any(): + n_nan = torch.isnan(w_k_base).sum().item() + n_inf = torch.isinf(w_k_base).sum().item() + logging.error(f" ❌ w_k_baseabnormal: {n_nan} NaN, {n_inf} Inf") + logging.error(f" fall back to SIMP weightingw_k") + w_k_base = w_k_scaled + + # Use the recovered energy downstream. + compliance_mean = w_k_base.mean().item() + w_k = w_k_base # Downstream sensitivity uses the recovered energy. + + # Diagnostics. + logging.info(f" Compliance (true) ={compliance_mean:.2e}") + logging.info(f" w_k_base: max={w_k.max():.2e}, stress concentration={w_k.max()/(w_k.mean() + 1e-10):.1f}x") + + # ALM normalized constraint: g = D / D_thr - 1. + compliance_threshold = self.config.compliance_threshold if self.config.compliance_threshold is not None else 1.0 + g_raw = compliance_mean / (compliance_threshold + 1e-8) - 1.0 + g_pos = max(0.0, g_raw) + logging.info(f" constraint normalization: g={g_raw:+.3e}, [g]+={g_pos:.3e}, D_thr={compliance_threshold:.2e}") + + # Dynamic clip limit used by the ALM scaling guard. + base_max_grad = 1000.0 + lagrange_bonus = min((lagrange + rho * g_pos) * 10.0, 1000.0) + max_grad_norm = base_max_grad + lagrange_bonus + + # 4.3 Sensitivity formula aligned with the reference code: + # sensitivity = -p * occ^(p-1) * w_k + self.sensitivity_density = ( + -self.config.p_exponent + * self.coarse_occ ** (self.config.p_exponent - 1) + * w_k + ) + + # 4.4 Volume regularization is intentionally disabled here so the pure + # physics signal can be validated first. + if False and self.config.volume_term > 0.0: # Temporarily forced off. + # Initialize the reference volume on first use. + if not hasattr(self, 'init_volume'): + self.init_volume = self.coarse_occ.clone() + logging.info(f" record initial volume: sum={self.init_volume.sum().item():.2f}") + + # Volume sensitivity term. + sensitivity_volume = ( + self.config.volume_term + * (1.0 / self.config.res) ** 3 + * torch.ones_like(self.sensitivity_density) + ) + + # Choose the sign from the current volume change. + volume_sign = 1.0 if self.coarse_occ.sum() >= self.init_volume.sum() else -1.0 + sensitivity_volume *= volume_sign + + self.sensitivity_density += sensitivity_volume + + volume_ratio = self.coarse_occ.sum() / self.init_volume.sum() + logging.info(f" volume constraint: ratio={volume_ratio.item():.3f}, " + f"{'penalize' if volume_sign > 0 else 'encourage'}") + else: + logging.info(f" volume constraint: disabled (physicsoptimizationdominates) ") + + # Sensitivity diagnostics. + sens_norm = torch.norm(self.sensitivity_density).item() + sens_min = self.sensitivity_density.min().item() + sens_max = self.sensitivity_density.max().item() + logging.info(f" sensitivity: norm={sens_norm:.2e}, range=[{sens_min:.2e}, {sens_max:.2e}]") + + # ==================== Step 5: backward pass via VJP ==================== + self.backward_step(self.sensitivity_density) + + # ==================== Step 6: apply ALM weighting (lambda + rho[g]+) ==================== + if self.latents.grad is not None: + phys_grad_norm = torch.norm(self.latents.grad).item() + phys_grad_unscaled = self.latents.grad.clone() # Unscaled physics gradient for SDS comparisons. + + if g_pos > 0.0: + alm_scale_raw = (lagrange + rho * g_pos) / (compliance_threshold + 1e-8) + alm_scale = alm_scale_raw + guard_ratio = min(max(self.config.alm_scale_guard_ratio, 0.0), 1.0) + if phys_grad_norm > 0.0 and max_grad_norm > 0.0 and guard_ratio > 0.0: + alm_scale_guard = (max_grad_norm * guard_ratio) / (phys_grad_norm + 1e-8) + if alm_scale > alm_scale_guard: + logging.info( + f" 🔧 ALMscaling limit: raw={alm_scale_raw:.3e} -> {alm_scale_guard:.3e} " + f"(guard={guard_ratio:.2f}, max_grad={max_grad_norm:.1f})" + ) + alm_scale = alm_scale_guard + self.latents.grad *= alm_scale + else: + alm_scale = 0.0 + self.latents.grad.zero_() + + scaled_grad_norm = torch.norm(self.latents.grad).item() + logging.info( + f" physics gradient(ALM): {phys_grad_norm:.2e} → {scaled_grad_norm:.2e} " + f"(×scale={alm_scale:.3e}, λ={lagrange:.2f}, ρ={rho:.2f})" + ) + else: + phys_grad_unscaled = None + alm_scale = 0.0 + + # ==================== Step 7: shape loss toward target_z0 ==================== + + # 7.1 Compute the denoised target_z0. + import math + if use_sds: + target_z0, _, _ = self._get_target_z0(step) + else: + target_z0 = self.latents.detach() + + # Optionally validate and save a target_z0 mesh every 10 steps. + if use_sds: + self._maybe_save_target_z0_mesh(target_z0, save_step_id) + + # Shape loss is a simple MSE pulling latents toward target_z0. + shape_loss = torch.nn.functional.mse_loss(self.latents, target_z0.detach()) + + # 7.2 Decide whether shape loss is active this step. + current_sds_weight = self.get_current_sds_weight(step) if use_sds else 0.0 + use_sds_this_step = current_sds_weight > 0.0 + + if not use_sds_this_step: + logging.info(f" 🚫 Shape Loss disabled (physicsoptimizationmode) ") + weighted_sds = 0.0 + shape_grad_norm = 0.0 + else: + # Weighted shape loss. + weighted_shape_loss = current_sds_weight * shape_loss + + # Validate shape loss before backpropagating it. + if torch.isnan(shape_loss) or torch.isinf(shape_loss): + logging.error(f" ❌ Shape Loss contains NaN or Inf; skipping the shape constraint") + weighted_sds = 0.0 + shape_grad_norm = 0.0 + else: + # Backpropagate the shape loss into latents.grad. + weighted_shape_loss.backward() + + # Measure the shape-gradient norm for logging. + if self.latents.grad is not None and phys_grad_unscaled is not None: + # Isolate the shape part from the combined gradient. + shape_gradient = self.latents.grad - phys_grad_unscaled * alm_scale + shape_grad_norm = torch.norm(shape_gradient).item() + phys_grad_norm_current = torch.norm(phys_grad_unscaled * alm_scale).item() + shape_phys_ratio = shape_grad_norm / (phys_grad_norm_current + 1e-10) + + if shape_phys_ratio > 100.0: + logging.error(f" ❌ Shape gradient is too large (Shape/physics={shape_phys_ratio:.1f}x)!") + logging.error(f" consider lowering sds_weight_end: {self.config.sds_weight_end} → {self.config.sds_weight_end/100:.4f}") + elif shape_phys_ratio > 10.0: + logging.warning(f" ⚠️ Shape gradient is relatively large (Shape/physics={shape_phys_ratio:.1f}x)") + + # Compare the directions of physics and shape gradients. + cos_angle = (phys_grad_unscaled * shape_gradient).sum() / ( + torch.norm(phys_grad_unscaled) * torch.norm(shape_gradient) + 1e-10 + ) + angle_deg = torch.acos(torch.clamp(cos_angle, -1, 1)) * 180 / math.pi + direction = "same direction✅" if angle_deg < 90 else "opposite direction⚠️" + + logging.info(f" Shapegradient: norm={shape_grad_norm:.4e}, weight={current_sds_weight:.6f}") + logging.info(f" gradient direction: physics vs Shape = {angle_deg:.1f}° ({direction})") + elif self.latents.grad is not None: + shape_grad_norm = torch.norm(self.latents.grad).item() + logging.info(f" Shapegradient: norm={shape_grad_norm:.4e} (no physics gradient)") + else: + shape_grad_norm = 0.0 + + weighted_sds = weighted_shape_loss.item() + + # ==================== Step 8: combine losses and clip if needed ==================== + compliance_loss_item = compliance_mean + alm_penalty = lagrange * g_pos + 0.5 * rho * (g_pos ** 2) + total_loss = alm_penalty + weighted_sds + + # Log the combined loss terms. + if use_sds_this_step: + logging.info( + f" 📊 weighted loss: Compliance={compliance_loss_item:.4e}, g={g_raw:+.3e}, " + f"ALM={alm_penalty:.4e} (λ={lagrange:.2f}, ρ={rho:.2f}), " + f"Shape={weighted_sds:.4e} (×w={current_sds_weight:.6f}), Total={total_loss:.4e}" + ) + else: + logging.info( + f" 📊 weighted loss: Compliance={compliance_loss_item:.4e}, g={g_raw:+.3e}, " + f"ALM={alm_penalty:.4e} (λ={lagrange:.2f}, ρ={rho:.2f}), " + f"Shape=0.00e+00 (disabled), Total={total_loss:.4e}" + ) + + # Log gradient composition details. + if self.latents.grad is not None: + grad_norm = torch.norm(self.latents.grad).item() + + # Report each gradient contribution. + if phys_grad_unscaled is not None: + weighted_phys_grad_norm = torch.norm(phys_grad_unscaled * alm_scale).item() + logging.info(f" 🔍 gradient composition: Weighted Compliance Grad={weighted_phys_grad_norm:.4e} (ALM scale={alm_scale:.3e})") + + if use_sds_this_step and shape_grad_norm > 0: + logging.info(f" Scaled Shape Grad={shape_grad_norm:.4e} (Shape×w={current_sds_weight:.6f})") + if phys_grad_unscaled is not None: + grad_ratio = shape_grad_norm / (weighted_phys_grad_norm + 1e-10) + logging.info(f" ratio: Shape/Compliance = {grad_ratio:.4f} ({grad_ratio*100:.2f}%)") + + logging.info(f" Total Grad={grad_norm:.4e}") + + # Optional gradient clipping. + if self.latents.grad is not None: + grad_norm = torch.norm(self.latents.grad).item() + + if torch.isnan(self.latents.grad).any() or torch.isinf(self.latents.grad).any(): + logging.error(f"❌ the final gradient contains NaN or Inf!skip this steps") + return (compliance_loss_item, u_mean, shape_loss.item(), total_loss) + + if self.config.grad_clip_enabled: + if grad_norm > max_grad_norm: + clip_factor = max_grad_norm / grad_norm + self.latents.grad = self.latents.grad * clip_factor + logging.info(f" ✂️ gradient clipping: {grad_norm:.4e} -> {max_grad_norm:.1f} (×{clip_factor:.3f})") + else: + logging.info(f" ✅ gradient not clipped: {grad_norm:.4e} (max={max_grad_norm:.1f})") + + # ==================== Step 9: optimizer step ==================== + + # Save the previous latents for diagnostics. + old_latents = self.latents.data.clone() + + self.optimizer.step() + + # Diagnose latent changes after the optimizer step. + with torch.no_grad(): + latents_change = torch.norm(self.latents.data - old_latents).item() + latents_norm = torch.norm(old_latents).item() + latents_change_percent = (latents_change / (latents_norm + 1e-10)) * 100 + max_latents_change = torch.abs(self.latents.data - old_latents).max().item() + + logging.info(f" 🔄 Latentschange: L2={latents_change:.4e} ({latents_change_percent:.3f}%), max={max_latents_change:.4e}") + + if latents_change < 1e-6: + logging.warning(f" ⚠️ latents almost did not change!the learning rate may be too small or the gradient may be too weak") + + # Return the scalar loss values. + return (compliance_loss_item, u_mean, shape_loss.item(), total_loss) + + def save_mesh(self, step: int, output_dir: str = "results/hunyuan_meshes", high_quality: bool = False, suffix="step"): + """Save frontlatentsmesh + + Args: + step: front steps + output_dir: outputdirectory + high_quality: YesNouse (Resolution) , Trueuse256resolution + """ + os.makedirs(output_dir, exist_ok=True) + + try: + # finalSave use256resolution, Stepuse128resolution + octree_res = 256 if high_quality else 128 + mesh = self.latents_to_mesh(self.latents, octree_res=octree_res) + if mesh is None: + logging.warning(f" ⚠️ warning: Step {step} - Marching cubesno surface found, skipSave ") + return + + # finalSave filterfloating + if high_quality: + mesh = self._filter_floating_components(mesh) + + mesh_path = os.path.join(output_dir, f"{suffix}_{step:04d}.obj") + mesh.export(mesh_path) + quality_label = "256resolution" if high_quality else "128resolution" + logging.info(f" 💾 Save mesh ({quality_label}): {mesh_path}") + except Exception as e: + logging.warning(f" ⚠️ warning: Step {step} - Save meshfailed: {e}") + + + def _maybe_save_target_z0_mesh(self, target_z0: torch.Tensor, step_id: int, force: bool = False): + """Save a mesh decoded from target_z0 for diagnostics.""" + if (not force) and (step_id % 10 != 0): + return + + with torch.no_grad(): + deviation = torch.norm(target_z0 - self.latents).item() + latents_norm = torch.norm(self.latents).item() + relative_deviation = deviation / (latents_norm + 1e-8) + + if relative_deviation > 0.5: + logging.warning( + f" ⚠️ target_z0 deviation is too large: {relative_deviation:.1%} " + f"(||target_z0 - latents||={deviation:.3e}, ||latents||={latents_norm:.3e})" + ) + logging.warning(f" thismaySave target meshshape is abnormal") + + try: + target_norm = torch.norm(target_z0).item() + target_max = torch.abs(target_z0).max().item() + target_has_nan = torch.isnan(target_z0).any().item() + target_has_inf = torch.isinf(target_z0).any().item() + + # Save only when target_z0 looks numerically healthy. + if (not target_has_nan and not target_has_inf and + target_max < 100.0 and relative_deviation < 1.0): + target_z0_clean = target_z0.detach().clone() + + logging.info(f" 📊 target_z0 statistics:") + logging.info(f" - shape: {target_z0_clean.shape}") + logging.info(f" - range: [{target_z0_clean.min():.3e}, {target_z0_clean.max():.3e}]") + logging.info(f" - mean: {target_z0_clean.mean():.3e}, Std: {target_z0_clean.std():.3e}") + logging.info(f" - deviation from latents: {relative_deviation:.1%}") + + target_mesh = self.latents_to_mesh(target_z0_clean, octree_res=128) + if target_mesh is not None: + target_mesh_dir = os.path.join( + self.config.out_folder if hasattr(self.config, 'out_folder') + else "results/hunyuan_meshes", + "target_z0_meshes" + ) + os.makedirs(target_mesh_dir, exist_ok=True) + target_mesh_path = os.path.join(target_mesh_dir, f"target_z0_step_{step_id:04d}.obj") + target_mesh.export(target_mesh_path) + logging.info(f" 💾 Save target_z0 mesh (||z||={target_norm:.2e}): {target_mesh_path}") + else: + logging.debug(f" skipSave target_z0: marching cubesno surface found") + else: + logging.warning( + f" ⚠️ skipSave target_z0: containsabnormal values " + f"(nan={target_has_nan}, inf={target_has_inf}, max={target_max:.2e})" + ) + except (ValueError, RuntimeError) as e: + error_msg = str(e) + if "Surface level must be within volume data range" in error_msg or "No surface found" in error_msg: + logging.debug(f" skipSave target_z0: SDFvalueoutside the valid range or has no surface") + else: + logging.warning(f" Save target_z0 meshfailed: {type(e).__name__}: {error_msg[:100]}") + except Exception as e: + logging.warning(f" Save target_z0 meshfailed: {type(e).__name__}: {str(e)[:100]}") + + def save_final_target_z0_mesh(self, step_id: int): + """Force-save a target_z0 mesh at the final step.""" + try: + if self.target_z0_ema is not None: + target_z0 = self.target_z0_ema.detach().clone() + else: + target_z0, _ = self._computation_target_z0_current(step_id) + self._maybe_save_target_z0_mesh(target_z0, step_id, force=True) + except Exception as e: + logging.warning(f" ⚠️ failed to save the final target_z0: {type(e).__name__}: {str(e)[:100]}") + + def save_deformed_mesh(self, step: int, displacement: torch.Tensor, output_dir: str = None, suffix="step"): + """Save FEM solvebackdeformed mesh + + Args: + step: front steps + displacement: FEM solve [num_nodes, 3] + output_dir: outputdirectory, useconfig.out_folder/deformed_meshes + """ + if output_dir is None: + if hasattr(self.config, 'out_folder'): + output_dir = os.path.join(self.config.out_folder, "deformed_meshes") + else: + output_dir = "results/deformed_meshes" + + os.makedirs(output_dir, exist_ok=True) + + try: + # originalnodespositionandbackposition + original_nodes = self.nodes.detach().cpu().numpy() # [num_nodes, 3] + displacement_np = displacement.detach().cpu().numpy() # [num_nodes, 3] + deformed_nodes = original_nodes + displacement_np + + # elements + elements_np = self.elements.detach().cpu().numpy() # [num_elements, 8] + + # # Save VTK format (ParaView, contains) + # vtk_path = os.path.join(output_dir, f"deformed_step_{step:04d}.vtk") + # self._save_hex_mesh_vtk(deformed_nodes, elements_np, displacement_np, vtk_path, step) + + # Save OBJ/PLY (usedecodemesh, ) + decoded_mesh = self.latents_to_mesh(self.latents, octree_res=128) + if decoded_mesh is not None: + disp_vertices = self._sample_displacement_to_vertices( + decoded_mesh.vertices, original_nodes, displacement_np + ) + deformed_vertices = decoded_mesh.vertices + disp_vertices + colors = self._make_displacement_colors(disp_vertices) + + deformed_mesh = trimesh.Trimesh( + vertices=deformed_vertices, + faces=decoded_mesh.faces, + process=False, + ) + deformed_mesh.visual.vertex_colors = colors + + obj_path = os.path.join(output_dir, f"deformed_{suffix}_{step:04d}.obj") + # ply_path = os.path.join(output_dir, f"deformed_step_{step:04d}.ply") + deformed_mesh.export(obj_path) + # deformed_mesh.export(ply_path) + else: + # fallback: usemesh + obj_path = os.path.join(output_dir, f"deformed_{suffix}_{step:04d}.obj") + # ply_path = os.path.join(output_dir, f"deformed_step_{step:04d}.ply") + self._save_surface_mesh_obj(deformed_nodes, elements_np, obj_path) + # self._save_surface_mesh_ply(deformed_nodes, elements_np, displacement_np, ply_path) + + # displacement statistics + disp_mean = np.abs(displacement_np).mean() + disp_max = np.abs(displacement_np).max() + logging.info(f" 💾 saved deformed mesh : OBJ={obj_path.split('/')[-1]}") + logging.debug(f" : mean={disp_mean:.4e}, max={disp_max:.4e}") + + except Exception as e: + logging.warning(f" ⚠️ Save deformed meshfailed (Step {step}): {e}") + + def save_final_deformed_mesh(self, step_id: int, suffix="step"): + """force at the final step toSave deformed mesh (re-solveFEM) """ + if not hasattr(self, 'nodes') or not hasattr(self, 'elements'): + logging.warning(" ⚠️ unable to save the finaldeformed mesh: missingnodes/elements") + return + if not hasattr(self, 'forces') or not hasattr(self, 'boundary_mask'): + logging.warning(" ⚠️ unable to save the finaldeformed mesh: missingforces/boundary_mask") + return + + try: + from torchfem.materials import IsotropicElasticity3D + from physiopt.opt.solid_grid import SolidGrid + from physiopt.opt.field import occ_kernel + + with torch.no_grad(): + # update occupancyalignfrontlatents + sdf = self.get_field(self.nodes) + occ = occ_kernel(sdf, self.config.res, self.config.occ_sdf_beta) + self.coarse_occ = occ[self.elements].mean(1) + + if self.config.alpha_min > 0.0: + self.coarse_occ = torch.clamp(self.coarse_occ, self.config.alpha_min) + + vectorized_material = IsotropicElasticity3D( + E=self.config.youngs_modulus, + nu=self.config.poissons_ratio, + rho=self.config.density, + ).vectorize(self.elements.shape[0]) + + vectorized_material.C *= ( + self.coarse_occ[:, None, None] ** self.config.p_exponent + ) + + solid = SolidGrid(self.nodes, self.elements, vectorized_material) + solid.constraints[self.boundary_mask, :] = True + solid.forces = self.forces + + logging.info(" 🧱 final deformed mesh: re-solve the FEM system to save ") + u, _, _, _, _, _ = solid.solve(max_iter=1) + self.save_deformed_mesh(step_id, u, suffix=suffix) + except Exception as e: + logging.warning(f" ⚠️ final deformed meshSave failed: {type(e).__name__}: {str(e)[:100]}") + + def _save_surface_mesh_obj(self, nodes: np.ndarray, elements: np.ndarray, filename: str): + """Extract the surface from a hexahedral mesh and save it as OBJ.""" + # The six faces of a hexahedron. + hex_faces = [ + [0, 1, 2, 3], [4, 5, 6, 7], # Bottom, top. + [0, 1, 5, 4], [2, 3, 7, 6], # Front, back. + [0, 3, 7, 4], [1, 2, 6, 5], # Left, right. + ] + + # Collect faces that appear only once, i.e. surface faces. + face_count = {} + for elem in elements: + for face_indices in hex_faces: + face_nodes = tuple(sorted([elem[i] for i in face_indices])) + if face_nodes in face_count: + face_count[face_nodes] += 1 + else: + face_count[face_nodes] = 1 + + # Keep only surface faces. + surface_faces = [face for face, count in face_count.items() if count == 1] + + # Save OBJ. + with open(filename, 'w') as f: + f.write("# Deformed mesh surface\n") + for node in nodes: + f.write(f"v {node[0]:.6f} {node[1]:.6f} {node[2]:.6f}\n") + for face in surface_faces: + # OBJ indices are 1-based. + f.write(f"f {face[0]+1} {face[1]+1} {face[2]+1} {face[3]+1}\n") + + def _save_force_visualization(self, seat_nodes_mask: torch.Tensor, total_force: np.ndarray): + """Save voxel-level load data for visualization and validation. + + This exports: + 1. NumPy (.npz) with full node/load data + 2. OBJ point clouds for quick inspection + 3. Optional VTK data for ParaView + + Args: + seat_nodes_mask: Mask of seat/contact nodes [num_nodes]. + total_force: Total force vector [3]. + """ + if not hasattr(self.config, 'out_folder'): + logging.warning(" out_folder is not set, skipSave loaded voxel") + return + + # Create the force_visualization subdirectory. + vis_dir = os.path.join(self.config.out_folder, "force_visualization") + os.makedirs(vis_dir, exist_ok=True) + + # ==================== 1. Save NumPy data (most complete format) ==================== + all_nodes_cpu = self.nodes.cpu().numpy() + all_forces_cpu = self.forces.cpu().numpy() + seat_mask_cpu = seat_nodes_mask.cpu().numpy() + + # Extract loaded nodes. + seat_nodes = all_nodes_cpu[seat_mask_cpu] + seat_forces = all_forces_cpu[seat_mask_cpu] + + npz_path = os.path.join(vis_dir, "force_nodes.npz") + np.savez( + npz_path, + # All node data. + all_nodes=all_nodes_cpu, + all_forces=all_forces_cpu, + # Loaded-node data. + seat_nodes=seat_nodes, + seat_forces=seat_forces, + seat_mask=seat_mask_cpu, + # Boundary-node data. + boundary_mask=self.boundary_mask.cpu().numpy() if hasattr(self, 'boundary_mask') else None, + # Metadata. + total_force=total_force, + num_seat_nodes=len(seat_nodes), + num_all_nodes=len(all_nodes_cpu), + ) + logging.info(f" 💾 Save load data (NumPy format) : {npz_path}") + + # ==================== 2. Save OBJ point clouds ==================== + # 2a. Loaded nodes (red point cloud). + seat_obj_path = os.path.join(vis_dir, "seat_nodes.obj") + with open(seat_obj_path, 'w') as f: + f.write("# Seat nodes (loaded area)\n") + f.write(f"# Total: {len(seat_nodes)} nodes\n") + f.write(f"# Force per node: {seat_forces[0] if len(seat_forces) > 0 else [0,0,0]}\n") + for node in seat_nodes: + f.write(f"v {node[0]:.6f} {node[1]:.6f} {node[2]:.6f}\n") + logging.info(f" 💾 Save seat nodes (OBJpoint cloud) : {seat_obj_path}") + + # 2b. Boundary nodes (blue point cloud). + if hasattr(self, 'boundary_mask'): + boundary_nodes = all_nodes_cpu[self.boundary_mask.cpu().numpy()] + boundary_obj_path = os.path.join(vis_dir, "boundary_nodes.obj") + with open(boundary_obj_path, 'w') as f: + f.write("# Boundary nodes (fixed area)\n") + f.write(f"# Total: {len(boundary_nodes)} nodes\n") + for node in boundary_nodes: + f.write(f"v {node[0]:.6f} {node[1]:.6f} {node[2]:.6f}\n") + logging.info(f" 💾 Save boundary nodes (OBJpoint cloud) : {boundary_obj_path}") + + # 2c. All nodes (gray point cloud) for comparison. + all_obj_path = os.path.join(vis_dir, "all_nodes.obj") + with open(all_obj_path, 'w') as f: + f.write("# All nodes\n") + f.write(f"# Total: {len(all_nodes_cpu)} nodes\n") + for node in all_nodes_cpu: + f.write(f"v {node[0]:.6f} {node[1]:.6f} {node[2]:.6f}\n") + logging.info(f" 💾 Save all nodes (OBJpoint cloud) : {all_obj_path}") + + # ==================== 3. Save VTK data for ParaView ==================== + try: + vtk_path = os.path.join(vis_dir, "force_field.vtk") + with open(vtk_path, 'w') as f: + # VTK Header + f.write("# vtk DataFile Version 3.0\n") + f.write("Force field visualization\n") + f.write("ASCII\n") + f.write("DATASET UNSTRUCTURED_GRID\n") + + # Points + f.write(f"POINTS {len(all_nodes_cpu)} float\n") + for node in all_nodes_cpu: + f.write(f"{node[0]:.6f} {node[1]:.6f} {node[2]:.6f}\n") + + # Cells (vertices) + f.write(f"\nCELLS {len(all_nodes_cpu)} {len(all_nodes_cpu)*2}\n") + for i in range(len(all_nodes_cpu)): + f.write(f"1 {i}\n") + + # Cell types (1 = vertex) + f.write(f"\nCELL_TYPES {len(all_nodes_cpu)}\n") + for _ in range(len(all_nodes_cpu)): + f.write("1\n") + + # Point data (force vectors) + f.write(f"\nPOINT_DATA {len(all_nodes_cpu)}\n") + f.write("VECTORS force float\n") + for force in all_forces_cpu: + f.write(f"{force[0]:.6e} {force[1]:.6e} {force[2]:.6e}\n") + + # Scalar field: force magnitude + f.write("\nSCALARS force_magnitude float 1\n") + f.write("LOOKUP_TABLE default\n") + for force in all_forces_cpu: + mag = np.linalg.norm(force) + f.write(f"{mag:.6e}\n") + + # Scalar field: is_seat (0 or 1) + f.write("\nSCALARS is_seat int 1\n") + f.write("LOOKUP_TABLE default\n") + for is_seat in seat_mask_cpu: + f.write(f"{int(is_seat)}\n") + + logging.info(f" 💾 Save force field (VTK format, ParaView) : {vtk_path}") + except Exception as e: + logging.warning(f" ⚠️ Save VTK formatfailed: {e}") + + # ==================== 4. Generate a Python visualization script ==================== + vis_script_path = os.path.join(vis_dir, "visualize_forces.py") + with open(vis_script_path, 'w') as f: + f.write("""#!/usr/bin/env python3 +\"""Visualize voxel load data + +Usage: + python visualize_forces.py + +Requirements: + pip install numpy matplotlib + +\""" +import numpy as np +import matplotlib.pyplot as plt +from mpl_toolkits.mplot3d import Axes3D + +# Load data. +data = np.load('force_nodes.npz') +all_nodes = data['all_nodes'] +seat_nodes = data['seat_nodes'] +seat_forces = data['seat_forces'] +total_force = data['total_force'] + +# Create the 3D figure. +fig = plt.figure(figsize=(15, 5)) + +# Subplot 1: all nodes (gray) + loaded nodes (red). +ax1 = fig.add_subplot(131, projection='3d') +ax1.scatter(all_nodes[:, 0], all_nodes[:, 1], all_nodes[:, 2], + c='lightgray', s=0.5, alpha=0.3, label='All nodes') +ax1.scatter(seat_nodes[:, 0], seat_nodes[:, 1], seat_nodes[:, 2], + c='red', s=5, alpha=1.0, label='Seat nodes (loaded)') +ax1.set_xlabel('X') +ax1.set_ylabel('Y (up)') +ax1.set_zlabel('Z') +ax1.set_title(f'Loaded Nodes\\n({len(seat_nodes)}/{len(all_nodes)} nodes)') +ax1.legend() + +# Subplot 2: Y distribution of loaded nodes. +ax2 = fig.add_subplot(132) +y_coords = seat_nodes[:, 1] +ax2.hist(y_coords, bins=30, color='red', alpha=0.7, edgecolor='black') +ax2.axvline(y_coords.min(), color='blue', linestyle='--', label=f'Y_min={y_coords.min():.3f}') +ax2.axvline(y_coords.max(), color='green', linestyle='--', label=f'Y_max={y_coords.max():.3f}') +ax2.set_xlabel('Y coordinate (height)') +ax2.set_ylabel('Number of nodes') +ax2.set_title('Seat Node Y Distribution') +ax2.legend() +ax2.grid(True, alpha=0.3) + +# Subplot 3: XZ force-vector layout in top view. +ax3 = fig.add_subplot(133) +ax3.scatter(seat_nodes[:, 0], seat_nodes[:, 2], c='red', s=10, alpha=0.5) +# Draw a sparse subset of force vectors to avoid clutter. +step = max(1, len(seat_nodes) // 50) +for i in range(0, len(seat_nodes), step): + node = seat_nodes[i] + force = seat_forces[i] + # Scale force vectors for visualization. + scale = 0.01 + ax3.arrow(node[0], node[2], force[0]*scale, force[2]*scale, + head_width=0.02, head_length=0.01, fc='blue', ec='blue', alpha=0.7) +ax3.set_xlabel('X') +ax3.set_ylabel('Z') +ax3.set_title(f'Top View (XZ plane)\\nForce: {total_force}') +ax3.axis('equal') +ax3.grid(True, alpha=0.3) + +plt.tight_layout() +plt.savefig('force_visualization.png', dpi=150, bbox_inches='tight') +logging.info("✅ image saved : force_visualization.png") +plt.show() + +# Print summary statistics. +logging.info("\\n" + "="*60) +logging.info("force voxel statistics") +logging.info("="*60) +logging.info(f"total node count: {len(all_nodes)}") +logging.info(f"loaded node count: {len(seat_nodes)} ({len(seat_nodes)/len(all_nodes)*100:.1f}%)") +logging.info(f"total: {total_force}") +logging.info(f"per nodeaverage force per node: {seat_forces.mean(axis=0)}") +logging.info(f"\\nY-coordinate range:") +logging.info(f" - min: {y_coords.min():.3f}") +logging.info(f" - max: {y_coords.max():.3f}") +logging.info(f" - mean: {y_coords.mean():.3f}") +logging.info(f" - height span: {y_coords.max() - y_coords.min():.3f}") +logging.info("="*60) +""") + os.chmod(vis_script_path, 0o755) # Add execute permission. + logging.info(f" 💾 Save visualization script: {vis_script_path}") + + # ==================== 5. Generate a README document ==================== + readme_path = os.path.join(vis_dir, "README.md") + with open(readme_path, 'w') as f: + f.write(f"""# Load Voxel Visualization Data + +Generated at: {np.datetime64('now')} + +## Statistics + +- **Total nodes**: {len(all_nodes_cpu)} +- **Loaded nodes**: {len(seat_nodes)} ({len(seat_nodes)/len(all_nodes_cpu)*100:.1f}%) +- **Total force**: {total_force} +- **Force per node**: {seat_forces[0] if len(seat_forces) > 0 else [0,0,0]} + +## Files + +### 1. NumPy format (recommended for analysis) + +- `force_nodes.npz`: contains the full dataset + - `all_nodes`: coordinates of all nodes [{len(all_nodes_cpu)}, 3] + - `all_forces`: force vectors on all nodes [{len(all_nodes_cpu)}, 3] + - `seat_nodes`: coordinates of loaded nodes [{len(seat_nodes)}, 3] + - `seat_forces`: force vectors on loaded nodes [{len(seat_nodes)}, 3] + - `seat_mask`: mask of loaded nodes [{len(all_nodes_cpu)}] + - `boundary_mask`: mask of boundary nodes [{len(all_nodes_cpu)}] + +**Example**: +```python +import numpy as np +data = np.load('force_nodes.npz') +seat_nodes = data['seat_nodes'] +print(f"Loaded nodes: {{len(seat_nodes)}}") +``` + +### 2. OBJ format (recommended for quick inspection) + +- `seat_nodes.obj`: loaded nodes (red point cloud) +- `boundary_nodes.obj`: boundary nodes (blue point cloud) +- `all_nodes.obj`: all nodes (gray point cloud) + +**Usage**: +1. Open in Meshlab: `meshlab seat_nodes.obj` +2. Or import the OBJ files into Blender +3. You can load multiple OBJ files together for comparison + +### 3. VTK format (recommended for professional visualization) + +- `force_field.vtk`: force-field data with vector information + +**Usage**: +1. Open in ParaView: `paraview force_field.vtk` +2. In ParaView: + - Use `Glyph` to visualize force vectors + - Color by `force_magnitude` to inspect strength + - Filter by `is_seat` to isolate the loaded region + +### 4. Visualization script + +- `visualize_forces.py`: Python visualization script + +**Usage**: +```bash +python visualize_forces.py +``` +""") + logging.info(f" 💾 Save README document: {readme_path}") + + # Print a short summary. + logging.info(f" ✅ force voxel data saved successfully!") + logging.info(f" - view directory: {vis_dir}") + logging.info(f" - quick visualization: cd {vis_dir} && python visualize_forces.py") + logging.info(f" - view in Meshlab: meshlab {os.path.join(vis_dir, 'seat_nodes.obj')}") + + +def load_hunyuan_models(model_path: str = "tencent/Hunyuan3D-2.1", + subfolder: str = "hunyuan3d-shapegen", + use_safetensors: bool = True): + """Load the Hunyuan3D models (VAE, Flow Model, and Scheduler). + + Args: + model_path: Model path, either a Hugging Face ID or a local directory. + subfolder: Model subfolder name. + use_safetensors: Whether to load safetensors checkpoints. + + Returns: + (vae, flow_model, scheduler): the VAE, Flow Matching model, and scheduler. + """ + logging.info(f"🔧 loading Hunyuan3D-2.1model...") + logging.info(f" modelpath: {model_path}") + logging.info(f" subfolder: {subfolder}") + logging.info(f" modelformat: {'safetensors' if use_safetensors else 'checkpoint'}") + + try: + pipeline = Hunyuan3DDiTFlowMatchingPipeline.from_pretrained( + model_path, + subfolder=subfolder, + torch_dtype=torch.float16, + use_safetensors=use_safetensors + ) + + if pipeline is None: + raise ValueError("pipeline loading failed and returned None") + + logging.info(" ✅ pipeline loaded successfully") + + pipeline.to('cuda') + logging.info(" ✅ modelmoved to CUDA (dtype: fp16)") + + vae = pipeline.vae + flow_model = pipeline.model + scheduler = pipeline.scheduler + + return vae, flow_model, scheduler + + except Exception as e: + logging.error(f"\n❌ modelloadfailed: {e}") + logging.error(f"\nPossible fixes:") + logging.error(f"1. make sure Hunyuan3D is installed-2.1: cd Hunyuan3D-2.1 && pip install -e .") + logging.error(f"2. check network connectivity to huggingface.co") + logging.error(f"3. or download manually: git clone https://huggingface.co/tencent/Hunyuan3D-2") + import traceback + traceback.print_exc() + sys.exit(1) + + +def plot_history(history: dict, save_dir: str, filename: str = "optimization_metrics.png"): + + epochs = list(range(1, len(history["compliance"]) + 1)) + + # 2. Create the figure with a 2x2 grid + fig, axs = plt.subplots(2, 2, figsize=(14, 10)) + fig.suptitle("Optimization Metrics Evolution", fontsize=16, fontweight='bold') + + # --- Plot 1: Compliance --- + axs[0, 0].plot(epochs, history["compliance"], marker='o', color='#1f77b4', linewidth=2) + axs[0, 0].set_title("Compliance (Strain Energy)") + axs[0, 0].set_xlabel("Epoch") + axs[0, 0].grid(True, linestyle='--', alpha=0.7) + + # --- Plot 2: u_mean --- + axs[0, 1].plot(epochs, history["u_mean"], marker='s', color='#2ca02c', linewidth=2) + axs[0, 1].set_title("Mean Displacement (|u|_mean)") + axs[0, 1].set_xlabel("Epoch") + axs[0, 1].grid(True, linestyle='--', alpha=0.7) + + # --- Plot 3: c_relative_decrease --- + axs[1, 0].plot(epochs, history["c_relative_decrease"], marker='^', color='#d62728', linewidth=2) + axs[1, 0].set_title("Relative Compliance Decrease") + axs[1, 0].set_xlabel("Epoch") + axs[1, 0].grid(True, linestyle='--', alpha=0.7) + + # --- Plot 4: u_relative_decrease --- + axs[1, 1].plot(epochs, history["u_relative_decrease"], marker='v', color='#9467bd', linewidth=2) + axs[1, 1].set_title("Relative Displacement Decrease") + axs[1, 1].set_xlabel("Epoch") + axs[1, 1].grid(True, linestyle='--', alpha=0.7) + + # 3. Adjust layout to prevent text from overlapping + plt.tight_layout() + fig.subplots_adjust(top=0.92) # Leave space for the main super-title + + # 4. Save the figure + os.makedirs(save_dir, exist_ok=True) + full_path = os.path.join(save_dir, filename) + + plt.savefig(full_path, dpi=300, bbox_inches='tight') + plt.close(fig) + + logging.info(f" 📊 Plot successfully saved to: {full_path}") + + +def main(): + """Parse CLI arguments and run the optimization.""" + import argparse + + parser = argparse.ArgumentParser(description="Hunyuan3D physics optimization + shape-prior optimization") + + # Required arguments. + parser.add_argument("--latents", type=str, required=True, + help="Input latents file path (.pt)") + parser.add_argument("--out_folder", type=str, default="../out/hunyuan_opt", + help="Output folder path") + + # Model arguments. + parser.add_argument("--model_path", type=str, default="tencent/Hunyuan3D-2.1", + help="Model path (using v2.1)") + parser.add_argument("--subfolder", type=str, default="hunyuan3d-dit-v2-1", + help="Model subfolder") + parser.add_argument("--use_safetensors", action="store_true", + help="Use safetensors format (default: ckpt)") + + # Physical-simulation arguments. + parser.add_argument("--use_physics", action="store_true", + help="Enable physics-constrained optimization") + parser.add_argument("--res", type=int, default=16, + help="Voxel resolution (16/32/64)") + parser.add_argument("--youngs_modulus_scale", type=float, default=2.0, + help="Final Young's modulus multiplier (default 2x after the last projection)") + parser.add_argument("--compliance_threshold", type=float, default=None, + help="Target compliance threshold (None = automatic)") + parser.add_argument("--compliance_threshold_ratio", type=float, default=0.3, + help="Automatic threshold ratio (threshold = initial value × ratio)") + + # Optimization arguments. + parser.add_argument("--num_steps", type=int, default=300, + help="Number of optimization steps (pure SDS only; in physics mode it becomes outer_cycles * phys_steps_per_cycle automatically)") + parser.add_argument("--outer_cycles", type=int, default=100, + help="Number of outer cycles (each cycle = physics optimization + projection)") + parser.add_argument("--phys_steps_per_cycle", type=int, default=5, + help="Number of physics-optimization steps per outer cycle") + parser.add_argument("--lr", type=float, default=5e-3, + help="Learning rate (increase to 0.005 to help the mesh thicken faster) ") + parser.add_argument("--lagrange_max", type=float, default=10.0, + help="Maximum Lagrange multiplier (recommended: 5-20)") + parser.add_argument("--alm_rho_init", type=float, default=1.0, + help="ALM rhoinitial value") + parser.add_argument("--alm_rho_max", type=float, default=1000.0, + help="ALM rhoMax") + parser.add_argument("--alm_rho_increase_factor", type=float, default=2.0, + help="ALM rhogrowth factor") + parser.add_argument("--alm_rho_increase_patience", type=int, default=5, + help="ALM rhonumber of consecutive violation steps required before increasing") + parser.add_argument("--alm_scale_guard_ratio", type=float, default=0.95, + help="ALMscaling guard ratio(<=1), control the upper bound of the physics-gradient target=this ratio x clipping-threshold value") + parser.add_argument("--grad_clip_enabled", action="store_true", + help="Enable gradient clipping (disabled by default; otherwise only NaN/Inf checks are kept)") + parser.add_argument("--use_sgd", action="store_true", + help="Use SGD instead of Adam") + parser.add_argument("--force_config", type=str, default=None, + help="Path to the external-force JSON config (generated by the web UI)") + parser.add_argument("--force", type=float, nargs=3, action="append", default=None, + help="External force vector [fx fy fz] (N, Y-up coordinates; can be specified multiple times)") + parser.add_argument("--global_loading", action="store_true", + help="Use global uniform loading (disable local loading)") + parser.add_argument("--force_region_mode", type=str, default="top_percent", + choices=["top_percent", "height_ratio", "bbox"], + help="How to choose the local loading region") + parser.add_argument("--force_top_percent", type=float, default=0.05, + help="top_percent mode: select the highest-Y fraction") + parser.add_argument("--force_bbox", type=float, nargs=6, default=None, + help="bbox mode: x_min x_max y_min y_max z_min z_max (absolute coordinates)") + parser.add_argument("--force_bbox_ratio", type=float, nargs=6, default=None, + help="bbox mode (0-1): bbox relative to the node bounds") + parser.add_argument("--seat_height_min_ratio", type=float, default=0.3, + help="height_ratio mode: lower seat boundary (0-1)") + parser.add_argument("--seat_height_max_ratio", type=float, default=0.5, + help="height_ratio mode: upper seat boundary (0-1)") + + # SDS arguments. + parser.add_argument("--sds_weight", type=float, default=1.0, + help="SDS gradient weight (deprecated; use sds_weight_start and sds_weight_end instead)") + parser.add_argument("--sds_weight_start", type=float, default=10.0, + help="Initial SDS weight (linearly increased; 0.0001 is recommended to avoid disturbing physics optimization)") + parser.add_argument("--sds_weight_end", type=float, default=10.0, + help="Final SDS weight (linearly increased; 0.001 is recommended, about 1/10 of the physics gradient)") + parser.add_argument("--sds_timestep", type=float, default=0.1, + help="SDS timestep (recommended: 0.05-0.2)") + parser.add_argument("--sds_target_z0_ema_beta", type=float, default=0.9, + help="target_z0 EMA smoothing factor (larger means smoother)") + parser.add_argument("--deformed_mesh_interval", type=int, default=10, + help="Interval for saving deformed meshes (steps)") + parser.add_argument("--deformed_mesh_disp_min", type=float, default=0.0, + help="Minimum displacement for deformed-mesh color mapping (default 0.0)") + parser.add_argument("--deformed_mesh_disp_max", type=float, default=0.2, + help="Maximum displacement for deformed-mesh color mapping (<=0 enables per-step auto scaling)") + parser.add_argument("--guidance_scale", type=float, default=7.5, + help="CFG guidance scale (standard value: 7.5; larger means stronger image conditioning)") + parser.add_argument("--sds_projection_max_rel", type=float, default=0.0, + help="Maximum relative target_z0 projection deviation (0 = unlimited)") + parser.add_argument("--sds_use_uncond", action="store_true", + help="Use the unconditional branch (only takes effect when guidance_scale <= 1)") + + # Topology control. + parser.add_argument("--keep_all_components", action="store_true", + help="Keep all connected components (to avoid disappearing chair legs)") + parser.add_argument("--re_extract_interval", type=int, default=1, + help="Solid re-extraction interval (0 = disabled)") + + args = parser.parse_args() + + def _normalize_force_vectors(value): + if value is None: + return None + if isinstance(value, (list, tuple)) and len(value) > 0: + if isinstance(value[0], (list, tuple)): + candidates = value + else: + candidates = [value] + else: + return None + normalized = [] + for vec in candidates: + if not isinstance(vec, (list, tuple)) or len(vec) != 3: + continue + try: + normalized.append([float(v) for v in vec]) + except Exception: + continue + return normalized if normalized else None + + def _normalize_force_entry(entry): + if not isinstance(entry, dict): + return None + forces = _normalize_force_vectors(entry.get("forces")) + if forces is None: + forces = _normalize_force_vectors(entry.get("force")) + if forces is None: + return None + out = dict(entry) + if len(forces) > 1: + out["forces"] = forces + out["force"] = [float(sum(v[i] for v in forces)) for i in range(3)] + else: + out["force"] = forces[0] + out.pop("forces", None) + if "force_region_mode" in out: + out["force_region_mode"] = str(out["force_region_mode"]) + if "global_loading" in out: + out["global_loading"] = bool(out["global_loading"]) + if "force_top_percent" in out: + out["force_top_percent"] = float(out["force_top_percent"]) + if "seat_height_min_ratio" in out: + out["seat_height_min_ratio"] = float(out["seat_height_min_ratio"]) + if "seat_height_max_ratio" in out: + out["seat_height_max_ratio"] = float(out["seat_height_max_ratio"]) + if "force_bbox" in out and isinstance(out["force_bbox"], (list, tuple)) and len(out["force_bbox"]) == 6: + out["force_bbox"] = [float(v) for v in out["force_bbox"]] + elif "force_bbox" in out: + out.pop("force_bbox", None) + if "force_bbox_ratio" in out and isinstance(out["force_bbox_ratio"], (list, tuple)) and len(out["force_bbox_ratio"]) == 6: + out["force_bbox_ratio"] = [float(v) for v in out["force_bbox_ratio"]] + elif "force_bbox_ratio" in out: + out.pop("force_bbox_ratio", None) + return out + + # Load force configuration from JSON, typically exported from the web UI. + force_config_loaded = False + force_config_error = None + force_entries = None + if args.force_config: + raw_force_config = args.force_config + candidates = [] + if os.path.isabs(raw_force_config): + candidates.append(raw_force_config) + else: + candidates.append(raw_force_config) + script_dir = os.path.dirname(os.path.abspath(__file__)) + candidates.append(os.path.join(script_dir, raw_force_config)) + candidates.append(os.path.join(os.path.dirname(script_dir), raw_force_config)) + force_config_path = next((p for p in candidates if os.path.exists(p)), None) + if force_config_path is None: + force_config_error = f"Path does not exist; tried: {candidates}" + else: + args.force_config = force_config_path + try: + with open(force_config_path, "r") as f: + force_cfg = json.load(f) + if isinstance(force_cfg, dict): + cfg_forces = _normalize_force_vectors(force_cfg.get("forces")) + if cfg_forces is not None: + args.force = cfg_forces + else: + cfg_force = _normalize_force_vectors(force_cfg.get("force")) + if cfg_force is not None: + args.force = cfg_force + elif "force" in force_cfg or "forces" in force_cfg: + force_config_error = "force/forcesinvalid format" + if "global_loading" in force_cfg: + args.global_loading = bool(force_cfg["global_loading"]) + if "force_region_mode" in force_cfg: + args.force_region_mode = str(force_cfg["force_region_mode"]) + if "force_top_percent" in force_cfg: + args.force_top_percent = float(force_cfg["force_top_percent"]) + if "seat_height_min_ratio" in force_cfg: + args.seat_height_min_ratio = float(force_cfg["seat_height_min_ratio"]) + if "seat_height_max_ratio" in force_cfg: + args.seat_height_max_ratio = float(force_cfg["seat_height_max_ratio"]) + if "force_bbox" in force_cfg: + args.force_bbox = force_cfg["force_bbox"] + if "force_bbox_ratio" in force_cfg: + args.force_bbox_ratio = force_cfg["force_bbox_ratio"] + if "force_entries" in force_cfg: + raw_entries = force_cfg["force_entries"] + if isinstance(raw_entries, list): + normalized_entries = [] + for entry in raw_entries: + norm_entry = _normalize_force_entry(entry) + if norm_entry is not None: + normalized_entries.append(norm_entry) + if normalized_entries: + force_entries = normalized_entries + else: + force_config_error = "force_entries has no valid entries" + else: + force_config_error = "force_entriesinvalid format" + force_config_loaded = True + else: + force_config_error = f"force_configis not a dict: {type(force_cfg)}" + except Exception as e: + force_config_error = f"read failed: {e}" + + # Configure logging. force=True ensures this replaces any prior setup. + os.makedirs(args.out_folder, exist_ok=True) + log_file = os.path.join(args.out_folder, "optimization.log") + + # Remove any existing handlers. + for handler in logging.root.handlers[:]: + logging.root.removeHandler(handler) + + # Reconfigure logging. + logging.basicConfig( + level=logging.INFO, + format='%(asctime)s - %(levelname)s - %(message)s', + handlers=[ + logging.FileHandler(log_file, mode='w'), # Rewrite the log on each run. + logging.StreamHandler() + ], + force=True # Python 3.8+: force a full reconfiguration. + ) + + logging.info(f"🔧 logging configuration completed") + logging.info(f" - log file: {log_file}") + logging.info(f" - output mode: file + console") + if args.force_config: + if force_config_loaded: + logging.info(" ✅ force_configloaded") + logging.info(f" - path: {args.force_config}") + logging.info(f" - forces: {args.force}") + if force_entries: + logging.info(f" - force_entries: {len(force_entries)}") + logging.info(f" - global_loading: {args.global_loading}") + logging.info(f" - force_region_mode: {args.force_region_mode}") + logging.info(f" - force_top_percent: {args.force_top_percent}") + logging.info(f" - seat_height_min_ratio: {args.seat_height_min_ratio}") + logging.info(f" - seat_height_max_ratio: {args.seat_height_max_ratio}") + logging.info(f" - force_bbox: {args.force_bbox}") + logging.info(f" - force_bbox_ratio: {args.force_bbox_ratio}") + if force_config_error: + logging.warning(f" ⚠️ force_configsome fields are invalid: {force_config_error}") + else: + logging.warning(f" ⚠️ force_configloadfailed: {force_config_error}") + + # In physics mode, derive num_steps from outer_cycles and phys_steps_per_cycle. + if args.use_physics: + outer_cycles = max(1, int(args.outer_cycles)) + phys_steps_per_cycle = max(1, int(args.phys_steps_per_cycle)) + derived_num_steps = outer_cycles * phys_steps_per_cycle + if args.num_steps != derived_num_steps: + logging.info( + f" - num_stepsautomatically set: {args.num_steps} → {derived_num_steps} " + f"(outer_cycles={outer_cycles}, phys_steps_per_cycle={phys_steps_per_cycle})" + ) + args.num_steps = derived_num_steps + + # ==================== Save run metadata ==================== + # 1. Save the command line. + command_file = os.path.join(args.out_folder, "run_command.txt") + try: + with open(command_file, 'w') as f: + f.write("=" * 80 + "\n") + f.write("Command used (Command Used)\n") + f.write("=" * 80 + "\n\n") + f.write("Full command:\n") + f.write("python " + " ".join(sys.argv) + "\n\n") + + f.write("=" * 80 + "\n") + f.write("Arguments (Arguments)\n") + f.write("=" * 80 + "\n\n") + for arg, value in vars(args).items(): + f.write(f"{arg}: {value}\n") + + f.write("\n" + "=" * 80 + "\n") + f.write("Environment (Environment)\n") + f.write("=" * 80 + "\n\n") + f.write(f"Python: {sys.version}\n") + f.write(f"PyTorch: {torch.__version__}\n") + f.write(f"CUDA Available: {torch.cuda.is_available()}\n") + if torch.cuda.is_available(): + f.write(f"CUDA Version: {torch.version.cuda}\n") + f.write(f"GPU Count: {torch.cuda.device_count()}\n") + + logging.info(f" - saved command used : {command_file}") + except Exception as e: + logging.warning(f" ⚠️ Save Command usedfailed: {e}") + + # 2. Save a copy of the current script. + script_backup = os.path.join(args.out_folder, "viewer_hunyuan_web_alternate.py") + try: + current_script = os.path.abspath(__file__) + shutil.copy2(current_script, script_backup) + logging.info(f" - saved script copy : {script_backup}") + except Exception as e: + logging.warning(f" ⚠️ Save failed to save script copy: {e}") + + # Load latents and conditioning data. + logging.info(f"\n📂 loading input data...") + logging.info(f" - Latents: {args.latents}") + + data = torch.load(args.latents, map_location='cpu') + + # Extract latents. + if isinstance(data, dict) and 'latents' in data: + latents = data['latents'] + else: + latents = data + + logging.info(f" ✅ Latents shape: {latents.shape}") + + # Check conditioning data (image_embeds or image). + need_encode_cond = False + image_embeds = None + image = None + + if isinstance(data, dict): + if 'image' in data: + # New format: only the image was saved, so we need to re-encode it. + logging.info(f" - detected image data; re-encoding as conditional embeds") + image_array = data['image'] + image = Image.fromarray(image_array) + need_encode_cond = True + elif 'image_embeds' in data: + # Legacy format: embeddings are already saved. + logging.info(f" - using the saved conditional embeds") + image_embeds = data['image_embeds'] + need_encode_cond = False + elif 'cond' in data: + # Alternate format using a saved cond dict. + logging.info(f" - using the saved cond") + image_embeds = data['cond'] + need_encode_cond = False + else: + raise ValueError("latents.ptis missingimage, image_embedsor cond data") + else: + raise ValueError("latentsmust be a dictionary containing'latents'andconditioninformation dict") + + if image_embeds is not None: + if isinstance(image_embeds, dict): + logging.info(f" ✅ Cond keys: {list(image_embeds.keys())}") + else: + logging.info(f" ✅ Image embeds shape: {image_embeds.shape}") + + # Load models. + logging.info(f"\n🔧 loading Hunyuan3Dmodel...") + vae, flow_model, scheduler = load_hunyuan_models( + model_path=args.model_path, + subfolder=args.subfolder, + use_safetensors=args.use_safetensors + ) + + # ==================== Encode conditioning data if needed ==================== + if need_encode_cond: + logging.info("🎨 encoding conditional embeds from the image...") + + # Reload the full pipeline for condition encoding. + from hy3dgen.shapegen import Hunyuan3DDiTFlowMatchingPipeline + + pipeline = Hunyuan3DDiTFlowMatchingPipeline.from_pretrained( + args.model_path, + subfolder=args.subfolder, + torch_dtype=torch.float16, + use_safetensors=args.use_safetensors + ) + pipeline.to('cuda') + + with torch.no_grad(): + # Prepare the image. + cond_inputs = pipeline.prepare_image(image) + image_tensor = cond_inputs.pop('image') + + # Enable CFG so the encoded condition contains both branches. + cond_dict = pipeline.encode_cond( + image=image_tensor, + additional_cond_inputs=cond_inputs, + do_classifier_free_guidance=True, # Enable CFG. + dual_guidance=False, + ) + + # Save the condition dict. + image_embeds = cond_dict + + logging.info(f" ✅ condition encoding completed (CFG mode) ") + logging.info(f" - Cond keys: {list(cond_dict.keys()) if isinstance(cond_dict, dict) else 'tensor'}") + + # Resolve the compliance threshold. + if args.compliance_threshold is None: + compliance_threshold = 200.0 + logging.info(f" using the default compliance threshold: {compliance_threshold}") + else: + compliance_threshold = args.compliance_threshold + logging.info(f" using the custom compliance threshold: {compliance_threshold}") + + target_z0_update_interval = max(1, int(args.phys_steps_per_cycle)) + forces = None + normalized_forces = _normalize_force_vectors(args.force) + if normalized_forces: + forces = [{'external_force': vec} for vec in normalized_forces] + elif args.force is not None: + logging.warning(f" ⚠️ invalid external force vector; ignoring: {args.force}") + # Build the optimization config. + config = OptimizationConfig( + num_steps=args.num_steps, + lr=args.lr, + sds_timestep=args.sds_timestep, + sds_weight=args.sds_weight if args.use_physics else 1.0, # Keep backward compatibility. + sds_weight_start=args.sds_weight_start, # Dynamic weight schedule start. + sds_weight_end=args.sds_weight_end, # Dynamic weight schedule end. + guidance_scale=args.guidance_scale, # CFG guidance scale. + sds_projection_max_rel=args.sds_projection_max_rel, + sds_use_uncond=args.sds_use_uncond, + sds_target_z0_update_interval=target_z0_update_interval, + sds_target_z0_ema_beta=args.sds_target_z0_ema_beta, + deformed_mesh_interval=args.deformed_mesh_interval, + deformed_mesh_disp_min=args.deformed_mesh_disp_min, + deformed_mesh_disp_max=args.deformed_mesh_disp_max, + use_sgd=args.use_sgd, + grad_clip_enabled=args.grad_clip_enabled, + # Physical parameters. + res=args.res, + lagrange_max=args.lagrange_max, + compliance_threshold=compliance_threshold, + alm_rho_init=args.alm_rho_init, + alm_rho_max=args.alm_rho_max, + alm_rho_increase_factor=args.alm_rho_increase_factor, + alm_rho_increase_patience=args.alm_rho_increase_patience, + alm_scale_guard_ratio=args.alm_scale_guard_ratio, + youngs_modulus_scale=args.youngs_modulus_scale, + # Topology control. + one_cc_only=not args.keep_all_components, + re_extract_interval=args.re_extract_interval, + # Loads and load-region settings. + forces=forces, + force_entries=force_entries, + use_local_loading=not args.global_loading, + seat_height_min_ratio=args.seat_height_min_ratio, + seat_height_max_ratio=args.seat_height_max_ratio, + force_region_mode=args.force_region_mode, + force_top_percent=args.force_top_percent, + force_bbox=args.force_bbox, + force_bbox_ratio=args.force_bbox_ratio, + # Output path. + out_folder=args.out_folder, + ) + + # Create the optimizer. + optimizer = HunyuanSDSOptimizer( + latents=latents, + cond=image_embeds, + vae=vae, + flow_model=flow_model, + scheduler=scheduler, + config=config, + device='cuda' + ) + + # Prepare physics if requested. + final_step = args.num_steps + if args.use_physics: + logging.info(f"\n🔬 enable physics optimization mode") + logging.info(f" - Voxel resolution: {args.res}") + logging.info(f" - physics steps/cycle: {args.phys_steps_per_cycle}, outer cycles: {args.outer_cycles}") + logging.info(f" - projection noise: sds_timestep={args.sds_timestep}") + logging.info(f" - target_z0update interval: {target_z0_update_interval} (consistent with phys_steps_per_cycle)") + logging.info(f" - LagrangeMax: {args.lagrange_max}") + + try: + optimizer.extract_solid(step=-1) # Initial extraction. + optimizer.prepare_physical_simulation() + logging.info(f" ✅ physics simulationInitializationsucceeded") + except Exception as e: + logging.warning(f" ⚠️ warning: initial mesh extraction failed (this is normal, optimizationbe repaired during the optimization process) ") + logging.warning(f" error information: {str(e)[:100]}") + # Continue anyway: the key physical state is the occupancy field, not the mesh. + else: + logging.info(f"\n🎨 using pure SDS optimization mode") + + # Optimization loop. + optimization_mode = "Alternating Phys/Projection" if args.use_physics else "Pure SDS" + total_steps_hint = ( + int(args.outer_cycles) * (int(args.phys_steps_per_cycle) + 1) + if args.use_physics + else args.num_steps + ) + logging.info(f"\n🚀 start{optimization_mode}optimization ({total_steps_hint} steps)...") + + if args.use_physics: + lagrange_multiplier = 0.0 + rho = config.alm_rho_init + violation_count = 0 + + # Automatically set the compliance threshold when needed. + if config.compliance_threshold is None or config.compliance_threshold == 200.0: + logging.info(f" 📊 computationinitialcompliancethreshold value...") + try: + initial_compliance, _, _, _ = optimizer.training_step( + 0, 0.0, 0.0, use_sds=False + ) + # Auto threshold: initial compliance times the requested ratio. + auto_threshold = initial_compliance * args.compliance_threshold_ratio + auto_threshold = min(auto_threshold, 100000.0) # Upper bound only. + compliance_threshold = auto_threshold + config.compliance_threshold = auto_threshold + logging.info( + f" ✅ Automatically set the threshold: {initial_compliance:.2e} × {args.compliance_threshold_ratio:.2f} " + f"= {compliance_threshold:.2e}" + ) + + # Warn when the structure already looks extremely stiff or too soft. + if initial_compliance < 0.01: # Already very stiff. + logging.warning(f" ⚠️ initial compliance is very small ({initial_compliance:.2e}), the structure may already be stiff enough!") + logging.warning(f" consider increasing the external force or using a softer material to create visible deformation") + logging.warning(f" current material: E={config.youngs_modulus:.2e} Pa, ν={config.poissons_ratio}") + elif initial_compliance > 1000.0: # Likely too soft. + logging.warning(f" ⚠️ initial compliance is very large ({initial_compliance:.2e}), the structure may be too soft!") + logging.warning(f" consider using a stiffer material or reducing the external force") + except Exception as e: + logging.warning(f" ⚠️ automatic computation failed, usethreshold value200: {e}") + compliance_threshold = 200.0 + else: + compliance_threshold = config.compliance_threshold + + logging.info(f"🎯 parameters:") + logging.info(f" - initial lambda: {lagrange_multiplier}") + logging.info(f" - initial rho: {rho}") + logging.info(f" - Compliancethreshold value: {compliance_threshold:.2e}") + logging.info(f" - λMax: {args.lagrange_max}") + logging.info(f" - ρMax: {config.alm_rho_max:.1e}") + logging.info(f" - rho growth: ×{config.alm_rho_increase_factor:.1f} (continuous violations{config.alm_rho_increase_patience} steps)") + logging.info(f" - ALMscaling guard ratio: {config.alm_scale_guard_ratio:.2f}") + logging.info(f" - gradient clipping: {'enabled' if config.grad_clip_enabled else 'disabled'}") + + outer_cycles = max(1, int(args.outer_cycles)) + phys_steps_per_cycle = max(1, int(args.phys_steps_per_cycle)) + total_steps = outer_cycles * (phys_steps_per_cycle + 1) + logging.info( + f"🔁 Alternating optimization: outer cycles={outer_cycles}, physics steps/cycle={phys_steps_per_cycle}, " + f"total steps(including projections)≈{total_steps}" + ) + base_youngs_modulus = float(config.youngs_modulus) + youngs_modulus_scale = float(config.youngs_modulus_scale) + youngs_modulus_target = base_youngs_modulus * youngs_modulus_scale + youngs_modulus_delta = (youngs_modulus_target - base_youngs_modulus) / outer_cycles + projection_count = 0 + logging.info( + f" - linearly increase Young's modulus: E0={base_youngs_modulus:.2e}, " + f"Δ/projection={youngs_modulus_delta:.2e}, E_final={youngs_modulus_target:.2e} " + f"(scale={youngs_modulus_scale:.2f}x)" + ) + global_step = 0 + phys_step_count = 0 + + history = {"compliance": [], + "u_mean": [], + "c_relative_decrease": [], + "u_relative_decrease": [], + "epoch": []} + + thresholds = [0, 30, 40, 50, 60, 65, 70, 75, 80] + thresh_idx = 0 + latents_dir = os.path.join(args.out_folder, "latents") + os.makedirs(latents_dir, exist_ok=True) + finish = False + for cycle in range(outer_cycles): + if finish: + break + logging.info(f"\n{'='*60}") + logging.info(f"Outer Cycle {cycle+1}/{outer_cycles}") + logging.info(f"{'='*60}") + + for inner in range(phys_steps_per_cycle): + step_id = global_step + phys_step = phys_step_count + + # Physics optimization step with ALM. + compliance_loss, u_mean, sds_loss, total_loss = optimizer.training_step( + phys_step, lagrange_multiplier, rho, use_sds=True, save_step=step_id + ) + + # Update history + history["compliance"].append(compliance_loss) + history["u_mean"].append(u_mean) + + # Calculate relative decreases using current variables + c_decrease = (history["compliance"][0] - compliance_loss) / history["compliance"][0] * 100 + u_decrease = (history["u_mean"][0] - u_mean) / history["u_mean"][0] * 100 + history["c_relative_decrease"].append(c_decrease) + history["u_relative_decrease"].append(u_decrease) + logging.info( + f" 📉 Metrics | Comp: {compliance_loss:.3e} (↓ {c_decrease:.1f}%) | u_mean: {u_mean:.3e} (↓ {u_decrease:.1f}%)" + ) + + if inner==0: + current_threshold = thresholds[thresh_idx] + if (c_decrease > current_threshold) or (c_decrease == current_threshold) : + logging.info(f"\n✅ Threshold reached: {current_threshold}") + optimizer.save_mesh(current_threshold, args.out_folder, suffix="decrease", high_quality=True) + latent_path = os.path.join(latents_dir, f"latent_{current_threshold}.pt") + torch.save({ + 'latents': optimizer.latents.detach().cpu(), + 'cond': optimizer.cond, + }, latent_path) + optimizer.save_final_deformed_mesh(current_threshold, suffix="decrease") + history["epoch"].append(phys_step) + thresh_idx += 1 + if (thresh_idx >= len(thresholds)): + finish = True + break + + + # Normalized constraint: g = D / D_thr - 1. + violation = (compliance_loss / (compliance_threshold + 1e-8)) - 1.0 + g_pos = max(0.0, violation) + + # Update lambda and project it to the non-negative range. + lagrange_multiplier = max(0.0, lagrange_multiplier + rho * violation) + lagrange_multiplier = min(lagrange_multiplier, args.lagrange_max) + + # Increase rho after persistent violations. + if g_pos > 0.0: + violation_count += 1 + if violation_count >= config.alm_rho_increase_patience: + new_rho = min(rho * config.alm_rho_increase_factor, config.alm_rho_max) + if new_rho > rho: + rho = new_rho + logging.info(f" 🔧 rho increased: {rho:.2e} (continuous violations{config.alm_rho_increase_patience} steps)") + violation_count = 0 + else: + violation_count = 0 + + status = "❌ violating" if violation > 0 else "✅ within threshold" + + # Log a compact ALM summary. + logging.info( + f" 📊 Compliance (true) : {compliance_loss:.2e} vs threshold value{compliance_threshold:.2e} " + f"(g={violation:+.3e}, [g]+={g_pos:.3e}) {status}" + ) + logging.info(f" ⚖️ ALMStatus: λ={lagrange_multiplier:.4f} (max={args.lagrange_max}), ρ={rho:.2e}") + current_sds_weight = optimizer.get_current_sds_weight(phys_step) + if current_sds_weight > 0.0: + sds_percentage = (current_sds_weight * sds_loss) / (total_loss + 1e-10) * 100 + logging.info( + f" 🎨 Shape Loss: weight={current_sds_weight:.6f}, " + f"loss={sds_loss:.4e}, ratio={sds_percentage:.2f}%" + ) + else: + logging.info(f" 🎨 Shape Loss: disabled (weight is 0)") + + # Save only the first and last physics step of each outer cycle. + # is_first_phys_step = inner == 0 + # is_last_phys_step = inner == phys_steps_per_cycle - 1 + # if is_first_phys_step or is_last_phys_step: + # optimizer.save_mesh(step_id, args.out_folder) + + global_step += 1 + phys_step_count += 1 + + # Project back to the manifold by replacing latents with target_z0. + logging.info(f"\nStep {global_step} | Projection (E={optimizer.config.youngs_modulus:.2e} Pa)") + logging.info(" 🔮 manifold projection: add noise and compute target_z0, backreplace directlylatents") + projected = optimizer.project_to_manifold(step=global_step) + if not projected: + logging.warning(" ⚠️ projection failed, keep the physical result for this cycle") + else: + projection_count += 1 + new_E = base_youngs_modulus + youngs_modulus_delta * projection_count + new_E = min(new_E, youngs_modulus_target) + optimizer.config.youngs_modulus = new_E + if hasattr(optimizer, "E"): + optimizer.E = new_E + logging.info( + f" 🧱 Young's modulusupdate: E={new_E:.2e} " + f"(projection {projection_count}/{outer_cycles})" + ) + # if global_step % 20 == 0: + # projection_dir = os.path.join(args.out_folder, "projection_meshes") + # os.makedirs(projection_dir, exist_ok=True) + # optimizer.save_mesh(global_step, projection_dir) + global_step += 1 + + final_step = global_step + else: + # Pure SDS optimization. + for step in range(args.num_steps): + logging.info(f"\nStep {step}/{args.num_steps}") + optimizer.training_step_sds(step) + if step % 20 == 0: + optimizer.save_mesh(step, args.out_folder) + + # Save final results. + logging.info("\n✅ Optimization finished!save final results...") + optimizer.save_mesh(final_step, args.out_folder, high_quality=True) + if args.use_physics: + optimizer.save_final_target_z0_mesh(final_step) + optimizer.save_final_deformed_mesh(final_step) + + final_latents_path = os.path.join(args.out_folder, "optimized_latents.pt") + torch.save({ + 'latents': optimizer.latents.detach().cpu(), + 'cond': optimizer.cond, + }, final_latents_path) + logging.info(f"💾 save optimized latents: {final_latents_path}") + logging.info(f"\n✅ all files saved to: {args.out_folder}") + + history_path = os.path.join(args.out_folder, "history.json") + with open(history_path, "w", encoding="utf-8") as f: + json.dump(history, f, indent=4) + plot_history(history, save_dir=args.out_folder, filename="optimization_metrics.png") + + if args.use_physics: + logging.info(f"\n📊 force visualization data:") + logging.info(f" - directory: {os.path.join(args.out_folder, 'force_visualization')}") + logging.info(f" - quick view: cd {os.path.join(args.out_folder, 'force_visualization')} && python visualize_forces.py") + + +if __name__ == "__main__": + main() diff --git a/cfd_workflow_20261012/_seiler_ref/physiopt_new_scripts/hunyuan_dflow_me.py b/cfd_workflow_20261012/_seiler_ref/physiopt_new_scripts/hunyuan_dflow_me.py new file mode 100644 index 0000000000000000000000000000000000000000..515cb727e586e713f8c7814f0d44330f24803280 --- /dev/null +++ b/cfd_workflow_20261012/_seiler_ref/physiopt_new_scripts/hunyuan_dflow_me.py @@ -0,0 +1,3361 @@ +""" +Hunyuan3D-2.1 physical optimization + shape-prior optimization. +""" + +import os +import copy +# os.environ['TORCH_HOME'] = '/mnt/cvlab/scratch/cvlab/home/hantzhan/.torch' +import sys +import shutil + +# Add Hunyuan3D-2.1 to the Python path. +hunyuan_path = os.path.abspath(os.path.join(os.path.dirname(__file__), "../../Hunyuan3D-2.1")) +# Note: logging is not imported yet, so use print here if needed. +# Basic logging is configured near the top of the file after import. + +sys.path.append("..") + +from matplotlib import pyplot as plt +import torch +import torch.nn.functional as F +import trimesh +import numpy as np +from PIL import Image +import argparse +import json +from typing import Tuple, Optional, List +from dataclasses import dataclass, field +import traceback +import logging + +# Configure logging here only conceptually; main() will reconfigure it to +# log to both the console and a file. +# Do not call basicConfig here so the main() configuration remains effective. +# logging.basicConfig(level=logging.INFO, format='%(levelname)s: %(message)s') + +# Physical-simulation imports. +PHYSIOPT_AVAILABLE = False +try: + from physiopt.utils.phys_utils import generate_hex + from physiopt.utils.grid_utils import filter_one_component + from physiopt.opt.field import occ_kernel + from physiopt.opt.forces import ForceConfig + PHYSIOPT_AVAILABLE = True + logging.info("✅ physics simulation moduleimportsucceeded") +except ImportError as e: + logging.warning(f"⚠️ warning: physics simulation moduleimportfailed: {e}") + logging.warning(" if you only run SDS optimization, you can ignore this warning") + PHYSIOPT_AVAILABLE = False + + def generate_hex(res, limits=[(-0.5, 0.5), (-0.5, 0.5), (-0.5, 0.5)], device="cuda", return_coords=False): + """Placeholder for hexahedral grid generation. + + Returns tensors in the same format as the real function. + """ + logging.warning(f"⚠️ warning: using placeholdergenerate_hex, please install the physiopt module") + return None, None + + def filter_one_component(mask, res): + """Placeholder for connected-component filtering. + + Args: + mask: Element mask [res*res*res] + res: Voxel resolution + """ + return mask + + def occ_kernel(sdf, res, beta): + """Placeholder for SDF-to-occupancy conversion.""" + return torch.sigmoid(-sdf * beta) + +# Warp physics-engine import. +try: + import warp as wp + wp.init() + WARP_AVAILABLE = True + logging.info("✅ Warp physics engineInitializationsucceeded") +except ImportError: + WARP_AVAILABLE = False + logging.warning("⚠️ warning: Warp physics enginenot installed, physics simulationwill be unavailable") + logging.warning(" Install: pip install warp-lang") + +# Hunyuan3D imports +try: + from hy3dgen.shapegen.models.autoencoders import ShapeVAE + from hy3dgen.shapegen import Hunyuan3DDiTFlowMatchingPipeline + from hy3dgen.shapegen.pipelines import export_to_trimesh +except ImportError as e: + logging.error(f"❌ failed to import Hunyuan3D modules: {e}") + logging.error(f"\nplease follow these steps to set upHunyuan3D-2.1:") + logging.error(f"1. cd {os.path.dirname(hunyuan_path)}") + logging.error(f"2. git clone https://github.com/Tencent/Hunyuan3D-2.git Hunyuan3D-2.1") + logging.error(f"3. cd Hunyuan3D-2.1") + logging.error(f"4. pip install -e .") + sys.exit(1) + + +@dataclass +class OptimizationConfig: + """Optimization config for physics + SDS.""" + # Physical-simulation parameters. + res: int = 32 # Voxel resolution (16/32/64), matching the reference code. + # Restored physical settings from the stable v90 configuration. + p_exponent: float = 1.0 # SIMP penalty exponent. + alpha_min: float = 0.01 # Minimum density, restored from v90. + volume_term: float = 1000000.0 # Volume-constraint weight, currently disabled. + occ_sdf_beta: float = 2.0 # Sigmoid-kernel beta, restored from v90. + one_cc_only: bool = False # Keep only the largest connected component. + + # SDS parameters. + # Use dynamic SDS weights so physics dominates early and aesthetics enters later. + sds_timestep: float = 0.1 # SDS timestep; smaller values preserve more detail. + sds_weight: float = 1.0 # SDS weight relative to the physical gradient. + sds_weight_start: float = 1e5 # 0.1 # 0.0001 # Initial SDS weight. + sds_weight_end: float = 1e5 # 1.0 # 0.001 # Final SDS weight. + guidance_scale: float = 7.5 # Standard CFG guidance scale for stronger image conditioning. + sds_projection_max_rel: float = 0.0 # Max relative target_z0 projection offset (0 = unlimited). + sds_use_uncond: bool = False # Use the unconditional branch when guidance_scale <= 1. + sds_target_z0_update_interval: int = 10 # target_z0 update interval; tied to phys_steps_per_cycle. + sds_target_z0_ema_beta: float = 0.9 # EMA smoothing coefficient; larger is smoother. + + lagrange_max: float = 50.0 # Max lambda. + compliance_threshold: float = 200.0 # Compliance threshold used for normalization. + alm_rho_init: float = 1.0 # Initial rho. + alm_rho_max: float = 1000.0 # Max rho. + alm_rho_increase_factor: float = 2.0 # Rho growth factor. + alm_rho_increase_patience: int = 5 # Number of consecutive violations before increasing rho. + alm_scale_guard_ratio: float = 0.95 # ALM scaling guard to stay below gradient clipping. + + # Topology control. + re_extract_interval: int = 5 # Re-extract the solid every N steps; 0 disables it. + + # Material properties. Values are aligned with the reference setup. + # youngs_modulus is already specified directly in Pa, so no unit conversion is needed. + youngs_modulus: float = 5e8 # 1e9 # Pa (= 1 GPa), restored from v90. + youngs_modulus_scale: float = 2.0 # Final multiplier after the last projection in alternating mode. + poissons_ratio: float = 0.3 # Poisson's ratio (dimensionless). + density: float = 650.0 # Material density (kg/m^3). + + ## Wood + # youngs_modulus: float = 9e9 # Pa (= 1 GPa), aligned with the reference code. + # poissons_ratio: float = 0.35 # Poisson's ratio (dimensionless), matches the reference. + # density: float = 400.0 # Material density (kg/m^3), matches the reference. + + ## PVG + # youngs_modulus: float = 3.25e9 # Pa (= 1 GPa), aligned with the reference code. + # poissons_ratio: float = 0.38 # Poisson's ratio (dimensionless), matches the reference. + # density: float = 1380.0 # Material density (kg/m^3), matches the reference. + + # Load conditions; supports multiple forces like config.json. + forces: List = None # List of ForceConfig objects. + # Multiple localized load entries, each with its own force and region settings. + force_entries: Optional[List[dict]] = None + + # Local-loading settings, e.g. to mimic a person sitting on a chair. + use_local_loading: bool = True # Use local loading instead of global uniform loading. + seat_height_min_ratio: float = 0.3 # Lower bound of the seat band as a height ratio. + seat_height_max_ratio: float = 0.5 # Upper bound of the seat band as a height ratio. + force_region_mode: str = "top_percent" # Load-region mode: top_percent / height_ratio / bbox. + force_top_percent: float = 0.05 # In top_percent mode, use the highest-Y fraction of nodes. + force_bbox: Optional[List[float]] = None # bbox mode: x_min x_max y_min y_max z_min z_max. + force_bbox_ratio: Optional[List[float]] = None # bbox mode in normalized node bounds [0, 1]. + + # Optimization parameters, restored from the stable v90 configuration. + lr: float = 0.001 # Learning rate. + num_steps: int = 100 # Number of optimization steps. + use_sgd: bool = False # Use SGD instead of Adam. + grad_clip_enabled: bool = False # Enable gradient clipping; off by default. + save_every: int = 10 # Save interval in steps. + deformed_mesh_interval: int = 10 # Save interval for deformed meshes. + deformed_mesh_disp_min: float = 0.0 # Minimum displacement for deformed-mesh color mapping. + deformed_mesh_disp_max: float = 0.2 # Maximum displacement for deformed-mesh color mapping. + + # Output path. + out_folder: str = "../out/hunyuan_opt" # Output directory. + + # Device. + device: str = "cuda" # Compute device. + + # Whether to enable physics optimization. + use_physics: bool = True # Enable physical-constraint optimization. + + def __post_init__(self): + # Set default loads in the Hunyuan Y-up coordinate system: + # X = right, Y = up, Z = forward. + if self.forces is None: + try: + from physiopt.opt.forces import ForceConfig + self.forces = [ + ForceConfig(external_force=[0.0, -100000.0, 0.0]) # 100 kN downward along Y. + # ForceConfig(external_force=[0.0, 0.0, -500.0]), # 500 N backward along Z. + ] + except ImportError: + # Fallback format if physiopt is unavailable; keep only the force vectors. + self.forces = [ + {'external_force': [0.0, -100000.0, 0.0]} # 100 kN downward along Y. + # {'external_force': [0.0, 0.0, -500.0]}, # Backward along Z. + ] + + +class HunyuanSDSOptimizer: + """Hunyuan3D SDS optimizer with differentiable physics support.""" + + def __init__( + self, + latents: torch.Tensor, + cond: dict, # Condition dict containing positive and negative branches. + vae: ShapeVAE, + flow_model: torch.nn.Module, + config: OptimizationConfig, + scheduler=None, + device: str = 'cuda' + ): + """ + Args: + latents: Initial latent tokens [1, N, D]. + cond: Condition dict returned by pipeline.encode_cond. + vae: Hunyuan3D VAE model. + flow_model: Hunyuan3D Flow Matching model. + scheduler: Hunyuan3D Flow Matching scheduler used to align target_z0. + config: Optimization config. + device: Compute device. + """ + self.device = device + self.config = config + + # Models. + self.vae = vae.to(device).eval() + self.flow_model = flow_model.to(device).eval() + if scheduler is not None: + try: + self.sds_scheduler = copy.deepcopy(scheduler) + except Exception: + self.sds_scheduler = scheduler + logging.warning("⚠️ Scheduler deepcopyfailed, already fallback to originalscheduler") + else: + self.sds_scheduler = None + + # Create a differentiable SDF query helper. + from hy3dgen.shapegen.models.autoencoders.differentiable_sdf_query import DifferentiableSDFQuery + self.sdf_query = DifferentiableSDFQuery( + vae=self.vae, + bounds=0.8, # Our coordinate range is [-0.8, 0.8]. + chunk_size=8192 # Batch query size. + ) + logging.info(f"✅ created differentiable SDF query helper") + + # Latent tokens are the variables being optimized. + # Use float32 instead of float16 to avoid numeric overflow. + self.latents = latents.clone().to(device).to(torch.float32).requires_grad_(True) + + logging.info(f" ⚠️ note: Latentsfloat32FP16value") + + # Move conditioning data to the target device recursively. + def to_device_recursive(obj): + if isinstance(obj, torch.Tensor): + return obj.to(device) + elif isinstance(obj, dict): + return {k: to_device_recursive(v) for k, v in obj.items()} + elif isinstance(obj, (list, tuple)): + return type(obj)(to_device_recursive(item) for item in obj) + else: + return obj + + self.cond = to_device_recursive(cond) + self._cond_warned_cfg_repeat = False + self._cond_warned_nocfg_slice = False + + # Optimizer selection. + if config.use_sgd: + self.noise = torch.rand_like(self.latents).detach().requires_grad_(True) + self.optimizer = torch.optim.SGD([self.noise], lr=config.lr, momentum=0.0) + opt_name = "SGD" + else: + self.noise = torch.rand_like(self.latents).detach().requires_grad_(True) + self.optimizer = torch.optim.Adam([self.noise], lr=config.lr, betas=(0.9, 0.999), eps=1e-8) + opt_name = "Adam" + + logging.info(f"✅ HunyuanSDSOptimizerInitializationcompleted (with differentiable physics support) ") + logging.info(f" - Latents shape: {self.latents.shape}") + logging.info(f" - Latents dtype: {self.latents.dtype} (optimized in float32)") + logging.info(f" - Device: {device}") + logging.info(f" - Optimizer: {opt_name}") + logging.info(f" - Learning rate: {config.lr}") + + # target_z0 EMA cache. + self.target_z0_ema = None + self.target_z0_last_velocity = None + self.target_z0_last_update = None + + def get_field(self, x: torch.Tensor, latents: torch.Tensor = None) -> torch.Tensor: + """Differentiable SDF query through the VAE geo_decoder. + + Args: + x: Query points [N, 3] in the range [-0.8, 0.8]^3. + latents: Optional latent tokens; defaults to self.latents. + + Returns: + sdf: SDF values [N] with gradient support. + """ + if latents is None: + latents = self.latents + + # Match the official pipeline: divide by scale_factor before decoding. + scale_factor = getattr(self.vae, "scale_factor", 1.0) + latents_scaled = latents / scale_factor + + # Convert to FP16 because the VAE expects FP16 inputs. + latents_fp16 = latents_scaled.to(torch.float16) + + # Decode with the VAE decoder while preserving gradients. + decoded_latents = self.vae.decode(latents_fp16) + + # Query the SDF through the differentiable helper. + # sdf_query calls geo_decoder internally, so keep FP16 to match VAE weights. + sdf = self.sdf_query( + decoded_latents, # Keep FP16 and let sdf_query handle the rest. + x, + return_occupancy=False # Return SDF instead of occupancy. + ) # [N] + + return sdf + + def _cond_batch_size(self, cond) -> Optional[int]: + if isinstance(cond, torch.Tensor): + return cond.shape[0] if cond.dim() >= 1 else None + if isinstance(cond, dict): + for v in cond.values(): + bsz = self._cond_batch_size(v) + if bsz is not None: + return bsz + if isinstance(cond, (list, tuple)): + for v in cond: + bsz = self._cond_batch_size(v) + if bsz is not None: + return bsz + return None + + def _cond_slice(self, cond, batch_slice: slice): + if isinstance(cond, torch.Tensor): + if cond.dim() >= 1 and cond.shape[0] >= batch_slice.stop: + return cond[batch_slice] + return cond + if isinstance(cond, dict): + return {k: self._cond_slice(v, batch_slice) for k, v in cond.items()} + if isinstance(cond, (list, tuple)): + return type(cond)(self._cond_slice(v, batch_slice) for v in cond) + return cond + + def _cond_repeat(self, cond, repeats: int): + if isinstance(cond, torch.Tensor): + if cond.dim() >= 1: + rep_shape = (repeats,) + (1,) * (cond.dim() - 1) + return cond.repeat(rep_shape) + return cond + if isinstance(cond, dict): + return {k: self._cond_repeat(v, repeats) for k, v in cond.items()} + if isinstance(cond, (list, tuple)): + return type(cond)(self._cond_repeat(v, repeats) for v in cond) + return cond + + def _get_cond_for_guidance(self, use_cfg: bool): + cond = self.cond + bsz = self._cond_batch_size(cond) + if use_cfg: + if bsz == 1: + if not self._cond_warned_cfg_repeat: + logging.warning("⚠️ guidance_scale>1 cond batch=1, already condCFG") + self._cond_warned_cfg_repeat = True + return self._cond_repeat(cond, 2) + if bsz is not None and bsz > 2: + return self._cond_slice(cond, slice(0, 2)) + return cond + # no-CFG + if bsz is not None and bsz >= 2: + if self.config.sds_use_uncond: + if not self._cond_warned_nocfg_slice: + logging.info("ℹ️ guidance_scale<=1, useno conditioncond[1:2]") + self._cond_warned_nocfg_slice = True + return self._cond_slice(cond, slice(1, 2)) + if not self._cond_warned_nocfg_slice: + logging.info("ℹ️ guidance_scale<=1, already usecond[0:1]batch") + self._cond_warned_nocfg_slice = True + return self._cond_slice(cond, slice(0, 1)) + if self.config.sds_use_uncond and bsz == 1 and not self._cond_warned_nocfg_slice: + logging.warning("⚠️ sds_use_uncond=1 cond batch=1, already fallback to conditself") + self._cond_warned_nocfg_slice = True + return cond + + def latents_to_mesh(self, latents: torch.Tensor, octree_res: int = 128) -> Optional[trimesh.Trimesh]: + """Decode latent tokens into a mesh. + + Args: + latents: Latent tokens [1, N, D] (float32). + octree_res: Octree resolution. 128 is faster; 256 is higher quality. + + Returns: + A trimesh.Trimesh object, or None on failure. + """ + with torch.no_grad(): + # Skip invalid latent tensors early. + if torch.isnan(latents).any() or torch.isinf(latents).any(): + logging.warning(" latents_to_mesh: latentscontains NaN or Inf, skip") + return None + + # Match the official pipeline by dividing by scale_factor first. + scale_factor = getattr(self.vae, "scale_factor", 1.0) + latents_scaled = latents / scale_factor + + # Decode in FP16 because the VAE expects FP16 inputs. + latents_fp16 = latents_scaled.to(torch.float16) + + try: + # VAE decode. + decoded_latents = self.vae.decode(latents_fp16) + + # Skip invalid decoded latents. + if torch.isnan(decoded_latents).any() or torch.isinf(decoded_latents).any(): + logging.warning(" latents_to_mesh: decoded_latentscontains NaN or Inf, skip") + return None + except Exception as e: + logging.debug(f" latents_to_mesh: VAE decodingfailed: {e}") + return None + + # Use an adaptive mc_level fallback if the default level fails. + try: + # First try the standard mc_level=0.0. + mesh = self.vae.latents2mesh( + decoded_latents, + output_type='trimesh', + bounds=1.01, + mc_level=0.0, + num_chunks=20000, + octree_resolution=octree_res, + mc_algo='mc', + enable_pbar=False + ) + mesh = export_to_trimesh(mesh)[0] + return mesh + + except ValueError as e: + error_msg = str(e) + if "Surface level must be within volume data range" in error_msg: + # Estimate a better mc_level from sampled SDF statistics. + logging.debug(f" latents_to_mesh: mc_level=0.0 failed, try an adaptive level...") + + try: + # Sample a coarse grid to estimate the SDF range. + grid_size = 32 + x = torch.linspace(-1.0, 1.0, grid_size, device=decoded_latents.device) + y = torch.linspace(-1.0, 1.0, grid_size, device=decoded_latents.device) + z = torch.linspace(-1.0, 1.0, grid_size, device=decoded_latents.device) + xx, yy, zz = torch.meshgrid(x, y, z, indexing='ij') + points = torch.stack([xx, yy, zz], dim=-1).reshape(-1, 3) # [N, 3] + + # query the SDF values. + sdf_values = self.get_field(points, latents=latents) + + # Compute basic statistics. + sdf_median = torch.median(sdf_values).item() + sdf_min = sdf_values.min().item() + sdf_max = sdf_values.max().item() + sdf_mean = sdf_values.mean().item() + + logging.debug(f" SDFstatistics: min={sdf_min:.4f}, max={sdf_max:.4f}, median={sdf_median:.4f}, mean={sdf_mean:.4f}") + + # No clear surface can be extracted if the SDF range is too small. + if abs(sdf_max - sdf_min) < 1e-4: + logging.debug(f" SDFrange is too small to extract a surface") + return None + + # Try several plausible candidate levels. + candidate_levels = [ + sdf_median, # Median. + sdf_mean, # Mean. + (sdf_min + sdf_max) / 2, # Midpoint of the range. + sdf_min + (sdf_max - sdf_min) * 0.3, # 30% point. + sdf_min + (sdf_max - sdf_min) * 0.7, # 70% point. + ] + + # Clamp all levels to the valid range. + valid_levels = [ + max(sdf_min + 0.001, min(sdf_max - 0.001, level)) + for level in candidate_levels + ] + + # Remove duplicates. + valid_levels = list(set(valid_levels)) + + logging.debug(f" try {len(valid_levels)} candidate levels: {[f'{l:.4f}' for l in valid_levels[:3]]}...") + + # Try each candidate level in order. + for i, adaptive_level in enumerate(valid_levels): + try: + mesh = self.vae.latents2mesh( + decoded_latents, + output_type='trimesh', + bounds=1.01, + mc_level=adaptive_level, + num_chunks=20000, + octree_resolution=octree_res, + mc_algo='mc', + enable_pbar=False + ) + mesh = export_to_trimesh(mesh)[0] + logging.info(f" ✅ uselevelsucceeded (level={adaptive_level:.4f}, attempt {i+1})") + return mesh + except (ValueError, RuntimeError) as level_error: + # Try the next level if this one fails. + if i < len(valid_levels) - 1: + continue + else: + # All candidate levels failed. + logging.debug(f" all candidate levels failed") + return None + + # No candidate succeeded. + return None + + except Exception as adaptive_error: + logging.debug(f" adaptive extraction failed: {type(adaptive_error).__name__}: {str(adaptive_error)[:50]}") + return None + + elif "No surface found" in error_msg: + logging.debug(f" latents_to_mesh: Marching cubesno surface found, skip") + return None + else: + logging.warning(f" latents_to_mesh: unknown ValueError: {error_msg}") + return None + + except RuntimeError as e: + error_msg = str(e) + if "No surface found" in error_msg or "Surface level" in error_msg: + logging.debug(f" latents_to_mesh: Marching cubesfailed, skip") + return None + else: + logging.warning(f" latents_to_mesh: RuntimeError: {error_msg}") + return None + + except Exception as e: + # Catch any other unexpected failure. + logging.warning(f" latents_to_mesh: unexpected exception: {type(e).__name__}: {e}") + return None + + def _filter_floating_components(self, mesh: trimesh.Trimesh) -> trimesh.Trimesh: + """Remove small floating fragments and keep only the largest component.""" + try: + components = mesh.split(only_watertight=False) + if len(components) <= 1: + return mesh + + face_counts = [len(comp.faces) for comp in components] + max_idx = int(np.argmax(face_counts)) + filtered = components[max_idx] + dropped = len(components) - 1 + + logging.info(f" 🧹 filter floating fragments: kept{len(filtered.faces)} faces, discarded{dropped} small components") + return filtered + except Exception as e: + logging.warning(f" failed to filter floating fragments: {type(e).__name__}: {str(e)[:100]}") + return mesh + + def _sample_displacement_to_vertices( + self, + vertices: np.ndarray, + nodes: np.ndarray, + displacement: np.ndarray, + ) -> np.ndarray: + """Sample the voxel-node displacement field onto mesh vertices by nearest neighbor.""" + try: + from scipy.spatial import cKDTree + tree = cKDTree(nodes) + _, idx = tree.query(vertices, k=1) + return displacement[idx] + except Exception as e: + try: + from sklearn.neighbors import NearestNeighbors + nn = NearestNeighbors(n_neighbors=1, algorithm="auto") + nn.fit(nodes) + idx = nn.kneighbors(vertices, return_distance=False).squeeze(1) + return displacement[idx] + except Exception as e2: + logging.warning(f" displacement sampling failed, fallback to zero displacement: {type(e).__name__}: {str(e)[:100]}") + logging.debug(f" secondaryError: {type(e2).__name__}: {str(e2)[:100]}") + return np.zeros_like(vertices) + + def _normalize_displacement_magnitude( + self, disp_mag: np.ndarray + ) -> Tuple[np.ndarray, float, float, bool]: + """Normalize displacement magnitude, optionally with a fixed range.""" + mag_max_cfg = getattr(self.config, "deformed_mesh_disp_max", None) + mag_min_cfg = getattr(self.config, "deformed_mesh_disp_min", None) + use_fixed = mag_max_cfg is not None and mag_max_cfg > 0.0 + if use_fixed: + mag_min = 0.0 if mag_min_cfg is None else float(mag_min_cfg) + mag_max = float(mag_max_cfg) + if mag_max <= mag_min: + use_fixed = False + if not use_fixed: + mag_min = float(disp_mag.min()) + mag_max = float(disp_mag.max()) + denom = max(1e-12, mag_max - mag_min) + norm = (disp_mag - mag_min) / denom + if use_fixed: + norm = np.clip(norm, 0.0, 1.0) + return norm, mag_min, mag_max, use_fixed + + def _make_displacement_colors(self, displacement: np.ndarray) -> np.ndarray: + """Map displacement magnitude to vertex colors (blue -> red).""" + disp_mag = np.linalg.norm(displacement, axis=1) + norm, _, _, _ = self._normalize_displacement_magnitude(disp_mag) + colors = np.stack([norm, np.zeros_like(norm), 1.0 - norm], axis=1) + return (colors * 255).astype(np.uint8) + + def _log_physical_quantities( + self, + u: torch.Tensor, + sigma: Optional[torch.Tensor], + ) -> None: + """Log displacement and von Mises stress statistics.""" + with torch.no_grad(): + u_max = None + u_avg = None + try: + u_mag = torch.norm(u, dim=1) + u_max = u_mag.max().item() + u_avg = u_mag.mean().item() + except Exception as e: + logging.warning( + f" ⚠️ displacement statistics failed: {type(e).__name__}: {str(e)[:100]}" + ) + + sigma_vm_max = None + sigma_vm_avg = None + if sigma is not None: + try: + if sigma.dim() == 2 and sigma.shape[1] >= 6: + s_xx = sigma[:, 0] + s_yy = sigma[:, 1] + s_zz = sigma[:, 2] + s_yz = sigma[:, 3] + s_xz = sigma[:, 4] + s_xy = sigma[:, 5] + mises_sq = 0.5 * ( + (s_xx - s_yy) ** 2 + + (s_yy - s_zz) ** 2 + + (s_zz - s_xx) ** 2 + + 6.0 * (s_xy ** 2 + s_yz ** 2 + s_xz ** 2) + ) + mises = torch.sqrt(torch.clamp(mises_sq, min=0.0)) + sigma_vm_max = mises.max().item() + sigma_vm_avg = mises.mean().item() + else: + logging.warning( + f" ⚠️ sigmashape does not match expectations, skip von Mises statistics: {tuple(sigma.shape)}" + ) + except Exception as e: + logging.warning( + f" ⚠️ von Mises statistics failed: {type(e).__name__}: {str(e)[:100]}" + ) + + if u_max is not None and u_avg is not None: + if sigma_vm_max is not None and sigma_vm_avg is not None: + logging.info( + f" physical metrics: u_max={u_max:.3e}, u_avg={u_avg:.3e}, " + f"sigma_vm_max={sigma_vm_max:.3e}, sigma_vm_avg={sigma_vm_avg:.3e}" + ) + else: + logging.info( + f" physical metrics: u_max={u_max:.3e}, u_avg={u_avg:.3e}" + ) + + def backward_step(self, sensitivity_density: torch.Tensor): + """Backpropagate with VJP, aligned with the reference code. + + Reference: viewer_deepsdf.py Line 148-183. + This uses torch.autograd.functional.vjp to propagate sensitivity to latents. + """ + def f(latents: torch.Tensor): + """ + Compute occupancy from a given latent tensor. + Aligned with viewer_deepsdf.py Line 155-173. + """ + # Query the SDF. + sdf = self.get_field(self.nodes, latents) + + # SDF → occupancy + from physiopt.opt.field import occ_kernel + occ = occ_kernel(sdf, self.config.res, self.config.occ_sdf_beta) + + # Element occupancy is the average over the 8 nodes. + occ_elem = occ[self.elements].mean(1) + + # Clamp by alpha_min if requested. + if self.config.alpha_min > 0.0: + occ_elem = torch.clamp(occ_elem, self.config.alpha_min) + + return occ_elem + + # VJP computations d occ / d latents^T times the sensitivity vector. + # Aligned with viewer_deepsdf.py Line 175-180. + try: + grad_latent = torch.autograd.functional.vjp( + f, + self.latents.clone().requires_grad_(True), + sensitivity_density, + )[1] + + # Validate the returned gradient. + if grad_latent is None: + logging.error(" ❌ VJP returned None!") + return + + grad_norm = torch.norm(grad_latent).item() + logging.info(f" VJP gradient: norm={grad_norm:.2e}") + + # Assign the gradient manually, matching the reference implementation. + self.latents.grad = grad_latent + + except Exception as e: + logging.error(f" ❌ VJP failed: {e}") + import traceback + traceback.print_exc() + + def prepare_physical_simulation(self): + """Prepare the physical simulation and FEM solver state. + + Initialization includes: + 1. Material properties + 2. Boundary conditions + 3. External forces + """ + if not WARP_AVAILABLE: + logging.warning("Warpnot installed, skipphysics simulation preparation") + return + + if not hasattr(self, 'nodes') or not hasattr(self, 'elements'): + logging.error("please call extract_solid() to extract the solid first") + return + + logging.info("prepare physical simulation...") + + # Initialize Warp. + wp.init() + + # Normalize device names such as "cuda" and "cuda:0". + if 'cuda' in self.device: + # Extract the device id when needed. + if ':' in self.device: + device_id = self.device.split(':')[-1] + warp_device = f"cuda:{device_id}" + else: + warp_device = "cuda:0" # default to cuda:0 + else: + warp_device = "cpu" + + wp.set_device(warp_device) + logging.info(f"Warpdevice: {warp_device}") + + # Material properties. + self.E = self.config.youngs_modulus # Young's modulus. + self.nu = self.config.poissons_ratio # Poisson's ratio. + self.rho = self.config.density # Density. + + # Boundary condition: fix bottom nodes using Hunyuan's Y-up frame. + y_coords = self.nodes[:, 1] + y_min = y_coords.min() + boundary_threshold = y_min + 0.05 # 0.2 # 0.05 # Bottom 5% band. + self.boundary_mask = y_coords < boundary_threshold + + logging.info(f" coordinate system: Y-up (Hunyuan-native), fix Y < {boundary_threshold:.3f}nodes") + + # Apply load locally instead of spreading it across all nodes. + # The default heuristic targets a seat-like region in the Y-up frame. + + # Compute the total force, giving priority to force_entries. + total_force = np.zeros(3, dtype=np.float32) + force_entries = getattr(self.config, "force_entries", None) + valid_force_entries = None + if force_entries: + valid_force_entries = [] + for entry in force_entries: + if not isinstance(entry, dict): + continue + entry_force = None + if "force" in entry: + try: + entry_force = np.array(entry["force"], dtype=np.float32) + except Exception: + entry_force = None + elif "forces" in entry and isinstance(entry["forces"], list): + try: + entry_force = np.sum( + np.array(entry["forces"], dtype=np.float32), axis=0 + ) + except Exception: + entry_force = None + if entry_force is None or entry_force.shape != (3,): + continue + valid_force_entries.append(entry) + total_force += entry_force + if valid_force_entries: + self.force_entries_preset = valid_force_entries + logging.info(f" force entries: {len(valid_force_entries)}") + else: + logging.warning(" ⚠️ force_entries has no valid entries, fallback to forces") + valid_force_entries = None + + if valid_force_entries is None: + for force_config in self.config.forces: + if hasattr(force_config, 'get_total_force'): + # ForceConfig object. + total_force += force_config.get_total_force() + elif isinstance(force_config, dict) and 'external_force' in force_config: + # Compatibility format using a plain dict. + total_force += np.array(force_config['external_force'], dtype=np.float32) + else: + logging.warning(f"unknown force format: {type(force_config)}") + + logging.info(f" sum of external forces (Y-up coordinates): {total_force}") + + # Choose the loading strategy from the config. + if valid_force_entries is not None: + # Multiple localized loads, each with its own region. + self._setup_local_loading(total_force) + elif self.config.use_local_loading: + # Preferred mode: local loading. + self._setup_local_loading(total_force) + else: + # Fallback mode: global uniform loading. + logging.info(f" ℹ️ using global uniform loading mode") + total_force_tensor = torch.from_numpy(total_force).float().to(self.device) + num_nodes = self.nodes.shape[0] + self.forces = total_force_tensor[None, :].repeat(num_nodes, 1) + logging.info(f" 💨 distributed the total force uniformly to{num_nodes}nodes") + + logging.info(f"boundary conditions: {self.boundary_mask.sum().item()}fixed nodes") + logging.info(f"material properties: E={self.E:.2e}, ν={self.nu}, ρ={self.rho}") + + def _setup_local_loading(self, total_force: np.ndarray): + """Set up local loading on the selected seat/contact region. + + The total force is distributed uniformly across the selected nodes so + that sum(forces) equals total_force. + + Args: + total_force: Total force vector [3] in the Y-up frame, in Newtons. + """ + # Cache the total force for later updates. + self.total_force_preset = torch.from_numpy(total_force).float().to(self.device) + + # Reuse the generic update routine for the initial setup. + self._update_forces(initial_setup=True) + + def _update_forces(self, initial_setup: bool = False): + """Update the force distribution for the current mesh state. + + Core logic: + 1. Re-identify contact nodes + 2. Spread the preset total force uniformly over those nodes + 3. Keep total force conserved + + Args: + initial_setup: Whether this is the first setup pass. + """ + if not hasattr(self, 'total_force_preset'): + logging.warning("No preset total force is set, so the force distribution cannot be updated") + return + + # Step 1: inspect the Y-coordinate distribution. + y_coords = self.nodes[:, 1] + num_nodes = self.nodes.shape[0] + + force_entries = getattr(self, "force_entries_preset", None) + if force_entries: + def _select_nodes_for_mode(mode, top_percent, min_ratio, max_ratio, bbox, bbox_ratio): + seat_mask = torch.zeros(num_nodes, dtype=torch.bool, device=self.device) + mode_used = mode + bbox_desc = None + + if mode_used not in ("top_percent", "height_ratio", "bbox", "global"): + logging.warning(f" ⚠️ invalid force_region_mode: {mode_used}, fallback to top_percent") + mode_used = "top_percent" + + if mode_used == "global": + seat_mask[:] = True + return seat_mask, mode_used, bbox_desc + + if mode_used == "bbox": + bbox_vals = None + if bbox is not None and len(bbox) == 6: + bbox_vals = [float(v) for v in bbox] + bbox_desc = "abs" + elif bbox_ratio is not None and len(bbox_ratio) == 6: + bbox_ratio_vals = [float(v) for v in bbox_ratio] + bounds_min = self.nodes.min(dim=0).values + bounds_max = self.nodes.max(dim=0).values + bbox_vals = [ + bounds_min[0].item() + bbox_ratio_vals[0] * (bounds_max[0] - bounds_min[0]).item(), + bounds_min[0].item() + bbox_ratio_vals[1] * (bounds_max[0] - bounds_min[0]).item(), + bounds_min[1].item() + bbox_ratio_vals[2] * (bounds_max[1] - bounds_min[1]).item(), + bounds_min[1].item() + bbox_ratio_vals[3] * (bounds_max[1] - bounds_min[1]).item(), + bounds_min[2].item() + bbox_ratio_vals[4] * (bounds_max[2] - bounds_min[2]).item(), + bounds_min[2].item() + bbox_ratio_vals[5] * (bounds_max[2] - bounds_min[2]).item(), + ] + bbox_desc = "ratio" + else: + logging.warning(" ⚠️ bbox mode did not provide a valid bbox, fallback to top_percent") + mode_used = "top_percent" + + if mode_used == "bbox" and bbox_vals is not None: + x0, x1 = sorted([bbox_vals[0], bbox_vals[1]]) + y0, y1 = sorted([bbox_vals[2], bbox_vals[3]]) + z0, z1 = sorted([bbox_vals[4], bbox_vals[5]]) + seat_mask = ( + (self.nodes[:, 0] >= x0) & (self.nodes[:, 0] <= x1) + & (self.nodes[:, 1] >= y0) & (self.nodes[:, 1] <= y1) + & (self.nodes[:, 2] >= z0) & (self.nodes[:, 2] <= z1) + ) + if seat_mask.sum().item() < 1: + logging.warning(" ⚠️ bbox region matched no nodes, fallback to top_percent") + mode_used = "top_percent" + else: + bbox_desc = f"{bbox_desc}: [{x0:.3f},{x1:.3f}]x[{y0:.3f},{y1:.3f}]x[{z0:.3f},{z1:.3f}]" + + if mode_used == "height_ratio": + y_min = y_coords.min().item() + y_max = y_coords.max().item() + y_range = max(1e-8, y_max - y_min) + if not (0.0 <= min_ratio < max_ratio <= 1.0): + logging.warning( + f" ⚠️ invalid height_ratio: min={min_ratio}, max={max_ratio}, fallback to top_percent" + ) + mode_used = "top_percent" + else: + seat_y_min = y_min + y_range * min_ratio + seat_y_max = y_min + y_range * max_ratio + seat_mask = (y_coords >= seat_y_min) & (y_coords <= seat_y_max) + if seat_mask.sum().item() < 1: + logging.warning(" ⚠️ height_ratio matched no nodes, fallback to top_percent") + mode_used = "top_percent" + + if mode_used == "top_percent": + top_percent = float(top_percent) + top_percent = max(0.0, min(1.0, top_percent)) + if top_percent <= 0.0: + top_percent = 0.05 + num_seat_nodes = max(1, int(num_nodes * top_percent)) + _, top_indices = torch.topk(y_coords, k=num_seat_nodes, largest=True) + seat_mask = torch.zeros(num_nodes, dtype=torch.bool, device=self.device) + seat_mask[top_indices] = True + + return seat_mask, mode_used, bbox_desc + + self.forces = torch.zeros((num_nodes, 3), dtype=torch.float32, device=self.device) + combined_mask = torch.zeros(num_nodes, dtype=torch.bool, device=self.device) + total_force = torch.zeros(3, dtype=torch.float32, device=self.device) + + for idx, entry in enumerate(force_entries): + if not isinstance(entry, dict): + continue + entry_label = entry.get("label") or entry.get("name") or f"{idx+1}" + entry_force = None + if "forces" in entry and isinstance(entry["forces"], list): + try: + entry_force = np.sum(np.array(entry["forces"], dtype=np.float32), axis=0) + except Exception: + entry_force = None + if entry_force is None and "force" in entry: + try: + entry_force = np.array(entry["force"], dtype=np.float32) + except Exception: + entry_force = None + if entry_force is None or entry_force.shape != (3,): + logging.warning(f" ⚠️ invalid force entry[{entry_label}], skip") + continue + + entry_force_tensor = torch.from_numpy(entry_force).float().to(self.device) + total_force += entry_force_tensor + + mode = str(entry.get("force_region_mode", self.config.force_region_mode)).lower() + if entry.get("global_loading") is True: + mode = "global" + + top_percent = entry.get("force_top_percent", self.config.force_top_percent) + min_ratio = entry.get("seat_height_min_ratio", self.config.seat_height_min_ratio) + max_ratio = entry.get("seat_height_max_ratio", self.config.seat_height_max_ratio) + bbox = entry.get("force_bbox", self.config.force_bbox) + bbox_ratio = entry.get("force_bbox_ratio", self.config.force_bbox_ratio) + + seat_nodes_mask, mode_used, bbox_desc = _select_nodes_for_mode( + mode, top_percent, min_ratio, max_ratio, bbox, bbox_ratio + ) + + num_seat_nodes = int(seat_nodes_mask.sum().item()) + if num_seat_nodes < 1: + logging.warning(f" ⚠️ entry[{entry_label}]matched no nodes, skip") + continue + + force_per_node = entry_force_tensor / num_seat_nodes + self.forces[seat_nodes_mask] += force_per_node + combined_mask |= seat_nodes_mask + + seat_y_values = y_coords[seat_nodes_mask] + seat_y_min = seat_y_values.min().item() + seat_y_max = seat_y_values.max().item() + seat_y_mean = seat_y_values.mean().item() + + if initial_setup: + if mode_used == "bbox": + logging.info(f" 🪑 contact surface[{entry_label}]: bbox ({bbox_desc})") + elif mode_used == "height_ratio": + logging.info( + f" 🪑 contact surface[{entry_label}]: height_ratio " + f"[{min_ratio:.2f}, {max_ratio:.2f}]" + ) + elif mode_used == "global": + logging.info(f" 🪑 contact surface[{entry_label}]: global") + else: + logging.info( + f" 🪑 contact surface[{entry_label}]: highest-Y {float(top_percent):.1%} nodes" + ) + logging.info( + f" 🪑 seat-node count[{entry_label}]: {num_seat_nodes}/{num_nodes} " + f"({num_seat_nodes/num_nodes:.1%})" + ) + logging.info( + f" 🪑 Y range[{entry_label}]: [{seat_y_min:.3f}, {seat_y_max:.3f}], " + f"mean: {seat_y_mean:.3f}" + ) + logging.info(f" 💺 force[{entry_label}]: {entry_force}") + logging.info(f" 💺 per node[{entry_label}]: {force_per_node.cpu().numpy()}") + + self.total_force_preset = total_force + actual_total_force = self.forces.sum(dim=0) + force_error = torch.norm(actual_total_force - total_force).item() + force_error_percent = (force_error / (torch.norm(total_force).item() + 1e-10)) * 100 + + if initial_setup: + logging.info( + f" ✅ total-force check: {actual_total_force.cpu().numpy()} " + f"(error: {force_error:.2e}, {force_error_percent:.3f}%)" + ) + if combined_mask.any(): + self._save_force_visualization( + combined_mask, total_force.cpu().numpy() + ) + else: + logging.debug( + f" 🔄 force update: loaded nodes {int(combined_mask.sum().item())}, " + f"total force error {force_error:.2e}" + ) + + self._last_num_seat_nodes = int(combined_mask.sum().item()) + return + + # Contact-region selection supports top_percent / height_ratio / bbox. + mode = str(getattr(self.config, "force_region_mode", "top_percent")).lower() + seat_nodes_mask = torch.zeros(num_nodes, dtype=torch.bool, device=self.device) + mode_used = mode + bbox_desc = None + if mode_used not in ("top_percent", "height_ratio", "bbox"): + logging.warning(f" ⚠️ invalid force_region_mode: {mode_used}, fallback to top_percent") + mode_used = "top_percent" + + if mode_used == "bbox": + bbox = getattr(self.config, "force_bbox", None) + bbox_ratio = getattr(self.config, "force_bbox_ratio", None) + bbox_vals = None + if bbox is not None and len(bbox) == 6: + bbox_vals = [float(v) for v in bbox] + bbox_desc = "abs" + elif bbox_ratio is not None and len(bbox_ratio) == 6: + bbox_ratio_vals = [float(v) for v in bbox_ratio] + bounds_min = self.nodes.min(dim=0).values + bounds_max = self.nodes.max(dim=0).values + bbox_vals = [ + bounds_min[0].item() + bbox_ratio_vals[0] * (bounds_max[0] - bounds_min[0]).item(), + bounds_min[0].item() + bbox_ratio_vals[1] * (bounds_max[0] - bounds_min[0]).item(), + bounds_min[1].item() + bbox_ratio_vals[2] * (bounds_max[1] - bounds_min[1]).item(), + bounds_min[1].item() + bbox_ratio_vals[3] * (bounds_max[1] - bounds_min[1]).item(), + bounds_min[2].item() + bbox_ratio_vals[4] * (bounds_max[2] - bounds_min[2]).item(), + bounds_min[2].item() + bbox_ratio_vals[5] * (bounds_max[2] - bounds_min[2]).item(), + ] + bbox_desc = "ratio" + else: + logging.warning(" ⚠️ bbox mode did not provide a valid bbox, fallback to top_percent") + mode_used = "top_percent" + + if mode_used == "bbox" and bbox_vals is not None: + x0, x1 = sorted([bbox_vals[0], bbox_vals[1]]) + y0, y1 = sorted([bbox_vals[2], bbox_vals[3]]) + z0, z1 = sorted([bbox_vals[4], bbox_vals[5]]) + seat_nodes_mask = ( + (self.nodes[:, 0] >= x0) & (self.nodes[:, 0] <= x1) + & (self.nodes[:, 1] >= y0) & (self.nodes[:, 1] <= y1) + & (self.nodes[:, 2] >= z0) & (self.nodes[:, 2] <= z1) + ) + if seat_nodes_mask.sum().item() < 1: + logging.warning(" ⚠️ bbox region matched no nodes, fallback to top_percent") + mode_used = "top_percent" + else: + bbox_desc = f"{bbox_desc}: [{x0:.3f},{x1:.3f}]x[{y0:.3f},{y1:.3f}]x[{z0:.3f},{z1:.3f}]" + + if mode_used == "height_ratio": + y_min = y_coords.min().item() + y_max = y_coords.max().item() + y_range = max(1e-8, y_max - y_min) + min_ratio = float(self.config.seat_height_min_ratio) + max_ratio = float(self.config.seat_height_max_ratio) + if not (0.0 <= min_ratio < max_ratio <= 1.0): + logging.warning( + f" ⚠️ invalid height_ratio: min={min_ratio}, max={max_ratio}, fallback to top_percent" + ) + mode_used = "top_percent" + else: + seat_y_min = y_min + y_range * min_ratio + seat_y_max = y_min + y_range * max_ratio + seat_nodes_mask = (y_coords >= seat_y_min) & (y_coords <= seat_y_max) + if seat_nodes_mask.sum().item() < 1: + logging.warning(" ⚠️ height_ratio matched no nodes, fallback to top_percent") + mode_used = "top_percent" + + if mode_used == "top_percent": + top_percent = float(getattr(self.config, "force_top_percent", 0.05)) + top_percent = max(0.0, min(1.0, top_percent)) + if top_percent <= 0.0: + top_percent = 0.05 + num_seat_nodes = max(1, int(num_nodes * top_percent)) + _, top_indices = torch.topk(y_coords, k=num_seat_nodes, largest=True) + seat_nodes_mask = torch.zeros(num_nodes, dtype=torch.bool, device=self.device) + seat_nodes_mask[top_indices] = True + + num_seat_nodes = int(seat_nodes_mask.sum().item()) + + # Step 3: gather region statistics. + seat_y_values = y_coords[seat_nodes_mask] + seat_y_min = seat_y_values.min().item() + seat_y_max = seat_y_values.max().item() + seat_y_mean = seat_y_values.mean().item() + + # Step 4: computation the per-node load with uniform distribution. + force_per_node = self.total_force_preset / num_seat_nodes + + # Initialize all node forces to zero. + self.forces = torch.zeros((num_nodes, 3), dtype=torch.float32, device=self.device) + + # Apply force only to the selected seat/contact nodes. + self.forces[seat_nodes_mask] = force_per_node + + # Step 5: verify total-force conservation. + actual_total_force = self.forces.sum(dim=0) + force_error = torch.norm(actual_total_force - self.total_force_preset).item() + force_error_percent = (force_error / torch.norm(self.total_force_preset).item()) * 100 + + # Logging. + if initial_setup: + if mode_used == "bbox": + logging.info(f" 🪑 contact-surface setup: bbox ({bbox_desc})") + elif mode_used == "height_ratio": + logging.info( + f" 🪑 contact-surface setup: height_ratio " + f"[{self.config.seat_height_min_ratio:.2f}, {self.config.seat_height_max_ratio:.2f}]" + ) + else: + logging.info( + f" 🪑 contact-surface setup: highest-Y {float(getattr(self.config, 'force_top_percent', 0.05)):.1%} nodes" + ) + logging.info(f" 🪑 seat-node count: {num_seat_nodes}/{num_nodes} ({num_seat_nodes/num_nodes:.1%})") + logging.info(f" 🪑 Y-coordinate range: [{seat_y_min:.3f}, {seat_y_max:.3f}], mean: {seat_y_mean:.3f}") + logging.info(f" 💺 preset total force: {self.total_force_preset.cpu().numpy()}") + logging.info(f" 💺 force per node: {force_per_node.cpu().numpy()}") + logging.info(f" ✅ total-force check: {actual_total_force.cpu().numpy()} (error: {force_error:.2e}, {force_error_percent:.3f}%)") + + # Estimate the equivalent pressure. + y_range = y_coords.max().item() - y_coords.min().item() + grid_spacing = y_range / self.config.res if y_range > 0 else 0.01 + estimated_area = num_seat_nodes * (grid_spacing ** 2) + if estimated_area > 0 and abs(self.total_force_preset[1].item()) > 0: + pressure_kpa = abs(self.total_force_preset[1].item()) / estimated_area / 1000 + logging.info(f" 📏 equivalent pressure: {pressure_kpa:.1f} kPa (contact area≈{estimated_area:.4f} m²)") + + if pressure_kpa < 5: + logging.warning(f" ⚠️ pressure is too small ({pressure_kpa:.1f} kPa < 5 kPa)") + elif pressure_kpa > 50: + logging.warning(f" ⚠️ pressure is too large ({pressure_kpa:.1f} kPa > 50 kPa)") + + # Save visualization data. + self._save_force_visualization(seat_nodes_mask, self.total_force_preset.cpu().numpy()) + else: + # Shorter logging during optimization. + logging.debug(f" 🔄 force update: seat nodes {num_seat_nodes}, per node {force_per_node.cpu().numpy()}, " + f"total force error {force_error:.2e}") + + # Watch for changes in the number of loaded nodes. + if hasattr(self, '_last_num_seat_nodes') and self._last_num_seat_nodes != num_seat_nodes: + logging.info(f" ⚠️ seat-node count changed: {self._last_num_seat_nodes} → {num_seat_nodes}") + + # Cache the current state for the next comparison. + self._last_num_seat_nodes = num_seat_nodes + + def extract_solid(self, step: int = -1): + """Extract the physical solid by querying the node SDF directly. + + This method rebuilds the FEM mesh from the current latents so topology + changes in the SDF field can be reflected by the simulation mesh. + + Args: + step: Current optimization step, used for logging. + """ + if not WARP_AVAILABLE: + logging.warning("Warpnot installed, unable toperformphysics simulation") + return + + # Re-check physiopt availability at runtime. + try: + from physiopt.utils.phys_utils import generate_hex as _generate_hex + from physiopt.utils.grid_utils import filter_one_component as _filter_one_component + from physiopt.opt.field import occ_kernel as _occ_kernel + generate_hex_func = _generate_hex + filter_one_component_func = _filter_one_component + occ_kernel_func = _occ_kernel + logging.info("✅ physioptmoduleruntime check succeeded") + except ImportError as e: + logging.error(f"physioptmodulenot installed: {e}") + logging.error("please make sure physiopt is installed correctly: cd /mnt/cvlab/scratch/cvlab/home/hantzhan/physiopt && pip install -e .") + return + + res = self.config.res + step_label = f"Step {step}" if step >= 0 else "Initialization" + logging.info(f"{'🔄' if step >= 0 else '🆕'} [{step_label}] generate/update a mesh at resolution {res} hexahedral mesh...") + + # Keep the previous mesh size for comparison. + old_num_nodes = len(self.nodes) if hasattr(self, 'nodes') else 0 + old_num_elements = len(self.elements) if hasattr(self, 'elements') else 0 + + # 1. Generate the full hexahedral grid. + full_nodes, full_elements = generate_hex_func( + res=res, + limits=[(-0.8, 0.8), (-0.8, 0.8), (-0.8, 0.8)], + device=self.device, + return_coords=False + ) + + if full_nodes is None or full_elements is None: + logging.error("failed to generate the hexahedral mesh") + return + + full_nodes = full_nodes.to(self.device).float() + full_elements = full_elements.to(self.device).long() + + logging.info(f"hexahedral mesh generated successfully: {full_nodes.shape[0]}nodes, {full_elements.shape[0]}elements") + + # 2. Query the SDF directly through get_field. + logging.info("query node SDF values...") + sdf = self.get_field(full_nodes) + + # Make sure the SDF is a 1D tensor [N]. + if sdf.dim() > 1: + logging.warning(f"⚠️ SDFYesmulti-dimensional tensor: {sdf.shape}, will be flattened to 1D") + sdf = sdf.squeeze() # remove all size-1 dimensions + if sdf.dim() > 1: + sdf = sdf.reshape(-1) # force-flatten to 1D + + logging.info(f" ✅ SDF query succeeded: range=[{sdf.min():.3f}, {sdf.max():.3f}]") + logging.info(f" nodescount: {full_nodes.shape[0]}, SDF count: {sdf.shape[0]}") + + # Verify that the SDF count matches the node count. + if sdf.shape[0] != full_nodes.shape[0]: + logging.error(f"❌ SDF count({sdf.shape[0]}) vs. node count ({full_nodes.shape[0]})do not match!") + return + + # 3. Convert SDF values to occupancy. + logging.info("convert the SDF into an occupancy field...") + occ = occ_kernel_func(sdf, res, self.config.occ_sdf_beta) + + # 4. Select solid elements using an SDF threshold instead of an + # occupancy threshold. The threshold is intentionally relaxed so thin + # structures such as chair legs are kept. + SDF_FILTER_VALUE = 2.0 / res + nodewise_mask = sdf <= SDF_FILTER_VALUE + + # Diagnostic SDF statistics. + sdf_inside = sdf[nodewise_mask] + sdf_outside = sdf[~nodewise_mask] + logging.info(f" SDF threshold: {SDF_FILTER_VALUE:.4f}") + logging.info(f" interior nodes: {nodewise_mask.sum().item()}/{len(sdf)} ({100*nodewise_mask.sum().item()/len(sdf):.1f}%)") + if len(sdf_inside) > 0: + logging.info(f" inner SDF range: [{sdf_inside.min():.4f}, {sdf_inside.max():.4f}]") + if len(sdf_outside) > 0: + logging.info(f" outside-SDF range: [{sdf_outside.min():.4f}, {sdf_outside.max():.4f}]") + + # Debug the element-index range. + max_elem_idx = full_elements.max().item() + num_nodes = full_nodes.shape[0] + logging.info(f" elementsindex range: [0, {max_elem_idx}], nodescount: {num_nodes}") + + if max_elem_idx >= num_nodes: + logging.error(f"❌ index out of bounds!maximum element index({max_elem_idx}) >= nodescount({num_nodes})") + logging.error(f" this may be a problem with generate_hex") + # Clamp indices to the valid range. + valid_mask = (full_elements >= 0) & (full_elements < num_nodes) + if not valid_mask.all(): + logging.warning(f" found{(~valid_mask).sum().item()} invalid indices; filtering elements") + # Keep only elements whose node indices are all valid. + valid_elements_mask = valid_mask.all(dim=1) + full_elements = full_elements[valid_elements_mask] + logging.info(f" element count after filtering: {full_elements.shape[0]}") + + # Keep an element if any of its nodes passes the threshold. + elementwise_mask = torch.any(nodewise_mask[full_elements], dim=1) + + num_solid_elements = elementwise_mask.sum().item() + logging.info(f"SDF thresholdfiltering: {num_solid_elements}/{len(elementwise_mask)} solid elements") + + if num_solid_elements == 0: + logging.error("No solid elements were found; please check the SDF or adjust the threshold") + return + + # 5. Optionally keep only one connected component. + if self.config.one_cc_only: + element_res = res - 1 + try: + num_before_filter = elementwise_mask.sum().item() + elementwise_mask = filter_one_component_func(elementwise_mask, element_res) + num_filtered_elements = elementwise_mask.sum().item() + num_removed = num_before_filter - num_filtered_elements + logging.info(f"connectivity filtering: {num_filtered_elements} elements kept (removed{num_removed} small components)") + if num_removed > num_filtered_elements * 0.1: + logging.warning(f" ⚠️ removed{num_removed}elements({100*num_removed/num_before_filter:.1f}%), may have filtered out important parts (such as chair legs) ") + logging.warning(f" Suggestion: check the SDF threshold or consider disabling one_cc_only") + except IndexError as e: + logging.warning(f"connectivity filteringfailed: {e}, using the original mask") + else: + logging.info("connectivity filteringdisabled, keep all connected components") + + # 6. Select the active elements and nodes. + selected_elements = full_elements[elementwise_mask] + selected_node_indices, selected_elements = torch.unique( + selected_elements, return_inverse=True + ) + + self.elements = selected_elements + self.nodes = full_nodes[selected_node_indices] + + # 7. Compute occupancy for the selected nodes used in the simulation. + coarse_sdf = sdf[selected_node_indices] + coarse_occ_nodes = occ_kernel_func( + coarse_sdf, self.config.res, self.config.occ_sdf_beta + ) + # Each element occupancy is the mean over its 8 nodes. + self.coarse_occ = coarse_occ_nodes[self.elements].mean(1) + + # Diagnostic statistics for mesh-size changes. + new_num_nodes = len(self.nodes) + new_num_elements = len(self.elements) + + if old_num_nodes > 0: + node_change = new_num_nodes - old_num_nodes + element_change = new_num_elements - old_num_elements + node_change_pct = (node_change / old_num_nodes) * 100 + element_change_pct = (element_change / old_num_elements) * 100 + + logging.info(f"✅ solid extraction completed:") + logging.info(f" nodes: {old_num_nodes} → {new_num_nodes} ({node_change:+d}, {node_change_pct:+.1f}%)") + logging.info(f" elements: {old_num_elements} → {new_num_elements} ({element_change:+d}, {element_change_pct:+.1f}%)") + + if node_change > 0: + logging.info(f" ✅ mesh expanded!added{node_change}nodes (chair legs may have thickened) ") + elif node_change < 0: + logging.warning(f" ⚠️ mesh shrank!removed{-node_change}nodes (chair legs may have become thinner) ") + else: + logging.info(f"✅ solid extraction succeeded: {new_num_nodes}nodes, {new_num_elements}elements") + + # 8. Recomputation the boundary mask because the node count may change. + y_coords = self.nodes[:, 1] + y_min = y_coords.min() + boundary_threshold = y_min + 0.05 # bottom 5% region + self.boundary_mask = y_coords < boundary_threshold + + num_boundary = self.boundary_mask.sum().item() + logging.debug(f" 🔧 boundary conditionsupdated: {num_boundary}fixed nodes (Y < {boundary_threshold:.3f})") + + def get_current_sds_weight(self, step: int) -> float: + """Return the current SDS weight by linear interpolation. + + Args: + step: Current optimization step. + + Returns: + The SDS weight interpolated from sds_weight_start to sds_weight_end. + """ + # Linear interpolation from sds_weight_start to sds_weight_end. + progress = min(1.0, step / max(1, self.config.num_steps - 1)) + current_weight = self.config.sds_weight_start + progress * (self.config.sds_weight_end - self.config.sds_weight_start) + return current_weight + + def _computation_target_z0_current(self, step: int, noise=None) -> Tuple[torch.Tensor, torch.Tensor]: + """Compute the current target_z0 for one update.""" + noise_level = float(self.config.sds_timestep) + t = 1.0 - noise_level # Hunyuan3D-2.1 uses t=0 for noise and t=1 for data. + if noise is None: + epsilon = torch.randn_like(self.latents) + else: + epsilon = noise + self.sds_scheduler.config.num_train_timesteps = 10 + # Match the official Flow Matching noise process: + # x_t = (1 - sigma) * x0 + sigma * eps. + sigma_step = 1.0 / float(self.sds_scheduler.config.num_train_timesteps) + total_span = max(0.0, 1.0 - t) + num_steps = int(np.ceil(total_span / sigma_step)) + sigmas = np.linspace(t, 1.0, num_steps + 1, dtype=np.float32) + self.sds_scheduler.set_timesteps(sigmas=sigmas, device=self.device) + t_scheds = self.sds_scheduler.timesteps + t_sched0 = t_scheds[0] + t_model0 = (t_sched0 / self.sds_scheduler.config.num_train_timesteps).to(self.latents.dtype) + logging.info( + f" 🎯 target_z0/sigmaalign: noise={noise_level:.4f}, t_start={t:.4f}, " + f"t_sched={t_sched0.item():.2f}, t_model={t_model0.item():.6f}, " + f"steps={num_steps}, sigma_step={sigma_step:.4g}" + ) + + # with torch.no_grad(): + with torch.enable_grad(): + + # Integrate over multiple small sigma steps from sigma=t to 0. + cond_for_model = self._get_cond_for_guidance(self.config.guidance_scale > 1.0) + t_sched0 = t_scheds[0] + # t_sched_batch = t_sched0.reshape(1).expand(self.latents.shape[0]) + # Hunyuan3D convention: t=0 is noise and t=1 is data. + # z_t = self.sds_scheduler.scale_noise(epsilon, t_sched_batch, noise=self.latents) + + z_curr = epsilon + velocity = None + + for i in range(len(t_scheds) - 1): + logging.info(f"Step {i}...") + t_sched = t_scheds[i] + t_model = (t_sched / self.sds_scheduler.config.num_train_timesteps).to(self.latents.dtype) + z_t_fp16 = z_curr.to(torch.float16) + t_tensor = t_model.to(device=self.device, dtype=z_t_fp16.dtype) + + if self.config.guidance_scale > 1.0: + + latent_model_input = torch.cat([z_t_fp16, z_t_fp16]) + timestep_input = t_tensor.expand(latent_model_input.shape[0]) + + velocity_pred_fp16 = self.flow_model( + latent_model_input, + timestep_input, + cond_for_model, + guidance=None, + ) + + velocity_cond_fp16, velocity_uncond_fp16 = velocity_pred_fp16.chunk(2) + velocity_fp16 = velocity_uncond_fp16 + self.config.guidance_scale * (velocity_cond_fp16 - velocity_uncond_fp16) + + if i % 10 == 0 and i == 0: + logging.debug( + f" CFG (SDS): guidance_scale={self.config.guidance_scale:.1f}, " + f"||v_cond||={torch.norm(velocity_cond_fp16).item():.3e}, " + f"||v_uncond||={torch.norm(velocity_uncond_fp16).item():.3e}" + ) + else: + velocity_fp16 = self.flow_model( + z_t_fp16, + t_tensor.expand(z_t_fp16.shape[0]), + cond_for_model, + guidance=None, + ) + + velocity = velocity_fp16.to(torch.float32) + z_curr = self.sds_scheduler.step(velocity, t_sched, z_curr).prev_sample + target_z0_current = z_curr + + return target_z0_current, velocity + + def _get_target_z0(self, step: int) -> Tuple[torch.Tensor, Optional[torch.Tensor], bool]: + """Update target_z0 on schedule and smooth it with EMA.""" + update_interval = max(1, int(self.config.sds_target_z0_update_interval)) + do_update = self.target_z0_ema is None or step % update_interval == 0 + + if do_update: + target_z0_current, velocity = self._computation_target_z0_current(step) + target_z0_current = target_z0_current.detach() + + if self.target_z0_ema is None: + self.target_z0_ema = target_z0_current.clone() + diff_norm = 0.0 + else: + diff = target_z0_current - self.target_z0_ema + diff_norm = torch.norm(diff).item() + alpha = 1.0 - self.config.sds_target_z0_ema_beta + self.target_z0_ema = self.target_z0_ema + alpha * diff + + self.target_z0_last_velocity = velocity + self.target_z0_last_update = step + + if step % update_interval == 0: + logging.info( + f" 🧭 target_z0 EMAupdate: interval={update_interval}, " + f"beta={self.config.sds_target_z0_ema_beta:.2f}, diff_norm={diff_norm:.3e}" + ) + else: + velocity = self.target_z0_last_velocity + + return self.target_z0_ema, velocity, do_update + + def project_to_manifold(self, step: int) -> bool: + """Project the current latents back to the manifold by replacing them with target_z0.""" + with torch.no_grad(): + target_z0, _ = self._computation_target_z0_current(step) + if torch.isnan(target_z0).any() or torch.isinf(target_z0).any(): + logging.warning(" ⚠️ projection failed: target_z0 contains NaN/Inf") + return False + deviation = torch.norm(target_z0 - self.latents).item() + latents_norm = torch.norm(self.latents).item() + rel = deviation / (latents_norm + 1e-8) + logging.info(f" 🧭 projection deviation: {deviation:.3e} (rel={rel:.2%})") + self.latents.data.copy_(target_z0) + if self.latents.grad is not None: + self.latents.grad.zero_() + # Reset optimizer state to avoid stale momentum. + self.optimizer.state.clear() + # Sync the EMA cache with the projected state. + self.target_z0_ema = target_z0.detach().clone() + self.target_z0_last_velocity = None + self.target_z0_last_update = step + return True + + def training_step_sds(self, step: int) -> Tuple[float]: + """Run one SDS optimization step. + + Returns: + (recon_loss,) + """ + self.optimizer.zero_grad() + + # ==================== SDS loss (Rectified Flow) ==================== + t = self.config.sds_timestep + target_z0, velocity, _ = self._get_target_z0(step) + + # SDS gradient: grad = z_0 - target_z0. + # This pulls the current z_0 (self.latents) toward target_z0. + sds_gradient = self.latents - target_z0.detach() + recon_loss = torch.mean(sds_gradient ** 2) / 2 + + # Debug information. + with torch.no_grad(): + target_norm = torch.norm(target_z0).item() + current_norm = torch.norm(self.latents).item() + grad_norm = torch.norm(sds_gradient).item() + velocity_norm = torch.norm(velocity).item() if velocity is not None else 0.0 + + logging.info(f"📐 Step {step:3d} | SDS: ||z_0||={current_norm:.2e}, " + f"||target_z_0||={target_norm:.2e}, " + f"||v||={velocity_norm:.2e}, " + f"||∇||={grad_norm:.2e}, t={t:.2f}, loss={recon_loss.item():.6e}") + + # Backpropagation. + sds_gradient_scaled = self.config.sds_weight * sds_gradient + + # Guard against invalid gradients. + if torch.isnan(sds_gradient_scaled).any() or torch.isinf(sds_gradient_scaled).any(): + logging.error(f"❌ Error: SDS gradient contains NaN or Inf!") + logging.error(f" ||sds_gradient||: {grad_norm:.2e}") + logging.error(f" sds_weight: {self.config.sds_weight}") + logging.error(f" target_z0 range: [{target_z0.min().item():.2e}, {target_z0.max().item():.2e}]") + logging.error(f" latents range: [{self.latents.min().item():.2e}, {self.latents.max().item():.2e}]") + if velocity is not None: + logging.error(f" velocity range: [{velocity.min().item():.2e}, {velocity.max().item():.2e}]") + return (recon_loss.item(),) + + if self.latents.grad is not None: + self.latents.grad.zero_() + + self.latents.grad = sds_gradient_scaled + + # Optional gradient clipping. + if self.config.grad_clip_enabled: + grad_norm_total = torch.norm(self.latents.grad).item() + max_grad_norm = 100.0 # 1e5lower to100 + if grad_norm_total > max_grad_norm: + clip_factor = max_grad_norm / grad_norm_total + self.latents.grad *= clip_factor + logging.warning(f"⚠️ gradient clipping: {grad_norm_total:.4e} -> {max_grad_norm:.4e}") + + # Save the pre-update latents for diagnostics. + old_latents = self.latents.data.clone() + + # Re-check the gradient before the optimizer step. + if torch.isnan(self.latents.grad).any(): + logging.error(f"❌ Error: gradient contains NaN (optimizerupdatefront) !") + return (recon_loss.item(),) + + # Optimizer update. + self.optimizer.step() + + # Measure parameter change after the update. + param_change = torch.norm(self.latents.data - old_latents).item() + + # Validate the updated latents. + if torch.isnan(self.latents).any(): + logging.error(f"❌ Error: latents contain NaN (optimizerupdateback) !") + logging.error(f" gradient norm: {grad_norm_total:.4e}") + logging.error(f" Learning rate: {self.config.lr}") + logging.error(f" Param change: {param_change:.4e}") + logging.error(f" suggestion: this may be caused by Adam optimizer momentum") + logging.error(f" : 1) reset optimizer 2) Use SGD instead of Adam") + # Restore the previous value. + self.latents.data.copy_(old_latents) + # Clear optimizer momentum/state before retrying. + self.optimizer.state.clear() + logging.info(f" ✅ already reset optimizerStatus, will retry on the next step") + return (recon_loss.item(),) + + # Sanity-check the latent magnitude. + latents_max = torch.abs(self.latents).max().item() + if latents_max > 1000: + logging.warning(f"⚠️ warning: latent values are too large (max={latents_max:.2e})") + logging.warning(f" you may need to lower the learning rate or SDS timestep") + + logging.info(f"✏️ Step {step:3d} | Param change: {param_change:.4e}, max|z|: {latents_max:.2e}") + + return (recon_loss.item(),) + + def training_step( + self, + step: int, + lagrange: float, + rho: float, + use_sds: bool = True, + save_step: Optional[int] = None, + ) -> Tuple[float, float, float]: + """Physics optimization. + + This follows the computation_phys_loss_grad flow from viewer_base.py: + 1. optimizer.zero_grad() + 2. with torch.no_grad(): prepare_solid() + solve() + 3. Compute sensitivities with the reference-style formula + 4. backward_step() via VJP + 5. Apply ALM weighting (lambda + rho[g]_+) + 6. optimizer.step() + + Reference: + physiopt/src/physiopt/vis/viewer_base.py Line 1297-1430 + """ + save_step_id = step if save_step is None else int(save_step) + + # ==================== Step 1: zero gradients ==================== + self.optimizer.zero_grad() + + # ==================== Step 2: update occupancy on the fixed topology ==================== + if step > 0: + logging.info(f"🔄 [Step {step}] update occupancy (mesh topology fixed) ...") + # Keep the previous occupancy for diagnostics. + old_occ = self.coarse_occ.clone() + + # Re-query the SDF and occupancy on the fixed mesh. + sdf = self.get_field(self.nodes) + from physiopt.opt.field import occ_kernel + occ = occ_kernel(sdf, self.config.res, self.config.occ_sdf_beta) + self.coarse_occ = occ[self.elements].mean(1) + + # Diagnose occupancy changes. + occ_change = self.coarse_occ - old_occ + occ_mean_change = occ_change.mean().item() + occ_increase_ratio = (occ_change > 0).float().mean().item() + + logging.info(f" occupancy range: [{self.coarse_occ.min():.3f}, {self.coarse_occ.max():.3f}]") + logging.info(f" occupancy change: mean={occ_mean_change:+.3e}, increase ratio={occ_increase_ratio:.1%}") + + # ==================== Step 3: physics simulation (with torch.no_grad) ==================== + # Aligned with the reference flow around Line 1317-1356. + with torch.no_grad(): + # 3.1 prepare_solid: apply SIMP scaling and build SolidGrid. + if self.config.alpha_min > 0.0: + self.coarse_occ = torch.clamp(self.coarse_occ, self.config.alpha_min) + + # Material SIMP scaling. + from torchfem.materials import IsotropicElasticity3D + from physiopt.opt.solid_grid import SolidGrid + + vectorized_material = IsotropicElasticity3D( + E=self.config.youngs_modulus, + nu=self.config.poissons_ratio, + rho=self.config.density, + ).vectorize(self.elements.shape[0]) + + vectorized_material.C *= ( + self.coarse_occ[:, None, None] ** self.config.p_exponent + ) + + # Create the SolidGrid solver state. + solid = SolidGrid(self.nodes, self.elements, vectorized_material) + solid.constraints[self.boundary_mask, :] = True + solid.forces = self.forces + + # 3.2 FEM solve. + logging.info(f"Step {step}: FEM solve...") + u, f_int, f_ext, sigma, _, _ = solid.solve(max_iter=1) + u_mean = torch.abs(u).mean().item() + logging.info(f" |u|_mean={u_mean}") + self._log_physical_quantities(u, sigma) + + # Save the deformed mesh every N steps. + # if self.config.deformed_mesh_interval > 0 and save_step_id % self.config.deformed_mesh_interval == 0: + # try: + # self.save_deformed_mesh(save_step_id, u) + # except Exception as e: + # logging.warning(f" ⚠️ error while saving the deformed mesh: {e}") + + # ==================== Step 4: sensitivity computation ==================== + # Strictly aligned with the reference flow around Line 1368-1399. + + # 4.1 Compute strain energy. We recover the unweighted energy by + # dividing out occ^p and keep strong numerical guards. + k0 = solid.k0() # occ^p * K_base after stiffness scaling. + u_j = u[self.elements].reshape(solid.n_elem, -1) + w_k_scaled = torch.einsum("...i, ...ij, ...j", u_j, k0, u_j) + + # Remove occ^p scaling to recover the base energy. + occ_power = torch.clamp( + self.coarse_occ ** self.config.p_exponent, + min=1e-6, # Avoid division by zero. + max=1.0 # Avoid overflow. + ) + + # Check again before division. + if torch.any(occ_power < 1e-6): + n_small = (occ_power < 1e-6).sum().item() + logging.warning(f" ⚠️ {n_small} elements have extremely small occ^p and were clamped to 1e-6") + + w_k_base = w_k_scaled / occ_power + + # Fall back if the recovered energy becomes invalid. + if torch.isnan(w_k_base).any() or torch.isinf(w_k_base).any(): + n_nan = torch.isnan(w_k_base).sum().item() + n_inf = torch.isinf(w_k_base).sum().item() + logging.error(f" ❌ w_k_baseabnormal: {n_nan} NaN, {n_inf} Inf") + logging.error(f" fall back to SIMP weightingw_k") + w_k_base = w_k_scaled + + # Use the recovered energy downstream. + compliance_mean = w_k_base.mean().item() + w_k = w_k_base # Downstream sensitivity uses the recovered energy. + + # Diagnostics. + logging.info(f" Compliance (true) ={compliance_mean:.2e}") + logging.info(f" w_k_base: max={w_k.max():.2e}, stress concentration={w_k.max()/(w_k.mean() + 1e-10):.1f}x") + + # ALM normalized constraint: g = D / D_thr - 1. + compliance_threshold = self.config.compliance_threshold if self.config.compliance_threshold is not None else 1.0 + g_raw = compliance_mean / (compliance_threshold + 1e-8) - 1.0 + g_pos = max(0.0, g_raw) + logging.info(f" constraint normalization: g={g_raw:+.3e}, [g]+={g_pos:.3e}, D_thr={compliance_threshold:.2e}") + + # Dynamic clip limit used by the ALM scaling guard. + base_max_grad = 1000.0 + lagrange_bonus = min((lagrange + rho * g_pos) * 10.0, 1000.0) + max_grad_norm = base_max_grad + lagrange_bonus + + # 4.3 Sensitivity formula aligned with the reference code: + # sensitivity = -p * occ^(p-1) * w_k + self.sensitivity_density = ( + -self.config.p_exponent + * self.coarse_occ ** (self.config.p_exponent - 1) + * w_k + ) + + # 4.4 Volume regularization is intentionally disabled here so the pure + # physics signal can be validated first. + if False and self.config.volume_term > 0.0: # Temporarily forced off. + # Initialize the reference volume on first use. + if not hasattr(self, 'init_volume'): + self.init_volume = self.coarse_occ.clone() + logging.info(f" record initial volume: sum={self.init_volume.sum().item():.2f}") + + # Volume sensitivity term. + sensitivity_volume = ( + self.config.volume_term + * (1.0 / self.config.res) ** 3 + * torch.ones_like(self.sensitivity_density) + ) + + # Choose the sign from the current volume change. + volume_sign = 1.0 if self.coarse_occ.sum() >= self.init_volume.sum() else -1.0 + sensitivity_volume *= volume_sign + + self.sensitivity_density += sensitivity_volume + + volume_ratio = self.coarse_occ.sum() / self.init_volume.sum() + logging.info(f" volume constraint: ratio={volume_ratio.item():.3f}, " + f"{'penalize' if volume_sign > 0 else 'encourage'}") + else: + logging.info(f" volume constraint: disabled (physicsoptimizationdominates) ") + + # Sensitivity diagnostics. + sens_norm = torch.norm(self.sensitivity_density).item() + sens_min = self.sensitivity_density.min().item() + sens_max = self.sensitivity_density.max().item() + logging.info(f" sensitivity: norm={sens_norm:.2e}, range=[{sens_min:.2e}, {sens_max:.2e}]") + + # ==================== Step 5: backward pass via VJP ==================== + self.backward_step(self.sensitivity_density) + + # ==================== Step 6: apply ALM weighting (lambda + rho[g]+) ==================== + if self.latents.grad is not None: + phys_grad_norm = torch.norm(self.latents.grad).item() + phys_grad_unscaled = self.latents.grad.clone() # Unscaled physics gradient for SDS comparisons. + + if g_pos > 0.0: + alm_scale_raw = (lagrange + rho * g_pos) / (compliance_threshold + 1e-8) + alm_scale = alm_scale_raw + guard_ratio = min(max(self.config.alm_scale_guard_ratio, 0.0), 1.0) + if phys_grad_norm > 0.0 and max_grad_norm > 0.0 and guard_ratio > 0.0: + alm_scale_guard = (max_grad_norm * guard_ratio) / (phys_grad_norm + 1e-8) + if alm_scale > alm_scale_guard: + logging.info( + f" 🔧 ALMscaling limit: raw={alm_scale_raw:.3e} -> {alm_scale_guard:.3e} " + f"(guard={guard_ratio:.2f}, max_grad={max_grad_norm:.1f})" + ) + alm_scale = alm_scale_guard + self.latents.grad *= alm_scale + else: + alm_scale = 0.0 + self.latents.grad.zero_() + + scaled_grad_norm = torch.norm(self.latents.grad).item() + logging.info( + f" physics gradient(ALM): {phys_grad_norm:.2e} → {scaled_grad_norm:.2e} " + f"(×scale={alm_scale:.3e}, λ={lagrange:.2f}, ρ={rho:.2f})" + ) + else: + phys_grad_unscaled = None + alm_scale = 0.0 + + # ==================== Step 7: shape loss toward target_z0 ==================== + + # 7.1 Compute the denoised target_z0. + import math + if use_sds: + target_z0, _, _ = self._get_target_z0(step) + else: + target_z0 = self.latents.detach() + + # Optionally validate and save a target_z0 mesh every 10 steps. + if use_sds: + self._maybe_save_target_z0_mesh(target_z0, save_step_id) + + # Shape loss is a simple MSE pulling latents toward target_z0. + shape_loss = torch.nn.functional.mse_loss(self.latents, target_z0.detach()) + + # 7.2 Decide whether shape loss is active this step. + current_sds_weight = self.get_current_sds_weight(step) if use_sds else 0.0 + use_sds_this_step = current_sds_weight > 0.0 + + if not use_sds_this_step: + logging.info(f" 🚫 Shape Loss disabled (physicsoptimizationmode) ") + weighted_sds = 0.0 + shape_grad_norm = 0.0 + else: + # Weighted shape loss. + weighted_shape_loss = current_sds_weight * shape_loss + + # Validate shape loss before backpropagating it. + if torch.isnan(shape_loss) or torch.isinf(shape_loss): + logging.error(f" ❌ Shape Loss contains NaN or Inf; skipping the shape constraint") + weighted_sds = 0.0 + shape_grad_norm = 0.0 + else: + # Backpropagate the shape loss into latents.grad. + weighted_shape_loss.backward() + + # Measure the shape-gradient norm for logging. + if self.latents.grad is not None and phys_grad_unscaled is not None: + # Isolate the shape part from the combined gradient. + shape_gradient = self.latents.grad - phys_grad_unscaled * alm_scale + shape_grad_norm = torch.norm(shape_gradient).item() + phys_grad_norm_current = torch.norm(phys_grad_unscaled * alm_scale).item() + shape_phys_ratio = shape_grad_norm / (phys_grad_norm_current + 1e-10) + + if shape_phys_ratio > 100.0: + logging.error(f" ❌ Shape gradient is too large (Shape/physics={shape_phys_ratio:.1f}x)!") + logging.error(f" consider lowering sds_weight_end: {self.config.sds_weight_end} → {self.config.sds_weight_end/100:.4f}") + elif shape_phys_ratio > 10.0: + logging.warning(f" ⚠️ Shape gradient is relatively large (Shape/physics={shape_phys_ratio:.1f}x)") + + # Compare the directions of physics and shape gradients. + cos_angle = (phys_grad_unscaled * shape_gradient).sum() / ( + torch.norm(phys_grad_unscaled) * torch.norm(shape_gradient) + 1e-10 + ) + angle_deg = torch.acos(torch.clamp(cos_angle, -1, 1)) * 180 / math.pi + direction = "same direction✅" if angle_deg < 90 else "opposite direction⚠️" + + logging.info(f" Shapegradient: norm={shape_grad_norm:.4e}, weight={current_sds_weight:.6f}") + logging.info(f" gradient direction: physics vs Shape = {angle_deg:.1f}° ({direction})") + elif self.latents.grad is not None: + shape_grad_norm = torch.norm(self.latents.grad).item() + logging.info(f" Shapegradient: norm={shape_grad_norm:.4e} (no physics gradient)") + else: + shape_grad_norm = 0.0 + + weighted_sds = weighted_shape_loss.item() + + # ==================== Step 8: combine losses and clip if needed ==================== + compliance_loss_item = compliance_mean + alm_penalty = lagrange * g_pos + 0.5 * rho * (g_pos ** 2) + total_loss = alm_penalty + weighted_sds + + # Log the combined loss terms. + if use_sds_this_step: + logging.info( + f" 📊 weighted loss: Compliance={compliance_loss_item:.4e}, g={g_raw:+.3e}, " + f"ALM={alm_penalty:.4e} (λ={lagrange:.2f}, ρ={rho:.2f}), " + f"Shape={weighted_sds:.4e} (×w={current_sds_weight:.6f}), Total={total_loss:.4e}" + ) + else: + logging.info( + f" 📊 weighted loss: Compliance={compliance_loss_item:.4e}, g={g_raw:+.3e}, " + f"ALM={alm_penalty:.4e} (λ={lagrange:.2f}, ρ={rho:.2f}), " + f"Shape=0.00e+00 (disabled), Total={total_loss:.4e}" + ) + + # Log gradient composition details. + if self.latents.grad is not None: + grad_norm = torch.norm(self.latents.grad).item() + + # Report each gradient contribution. + if phys_grad_unscaled is not None: + weighted_phys_grad_norm = torch.norm(phys_grad_unscaled * alm_scale).item() + logging.info(f" 🔍 gradient composition: Weighted Compliance Grad={weighted_phys_grad_norm:.4e} (ALM scale={alm_scale:.3e})") + + if use_sds_this_step and shape_grad_norm > 0: + logging.info(f" Scaled Shape Grad={shape_grad_norm:.4e} (Shape×w={current_sds_weight:.6f})") + if phys_grad_unscaled is not None: + grad_ratio = shape_grad_norm / (weighted_phys_grad_norm + 1e-10) + logging.info(f" ratio: Shape/Compliance = {grad_ratio:.4f} ({grad_ratio*100:.2f}%)") + + logging.info(f" Total Grad={grad_norm:.4e}") + + # Optional gradient clipping. + if self.latents.grad is not None: + grad_norm = torch.norm(self.latents.grad).item() + + if torch.isnan(self.latents.grad).any() or torch.isinf(self.latents.grad).any(): + logging.error(f"❌ the final gradient contains NaN or Inf!skip this steps") + return (compliance_loss_item, u_mean, shape_loss.item(), total_loss) + + if self.config.grad_clip_enabled: + if grad_norm > max_grad_norm: + clip_factor = max_grad_norm / grad_norm + self.latents.grad = self.latents.grad * clip_factor + logging.info(f" ✂️ gradient clipping: {grad_norm:.4e} -> {max_grad_norm:.1f} (×{clip_factor:.3f})") + else: + logging.info(f" ✅ gradient not clipped: {grad_norm:.4e} (max={max_grad_norm:.1f})") + + # ==================== Step 9: optimizer step ==================== + + # Save the previous latents for diagnostics. + old_latents = self.latents.data.clone() + + self.optimizer.step() + + # Diagnose latent changes after the optimizer step. + with torch.no_grad(): + latents_change = torch.norm(self.latents.data - old_latents).item() + latents_norm = torch.norm(old_latents).item() + latents_change_percent = (latents_change / (latents_norm + 1e-10)) * 100 + max_latents_change = torch.abs(self.latents.data - old_latents).max().item() + + logging.info(f" 🔄 Latentschange: L2={latents_change:.4e} ({latents_change_percent:.3f}%), max={max_latents_change:.4e}") + + if latents_change < 1e-6: + logging.warning(f" ⚠️ latents almost did not change!the learning rate may be too small or the gradient may be too weak") + + # Return the scalar loss values. + return (compliance_loss_item, u_mean, shape_loss.item(), total_loss) + + def save_mesh(self, step: int, output_dir: str = "results/hunyuan_meshes", high_quality: bool = False, suffix="step", latents=None): + """Save frontlatentsmesh + + Args: + step: front steps + output_dir: outputdirectory + high_quality: YesNouse (Resolution) , Trueuse256resolution + """ + os.makedirs(output_dir, exist_ok=True) + + try: + # finalSave use256resolution, Stepuse128resolution + octree_res = 256 if high_quality else 128 + if latents is None: + mesh = self.latents_to_mesh(self.latents, octree_res=octree_res) + else: + mesh = self.latents_to_mesh(latents, octree_res=octree_res) + if mesh is None: + logging.warning(f" ⚠️ warning: Step {step} - Marching cubesno surface found, skipSave ") + return + + # finalSave filterfloating + if high_quality: + mesh = self._filter_floating_components(mesh) + + mesh_path = os.path.join(output_dir, f"{suffix}_{step:04d}.obj") + mesh.export(mesh_path) + quality_label = "256resolution" if high_quality else "128resolution" + logging.info(f" 💾 Save mesh ({quality_label}): {mesh_path}") + except Exception as e: + logging.warning(f" ⚠️ warning: Step {step} - Save meshfailed: {e}") + + + def _maybe_save_target_z0_mesh(self, target_z0: torch.Tensor, step_id: int, force: bool = False): + """Save a mesh decoded from target_z0 for diagnostics.""" + if (not force) and (step_id % 10 != 0): + return + + with torch.no_grad(): + deviation = torch.norm(target_z0 - self.latents).item() + latents_norm = torch.norm(self.latents).item() + relative_deviation = deviation / (latents_norm + 1e-8) + + if relative_deviation > 0.5: + logging.warning( + f" ⚠️ target_z0 deviation is too large: {relative_deviation:.1%} " + f"(||target_z0 - latents||={deviation:.3e}, ||latents||={latents_norm:.3e})" + ) + logging.warning(f" thismaySave target meshshape is abnormal") + + try: + target_norm = torch.norm(target_z0).item() + target_max = torch.abs(target_z0).max().item() + target_has_nan = torch.isnan(target_z0).any().item() + target_has_inf = torch.isinf(target_z0).any().item() + + # Save only when target_z0 looks numerically healthy. + if (not target_has_nan and not target_has_inf and + target_max < 100.0 and relative_deviation < 1.0): + target_z0_clean = target_z0.detach().clone() + + logging.info(f" 📊 target_z0 statistics:") + logging.info(f" - shape: {target_z0_clean.shape}") + logging.info(f" - range: [{target_z0_clean.min():.3e}, {target_z0_clean.max():.3e}]") + logging.info(f" - mean: {target_z0_clean.mean():.3e}, Std: {target_z0_clean.std():.3e}") + logging.info(f" - deviation from latents: {relative_deviation:.1%}") + + target_mesh = self.latents_to_mesh(target_z0_clean, octree_res=128) + if target_mesh is not None: + target_mesh_dir = os.path.join( + self.config.out_folder if hasattr(self.config, 'out_folder') + else "results/hunyuan_meshes", + "target_z0_meshes" + ) + os.makedirs(target_mesh_dir, exist_ok=True) + target_mesh_path = os.path.join(target_mesh_dir, f"target_z0_step_{step_id:04d}.obj") + target_mesh.export(target_mesh_path) + logging.info(f" 💾 Save target_z0 mesh (||z||={target_norm:.2e}): {target_mesh_path}") + else: + logging.debug(f" skipSave target_z0: marching cubesno surface found") + else: + logging.warning( + f" ⚠️ skipSave target_z0: containsabnormal values " + f"(nan={target_has_nan}, inf={target_has_inf}, max={target_max:.2e})" + ) + except (ValueError, RuntimeError) as e: + error_msg = str(e) + if "Surface level must be within volume data range" in error_msg or "No surface found" in error_msg: + logging.debug(f" skipSave target_z0: SDFvalueoutside the valid range or has no surface") + else: + logging.warning(f" Save target_z0 meshfailed: {type(e).__name__}: {error_msg[:100]}") + except Exception as e: + logging.warning(f" Save target_z0 meshfailed: {type(e).__name__}: {str(e)[:100]}") + + def save_final_target_z0_mesh(self, step_id: int): + """Force-save a target_z0 mesh at the final step.""" + try: + if self.target_z0_ema is not None: + target_z0 = self.target_z0_ema.detach().clone() + else: + target_z0, _ = self._computation_target_z0_current(step_id) + self._maybe_save_target_z0_mesh(target_z0, step_id, force=True) + except Exception as e: + logging.warning(f" ⚠️ failed to save the final target_z0: {type(e).__name__}: {str(e)[:100]}") + + def save_deformed_mesh(self, step: int, displacement: torch.Tensor, output_dir: str = None, suffix="step"): + """Save FEM solvebackdeformed mesh + + Args: + step: front steps + displacement: FEM solve [num_nodes, 3] + output_dir: outputdirectory, useconfig.out_folder/deformed_meshes + """ + if output_dir is None: + if hasattr(self.config, 'out_folder'): + output_dir = os.path.join(self.config.out_folder, "deformed_meshes") + else: + output_dir = "results/deformed_meshes" + + os.makedirs(output_dir, exist_ok=True) + + try: + # originalnodespositionandbackposition + original_nodes = self.nodes.detach().cpu().numpy() # [num_nodes, 3] + displacement_np = displacement.detach().cpu().numpy() # [num_nodes, 3] + deformed_nodes = original_nodes + displacement_np + + # elements + elements_np = self.elements.detach().cpu().numpy() # [num_elements, 8] + + # # Save VTK format (ParaView, contains) + # vtk_path = os.path.join(output_dir, f"deformed_step_{step:04d}.vtk") + # self._save_hex_mesh_vtk(deformed_nodes, elements_np, displacement_np, vtk_path, step) + + # Save OBJ/PLY (usedecodemesh, ) + decoded_mesh = self.latents_to_mesh(self.latents, octree_res=128) + if decoded_mesh is not None: + disp_vertices = self._sample_displacement_to_vertices( + decoded_mesh.vertices, original_nodes, displacement_np + ) + deformed_vertices = decoded_mesh.vertices + disp_vertices + colors = self._make_displacement_colors(disp_vertices) + + deformed_mesh = trimesh.Trimesh( + vertices=deformed_vertices, + faces=decoded_mesh.faces, + process=False, + ) + deformed_mesh.visual.vertex_colors = colors + + obj_path = os.path.join(output_dir, f"deformed_{suffix}_{step:04d}.obj") + # ply_path = os.path.join(output_dir, f"deformed_step_{step:04d}.ply") + deformed_mesh.export(obj_path) + # deformed_mesh.export(ply_path) + else: + # fallback: usemesh + obj_path = os.path.join(output_dir, f"deformed_{suffix}_{step:04d}.obj") + # ply_path = os.path.join(output_dir, f"deformed_step_{step:04d}.ply") + self._save_surface_mesh_obj(deformed_nodes, elements_np, obj_path) + # self._save_surface_mesh_ply(deformed_nodes, elements_np, displacement_np, ply_path) + + # displacement statistics + disp_mean = np.abs(displacement_np).mean() + disp_max = np.abs(displacement_np).max() + logging.info(f" 💾 saved deformed mesh : OBJ={obj_path.split('/')[-1]}") + logging.debug(f" : mean={disp_mean:.4e}, max={disp_max:.4e}") + + except Exception as e: + logging.warning(f" ⚠️ Save deformed meshfailed (Step {step}): {e}") + + def save_final_deformed_mesh(self, step_id: int, suffix="step"): + """force at the final step toSave deformed mesh (re-solveFEM) """ + if not hasattr(self, 'nodes') or not hasattr(self, 'elements'): + logging.warning(" ⚠️ unable to save the finaldeformed mesh: missingnodes/elements") + return + if not hasattr(self, 'forces') or not hasattr(self, 'boundary_mask'): + logging.warning(" ⚠️ unable to save the finaldeformed mesh: missingforces/boundary_mask") + return + + try: + from torchfem.materials import IsotropicElasticity3D + from physiopt.opt.solid_grid import SolidGrid + from physiopt.opt.field import occ_kernel + + with torch.no_grad(): + # update occupancyalignfrontlatents + sdf = self.get_field(self.nodes) + occ = occ_kernel(sdf, self.config.res, self.config.occ_sdf_beta) + self.coarse_occ = occ[self.elements].mean(1) + + if self.config.alpha_min > 0.0: + self.coarse_occ = torch.clamp(self.coarse_occ, self.config.alpha_min) + + vectorized_material = IsotropicElasticity3D( + E=self.config.youngs_modulus, + nu=self.config.poissons_ratio, + rho=self.config.density, + ).vectorize(self.elements.shape[0]) + + vectorized_material.C *= ( + self.coarse_occ[:, None, None] ** self.config.p_exponent + ) + + solid = SolidGrid(self.nodes, self.elements, vectorized_material) + solid.constraints[self.boundary_mask, :] = True + solid.forces = self.forces + + logging.info(" 🧱 final deformed mesh: re-solve the FEM system to save ") + u, _, _, _, _, _ = solid.solve(max_iter=1) + self.save_deformed_mesh(step_id, u, suffix=suffix) + except Exception as e: + logging.warning(f" ⚠️ final deformed meshSave failed: {type(e).__name__}: {str(e)[:100]}") + + def _save_surface_mesh_obj(self, nodes: np.ndarray, elements: np.ndarray, filename: str): + """Extract the surface from a hexahedral mesh and save it as OBJ.""" + # The six faces of a hexahedron. + hex_faces = [ + [0, 1, 2, 3], [4, 5, 6, 7], # Bottom, top. + [0, 1, 5, 4], [2, 3, 7, 6], # Front, back. + [0, 3, 7, 4], [1, 2, 6, 5], # Left, right. + ] + + # Collect faces that appear only once, i.e. surface faces. + face_count = {} + for elem in elements: + for face_indices in hex_faces: + face_nodes = tuple(sorted([elem[i] for i in face_indices])) + if face_nodes in face_count: + face_count[face_nodes] += 1 + else: + face_count[face_nodes] = 1 + + # Keep only surface faces. + surface_faces = [face for face, count in face_count.items() if count == 1] + + # Save OBJ. + with open(filename, 'w') as f: + f.write("# Deformed mesh surface\n") + for node in nodes: + f.write(f"v {node[0]:.6f} {node[1]:.6f} {node[2]:.6f}\n") + for face in surface_faces: + # OBJ indices are 1-based. + f.write(f"f {face[0]+1} {face[1]+1} {face[2]+1} {face[3]+1}\n") + + def _save_force_visualization(self, seat_nodes_mask: torch.Tensor, total_force: np.ndarray): + """Save voxel-level load data for visualization and validation. + + This exports: + 1. NumPy (.npz) with full node/load data + 2. OBJ point clouds for quick inspection + 3. Optional VTK data for ParaView + + Args: + seat_nodes_mask: Mask of seat/contact nodes [num_nodes]. + total_force: Total force vector [3]. + """ + if not hasattr(self.config, 'out_folder'): + logging.warning(" out_folder is not set, skipSave loaded voxel") + return + + # Create the force_visualization subdirectory. + vis_dir = os.path.join(self.config.out_folder, "force_visualization") + os.makedirs(vis_dir, exist_ok=True) + + # ==================== 1. Save NumPy data (most complete format) ==================== + all_nodes_cpu = self.nodes.cpu().numpy() + all_forces_cpu = self.forces.cpu().numpy() + seat_mask_cpu = seat_nodes_mask.cpu().numpy() + + # Extract loaded nodes. + seat_nodes = all_nodes_cpu[seat_mask_cpu] + seat_forces = all_forces_cpu[seat_mask_cpu] + + npz_path = os.path.join(vis_dir, "force_nodes.npz") + np.savez( + npz_path, + # All node data. + all_nodes=all_nodes_cpu, + all_forces=all_forces_cpu, + # Loaded-node data. + seat_nodes=seat_nodes, + seat_forces=seat_forces, + seat_mask=seat_mask_cpu, + # Boundary-node data. + boundary_mask=self.boundary_mask.cpu().numpy() if hasattr(self, 'boundary_mask') else None, + # Metadata. + total_force=total_force, + num_seat_nodes=len(seat_nodes), + num_all_nodes=len(all_nodes_cpu), + ) + logging.info(f" 💾 Save load data (NumPy format) : {npz_path}") + + # ==================== 2. Save OBJ point clouds ==================== + # 2a. Loaded nodes (red point cloud). + seat_obj_path = os.path.join(vis_dir, "seat_nodes.obj") + with open(seat_obj_path, 'w') as f: + f.write("# Seat nodes (loaded area)\n") + f.write(f"# Total: {len(seat_nodes)} nodes\n") + f.write(f"# Force per node: {seat_forces[0] if len(seat_forces) > 0 else [0,0,0]}\n") + for node in seat_nodes: + f.write(f"v {node[0]:.6f} {node[1]:.6f} {node[2]:.6f}\n") + logging.info(f" 💾 Save seat nodes (OBJpoint cloud) : {seat_obj_path}") + + # 2b. Boundary nodes (blue point cloud). + if hasattr(self, 'boundary_mask'): + boundary_nodes = all_nodes_cpu[self.boundary_mask.cpu().numpy()] + boundary_obj_path = os.path.join(vis_dir, "boundary_nodes.obj") + with open(boundary_obj_path, 'w') as f: + f.write("# Boundary nodes (fixed area)\n") + f.write(f"# Total: {len(boundary_nodes)} nodes\n") + for node in boundary_nodes: + f.write(f"v {node[0]:.6f} {node[1]:.6f} {node[2]:.6f}\n") + logging.info(f" 💾 Save boundary nodes (OBJpoint cloud) : {boundary_obj_path}") + + # 2c. All nodes (gray point cloud) for comparison. + all_obj_path = os.path.join(vis_dir, "all_nodes.obj") + with open(all_obj_path, 'w') as f: + f.write("# All nodes\n") + f.write(f"# Total: {len(all_nodes_cpu)} nodes\n") + for node in all_nodes_cpu: + f.write(f"v {node[0]:.6f} {node[1]:.6f} {node[2]:.6f}\n") + logging.info(f" 💾 Save all nodes (OBJpoint cloud) : {all_obj_path}") + + # ==================== 3. Save VTK data for ParaView ==================== + try: + vtk_path = os.path.join(vis_dir, "force_field.vtk") + with open(vtk_path, 'w') as f: + # VTK Header + f.write("# vtk DataFile Version 3.0\n") + f.write("Force field visualization\n") + f.write("ASCII\n") + f.write("DATASET UNSTRUCTURED_GRID\n") + + # Points + f.write(f"POINTS {len(all_nodes_cpu)} float\n") + for node in all_nodes_cpu: + f.write(f"{node[0]:.6f} {node[1]:.6f} {node[2]:.6f}\n") + + # Cells (vertices) + f.write(f"\nCELLS {len(all_nodes_cpu)} {len(all_nodes_cpu)*2}\n") + for i in range(len(all_nodes_cpu)): + f.write(f"1 {i}\n") + + # Cell types (1 = vertex) + f.write(f"\nCELL_TYPES {len(all_nodes_cpu)}\n") + for _ in range(len(all_nodes_cpu)): + f.write("1\n") + + # Point data (force vectors) + f.write(f"\nPOINT_DATA {len(all_nodes_cpu)}\n") + f.write("VECTORS force float\n") + for force in all_forces_cpu: + f.write(f"{force[0]:.6e} {force[1]:.6e} {force[2]:.6e}\n") + + # Scalar field: force magnitude + f.write("\nSCALARS force_magnitude float 1\n") + f.write("LOOKUP_TABLE default\n") + for force in all_forces_cpu: + mag = np.linalg.norm(force) + f.write(f"{mag:.6e}\n") + + # Scalar field: is_seat (0 or 1) + f.write("\nSCALARS is_seat int 1\n") + f.write("LOOKUP_TABLE default\n") + for is_seat in seat_mask_cpu: + f.write(f"{int(is_seat)}\n") + + logging.info(f" 💾 Save force field (VTK format, ParaView) : {vtk_path}") + except Exception as e: + logging.warning(f" ⚠️ Save VTK formatfailed: {e}") + + # ==================== 4. Generate a Python visualization script ==================== + vis_script_path = os.path.join(vis_dir, "visualize_forces.py") + with open(vis_script_path, 'w') as f: + f.write("""#!/usr/bin/env python3 +\"""Visualize voxel load data + +Usage: + python visualize_forces.py + +Requirements: + pip install numpy matplotlib + +\""" +import numpy as np +import matplotlib.pyplot as plt +from mpl_toolkits.mplot3d import Axes3D + +# Load data. +data = np.load('force_nodes.npz') +all_nodes = data['all_nodes'] +seat_nodes = data['seat_nodes'] +seat_forces = data['seat_forces'] +total_force = data['total_force'] + +# Create the 3D figure. +fig = plt.figure(figsize=(15, 5)) + +# Subplot 1: all nodes (gray) + loaded nodes (red). +ax1 = fig.add_subplot(131, projection='3d') +ax1.scatter(all_nodes[:, 0], all_nodes[:, 1], all_nodes[:, 2], + c='lightgray', s=0.5, alpha=0.3, label='All nodes') +ax1.scatter(seat_nodes[:, 0], seat_nodes[:, 1], seat_nodes[:, 2], + c='red', s=5, alpha=1.0, label='Seat nodes (loaded)') +ax1.set_xlabel('X') +ax1.set_ylabel('Y (up)') +ax1.set_zlabel('Z') +ax1.set_title(f'Loaded Nodes\\n({len(seat_nodes)}/{len(all_nodes)} nodes)') +ax1.legend() + +# Subplot 2: Y distribution of loaded nodes. +ax2 = fig.add_subplot(132) +y_coords = seat_nodes[:, 1] +ax2.hist(y_coords, bins=30, color='red', alpha=0.7, edgecolor='black') +ax2.axvline(y_coords.min(), color='blue', linestyle='--', label=f'Y_min={y_coords.min():.3f}') +ax2.axvline(y_coords.max(), color='green', linestyle='--', label=f'Y_max={y_coords.max():.3f}') +ax2.set_xlabel('Y coordinate (height)') +ax2.set_ylabel('Number of nodes') +ax2.set_title('Seat Node Y Distribution') +ax2.legend() +ax2.grid(True, alpha=0.3) + +# Subplot 3: XZ force-vector layout in top view. +ax3 = fig.add_subplot(133) +ax3.scatter(seat_nodes[:, 0], seat_nodes[:, 2], c='red', s=10, alpha=0.5) +# Draw a sparse subset of force vectors to avoid clutter. +step = max(1, len(seat_nodes) // 50) +for i in range(0, len(seat_nodes), step): + node = seat_nodes[i] + force = seat_forces[i] + # Scale force vectors for visualization. + scale = 0.01 + ax3.arrow(node[0], node[2], force[0]*scale, force[2]*scale, + head_width=0.02, head_length=0.01, fc='blue', ec='blue', alpha=0.7) +ax3.set_xlabel('X') +ax3.set_ylabel('Z') +ax3.set_title(f'Top View (XZ plane)\\nForce: {total_force}') +ax3.axis('equal') +ax3.grid(True, alpha=0.3) + +plt.tight_layout() +plt.savefig('force_visualization.png', dpi=150, bbox_inches='tight') +logging.info("✅ image saved : force_visualization.png") +plt.show() + +# Print summary statistics. +logging.info("\\n" + "="*60) +logging.info("force voxel statistics") +logging.info("="*60) +logging.info(f"total node count: {len(all_nodes)}") +logging.info(f"loaded node count: {len(seat_nodes)} ({len(seat_nodes)/len(all_nodes)*100:.1f}%)") +logging.info(f"total: {total_force}") +logging.info(f"per nodeaverage force per node: {seat_forces.mean(axis=0)}") +logging.info(f"\\nY-coordinate range:") +logging.info(f" - min: {y_coords.min():.3f}") +logging.info(f" - max: {y_coords.max():.3f}") +logging.info(f" - mean: {y_coords.mean():.3f}") +logging.info(f" - height span: {y_coords.max() - y_coords.min():.3f}") +logging.info("="*60) +""") + os.chmod(vis_script_path, 0o755) # Add execute permission. + logging.info(f" 💾 Save visualization script: {vis_script_path}") + + # ==================== 5. Generate a README document ==================== + readme_path = os.path.join(vis_dir, "README.md") + with open(readme_path, 'w') as f: + f.write(f"""# Load Voxel Visualization Data + +Generated at: {np.datetime64('now')} + +## Statistics + +- **Total nodes**: {len(all_nodes_cpu)} +- **Loaded nodes**: {len(seat_nodes)} ({len(seat_nodes)/len(all_nodes_cpu)*100:.1f}%) +- **Total force**: {total_force} +- **Force per node**: {seat_forces[0] if len(seat_forces) > 0 else [0,0,0]} + +## Files + +### 1. NumPy format (recommended for analysis) + +- `force_nodes.npz`: contains the full dataset + - `all_nodes`: coordinates of all nodes [{len(all_nodes_cpu)}, 3] + - `all_forces`: force vectors on all nodes [{len(all_nodes_cpu)}, 3] + - `seat_nodes`: coordinates of loaded nodes [{len(seat_nodes)}, 3] + - `seat_forces`: force vectors on loaded nodes [{len(seat_nodes)}, 3] + - `seat_mask`: mask of loaded nodes [{len(all_nodes_cpu)}] + - `boundary_mask`: mask of boundary nodes [{len(all_nodes_cpu)}] + +**Example**: +```python +import numpy as np +data = np.load('force_nodes.npz') +seat_nodes = data['seat_nodes'] +print(f"Loaded nodes: {{len(seat_nodes)}}") +``` + +### 2. OBJ format (recommended for quick inspection) + +- `seat_nodes.obj`: loaded nodes (red point cloud) +- `boundary_nodes.obj`: boundary nodes (blue point cloud) +- `all_nodes.obj`: all nodes (gray point cloud) + +**Usage**: +1. Open in Meshlab: `meshlab seat_nodes.obj` +2. Or import the OBJ files into Blender +3. You can load multiple OBJ files together for comparison + +### 3. VTK format (recommended for professional visualization) + +- `force_field.vtk`: force-field data with vector information + +**Usage**: +1. Open in ParaView: `paraview force_field.vtk` +2. In ParaView: + - Use `Glyph` to visualize force vectors + - Color by `force_magnitude` to inspect strength + - Filter by `is_seat` to isolate the loaded region + +### 4. Visualization script + +- `visualize_forces.py`: Python visualization script + +**Usage**: +```bash +python visualize_forces.py +``` +""") + logging.info(f" 💾 Save README document: {readme_path}") + + # Print a short summary. + logging.info(f" ✅ force voxel data saved successfully!") + logging.info(f" - view directory: {vis_dir}") + logging.info(f" - quick visualization: cd {vis_dir} && python visualize_forces.py") + logging.info(f" - view in Meshlab: meshlab {os.path.join(vis_dir, 'seat_nodes.obj')}") + + +def load_hunyuan_models(model_path: str = "tencent/Hunyuan3D-2.1", + subfolder: str = "hunyuan3d-shapegen", + use_safetensors: bool = True): + """Load the Hunyuan3D models (VAE, Flow Model, and Scheduler). + + Args: + model_path: Model path, either a Hugging Face ID or a local directory. + subfolder: Model subfolder name. + use_safetensors: Whether to load safetensors checkpoints. + + Returns: + (vae, flow_model, scheduler): the VAE, Flow Matching model, and scheduler. + """ + logging.info(f"🔧 loading Hunyuan3D-2.1model...") + logging.info(f" modelpath: {model_path}") + logging.info(f" subfolder: {subfolder}") + logging.info(f" modelformat: {'safetensors' if use_safetensors else 'checkpoint'}") + + try: + pipeline = Hunyuan3DDiTFlowMatchingPipeline.from_pretrained( + model_path, + subfolder=subfolder, + torch_dtype=torch.float16, + use_safetensors=use_safetensors + ) + + if pipeline is None: + raise ValueError("pipeline loading failed and returned None") + + logging.info(" ✅ pipeline loaded successfully") + + pipeline.to('cuda') + logging.info(" ✅ modelmoved to CUDA (dtype: fp16)") + + vae = pipeline.vae + flow_model = pipeline.model + scheduler = pipeline.scheduler + + return vae, flow_model, scheduler + + except Exception as e: + logging.error(f"\n❌ modelloadfailed: {e}") + logging.error(f"\nPossible fixes:") + logging.error(f"1. make sure Hunyuan3D is installed-2.1: cd Hunyuan3D-2.1 && pip install -e .") + logging.error(f"2. check network connectivity to huggingface.co") + logging.error(f"3. or download manually: git clone https://huggingface.co/tencent/Hunyuan3D-2") + import traceback + traceback.print_exc() + sys.exit(1) + + +def plot_history(history: dict, save_dir: str, filename: str = "optimization_metrics.png"): + + epochs = list(range(1, len(history["compliance"]) + 1)) + + # 2. Create the figure with a 2x2 grid + fig, axs = plt.subplots(2, 2, figsize=(14, 10)) + fig.suptitle("Optimization Metrics Evolution", fontsize=16, fontweight='bold') + + # --- Plot 1: Compliance --- + axs[0, 0].plot(epochs, history["compliance"], marker='o', color='#1f77b4', linewidth=2) + axs[0, 0].set_title("Compliance (Strain Energy)") + axs[0, 0].set_xlabel("Epoch") + axs[0, 0].grid(True, linestyle='--', alpha=0.7) + + # --- Plot 2: u_mean --- + axs[0, 1].plot(epochs, history["u_mean"], marker='s', color='#2ca02c', linewidth=2) + axs[0, 1].set_title("Mean Displacement (|u|_mean)") + axs[0, 1].set_xlabel("Epoch") + axs[0, 1].grid(True, linestyle='--', alpha=0.7) + + # --- Plot 3: c_relative_decrease --- + axs[1, 0].plot(epochs, history["c_relative_decrease"], marker='^', color='#d62728', linewidth=2) + axs[1, 0].set_title("Relative Compliance Decrease") + axs[1, 0].set_xlabel("Epoch") + axs[1, 0].grid(True, linestyle='--', alpha=0.7) + + # --- Plot 4: u_relative_decrease --- + axs[1, 1].plot(epochs, history["u_relative_decrease"], marker='v', color='#9467bd', linewidth=2) + axs[1, 1].set_title("Relative Displacement Decrease") + axs[1, 1].set_xlabel("Epoch") + axs[1, 1].grid(True, linestyle='--', alpha=0.7) + + # 3. Adjust layout to prevent text from overlapping + plt.tight_layout() + fig.subplots_adjust(top=0.92) # Leave space for the main super-title + + # 4. Save the figure + os.makedirs(save_dir, exist_ok=True) + full_path = os.path.join(save_dir, filename) + + plt.savefig(full_path, dpi=300, bbox_inches='tight') + plt.close(fig) + + logging.info(f" 📊 Plot successfully saved to: {full_path}") + + +def main(): + """Parse CLI arguments and run the optimization.""" + import argparse + + parser = argparse.ArgumentParser(description="Hunyuan3D physics optimization + shape-prior optimization") + + # Required arguments. + parser.add_argument("--latents", type=str, required=True, + help="Input latents file path (.pt)") + parser.add_argument("--out_folder", type=str, default="../out/hunyuan_opt", + help="Output folder path") + + # Model arguments. + parser.add_argument("--model_path", type=str, default="tencent/Hunyuan3D-2.1", + help="Model path (using v2.1)") + parser.add_argument("--subfolder", type=str, default="hunyuan3d-dit-v2-1", + help="Model subfolder") + parser.add_argument("--use_safetensors", action="store_true", + help="Use safetensors format (default: ckpt)") + + # Physical-simulation arguments. + parser.add_argument("--use_physics", action="store_true", + help="Enable physics-constrained optimization") + parser.add_argument("--res", type=int, default=16, + help="Voxel resolution (16/32/64)") + parser.add_argument("--youngs_modulus_scale", type=float, default=2.0, + help="Final Young's modulus multiplier (default 2x after the last projection)") + parser.add_argument("--compliance_threshold", type=float, default=None, + help="Target compliance threshold (None = automatic)") + parser.add_argument("--compliance_threshold_ratio", type=float, default=0.3, + help="Automatic threshold ratio (threshold = initial value × ratio)") + + # Optimization arguments. + parser.add_argument("--num_steps", type=int, default=300, + help="Number of optimization steps (pure SDS only; in physics mode it becomes outer_cycles * phys_steps_per_cycle automatically)") + parser.add_argument("--outer_cycles", type=int, default=100, + help="Number of outer cycles (each cycle = physics optimization + projection)") + parser.add_argument("--phys_steps_per_cycle", type=int, default=5, + help="Number of physics-optimization steps per outer cycle") + parser.add_argument("--lr", type=float, default=5e-3, + help="Learning rate (increase to 0.005 to help the mesh thicken faster) ") + parser.add_argument("--lagrange_max", type=float, default=10.0, + help="Maximum Lagrange multiplier (recommended: 5-20)") + parser.add_argument("--alm_rho_init", type=float, default=1.0, + help="ALM rhoinitial value") + parser.add_argument("--alm_rho_max", type=float, default=1000.0, + help="ALM rhoMax") + parser.add_argument("--alm_rho_increase_factor", type=float, default=2.0, + help="ALM rhogrowth factor") + parser.add_argument("--alm_rho_increase_patience", type=int, default=5, + help="ALM rhonumber of consecutive violation steps required before increasing") + parser.add_argument("--alm_scale_guard_ratio", type=float, default=0.95, + help="ALMscaling guard ratio(<=1), control the upper bound of the physics-gradient target=this ratio x clipping-threshold value") + parser.add_argument("--grad_clip_enabled", action="store_true", + help="Enable gradient clipping (disabled by default; otherwise only NaN/Inf checks are kept)") + parser.add_argument("--use_sgd", action="store_true", + help="Use SGD instead of Adam") + parser.add_argument("--force_config", type=str, default=None, + help="Path to the external-force JSON config (generated by the web UI)") + parser.add_argument("--force", type=float, nargs=3, action="append", default=None, + help="External force vector [fx fy fz] (N, Y-up coordinates; can be specified multiple times)") + parser.add_argument("--global_loading", action="store_true", + help="Use global uniform loading (disable local loading)") + parser.add_argument("--force_region_mode", type=str, default="top_percent", + choices=["top_percent", "height_ratio", "bbox"], + help="How to choose the local loading region") + parser.add_argument("--force_top_percent", type=float, default=0.05, + help="top_percent mode: select the highest-Y fraction") + parser.add_argument("--force_bbox", type=float, nargs=6, default=None, + help="bbox mode: x_min x_max y_min y_max z_min z_max (absolute coordinates)") + parser.add_argument("--force_bbox_ratio", type=float, nargs=6, default=None, + help="bbox mode (0-1): bbox relative to the node bounds") + parser.add_argument("--seat_height_min_ratio", type=float, default=0.3, + help="height_ratio mode: lower seat boundary (0-1)") + parser.add_argument("--seat_height_max_ratio", type=float, default=0.5, + help="height_ratio mode: upper seat boundary (0-1)") + + # SDS arguments. + parser.add_argument("--sds_weight", type=float, default=1.0, + help="SDS gradient weight (deprecated; use sds_weight_start and sds_weight_end instead)") + parser.add_argument("--sds_weight_start", type=float, default=10.0, + help="Initial SDS weight (linearly increased; 0.0001 is recommended to avoid disturbing physics optimization)") + parser.add_argument("--sds_weight_end", type=float, default=10.0, + help="Final SDS weight (linearly increased; 0.001 is recommended, about 1/10 of the physics gradient)") + parser.add_argument("--sds_timestep", type=float, default=0.1, + help="SDS timestep (recommended: 0.05-0.2)") + parser.add_argument("--sds_target_z0_ema_beta", type=float, default=0.9, + help="target_z0 EMA smoothing factor (larger means smoother)") + parser.add_argument("--deformed_mesh_interval", type=int, default=10, + help="Interval for saving deformed meshes (steps)") + parser.add_argument("--deformed_mesh_disp_min", type=float, default=0.0, + help="Minimum displacement for deformed-mesh color mapping (default 0.0)") + parser.add_argument("--deformed_mesh_disp_max", type=float, default=0.2, + help="Maximum displacement for deformed-mesh color mapping (<=0 enables per-step auto scaling)") + parser.add_argument("--guidance_scale", type=float, default=7.5, + help="CFG guidance scale (standard value: 7.5; larger means stronger image conditioning)") + parser.add_argument("--sds_projection_max_rel", type=float, default=0.0, + help="Maximum relative target_z0 projection deviation (0 = unlimited)") + parser.add_argument("--sds_use_uncond", action="store_true", + help="Use the unconditional branch (only takes effect when guidance_scale <= 1)") + + # Topology control. + parser.add_argument("--keep_all_components", action="store_true", + help="Keep all connected components (to avoid disappearing chair legs)") + parser.add_argument("--re_extract_interval", type=int, default=1, + help="Solid re-extraction interval (0 = disabled)") + + args = parser.parse_args() + + def _normalize_force_vectors(value): + if value is None: + return None + if isinstance(value, (list, tuple)) and len(value) > 0: + if isinstance(value[0], (list, tuple)): + candidates = value + else: + candidates = [value] + else: + return None + normalized = [] + for vec in candidates: + if not isinstance(vec, (list, tuple)) or len(vec) != 3: + continue + try: + normalized.append([float(v) for v in vec]) + except Exception: + continue + return normalized if normalized else None + + def _normalize_force_entry(entry): + if not isinstance(entry, dict): + return None + forces = _normalize_force_vectors(entry.get("forces")) + if forces is None: + forces = _normalize_force_vectors(entry.get("force")) + if forces is None: + return None + out = dict(entry) + if len(forces) > 1: + out["forces"] = forces + out["force"] = [float(sum(v[i] for v in forces)) for i in range(3)] + else: + out["force"] = forces[0] + out.pop("forces", None) + if "force_region_mode" in out: + out["force_region_mode"] = str(out["force_region_mode"]) + if "global_loading" in out: + out["global_loading"] = bool(out["global_loading"]) + if "force_top_percent" in out: + out["force_top_percent"] = float(out["force_top_percent"]) + if "seat_height_min_ratio" in out: + out["seat_height_min_ratio"] = float(out["seat_height_min_ratio"]) + if "seat_height_max_ratio" in out: + out["seat_height_max_ratio"] = float(out["seat_height_max_ratio"]) + if "force_bbox" in out and isinstance(out["force_bbox"], (list, tuple)) and len(out["force_bbox"]) == 6: + out["force_bbox"] = [float(v) for v in out["force_bbox"]] + elif "force_bbox" in out: + out.pop("force_bbox", None) + if "force_bbox_ratio" in out and isinstance(out["force_bbox_ratio"], (list, tuple)) and len(out["force_bbox_ratio"]) == 6: + out["force_bbox_ratio"] = [float(v) for v in out["force_bbox_ratio"]] + elif "force_bbox_ratio" in out: + out.pop("force_bbox_ratio", None) + return out + + # Load force configuration from JSON, typically exported from the web UI. + force_config_loaded = False + force_config_error = None + force_entries = None + if args.force_config: + raw_force_config = args.force_config + candidates = [] + if os.path.isabs(raw_force_config): + candidates.append(raw_force_config) + else: + candidates.append(raw_force_config) + script_dir = os.path.dirname(os.path.abspath(__file__)) + candidates.append(os.path.join(script_dir, raw_force_config)) + candidates.append(os.path.join(os.path.dirname(script_dir), raw_force_config)) + force_config_path = next((p for p in candidates if os.path.exists(p)), None) + if force_config_path is None: + force_config_error = f"Path does not exist; tried: {candidates}" + else: + args.force_config = force_config_path + try: + with open(force_config_path, "r") as f: + force_cfg = json.load(f) + if isinstance(force_cfg, dict): + cfg_forces = _normalize_force_vectors(force_cfg.get("forces")) + if cfg_forces is not None: + args.force = cfg_forces + else: + cfg_force = _normalize_force_vectors(force_cfg.get("force")) + if cfg_force is not None: + args.force = cfg_force + elif "force" in force_cfg or "forces" in force_cfg: + force_config_error = "force/forcesinvalid format" + if "global_loading" in force_cfg: + args.global_loading = bool(force_cfg["global_loading"]) + if "force_region_mode" in force_cfg: + args.force_region_mode = str(force_cfg["force_region_mode"]) + if "force_top_percent" in force_cfg: + args.force_top_percent = float(force_cfg["force_top_percent"]) + if "seat_height_min_ratio" in force_cfg: + args.seat_height_min_ratio = float(force_cfg["seat_height_min_ratio"]) + if "seat_height_max_ratio" in force_cfg: + args.seat_height_max_ratio = float(force_cfg["seat_height_max_ratio"]) + if "force_bbox" in force_cfg: + args.force_bbox = force_cfg["force_bbox"] + if "force_bbox_ratio" in force_cfg: + args.force_bbox_ratio = force_cfg["force_bbox_ratio"] + if "force_entries" in force_cfg: + raw_entries = force_cfg["force_entries"] + if isinstance(raw_entries, list): + normalized_entries = [] + for entry in raw_entries: + norm_entry = _normalize_force_entry(entry) + if norm_entry is not None: + normalized_entries.append(norm_entry) + if normalized_entries: + force_entries = normalized_entries + else: + force_config_error = "force_entries has no valid entries" + else: + force_config_error = "force_entriesinvalid format" + force_config_loaded = True + else: + force_config_error = f"force_configis not a dict: {type(force_cfg)}" + except Exception as e: + force_config_error = f"read failed: {e}" + + # Configure logging. force=True ensures this replaces any prior setup. + os.makedirs(args.out_folder, exist_ok=True) + log_file = os.path.join(args.out_folder, "optimization.log") + + # Remove any existing handlers. + for handler in logging.root.handlers[:]: + logging.root.removeHandler(handler) + + # Reconfigure logging. + logging.basicConfig( + level=logging.INFO, + format='%(asctime)s - %(levelname)s - %(message)s', + handlers=[ + logging.FileHandler(log_file, mode='w'), # Rewrite the log on each run. + logging.StreamHandler() + ], + force=True # Python 3.8+: force a full reconfiguration. + ) + + logging.info(f"🔧 logging configuration completed") + logging.info(f" - log file: {log_file}") + logging.info(f" - output mode: file + console") + if args.force_config: + if force_config_loaded: + logging.info(" ✅ force_configloaded") + logging.info(f" - path: {args.force_config}") + logging.info(f" - forces: {args.force}") + if force_entries: + logging.info(f" - force_entries: {len(force_entries)}") + logging.info(f" - global_loading: {args.global_loading}") + logging.info(f" - force_region_mode: {args.force_region_mode}") + logging.info(f" - force_top_percent: {args.force_top_percent}") + logging.info(f" - seat_height_min_ratio: {args.seat_height_min_ratio}") + logging.info(f" - seat_height_max_ratio: {args.seat_height_max_ratio}") + logging.info(f" - force_bbox: {args.force_bbox}") + logging.info(f" - force_bbox_ratio: {args.force_bbox_ratio}") + if force_config_error: + logging.warning(f" ⚠️ force_configsome fields are invalid: {force_config_error}") + else: + logging.warning(f" ⚠️ force_configloadfailed: {force_config_error}") + + # In physics mode, derive num_steps from outer_cycles and phys_steps_per_cycle. + if args.use_physics: + outer_cycles = max(1, int(args.outer_cycles)) + phys_steps_per_cycle = max(1, int(args.phys_steps_per_cycle)) + derived_num_steps = outer_cycles * phys_steps_per_cycle + if args.num_steps != derived_num_steps: + logging.info( + f" - num_stepsautomatically set: {args.num_steps} → {derived_num_steps} " + f"(outer_cycles={outer_cycles}, phys_steps_per_cycle={phys_steps_per_cycle})" + ) + args.num_steps = derived_num_steps + + # ==================== Save run metadata ==================== + # 1. Save the command line. + command_file = os.path.join(args.out_folder, "run_command.txt") + try: + with open(command_file, 'w') as f: + f.write("=" * 80 + "\n") + f.write("Command used (Command Used)\n") + f.write("=" * 80 + "\n\n") + f.write("Full command:\n") + f.write("python " + " ".join(sys.argv) + "\n\n") + + f.write("=" * 80 + "\n") + f.write("Arguments (Arguments)\n") + f.write("=" * 80 + "\n\n") + for arg, value in vars(args).items(): + f.write(f"{arg}: {value}\n") + + f.write("\n" + "=" * 80 + "\n") + f.write("Environment (Environment)\n") + f.write("=" * 80 + "\n\n") + f.write(f"Python: {sys.version}\n") + f.write(f"PyTorch: {torch.__version__}\n") + f.write(f"CUDA Available: {torch.cuda.is_available()}\n") + if torch.cuda.is_available(): + f.write(f"CUDA Version: {torch.version.cuda}\n") + f.write(f"GPU Count: {torch.cuda.device_count()}\n") + + logging.info(f" - saved command used : {command_file}") + except Exception as e: + logging.warning(f" ⚠️ Save Command usedfailed: {e}") + + # 2. Save a copy of the current script. + script_backup = os.path.join(args.out_folder, "viewer_hunyuan_web_alternate.py") + try: + current_script = os.path.abspath(__file__) + shutil.copy2(current_script, script_backup) + logging.info(f" - saved script copy : {script_backup}") + except Exception as e: + logging.warning(f" ⚠️ Save failed to save script copy: {e}") + + # Load latents and conditioning data. + logging.info(f"\n📂 loading input data...") + logging.info(f" - Latents: {args.latents}") + + data = torch.load(args.latents, map_location='cpu') + + # Extract latents. + if isinstance(data, dict) and 'latents' in data: + latents = data['latents'] + else: + latents = data + + logging.info(f" ✅ Latents shape: {latents.shape}") + + # Check conditioning data (image_embeds or image). + need_encode_cond = False + image_embeds = None + image = None + + if isinstance(data, dict): + if 'image' in data: + # New format: only the image was saved, so we need to re-encode it. + logging.info(f" - detected image data; re-encoding as conditional embeds") + image_array = data['image'] + image = Image.fromarray(image_array) + need_encode_cond = True + elif 'image_embeds' in data: + # Legacy format: embeddings are already saved. + logging.info(f" - using the saved conditional embeds") + image_embeds = data['image_embeds'] + need_encode_cond = False + elif 'cond' in data: + # Alternate format using a saved cond dict. + logging.info(f" - using the saved cond") + image_embeds = data['cond'] + need_encode_cond = False + else: + raise ValueError("latents.ptis missingimage, image_embedsor cond data") + else: + raise ValueError("latentsmust be a dictionary containing'latents'andconditioninformation dict") + + if image_embeds is not None: + if isinstance(image_embeds, dict): + logging.info(f" ✅ Cond keys: {list(image_embeds.keys())}") + else: + logging.info(f" ✅ Image embeds shape: {image_embeds.shape}") + + # Load models. + logging.info(f"\n🔧 loading Hunyuan3Dmodel...") + vae, flow_model, scheduler = load_hunyuan_models( + model_path=args.model_path, + subfolder=args.subfolder, + use_safetensors=args.use_safetensors + ) + + # ==================== Encode conditioning data if needed ==================== + if need_encode_cond: + logging.info("🎨 encoding conditional embeds from the image...") + + # Reload the full pipeline for condition encoding. + from hy3dgen.shapegen import Hunyuan3DDiTFlowMatchingPipeline + + pipeline = Hunyuan3DDiTFlowMatchingPipeline.from_pretrained( + args.model_path, + subfolder=args.subfolder, + torch_dtype=torch.float16, + use_safetensors=args.use_safetensors + ) + pipeline.to('cuda') + + with torch.no_grad(): + # Prepare the image. + cond_inputs = pipeline.prepare_image(image) + image_tensor = cond_inputs.pop('image') + + # Enable CFG so the encoded condition contains both branches. + cond_dict = pipeline.encode_cond( + image=image_tensor, + additional_cond_inputs=cond_inputs, + do_classifier_free_guidance=True, # Enable CFG. + dual_guidance=False, + ) + + # Save the condition dict. + image_embeds = cond_dict + + logging.info(f" ✅ condition encoding completed (CFG mode) ") + logging.info(f" - Cond keys: {list(cond_dict.keys()) if isinstance(cond_dict, dict) else 'tensor'}") + + # Resolve the compliance threshold. + if args.compliance_threshold is None: + compliance_threshold = 200.0 + logging.info(f" using the default compliance threshold: {compliance_threshold}") + else: + compliance_threshold = args.compliance_threshold + logging.info(f" using the custom compliance threshold: {compliance_threshold}") + + target_z0_update_interval = max(1, int(args.phys_steps_per_cycle)) + forces = None + normalized_forces = _normalize_force_vectors(args.force) + if normalized_forces: + forces = [{'external_force': vec} for vec in normalized_forces] + elif args.force is not None: + logging.warning(f" ⚠️ invalid external force vector; ignoring: {args.force}") + # Build the optimization config. + config = OptimizationConfig( + num_steps=args.num_steps, + lr=args.lr, + sds_timestep=args.sds_timestep, + sds_weight=args.sds_weight if args.use_physics else 1.0, # Keep backward compatibility. + sds_weight_start=args.sds_weight_start, # Dynamic weight schedule start. + sds_weight_end=args.sds_weight_end, # Dynamic weight schedule end. + guidance_scale=args.guidance_scale, # CFG guidance scale. + sds_projection_max_rel=args.sds_projection_max_rel, + sds_use_uncond=args.sds_use_uncond, + sds_target_z0_update_interval=target_z0_update_interval, + sds_target_z0_ema_beta=args.sds_target_z0_ema_beta, + deformed_mesh_interval=args.deformed_mesh_interval, + deformed_mesh_disp_min=args.deformed_mesh_disp_min, + deformed_mesh_disp_max=args.deformed_mesh_disp_max, + use_sgd=args.use_sgd, + grad_clip_enabled=args.grad_clip_enabled, + # Physical parameters. + res=args.res, + lagrange_max=args.lagrange_max, + compliance_threshold=compliance_threshold, + alm_rho_init=args.alm_rho_init, + alm_rho_max=args.alm_rho_max, + alm_rho_increase_factor=args.alm_rho_increase_factor, + alm_rho_increase_patience=args.alm_rho_increase_patience, + alm_scale_guard_ratio=args.alm_scale_guard_ratio, + youngs_modulus_scale=args.youngs_modulus_scale, + # Topology control. + one_cc_only=not args.keep_all_components, + re_extract_interval=args.re_extract_interval, + # Loads and load-region settings. + forces=forces, + force_entries=force_entries, + use_local_loading=not args.global_loading, + seat_height_min_ratio=args.seat_height_min_ratio, + seat_height_max_ratio=args.seat_height_max_ratio, + force_region_mode=args.force_region_mode, + force_top_percent=args.force_top_percent, + force_bbox=args.force_bbox, + force_bbox_ratio=args.force_bbox_ratio, + # Output path. + out_folder=args.out_folder, + ) + + # Create the optimizer. + optimizer = HunyuanSDSOptimizer( + latents=latents, + cond=image_embeds, + vae=vae, + flow_model=flow_model, + scheduler=scheduler, + config=config, + device='cuda' + ) + + # Prepare physics if requested. + final_step = args.num_steps + if args.use_physics: + logging.info(f"\n🔬 enable physics optimization mode") + logging.info(f" - Voxel resolution: {args.res}") + logging.info(f" - physics steps/cycle: {args.phys_steps_per_cycle}, outer cycles: {args.outer_cycles}") + logging.info(f" - projection noise: sds_timestep={args.sds_timestep}") + logging.info(f" - target_z0update interval: {target_z0_update_interval} (consistent with phys_steps_per_cycle)") + logging.info(f" - LagrangeMax: {args.lagrange_max}") + + try: + optimizer.extract_solid(step=-1) # Initial extraction. + optimizer.prepare_physical_simulation() + logging.info(f" ✅ physics simulationInitializationsucceeded") + except Exception as e: + logging.warning(f" ⚠️ warning: initial mesh extraction failed (this is normal, optimizationbe repaired during the optimization process) ") + logging.warning(f" error information: {str(e)[:100]}") + # Continue anyway: the key physical state is the occupancy field, not the mesh. + else: + logging.info(f"\n🎨 using pure SDS optimization mode") + + # Optimization loop. + optimization_mode = "Alternating Phys/Projection" if args.use_physics else "Pure SDS" + total_steps_hint = ( + int(args.outer_cycles) * (int(args.phys_steps_per_cycle) + 1) + if args.use_physics + else args.num_steps + ) + logging.info(f"\n🚀 start{optimization_mode}optimization ({total_steps_hint} steps)...") + + if args.use_physics: + lagrange_multiplier = 0.0 + rho = config.alm_rho_init + violation_count = 0 + + # Automatically set the compliance threshold when needed. + if config.compliance_threshold is None or config.compliance_threshold == 200.0: + logging.info(f" 📊 computationinitialcompliancethreshold value...") + try: + initial_compliance, _, _, _ = optimizer.training_step( + 0, 0.0, 0.0, use_sds=False + ) + # Auto threshold: initial compliance times the requested ratio. + auto_threshold = initial_compliance * args.compliance_threshold_ratio + auto_threshold = min(auto_threshold, 100000.0) # Upper bound only. + compliance_threshold = auto_threshold + config.compliance_threshold = auto_threshold + logging.info( + f" ✅ Automatically set the threshold: {initial_compliance:.2e} × {args.compliance_threshold_ratio:.2f} " + f"= {compliance_threshold:.2e}" + ) + + # Warn when the structure already looks extremely stiff or too soft. + if initial_compliance < 0.01: # Already very stiff. + logging.warning(f" ⚠️ initial compliance is very small ({initial_compliance:.2e}), the structure may already be stiff enough!") + logging.warning(f" consider increasing the external force or using a softer material to create visible deformation") + logging.warning(f" current material: E={config.youngs_modulus:.2e} Pa, ν={config.poissons_ratio}") + elif initial_compliance > 1000.0: # Likely too soft. + logging.warning(f" ⚠️ initial compliance is very large ({initial_compliance:.2e}), the structure may be too soft!") + logging.warning(f" consider using a stiffer material or reducing the external force") + except Exception as e: + logging.warning(f" ⚠️ automatic computation failed, usethreshold value200: {e}") + compliance_threshold = 200.0 + else: + compliance_threshold = config.compliance_threshold + + logging.info(f"🎯 parameters:") + logging.info(f" - initial lambda: {lagrange_multiplier}") + logging.info(f" - initial rho: {rho}") + logging.info(f" - Compliancethreshold value: {compliance_threshold:.2e}") + logging.info(f" - λMax: {args.lagrange_max}") + logging.info(f" - ρMax: {config.alm_rho_max:.1e}") + logging.info(f" - rho growth: ×{config.alm_rho_increase_factor:.1f} (continuous violations{config.alm_rho_increase_patience} steps)") + logging.info(f" - ALMscaling guard ratio: {config.alm_scale_guard_ratio:.2f}") + logging.info(f" - gradient clipping: {'enabled' if config.grad_clip_enabled else 'disabled'}") + + outer_cycles = max(1, int(args.outer_cycles)) + phys_steps_per_cycle = max(1, int(args.phys_steps_per_cycle)) + total_steps = outer_cycles * (phys_steps_per_cycle + 1) + logging.info( + f"🔁 Alternating optimization: outer cycles={outer_cycles}, physics steps/cycle={phys_steps_per_cycle}, " + f"total steps(including projections)≈{total_steps}" + ) + base_youngs_modulus = float(config.youngs_modulus) + youngs_modulus_scale = float(config.youngs_modulus_scale) + youngs_modulus_target = base_youngs_modulus * youngs_modulus_scale + youngs_modulus_delta = (youngs_modulus_target - base_youngs_modulus) / outer_cycles + projection_count = 0 + logging.info( + f" - linearly increase Young's modulus: E0={base_youngs_modulus:.2e}, " + f"Δ/projection={youngs_modulus_delta:.2e}, E_final={youngs_modulus_target:.2e} " + f"(scale={youngs_modulus_scale:.2f}x)" + ) + global_step = 0 + phys_step_count = 0 + + history = {"compliance": [], + "u_mean": [], + "c_relative_decrease": [], + "u_relative_decrease": [], + "epoch": []} + + thresholds = [0, 30, 40, 50, 60, 65, 70, 75, 80] + thresh_idx = 0 + latents_dir = os.path.join(args.out_folder, "latents") + os.makedirs(latents_dir, exist_ok=True) + finish = False + for cycle in range(outer_cycles): + if finish: + break + logging.info(f"\n{'='*60}") + logging.info(f"Outer Cycle {cycle+1}/{outer_cycles}") + logging.info(f"{'='*60}") + + for inner in range(phys_steps_per_cycle): + step_id = global_step + phys_step = phys_step_count + + # Physics optimization step with ALM. + latent, _ = optimizer._computation_target_z0_current(step=phys_step, noise=optimizer.noise) + optimizer.save_mesh(step=phys_step, output_dir="/scratch/cvlab/home/seiler/physiopt_new/output/hunyuan_gen/0001/dflow_physiopt_64_180", high_quality=True, suffix="test", latents=latent) + optimizer.latents = latent + compliance_loss, u_mean, sds_loss, total_loss = optimizer.training_step( + phys_step, lagrange_multiplier, rho, use_sds=True, save_step=step_id + ) + + # Update history + history["compliance"].append(compliance_loss) + history["u_mean"].append(u_mean) + + # Calculate relative decreases using current variables + c_decrease = (history["compliance"][0] - compliance_loss) / history["compliance"][0] * 100 + u_decrease = (history["u_mean"][0] - u_mean) / history["u_mean"][0] * 100 + history["c_relative_decrease"].append(c_decrease) + history["u_relative_decrease"].append(u_decrease) + logging.info( + f" 📉 Metrics | Comp: {compliance_loss:.3e} (↓ {c_decrease:.1f}%) | u_mean: {u_mean:.3e} (↓ {u_decrease:.1f}%)" + ) + + if thresh_idx < len(thresholds): + current_threshold = thresholds[thresh_idx] + if (c_decrease > current_threshold) or (c_decrease == current_threshold) : + logging.info(f"\n✅ Threshold reached: {current_threshold}") + optimizer.save_mesh(current_threshold, args.out_folder, suffix="decrease", high_quality=True) + + latent_path = os.path.join(latents_dir, f"latent_{current_threshold}.pt") + torch.save({ + 'latents': optimizer.latents.detach().cpu(), + 'cond': optimizer.cond, + }, latent_path) + + optimizer.save_final_deformed_mesh(current_threshold, suffix="decrease") + + history["epoch"].append(phys_step) + thresh_idx += 1 + else: + finish = True + break + + # Normalized constraint: g = D / D_thr - 1. + violation = (compliance_loss / (compliance_threshold + 1e-8)) - 1.0 + g_pos = max(0.0, violation) + + # Update lambda and project it to the non-negative range. + lagrange_multiplier = max(0.0, lagrange_multiplier + rho * violation) + lagrange_multiplier = min(lagrange_multiplier, args.lagrange_max) + + # Increase rho after persistent violations. + if g_pos > 0.0: + violation_count += 1 + if violation_count >= config.alm_rho_increase_patience: + new_rho = min(rho * config.alm_rho_increase_factor, config.alm_rho_max) + if new_rho > rho: + rho = new_rho + logging.info(f" 🔧 rho increased: {rho:.2e} (continuous violations{config.alm_rho_increase_patience} steps)") + violation_count = 0 + else: + violation_count = 0 + + status = "❌ violating" if violation > 0 else "✅ within threshold" + + # Log a compact ALM summary. + logging.info( + f" 📊 Compliance (true) : {compliance_loss:.2e} vs threshold value{compliance_threshold:.2e} " + f"(g={violation:+.3e}, [g]+={g_pos:.3e}) {status}" + ) + logging.info(f" ⚖️ ALMStatus: λ={lagrange_multiplier:.4f} (max={args.lagrange_max}), ρ={rho:.2e}") + current_sds_weight = optimizer.get_current_sds_weight(phys_step) + if current_sds_weight > 0.0: + sds_percentage = (current_sds_weight * sds_loss) / (total_loss + 1e-10) * 100 + logging.info( + f" 🎨 Shape Loss: weight={current_sds_weight:.6f}, " + f"loss={sds_loss:.4e}, ratio={sds_percentage:.2f}%" + ) + else: + logging.info(f" 🎨 Shape Loss: disabled (weight is 0)") + + # Save only the first and last physics step of each outer cycle. + # is_first_phys_step = inner == 0 + # is_last_phys_step = inner == phys_steps_per_cycle - 1 + # if is_first_phys_step or is_last_phys_step: + # optimizer.save_mesh(step_id, args.out_folder) + + global_step += 1 + phys_step_count += 1 + + # Project back to the manifold by replacing latents with target_z0. + # logging.info(f"\nStep {global_step} | Projection (E={optimizer.config.youngs_modulus:.2e} Pa)") + # logging.info(" 🔮 manifold projection: add noise and compute target_z0, backreplace directlylatents") + # projected = optimizer.project_to_manifold(step=global_step) + # if not projected: + # logging.warning(" ⚠️ projection failed, keep the physical result for this cycle") + # else: + # projection_count += 1 + # new_E = base_youngs_modulus + youngs_modulus_delta * projection_count + # new_E = min(new_E, youngs_modulus_target) + # optimizer.config.youngs_modulus = new_E + # if hasattr(optimizer, "E"): + # optimizer.E = new_E + # logging.info( + # f" 🧱 Young's modulusupdate: E={new_E:.2e} " + # f"(projection {projection_count}/{outer_cycles})" + # ) + # if global_step % 20 == 0: + # projection_dir = os.path.join(args.out_folder, "projection_meshes") + # os.makedirs(projection_dir, exist_ok=True) + # optimizer.save_mesh(global_step, projection_dir) + global_step += 1 + + final_step = global_step + else: + # Pure SDS optimization. + for step in range(args.num_steps): + logging.info(f"\nStep {step}/{args.num_steps}") + optimizer.training_step_sds(step) + if step % 20 == 0: + optimizer.save_mesh(step, args.out_folder) + + # Save final results. + logging.info("\n✅ Optimization finished!save final results...") + optimizer.save_mesh(final_step, args.out_folder, high_quality=True) + if args.use_physics: + optimizer.save_final_target_z0_mesh(final_step) + optimizer.save_final_deformed_mesh(final_step) + + final_latents_path = os.path.join(args.out_folder, "optimized_latents.pt") + torch.save({ + 'latents': optimizer.latents.detach().cpu(), + 'cond': optimizer.cond, + }, final_latents_path) + logging.info(f"💾 save optimized latents: {final_latents_path}") + logging.info(f"\n✅ all files saved to: {args.out_folder}") + + history_path = os.path.join(args.out_folder, "history.json") + with open(history_path, "w", encoding="utf-8") as f: + json.dump(history, f, indent=4) + plot_history(history, save_dir=args.out_folder, filename="optimization_metrics.png") + + if args.use_physics: + logging.info(f"\n📊 force visualization data:") + logging.info(f" - directory: {os.path.join(args.out_folder, 'force_visualization')}") + logging.info(f" - quick view: cd {os.path.join(args.out_folder, 'force_visualization')} && python visualize_forces.py") + + +if __name__ == "__main__": + main() diff --git a/cfd_workflow_20261012/_seiler_ref/physiopt_new_scripts/hunyuan_ictm_me.py b/cfd_workflow_20261012/_seiler_ref/physiopt_new_scripts/hunyuan_ictm_me.py new file mode 100644 index 0000000000000000000000000000000000000000..b94e4685c8f26635fbf60751f17944a37c22ffff --- /dev/null +++ b/cfd_workflow_20261012/_seiler_ref/physiopt_new_scripts/hunyuan_ictm_me.py @@ -0,0 +1,3185 @@ +""" +Hunyuan3D-2.1 physical optimization + shape-prior optimization. +""" + +import os +import copy +# os.environ['TORCH_HOME'] = '/mnt/cvlab/scratch/cvlab/home/hantzhan/.torch' +import sys +import shutil + +# Add Hunyuan3D-2.1 to the Python path. +hunyuan_path = os.path.abspath(os.path.join(os.path.dirname(__file__), "../../Hunyuan3D-2.1")) +# Note: logging is not imported yet, so use print here if needed. +# Basic logging is configured near the top of the file after import. + +sys.path.append("..") + +from matplotlib import pyplot as plt +import torch +import torch.nn.functional as F +import trimesh +import numpy as np +from PIL import Image +import argparse +import json +from typing import Tuple, Optional, List +from dataclasses import dataclass, field +import traceback +import logging + +# Configure logging here only conceptually; main() will reconfigure it to +# log to both the console and a file. +# Do not call basicConfig here so the main() configuration remains effective. +# logging.basicConfig(level=logging.INFO, format='%(levelname)s: %(message)s') + +# Physical-simulation imports. +PHYSIOPT_AVAILABLE = False +try: + from physiopt.utils.phys_utils import generate_hex + from physiopt.utils.grid_utils import filter_one_component + from physiopt.opt.field import occ_kernel + from physiopt.opt.forces import ForceConfig + PHYSIOPT_AVAILABLE = True + logging.info("✅ physics simulation moduleimportsucceeded") +except ImportError as e: + logging.warning(f"⚠️ warning: physics simulation moduleimportfailed: {e}") + logging.warning(" if you only run SDS optimization, you can ignore this warning") + PHYSIOPT_AVAILABLE = False + + def generate_hex(res, limits=[(-0.5, 0.5), (-0.5, 0.5), (-0.5, 0.5)], device="cuda", return_coords=False): + """Placeholder for hexahedral grid generation. + + Returns tensors in the same format as the real function. + """ + logging.warning(f"⚠️ warning: using placeholdergenerate_hex, please install the physiopt module") + return None, None + + def filter_one_component(mask, res): + """Placeholder for connected-component filtering. + + Args: + mask: Element mask [res*res*res] + res: Voxel resolution + """ + return mask + + def occ_kernel(sdf, res, beta): + """Placeholder for SDF-to-occupancy conversion.""" + return torch.sigmoid(-sdf * beta) + +# Warp physics-engine import. +try: + import warp as wp + wp.init() + WARP_AVAILABLE = True + logging.info("✅ Warp physics engineInitializationsucceeded") +except ImportError: + WARP_AVAILABLE = False + logging.warning("⚠️ warning: Warp physics enginenot installed, physics simulationwill be unavailable") + logging.warning(" Install: pip install warp-lang") + +# Hunyuan3D imports +try: + from hy3dgen.shapegen.models.autoencoders import ShapeVAE + from hy3dgen.shapegen import Hunyuan3DDiTFlowMatchingPipeline + from hy3dgen.shapegen.pipelines import export_to_trimesh +except ImportError as e: + logging.error(f"❌ failed to import Hunyuan3D modules: {e}") + logging.error(f"\nplease follow these steps to set upHunyuan3D-2.1:") + logging.error(f"1. cd {os.path.dirname(hunyuan_path)}") + logging.error(f"2. git clone https://github.com/Tencent/Hunyuan3D-2.git Hunyuan3D-2.1") + logging.error(f"3. cd Hunyuan3D-2.1") + logging.error(f"4. pip install -e .") + sys.exit(1) + + +@dataclass +class OptimizationConfig: + """Optimization config for physics + SDS.""" + # Physical-simulation parameters. + res: int = 32 # Voxel resolution (16/32/64), matching the reference code. + # Restored physical settings from the stable v90 configuration. + p_exponent: float = 1.0 # SIMP penalty exponent. + alpha_min: float = 0.01 # Minimum density, restored from v90. + volume_term: float = 1000000.0 # Volume-constraint weight, currently disabled. + occ_sdf_beta: float = 2.0 # Sigmoid-kernel beta, restored from v90. + one_cc_only: bool = False # Keep only the largest connected component. + + # SDS parameters. + # Use dynamic SDS weights so physics dominates early and aesthetics enters later. + sds_timestep: float = 0.1 # SDS timestep; smaller values preserve more detail. + sds_weight: float = 1.0 # SDS weight relative to the physical gradient. + sds_weight_start: float = 1e5 # 0.1 # 0.0001 # Initial SDS weight. + sds_weight_end: float = 1e5 # 1.0 # 0.001 # Final SDS weight. + guidance_scale: float = 7.5 # Standard CFG guidance scale for stronger image conditioning. + sds_projection_max_rel: float = 0.0 # Max relative target_z0 projection offset (0 = unlimited). + sds_use_uncond: bool = False # Use the unconditional branch when guidance_scale <= 1. + sds_target_z0_update_interval: int = 10 # target_z0 update interval; tied to phys_steps_per_cycle. + sds_target_z0_ema_beta: float = 0.9 # EMA smoothing coefficient; larger is smoother. + + lagrange_max: float = 50.0 # Max lambda. + compliance_threshold: float = 200.0 # Compliance threshold used for normalization. + alm_rho_init: float = 1.0 # Initial rho. + alm_rho_max: float = 1000.0 # Max rho. + alm_rho_increase_factor: float = 2.0 # Rho growth factor. + alm_rho_increase_patience: int = 5 # Number of consecutive violations before increasing rho. + alm_scale_guard_ratio: float = 0.95 # ALM scaling guard to stay below gradient clipping. + + # Topology control. + re_extract_interval: int = 5 # Re-extract the solid every N steps; 0 disables it. + + # Material properties. Values are aligned with the reference setup. + # youngs_modulus is already specified directly in Pa, so no unit conversion is needed. + youngs_modulus: float = 5e8 # 1e9 # Pa (= 1 GPa), restored from v90. + youngs_modulus_scale: float = 2.0 # Final multiplier after the last projection in alternating mode. + poissons_ratio: float = 0.3 # Poisson's ratio (dimensionless). + density: float = 650.0 # Material density (kg/m^3). + + ## Wood + # youngs_modulus: float = 9e9 # Pa (= 1 GPa), aligned with the reference code. + # poissons_ratio: float = 0.35 # Poisson's ratio (dimensionless), matches the reference. + # density: float = 400.0 # Material density (kg/m^3), matches the reference. + + ## PVG + # youngs_modulus: float = 3.25e9 # Pa (= 1 GPa), aligned with the reference code. + # poissons_ratio: float = 0.38 # Poisson's ratio (dimensionless), matches the reference. + # density: float = 1380.0 # Material density (kg/m^3), matches the reference. + + # Load conditions; supports multiple forces like config.json. + forces: List = None # List of ForceConfig objects. + # Multiple localized load entries, each with its own force and region settings. + force_entries: Optional[List[dict]] = None + + # Local-loading settings, e.g. to mimic a person sitting on a chair. + use_local_loading: bool = True # Use local loading instead of global uniform loading. + seat_height_min_ratio: float = 0.3 # Lower bound of the seat band as a height ratio. + seat_height_max_ratio: float = 0.5 # Upper bound of the seat band as a height ratio. + force_region_mode: str = "top_percent" # Load-region mode: top_percent / height_ratio / bbox. + force_top_percent: float = 0.05 # In top_percent mode, use the highest-Y fraction of nodes. + force_bbox: Optional[List[float]] = None # bbox mode: x_min x_max y_min y_max z_min z_max. + force_bbox_ratio: Optional[List[float]] = None # bbox mode in normalized node bounds [0, 1]. + + # Optimization parameters, restored from the stable v90 configuration. + lr: float = 0.001 # Learning rate. + num_steps: int = 100 # Number of optimization steps. + use_sgd: bool = False # Use SGD instead of Adam. + grad_clip_enabled: bool = False # Enable gradient clipping; off by default. + save_every: int = 10 # Save interval in steps. + deformed_mesh_interval: int = 10 # Save interval for deformed meshes. + deformed_mesh_disp_min: float = 0.0 # Minimum displacement for deformed-mesh color mapping. + deformed_mesh_disp_max: float = 0.2 # Maximum displacement for deformed-mesh color mapping. + + # Output path. + out_folder: str = "../out/hunyuan_opt" # Output directory. + + # Device. + device: str = "cuda" # Compute device. + + # Whether to enable physics optimization. + use_physics: bool = True # Enable physical-constraint optimization. + + def __post_init__(self): + # Set default loads in the Hunyuan Y-up coordinate system: + # X = right, Y = up, Z = forward. + if self.forces is None: + try: + from physiopt.opt.forces import ForceConfig + self.forces = [ + ForceConfig(external_force=[0.0, -100000.0, 0.0]) # 100 kN downward along Y. + # ForceConfig(external_force=[0.0, 0.0, -500.0]), # 500 N backward along Z. + ] + except ImportError: + # Fallback format if physiopt is unavailable; keep only the force vectors. + self.forces = [ + {'external_force': [0.0, -100000.0, 0.0]} # 100 kN downward along Y. + # {'external_force': [0.0, 0.0, -500.0]}, # Backward along Z. + ] + + +class HunyuanSDSOptimizer: + """Hunyuan3D SDS optimizer with differentiable physics support.""" + + def __init__( + self, + latents: torch.Tensor, + cond: dict, # Condition dict containing positive and negative branches. + vae: ShapeVAE, + flow_model: torch.nn.Module, + config: OptimizationConfig, + scheduler=None, + device: str = 'cuda' + ): + """ + Args: + latents: Initial latent tokens [1, N, D]. + cond: Condition dict returned by pipeline.encode_cond. + vae: Hunyuan3D VAE model. + flow_model: Hunyuan3D Flow Matching model. + scheduler: Hunyuan3D Flow Matching scheduler used to align target_z0. + config: Optimization config. + device: Compute device. + """ + self.device = device + self.config = config + + # Models. + self.vae = vae.to(device).eval() + self.flow_model = flow_model.to(device).eval() + if scheduler is not None: + try: + self.sds_scheduler = copy.deepcopy(scheduler) + except Exception: + self.sds_scheduler = scheduler + logging.warning("⚠️ Scheduler deepcopyfailed, already fallback to originalscheduler") + else: + self.sds_scheduler = None + + # Create a differentiable SDF query helper. + from hy3dgen.shapegen.models.autoencoders.differentiable_sdf_query import DifferentiableSDFQuery + self.sdf_query = DifferentiableSDFQuery( + vae=self.vae, + bounds=0.8, # Our coordinate range is [-0.8, 0.8]. + chunk_size=8192 # Batch query size. + ) + logging.info(f"✅ created differentiable SDF query helper") + + # Latent tokens are the variables being optimized. + # Use float32 instead of float16 to avoid numeric overflow. + self.latents = latents.clone().to(device).to(torch.float32).requires_grad_(True) + + logging.info(f" ⚠️ note: Latentsfloat32FP16value") + + # Move conditioning data to the target device recursively. + def to_device_recursive(obj): + if isinstance(obj, torch.Tensor): + return obj.to(device) + elif isinstance(obj, dict): + return {k: to_device_recursive(v) for k, v in obj.items()} + elif isinstance(obj, (list, tuple)): + return type(obj)(to_device_recursive(item) for item in obj) + else: + return obj + + self.cond = to_device_recursive(cond) + self._cond_warned_cfg_repeat = False + self._cond_warned_nocfg_slice = False + + # Optimizer selection. + if config.use_sgd: + self.optimizer = torch.optim.SGD([self.latents], lr=config.lr, momentum=0.0) + opt_name = "SGD" + else: + self.optimizer = torch.optim.Adam([self.latents], lr=config.lr, betas=(0.9, 0.999), eps=1e-8) + opt_name = "Adam" + + logging.info(f"✅ HunyuanSDSOptimizerInitializationcompleted (with differentiable physics support) ") + logging.info(f" - Latents shape: {self.latents.shape}") + logging.info(f" - Latents dtype: {self.latents.dtype} (optimized in float32)") + logging.info(f" - Device: {device}") + logging.info(f" - Optimizer: {opt_name}") + logging.info(f" - Learning rate: {config.lr}") + + # target_z0 EMA cache. + self.target_z0_ema = None + self.target_z0_last_velocity = None + self.target_z0_last_update = None + + def get_field(self, x: torch.Tensor, latents: torch.Tensor = None) -> torch.Tensor: + """Differentiable SDF query through the VAE geo_decoder. + + Args: + x: Query points [N, 3] in the range [-0.8, 0.8]^3. + latents: Optional latent tokens; defaults to self.latents. + + Returns: + sdf: SDF values [N] with gradient support. + """ + if latents is None: + latents = self.latents + + # Match the official pipeline: divide by scale_factor before decoding. + scale_factor = getattr(self.vae, "scale_factor", 1.0) + latents_scaled = latents / scale_factor + + # Convert to FP16 because the VAE expects FP16 inputs. + latents_fp16 = latents_scaled.to(torch.float16) + + # Decode with the VAE decoder while preserving gradients. + decoded_latents = self.vae.decode(latents_fp16) + + # Query the SDF through the differentiable helper. + # sdf_query calls geo_decoder internally, so keep FP16 to match VAE weights. + sdf = self.sdf_query( + decoded_latents, # Keep FP16 and let sdf_query handle the rest. + x, + return_occupancy=False # Return SDF instead of occupancy. + ) # [N] + + return sdf + + def _cond_batch_size(self, cond) -> Optional[int]: + if isinstance(cond, torch.Tensor): + return cond.shape[0] if cond.dim() >= 1 else None + if isinstance(cond, dict): + for v in cond.values(): + bsz = self._cond_batch_size(v) + if bsz is not None: + return bsz + if isinstance(cond, (list, tuple)): + for v in cond: + bsz = self._cond_batch_size(v) + if bsz is not None: + return bsz + return None + + def _cond_slice(self, cond, batch_slice: slice): + if isinstance(cond, torch.Tensor): + if cond.dim() >= 1 and cond.shape[0] >= batch_slice.stop: + return cond[batch_slice] + return cond + if isinstance(cond, dict): + return {k: self._cond_slice(v, batch_slice) for k, v in cond.items()} + if isinstance(cond, (list, tuple)): + return type(cond)(self._cond_slice(v, batch_slice) for v in cond) + return cond + + def _cond_repeat(self, cond, repeats: int): + if isinstance(cond, torch.Tensor): + if cond.dim() >= 1: + rep_shape = (repeats,) + (1,) * (cond.dim() - 1) + return cond.repeat(rep_shape) + return cond + if isinstance(cond, dict): + return {k: self._cond_repeat(v, repeats) for k, v in cond.items()} + if isinstance(cond, (list, tuple)): + return type(cond)(self._cond_repeat(v, repeats) for v in cond) + return cond + + def _get_cond_for_guidance(self, use_cfg: bool): + cond = self.cond + bsz = self._cond_batch_size(cond) + if use_cfg: + if bsz == 1: + if not self._cond_warned_cfg_repeat: + logging.warning("⚠️ guidance_scale>1 cond batch=1, already condCFG") + self._cond_warned_cfg_repeat = True + return self._cond_repeat(cond, 2) + if bsz is not None and bsz > 2: + return self._cond_slice(cond, slice(0, 2)) + return cond + # no-CFG + if bsz is not None and bsz >= 2: + if self.config.sds_use_uncond: + if not self._cond_warned_nocfg_slice: + logging.info("ℹ️ guidance_scale<=1, useno conditioncond[1:2]") + self._cond_warned_nocfg_slice = True + return self._cond_slice(cond, slice(1, 2)) + if not self._cond_warned_nocfg_slice: + logging.info("ℹ️ guidance_scale<=1, already usecond[0:1]batch") + self._cond_warned_nocfg_slice = True + return self._cond_slice(cond, slice(0, 1)) + if self.config.sds_use_uncond and bsz == 1 and not self._cond_warned_nocfg_slice: + logging.warning("⚠️ sds_use_uncond=1 cond batch=1, already fallback to conditself") + self._cond_warned_nocfg_slice = True + return cond + + def latents_to_mesh(self, latents: torch.Tensor, octree_res: int = 128) -> Optional[trimesh.Trimesh]: + """Decode latent tokens into a mesh. + + Args: + latents: Latent tokens [1, N, D] (float32). + octree_res: Octree resolution. 128 is faster; 256 is higher quality. + + Returns: + A trimesh.Trimesh object, or None on failure. + """ + with torch.no_grad(): + # Skip invalid latent tensors early. + if torch.isnan(latents).any() or torch.isinf(latents).any(): + logging.warning(" latents_to_mesh: latentscontains NaN or Inf, skip") + return None + + # Match the official pipeline by dividing by scale_factor first. + scale_factor = getattr(self.vae, "scale_factor", 1.0) + latents_scaled = latents / scale_factor + + # Decode in FP16 because the VAE expects FP16 inputs. + latents_fp16 = latents_scaled.to(torch.float16) + + try: + # VAE decode. + decoded_latents = self.vae.decode(latents_fp16) + + # Skip invalid decoded latents. + if torch.isnan(decoded_latents).any() or torch.isinf(decoded_latents).any(): + logging.warning(" latents_to_mesh: decoded_latentscontains NaN or Inf, skip") + return None + except Exception as e: + logging.debug(f" latents_to_mesh: VAE decodingfailed: {e}") + return None + + # Use an adaptive mc_level fallback if the default level fails. + try: + # First try the standard mc_level=0.0. + mesh = self.vae.latents2mesh( + decoded_latents, + output_type='trimesh', + bounds=1.01, + mc_level=0.0, + num_chunks=20000, + octree_resolution=octree_res, + mc_algo='mc', + enable_pbar=False + ) + mesh = export_to_trimesh(mesh)[0] + return mesh + + except ValueError as e: + error_msg = str(e) + if "Surface level must be within volume data range" in error_msg: + # Estimate a better mc_level from sampled SDF statistics. + logging.debug(f" latents_to_mesh: mc_level=0.0 failed, try an adaptive level...") + + try: + # Sample a coarse grid to estimate the SDF range. + grid_size = 32 + x = torch.linspace(-1.0, 1.0, grid_size, device=decoded_latents.device) + y = torch.linspace(-1.0, 1.0, grid_size, device=decoded_latents.device) + z = torch.linspace(-1.0, 1.0, grid_size, device=decoded_latents.device) + xx, yy, zz = torch.meshgrid(x, y, z, indexing='ij') + points = torch.stack([xx, yy, zz], dim=-1).reshape(-1, 3) # [N, 3] + + # query the SDF values. + sdf_values = self.get_field(points, latents=latents) + + # Compute basic statistics. + sdf_median = torch.median(sdf_values).item() + sdf_min = sdf_values.min().item() + sdf_max = sdf_values.max().item() + sdf_mean = sdf_values.mean().item() + + logging.debug(f" SDFstatistics: min={sdf_min:.4f}, max={sdf_max:.4f}, median={sdf_median:.4f}, mean={sdf_mean:.4f}") + + # No clear surface can be extracted if the SDF range is too small. + if abs(sdf_max - sdf_min) < 1e-4: + logging.debug(f" SDFrange is too small to extract a surface") + return None + + # Try several plausible candidate levels. + candidate_levels = [ + sdf_median, # Median. + sdf_mean, # Mean. + (sdf_min + sdf_max) / 2, # Midpoint of the range. + sdf_min + (sdf_max - sdf_min) * 0.3, # 30% point. + sdf_min + (sdf_max - sdf_min) * 0.7, # 70% point. + ] + + # Clamp all levels to the valid range. + valid_levels = [ + max(sdf_min + 0.001, min(sdf_max - 0.001, level)) + for level in candidate_levels + ] + + # Remove duplicates. + valid_levels = list(set(valid_levels)) + + logging.debug(f" try {len(valid_levels)} candidate levels: {[f'{l:.4f}' for l in valid_levels[:3]]}...") + + # Try each candidate level in order. + for i, adaptive_level in enumerate(valid_levels): + try: + mesh = self.vae.latents2mesh( + decoded_latents, + output_type='trimesh', + bounds=1.01, + mc_level=adaptive_level, + num_chunks=20000, + octree_resolution=octree_res, + mc_algo='mc', + enable_pbar=False + ) + mesh = export_to_trimesh(mesh)[0] + logging.info(f" ✅ uselevelsucceeded (level={adaptive_level:.4f}, attempt {i+1})") + return mesh + except (ValueError, RuntimeError) as level_error: + # Try the next level if this one fails. + if i < len(valid_levels) - 1: + continue + else: + # All candidate levels failed. + logging.debug(f" all candidate levels failed") + return None + + # No candidate succeeded. + return None + + except Exception as adaptive_error: + logging.debug(f" adaptive extraction failed: {type(adaptive_error).__name__}: {str(adaptive_error)[:50]}") + return None + + elif "No surface found" in error_msg: + logging.debug(f" latents_to_mesh: Marching cubesno surface found, skip") + return None + else: + logging.warning(f" latents_to_mesh: unknown ValueError: {error_msg}") + return None + + except RuntimeError as e: + error_msg = str(e) + if "No surface found" in error_msg or "Surface level" in error_msg: + logging.debug(f" latents_to_mesh: Marching cubesfailed, skip") + return None + else: + logging.warning(f" latents_to_mesh: RuntimeError: {error_msg}") + return None + + except Exception as e: + # Catch any other unexpected failure. + logging.warning(f" latents_to_mesh: unexpected exception: {type(e).__name__}: {e}") + return None + + def _filter_floating_components(self, mesh: trimesh.Trimesh) -> trimesh.Trimesh: + """Remove small floating fragments and keep only the largest component.""" + try: + components = mesh.split(only_watertight=False) + if len(components) <= 1: + return mesh + + face_counts = [len(comp.faces) for comp in components] + max_idx = int(np.argmax(face_counts)) + filtered = components[max_idx] + dropped = len(components) - 1 + + logging.info(f" 🧹 filter floating fragments: kept{len(filtered.faces)} faces, discarded{dropped} small components") + return filtered + except Exception as e: + logging.warning(f" failed to filter floating fragments: {type(e).__name__}: {str(e)[:100]}") + return mesh + + def _sample_displacement_to_vertices( + self, + vertices: np.ndarray, + nodes: np.ndarray, + displacement: np.ndarray, + ) -> np.ndarray: + """Sample the voxel-node displacement field onto mesh vertices by nearest neighbor.""" + try: + from scipy.spatial import cKDTree + tree = cKDTree(nodes) + _, idx = tree.query(vertices, k=1) + return displacement[idx] + except Exception as e: + try: + from sklearn.neighbors import NearestNeighbors + nn = NearestNeighbors(n_neighbors=1, algorithm="auto") + nn.fit(nodes) + idx = nn.kneighbors(vertices, return_distance=False).squeeze(1) + return displacement[idx] + except Exception as e2: + logging.warning(f" displacement sampling failed, fallback to zero displacement: {type(e).__name__}: {str(e)[:100]}") + logging.debug(f" secondaryError: {type(e2).__name__}: {str(e2)[:100]}") + return np.zeros_like(vertices) + + def _normalize_displacement_magnitude( + self, disp_mag: np.ndarray + ) -> Tuple[np.ndarray, float, float, bool]: + """Normalize displacement magnitude, optionally with a fixed range.""" + mag_max_cfg = getattr(self.config, "deformed_mesh_disp_max", None) + mag_min_cfg = getattr(self.config, "deformed_mesh_disp_min", None) + use_fixed = mag_max_cfg is not None and mag_max_cfg > 0.0 + if use_fixed: + mag_min = 0.0 if mag_min_cfg is None else float(mag_min_cfg) + mag_max = float(mag_max_cfg) + if mag_max <= mag_min: + use_fixed = False + if not use_fixed: + mag_min = float(disp_mag.min()) + mag_max = float(disp_mag.max()) + denom = max(1e-12, mag_max - mag_min) + norm = (disp_mag - mag_min) / denom + if use_fixed: + norm = np.clip(norm, 0.0, 1.0) + return norm, mag_min, mag_max, use_fixed + + def _make_displacement_colors(self, displacement: np.ndarray) -> np.ndarray: + """Map displacement magnitude to vertex colors (blue -> red).""" + disp_mag = np.linalg.norm(displacement, axis=1) + norm, _, _, _ = self._normalize_displacement_magnitude(disp_mag) + colors = np.stack([norm, np.zeros_like(norm), 1.0 - norm], axis=1) + return (colors * 255).astype(np.uint8) + + def _log_physical_quantities( + self, + u: torch.Tensor, + sigma: Optional[torch.Tensor], + ) -> None: + """Log displacement and von Mises stress statistics.""" + with torch.no_grad(): + u_max = None + u_avg = None + try: + u_mag = torch.norm(u, dim=1) + u_max = u_mag.max().item() + u_avg = u_mag.mean().item() + except Exception as e: + logging.warning( + f" ⚠️ displacement statistics failed: {type(e).__name__}: {str(e)[:100]}" + ) + + sigma_vm_max = None + sigma_vm_avg = None + if sigma is not None: + try: + if sigma.dim() == 2 and sigma.shape[1] >= 6: + s_xx = sigma[:, 0] + s_yy = sigma[:, 1] + s_zz = sigma[:, 2] + s_yz = sigma[:, 3] + s_xz = sigma[:, 4] + s_xy = sigma[:, 5] + mises_sq = 0.5 * ( + (s_xx - s_yy) ** 2 + + (s_yy - s_zz) ** 2 + + (s_zz - s_xx) ** 2 + + 6.0 * (s_xy ** 2 + s_yz ** 2 + s_xz ** 2) + ) + mises = torch.sqrt(torch.clamp(mises_sq, min=0.0)) + sigma_vm_max = mises.max().item() + sigma_vm_avg = mises.mean().item() + else: + logging.warning( + f" ⚠️ sigmashape does not match expectations, skip von Mises statistics: {tuple(sigma.shape)}" + ) + except Exception as e: + logging.warning( + f" ⚠️ von Mises statistics failed: {type(e).__name__}: {str(e)[:100]}" + ) + + if u_max is not None and u_avg is not None: + if sigma_vm_max is not None and sigma_vm_avg is not None: + logging.info( + f" physical metrics: u_max={u_max:.3e}, u_avg={u_avg:.3e}, " + f"sigma_vm_max={sigma_vm_max:.3e}, sigma_vm_avg={sigma_vm_avg:.3e}" + ) + else: + logging.info( + f" physical metrics: u_max={u_max:.3e}, u_avg={u_avg:.3e}" + ) + + def backward_step(self, sensitivity_density: torch.Tensor, latents=None): + """Backpropagate with VJP, aligned with the reference code. + + Reference: viewer_deepsdf.py Line 148-183. + This uses torch.autograd.functional.vjp to propagate sensitivity to latents. + """ + def f(latents: torch.Tensor): + """ + Compute occupancy from a given latent tensor. + Aligned with viewer_deepsdf.py Line 155-173. + """ + # Query the SDF. + sdf = self.get_field(self.nodes, latents) + + # SDF → occupancy + from physiopt.opt.field import occ_kernel + occ = occ_kernel(sdf, self.config.res, self.config.occ_sdf_beta) + + # Element occupancy is the average over the 8 nodes. + occ_elem = occ[self.elements].mean(1) + + # Clamp by alpha_min if requested. + if self.config.alpha_min > 0.0: + occ_elem = torch.clamp(occ_elem, self.config.alpha_min) + + return occ_elem + + # VJP computations d occ / d latents^T times the sensitivity vector. + # Aligned with viewer_deepsdf.py Line 175-180. + try: + target_latents = self.latents if latents is None else latents + + grad_latent = torch.autograd.functional.vjp( + f, + target_latents.clone().requires_grad_(True), + sensitivity_density, + )[1] + + if grad_latent is None: + logging.error(" ❌ VJP returned None!") + return + + grad_norm = torch.norm(grad_latent).item() + logging.info(f" VJP gradient: norm={grad_norm:.2e}") + + target_latents.grad = grad_latent + + if latents is None: + return True + else: + return target_latents + + except Exception as e: + logging.error(f" ❌ VJP failed: {e}") + import traceback + traceback.print_exc() + + def prepare_physical_simulation(self): + """Prepare the physical simulation and FEM solver state. + + Initialization includes: + 1. Material properties + 2. Boundary conditions + 3. External forces + """ + if not WARP_AVAILABLE: + logging.warning("Warpnot installed, skipphysics simulation preparation") + return + + if not hasattr(self, 'nodes') or not hasattr(self, 'elements'): + logging.error("please call extract_solid() to extract the solid first") + return + + logging.info("prepare physical simulation...") + + # Initialize Warp. + wp.init() + + # Normalize device names such as "cuda" and "cuda:0". + if 'cuda' in self.device: + # Extract the device id when needed. + if ':' in self.device: + device_id = self.device.split(':')[-1] + warp_device = f"cuda:{device_id}" + else: + warp_device = "cuda:0" # default to cuda:0 + else: + warp_device = "cpu" + + wp.set_device(warp_device) + logging.info(f"Warpdevice: {warp_device}") + + # Material properties. + self.E = self.config.youngs_modulus # Young's modulus. + self.nu = self.config.poissons_ratio # Poisson's ratio. + self.rho = self.config.density # Density. + + # Boundary condition: fix bottom nodes using Hunyuan's Y-up frame. + y_coords = self.nodes[:, 1] + y_min = y_coords.min() + boundary_threshold = y_min + 0.05 # 0.2 # 0.05 # Bottom 5% band. + self.boundary_mask = y_coords < boundary_threshold + + logging.info(f" coordinate system: Y-up (Hunyuan-native), fix Y < {boundary_threshold:.3f}nodes") + + # Apply load locally instead of spreading it across all nodes. + # The default heuristic targets a seat-like region in the Y-up frame. + + # Compute the total force, giving priority to force_entries. + total_force = np.zeros(3, dtype=np.float32) + force_entries = getattr(self.config, "force_entries", None) + valid_force_entries = None + if force_entries: + valid_force_entries = [] + for entry in force_entries: + if not isinstance(entry, dict): + continue + entry_force = None + if "force" in entry: + try: + entry_force = np.array(entry["force"], dtype=np.float32) + except Exception: + entry_force = None + elif "forces" in entry and isinstance(entry["forces"], list): + try: + entry_force = np.sum( + np.array(entry["forces"], dtype=np.float32), axis=0 + ) + except Exception: + entry_force = None + if entry_force is None or entry_force.shape != (3,): + continue + valid_force_entries.append(entry) + total_force += entry_force + if valid_force_entries: + self.force_entries_preset = valid_force_entries + logging.info(f" force entries: {len(valid_force_entries)}") + else: + logging.warning(" ⚠️ force_entries has no valid entries, fallback to forces") + valid_force_entries = None + + if valid_force_entries is None: + for force_config in self.config.forces: + if hasattr(force_config, 'get_total_force'): + # ForceConfig object. + total_force += force_config.get_total_force() + elif isinstance(force_config, dict) and 'external_force' in force_config: + # Compatibility format using a plain dict. + total_force += np.array(force_config['external_force'], dtype=np.float32) + else: + logging.warning(f"unknown force format: {type(force_config)}") + + logging.info(f" sum of external forces (Y-up coordinates): {total_force}") + + # Choose the loading strategy from the config. + if valid_force_entries is not None: + # Multiple localized loads, each with its own region. + self._setup_local_loading(total_force) + elif self.config.use_local_loading: + # Preferred mode: local loading. + self._setup_local_loading(total_force) + else: + # Fallback mode: global uniform loading. + logging.info(f" ℹ️ using global uniform loading mode") + total_force_tensor = torch.from_numpy(total_force).float().to(self.device) + num_nodes = self.nodes.shape[0] + self.forces = total_force_tensor[None, :].repeat(num_nodes, 1) + logging.info(f" 💨 distributed the total force uniformly to{num_nodes}nodes") + + logging.info(f"boundary conditions: {self.boundary_mask.sum().item()}fixed nodes") + logging.info(f"material properties: E={self.E:.2e}, ν={self.nu}, ρ={self.rho}") + + def _setup_local_loading(self, total_force: np.ndarray): + """Set up local loading on the selected seat/contact region. + + The total force is distributed uniformly across the selected nodes so + that sum(forces) equals total_force. + + Args: + total_force: Total force vector [3] in the Y-up frame, in Newtons. + """ + # Cache the total force for later updates. + self.total_force_preset = torch.from_numpy(total_force).float().to(self.device) + + # Reuse the generic update routine for the initial setup. + self._update_forces(initial_setup=True) + + def _update_forces(self, initial_setup: bool = False): + """Update the force distribution for the current mesh state. + + Core logic: + 1. Re-identify contact nodes + 2. Spread the preset total force uniformly over those nodes + 3. Keep total force conserved + + Args: + initial_setup: Whether this is the first setup pass. + """ + if not hasattr(self, 'total_force_preset'): + logging.warning("No preset total force is set, so the force distribution cannot be updated") + return + + # Step 1: inspect the Y-coordinate distribution. + y_coords = self.nodes[:, 1] + num_nodes = self.nodes.shape[0] + + force_entries = getattr(self, "force_entries_preset", None) + if force_entries: + def _select_nodes_for_mode(mode, top_percent, min_ratio, max_ratio, bbox, bbox_ratio): + seat_mask = torch.zeros(num_nodes, dtype=torch.bool, device=self.device) + mode_used = mode + bbox_desc = None + + if mode_used not in ("top_percent", "height_ratio", "bbox", "global"): + logging.warning(f" ⚠️ invalid force_region_mode: {mode_used}, fallback to top_percent") + mode_used = "top_percent" + + if mode_used == "global": + seat_mask[:] = True + return seat_mask, mode_used, bbox_desc + + if mode_used == "bbox": + bbox_vals = None + if bbox is not None and len(bbox) == 6: + bbox_vals = [float(v) for v in bbox] + bbox_desc = "abs" + elif bbox_ratio is not None and len(bbox_ratio) == 6: + bbox_ratio_vals = [float(v) for v in bbox_ratio] + bounds_min = self.nodes.min(dim=0).values + bounds_max = self.nodes.max(dim=0).values + bbox_vals = [ + bounds_min[0].item() + bbox_ratio_vals[0] * (bounds_max[0] - bounds_min[0]).item(), + bounds_min[0].item() + bbox_ratio_vals[1] * (bounds_max[0] - bounds_min[0]).item(), + bounds_min[1].item() + bbox_ratio_vals[2] * (bounds_max[1] - bounds_min[1]).item(), + bounds_min[1].item() + bbox_ratio_vals[3] * (bounds_max[1] - bounds_min[1]).item(), + bounds_min[2].item() + bbox_ratio_vals[4] * (bounds_max[2] - bounds_min[2]).item(), + bounds_min[2].item() + bbox_ratio_vals[5] * (bounds_max[2] - bounds_min[2]).item(), + ] + bbox_desc = "ratio" + else: + logging.warning(" ⚠️ bbox mode did not provide a valid bbox, fallback to top_percent") + mode_used = "top_percent" + + if mode_used == "bbox" and bbox_vals is not None: + x0, x1 = sorted([bbox_vals[0], bbox_vals[1]]) + y0, y1 = sorted([bbox_vals[2], bbox_vals[3]]) + z0, z1 = sorted([bbox_vals[4], bbox_vals[5]]) + seat_mask = ( + (self.nodes[:, 0] >= x0) & (self.nodes[:, 0] <= x1) + & (self.nodes[:, 1] >= y0) & (self.nodes[:, 1] <= y1) + & (self.nodes[:, 2] >= z0) & (self.nodes[:, 2] <= z1) + ) + if seat_mask.sum().item() < 1: + logging.warning(" ⚠️ bbox region matched no nodes, fallback to top_percent") + mode_used = "top_percent" + else: + bbox_desc = f"{bbox_desc}: [{x0:.3f},{x1:.3f}]x[{y0:.3f},{y1:.3f}]x[{z0:.3f},{z1:.3f}]" + + if mode_used == "height_ratio": + y_min = y_coords.min().item() + y_max = y_coords.max().item() + y_range = max(1e-8, y_max - y_min) + if not (0.0 <= min_ratio < max_ratio <= 1.0): + logging.warning( + f" ⚠️ invalid height_ratio: min={min_ratio}, max={max_ratio}, fallback to top_percent" + ) + mode_used = "top_percent" + else: + seat_y_min = y_min + y_range * min_ratio + seat_y_max = y_min + y_range * max_ratio + seat_mask = (y_coords >= seat_y_min) & (y_coords <= seat_y_max) + if seat_mask.sum().item() < 1: + logging.warning(" ⚠️ height_ratio matched no nodes, fallback to top_percent") + mode_used = "top_percent" + + if mode_used == "top_percent": + top_percent = float(top_percent) + top_percent = max(0.0, min(1.0, top_percent)) + if top_percent <= 0.0: + top_percent = 0.05 + num_seat_nodes = max(1, int(num_nodes * top_percent)) + _, top_indices = torch.topk(y_coords, k=num_seat_nodes, largest=True) + seat_mask = torch.zeros(num_nodes, dtype=torch.bool, device=self.device) + seat_mask[top_indices] = True + + return seat_mask, mode_used, bbox_desc + + self.forces = torch.zeros((num_nodes, 3), dtype=torch.float32, device=self.device) + combined_mask = torch.zeros(num_nodes, dtype=torch.bool, device=self.device) + total_force = torch.zeros(3, dtype=torch.float32, device=self.device) + + for idx, entry in enumerate(force_entries): + if not isinstance(entry, dict): + continue + entry_label = entry.get("label") or entry.get("name") or f"{idx+1}" + entry_force = None + if "forces" in entry and isinstance(entry["forces"], list): + try: + entry_force = np.sum(np.array(entry["forces"], dtype=np.float32), axis=0) + except Exception: + entry_force = None + if entry_force is None and "force" in entry: + try: + entry_force = np.array(entry["force"], dtype=np.float32) + except Exception: + entry_force = None + if entry_force is None or entry_force.shape != (3,): + logging.warning(f" ⚠️ invalid force entry[{entry_label}], skip") + continue + + entry_force_tensor = torch.from_numpy(entry_force).float().to(self.device) + total_force += entry_force_tensor + + mode = str(entry.get("force_region_mode", self.config.force_region_mode)).lower() + if entry.get("global_loading") is True: + mode = "global" + + top_percent = entry.get("force_top_percent", self.config.force_top_percent) + min_ratio = entry.get("seat_height_min_ratio", self.config.seat_height_min_ratio) + max_ratio = entry.get("seat_height_max_ratio", self.config.seat_height_max_ratio) + bbox = entry.get("force_bbox", self.config.force_bbox) + bbox_ratio = entry.get("force_bbox_ratio", self.config.force_bbox_ratio) + + seat_nodes_mask, mode_used, bbox_desc = _select_nodes_for_mode( + mode, top_percent, min_ratio, max_ratio, bbox, bbox_ratio + ) + + num_seat_nodes = int(seat_nodes_mask.sum().item()) + if num_seat_nodes < 1: + logging.warning(f" ⚠️ entry[{entry_label}]matched no nodes, skip") + continue + + force_per_node = entry_force_tensor / num_seat_nodes + self.forces[seat_nodes_mask] += force_per_node + combined_mask |= seat_nodes_mask + + seat_y_values = y_coords[seat_nodes_mask] + seat_y_min = seat_y_values.min().item() + seat_y_max = seat_y_values.max().item() + seat_y_mean = seat_y_values.mean().item() + + if initial_setup: + if mode_used == "bbox": + logging.info(f" 🪑 contact surface[{entry_label}]: bbox ({bbox_desc})") + elif mode_used == "height_ratio": + logging.info( + f" 🪑 contact surface[{entry_label}]: height_ratio " + f"[{min_ratio:.2f}, {max_ratio:.2f}]" + ) + elif mode_used == "global": + logging.info(f" 🪑 contact surface[{entry_label}]: global") + else: + logging.info( + f" 🪑 contact surface[{entry_label}]: highest-Y {float(top_percent):.1%} nodes" + ) + logging.info( + f" 🪑 seat-node count[{entry_label}]: {num_seat_nodes}/{num_nodes} " + f"({num_seat_nodes/num_nodes:.1%})" + ) + logging.info( + f" 🪑 Y range[{entry_label}]: [{seat_y_min:.3f}, {seat_y_max:.3f}], " + f"mean: {seat_y_mean:.3f}" + ) + logging.info(f" 💺 force[{entry_label}]: {entry_force}") + logging.info(f" 💺 per node[{entry_label}]: {force_per_node.cpu().numpy()}") + + self.total_force_preset = total_force + actual_total_force = self.forces.sum(dim=0) + force_error = torch.norm(actual_total_force - total_force).item() + force_error_percent = (force_error / (torch.norm(total_force).item() + 1e-10)) * 100 + + if initial_setup: + logging.info( + f" ✅ total-force check: {actual_total_force.cpu().numpy()} " + f"(error: {force_error:.2e}, {force_error_percent:.3f}%)" + ) + if combined_mask.any(): + self._save_force_visualization( + combined_mask, total_force.cpu().numpy() + ) + else: + logging.debug( + f" 🔄 force update: loaded nodes {int(combined_mask.sum().item())}, " + f"total force error {force_error:.2e}" + ) + + self._last_num_seat_nodes = int(combined_mask.sum().item()) + return + + # Contact-region selection supports top_percent / height_ratio / bbox. + mode = str(getattr(self.config, "force_region_mode", "top_percent")).lower() + seat_nodes_mask = torch.zeros(num_nodes, dtype=torch.bool, device=self.device) + mode_used = mode + bbox_desc = None + if mode_used not in ("top_percent", "height_ratio", "bbox"): + logging.warning(f" ⚠️ invalid force_region_mode: {mode_used}, fallback to top_percent") + mode_used = "top_percent" + + if mode_used == "bbox": + bbox = getattr(self.config, "force_bbox", None) + bbox_ratio = getattr(self.config, "force_bbox_ratio", None) + bbox_vals = None + if bbox is not None and len(bbox) == 6: + bbox_vals = [float(v) for v in bbox] + bbox_desc = "abs" + elif bbox_ratio is not None and len(bbox_ratio) == 6: + bbox_ratio_vals = [float(v) for v in bbox_ratio] + bounds_min = self.nodes.min(dim=0).values + bounds_max = self.nodes.max(dim=0).values + bbox_vals = [ + bounds_min[0].item() + bbox_ratio_vals[0] * (bounds_max[0] - bounds_min[0]).item(), + bounds_min[0].item() + bbox_ratio_vals[1] * (bounds_max[0] - bounds_min[0]).item(), + bounds_min[1].item() + bbox_ratio_vals[2] * (bounds_max[1] - bounds_min[1]).item(), + bounds_min[1].item() + bbox_ratio_vals[3] * (bounds_max[1] - bounds_min[1]).item(), + bounds_min[2].item() + bbox_ratio_vals[4] * (bounds_max[2] - bounds_min[2]).item(), + bounds_min[2].item() + bbox_ratio_vals[5] * (bounds_max[2] - bounds_min[2]).item(), + ] + bbox_desc = "ratio" + else: + logging.warning(" ⚠️ bbox mode did not provide a valid bbox, fallback to top_percent") + mode_used = "top_percent" + + if mode_used == "bbox" and bbox_vals is not None: + x0, x1 = sorted([bbox_vals[0], bbox_vals[1]]) + y0, y1 = sorted([bbox_vals[2], bbox_vals[3]]) + z0, z1 = sorted([bbox_vals[4], bbox_vals[5]]) + seat_nodes_mask = ( + (self.nodes[:, 0] >= x0) & (self.nodes[:, 0] <= x1) + & (self.nodes[:, 1] >= y0) & (self.nodes[:, 1] <= y1) + & (self.nodes[:, 2] >= z0) & (self.nodes[:, 2] <= z1) + ) + if seat_nodes_mask.sum().item() < 1: + logging.warning(" ⚠️ bbox region matched no nodes, fallback to top_percent") + mode_used = "top_percent" + else: + bbox_desc = f"{bbox_desc}: [{x0:.3f},{x1:.3f}]x[{y0:.3f},{y1:.3f}]x[{z0:.3f},{z1:.3f}]" + + if mode_used == "height_ratio": + y_min = y_coords.min().item() + y_max = y_coords.max().item() + y_range = max(1e-8, y_max - y_min) + min_ratio = float(self.config.seat_height_min_ratio) + max_ratio = float(self.config.seat_height_max_ratio) + if not (0.0 <= min_ratio < max_ratio <= 1.0): + logging.warning( + f" ⚠️ invalid height_ratio: min={min_ratio}, max={max_ratio}, fallback to top_percent" + ) + mode_used = "top_percent" + else: + seat_y_min = y_min + y_range * min_ratio + seat_y_max = y_min + y_range * max_ratio + seat_nodes_mask = (y_coords >= seat_y_min) & (y_coords <= seat_y_max) + if seat_nodes_mask.sum().item() < 1: + logging.warning(" ⚠️ height_ratio matched no nodes, fallback to top_percent") + mode_used = "top_percent" + + if mode_used == "top_percent": + top_percent = float(getattr(self.config, "force_top_percent", 0.05)) + top_percent = max(0.0, min(1.0, top_percent)) + if top_percent <= 0.0: + top_percent = 0.05 + num_seat_nodes = max(1, int(num_nodes * top_percent)) + _, top_indices = torch.topk(y_coords, k=num_seat_nodes, largest=True) + seat_nodes_mask = torch.zeros(num_nodes, dtype=torch.bool, device=self.device) + seat_nodes_mask[top_indices] = True + + num_seat_nodes = int(seat_nodes_mask.sum().item()) + + # Step 3: gather region statistics. + seat_y_values = y_coords[seat_nodes_mask] + seat_y_min = seat_y_values.min().item() + seat_y_max = seat_y_values.max().item() + seat_y_mean = seat_y_values.mean().item() + + # Step 4: computation the per-node load with uniform distribution. + force_per_node = self.total_force_preset / num_seat_nodes + + # Initialize all node forces to zero. + self.forces = torch.zeros((num_nodes, 3), dtype=torch.float32, device=self.device) + + # Apply force only to the selected seat/contact nodes. + self.forces[seat_nodes_mask] = force_per_node + + # Step 5: verify total-force conservation. + actual_total_force = self.forces.sum(dim=0) + force_error = torch.norm(actual_total_force - self.total_force_preset).item() + force_error_percent = (force_error / torch.norm(self.total_force_preset).item()) * 100 + + # Logging. + if initial_setup: + if mode_used == "bbox": + logging.info(f" 🪑 contact-surface setup: bbox ({bbox_desc})") + elif mode_used == "height_ratio": + logging.info( + f" 🪑 contact-surface setup: height_ratio " + f"[{self.config.seat_height_min_ratio:.2f}, {self.config.seat_height_max_ratio:.2f}]" + ) + else: + logging.info( + f" 🪑 contact-surface setup: highest-Y {float(getattr(self.config, 'force_top_percent', 0.05)):.1%} nodes" + ) + logging.info(f" 🪑 seat-node count: {num_seat_nodes}/{num_nodes} ({num_seat_nodes/num_nodes:.1%})") + logging.info(f" 🪑 Y-coordinate range: [{seat_y_min:.3f}, {seat_y_max:.3f}], mean: {seat_y_mean:.3f}") + logging.info(f" 💺 preset total force: {self.total_force_preset.cpu().numpy()}") + logging.info(f" 💺 force per node: {force_per_node.cpu().numpy()}") + logging.info(f" ✅ total-force check: {actual_total_force.cpu().numpy()} (error: {force_error:.2e}, {force_error_percent:.3f}%)") + + # Estimate the equivalent pressure. + y_range = y_coords.max().item() - y_coords.min().item() + grid_spacing = y_range / self.config.res if y_range > 0 else 0.01 + estimated_area = num_seat_nodes * (grid_spacing ** 2) + if estimated_area > 0 and abs(self.total_force_preset[1].item()) > 0: + pressure_kpa = abs(self.total_force_preset[1].item()) / estimated_area / 1000 + logging.info(f" 📏 equivalent pressure: {pressure_kpa:.1f} kPa (contact area≈{estimated_area:.4f} m²)") + + if pressure_kpa < 5: + logging.warning(f" ⚠️ pressure is too small ({pressure_kpa:.1f} kPa < 5 kPa)") + elif pressure_kpa > 50: + logging.warning(f" ⚠️ pressure is too large ({pressure_kpa:.1f} kPa > 50 kPa)") + + # Save visualization data. + self._save_force_visualization(seat_nodes_mask, self.total_force_preset.cpu().numpy()) + else: + # Shorter logging during optimization. + logging.debug(f" 🔄 force update: seat nodes {num_seat_nodes}, per node {force_per_node.cpu().numpy()}, " + f"total force error {force_error:.2e}") + + # Watch for changes in the number of loaded nodes. + if hasattr(self, '_last_num_seat_nodes') and self._last_num_seat_nodes != num_seat_nodes: + logging.info(f" ⚠️ seat-node count changed: {self._last_num_seat_nodes} → {num_seat_nodes}") + + # Cache the current state for the next comparison. + self._last_num_seat_nodes = num_seat_nodes + + def extract_solid(self, step: int = -1): + """Extract the physical solid by querying the node SDF directly. + + This method rebuilds the FEM mesh from the current latents so topology + changes in the SDF field can be reflected by the simulation mesh. + + Args: + step: Current optimization step, used for logging. + """ + if not WARP_AVAILABLE: + logging.warning("Warpnot installed, unable toperformphysics simulation") + return + + # Re-check physiopt availability at runtime. + try: + from physiopt.utils.phys_utils import generate_hex as _generate_hex + from physiopt.utils.grid_utils import filter_one_component as _filter_one_component + from physiopt.opt.field import occ_kernel as _occ_kernel + generate_hex_func = _generate_hex + filter_one_component_func = _filter_one_component + occ_kernel_func = _occ_kernel + logging.info("✅ physioptmoduleruntime check succeeded") + except ImportError as e: + logging.error(f"physioptmodulenot installed: {e}") + logging.error("please make sure physiopt is installed correctly: cd /mnt/cvlab/scratch/cvlab/home/hantzhan/physiopt && pip install -e .") + return + + res = self.config.res + step_label = f"Step {step}" if step >= 0 else "Initialization" + logging.info(f"{'🔄' if step >= 0 else '🆕'} [{step_label}] generate/update a mesh at resolution {res} hexahedral mesh...") + + # Keep the previous mesh size for comparison. + old_num_nodes = len(self.nodes) if hasattr(self, 'nodes') else 0 + old_num_elements = len(self.elements) if hasattr(self, 'elements') else 0 + + # 1. Generate the full hexahedral grid. + full_nodes, full_elements = generate_hex_func( + res=res, + limits=[(-0.8, 0.8), (-0.8, 0.8), (-0.8, 0.8)], + device=self.device, + return_coords=False + ) + + if full_nodes is None or full_elements is None: + logging.error("failed to generate the hexahedral mesh") + return + + full_nodes = full_nodes.to(self.device).float() + full_elements = full_elements.to(self.device).long() + + logging.info(f"hexahedral mesh generated successfully: {full_nodes.shape[0]}nodes, {full_elements.shape[0]}elements") + + # 2. Query the SDF directly through get_field. + logging.info("query node SDF values...") + sdf = self.get_field(full_nodes) + + # Make sure the SDF is a 1D tensor [N]. + if sdf.dim() > 1: + logging.warning(f"⚠️ SDFYesmulti-dimensional tensor: {sdf.shape}, will be flattened to 1D") + sdf = sdf.squeeze() # remove all size-1 dimensions + if sdf.dim() > 1: + sdf = sdf.reshape(-1) # force-flatten to 1D + + logging.info(f" ✅ SDF query succeeded: range=[{sdf.min():.3f}, {sdf.max():.3f}]") + logging.info(f" nodescount: {full_nodes.shape[0]}, SDF count: {sdf.shape[0]}") + + # Verify that the SDF count matches the node count. + if sdf.shape[0] != full_nodes.shape[0]: + logging.error(f"❌ SDF count({sdf.shape[0]}) vs. node count ({full_nodes.shape[0]})do not match!") + return + + # 3. Convert SDF values to occupancy. + logging.info("convert the SDF into an occupancy field...") + occ = occ_kernel_func(sdf, res, self.config.occ_sdf_beta) + + # 4. Select solid elements using an SDF threshold instead of an + # occupancy threshold. The threshold is intentionally relaxed so thin + # structures such as chair legs are kept. + SDF_FILTER_VALUE = 2.0 / res + nodewise_mask = sdf <= SDF_FILTER_VALUE + + # Diagnostic SDF statistics. + sdf_inside = sdf[nodewise_mask] + sdf_outside = sdf[~nodewise_mask] + logging.info(f" SDF threshold: {SDF_FILTER_VALUE:.4f}") + logging.info(f" interior nodes: {nodewise_mask.sum().item()}/{len(sdf)} ({100*nodewise_mask.sum().item()/len(sdf):.1f}%)") + if len(sdf_inside) > 0: + logging.info(f" inner SDF range: [{sdf_inside.min():.4f}, {sdf_inside.max():.4f}]") + if len(sdf_outside) > 0: + logging.info(f" outside-SDF range: [{sdf_outside.min():.4f}, {sdf_outside.max():.4f}]") + + # Debug the element-index range. + max_elem_idx = full_elements.max().item() + num_nodes = full_nodes.shape[0] + logging.info(f" elementsindex range: [0, {max_elem_idx}], nodescount: {num_nodes}") + + if max_elem_idx >= num_nodes: + logging.error(f"❌ index out of bounds!maximum element index({max_elem_idx}) >= nodescount({num_nodes})") + logging.error(f" this may be a problem with generate_hex") + # Clamp indices to the valid range. + valid_mask = (full_elements >= 0) & (full_elements < num_nodes) + if not valid_mask.all(): + logging.warning(f" found{(~valid_mask).sum().item()} invalid indices; filtering elements") + # Keep only elements whose node indices are all valid. + valid_elements_mask = valid_mask.all(dim=1) + full_elements = full_elements[valid_elements_mask] + logging.info(f" element count after filtering: {full_elements.shape[0]}") + + # Keep an element if any of its nodes passes the threshold. + elementwise_mask = torch.any(nodewise_mask[full_elements], dim=1) + + num_solid_elements = elementwise_mask.sum().item() + logging.info(f"SDF thresholdfiltering: {num_solid_elements}/{len(elementwise_mask)} solid elements") + + if num_solid_elements == 0: + logging.error("No solid elements were found; please check the SDF or adjust the threshold") + return + + # 5. Optionally keep only one connected component. + if self.config.one_cc_only: + element_res = res - 1 + try: + num_before_filter = elementwise_mask.sum().item() + elementwise_mask = filter_one_component_func(elementwise_mask, element_res) + num_filtered_elements = elementwise_mask.sum().item() + num_removed = num_before_filter - num_filtered_elements + logging.info(f"connectivity filtering: {num_filtered_elements} elements kept (removed{num_removed} small components)") + if num_removed > num_filtered_elements * 0.1: + logging.warning(f" ⚠️ removed{num_removed}elements({100*num_removed/num_before_filter:.1f}%), may have filtered out important parts (such as chair legs) ") + logging.warning(f" Suggestion: check the SDF threshold or consider disabling one_cc_only") + except IndexError as e: + logging.warning(f"connectivity filteringfailed: {e}, using the original mask") + else: + logging.info("connectivity filteringdisabled, keep all connected components") + + # 6. Select the active elements and nodes. + selected_elements = full_elements[elementwise_mask] + selected_node_indices, selected_elements = torch.unique( + selected_elements, return_inverse=True + ) + + self.elements = selected_elements + self.nodes = full_nodes[selected_node_indices] + + # 7. Compute occupancy for the selected nodes used in the simulation. + coarse_sdf = sdf[selected_node_indices] + coarse_occ_nodes = occ_kernel_func( + coarse_sdf, self.config.res, self.config.occ_sdf_beta + ) + # Each element occupancy is the mean over its 8 nodes. + self.coarse_occ = coarse_occ_nodes[self.elements].mean(1) + + # Diagnostic statistics for mesh-size changes. + new_num_nodes = len(self.nodes) + new_num_elements = len(self.elements) + + if old_num_nodes > 0: + node_change = new_num_nodes - old_num_nodes + element_change = new_num_elements - old_num_elements + node_change_pct = (node_change / old_num_nodes) * 100 + element_change_pct = (element_change / old_num_elements) * 100 + + logging.info(f"✅ solid extraction completed:") + logging.info(f" nodes: {old_num_nodes} → {new_num_nodes} ({node_change:+d}, {node_change_pct:+.1f}%)") + logging.info(f" elements: {old_num_elements} → {new_num_elements} ({element_change:+d}, {element_change_pct:+.1f}%)") + + if node_change > 0: + logging.info(f" ✅ mesh expanded!added{node_change}nodes (chair legs may have thickened) ") + elif node_change < 0: + logging.warning(f" ⚠️ mesh shrank!removed{-node_change}nodes (chair legs may have become thinner) ") + else: + logging.info(f"✅ solid extraction succeeded: {new_num_nodes}nodes, {new_num_elements}elements") + + # 8. Recomputation the boundary mask because the node count may change. + y_coords = self.nodes[:, 1] + y_min = y_coords.min() + boundary_threshold = y_min + 0.05 # bottom 5% region + self.boundary_mask = y_coords < boundary_threshold + + num_boundary = self.boundary_mask.sum().item() + logging.debug(f" 🔧 boundary conditionsupdated: {num_boundary}fixed nodes (Y < {boundary_threshold:.3f})") + + def get_current_sds_weight(self, step: int) -> float: + """Return the current SDS weight by linear interpolation. + + Args: + step: Current optimization step. + + Returns: + The SDS weight interpolated from sds_weight_start to sds_weight_end. + """ + # Linear interpolation from sds_weight_start to sds_weight_end. + progress = min(1.0, step / max(1, self.config.num_steps - 1)) + current_weight = self.config.sds_weight_start + progress * (self.config.sds_weight_end - self.config.sds_weight_start) + return current_weight + + def flow_matching_with_ictm(self, step: int, guidance_value: float, lambda_guidance: float, lambda_score: float) -> Tuple[torch.Tensor, torch.Tensor]: + """Compute the current target_z0 for one update.""" + if step == 0: + noise_level = float(0) + else: + noise_level = float(self.config.sds_timestep) + noise_level = float(self.config.sds_timestep) + t = 1.0 - noise_level # Hunyuan3D-2.1 uses t=0 for noise and t=1 for data. + epsilon = torch.randn_like(self.latents) + + self.sds_scheduler.config.num_train_timesteps = 100 + if self.sds_scheduler is not None: + # Match the official Flow Matching noise process: + # x_t = (1 - sigma) * x0 + sigma * eps. + sigma_step = 1.0 / float(self.sds_scheduler.config.num_train_timesteps) + total_span = max(0.0, 1.0 - t) + num_steps = int(np.ceil(total_span / sigma_step)) + sigmas = np.linspace(t, 1.0, num_steps + 1, dtype=np.float32) + self.sds_scheduler.set_timesteps(sigmas=sigmas, device=self.device) + t_scheds = self.sds_scheduler.timesteps + t_sched0 = t_scheds[0] + t_model0 = (t_sched0 / self.sds_scheduler.config.num_train_timesteps).to(self.latents.dtype) + if step % max(1, int(self.config.sds_target_z0_update_interval)) == 0: + logging.info( + f" 🎯 target_z0/sigmaalign: noise={noise_level:.4f}, t_start={t:.4f}, " + f"t_sched={t_sched0.item():.2f}, t_model={t_model0.item():.6f}, " + f"steps={num_steps}, sigma_step={sigma_step:.4g}" + ) + else: + t_sched = None + z_t = (1 - t) * epsilon + t * self.latents + t_model = torch.tensor([t], device=self.device, dtype=self.latents.dtype) + + with torch.no_grad(): + # Integrate over multiple small sigma steps from sigma=t to 0. + cond_for_model = self._get_cond_for_guidance(self.config.guidance_scale > 1.0) + t_sched0 = t_scheds[0] + t_sched_batch = t_sched0.reshape(1).expand(self.latents.shape[0]) + # Hunyuan3D convention: t=0 is noise and t=1 is data. + z_t = self.sds_scheduler.scale_noise(epsilon, t_sched_batch, noise=self.latents) + z_curr = z_t + velocity = None + + logging.info(f"Starting Guided projection with {len(t_scheds) - 1} steps") + for i in range(len(t_scheds) - 1): + + t_sched = t_scheds[i] + t_model = (t_sched / self.sds_scheduler.config.num_train_timesteps).to(self.latents.dtype) + z_t_fp16 = z_curr.to(torch.float16) + t_tensor = t_model.to(device=self.device, dtype=z_t_fp16.dtype) + + if self.config.guidance_scale > 1.0: + latent_model_input = torch.cat([z_t_fp16, z_t_fp16]) + timestep_input = t_tensor.expand(latent_model_input.shape[0]) + + velocity_pred_fp16 = self.flow_model( + latent_model_input, + timestep_input, + cond_for_model, + guidance=None, + ) + + velocity_cond_fp16, velocity_uncond_fp16 = velocity_pred_fp16.chunk(2) + velocity_fp16 = velocity_uncond_fp16 + self.config.guidance_scale * (velocity_cond_fp16 - velocity_uncond_fp16) + + if step % 10 == 0 and i == 0: + logging.debug( + f" CFG (SDS): guidance_scale={self.config.guidance_scale:.1f}, " + f"||v_cond||={torch.norm(velocity_cond_fp16).item():.3e}, " + f"||v_uncond||={torch.norm(velocity_uncond_fp16).item():.3e}" + ) + else: + velocity_fp16 = self.flow_model( + z_t_fp16, + t_tensor.expand(z_t_fp16.shape[0]), + cond_for_model, + guidance=None, + ) + + velocity = velocity_fp16.to(torch.float32) + z_curr = self.sds_scheduler.step(velocity, t_sched, z_curr).prev_sample + + # ============= Step 2: update occupancy on the fixed topology ====== + sdf = self.get_field(self.nodes, latents=z_curr) + occ = occ_kernel(sdf, self.config.res, self.config.occ_sdf_beta) + self.coarse_occ = occ[self.elements].mean(1) + + # =============== Step 3: physics simulation (with torch.no_grad) ============ + with torch.no_grad(): + if self.config.alpha_min > 0.0: + self.coarse_occ = torch.clamp(self.coarse_occ, self.config.alpha_min) + + from torchfem.materials import IsotropicElasticity3D + from physiopt.opt.solid_grid import SolidGrid + + vectorized_material = IsotropicElasticity3D( + E=self.config.youngs_modulus, + nu=self.config.poissons_ratio, + rho=self.config.density, + ).vectorize(self.elements.shape[0]) + + vectorized_material.C *= ( + self.coarse_occ[:, None, None] ** self.config.p_exponent + ) + + solid = SolidGrid(self.nodes, self.elements, vectorized_material) + solid.constraints[self.boundary_mask, :] = True + solid.forces = self.forces + + # 3.2 FEM solve. + logging.info(f"Step {i}: FEM solve...") + u, f_int, f_ext, sigma, _, _ = solid.solve(max_iter=1) + u_mean = torch.abs(u).mean().item() + logging.info(f" |u|_mean={u_mean}") + self._log_physical_quantities(u, sigma) + + # ==================== Step 4: sensitivity computation ==================== + k0 = solid.k0() + u_j = u[self.elements].reshape(solid.n_elem, -1) + w_k_scaled = torch.einsum("...i, ...ij, ...j", u_j, k0, u_j) + occ_power = torch.clamp( + self.coarse_occ ** self.config.p_exponent, + min=1e-6, # Avoid division by zero. + max=1.0 # Avoid overflow. + ) + if torch.any(occ_power < 1e-6): + n_small = (occ_power < 1e-6).sum().item() + logging.warning(f" ⚠️ {n_small} elements have extremely small occ^p and were clamped to 1e-6") + w_k_base = w_k_scaled / occ_power + if torch.isnan(w_k_base).any() or torch.isinf(w_k_base).any(): + n_nan = torch.isnan(w_k_base).sum().item() + n_inf = torch.isinf(w_k_base).sum().item() + logging.error(f" ❌ w_k_baseabnormal: {n_nan} NaN, {n_inf} Inf") + logging.error(f" fall back to SIMP weightingw_k") + w_k_base = w_k_scaled + compliance_mean = w_k_base.mean().item() + w_k = w_k_base # Downstream sensitivity uses the recovered energy. + logging.info(f" Compliance (true) ={compliance_mean:.2e}") + + diff = compliance_mean - guidance_value + logging.info(f" Error ={diff:.2e}") + + self.sensitivity_density = ( + -self.config.p_exponent + * self.coarse_occ ** (self.config.p_exponent - 1) + * w_k + ) + + z_curr = z_curr.detach() + + raw_input = diff * self.sensitivity_density + max_abs_val = raw_input.abs().max() + if max_abs_val > 100.0: + safe_input = (raw_input / max_abs_val) * 100.0 + logging.info(f" 🗜️ Scaling Anti-NaN : max {max_abs_val:.2e} to 100.0") + else: + safe_input = raw_input + + # ==================== Step 5: backward pass via VJP ==================== + with torch.enable_grad(): + # self.backward_step(diff * self.sensitivity_density, latents=z_curr) + z_curr = self.backward_step(safe_input, latents=z_curr) + + # ==================== Step 6: optimization step ==================== + with torch.no_grad(): + z_curr = z_curr - lambda_guidance * z_curr.grad + + # ==================== Step 7: Score step ==================== + with torch.no_grad(): + grad_log_p = (1.0 / (1.0 - t_tensor)) * (t_tensor * velocity - z_curr) + z_curr = z_curr - lambda_score * grad_log_p + + + # ==================== Step 8: Trace Loss Step (AMP / Autocast) ==================== + import gc + torch.cuda.empty_cache() + gc.collect() + + self.flow_model.requires_grad_(False) + z_curr = z_curr.detach().float().requires_grad_(True) + + epsilon = 1e-3 + n_samples = 1 + factor = sigma_step / (epsilon * n_samples) + loss_scale = 1024.0 + + with torch.enable_grad(): + for _ in range(n_samples): + z = torch.randint(low=0, high=2, size=z_curr.shape, device=z_curr.device).float() * 2 - 1 + + t_input = t_tensor.expand(z_curr.shape[0]).float() + + with torch.autocast(device_type='cuda', dtype=torch.float16): + v_base = self.flow_model(z_curr, t_input, cond_for_model, guidance=None) + + loss_base = -torch.sum(v_base.float() * z) * factor + (loss_base / loss_scale).backward() + + del v_base, loss_base + torch.cuda.empty_cache() + + x_perturbed = z_curr + epsilon * z + + with torch.autocast(device_type='cuda', dtype=torch.float16): + v_perturbed = self.flow_model(x_perturbed, t_input, cond_for_model, guidance=None) + + loss_perturbed = torch.sum(v_perturbed.float() * z) * factor + (loss_perturbed / loss_scale).backward() + + del v_perturbed, loss_perturbed, x_perturbed + torch.cuda.empty_cache() + + with torch.no_grad(): + raw_grad = z_curr.grad * loss_scale + + if torch.isnan(raw_grad).any() or torch.isinf(raw_grad).any(): + logging.warning(" ⚠️ NaNs détectés (Malgré FP32 grad) !") + raw_grad = torch.nan_to_num(raw_grad, nan=0.0, posinf=100.0, neginf=-100.0) + + max_abs_val = raw_grad.abs().max() + if max_abs_val > 100.0: + safe_grad = (raw_grad / max_abs_val) * 100.0 + logging.info(f" 🗜️ Clipping Trace Grad : max {max_abs_val:.2e} to 100.0") + else: + safe_grad = raw_grad + + z_curr = z_curr - lambda_score * safe_grad + + trace_grad_norm = safe_grad.norm().item() + logging.info(f" 📉 Trace Grad Norm Final : {trace_grad_norm:.2e}") + + + return z_curr, compliance_mean, u_mean, diff + + + def training_step( + self, + step: int, + lagrange: float, + rho: float, + use_sds: bool = True, + save_step: Optional[int] = None, + ) -> Tuple[float, float, float]: + """Physics optimization. + + This follows the computation_phys_loss_grad flow from viewer_base.py: + 1. optimizer.zero_grad() + 2. with torch.no_grad(): prepare_solid() + solve() + 3. Compute sensitivities with the reference-style formula + 4. backward_step() via VJP + 5. Apply ALM weighting (lambda + rho[g]_+) + 6. optimizer.step() + + Reference: + physiopt/src/physiopt/vis/viewer_base.py Line 1297-1430 + """ + save_step_id = step if save_step is None else int(save_step) + + # ==================== Step 1: zero gradients ==================== + self.optimizer.zero_grad() + + # ==================== Step 2: update occupancy on the fixed topology ==================== + if step > 0: + logging.info(f"🔄 [Step {step}] update occupancy (mesh topology fixed) ...") + # Keep the previous occupancy for diagnostics. + old_occ = self.coarse_occ.clone() + + # Re-query the SDF and occupancy on the fixed mesh. + sdf = self.get_field(self.nodes) + from physiopt.opt.field import occ_kernel + occ = occ_kernel(sdf, self.config.res, self.config.occ_sdf_beta) + self.coarse_occ = occ[self.elements].mean(1) + + # Diagnose occupancy changes. + occ_change = self.coarse_occ - old_occ + occ_mean_change = occ_change.mean().item() + occ_increase_ratio = (occ_change > 0).float().mean().item() + + logging.info(f" occupancy range: [{self.coarse_occ.min():.3f}, {self.coarse_occ.max():.3f}]") + logging.info(f" occupancy change: mean={occ_mean_change:+.3e}, increase ratio={occ_increase_ratio:.1%}") + + # ==================== Step 3: physics simulation (with torch.no_grad) ==================== + # Aligned with the reference flow around Line 1317-1356. + with torch.no_grad(): + # 3.1 prepare_solid: apply SIMP scaling and build SolidGrid. + if self.config.alpha_min > 0.0: + self.coarse_occ = torch.clamp(self.coarse_occ, self.config.alpha_min) + + # Material SIMP scaling. + from torchfem.materials import IsotropicElasticity3D + from physiopt.opt.solid_grid import SolidGrid + + vectorized_material = IsotropicElasticity3D( + E=self.config.youngs_modulus, + nu=self.config.poissons_ratio, + rho=self.config.density, + ).vectorize(self.elements.shape[0]) + + vectorized_material.C *= ( + self.coarse_occ[:, None, None] ** self.config.p_exponent + ) + + # Create the SolidGrid solver state. + solid = SolidGrid(self.nodes, self.elements, vectorized_material) + solid.constraints[self.boundary_mask, :] = True + solid.forces = self.forces + + # 3.2 FEM solve. + logging.info(f"Step {step}: FEM solve...") + u, f_int, f_ext, sigma, _, _ = solid.solve(max_iter=1) + u_mean = torch.abs(u).mean().item() + logging.info(f" |u|_mean={u_mean}") + self._log_physical_quantities(u, sigma) + + # Save the deformed mesh every N steps. + # if self.config.deformed_mesh_interval > 0 and save_step_id % self.config.deformed_mesh_interval == 0: + # try: + # self.save_deformed_mesh(save_step_id, u) + # except Exception as e: + # logging.warning(f" ⚠️ error while saving the deformed mesh: {e}") + + # ==================== Step 4: sensitivity computation ==================== + # Strictly aligned with the reference flow around Line 1368-1399. + + # 4.1 Compute strain energy. We recover the unweighted energy by + # dividing out occ^p and keep strong numerical guards. + k0 = solid.k0() # occ^p * K_base after stiffness scaling. + u_j = u[self.elements].reshape(solid.n_elem, -1) + w_k_scaled = torch.einsum("...i, ...ij, ...j", u_j, k0, u_j) + + # Remove occ^p scaling to recover the base energy. + occ_power = torch.clamp( + self.coarse_occ ** self.config.p_exponent, + min=1e-6, # Avoid division by zero. + max=1.0 # Avoid overflow. + ) + + # Check again before division. + if torch.any(occ_power < 1e-6): + n_small = (occ_power < 1e-6).sum().item() + logging.warning(f" ⚠️ {n_small} elements have extremely small occ^p and were clamped to 1e-6") + + w_k_base = w_k_scaled / occ_power + + # Fall back if the recovered energy becomes invalid. + if torch.isnan(w_k_base).any() or torch.isinf(w_k_base).any(): + n_nan = torch.isnan(w_k_base).sum().item() + n_inf = torch.isinf(w_k_base).sum().item() + logging.error(f" ❌ w_k_baseabnormal: {n_nan} NaN, {n_inf} Inf") + logging.error(f" fall back to SIMP weightingw_k") + w_k_base = w_k_scaled + + # Use the recovered energy downstream. + compliance_mean = w_k_base.mean().item() + w_k = w_k_base # Downstream sensitivity uses the recovered energy. + + # Diagnostics. + logging.info(f" Compliance (true) ={compliance_mean:.2e}") + logging.info(f" w_k_base: max={w_k.max():.2e}, stress concentration={w_k.max()/(w_k.mean() + 1e-10):.1f}x") + + # ALM normalized constraint: g = D / D_thr - 1. + compliance_threshold = self.config.compliance_threshold if self.config.compliance_threshold is not None else 1.0 + g_raw = compliance_mean / (compliance_threshold + 1e-8) - 1.0 + g_pos = max(0.0, g_raw) + logging.info(f" constraint normalization: g={g_raw:+.3e}, [g]+={g_pos:.3e}, D_thr={compliance_threshold:.2e}") + + # Dynamic clip limit used by the ALM scaling guard. + base_max_grad = 1000.0 + lagrange_bonus = min((lagrange + rho * g_pos) * 10.0, 1000.0) + max_grad_norm = base_max_grad + lagrange_bonus + + # 4.3 Sensitivity formula aligned with the reference code: + # sensitivity = -p * occ^(p-1) * w_k + self.sensitivity_density = ( + -self.config.p_exponent + * self.coarse_occ ** (self.config.p_exponent - 1) + * w_k + ) + + # 4.4 Volume regularization is intentionally disabled here so the pure + # physics signal can be validated first. + if False and self.config.volume_term > 0.0: # Temporarily forced off. + # Initialize the reference volume on first use. + if not hasattr(self, 'init_volume'): + self.init_volume = self.coarse_occ.clone() + logging.info(f" record initial volume: sum={self.init_volume.sum().item():.2f}") + + # Volume sensitivity term. + sensitivity_volume = ( + self.config.volume_term + * (1.0 / self.config.res) ** 3 + * torch.ones_like(self.sensitivity_density) + ) + + # Choose the sign from the current volume change. + volume_sign = 1.0 if self.coarse_occ.sum() >= self.init_volume.sum() else -1.0 + sensitivity_volume *= volume_sign + + self.sensitivity_density += sensitivity_volume + + volume_ratio = self.coarse_occ.sum() / self.init_volume.sum() + logging.info(f" volume constraint: ratio={volume_ratio.item():.3f}, " + f"{'penalize' if volume_sign > 0 else 'encourage'}") + else: + logging.info(f" volume constraint: disabled (physicsoptimizationdominates) ") + + # Sensitivity diagnostics. + sens_norm = torch.norm(self.sensitivity_density).item() + sens_min = self.sensitivity_density.min().item() + sens_max = self.sensitivity_density.max().item() + logging.info(f" sensitivity: norm={sens_norm:.2e}, range=[{sens_min:.2e}, {sens_max:.2e}]") + + # ==================== Step 5: backward pass via VJP ==================== + self.backward_step(self.sensitivity_density) + + # ==================== Step 6: apply ALM weighting (lambda + rho[g]+) ==================== + if self.latents.grad is not None: + phys_grad_norm = torch.norm(self.latents.grad).item() + phys_grad_unscaled = self.latents.grad.clone() # Unscaled physics gradient for SDS comparisons. + + if g_pos > 0.0: + alm_scale_raw = (lagrange + rho * g_pos) / (compliance_threshold + 1e-8) + alm_scale = alm_scale_raw + guard_ratio = min(max(self.config.alm_scale_guard_ratio, 0.0), 1.0) + if phys_grad_norm > 0.0 and max_grad_norm > 0.0 and guard_ratio > 0.0: + alm_scale_guard = (max_grad_norm * guard_ratio) / (phys_grad_norm + 1e-8) + if alm_scale > alm_scale_guard: + logging.info( + f" 🔧 ALMscaling limit: raw={alm_scale_raw:.3e} -> {alm_scale_guard:.3e} " + f"(guard={guard_ratio:.2f}, max_grad={max_grad_norm:.1f})" + ) + alm_scale = alm_scale_guard + self.latents.grad *= alm_scale + else: + alm_scale = 0.0 + self.latents.grad.zero_() + + scaled_grad_norm = torch.norm(self.latents.grad).item() + logging.info( + f" physics gradient(ALM): {phys_grad_norm:.2e} → {scaled_grad_norm:.2e} " + f"(×scale={alm_scale:.3e}, λ={lagrange:.2f}, ρ={rho:.2f})" + ) + else: + phys_grad_unscaled = None + alm_scale = 0.0 + + # ==================== Step 7: shape loss toward target_z0 ==================== + + # 7.1 Compute the denoised target_z0. + import math + if use_sds: + target_z0, _, _ = self._get_target_z0(step) + else: + target_z0 = self.latents.detach() + + # Optionally validate and save a target_z0 mesh every 10 steps. + if use_sds: + self._maybe_save_target_z0_mesh(target_z0, save_step_id) + + # Shape loss is a simple MSE pulling latents toward target_z0. + shape_loss = torch.nn.functional.mse_loss(self.latents, target_z0.detach()) + + # 7.2 Decide whether shape loss is active this step. + current_sds_weight = self.get_current_sds_weight(step) if use_sds else 0.0 + use_sds_this_step = current_sds_weight > 0.0 + + if not use_sds_this_step: + logging.info(f" 🚫 Shape Loss disabled (physicsoptimizationmode) ") + weighted_sds = 0.0 + shape_grad_norm = 0.0 + else: + # Weighted shape loss. + weighted_shape_loss = current_sds_weight * shape_loss + + # Validate shape loss before backpropagating it. + if torch.isnan(shape_loss) or torch.isinf(shape_loss): + logging.error(f" ❌ Shape Loss contains NaN or Inf; skipping the shape constraint") + weighted_sds = 0.0 + shape_grad_norm = 0.0 + else: + # Backpropagate the shape loss into latents.grad. + weighted_shape_loss.backward() + + # Measure the shape-gradient norm for logging. + if self.latents.grad is not None and phys_grad_unscaled is not None: + # Isolate the shape part from the combined gradient. + shape_gradient = self.latents.grad - phys_grad_unscaled * alm_scale + shape_grad_norm = torch.norm(shape_gradient).item() + phys_grad_norm_current = torch.norm(phys_grad_unscaled * alm_scale).item() + shape_phys_ratio = shape_grad_norm / (phys_grad_norm_current + 1e-10) + + if shape_phys_ratio > 100.0: + logging.error(f" ❌ Shape gradient is too large (Shape/physics={shape_phys_ratio:.1f}x)!") + logging.error(f" consider lowering sds_weight_end: {self.config.sds_weight_end} → {self.config.sds_weight_end/100:.4f}") + elif shape_phys_ratio > 10.0: + logging.warning(f" ⚠️ Shape gradient is relatively large (Shape/physics={shape_phys_ratio:.1f}x)") + + # Compare the directions of physics and shape gradients. + cos_angle = (phys_grad_unscaled * shape_gradient).sum() / ( + torch.norm(phys_grad_unscaled) * torch.norm(shape_gradient) + 1e-10 + ) + angle_deg = torch.acos(torch.clamp(cos_angle, -1, 1)) * 180 / math.pi + direction = "same direction✅" if angle_deg < 90 else "opposite direction⚠️" + + logging.info(f" Shapegradient: norm={shape_grad_norm:.4e}, weight={current_sds_weight:.6f}") + logging.info(f" gradient direction: physics vs Shape = {angle_deg:.1f}° ({direction})") + elif self.latents.grad is not None: + shape_grad_norm = torch.norm(self.latents.grad).item() + logging.info(f" Shapegradient: norm={shape_grad_norm:.4e} (no physics gradient)") + else: + shape_grad_norm = 0.0 + + weighted_sds = weighted_shape_loss.item() + + # ==================== Step 8: combine losses and clip if needed ==================== + compliance_loss_item = compliance_mean + alm_penalty = lagrange * g_pos + 0.5 * rho * (g_pos ** 2) + total_loss = alm_penalty + weighted_sds + + # Log the combined loss terms. + if use_sds_this_step: + logging.info( + f" 📊 weighted loss: Compliance={compliance_loss_item:.4e}, g={g_raw:+.3e}, " + f"ALM={alm_penalty:.4e} (λ={lagrange:.2f}, ρ={rho:.2f}), " + f"Shape={weighted_sds:.4e} (×w={current_sds_weight:.6f}), Total={total_loss:.4e}" + ) + else: + logging.info( + f" 📊 weighted loss: Compliance={compliance_loss_item:.4e}, g={g_raw:+.3e}, " + f"ALM={alm_penalty:.4e} (λ={lagrange:.2f}, ρ={rho:.2f}), " + f"Shape=0.00e+00 (disabled), Total={total_loss:.4e}" + ) + + # Log gradient composition details. + if self.latents.grad is not None: + grad_norm = torch.norm(self.latents.grad).item() + + # Report each gradient contribution. + if phys_grad_unscaled is not None: + weighted_phys_grad_norm = torch.norm(phys_grad_unscaled * alm_scale).item() + logging.info(f" 🔍 gradient composition: Weighted Compliance Grad={weighted_phys_grad_norm:.4e} (ALM scale={alm_scale:.3e})") + + if use_sds_this_step and shape_grad_norm > 0: + logging.info(f" Scaled Shape Grad={shape_grad_norm:.4e} (Shape×w={current_sds_weight:.6f})") + if phys_grad_unscaled is not None: + grad_ratio = shape_grad_norm / (weighted_phys_grad_norm + 1e-10) + logging.info(f" ratio: Shape/Compliance = {grad_ratio:.4f} ({grad_ratio*100:.2f}%)") + + logging.info(f" Total Grad={grad_norm:.4e}") + + # Optional gradient clipping. + if self.latents.grad is not None: + grad_norm = torch.norm(self.latents.grad).item() + + if torch.isnan(self.latents.grad).any() or torch.isinf(self.latents.grad).any(): + logging.error(f"❌ the final gradient contains NaN or Inf!skip this steps") + return (compliance_loss_item, u_mean, shape_loss.item(), total_loss) + + if self.config.grad_clip_enabled: + if grad_norm > max_grad_norm: + clip_factor = max_grad_norm / grad_norm + self.latents.grad = self.latents.grad * clip_factor + logging.info(f" ✂️ gradient clipping: {grad_norm:.4e} -> {max_grad_norm:.1f} (×{clip_factor:.3f})") + else: + logging.info(f" ✅ gradient not clipped: {grad_norm:.4e} (max={max_grad_norm:.1f})") + + # ==================== Step 9: optimizer step ==================== + + # Save the previous latents for diagnostics. + old_latents = self.latents.data.clone() + + self.optimizer.step() + + # Diagnose latent changes after the optimizer step. + with torch.no_grad(): + latents_change = torch.norm(self.latents.data - old_latents).item() + latents_norm = torch.norm(old_latents).item() + latents_change_percent = (latents_change / (latents_norm + 1e-10)) * 100 + max_latents_change = torch.abs(self.latents.data - old_latents).max().item() + + logging.info(f" 🔄 Latentschange: L2={latents_change:.4e} ({latents_change_percent:.3f}%), max={max_latents_change:.4e}") + + if latents_change < 1e-6: + logging.warning(f" ⚠️ latents almost did not change!the learning rate may be too small or the gradient may be too weak") + + # Return the scalar loss values. + return (compliance_loss_item, u_mean, shape_loss.item(), total_loss) + + + def save_mesh(self, step: int, output_dir: str = "results/hunyuan_meshes", high_quality: bool = False, suffix="step", latents=None): + """Save frontlatentsmesh + + Args: + step: front steps + output_dir: outputdirectory + high_quality: YesNouse (Resolution) , Trueuse256resolution + """ + os.makedirs(output_dir, exist_ok=True) + + try: + # finalSave use256resolution, Stepuse128resolution + octree_res = 256 if high_quality else 128 + if latents is None: + mesh = self.latents_to_mesh(self.latents, octree_res=octree_res) + else: + mesh = self.latents_to_mesh(latents, octree_res=octree_res) + + if mesh is None: + logging.warning(f" ⚠️ warning: Step {step} - Marching cubesno surface found, skipSave ") + return + + # finalSave filterfloating + if high_quality: + mesh = self._filter_floating_components(mesh) + + mesh_path = os.path.join(output_dir, f"{suffix}_{step:04d}.obj") + mesh.export(mesh_path) + quality_label = "256resolution" if high_quality else "128resolution" + logging.info(f" 💾 Save mesh ({quality_label}): {mesh_path}") + except Exception as e: + logging.warning(f" ⚠️ warning: Step {step} - Save meshfailed: {e}") + + + def save_deformed_mesh(self, step: int, displacement: torch.Tensor, output_dir: str = None, suffix="step"): + """Save FEM solvebackdeformed mesh + + Args: + step: front steps + displacement: FEM solve [num_nodes, 3] + output_dir: outputdirectory, useconfig.out_folder/deformed_meshes + """ + if output_dir is None: + if hasattr(self.config, 'out_folder'): + output_dir = os.path.join(self.config.out_folder, "deformed_meshes") + else: + output_dir = "results/deformed_meshes" + + os.makedirs(output_dir, exist_ok=True) + + try: + # originalnodespositionandbackposition + original_nodes = self.nodes.detach().cpu().numpy() # [num_nodes, 3] + displacement_np = displacement.detach().cpu().numpy() # [num_nodes, 3] + deformed_nodes = original_nodes + displacement_np + + # elements + elements_np = self.elements.detach().cpu().numpy() # [num_elements, 8] + + # # Save VTK format (ParaView, contains) + # vtk_path = os.path.join(output_dir, f"deformed_step_{step:04d}.vtk") + # self._save_hex_mesh_vtk(deformed_nodes, elements_np, displacement_np, vtk_path, step) + + # Save OBJ/PLY (usedecodemesh, ) + decoded_mesh = self.latents_to_mesh(self.latents, octree_res=128) + if decoded_mesh is not None: + disp_vertices = self._sample_displacement_to_vertices( + decoded_mesh.vertices, original_nodes, displacement_np + ) + deformed_vertices = decoded_mesh.vertices + disp_vertices + colors = self._make_displacement_colors(disp_vertices) + + deformed_mesh = trimesh.Trimesh( + vertices=deformed_vertices, + faces=decoded_mesh.faces, + process=False, + ) + deformed_mesh.visual.vertex_colors = colors + + obj_path = os.path.join(output_dir, f"deformed_{suffix}_{step:04d}.obj") + # ply_path = os.path.join(output_dir, f"deformed_step_{step:04d}.ply") + deformed_mesh.export(obj_path) + # deformed_mesh.export(ply_path) + else: + # fallback: usemesh + obj_path = os.path.join(output_dir, f"deformed_{suffix}_{step:04d}.obj") + # ply_path = os.path.join(output_dir, f"deformed_step_{step:04d}.ply") + self._save_surface_mesh_obj(deformed_nodes, elements_np, obj_path) + # self._save_surface_mesh_ply(deformed_nodes, elements_np, displacement_np, ply_path) + + # displacement statistics + disp_mean = np.abs(displacement_np).mean() + disp_max = np.abs(displacement_np).max() + logging.info(f" 💾 saved deformed mesh : OBJ={obj_path.split('/')[-1]}") + logging.debug(f" : mean={disp_mean:.4e}, max={disp_max:.4e}") + + except Exception as e: + logging.warning(f" ⚠️ Save deformed meshfailed (Step {step}): {e}") + + + def save_final_deformed_mesh(self, step_id: int, suffix="step", latents=None): + """force at the final step toSave deformed mesh (re-solveFEM) """ + if not hasattr(self, 'nodes') or not hasattr(self, 'elements'): + logging.warning(" ⚠️ unable to save the finaldeformed mesh: missingnodes/elements") + return + if not hasattr(self, 'forces') or not hasattr(self, 'boundary_mask'): + logging.warning(" ⚠️ unable to save the finaldeformed mesh: missingforces/boundary_mask") + return + + try: + from torchfem.materials import IsotropicElasticity3D + from physiopt.opt.solid_grid import SolidGrid + from physiopt.opt.field import occ_kernel + + with torch.no_grad(): + # update occupancyalignfrontlatents + sdf = self.get_field(self.nodes, latents=latents) + occ = occ_kernel(sdf, self.config.res, self.config.occ_sdf_beta) + self.coarse_occ = occ[self.elements].mean(1) + + if self.config.alpha_min > 0.0: + self.coarse_occ = torch.clamp(self.coarse_occ, self.config.alpha_min) + + vectorized_material = IsotropicElasticity3D( + E=self.config.youngs_modulus, + nu=self.config.poissons_ratio, + rho=self.config.density, + ).vectorize(self.elements.shape[0]) + + vectorized_material.C *= ( + self.coarse_occ[:, None, None] ** self.config.p_exponent + ) + + solid = SolidGrid(self.nodes, self.elements, vectorized_material) + solid.constraints[self.boundary_mask, :] = True + solid.forces = self.forces + + logging.info(" 🧱 final deformed mesh: re-solve the FEM system to save ") + u, _, _, _, _, _ = solid.solve(max_iter=1) + self.save_deformed_mesh(step_id, u, suffix=suffix) + except Exception as e: + logging.warning(f" ⚠️ final deformed meshSave failed: {type(e).__name__}: {str(e)[:100]}") + + + def _save_surface_mesh_obj(self, nodes: np.ndarray, elements: np.ndarray, filename: str): + """Extract the surface from a hexahedral mesh and save it as OBJ.""" + # The six faces of a hexahedron. + hex_faces = [ + [0, 1, 2, 3], [4, 5, 6, 7], # Bottom, top. + [0, 1, 5, 4], [2, 3, 7, 6], # Front, back. + [0, 3, 7, 4], [1, 2, 6, 5], # Left, right. + ] + + # Collect faces that appear only once, i.e. surface faces. + face_count = {} + for elem in elements: + for face_indices in hex_faces: + face_nodes = tuple(sorted([elem[i] for i in face_indices])) + if face_nodes in face_count: + face_count[face_nodes] += 1 + else: + face_count[face_nodes] = 1 + + # Keep only surface faces. + surface_faces = [face for face, count in face_count.items() if count == 1] + + # Save OBJ. + with open(filename, 'w') as f: + f.write("# Deformed mesh surface\n") + for node in nodes: + f.write(f"v {node[0]:.6f} {node[1]:.6f} {node[2]:.6f}\n") + for face in surface_faces: + # OBJ indices are 1-based. + f.write(f"f {face[0]+1} {face[1]+1} {face[2]+1} {face[3]+1}\n") + + + def _save_force_visualization(self, seat_nodes_mask: torch.Tensor, total_force: np.ndarray): + """Save voxel-level load data for visualization and validation. + + This exports: + 1. NumPy (.npz) with full node/load data + 2. OBJ point clouds for quick inspection + 3. Optional VTK data for ParaView + + Args: + seat_nodes_mask: Mask of seat/contact nodes [num_nodes]. + total_force: Total force vector [3]. + """ + if not hasattr(self.config, 'out_folder'): + logging.warning(" out_folder is not set, skipSave loaded voxel") + return + + # Create the force_visualization subdirectory. + vis_dir = os.path.join(self.config.out_folder, "force_visualization") + os.makedirs(vis_dir, exist_ok=True) + + # ==================== 1. Save NumPy data (most complete format) ==================== + all_nodes_cpu = self.nodes.cpu().numpy() + all_forces_cpu = self.forces.cpu().numpy() + seat_mask_cpu = seat_nodes_mask.cpu().numpy() + + # Extract loaded nodes. + seat_nodes = all_nodes_cpu[seat_mask_cpu] + seat_forces = all_forces_cpu[seat_mask_cpu] + + npz_path = os.path.join(vis_dir, "force_nodes.npz") + np.savez( + npz_path, + # All node data. + all_nodes=all_nodes_cpu, + all_forces=all_forces_cpu, + # Loaded-node data. + seat_nodes=seat_nodes, + seat_forces=seat_forces, + seat_mask=seat_mask_cpu, + # Boundary-node data. + boundary_mask=self.boundary_mask.cpu().numpy() if hasattr(self, 'boundary_mask') else None, + # Metadata. + total_force=total_force, + num_seat_nodes=len(seat_nodes), + num_all_nodes=len(all_nodes_cpu), + ) + logging.info(f" 💾 Save load data (NumPy format) : {npz_path}") + + # ==================== 2. Save OBJ point clouds ==================== + # 2a. Loaded nodes (red point cloud). + seat_obj_path = os.path.join(vis_dir, "seat_nodes.obj") + with open(seat_obj_path, 'w') as f: + f.write("# Seat nodes (loaded area)\n") + f.write(f"# Total: {len(seat_nodes)} nodes\n") + f.write(f"# Force per node: {seat_forces[0] if len(seat_forces) > 0 else [0,0,0]}\n") + for node in seat_nodes: + f.write(f"v {node[0]:.6f} {node[1]:.6f} {node[2]:.6f}\n") + logging.info(f" 💾 Save seat nodes (OBJpoint cloud) : {seat_obj_path}") + + # 2b. Boundary nodes (blue point cloud). + if hasattr(self, 'boundary_mask'): + boundary_nodes = all_nodes_cpu[self.boundary_mask.cpu().numpy()] + boundary_obj_path = os.path.join(vis_dir, "boundary_nodes.obj") + with open(boundary_obj_path, 'w') as f: + f.write("# Boundary nodes (fixed area)\n") + f.write(f"# Total: {len(boundary_nodes)} nodes\n") + for node in boundary_nodes: + f.write(f"v {node[0]:.6f} {node[1]:.6f} {node[2]:.6f}\n") + logging.info(f" 💾 Save boundary nodes (OBJpoint cloud) : {boundary_obj_path}") + + # 2c. All nodes (gray point cloud) for comparison. + all_obj_path = os.path.join(vis_dir, "all_nodes.obj") + with open(all_obj_path, 'w') as f: + f.write("# All nodes\n") + f.write(f"# Total: {len(all_nodes_cpu)} nodes\n") + for node in all_nodes_cpu: + f.write(f"v {node[0]:.6f} {node[1]:.6f} {node[2]:.6f}\n") + logging.info(f" 💾 Save all nodes (OBJpoint cloud) : {all_obj_path}") + + # ==================== 3. Save VTK data for ParaView ==================== + try: + vtk_path = os.path.join(vis_dir, "force_field.vtk") + with open(vtk_path, 'w') as f: + # VTK Header + f.write("# vtk DataFile Version 3.0\n") + f.write("Force field visualization\n") + f.write("ASCII\n") + f.write("DATASET UNSTRUCTURED_GRID\n") + + # Points + f.write(f"POINTS {len(all_nodes_cpu)} float\n") + for node in all_nodes_cpu: + f.write(f"{node[0]:.6f} {node[1]:.6f} {node[2]:.6f}\n") + + # Cells (vertices) + f.write(f"\nCELLS {len(all_nodes_cpu)} {len(all_nodes_cpu)*2}\n") + for i in range(len(all_nodes_cpu)): + f.write(f"1 {i}\n") + + # Cell types (1 = vertex) + f.write(f"\nCELL_TYPES {len(all_nodes_cpu)}\n") + for _ in range(len(all_nodes_cpu)): + f.write("1\n") + + # Point data (force vectors) + f.write(f"\nPOINT_DATA {len(all_nodes_cpu)}\n") + f.write("VECTORS force float\n") + for force in all_forces_cpu: + f.write(f"{force[0]:.6e} {force[1]:.6e} {force[2]:.6e}\n") + + # Scalar field: force magnitude + f.write("\nSCALARS force_magnitude float 1\n") + f.write("LOOKUP_TABLE default\n") + for force in all_forces_cpu: + mag = np.linalg.norm(force) + f.write(f"{mag:.6e}\n") + + # Scalar field: is_seat (0 or 1) + f.write("\nSCALARS is_seat int 1\n") + f.write("LOOKUP_TABLE default\n") + for is_seat in seat_mask_cpu: + f.write(f"{int(is_seat)}\n") + + logging.info(f" 💾 Save force field (VTK format, ParaView) : {vtk_path}") + except Exception as e: + logging.warning(f" ⚠️ Save VTK formatfailed: {e}") + + # ==================== 4. Generate a Python visualization script ==================== + vis_script_path = os.path.join(vis_dir, "visualize_forces.py") + with open(vis_script_path, 'w') as f: + f.write("""#!/usr/bin/env python3 +\"""Visualize voxel load data + +Usage: + python visualize_forces.py + +Requirements: + pip install numpy matplotlib + +\""" +import numpy as np +import matplotlib.pyplot as plt +from mpl_toolkits.mplot3d import Axes3D + +# Load data. +data = np.load('force_nodes.npz') +all_nodes = data['all_nodes'] +seat_nodes = data['seat_nodes'] +seat_forces = data['seat_forces'] +total_force = data['total_force'] + +# Create the 3D figure. +fig = plt.figure(figsize=(15, 5)) + +# Subplot 1: all nodes (gray) + loaded nodes (red). +ax1 = fig.add_subplot(131, projection='3d') +ax1.scatter(all_nodes[:, 0], all_nodes[:, 1], all_nodes[:, 2], + c='lightgray', s=0.5, alpha=0.3, label='All nodes') +ax1.scatter(seat_nodes[:, 0], seat_nodes[:, 1], seat_nodes[:, 2], + c='red', s=5, alpha=1.0, label='Seat nodes (loaded)') +ax1.set_xlabel('X') +ax1.set_ylabel('Y (up)') +ax1.set_zlabel('Z') +ax1.set_title(f'Loaded Nodes\\n({len(seat_nodes)}/{len(all_nodes)} nodes)') +ax1.legend() + +# Subplot 2: Y distribution of loaded nodes. +ax2 = fig.add_subplot(132) +y_coords = seat_nodes[:, 1] +ax2.hist(y_coords, bins=30, color='red', alpha=0.7, edgecolor='black') +ax2.axvline(y_coords.min(), color='blue', linestyle='--', label=f'Y_min={y_coords.min():.3f}') +ax2.axvline(y_coords.max(), color='green', linestyle='--', label=f'Y_max={y_coords.max():.3f}') +ax2.set_xlabel('Y coordinate (height)') +ax2.set_ylabel('Number of nodes') +ax2.set_title('Seat Node Y Distribution') +ax2.legend() +ax2.grid(True, alpha=0.3) + +# Subplot 3: XZ force-vector layout in top view. +ax3 = fig.add_subplot(133) +ax3.scatter(seat_nodes[:, 0], seat_nodes[:, 2], c='red', s=10, alpha=0.5) +# Draw a sparse subset of force vectors to avoid clutter. +step = max(1, len(seat_nodes) // 50) +for i in range(0, len(seat_nodes), step): + node = seat_nodes[i] + force = seat_forces[i] + # Scale force vectors for visualization. + scale = 0.01 + ax3.arrow(node[0], node[2], force[0]*scale, force[2]*scale, + head_width=0.02, head_length=0.01, fc='blue', ec='blue', alpha=0.7) +ax3.set_xlabel('X') +ax3.set_ylabel('Z') +ax3.set_title(f'Top View (XZ plane)\\nForce: {total_force}') +ax3.axis('equal') +ax3.grid(True, alpha=0.3) + +plt.tight_layout() +plt.savefig('force_visualization.png', dpi=150, bbox_inches='tight') +logging.info("✅ image saved : force_visualization.png") +plt.show() + +# Print summary statistics. +logging.info("\\n" + "="*60) +logging.info("force voxel statistics") +logging.info("="*60) +logging.info(f"total node count: {len(all_nodes)}") +logging.info(f"loaded node count: {len(seat_nodes)} ({len(seat_nodes)/len(all_nodes)*100:.1f}%)") +logging.info(f"total: {total_force}") +logging.info(f"per nodeaverage force per node: {seat_forces.mean(axis=0)}") +logging.info(f"\\nY-coordinate range:") +logging.info(f" - min: {y_coords.min():.3f}") +logging.info(f" - max: {y_coords.max():.3f}") +logging.info(f" - mean: {y_coords.mean():.3f}") +logging.info(f" - height span: {y_coords.max() - y_coords.min():.3f}") +logging.info("="*60) +""") + os.chmod(vis_script_path, 0o755) # Add execute permission. + logging.info(f" 💾 Save visualization script: {vis_script_path}") + + # ==================== 5. Generate a README document ==================== + readme_path = os.path.join(vis_dir, "README.md") + with open(readme_path, 'w') as f: + f.write(f"""# Load Voxel Visualization Data + +Generated at: {np.datetime64('now')} + +## Statistics + +- **Total nodes**: {len(all_nodes_cpu)} +- **Loaded nodes**: {len(seat_nodes)} ({len(seat_nodes)/len(all_nodes_cpu)*100:.1f}%) +- **Total force**: {total_force} +- **Force per node**: {seat_forces[0] if len(seat_forces) > 0 else [0,0,0]} + +## Files + +### 1. NumPy format (recommended for analysis) + +- `force_nodes.npz`: contains the full dataset + - `all_nodes`: coordinates of all nodes [{len(all_nodes_cpu)}, 3] + - `all_forces`: force vectors on all nodes [{len(all_nodes_cpu)}, 3] + - `seat_nodes`: coordinates of loaded nodes [{len(seat_nodes)}, 3] + - `seat_forces`: force vectors on loaded nodes [{len(seat_nodes)}, 3] + - `seat_mask`: mask of loaded nodes [{len(all_nodes_cpu)}] + - `boundary_mask`: mask of boundary nodes [{len(all_nodes_cpu)}] + +**Example**: +```python +import numpy as np +data = np.load('force_nodes.npz') +seat_nodes = data['seat_nodes'] +print(f"Loaded nodes: {{len(seat_nodes)}}") +``` + +### 2. OBJ format (recommended for quick inspection) + +- `seat_nodes.obj`: loaded nodes (red point cloud) +- `boundary_nodes.obj`: boundary nodes (blue point cloud) +- `all_nodes.obj`: all nodes (gray point cloud) + +**Usage**: +1. Open in Meshlab: `meshlab seat_nodes.obj` +2. Or import the OBJ files into Blender +3. You can load multiple OBJ files together for comparison + +### 3. VTK format (recommended for professional visualization) + +- `force_field.vtk`: force-field data with vector information + +**Usage**: +1. Open in ParaView: `paraview force_field.vtk` +2. In ParaView: + - Use `Glyph` to visualize force vectors + - Color by `force_magnitude` to inspect strength + - Filter by `is_seat` to isolate the loaded region + +### 4. Visualization script + +- `visualize_forces.py`: Python visualization script + +**Usage**: +```bash +python visualize_forces.py +``` +""") + logging.info(f" 💾 Save README document: {readme_path}") + + # Print a short summary. + logging.info(f" ✅ force voxel data saved successfully!") + logging.info(f" - view directory: {vis_dir}") + logging.info(f" - quick visualization: cd {vis_dir} && python visualize_forces.py") + logging.info(f" - view in Meshlab: meshlab {os.path.join(vis_dir, 'seat_nodes.obj')}") + + +def load_hunyuan_models(model_path: str = "tencent/Hunyuan3D-2.1", + subfolder: str = "hunyuan3d-shapegen", + use_safetensors: bool = True): + """Load the Hunyuan3D models (VAE, Flow Model, and Scheduler). + + Args: + model_path: Model path, either a Hugging Face ID or a local directory. + subfolder: Model subfolder name. + use_safetensors: Whether to load safetensors checkpoints. + + Returns: + (vae, flow_model, scheduler): the VAE, Flow Matching model, and scheduler. + """ + logging.info(f"🔧 loading Hunyuan3D-2.1model...") + logging.info(f" modelpath: {model_path}") + logging.info(f" subfolder: {subfolder}") + logging.info(f" modelformat: {'safetensors' if use_safetensors else 'checkpoint'}") + + try: + pipeline = Hunyuan3DDiTFlowMatchingPipeline.from_pretrained( + model_path, + subfolder=subfolder, + torch_dtype=torch.float16, + use_safetensors=use_safetensors + ) + + if pipeline is None: + raise ValueError("pipeline loading failed and returned None") + + logging.info(" ✅ pipeline loaded successfully") + + pipeline.to('cuda') + logging.info(" ✅ modelmoved to CUDA (dtype: fp16)") + + vae = pipeline.vae + flow_model = pipeline.model + scheduler = pipeline.scheduler + + return vae, flow_model, scheduler + + except Exception as e: + logging.error(f"\n❌ modelloadfailed: {e}") + logging.error(f"\nPossible fixes:") + logging.error(f"1. make sure Hunyuan3D is installed-2.1: cd Hunyuan3D-2.1 && pip install -e .") + logging.error(f"2. check network connectivity to huggingface.co") + logging.error(f"3. or download manually: git clone https://huggingface.co/tencent/Hunyuan3D-2") + import traceback + traceback.print_exc() + sys.exit(1) + + +def plot_history(history: dict, save_dir: str, filename: str = "optimization_metrics.png"): + + epochs = list(range(1, len(history["compliance"]) + 1)) + + # 2. Create the figure with a 2x2 grid + fig, axs = plt.subplots(2, 2, figsize=(14, 10)) + fig.suptitle("Optimization Metrics Evolution", fontsize=16, fontweight='bold') + + # --- Plot 1: Compliance --- + axs[0, 0].plot(epochs, history["compliance"], marker='o', color='#1f77b4', linewidth=2) + axs[0, 0].set_title("Compliance (Strain Energy)") + axs[0, 0].set_xlabel("Epoch") + axs[0, 0].grid(True, linestyle='--', alpha=0.7) + + # --- Plot 2: u_mean --- + axs[0, 1].plot(epochs, history["u_mean"], marker='s', color='#2ca02c', linewidth=2) + axs[0, 1].set_title("Mean Displacement (|u|_mean)") + axs[0, 1].set_xlabel("Epoch") + axs[0, 1].grid(True, linestyle='--', alpha=0.7) + + # --- Plot 3: c_relative_decrease --- + axs[1, 0].plot(epochs, history["c_relative_decrease"], marker='^', color='#d62728', linewidth=2) + axs[1, 0].set_title("Relative Compliance Decrease") + axs[1, 0].set_xlabel("Epoch") + axs[1, 0].grid(True, linestyle='--', alpha=0.7) + + # --- Plot 4: u_relative_decrease --- + axs[1, 1].plot(epochs, history["u_relative_decrease"], marker='v', color='#9467bd', linewidth=2) + axs[1, 1].set_title("Relative Displacement Decrease") + axs[1, 1].set_xlabel("Epoch") + axs[1, 1].grid(True, linestyle='--', alpha=0.7) + + # 3. Adjust layout to prevent text from overlapping + plt.tight_layout() + fig.subplots_adjust(top=0.92) # Leave space for the main super-title + + # 4. Save the figure + os.makedirs(save_dir, exist_ok=True) + full_path = os.path.join(save_dir, filename) + + plt.savefig(full_path, dpi=300, bbox_inches='tight') + plt.close(fig) + + logging.info(f" 📊 Plot successfully saved to: {full_path}") + + +def main(): + """Parse CLI arguments and run the optimization.""" + import argparse + + parser = argparse.ArgumentParser(description="Hunyuan3D physics optimization + shape-prior optimization") + + # Required arguments. + parser.add_argument("--latents", type=str, required=True, + help="Input latents file path (.pt)") + parser.add_argument("--out_folder", type=str, default="../out/hunyuan_opt", + help="Output folder path") + + # Model arguments. + parser.add_argument("--model_path", type=str, default="tencent/Hunyuan3D-2.1", + help="Model path (using v2.1)") + parser.add_argument("--subfolder", type=str, default="hunyuan3d-dit-v2-1", + help="Model subfolder") + parser.add_argument("--use_safetensors", action="store_true", + help="Use safetensors format (default: ckpt)") + + # Physical-simulation arguments. + parser.add_argument("--use_physics", action="store_true", + help="Enable physics-constrained optimization") + parser.add_argument("--res", type=int, default=16, + help="Voxel resolution (16/32/64)") + parser.add_argument("--youngs_modulus_scale", type=float, default=2.0, + help="Final Young's modulus multiplier (default 2x after the last projection)") + parser.add_argument("--compliance_threshold", type=float, default=None, + help="Target compliance threshold (None = automatic)") + parser.add_argument("--compliance_threshold_ratio", type=float, default=0.3, + help="Automatic threshold ratio (threshold = initial value × ratio)") + + # Optimization arguments. + parser.add_argument("--lambda_guidance", type=float, default=0.1) + parser.add_argument("--lambda_score", type=float, default=0.1) + + parser.add_argument("--num_steps", type=int, default=300, + help="Number of optimization steps (pure SDS only; in physics mode it becomes outer_cycles * phys_steps_per_cycle automatically)") + parser.add_argument("--outer_cycles", type=int, default=100, + help="Number of outer cycles (each cycle = physics optimization + projection)") + parser.add_argument("--phys_steps_per_cycle", type=int, default=5, + help="Number of physics-optimization steps per outer cycle") + parser.add_argument("--lr", type=float, default=5e-3, + help="Learning rate (increase to 0.005 to help the mesh thicken faster) ") + parser.add_argument("--lagrange_max", type=float, default=10.0, + help="Maximum Lagrange multiplier (recommended: 5-20)") + parser.add_argument("--alm_rho_init", type=float, default=1.0, + help="ALM rhoinitial value") + parser.add_argument("--alm_rho_max", type=float, default=1000.0, + help="ALM rhoMax") + parser.add_argument("--alm_rho_increase_factor", type=float, default=2.0, + help="ALM rhogrowth factor") + parser.add_argument("--alm_rho_increase_patience", type=int, default=5, + help="ALM rhonumber of consecutive violation steps required before increasing") + parser.add_argument("--alm_scale_guard_ratio", type=float, default=0.95, + help="ALMscaling guard ratio(<=1), control the upper bound of the physics-gradient target=this ratio x clipping-threshold value") + parser.add_argument("--grad_clip_enabled", action="store_true", + help="Enable gradient clipping (disabled by default; otherwise only NaN/Inf checks are kept)") + parser.add_argument("--use_sgd", action="store_true", + help="Use SGD instead of Adam") + parser.add_argument("--force_config", type=str, default=None, + help="Path to the external-force JSON config (generated by the web UI)") + parser.add_argument("--force", type=float, nargs=3, action="append", default=None, + help="External force vector [fx fy fz] (N, Y-up coordinates; can be specified multiple times)") + parser.add_argument("--global_loading", action="store_true", + help="Use global uniform loading (disable local loading)") + parser.add_argument("--force_region_mode", type=str, default="top_percent", + choices=["top_percent", "height_ratio", "bbox"], + help="How to choose the local loading region") + parser.add_argument("--force_top_percent", type=float, default=0.05, + help="top_percent mode: select the highest-Y fraction") + parser.add_argument("--force_bbox", type=float, nargs=6, default=None, + help="bbox mode: x_min x_max y_min y_max z_min z_max (absolute coordinates)") + parser.add_argument("--force_bbox_ratio", type=float, nargs=6, default=None, + help="bbox mode (0-1): bbox relative to the node bounds") + parser.add_argument("--seat_height_min_ratio", type=float, default=0.3, + help="height_ratio mode: lower seat boundary (0-1)") + parser.add_argument("--seat_height_max_ratio", type=float, default=0.5, + help="height_ratio mode: upper seat boundary (0-1)") + + # SDS arguments. + parser.add_argument("--sds_weight", type=float, default=1.0, + help="SDS gradient weight (deprecated; use sds_weight_start and sds_weight_end instead)") + parser.add_argument("--sds_weight_start", type=float, default=10.0, + help="Initial SDS weight (linearly increased; 0.0001 is recommended to avoid disturbing physics optimization)") + parser.add_argument("--sds_weight_end", type=float, default=10.0, + help="Final SDS weight (linearly increased; 0.001 is recommended, about 1/10 of the physics gradient)") + parser.add_argument("--sds_timestep", type=float, default=0.1, + help="SDS timestep (recommended: 0.05-0.2)") + parser.add_argument("--sds_target_z0_ema_beta", type=float, default=0.9, + help="target_z0 EMA smoothing factor (larger means smoother)") + parser.add_argument("--deformed_mesh_interval", type=int, default=10, + help="Interval for saving deformed meshes (steps)") + parser.add_argument("--deformed_mesh_disp_min", type=float, default=0.0, + help="Minimum displacement for deformed-mesh color mapping (default 0.0)") + parser.add_argument("--deformed_mesh_disp_max", type=float, default=0.2, + help="Maximum displacement for deformed-mesh color mapping (<=0 enables per-step auto scaling)") + parser.add_argument("--guidance_scale", type=float, default=7.5, + help="CFG guidance scale (standard value: 7.5; larger means stronger image conditioning)") + parser.add_argument("--sds_projection_max_rel", type=float, default=0.0, + help="Maximum relative target_z0 projection deviation (0 = unlimited)") + parser.add_argument("--sds_use_uncond", action="store_true", + help="Use the unconditional branch (only takes effect when guidance_scale <= 1)") + + # Topology control. + parser.add_argument("--keep_all_components", action="store_true", + help="Keep all connected components (to avoid disappearing chair legs)") + parser.add_argument("--re_extract_interval", type=int, default=1, + help="Solid re-extraction interval (0 = disabled)") + + args = parser.parse_args() + + def _normalize_force_vectors(value): + if value is None: + return None + if isinstance(value, (list, tuple)) and len(value) > 0: + if isinstance(value[0], (list, tuple)): + candidates = value + else: + candidates = [value] + else: + return None + normalized = [] + for vec in candidates: + if not isinstance(vec, (list, tuple)) or len(vec) != 3: + continue + try: + normalized.append([float(v) for v in vec]) + except Exception: + continue + return normalized if normalized else None + + def _normalize_force_entry(entry): + if not isinstance(entry, dict): + return None + forces = _normalize_force_vectors(entry.get("forces")) + if forces is None: + forces = _normalize_force_vectors(entry.get("force")) + if forces is None: + return None + out = dict(entry) + if len(forces) > 1: + out["forces"] = forces + out["force"] = [float(sum(v[i] for v in forces)) for i in range(3)] + else: + out["force"] = forces[0] + out.pop("forces", None) + if "force_region_mode" in out: + out["force_region_mode"] = str(out["force_region_mode"]) + if "global_loading" in out: + out["global_loading"] = bool(out["global_loading"]) + if "force_top_percent" in out: + out["force_top_percent"] = float(out["force_top_percent"]) + if "seat_height_min_ratio" in out: + out["seat_height_min_ratio"] = float(out["seat_height_min_ratio"]) + if "seat_height_max_ratio" in out: + out["seat_height_max_ratio"] = float(out["seat_height_max_ratio"]) + if "force_bbox" in out and isinstance(out["force_bbox"], (list, tuple)) and len(out["force_bbox"]) == 6: + out["force_bbox"] = [float(v) for v in out["force_bbox"]] + elif "force_bbox" in out: + out.pop("force_bbox", None) + if "force_bbox_ratio" in out and isinstance(out["force_bbox_ratio"], (list, tuple)) and len(out["force_bbox_ratio"]) == 6: + out["force_bbox_ratio"] = [float(v) for v in out["force_bbox_ratio"]] + elif "force_bbox_ratio" in out: + out.pop("force_bbox_ratio", None) + return out + + # Load force configuration from JSON, typically exported from the web UI. + force_config_loaded = False + force_config_error = None + force_entries = None + if args.force_config: + raw_force_config = args.force_config + candidates = [] + if os.path.isabs(raw_force_config): + candidates.append(raw_force_config) + else: + candidates.append(raw_force_config) + script_dir = os.path.dirname(os.path.abspath(__file__)) + candidates.append(os.path.join(script_dir, raw_force_config)) + candidates.append(os.path.join(os.path.dirname(script_dir), raw_force_config)) + force_config_path = next((p for p in candidates if os.path.exists(p)), None) + if force_config_path is None: + force_config_error = f"Path does not exist; tried: {candidates}" + else: + args.force_config = force_config_path + try: + with open(force_config_path, "r") as f: + force_cfg = json.load(f) + if isinstance(force_cfg, dict): + cfg_forces = _normalize_force_vectors(force_cfg.get("forces")) + if cfg_forces is not None: + args.force = cfg_forces + else: + cfg_force = _normalize_force_vectors(force_cfg.get("force")) + if cfg_force is not None: + args.force = cfg_force + elif "force" in force_cfg or "forces" in force_cfg: + force_config_error = "force/forcesinvalid format" + if "global_loading" in force_cfg: + args.global_loading = bool(force_cfg["global_loading"]) + if "force_region_mode" in force_cfg: + args.force_region_mode = str(force_cfg["force_region_mode"]) + if "force_top_percent" in force_cfg: + args.force_top_percent = float(force_cfg["force_top_percent"]) + if "seat_height_min_ratio" in force_cfg: + args.seat_height_min_ratio = float(force_cfg["seat_height_min_ratio"]) + if "seat_height_max_ratio" in force_cfg: + args.seat_height_max_ratio = float(force_cfg["seat_height_max_ratio"]) + if "force_bbox" in force_cfg: + args.force_bbox = force_cfg["force_bbox"] + if "force_bbox_ratio" in force_cfg: + args.force_bbox_ratio = force_cfg["force_bbox_ratio"] + if "force_entries" in force_cfg: + raw_entries = force_cfg["force_entries"] + if isinstance(raw_entries, list): + normalized_entries = [] + for entry in raw_entries: + norm_entry = _normalize_force_entry(entry) + if norm_entry is not None: + normalized_entries.append(norm_entry) + if normalized_entries: + force_entries = normalized_entries + else: + force_config_error = "force_entries has no valid entries" + else: + force_config_error = "force_entriesinvalid format" + force_config_loaded = True + else: + force_config_error = f"force_configis not a dict: {type(force_cfg)}" + except Exception as e: + force_config_error = f"read failed: {e}" + + # Configure logging. force=True ensures this replaces any prior setup. + os.makedirs(args.out_folder, exist_ok=True) + log_file = os.path.join(args.out_folder, "optimization.log") + + # Remove any existing handlers. + for handler in logging.root.handlers[:]: + logging.root.removeHandler(handler) + + # Reconfigure logging. + logging.basicConfig( + level=logging.INFO, + format='%(asctime)s - %(levelname)s - %(message)s', + handlers=[ + logging.FileHandler(log_file, mode='w'), # Rewrite the log on each run. + logging.StreamHandler() + ], + force=True # Python 3.8+: force a full reconfiguration. + ) + + logging.info(f"🔧 logging configuration completed") + logging.info(f" - log file: {log_file}") + logging.info(f" - output mode: file + console") + if args.force_config: + if force_config_loaded: + logging.info(" ✅ force_configloaded") + logging.info(f" - path: {args.force_config}") + logging.info(f" - forces: {args.force}") + if force_entries: + logging.info(f" - force_entries: {len(force_entries)}") + logging.info(f" - global_loading: {args.global_loading}") + logging.info(f" - force_region_mode: {args.force_region_mode}") + logging.info(f" - force_top_percent: {args.force_top_percent}") + logging.info(f" - seat_height_min_ratio: {args.seat_height_min_ratio}") + logging.info(f" - seat_height_max_ratio: {args.seat_height_max_ratio}") + logging.info(f" - force_bbox: {args.force_bbox}") + logging.info(f" - force_bbox_ratio: {args.force_bbox_ratio}") + if force_config_error: + logging.warning(f" ⚠️ force_configsome fields are invalid: {force_config_error}") + else: + logging.warning(f" ⚠️ force_configloadfailed: {force_config_error}") + + # In physics mode, derive num_steps from outer_cycles and phys_steps_per_cycle. + if args.use_physics: + outer_cycles = max(1, int(args.outer_cycles)) + phys_steps_per_cycle = max(1, int(args.phys_steps_per_cycle)) + derived_num_steps = outer_cycles * phys_steps_per_cycle + if args.num_steps != derived_num_steps: + logging.info( + f" - num_stepsautomatically set: {args.num_steps} → {derived_num_steps} " + f"(outer_cycles={outer_cycles}, phys_steps_per_cycle={phys_steps_per_cycle})" + ) + args.num_steps = derived_num_steps + + # ==================== Save run metadata ==================== + # 1. Save the command line. + command_file = os.path.join(args.out_folder, "run_command.txt") + try: + with open(command_file, 'w') as f: + f.write("=" * 80 + "\n") + f.write("Command used (Command Used)\n") + f.write("=" * 80 + "\n\n") + f.write("Full command:\n") + f.write("python " + " ".join(sys.argv) + "\n\n") + + f.write("=" * 80 + "\n") + f.write("Arguments (Arguments)\n") + f.write("=" * 80 + "\n\n") + for arg, value in vars(args).items(): + f.write(f"{arg}: {value}\n") + + f.write("\n" + "=" * 80 + "\n") + f.write("Environment (Environment)\n") + f.write("=" * 80 + "\n\n") + f.write(f"Python: {sys.version}\n") + f.write(f"PyTorch: {torch.__version__}\n") + f.write(f"CUDA Available: {torch.cuda.is_available()}\n") + if torch.cuda.is_available(): + f.write(f"CUDA Version: {torch.version.cuda}\n") + f.write(f"GPU Count: {torch.cuda.device_count()}\n") + + logging.info(f" - saved command used : {command_file}") + except Exception as e: + logging.warning(f" ⚠️ Save Command usedfailed: {e}") + + # 2. Save a copy of the current script. + script_backup = os.path.join(args.out_folder, "viewer_hunyuan_web_alternate.py") + try: + current_script = os.path.abspath(__file__) + shutil.copy2(current_script, script_backup) + logging.info(f" - saved script copy : {script_backup}") + except Exception as e: + logging.warning(f" ⚠️ Save failed to save script copy: {e}") + + # Load latents and conditioning data. + logging.info(f"\n📂 loading input data...") + logging.info(f" - Latents: {args.latents}") + + data = torch.load(args.latents, map_location='cpu') + + # Extract latents. + if isinstance(data, dict) and 'latents' in data: + latents = data['latents'] + else: + latents = data + + logging.info(f" ✅ Latents shape: {latents.shape}") + + # Check conditioning data (image_embeds or image). + need_encode_cond = False + image_embeds = None + image = None + + if isinstance(data, dict): + if 'image' in data: + # New format: only the image was saved, so we need to re-encode it. + logging.info(f" - detected image data; re-encoding as conditional embeds") + image_array = data['image'] + image = Image.fromarray(image_array) + need_encode_cond = True + elif 'image_embeds' in data: + # Legacy format: embeddings are already saved. + logging.info(f" - using the saved conditional embeds") + image_embeds = data['image_embeds'] + need_encode_cond = False + elif 'cond' in data: + # Alternate format using a saved cond dict. + logging.info(f" - using the saved cond") + image_embeds = data['cond'] + need_encode_cond = False + else: + raise ValueError("latents.ptis missingimage, image_embedsor cond data") + else: + raise ValueError("latentsmust be a dictionary containing'latents'andconditioninformation dict") + + if image_embeds is not None: + if isinstance(image_embeds, dict): + logging.info(f" ✅ Cond keys: {list(image_embeds.keys())}") + else: + logging.info(f" ✅ Image embeds shape: {image_embeds.shape}") + + # Load models. + logging.info(f"\n🔧 loading Hunyuan3Dmodel...") + vae, flow_model, scheduler = load_hunyuan_models( + model_path=args.model_path, + subfolder=args.subfolder, + use_safetensors=args.use_safetensors + ) + + # ==================== Encode conditioning data if needed ==================== + if need_encode_cond: + logging.info("🎨 encoding conditional embeds from the image...") + + # Reload the full pipeline for condition encoding. + from hy3dgen.shapegen import Hunyuan3DDiTFlowMatchingPipeline + + pipeline = Hunyuan3DDiTFlowMatchingPipeline.from_pretrained( + args.model_path, + subfolder=args.subfolder, + torch_dtype=torch.float16, + use_safetensors=args.use_safetensors + ) + pipeline.to('cuda') + + with torch.no_grad(): + # Prepare the image. + cond_inputs = pipeline.prepare_image(image) + image_tensor = cond_inputs.pop('image') + + # Enable CFG so the encoded condition contains both branches. + cond_dict = pipeline.encode_cond( + image=image_tensor, + additional_cond_inputs=cond_inputs, + do_classifier_free_guidance=True, # Enable CFG. + dual_guidance=False, + ) + + # Save the condition dict. + image_embeds = cond_dict + + logging.info(f" ✅ condition encoding completed (CFG mode) ") + logging.info(f" - Cond keys: {list(cond_dict.keys()) if isinstance(cond_dict, dict) else 'tensor'}") + + # Resolve the compliance threshold. + if args.compliance_threshold is None: + compliance_threshold = 200.0 + logging.info(f" using the default compliance threshold: {compliance_threshold}") + else: + compliance_threshold = args.compliance_threshold + logging.info(f" using the custom compliance threshold: {compliance_threshold}") + + target_z0_update_interval = max(1, int(args.phys_steps_per_cycle)) + forces = None + normalized_forces = _normalize_force_vectors(args.force) + if normalized_forces: + forces = [{'external_force': vec} for vec in normalized_forces] + elif args.force is not None: + logging.warning(f" ⚠️ invalid external force vector; ignoring: {args.force}") + # Build the optimization config. + config = OptimizationConfig( + num_steps=args.num_steps, + lr=args.lr, + sds_timestep=args.sds_timestep, + sds_weight=args.sds_weight if args.use_physics else 1.0, # Keep backward compatibility. + sds_weight_start=args.sds_weight_start, # Dynamic weight schedule start. + sds_weight_end=args.sds_weight_end, # Dynamic weight schedule end. + guidance_scale=args.guidance_scale, # CFG guidance scale. + sds_projection_max_rel=args.sds_projection_max_rel, + sds_use_uncond=args.sds_use_uncond, + sds_target_z0_update_interval=target_z0_update_interval, + sds_target_z0_ema_beta=args.sds_target_z0_ema_beta, + deformed_mesh_interval=args.deformed_mesh_interval, + deformed_mesh_disp_min=args.deformed_mesh_disp_min, + deformed_mesh_disp_max=args.deformed_mesh_disp_max, + use_sgd=args.use_sgd, + grad_clip_enabled=args.grad_clip_enabled, + # Physical parameters. + res=args.res, + lagrange_max=args.lagrange_max, + compliance_threshold=compliance_threshold, + alm_rho_init=args.alm_rho_init, + alm_rho_max=args.alm_rho_max, + alm_rho_increase_factor=args.alm_rho_increase_factor, + alm_rho_increase_patience=args.alm_rho_increase_patience, + alm_scale_guard_ratio=args.alm_scale_guard_ratio, + youngs_modulus_scale=args.youngs_modulus_scale, + # Topology control. + one_cc_only=not args.keep_all_components, + re_extract_interval=args.re_extract_interval, + # Loads and load-region settings. + forces=forces, + force_entries=force_entries, + use_local_loading=not args.global_loading, + seat_height_min_ratio=args.seat_height_min_ratio, + seat_height_max_ratio=args.seat_height_max_ratio, + force_region_mode=args.force_region_mode, + force_top_percent=args.force_top_percent, + force_bbox=args.force_bbox, + force_bbox_ratio=args.force_bbox_ratio, + # Output path. + out_folder=args.out_folder, + ) + + # Create the optimizer. + optimizer = HunyuanSDSOptimizer( + latents=latents, + cond=image_embeds, + vae=vae, + flow_model=flow_model, + scheduler=scheduler, + config=config, + device='cuda' + ) + + # Prepare physics if requested. + final_step = args.num_steps + if args.use_physics: + logging.info(f"\n🔬 enable physics optimization mode") + logging.info(f" - Voxel resolution: {args.res}") + logging.info(f" - physics steps/cycle: {args.phys_steps_per_cycle}, outer cycles: {args.outer_cycles}") + logging.info(f" - projection noise: sds_timestep={args.sds_timestep}") + logging.info(f" - target_z0update interval: {target_z0_update_interval} (consistent with phys_steps_per_cycle)") + logging.info(f" - LagrangeMax: {args.lagrange_max}") + + try: + optimizer.extract_solid(step=-1) # Initial extraction. + optimizer.prepare_physical_simulation() + logging.info(f" ✅ physics simulationInitializationsucceeded") + except Exception as e: + logging.warning(f" ⚠️ warning: initial mesh extraction failed (this is normal, optimizationbe repaired during the optimization process) ") + logging.warning(f" error information: {str(e)[:100]}") + # Continue anyway: the key physical state is the occupancy field, not the mesh. + else: + logging.info(f"\n🎨 using pure SDS optimization mode") + + # Optimization loop. + optimization_mode = "Alternating Phys/Projection" if args.use_physics else "Pure SDS" + total_steps_hint = ( + int(args.outer_cycles) * (int(args.phys_steps_per_cycle) + 1) + if args.use_physics + else args.num_steps + ) + logging.info(f"\n🚀 start{optimization_mode}optimization ({total_steps_hint} steps)...") + + if args.use_physics: + lagrange_multiplier = 0.0 + rho = config.alm_rho_init + violation_count = 0 + + # Automatically set the compliance threshold when needed. + if config.compliance_threshold is None or config.compliance_threshold == 200.0: + logging.info(f" 📊 computationinitialcompliancethreshold value...") + try: + initial_compliance, initial_u, _, _ = optimizer.training_step( + 0, 0.0, 0.0, use_sds=False + ) + # Auto threshold: initial compliance times the requested ratio. + auto_threshold = initial_compliance * args.compliance_threshold_ratio + auto_threshold = min(auto_threshold, 100000.0) # Upper bound only. + compliance_threshold = auto_threshold + config.compliance_threshold = auto_threshold + logging.info( + f" ✅ Automatically set the threshold: {initial_compliance:.2e} × {args.compliance_threshold_ratio:.2f} " + f"= {compliance_threshold:.2e}" + ) + + # Warn when the structure already looks extremely stiff or too soft. + if initial_compliance < 0.01: # Already very stiff. + logging.warning(f" ⚠️ initial compliance is very small ({initial_compliance:.2e}), the structure may already be stiff enough!") + logging.warning(f" consider increasing the external force or using a softer material to create visible deformation") + logging.warning(f" current material: E={config.youngs_modulus:.2e} Pa, ν={config.poissons_ratio}") + elif initial_compliance > 1000.0: # Likely too soft. + logging.warning(f" ⚠️ initial compliance is very large ({initial_compliance:.2e}), the structure may be too soft!") + logging.warning(f" consider using a stiffer material or reducing the external force") + except Exception as e: + logging.warning(f" ⚠️ automatic computation failed, usethreshold value200: {e}") + compliance_threshold = 200.0 + else: + compliance_threshold = config.compliance_threshold + + logging.info(f"🎯 parameters:") + logging.info(f" - initial lambda: {lagrange_multiplier}") + logging.info(f" - initial rho: {rho}") + logging.info(f" - Compliancethreshold value: {compliance_threshold:.2e}") + logging.info(f" - λMax: {args.lagrange_max}") + logging.info(f" - ρMax: {config.alm_rho_max:.1e}") + logging.info(f" - rho growth: ×{config.alm_rho_increase_factor:.1f} (continuous violations{config.alm_rho_increase_patience} steps)") + logging.info(f" - ALMscaling guard ratio: {config.alm_scale_guard_ratio:.2f}") + logging.info(f" - gradient clipping: {'enabled' if config.grad_clip_enabled else 'disabled'}") + + outer_cycles = max(1, int(args.outer_cycles)) + phys_steps_per_cycle = max(1, int(args.phys_steps_per_cycle)) + total_steps = outer_cycles * (phys_steps_per_cycle + 1) + logging.info( + f"🔁 Alternating optimization: outer cycles={outer_cycles}, physics steps/cycle={phys_steps_per_cycle}, " + f"total steps(including projections)≈{total_steps}" + ) + base_youngs_modulus = float(config.youngs_modulus) + youngs_modulus_scale = float(config.youngs_modulus_scale) + youngs_modulus_target = base_youngs_modulus * youngs_modulus_scale + youngs_modulus_delta = (youngs_modulus_target - base_youngs_modulus) / outer_cycles + projection_count = 0 + logging.info( + f" - linearly increase Young's modulus: E0={base_youngs_modulus:.2e}, " + f"Δ/projection={youngs_modulus_delta:.2e}, E_final={youngs_modulus_target:.2e} " + f"(scale={youngs_modulus_scale:.2f}x)" + ) + global_step = 0 + + history = {"compliance": [], + "u_mean": [], + "c_relative_decrease": [], + "u_relative_decrease": [], + "error": [], + "epoch": []} + + # thresholds = [0, 30, 40, 50, 60, 65, 70, 75, 80, 90, 95] + thresholds = [0, 20, 30, 40, 50, 55, 60, 70, 80] + latents_dir = os.path.join(args.out_folder, "latents") + os.makedirs(latents_dir, exist_ok=True) + + for current_threshold in thresholds: + logging.info(f"\n✅ Threshold : {current_threshold}") + + target_compliance = initial_compliance - current_threshold*initial_compliance/100 + logging.info(f"Target compliance: {target_compliance}") + + optimize_latent, compliance_loss, u_mean, diff = optimizer.flow_matching_with_ictm(step=current_threshold, guidance_value=target_compliance, lambda_guidance=args.lambda_guidance, lambda_score=args.lambda_score) + + # Update history + history["compliance"].append(compliance_loss) + history["u_mean"].append(u_mean) + history["error"].append(np.abs(diff)) + + # Calculate relative decreases using current variables + c_decrease = (initial_compliance - compliance_loss) / initial_compliance * 100 + u_decrease = (initial_u - u_mean) / initial_u * 100 + history["c_relative_decrease"].append(c_decrease) + history["u_relative_decrease"].append(u_decrease) + logging.info(f" 📉 Metrics | Comp: {compliance_loss:.3e} (↓ {c_decrease:.1f}%) | u_mean: {u_mean:.3e} (↓ {u_decrease:.1f}%)") + + optimizer.save_mesh(current_threshold, args.out_folder, suffix="decrease", high_quality=True, latents=optimize_latent) + latent_path = os.path.join(latents_dir, f"latent_{current_threshold}.pt") + torch.save({'latents': optimizer.latents.detach().cpu(), 'cond': optimizer.cond}, latent_path) + + optimizer.save_final_deformed_mesh(current_threshold, suffix="decrease", latents=optimize_latent) + + # Save final results. + logging.info("\n✅ Optimization finished!") + + history_path = os.path.join(args.out_folder, "history.json") + with open(history_path, "w", encoding="utf-8") as f: + json.dump(history, f, indent=4) + + plot_history(history, save_dir=args.out_folder, filename="optimization_metrics.png") + + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/cfd_workflow_20261012/_seiler_ref/physiopt_new_scripts/hunyuan_sdedit_me.py b/cfd_workflow_20261012/_seiler_ref/physiopt_new_scripts/hunyuan_sdedit_me.py new file mode 100644 index 0000000000000000000000000000000000000000..a226bf1a0a3a32ac298680ad5923c6f8711bc640 --- /dev/null +++ b/cfd_workflow_20261012/_seiler_ref/physiopt_new_scripts/hunyuan_sdedit_me.py @@ -0,0 +1,3124 @@ +""" +Hunyuan3D-2.1 physical optimization + shape-prior optimization. +""" + +import os +import copy +# os.environ['TORCH_HOME'] = '/mnt/cvlab/scratch/cvlab/home/hantzhan/.torch' +import sys +import shutil + +# Add Hunyuan3D-2.1 to the Python path. +hunyuan_path = os.path.abspath(os.path.join(os.path.dirname(__file__), "../../Hunyuan3D-2.1")) +# Note: logging is not imported yet, so use print here if needed. +# Basic logging is configured near the top of the file after import. + +sys.path.append("..") + +from matplotlib import pyplot as plt +import torch +import torch.nn.functional as F +import trimesh +import numpy as np +from PIL import Image +import argparse +import json +from typing import Tuple, Optional, List +from dataclasses import dataclass, field +import traceback +import logging + +# Configure logging here only conceptually; main() will reconfigure it to +# log to both the console and a file. +# Do not call basicConfig here so the main() configuration remains effective. +# logging.basicConfig(level=logging.INFO, format='%(levelname)s: %(message)s') + +# Physical-simulation imports. +PHYSIOPT_AVAILABLE = False +try: + from physiopt.utils.phys_utils import generate_hex + from physiopt.utils.grid_utils import filter_one_component + from physiopt.opt.field import occ_kernel + from physiopt.opt.forces import ForceConfig + PHYSIOPT_AVAILABLE = True + logging.info("✅ physics simulation moduleimportsucceeded") +except ImportError as e: + logging.warning(f"⚠️ warning: physics simulation moduleimportfailed: {e}") + logging.warning(" if you only run SDS optimization, you can ignore this warning") + PHYSIOPT_AVAILABLE = False + + def generate_hex(res, limits=[(-0.5, 0.5), (-0.5, 0.5), (-0.5, 0.5)], device="cuda", return_coords=False): + """Placeholder for hexahedral grid generation. + + Returns tensors in the same format as the real function. + """ + logging.warning(f"⚠️ warning: using placeholdergenerate_hex, please install the physiopt module") + return None, None + + def filter_one_component(mask, res): + """Placeholder for connected-component filtering. + + Args: + mask: Element mask [res*res*res] + res: Voxel resolution + """ + return mask + + def occ_kernel(sdf, res, beta): + """Placeholder for SDF-to-occupancy conversion.""" + return torch.sigmoid(-sdf * beta) + +# Warp physics-engine import. +try: + import warp as wp + wp.init() + WARP_AVAILABLE = True + logging.info("✅ Warp physics engineInitializationsucceeded") +except ImportError: + WARP_AVAILABLE = False + logging.warning("⚠️ warning: Warp physics enginenot installed, physics simulationwill be unavailable") + logging.warning(" Install: pip install warp-lang") + +# Hunyuan3D imports +try: + from hy3dgen.shapegen.models.autoencoders import ShapeVAE + from hy3dgen.shapegen import Hunyuan3DDiTFlowMatchingPipeline + from hy3dgen.shapegen.pipelines import export_to_trimesh +except ImportError as e: + logging.error(f"❌ failed to import Hunyuan3D modules: {e}") + logging.error(f"\nplease follow these steps to set upHunyuan3D-2.1:") + logging.error(f"1. cd {os.path.dirname(hunyuan_path)}") + logging.error(f"2. git clone https://github.com/Tencent/Hunyuan3D-2.git Hunyuan3D-2.1") + logging.error(f"3. cd Hunyuan3D-2.1") + logging.error(f"4. pip install -e .") + sys.exit(1) + + +@dataclass +class OptimizationConfig: + """Optimization config for physics + SDS.""" + # Physical-simulation parameters. + res: int = 32 # Voxel resolution (16/32/64), matching the reference code. + # Restored physical settings from the stable v90 configuration. + p_exponent: float = 1.0 # SIMP penalty exponent. + alpha_min: float = 0.01 # Minimum density, restored from v90. + volume_term: float = 1000000.0 # Volume-constraint weight, currently disabled. + occ_sdf_beta: float = 2.0 # Sigmoid-kernel beta, restored from v90. + one_cc_only: bool = False # Keep only the largest connected component. + + # SDS parameters. + # Use dynamic SDS weights so physics dominates early and aesthetics enters later. + sds_timestep: float = 0.1 # SDS timestep; smaller values preserve more detail. + sds_weight: float = 1.0 # SDS weight relative to the physical gradient. + sds_weight_start: float = 1e5 # 0.1 # 0.0001 # Initial SDS weight. + sds_weight_end: float = 1e5 # 1.0 # 0.001 # Final SDS weight. + guidance_scale: float = 7.5 # Standard CFG guidance scale for stronger image conditioning. + sds_projection_max_rel: float = 0.0 # Max relative target_z0 projection offset (0 = unlimited). + sds_use_uncond: bool = False # Use the unconditional branch when guidance_scale <= 1. + sds_target_z0_update_interval: int = 10 # target_z0 update interval; tied to phys_steps_per_cycle. + sds_target_z0_ema_beta: float = 0.9 # EMA smoothing coefficient; larger is smoother. + + lagrange_max: float = 50.0 # Max lambda. + compliance_threshold: float = 200.0 # Compliance threshold used for normalization. + alm_rho_init: float = 1.0 # Initial rho. + alm_rho_max: float = 1000.0 # Max rho. + alm_rho_increase_factor: float = 2.0 # Rho growth factor. + alm_rho_increase_patience: int = 5 # Number of consecutive violations before increasing rho. + alm_scale_guard_ratio: float = 0.95 # ALM scaling guard to stay below gradient clipping. + + # Topology control. + re_extract_interval: int = 5 # Re-extract the solid every N steps; 0 disables it. + + # Material properties. Values are aligned with the reference setup. + # youngs_modulus is already specified directly in Pa, so no unit conversion is needed. + youngs_modulus: float = 5e8 # 1e9 # Pa (= 1 GPa), restored from v90. + youngs_modulus_scale: float = 2.0 # Final multiplier after the last projection in alternating mode. + poissons_ratio: float = 0.3 # Poisson's ratio (dimensionless). + density: float = 650.0 # Material density (kg/m^3). + + ## Wood + # youngs_modulus: float = 9e9 # Pa (= 1 GPa), aligned with the reference code. + # poissons_ratio: float = 0.35 # Poisson's ratio (dimensionless), matches the reference. + # density: float = 400.0 # Material density (kg/m^3), matches the reference. + + ## PVG + # youngs_modulus: float = 3.25e9 # Pa (= 1 GPa), aligned with the reference code. + # poissons_ratio: float = 0.38 # Poisson's ratio (dimensionless), matches the reference. + # density: float = 1380.0 # Material density (kg/m^3), matches the reference. + + # Load conditions; supports multiple forces like config.json. + forces: List = None # List of ForceConfig objects. + # Multiple localized load entries, each with its own force and region settings. + force_entries: Optional[List[dict]] = None + + # Local-loading settings, e.g. to mimic a person sitting on a chair. + use_local_loading: bool = True # Use local loading instead of global uniform loading. + seat_height_min_ratio: float = 0.3 # Lower bound of the seat band as a height ratio. + seat_height_max_ratio: float = 0.5 # Upper bound of the seat band as a height ratio. + force_region_mode: str = "top_percent" # Load-region mode: top_percent / height_ratio / bbox. + force_top_percent: float = 0.05 # In top_percent mode, use the highest-Y fraction of nodes. + force_bbox: Optional[List[float]] = None # bbox mode: x_min x_max y_min y_max z_min z_max. + force_bbox_ratio: Optional[List[float]] = None # bbox mode in normalized node bounds [0, 1]. + + # Optimization parameters, restored from the stable v90 configuration. + lr: float = 0.001 # Learning rate. + num_steps: int = 100 # Number of optimization steps. + use_sgd: bool = False # Use SGD instead of Adam. + grad_clip_enabled: bool = False # Enable gradient clipping; off by default. + save_every: int = 10 # Save interval in steps. + deformed_mesh_interval: int = 10 # Save interval for deformed meshes. + deformed_mesh_disp_min: float = 0.0 # Minimum displacement for deformed-mesh color mapping. + deformed_mesh_disp_max: float = 0.2 # Maximum displacement for deformed-mesh color mapping. + + # Output path. + out_folder: str = "../out/hunyuan_opt" # Output directory. + + # Device. + device: str = "cuda" # Compute device. + + # Whether to enable physics optimization. + use_physics: bool = True # Enable physical-constraint optimization. + + def __post_init__(self): + # Set default loads in the Hunyuan Y-up coordinate system: + # X = right, Y = up, Z = forward. + if self.forces is None: + try: + from physiopt.opt.forces import ForceConfig + self.forces = [ + ForceConfig(external_force=[0.0, -100000.0, 0.0]) # 100 kN downward along Y. + # ForceConfig(external_force=[0.0, 0.0, -500.0]), # 500 N backward along Z. + ] + except ImportError: + # Fallback format if physiopt is unavailable; keep only the force vectors. + self.forces = [ + {'external_force': [0.0, -100000.0, 0.0]} # 100 kN downward along Y. + # {'external_force': [0.0, 0.0, -500.0]}, # Backward along Z. + ] + + +class HunyuanSDSOptimizer: + """Hunyuan3D SDS optimizer with differentiable physics support.""" + + def __init__( + self, + latents: torch.Tensor, + cond: dict, # Condition dict containing positive and negative branches. + vae: ShapeVAE, + flow_model: torch.nn.Module, + config: OptimizationConfig, + scheduler=None, + device: str = 'cuda' + ): + """ + Args: + latents: Initial latent tokens [1, N, D]. + cond: Condition dict returned by pipeline.encode_cond. + vae: Hunyuan3D VAE model. + flow_model: Hunyuan3D Flow Matching model. + scheduler: Hunyuan3D Flow Matching scheduler used to align target_z0. + config: Optimization config. + device: Compute device. + """ + self.device = device + self.config = config + + # Models. + self.vae = vae.to(device).eval() + self.flow_model = flow_model.to(device).eval() + if scheduler is not None: + try: + self.sds_scheduler = copy.deepcopy(scheduler) + except Exception: + self.sds_scheduler = scheduler + logging.warning("⚠️ Scheduler deepcopyfailed, already fallback to originalscheduler") + else: + self.sds_scheduler = None + + # Create a differentiable SDF query helper. + from hy3dgen.shapegen.models.autoencoders.differentiable_sdf_query import DifferentiableSDFQuery + self.sdf_query = DifferentiableSDFQuery( + vae=self.vae, + bounds=0.8, # Our coordinate range is [-0.8, 0.8]. + chunk_size=8192 # Batch query size. + ) + logging.info(f"✅ created differentiable SDF query helper") + + # Latent tokens are the variables being optimized. + # Use float32 instead of float16 to avoid numeric overflow. + self.latents = latents.clone().to(device).to(torch.float32).requires_grad_(True) + + logging.info(f" ⚠️ note: Latentsfloat32FP16value") + + # Move conditioning data to the target device recursively. + def to_device_recursive(obj): + if isinstance(obj, torch.Tensor): + return obj.to(device) + elif isinstance(obj, dict): + return {k: to_device_recursive(v) for k, v in obj.items()} + elif isinstance(obj, (list, tuple)): + return type(obj)(to_device_recursive(item) for item in obj) + else: + return obj + + self.cond = to_device_recursive(cond) + self._cond_warned_cfg_repeat = False + self._cond_warned_nocfg_slice = False + + # Optimizer selection. + if config.use_sgd: + self.optimizer = torch.optim.SGD([self.latents], lr=config.lr, momentum=0.0) + opt_name = "SGD" + else: + self.optimizer = torch.optim.Adam([self.latents], lr=config.lr, betas=(0.9, 0.999), eps=1e-8) + opt_name = "Adam" + + logging.info(f"✅ HunyuanSDSOptimizerInitializationcompleted (with differentiable physics support) ") + logging.info(f" - Latents shape: {self.latents.shape}") + logging.info(f" - Latents dtype: {self.latents.dtype} (optimized in float32)") + logging.info(f" - Device: {device}") + logging.info(f" - Optimizer: {opt_name}") + logging.info(f" - Learning rate: {config.lr}") + + # target_z0 EMA cache. + self.target_z0_ema = None + self.target_z0_last_velocity = None + self.target_z0_last_update = None + + def get_field(self, x: torch.Tensor, latents: torch.Tensor = None) -> torch.Tensor: + """Differentiable SDF query through the VAE geo_decoder. + + Args: + x: Query points [N, 3] in the range [-0.8, 0.8]^3. + latents: Optional latent tokens; defaults to self.latents. + + Returns: + sdf: SDF values [N] with gradient support. + """ + if latents is None: + latents = self.latents + + # Match the official pipeline: divide by scale_factor before decoding. + scale_factor = getattr(self.vae, "scale_factor", 1.0) + latents_scaled = latents / scale_factor + + # Convert to FP16 because the VAE expects FP16 inputs. + latents_fp16 = latents_scaled.to(torch.float16) + + # Decode with the VAE decoder while preserving gradients. + decoded_latents = self.vae.decode(latents_fp16) + + # Query the SDF through the differentiable helper. + # sdf_query calls geo_decoder internally, so keep FP16 to match VAE weights. + sdf = self.sdf_query( + decoded_latents, # Keep FP16 and let sdf_query handle the rest. + x, + return_occupancy=False # Return SDF instead of occupancy. + ) # [N] + + return sdf + + def _cond_batch_size(self, cond) -> Optional[int]: + if isinstance(cond, torch.Tensor): + return cond.shape[0] if cond.dim() >= 1 else None + if isinstance(cond, dict): + for v in cond.values(): + bsz = self._cond_batch_size(v) + if bsz is not None: + return bsz + if isinstance(cond, (list, tuple)): + for v in cond: + bsz = self._cond_batch_size(v) + if bsz is not None: + return bsz + return None + + def _cond_slice(self, cond, batch_slice: slice): + if isinstance(cond, torch.Tensor): + if cond.dim() >= 1 and cond.shape[0] >= batch_slice.stop: + return cond[batch_slice] + return cond + if isinstance(cond, dict): + return {k: self._cond_slice(v, batch_slice) for k, v in cond.items()} + if isinstance(cond, (list, tuple)): + return type(cond)(self._cond_slice(v, batch_slice) for v in cond) + return cond + + def _cond_repeat(self, cond, repeats: int): + if isinstance(cond, torch.Tensor): + if cond.dim() >= 1: + rep_shape = (repeats,) + (1,) * (cond.dim() - 1) + return cond.repeat(rep_shape) + return cond + if isinstance(cond, dict): + return {k: self._cond_repeat(v, repeats) for k, v in cond.items()} + if isinstance(cond, (list, tuple)): + return type(cond)(self._cond_repeat(v, repeats) for v in cond) + return cond + + def _get_cond_for_guidance(self, use_cfg: bool): + cond = self.cond + bsz = self._cond_batch_size(cond) + if use_cfg: + if bsz == 1: + if not self._cond_warned_cfg_repeat: + logging.warning("⚠️ guidance_scale>1 cond batch=1, already condCFG") + self._cond_warned_cfg_repeat = True + return self._cond_repeat(cond, 2) + if bsz is not None and bsz > 2: + return self._cond_slice(cond, slice(0, 2)) + return cond + # no-CFG + if bsz is not None and bsz >= 2: + if self.config.sds_use_uncond: + if not self._cond_warned_nocfg_slice: + logging.info("ℹ️ guidance_scale<=1, useno conditioncond[1:2]") + self._cond_warned_nocfg_slice = True + return self._cond_slice(cond, slice(1, 2)) + if not self._cond_warned_nocfg_slice: + logging.info("ℹ️ guidance_scale<=1, already usecond[0:1]batch") + self._cond_warned_nocfg_slice = True + return self._cond_slice(cond, slice(0, 1)) + if self.config.sds_use_uncond and bsz == 1 and not self._cond_warned_nocfg_slice: + logging.warning("⚠️ sds_use_uncond=1 cond batch=1, already fallback to conditself") + self._cond_warned_nocfg_slice = True + return cond + + def latents_to_mesh(self, latents: torch.Tensor, octree_res: int = 128) -> Optional[trimesh.Trimesh]: + """Decode latent tokens into a mesh. + + Args: + latents: Latent tokens [1, N, D] (float32). + octree_res: Octree resolution. 128 is faster; 256 is higher quality. + + Returns: + A trimesh.Trimesh object, or None on failure. + """ + with torch.no_grad(): + # Skip invalid latent tensors early. + if torch.isnan(latents).any() or torch.isinf(latents).any(): + logging.warning(" latents_to_mesh: latentscontains NaN or Inf, skip") + return None + + # Match the official pipeline by dividing by scale_factor first. + scale_factor = getattr(self.vae, "scale_factor", 1.0) + latents_scaled = latents / scale_factor + + # Decode in FP16 because the VAE expects FP16 inputs. + latents_fp16 = latents_scaled.to(torch.float16) + + try: + # VAE decode. + decoded_latents = self.vae.decode(latents_fp16) + + # Skip invalid decoded latents. + if torch.isnan(decoded_latents).any() or torch.isinf(decoded_latents).any(): + logging.warning(" latents_to_mesh: decoded_latentscontains NaN or Inf, skip") + return None + except Exception as e: + logging.debug(f" latents_to_mesh: VAE decodingfailed: {e}") + return None + + # Use an adaptive mc_level fallback if the default level fails. + try: + # First try the standard mc_level=0.0. + mesh = self.vae.latents2mesh( + decoded_latents, + output_type='trimesh', + bounds=1.01, + mc_level=0.0, + num_chunks=20000, + octree_resolution=octree_res, + mc_algo='mc', + enable_pbar=False + ) + mesh = export_to_trimesh(mesh)[0] + return mesh + + except ValueError as e: + error_msg = str(e) + if "Surface level must be within volume data range" in error_msg: + # Estimate a better mc_level from sampled SDF statistics. + logging.debug(f" latents_to_mesh: mc_level=0.0 failed, try an adaptive level...") + + try: + # Sample a coarse grid to estimate the SDF range. + grid_size = 32 + x = torch.linspace(-1.0, 1.0, grid_size, device=decoded_latents.device) + y = torch.linspace(-1.0, 1.0, grid_size, device=decoded_latents.device) + z = torch.linspace(-1.0, 1.0, grid_size, device=decoded_latents.device) + xx, yy, zz = torch.meshgrid(x, y, z, indexing='ij') + points = torch.stack([xx, yy, zz], dim=-1).reshape(-1, 3) # [N, 3] + + # query the SDF values. + sdf_values = self.get_field(points, latents=latents) + + # Compute basic statistics. + sdf_median = torch.median(sdf_values).item() + sdf_min = sdf_values.min().item() + sdf_max = sdf_values.max().item() + sdf_mean = sdf_values.mean().item() + + logging.debug(f" SDFstatistics: min={sdf_min:.4f}, max={sdf_max:.4f}, median={sdf_median:.4f}, mean={sdf_mean:.4f}") + + # No clear surface can be extracted if the SDF range is too small. + if abs(sdf_max - sdf_min) < 1e-4: + logging.debug(f" SDFrange is too small to extract a surface") + return None + + # Try several plausible candidate levels. + candidate_levels = [ + sdf_median, # Median. + sdf_mean, # Mean. + (sdf_min + sdf_max) / 2, # Midpoint of the range. + sdf_min + (sdf_max - sdf_min) * 0.3, # 30% point. + sdf_min + (sdf_max - sdf_min) * 0.7, # 70% point. + ] + + # Clamp all levels to the valid range. + valid_levels = [ + max(sdf_min + 0.001, min(sdf_max - 0.001, level)) + for level in candidate_levels + ] + + # Remove duplicates. + valid_levels = list(set(valid_levels)) + + logging.debug(f" try {len(valid_levels)} candidate levels: {[f'{l:.4f}' for l in valid_levels[:3]]}...") + + # Try each candidate level in order. + for i, adaptive_level in enumerate(valid_levels): + try: + mesh = self.vae.latents2mesh( + decoded_latents, + output_type='trimesh', + bounds=1.01, + mc_level=adaptive_level, + num_chunks=20000, + octree_resolution=octree_res, + mc_algo='mc', + enable_pbar=False + ) + mesh = export_to_trimesh(mesh)[0] + logging.info(f" ✅ uselevelsucceeded (level={adaptive_level:.4f}, attempt {i+1})") + return mesh + except (ValueError, RuntimeError) as level_error: + # Try the next level if this one fails. + if i < len(valid_levels) - 1: + continue + else: + # All candidate levels failed. + logging.debug(f" all candidate levels failed") + return None + + # No candidate succeeded. + return None + + except Exception as adaptive_error: + logging.debug(f" adaptive extraction failed: {type(adaptive_error).__name__}: {str(adaptive_error)[:50]}") + return None + + elif "No surface found" in error_msg: + logging.debug(f" latents_to_mesh: Marching cubesno surface found, skip") + return None + else: + logging.warning(f" latents_to_mesh: unknown ValueError: {error_msg}") + return None + + except RuntimeError as e: + error_msg = str(e) + if "No surface found" in error_msg or "Surface level" in error_msg: + logging.debug(f" latents_to_mesh: Marching cubesfailed, skip") + return None + else: + logging.warning(f" latents_to_mesh: RuntimeError: {error_msg}") + return None + + except Exception as e: + # Catch any other unexpected failure. + logging.warning(f" latents_to_mesh: unexpected exception: {type(e).__name__}: {e}") + return None + + def _filter_floating_components(self, mesh: trimesh.Trimesh) -> trimesh.Trimesh: + """Remove small floating fragments and keep only the largest component.""" + try: + components = mesh.split(only_watertight=False) + if len(components) <= 1: + return mesh + + face_counts = [len(comp.faces) for comp in components] + max_idx = int(np.argmax(face_counts)) + filtered = components[max_idx] + dropped = len(components) - 1 + + logging.info(f" 🧹 filter floating fragments: kept{len(filtered.faces)} faces, discarded{dropped} small components") + return filtered + except Exception as e: + logging.warning(f" failed to filter floating fragments: {type(e).__name__}: {str(e)[:100]}") + return mesh + + def _sample_displacement_to_vertices( + self, + vertices: np.ndarray, + nodes: np.ndarray, + displacement: np.ndarray, + ) -> np.ndarray: + """Sample the voxel-node displacement field onto mesh vertices by nearest neighbor.""" + try: + from scipy.spatial import cKDTree + tree = cKDTree(nodes) + _, idx = tree.query(vertices, k=1) + return displacement[idx] + except Exception as e: + try: + from sklearn.neighbors import NearestNeighbors + nn = NearestNeighbors(n_neighbors=1, algorithm="auto") + nn.fit(nodes) + idx = nn.kneighbors(vertices, return_distance=False).squeeze(1) + return displacement[idx] + except Exception as e2: + logging.warning(f" displacement sampling failed, fallback to zero displacement: {type(e).__name__}: {str(e)[:100]}") + logging.debug(f" secondaryError: {type(e2).__name__}: {str(e2)[:100]}") + return np.zeros_like(vertices) + + def _normalize_displacement_magnitude( + self, disp_mag: np.ndarray + ) -> Tuple[np.ndarray, float, float, bool]: + """Normalize displacement magnitude, optionally with a fixed range.""" + mag_max_cfg = getattr(self.config, "deformed_mesh_disp_max", None) + mag_min_cfg = getattr(self.config, "deformed_mesh_disp_min", None) + use_fixed = mag_max_cfg is not None and mag_max_cfg > 0.0 + if use_fixed: + mag_min = 0.0 if mag_min_cfg is None else float(mag_min_cfg) + mag_max = float(mag_max_cfg) + if mag_max <= mag_min: + use_fixed = False + if not use_fixed: + mag_min = float(disp_mag.min()) + mag_max = float(disp_mag.max()) + denom = max(1e-12, mag_max - mag_min) + norm = (disp_mag - mag_min) / denom + if use_fixed: + norm = np.clip(norm, 0.0, 1.0) + return norm, mag_min, mag_max, use_fixed + + def _make_displacement_colors(self, displacement: np.ndarray) -> np.ndarray: + """Map displacement magnitude to vertex colors (blue -> red).""" + disp_mag = np.linalg.norm(displacement, axis=1) + norm, _, _, _ = self._normalize_displacement_magnitude(disp_mag) + colors = np.stack([norm, np.zeros_like(norm), 1.0 - norm], axis=1) + return (colors * 255).astype(np.uint8) + + def _log_physical_quantities( + self, + u: torch.Tensor, + sigma: Optional[torch.Tensor], + ) -> None: + """Log displacement and von Mises stress statistics.""" + with torch.no_grad(): + u_max = None + u_avg = None + try: + u_mag = torch.norm(u, dim=1) + u_max = u_mag.max().item() + u_avg = u_mag.mean().item() + except Exception as e: + logging.warning( + f" ⚠️ displacement statistics failed: {type(e).__name__}: {str(e)[:100]}" + ) + + sigma_vm_max = None + sigma_vm_avg = None + if sigma is not None: + try: + if sigma.dim() == 2 and sigma.shape[1] >= 6: + s_xx = sigma[:, 0] + s_yy = sigma[:, 1] + s_zz = sigma[:, 2] + s_yz = sigma[:, 3] + s_xz = sigma[:, 4] + s_xy = sigma[:, 5] + mises_sq = 0.5 * ( + (s_xx - s_yy) ** 2 + + (s_yy - s_zz) ** 2 + + (s_zz - s_xx) ** 2 + + 6.0 * (s_xy ** 2 + s_yz ** 2 + s_xz ** 2) + ) + mises = torch.sqrt(torch.clamp(mises_sq, min=0.0)) + sigma_vm_max = mises.max().item() + sigma_vm_avg = mises.mean().item() + else: + logging.warning( + f" ⚠️ sigmashape does not match expectations, skip von Mises statistics: {tuple(sigma.shape)}" + ) + except Exception as e: + logging.warning( + f" ⚠️ von Mises statistics failed: {type(e).__name__}: {str(e)[:100]}" + ) + + if u_max is not None and u_avg is not None: + if sigma_vm_max is not None and sigma_vm_avg is not None: + logging.info( + f" physical metrics: u_max={u_max:.3e}, u_avg={u_avg:.3e}, " + f"sigma_vm_max={sigma_vm_max:.3e}, sigma_vm_avg={sigma_vm_avg:.3e}" + ) + else: + logging.info( + f" physical metrics: u_max={u_max:.3e}, u_avg={u_avg:.3e}" + ) + + def backward_step(self, sensitivity_density: torch.Tensor, latents=None): + """Backpropagate with VJP, aligned with the reference code. + + Reference: viewer_deepsdf.py Line 148-183. + This uses torch.autograd.functional.vjp to propagate sensitivity to latents. + """ + def f(latents: torch.Tensor): + """ + Compute occupancy from a given latent tensor. + Aligned with viewer_deepsdf.py Line 155-173. + """ + # Query the SDF. + sdf = self.get_field(self.nodes, latents) + + # SDF → occupancy + from physiopt.opt.field import occ_kernel + occ = occ_kernel(sdf, self.config.res, self.config.occ_sdf_beta) + + # Element occupancy is the average over the 8 nodes. + occ_elem = occ[self.elements].mean(1) + + # Clamp by alpha_min if requested. + if self.config.alpha_min > 0.0: + occ_elem = torch.clamp(occ_elem, self.config.alpha_min) + + return occ_elem + + # VJP computations d occ / d latents^T times the sensitivity vector. + # Aligned with viewer_deepsdf.py Line 175-180. + try: + target_latents = self.latents if latents is None else latents + + grad_latent = torch.autograd.functional.vjp( + f, + target_latents.clone().requires_grad_(True), + sensitivity_density, + )[1] + + if grad_latent is None: + logging.error(" ❌ VJP returned None!") + return + + grad_norm = torch.norm(grad_latent).item() + logging.info(f" VJP gradient: norm={grad_norm:.2e}") + + target_latents.grad = grad_latent + + if latents is None: + return True + else: + return target_latents + + except Exception as e: + logging.error(f" ❌ VJP failed: {e}") + import traceback + traceback.print_exc() + + def prepare_physical_simulation(self): + """Prepare the physical simulation and FEM solver state. + + Initialization includes: + 1. Material properties + 2. Boundary conditions + 3. External forces + """ + if not WARP_AVAILABLE: + logging.warning("Warpnot installed, skipphysics simulation preparation") + return + + if not hasattr(self, 'nodes') or not hasattr(self, 'elements'): + logging.error("please call extract_solid() to extract the solid first") + return + + logging.info("prepare physical simulation...") + + # Initialize Warp. + wp.init() + + # Normalize device names such as "cuda" and "cuda:0". + if 'cuda' in self.device: + # Extract the device id when needed. + if ':' in self.device: + device_id = self.device.split(':')[-1] + warp_device = f"cuda:{device_id}" + else: + warp_device = "cuda:0" # default to cuda:0 + else: + warp_device = "cpu" + + wp.set_device(warp_device) + logging.info(f"Warpdevice: {warp_device}") + + # Material properties. + self.E = self.config.youngs_modulus # Young's modulus. + self.nu = self.config.poissons_ratio # Poisson's ratio. + self.rho = self.config.density # Density. + + # Boundary condition: fix bottom nodes using Hunyuan's Y-up frame. + y_coords = self.nodes[:, 1] + y_min = y_coords.min() + boundary_threshold = y_min + 0.05 # 0.2 # 0.05 # Bottom 5% band. + self.boundary_mask = y_coords < boundary_threshold + + logging.info(f" coordinate system: Y-up (Hunyuan-native), fix Y < {boundary_threshold:.3f}nodes") + + # Apply load locally instead of spreading it across all nodes. + # The default heuristic targets a seat-like region in the Y-up frame. + + # Compute the total force, giving priority to force_entries. + total_force = np.zeros(3, dtype=np.float32) + force_entries = getattr(self.config, "force_entries", None) + valid_force_entries = None + if force_entries: + valid_force_entries = [] + for entry in force_entries: + if not isinstance(entry, dict): + continue + entry_force = None + if "force" in entry: + try: + entry_force = np.array(entry["force"], dtype=np.float32) + except Exception: + entry_force = None + elif "forces" in entry and isinstance(entry["forces"], list): + try: + entry_force = np.sum( + np.array(entry["forces"], dtype=np.float32), axis=0 + ) + except Exception: + entry_force = None + if entry_force is None or entry_force.shape != (3,): + continue + valid_force_entries.append(entry) + total_force += entry_force + if valid_force_entries: + self.force_entries_preset = valid_force_entries + logging.info(f" force entries: {len(valid_force_entries)}") + else: + logging.warning(" ⚠️ force_entries has no valid entries, fallback to forces") + valid_force_entries = None + + if valid_force_entries is None: + for force_config in self.config.forces: + if hasattr(force_config, 'get_total_force'): + # ForceConfig object. + total_force += force_config.get_total_force() + elif isinstance(force_config, dict) and 'external_force' in force_config: + # Compatibility format using a plain dict. + total_force += np.array(force_config['external_force'], dtype=np.float32) + else: + logging.warning(f"unknown force format: {type(force_config)}") + + logging.info(f" sum of external forces (Y-up coordinates): {total_force}") + + # Choose the loading strategy from the config. + if valid_force_entries is not None: + # Multiple localized loads, each with its own region. + self._setup_local_loading(total_force) + elif self.config.use_local_loading: + # Preferred mode: local loading. + self._setup_local_loading(total_force) + else: + # Fallback mode: global uniform loading. + logging.info(f" ℹ️ using global uniform loading mode") + total_force_tensor = torch.from_numpy(total_force).float().to(self.device) + num_nodes = self.nodes.shape[0] + self.forces = total_force_tensor[None, :].repeat(num_nodes, 1) + logging.info(f" 💨 distributed the total force uniformly to{num_nodes}nodes") + + logging.info(f"boundary conditions: {self.boundary_mask.sum().item()}fixed nodes") + logging.info(f"material properties: E={self.E:.2e}, ν={self.nu}, ρ={self.rho}") + + def _setup_local_loading(self, total_force: np.ndarray): + """Set up local loading on the selected seat/contact region. + + The total force is distributed uniformly across the selected nodes so + that sum(forces) equals total_force. + + Args: + total_force: Total force vector [3] in the Y-up frame, in Newtons. + """ + # Cache the total force for later updates. + self.total_force_preset = torch.from_numpy(total_force).float().to(self.device) + + # Reuse the generic update routine for the initial setup. + self._update_forces(initial_setup=True) + + def _update_forces(self, initial_setup: bool = False): + """Update the force distribution for the current mesh state. + + Core logic: + 1. Re-identify contact nodes + 2. Spread the preset total force uniformly over those nodes + 3. Keep total force conserved + + Args: + initial_setup: Whether this is the first setup pass. + """ + if not hasattr(self, 'total_force_preset'): + logging.warning("No preset total force is set, so the force distribution cannot be updated") + return + + # Step 1: inspect the Y-coordinate distribution. + y_coords = self.nodes[:, 1] + num_nodes = self.nodes.shape[0] + + force_entries = getattr(self, "force_entries_preset", None) + if force_entries: + def _select_nodes_for_mode(mode, top_percent, min_ratio, max_ratio, bbox, bbox_ratio): + seat_mask = torch.zeros(num_nodes, dtype=torch.bool, device=self.device) + mode_used = mode + bbox_desc = None + + if mode_used not in ("top_percent", "height_ratio", "bbox", "global"): + logging.warning(f" ⚠️ invalid force_region_mode: {mode_used}, fallback to top_percent") + mode_used = "top_percent" + + if mode_used == "global": + seat_mask[:] = True + return seat_mask, mode_used, bbox_desc + + if mode_used == "bbox": + bbox_vals = None + if bbox is not None and len(bbox) == 6: + bbox_vals = [float(v) for v in bbox] + bbox_desc = "abs" + elif bbox_ratio is not None and len(bbox_ratio) == 6: + bbox_ratio_vals = [float(v) for v in bbox_ratio] + bounds_min = self.nodes.min(dim=0).values + bounds_max = self.nodes.max(dim=0).values + bbox_vals = [ + bounds_min[0].item() + bbox_ratio_vals[0] * (bounds_max[0] - bounds_min[0]).item(), + bounds_min[0].item() + bbox_ratio_vals[1] * (bounds_max[0] - bounds_min[0]).item(), + bounds_min[1].item() + bbox_ratio_vals[2] * (bounds_max[1] - bounds_min[1]).item(), + bounds_min[1].item() + bbox_ratio_vals[3] * (bounds_max[1] - bounds_min[1]).item(), + bounds_min[2].item() + bbox_ratio_vals[4] * (bounds_max[2] - bounds_min[2]).item(), + bounds_min[2].item() + bbox_ratio_vals[5] * (bounds_max[2] - bounds_min[2]).item(), + ] + bbox_desc = "ratio" + else: + logging.warning(" ⚠️ bbox mode did not provide a valid bbox, fallback to top_percent") + mode_used = "top_percent" + + if mode_used == "bbox" and bbox_vals is not None: + x0, x1 = sorted([bbox_vals[0], bbox_vals[1]]) + y0, y1 = sorted([bbox_vals[2], bbox_vals[3]]) + z0, z1 = sorted([bbox_vals[4], bbox_vals[5]]) + seat_mask = ( + (self.nodes[:, 0] >= x0) & (self.nodes[:, 0] <= x1) + & (self.nodes[:, 1] >= y0) & (self.nodes[:, 1] <= y1) + & (self.nodes[:, 2] >= z0) & (self.nodes[:, 2] <= z1) + ) + if seat_mask.sum().item() < 1: + logging.warning(" ⚠️ bbox region matched no nodes, fallback to top_percent") + mode_used = "top_percent" + else: + bbox_desc = f"{bbox_desc}: [{x0:.3f},{x1:.3f}]x[{y0:.3f},{y1:.3f}]x[{z0:.3f},{z1:.3f}]" + + if mode_used == "height_ratio": + y_min = y_coords.min().item() + y_max = y_coords.max().item() + y_range = max(1e-8, y_max - y_min) + if not (0.0 <= min_ratio < max_ratio <= 1.0): + logging.warning( + f" ⚠️ invalid height_ratio: min={min_ratio}, max={max_ratio}, fallback to top_percent" + ) + mode_used = "top_percent" + else: + seat_y_min = y_min + y_range * min_ratio + seat_y_max = y_min + y_range * max_ratio + seat_mask = (y_coords >= seat_y_min) & (y_coords <= seat_y_max) + if seat_mask.sum().item() < 1: + logging.warning(" ⚠️ height_ratio matched no nodes, fallback to top_percent") + mode_used = "top_percent" + + if mode_used == "top_percent": + top_percent = float(top_percent) + top_percent = max(0.0, min(1.0, top_percent)) + if top_percent <= 0.0: + top_percent = 0.05 + num_seat_nodes = max(1, int(num_nodes * top_percent)) + _, top_indices = torch.topk(y_coords, k=num_seat_nodes, largest=True) + seat_mask = torch.zeros(num_nodes, dtype=torch.bool, device=self.device) + seat_mask[top_indices] = True + + return seat_mask, mode_used, bbox_desc + + self.forces = torch.zeros((num_nodes, 3), dtype=torch.float32, device=self.device) + combined_mask = torch.zeros(num_nodes, dtype=torch.bool, device=self.device) + total_force = torch.zeros(3, dtype=torch.float32, device=self.device) + + for idx, entry in enumerate(force_entries): + if not isinstance(entry, dict): + continue + entry_label = entry.get("label") or entry.get("name") or f"{idx+1}" + entry_force = None + if "forces" in entry and isinstance(entry["forces"], list): + try: + entry_force = np.sum(np.array(entry["forces"], dtype=np.float32), axis=0) + except Exception: + entry_force = None + if entry_force is None and "force" in entry: + try: + entry_force = np.array(entry["force"], dtype=np.float32) + except Exception: + entry_force = None + if entry_force is None or entry_force.shape != (3,): + logging.warning(f" ⚠️ invalid force entry[{entry_label}], skip") + continue + + entry_force_tensor = torch.from_numpy(entry_force).float().to(self.device) + total_force += entry_force_tensor + + mode = str(entry.get("force_region_mode", self.config.force_region_mode)).lower() + if entry.get("global_loading") is True: + mode = "global" + + top_percent = entry.get("force_top_percent", self.config.force_top_percent) + min_ratio = entry.get("seat_height_min_ratio", self.config.seat_height_min_ratio) + max_ratio = entry.get("seat_height_max_ratio", self.config.seat_height_max_ratio) + bbox = entry.get("force_bbox", self.config.force_bbox) + bbox_ratio = entry.get("force_bbox_ratio", self.config.force_bbox_ratio) + + seat_nodes_mask, mode_used, bbox_desc = _select_nodes_for_mode( + mode, top_percent, min_ratio, max_ratio, bbox, bbox_ratio + ) + + num_seat_nodes = int(seat_nodes_mask.sum().item()) + if num_seat_nodes < 1: + logging.warning(f" ⚠️ entry[{entry_label}]matched no nodes, skip") + continue + + force_per_node = entry_force_tensor / num_seat_nodes + self.forces[seat_nodes_mask] += force_per_node + combined_mask |= seat_nodes_mask + + seat_y_values = y_coords[seat_nodes_mask] + seat_y_min = seat_y_values.min().item() + seat_y_max = seat_y_values.max().item() + seat_y_mean = seat_y_values.mean().item() + + if initial_setup: + if mode_used == "bbox": + logging.info(f" 🪑 contact surface[{entry_label}]: bbox ({bbox_desc})") + elif mode_used == "height_ratio": + logging.info( + f" 🪑 contact surface[{entry_label}]: height_ratio " + f"[{min_ratio:.2f}, {max_ratio:.2f}]" + ) + elif mode_used == "global": + logging.info(f" 🪑 contact surface[{entry_label}]: global") + else: + logging.info( + f" 🪑 contact surface[{entry_label}]: highest-Y {float(top_percent):.1%} nodes" + ) + logging.info( + f" 🪑 seat-node count[{entry_label}]: {num_seat_nodes}/{num_nodes} " + f"({num_seat_nodes/num_nodes:.1%})" + ) + logging.info( + f" 🪑 Y range[{entry_label}]: [{seat_y_min:.3f}, {seat_y_max:.3f}], " + f"mean: {seat_y_mean:.3f}" + ) + logging.info(f" 💺 force[{entry_label}]: {entry_force}") + logging.info(f" 💺 per node[{entry_label}]: {force_per_node.cpu().numpy()}") + + self.total_force_preset = total_force + actual_total_force = self.forces.sum(dim=0) + force_error = torch.norm(actual_total_force - total_force).item() + force_error_percent = (force_error / (torch.norm(total_force).item() + 1e-10)) * 100 + + if initial_setup: + logging.info( + f" ✅ total-force check: {actual_total_force.cpu().numpy()} " + f"(error: {force_error:.2e}, {force_error_percent:.3f}%)" + ) + if combined_mask.any(): + self._save_force_visualization( + combined_mask, total_force.cpu().numpy() + ) + else: + logging.debug( + f" 🔄 force update: loaded nodes {int(combined_mask.sum().item())}, " + f"total force error {force_error:.2e}" + ) + + self._last_num_seat_nodes = int(combined_mask.sum().item()) + return + + # Contact-region selection supports top_percent / height_ratio / bbox. + mode = str(getattr(self.config, "force_region_mode", "top_percent")).lower() + seat_nodes_mask = torch.zeros(num_nodes, dtype=torch.bool, device=self.device) + mode_used = mode + bbox_desc = None + if mode_used not in ("top_percent", "height_ratio", "bbox"): + logging.warning(f" ⚠️ invalid force_region_mode: {mode_used}, fallback to top_percent") + mode_used = "top_percent" + + if mode_used == "bbox": + bbox = getattr(self.config, "force_bbox", None) + bbox_ratio = getattr(self.config, "force_bbox_ratio", None) + bbox_vals = None + if bbox is not None and len(bbox) == 6: + bbox_vals = [float(v) for v in bbox] + bbox_desc = "abs" + elif bbox_ratio is not None and len(bbox_ratio) == 6: + bbox_ratio_vals = [float(v) for v in bbox_ratio] + bounds_min = self.nodes.min(dim=0).values + bounds_max = self.nodes.max(dim=0).values + bbox_vals = [ + bounds_min[0].item() + bbox_ratio_vals[0] * (bounds_max[0] - bounds_min[0]).item(), + bounds_min[0].item() + bbox_ratio_vals[1] * (bounds_max[0] - bounds_min[0]).item(), + bounds_min[1].item() + bbox_ratio_vals[2] * (bounds_max[1] - bounds_min[1]).item(), + bounds_min[1].item() + bbox_ratio_vals[3] * (bounds_max[1] - bounds_min[1]).item(), + bounds_min[2].item() + bbox_ratio_vals[4] * (bounds_max[2] - bounds_min[2]).item(), + bounds_min[2].item() + bbox_ratio_vals[5] * (bounds_max[2] - bounds_min[2]).item(), + ] + bbox_desc = "ratio" + else: + logging.warning(" ⚠️ bbox mode did not provide a valid bbox, fallback to top_percent") + mode_used = "top_percent" + + if mode_used == "bbox" and bbox_vals is not None: + x0, x1 = sorted([bbox_vals[0], bbox_vals[1]]) + y0, y1 = sorted([bbox_vals[2], bbox_vals[3]]) + z0, z1 = sorted([bbox_vals[4], bbox_vals[5]]) + seat_nodes_mask = ( + (self.nodes[:, 0] >= x0) & (self.nodes[:, 0] <= x1) + & (self.nodes[:, 1] >= y0) & (self.nodes[:, 1] <= y1) + & (self.nodes[:, 2] >= z0) & (self.nodes[:, 2] <= z1) + ) + if seat_nodes_mask.sum().item() < 1: + logging.warning(" ⚠️ bbox region matched no nodes, fallback to top_percent") + mode_used = "top_percent" + else: + bbox_desc = f"{bbox_desc}: [{x0:.3f},{x1:.3f}]x[{y0:.3f},{y1:.3f}]x[{z0:.3f},{z1:.3f}]" + + if mode_used == "height_ratio": + y_min = y_coords.min().item() + y_max = y_coords.max().item() + y_range = max(1e-8, y_max - y_min) + min_ratio = float(self.config.seat_height_min_ratio) + max_ratio = float(self.config.seat_height_max_ratio) + if not (0.0 <= min_ratio < max_ratio <= 1.0): + logging.warning( + f" ⚠️ invalid height_ratio: min={min_ratio}, max={max_ratio}, fallback to top_percent" + ) + mode_used = "top_percent" + else: + seat_y_min = y_min + y_range * min_ratio + seat_y_max = y_min + y_range * max_ratio + seat_nodes_mask = (y_coords >= seat_y_min) & (y_coords <= seat_y_max) + if seat_nodes_mask.sum().item() < 1: + logging.warning(" ⚠️ height_ratio matched no nodes, fallback to top_percent") + mode_used = "top_percent" + + if mode_used == "top_percent": + top_percent = float(getattr(self.config, "force_top_percent", 0.05)) + top_percent = max(0.0, min(1.0, top_percent)) + if top_percent <= 0.0: + top_percent = 0.05 + num_seat_nodes = max(1, int(num_nodes * top_percent)) + _, top_indices = torch.topk(y_coords, k=num_seat_nodes, largest=True) + seat_nodes_mask = torch.zeros(num_nodes, dtype=torch.bool, device=self.device) + seat_nodes_mask[top_indices] = True + + num_seat_nodes = int(seat_nodes_mask.sum().item()) + + # Step 3: gather region statistics. + seat_y_values = y_coords[seat_nodes_mask] + seat_y_min = seat_y_values.min().item() + seat_y_max = seat_y_values.max().item() + seat_y_mean = seat_y_values.mean().item() + + # Step 4: computation the per-node load with uniform distribution. + force_per_node = self.total_force_preset / num_seat_nodes + + # Initialize all node forces to zero. + self.forces = torch.zeros((num_nodes, 3), dtype=torch.float32, device=self.device) + + # Apply force only to the selected seat/contact nodes. + self.forces[seat_nodes_mask] = force_per_node + + # Step 5: verify total-force conservation. + actual_total_force = self.forces.sum(dim=0) + force_error = torch.norm(actual_total_force - self.total_force_preset).item() + force_error_percent = (force_error / torch.norm(self.total_force_preset).item()) * 100 + + # Logging. + if initial_setup: + if mode_used == "bbox": + logging.info(f" 🪑 contact-surface setup: bbox ({bbox_desc})") + elif mode_used == "height_ratio": + logging.info( + f" 🪑 contact-surface setup: height_ratio " + f"[{self.config.seat_height_min_ratio:.2f}, {self.config.seat_height_max_ratio:.2f}]" + ) + else: + logging.info( + f" 🪑 contact-surface setup: highest-Y {float(getattr(self.config, 'force_top_percent', 0.05)):.1%} nodes" + ) + logging.info(f" 🪑 seat-node count: {num_seat_nodes}/{num_nodes} ({num_seat_nodes/num_nodes:.1%})") + logging.info(f" 🪑 Y-coordinate range: [{seat_y_min:.3f}, {seat_y_max:.3f}], mean: {seat_y_mean:.3f}") + logging.info(f" 💺 preset total force: {self.total_force_preset.cpu().numpy()}") + logging.info(f" 💺 force per node: {force_per_node.cpu().numpy()}") + logging.info(f" ✅ total-force check: {actual_total_force.cpu().numpy()} (error: {force_error:.2e}, {force_error_percent:.3f}%)") + + # Estimate the equivalent pressure. + y_range = y_coords.max().item() - y_coords.min().item() + grid_spacing = y_range / self.config.res if y_range > 0 else 0.01 + estimated_area = num_seat_nodes * (grid_spacing ** 2) + if estimated_area > 0 and abs(self.total_force_preset[1].item()) > 0: + pressure_kpa = abs(self.total_force_preset[1].item()) / estimated_area / 1000 + logging.info(f" 📏 equivalent pressure: {pressure_kpa:.1f} kPa (contact area≈{estimated_area:.4f} m²)") + + if pressure_kpa < 5: + logging.warning(f" ⚠️ pressure is too small ({pressure_kpa:.1f} kPa < 5 kPa)") + elif pressure_kpa > 50: + logging.warning(f" ⚠️ pressure is too large ({pressure_kpa:.1f} kPa > 50 kPa)") + + # Save visualization data. + self._save_force_visualization(seat_nodes_mask, self.total_force_preset.cpu().numpy()) + else: + # Shorter logging during optimization. + logging.debug(f" 🔄 force update: seat nodes {num_seat_nodes}, per node {force_per_node.cpu().numpy()}, " + f"total force error {force_error:.2e}") + + # Watch for changes in the number of loaded nodes. + if hasattr(self, '_last_num_seat_nodes') and self._last_num_seat_nodes != num_seat_nodes: + logging.info(f" ⚠️ seat-node count changed: {self._last_num_seat_nodes} → {num_seat_nodes}") + + # Cache the current state for the next comparison. + self._last_num_seat_nodes = num_seat_nodes + + def extract_solid(self, step: int = -1): + """Extract the physical solid by querying the node SDF directly. + + This method rebuilds the FEM mesh from the current latents so topology + changes in the SDF field can be reflected by the simulation mesh. + + Args: + step: Current optimization step, used for logging. + """ + if not WARP_AVAILABLE: + logging.warning("Warpnot installed, unable toperformphysics simulation") + return + + # Re-check physiopt availability at runtime. + try: + from physiopt.utils.phys_utils import generate_hex as _generate_hex + from physiopt.utils.grid_utils import filter_one_component as _filter_one_component + from physiopt.opt.field import occ_kernel as _occ_kernel + generate_hex_func = _generate_hex + filter_one_component_func = _filter_one_component + occ_kernel_func = _occ_kernel + logging.info("✅ physioptmoduleruntime check succeeded") + except ImportError as e: + logging.error(f"physioptmodulenot installed: {e}") + logging.error("please make sure physiopt is installed correctly: cd /mnt/cvlab/scratch/cvlab/home/hantzhan/physiopt && pip install -e .") + return + + res = self.config.res + step_label = f"Step {step}" if step >= 0 else "Initialization" + logging.info(f"{'🔄' if step >= 0 else '🆕'} [{step_label}] generate/update a mesh at resolution {res} hexahedral mesh...") + + # Keep the previous mesh size for comparison. + old_num_nodes = len(self.nodes) if hasattr(self, 'nodes') else 0 + old_num_elements = len(self.elements) if hasattr(self, 'elements') else 0 + + # 1. Generate the full hexahedral grid. + full_nodes, full_elements = generate_hex_func( + res=res, + limits=[(-0.8, 0.8), (-0.8, 0.8), (-0.8, 0.8)], + device=self.device, + return_coords=False + ) + + if full_nodes is None or full_elements is None: + logging.error("failed to generate the hexahedral mesh") + return + + full_nodes = full_nodes.to(self.device).float() + full_elements = full_elements.to(self.device).long() + + logging.info(f"hexahedral mesh generated successfully: {full_nodes.shape[0]}nodes, {full_elements.shape[0]}elements") + + # 2. Query the SDF directly through get_field. + logging.info("query node SDF values...") + sdf = self.get_field(full_nodes) + + # Make sure the SDF is a 1D tensor [N]. + if sdf.dim() > 1: + logging.warning(f"⚠️ SDFYesmulti-dimensional tensor: {sdf.shape}, will be flattened to 1D") + sdf = sdf.squeeze() # remove all size-1 dimensions + if sdf.dim() > 1: + sdf = sdf.reshape(-1) # force-flatten to 1D + + logging.info(f" ✅ SDF query succeeded: range=[{sdf.min():.3f}, {sdf.max():.3f}]") + logging.info(f" nodescount: {full_nodes.shape[0]}, SDF count: {sdf.shape[0]}") + + # Verify that the SDF count matches the node count. + if sdf.shape[0] != full_nodes.shape[0]: + logging.error(f"❌ SDF count({sdf.shape[0]}) vs. node count ({full_nodes.shape[0]})do not match!") + return + + # 3. Convert SDF values to occupancy. + logging.info("convert the SDF into an occupancy field...") + occ = occ_kernel_func(sdf, res, self.config.occ_sdf_beta) + + # 4. Select solid elements using an SDF threshold instead of an + # occupancy threshold. The threshold is intentionally relaxed so thin + # structures such as chair legs are kept. + SDF_FILTER_VALUE = 2.0 / res + nodewise_mask = sdf <= SDF_FILTER_VALUE + + # Diagnostic SDF statistics. + sdf_inside = sdf[nodewise_mask] + sdf_outside = sdf[~nodewise_mask] + logging.info(f" SDF threshold: {SDF_FILTER_VALUE:.4f}") + logging.info(f" interior nodes: {nodewise_mask.sum().item()}/{len(sdf)} ({100*nodewise_mask.sum().item()/len(sdf):.1f}%)") + if len(sdf_inside) > 0: + logging.info(f" inner SDF range: [{sdf_inside.min():.4f}, {sdf_inside.max():.4f}]") + if len(sdf_outside) > 0: + logging.info(f" outside-SDF range: [{sdf_outside.min():.4f}, {sdf_outside.max():.4f}]") + + # Debug the element-index range. + max_elem_idx = full_elements.max().item() + num_nodes = full_nodes.shape[0] + logging.info(f" elementsindex range: [0, {max_elem_idx}], nodescount: {num_nodes}") + + if max_elem_idx >= num_nodes: + logging.error(f"❌ index out of bounds!maximum element index({max_elem_idx}) >= nodescount({num_nodes})") + logging.error(f" this may be a problem with generate_hex") + # Clamp indices to the valid range. + valid_mask = (full_elements >= 0) & (full_elements < num_nodes) + if not valid_mask.all(): + logging.warning(f" found{(~valid_mask).sum().item()} invalid indices; filtering elements") + # Keep only elements whose node indices are all valid. + valid_elements_mask = valid_mask.all(dim=1) + full_elements = full_elements[valid_elements_mask] + logging.info(f" element count after filtering: {full_elements.shape[0]}") + + # Keep an element if any of its nodes passes the threshold. + elementwise_mask = torch.any(nodewise_mask[full_elements], dim=1) + + num_solid_elements = elementwise_mask.sum().item() + logging.info(f"SDF thresholdfiltering: {num_solid_elements}/{len(elementwise_mask)} solid elements") + + if num_solid_elements == 0: + logging.error("No solid elements were found; please check the SDF or adjust the threshold") + return + + # 5. Optionally keep only one connected component. + if self.config.one_cc_only: + element_res = res - 1 + try: + num_before_filter = elementwise_mask.sum().item() + elementwise_mask = filter_one_component_func(elementwise_mask, element_res) + num_filtered_elements = elementwise_mask.sum().item() + num_removed = num_before_filter - num_filtered_elements + logging.info(f"connectivity filtering: {num_filtered_elements} elements kept (removed{num_removed} small components)") + if num_removed > num_filtered_elements * 0.1: + logging.warning(f" ⚠️ removed{num_removed}elements({100*num_removed/num_before_filter:.1f}%), may have filtered out important parts (such as chair legs) ") + logging.warning(f" Suggestion: check the SDF threshold or consider disabling one_cc_only") + except IndexError as e: + logging.warning(f"connectivity filteringfailed: {e}, using the original mask") + else: + logging.info("connectivity filteringdisabled, keep all connected components") + + # 6. Select the active elements and nodes. + selected_elements = full_elements[elementwise_mask] + selected_node_indices, selected_elements = torch.unique( + selected_elements, return_inverse=True + ) + + self.elements = selected_elements + self.nodes = full_nodes[selected_node_indices] + + # 7. Compute occupancy for the selected nodes used in the simulation. + coarse_sdf = sdf[selected_node_indices] + coarse_occ_nodes = occ_kernel_func( + coarse_sdf, self.config.res, self.config.occ_sdf_beta + ) + # Each element occupancy is the mean over its 8 nodes. + self.coarse_occ = coarse_occ_nodes[self.elements].mean(1) + + # Diagnostic statistics for mesh-size changes. + new_num_nodes = len(self.nodes) + new_num_elements = len(self.elements) + + if old_num_nodes > 0: + node_change = new_num_nodes - old_num_nodes + element_change = new_num_elements - old_num_elements + node_change_pct = (node_change / old_num_nodes) * 100 + element_change_pct = (element_change / old_num_elements) * 100 + + logging.info(f"✅ solid extraction completed:") + logging.info(f" nodes: {old_num_nodes} → {new_num_nodes} ({node_change:+d}, {node_change_pct:+.1f}%)") + logging.info(f" elements: {old_num_elements} → {new_num_elements} ({element_change:+d}, {element_change_pct:+.1f}%)") + + if node_change > 0: + logging.info(f" ✅ mesh expanded!added{node_change}nodes (chair legs may have thickened) ") + elif node_change < 0: + logging.warning(f" ⚠️ mesh shrank!removed{-node_change}nodes (chair legs may have become thinner) ") + else: + logging.info(f"✅ solid extraction succeeded: {new_num_nodes}nodes, {new_num_elements}elements") + + # 8. Recomputation the boundary mask because the node count may change. + y_coords = self.nodes[:, 1] + y_min = y_coords.min() + boundary_threshold = y_min + 0.05 # bottom 5% region + self.boundary_mask = y_coords < boundary_threshold + + num_boundary = self.boundary_mask.sum().item() + logging.debug(f" 🔧 boundary conditionsupdated: {num_boundary}fixed nodes (Y < {boundary_threshold:.3f})") + + def get_current_sds_weight(self, step: int) -> float: + """Return the current SDS weight by linear interpolation. + + Args: + step: Current optimization step. + + Returns: + The SDS weight interpolated from sds_weight_start to sds_weight_end. + """ + # Linear interpolation from sds_weight_start to sds_weight_end. + progress = min(1.0, step / max(1, self.config.num_steps - 1)) + current_weight = self.config.sds_weight_start + progress * (self.config.sds_weight_end - self.config.sds_weight_start) + return current_weight + + def flow_matching_with_guidance(self, step: int, guidance_value: float, lambda_guidance: float) -> Tuple[torch.Tensor, torch.Tensor]: + """Compute the current target_z0 for one update.""" + if step == 0: + noise_level = float(0) + compliance_mean = 0 + u_mean = 0 + z_curr = self.latents + diff = 0 + else: + noise_level = float(self.config.sds_timestep) + t = 1.0 - noise_level # Hunyuan3D-2.1 uses t=0 for noise and t=1 for data. + epsilon = torch.randn_like(self.latents) + + self.sds_scheduler.config.num_train_timesteps = 100 + if self.sds_scheduler is not None: + # Match the official Flow Matching noise process: + # x_t = (1 - sigma) * x0 + sigma * eps. + sigma_step = 1.0 / float(self.sds_scheduler.config.num_train_timesteps) + total_span = max(0.0, 1.0 - t) + num_steps = int(np.ceil(total_span / sigma_step)) + sigmas = np.linspace(t, 1.0, num_steps + 1, dtype=np.float32) + self.sds_scheduler.set_timesteps(sigmas=sigmas, device=self.device) + t_scheds = self.sds_scheduler.timesteps + t_sched0 = t_scheds[0] + t_model0 = (t_sched0 / self.sds_scheduler.config.num_train_timesteps).to(self.latents.dtype) + if step % max(1, int(self.config.sds_target_z0_update_interval)) == 0: + logging.info( + f" 🎯 target_z0/sigmaalign: noise={noise_level:.4f}, t_start={t:.4f}, " + f"t_sched={t_sched0.item():.2f}, t_model={t_model0.item():.6f}, " + f"steps={num_steps}, sigma_step={sigma_step:.4g}" + ) + else: + t_sched = None + z_t = (1 - t) * epsilon + t * self.latents + t_model = torch.tensor([t], device=self.device, dtype=self.latents.dtype) + + with torch.no_grad(): + # Integrate over multiple small sigma steps from sigma=t to 0. + cond_for_model = self._get_cond_for_guidance(self.config.guidance_scale > 1.0) + t_sched0 = t_scheds[0] + t_sched_batch = t_sched0.reshape(1).expand(self.latents.shape[0]) + # Hunyuan3D convention: t=0 is noise and t=1 is data. + z_t = self.sds_scheduler.scale_noise(epsilon, t_sched_batch, noise=self.latents) + z_curr = z_t + velocity = None + + logging.info(f"Starting Guided projection with {len(t_scheds) - 1} steps") + for i in range(len(t_scheds) - 1): + + t_sched = t_scheds[i] + t_model = (t_sched / self.sds_scheduler.config.num_train_timesteps).to(self.latents.dtype) + z_t_fp16 = z_curr.to(torch.float16) + t_tensor = t_model.to(device=self.device, dtype=z_t_fp16.dtype) + + if self.config.guidance_scale > 1.0: + latent_model_input = torch.cat([z_t_fp16, z_t_fp16]) + timestep_input = t_tensor.expand(latent_model_input.shape[0]) + + velocity_pred_fp16 = self.flow_model( + latent_model_input, + timestep_input, + cond_for_model, + guidance=None, + ) + + velocity_cond_fp16, velocity_uncond_fp16 = velocity_pred_fp16.chunk(2) + velocity_fp16 = velocity_uncond_fp16 + self.config.guidance_scale * (velocity_cond_fp16 - velocity_uncond_fp16) + + if step % 10 == 0 and i == 0: + logging.debug( + f" CFG (SDS): guidance_scale={self.config.guidance_scale:.1f}, " + f"||v_cond||={torch.norm(velocity_cond_fp16).item():.3e}, " + f"||v_uncond||={torch.norm(velocity_uncond_fp16).item():.3e}" + ) + else: + velocity_fp16 = self.flow_model( + z_t_fp16, + t_tensor.expand(z_t_fp16.shape[0]), + cond_for_model, + guidance=None, + ) + + velocity = velocity_fp16.to(torch.float32) + z_curr = self.sds_scheduler.step(velocity, t_sched, z_curr).prev_sample + + # ============= Step 2: update occupancy on the fixed topology ====== + sdf = self.get_field(self.nodes, latents=z_curr) + occ = occ_kernel(sdf, self.config.res, self.config.occ_sdf_beta) + self.coarse_occ = occ[self.elements].mean(1) + + # =============== Step 3: physics simulation (with torch.no_grad) ============ + with torch.no_grad(): + if self.config.alpha_min > 0.0: + self.coarse_occ = torch.clamp(self.coarse_occ, self.config.alpha_min) + + from torchfem.materials import IsotropicElasticity3D + from physiopt.opt.solid_grid import SolidGrid + + vectorized_material = IsotropicElasticity3D( + E=self.config.youngs_modulus, + nu=self.config.poissons_ratio, + rho=self.config.density, + ).vectorize(self.elements.shape[0]) + + vectorized_material.C *= ( + self.coarse_occ[:, None, None] ** self.config.p_exponent + ) + + solid = SolidGrid(self.nodes, self.elements, vectorized_material) + solid.constraints[self.boundary_mask, :] = True + solid.forces = self.forces + + # 3.2 FEM solve. + logging.info(f"Step {i}: FEM solve...") + u, f_int, f_ext, sigma, _, _ = solid.solve(max_iter=1) + u_mean = torch.abs(u).mean().item() + logging.info(f" |u|_mean={u_mean}") + self._log_physical_quantities(u, sigma) + + # ==================== Step 4: sensitivity computation ==================== + k0 = solid.k0() + u_j = u[self.elements].reshape(solid.n_elem, -1) + w_k_scaled = torch.einsum("...i, ...ij, ...j", u_j, k0, u_j) + occ_power = torch.clamp( + self.coarse_occ ** self.config.p_exponent, + min=1e-6, # Avoid division by zero. + max=1.0 # Avoid overflow. + ) + if torch.any(occ_power < 1e-6): + n_small = (occ_power < 1e-6).sum().item() + logging.warning(f" ⚠️ {n_small} elements have extremely small occ^p and were clamped to 1e-6") + w_k_base = w_k_scaled / occ_power + if torch.isnan(w_k_base).any() or torch.isinf(w_k_base).any(): + n_nan = torch.isnan(w_k_base).sum().item() + n_inf = torch.isinf(w_k_base).sum().item() + logging.error(f" ❌ w_k_baseabnormal: {n_nan} NaN, {n_inf} Inf") + logging.error(f" fall back to SIMP weightingw_k") + w_k_base = w_k_scaled + compliance_mean = w_k_base.mean().item() + w_k = w_k_base # Downstream sensitivity uses the recovered energy. + logging.info(f" Compliance (true) ={compliance_mean:.2e}") + + diff = compliance_mean - guidance_value + logging.info(f" Error ={diff:.2e}") + + self.sensitivity_density = ( + -self.config.p_exponent + * self.coarse_occ ** (self.config.p_exponent - 1) + * w_k + ) + + z_curr = z_curr.detach() + + raw_input = diff * self.sensitivity_density + max_abs_val = raw_input.abs().max() + if max_abs_val > 100.0: + safe_input = (raw_input / max_abs_val) * 100.0 + logging.info(f" 🗜️ Scaling Anti-NaN : max {max_abs_val:.2e} to 100.0") + else: + safe_input = raw_input + + # ==================== Step 5: backward pass via VJP ==================== + with torch.enable_grad(): + # self.backward_step(diff * self.sensitivity_density, latents=z_curr) + z_curr = self.backward_step(safe_input, latents=z_curr) + + # self.save_mesh(step=i, output_dir="output/hunyuan_gen/0001/sdedit_physiopt_64_180", high_quality=True, suffix="test", latents=z_curr) + # ==================== Step 6: optimization step ==================== + with torch.no_grad(): + z_curr = z_curr - lambda_guidance * z_curr.grad + + return z_curr, compliance_mean, u_mean, diff + + + def training_step( + self, + step: int, + lagrange: float, + rho: float, + use_sds: bool = True, + save_step: Optional[int] = None, + ) -> Tuple[float, float, float]: + """Physics optimization. + + This follows the computation_phys_loss_grad flow from viewer_base.py: + 1. optimizer.zero_grad() + 2. with torch.no_grad(): prepare_solid() + solve() + 3. Compute sensitivities with the reference-style formula + 4. backward_step() via VJP + 5. Apply ALM weighting (lambda + rho[g]_+) + 6. optimizer.step() + + Reference: + physiopt/src/physiopt/vis/viewer_base.py Line 1297-1430 + """ + save_step_id = step if save_step is None else int(save_step) + + # ==================== Step 1: zero gradients ==================== + self.optimizer.zero_grad() + + # ==================== Step 2: update occupancy on the fixed topology ==================== + if step > 0: + logging.info(f"🔄 [Step {step}] update occupancy (mesh topology fixed) ...") + # Keep the previous occupancy for diagnostics. + old_occ = self.coarse_occ.clone() + + # Re-query the SDF and occupancy on the fixed mesh. + sdf = self.get_field(self.nodes) + from physiopt.opt.field import occ_kernel + occ = occ_kernel(sdf, self.config.res, self.config.occ_sdf_beta) + self.coarse_occ = occ[self.elements].mean(1) + + # Diagnose occupancy changes. + occ_change = self.coarse_occ - old_occ + occ_mean_change = occ_change.mean().item() + occ_increase_ratio = (occ_change > 0).float().mean().item() + + logging.info(f" occupancy range: [{self.coarse_occ.min():.3f}, {self.coarse_occ.max():.3f}]") + logging.info(f" occupancy change: mean={occ_mean_change:+.3e}, increase ratio={occ_increase_ratio:.1%}") + + # ==================== Step 3: physics simulation (with torch.no_grad) ==================== + # Aligned with the reference flow around Line 1317-1356. + with torch.no_grad(): + # 3.1 prepare_solid: apply SIMP scaling and build SolidGrid. + if self.config.alpha_min > 0.0: + self.coarse_occ = torch.clamp(self.coarse_occ, self.config.alpha_min) + + # Material SIMP scaling. + from torchfem.materials import IsotropicElasticity3D + from physiopt.opt.solid_grid import SolidGrid + + vectorized_material = IsotropicElasticity3D( + E=self.config.youngs_modulus, + nu=self.config.poissons_ratio, + rho=self.config.density, + ).vectorize(self.elements.shape[0]) + + vectorized_material.C *= ( + self.coarse_occ[:, None, None] ** self.config.p_exponent + ) + + # Create the SolidGrid solver state. + solid = SolidGrid(self.nodes, self.elements, vectorized_material) + solid.constraints[self.boundary_mask, :] = True + solid.forces = self.forces + + # 3.2 FEM solve. + logging.info(f"Step {step}: FEM solve...") + u, f_int, f_ext, sigma, _, _ = solid.solve(max_iter=1) + u_mean = torch.abs(u).mean().item() + logging.info(f" |u|_mean={u_mean}") + self._log_physical_quantities(u, sigma) + + # Save the deformed mesh every N steps. + # if self.config.deformed_mesh_interval > 0 and save_step_id % self.config.deformed_mesh_interval == 0: + # try: + # self.save_deformed_mesh(save_step_id, u) + # except Exception as e: + # logging.warning(f" ⚠️ error while saving the deformed mesh: {e}") + + # ==================== Step 4: sensitivity computation ==================== + # Strictly aligned with the reference flow around Line 1368-1399. + + # 4.1 Compute strain energy. We recover the unweighted energy by + # dividing out occ^p and keep strong numerical guards. + k0 = solid.k0() # occ^p * K_base after stiffness scaling. + u_j = u[self.elements].reshape(solid.n_elem, -1) + w_k_scaled = torch.einsum("...i, ...ij, ...j", u_j, k0, u_j) + + # Remove occ^p scaling to recover the base energy. + occ_power = torch.clamp( + self.coarse_occ ** self.config.p_exponent, + min=1e-6, # Avoid division by zero. + max=1.0 # Avoid overflow. + ) + + # Check again before division. + if torch.any(occ_power < 1e-6): + n_small = (occ_power < 1e-6).sum().item() + logging.warning(f" ⚠️ {n_small} elements have extremely small occ^p and were clamped to 1e-6") + + w_k_base = w_k_scaled / occ_power + + # Fall back if the recovered energy becomes invalid. + if torch.isnan(w_k_base).any() or torch.isinf(w_k_base).any(): + n_nan = torch.isnan(w_k_base).sum().item() + n_inf = torch.isinf(w_k_base).sum().item() + logging.error(f" ❌ w_k_baseabnormal: {n_nan} NaN, {n_inf} Inf") + logging.error(f" fall back to SIMP weightingw_k") + w_k_base = w_k_scaled + + # Use the recovered energy downstream. + compliance_mean = w_k_base.mean().item() + w_k = w_k_base # Downstream sensitivity uses the recovered energy. + + # Diagnostics. + logging.info(f" Compliance (true) ={compliance_mean:.2e}") + logging.info(f" w_k_base: max={w_k.max():.2e}, stress concentration={w_k.max()/(w_k.mean() + 1e-10):.1f}x") + + # ALM normalized constraint: g = D / D_thr - 1. + compliance_threshold = self.config.compliance_threshold if self.config.compliance_threshold is not None else 1.0 + g_raw = compliance_mean / (compliance_threshold + 1e-8) - 1.0 + g_pos = max(0.0, g_raw) + logging.info(f" constraint normalization: g={g_raw:+.3e}, [g]+={g_pos:.3e}, D_thr={compliance_threshold:.2e}") + + # Dynamic clip limit used by the ALM scaling guard. + base_max_grad = 1000.0 + lagrange_bonus = min((lagrange + rho * g_pos) * 10.0, 1000.0) + max_grad_norm = base_max_grad + lagrange_bonus + + # 4.3 Sensitivity formula aligned with the reference code: + # sensitivity = -p * occ^(p-1) * w_k + self.sensitivity_density = ( + -self.config.p_exponent + * self.coarse_occ ** (self.config.p_exponent - 1) + * w_k + ) + + # 4.4 Volume regularization is intentionally disabled here so the pure + # physics signal can be validated first. + if False and self.config.volume_term > 0.0: # Temporarily forced off. + # Initialize the reference volume on first use. + if not hasattr(self, 'init_volume'): + self.init_volume = self.coarse_occ.clone() + logging.info(f" record initial volume: sum={self.init_volume.sum().item():.2f}") + + # Volume sensitivity term. + sensitivity_volume = ( + self.config.volume_term + * (1.0 / self.config.res) ** 3 + * torch.ones_like(self.sensitivity_density) + ) + + # Choose the sign from the current volume change. + volume_sign = 1.0 if self.coarse_occ.sum() >= self.init_volume.sum() else -1.0 + sensitivity_volume *= volume_sign + + self.sensitivity_density += sensitivity_volume + + volume_ratio = self.coarse_occ.sum() / self.init_volume.sum() + logging.info(f" volume constraint: ratio={volume_ratio.item():.3f}, " + f"{'penalize' if volume_sign > 0 else 'encourage'}") + else: + logging.info(f" volume constraint: disabled (physicsoptimizationdominates) ") + + # Sensitivity diagnostics. + sens_norm = torch.norm(self.sensitivity_density).item() + sens_min = self.sensitivity_density.min().item() + sens_max = self.sensitivity_density.max().item() + logging.info(f" sensitivity: norm={sens_norm:.2e}, range=[{sens_min:.2e}, {sens_max:.2e}]") + + # ==================== Step 5: backward pass via VJP ==================== + self.backward_step(self.sensitivity_density) + + # ==================== Step 6: apply ALM weighting (lambda + rho[g]+) ==================== + if self.latents.grad is not None: + phys_grad_norm = torch.norm(self.latents.grad).item() + phys_grad_unscaled = self.latents.grad.clone() # Unscaled physics gradient for SDS comparisons. + + if g_pos > 0.0: + alm_scale_raw = (lagrange + rho * g_pos) / (compliance_threshold + 1e-8) + alm_scale = alm_scale_raw + guard_ratio = min(max(self.config.alm_scale_guard_ratio, 0.0), 1.0) + if phys_grad_norm > 0.0 and max_grad_norm > 0.0 and guard_ratio > 0.0: + alm_scale_guard = (max_grad_norm * guard_ratio) / (phys_grad_norm + 1e-8) + if alm_scale > alm_scale_guard: + logging.info( + f" 🔧 ALMscaling limit: raw={alm_scale_raw:.3e} -> {alm_scale_guard:.3e} " + f"(guard={guard_ratio:.2f}, max_grad={max_grad_norm:.1f})" + ) + alm_scale = alm_scale_guard + self.latents.grad *= alm_scale + else: + alm_scale = 0.0 + self.latents.grad.zero_() + + scaled_grad_norm = torch.norm(self.latents.grad).item() + logging.info( + f" physics gradient(ALM): {phys_grad_norm:.2e} → {scaled_grad_norm:.2e} " + f"(×scale={alm_scale:.3e}, λ={lagrange:.2f}, ρ={rho:.2f})" + ) + else: + phys_grad_unscaled = None + alm_scale = 0.0 + + # ==================== Step 7: shape loss toward target_z0 ==================== + + # 7.1 Compute the denoised target_z0. + import math + if use_sds: + target_z0, _, _ = self._get_target_z0(step) + else: + target_z0 = self.latents.detach() + + # Optionally validate and save a target_z0 mesh every 10 steps. + if use_sds: + self._maybe_save_target_z0_mesh(target_z0, save_step_id) + + # Shape loss is a simple MSE pulling latents toward target_z0. + shape_loss = torch.nn.functional.mse_loss(self.latents, target_z0.detach()) + + # 7.2 Decide whether shape loss is active this step. + current_sds_weight = self.get_current_sds_weight(step) if use_sds else 0.0 + use_sds_this_step = current_sds_weight > 0.0 + + if not use_sds_this_step: + logging.info(f" 🚫 Shape Loss disabled (physicsoptimizationmode) ") + weighted_sds = 0.0 + shape_grad_norm = 0.0 + else: + # Weighted shape loss. + weighted_shape_loss = current_sds_weight * shape_loss + + # Validate shape loss before backpropagating it. + if torch.isnan(shape_loss) or torch.isinf(shape_loss): + logging.error(f" ❌ Shape Loss contains NaN or Inf; skipping the shape constraint") + weighted_sds = 0.0 + shape_grad_norm = 0.0 + else: + # Backpropagate the shape loss into latents.grad. + weighted_shape_loss.backward() + + # Measure the shape-gradient norm for logging. + if self.latents.grad is not None and phys_grad_unscaled is not None: + # Isolate the shape part from the combined gradient. + shape_gradient = self.latents.grad - phys_grad_unscaled * alm_scale + shape_grad_norm = torch.norm(shape_gradient).item() + phys_grad_norm_current = torch.norm(phys_grad_unscaled * alm_scale).item() + shape_phys_ratio = shape_grad_norm / (phys_grad_norm_current + 1e-10) + + if shape_phys_ratio > 100.0: + logging.error(f" ❌ Shape gradient is too large (Shape/physics={shape_phys_ratio:.1f}x)!") + logging.error(f" consider lowering sds_weight_end: {self.config.sds_weight_end} → {self.config.sds_weight_end/100:.4f}") + elif shape_phys_ratio > 10.0: + logging.warning(f" ⚠️ Shape gradient is relatively large (Shape/physics={shape_phys_ratio:.1f}x)") + + # Compare the directions of physics and shape gradients. + cos_angle = (phys_grad_unscaled * shape_gradient).sum() / ( + torch.norm(phys_grad_unscaled) * torch.norm(shape_gradient) + 1e-10 + ) + angle_deg = torch.acos(torch.clamp(cos_angle, -1, 1)) * 180 / math.pi + direction = "same direction✅" if angle_deg < 90 else "opposite direction⚠️" + + logging.info(f" Shapegradient: norm={shape_grad_norm:.4e}, weight={current_sds_weight:.6f}") + logging.info(f" gradient direction: physics vs Shape = {angle_deg:.1f}° ({direction})") + elif self.latents.grad is not None: + shape_grad_norm = torch.norm(self.latents.grad).item() + logging.info(f" Shapegradient: norm={shape_grad_norm:.4e} (no physics gradient)") + else: + shape_grad_norm = 0.0 + + weighted_sds = weighted_shape_loss.item() + + # ==================== Step 8: combine losses and clip if needed ==================== + compliance_loss_item = compliance_mean + alm_penalty = lagrange * g_pos + 0.5 * rho * (g_pos ** 2) + total_loss = alm_penalty + weighted_sds + + # Log the combined loss terms. + if use_sds_this_step: + logging.info( + f" 📊 weighted loss: Compliance={compliance_loss_item:.4e}, g={g_raw:+.3e}, " + f"ALM={alm_penalty:.4e} (λ={lagrange:.2f}, ρ={rho:.2f}), " + f"Shape={weighted_sds:.4e} (×w={current_sds_weight:.6f}), Total={total_loss:.4e}" + ) + else: + logging.info( + f" 📊 weighted loss: Compliance={compliance_loss_item:.4e}, g={g_raw:+.3e}, " + f"ALM={alm_penalty:.4e} (λ={lagrange:.2f}, ρ={rho:.2f}), " + f"Shape=0.00e+00 (disabled), Total={total_loss:.4e}" + ) + + # Log gradient composition details. + if self.latents.grad is not None: + grad_norm = torch.norm(self.latents.grad).item() + + # Report each gradient contribution. + if phys_grad_unscaled is not None: + weighted_phys_grad_norm = torch.norm(phys_grad_unscaled * alm_scale).item() + logging.info(f" 🔍 gradient composition: Weighted Compliance Grad={weighted_phys_grad_norm:.4e} (ALM scale={alm_scale:.3e})") + + if use_sds_this_step and shape_grad_norm > 0: + logging.info(f" Scaled Shape Grad={shape_grad_norm:.4e} (Shape×w={current_sds_weight:.6f})") + if phys_grad_unscaled is not None: + grad_ratio = shape_grad_norm / (weighted_phys_grad_norm + 1e-10) + logging.info(f" ratio: Shape/Compliance = {grad_ratio:.4f} ({grad_ratio*100:.2f}%)") + + logging.info(f" Total Grad={grad_norm:.4e}") + + # Optional gradient clipping. + if self.latents.grad is not None: + grad_norm = torch.norm(self.latents.grad).item() + + if torch.isnan(self.latents.grad).any() or torch.isinf(self.latents.grad).any(): + logging.error(f"❌ the final gradient contains NaN or Inf!skip this steps") + return (compliance_loss_item, u_mean, shape_loss.item(), total_loss) + + if self.config.grad_clip_enabled: + if grad_norm > max_grad_norm: + clip_factor = max_grad_norm / grad_norm + self.latents.grad = self.latents.grad * clip_factor + logging.info(f" ✂️ gradient clipping: {grad_norm:.4e} -> {max_grad_norm:.1f} (×{clip_factor:.3f})") + else: + logging.info(f" ✅ gradient not clipped: {grad_norm:.4e} (max={max_grad_norm:.1f})") + + # ==================== Step 9: optimizer step ==================== + + # Save the previous latents for diagnostics. + old_latents = self.latents.data.clone() + + self.optimizer.step() + + # Diagnose latent changes after the optimizer step. + with torch.no_grad(): + latents_change = torch.norm(self.latents.data - old_latents).item() + latents_norm = torch.norm(old_latents).item() + latents_change_percent = (latents_change / (latents_norm + 1e-10)) * 100 + max_latents_change = torch.abs(self.latents.data - old_latents).max().item() + + logging.info(f" 🔄 Latentschange: L2={latents_change:.4e} ({latents_change_percent:.3f}%), max={max_latents_change:.4e}") + + if latents_change < 1e-6: + logging.warning(f" ⚠️ latents almost did not change!the learning rate may be too small or the gradient may be too weak") + + # Return the scalar loss values. + return (compliance_loss_item, u_mean, shape_loss.item(), total_loss) + + + def save_mesh(self, step: int, output_dir: str = "results/hunyuan_meshes", high_quality: bool = False, suffix="step", latents=None): + """Save frontlatentsmesh + + Args: + step: front steps + output_dir: outputdirectory + high_quality: YesNouse (Resolution) , Trueuse256resolution + """ + os.makedirs(output_dir, exist_ok=True) + + try: + # finalSave use256resolution, Stepuse128resolution + octree_res = 256 if high_quality else 128 + if latents is None: + mesh = self.latents_to_mesh(self.latents, octree_res=octree_res) + else: + mesh = self.latents_to_mesh(latents, octree_res=octree_res) + + if mesh is None: + logging.warning(f" ⚠️ warning: Step {step} - Marching cubesno surface found, skipSave ") + return + + # finalSave filterfloating + if high_quality: + mesh = self._filter_floating_components(mesh) + + mesh_path = os.path.join(output_dir, f"{suffix}_{step:04d}.obj") + mesh.export(mesh_path) + quality_label = "256resolution" if high_quality else "128resolution" + logging.info(f" 💾 Save mesh ({quality_label}): {mesh_path}") + except Exception as e: + logging.warning(f" ⚠️ warning: Step {step} - Save meshfailed: {e}") + + + def save_deformed_mesh(self, step: int, displacement: torch.Tensor, output_dir: str = None, suffix="step"): + """Save FEM solvebackdeformed mesh + + Args: + step: front steps + displacement: FEM solve [num_nodes, 3] + output_dir: outputdirectory, useconfig.out_folder/deformed_meshes + """ + if output_dir is None: + if hasattr(self.config, 'out_folder'): + output_dir = os.path.join(self.config.out_folder, "deformed_meshes") + else: + output_dir = "results/deformed_meshes" + + os.makedirs(output_dir, exist_ok=True) + + try: + # originalnodespositionandbackposition + original_nodes = self.nodes.detach().cpu().numpy() # [num_nodes, 3] + displacement_np = displacement.detach().cpu().numpy() # [num_nodes, 3] + deformed_nodes = original_nodes + displacement_np + + # elements + elements_np = self.elements.detach().cpu().numpy() # [num_elements, 8] + + # # Save VTK format (ParaView, contains) + # vtk_path = os.path.join(output_dir, f"deformed_step_{step:04d}.vtk") + # self._save_hex_mesh_vtk(deformed_nodes, elements_np, displacement_np, vtk_path, step) + + # Save OBJ/PLY (usedecodemesh, ) + decoded_mesh = self.latents_to_mesh(self.latents, octree_res=128) + if decoded_mesh is not None: + disp_vertices = self._sample_displacement_to_vertices( + decoded_mesh.vertices, original_nodes, displacement_np + ) + deformed_vertices = decoded_mesh.vertices + disp_vertices + colors = self._make_displacement_colors(disp_vertices) + + deformed_mesh = trimesh.Trimesh( + vertices=deformed_vertices, + faces=decoded_mesh.faces, + process=False, + ) + deformed_mesh.visual.vertex_colors = colors + + obj_path = os.path.join(output_dir, f"deformed_{suffix}_{step:04d}.obj") + # ply_path = os.path.join(output_dir, f"deformed_step_{step:04d}.ply") + deformed_mesh.export(obj_path) + # deformed_mesh.export(ply_path) + else: + # fallback: usemesh + obj_path = os.path.join(output_dir, f"deformed_{suffix}_{step:04d}.obj") + # ply_path = os.path.join(output_dir, f"deformed_step_{step:04d}.ply") + self._save_surface_mesh_obj(deformed_nodes, elements_np, obj_path) + # self._save_surface_mesh_ply(deformed_nodes, elements_np, displacement_np, ply_path) + + # displacement statistics + disp_mean = np.abs(displacement_np).mean() + disp_max = np.abs(displacement_np).max() + logging.info(f" 💾 saved deformed mesh : OBJ={obj_path.split('/')[-1]}") + logging.debug(f" : mean={disp_mean:.4e}, max={disp_max:.4e}") + + except Exception as e: + logging.warning(f" ⚠️ Save deformed meshfailed (Step {step}): {e}") + + + def save_final_deformed_mesh(self, step_id: int, suffix="step", latents=None): + """force at the final step toSave deformed mesh (re-solveFEM) """ + if not hasattr(self, 'nodes') or not hasattr(self, 'elements'): + logging.warning(" ⚠️ unable to save the finaldeformed mesh: missingnodes/elements") + return + if not hasattr(self, 'forces') or not hasattr(self, 'boundary_mask'): + logging.warning(" ⚠️ unable to save the finaldeformed mesh: missingforces/boundary_mask") + return + + try: + from torchfem.materials import IsotropicElasticity3D + from physiopt.opt.solid_grid import SolidGrid + from physiopt.opt.field import occ_kernel + + with torch.no_grad(): + # update occupancyalignfrontlatents + sdf = self.get_field(self.nodes, latents=latents) + occ = occ_kernel(sdf, self.config.res, self.config.occ_sdf_beta) + self.coarse_occ = occ[self.elements].mean(1) + + if self.config.alpha_min > 0.0: + self.coarse_occ = torch.clamp(self.coarse_occ, self.config.alpha_min) + + vectorized_material = IsotropicElasticity3D( + E=self.config.youngs_modulus, + nu=self.config.poissons_ratio, + rho=self.config.density, + ).vectorize(self.elements.shape[0]) + + vectorized_material.C *= ( + self.coarse_occ[:, None, None] ** self.config.p_exponent + ) + + solid = SolidGrid(self.nodes, self.elements, vectorized_material) + solid.constraints[self.boundary_mask, :] = True + solid.forces = self.forces + + logging.info(" 🧱 final deformed mesh: re-solve the FEM system to save ") + u, _, _, _, _, _ = solid.solve(max_iter=1) + self.save_deformed_mesh(step_id, u, suffix=suffix) + except Exception as e: + logging.warning(f" ⚠️ final deformed meshSave failed: {type(e).__name__}: {str(e)[:100]}") + + + def _save_surface_mesh_obj(self, nodes: np.ndarray, elements: np.ndarray, filename: str): + """Extract the surface from a hexahedral mesh and save it as OBJ.""" + # The six faces of a hexahedron. + hex_faces = [ + [0, 1, 2, 3], [4, 5, 6, 7], # Bottom, top. + [0, 1, 5, 4], [2, 3, 7, 6], # Front, back. + [0, 3, 7, 4], [1, 2, 6, 5], # Left, right. + ] + + # Collect faces that appear only once, i.e. surface faces. + face_count = {} + for elem in elements: + for face_indices in hex_faces: + face_nodes = tuple(sorted([elem[i] for i in face_indices])) + if face_nodes in face_count: + face_count[face_nodes] += 1 + else: + face_count[face_nodes] = 1 + + # Keep only surface faces. + surface_faces = [face for face, count in face_count.items() if count == 1] + + # Save OBJ. + with open(filename, 'w') as f: + f.write("# Deformed mesh surface\n") + for node in nodes: + f.write(f"v {node[0]:.6f} {node[1]:.6f} {node[2]:.6f}\n") + for face in surface_faces: + # OBJ indices are 1-based. + f.write(f"f {face[0]+1} {face[1]+1} {face[2]+1} {face[3]+1}\n") + + + def _save_force_visualization(self, seat_nodes_mask: torch.Tensor, total_force: np.ndarray): + """Save voxel-level load data for visualization and validation. + + This exports: + 1. NumPy (.npz) with full node/load data + 2. OBJ point clouds for quick inspection + 3. Optional VTK data for ParaView + + Args: + seat_nodes_mask: Mask of seat/contact nodes [num_nodes]. + total_force: Total force vector [3]. + """ + if not hasattr(self.config, 'out_folder'): + logging.warning(" out_folder is not set, skipSave loaded voxel") + return + + # Create the force_visualization subdirectory. + vis_dir = os.path.join(self.config.out_folder, "force_visualization") + os.makedirs(vis_dir, exist_ok=True) + + # ==================== 1. Save NumPy data (most complete format) ==================== + all_nodes_cpu = self.nodes.cpu().numpy() + all_forces_cpu = self.forces.cpu().numpy() + seat_mask_cpu = seat_nodes_mask.cpu().numpy() + + # Extract loaded nodes. + seat_nodes = all_nodes_cpu[seat_mask_cpu] + seat_forces = all_forces_cpu[seat_mask_cpu] + + npz_path = os.path.join(vis_dir, "force_nodes.npz") + np.savez( + npz_path, + # All node data. + all_nodes=all_nodes_cpu, + all_forces=all_forces_cpu, + # Loaded-node data. + seat_nodes=seat_nodes, + seat_forces=seat_forces, + seat_mask=seat_mask_cpu, + # Boundary-node data. + boundary_mask=self.boundary_mask.cpu().numpy() if hasattr(self, 'boundary_mask') else None, + # Metadata. + total_force=total_force, + num_seat_nodes=len(seat_nodes), + num_all_nodes=len(all_nodes_cpu), + ) + logging.info(f" 💾 Save load data (NumPy format) : {npz_path}") + + # ==================== 2. Save OBJ point clouds ==================== + # 2a. Loaded nodes (red point cloud). + seat_obj_path = os.path.join(vis_dir, "seat_nodes.obj") + with open(seat_obj_path, 'w') as f: + f.write("# Seat nodes (loaded area)\n") + f.write(f"# Total: {len(seat_nodes)} nodes\n") + f.write(f"# Force per node: {seat_forces[0] if len(seat_forces) > 0 else [0,0,0]}\n") + for node in seat_nodes: + f.write(f"v {node[0]:.6f} {node[1]:.6f} {node[2]:.6f}\n") + logging.info(f" 💾 Save seat nodes (OBJpoint cloud) : {seat_obj_path}") + + # 2b. Boundary nodes (blue point cloud). + if hasattr(self, 'boundary_mask'): + boundary_nodes = all_nodes_cpu[self.boundary_mask.cpu().numpy()] + boundary_obj_path = os.path.join(vis_dir, "boundary_nodes.obj") + with open(boundary_obj_path, 'w') as f: + f.write("# Boundary nodes (fixed area)\n") + f.write(f"# Total: {len(boundary_nodes)} nodes\n") + for node in boundary_nodes: + f.write(f"v {node[0]:.6f} {node[1]:.6f} {node[2]:.6f}\n") + logging.info(f" 💾 Save boundary nodes (OBJpoint cloud) : {boundary_obj_path}") + + # 2c. All nodes (gray point cloud) for comparison. + all_obj_path = os.path.join(vis_dir, "all_nodes.obj") + with open(all_obj_path, 'w') as f: + f.write("# All nodes\n") + f.write(f"# Total: {len(all_nodes_cpu)} nodes\n") + for node in all_nodes_cpu: + f.write(f"v {node[0]:.6f} {node[1]:.6f} {node[2]:.6f}\n") + logging.info(f" 💾 Save all nodes (OBJpoint cloud) : {all_obj_path}") + + # ==================== 3. Save VTK data for ParaView ==================== + try: + vtk_path = os.path.join(vis_dir, "force_field.vtk") + with open(vtk_path, 'w') as f: + # VTK Header + f.write("# vtk DataFile Version 3.0\n") + f.write("Force field visualization\n") + f.write("ASCII\n") + f.write("DATASET UNSTRUCTURED_GRID\n") + + # Points + f.write(f"POINTS {len(all_nodes_cpu)} float\n") + for node in all_nodes_cpu: + f.write(f"{node[0]:.6f} {node[1]:.6f} {node[2]:.6f}\n") + + # Cells (vertices) + f.write(f"\nCELLS {len(all_nodes_cpu)} {len(all_nodes_cpu)*2}\n") + for i in range(len(all_nodes_cpu)): + f.write(f"1 {i}\n") + + # Cell types (1 = vertex) + f.write(f"\nCELL_TYPES {len(all_nodes_cpu)}\n") + for _ in range(len(all_nodes_cpu)): + f.write("1\n") + + # Point data (force vectors) + f.write(f"\nPOINT_DATA {len(all_nodes_cpu)}\n") + f.write("VECTORS force float\n") + for force in all_forces_cpu: + f.write(f"{force[0]:.6e} {force[1]:.6e} {force[2]:.6e}\n") + + # Scalar field: force magnitude + f.write("\nSCALARS force_magnitude float 1\n") + f.write("LOOKUP_TABLE default\n") + for force in all_forces_cpu: + mag = np.linalg.norm(force) + f.write(f"{mag:.6e}\n") + + # Scalar field: is_seat (0 or 1) + f.write("\nSCALARS is_seat int 1\n") + f.write("LOOKUP_TABLE default\n") + for is_seat in seat_mask_cpu: + f.write(f"{int(is_seat)}\n") + + logging.info(f" 💾 Save force field (VTK format, ParaView) : {vtk_path}") + except Exception as e: + logging.warning(f" ⚠️ Save VTK formatfailed: {e}") + + # ==================== 4. Generate a Python visualization script ==================== + vis_script_path = os.path.join(vis_dir, "visualize_forces.py") + with open(vis_script_path, 'w') as f: + f.write("""#!/usr/bin/env python3 +\"""Visualize voxel load data + +Usage: + python visualize_forces.py + +Requirements: + pip install numpy matplotlib + +\""" +import numpy as np +import matplotlib.pyplot as plt +from mpl_toolkits.mplot3d import Axes3D + +# Load data. +data = np.load('force_nodes.npz') +all_nodes = data['all_nodes'] +seat_nodes = data['seat_nodes'] +seat_forces = data['seat_forces'] +total_force = data['total_force'] + +# Create the 3D figure. +fig = plt.figure(figsize=(15, 5)) + +# Subplot 1: all nodes (gray) + loaded nodes (red). +ax1 = fig.add_subplot(131, projection='3d') +ax1.scatter(all_nodes[:, 0], all_nodes[:, 1], all_nodes[:, 2], + c='lightgray', s=0.5, alpha=0.3, label='All nodes') +ax1.scatter(seat_nodes[:, 0], seat_nodes[:, 1], seat_nodes[:, 2], + c='red', s=5, alpha=1.0, label='Seat nodes (loaded)') +ax1.set_xlabel('X') +ax1.set_ylabel('Y (up)') +ax1.set_zlabel('Z') +ax1.set_title(f'Loaded Nodes\\n({len(seat_nodes)}/{len(all_nodes)} nodes)') +ax1.legend() + +# Subplot 2: Y distribution of loaded nodes. +ax2 = fig.add_subplot(132) +y_coords = seat_nodes[:, 1] +ax2.hist(y_coords, bins=30, color='red', alpha=0.7, edgecolor='black') +ax2.axvline(y_coords.min(), color='blue', linestyle='--', label=f'Y_min={y_coords.min():.3f}') +ax2.axvline(y_coords.max(), color='green', linestyle='--', label=f'Y_max={y_coords.max():.3f}') +ax2.set_xlabel('Y coordinate (height)') +ax2.set_ylabel('Number of nodes') +ax2.set_title('Seat Node Y Distribution') +ax2.legend() +ax2.grid(True, alpha=0.3) + +# Subplot 3: XZ force-vector layout in top view. +ax3 = fig.add_subplot(133) +ax3.scatter(seat_nodes[:, 0], seat_nodes[:, 2], c='red', s=10, alpha=0.5) +# Draw a sparse subset of force vectors to avoid clutter. +step = max(1, len(seat_nodes) // 50) +for i in range(0, len(seat_nodes), step): + node = seat_nodes[i] + force = seat_forces[i] + # Scale force vectors for visualization. + scale = 0.01 + ax3.arrow(node[0], node[2], force[0]*scale, force[2]*scale, + head_width=0.02, head_length=0.01, fc='blue', ec='blue', alpha=0.7) +ax3.set_xlabel('X') +ax3.set_ylabel('Z') +ax3.set_title(f'Top View (XZ plane)\\nForce: {total_force}') +ax3.axis('equal') +ax3.grid(True, alpha=0.3) + +plt.tight_layout() +plt.savefig('force_visualization.png', dpi=150, bbox_inches='tight') +logging.info("✅ image saved : force_visualization.png") +plt.show() + +# Print summary statistics. +logging.info("\\n" + "="*60) +logging.info("force voxel statistics") +logging.info("="*60) +logging.info(f"total node count: {len(all_nodes)}") +logging.info(f"loaded node count: {len(seat_nodes)} ({len(seat_nodes)/len(all_nodes)*100:.1f}%)") +logging.info(f"total: {total_force}") +logging.info(f"per nodeaverage force per node: {seat_forces.mean(axis=0)}") +logging.info(f"\\nY-coordinate range:") +logging.info(f" - min: {y_coords.min():.3f}") +logging.info(f" - max: {y_coords.max():.3f}") +logging.info(f" - mean: {y_coords.mean():.3f}") +logging.info(f" - height span: {y_coords.max() - y_coords.min():.3f}") +logging.info("="*60) +""") + os.chmod(vis_script_path, 0o755) # Add execute permission. + logging.info(f" 💾 Save visualization script: {vis_script_path}") + + # ==================== 5. Generate a README document ==================== + readme_path = os.path.join(vis_dir, "README.md") + with open(readme_path, 'w') as f: + f.write(f"""# Load Voxel Visualization Data + +Generated at: {np.datetime64('now')} + +## Statistics + +- **Total nodes**: {len(all_nodes_cpu)} +- **Loaded nodes**: {len(seat_nodes)} ({len(seat_nodes)/len(all_nodes_cpu)*100:.1f}%) +- **Total force**: {total_force} +- **Force per node**: {seat_forces[0] if len(seat_forces) > 0 else [0,0,0]} + +## Files + +### 1. NumPy format (recommended for analysis) + +- `force_nodes.npz`: contains the full dataset + - `all_nodes`: coordinates of all nodes [{len(all_nodes_cpu)}, 3] + - `all_forces`: force vectors on all nodes [{len(all_nodes_cpu)}, 3] + - `seat_nodes`: coordinates of loaded nodes [{len(seat_nodes)}, 3] + - `seat_forces`: force vectors on loaded nodes [{len(seat_nodes)}, 3] + - `seat_mask`: mask of loaded nodes [{len(all_nodes_cpu)}] + - `boundary_mask`: mask of boundary nodes [{len(all_nodes_cpu)}] + +**Example**: +```python +import numpy as np +data = np.load('force_nodes.npz') +seat_nodes = data['seat_nodes'] +print(f"Loaded nodes: {{len(seat_nodes)}}") +``` + +### 2. OBJ format (recommended for quick inspection) + +- `seat_nodes.obj`: loaded nodes (red point cloud) +- `boundary_nodes.obj`: boundary nodes (blue point cloud) +- `all_nodes.obj`: all nodes (gray point cloud) + +**Usage**: +1. Open in Meshlab: `meshlab seat_nodes.obj` +2. Or import the OBJ files into Blender +3. You can load multiple OBJ files together for comparison + +### 3. VTK format (recommended for professional visualization) + +- `force_field.vtk`: force-field data with vector information + +**Usage**: +1. Open in ParaView: `paraview force_field.vtk` +2. In ParaView: + - Use `Glyph` to visualize force vectors + - Color by `force_magnitude` to inspect strength + - Filter by `is_seat` to isolate the loaded region + +### 4. Visualization script + +- `visualize_forces.py`: Python visualization script + +**Usage**: +```bash +python visualize_forces.py +``` +""") + logging.info(f" 💾 Save README document: {readme_path}") + + # Print a short summary. + logging.info(f" ✅ force voxel data saved successfully!") + logging.info(f" - view directory: {vis_dir}") + logging.info(f" - quick visualization: cd {vis_dir} && python visualize_forces.py") + logging.info(f" - view in Meshlab: meshlab {os.path.join(vis_dir, 'seat_nodes.obj')}") + + +def load_hunyuan_models(model_path: str = "tencent/Hunyuan3D-2.1", + subfolder: str = "hunyuan3d-shapegen", + use_safetensors: bool = True): + """Load the Hunyuan3D models (VAE, Flow Model, and Scheduler). + + Args: + model_path: Model path, either a Hugging Face ID or a local directory. + subfolder: Model subfolder name. + use_safetensors: Whether to load safetensors checkpoints. + + Returns: + (vae, flow_model, scheduler): the VAE, Flow Matching model, and scheduler. + """ + logging.info(f"🔧 loading Hunyuan3D-2.1model...") + logging.info(f" modelpath: {model_path}") + logging.info(f" subfolder: {subfolder}") + logging.info(f" modelformat: {'safetensors' if use_safetensors else 'checkpoint'}") + + try: + pipeline = Hunyuan3DDiTFlowMatchingPipeline.from_pretrained( + model_path, + subfolder=subfolder, + torch_dtype=torch.float16, + use_safetensors=use_safetensors + ) + + if pipeline is None: + raise ValueError("pipeline loading failed and returned None") + + logging.info(" ✅ pipeline loaded successfully") + + pipeline.to('cuda') + logging.info(" ✅ modelmoved to CUDA (dtype: fp16)") + + vae = pipeline.vae + flow_model = pipeline.model + scheduler = pipeline.scheduler + + return vae, flow_model, scheduler + + except Exception as e: + logging.error(f"\n❌ modelloadfailed: {e}") + logging.error(f"\nPossible fixes:") + logging.error(f"1. make sure Hunyuan3D is installed-2.1: cd Hunyuan3D-2.1 && pip install -e .") + logging.error(f"2. check network connectivity to huggingface.co") + logging.error(f"3. or download manually: git clone https://huggingface.co/tencent/Hunyuan3D-2") + import traceback + traceback.print_exc() + sys.exit(1) + + +def plot_history(history: dict, save_dir: str, filename: str = "optimization_metrics.png"): + + epochs = list(range(1, len(history["compliance"]) + 1)) + + # 2. Create the figure with a 2x2 grid + fig, axs = plt.subplots(2, 2, figsize=(14, 10)) + fig.suptitle("Optimization Metrics Evolution", fontsize=16, fontweight='bold') + + # --- Plot 1: Compliance --- + axs[0, 0].plot(epochs, history["compliance"], marker='o', color='#1f77b4', linewidth=2) + axs[0, 0].set_title("Compliance (Strain Energy)") + axs[0, 0].set_xlabel("Epoch") + axs[0, 0].grid(True, linestyle='--', alpha=0.7) + + # --- Plot 2: u_mean --- + axs[0, 1].plot(epochs, history["u_mean"], marker='s', color='#2ca02c', linewidth=2) + axs[0, 1].set_title("Mean Displacement (|u|_mean)") + axs[0, 1].set_xlabel("Epoch") + axs[0, 1].grid(True, linestyle='--', alpha=0.7) + + # --- Plot 3: c_relative_decrease --- + axs[1, 0].plot(epochs, history["c_relative_decrease"], marker='^', color='#d62728', linewidth=2) + axs[1, 0].set_title("Relative Compliance Decrease") + axs[1, 0].set_xlabel("Epoch") + axs[1, 0].grid(True, linestyle='--', alpha=0.7) + + # --- Plot 4: u_relative_decrease --- + axs[1, 1].plot(epochs, history["u_relative_decrease"], marker='v', color='#9467bd', linewidth=2) + axs[1, 1].set_title("Relative Displacement Decrease") + axs[1, 1].set_xlabel("Epoch") + axs[1, 1].grid(True, linestyle='--', alpha=0.7) + + # 3. Adjust layout to prevent text from overlapping + plt.tight_layout() + fig.subplots_adjust(top=0.92) # Leave space for the main super-title + + # 4. Save the figure + os.makedirs(save_dir, exist_ok=True) + full_path = os.path.join(save_dir, filename) + + plt.savefig(full_path, dpi=300, bbox_inches='tight') + plt.close(fig) + + logging.info(f" 📊 Plot successfully saved to: {full_path}") + + +def main(): + """Parse CLI arguments and run the optimization.""" + import argparse + + parser = argparse.ArgumentParser(description="Hunyuan3D physics optimization + shape-prior optimization") + + # Required arguments. + parser.add_argument("--latents", type=str, required=True, + help="Input latents file path (.pt)") + parser.add_argument("--out_folder", type=str, default="../out/hunyuan_opt", + help="Output folder path") + + # Model arguments. + parser.add_argument("--model_path", type=str, default="tencent/Hunyuan3D-2.1", + help="Model path (using v2.1)") + parser.add_argument("--subfolder", type=str, default="hunyuan3d-dit-v2-1", + help="Model subfolder") + parser.add_argument("--use_safetensors", action="store_true", + help="Use safetensors format (default: ckpt)") + + # Physical-simulation arguments. + parser.add_argument("--use_physics", action="store_true", + help="Enable physics-constrained optimization") + parser.add_argument("--res", type=int, default=16, + help="Voxel resolution (16/32/64)") + parser.add_argument("--youngs_modulus_scale", type=float, default=2.0, + help="Final Young's modulus multiplier (default 2x after the last projection)") + parser.add_argument("--compliance_threshold", type=float, default=None, + help="Target compliance threshold (None = automatic)") + parser.add_argument("--compliance_threshold_ratio", type=float, default=0.3, + help="Automatic threshold ratio (threshold = initial value × ratio)") + + # Optimization arguments. + parser.add_argument("--lambda_guidance", type=float, default=0.1) + parser.add_argument("--num_steps", type=int, default=300, + help="Number of optimization steps (pure SDS only; in physics mode it becomes outer_cycles * phys_steps_per_cycle automatically)") + parser.add_argument("--outer_cycles", type=int, default=100, + help="Number of outer cycles (each cycle = physics optimization + projection)") + parser.add_argument("--phys_steps_per_cycle", type=int, default=5, + help="Number of physics-optimization steps per outer cycle") + parser.add_argument("--lr", type=float, default=5e-3, + help="Learning rate (increase to 0.005 to help the mesh thicken faster) ") + parser.add_argument("--lagrange_max", type=float, default=10.0, + help="Maximum Lagrange multiplier (recommended: 5-20)") + parser.add_argument("--alm_rho_init", type=float, default=1.0, + help="ALM rhoinitial value") + parser.add_argument("--alm_rho_max", type=float, default=1000.0, + help="ALM rhoMax") + parser.add_argument("--alm_rho_increase_factor", type=float, default=2.0, + help="ALM rhogrowth factor") + parser.add_argument("--alm_rho_increase_patience", type=int, default=5, + help="ALM rhonumber of consecutive violation steps required before increasing") + parser.add_argument("--alm_scale_guard_ratio", type=float, default=0.95, + help="ALMscaling guard ratio(<=1), control the upper bound of the physics-gradient target=this ratio x clipping-threshold value") + parser.add_argument("--grad_clip_enabled", action="store_true", + help="Enable gradient clipping (disabled by default; otherwise only NaN/Inf checks are kept)") + parser.add_argument("--use_sgd", action="store_true", + help="Use SGD instead of Adam") + parser.add_argument("--force_config", type=str, default=None, + help="Path to the external-force JSON config (generated by the web UI)") + parser.add_argument("--force", type=float, nargs=3, action="append", default=None, + help="External force vector [fx fy fz] (N, Y-up coordinates; can be specified multiple times)") + parser.add_argument("--global_loading", action="store_true", + help="Use global uniform loading (disable local loading)") + parser.add_argument("--force_region_mode", type=str, default="top_percent", + choices=["top_percent", "height_ratio", "bbox"], + help="How to choose the local loading region") + parser.add_argument("--force_top_percent", type=float, default=0.05, + help="top_percent mode: select the highest-Y fraction") + parser.add_argument("--force_bbox", type=float, nargs=6, default=None, + help="bbox mode: x_min x_max y_min y_max z_min z_max (absolute coordinates)") + parser.add_argument("--force_bbox_ratio", type=float, nargs=6, default=None, + help="bbox mode (0-1): bbox relative to the node bounds") + parser.add_argument("--seat_height_min_ratio", type=float, default=0.3, + help="height_ratio mode: lower seat boundary (0-1)") + parser.add_argument("--seat_height_max_ratio", type=float, default=0.5, + help="height_ratio mode: upper seat boundary (0-1)") + + # SDS arguments. + parser.add_argument("--sds_weight", type=float, default=1.0, + help="SDS gradient weight (deprecated; use sds_weight_start and sds_weight_end instead)") + parser.add_argument("--sds_weight_start", type=float, default=10.0, + help="Initial SDS weight (linearly increased; 0.0001 is recommended to avoid disturbing physics optimization)") + parser.add_argument("--sds_weight_end", type=float, default=10.0, + help="Final SDS weight (linearly increased; 0.001 is recommended, about 1/10 of the physics gradient)") + parser.add_argument("--sds_timestep", type=float, default=0.1, + help="SDS timestep (recommended: 0.05-0.2)") + parser.add_argument("--sds_target_z0_ema_beta", type=float, default=0.9, + help="target_z0 EMA smoothing factor (larger means smoother)") + parser.add_argument("--deformed_mesh_interval", type=int, default=10, + help="Interval for saving deformed meshes (steps)") + parser.add_argument("--deformed_mesh_disp_min", type=float, default=0.0, + help="Minimum displacement for deformed-mesh color mapping (default 0.0)") + parser.add_argument("--deformed_mesh_disp_max", type=float, default=0.2, + help="Maximum displacement for deformed-mesh color mapping (<=0 enables per-step auto scaling)") + parser.add_argument("--guidance_scale", type=float, default=7.5, + help="CFG guidance scale (standard value: 7.5; larger means stronger image conditioning)") + parser.add_argument("--sds_projection_max_rel", type=float, default=0.0, + help="Maximum relative target_z0 projection deviation (0 = unlimited)") + parser.add_argument("--sds_use_uncond", action="store_true", + help="Use the unconditional branch (only takes effect when guidance_scale <= 1)") + + # Topology control. + parser.add_argument("--keep_all_components", action="store_true", + help="Keep all connected components (to avoid disappearing chair legs)") + parser.add_argument("--re_extract_interval", type=int, default=1, + help="Solid re-extraction interval (0 = disabled)") + + args = parser.parse_args() + + def _normalize_force_vectors(value): + if value is None: + return None + if isinstance(value, (list, tuple)) and len(value) > 0: + if isinstance(value[0], (list, tuple)): + candidates = value + else: + candidates = [value] + else: + return None + normalized = [] + for vec in candidates: + if not isinstance(vec, (list, tuple)) or len(vec) != 3: + continue + try: + normalized.append([float(v) for v in vec]) + except Exception: + continue + return normalized if normalized else None + + def _normalize_force_entry(entry): + if not isinstance(entry, dict): + return None + forces = _normalize_force_vectors(entry.get("forces")) + if forces is None: + forces = _normalize_force_vectors(entry.get("force")) + if forces is None: + return None + out = dict(entry) + if len(forces) > 1: + out["forces"] = forces + out["force"] = [float(sum(v[i] for v in forces)) for i in range(3)] + else: + out["force"] = forces[0] + out.pop("forces", None) + if "force_region_mode" in out: + out["force_region_mode"] = str(out["force_region_mode"]) + if "global_loading" in out: + out["global_loading"] = bool(out["global_loading"]) + if "force_top_percent" in out: + out["force_top_percent"] = float(out["force_top_percent"]) + if "seat_height_min_ratio" in out: + out["seat_height_min_ratio"] = float(out["seat_height_min_ratio"]) + if "seat_height_max_ratio" in out: + out["seat_height_max_ratio"] = float(out["seat_height_max_ratio"]) + if "force_bbox" in out and isinstance(out["force_bbox"], (list, tuple)) and len(out["force_bbox"]) == 6: + out["force_bbox"] = [float(v) for v in out["force_bbox"]] + elif "force_bbox" in out: + out.pop("force_bbox", None) + if "force_bbox_ratio" in out and isinstance(out["force_bbox_ratio"], (list, tuple)) and len(out["force_bbox_ratio"]) == 6: + out["force_bbox_ratio"] = [float(v) for v in out["force_bbox_ratio"]] + elif "force_bbox_ratio" in out: + out.pop("force_bbox_ratio", None) + return out + + # Load force configuration from JSON, typically exported from the web UI. + force_config_loaded = False + force_config_error = None + force_entries = None + if args.force_config: + raw_force_config = args.force_config + candidates = [] + if os.path.isabs(raw_force_config): + candidates.append(raw_force_config) + else: + candidates.append(raw_force_config) + script_dir = os.path.dirname(os.path.abspath(__file__)) + candidates.append(os.path.join(script_dir, raw_force_config)) + candidates.append(os.path.join(os.path.dirname(script_dir), raw_force_config)) + force_config_path = next((p for p in candidates if os.path.exists(p)), None) + if force_config_path is None: + force_config_error = f"Path does not exist; tried: {candidates}" + else: + args.force_config = force_config_path + try: + with open(force_config_path, "r") as f: + force_cfg = json.load(f) + if isinstance(force_cfg, dict): + cfg_forces = _normalize_force_vectors(force_cfg.get("forces")) + if cfg_forces is not None: + args.force = cfg_forces + else: + cfg_force = _normalize_force_vectors(force_cfg.get("force")) + if cfg_force is not None: + args.force = cfg_force + elif "force" in force_cfg or "forces" in force_cfg: + force_config_error = "force/forcesinvalid format" + if "global_loading" in force_cfg: + args.global_loading = bool(force_cfg["global_loading"]) + if "force_region_mode" in force_cfg: + args.force_region_mode = str(force_cfg["force_region_mode"]) + if "force_top_percent" in force_cfg: + args.force_top_percent = float(force_cfg["force_top_percent"]) + if "seat_height_min_ratio" in force_cfg: + args.seat_height_min_ratio = float(force_cfg["seat_height_min_ratio"]) + if "seat_height_max_ratio" in force_cfg: + args.seat_height_max_ratio = float(force_cfg["seat_height_max_ratio"]) + if "force_bbox" in force_cfg: + args.force_bbox = force_cfg["force_bbox"] + if "force_bbox_ratio" in force_cfg: + args.force_bbox_ratio = force_cfg["force_bbox_ratio"] + if "force_entries" in force_cfg: + raw_entries = force_cfg["force_entries"] + if isinstance(raw_entries, list): + normalized_entries = [] + for entry in raw_entries: + norm_entry = _normalize_force_entry(entry) + if norm_entry is not None: + normalized_entries.append(norm_entry) + if normalized_entries: + force_entries = normalized_entries + else: + force_config_error = "force_entries has no valid entries" + else: + force_config_error = "force_entriesinvalid format" + force_config_loaded = True + else: + force_config_error = f"force_configis not a dict: {type(force_cfg)}" + except Exception as e: + force_config_error = f"read failed: {e}" + + # Configure logging. force=True ensures this replaces any prior setup. + os.makedirs(args.out_folder, exist_ok=True) + log_file = os.path.join(args.out_folder, "optimization.log") + + # Remove any existing handlers. + for handler in logging.root.handlers[:]: + logging.root.removeHandler(handler) + + # Reconfigure logging. + logging.basicConfig( + level=logging.INFO, + format='%(asctime)s - %(levelname)s - %(message)s', + handlers=[ + logging.FileHandler(log_file, mode='w'), # Rewrite the log on each run. + logging.StreamHandler() + ], + force=True # Python 3.8+: force a full reconfiguration. + ) + + logging.info(f"🔧 logging configuration completed") + logging.info(f" - log file: {log_file}") + logging.info(f" - output mode: file + console") + if args.force_config: + if force_config_loaded: + logging.info(" ✅ force_configloaded") + logging.info(f" - path: {args.force_config}") + logging.info(f" - forces: {args.force}") + if force_entries: + logging.info(f" - force_entries: {len(force_entries)}") + logging.info(f" - global_loading: {args.global_loading}") + logging.info(f" - force_region_mode: {args.force_region_mode}") + logging.info(f" - force_top_percent: {args.force_top_percent}") + logging.info(f" - seat_height_min_ratio: {args.seat_height_min_ratio}") + logging.info(f" - seat_height_max_ratio: {args.seat_height_max_ratio}") + logging.info(f" - force_bbox: {args.force_bbox}") + logging.info(f" - force_bbox_ratio: {args.force_bbox_ratio}") + if force_config_error: + logging.warning(f" ⚠️ force_configsome fields are invalid: {force_config_error}") + else: + logging.warning(f" ⚠️ force_configloadfailed: {force_config_error}") + + # In physics mode, derive num_steps from outer_cycles and phys_steps_per_cycle. + if args.use_physics: + outer_cycles = max(1, int(args.outer_cycles)) + phys_steps_per_cycle = max(1, int(args.phys_steps_per_cycle)) + derived_num_steps = outer_cycles * phys_steps_per_cycle + if args.num_steps != derived_num_steps: + logging.info( + f" - num_stepsautomatically set: {args.num_steps} → {derived_num_steps} " + f"(outer_cycles={outer_cycles}, phys_steps_per_cycle={phys_steps_per_cycle})" + ) + args.num_steps = derived_num_steps + + # ==================== Save run metadata ==================== + # 1. Save the command line. + command_file = os.path.join(args.out_folder, "run_command.txt") + try: + with open(command_file, 'w') as f: + f.write("=" * 80 + "\n") + f.write("Command used (Command Used)\n") + f.write("=" * 80 + "\n\n") + f.write("Full command:\n") + f.write("python " + " ".join(sys.argv) + "\n\n") + + f.write("=" * 80 + "\n") + f.write("Arguments (Arguments)\n") + f.write("=" * 80 + "\n\n") + for arg, value in vars(args).items(): + f.write(f"{arg}: {value}\n") + + f.write("\n" + "=" * 80 + "\n") + f.write("Environment (Environment)\n") + f.write("=" * 80 + "\n\n") + f.write(f"Python: {sys.version}\n") + f.write(f"PyTorch: {torch.__version__}\n") + f.write(f"CUDA Available: {torch.cuda.is_available()}\n") + if torch.cuda.is_available(): + f.write(f"CUDA Version: {torch.version.cuda}\n") + f.write(f"GPU Count: {torch.cuda.device_count()}\n") + + logging.info(f" - saved command used : {command_file}") + except Exception as e: + logging.warning(f" ⚠️ Save Command usedfailed: {e}") + + # 2. Save a copy of the current script. + script_backup = os.path.join(args.out_folder, "viewer_hunyuan_web_alternate.py") + try: + current_script = os.path.abspath(__file__) + shutil.copy2(current_script, script_backup) + logging.info(f" - saved script copy : {script_backup}") + except Exception as e: + logging.warning(f" ⚠️ Save failed to save script copy: {e}") + + # Load latents and conditioning data. + logging.info(f"\n📂 loading input data...") + logging.info(f" - Latents: {args.latents}") + + data = torch.load(args.latents, map_location='cpu') + + # Extract latents. + if isinstance(data, dict) and 'latents' in data: + latents = data['latents'] + else: + latents = data + + logging.info(f" ✅ Latents shape: {latents.shape}") + + # Check conditioning data (image_embeds or image). + need_encode_cond = False + image_embeds = None + image = None + + if isinstance(data, dict): + if 'image' in data: + # New format: only the image was saved, so we need to re-encode it. + logging.info(f" - detected image data; re-encoding as conditional embeds") + image_array = data['image'] + image = Image.fromarray(image_array) + need_encode_cond = True + elif 'image_embeds' in data: + # Legacy format: embeddings are already saved. + logging.info(f" - using the saved conditional embeds") + image_embeds = data['image_embeds'] + need_encode_cond = False + elif 'cond' in data: + # Alternate format using a saved cond dict. + logging.info(f" - using the saved cond") + image_embeds = data['cond'] + need_encode_cond = False + else: + raise ValueError("latents.ptis missingimage, image_embedsor cond data") + else: + raise ValueError("latentsmust be a dictionary containing'latents'andconditioninformation dict") + + if image_embeds is not None: + if isinstance(image_embeds, dict): + logging.info(f" ✅ Cond keys: {list(image_embeds.keys())}") + else: + logging.info(f" ✅ Image embeds shape: {image_embeds.shape}") + + # Load models. + logging.info(f"\n🔧 loading Hunyuan3Dmodel...") + vae, flow_model, scheduler = load_hunyuan_models( + model_path=args.model_path, + subfolder=args.subfolder, + use_safetensors=args.use_safetensors + ) + + # ==================== Encode conditioning data if needed ==================== + if need_encode_cond: + logging.info("🎨 encoding conditional embeds from the image...") + + # Reload the full pipeline for condition encoding. + from hy3dgen.shapegen import Hunyuan3DDiTFlowMatchingPipeline + + pipeline = Hunyuan3DDiTFlowMatchingPipeline.from_pretrained( + args.model_path, + subfolder=args.subfolder, + torch_dtype=torch.float16, + use_safetensors=args.use_safetensors + ) + pipeline.to('cuda') + + with torch.no_grad(): + # Prepare the image. + cond_inputs = pipeline.prepare_image(image) + image_tensor = cond_inputs.pop('image') + + # Enable CFG so the encoded condition contains both branches. + cond_dict = pipeline.encode_cond( + image=image_tensor, + additional_cond_inputs=cond_inputs, + do_classifier_free_guidance=True, # Enable CFG. + dual_guidance=False, + ) + + # Save the condition dict. + image_embeds = cond_dict + + logging.info(f" ✅ condition encoding completed (CFG mode) ") + logging.info(f" - Cond keys: {list(cond_dict.keys()) if isinstance(cond_dict, dict) else 'tensor'}") + + # Resolve the compliance threshold. + if args.compliance_threshold is None: + compliance_threshold = 200.0 + logging.info(f" using the default compliance threshold: {compliance_threshold}") + else: + compliance_threshold = args.compliance_threshold + logging.info(f" using the custom compliance threshold: {compliance_threshold}") + + target_z0_update_interval = max(1, int(args.phys_steps_per_cycle)) + forces = None + normalized_forces = _normalize_force_vectors(args.force) + if normalized_forces: + forces = [{'external_force': vec} for vec in normalized_forces] + elif args.force is not None: + logging.warning(f" ⚠️ invalid external force vector; ignoring: {args.force}") + # Build the optimization config. + config = OptimizationConfig( + num_steps=args.num_steps, + lr=args.lr, + sds_timestep=args.sds_timestep, + sds_weight=args.sds_weight if args.use_physics else 1.0, # Keep backward compatibility. + sds_weight_start=args.sds_weight_start, # Dynamic weight schedule start. + sds_weight_end=args.sds_weight_end, # Dynamic weight schedule end. + guidance_scale=args.guidance_scale, # CFG guidance scale. + sds_projection_max_rel=args.sds_projection_max_rel, + sds_use_uncond=args.sds_use_uncond, + sds_target_z0_update_interval=target_z0_update_interval, + sds_target_z0_ema_beta=args.sds_target_z0_ema_beta, + deformed_mesh_interval=args.deformed_mesh_interval, + deformed_mesh_disp_min=args.deformed_mesh_disp_min, + deformed_mesh_disp_max=args.deformed_mesh_disp_max, + use_sgd=args.use_sgd, + grad_clip_enabled=args.grad_clip_enabled, + # Physical parameters. + res=args.res, + lagrange_max=args.lagrange_max, + compliance_threshold=compliance_threshold, + alm_rho_init=args.alm_rho_init, + alm_rho_max=args.alm_rho_max, + alm_rho_increase_factor=args.alm_rho_increase_factor, + alm_rho_increase_patience=args.alm_rho_increase_patience, + alm_scale_guard_ratio=args.alm_scale_guard_ratio, + youngs_modulus_scale=args.youngs_modulus_scale, + # Topology control. + one_cc_only=not args.keep_all_components, + re_extract_interval=args.re_extract_interval, + # Loads and load-region settings. + forces=forces, + force_entries=force_entries, + use_local_loading=not args.global_loading, + seat_height_min_ratio=args.seat_height_min_ratio, + seat_height_max_ratio=args.seat_height_max_ratio, + force_region_mode=args.force_region_mode, + force_top_percent=args.force_top_percent, + force_bbox=args.force_bbox, + force_bbox_ratio=args.force_bbox_ratio, + # Output path. + out_folder=args.out_folder, + ) + + # Create the optimizer. + optimizer = HunyuanSDSOptimizer( + latents=latents, + cond=image_embeds, + vae=vae, + flow_model=flow_model, + scheduler=scheduler, + config=config, + device='cuda' + ) + + # Prepare physics if requested. + final_step = args.num_steps + if args.use_physics: + logging.info(f"\n🔬 enable physics optimization mode") + logging.info(f" - Voxel resolution: {args.res}") + logging.info(f" - physics steps/cycle: {args.phys_steps_per_cycle}, outer cycles: {args.outer_cycles}") + logging.info(f" - projection noise: sds_timestep={args.sds_timestep}") + logging.info(f" - target_z0update interval: {target_z0_update_interval} (consistent with phys_steps_per_cycle)") + logging.info(f" - LagrangeMax: {args.lagrange_max}") + + try: + optimizer.extract_solid(step=-1) # Initial extraction. + optimizer.prepare_physical_simulation() + logging.info(f" ✅ physics simulationInitializationsucceeded") + except Exception as e: + logging.warning(f" ⚠️ warning: initial mesh extraction failed (this is normal, optimizationbe repaired during the optimization process) ") + logging.warning(f" error information: {str(e)[:100]}") + # Continue anyway: the key physical state is the occupancy field, not the mesh. + else: + logging.info(f"\n🎨 using pure SDS optimization mode") + + # Optimization loop. + optimization_mode = "Alternating Phys/Projection" if args.use_physics else "Pure SDS" + total_steps_hint = ( + int(args.outer_cycles) * (int(args.phys_steps_per_cycle) + 1) + if args.use_physics + else args.num_steps + ) + logging.info(f"\n🚀 start{optimization_mode}optimization ({total_steps_hint} steps)...") + + if args.use_physics: + lagrange_multiplier = 0.0 + rho = config.alm_rho_init + violation_count = 0 + + # Automatically set the compliance threshold when needed. + if config.compliance_threshold is None or config.compliance_threshold == 200.0: + logging.info(f" 📊 computationinitialcompliancethreshold value...") + try: + initial_compliance, initial_u, _, _ = optimizer.training_step( + 0, 0.0, 0.0, use_sds=False + ) + # Auto threshold: initial compliance times the requested ratio. + auto_threshold = initial_compliance * args.compliance_threshold_ratio + auto_threshold = min(auto_threshold, 100000.0) # Upper bound only. + compliance_threshold = auto_threshold + config.compliance_threshold = auto_threshold + logging.info( + f" ✅ Automatically set the threshold: {initial_compliance:.2e} × {args.compliance_threshold_ratio:.2f} " + f"= {compliance_threshold:.2e}" + ) + + # Warn when the structure already looks extremely stiff or too soft. + if initial_compliance < 0.01: # Already very stiff. + logging.warning(f" ⚠️ initial compliance is very small ({initial_compliance:.2e}), the structure may already be stiff enough!") + logging.warning(f" consider increasing the external force or using a softer material to create visible deformation") + logging.warning(f" current material: E={config.youngs_modulus:.2e} Pa, ν={config.poissons_ratio}") + elif initial_compliance > 1000.0: # Likely too soft. + logging.warning(f" ⚠️ initial compliance is very large ({initial_compliance:.2e}), the structure may be too soft!") + logging.warning(f" consider using a stiffer material or reducing the external force") + except Exception as e: + logging.warning(f" ⚠️ automatic computation failed, usethreshold value200: {e}") + compliance_threshold = 200.0 + else: + compliance_threshold = config.compliance_threshold + + logging.info(f"🎯 parameters:") + logging.info(f" - initial lambda: {lagrange_multiplier}") + logging.info(f" - initial rho: {rho}") + logging.info(f" - Compliancethreshold value: {compliance_threshold:.2e}") + logging.info(f" - λMax: {args.lagrange_max}") + logging.info(f" - ρMax: {config.alm_rho_max:.1e}") + logging.info(f" - rho growth: ×{config.alm_rho_increase_factor:.1f} (continuous violations{config.alm_rho_increase_patience} steps)") + logging.info(f" - ALMscaling guard ratio: {config.alm_scale_guard_ratio:.2f}") + logging.info(f" - gradient clipping: {'enabled' if config.grad_clip_enabled else 'disabled'}") + + outer_cycles = max(1, int(args.outer_cycles)) + phys_steps_per_cycle = max(1, int(args.phys_steps_per_cycle)) + total_steps = outer_cycles * (phys_steps_per_cycle + 1) + logging.info( + f"🔁 Alternating optimization: outer cycles={outer_cycles}, physics steps/cycle={phys_steps_per_cycle}, " + f"total steps(including projections)≈{total_steps}" + ) + base_youngs_modulus = float(config.youngs_modulus) + youngs_modulus_scale = float(config.youngs_modulus_scale) + youngs_modulus_target = base_youngs_modulus * youngs_modulus_scale + youngs_modulus_delta = (youngs_modulus_target - base_youngs_modulus) / outer_cycles + projection_count = 0 + logging.info( + f" - linearly increase Young's modulus: E0={base_youngs_modulus:.2e}, " + f"Δ/projection={youngs_modulus_delta:.2e}, E_final={youngs_modulus_target:.2e} " + f"(scale={youngs_modulus_scale:.2f}x)" + ) + global_step = 0 + + history = {"compliance": [], + "u_mean": [], + "c_relative_decrease": [], + "u_relative_decrease": [], + "error": [], + "epoch": []} + + thresholds = [0, 30, 40, 50, 60, 65, 70, 75, 80, 90, 95] + # thresholds = [0, 20, 30, 40, 50, 55, 60, 70, 80] + + latents_dir = os.path.join(args.out_folder, "latents") + os.makedirs(latents_dir, exist_ok=True) + + for current_threshold in thresholds: + logging.info(f"\n✅ Threshold : {current_threshold}") + + target_compliance = initial_compliance - current_threshold*initial_compliance/100 + logging.info(f"Target compliance: {target_compliance}") + + optimize_latent, compliance_loss, u_mean, diff = optimizer.flow_matching_with_guidance(step=current_threshold, guidance_value=target_compliance, lambda_guidance=args.lambda_guidance) + + # Update history + history["compliance"].append(compliance_loss) + history["u_mean"].append(u_mean) + history["error"].append(int(np.abs(diff))) + + # Calculate relative decreases using current variables + c_decrease = (initial_compliance - compliance_loss) / initial_compliance * 100 + u_decrease = (initial_u - u_mean) / initial_u * 100 + history["c_relative_decrease"].append(c_decrease) + history["u_relative_decrease"].append(u_decrease) + logging.info(f" 📉 Metrics | Comp: {compliance_loss:.3e} (↓ {c_decrease:.1f}%) | u_mean: {u_mean:.3e} (↓ {u_decrease:.1f}%)") + + optimizer.save_mesh(current_threshold, args.out_folder, suffix="decrease", high_quality=True, latents=optimize_latent) + latent_path = os.path.join(latents_dir, f"latent_{current_threshold}.pt") + torch.save({'latents': optimizer.latents.detach().cpu(), 'cond': optimizer.cond}, latent_path) + + optimizer.save_final_deformed_mesh(current_threshold, suffix="decrease", latents=optimize_latent) + + # Save final results. + logging.info("\n✅ Optimization finished!") + + + + plot_history(history, save_dir=args.out_folder, filename="optimization_metrics.png") + + history_path = os.path.join(args.out_folder, "history.json") + with open(history_path, "w", encoding="utf-8") as f: + json.dump(history, f, indent=4) + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/cfd_workflow_20261012/_seiler_ref/physiopt_new_scripts/hunyuan_sgo_me.py b/cfd_workflow_20261012/_seiler_ref/physiopt_new_scripts/hunyuan_sgo_me.py new file mode 100644 index 0000000000000000000000000000000000000000..438e08c5637636db3e95523ca28d871a616de6bc --- /dev/null +++ b/cfd_workflow_20261012/_seiler_ref/physiopt_new_scripts/hunyuan_sgo_me.py @@ -0,0 +1,3458 @@ +""" +Hunyuan3D-2.1 physical optimization + shape-prior optimization. +""" + +import os +import copy +# os.environ['TORCH_HOME'] = '/mnt/cvlab/scratch/cvlab/home/hantzhan/.torch' +import sys +import shutil + +# Add Hunyuan3D-2.1 to the Python path. +hunyuan_path = os.path.abspath(os.path.join(os.path.dirname(__file__), "../../Hunyuan3D-2.1")) +# Note: logging is not imported yet, so use print here if needed. +# Basic logging is configured near the top of the file after import. + +sys.path.append("..") + +import torch +import torch.nn.functional as F +import trimesh +import numpy as np +from PIL import Image +import argparse +import json +from typing import Tuple, Optional, List +from dataclasses import dataclass, field +import traceback +import logging +import matplotlib.pyplot as plt + +# Configure logging here only conceptually; main() will reconfigure it to +# log to both the console and a file. +# Do not call basicConfig here so the main() configuration remains effective. +# logging.basicConfig(level=logging.INFO, format='%(levelname)s: %(message)s') + +# Physical-simulation imports. +PHYSIOPT_AVAILABLE = False +try: + from physiopt.utils.phys_utils import generate_hex + from physiopt.utils.grid_utils import filter_one_component + from physiopt.opt.field import occ_kernel + from physiopt.opt.forces import ForceConfig + PHYSIOPT_AVAILABLE = True + logging.info("✅ physics simulation moduleimportsucceeded") +except ImportError as e: + logging.warning(f"⚠️ warning: physics simulation moduleimportfailed: {e}") + logging.warning(" if you only run SDS optimization, you can ignore this warning") + PHYSIOPT_AVAILABLE = False + + def generate_hex(res, limits=[(-0.5, 0.5), (-0.5, 0.5), (-0.5, 0.5)], device="cuda", return_coords=False): + """Placeholder for hexahedral grid generation. + + Returns tensors in the same format as the real function. + """ + logging.warning(f"⚠️ warning: using placeholdergenerate_hex, please install the physiopt module") + return None, None + + def filter_one_component(mask, res): + """Placeholder for connected-component filtering. + + Args: + mask: Element mask [res*res*res] + res: Voxel resolution + """ + return mask + + def occ_kernel(sdf, res, beta): + """Placeholder for SDF-to-occupancy conversion.""" + return torch.sigmoid(-sdf * beta) + +# Warp physics-engine import. +try: + import warp as wp + wp.init() + WARP_AVAILABLE = True + logging.info("✅ Warp physics engineInitializationsucceeded") +except ImportError: + WARP_AVAILABLE = False + logging.warning("⚠️ warning: Warp physics enginenot installed, physics simulationwill be unavailable") + logging.warning(" Install: pip install warp-lang") + +# Hunyuan3D imports +try: + from hy3dgen.shapegen.models.autoencoders import ShapeVAE + from hy3dgen.shapegen import Hunyuan3DDiTFlowMatchingPipeline + from hy3dgen.shapegen.pipelines import export_to_trimesh +except ImportError as e: + logging.error(f"❌ failed to import Hunyuan3D modules: {e}") + logging.error(f"\nplease follow these steps to set upHunyuan3D-2.1:") + logging.error(f"1. cd {os.path.dirname(hunyuan_path)}") + logging.error(f"2. git clone https://github.com/Tencent/Hunyuan3D-2.git Hunyuan3D-2.1") + logging.error(f"3. cd Hunyuan3D-2.1") + logging.error(f"4. pip install -e .") + sys.exit(1) + + +@dataclass +class OptimizationConfig: + """Optimization config for physics + SDS.""" + # Physical-simulation parameters. + res: int = 32 # Voxel resolution (16/32/64), matching the reference code. + # Restored physical settings from the stable v90 configuration. + p_exponent: float = 1.0 # SIMP penalty exponent. + alpha_min: float = 0.01 # Minimum density, restored from v90. + volume_term: float = 1000000.0 # Volume-constraint weight, currently disabled. + occ_sdf_beta: float = 2.0 # Sigmoid-kernel beta, restored from v90. + one_cc_only: bool = False # Keep only the largest connected component. + + # SDS parameters. + # Use dynamic SDS weights so physics dominates early and aesthetics enters later. + sds_timestep: float = 0.1 # SDS timestep; smaller values preserve more detail. + sds_weight: float = 1.0 # SDS weight relative to the physical gradient. + sds_weight_start: float = 1e5 # 0.1 # 0.0001 # Initial SDS weight. + sds_weight_end: float = 1e5 # 1.0 # 0.001 # Final SDS weight. + guidance_scale: float = 7.5 # Standard CFG guidance scale for stronger image conditioning. + sds_projection_max_rel: float = 0.0 # Max relative target_z0 projection offset (0 = unlimited). + sds_use_uncond: bool = False # Use the unconditional branch when guidance_scale <= 1. + sds_target_z0_update_interval: int = 10 # target_z0 update interval; tied to phys_steps_per_cycle. + sds_target_z0_ema_beta: float = 0.9 # EMA smoothing coefficient; larger is smoother. + + lagrange_max: float = 50.0 # Max lambda. + compliance_threshold: float = 200.0 # Compliance threshold used for normalization. + alm_rho_init: float = 1.0 # Initial rho. + alm_rho_max: float = 1000.0 # Max rho. + alm_rho_increase_factor: float = 2.0 # Rho growth factor. + alm_rho_increase_patience: int = 5 # Number of consecutive violations before increasing rho. + alm_scale_guard_ratio: float = 0.95 # ALM scaling guard to stay below gradient clipping. + + # Topology control. + re_extract_interval: int = 5 # Re-extract the solid every N steps; 0 disables it. + + # Material properties. Values are aligned with the reference setup. + # youngs_modulus is already specified directly in Pa, so no unit conversion is needed. + youngs_modulus: float = 5e8 # 1e9 # Pa (= 1 GPa), restored from v90. + youngs_modulus_scale: float = 2.0 # Final multiplier after the last projection in alternating mode. + poissons_ratio: float = 0.3 # Poisson's ratio (dimensionless). + density: float = 650.0 # Material density (kg/m^3). + + ## Wood + # youngs_modulus: float = 9e9 # Pa (= 1 GPa), aligned with the reference code. + # poissons_ratio: float = 0.35 # Poisson's ratio (dimensionless), matches the reference. + # density: float = 400.0 # Material density (kg/m^3), matches the reference. + + ## PVG + # youngs_modulus: float = 3.25e9 # Pa (= 1 GPa), aligned with the reference code. + # poissons_ratio: float = 0.38 # Poisson's ratio (dimensionless), matches the reference. + # density: float = 1380.0 # Material density (kg/m^3), matches the reference. + + # Load conditions; supports multiple forces like config.json. + forces: List = None # List of ForceConfig objects. + # Multiple localized load entries, each with its own force and region settings. + force_entries: Optional[List[dict]] = None + + # Local-loading settings, e.g. to mimic a person sitting on a chair. + use_local_loading: bool = True # Use local loading instead of global uniform loading. + seat_height_min_ratio: float = 0.3 # Lower bound of the seat band as a height ratio. + seat_height_max_ratio: float = 0.5 # Upper bound of the seat band as a height ratio. + force_region_mode: str = "top_percent" # Load-region mode: top_percent / height_ratio / bbox. + force_top_percent: float = 0.05 # In top_percent mode, use the highest-Y fraction of nodes. + force_bbox: Optional[List[float]] = None # bbox mode: x_min x_max y_min y_max z_min z_max. + force_bbox_ratio: Optional[List[float]] = None # bbox mode in normalized node bounds [0, 1]. + + # Optimization parameters, restored from the stable v90 configuration. + lr: float = 0.001 # Learning rate. + num_steps: int = 100 # Number of optimization steps. + use_sgd: bool = False # Use SGD instead of Adam. + grad_clip_enabled: bool = False # Enable gradient clipping; off by default. + save_every: int = 10 # Save interval in steps. + deformed_mesh_interval: int = 10 # Save interval for deformed meshes. + deformed_mesh_disp_min: float = 0.0 # Minimum displacement for deformed-mesh color mapping. + deformed_mesh_disp_max: float = 0.2 # Maximum displacement for deformed-mesh color mapping. + + # Output path. + out_folder: str = "../out/hunyuan_opt" # Output directory. + + # Device. + device: str = "cuda" # Compute device. + + # Whether to enable physics optimization. + use_physics: bool = True # Enable physical-constraint optimization. + + def __post_init__(self): + # Set default loads in the Hunyuan Y-up coordinate system: + # X = right, Y = up, Z = forward. + if self.forces is None: + try: + from physiopt.opt.forces import ForceConfig + self.forces = [ + ForceConfig(external_force=[0.0, -100000.0, 0.0]) # 100 kN downward along Y. + # ForceConfig(external_force=[0.0, 0.0, -500.0]), # 500 N backward along Z. + ] + except ImportError: + # Fallback format if physiopt is unavailable; keep only the force vectors. + self.forces = [ + {'external_force': [0.0, -100000.0, 0.0]} # 100 kN downward along Y. + # {'external_force': [0.0, 0.0, -500.0]}, # Backward along Z. + ] + + +class HunyuanSDSOptimizer: + """Hunyuan3D SDS optimizer with differentiable physics support.""" + + def __init__( + self, + latents: torch.Tensor, + cond: dict, # Condition dict containing positive and negative branches. + vae: ShapeVAE, + flow_model: torch.nn.Module, + config: OptimizationConfig, + scheduler=None, + device: str = 'cuda' + ): + """ + Args: + latents: Initial latent tokens [1, N, D]. + cond: Condition dict returned by pipeline.encode_cond. + vae: Hunyuan3D VAE model. + flow_model: Hunyuan3D Flow Matching model. + scheduler: Hunyuan3D Flow Matching scheduler used to align target_z0. + config: Optimization config. + device: Compute device. + """ + self.device = device + self.config = config + + # Models. + self.vae = vae.to(device).eval() + self.flow_model = flow_model.to(device).eval() + if scheduler is not None: + try: + self.sds_scheduler = copy.deepcopy(scheduler) + except Exception: + self.sds_scheduler = scheduler + logging.warning("⚠️ Scheduler deepcopyfailed, already fallback to originalscheduler") + else: + self.sds_scheduler = None + + # Create a differentiable SDF query helper. + from hy3dgen.shapegen.models.autoencoders.differentiable_sdf_query import DifferentiableSDFQuery + self.sdf_query = DifferentiableSDFQuery( + vae=self.vae, + bounds=0.8, # Our coordinate range is [-0.8, 0.8]. + chunk_size=8192 # Batch query size. + ) + logging.info(f"✅ created differentiable SDF query helper") + + # Latent tokens are the variables being optimized. + # Use float32 instead of float16 to avoid numeric overflow. + self.latents = latents.clone().to(device).to(torch.float32).requires_grad_(True) + + logging.info(f" ⚠️ note: Latentsfloat32FP16value") + + # Move conditioning data to the target device recursively. + def to_device_recursive(obj): + if isinstance(obj, torch.Tensor): + return obj.to(device) + elif isinstance(obj, dict): + return {k: to_device_recursive(v) for k, v in obj.items()} + elif isinstance(obj, (list, tuple)): + return type(obj)(to_device_recursive(item) for item in obj) + else: + return obj + + self.cond = to_device_recursive(cond) + self._cond_warned_cfg_repeat = False + self._cond_warned_nocfg_slice = False + + # Optimizer selection. + if config.use_sgd: + self.optimizer = torch.optim.SGD([self.latents], lr=config.lr, momentum=0.0) + opt_name = "SGD" + else: + self.optimizer = torch.optim.Adam([self.latents], lr=config.lr, betas=(0.9, 0.999), eps=1e-8) + opt_name = "Adam" + + logging.info(f"✅ HunyuanSDSOptimizerInitializationcompleted (with differentiable physics support) ") + logging.info(f" - Latents shape: {self.latents.shape}") + logging.info(f" - Latents dtype: {self.latents.dtype} (optimized in float32)") + logging.info(f" - Device: {device}") + logging.info(f" - Optimizer: {opt_name}") + logging.info(f" - Learning rate: {config.lr}") + + # target_z0 EMA cache. + self.target_z0_ema = None + self.target_z0_last_velocity = None + self.target_z0_last_update = None + + def get_field(self, x: torch.Tensor, latents: torch.Tensor = None) -> torch.Tensor: + """Differentiable SDF query through the VAE geo_decoder. + + Args: + x: Query points [N, 3] in the range [-0.8, 0.8]^3. + latents: Optional latent tokens; defaults to self.latents. + + Returns: + sdf: SDF values [N] with gradient support. + """ + if latents is None: + latents = self.latents + + # Match the official pipeline: divide by scale_factor before decoding. + scale_factor = getattr(self.vae, "scale_factor", 1.0) + latents_scaled = latents / scale_factor + + # Convert to FP16 because the VAE expects FP16 inputs. + latents_fp16 = latents_scaled.to(torch.float16) + + # Decode with the VAE decoder while preserving gradients. + decoded_latents = self.vae.decode(latents_fp16) + + # Query the SDF through the differentiable helper. + # sdf_query calls geo_decoder internally, so keep FP16 to match VAE weights. + sdf = self.sdf_query( + decoded_latents, # Keep FP16 and let sdf_query handle the rest. + x, + return_occupancy=False # Return SDF instead of occupancy. + ) # [N] + + return sdf + + def _cond_batch_size(self, cond) -> Optional[int]: + if isinstance(cond, torch.Tensor): + return cond.shape[0] if cond.dim() >= 1 else None + if isinstance(cond, dict): + for v in cond.values(): + bsz = self._cond_batch_size(v) + if bsz is not None: + return bsz + if isinstance(cond, (list, tuple)): + for v in cond: + bsz = self._cond_batch_size(v) + if bsz is not None: + return bsz + return None + + def _cond_slice(self, cond, batch_slice: slice): + if isinstance(cond, torch.Tensor): + if cond.dim() >= 1 and cond.shape[0] >= batch_slice.stop: + return cond[batch_slice] + return cond + if isinstance(cond, dict): + return {k: self._cond_slice(v, batch_slice) for k, v in cond.items()} + if isinstance(cond, (list, tuple)): + return type(cond)(self._cond_slice(v, batch_slice) for v in cond) + return cond + + def _cond_repeat(self, cond, repeats: int): + if isinstance(cond, torch.Tensor): + if cond.dim() >= 1: + rep_shape = (repeats,) + (1,) * (cond.dim() - 1) + return cond.repeat(rep_shape) + return cond + if isinstance(cond, dict): + return {k: self._cond_repeat(v, repeats) for k, v in cond.items()} + if isinstance(cond, (list, tuple)): + return type(cond)(self._cond_repeat(v, repeats) for v in cond) + return cond + + def _get_cond_for_guidance(self, use_cfg: bool): + cond = self.cond + bsz = self._cond_batch_size(cond) + if use_cfg: + if bsz == 1: + if not self._cond_warned_cfg_repeat: + logging.warning("⚠️ guidance_scale>1 cond batch=1, already condCFG") + self._cond_warned_cfg_repeat = True + return self._cond_repeat(cond, 2) + if bsz is not None and bsz > 2: + return self._cond_slice(cond, slice(0, 2)) + return cond + # no-CFG + if bsz is not None and bsz >= 2: + if self.config.sds_use_uncond: + if not self._cond_warned_nocfg_slice: + logging.info("ℹ️ guidance_scale<=1, useno conditioncond[1:2]") + self._cond_warned_nocfg_slice = True + return self._cond_slice(cond, slice(1, 2)) + if not self._cond_warned_nocfg_slice: + logging.info("ℹ️ guidance_scale<=1, already usecond[0:1]batch") + self._cond_warned_nocfg_slice = True + return self._cond_slice(cond, slice(0, 1)) + if self.config.sds_use_uncond and bsz == 1 and not self._cond_warned_nocfg_slice: + logging.warning("⚠️ sds_use_uncond=1 cond batch=1, already fallback to conditself") + self._cond_warned_nocfg_slice = True + return cond + + def latents_to_mesh(self, latents: torch.Tensor, octree_res: int = 128) -> Optional[trimesh.Trimesh]: + """Decode latent tokens into a mesh. + + Args: + latents: Latent tokens [1, N, D] (float32). + octree_res: Octree resolution. 128 is faster; 256 is higher quality. + + Returns: + A trimesh.Trimesh object, or None on failure. + """ + with torch.no_grad(): + # Skip invalid latent tensors early. + if torch.isnan(latents).any() or torch.isinf(latents).any(): + logging.warning(" latents_to_mesh: latentscontains NaN or Inf, skip") + return None + + # Match the official pipeline by dividing by scale_factor first. + scale_factor = getattr(self.vae, "scale_factor", 1.0) + latents_scaled = latents / scale_factor + + # Decode in FP16 because the VAE expects FP16 inputs. + latents_fp16 = latents_scaled.to(torch.float16) + + try: + # VAE decode. + decoded_latents = self.vae.decode(latents_fp16) + + # Skip invalid decoded latents. + if torch.isnan(decoded_latents).any() or torch.isinf(decoded_latents).any(): + logging.warning(" latents_to_mesh: decoded_latentscontains NaN or Inf, skip") + return None + except Exception as e: + logging.debug(f" latents_to_mesh: VAE decodingfailed: {e}") + return None + + # Use an adaptive mc_level fallback if the default level fails. + try: + # First try the standard mc_level=0.0. + mesh = self.vae.latents2mesh( + decoded_latents, + output_type='trimesh', + bounds=1.01, + mc_level=0.0, + num_chunks=20000, + octree_resolution=octree_res, + mc_algo='mc', + enable_pbar=False + ) + mesh = export_to_trimesh(mesh)[0] + return mesh + + except ValueError as e: + error_msg = str(e) + if "Surface level must be within volume data range" in error_msg: + # Estimate a better mc_level from sampled SDF statistics. + logging.debug(f" latents_to_mesh: mc_level=0.0 failed, try an adaptive level...") + + try: + # Sample a coarse grid to estimate the SDF range. + grid_size = 32 + x = torch.linspace(-1.0, 1.0, grid_size, device=decoded_latents.device) + y = torch.linspace(-1.0, 1.0, grid_size, device=decoded_latents.device) + z = torch.linspace(-1.0, 1.0, grid_size, device=decoded_latents.device) + xx, yy, zz = torch.meshgrid(x, y, z, indexing='ij') + points = torch.stack([xx, yy, zz], dim=-1).reshape(-1, 3) # [N, 3] + + # query the SDF values. + sdf_values = self.get_field(points, latents=latents) + + # Compute basic statistics. + sdf_median = torch.median(sdf_values).item() + sdf_min = sdf_values.min().item() + sdf_max = sdf_values.max().item() + sdf_mean = sdf_values.mean().item() + + logging.debug(f" SDFstatistics: min={sdf_min:.4f}, max={sdf_max:.4f}, median={sdf_median:.4f}, mean={sdf_mean:.4f}") + + # No clear surface can be extracted if the SDF range is too small. + if abs(sdf_max - sdf_min) < 1e-4: + logging.debug(f" SDFrange is too small to extract a surface") + return None + + # Try several plausible candidate levels. + candidate_levels = [ + sdf_median, # Median. + sdf_mean, # Mean. + (sdf_min + sdf_max) / 2, # Midpoint of the range. + sdf_min + (sdf_max - sdf_min) * 0.3, # 30% point. + sdf_min + (sdf_max - sdf_min) * 0.7, # 70% point. + ] + + # Clamp all levels to the valid range. + valid_levels = [ + max(sdf_min + 0.001, min(sdf_max - 0.001, level)) + for level in candidate_levels + ] + + # Remove duplicates. + valid_levels = list(set(valid_levels)) + + logging.debug(f" try {len(valid_levels)} candidate levels: {[f'{l:.4f}' for l in valid_levels[:3]]}...") + + # Try each candidate level in order. + for i, adaptive_level in enumerate(valid_levels): + try: + mesh = self.vae.latents2mesh( + decoded_latents, + output_type='trimesh', + bounds=1.01, + mc_level=adaptive_level, + num_chunks=20000, + octree_resolution=octree_res, + mc_algo='mc', + enable_pbar=False + ) + mesh = export_to_trimesh(mesh)[0] + logging.info(f" ✅ uselevelsucceeded (level={adaptive_level:.4f}, attempt {i+1})") + return mesh + except (ValueError, RuntimeError) as level_error: + # Try the next level if this one fails. + if i < len(valid_levels) - 1: + continue + else: + # All candidate levels failed. + logging.debug(f" all candidate levels failed") + return None + + # No candidate succeeded. + return None + + except Exception as adaptive_error: + logging.debug(f" adaptive extraction failed: {type(adaptive_error).__name__}: {str(adaptive_error)[:50]}") + return None + + elif "No surface found" in error_msg: + logging.debug(f" latents_to_mesh: Marching cubesno surface found, skip") + return None + else: + logging.warning(f" latents_to_mesh: unknown ValueError: {error_msg}") + return None + + except RuntimeError as e: + error_msg = str(e) + if "No surface found" in error_msg or "Surface level" in error_msg: + logging.debug(f" latents_to_mesh: Marching cubesfailed, skip") + return None + else: + logging.warning(f" latents_to_mesh: RuntimeError: {error_msg}") + return None + + except Exception as e: + # Catch any other unexpected failure. + logging.warning(f" latents_to_mesh: unexpected exception: {type(e).__name__}: {e}") + return None + + def _filter_floating_components(self, mesh: trimesh.Trimesh) -> trimesh.Trimesh: + """Remove small floating fragments and keep only the largest component.""" + try: + components = mesh.split(only_watertight=False) + if len(components) <= 1: + return mesh + + face_counts = [len(comp.faces) for comp in components] + max_idx = int(np.argmax(face_counts)) + filtered = components[max_idx] + dropped = len(components) - 1 + + logging.info(f" 🧹 filter floating fragments: kept{len(filtered.faces)} faces, discarded{dropped} small components") + return filtered + except Exception as e: + logging.warning(f" failed to filter floating fragments: {type(e).__name__}: {str(e)[:100]}") + return mesh + + def _sample_displacement_to_vertices( + self, + vertices: np.ndarray, + nodes: np.ndarray, + displacement: np.ndarray, + ) -> np.ndarray: + """Sample the voxel-node displacement field onto mesh vertices by nearest neighbor.""" + try: + from scipy.spatial import cKDTree + tree = cKDTree(nodes) + _, idx = tree.query(vertices, k=1) + return displacement[idx] + except Exception as e: + try: + from sklearn.neighbors import NearestNeighbors + nn = NearestNeighbors(n_neighbors=1, algorithm="auto") + nn.fit(nodes) + idx = nn.kneighbors(vertices, return_distance=False).squeeze(1) + return displacement[idx] + except Exception as e2: + logging.warning(f" displacement sampling failed, fallback to zero displacement: {type(e).__name__}: {str(e)[:100]}") + logging.debug(f" secondaryError: {type(e2).__name__}: {str(e2)[:100]}") + return np.zeros_like(vertices) + + def _normalize_displacement_magnitude( + self, disp_mag: np.ndarray + ) -> Tuple[np.ndarray, float, float, bool]: + """Normalize displacement magnitude, optionally with a fixed range.""" + mag_max_cfg = getattr(self.config, "deformed_mesh_disp_max", None) + mag_min_cfg = getattr(self.config, "deformed_mesh_disp_min", None) + use_fixed = mag_max_cfg is not None and mag_max_cfg > 0.0 + if use_fixed: + mag_min = 0.0 if mag_min_cfg is None else float(mag_min_cfg) + mag_max = float(mag_max_cfg) + if mag_max <= mag_min: + use_fixed = False + if not use_fixed: + mag_min = float(disp_mag.min()) + mag_max = float(disp_mag.max()) + denom = max(1e-12, mag_max - mag_min) + norm = (disp_mag - mag_min) / denom + if use_fixed: + norm = np.clip(norm, 0.0, 1.0) + return norm, mag_min, mag_max, use_fixed + + def _make_displacement_colors(self, displacement: np.ndarray) -> np.ndarray: + """Map displacement magnitude to vertex colors (blue -> red).""" + disp_mag = np.linalg.norm(displacement, axis=1) + norm, _, _, _ = self._normalize_displacement_magnitude(disp_mag) + colors = np.stack([norm, np.zeros_like(norm), 1.0 - norm], axis=1) + return (colors * 255).astype(np.uint8) + + def _log_physical_quantities( + self, + u: torch.Tensor, + sigma: Optional[torch.Tensor], + ) -> None: + """Log displacement and von Mises stress statistics.""" + with torch.no_grad(): + u_max = None + u_avg = None + try: + u_mag = torch.norm(u, dim=1) + u_max = u_mag.max().item() + u_avg = u_mag.mean().item() + except Exception as e: + logging.warning( + f" ⚠️ displacement statistics failed: {type(e).__name__}: {str(e)[:100]}" + ) + + sigma_vm_max = None + sigma_vm_avg = None + if sigma is not None: + try: + if sigma.dim() == 2 and sigma.shape[1] >= 6: + s_xx = sigma[:, 0] + s_yy = sigma[:, 1] + s_zz = sigma[:, 2] + s_yz = sigma[:, 3] + s_xz = sigma[:, 4] + s_xy = sigma[:, 5] + mises_sq = 0.5 * ( + (s_xx - s_yy) ** 2 + + (s_yy - s_zz) ** 2 + + (s_zz - s_xx) ** 2 + + 6.0 * (s_xy ** 2 + s_yz ** 2 + s_xz ** 2) + ) + mises = torch.sqrt(torch.clamp(mises_sq, min=0.0)) + sigma_vm_max = mises.max().item() + sigma_vm_avg = mises.mean().item() + else: + logging.warning( + f" ⚠️ sigmashape does not match expectations, skip von Mises statistics: {tuple(sigma.shape)}" + ) + except Exception as e: + logging.warning( + f" ⚠️ von Mises statistics failed: {type(e).__name__}: {str(e)[:100]}" + ) + + if u_max is not None and u_avg is not None: + if sigma_vm_max is not None and sigma_vm_avg is not None: + logging.info( + f" physical metrics: u_max={u_max:.3e}, u_avg={u_avg:.3e}, " + f"sigma_vm_max={sigma_vm_max:.3e}, sigma_vm_avg={sigma_vm_avg:.3e}" + ) + else: + logging.info( + f" physical metrics: u_max={u_max:.3e}, u_avg={u_avg:.3e}" + ) + + def backward_step(self, sensitivity_density: torch.Tensor): + """Backpropagate with VJP, aligned with the reference code. + + Reference: viewer_deepsdf.py Line 148-183. + This uses torch.autograd.functional.vjp to propagate sensitivity to latents. + """ + def f(latents: torch.Tensor): + """ + Compute occupancy from a given latent tensor. + Aligned with viewer_deepsdf.py Line 155-173. + """ + # Query the SDF. + sdf = self.get_field(self.nodes, latents) + + # SDF → occupancy + from physiopt.opt.field import occ_kernel + occ = occ_kernel(sdf, self.config.res, self.config.occ_sdf_beta) + + # Element occupancy is the average over the 8 nodes. + occ_elem = occ[self.elements].mean(1) + + # Clamp by alpha_min if requested. + if self.config.alpha_min > 0.0: + occ_elem = torch.clamp(occ_elem, self.config.alpha_min) + + return occ_elem + + # VJP computations d occ / d latents^T times the sensitivity vector. + # Aligned with viewer_deepsdf.py Line 175-180. + try: + grad_latent = torch.autograd.functional.vjp( + f, + self.latents.clone().requires_grad_(True), + sensitivity_density, + )[1] + + # Validate the returned gradient. + if grad_latent is None: + logging.error(" ❌ VJP returned None!") + return + + grad_norm = torch.norm(grad_latent).item() + logging.info(f" VJP gradient: norm={grad_norm:.2e}") + + # Assign the gradient manually, matching the reference implementation. + self.latents.grad = grad_latent + + except Exception as e: + logging.error(f" ❌ VJP failed: {e}") + import traceback + traceback.print_exc() + + def prepare_physical_simulation(self): + """Prepare the physical simulation and FEM solver state. + + Initialization includes: + 1. Material properties + 2. Boundary conditions + 3. External forces + """ + if not WARP_AVAILABLE: + logging.warning("Warpnot installed, skipphysics simulation preparation") + return + + if not hasattr(self, 'nodes') or not hasattr(self, 'elements'): + logging.error("please call extract_solid() to extract the solid first") + return + + logging.info("prepare physical simulation...") + + # Initialize Warp. + wp.init() + + # Normalize device names such as "cuda" and "cuda:0". + if 'cuda' in self.device: + # Extract the device id when needed. + if ':' in self.device: + device_id = self.device.split(':')[-1] + warp_device = f"cuda:{device_id}" + else: + warp_device = "cuda:0" # default to cuda:0 + else: + warp_device = "cpu" + + wp.set_device(warp_device) + logging.info(f"Warpdevice: {warp_device}") + + # Material properties. + self.E = self.config.youngs_modulus # Young's modulus. + self.nu = self.config.poissons_ratio # Poisson's ratio. + self.rho = self.config.density # Density. + + # Boundary condition: fix bottom nodes using Hunyuan's Y-up frame. + y_coords = self.nodes[:, 1] + y_min = y_coords.min() + boundary_threshold = y_min + 0.05 # 0.2 # 0.05 # Bottom 5% band. + self.boundary_mask = y_coords < boundary_threshold + + logging.info(f" coordinate system: Y-up (Hunyuan-native), fix Y < {boundary_threshold:.3f}nodes") + + # Apply load locally instead of spreading it across all nodes. + # The default heuristic targets a seat-like region in the Y-up frame. + + # Compute the total force, giving priority to force_entries. + total_force = np.zeros(3, dtype=np.float32) + force_entries = getattr(self.config, "force_entries", None) + valid_force_entries = None + if force_entries: + valid_force_entries = [] + for entry in force_entries: + if not isinstance(entry, dict): + continue + entry_force = None + if "force" in entry: + try: + entry_force = np.array(entry["force"], dtype=np.float32) + except Exception: + entry_force = None + elif "forces" in entry and isinstance(entry["forces"], list): + try: + entry_force = np.sum( + np.array(entry["forces"], dtype=np.float32), axis=0 + ) + except Exception: + entry_force = None + if entry_force is None or entry_force.shape != (3,): + continue + valid_force_entries.append(entry) + total_force += entry_force + if valid_force_entries: + self.force_entries_preset = valid_force_entries + logging.info(f" force entries: {len(valid_force_entries)}") + else: + logging.warning(" ⚠️ force_entries has no valid entries, fallback to forces") + valid_force_entries = None + + if valid_force_entries is None: + for force_config in self.config.forces: + if hasattr(force_config, 'get_total_force'): + # ForceConfig object. + total_force += force_config.get_total_force() + elif isinstance(force_config, dict) and 'external_force' in force_config: + # Compatibility format using a plain dict. + total_force += np.array(force_config['external_force'], dtype=np.float32) + else: + logging.warning(f"unknown force format: {type(force_config)}") + + logging.info(f" sum of external forces (Y-up coordinates): {total_force}") + + # Choose the loading strategy from the config. + if valid_force_entries is not None: + # Multiple localized loads, each with its own region. + self._setup_local_loading(total_force) + elif self.config.use_local_loading: + # Preferred mode: local loading. + self._setup_local_loading(total_force) + else: + # Fallback mode: global uniform loading. + logging.info(f" ℹ️ using global uniform loading mode") + total_force_tensor = torch.from_numpy(total_force).float().to(self.device) + num_nodes = self.nodes.shape[0] + self.forces = total_force_tensor[None, :].repeat(num_nodes, 1) + logging.info(f" 💨 distributed the total force uniformly to{num_nodes}nodes") + + logging.info(f"boundary conditions: {self.boundary_mask.sum().item()}fixed nodes") + logging.info(f"material properties: E={self.E:.2e}, ν={self.nu}, ρ={self.rho}") + + def _setup_local_loading(self, total_force: np.ndarray): + """Set up local loading on the selected seat/contact region. + + The total force is distributed uniformly across the selected nodes so + that sum(forces) equals total_force. + + Args: + total_force: Total force vector [3] in the Y-up frame, in Newtons. + """ + # Cache the total force for later updates. + self.total_force_preset = torch.from_numpy(total_force).float().to(self.device) + + # Reuse the generic update routine for the initial setup. + self._update_forces(initial_setup=True) + + def _update_forces(self, initial_setup: bool = False): + """Update the force distribution for the current mesh state. + + Core logic: + 1. Re-identify contact nodes + 2. Spread the preset total force uniformly over those nodes + 3. Keep total force conserved + + Args: + initial_setup: Whether this is the first setup pass. + """ + if not hasattr(self, 'total_force_preset'): + logging.warning("No preset total force is set, so the force distribution cannot be updated") + return + + # Step 1: inspect the Y-coordinate distribution. + y_coords = self.nodes[:, 1] + num_nodes = self.nodes.shape[0] + + force_entries = getattr(self, "force_entries_preset", None) + if force_entries: + def _select_nodes_for_mode(mode, top_percent, min_ratio, max_ratio, bbox, bbox_ratio): + seat_mask = torch.zeros(num_nodes, dtype=torch.bool, device=self.device) + mode_used = mode + bbox_desc = None + + if mode_used not in ("top_percent", "height_ratio", "bbox", "global"): + logging.warning(f" ⚠️ invalid force_region_mode: {mode_used}, fallback to top_percent") + mode_used = "top_percent" + + if mode_used == "global": + seat_mask[:] = True + return seat_mask, mode_used, bbox_desc + + if mode_used == "bbox": + bbox_vals = None + if bbox is not None and len(bbox) == 6: + bbox_vals = [float(v) for v in bbox] + bbox_desc = "abs" + elif bbox_ratio is not None and len(bbox_ratio) == 6: + bbox_ratio_vals = [float(v) for v in bbox_ratio] + bounds_min = self.nodes.min(dim=0).values + bounds_max = self.nodes.max(dim=0).values + bbox_vals = [ + bounds_min[0].item() + bbox_ratio_vals[0] * (bounds_max[0] - bounds_min[0]).item(), + bounds_min[0].item() + bbox_ratio_vals[1] * (bounds_max[0] - bounds_min[0]).item(), + bounds_min[1].item() + bbox_ratio_vals[2] * (bounds_max[1] - bounds_min[1]).item(), + bounds_min[1].item() + bbox_ratio_vals[3] * (bounds_max[1] - bounds_min[1]).item(), + bounds_min[2].item() + bbox_ratio_vals[4] * (bounds_max[2] - bounds_min[2]).item(), + bounds_min[2].item() + bbox_ratio_vals[5] * (bounds_max[2] - bounds_min[2]).item(), + ] + bbox_desc = "ratio" + else: + logging.warning(" ⚠️ bbox mode did not provide a valid bbox, fallback to top_percent") + mode_used = "top_percent" + + if mode_used == "bbox" and bbox_vals is not None: + x0, x1 = sorted([bbox_vals[0], bbox_vals[1]]) + y0, y1 = sorted([bbox_vals[2], bbox_vals[3]]) + z0, z1 = sorted([bbox_vals[4], bbox_vals[5]]) + seat_mask = ( + (self.nodes[:, 0] >= x0) & (self.nodes[:, 0] <= x1) + & (self.nodes[:, 1] >= y0) & (self.nodes[:, 1] <= y1) + & (self.nodes[:, 2] >= z0) & (self.nodes[:, 2] <= z1) + ) + if seat_mask.sum().item() < 1: + logging.warning(" ⚠️ bbox region matched no nodes, fallback to top_percent") + mode_used = "top_percent" + else: + bbox_desc = f"{bbox_desc}: [{x0:.3f},{x1:.3f}]x[{y0:.3f},{y1:.3f}]x[{z0:.3f},{z1:.3f}]" + + if mode_used == "height_ratio": + y_min = y_coords.min().item() + y_max = y_coords.max().item() + y_range = max(1e-8, y_max - y_min) + if not (0.0 <= min_ratio < max_ratio <= 1.0): + logging.warning( + f" ⚠️ invalid height_ratio: min={min_ratio}, max={max_ratio}, fallback to top_percent" + ) + mode_used = "top_percent" + else: + seat_y_min = y_min + y_range * min_ratio + seat_y_max = y_min + y_range * max_ratio + seat_mask = (y_coords >= seat_y_min) & (y_coords <= seat_y_max) + if seat_mask.sum().item() < 1: + logging.warning(" ⚠️ height_ratio matched no nodes, fallback to top_percent") + mode_used = "top_percent" + + if mode_used == "top_percent": + top_percent = float(top_percent) + top_percent = max(0.0, min(1.0, top_percent)) + if top_percent <= 0.0: + top_percent = 0.05 + num_seat_nodes = max(1, int(num_nodes * top_percent)) + _, top_indices = torch.topk(y_coords, k=num_seat_nodes, largest=True) + seat_mask = torch.zeros(num_nodes, dtype=torch.bool, device=self.device) + seat_mask[top_indices] = True + + return seat_mask, mode_used, bbox_desc + + self.forces = torch.zeros((num_nodes, 3), dtype=torch.float32, device=self.device) + combined_mask = torch.zeros(num_nodes, dtype=torch.bool, device=self.device) + total_force = torch.zeros(3, dtype=torch.float32, device=self.device) + + for idx, entry in enumerate(force_entries): + if not isinstance(entry, dict): + continue + entry_label = entry.get("label") or entry.get("name") or f"{idx+1}" + entry_force = None + if "forces" in entry and isinstance(entry["forces"], list): + try: + entry_force = np.sum(np.array(entry["forces"], dtype=np.float32), axis=0) + except Exception: + entry_force = None + if entry_force is None and "force" in entry: + try: + entry_force = np.array(entry["force"], dtype=np.float32) + except Exception: + entry_force = None + if entry_force is None or entry_force.shape != (3,): + logging.warning(f" ⚠️ invalid force entry[{entry_label}], skip") + continue + + entry_force_tensor = torch.from_numpy(entry_force).float().to(self.device) + total_force += entry_force_tensor + + mode = str(entry.get("force_region_mode", self.config.force_region_mode)).lower() + if entry.get("global_loading") is True: + mode = "global" + + top_percent = entry.get("force_top_percent", self.config.force_top_percent) + min_ratio = entry.get("seat_height_min_ratio", self.config.seat_height_min_ratio) + max_ratio = entry.get("seat_height_max_ratio", self.config.seat_height_max_ratio) + bbox = entry.get("force_bbox", self.config.force_bbox) + bbox_ratio = entry.get("force_bbox_ratio", self.config.force_bbox_ratio) + + seat_nodes_mask, mode_used, bbox_desc = _select_nodes_for_mode( + mode, top_percent, min_ratio, max_ratio, bbox, bbox_ratio + ) + + num_seat_nodes = int(seat_nodes_mask.sum().item()) + if num_seat_nodes < 1: + logging.warning(f" ⚠️ entry[{entry_label}]matched no nodes, skip") + continue + + force_per_node = entry_force_tensor / num_seat_nodes + self.forces[seat_nodes_mask] += force_per_node + combined_mask |= seat_nodes_mask + + seat_y_values = y_coords[seat_nodes_mask] + seat_y_min = seat_y_values.min().item() + seat_y_max = seat_y_values.max().item() + seat_y_mean = seat_y_values.mean().item() + + if initial_setup: + if mode_used == "bbox": + logging.info(f" 🪑 contact surface[{entry_label}]: bbox ({bbox_desc})") + elif mode_used == "height_ratio": + logging.info( + f" 🪑 contact surface[{entry_label}]: height_ratio " + f"[{min_ratio:.2f}, {max_ratio:.2f}]" + ) + elif mode_used == "global": + logging.info(f" 🪑 contact surface[{entry_label}]: global") + else: + logging.info( + f" 🪑 contact surface[{entry_label}]: highest-Y {float(top_percent):.1%} nodes" + ) + logging.info( + f" 🪑 seat-node count[{entry_label}]: {num_seat_nodes}/{num_nodes} " + f"({num_seat_nodes/num_nodes:.1%})" + ) + logging.info( + f" 🪑 Y range[{entry_label}]: [{seat_y_min:.3f}, {seat_y_max:.3f}], " + f"mean: {seat_y_mean:.3f}" + ) + logging.info(f" 💺 force[{entry_label}]: {entry_force}") + logging.info(f" 💺 per node[{entry_label}]: {force_per_node.cpu().numpy()}") + + self.total_force_preset = total_force + actual_total_force = self.forces.sum(dim=0) + force_error = torch.norm(actual_total_force - total_force).item() + force_error_percent = (force_error / (torch.norm(total_force).item() + 1e-10)) * 100 + + if initial_setup: + logging.info( + f" ✅ total-force check: {actual_total_force.cpu().numpy()} " + f"(error: {force_error:.2e}, {force_error_percent:.3f}%)" + ) + if combined_mask.any(): + self._save_force_visualization( + combined_mask, total_force.cpu().numpy() + ) + else: + logging.debug( + f" 🔄 force update: loaded nodes {int(combined_mask.sum().item())}, " + f"total force error {force_error:.2e}" + ) + + self._last_num_seat_nodes = int(combined_mask.sum().item()) + return + + # Contact-region selection supports top_percent / height_ratio / bbox. + mode = str(getattr(self.config, "force_region_mode", "top_percent")).lower() + seat_nodes_mask = torch.zeros(num_nodes, dtype=torch.bool, device=self.device) + mode_used = mode + bbox_desc = None + if mode_used not in ("top_percent", "height_ratio", "bbox"): + logging.warning(f" ⚠️ invalid force_region_mode: {mode_used}, fallback to top_percent") + mode_used = "top_percent" + + if mode_used == "bbox": + bbox = getattr(self.config, "force_bbox", None) + bbox_ratio = getattr(self.config, "force_bbox_ratio", None) + bbox_vals = None + if bbox is not None and len(bbox) == 6: + bbox_vals = [float(v) for v in bbox] + bbox_desc = "abs" + elif bbox_ratio is not None and len(bbox_ratio) == 6: + bbox_ratio_vals = [float(v) for v in bbox_ratio] + bounds_min = self.nodes.min(dim=0).values + bounds_max = self.nodes.max(dim=0).values + bbox_vals = [ + bounds_min[0].item() + bbox_ratio_vals[0] * (bounds_max[0] - bounds_min[0]).item(), + bounds_min[0].item() + bbox_ratio_vals[1] * (bounds_max[0] - bounds_min[0]).item(), + bounds_min[1].item() + bbox_ratio_vals[2] * (bounds_max[1] - bounds_min[1]).item(), + bounds_min[1].item() + bbox_ratio_vals[3] * (bounds_max[1] - bounds_min[1]).item(), + bounds_min[2].item() + bbox_ratio_vals[4] * (bounds_max[2] - bounds_min[2]).item(), + bounds_min[2].item() + bbox_ratio_vals[5] * (bounds_max[2] - bounds_min[2]).item(), + ] + bbox_desc = "ratio" + else: + logging.warning(" ⚠️ bbox mode did not provide a valid bbox, fallback to top_percent") + mode_used = "top_percent" + + if mode_used == "bbox" and bbox_vals is not None: + x0, x1 = sorted([bbox_vals[0], bbox_vals[1]]) + y0, y1 = sorted([bbox_vals[2], bbox_vals[3]]) + z0, z1 = sorted([bbox_vals[4], bbox_vals[5]]) + seat_nodes_mask = ( + (self.nodes[:, 0] >= x0) & (self.nodes[:, 0] <= x1) + & (self.nodes[:, 1] >= y0) & (self.nodes[:, 1] <= y1) + & (self.nodes[:, 2] >= z0) & (self.nodes[:, 2] <= z1) + ) + if seat_nodes_mask.sum().item() < 1: + logging.warning(" ⚠️ bbox region matched no nodes, fallback to top_percent") + mode_used = "top_percent" + else: + bbox_desc = f"{bbox_desc}: [{x0:.3f},{x1:.3f}]x[{y0:.3f},{y1:.3f}]x[{z0:.3f},{z1:.3f}]" + + if mode_used == "height_ratio": + y_min = y_coords.min().item() + y_max = y_coords.max().item() + y_range = max(1e-8, y_max - y_min) + min_ratio = float(self.config.seat_height_min_ratio) + max_ratio = float(self.config.seat_height_max_ratio) + if not (0.0 <= min_ratio < max_ratio <= 1.0): + logging.warning( + f" ⚠️ invalid height_ratio: min={min_ratio}, max={max_ratio}, fallback to top_percent" + ) + mode_used = "top_percent" + else: + seat_y_min = y_min + y_range * min_ratio + seat_y_max = y_min + y_range * max_ratio + seat_nodes_mask = (y_coords >= seat_y_min) & (y_coords <= seat_y_max) + if seat_nodes_mask.sum().item() < 1: + logging.warning(" ⚠️ height_ratio matched no nodes, fallback to top_percent") + mode_used = "top_percent" + + if mode_used == "top_percent": + top_percent = float(getattr(self.config, "force_top_percent", 0.05)) + top_percent = max(0.0, min(1.0, top_percent)) + if top_percent <= 0.0: + top_percent = 0.05 + num_seat_nodes = max(1, int(num_nodes * top_percent)) + _, top_indices = torch.topk(y_coords, k=num_seat_nodes, largest=True) + seat_nodes_mask = torch.zeros(num_nodes, dtype=torch.bool, device=self.device) + seat_nodes_mask[top_indices] = True + + num_seat_nodes = int(seat_nodes_mask.sum().item()) + + # Step 3: gather region statistics. + seat_y_values = y_coords[seat_nodes_mask] + seat_y_min = seat_y_values.min().item() + seat_y_max = seat_y_values.max().item() + seat_y_mean = seat_y_values.mean().item() + + # Step 4: computation the per-node load with uniform distribution. + force_per_node = self.total_force_preset / num_seat_nodes + + # Initialize all node forces to zero. + self.forces = torch.zeros((num_nodes, 3), dtype=torch.float32, device=self.device) + + # Apply force only to the selected seat/contact nodes. + self.forces[seat_nodes_mask] = force_per_node + + # Step 5: verify total-force conservation. + actual_total_force = self.forces.sum(dim=0) + force_error = torch.norm(actual_total_force - self.total_force_preset).item() + force_error_percent = (force_error / torch.norm(self.total_force_preset).item()) * 100 + + # Logging. + if initial_setup: + if mode_used == "bbox": + logging.info(f" 🪑 contact-surface setup: bbox ({bbox_desc})") + elif mode_used == "height_ratio": + logging.info( + f" 🪑 contact-surface setup: height_ratio " + f"[{self.config.seat_height_min_ratio:.2f}, {self.config.seat_height_max_ratio:.2f}]" + ) + else: + logging.info( + f" 🪑 contact-surface setup: highest-Y {float(getattr(self.config, 'force_top_percent', 0.05)):.1%} nodes" + ) + logging.info(f" 🪑 seat-node count: {num_seat_nodes}/{num_nodes} ({num_seat_nodes/num_nodes:.1%})") + logging.info(f" 🪑 Y-coordinate range: [{seat_y_min:.3f}, {seat_y_max:.3f}], mean: {seat_y_mean:.3f}") + logging.info(f" 💺 preset total force: {self.total_force_preset.cpu().numpy()}") + logging.info(f" 💺 force per node: {force_per_node.cpu().numpy()}") + logging.info(f" ✅ total-force check: {actual_total_force.cpu().numpy()} (error: {force_error:.2e}, {force_error_percent:.3f}%)") + + # Estimate the equivalent pressure. + y_range = y_coords.max().item() - y_coords.min().item() + grid_spacing = y_range / self.config.res if y_range > 0 else 0.01 + estimated_area = num_seat_nodes * (grid_spacing ** 2) + if estimated_area > 0 and abs(self.total_force_preset[1].item()) > 0: + pressure_kpa = abs(self.total_force_preset[1].item()) / estimated_area / 1000 + logging.info(f" 📏 equivalent pressure: {pressure_kpa:.1f} kPa (contact area≈{estimated_area:.4f} m²)") + + if pressure_kpa < 5: + logging.warning(f" ⚠️ pressure is too small ({pressure_kpa:.1f} kPa < 5 kPa)") + elif pressure_kpa > 50: + logging.warning(f" ⚠️ pressure is too large ({pressure_kpa:.1f} kPa > 50 kPa)") + + # Save visualization data. + self._save_force_visualization(seat_nodes_mask, self.total_force_preset.cpu().numpy()) + else: + # Shorter logging during optimization. + logging.debug(f" 🔄 force update: seat nodes {num_seat_nodes}, per node {force_per_node.cpu().numpy()}, " + f"total force error {force_error:.2e}") + + # Watch for changes in the number of loaded nodes. + if hasattr(self, '_last_num_seat_nodes') and self._last_num_seat_nodes != num_seat_nodes: + logging.info(f" ⚠️ seat-node count changed: {self._last_num_seat_nodes} → {num_seat_nodes}") + + # Cache the current state for the next comparison. + self._last_num_seat_nodes = num_seat_nodes + + def extract_solid(self, step: int = -1): + """Extract the physical solid by querying the node SDF directly. + + This method rebuilds the FEM mesh from the current latents so topology + changes in the SDF field can be reflected by the simulation mesh. + + Args: + step: Current optimization step, used for logging. + """ + if not WARP_AVAILABLE: + logging.warning("Warpnot installed, unable toperformphysics simulation") + return + + # Re-check physiopt availability at runtime. + try: + from physiopt.utils.phys_utils import generate_hex as _generate_hex + from physiopt.utils.grid_utils import filter_one_component as _filter_one_component + from physiopt.opt.field import occ_kernel as _occ_kernel + generate_hex_func = _generate_hex + filter_one_component_func = _filter_one_component + occ_kernel_func = _occ_kernel + logging.info("✅ physioptmoduleruntime check succeeded") + except ImportError as e: + logging.error(f"physioptmodulenot installed: {e}") + logging.error("please make sure physiopt is installed correctly: cd /mnt/cvlab/scratch/cvlab/home/hantzhan/physiopt && pip install -e .") + return + + res = self.config.res + step_label = f"Step {step}" if step >= 0 else "Initialization" + logging.info(f"{'🔄' if step >= 0 else '🆕'} [{step_label}] generate/update a mesh at resolution {res} hexahedral mesh...") + + # Keep the previous mesh size for comparison. + old_num_nodes = len(self.nodes) if hasattr(self, 'nodes') else 0 + old_num_elements = len(self.elements) if hasattr(self, 'elements') else 0 + + # 1. Generate the full hexahedral grid. + full_nodes, full_elements = generate_hex_func( + res=res, + limits=[(-0.8, 0.8), (-0.8, 0.8), (-0.8, 0.8)], + device=self.device, + return_coords=False + ) + + if full_nodes is None or full_elements is None: + logging.error("failed to generate the hexahedral mesh") + return + + full_nodes = full_nodes.to(self.device).float() + full_elements = full_elements.to(self.device).long() + + logging.info(f"hexahedral mesh generated successfully: {full_nodes.shape[0]}nodes, {full_elements.shape[0]}elements") + + # 2. Query the SDF directly through get_field. + logging.info("query node SDF values...") + sdf = self.get_field(full_nodes) + + # Make sure the SDF is a 1D tensor [N]. + if sdf.dim() > 1: + logging.warning(f"⚠️ SDFYesmulti-dimensional tensor: {sdf.shape}, will be flattened to 1D") + sdf = sdf.squeeze() # remove all size-1 dimensions + if sdf.dim() > 1: + sdf = sdf.reshape(-1) # force-flatten to 1D + + logging.info(f" ✅ SDF query succeeded: range=[{sdf.min():.3f}, {sdf.max():.3f}]") + logging.info(f" nodescount: {full_nodes.shape[0]}, SDF count: {sdf.shape[0]}") + + # Verify that the SDF count matches the node count. + if sdf.shape[0] != full_nodes.shape[0]: + logging.error(f"❌ SDF count({sdf.shape[0]}) vs. node count ({full_nodes.shape[0]})do not match!") + return + + # 3. Convert SDF values to occupancy. + logging.info("convert the SDF into an occupancy field...") + occ = occ_kernel_func(sdf, res, self.config.occ_sdf_beta) + + # 4. Select solid elements using an SDF threshold instead of an + # occupancy threshold. The threshold is intentionally relaxed so thin + # structures such as chair legs are kept. + SDF_FILTER_VALUE = 2.0 / res + nodewise_mask = sdf <= SDF_FILTER_VALUE + + # Diagnostic SDF statistics. + sdf_inside = sdf[nodewise_mask] + sdf_outside = sdf[~nodewise_mask] + logging.info(f" SDF threshold: {SDF_FILTER_VALUE:.4f}") + logging.info(f" interior nodes: {nodewise_mask.sum().item()}/{len(sdf)} ({100*nodewise_mask.sum().item()/len(sdf):.1f}%)") + if len(sdf_inside) > 0: + logging.info(f" inner SDF range: [{sdf_inside.min():.4f}, {sdf_inside.max():.4f}]") + if len(sdf_outside) > 0: + logging.info(f" outside-SDF range: [{sdf_outside.min():.4f}, {sdf_outside.max():.4f}]") + + # Debug the element-index range. + max_elem_idx = full_elements.max().item() + num_nodes = full_nodes.shape[0] + logging.info(f" elementsindex range: [0, {max_elem_idx}], nodescount: {num_nodes}") + + if max_elem_idx >= num_nodes: + logging.error(f"❌ index out of bounds!maximum element index({max_elem_idx}) >= nodescount({num_nodes})") + logging.error(f" this may be a problem with generate_hex") + # Clamp indices to the valid range. + valid_mask = (full_elements >= 0) & (full_elements < num_nodes) + if not valid_mask.all(): + logging.warning(f" found{(~valid_mask).sum().item()} invalid indices; filtering elements") + # Keep only elements whose node indices are all valid. + valid_elements_mask = valid_mask.all(dim=1) + full_elements = full_elements[valid_elements_mask] + logging.info(f" element count after filtering: {full_elements.shape[0]}") + + # Keep an element if any of its nodes passes the threshold. + elementwise_mask = torch.any(nodewise_mask[full_elements], dim=1) + + num_solid_elements = elementwise_mask.sum().item() + logging.info(f"SDF thresholdfiltering: {num_solid_elements}/{len(elementwise_mask)} solid elements") + + if num_solid_elements == 0: + logging.error("No solid elements were found; please check the SDF or adjust the threshold") + return + + # 5. Optionally keep only one connected component. + if self.config.one_cc_only: + element_res = res - 1 + try: + num_before_filter = elementwise_mask.sum().item() + elementwise_mask = filter_one_component_func(elementwise_mask, element_res) + num_filtered_elements = elementwise_mask.sum().item() + num_removed = num_before_filter - num_filtered_elements + logging.info(f"connectivity filtering: {num_filtered_elements} elements kept (removed{num_removed} small components)") + if num_removed > num_filtered_elements * 0.1: + logging.warning(f" ⚠️ removed{num_removed}elements({100*num_removed/num_before_filter:.1f}%), may have filtered out important parts (such as chair legs) ") + logging.warning(f" Suggestion: check the SDF threshold or consider disabling one_cc_only") + except IndexError as e: + logging.warning(f"connectivity filteringfailed: {e}, using the original mask") + else: + logging.info("connectivity filteringdisabled, keep all connected components") + + # 6. Select the active elements and nodes. + selected_elements = full_elements[elementwise_mask] + selected_node_indices, selected_elements = torch.unique( + selected_elements, return_inverse=True + ) + + self.elements = selected_elements + self.nodes = full_nodes[selected_node_indices] + + # 7. Compute occupancy for the selected nodes used in the simulation. + coarse_sdf = sdf[selected_node_indices] + coarse_occ_nodes = occ_kernel_func( + coarse_sdf, self.config.res, self.config.occ_sdf_beta + ) + # Each element occupancy is the mean over its 8 nodes. + self.coarse_occ = coarse_occ_nodes[self.elements].mean(1) + + # Diagnostic statistics for mesh-size changes. + new_num_nodes = len(self.nodes) + new_num_elements = len(self.elements) + + if old_num_nodes > 0: + node_change = new_num_nodes - old_num_nodes + element_change = new_num_elements - old_num_elements + node_change_pct = (node_change / old_num_nodes) * 100 + element_change_pct = (element_change / old_num_elements) * 100 + + logging.info(f"✅ solid extraction completed:") + logging.info(f" nodes: {old_num_nodes} → {new_num_nodes} ({node_change:+d}, {node_change_pct:+.1f}%)") + logging.info(f" elements: {old_num_elements} → {new_num_elements} ({element_change:+d}, {element_change_pct:+.1f}%)") + + if node_change > 0: + logging.info(f" ✅ mesh expanded!added{node_change}nodes (chair legs may have thickened) ") + elif node_change < 0: + logging.warning(f" ⚠️ mesh shrank!removed{-node_change}nodes (chair legs may have become thinner) ") + else: + logging.info(f"✅ solid extraction succeeded: {new_num_nodes}nodes, {new_num_elements}elements") + + # 8. Recomputation the boundary mask because the node count may change. + y_coords = self.nodes[:, 1] + y_min = y_coords.min() + boundary_threshold = y_min + 0.05 # bottom 5% region + self.boundary_mask = y_coords < boundary_threshold + + num_boundary = self.boundary_mask.sum().item() + logging.debug(f" 🔧 boundary conditionsupdated: {num_boundary}fixed nodes (Y < {boundary_threshold:.3f})") + + def get_current_sds_weight(self, step: int) -> float: + """Return the current SDS weight by linear interpolation. + + Args: + step: Current optimization step. + + Returns: + The SDS weight interpolated from sds_weight_start to sds_weight_end. + """ + # Linear interpolation from sds_weight_start to sds_weight_end. + progress = min(1.0, step / max(1, self.config.num_steps - 1)) + current_weight = self.config.sds_weight_start + progress * (self.config.sds_weight_end - self.config.sds_weight_start) + return current_weight + + def _computation_target_z0_current(self, step: int) -> Tuple[torch.Tensor, torch.Tensor]: + """Compute the current target_z0 for one update.""" + noise_level = float(self.config.sds_timestep) + t = 1.0 - noise_level # Hunyuan3D-2.1 uses t=0 for noise and t=1 for data. + epsilon = torch.randn_like(self.latents) + + self.sds_scheduler.config.num_train_timesteps = 100 + if self.sds_scheduler is not None: + # Match the official Flow Matching noise process: + # x_t = (1 - sigma) * x0 + sigma * eps. + sigma_step = 1.0 / float(self.sds_scheduler.config.num_train_timesteps) + total_span = max(0.0, 1.0 - t) + num_steps = int(np.ceil(total_span / sigma_step)) + sigmas = np.linspace(t, 1.0, num_steps + 1, dtype=np.float32) + self.sds_scheduler.set_timesteps(sigmas=sigmas, device=self.device) + t_scheds = self.sds_scheduler.timesteps + t_sched0 = t_scheds[0] + t_model0 = (t_sched0 / self.sds_scheduler.config.num_train_timesteps).to(self.latents.dtype) + if step % max(1, int(self.config.sds_target_z0_update_interval)) == 0: + logging.info( + f" 🎯 target_z0/sigmaalign: noise={noise_level:.4f}, t_start={t:.4f}, " + f"t_sched={t_sched0.item():.2f}, t_model={t_model0.item():.6f}, " + f"steps={num_steps}, sigma_step={sigma_step:.4g}" + ) + else: + t_sched = None + z_t = (1 - t) * epsilon + t * self.latents + t_model = torch.tensor([t], device=self.device, dtype=self.latents.dtype) + + with torch.no_grad(): + if self.sds_scheduler is not None: + # Integrate over multiple small sigma steps from sigma=t to 0. + cond_for_model = self._get_cond_for_guidance(self.config.guidance_scale > 1.0) + t_sched0 = t_scheds[0] + t_sched_batch = t_sched0.reshape(1).expand(self.latents.shape[0]) + # Hunyuan3D convention: t=0 is noise and t=1 is data. + z_t = self.sds_scheduler.scale_noise(epsilon, t_sched_batch, noise=self.latents) + + z_curr = z_t + velocity = None + for i in range(len(t_scheds) - 1): + t_sched = t_scheds[i] + t_model = (t_sched / self.sds_scheduler.config.num_train_timesteps).to(self.latents.dtype) + z_t_fp16 = z_curr.to(torch.float16) + t_tensor = t_model.to(device=self.device, dtype=z_t_fp16.dtype) + + if self.config.guidance_scale > 1.0: + latent_model_input = torch.cat([z_t_fp16, z_t_fp16]) + timestep_input = t_tensor.expand(latent_model_input.shape[0]) + + velocity_pred_fp16 = self.flow_model( + latent_model_input, + timestep_input, + cond_for_model, + guidance=None, + ) + + velocity_cond_fp16, velocity_uncond_fp16 = velocity_pred_fp16.chunk(2) + velocity_fp16 = velocity_uncond_fp16 + self.config.guidance_scale * (velocity_cond_fp16 - velocity_uncond_fp16) + + if step % 10 == 0 and i == 0: + logging.debug( + f" CFG (SDS): guidance_scale={self.config.guidance_scale:.1f}, " + f"||v_cond||={torch.norm(velocity_cond_fp16).item():.3e}, " + f"||v_uncond||={torch.norm(velocity_uncond_fp16).item():.3e}" + ) + else: + velocity_fp16 = self.flow_model( + z_t_fp16, + t_tensor.expand(z_t_fp16.shape[0]), + cond_for_model, + guidance=None, + ) + + velocity = velocity_fp16.to(torch.float32) + z_curr = self.sds_scheduler.step(velocity, t_sched, z_curr).prev_sample + + target_z0_current = z_curr + else: + cond_for_model = self._get_cond_for_guidance(self.config.guidance_scale > 1.0) + z_t_fp16 = z_t.to(torch.float16) + t_tensor = t_model.to(device=self.device, dtype=z_t_fp16.dtype) + + if self.config.guidance_scale > 1.0: + latent_model_input = torch.cat([z_t_fp16, z_t_fp16]) + timestep_input = t_tensor.expand(latent_model_input.shape[0]) + + velocity_pred_fp16 = self.flow_model( + latent_model_input, + timestep_input, + cond_for_model, + guidance=None, + ) + + velocity_cond_fp16, velocity_uncond_fp16 = velocity_pred_fp16.chunk(2) + velocity_fp16 = velocity_uncond_fp16 + self.config.guidance_scale * (velocity_cond_fp16 - velocity_uncond_fp16) + + if step % 10 == 0: + logging.debug( + f" CFG (SDS): guidance_scale={self.config.guidance_scale:.1f}, " + f"||v_cond||={torch.norm(velocity_cond_fp16).item():.3e}, " + f"||v_uncond||={torch.norm(velocity_uncond_fp16).item():.3e}" + ) + else: + velocity_fp16 = self.flow_model( + z_t_fp16, + t_tensor.expand(z_t_fp16.shape[0]), + cond_for_model, + guidance=None, + ) + + velocity = velocity_fp16.to(torch.float32) + # Fallback: one forward-Euler step to t=1. + target_z0_current = z_t + (1.0 - t) * velocity + + # Optional trust region to keep target_z0 from moving too far away. + max_rel = float(getattr(self.config, "sds_projection_max_rel", 0.0)) + if max_rel > 0.0: + with torch.no_grad(): + diff = target_z0_current - self.latents + diff_norm = torch.norm(diff).item() + latents_norm = torch.norm(self.latents).item() + max_norm = max_rel * (latents_norm + 1e-8) + if diff_norm > max_norm and max_norm > 0.0: + scale = max_norm / (diff_norm + 1e-8) + target_z0_current = self.latents + diff * scale + if step % max(1, int(self.config.sds_target_z0_update_interval)) == 0: + logging.info( + f" 🧱 target_z0 projection limit: diff={diff_norm:.3e} → {max_norm:.3e} " + f"(rel={max_rel:.2f})" + ) + return target_z0_current, velocity + + def _get_target_z0(self, step: int) -> Tuple[torch.Tensor, Optional[torch.Tensor], bool]: + """Update target_z0 on schedule and smooth it with EMA.""" + update_interval = max(1, int(self.config.sds_target_z0_update_interval)) + do_update = self.target_z0_ema is None or step % update_interval == 0 + + if do_update: + target_z0_current, velocity = self._computation_target_z0_current(step) + target_z0_current = target_z0_current.detach() + + if self.target_z0_ema is None: + self.target_z0_ema = target_z0_current.clone() + diff_norm = 0.0 + else: + diff = target_z0_current - self.target_z0_ema + diff_norm = torch.norm(diff).item() + alpha = 1.0 - self.config.sds_target_z0_ema_beta + self.target_z0_ema = self.target_z0_ema + alpha * diff + + self.target_z0_last_velocity = velocity + self.target_z0_last_update = step + + if step % update_interval == 0: + logging.info( + f" 🧭 target_z0 EMAupdate: interval={update_interval}, " + f"beta={self.config.sds_target_z0_ema_beta:.2f}, diff_norm={diff_norm:.3e}" + ) + else: + velocity = self.target_z0_last_velocity + + return self.target_z0_ema, velocity, do_update + + def project_to_manifold(self, step: int) -> bool: + """Project the current latents back to the manifold by replacing them with target_z0.""" + with torch.no_grad(): + target_z0, _ = self._computation_target_z0_current(step) + if torch.isnan(target_z0).any() or torch.isinf(target_z0).any(): + logging.warning(" ⚠️ projection failed: target_z0 contains NaN/Inf") + return False + deviation = torch.norm(target_z0 - self.latents).item() + latents_norm = torch.norm(self.latents).item() + rel = deviation / (latents_norm + 1e-8) + logging.info(f" 🧭 projection deviation: {deviation:.3e} (rel={rel:.2%})") + self.latents.data.copy_(target_z0) + if self.latents.grad is not None: + self.latents.grad.zero_() + # Reset optimizer state to avoid stale momentum. + self.optimizer.state.clear() + # Sync the EMA cache with the projected state. + self.target_z0_ema = target_z0.detach().clone() + self.target_z0_last_velocity = None + self.target_z0_last_update = step + return True + + def training_step_sds(self, step: int) -> Tuple[float]: + """Run one SDS optimization step. + + Returns: + (recon_loss,) + """ + self.optimizer.zero_grad() + + # ==================== SDS loss (Rectified Flow) ==================== + t = self.config.sds_timestep + target_z0, velocity, _ = self._get_target_z0(step) + + # SDS gradient: grad = z_0 - target_z0. + # This pulls the current z_0 (self.latents) toward target_z0. + sds_gradient = self.latents - target_z0.detach() + recon_loss = torch.mean(sds_gradient ** 2) / 2 + + # Debug information. + with torch.no_grad(): + target_norm = torch.norm(target_z0).item() + current_norm = torch.norm(self.latents).item() + grad_norm = torch.norm(sds_gradient).item() + velocity_norm = torch.norm(velocity).item() if velocity is not None else 0.0 + + logging.info(f"📐 Step {step:3d} | SDS: ||z_0||={current_norm:.2e}, " + f"||target_z_0||={target_norm:.2e}, " + f"||v||={velocity_norm:.2e}, " + f"||∇||={grad_norm:.2e}, t={t:.2f}, loss={recon_loss.item():.6e}") + + # Backpropagation. + sds_gradient_scaled = self.config.sds_weight * sds_gradient + + # Guard against invalid gradients. + if torch.isnan(sds_gradient_scaled).any() or torch.isinf(sds_gradient_scaled).any(): + logging.error(f"❌ Error: SDS gradient contains NaN or Inf!") + logging.error(f" ||sds_gradient||: {grad_norm:.2e}") + logging.error(f" sds_weight: {self.config.sds_weight}") + logging.error(f" target_z0 range: [{target_z0.min().item():.2e}, {target_z0.max().item():.2e}]") + logging.error(f" latents range: [{self.latents.min().item():.2e}, {self.latents.max().item():.2e}]") + if velocity is not None: + logging.error(f" velocity range: [{velocity.min().item():.2e}, {velocity.max().item():.2e}]") + return (recon_loss.item(),) + + if self.latents.grad is not None: + self.latents.grad.zero_() + + self.latents.grad = sds_gradient_scaled + + # Optional gradient clipping. + if self.config.grad_clip_enabled: + grad_norm_total = torch.norm(self.latents.grad).item() + max_grad_norm = 100.0 # 1e5lower to100 + if grad_norm_total > max_grad_norm: + clip_factor = max_grad_norm / grad_norm_total + self.latents.grad *= clip_factor + logging.warning(f"⚠️ gradient clipping: {grad_norm_total:.4e} -> {max_grad_norm:.4e}") + + # Save the pre-update latents for diagnostics. + old_latents = self.latents.data.clone() + + # Re-check the gradient before the optimizer step. + if torch.isnan(self.latents.grad).any(): + logging.error(f"❌ Error: gradient contains NaN (optimizerupdatefront) !") + return (recon_loss.item(),) + + # Optimizer update. + self.optimizer.step() + + # Measure parameter change after the update. + param_change = torch.norm(self.latents.data - old_latents).item() + + # Validate the updated latents. + if torch.isnan(self.latents).any(): + logging.error(f"❌ Error: latents contain NaN (optimizerupdateback) !") + logging.error(f" gradient norm: {grad_norm_total:.4e}") + logging.error(f" Learning rate: {self.config.lr}") + logging.error(f" Param change: {param_change:.4e}") + logging.error(f" suggestion: this may be caused by Adam optimizer momentum") + logging.error(f" : 1) reset optimizer 2) Use SGD instead of Adam") + # Restore the previous value. + self.latents.data.copy_(old_latents) + # Clear optimizer momentum/state before retrying. + self.optimizer.state.clear() + logging.info(f" ✅ already reset optimizerStatus, will retry on the next step") + return (recon_loss.item(),) + + # Sanity-check the latent magnitude. + latents_max = torch.abs(self.latents).max().item() + if latents_max > 1000: + logging.warning(f"⚠️ warning: latent values are too large (max={latents_max:.2e})") + logging.warning(f" you may need to lower the learning rate or SDS timestep") + + logging.info(f"✏️ Step {step:3d} | Param change: {param_change:.4e}, max|z|: {latents_max:.2e}") + + return (recon_loss.item(),) + + def training_step( + self, + step: int, + lagrange: float, + rho: float, + lambda_reg: float, + use_sds: bool = True, + save_step: Optional[int] = None, + ) -> Tuple[float, float, float]: + """Physics optimization. + + This follows the computation_phys_loss_grad flow from viewer_base.py: + 1. optimizer.zero_grad() + 2. with torch.no_grad(): prepare_solid() + solve() + 3. Compute sensitivities with the reference-style formula + 4. backward_step() via VJP + 5. Apply ALM weighting (lambda + rho[g]_+) + 6. optimizer.step() + + Reference: + physiopt/src/physiopt/vis/viewer_base.py Line 1297-1430 + """ + save_step_id = step if save_step is None else int(save_step) + + # ==================== Step 1: zero gradients ==================== + self.optimizer.zero_grad() + + # ==================== Step 2: update occupancy on the fixed topology ==================== + if step > 0: + logging.info(f"🔄 [Step {step}] update occupancy (mesh topology fixed) ...") + # Keep the previous occupancy for diagnostics. + old_occ = self.coarse_occ.clone() + + # Re-query the SDF and occupancy on the fixed mesh. + sdf = self.get_field(self.nodes) + from physiopt.opt.field import occ_kernel + occ = occ_kernel(sdf, self.config.res, self.config.occ_sdf_beta) + self.coarse_occ = occ[self.elements].mean(1) + + # Diagnose occupancy changes. + occ_change = self.coarse_occ - old_occ + occ_mean_change = occ_change.mean().item() + occ_increase_ratio = (occ_change > 0).float().mean().item() + + logging.info(f" occupancy range: [{self.coarse_occ.min():.3f}, {self.coarse_occ.max():.3f}]") + logging.info(f" occupancy change: mean={occ_mean_change:+.3e}, increase ratio={occ_increase_ratio:.1%}") + + # ==================== Step 3: physics simulation (with torch.no_grad) ==================== + # Aligned with the reference flow around Line 1317-1356. + with torch.no_grad(): + # 3.1 prepare_solid: apply SIMP scaling and build SolidGrid. + if self.config.alpha_min > 0.0: + self.coarse_occ = torch.clamp(self.coarse_occ, self.config.alpha_min) + + # Material SIMP scaling. + from torchfem.materials import IsotropicElasticity3D + from physiopt.opt.solid_grid import SolidGrid + + vectorized_material = IsotropicElasticity3D( + E=self.config.youngs_modulus, + nu=self.config.poissons_ratio, + rho=self.config.density, + ).vectorize(self.elements.shape[0]) + + vectorized_material.C *= ( + self.coarse_occ[:, None, None] ** self.config.p_exponent + ) + + # Create the SolidGrid solver state. + solid = SolidGrid(self.nodes, self.elements, vectorized_material) + solid.constraints[self.boundary_mask, :] = True + solid.forces = self.forces + + # 3.2 FEM solve. + logging.info(f"Step {step}: FEM solve...") + u, f_int, f_ext, sigma, _, _ = solid.solve(max_iter=1) + u_mean = torch.abs(u).mean().item() + logging.info(f" |u|_mean={u_mean}") + self._log_physical_quantities(u, sigma) + + # Save the deformed mesh every N steps. + # if self.config.deformed_mesh_interval > 0 and save_step_id % self.config.deformed_mesh_interval == 0: + # try: + # self.save_deformed_mesh(save_step_id, u) + # except Exception as e: + # logging.warning(f" ⚠️ error while saving the deformed mesh: {e}") + + # ==================== Step 4: sensitivity computation ==================== + # Strictly aligned with the reference flow around Line 1368-1399. + + # 4.1 Compute strain energy. We recover the unweighted energy by + # dividing out occ^p and keep strong numerical guards. + k0 = solid.k0() # occ^p * K_base after stiffness scaling. + u_j = u[self.elements].reshape(solid.n_elem, -1) + w_k_scaled = torch.einsum("...i, ...ij, ...j", u_j, k0, u_j) + + # Remove occ^p scaling to recover the base energy. + occ_power = torch.clamp( + self.coarse_occ ** self.config.p_exponent, + min=1e-6, # Avoid division by zero. + max=1.0 # Avoid overflow. + ) + + # Check again before division. + if torch.any(occ_power < 1e-6): + n_small = (occ_power < 1e-6).sum().item() + logging.warning(f" ⚠️ {n_small} elements have extremely small occ^p and were clamped to 1e-6") + + w_k_base = w_k_scaled / occ_power + + # Fall back if the recovered energy becomes invalid. + if torch.isnan(w_k_base).any() or torch.isinf(w_k_base).any(): + n_nan = torch.isnan(w_k_base).sum().item() + n_inf = torch.isinf(w_k_base).sum().item() + logging.error(f" ❌ w_k_baseabnormal: {n_nan} NaN, {n_inf} Inf") + logging.error(f" fall back to SIMP weightingw_k") + w_k_base = w_k_scaled + + # Use the recovered energy downstream. + compliance_mean = w_k_base.mean().item() + w_k = w_k_base # Downstream sensitivity uses the recovered energy. + + # Diagnostics. + logging.info(f" Compliance (true) ={compliance_mean:.2e}") + logging.info(f" w_k_base: max={w_k.max():.2e}, stress concentration={w_k.max()/(w_k.mean() + 1e-10):.1f}x") + + # ALM normalized constraint: g = D / D_thr - 1. + compliance_threshold = self.config.compliance_threshold if self.config.compliance_threshold is not None else 1.0 + g_raw = compliance_mean / (compliance_threshold + 1e-8) - 1.0 + g_pos = max(0.0, g_raw) + logging.info(f" constraint normalization: g={g_raw:+.3e}, [g]+={g_pos:.3e}, D_thr={compliance_threshold:.2e}") + + # Dynamic clip limit used by the ALM scaling guard. + base_max_grad = 1000.0 + lagrange_bonus = min((lagrange + rho * g_pos) * 10.0, 1000.0) + max_grad_norm = base_max_grad + lagrange_bonus + + # 4.3 Sensitivity formula aligned with the reference code: + # sensitivity = -p * occ^(p-1) * w_k + self.sensitivity_density = ( + -self.config.p_exponent + * self.coarse_occ ** (self.config.p_exponent - 1) + * w_k + ) + + # 4.4 Volume regularization is intentionally disabled here so the pure + # physics signal can be validated first. + if False and self.config.volume_term > 0.0: # Temporarily forced off. + # Initialize the reference volume on first use. + if not hasattr(self, 'init_volume'): + self.init_volume = self.coarse_occ.clone() + logging.info(f" record initial volume: sum={self.init_volume.sum().item():.2f}") + + # Volume sensitivity term. + sensitivity_volume = ( + self.config.volume_term + * (1.0 / self.config.res) ** 3 + * torch.ones_like(self.sensitivity_density) + ) + + # Choose the sign from the current volume change. + volume_sign = 1.0 if self.coarse_occ.sum() >= self.init_volume.sum() else -1.0 + sensitivity_volume *= volume_sign + + self.sensitivity_density += sensitivity_volume + + volume_ratio = self.coarse_occ.sum() / self.init_volume.sum() + logging.info(f" volume constraint: ratio={volume_ratio.item():.3f}, " + f"{'penalize' if volume_sign > 0 else 'encourage'}") + else: + logging.info(f" volume constraint: disabled (physicsoptimizationdominates) ") + + # Sensitivity diagnostics. + sens_norm = torch.norm(self.sensitivity_density).item() + sens_min = self.sensitivity_density.min().item() + sens_max = self.sensitivity_density.max().item() + logging.info(f" sensitivity: norm={sens_norm:.2e}, range=[{sens_min:.2e}, {sens_max:.2e}]") + + # ==================== Step 5: backward pass via VJP ==================== + self.backward_step(self.sensitivity_density) + + # ==================== Step 6: apply ALM weighting (lambda + rho[g]+) ==================== + if self.latents.grad is not None: + phys_grad_norm = torch.norm(self.latents.grad).item() + phys_grad_unscaled = self.latents.grad.clone() # Unscaled physics gradient for SDS comparisons. + + if g_pos > 0.0: + alm_scale_raw = (lagrange + rho * g_pos) / (compliance_threshold + 1e-8) + alm_scale = alm_scale_raw + guard_ratio = min(max(self.config.alm_scale_guard_ratio, 0.0), 1.0) + if phys_grad_norm > 0.0 and max_grad_norm > 0.0 and guard_ratio > 0.0: + alm_scale_guard = (max_grad_norm * guard_ratio) / (phys_grad_norm + 1e-8) + if alm_scale > alm_scale_guard: + logging.info( + f" 🔧 ALMscaling limit: raw={alm_scale_raw:.3e} -> {alm_scale_guard:.3e} " + f"(guard={guard_ratio:.2f}, max_grad={max_grad_norm:.1f})" + ) + alm_scale = alm_scale_guard + self.latents.grad *= alm_scale + else: + alm_scale = 0.0 + self.latents.grad.zero_() + + scaled_grad_norm = torch.norm(self.latents.grad).item() + logging.info( + f" physics gradient(ALM): {phys_grad_norm:.2e} → {scaled_grad_norm:.2e} " + f"(×scale={alm_scale:.3e}, λ={lagrange:.2f}, ρ={rho:.2f})" + ) + else: + phys_grad_unscaled = None + alm_scale = 0.0 + + # ==================== Step 7: shape loss toward target_z0 ==================== + + # 7.1 Compute the denoised target_z0. + import math + if use_sds: + target_z0, _, _ = self._get_target_z0(step) + else: + target_z0 = self.latents.detach() + + # Optionally validate and save a target_z0 mesh every 10 steps. + if use_sds: + self._maybe_save_target_z0_mesh(target_z0, save_step_id) + + # Shape loss is a simple MSE pulling latents toward target_z0. + shape_loss = torch.nn.functional.mse_loss(self.latents, target_z0.detach()) + + # 7.2 Decide whether shape loss is active this step. + current_sds_weight = self.get_current_sds_weight(step) if use_sds else 0.0 + use_sds_this_step = current_sds_weight > 0.0 + + if not use_sds_this_step: + logging.info(f" 🚫 Shape Loss disabled (physicsoptimizationmode) ") + weighted_sds = 0.0 + shape_grad_norm = 0.0 + else: + # Weighted shape loss. + weighted_shape_loss = current_sds_weight * shape_loss + + # Validate shape loss before backpropagating it. + if torch.isnan(shape_loss) or torch.isinf(shape_loss): + logging.error(f" ❌ Shape Loss contains NaN or Inf; skipping the shape constraint") + weighted_sds = 0.0 + shape_grad_norm = 0.0 + else: + # Backpropagate the shape loss into latents.grad. + weighted_shape_loss.backward() + + # Measure the shape-gradient norm for logging. + if self.latents.grad is not None and phys_grad_unscaled is not None: + # Isolate the shape part from the combined gradient. + shape_gradient = self.latents.grad - phys_grad_unscaled * alm_scale + shape_grad_norm = torch.norm(shape_gradient).item() + phys_grad_norm_current = torch.norm(phys_grad_unscaled * alm_scale).item() + shape_phys_ratio = shape_grad_norm / (phys_grad_norm_current + 1e-10) + + if shape_phys_ratio > 100.0: + logging.error(f" ❌ Shape gradient is too large (Shape/physics={shape_phys_ratio:.1f}x)!") + logging.error(f" consider lowering sds_weight_end: {self.config.sds_weight_end} → {self.config.sds_weight_end/100:.4f}") + elif shape_phys_ratio > 10.0: + logging.warning(f" ⚠️ Shape gradient is relatively large (Shape/physics={shape_phys_ratio:.1f}x)") + + # Compare the directions of physics and shape gradients. + cos_angle = (phys_grad_unscaled * shape_gradient).sum() / ( + torch.norm(phys_grad_unscaled) * torch.norm(shape_gradient) + 1e-10 + ) + angle_deg = torch.acos(torch.clamp(cos_angle, -1, 1)) * 180 / math.pi + direction = "same direction✅" if angle_deg < 90 else "opposite direction⚠️" + + logging.info(f" Shapegradient: norm={shape_grad_norm:.4e}, weight={current_sds_weight:.6f}") + logging.info(f" gradient direction: physics vs Shape = {angle_deg:.1f}° ({direction})") + elif self.latents.grad is not None: + shape_grad_norm = torch.norm(self.latents.grad).item() + logging.info(f" Shapegradient: norm={shape_grad_norm:.4e} (no physics gradient)") + else: + shape_grad_norm = 0.0 + + weighted_sds = weighted_shape_loss.item() + + # ==================== Step 8: combine losses and clip if needed ==================== + compliance_loss_item = compliance_mean + alm_penalty = lagrange * g_pos + 0.5 * rho * (g_pos ** 2) + total_loss = alm_penalty + weighted_sds + + # Log the combined loss terms. + if use_sds_this_step: + logging.info( + f" 📊 weighted loss: Compliance={compliance_loss_item:.4e}, g={g_raw:+.3e}, " + f"ALM={alm_penalty:.4e} (λ={lagrange:.2f}, ρ={rho:.2f}), " + f"Shape={weighted_sds:.4e} (×w={current_sds_weight:.6f}), Total={total_loss:.4e}" + ) + else: + logging.info( + f" 📊 weighted loss: Compliance={compliance_loss_item:.4e}, g={g_raw:+.3e}, " + f"ALM={alm_penalty:.4e} (λ={lagrange:.2f}, ρ={rho:.2f}), " + f"Shape=0.00e+00 (disabled), Total={total_loss:.4e}" + ) + + # Log gradient composition details. + if self.latents.grad is not None: + grad_norm = torch.norm(self.latents.grad).item() + + # Report each gradient contribution. + if phys_grad_unscaled is not None: + weighted_phys_grad_norm = torch.norm(phys_grad_unscaled * alm_scale).item() + logging.info(f" 🔍 gradient composition: Weighted Compliance Grad={weighted_phys_grad_norm:.4e} (ALM scale={alm_scale:.3e})") + + if use_sds_this_step and shape_grad_norm > 0: + logging.info(f" Scaled Shape Grad={shape_grad_norm:.4e} (Shape×w={current_sds_weight:.6f})") + if phys_grad_unscaled is not None: + grad_ratio = shape_grad_norm / (weighted_phys_grad_norm + 1e-10) + logging.info(f" ratio: Shape/Compliance = {grad_ratio:.4f} ({grad_ratio*100:.2f}%)") + + logging.info(f" Total Grad={grad_norm:.4e}") + + # Optional gradient clipping. + if self.latents.grad is not None: + grad_norm = torch.norm(self.latents.grad).item() + + if torch.isnan(self.latents.grad).any() or torch.isinf(self.latents.grad).any(): + logging.error(f"❌ the final gradient contains NaN or Inf!skip this steps") + return (compliance_loss_item, u_mean, shape_loss.item(), total_loss) + + if self.config.grad_clip_enabled: + if grad_norm > max_grad_norm: + clip_factor = max_grad_norm / grad_norm + self.latents.grad = self.latents.grad * clip_factor + logging.info(f" ✂️ gradient clipping: {grad_norm:.4e} -> {max_grad_norm:.1f} (×{clip_factor:.3f})") + else: + logging.info(f" ✅ gradient not clipped: {grad_norm:.4e} (max={max_grad_norm:.1f})") + + # ==================== Step7: SGO regularization ==================== + def get_schedule_params(t): + """ + Définit alpha_t, sigma_t et leurs dérivées. + Exemple ici pour un Optimal Transport / Rectified Flow (souvent utilisé par DiT). + """ + alpha_t = t + sigma_t = 1.0 - t + dot_alpha_t = 1.0 + dot_sigma_t = -1.0 + return alpha_t, sigma_t, dot_alpha_t, dot_sigma_t + + with torch.no_grad(): + t_min = 0.02 + t_max = 0.98 + t_min_k = t_min + (t_max - t_min) * (step / self.config.num_steps) + t_val = torch.empty(1).uniform_(t_min_k, t_max).item() + t_tensor = torch.tensor([t_val], device="cuda").half() + + alpha_t, sigma_t, dot_alpha_t, dot_sigma_t = get_schedule_params(t_val) + b_t = (dot_alpha_t * sigma_t - dot_sigma_t * alpha_t) / sigma_t + s_t = b_t * (sigma_t**2) / alpha_t + + noise_eps = torch.randn_like(self.latents).half() + xt = alpha_t * self.latents + sigma_t * noise_eps + xt = xt.half() + + cond_for_model = self._get_cond_for_guidance(self.config.guidance_scale > 1.0) + vt = self.flow_model(xt, t_tensor, cond_for_model, guidance=None) + + score_estimate = (vt - (dot_alpha_t / alpha_t) * xt) / s_t + self.latents.grad -= lambda_reg * score_estimate + + # ==================== Step 9: optimizer step ==================== + + # Save the previous latents for diagnostics. + old_latents = self.latents.data.clone() + self.optimizer.step() + + # Diagnose latent changes after the optimizer step. + with torch.no_grad(): + latents_change = torch.norm(self.latents.data - old_latents).item() + latents_norm = torch.norm(old_latents).item() + latents_change_percent = (latents_change / (latents_norm + 1e-10)) * 100 + max_latents_change = torch.abs(self.latents.data - old_latents).max().item() + + logging.info(f" 🔄 Latentschange: L2={latents_change:.4e} ({latents_change_percent:.3f}%), max={max_latents_change:.4e}") + + if latents_change < 1e-6: + logging.warning(f" ⚠️ latents almost did not change!the learning rate may be too small or the gradient may be too weak") + + # Return the scalar loss values. + return (compliance_loss_item, u_mean, shape_loss.item(), total_loss) + + def save_mesh(self, step: int, output_dir: str = "results/hunyuan_meshes", high_quality: bool = False, suffix="step"): + """Save frontlatentsmesh + + Args: + step: front steps + output_dir: outputdirectory + high_quality: YesNouse (Resolution) , Trueuse256resolution + """ + os.makedirs(output_dir, exist_ok=True) + + try: + # finalSave use256resolution, Stepuse128resolution + octree_res = 256 if high_quality else 128 + mesh = self.latents_to_mesh(self.latents, octree_res=octree_res) + if mesh is None: + logging.warning(f" ⚠️ warning: Step {step} - Marching cubesno surface found, skipSave ") + return + + # finalSave filterfloating + if high_quality: + mesh = self._filter_floating_components(mesh) + + mesh_path = os.path.join(output_dir, f"{suffix}_{step:04d}.obj") + mesh.export(mesh_path) + quality_label = "256resolution" if high_quality else "128resolution" + logging.info(f" 💾 Save mesh ({quality_label}): {mesh_path}") + except Exception as e: + logging.warning(f" ⚠️ warning: Step {step} - Save meshfailed: {e}") + + + def _maybe_save_target_z0_mesh(self, target_z0: torch.Tensor, step_id: int, force: bool = False): + """Save a mesh decoded from target_z0 for diagnostics.""" + if (not force) and (step_id % 10 != 0): + return + + with torch.no_grad(): + deviation = torch.norm(target_z0 - self.latents).item() + latents_norm = torch.norm(self.latents).item() + relative_deviation = deviation / (latents_norm + 1e-8) + + if relative_deviation > 0.5: + logging.warning( + f" ⚠️ target_z0 deviation is too large: {relative_deviation:.1%} " + f"(||target_z0 - latents||={deviation:.3e}, ||latents||={latents_norm:.3e})" + ) + logging.warning(f" thismaySave target meshshape is abnormal") + + try: + target_norm = torch.norm(target_z0).item() + target_max = torch.abs(target_z0).max().item() + target_has_nan = torch.isnan(target_z0).any().item() + target_has_inf = torch.isinf(target_z0).any().item() + + # Save only when target_z0 looks numerically healthy. + if (not target_has_nan and not target_has_inf and + target_max < 100.0 and relative_deviation < 1.0): + target_z0_clean = target_z0.detach().clone() + + logging.info(f" 📊 target_z0 statistics:") + logging.info(f" - shape: {target_z0_clean.shape}") + logging.info(f" - range: [{target_z0_clean.min():.3e}, {target_z0_clean.max():.3e}]") + logging.info(f" - mean: {target_z0_clean.mean():.3e}, Std: {target_z0_clean.std():.3e}") + logging.info(f" - deviation from latents: {relative_deviation:.1%}") + + target_mesh = self.latents_to_mesh(target_z0_clean, octree_res=128) + if target_mesh is not None: + target_mesh_dir = os.path.join( + self.config.out_folder if hasattr(self.config, 'out_folder') + else "results/hunyuan_meshes", + "target_z0_meshes" + ) + os.makedirs(target_mesh_dir, exist_ok=True) + target_mesh_path = os.path.join(target_mesh_dir, f"target_z0_step_{step_id:04d}.obj") + target_mesh.export(target_mesh_path) + logging.info(f" 💾 Save target_z0 mesh (||z||={target_norm:.2e}): {target_mesh_path}") + else: + logging.debug(f" skipSave target_z0: marching cubesno surface found") + else: + logging.warning( + f" ⚠️ skipSave target_z0: containsabnormal values " + f"(nan={target_has_nan}, inf={target_has_inf}, max={target_max:.2e})" + ) + except (ValueError, RuntimeError) as e: + error_msg = str(e) + if "Surface level must be within volume data range" in error_msg or "No surface found" in error_msg: + logging.debug(f" skipSave target_z0: SDFvalueoutside the valid range or has no surface") + else: + logging.warning(f" Save target_z0 meshfailed: {type(e).__name__}: {error_msg[:100]}") + except Exception as e: + logging.warning(f" Save target_z0 meshfailed: {type(e).__name__}: {str(e)[:100]}") + + def save_final_target_z0_mesh(self, step_id: int): + """Force-save a target_z0 mesh at the final step.""" + try: + if self.target_z0_ema is not None: + target_z0 = self.target_z0_ema.detach().clone() + else: + target_z0, _ = self._computation_target_z0_current(step_id) + self._maybe_save_target_z0_mesh(target_z0, step_id, force=True) + except Exception as e: + logging.warning(f" ⚠️ failed to save the final target_z0: {type(e).__name__}: {str(e)[:100]}") + + def save_deformed_mesh(self, step: int, displacement: torch.Tensor, output_dir: str = None, suffix="step"): + """Save FEM solvebackdeformed mesh + + Args: + step: front steps + displacement: FEM solve [num_nodes, 3] + output_dir: outputdirectory, useconfig.out_folder/deformed_meshes + """ + if output_dir is None: + if hasattr(self.config, 'out_folder'): + output_dir = os.path.join(self.config.out_folder, "deformed_meshes") + else: + output_dir = "results/deformed_meshes" + + os.makedirs(output_dir, exist_ok=True) + + try: + # originalnodespositionandbackposition + original_nodes = self.nodes.detach().cpu().numpy() # [num_nodes, 3] + displacement_np = displacement.detach().cpu().numpy() # [num_nodes, 3] + deformed_nodes = original_nodes + displacement_np + + # elements + elements_np = self.elements.detach().cpu().numpy() # [num_elements, 8] + + # # Save VTK format (ParaView, contains) + # vtk_path = os.path.join(output_dir, f"deformed_step_{step:04d}.vtk") + # self._save_hex_mesh_vtk(deformed_nodes, elements_np, displacement_np, vtk_path, step) + + # Save OBJ/PLY (usedecodemesh, ) + decoded_mesh = self.latents_to_mesh(self.latents, octree_res=128) + if decoded_mesh is not None: + disp_vertices = self._sample_displacement_to_vertices( + decoded_mesh.vertices, original_nodes, displacement_np + ) + deformed_vertices = decoded_mesh.vertices + disp_vertices + colors = self._make_displacement_colors(disp_vertices) + + deformed_mesh = trimesh.Trimesh( + vertices=deformed_vertices, + faces=decoded_mesh.faces, + process=False, + ) + deformed_mesh.visual.vertex_colors = colors + + obj_path = os.path.join(output_dir, f"deformed_{suffix}_{step:04d}.obj") + # ply_path = os.path.join(output_dir, f"deformed_step_{step:04d}.ply") + deformed_mesh.export(obj_path) + # deformed_mesh.export(ply_path) + else: + # fallback: usemesh + obj_path = os.path.join(output_dir, f"deformed_{suffix}_{step:04d}.obj") + # ply_path = os.path.join(output_dir, f"deformed_step_{step:04d}.ply") + self._save_surface_mesh_obj(deformed_nodes, elements_np, obj_path) + # self._save_surface_mesh_ply(deformed_nodes, elements_np, displacement_np, ply_path) + + # displacement statistics + disp_mean = np.abs(displacement_np).mean() + disp_max = np.abs(displacement_np).max() + logging.info(f" 💾 saved deformed mesh : OBJ={obj_path.split('/')[-1]}") + logging.debug(f" : mean={disp_mean:.4e}, max={disp_max:.4e}") + + except Exception as e: + logging.warning(f" ⚠️ Save deformed meshfailed (Step {step}): {e}") + + def save_final_deformed_mesh(self, step_id: int, suffix="step"): + """force at the final step toSave deformed mesh (re-solveFEM) """ + if not hasattr(self, 'nodes') or not hasattr(self, 'elements'): + logging.warning(" ⚠️ unable to save the finaldeformed mesh: missingnodes/elements") + return + if not hasattr(self, 'forces') or not hasattr(self, 'boundary_mask'): + logging.warning(" ⚠️ unable to save the finaldeformed mesh: missingforces/boundary_mask") + return + + try: + from torchfem.materials import IsotropicElasticity3D + from physiopt.opt.solid_grid import SolidGrid + from physiopt.opt.field import occ_kernel + + with torch.no_grad(): + # update occupancyalignfrontlatents + sdf = self.get_field(self.nodes) + occ = occ_kernel(sdf, self.config.res, self.config.occ_sdf_beta) + self.coarse_occ = occ[self.elements].mean(1) + + if self.config.alpha_min > 0.0: + self.coarse_occ = torch.clamp(self.coarse_occ, self.config.alpha_min) + + vectorized_material = IsotropicElasticity3D( + E=self.config.youngs_modulus, + nu=self.config.poissons_ratio, + rho=self.config.density, + ).vectorize(self.elements.shape[0]) + + vectorized_material.C *= ( + self.coarse_occ[:, None, None] ** self.config.p_exponent + ) + + solid = SolidGrid(self.nodes, self.elements, vectorized_material) + solid.constraints[self.boundary_mask, :] = True + solid.forces = self.forces + + logging.info(" 🧱 final deformed mesh: re-solve the FEM system to save ") + u, _, _, _, _, _ = solid.solve(max_iter=1) + self.save_deformed_mesh(step_id, u, suffix=suffix) + except Exception as e: + logging.warning(f" ⚠️ final deformed meshSave failed: {type(e).__name__}: {str(e)[:100]}") + + def _save_surface_mesh_obj(self, nodes: np.ndarray, elements: np.ndarray, filename: str): + """Extract the surface from a hexahedral mesh and save it as OBJ.""" + # The six faces of a hexahedron. + hex_faces = [ + [0, 1, 2, 3], [4, 5, 6, 7], # Bottom, top. + [0, 1, 5, 4], [2, 3, 7, 6], # Front, back. + [0, 3, 7, 4], [1, 2, 6, 5], # Left, right. + ] + + # Collect faces that appear only once, i.e. surface faces. + face_count = {} + for elem in elements: + for face_indices in hex_faces: + face_nodes = tuple(sorted([elem[i] for i in face_indices])) + if face_nodes in face_count: + face_count[face_nodes] += 1 + else: + face_count[face_nodes] = 1 + + # Keep only surface faces. + surface_faces = [face for face, count in face_count.items() if count == 1] + + # Save OBJ. + with open(filename, 'w') as f: + f.write("# Deformed mesh surface\n") + for node in nodes: + f.write(f"v {node[0]:.6f} {node[1]:.6f} {node[2]:.6f}\n") + for face in surface_faces: + # OBJ indices are 1-based. + f.write(f"f {face[0]+1} {face[1]+1} {face[2]+1} {face[3]+1}\n") + + def _save_force_visualization(self, seat_nodes_mask: torch.Tensor, total_force: np.ndarray): + """Save voxel-level load data for visualization and validation. + + This exports: + 1. NumPy (.npz) with full node/load data + 2. OBJ point clouds for quick inspection + 3. Optional VTK data for ParaView + + Args: + seat_nodes_mask: Mask of seat/contact nodes [num_nodes]. + total_force: Total force vector [3]. + """ + if not hasattr(self.config, 'out_folder'): + logging.warning(" out_folder is not set, skipSave loaded voxel") + return + + # Create the force_visualization subdirectory. + vis_dir = os.path.join(self.config.out_folder, "force_visualization") + os.makedirs(vis_dir, exist_ok=True) + + # ==================== 1. Save NumPy data (most complete format) ==================== + all_nodes_cpu = self.nodes.cpu().numpy() + all_forces_cpu = self.forces.cpu().numpy() + seat_mask_cpu = seat_nodes_mask.cpu().numpy() + + # Extract loaded nodes. + seat_nodes = all_nodes_cpu[seat_mask_cpu] + seat_forces = all_forces_cpu[seat_mask_cpu] + + npz_path = os.path.join(vis_dir, "force_nodes.npz") + np.savez( + npz_path, + # All node data. + all_nodes=all_nodes_cpu, + all_forces=all_forces_cpu, + # Loaded-node data. + seat_nodes=seat_nodes, + seat_forces=seat_forces, + seat_mask=seat_mask_cpu, + # Boundary-node data. + boundary_mask=self.boundary_mask.cpu().numpy() if hasattr(self, 'boundary_mask') else None, + # Metadata. + total_force=total_force, + num_seat_nodes=len(seat_nodes), + num_all_nodes=len(all_nodes_cpu), + ) + logging.info(f" 💾 Save load data (NumPy format) : {npz_path}") + + # ==================== 2. Save OBJ point clouds ==================== + # 2a. Loaded nodes (red point cloud). + seat_obj_path = os.path.join(vis_dir, "seat_nodes.obj") + with open(seat_obj_path, 'w') as f: + f.write("# Seat nodes (loaded area)\n") + f.write(f"# Total: {len(seat_nodes)} nodes\n") + f.write(f"# Force per node: {seat_forces[0] if len(seat_forces) > 0 else [0,0,0]}\n") + for node in seat_nodes: + f.write(f"v {node[0]:.6f} {node[1]:.6f} {node[2]:.6f}\n") + logging.info(f" 💾 Save seat nodes (OBJpoint cloud) : {seat_obj_path}") + + # 2b. Boundary nodes (blue point cloud). + if hasattr(self, 'boundary_mask'): + boundary_nodes = all_nodes_cpu[self.boundary_mask.cpu().numpy()] + boundary_obj_path = os.path.join(vis_dir, "boundary_nodes.obj") + with open(boundary_obj_path, 'w') as f: + f.write("# Boundary nodes (fixed area)\n") + f.write(f"# Total: {len(boundary_nodes)} nodes\n") + for node in boundary_nodes: + f.write(f"v {node[0]:.6f} {node[1]:.6f} {node[2]:.6f}\n") + logging.info(f" 💾 Save boundary nodes (OBJpoint cloud) : {boundary_obj_path}") + + # 2c. All nodes (gray point cloud) for comparison. + all_obj_path = os.path.join(vis_dir, "all_nodes.obj") + with open(all_obj_path, 'w') as f: + f.write("# All nodes\n") + f.write(f"# Total: {len(all_nodes_cpu)} nodes\n") + for node in all_nodes_cpu: + f.write(f"v {node[0]:.6f} {node[1]:.6f} {node[2]:.6f}\n") + logging.info(f" 💾 Save all nodes (OBJpoint cloud) : {all_obj_path}") + + # ==================== 3. Save VTK data for ParaView ==================== + try: + vtk_path = os.path.join(vis_dir, "force_field.vtk") + with open(vtk_path, 'w') as f: + # VTK Header + f.write("# vtk DataFile Version 3.0\n") + f.write("Force field visualization\n") + f.write("ASCII\n") + f.write("DATASET UNSTRUCTURED_GRID\n") + + # Points + f.write(f"POINTS {len(all_nodes_cpu)} float\n") + for node in all_nodes_cpu: + f.write(f"{node[0]:.6f} {node[1]:.6f} {node[2]:.6f}\n") + + # Cells (vertices) + f.write(f"\nCELLS {len(all_nodes_cpu)} {len(all_nodes_cpu)*2}\n") + for i in range(len(all_nodes_cpu)): + f.write(f"1 {i}\n") + + # Cell types (1 = vertex) + f.write(f"\nCELL_TYPES {len(all_nodes_cpu)}\n") + for _ in range(len(all_nodes_cpu)): + f.write("1\n") + + # Point data (force vectors) + f.write(f"\nPOINT_DATA {len(all_nodes_cpu)}\n") + f.write("VECTORS force float\n") + for force in all_forces_cpu: + f.write(f"{force[0]:.6e} {force[1]:.6e} {force[2]:.6e}\n") + + # Scalar field: force magnitude + f.write("\nSCALARS force_magnitude float 1\n") + f.write("LOOKUP_TABLE default\n") + for force in all_forces_cpu: + mag = np.linalg.norm(force) + f.write(f"{mag:.6e}\n") + + # Scalar field: is_seat (0 or 1) + f.write("\nSCALARS is_seat int 1\n") + f.write("LOOKUP_TABLE default\n") + for is_seat in seat_mask_cpu: + f.write(f"{int(is_seat)}\n") + + logging.info(f" 💾 Save force field (VTK format, ParaView) : {vtk_path}") + except Exception as e: + logging.warning(f" ⚠️ Save VTK formatfailed: {e}") + + # ==================== 4. Generate a Python visualization script ==================== + vis_script_path = os.path.join(vis_dir, "visualize_forces.py") + with open(vis_script_path, 'w') as f: + f.write("""#!/usr/bin/env python3 +\"""Visualize voxel load data + +Usage: + python visualize_forces.py + +Requirements: + pip install numpy matplotlib + +\""" +import numpy as np +import matplotlib.pyplot as plt +from mpl_toolkits.mplot3d import Axes3D + +# Load data. +data = np.load('force_nodes.npz') +all_nodes = data['all_nodes'] +seat_nodes = data['seat_nodes'] +seat_forces = data['seat_forces'] +total_force = data['total_force'] + +# Create the 3D figure. +fig = plt.figure(figsize=(15, 5)) + +# Subplot 1: all nodes (gray) + loaded nodes (red). +ax1 = fig.add_subplot(131, projection='3d') +ax1.scatter(all_nodes[:, 0], all_nodes[:, 1], all_nodes[:, 2], + c='lightgray', s=0.5, alpha=0.3, label='All nodes') +ax1.scatter(seat_nodes[:, 0], seat_nodes[:, 1], seat_nodes[:, 2], + c='red', s=5, alpha=1.0, label='Seat nodes (loaded)') +ax1.set_xlabel('X') +ax1.set_ylabel('Y (up)') +ax1.set_zlabel('Z') +ax1.set_title(f'Loaded Nodes\\n({len(seat_nodes)}/{len(all_nodes)} nodes)') +ax1.legend() + +# Subplot 2: Y distribution of loaded nodes. +ax2 = fig.add_subplot(132) +y_coords = seat_nodes[:, 1] +ax2.hist(y_coords, bins=30, color='red', alpha=0.7, edgecolor='black') +ax2.axvline(y_coords.min(), color='blue', linestyle='--', label=f'Y_min={y_coords.min():.3f}') +ax2.axvline(y_coords.max(), color='green', linestyle='--', label=f'Y_max={y_coords.max():.3f}') +ax2.set_xlabel('Y coordinate (height)') +ax2.set_ylabel('Number of nodes') +ax2.set_title('Seat Node Y Distribution') +ax2.legend() +ax2.grid(True, alpha=0.3) + +# Subplot 3: XZ force-vector layout in top view. +ax3 = fig.add_subplot(133) +ax3.scatter(seat_nodes[:, 0], seat_nodes[:, 2], c='red', s=10, alpha=0.5) +# Draw a sparse subset of force vectors to avoid clutter. +step = max(1, len(seat_nodes) // 50) +for i in range(0, len(seat_nodes), step): + node = seat_nodes[i] + force = seat_forces[i] + # Scale force vectors for visualization. + scale = 0.01 + ax3.arrow(node[0], node[2], force[0]*scale, force[2]*scale, + head_width=0.02, head_length=0.01, fc='blue', ec='blue', alpha=0.7) +ax3.set_xlabel('X') +ax3.set_ylabel('Z') +ax3.set_title(f'Top View (XZ plane)\\nForce: {total_force}') +ax3.axis('equal') +ax3.grid(True, alpha=0.3) + +plt.tight_layout() +plt.savefig('force_visualization.png', dpi=150, bbox_inches='tight') +logging.info("✅ image saved : force_visualization.png") +plt.show() + +# Print summary statistics. +logging.info("\\n" + "="*60) +logging.info("force voxel statistics") +logging.info("="*60) +logging.info(f"total node count: {len(all_nodes)}") +logging.info(f"loaded node count: {len(seat_nodes)} ({len(seat_nodes)/len(all_nodes)*100:.1f}%)") +logging.info(f"total: {total_force}") +logging.info(f"per nodeaverage force per node: {seat_forces.mean(axis=0)}") +logging.info(f"\\nY-coordinate range:") +logging.info(f" - min: {y_coords.min():.3f}") +logging.info(f" - max: {y_coords.max():.3f}") +logging.info(f" - mean: {y_coords.mean():.3f}") +logging.info(f" - height span: {y_coords.max() - y_coords.min():.3f}") +logging.info("="*60) +""") + os.chmod(vis_script_path, 0o755) # Add execute permission. + logging.info(f" 💾 Save visualization script: {vis_script_path}") + + # ==================== 5. Generate a README document ==================== + readme_path = os.path.join(vis_dir, "README.md") + with open(readme_path, 'w') as f: + f.write(f"""# Load Voxel Visualization Data + +Generated at: {np.datetime64('now')} + +## Statistics + +- **Total nodes**: {len(all_nodes_cpu)} +- **Loaded nodes**: {len(seat_nodes)} ({len(seat_nodes)/len(all_nodes_cpu)*100:.1f}%) +- **Total force**: {total_force} +- **Force per node**: {seat_forces[0] if len(seat_forces) > 0 else [0,0,0]} + +## Files + +### 1. NumPy format (recommended for analysis) + +- `force_nodes.npz`: contains the full dataset + - `all_nodes`: coordinates of all nodes [{len(all_nodes_cpu)}, 3] + - `all_forces`: force vectors on all nodes [{len(all_nodes_cpu)}, 3] + - `seat_nodes`: coordinates of loaded nodes [{len(seat_nodes)}, 3] + - `seat_forces`: force vectors on loaded nodes [{len(seat_nodes)}, 3] + - `seat_mask`: mask of loaded nodes [{len(all_nodes_cpu)}] + - `boundary_mask`: mask of boundary nodes [{len(all_nodes_cpu)}] + +**Example**: +```python +import numpy as np +data = np.load('force_nodes.npz') +seat_nodes = data['seat_nodes'] +print(f"Loaded nodes: {{len(seat_nodes)}}") +``` + +### 2. OBJ format (recommended for quick inspection) + +- `seat_nodes.obj`: loaded nodes (red point cloud) +- `boundary_nodes.obj`: boundary nodes (blue point cloud) +- `all_nodes.obj`: all nodes (gray point cloud) + +**Usage**: +1. Open in Meshlab: `meshlab seat_nodes.obj` +2. Or import the OBJ files into Blender +3. You can load multiple OBJ files together for comparison + +### 3. VTK format (recommended for professional visualization) + +- `force_field.vtk`: force-field data with vector information + +**Usage**: +1. Open in ParaView: `paraview force_field.vtk` +2. In ParaView: + - Use `Glyph` to visualize force vectors + - Color by `force_magnitude` to inspect strength + - Filter by `is_seat` to isolate the loaded region + +### 4. Visualization script + +- `visualize_forces.py`: Python visualization script + +**Usage**: +```bash +python visualize_forces.py +``` +""") + logging.info(f" 💾 Save README document: {readme_path}") + + # Print a short summary. + logging.info(f" ✅ force voxel data saved successfully!") + logging.info(f" - view directory: {vis_dir}") + logging.info(f" - quick visualization: cd {vis_dir} && python visualize_forces.py") + logging.info(f" - view in Meshlab: meshlab {os.path.join(vis_dir, 'seat_nodes.obj')}") + + +def load_hunyuan_models(model_path: str = "tencent/Hunyuan3D-2.1", + subfolder: str = "hunyuan3d-shapegen", + use_safetensors: bool = True): + """Load the Hunyuan3D models (VAE, Flow Model, and Scheduler). + + Args: + model_path: Model path, either a Hugging Face ID or a local directory. + subfolder: Model subfolder name. + use_safetensors: Whether to load safetensors checkpoints. + + Returns: + (vae, flow_model, scheduler): the VAE, Flow Matching model, and scheduler. + """ + logging.info(f"🔧 loading Hunyuan3D-2.1model...") + logging.info(f" modelpath: {model_path}") + logging.info(f" subfolder: {subfolder}") + logging.info(f" modelformat: {'safetensors' if use_safetensors else 'checkpoint'}") + + try: + pipeline = Hunyuan3DDiTFlowMatchingPipeline.from_pretrained( + model_path, + subfolder=subfolder, + torch_dtype=torch.float16, + use_safetensors=use_safetensors + ) + + if pipeline is None: + raise ValueError("pipeline loading failed and returned None") + + logging.info(" ✅ pipeline loaded successfully") + + pipeline.to('cuda') + logging.info(" ✅ modelmoved to CUDA (dtype: fp16)") + + vae = pipeline.vae + flow_model = pipeline.model + scheduler = pipeline.scheduler + + return vae, flow_model, scheduler + + except Exception as e: + logging.error(f"\n❌ modelloadfailed: {e}") + logging.error(f"\nPossible fixes:") + logging.error(f"1. make sure Hunyuan3D is installed-2.1: cd Hunyuan3D-2.1 && pip install -e .") + logging.error(f"2. check network connectivity to huggingface.co") + logging.error(f"3. or download manually: git clone https://huggingface.co/tencent/Hunyuan3D-2") + import traceback + traceback.print_exc() + sys.exit(1) + + + +def plot_history(history: dict, save_dir: str, filename: str = "optimization_metrics.png"): + + epochs = list(range(1, len(history["compliance"]) + 1)) + + # 2. Create the figure with a 2x2 grid + fig, axs = plt.subplots(2, 2, figsize=(14, 10)) + fig.suptitle("Optimization Metrics Evolution", fontsize=16, fontweight='bold') + + # --- Plot 1: Compliance --- + axs[0, 0].plot(epochs, history["compliance"], marker='o', color='#1f77b4', linewidth=2) + axs[0, 0].set_title("Compliance (Strain Energy)") + axs[0, 0].set_xlabel("Epoch") + axs[0, 0].grid(True, linestyle='--', alpha=0.7) + + # --- Plot 2: u_mean --- + axs[0, 1].plot(epochs, history["u_mean"], marker='s', color='#2ca02c', linewidth=2) + axs[0, 1].set_title("Mean Displacement (|u|_mean)") + axs[0, 1].set_xlabel("Epoch") + axs[0, 1].grid(True, linestyle='--', alpha=0.7) + + # --- Plot 3: c_relative_decrease --- + axs[1, 0].plot(epochs, history["c_relative_decrease"], marker='^', color='#d62728', linewidth=2) + axs[1, 0].set_title("Relative Compliance Decrease") + axs[1, 0].set_xlabel("Epoch") + axs[1, 0].grid(True, linestyle='--', alpha=0.7) + + # --- Plot 4: u_relative_decrease --- + axs[1, 1].plot(epochs, history["u_relative_decrease"], marker='v', color='#9467bd', linewidth=2) + axs[1, 1].set_title("Relative Displacement Decrease") + axs[1, 1].set_xlabel("Epoch") + axs[1, 1].grid(True, linestyle='--', alpha=0.7) + + # 3. Adjust layout to prevent text from overlapping + plt.tight_layout() + fig.subplots_adjust(top=0.92) # Leave space for the main super-title + + # 4. Save the figure + os.makedirs(save_dir, exist_ok=True) + full_path = os.path.join(save_dir, filename) + + plt.savefig(full_path, dpi=300, bbox_inches='tight') + plt.close(fig) + + logging.info(f" 📊 Plot successfully saved to: {full_path}") + + +def main(): + """Parse CLI arguments and run the optimization.""" + import argparse + + parser = argparse.ArgumentParser(description="Hunyuan3D physics optimization + shape-prior optimization") + + # Required arguments. + parser.add_argument("--latents", type=str, required=True, + help="Input latents file path (.pt)") + parser.add_argument("--out_folder", type=str, default="../out/hunyuan_opt", + help="Output folder path") + parser.add_argument("--not_use_threshold", action="store_true") + + # Model arguments. + parser.add_argument("--model_path", type=str, default="tencent/Hunyuan3D-2.1", + help="Model path (using v2.1)") + parser.add_argument("--subfolder", type=str, default="hunyuan3d-dit-v2-1", + help="Model subfolder") + parser.add_argument("--use_safetensors", action="store_true", + help="Use safetensors format (default: ckpt)") + + # Physical-simulation arguments. + parser.add_argument("--use_physics", action="store_true", + help="Enable physics-constrained optimization") + parser.add_argument("--res", type=int, default=16, + help="Voxel resolution (16/32/64)") + parser.add_argument("--youngs_modulus_scale", type=float, default=2.0, + help="Final Young's modulus multiplier (default 2x after the last projection)") + parser.add_argument("--compliance_threshold", type=float, default=None, + help="Target compliance threshold (None = automatic)") + parser.add_argument("--compliance_threshold_ratio", type=float, default=0.3, + help="Automatic threshold ratio (threshold = initial value × ratio)") + + # Optimization arguments. + parser.add_argument("--lambda_reg", type=float, default=1e3, + help="Number of optimization steps (pure SDS only; in physics mode it becomes outer_cycles * phys_steps_per_cycle automatically)") + parser.add_argument("--num_steps", type=int, default=300, + help="Number of optimization steps (pure SDS only; in physics mode it becomes outer_cycles * phys_steps_per_cycle automatically)") + parser.add_argument("--outer_cycles", type=int, default=100, + help="Number of outer cycles (each cycle = physics optimization + projection)") + parser.add_argument("--phys_steps_per_cycle", type=int, default=5, + help="Number of physics-optimization steps per outer cycle") + parser.add_argument("--lr", type=float, default=5e-3, + help="Learning rate (increase to 0.005 to help the mesh thicken faster) ") + parser.add_argument("--lagrange_max", type=float, default=10.0, + help="Maximum Lagrange multiplier (recommended: 5-20)") + parser.add_argument("--alm_rho_init", type=float, default=1.0, + help="ALM rhoinitial value") + parser.add_argument("--alm_rho_max", type=float, default=1000.0, + help="ALM rhoMax") + parser.add_argument("--alm_rho_increase_factor", type=float, default=2.0, + help="ALM rhogrowth factor") + parser.add_argument("--alm_rho_increase_patience", type=int, default=5, + help="ALM rhonumber of consecutive violation steps required before increasing") + parser.add_argument("--alm_scale_guard_ratio", type=float, default=0.95, + help="ALMscaling guard ratio(<=1), control the upper bound of the physics-gradient target=this ratio x clipping-threshold value") + parser.add_argument("--grad_clip_enabled", action="store_true", + help="Enable gradient clipping (disabled by default; otherwise only NaN/Inf checks are kept)") + parser.add_argument("--use_sgd", action="store_true", + help="Use SGD instead of Adam") + parser.add_argument("--force_config", type=str, default=None, + help="Path to the external-force JSON config (generated by the web UI)") + parser.add_argument("--force", type=float, nargs=3, action="append", default=None, + help="External force vector [fx fy fz] (N, Y-up coordinates; can be specified multiple times)") + parser.add_argument("--global_loading", action="store_true", + help="Use global uniform loading (disable local loading)") + parser.add_argument("--force_region_mode", type=str, default="top_percent", + choices=["top_percent", "height_ratio", "bbox"], + help="How to choose the local loading region") + parser.add_argument("--force_top_percent", type=float, default=0.05, + help="top_percent mode: select the highest-Y fraction") + parser.add_argument("--force_bbox", type=float, nargs=6, default=None, + help="bbox mode: x_min x_max y_min y_max z_min z_max (absolute coordinates)") + parser.add_argument("--force_bbox_ratio", type=float, nargs=6, default=None, + help="bbox mode (0-1): bbox relative to the node bounds") + parser.add_argument("--seat_height_min_ratio", type=float, default=0.3, + help="height_ratio mode: lower seat boundary (0-1)") + parser.add_argument("--seat_height_max_ratio", type=float, default=0.5, + help="height_ratio mode: upper seat boundary (0-1)") + + # SDS arguments. + parser.add_argument("--sds_weight", type=float, default=1.0, + help="SDS gradient weight (deprecated; use sds_weight_start and sds_weight_end instead)") + parser.add_argument("--sds_weight_start", type=float, default=10.0, + help="Initial SDS weight (linearly increased; 0.0001 is recommended to avoid disturbing physics optimization)") + parser.add_argument("--sds_weight_end", type=float, default=10.0, + help="Final SDS weight (linearly increased; 0.001 is recommended, about 1/10 of the physics gradient)") + parser.add_argument("--sds_timestep", type=float, default=0.1, + help="SDS timestep (recommended: 0.05-0.2)") + parser.add_argument("--sds_target_z0_ema_beta", type=float, default=0.9, + help="target_z0 EMA smoothing factor (larger means smoother)") + parser.add_argument("--deformed_mesh_interval", type=int, default=10, + help="Interval for saving deformed meshes (steps)") + parser.add_argument("--deformed_mesh_disp_min", type=float, default=0.0, + help="Minimum displacement for deformed-mesh color mapping (default 0.0)") + parser.add_argument("--deformed_mesh_disp_max", type=float, default=0.2, + help="Maximum displacement for deformed-mesh color mapping (<=0 enables per-step auto scaling)") + parser.add_argument("--guidance_scale", type=float, default=7.5, + help="CFG guidance scale (standard value: 7.5; larger means stronger image conditioning)") + parser.add_argument("--sds_projection_max_rel", type=float, default=0.0, + help="Maximum relative target_z0 projection deviation (0 = unlimited)") + parser.add_argument("--sds_use_uncond", action="store_true", + help="Use the unconditional branch (only takes effect when guidance_scale <= 1)") + + # Topology control. + parser.add_argument("--keep_all_components", action="store_true", + help="Keep all connected components (to avoid disappearing chair legs)") + parser.add_argument("--re_extract_interval", type=int, default=1, + help="Solid re-extraction interval (0 = disabled)") + + args = parser.parse_args() + + def _normalize_force_vectors(value): + if value is None: + return None + if isinstance(value, (list, tuple)) and len(value) > 0: + if isinstance(value[0], (list, tuple)): + candidates = value + else: + candidates = [value] + else: + return None + normalized = [] + for vec in candidates: + if not isinstance(vec, (list, tuple)) or len(vec) != 3: + continue + try: + normalized.append([float(v) for v in vec]) + except Exception: + continue + return normalized if normalized else None + + def _normalize_force_entry(entry): + if not isinstance(entry, dict): + return None + forces = _normalize_force_vectors(entry.get("forces")) + if forces is None: + forces = _normalize_force_vectors(entry.get("force")) + if forces is None: + return None + out = dict(entry) + if len(forces) > 1: + out["forces"] = forces + out["force"] = [float(sum(v[i] for v in forces)) for i in range(3)] + else: + out["force"] = forces[0] + out.pop("forces", None) + if "force_region_mode" in out: + out["force_region_mode"] = str(out["force_region_mode"]) + if "global_loading" in out: + out["global_loading"] = bool(out["global_loading"]) + if "force_top_percent" in out: + out["force_top_percent"] = float(out["force_top_percent"]) + if "seat_height_min_ratio" in out: + out["seat_height_min_ratio"] = float(out["seat_height_min_ratio"]) + if "seat_height_max_ratio" in out: + out["seat_height_max_ratio"] = float(out["seat_height_max_ratio"]) + if "force_bbox" in out and isinstance(out["force_bbox"], (list, tuple)) and len(out["force_bbox"]) == 6: + out["force_bbox"] = [float(v) for v in out["force_bbox"]] + elif "force_bbox" in out: + out.pop("force_bbox", None) + if "force_bbox_ratio" in out and isinstance(out["force_bbox_ratio"], (list, tuple)) and len(out["force_bbox_ratio"]) == 6: + out["force_bbox_ratio"] = [float(v) for v in out["force_bbox_ratio"]] + elif "force_bbox_ratio" in out: + out.pop("force_bbox_ratio", None) + return out + + # Load force configuration from JSON, typically exported from the web UI. + force_config_loaded = False + force_config_error = None + force_entries = None + if args.force_config: + raw_force_config = args.force_config + candidates = [] + if os.path.isabs(raw_force_config): + candidates.append(raw_force_config) + else: + candidates.append(raw_force_config) + script_dir = os.path.dirname(os.path.abspath(__file__)) + candidates.append(os.path.join(script_dir, raw_force_config)) + candidates.append(os.path.join(os.path.dirname(script_dir), raw_force_config)) + force_config_path = next((p for p in candidates if os.path.exists(p)), None) + if force_config_path is None: + force_config_error = f"Path does not exist; tried: {candidates}" + else: + args.force_config = force_config_path + try: + with open(force_config_path, "r") as f: + force_cfg = json.load(f) + if isinstance(force_cfg, dict): + cfg_forces = _normalize_force_vectors(force_cfg.get("forces")) + if cfg_forces is not None: + args.force = cfg_forces + else: + cfg_force = _normalize_force_vectors(force_cfg.get("force")) + if cfg_force is not None: + args.force = cfg_force + elif "force" in force_cfg or "forces" in force_cfg: + force_config_error = "force/forcesinvalid format" + if "global_loading" in force_cfg: + args.global_loading = bool(force_cfg["global_loading"]) + if "force_region_mode" in force_cfg: + args.force_region_mode = str(force_cfg["force_region_mode"]) + if "force_top_percent" in force_cfg: + args.force_top_percent = float(force_cfg["force_top_percent"]) + if "seat_height_min_ratio" in force_cfg: + args.seat_height_min_ratio = float(force_cfg["seat_height_min_ratio"]) + if "seat_height_max_ratio" in force_cfg: + args.seat_height_max_ratio = float(force_cfg["seat_height_max_ratio"]) + if "force_bbox" in force_cfg: + args.force_bbox = force_cfg["force_bbox"] + if "force_bbox_ratio" in force_cfg: + args.force_bbox_ratio = force_cfg["force_bbox_ratio"] + if "force_entries" in force_cfg: + raw_entries = force_cfg["force_entries"] + if isinstance(raw_entries, list): + normalized_entries = [] + for entry in raw_entries: + norm_entry = _normalize_force_entry(entry) + if norm_entry is not None: + normalized_entries.append(norm_entry) + if normalized_entries: + force_entries = normalized_entries + else: + force_config_error = "force_entries has no valid entries" + else: + force_config_error = "force_entriesinvalid format" + force_config_loaded = True + else: + force_config_error = f"force_configis not a dict: {type(force_cfg)}" + except Exception as e: + force_config_error = f"read failed: {e}" + + # Configure logging. force=True ensures this replaces any prior setup. + os.makedirs(args.out_folder, exist_ok=True) + log_file = os.path.join(args.out_folder, "optimization.log") + + # Remove any existing handlers. + for handler in logging.root.handlers[:]: + logging.root.removeHandler(handler) + + # Reconfigure logging. + logging.basicConfig( + level=logging.INFO, + format='%(asctime)s - %(levelname)s - %(message)s', + handlers=[ + logging.FileHandler(log_file, mode='w'), # Rewrite the log on each run. + logging.StreamHandler() + ], + force=True # Python 3.8+: force a full reconfiguration. + ) + + logging.info(f"🔧 logging configuration completed") + logging.info(f" - log file: {log_file}") + logging.info(f" - output mode: file + console") + if args.force_config: + if force_config_loaded: + logging.info(" ✅ force_configloaded") + logging.info(f" - path: {args.force_config}") + logging.info(f" - forces: {args.force}") + if force_entries: + logging.info(f" - force_entries: {len(force_entries)}") + logging.info(f" - global_loading: {args.global_loading}") + logging.info(f" - force_region_mode: {args.force_region_mode}") + logging.info(f" - force_top_percent: {args.force_top_percent}") + logging.info(f" - seat_height_min_ratio: {args.seat_height_min_ratio}") + logging.info(f" - seat_height_max_ratio: {args.seat_height_max_ratio}") + logging.info(f" - force_bbox: {args.force_bbox}") + logging.info(f" - force_bbox_ratio: {args.force_bbox_ratio}") + if force_config_error: + logging.warning(f" ⚠️ force_configsome fields are invalid: {force_config_error}") + else: + logging.warning(f" ⚠️ force_configloadfailed: {force_config_error}") + + # In physics mode, derive num_steps from outer_cycles and phys_steps_per_cycle. + if args.use_physics: + outer_cycles = max(1, int(args.outer_cycles)) + phys_steps_per_cycle = max(1, int(args.phys_steps_per_cycle)) + derived_num_steps = outer_cycles * phys_steps_per_cycle + if args.num_steps != derived_num_steps: + logging.info( + f" - num_stepsautomatically set: {args.num_steps} → {derived_num_steps} " + f"(outer_cycles={outer_cycles}, phys_steps_per_cycle={phys_steps_per_cycle})" + ) + args.num_steps = derived_num_steps + + # ==================== Save run metadata ==================== + # 1. Save the command line. + command_file = os.path.join(args.out_folder, "run_command.txt") + try: + with open(command_file, 'w') as f: + f.write("=" * 80 + "\n") + f.write("Command used (Command Used)\n") + f.write("=" * 80 + "\n\n") + f.write("Full command:\n") + f.write("python " + " ".join(sys.argv) + "\n\n") + + f.write("=" * 80 + "\n") + f.write("Arguments (Arguments)\n") + f.write("=" * 80 + "\n\n") + for arg, value in vars(args).items(): + f.write(f"{arg}: {value}\n") + + f.write("\n" + "=" * 80 + "\n") + f.write("Environment (Environment)\n") + f.write("=" * 80 + "\n\n") + f.write(f"Python: {sys.version}\n") + f.write(f"PyTorch: {torch.__version__}\n") + f.write(f"CUDA Available: {torch.cuda.is_available()}\n") + if torch.cuda.is_available(): + f.write(f"CUDA Version: {torch.version.cuda}\n") + f.write(f"GPU Count: {torch.cuda.device_count()}\n") + + logging.info(f" - saved command used : {command_file}") + except Exception as e: + logging.warning(f" ⚠️ Save Command usedfailed: {e}") + + # 2. Save a copy of the current script. + script_backup = os.path.join(args.out_folder, "viewer_hunyuan_web_alternate.py") + try: + current_script = os.path.abspath(__file__) + shutil.copy2(current_script, script_backup) + logging.info(f" - saved script copy : {script_backup}") + except Exception as e: + logging.warning(f" ⚠️ Save failed to save script copy: {e}") + + # Load latents and conditioning data. + logging.info(f"\n📂 loading input data...") + logging.info(f" - Latents: {args.latents}") + + data = torch.load(args.latents, map_location='cpu') + + # Extract latents. + if isinstance(data, dict) and 'latents' in data: + latents = data['latents'] + else: + latents = data + + logging.info(f" ✅ Latents shape: {latents.shape}") + + # Check conditioning data (image_embeds or image). + need_encode_cond = False + image_embeds = None + image = None + + if isinstance(data, dict): + if 'image' in data: + # New format: only the image was saved, so we need to re-encode it. + logging.info(f" - detected image data; re-encoding as conditional embeds") + image_array = data['image'] + image = Image.fromarray(image_array) + need_encode_cond = True + elif 'image_embeds' in data: + # Legacy format: embeddings are already saved. + logging.info(f" - using the saved conditional embeds") + image_embeds = data['image_embeds'] + need_encode_cond = False + elif 'cond' in data: + # Alternate format using a saved cond dict. + logging.info(f" - using the saved cond") + image_embeds = data['cond'] + need_encode_cond = False + else: + raise ValueError("latents.ptis missingimage, image_embedsor cond data") + else: + raise ValueError("latentsmust be a dictionary containing'latents'andconditioninformation dict") + + if image_embeds is not None: + if isinstance(image_embeds, dict): + logging.info(f" ✅ Cond keys: {list(image_embeds.keys())}") + else: + logging.info(f" ✅ Image embeds shape: {image_embeds.shape}") + + # Load models. + logging.info(f"\n🔧 loading Hunyuan3Dmodel...") + vae, flow_model, scheduler = load_hunyuan_models( + model_path=args.model_path, + subfolder=args.subfolder, + use_safetensors=args.use_safetensors + ) + + # ==================== Encode conditioning data if needed ==================== + if need_encode_cond: + logging.info("🎨 encoding conditional embeds from the image...") + + # Reload the full pipeline for condition encoding. + from hy3dgen.shapegen import Hunyuan3DDiTFlowMatchingPipeline + + pipeline = Hunyuan3DDiTFlowMatchingPipeline.from_pretrained( + args.model_path, + subfolder=args.subfolder, + torch_dtype=torch.float16, + use_safetensors=args.use_safetensors + ) + pipeline.to('cuda') + + with torch.no_grad(): + # Prepare the image. + cond_inputs = pipeline.prepare_image(image) + image_tensor = cond_inputs.pop('image') + + # Enable CFG so the encoded condition contains both branches. + cond_dict = pipeline.encode_cond( + image=image_tensor, + additional_cond_inputs=cond_inputs, + do_classifier_free_guidance=True, # Enable CFG. + dual_guidance=False, + ) + + # Save the condition dict. + image_embeds = cond_dict + + logging.info(f" ✅ condition encoding completed (CFG mode) ") + logging.info(f" - Cond keys: {list(cond_dict.keys()) if isinstance(cond_dict, dict) else 'tensor'}") + + # Resolve the compliance threshold. + if args.compliance_threshold is None: + compliance_threshold = 200.0 + logging.info(f" using the default compliance threshold: {compliance_threshold}") + else: + compliance_threshold = args.compliance_threshold + logging.info(f" using the custom compliance threshold: {compliance_threshold}") + + target_z0_update_interval = max(1, int(args.phys_steps_per_cycle)) + forces = None + normalized_forces = _normalize_force_vectors(args.force) + if normalized_forces: + forces = [{'external_force': vec} for vec in normalized_forces] + elif args.force is not None: + logging.warning(f" ⚠️ invalid external force vector; ignoring: {args.force}") + # Build the optimization config. + config = OptimizationConfig( + num_steps=args.num_steps, + lr=args.lr, + sds_timestep=args.sds_timestep, + sds_weight=args.sds_weight if args.use_physics else 1.0, # Keep backward compatibility. + sds_weight_start=args.sds_weight_start, # Dynamic weight schedule start. + sds_weight_end=args.sds_weight_end, # Dynamic weight schedule end. + guidance_scale=args.guidance_scale, # CFG guidance scale. + sds_projection_max_rel=args.sds_projection_max_rel, + sds_use_uncond=args.sds_use_uncond, + sds_target_z0_update_interval=target_z0_update_interval, + sds_target_z0_ema_beta=args.sds_target_z0_ema_beta, + deformed_mesh_interval=args.deformed_mesh_interval, + deformed_mesh_disp_min=args.deformed_mesh_disp_min, + deformed_mesh_disp_max=args.deformed_mesh_disp_max, + use_sgd=args.use_sgd, + grad_clip_enabled=args.grad_clip_enabled, + # Physical parameters. + res=args.res, + lagrange_max=args.lagrange_max, + compliance_threshold=compliance_threshold, + alm_rho_init=args.alm_rho_init, + alm_rho_max=args.alm_rho_max, + alm_rho_increase_factor=args.alm_rho_increase_factor, + alm_rho_increase_patience=args.alm_rho_increase_patience, + alm_scale_guard_ratio=args.alm_scale_guard_ratio, + youngs_modulus_scale=args.youngs_modulus_scale, + # Topology control. + one_cc_only=not args.keep_all_components, + re_extract_interval=args.re_extract_interval, + # Loads and load-region settings. + forces=forces, + force_entries=force_entries, + use_local_loading=not args.global_loading, + seat_height_min_ratio=args.seat_height_min_ratio, + seat_height_max_ratio=args.seat_height_max_ratio, + force_region_mode=args.force_region_mode, + force_top_percent=args.force_top_percent, + force_bbox=args.force_bbox, + force_bbox_ratio=args.force_bbox_ratio, + # Output path. + out_folder=args.out_folder, + ) + + # Create the optimizer. + optimizer = HunyuanSDSOptimizer( + latents=latents, + cond=image_embeds, + vae=vae, + flow_model=flow_model, + scheduler=scheduler, + config=config, + device='cuda' + ) + + # Prepare physics if requested. + final_step = args.num_steps + if args.use_physics: + logging.info(f"\n🔬 enable physics optimization mode") + logging.info(f" - Voxel resolution: {args.res}") + logging.info(f" - physics steps/cycle: {args.phys_steps_per_cycle}, outer cycles: {args.outer_cycles}") + logging.info(f" - projection noise: sds_timestep={args.sds_timestep}") + logging.info(f" - target_z0update interval: {target_z0_update_interval} (consistent with phys_steps_per_cycle)") + logging.info(f" - LagrangeMax: {args.lagrange_max}") + + try: + optimizer.extract_solid(step=-1) # Initial extraction. + optimizer.prepare_physical_simulation() + logging.info(f" ✅ physics simulationInitializationsucceeded") + except Exception as e: + logging.warning(f" ⚠️ warning: initial mesh extraction failed (this is normal, optimizationbe repaired during the optimization process) ") + logging.warning(f" error information: {str(e)[:100]}") + # Continue anyway: the key physical state is the occupancy field, not the mesh. + else: + logging.info(f"\n🎨 using pure SDS optimization mode") + + # Optimization loop. + optimization_mode = "Alternating Phys/Projection" if args.use_physics else "Pure SDS" + total_steps_hint = ( + int(args.outer_cycles) * (int(args.phys_steps_per_cycle) + 1) + if args.use_physics + else args.num_steps + ) + logging.info(f"\n🚀 start{optimization_mode}optimization ({total_steps_hint} steps)...") + + if args.use_physics: + lagrange_multiplier = 0.0 + rho = config.alm_rho_init + violation_count = 0 + + # Automatically set the compliance threshold when needed. + if config.compliance_threshold is None or config.compliance_threshold == 200.0: + logging.info(f" 📊 computationinitialcompliancethreshold value...") + try: + initial_compliance, _, _, _ = optimizer.training_step( + 0, 0.0, 0.0, lambda_reg=0, use_sds=False + ) + # Auto threshold: initial compliance times the requested ratio. + auto_threshold = initial_compliance * args.compliance_threshold_ratio + auto_threshold = min(auto_threshold, 100000.0) # Upper bound only. + compliance_threshold = auto_threshold + config.compliance_threshold = auto_threshold + logging.info( + f" ✅ Automatically set the threshold: {initial_compliance:.2e} × {args.compliance_threshold_ratio:.2f} " + f"= {compliance_threshold:.2e}" + ) + + # Warn when the structure already looks extremely stiff or too soft. + if initial_compliance < 0.01: # Already very stiff. + logging.warning(f" ⚠️ initial compliance is very small ({initial_compliance:.2e}), the structure may already be stiff enough!") + logging.warning(f" consider increasing the external force or using a softer material to create visible deformation") + logging.warning(f" current material: E={config.youngs_modulus:.2e} Pa, ν={config.poissons_ratio}") + elif initial_compliance > 1000.0: # Likely too soft. + logging.warning(f" ⚠️ initial compliance is very large ({initial_compliance:.2e}), the structure may be too soft!") + logging.warning(f" consider using a stiffer material or reducing the external force") + except Exception as e: + logging.warning(f" ⚠️ automatic computation failed, usethreshold value200: {e}") + compliance_threshold = 200.0 + else: + compliance_threshold = config.compliance_threshold + + logging.info(f"🎯 parameters:") + logging.info(f" - initial lambda: {lagrange_multiplier}") + logging.info(f" - initial rho: {rho}") + logging.info(f" - Compliancethreshold value: {compliance_threshold:.2e}") + logging.info(f" - λMax: {args.lagrange_max}") + logging.info(f" - ρMax: {config.alm_rho_max:.1e}") + logging.info(f" - rho growth: ×{config.alm_rho_increase_factor:.1f} (continuous violations{config.alm_rho_increase_patience} steps)") + logging.info(f" - ALMscaling guard ratio: {config.alm_scale_guard_ratio:.2f}") + logging.info(f" - gradient clipping: {'enabled' if config.grad_clip_enabled else 'disabled'}") + + outer_cycles = max(1, int(args.outer_cycles)) + phys_steps_per_cycle = max(1, int(args.phys_steps_per_cycle)) + total_steps = outer_cycles * (phys_steps_per_cycle + 1) + logging.info( + f"🔁 Alternating optimization: outer cycles={outer_cycles}, physics steps/cycle={phys_steps_per_cycle}, " + f"total steps(including projections)≈{total_steps}" + ) + base_youngs_modulus = float(config.youngs_modulus) + youngs_modulus_scale = float(config.youngs_modulus_scale) + youngs_modulus_target = base_youngs_modulus * youngs_modulus_scale + youngs_modulus_delta = (youngs_modulus_target - base_youngs_modulus) / outer_cycles + projection_count = 0 + logging.info( + f" - linearly increase Young's modulus: E0={base_youngs_modulus:.2e}, " + f"Δ/projection={youngs_modulus_delta:.2e}, E_final={youngs_modulus_target:.2e} " + f"(scale={youngs_modulus_scale:.2f}x)" + ) + global_step = 0 + phys_step_count = 0 + + history = {"compliance": [], + "u_mean": [], + "c_relative_decrease": [], + "u_relative_decrease": [], + "epoch": []} + + thresholds = [0, 30, 40, 50, 60, 65, 70, 75, 80] + # thresholds = [0, 20, 30, 40, 50, 55, 60] + thresh_idx = 0 + latents_dir = os.path.join(args.out_folder, "latents") + os.makedirs(latents_dir, exist_ok=True) + finish = False + for cycle in range(outer_cycles): + if finish: + break + logging.info(f"\n{'='*60}") + logging.info(f"Outer Cycle {cycle+1}/{outer_cycles}") + logging.info(f"{'='*60}") + + for inner in range(phys_steps_per_cycle): + step_id = global_step + phys_step = phys_step_count + + # Physics optimization step with ALM. + compliance_loss, u_mean, sds_loss, total_loss = optimizer.training_step( + phys_step, lagrange_multiplier, rho, lambda_reg=args.lambda_reg, use_sds=True, save_step=step_id + ) + + # Update history + history["compliance"].append(compliance_loss) + history["u_mean"].append(u_mean) + + # Calculate relative decreases using current variables + c_decrease = (history["compliance"][0] - compliance_loss) / history["compliance"][0] * 100 + u_decrease = (history["u_mean"][0] - u_mean) / history["u_mean"][0] * 100 + history["c_relative_decrease"].append(c_decrease) + history["u_relative_decrease"].append(u_decrease) + logging.info( + f" 📉 Metrics | Comp: {compliance_loss:.3e} (↓ {c_decrease:.1f}%) | u_mean: {u_mean:.3e} (↓ {u_decrease:.1f}%)" + ) + + if not args.not_use_threshold: + if thresh_idx < len(thresholds): + current_threshold = thresholds[thresh_idx] + if (c_decrease > current_threshold) or (c_decrease == current_threshold) : + logging.info(f"\n✅ Threshold reached: {current_threshold}") + optimizer.save_mesh(current_threshold, args.out_folder, suffix="decrease", high_quality=True) + + latent_path = os.path.join(latents_dir, f"latent_{current_threshold}.pt") + torch.save({ + 'latents': optimizer.latents.detach().cpu(), + 'cond': optimizer.cond, + }, latent_path) + + optimizer.save_final_deformed_mesh(current_threshold, suffix="decrease") + + history["epoch"].append(phys_step) + thresh_idx += 1 + else: + finish = True + break + else: + is_first_phys_step = inner == 0 + is_last_phys_step = inner == phys_steps_per_cycle - 1 + if is_first_phys_step or is_last_phys_step: + optimizer.save_mesh(step_id, args.out_folder, high_quality=True) + latent_path = os.path.join(latents_dir, f"latent_{step_id}.pt") + torch.save({ + 'latents': optimizer.latents.detach().cpu(), + 'cond': optimizer.cond, + }, latent_path) + optimizer.save_final_deformed_mesh(step_id) + + # Normalized constraint: g = D / D_thr - 1. + violation = (compliance_loss / (compliance_threshold + 1e-8)) - 1.0 + g_pos = max(0.0, violation) + + # Update lambda and project it to the non-negative range. + lagrange_multiplier = max(0.0, lagrange_multiplier + rho * violation) + lagrange_multiplier = min(lagrange_multiplier, args.lagrange_max) + + # Increase rho after persistent violations. + if g_pos > 0.0: + violation_count += 1 + if violation_count >= config.alm_rho_increase_patience: + new_rho = min(rho * config.alm_rho_increase_factor, config.alm_rho_max) + if new_rho > rho: + rho = new_rho + logging.info(f" 🔧 rho increased: {rho:.2e} (continuous violations{config.alm_rho_increase_patience} steps)") + violation_count = 0 + else: + violation_count = 0 + + status = "❌ violating" if violation > 0 else "✅ within threshold" + + # Log a compact ALM summary. + logging.info( + f" 📊 Compliance (true) : {compliance_loss:.2e} vs threshold value{compliance_threshold:.2e} " + f"(g={violation:+.3e}, [g]+={g_pos:.3e}) {status}" + ) + logging.info(f" ⚖️ ALMStatus: λ={lagrange_multiplier:.4f} (max={args.lagrange_max}), ρ={rho:.2e}") + current_sds_weight = optimizer.get_current_sds_weight(phys_step) + if current_sds_weight > 0.0: + sds_percentage = (current_sds_weight * sds_loss) / (total_loss + 1e-10) * 100 + logging.info( + f" 🎨 Shape Loss: weight={current_sds_weight:.6f}, " + f"loss={sds_loss:.4e}, ratio={sds_percentage:.2f}%" + ) + else: + logging.info(f" 🎨 Shape Loss: disabled (weight is 0)") + + # Save only the first and last physics step of each outer cycle. + # is_first_phys_step = inner == 0 + # is_last_phys_step = inner == phys_steps_per_cycle - 1 + # if is_first_phys_step or is_last_phys_step: + # optimizer.save_mesh(step_id, args.out_folder) + + global_step += 1 + phys_step_count += 1 + + # Project back to the manifold by replacing latents with target_z0. + logging.info(f"\nStep {global_step} | Projection (E={optimizer.config.youngs_modulus:.2e} Pa)") + logging.info(" 🔮 manifold projection: add noise and compute target_z0, backreplace directlylatents") + projected = optimizer.project_to_manifold(step=global_step) + if not projected: + logging.warning(" ⚠️ projection failed, keep the physical result for this cycle") + else: + projection_count += 1 + new_E = base_youngs_modulus + youngs_modulus_delta * projection_count + new_E = min(new_E, youngs_modulus_target) + optimizer.config.youngs_modulus = new_E + if hasattr(optimizer, "E"): + optimizer.E = new_E + logging.info( + f" 🧱 Young's modulusupdate: E={new_E:.2e} " + f"(projection {projection_count}/{outer_cycles})" + ) + # if global_step % 20 == 0: + # projection_dir = os.path.join(args.out_folder, "projection_meshes") + # os.makedirs(projection_dir, exist_ok=True) + # optimizer.save_mesh(global_step, projection_dir) + global_step += 1 + + final_step = global_step + else: + # Pure SDS optimization. + for step in range(args.num_steps): + logging.info(f"\nStep {step}/{args.num_steps}") + optimizer.training_step_sds(step) + if step % 20 == 0: + optimizer.save_mesh(step, args.out_folder) + + # Save final results. + logging.info("\n✅ Optimization finished!save final results...") + optimizer.save_mesh(final_step, args.out_folder, high_quality=True) + if args.use_physics: + optimizer.save_final_target_z0_mesh(final_step) + optimizer.save_final_deformed_mesh(final_step) + + + final_latents_path = os.path.join(args.out_folder, "optimized_latents.pt") + torch.save({ + 'latents': optimizer.latents.detach().cpu(), + 'cond': optimizer.cond, + }, final_latents_path) + logging.info(f"💾 save optimized latents: {final_latents_path}") + logging.info(f"\n✅ all files saved to: {args.out_folder}") + + history_path = os.path.join(args.out_folder, "history.json") + with open(history_path, "w", encoding="utf-8") as f: + json.dump(history, f, indent=4) + + plot_history(history, save_dir=args.out_folder, filename="optimization_metrics.png") + + if args.use_physics: + logging.info(f"\n📊 force visualization data:") + logging.info(f" - directory: {os.path.join(args.out_folder, 'force_visualization')}") + logging.info(f" - quick view: cd {os.path.join(args.out_folder, 'force_visualization')} && python visualize_forces.py") + + +if __name__ == "__main__": + main() diff --git a/cfd_workflow_20261012/_seiler_ref/physiopt_new_scripts/sample_hunyuan.py b/cfd_workflow_20261012/_seiler_ref/physiopt_new_scripts/sample_hunyuan.py new file mode 100644 index 0000000000000000000000000000000000000000..e1b4cda469ecc246f2e2b5778a62af55dbf91b58 --- /dev/null +++ b/cfd_workflow_20261012/_seiler_ref/physiopt_new_scripts/sample_hunyuan.py @@ -0,0 +1,222 @@ +""" +Hunyuan3D-2.1 Shape Generation Script +Generate a 3D shape and save latent tokens for later physics optimization. +""" + +# python scripts/sample_hunyuan.py --image /scratch/cvlab/home/seiler/physiopt_new/input/new_york.png --out_folder /scratch/cvlab/home/seiler/physiopt_new/output/hunyuan_gen/new_york + +import os +# os.environ['TORCH_HOME'] = '/mnt/cvlab/scratch/cvlab/home/hantzhan/.torch' +import sys + +# Add Hunyuan3D-2.1 to the Python path. +hunyuan_path = os.path.abspath(os.path.join(os.path.dirname(__file__), "../Hunyuan3D-2.1")) +print(hunyuan_path) +if os.path.exists(hunyuan_path): + sys.path.insert(0, hunyuan_path) + print(f"✅ Added Hunyuan3D-2.1 to the Python path: {hunyuan_path}") +else: + print(f"⚠️ Warning: Hunyuan3D-2.1 path does not exist: {hunyuan_path}") + print(f" Please make sure Hunyuan3D-2.1 has been cloned to the correct location") + +sys.path.append("..") + +import torch +import trimesh +import numpy as np +from PIL import Image +from argparse import ArgumentParser + +try: + from hy3dgen.rembg import BackgroundRemover + from hy3dgen.shapegen import Hunyuan3DDiTFlowMatchingPipeline + from hy3dgen.shapegen.models.autoencoders import ShapeVAE +except ImportError as e: + print(f"❌ Failed to import the Hunyuan3D modules: {e}") + print(f"\nPlease set up Hunyuan3D-2.1 with the following steps:") + print(f"1. cd {os.path.dirname(hunyuan_path)}") + print(f"2. git clone https://github.com/Tencent/Hunyuan3D-2.git Hunyuan3D-2.1") + print(f"3. cd Hunyuan3D-2.1") + print(f"4. pip install -e .") + sys.exit(1) + + +if __name__ == "__main__": + parser = ArgumentParser() + parser.add_argument("--image", type=str, required=True, help="Input image path") + parser.add_argument("--out_folder", type=str, default="../out/hunyuan_tmp", help="Output directory") + parser.add_argument("--seed", type=int, default=42, help="Random seed (base value)") + parser.add_argument("--num_results", type=int, default=1, help="Number of generated results (different seeds)") + parser.add_argument("--num_inference_steps", type=int, default=50, help="Number of inference steps") + parser.add_argument("--guidance_scale", type=float, default=7.5, help="CFG strength") + parser.add_argument("--model_path", type=str, default="tencent/Hunyuan3D-2.1", help="Model path (using v2.1)") + parser.add_argument("--subfolder", type=str, default="hunyuan3d-dit-v2-1", help="Model subfolder") + parser.add_argument("--use_safetensors", action="store_true", help="Use safetensors format (default is ckpt)") + parser.add_argument("--octree_resolution", type=int, default=384, help="Octree resolution (higher is finer but slower)") + parser.add_argument("--mc_level", type=float, default=0, help="Marching Cubes threshold") + args = parser.parse_args() + + # Create the output directory. + os.makedirs(args.out_folder, exist_ok=True) + + # Print configuration details. + print("\n" + "="*60) + print("Hunyuan3D-2.1 configuration:") + print(f" - Model: {args.model_path}/{args.subfolder}") + print(f" - Model format: {'safetensors' if args.use_safetensors else 'checkpoint (.ckpt)'}") + print(f" - Inference steps: {args.num_inference_steps} (recommended: 50-100)") + print(f" - Result count: {args.num_results}") + print(f" - CFG strength: {args.guidance_scale} (recommended: 7.0-10.0)") + print(f" - Octree resolution: {args.octree_resolution} (recommended: 384-512)") + print(f" - MC threshold: {args.mc_level:.6f}") + print("="*60 + "\n") + + # ==================== Load the model ==================== + print("🔧 Loading the Hunyuan3D-2.1 model...") + print(f" Model path: {args.model_path}") + print(f" Subfolder: {args.subfolder}") + + try: + # Use the v2.1 model (newer and stronger). + # v2.1 uses the .ckpt format, so use_safetensors=False is required. + pipeline = Hunyuan3DDiTFlowMatchingPipeline.from_pretrained( + args.model_path, + subfolder=args.subfolder, + torch_dtype=torch.float16, + use_safetensors=args.use_safetensors + ) + + if pipeline is None: + raise ValueError("Pipeline loading failed and returned None") + + print(" ✅ Pipeline loaded successfully") + + # Note: to() may not return self, so do not reassign pipeline. + pipeline.to('cuda') + print(" ✅ Model moved to CUDA (dtype: fp16)") + + except Exception as e: + print(f"\n❌ Model loading failed: {e}") + print(f"\nPossible causes:") + print(f"1. The model has not been downloaded yet - the first run fetches it from Hugging Face") + print(f"2. Network issues - make sure huggingface.co is reachable") + print(f"3. Insufficient disk space") + print(f"\nSuggested fixes:") + print(f"1. Set a Hugging Face token if the model requires one:") + print(f" huggingface-cli login") + print(f"2. Or download the model manually:") + print(f" git lfs install") + print(f" git clone https://huggingface.co/tencent/Hunyuan3D-2.1") + print(f" Then use --model_path ./Hunyuan3D-2.1 --subfolder hunyuan3d-dit-v2-1") + print(f"3. Or use the v2.0 model instead:") + print(f" --model_path tencent/Hunyuan3D-2 --subfolder hunyuan3d-dit-v2-0") + import traceback + traceback.print_exc() + sys.exit(1) + + # Get the VAE for later mesh generation. + vae = pipeline.vae + print(f" ✅ VAE acquired successfully") + + # ==================== Prepare the input image ==================== + print(f"📷 Loading image: {args.image}") + image = Image.open(args.image).convert("RGBA") + + # If this is an RGB image, remove the background with rembg. + if image.mode == 'RGB': + print(" Removing background...") + rembg = BackgroundRemover() + image = rembg(image) + + # Save the processed image. + image.save(os.path.join(args.out_folder, "input_image.png")) + + # ==================== Generate the 3D shape ==================== + print(f"🎨 Generating a 3D shape (steps={args.num_inference_steps}, cfg={args.guidance_scale})...") + num_results = max(1, int(args.num_results)) + + for idx in range(num_results): + sample_seed = args.seed + idx + sample_out = args.out_folder if num_results == 1 else os.path.join(args.out_folder, f"sample_{idx:02d}") + os.makedirs(sample_out, exist_ok=True) + + if num_results > 1: + image.save(os.path.join(sample_out, "input_image.png")) + + print(f"\n=== Sample {idx+1}/{num_results} | seed={sample_seed} ===") + + # Set random seeds. + torch.manual_seed(sample_seed) + np.random.seed(sample_seed) + + # Use the simplified pipeline call, consistent with sample_hunyuan_simple.py. + # Step 1: generate and save latents. + latents = pipeline( + image=image, + num_inference_steps=args.num_inference_steps, + guidance_scale=args.guidance_scale, + generator=torch.Generator(device='cuda').manual_seed(sample_seed), + output_type='latent', # Return latents only; do not decode to mesh yet. + ) + + print("✅ Latent generation completed!") + + # ==================== Save latents for physics optimization ==================== + latents_path = os.path.join(sample_out, "latents.pt") + + # Save latents and the image. + save_dict = { + 'latents': latents.cpu() if isinstance(latents, torch.Tensor) else latents, + 'image': np.array(image) + } + + torch.save(save_dict, latents_path) + print(f"✅ Saved latents to: {latents_path}") + if isinstance(latents, torch.Tensor): + print(f" - Latents shape: {latents.shape}") + print(f" - Latents range: [{latents.min().item():.3f}, {latents.max().item():.3f}]") + + # Step 2: decode latents to a mesh with _export(). + print(f"🎭 Decoding latents into a mesh...") + print(f" Using parameters: octree_resolution={args.octree_resolution}, mc_level={args.mc_level:.6f}") + mesh = pipeline._export( + latents, + output_type='trimesh', + box_v=1.01, + mc_level=args.mc_level, + num_chunks=20000, + octree_resolution=args.octree_resolution, + mc_algo='mc', + enable_pbar=True + )[0] + + print("✅ Decoding completed!") + + # ==================== Save the mesh ==================== + mesh_path = os.path.join(sample_out, "generated_mesh.obj") + mesh.export(mesh_path) + print(f"💾 Saved mesh to: {mesh_path}") + + # Save GLB as well. + glb_path = os.path.join(sample_out, "generated_mesh.glb") + mesh.export(glb_path) + print(f"💾 Saved GLB to: {glb_path}") + + # ==================== Print summary statistics ==================== + print("\n📊 Generation summary:") + print(f" - Vertices: {len(mesh.vertices)}") + print(f" - Faces: {len(mesh.faces)}") + if isinstance(latents, torch.Tensor): + print(f" - Latent shape: {latents.shape}") + + # Free GPU memory. + del mesh + if torch.cuda.is_available(): + torch.cuda.empty_cache() + + print(f"\n✅ All done! Outputs were saved to: {args.out_folder}") + if num_results == 1: + print(f" - You can use latents.pt for physics optimization") + print(f" - Run: python viewer_hunyuan_web.py --latents {latents_path}") + else: + print(f" - Each sample is stored in its own sample_XX subdirectory") diff --git a/cfd_workflow_20261012/_seiler_ref/physiopt_new_scripts/sample_hunyuan_from_folder.py b/cfd_workflow_20261012/_seiler_ref/physiopt_new_scripts/sample_hunyuan_from_folder.py new file mode 100644 index 0000000000000000000000000000000000000000..3b668322758184ae7311fdd4f969f9d61d5249e4 --- /dev/null +++ b/cfd_workflow_20261012/_seiler_ref/physiopt_new_scripts/sample_hunyuan_from_folder.py @@ -0,0 +1,223 @@ +""" +Hunyuan3D-2.1 Shape Generation Script +Generate a 3D shape and save latent tokens for later physics optimization. +""" + +import os +import sys +import glob +import logging +import torch +import trimesh +import numpy as np +from PIL import Image +from argparse import ArgumentParser + +# Configure logging +logging.basicConfig( + level=logging.INFO, + format='%(asctime)s - %(levelname)s - %(message)s', + handlers=[logging.StreamHandler(sys.stdout)] +) + +# Add Hunyuan3D-2.1 to the Python path. +hunyuan_path = os.path.abspath(os.path.join(os.path.dirname(__file__), "../Hunyuan3D-2.1")) + +if os.path.exists(hunyuan_path): + sys.path.insert(0, hunyuan_path) + logging.info(f"✅ Added Hunyuan3D-2.1 to the Python path: {hunyuan_path}") +else: + logging.warning(f"⚠️ Hunyuan3D-2.1 path does not exist: {hunyuan_path}") + logging.warning(" Please make sure Hunyuan3D-2.1 has been cloned to the correct location") + +sys.path.append("..") + +try: + from hy3dgen.rembg import BackgroundRemover + from hy3dgen.shapegen import Hunyuan3DDiTFlowMatchingPipeline + from hy3dgen.shapegen.models.autoencoders import ShapeVAE +except ImportError as e: + logging.error(f"❌ Failed to import the Hunyuan3D modules: {e}") + logging.info("\nPlease set up Hunyuan3D-2.1 with the following steps:") + logging.info(f"1. cd {os.path.dirname(hunyuan_path)}") + logging.info("2. git clone https://github.com/Tencent/Hunyuan3D-2.git Hunyuan3D-2.1") + logging.info("3. cd Hunyuan3D-2.1") + logging.info("4. pip install -e .") + sys.exit(1) + + +if __name__ == "__main__": + parser = ArgumentParser() + parser.add_argument("--input", type=str, required=True, help="Input image path OR input folder path containing images") + parser.add_argument("--seed", type=int, default=42, help="Random seed (base value)") + parser.add_argument("--num_results", type=int, default=1, help="Number of generated results (different seeds)") + parser.add_argument("--num_inference_steps", type=int, default=50, help="Number of inference steps") + parser.add_argument("--guidance_scale", type=float, default=7.5, help="CFG strength") + parser.add_argument("--model_path", type=str, default="tencent/Hunyuan3D-2.1", help="Model path (using v2.1)") + parser.add_argument("--subfolder", type=str, default="hunyuan3d-dit-v2-1", help="Model subfolder") + parser.add_argument("--use_safetensors", action="store_true", help="Use safetensors format (default is ckpt)") + parser.add_argument("--octree_resolution", type=int, default=384, help="Octree resolution (higher is finer but slower)") + parser.add_argument("--mc_level", type=float, default=0, help="Marching Cubes threshold") + args = parser.parse_args() + + # Log configuration details + logging.info("="*60) + logging.info("Hunyuan3D-2.1 configuration:") + logging.info(f" - Model: {args.model_path}/{args.subfolder}") + logging.info(f" - Model format: {'safetensors' if args.use_safetensors else 'checkpoint (.ckpt)'}") + logging.info(f" - Inference steps: {args.num_inference_steps}") + logging.info(f" - Result count: {args.num_results}") + logging.info(f" - CFG strength: {args.guidance_scale}") + logging.info(f" - Octree resolution: {args.octree_resolution}") + logging.info(f" - MC threshold: {args.mc_level:.6f}") + logging.info("="*60) + + # ==================== Load the model ==================== + logging.info("🔧 Loading the Hunyuan3D-2.1 model...") + + try: + pipeline = Hunyuan3DDiTFlowMatchingPipeline.from_pretrained( + args.model_path, + subfolder=args.subfolder, + torch_dtype=torch.float16, + use_safetensors=args.use_safetensors + ) + + if pipeline is None: + raise ValueError("Pipeline loading failed and returned None") + + logging.info(" ✅ Pipeline loaded successfully") + pipeline.to('cuda') + logging.info(" ✅ Model moved to CUDA (dtype: fp16)") + + except Exception as e: + logging.error(f"❌ Model loading failed: {e}") + import traceback + logging.error(traceback.format_exc()) + sys.exit(1) + + vae = pipeline.vae + logging.info(" ✅ VAE acquired successfully") + + # Init Background Remover once (optimization) + logging.info(" 🔧 Initializing Background Remover...") + rembg = BackgroundRemover() + + # ==================== Gather Input Images & Set Up Folders ==================== + # Build absolute path for the input folder + input_folder = os.path.join("/scratch/cvlab/home/seiler/physiopt_new/input", args.input) + + # Check if the absolute path is a valid existing directory + if os.path.isdir(input_folder): + logging.info(f"📁 Input is a directory. Searching for images in: {input_folder}") + # Build image paths + image_paths = sorted([ + os.path.join(input_folder, f) for f in os.listdir(input_folder) + if f.lower().endswith(('.png', '.jpg', '.jpeg', '.webp')) + ]) + + # Base output folder takes the name of the input argument + base_out_folder = os.path.join("/scratch/cvlab/home/seiler/physiopt_new/output/hunyuan_gen", args.input) + else: + logging.error(f"❌ Error: Input path must be a valid folder. Could not find: {input_folder}") + sys.exit(1) + + if not image_paths: + logging.error(f"❌ No images found in {input_folder}") + sys.exit(1) + + logging.info(f"✅ Found {len(image_paths)} image(s) to process.") + + # Create the root output directory + os.makedirs(base_out_folder, exist_ok=True) + + # ==================== Main Loop over Images ==================== + for img_path in image_paths: + img_name = os.path.splitext(os.path.basename(img_path))[0] + current_out_folder = os.path.join(base_out_folder, img_name) + + # Skip if output already exists + check_file = os.path.join(current_out_folder, "latents.pt") + if os.path.exists(check_file): + logging.info(f"⏭️ Skipping: Output already exists for {img_name} ({check_file})") + continue + + os.makedirs(current_out_folder, exist_ok=True) + + logging.info("="*60) + logging.info(f"📷 Processing image: {img_path}") + logging.info(f"📁 Output will be saved to: {current_out_folder}") + + # Load and process image + image = Image.open(img_path).convert("RGBA") + + if image.mode == 'RGB': + logging.info(" Removing background...") + image = rembg(image) + + # Save the processed image + image.save(os.path.join(current_out_folder, "input_image.png")) + + # ==================== Generate the 3D shape ==================== + logging.info("🎨 Generating 3D shape(s)...") + num_results = max(1, int(args.num_results)) + + for idx in range(num_results): + sample_seed = args.seed + idx + # Handle subfolders for multiple results + if num_results == 1: + sample_out = current_out_folder + else: + sample_out = os.path.join(current_out_folder, f"sample_{idx:02d}") + os.makedirs(sample_out, exist_ok=True) + image.save(os.path.join(sample_out, "input_image.png")) + + logging.info(f" === Sample {idx+1}/{num_results} | seed={sample_seed} ===") + torch.manual_seed(sample_seed) + np.random.seed(sample_seed) + + # Step 1: generate and save latents + latents = pipeline( + image=image, + num_inference_steps=args.num_inference_steps, + guidance_scale=args.guidance_scale, + generator=torch.Generator(device='cuda').manual_seed(sample_seed), + output_type='latent', + ) + + # Save latents + latents_path = os.path.join(sample_out, "latents.pt") + save_dict = { + 'latents': latents.cpu() if isinstance(latents, torch.Tensor) else latents, + 'image': np.array(image) + } + torch.save(save_dict, latents_path) + logging.info(f" ✅ Saved latents to: {latents_path}") + + # Step 2: decode latents to a mesh + logging.info(" 🎭 Decoding latents into a mesh...") + mesh = pipeline._export( + latents, + output_type='trimesh', + box_v=1.01, + mc_level=args.mc_level, + num_chunks=20000, + octree_resolution=args.octree_resolution, + mc_algo='mc', + enable_pbar=False # Avoid progress bar spam + )[0] + + # Save the mesh + mesh.export(os.path.join(sample_out, "generated_mesh.obj")) + mesh.export(os.path.join(sample_out, "generated_mesh.glb")) + logging.info(" 💾 Saved OBJ and GLB meshes") + + # Free memory + del mesh + del latents + if torch.cuda.is_available(): + torch.cuda.empty_cache() + + logging.info("="*60) + logging.info(f"✅ All {len(image_paths)} images processed successfully!") + logging.info(f"📂 Check the outputs in: {base_out_folder}") \ No newline at end of file diff --git a/cfd_workflow_20261012/_seiler_ref/physiopt_new_scripts/test_init_compliance.py b/cfd_workflow_20261012/_seiler_ref/physiopt_new_scripts/test_init_compliance.py new file mode 100644 index 0000000000000000000000000000000000000000..9f784eac07fe69151f6a47f0223af7780d2cfd37 --- /dev/null +++ b/cfd_workflow_20261012/_seiler_ref/physiopt_new_scripts/test_init_compliance.py @@ -0,0 +1,3074 @@ +""" +Hunyuan3D-2.1 physical optimization + shape-prior optimization. +""" + +import os +import copy +# os.environ['TORCH_HOME'] = '/mnt/cvlab/scratch/cvlab/home/hantzhan/.torch' +import sys +import shutil + +# Add Hunyuan3D-2.1 to the Python path. +hunyuan_path = os.path.abspath(os.path.join(os.path.dirname(__file__), "../../Hunyuan3D-2.1")) +# Note: logging is not imported yet, so use print here if needed. +# Basic logging is configured near the top of the file after import. + +sys.path.append("..") + +from matplotlib import pyplot as plt +import torch +import torch.nn.functional as F +import trimesh +import numpy as np +from PIL import Image +import argparse +import json +from typing import Tuple, Optional, List +from dataclasses import dataclass, field +import traceback +import logging + +# Configure logging here only conceptually; main() will reconfigure it to +# log to both the console and a file. +# Do not call basicConfig here so the main() configuration remains effective. +# logging.basicConfig(level=logging.INFO, format='%(levelname)s: %(message)s') + +# Physical-simulation imports. +PHYSIOPT_AVAILABLE = False +try: + from physiopt.utils.phys_utils import generate_hex + from physiopt.utils.grid_utils import filter_one_component + from physiopt.opt.field import occ_kernel + from physiopt.opt.forces import ForceConfig + PHYSIOPT_AVAILABLE = True + logging.info("✅ physics simulation moduleimportsucceeded") +except ImportError as e: + logging.warning(f"⚠️ warning: physics simulation moduleimportfailed: {e}") + logging.warning(" if you only run SDS optimization, you can ignore this warning") + PHYSIOPT_AVAILABLE = False + + def generate_hex(res, limits=[(-0.5, 0.5), (-0.5, 0.5), (-0.5, 0.5)], device="cuda", return_coords=False): + """Placeholder for hexahedral grid generation. + + Returns tensors in the same format as the real function. + """ + logging.warning(f"⚠️ warning: using placeholdergenerate_hex, please install the physiopt module") + return None, None + + def filter_one_component(mask, res): + """Placeholder for connected-component filtering. + + Args: + mask: Element mask [res*res*res] + res: Voxel resolution + """ + return mask + + def occ_kernel(sdf, res, beta): + """Placeholder for SDF-to-occupancy conversion.""" + return torch.sigmoid(-sdf * beta) + +# Warp physics-engine import. +try: + import warp as wp + wp.init() + WARP_AVAILABLE = True + logging.info("✅ Warp physics engineInitializationsucceeded") +except ImportError: + WARP_AVAILABLE = False + logging.warning("⚠️ warning: Warp physics enginenot installed, physics simulationwill be unavailable") + logging.warning(" Install: pip install warp-lang") + +# Hunyuan3D imports +try: + from hy3dgen.shapegen.models.autoencoders import ShapeVAE + from hy3dgen.shapegen import Hunyuan3DDiTFlowMatchingPipeline + from hy3dgen.shapegen.pipelines import export_to_trimesh +except ImportError as e: + logging.error(f"❌ failed to import Hunyuan3D modules: {e}") + logging.error(f"\nplease follow these steps to set upHunyuan3D-2.1:") + logging.error(f"1. cd {os.path.dirname(hunyuan_path)}") + logging.error(f"2. git clone https://github.com/Tencent/Hunyuan3D-2.git Hunyuan3D-2.1") + logging.error(f"3. cd Hunyuan3D-2.1") + logging.error(f"4. pip install -e .") + sys.exit(1) + + +@dataclass +class OptimizationConfig: + """Optimization config for physics + SDS.""" + # Physical-simulation parameters. + res: int = 32 # Voxel resolution (16/32/64), matching the reference code. + # Restored physical settings from the stable v90 configuration. + p_exponent: float = 1.0 # SIMP penalty exponent. + alpha_min: float = 0.01 # Minimum density, restored from v90. + volume_term: float = 1000000.0 # Volume-constraint weight, currently disabled. + occ_sdf_beta: float = 2.0 # Sigmoid-kernel beta, restored from v90. + one_cc_only: bool = False # Keep only the largest connected component. + + # SDS parameters. + # Use dynamic SDS weights so physics dominates early and aesthetics enters later. + sds_timestep: float = 0.1 # SDS timestep; smaller values preserve more detail. + sds_weight: float = 1.0 # SDS weight relative to the physical gradient. + sds_weight_start: float = 1e5 # 0.1 # 0.0001 # Initial SDS weight. + sds_weight_end: float = 1e5 # 1.0 # 0.001 # Final SDS weight. + guidance_scale: float = 7.5 # Standard CFG guidance scale for stronger image conditioning. + sds_projection_max_rel: float = 0.0 # Max relative target_z0 projection offset (0 = unlimited). + sds_use_uncond: bool = False # Use the unconditional branch when guidance_scale <= 1. + sds_target_z0_update_interval: int = 10 # target_z0 update interval; tied to phys_steps_per_cycle. + sds_target_z0_ema_beta: float = 0.9 # EMA smoothing coefficient; larger is smoother. + + lagrange_max: float = 50.0 # Max lambda. + compliance_threshold: float = 200.0 # Compliance threshold used for normalization. + alm_rho_init: float = 1.0 # Initial rho. + alm_rho_max: float = 1000.0 # Max rho. + alm_rho_increase_factor: float = 2.0 # Rho growth factor. + alm_rho_increase_patience: int = 5 # Number of consecutive violations before increasing rho. + alm_scale_guard_ratio: float = 0.95 # ALM scaling guard to stay below gradient clipping. + + # Topology control. + re_extract_interval: int = 5 # Re-extract the solid every N steps; 0 disables it. + + # Material properties. Values are aligned with the reference setup. + # youngs_modulus is already specified directly in Pa, so no unit conversion is needed. + youngs_modulus: float = 5e8 # 1e9 # Pa (= 1 GPa), restored from v90. + youngs_modulus_scale: float = 2.0 # Final multiplier after the last projection in alternating mode. + poissons_ratio: float = 0.3 # Poisson's ratio (dimensionless). + density: float = 650.0 # Material density (kg/m^3). + + ## Wood + # youngs_modulus: float = 9e9 # Pa (= 1 GPa), aligned with the reference code. + # poissons_ratio: float = 0.35 # Poisson's ratio (dimensionless), matches the reference. + # density: float = 400.0 # Material density (kg/m^3), matches the reference. + + ## PVG + # youngs_modulus: float = 3.25e9 # Pa (= 1 GPa), aligned with the reference code. + # poissons_ratio: float = 0.38 # Poisson's ratio (dimensionless), matches the reference. + # density: float = 1380.0 # Material density (kg/m^3), matches the reference. + + # Load conditions; supports multiple forces like config.json. + forces: List = None # List of ForceConfig objects. + # Multiple localized load entries, each with its own force and region settings. + force_entries: Optional[List[dict]] = None + + # Local-loading settings, e.g. to mimic a person sitting on a chair. + use_local_loading: bool = True # Use local loading instead of global uniform loading. + seat_height_min_ratio: float = 0.3 # Lower bound of the seat band as a height ratio. + seat_height_max_ratio: float = 0.5 # Upper bound of the seat band as a height ratio. + force_region_mode: str = "top_percent" # Load-region mode: top_percent / height_ratio / bbox. + force_top_percent: float = 0.05 # In top_percent mode, use the highest-Y fraction of nodes. + force_bbox: Optional[List[float]] = None # bbox mode: x_min x_max y_min y_max z_min z_max. + force_bbox_ratio: Optional[List[float]] = None # bbox mode in normalized node bounds [0, 1]. + + # Optimization parameters, restored from the stable v90 configuration. + lr: float = 0.001 # Learning rate. + num_steps: int = 100 # Number of optimization steps. + use_sgd: bool = False # Use SGD instead of Adam. + grad_clip_enabled: bool = False # Enable gradient clipping; off by default. + save_every: int = 10 # Save interval in steps. + deformed_mesh_interval: int = 10 # Save interval for deformed meshes. + deformed_mesh_disp_min: float = 0.0 # Minimum displacement for deformed-mesh color mapping. + deformed_mesh_disp_max: float = 0.2 # Maximum displacement for deformed-mesh color mapping. + + # Output path. + out_folder: str = "../out/hunyuan_opt" # Output directory. + + # Device. + device: str = "cuda" # Compute device. + + # Whether to enable physics optimization. + use_physics: bool = True # Enable physical-constraint optimization. + + def __post_init__(self): + # Set default loads in the Hunyuan Y-up coordinate system: + # X = right, Y = up, Z = forward. + if self.forces is None: + try: + from physiopt.opt.forces import ForceConfig + self.forces = [ + ForceConfig(external_force=[0.0, -100000.0, 0.0]) # 100 kN downward along Y. + # ForceConfig(external_force=[0.0, 0.0, -500.0]), # 500 N backward along Z. + ] + except ImportError: + # Fallback format if physiopt is unavailable; keep only the force vectors. + self.forces = [ + {'external_force': [0.0, -100000.0, 0.0]} # 100 kN downward along Y. + # {'external_force': [0.0, 0.0, -500.0]}, # Backward along Z. + ] + + +class HunyuanSDSOptimizer: + """Hunyuan3D SDS optimizer with differentiable physics support.""" + + def __init__( + self, + latents: torch.Tensor, + cond: dict, # Condition dict containing positive and negative branches. + vae: ShapeVAE, + flow_model: torch.nn.Module, + config: OptimizationConfig, + scheduler=None, + device: str = 'cuda' + ): + """ + Args: + latents: Initial latent tokens [1, N, D]. + cond: Condition dict returned by pipeline.encode_cond. + vae: Hunyuan3D VAE model. + flow_model: Hunyuan3D Flow Matching model. + scheduler: Hunyuan3D Flow Matching scheduler used to align target_z0. + config: Optimization config. + device: Compute device. + """ + self.device = device + self.config = config + + # Models. + self.vae = vae.to(device).eval() + self.flow_model = flow_model.to(device).eval() + if scheduler is not None: + try: + self.sds_scheduler = copy.deepcopy(scheduler) + except Exception: + self.sds_scheduler = scheduler + logging.warning("⚠️ Scheduler deepcopyfailed, already fallback to originalscheduler") + else: + self.sds_scheduler = None + + # Create a differentiable SDF query helper. + from hy3dgen.shapegen.models.autoencoders.differentiable_sdf_query import DifferentiableSDFQuery + self.sdf_query = DifferentiableSDFQuery( + vae=self.vae, + bounds=0.8, # Our coordinate range is [-0.8, 0.8]. + chunk_size=8192 # Batch query size. + ) + logging.info(f"✅ created differentiable SDF query helper") + + # Latent tokens are the variables being optimized. + # Use float32 instead of float16 to avoid numeric overflow. + self.latents = latents.clone().to(device).to(torch.float32).requires_grad_(True) + + logging.info(f" ⚠️ note: Latentsfloat32FP16value") + + # Move conditioning data to the target device recursively. + def to_device_recursive(obj): + if isinstance(obj, torch.Tensor): + return obj.to(device) + elif isinstance(obj, dict): + return {k: to_device_recursive(v) for k, v in obj.items()} + elif isinstance(obj, (list, tuple)): + return type(obj)(to_device_recursive(item) for item in obj) + else: + return obj + + self.cond = to_device_recursive(cond) + self._cond_warned_cfg_repeat = False + self._cond_warned_nocfg_slice = False + + # Optimizer selection. + if config.use_sgd: + self.optimizer = torch.optim.SGD([self.latents], lr=config.lr, momentum=0.0) + opt_name = "SGD" + else: + self.optimizer = torch.optim.Adam([self.latents], lr=config.lr, betas=(0.9, 0.999), eps=1e-8) + opt_name = "Adam" + + logging.info(f"✅ HunyuanSDSOptimizerInitializationcompleted (with differentiable physics support) ") + logging.info(f" - Latents shape: {self.latents.shape}") + logging.info(f" - Latents dtype: {self.latents.dtype} (optimized in float32)") + logging.info(f" - Device: {device}") + logging.info(f" - Optimizer: {opt_name}") + logging.info(f" - Learning rate: {config.lr}") + + # target_z0 EMA cache. + self.target_z0_ema = None + self.target_z0_last_velocity = None + self.target_z0_last_update = None + + def get_field(self, x: torch.Tensor, latents: torch.Tensor = None) -> torch.Tensor: + """Differentiable SDF query through the VAE geo_decoder. + + Args: + x: Query points [N, 3] in the range [-0.8, 0.8]^3. + latents: Optional latent tokens; defaults to self.latents. + + Returns: + sdf: SDF values [N] with gradient support. + """ + if latents is None: + latents = self.latents + + # Match the official pipeline: divide by scale_factor before decoding. + scale_factor = getattr(self.vae, "scale_factor", 1.0) + latents_scaled = latents / scale_factor + + # Convert to FP16 because the VAE expects FP16 inputs. + latents_fp16 = latents_scaled.to(torch.float16) + + # Decode with the VAE decoder while preserving gradients. + decoded_latents = self.vae.decode(latents_fp16) + + # Query the SDF through the differentiable helper. + # sdf_query calls geo_decoder internally, so keep FP16 to match VAE weights. + sdf = self.sdf_query( + decoded_latents, # Keep FP16 and let sdf_query handle the rest. + x, + return_occupancy=False # Return SDF instead of occupancy. + ) # [N] + + return sdf + + def _cond_batch_size(self, cond) -> Optional[int]: + if isinstance(cond, torch.Tensor): + return cond.shape[0] if cond.dim() >= 1 else None + if isinstance(cond, dict): + for v in cond.values(): + bsz = self._cond_batch_size(v) + if bsz is not None: + return bsz + if isinstance(cond, (list, tuple)): + for v in cond: + bsz = self._cond_batch_size(v) + if bsz is not None: + return bsz + return None + + def _cond_slice(self, cond, batch_slice: slice): + if isinstance(cond, torch.Tensor): + if cond.dim() >= 1 and cond.shape[0] >= batch_slice.stop: + return cond[batch_slice] + return cond + if isinstance(cond, dict): + return {k: self._cond_slice(v, batch_slice) for k, v in cond.items()} + if isinstance(cond, (list, tuple)): + return type(cond)(self._cond_slice(v, batch_slice) for v in cond) + return cond + + def _cond_repeat(self, cond, repeats: int): + if isinstance(cond, torch.Tensor): + if cond.dim() >= 1: + rep_shape = (repeats,) + (1,) * (cond.dim() - 1) + return cond.repeat(rep_shape) + return cond + if isinstance(cond, dict): + return {k: self._cond_repeat(v, repeats) for k, v in cond.items()} + if isinstance(cond, (list, tuple)): + return type(cond)(self._cond_repeat(v, repeats) for v in cond) + return cond + + def _get_cond_for_guidance(self, use_cfg: bool): + cond = self.cond + bsz = self._cond_batch_size(cond) + if use_cfg: + if bsz == 1: + if not self._cond_warned_cfg_repeat: + logging.warning("⚠️ guidance_scale>1 cond batch=1, already condCFG") + self._cond_warned_cfg_repeat = True + return self._cond_repeat(cond, 2) + if bsz is not None and bsz > 2: + return self._cond_slice(cond, slice(0, 2)) + return cond + # no-CFG + if bsz is not None and bsz >= 2: + if self.config.sds_use_uncond: + if not self._cond_warned_nocfg_slice: + logging.info("ℹ️ guidance_scale<=1, useno conditioncond[1:2]") + self._cond_warned_nocfg_slice = True + return self._cond_slice(cond, slice(1, 2)) + if not self._cond_warned_nocfg_slice: + logging.info("ℹ️ guidance_scale<=1, already usecond[0:1]batch") + self._cond_warned_nocfg_slice = True + return self._cond_slice(cond, slice(0, 1)) + if self.config.sds_use_uncond and bsz == 1 and not self._cond_warned_nocfg_slice: + logging.warning("⚠️ sds_use_uncond=1 cond batch=1, already fallback to conditself") + self._cond_warned_nocfg_slice = True + return cond + + def latents_to_mesh(self, latents: torch.Tensor, octree_res: int = 128) -> Optional[trimesh.Trimesh]: + """Decode latent tokens into a mesh. + + Args: + latents: Latent tokens [1, N, D] (float32). + octree_res: Octree resolution. 128 is faster; 256 is higher quality. + + Returns: + A trimesh.Trimesh object, or None on failure. + """ + with torch.no_grad(): + # Skip invalid latent tensors early. + if torch.isnan(latents).any() or torch.isinf(latents).any(): + logging.warning(" latents_to_mesh: latentscontains NaN or Inf, skip") + return None + + # Match the official pipeline by dividing by scale_factor first. + scale_factor = getattr(self.vae, "scale_factor", 1.0) + latents_scaled = latents / scale_factor + + # Decode in FP16 because the VAE expects FP16 inputs. + latents_fp16 = latents_scaled.to(torch.float16) + + try: + # VAE decode. + decoded_latents = self.vae.decode(latents_fp16) + + # Skip invalid decoded latents. + if torch.isnan(decoded_latents).any() or torch.isinf(decoded_latents).any(): + logging.warning(" latents_to_mesh: decoded_latentscontains NaN or Inf, skip") + return None + except Exception as e: + logging.debug(f" latents_to_mesh: VAE decodingfailed: {e}") + return None + + # Use an adaptive mc_level fallback if the default level fails. + try: + # First try the standard mc_level=0.0. + mesh = self.vae.latents2mesh( + decoded_latents, + output_type='trimesh', + bounds=1.01, + mc_level=0.0, + num_chunks=20000, + octree_resolution=octree_res, + mc_algo='mc', + enable_pbar=False + ) + mesh = export_to_trimesh(mesh)[0] + return mesh + + except ValueError as e: + error_msg = str(e) + if "Surface level must be within volume data range" in error_msg: + # Estimate a better mc_level from sampled SDF statistics. + logging.debug(f" latents_to_mesh: mc_level=0.0 failed, try an adaptive level...") + + try: + # Sample a coarse grid to estimate the SDF range. + grid_size = 32 + x = torch.linspace(-1.0, 1.0, grid_size, device=decoded_latents.device) + y = torch.linspace(-1.0, 1.0, grid_size, device=decoded_latents.device) + z = torch.linspace(-1.0, 1.0, grid_size, device=decoded_latents.device) + xx, yy, zz = torch.meshgrid(x, y, z, indexing='ij') + points = torch.stack([xx, yy, zz], dim=-1).reshape(-1, 3) # [N, 3] + + # query the SDF values. + sdf_values = self.get_field(points, latents=latents) + + # Compute basic statistics. + sdf_median = torch.median(sdf_values).item() + sdf_min = sdf_values.min().item() + sdf_max = sdf_values.max().item() + sdf_mean = sdf_values.mean().item() + + logging.debug(f" SDFstatistics: min={sdf_min:.4f}, max={sdf_max:.4f}, median={sdf_median:.4f}, mean={sdf_mean:.4f}") + + # No clear surface can be extracted if the SDF range is too small. + if abs(sdf_max - sdf_min) < 1e-4: + logging.debug(f" SDFrange is too small to extract a surface") + return None + + # Try several plausible candidate levels. + candidate_levels = [ + sdf_median, # Median. + sdf_mean, # Mean. + (sdf_min + sdf_max) / 2, # Midpoint of the range. + sdf_min + (sdf_max - sdf_min) * 0.3, # 30% point. + sdf_min + (sdf_max - sdf_min) * 0.7, # 70% point. + ] + + # Clamp all levels to the valid range. + valid_levels = [ + max(sdf_min + 0.001, min(sdf_max - 0.001, level)) + for level in candidate_levels + ] + + # Remove duplicates. + valid_levels = list(set(valid_levels)) + + logging.debug(f" try {len(valid_levels)} candidate levels: {[f'{l:.4f}' for l in valid_levels[:3]]}...") + + # Try each candidate level in order. + for i, adaptive_level in enumerate(valid_levels): + try: + mesh = self.vae.latents2mesh( + decoded_latents, + output_type='trimesh', + bounds=1.01, + mc_level=adaptive_level, + num_chunks=20000, + octree_resolution=octree_res, + mc_algo='mc', + enable_pbar=False + ) + mesh = export_to_trimesh(mesh)[0] + logging.info(f" ✅ uselevelsucceeded (level={adaptive_level:.4f}, attempt {i+1})") + return mesh + except (ValueError, RuntimeError) as level_error: + # Try the next level if this one fails. + if i < len(valid_levels) - 1: + continue + else: + # All candidate levels failed. + logging.debug(f" all candidate levels failed") + return None + + # No candidate succeeded. + return None + + except Exception as adaptive_error: + logging.debug(f" adaptive extraction failed: {type(adaptive_error).__name__}: {str(adaptive_error)[:50]}") + return None + + elif "No surface found" in error_msg: + logging.debug(f" latents_to_mesh: Marching cubesno surface found, skip") + return None + else: + logging.warning(f" latents_to_mesh: unknown ValueError: {error_msg}") + return None + + except RuntimeError as e: + error_msg = str(e) + if "No surface found" in error_msg or "Surface level" in error_msg: + logging.debug(f" latents_to_mesh: Marching cubesfailed, skip") + return None + else: + logging.warning(f" latents_to_mesh: RuntimeError: {error_msg}") + return None + + except Exception as e: + # Catch any other unexpected failure. + logging.warning(f" latents_to_mesh: unexpected exception: {type(e).__name__}: {e}") + return None + + def _filter_floating_components(self, mesh: trimesh.Trimesh) -> trimesh.Trimesh: + """Remove small floating fragments and keep only the largest component.""" + try: + components = mesh.split(only_watertight=False) + if len(components) <= 1: + return mesh + + face_counts = [len(comp.faces) for comp in components] + max_idx = int(np.argmax(face_counts)) + filtered = components[max_idx] + dropped = len(components) - 1 + + logging.info(f" 🧹 filter floating fragments: kept{len(filtered.faces)} faces, discarded{dropped} small components") + return filtered + except Exception as e: + logging.warning(f" failed to filter floating fragments: {type(e).__name__}: {str(e)[:100]}") + return mesh + + def _sample_displacement_to_vertices( + self, + vertices: np.ndarray, + nodes: np.ndarray, + displacement: np.ndarray, + ) -> np.ndarray: + """Sample the voxel-node displacement field onto mesh vertices by nearest neighbor.""" + try: + from scipy.spatial import cKDTree + tree = cKDTree(nodes) + _, idx = tree.query(vertices, k=1) + return displacement[idx] + except Exception as e: + try: + from sklearn.neighbors import NearestNeighbors + nn = NearestNeighbors(n_neighbors=1, algorithm="auto") + nn.fit(nodes) + idx = nn.kneighbors(vertices, return_distance=False).squeeze(1) + return displacement[idx] + except Exception as e2: + logging.warning(f" displacement sampling failed, fallback to zero displacement: {type(e).__name__}: {str(e)[:100]}") + logging.debug(f" secondaryError: {type(e2).__name__}: {str(e2)[:100]}") + return np.zeros_like(vertices) + + def _normalize_displacement_magnitude( + self, disp_mag: np.ndarray + ) -> Tuple[np.ndarray, float, float, bool]: + """Normalize displacement magnitude, optionally with a fixed range.""" + mag_max_cfg = getattr(self.config, "deformed_mesh_disp_max", None) + mag_min_cfg = getattr(self.config, "deformed_mesh_disp_min", None) + use_fixed = mag_max_cfg is not None and mag_max_cfg > 0.0 + if use_fixed: + mag_min = 0.0 if mag_min_cfg is None else float(mag_min_cfg) + mag_max = float(mag_max_cfg) + if mag_max <= mag_min: + use_fixed = False + if not use_fixed: + mag_min = float(disp_mag.min()) + mag_max = float(disp_mag.max()) + denom = max(1e-12, mag_max - mag_min) + norm = (disp_mag - mag_min) / denom + if use_fixed: + norm = np.clip(norm, 0.0, 1.0) + return norm, mag_min, mag_max, use_fixed + + def _make_displacement_colors(self, displacement: np.ndarray) -> np.ndarray: + """Map displacement magnitude to vertex colors (blue -> red).""" + disp_mag = np.linalg.norm(displacement, axis=1) + norm, _, _, _ = self._normalize_displacement_magnitude(disp_mag) + colors = np.stack([norm, np.zeros_like(norm), 1.0 - norm], axis=1) + return (colors * 255).astype(np.uint8) + + def _log_physical_quantities( + self, + u: torch.Tensor, + sigma: Optional[torch.Tensor], + ) -> None: + """Log displacement and von Mises stress statistics.""" + with torch.no_grad(): + u_max = None + u_avg = None + try: + u_mag = torch.norm(u, dim=1) + u_max = u_mag.max().item() + u_avg = u_mag.mean().item() + except Exception as e: + logging.warning( + f" ⚠️ displacement statistics failed: {type(e).__name__}: {str(e)[:100]}" + ) + + sigma_vm_max = None + sigma_vm_avg = None + if sigma is not None: + try: + if sigma.dim() == 2 and sigma.shape[1] >= 6: + s_xx = sigma[:, 0] + s_yy = sigma[:, 1] + s_zz = sigma[:, 2] + s_yz = sigma[:, 3] + s_xz = sigma[:, 4] + s_xy = sigma[:, 5] + mises_sq = 0.5 * ( + (s_xx - s_yy) ** 2 + + (s_yy - s_zz) ** 2 + + (s_zz - s_xx) ** 2 + + 6.0 * (s_xy ** 2 + s_yz ** 2 + s_xz ** 2) + ) + mises = torch.sqrt(torch.clamp(mises_sq, min=0.0)) + sigma_vm_max = mises.max().item() + sigma_vm_avg = mises.mean().item() + else: + logging.warning( + f" ⚠️ sigmashape does not match expectations, skip von Mises statistics: {tuple(sigma.shape)}" + ) + except Exception as e: + logging.warning( + f" ⚠️ von Mises statistics failed: {type(e).__name__}: {str(e)[:100]}" + ) + + if u_max is not None and u_avg is not None: + if sigma_vm_max is not None and sigma_vm_avg is not None: + logging.info( + f" physical metrics: u_max={u_max:.3e}, u_avg={u_avg:.3e}, " + f"sigma_vm_max={sigma_vm_max:.3e}, sigma_vm_avg={sigma_vm_avg:.3e}" + ) + else: + logging.info( + f" physical metrics: u_max={u_max:.3e}, u_avg={u_avg:.3e}" + ) + + def backward_step(self, sensitivity_density: torch.Tensor): + """Backpropagate with VJP, aligned with the reference code. + + Reference: viewer_deepsdf.py Line 148-183. + This uses torch.autograd.functional.vjp to propagate sensitivity to latents. + """ + def f(latents: torch.Tensor): + """ + Compute occupancy from a given latent tensor. + Aligned with viewer_deepsdf.py Line 155-173. + """ + # Query the SDF. + sdf = self.get_field(self.nodes, latents) + + # SDF → occupancy + from physiopt.opt.field import occ_kernel + occ = occ_kernel(sdf, self.config.res, self.config.occ_sdf_beta) + + # Element occupancy is the average over the 8 nodes. + occ_elem = occ[self.elements].mean(1) + + # Clamp by alpha_min if requested. + if self.config.alpha_min > 0.0: + occ_elem = torch.clamp(occ_elem, self.config.alpha_min) + + return occ_elem + + # VJP computations d occ / d latents^T times the sensitivity vector. + # Aligned with viewer_deepsdf.py Line 175-180. + try: + grad_latent = torch.autograd.functional.vjp( + f, + self.latents.clone().requires_grad_(True), + sensitivity_density, + )[1] + + # Validate the returned gradient. + if grad_latent is None: + logging.error(" ❌ VJP returned None!") + return + + grad_norm = torch.norm(grad_latent).item() + logging.info(f" VJP gradient: norm={grad_norm:.2e}") + + # Assign the gradient manually, matching the reference implementation. + self.latents.grad = grad_latent + + except Exception as e: + logging.error(f" ❌ VJP failed: {e}") + import traceback + traceback.print_exc() + + def prepare_physical_simulation(self): + """Prepare the physical simulation and FEM solver state. + + Initialization includes: + 1. Material properties + 2. Boundary conditions + 3. External forces + """ + if not WARP_AVAILABLE: + logging.warning("Warpnot installed, skipphysics simulation preparation") + return + + if not hasattr(self, 'nodes') or not hasattr(self, 'elements'): + logging.error("please call extract_solid() to extract the solid first") + return + + logging.info("prepare physical simulation...") + + # Initialize Warp. + wp.init() + + # Normalize device names such as "cuda" and "cuda:0". + if 'cuda' in self.device: + # Extract the device id when needed. + if ':' in self.device: + device_id = self.device.split(':')[-1] + warp_device = f"cuda:{device_id}" + else: + warp_device = "cuda:0" # default to cuda:0 + else: + warp_device = "cpu" + + wp.set_device(warp_device) + logging.info(f"Warpdevice: {warp_device}") + + # Material properties. + self.E = self.config.youngs_modulus # Young's modulus. + self.nu = self.config.poissons_ratio # Poisson's ratio. + self.rho = self.config.density # Density. + + # Boundary condition: fix bottom nodes using Hunyuan's Y-up frame. + y_coords = self.nodes[:, 1] + y_min = y_coords.min() + boundary_threshold = y_min + 0.05 # 0.2 # 0.05 # Bottom 5% band. + self.boundary_mask = y_coords < boundary_threshold + + logging.info(f" coordinate system: Y-up (Hunyuan-native), fix Y < {boundary_threshold:.3f}nodes") + + # Apply load locally instead of spreading it across all nodes. + # The default heuristic targets a seat-like region in the Y-up frame. + + # Compute the total force, giving priority to force_entries. + total_force = np.zeros(3, dtype=np.float32) + force_entries = getattr(self.config, "force_entries", None) + valid_force_entries = None + if force_entries: + valid_force_entries = [] + for entry in force_entries: + if not isinstance(entry, dict): + continue + entry_force = None + if "force" in entry: + try: + entry_force = np.array(entry["force"], dtype=np.float32) + except Exception: + entry_force = None + elif "forces" in entry and isinstance(entry["forces"], list): + try: + entry_force = np.sum( + np.array(entry["forces"], dtype=np.float32), axis=0 + ) + except Exception: + entry_force = None + if entry_force is None or entry_force.shape != (3,): + continue + valid_force_entries.append(entry) + total_force += entry_force + if valid_force_entries: + self.force_entries_preset = valid_force_entries + logging.info(f" force entries: {len(valid_force_entries)}") + else: + logging.warning(" ⚠️ force_entries has no valid entries, fallback to forces") + valid_force_entries = None + + if valid_force_entries is None: + for force_config in self.config.forces: + if hasattr(force_config, 'get_total_force'): + # ForceConfig object. + total_force += force_config.get_total_force() + elif isinstance(force_config, dict) and 'external_force' in force_config: + # Compatibility format using a plain dict. + total_force += np.array(force_config['external_force'], dtype=np.float32) + else: + logging.warning(f"unknown force format: {type(force_config)}") + + logging.info(f" sum of external forces (Y-up coordinates): {total_force}") + + # Choose the loading strategy from the config. + if valid_force_entries is not None: + # Multiple localized loads, each with its own region. + self._setup_local_loading(total_force) + elif self.config.use_local_loading: + # Preferred mode: local loading. + self._setup_local_loading(total_force) + else: + # Fallback mode: global uniform loading. + logging.info(f" ℹ️ using global uniform loading mode") + total_force_tensor = torch.from_numpy(total_force).float().to(self.device) + num_nodes = self.nodes.shape[0] + self.forces = total_force_tensor[None, :].repeat(num_nodes, 1) + logging.info(f" 💨 distributed the total force uniformly to{num_nodes}nodes") + + logging.info(f"boundary conditions: {self.boundary_mask.sum().item()}fixed nodes") + logging.info(f"material properties: E={self.E:.2e}, ν={self.nu}, ρ={self.rho}") + + def _setup_local_loading(self, total_force: np.ndarray): + """Set up local loading on the selected seat/contact region. + + The total force is distributed uniformly across the selected nodes so + that sum(forces) equals total_force. + + Args: + total_force: Total force vector [3] in the Y-up frame, in Newtons. + """ + # Cache the total force for later updates. + self.total_force_preset = torch.from_numpy(total_force).float().to(self.device) + + # Reuse the generic update routine for the initial setup. + self._update_forces(initial_setup=True) + + def _update_forces(self, initial_setup: bool = False): + """Update the force distribution for the current mesh state. + + Core logic: + 1. Re-identify contact nodes + 2. Spread the preset total force uniformly over those nodes + 3. Keep total force conserved + + Args: + initial_setup: Whether this is the first setup pass. + """ + if not hasattr(self, 'total_force_preset'): + logging.warning("No preset total force is set, so the force distribution cannot be updated") + return + + # Step 1: inspect the Y-coordinate distribution. + y_coords = self.nodes[:, 1] + num_nodes = self.nodes.shape[0] + + force_entries = getattr(self, "force_entries_preset", None) + if force_entries: + def _select_nodes_for_mode(mode, top_percent, min_ratio, max_ratio, bbox, bbox_ratio): + seat_mask = torch.zeros(num_nodes, dtype=torch.bool, device=self.device) + mode_used = mode + bbox_desc = None + + if mode_used not in ("top_percent", "height_ratio", "bbox", "global"): + logging.warning(f" ⚠️ invalid force_region_mode: {mode_used}, fallback to top_percent") + mode_used = "top_percent" + + if mode_used == "global": + seat_mask[:] = True + return seat_mask, mode_used, bbox_desc + + if mode_used == "bbox": + bbox_vals = None + if bbox is not None and len(bbox) == 6: + bbox_vals = [float(v) for v in bbox] + bbox_desc = "abs" + elif bbox_ratio is not None and len(bbox_ratio) == 6: + bbox_ratio_vals = [float(v) for v in bbox_ratio] + bounds_min = self.nodes.min(dim=0).values + bounds_max = self.nodes.max(dim=0).values + bbox_vals = [ + bounds_min[0].item() + bbox_ratio_vals[0] * (bounds_max[0] - bounds_min[0]).item(), + bounds_min[0].item() + bbox_ratio_vals[1] * (bounds_max[0] - bounds_min[0]).item(), + bounds_min[1].item() + bbox_ratio_vals[2] * (bounds_max[1] - bounds_min[1]).item(), + bounds_min[1].item() + bbox_ratio_vals[3] * (bounds_max[1] - bounds_min[1]).item(), + bounds_min[2].item() + bbox_ratio_vals[4] * (bounds_max[2] - bounds_min[2]).item(), + bounds_min[2].item() + bbox_ratio_vals[5] * (bounds_max[2] - bounds_min[2]).item(), + ] + bbox_desc = "ratio" + else: + logging.warning(" ⚠️ bbox mode did not provide a valid bbox, fallback to top_percent") + mode_used = "top_percent" + + if mode_used == "bbox" and bbox_vals is not None: + x0, x1 = sorted([bbox_vals[0], bbox_vals[1]]) + y0, y1 = sorted([bbox_vals[2], bbox_vals[3]]) + z0, z1 = sorted([bbox_vals[4], bbox_vals[5]]) + seat_mask = ( + (self.nodes[:, 0] >= x0) & (self.nodes[:, 0] <= x1) + & (self.nodes[:, 1] >= y0) & (self.nodes[:, 1] <= y1) + & (self.nodes[:, 2] >= z0) & (self.nodes[:, 2] <= z1) + ) + if seat_mask.sum().item() < 1: + logging.warning(" ⚠️ bbox region matched no nodes, fallback to top_percent") + mode_used = "top_percent" + else: + bbox_desc = f"{bbox_desc}: [{x0:.3f},{x1:.3f}]x[{y0:.3f},{y1:.3f}]x[{z0:.3f},{z1:.3f}]" + + if mode_used == "height_ratio": + y_min = y_coords.min().item() + y_max = y_coords.max().item() + y_range = max(1e-8, y_max - y_min) + if not (0.0 <= min_ratio < max_ratio <= 1.0): + logging.warning( + f" ⚠️ invalid height_ratio: min={min_ratio}, max={max_ratio}, fallback to top_percent" + ) + mode_used = "top_percent" + else: + seat_y_min = y_min + y_range * min_ratio + seat_y_max = y_min + y_range * max_ratio + seat_mask = (y_coords >= seat_y_min) & (y_coords <= seat_y_max) + if seat_mask.sum().item() < 1: + logging.warning(" ⚠️ height_ratio matched no nodes, fallback to top_percent") + mode_used = "top_percent" + + if mode_used == "top_percent": + top_percent = float(top_percent) + top_percent = max(0.0, min(1.0, top_percent)) + if top_percent <= 0.0: + top_percent = 0.05 + num_seat_nodes = max(1, int(num_nodes * top_percent)) + _, top_indices = torch.topk(y_coords, k=num_seat_nodes, largest=True) + seat_mask = torch.zeros(num_nodes, dtype=torch.bool, device=self.device) + seat_mask[top_indices] = True + + return seat_mask, mode_used, bbox_desc + + self.forces = torch.zeros((num_nodes, 3), dtype=torch.float32, device=self.device) + combined_mask = torch.zeros(num_nodes, dtype=torch.bool, device=self.device) + total_force = torch.zeros(3, dtype=torch.float32, device=self.device) + + for idx, entry in enumerate(force_entries): + if not isinstance(entry, dict): + continue + entry_label = entry.get("label") or entry.get("name") or f"{idx+1}" + entry_force = None + if "forces" in entry and isinstance(entry["forces"], list): + try: + entry_force = np.sum(np.array(entry["forces"], dtype=np.float32), axis=0) + except Exception: + entry_force = None + if entry_force is None and "force" in entry: + try: + entry_force = np.array(entry["force"], dtype=np.float32) + except Exception: + entry_force = None + if entry_force is None or entry_force.shape != (3,): + logging.warning(f" ⚠️ invalid force entry[{entry_label}], skip") + continue + + entry_force_tensor = torch.from_numpy(entry_force).float().to(self.device) + total_force += entry_force_tensor + + mode = str(entry.get("force_region_mode", self.config.force_region_mode)).lower() + if entry.get("global_loading") is True: + mode = "global" + + top_percent = entry.get("force_top_percent", self.config.force_top_percent) + min_ratio = entry.get("seat_height_min_ratio", self.config.seat_height_min_ratio) + max_ratio = entry.get("seat_height_max_ratio", self.config.seat_height_max_ratio) + bbox = entry.get("force_bbox", self.config.force_bbox) + bbox_ratio = entry.get("force_bbox_ratio", self.config.force_bbox_ratio) + + seat_nodes_mask, mode_used, bbox_desc = _select_nodes_for_mode( + mode, top_percent, min_ratio, max_ratio, bbox, bbox_ratio + ) + + num_seat_nodes = int(seat_nodes_mask.sum().item()) + if num_seat_nodes < 1: + logging.warning(f" ⚠️ entry[{entry_label}]matched no nodes, skip") + continue + + force_per_node = entry_force_tensor / num_seat_nodes + self.forces[seat_nodes_mask] += force_per_node + combined_mask |= seat_nodes_mask + + seat_y_values = y_coords[seat_nodes_mask] + seat_y_min = seat_y_values.min().item() + seat_y_max = seat_y_values.max().item() + seat_y_mean = seat_y_values.mean().item() + + if initial_setup: + if mode_used == "bbox": + logging.info(f" 🪑 contact surface[{entry_label}]: bbox ({bbox_desc})") + elif mode_used == "height_ratio": + logging.info( + f" 🪑 contact surface[{entry_label}]: height_ratio " + f"[{min_ratio:.2f}, {max_ratio:.2f}]" + ) + elif mode_used == "global": + logging.info(f" 🪑 contact surface[{entry_label}]: global") + else: + logging.info( + f" 🪑 contact surface[{entry_label}]: highest-Y {float(top_percent):.1%} nodes" + ) + logging.info( + f" 🪑 seat-node count[{entry_label}]: {num_seat_nodes}/{num_nodes} " + f"({num_seat_nodes/num_nodes:.1%})" + ) + logging.info( + f" 🪑 Y range[{entry_label}]: [{seat_y_min:.3f}, {seat_y_max:.3f}], " + f"mean: {seat_y_mean:.3f}" + ) + logging.info(f" 💺 force[{entry_label}]: {entry_force}") + logging.info(f" 💺 per node[{entry_label}]: {force_per_node.cpu().numpy()}") + + self.total_force_preset = total_force + actual_total_force = self.forces.sum(dim=0) + force_error = torch.norm(actual_total_force - total_force).item() + force_error_percent = (force_error / (torch.norm(total_force).item() + 1e-10)) * 100 + + if initial_setup: + logging.info( + f" ✅ total-force check: {actual_total_force.cpu().numpy()} " + f"(error: {force_error:.2e}, {force_error_percent:.3f}%)" + ) + if combined_mask.any(): + self._save_force_visualization( + combined_mask, total_force.cpu().numpy() + ) + else: + logging.debug( + f" 🔄 force update: loaded nodes {int(combined_mask.sum().item())}, " + f"total force error {force_error:.2e}" + ) + + self._last_num_seat_nodes = int(combined_mask.sum().item()) + return + + # Contact-region selection supports top_percent / height_ratio / bbox. + mode = str(getattr(self.config, "force_region_mode", "top_percent")).lower() + seat_nodes_mask = torch.zeros(num_nodes, dtype=torch.bool, device=self.device) + mode_used = mode + bbox_desc = None + if mode_used not in ("top_percent", "height_ratio", "bbox"): + logging.warning(f" ⚠️ invalid force_region_mode: {mode_used}, fallback to top_percent") + mode_used = "top_percent" + + if mode_used == "bbox": + bbox = getattr(self.config, "force_bbox", None) + bbox_ratio = getattr(self.config, "force_bbox_ratio", None) + bbox_vals = None + if bbox is not None and len(bbox) == 6: + bbox_vals = [float(v) for v in bbox] + bbox_desc = "abs" + elif bbox_ratio is not None and len(bbox_ratio) == 6: + bbox_ratio_vals = [float(v) for v in bbox_ratio] + bounds_min = self.nodes.min(dim=0).values + bounds_max = self.nodes.max(dim=0).values + bbox_vals = [ + bounds_min[0].item() + bbox_ratio_vals[0] * (bounds_max[0] - bounds_min[0]).item(), + bounds_min[0].item() + bbox_ratio_vals[1] * (bounds_max[0] - bounds_min[0]).item(), + bounds_min[1].item() + bbox_ratio_vals[2] * (bounds_max[1] - bounds_min[1]).item(), + bounds_min[1].item() + bbox_ratio_vals[3] * (bounds_max[1] - bounds_min[1]).item(), + bounds_min[2].item() + bbox_ratio_vals[4] * (bounds_max[2] - bounds_min[2]).item(), + bounds_min[2].item() + bbox_ratio_vals[5] * (bounds_max[2] - bounds_min[2]).item(), + ] + bbox_desc = "ratio" + else: + logging.warning(" ⚠️ bbox mode did not provide a valid bbox, fallback to top_percent") + mode_used = "top_percent" + + if mode_used == "bbox" and bbox_vals is not None: + x0, x1 = sorted([bbox_vals[0], bbox_vals[1]]) + y0, y1 = sorted([bbox_vals[2], bbox_vals[3]]) + z0, z1 = sorted([bbox_vals[4], bbox_vals[5]]) + seat_nodes_mask = ( + (self.nodes[:, 0] >= x0) & (self.nodes[:, 0] <= x1) + & (self.nodes[:, 1] >= y0) & (self.nodes[:, 1] <= y1) + & (self.nodes[:, 2] >= z0) & (self.nodes[:, 2] <= z1) + ) + if seat_nodes_mask.sum().item() < 1: + logging.warning(" ⚠️ bbox region matched no nodes, fallback to top_percent") + mode_used = "top_percent" + else: + bbox_desc = f"{bbox_desc}: [{x0:.3f},{x1:.3f}]x[{y0:.3f},{y1:.3f}]x[{z0:.3f},{z1:.3f}]" + + if mode_used == "height_ratio": + y_min = y_coords.min().item() + y_max = y_coords.max().item() + y_range = max(1e-8, y_max - y_min) + min_ratio = float(self.config.seat_height_min_ratio) + max_ratio = float(self.config.seat_height_max_ratio) + if not (0.0 <= min_ratio < max_ratio <= 1.0): + logging.warning( + f" ⚠️ invalid height_ratio: min={min_ratio}, max={max_ratio}, fallback to top_percent" + ) + mode_used = "top_percent" + else: + seat_y_min = y_min + y_range * min_ratio + seat_y_max = y_min + y_range * max_ratio + seat_nodes_mask = (y_coords >= seat_y_min) & (y_coords <= seat_y_max) + if seat_nodes_mask.sum().item() < 1: + logging.warning(" ⚠️ height_ratio matched no nodes, fallback to top_percent") + mode_used = "top_percent" + + if mode_used == "top_percent": + top_percent = float(getattr(self.config, "force_top_percent", 0.05)) + top_percent = max(0.0, min(1.0, top_percent)) + if top_percent <= 0.0: + top_percent = 0.05 + num_seat_nodes = max(1, int(num_nodes * top_percent)) + _, top_indices = torch.topk(y_coords, k=num_seat_nodes, largest=True) + seat_nodes_mask = torch.zeros(num_nodes, dtype=torch.bool, device=self.device) + seat_nodes_mask[top_indices] = True + + num_seat_nodes = int(seat_nodes_mask.sum().item()) + + # Step 3: gather region statistics. + seat_y_values = y_coords[seat_nodes_mask] + seat_y_min = seat_y_values.min().item() + seat_y_max = seat_y_values.max().item() + seat_y_mean = seat_y_values.mean().item() + + # Step 4: computation the per-node load with uniform distribution. + force_per_node = self.total_force_preset / num_seat_nodes + + # Initialize all node forces to zero. + self.forces = torch.zeros((num_nodes, 3), dtype=torch.float32, device=self.device) + + # Apply force only to the selected seat/contact nodes. + self.forces[seat_nodes_mask] = force_per_node + + # Step 5: verify total-force conservation. + actual_total_force = self.forces.sum(dim=0) + force_error = torch.norm(actual_total_force - self.total_force_preset).item() + force_error_percent = (force_error / torch.norm(self.total_force_preset).item()) * 100 + + # Logging. + if initial_setup: + if mode_used == "bbox": + logging.info(f" 🪑 contact-surface setup: bbox ({bbox_desc})") + elif mode_used == "height_ratio": + logging.info( + f" 🪑 contact-surface setup: height_ratio " + f"[{self.config.seat_height_min_ratio:.2f}, {self.config.seat_height_max_ratio:.2f}]" + ) + else: + logging.info( + f" 🪑 contact-surface setup: highest-Y {float(getattr(self.config, 'force_top_percent', 0.05)):.1%} nodes" + ) + logging.info(f" 🪑 seat-node count: {num_seat_nodes}/{num_nodes} ({num_seat_nodes/num_nodes:.1%})") + logging.info(f" 🪑 Y-coordinate range: [{seat_y_min:.3f}, {seat_y_max:.3f}], mean: {seat_y_mean:.3f}") + logging.info(f" 💺 preset total force: {self.total_force_preset.cpu().numpy()}") + logging.info(f" 💺 force per node: {force_per_node.cpu().numpy()}") + logging.info(f" ✅ total-force check: {actual_total_force.cpu().numpy()} (error: {force_error:.2e}, {force_error_percent:.3f}%)") + + # Estimate the equivalent pressure. + y_range = y_coords.max().item() - y_coords.min().item() + grid_spacing = y_range / self.config.res if y_range > 0 else 0.01 + estimated_area = num_seat_nodes * (grid_spacing ** 2) + if estimated_area > 0 and abs(self.total_force_preset[1].item()) > 0: + pressure_kpa = abs(self.total_force_preset[1].item()) / estimated_area / 1000 + logging.info(f" 📏 equivalent pressure: {pressure_kpa:.1f} kPa (contact area≈{estimated_area:.4f} m²)") + + if pressure_kpa < 5: + logging.warning(f" ⚠️ pressure is too small ({pressure_kpa:.1f} kPa < 5 kPa)") + elif pressure_kpa > 50: + logging.warning(f" ⚠️ pressure is too large ({pressure_kpa:.1f} kPa > 50 kPa)") + + # Save visualization data. + self._save_force_visualization(seat_nodes_mask, self.total_force_preset.cpu().numpy()) + else: + # Shorter logging during optimization. + logging.debug(f" 🔄 force update: seat nodes {num_seat_nodes}, per node {force_per_node.cpu().numpy()}, " + f"total force error {force_error:.2e}") + + # Watch for changes in the number of loaded nodes. + if hasattr(self, '_last_num_seat_nodes') and self._last_num_seat_nodes != num_seat_nodes: + logging.info(f" ⚠️ seat-node count changed: {self._last_num_seat_nodes} → {num_seat_nodes}") + + # Cache the current state for the next comparison. + self._last_num_seat_nodes = num_seat_nodes + + def extract_solid(self, step: int = -1): + """Extract the physical solid by querying the node SDF directly. + + This method rebuilds the FEM mesh from the current latents so topology + changes in the SDF field can be reflected by the simulation mesh. + + Args: + step: Current optimization step, used for logging. + """ + if not WARP_AVAILABLE: + logging.warning("Warpnot installed, unable toperformphysics simulation") + return + + # Re-check physiopt availability at runtime. + try: + from physiopt.utils.phys_utils import generate_hex as _generate_hex + from physiopt.utils.grid_utils import filter_one_component as _filter_one_component + from physiopt.opt.field import occ_kernel as _occ_kernel + generate_hex_func = _generate_hex + filter_one_component_func = _filter_one_component + occ_kernel_func = _occ_kernel + logging.info("✅ physioptmoduleruntime check succeeded") + except ImportError as e: + logging.error(f"physioptmodulenot installed: {e}") + logging.error("please make sure physiopt is installed correctly: cd /mnt/cvlab/scratch/cvlab/home/hantzhan/physiopt && pip install -e .") + return + + res = self.config.res + step_label = f"Step {step}" if step >= 0 else "Initialization" + logging.info(f"{'🔄' if step >= 0 else '🆕'} [{step_label}] generate/update a mesh at resolution {res} hexahedral mesh...") + + # Keep the previous mesh size for comparison. + old_num_nodes = len(self.nodes) if hasattr(self, 'nodes') else 0 + old_num_elements = len(self.elements) if hasattr(self, 'elements') else 0 + + # 1. Generate the full hexahedral grid. + full_nodes, full_elements = generate_hex_func( + res=res, + limits=[(-0.8, 0.8), (-0.8, 0.8), (-0.8, 0.8)], + device=self.device, + return_coords=False + ) + + if full_nodes is None or full_elements is None: + logging.error("failed to generate the hexahedral mesh") + return + + full_nodes = full_nodes.to(self.device).float() + full_elements = full_elements.to(self.device).long() + + logging.info(f"hexahedral mesh generated successfully: {full_nodes.shape[0]}nodes, {full_elements.shape[0]}elements") + + # 2. Query the SDF directly through get_field. + logging.info("query node SDF values...") + sdf = self.get_field(full_nodes) + + # Make sure the SDF is a 1D tensor [N]. + if sdf.dim() > 1: + logging.warning(f"⚠️ SDFYesmulti-dimensional tensor: {sdf.shape}, will be flattened to 1D") + sdf = sdf.squeeze() # remove all size-1 dimensions + if sdf.dim() > 1: + sdf = sdf.reshape(-1) # force-flatten to 1D + + logging.info(f" ✅ SDF query succeeded: range=[{sdf.min():.3f}, {sdf.max():.3f}]") + logging.info(f" nodescount: {full_nodes.shape[0]}, SDF count: {sdf.shape[0]}") + + # Verify that the SDF count matches the node count. + if sdf.shape[0] != full_nodes.shape[0]: + logging.error(f"❌ SDF count({sdf.shape[0]}) vs. node count ({full_nodes.shape[0]})do not match!") + return + + # 3. Convert SDF values to occupancy. + logging.info("convert the SDF into an occupancy field...") + occ = occ_kernel_func(sdf, res, self.config.occ_sdf_beta) + + # 4. Select solid elements using an SDF threshold instead of an + # occupancy threshold. The threshold is intentionally relaxed so thin + # structures such as chair legs are kept. + SDF_FILTER_VALUE = 2.0 / res + nodewise_mask = sdf <= SDF_FILTER_VALUE + + # Diagnostic SDF statistics. + sdf_inside = sdf[nodewise_mask] + sdf_outside = sdf[~nodewise_mask] + logging.info(f" SDF threshold: {SDF_FILTER_VALUE:.4f}") + logging.info(f" interior nodes: {nodewise_mask.sum().item()}/{len(sdf)} ({100*nodewise_mask.sum().item()/len(sdf):.1f}%)") + if len(sdf_inside) > 0: + logging.info(f" inner SDF range: [{sdf_inside.min():.4f}, {sdf_inside.max():.4f}]") + if len(sdf_outside) > 0: + logging.info(f" outside-SDF range: [{sdf_outside.min():.4f}, {sdf_outside.max():.4f}]") + + # Debug the element-index range. + max_elem_idx = full_elements.max().item() + num_nodes = full_nodes.shape[0] + logging.info(f" elementsindex range: [0, {max_elem_idx}], nodescount: {num_nodes}") + + if max_elem_idx >= num_nodes: + logging.error(f"❌ index out of bounds!maximum element index({max_elem_idx}) >= nodescount({num_nodes})") + logging.error(f" this may be a problem with generate_hex") + # Clamp indices to the valid range. + valid_mask = (full_elements >= 0) & (full_elements < num_nodes) + if not valid_mask.all(): + logging.warning(f" found{(~valid_mask).sum().item()} invalid indices; filtering elements") + # Keep only elements whose node indices are all valid. + valid_elements_mask = valid_mask.all(dim=1) + full_elements = full_elements[valid_elements_mask] + logging.info(f" element count after filtering: {full_elements.shape[0]}") + + # Keep an element if any of its nodes passes the threshold. + elementwise_mask = torch.any(nodewise_mask[full_elements], dim=1) + + num_solid_elements = elementwise_mask.sum().item() + logging.info(f"SDF thresholdfiltering: {num_solid_elements}/{len(elementwise_mask)} solid elements") + + if num_solid_elements == 0: + logging.error("No solid elements were found; please check the SDF or adjust the threshold") + return + + # 5. Optionally keep only one connected component. + if self.config.one_cc_only: + element_res = res - 1 + try: + num_before_filter = elementwise_mask.sum().item() + elementwise_mask = filter_one_component_func(elementwise_mask, element_res) + num_filtered_elements = elementwise_mask.sum().item() + num_removed = num_before_filter - num_filtered_elements + logging.info(f"connectivity filtering: {num_filtered_elements} elements kept (removed{num_removed} small components)") + if num_removed > num_filtered_elements * 0.1: + logging.warning(f" ⚠️ removed{num_removed}elements({100*num_removed/num_before_filter:.1f}%), may have filtered out important parts (such as chair legs) ") + logging.warning(f" Suggestion: check the SDF threshold or consider disabling one_cc_only") + except IndexError as e: + logging.warning(f"connectivity filteringfailed: {e}, using the original mask") + else: + logging.info("connectivity filteringdisabled, keep all connected components") + + # 6. Select the active elements and nodes. + selected_elements = full_elements[elementwise_mask] + selected_node_indices, selected_elements = torch.unique( + selected_elements, return_inverse=True + ) + + self.elements = selected_elements + self.nodes = full_nodes[selected_node_indices] + + # 7. Compute occupancy for the selected nodes used in the simulation. + coarse_sdf = sdf[selected_node_indices] + coarse_occ_nodes = occ_kernel_func( + coarse_sdf, self.config.res, self.config.occ_sdf_beta + ) + # Each element occupancy is the mean over its 8 nodes. + self.coarse_occ = coarse_occ_nodes[self.elements].mean(1) + + # Diagnostic statistics for mesh-size changes. + new_num_nodes = len(self.nodes) + new_num_elements = len(self.elements) + + if old_num_nodes > 0: + node_change = new_num_nodes - old_num_nodes + element_change = new_num_elements - old_num_elements + node_change_pct = (node_change / old_num_nodes) * 100 + element_change_pct = (element_change / old_num_elements) * 100 + + logging.info(f"✅ solid extraction completed:") + logging.info(f" nodes: {old_num_nodes} → {new_num_nodes} ({node_change:+d}, {node_change_pct:+.1f}%)") + logging.info(f" elements: {old_num_elements} → {new_num_elements} ({element_change:+d}, {element_change_pct:+.1f}%)") + + if node_change > 0: + logging.info(f" ✅ mesh expanded!added{node_change}nodes (chair legs may have thickened) ") + elif node_change < 0: + logging.warning(f" ⚠️ mesh shrank!removed{-node_change}nodes (chair legs may have become thinner) ") + else: + logging.info(f"✅ solid extraction succeeded: {new_num_nodes}nodes, {new_num_elements}elements") + + # 8. Recomputation the boundary mask because the node count may change. + y_coords = self.nodes[:, 1] + y_min = y_coords.min() + boundary_threshold = y_min + 0.05 # bottom 5% region + self.boundary_mask = y_coords < boundary_threshold + + num_boundary = self.boundary_mask.sum().item() + logging.debug(f" 🔧 boundary conditionsupdated: {num_boundary}fixed nodes (Y < {boundary_threshold:.3f})") + + def get_current_sds_weight(self, step: int) -> float: + """Return the current SDS weight by linear interpolation. + + Args: + step: Current optimization step. + + Returns: + The SDS weight interpolated from sds_weight_start to sds_weight_end. + """ + # Linear interpolation from sds_weight_start to sds_weight_end. + progress = min(1.0, step / max(1, self.config.num_steps - 1)) + current_weight = self.config.sds_weight_start + progress * (self.config.sds_weight_end - self.config.sds_weight_start) + return current_weight + + def _computation_target_z0_current(self, step: int) -> Tuple[torch.Tensor, torch.Tensor]: + """Compute the current target_z0 for one update.""" + noise_level = float(self.config.sds_timestep) + t = 1.0 - noise_level # Hunyuan3D-2.1 uses t=0 for noise and t=1 for data. + epsilon = torch.randn_like(self.latents) + + self.sds_scheduler.config.num_train_timesteps = 100 + if self.sds_scheduler is not None: + # Match the official Flow Matching noise process: + # x_t = (1 - sigma) * x0 + sigma * eps. + sigma_step = 1.0 / float(self.sds_scheduler.config.num_train_timesteps) + total_span = max(0.0, 1.0 - t) + num_steps = int(np.ceil(total_span / sigma_step)) + sigmas = np.linspace(t, 1.0, num_steps + 1, dtype=np.float32) + self.sds_scheduler.set_timesteps(sigmas=sigmas, device=self.device) + t_scheds = self.sds_scheduler.timesteps + t_sched0 = t_scheds[0] + t_model0 = (t_sched0 / self.sds_scheduler.config.num_train_timesteps).to(self.latents.dtype) + if step % max(1, int(self.config.sds_target_z0_update_interval)) == 0: + logging.info( + f" 🎯 target_z0/sigmaalign: noise={noise_level:.4f}, t_start={t:.4f}, " + f"t_sched={t_sched0.item():.2f}, t_model={t_model0.item():.6f}, " + f"steps={num_steps}, sigma_step={sigma_step:.4g}" + ) + else: + t_sched = None + z_t = (1 - t) * epsilon + t * self.latents + t_model = torch.tensor([t], device=self.device, dtype=self.latents.dtype) + + with torch.no_grad(): + if self.sds_scheduler is not None: + # Integrate over multiple small sigma steps from sigma=t to 0. + cond_for_model = self._get_cond_for_guidance(self.config.guidance_scale > 1.0) + t_sched0 = t_scheds[0] + t_sched_batch = t_sched0.reshape(1).expand(self.latents.shape[0]) + # Hunyuan3D convention: t=0 is noise and t=1 is data. + z_t = self.sds_scheduler.scale_noise(epsilon, t_sched_batch, noise=self.latents) + + z_curr = z_t + velocity = None + for i in range(len(t_scheds) - 1): + t_sched = t_scheds[i] + t_model = (t_sched / self.sds_scheduler.config.num_train_timesteps).to(self.latents.dtype) + z_t_fp16 = z_curr.to(torch.float16) + t_tensor = t_model.to(device=self.device, dtype=z_t_fp16.dtype) + + if self.config.guidance_scale > 1.0: + latent_model_input = torch.cat([z_t_fp16, z_t_fp16]) + timestep_input = t_tensor.expand(latent_model_input.shape[0]) + + velocity_pred_fp16 = self.flow_model( + latent_model_input, + timestep_input, + cond_for_model, + guidance=None, + ) + + velocity_cond_fp16, velocity_uncond_fp16 = velocity_pred_fp16.chunk(2) + velocity_fp16 = velocity_uncond_fp16 + self.config.guidance_scale * (velocity_cond_fp16 - velocity_uncond_fp16) + + if step % 10 == 0 and i == 0: + logging.debug( + f" CFG (SDS): guidance_scale={self.config.guidance_scale:.1f}, " + f"||v_cond||={torch.norm(velocity_cond_fp16).item():.3e}, " + f"||v_uncond||={torch.norm(velocity_uncond_fp16).item():.3e}" + ) + else: + velocity_fp16 = self.flow_model( + z_t_fp16, + t_tensor.expand(z_t_fp16.shape[0]), + cond_for_model, + guidance=None, + ) + + velocity = velocity_fp16.to(torch.float32) + z_curr = self.sds_scheduler.step(velocity, t_sched, z_curr).prev_sample + + target_z0_current = z_curr + else: + cond_for_model = self._get_cond_for_guidance(self.config.guidance_scale > 1.0) + z_t_fp16 = z_t.to(torch.float16) + t_tensor = t_model.to(device=self.device, dtype=z_t_fp16.dtype) + + if self.config.guidance_scale > 1.0: + latent_model_input = torch.cat([z_t_fp16, z_t_fp16]) + timestep_input = t_tensor.expand(latent_model_input.shape[0]) + + velocity_pred_fp16 = self.flow_model( + latent_model_input, + timestep_input, + cond_for_model, + guidance=None, + ) + + velocity_cond_fp16, velocity_uncond_fp16 = velocity_pred_fp16.chunk(2) + velocity_fp16 = velocity_uncond_fp16 + self.config.guidance_scale * (velocity_cond_fp16 - velocity_uncond_fp16) + + if step % 10 == 0: + logging.debug( + f" CFG (SDS): guidance_scale={self.config.guidance_scale:.1f}, " + f"||v_cond||={torch.norm(velocity_cond_fp16).item():.3e}, " + f"||v_uncond||={torch.norm(velocity_uncond_fp16).item():.3e}" + ) + else: + velocity_fp16 = self.flow_model( + z_t_fp16, + t_tensor.expand(z_t_fp16.shape[0]), + cond_for_model, + guidance=None, + ) + + velocity = velocity_fp16.to(torch.float32) + # Fallback: one forward-Euler step to t=1. + target_z0_current = z_t + (1.0 - t) * velocity + + # Optional trust region to keep target_z0 from moving too far away. + max_rel = float(getattr(self.config, "sds_projection_max_rel", 0.0)) + if max_rel > 0.0: + with torch.no_grad(): + diff = target_z0_current - self.latents + diff_norm = torch.norm(diff).item() + latents_norm = torch.norm(self.latents).item() + max_norm = max_rel * (latents_norm + 1e-8) + if diff_norm > max_norm and max_norm > 0.0: + scale = max_norm / (diff_norm + 1e-8) + target_z0_current = self.latents + diff * scale + if step % max(1, int(self.config.sds_target_z0_update_interval)) == 0: + logging.info( + f" 🧱 target_z0 projection limit: diff={diff_norm:.3e} → {max_norm:.3e} " + f"(rel={max_rel:.2f})" + ) + return target_z0_current, velocity + + def _get_target_z0(self, step: int) -> Tuple[torch.Tensor, Optional[torch.Tensor], bool]: + """Update target_z0 on schedule and smooth it with EMA.""" + update_interval = max(1, int(self.config.sds_target_z0_update_interval)) + do_update = self.target_z0_ema is None or step % update_interval == 0 + + if do_update: + target_z0_current, velocity = self._computation_target_z0_current(step) + target_z0_current = target_z0_current.detach() + + if self.target_z0_ema is None: + self.target_z0_ema = target_z0_current.clone() + diff_norm = 0.0 + else: + diff = target_z0_current - self.target_z0_ema + diff_norm = torch.norm(diff).item() + alpha = 1.0 - self.config.sds_target_z0_ema_beta + self.target_z0_ema = self.target_z0_ema + alpha * diff + + self.target_z0_last_velocity = velocity + self.target_z0_last_update = step + + if step % update_interval == 0: + logging.info( + f" 🧭 target_z0 EMAupdate: interval={update_interval}, " + f"beta={self.config.sds_target_z0_ema_beta:.2f}, diff_norm={diff_norm:.3e}" + ) + else: + velocity = self.target_z0_last_velocity + + return self.target_z0_ema, velocity, do_update + + def project_to_manifold(self, step: int) -> bool: + """Project the current latents back to the manifold by replacing them with target_z0.""" + with torch.no_grad(): + target_z0, _ = self._computation_target_z0_current(step) + if torch.isnan(target_z0).any() or torch.isinf(target_z0).any(): + logging.warning(" ⚠️ projection failed: target_z0 contains NaN/Inf") + return False + deviation = torch.norm(target_z0 - self.latents).item() + latents_norm = torch.norm(self.latents).item() + rel = deviation / (latents_norm + 1e-8) + logging.info(f" 🧭 projection deviation: {deviation:.3e} (rel={rel:.2%})") + self.latents.data.copy_(target_z0) + if self.latents.grad is not None: + self.latents.grad.zero_() + # Reset optimizer state to avoid stale momentum. + self.optimizer.state.clear() + # Sync the EMA cache with the projected state. + self.target_z0_ema = target_z0.detach().clone() + self.target_z0_last_velocity = None + self.target_z0_last_update = step + return True + + def training_step_sds(self, step: int) -> Tuple[float]: + """Run one SDS optimization step. + + Returns: + (recon_loss,) + """ + self.optimizer.zero_grad() + + # ==================== SDS loss (Rectified Flow) ==================== + t = self.config.sds_timestep + target_z0, velocity, _ = self._get_target_z0(step) + + # SDS gradient: grad = z_0 - target_z0. + # This pulls the current z_0 (self.latents) toward target_z0. + sds_gradient = self.latents - target_z0.detach() + recon_loss = torch.mean(sds_gradient ** 2) / 2 + + # Debug information. + with torch.no_grad(): + target_norm = torch.norm(target_z0).item() + current_norm = torch.norm(self.latents).item() + grad_norm = torch.norm(sds_gradient).item() + velocity_norm = torch.norm(velocity).item() if velocity is not None else 0.0 + + logging.info(f"📐 Step {step:3d} | SDS: ||z_0||={current_norm:.2e}, " + f"||target_z_0||={target_norm:.2e}, " + f"||v||={velocity_norm:.2e}, " + f"||∇||={grad_norm:.2e}, t={t:.2f}, loss={recon_loss.item():.6e}") + + # Backpropagation. + sds_gradient_scaled = self.config.sds_weight * sds_gradient + + # Guard against invalid gradients. + if torch.isnan(sds_gradient_scaled).any() or torch.isinf(sds_gradient_scaled).any(): + logging.error(f"❌ Error: SDS gradient contains NaN or Inf!") + logging.error(f" ||sds_gradient||: {grad_norm:.2e}") + logging.error(f" sds_weight: {self.config.sds_weight}") + logging.error(f" target_z0 range: [{target_z0.min().item():.2e}, {target_z0.max().item():.2e}]") + logging.error(f" latents range: [{self.latents.min().item():.2e}, {self.latents.max().item():.2e}]") + if velocity is not None: + logging.error(f" velocity range: [{velocity.min().item():.2e}, {velocity.max().item():.2e}]") + return (recon_loss.item(),) + + if self.latents.grad is not None: + self.latents.grad.zero_() + + self.latents.grad = sds_gradient_scaled + + # Optional gradient clipping. + if self.config.grad_clip_enabled: + grad_norm_total = torch.norm(self.latents.grad).item() + max_grad_norm = 100.0 # 1e5lower to100 + if grad_norm_total > max_grad_norm: + clip_factor = max_grad_norm / grad_norm_total + self.latents.grad *= clip_factor + logging.warning(f"⚠️ gradient clipping: {grad_norm_total:.4e} -> {max_grad_norm:.4e}") + + # Save the pre-update latents for diagnostics. + old_latents = self.latents.data.clone() + + # Re-check the gradient before the optimizer step. + if torch.isnan(self.latents.grad).any(): + logging.error(f"❌ Error: gradient contains NaN (optimizerupdatefront) !") + return (recon_loss.item(),) + + # Optimizer update. + self.optimizer.step() + + # Measure parameter change after the update. + param_change = torch.norm(self.latents.data - old_latents).item() + + # Validate the updated latents. + if torch.isnan(self.latents).any(): + logging.error(f"❌ Error: latents contain NaN (optimizerupdateback) !") + logging.error(f" gradient norm: {grad_norm_total:.4e}") + logging.error(f" Learning rate: {self.config.lr}") + logging.error(f" Param change: {param_change:.4e}") + logging.error(f" suggestion: this may be caused by Adam optimizer momentum") + logging.error(f" : 1) reset optimizer 2) Use SGD instead of Adam") + # Restore the previous value. + self.latents.data.copy_(old_latents) + # Clear optimizer momentum/state before retrying. + self.optimizer.state.clear() + logging.info(f" ✅ already reset optimizerStatus, will retry on the next step") + return (recon_loss.item(),) + + # Sanity-check the latent magnitude. + latents_max = torch.abs(self.latents).max().item() + if latents_max > 1000: + logging.warning(f"⚠️ warning: latent values are too large (max={latents_max:.2e})") + logging.warning(f" you may need to lower the learning rate or SDS timestep") + + logging.info(f"✏️ Step {step:3d} | Param change: {param_change:.4e}, max|z|: {latents_max:.2e}") + + return (recon_loss.item(),) + + def training_step( + self, + step: int, + lagrange: float, + rho: float, + use_sds: bool = True, + save_step: Optional[int] = None, + ) -> Tuple[float, float, float]: + """Physics optimization. + + This follows the computation_phys_loss_grad flow from viewer_base.py: + 1. optimizer.zero_grad() + 2. with torch.no_grad(): prepare_solid() + solve() + 3. Compute sensitivities with the reference-style formula + 4. backward_step() via VJP + 5. Apply ALM weighting (lambda + rho[g]_+) + 6. optimizer.step() + + Reference: + physiopt/src/physiopt/vis/viewer_base.py Line 1297-1430 + """ + save_step_id = step if save_step is None else int(save_step) + + # ==================== Step 1: zero gradients ==================== + self.optimizer.zero_grad() + + # ==================== Step 2: update occupancy on the fixed topology ==================== + if step > 0: + logging.info(f"🔄 [Step {step}] update occupancy (mesh topology fixed) ...") + # Keep the previous occupancy for diagnostics. + old_occ = self.coarse_occ.clone() + + # Re-query the SDF and occupancy on the fixed mesh. + sdf = self.get_field(self.nodes) + from physiopt.opt.field import occ_kernel + occ = occ_kernel(sdf, self.config.res, self.config.occ_sdf_beta) + self.coarse_occ = occ[self.elements].mean(1) + + # Diagnose occupancy changes. + occ_change = self.coarse_occ - old_occ + occ_mean_change = occ_change.mean().item() + occ_increase_ratio = (occ_change > 0).float().mean().item() + + logging.info(f" occupancy range: [{self.coarse_occ.min():.3f}, {self.coarse_occ.max():.3f}]") + logging.info(f" occupancy change: mean={occ_mean_change:+.3e}, increase ratio={occ_increase_ratio:.1%}") + + # ==================== Step 3: physics simulation (with torch.no_grad) ==================== + # Aligned with the reference flow around Line 1317-1356. + with torch.no_grad(): + # 3.1 prepare_solid: apply SIMP scaling and build SolidGrid. + if self.config.alpha_min > 0.0: + self.coarse_occ = torch.clamp(self.coarse_occ, self.config.alpha_min) + + # Material SIMP scaling. + from torchfem.materials import IsotropicElasticity3D + from physiopt.opt.solid_grid import SolidGrid + + vectorized_material = IsotropicElasticity3D( + E=self.config.youngs_modulus, + nu=self.config.poissons_ratio, + rho=self.config.density, + ).vectorize(self.elements.shape[0]) + + vectorized_material.C *= ( + self.coarse_occ[:, None, None] ** self.config.p_exponent + ) + + # Create the SolidGrid solver state. + solid = SolidGrid(self.nodes, self.elements, vectorized_material) + solid.constraints[self.boundary_mask, :] = True + solid.forces = self.forces + + # 3.2 FEM solve. + logging.info(f"Step {step}: FEM solve...") + u, f_int, f_ext, sigma, _, _ = solid.solve(max_iter=1) + u_mean = torch.abs(u).mean().item() + logging.info(f" |u|_mean={u_mean}") + self._log_physical_quantities(u, sigma) + + # Save the deformed mesh every N steps. + # if self.config.deformed_mesh_interval > 0 and save_step_id % self.config.deformed_mesh_interval == 0: + # try: + # self.save_deformed_mesh(save_step_id, u) + # except Exception as e: + # logging.warning(f" ⚠️ error while saving the deformed mesh: {e}") + + # ==================== Step 4: sensitivity computation ==================== + # Strictly aligned with the reference flow around Line 1368-1399. + + # 4.1 Compute strain energy. We recover the unweighted energy by + # dividing out occ^p and keep strong numerical guards. + k0 = solid.k0() # occ^p * K_base after stiffness scaling. + u_j = u[self.elements].reshape(solid.n_elem, -1) + w_k_scaled = torch.einsum("...i, ...ij, ...j", u_j, k0, u_j) + + # Remove occ^p scaling to recover the base energy. + occ_power = torch.clamp( + self.coarse_occ ** self.config.p_exponent, + min=1e-6, # Avoid division by zero. + max=1.0 # Avoid overflow. + ) + + # Check again before division. + if torch.any(occ_power < 1e-6): + n_small = (occ_power < 1e-6).sum().item() + logging.warning(f" ⚠️ {n_small} elements have extremely small occ^p and were clamped to 1e-6") + + w_k_base = w_k_scaled / occ_power + + # Fall back if the recovered energy becomes invalid. + if torch.isnan(w_k_base).any() or torch.isinf(w_k_base).any(): + n_nan = torch.isnan(w_k_base).sum().item() + n_inf = torch.isinf(w_k_base).sum().item() + logging.error(f" ❌ w_k_baseabnormal: {n_nan} NaN, {n_inf} Inf") + logging.error(f" fall back to SIMP weightingw_k") + w_k_base = w_k_scaled + + # Use the recovered energy downstream. + compliance_mean = w_k_base.mean().item() + w_k = w_k_base # Downstream sensitivity uses the recovered energy. + + # Diagnostics. + logging.info(f" Compliance (true) ={compliance_mean:.2e}") + logging.info(f" w_k_base: max={w_k.max():.2e}, stress concentration={w_k.max()/(w_k.mean() + 1e-10):.1f}x") + + # ALM normalized constraint: g = D / D_thr - 1. + compliance_threshold = self.config.compliance_threshold if self.config.compliance_threshold is not None else 1.0 + g_raw = compliance_mean / (compliance_threshold + 1e-8) - 1.0 + g_pos = max(0.0, g_raw) + logging.info(f" constraint normalization: g={g_raw:+.3e}, [g]+={g_pos:.3e}, D_thr={compliance_threshold:.2e}") + + # Dynamic clip limit used by the ALM scaling guard. + base_max_grad = 1000.0 + lagrange_bonus = min((lagrange + rho * g_pos) * 10.0, 1000.0) + max_grad_norm = base_max_grad + lagrange_bonus + + # 4.3 Sensitivity formula aligned with the reference code: + # sensitivity = -p * occ^(p-1) * w_k + self.sensitivity_density = ( + -self.config.p_exponent + * self.coarse_occ ** (self.config.p_exponent - 1) + * w_k + ) + + # 4.4 Volume regularization is intentionally disabled here so the pure + # physics signal can be validated first. + if False and self.config.volume_term > 0.0: # Temporarily forced off. + # Initialize the reference volume on first use. + if not hasattr(self, 'init_volume'): + self.init_volume = self.coarse_occ.clone() + logging.info(f" record initial volume: sum={self.init_volume.sum().item():.2f}") + + # Volume sensitivity term. + sensitivity_volume = ( + self.config.volume_term + * (1.0 / self.config.res) ** 3 + * torch.ones_like(self.sensitivity_density) + ) + + # Choose the sign from the current volume change. + volume_sign = 1.0 if self.coarse_occ.sum() >= self.init_volume.sum() else -1.0 + sensitivity_volume *= volume_sign + + self.sensitivity_density += sensitivity_volume + + volume_ratio = self.coarse_occ.sum() / self.init_volume.sum() + logging.info(f" volume constraint: ratio={volume_ratio.item():.3f}, " + f"{'penalize' if volume_sign > 0 else 'encourage'}") + else: + logging.info(f" volume constraint: disabled (physicsoptimizationdominates) ") + + # Sensitivity diagnostics. + sens_norm = torch.norm(self.sensitivity_density).item() + sens_min = self.sensitivity_density.min().item() + sens_max = self.sensitivity_density.max().item() + logging.info(f" sensitivity: norm={sens_norm:.2e}, range=[{sens_min:.2e}, {sens_max:.2e}]") + + # ==================== Step 5: backward pass via VJP ==================== + self.backward_step(self.sensitivity_density) + + # ==================== Step 6: apply ALM weighting (lambda + rho[g]+) ==================== + if self.latents.grad is not None: + phys_grad_norm = torch.norm(self.latents.grad).item() + phys_grad_unscaled = self.latents.grad.clone() # Unscaled physics gradient for SDS comparisons. + + if g_pos > 0.0: + alm_scale_raw = (lagrange + rho * g_pos) / (compliance_threshold + 1e-8) + alm_scale = alm_scale_raw + guard_ratio = min(max(self.config.alm_scale_guard_ratio, 0.0), 1.0) + if phys_grad_norm > 0.0 and max_grad_norm > 0.0 and guard_ratio > 0.0: + alm_scale_guard = (max_grad_norm * guard_ratio) / (phys_grad_norm + 1e-8) + if alm_scale > alm_scale_guard: + logging.info( + f" 🔧 ALMscaling limit: raw={alm_scale_raw:.3e} -> {alm_scale_guard:.3e} " + f"(guard={guard_ratio:.2f}, max_grad={max_grad_norm:.1f})" + ) + alm_scale = alm_scale_guard + self.latents.grad *= alm_scale + else: + alm_scale = 0.0 + self.latents.grad.zero_() + + scaled_grad_norm = torch.norm(self.latents.grad).item() + logging.info( + f" physics gradient(ALM): {phys_grad_norm:.2e} → {scaled_grad_norm:.2e} " + f"(×scale={alm_scale:.3e}, λ={lagrange:.2f}, ρ={rho:.2f})" + ) + else: + phys_grad_unscaled = None + alm_scale = 0.0 + + # ==================== Step 7: shape loss toward target_z0 ==================== + + # 7.1 Compute the denoised target_z0. + import math + if use_sds: + target_z0, _, _ = self._get_target_z0(step) + else: + target_z0 = self.latents.detach() + + # Optionally validate and save a target_z0 mesh every 10 steps. + if use_sds: + self._maybe_save_target_z0_mesh(target_z0, save_step_id) + + # Shape loss is a simple MSE pulling latents toward target_z0. + shape_loss = torch.nn.functional.mse_loss(self.latents, target_z0.detach()) + + # 7.2 Decide whether shape loss is active this step. + current_sds_weight = self.get_current_sds_weight(step) if use_sds else 0.0 + use_sds_this_step = current_sds_weight > 0.0 + + if not use_sds_this_step: + logging.info(f" 🚫 Shape Loss disabled (physicsoptimizationmode) ") + weighted_sds = 0.0 + shape_grad_norm = 0.0 + else: + # Weighted shape loss. + weighted_shape_loss = current_sds_weight * shape_loss + + # Validate shape loss before backpropagating it. + if torch.isnan(shape_loss) or torch.isinf(shape_loss): + logging.error(f" ❌ Shape Loss contains NaN or Inf; skipping the shape constraint") + weighted_sds = 0.0 + shape_grad_norm = 0.0 + else: + # Backpropagate the shape loss into latents.grad. + weighted_shape_loss.backward() + + # Measure the shape-gradient norm for logging. + if self.latents.grad is not None and phys_grad_unscaled is not None: + # Isolate the shape part from the combined gradient. + shape_gradient = self.latents.grad - phys_grad_unscaled * alm_scale + shape_grad_norm = torch.norm(shape_gradient).item() + phys_grad_norm_current = torch.norm(phys_grad_unscaled * alm_scale).item() + shape_phys_ratio = shape_grad_norm / (phys_grad_norm_current + 1e-10) + + if shape_phys_ratio > 100.0: + logging.error(f" ❌ Shape gradient is too large (Shape/physics={shape_phys_ratio:.1f}x)!") + logging.error(f" consider lowering sds_weight_end: {self.config.sds_weight_end} → {self.config.sds_weight_end/100:.4f}") + elif shape_phys_ratio > 10.0: + logging.warning(f" ⚠️ Shape gradient is relatively large (Shape/physics={shape_phys_ratio:.1f}x)") + + # Compare the directions of physics and shape gradients. + cos_angle = (phys_grad_unscaled * shape_gradient).sum() / ( + torch.norm(phys_grad_unscaled) * torch.norm(shape_gradient) + 1e-10 + ) + angle_deg = torch.acos(torch.clamp(cos_angle, -1, 1)) * 180 / math.pi + direction = "same direction✅" if angle_deg < 90 else "opposite direction⚠️" + + logging.info(f" Shapegradient: norm={shape_grad_norm:.4e}, weight={current_sds_weight:.6f}") + logging.info(f" gradient direction: physics vs Shape = {angle_deg:.1f}° ({direction})") + elif self.latents.grad is not None: + shape_grad_norm = torch.norm(self.latents.grad).item() + logging.info(f" Shapegradient: norm={shape_grad_norm:.4e} (no physics gradient)") + else: + shape_grad_norm = 0.0 + + weighted_sds = weighted_shape_loss.item() + + # ==================== Step 8: combine losses and clip if needed ==================== + compliance_loss_item = compliance_mean + alm_penalty = lagrange * g_pos + 0.5 * rho * (g_pos ** 2) + total_loss = alm_penalty + weighted_sds + + # Log the combined loss terms. + if use_sds_this_step: + logging.info( + f" 📊 weighted loss: Compliance={compliance_loss_item:.4e}, g={g_raw:+.3e}, " + f"ALM={alm_penalty:.4e} (λ={lagrange:.2f}, ρ={rho:.2f}), " + f"Shape={weighted_sds:.4e} (×w={current_sds_weight:.6f}), Total={total_loss:.4e}" + ) + else: + logging.info( + f" 📊 weighted loss: Compliance={compliance_loss_item:.4e}, g={g_raw:+.3e}, " + f"ALM={alm_penalty:.4e} (λ={lagrange:.2f}, ρ={rho:.2f}), " + f"Shape=0.00e+00 (disabled), Total={total_loss:.4e}" + ) + + # Log gradient composition details. + if self.latents.grad is not None: + grad_norm = torch.norm(self.latents.grad).item() + + # Report each gradient contribution. + if phys_grad_unscaled is not None: + weighted_phys_grad_norm = torch.norm(phys_grad_unscaled * alm_scale).item() + logging.info(f" 🔍 gradient composition: Weighted Compliance Grad={weighted_phys_grad_norm:.4e} (ALM scale={alm_scale:.3e})") + + if use_sds_this_step and shape_grad_norm > 0: + logging.info(f" Scaled Shape Grad={shape_grad_norm:.4e} (Shape×w={current_sds_weight:.6f})") + if phys_grad_unscaled is not None: + grad_ratio = shape_grad_norm / (weighted_phys_grad_norm + 1e-10) + logging.info(f" ratio: Shape/Compliance = {grad_ratio:.4f} ({grad_ratio*100:.2f}%)") + + logging.info(f" Total Grad={grad_norm:.4e}") + + # Optional gradient clipping. + if self.latents.grad is not None: + grad_norm = torch.norm(self.latents.grad).item() + + if torch.isnan(self.latents.grad).any() or torch.isinf(self.latents.grad).any(): + logging.error(f"❌ the final gradient contains NaN or Inf!skip this steps") + return (compliance_loss_item, u_mean, shape_loss.item(), total_loss) + + if self.config.grad_clip_enabled: + if grad_norm > max_grad_norm: + clip_factor = max_grad_norm / grad_norm + self.latents.grad = self.latents.grad * clip_factor + logging.info(f" ✂️ gradient clipping: {grad_norm:.4e} -> {max_grad_norm:.1f} (×{clip_factor:.3f})") + else: + logging.info(f" ✅ gradient not clipped: {grad_norm:.4e} (max={max_grad_norm:.1f})") + + # ==================== Step 9: optimizer step ==================== + + # Save the previous latents for diagnostics. + old_latents = self.latents.data.clone() + + self.optimizer.step() + + # Diagnose latent changes after the optimizer step. + with torch.no_grad(): + latents_change = torch.norm(self.latents.data - old_latents).item() + latents_norm = torch.norm(old_latents).item() + latents_change_percent = (latents_change / (latents_norm + 1e-10)) * 100 + max_latents_change = torch.abs(self.latents.data - old_latents).max().item() + + logging.info(f" 🔄 Latentschange: L2={latents_change:.4e} ({latents_change_percent:.3f}%), max={max_latents_change:.4e}") + + if latents_change < 1e-6: + logging.warning(f" ⚠️ latents almost did not change!the learning rate may be too small or the gradient may be too weak") + + # Return the scalar loss values. + return (compliance_loss_item, u_mean, shape_loss.item(), total_loss) + + def save_mesh(self, step: int, output_dir: str = "results/hunyuan_meshes", high_quality: bool = False, suffix="step"): + """Save frontlatentsmesh + + Args: + step: front steps + output_dir: outputdirectory + high_quality: YesNouse (Resolution) , Trueuse256resolution + """ + os.makedirs(output_dir, exist_ok=True) + + try: + # finalSave use256resolution, Stepuse128resolution + octree_res = 256 if high_quality else 128 + mesh = self.latents_to_mesh(self.latents, octree_res=octree_res) + if mesh is None: + logging.warning(f" ⚠️ warning: Step {step} - Marching cubesno surface found, skipSave ") + return + + # finalSave filterfloating + if high_quality: + mesh = self._filter_floating_components(mesh) + + mesh_path = os.path.join(output_dir, f"{suffix}_{step:04d}.obj") + mesh.export(mesh_path) + quality_label = "256resolution" if high_quality else "128resolution" + logging.info(f" 💾 Save mesh ({quality_label}): {mesh_path}") + except Exception as e: + logging.warning(f" ⚠️ warning: Step {step} - Save meshfailed: {e}") + + + def _maybe_save_target_z0_mesh(self, target_z0: torch.Tensor, step_id: int, force: bool = False): + """Save a mesh decoded from target_z0 for diagnostics.""" + if (not force) and (step_id % 10 != 0): + return + + with torch.no_grad(): + deviation = torch.norm(target_z0 - self.latents).item() + latents_norm = torch.norm(self.latents).item() + relative_deviation = deviation / (latents_norm + 1e-8) + + if relative_deviation > 0.5: + logging.warning( + f" ⚠️ target_z0 deviation is too large: {relative_deviation:.1%} " + f"(||target_z0 - latents||={deviation:.3e}, ||latents||={latents_norm:.3e})" + ) + logging.warning(f" thismaySave target meshshape is abnormal") + + try: + target_norm = torch.norm(target_z0).item() + target_max = torch.abs(target_z0).max().item() + target_has_nan = torch.isnan(target_z0).any().item() + target_has_inf = torch.isinf(target_z0).any().item() + + # Save only when target_z0 looks numerically healthy. + if (not target_has_nan and not target_has_inf and + target_max < 100.0 and relative_deviation < 1.0): + target_z0_clean = target_z0.detach().clone() + + logging.info(f" 📊 target_z0 statistics:") + logging.info(f" - shape: {target_z0_clean.shape}") + logging.info(f" - range: [{target_z0_clean.min():.3e}, {target_z0_clean.max():.3e}]") + logging.info(f" - mean: {target_z0_clean.mean():.3e}, Std: {target_z0_clean.std():.3e}") + logging.info(f" - deviation from latents: {relative_deviation:.1%}") + + target_mesh = self.latents_to_mesh(target_z0_clean, octree_res=128) + if target_mesh is not None: + target_mesh_dir = os.path.join( + self.config.out_folder if hasattr(self.config, 'out_folder') + else "results/hunyuan_meshes", + "target_z0_meshes" + ) + os.makedirs(target_mesh_dir, exist_ok=True) + target_mesh_path = os.path.join(target_mesh_dir, f"target_z0_step_{step_id:04d}.obj") + target_mesh.export(target_mesh_path) + logging.info(f" 💾 Save target_z0 mesh (||z||={target_norm:.2e}): {target_mesh_path}") + else: + logging.debug(f" skipSave target_z0: marching cubesno surface found") + else: + logging.warning( + f" ⚠️ skipSave target_z0: containsabnormal values " + f"(nan={target_has_nan}, inf={target_has_inf}, max={target_max:.2e})" + ) + except (ValueError, RuntimeError) as e: + error_msg = str(e) + if "Surface level must be within volume data range" in error_msg or "No surface found" in error_msg: + logging.debug(f" skipSave target_z0: SDFvalueoutside the valid range or has no surface") + else: + logging.warning(f" Save target_z0 meshfailed: {type(e).__name__}: {error_msg[:100]}") + except Exception as e: + logging.warning(f" Save target_z0 meshfailed: {type(e).__name__}: {str(e)[:100]}") + + def save_final_target_z0_mesh(self, step_id: int): + """Force-save a target_z0 mesh at the final step.""" + try: + if self.target_z0_ema is not None: + target_z0 = self.target_z0_ema.detach().clone() + else: + target_z0, _ = self._computation_target_z0_current(step_id) + self._maybe_save_target_z0_mesh(target_z0, step_id, force=True) + except Exception as e: + logging.warning(f" ⚠️ failed to save the final target_z0: {type(e).__name__}: {str(e)[:100]}") + + def save_deformed_mesh(self, step: int, displacement: torch.Tensor, output_dir: str = None, suffix="step"): + """Save FEM solvebackdeformed mesh + + Args: + step: front steps + displacement: FEM solve [num_nodes, 3] + output_dir: outputdirectory, useconfig.out_folder/deformed_meshes + """ + if output_dir is None: + if hasattr(self.config, 'out_folder'): + output_dir = os.path.join(self.config.out_folder, "deformed_meshes") + else: + output_dir = "results/deformed_meshes" + + os.makedirs(output_dir, exist_ok=True) + + try: + # originalnodespositionandbackposition + original_nodes = self.nodes.detach().cpu().numpy() # [num_nodes, 3] + displacement_np = displacement.detach().cpu().numpy() # [num_nodes, 3] + deformed_nodes = original_nodes + displacement_np + + # elements + elements_np = self.elements.detach().cpu().numpy() # [num_elements, 8] + + # # Save VTK format (ParaView, contains) + # vtk_path = os.path.join(output_dir, f"deformed_step_{step:04d}.vtk") + # self._save_hex_mesh_vtk(deformed_nodes, elements_np, displacement_np, vtk_path, step) + + # Save OBJ/PLY (usedecodemesh, ) + decoded_mesh = self.latents_to_mesh(self.latents, octree_res=128) + if decoded_mesh is not None: + disp_vertices = self._sample_displacement_to_vertices( + decoded_mesh.vertices, original_nodes, displacement_np + ) + deformed_vertices = decoded_mesh.vertices + disp_vertices + colors = self._make_displacement_colors(disp_vertices) + + deformed_mesh = trimesh.Trimesh( + vertices=deformed_vertices, + faces=decoded_mesh.faces, + process=False, + ) + deformed_mesh.visual.vertex_colors = colors + + obj_path = os.path.join(output_dir, f"deformed_{suffix}_{step:04d}.obj") + # ply_path = os.path.join(output_dir, f"deformed_step_{step:04d}.ply") + deformed_mesh.export(obj_path) + # deformed_mesh.export(ply_path) + else: + # fallback: usemesh + obj_path = os.path.join(output_dir, f"deformed_{suffix}_{step:04d}.obj") + # ply_path = os.path.join(output_dir, f"deformed_step_{step:04d}.ply") + self._save_surface_mesh_obj(deformed_nodes, elements_np, obj_path) + # self._save_surface_mesh_ply(deformed_nodes, elements_np, displacement_np, ply_path) + + # displacement statistics + disp_mean = np.abs(displacement_np).mean() + disp_max = np.abs(displacement_np).max() + logging.info(f" 💾 saved deformed mesh : OBJ={obj_path.split('/')[-1]}") + logging.debug(f" : mean={disp_mean:.4e}, max={disp_max:.4e}") + + except Exception as e: + logging.warning(f" ⚠️ Save deformed meshfailed (Step {step}): {e}") + + def save_final_deformed_mesh(self, step_id: int, suffix="step"): + """force at the final step toSave deformed mesh (re-solveFEM) """ + if not hasattr(self, 'nodes') or not hasattr(self, 'elements'): + logging.warning(" ⚠️ unable to save the finaldeformed mesh: missingnodes/elements") + return + if not hasattr(self, 'forces') or not hasattr(self, 'boundary_mask'): + logging.warning(" ⚠️ unable to save the finaldeformed mesh: missingforces/boundary_mask") + return + + try: + from torchfem.materials import IsotropicElasticity3D + from physiopt.opt.solid_grid import SolidGrid + from physiopt.opt.field import occ_kernel + + with torch.no_grad(): + # update occupancyalignfrontlatents + sdf = self.get_field(self.nodes) + occ = occ_kernel(sdf, self.config.res, self.config.occ_sdf_beta) + self.coarse_occ = occ[self.elements].mean(1) + + if self.config.alpha_min > 0.0: + self.coarse_occ = torch.clamp(self.coarse_occ, self.config.alpha_min) + + vectorized_material = IsotropicElasticity3D( + E=self.config.youngs_modulus, + nu=self.config.poissons_ratio, + rho=self.config.density, + ).vectorize(self.elements.shape[0]) + + vectorized_material.C *= ( + self.coarse_occ[:, None, None] ** self.config.p_exponent + ) + + solid = SolidGrid(self.nodes, self.elements, vectorized_material) + solid.constraints[self.boundary_mask, :] = True + solid.forces = self.forces + + logging.info(" 🧱 final deformed mesh: re-solve the FEM system to save ") + u, _, _, _, _, _ = solid.solve(max_iter=1) + self.save_deformed_mesh(step_id, u, suffix=suffix) + except Exception as e: + logging.warning(f" ⚠️ final deformed meshSave failed: {type(e).__name__}: {str(e)[:100]}") + + def _save_surface_mesh_obj(self, nodes: np.ndarray, elements: np.ndarray, filename: str): + """Extract the surface from a hexahedral mesh and save it as OBJ.""" + # The six faces of a hexahedron. + hex_faces = [ + [0, 1, 2, 3], [4, 5, 6, 7], # Bottom, top. + [0, 1, 5, 4], [2, 3, 7, 6], # Front, back. + [0, 3, 7, 4], [1, 2, 6, 5], # Left, right. + ] + + # Collect faces that appear only once, i.e. surface faces. + face_count = {} + for elem in elements: + for face_indices in hex_faces: + face_nodes = tuple(sorted([elem[i] for i in face_indices])) + if face_nodes in face_count: + face_count[face_nodes] += 1 + else: + face_count[face_nodes] = 1 + + # Keep only surface faces. + surface_faces = [face for face, count in face_count.items() if count == 1] + + # Save OBJ. + with open(filename, 'w') as f: + f.write("# Deformed mesh surface\n") + for node in nodes: + f.write(f"v {node[0]:.6f} {node[1]:.6f} {node[2]:.6f}\n") + for face in surface_faces: + # OBJ indices are 1-based. + f.write(f"f {face[0]+1} {face[1]+1} {face[2]+1} {face[3]+1}\n") + + def _save_force_visualization(self, seat_nodes_mask: torch.Tensor, total_force: np.ndarray): + """Save voxel-level load data for visualization and validation. + + This exports: + 1. NumPy (.npz) with full node/load data + 2. OBJ point clouds for quick inspection + 3. Optional VTK data for ParaView + + Args: + seat_nodes_mask: Mask of seat/contact nodes [num_nodes]. + total_force: Total force vector [3]. + """ + if not hasattr(self.config, 'out_folder'): + logging.warning(" out_folder is not set, skipSave loaded voxel") + return + + # Create the force_visualization subdirectory. + vis_dir = os.path.join(self.config.out_folder, "force_visualization") + os.makedirs(vis_dir, exist_ok=True) + + # ==================== 1. Save NumPy data (most complete format) ==================== + all_nodes_cpu = self.nodes.cpu().numpy() + all_forces_cpu = self.forces.cpu().numpy() + seat_mask_cpu = seat_nodes_mask.cpu().numpy() + + # Extract loaded nodes. + seat_nodes = all_nodes_cpu[seat_mask_cpu] + seat_forces = all_forces_cpu[seat_mask_cpu] + + npz_path = os.path.join(vis_dir, "force_nodes.npz") + np.savez( + npz_path, + # All node data. + all_nodes=all_nodes_cpu, + all_forces=all_forces_cpu, + # Loaded-node data. + seat_nodes=seat_nodes, + seat_forces=seat_forces, + seat_mask=seat_mask_cpu, + # Boundary-node data. + boundary_mask=self.boundary_mask.cpu().numpy() if hasattr(self, 'boundary_mask') else None, + # Metadata. + total_force=total_force, + num_seat_nodes=len(seat_nodes), + num_all_nodes=len(all_nodes_cpu), + ) + logging.info(f" 💾 Save load data (NumPy format) : {npz_path}") + + # ==================== 2. Save OBJ point clouds ==================== + # 2a. Loaded nodes (red point cloud). + seat_obj_path = os.path.join(vis_dir, "seat_nodes.obj") + with open(seat_obj_path, 'w') as f: + f.write("# Seat nodes (loaded area)\n") + f.write(f"# Total: {len(seat_nodes)} nodes\n") + f.write(f"# Force per node: {seat_forces[0] if len(seat_forces) > 0 else [0,0,0]}\n") + for node in seat_nodes: + f.write(f"v {node[0]:.6f} {node[1]:.6f} {node[2]:.6f}\n") + logging.info(f" 💾 Save seat nodes (OBJpoint cloud) : {seat_obj_path}") + + # 2b. Boundary nodes (blue point cloud). + if hasattr(self, 'boundary_mask'): + boundary_nodes = all_nodes_cpu[self.boundary_mask.cpu().numpy()] + boundary_obj_path = os.path.join(vis_dir, "boundary_nodes.obj") + with open(boundary_obj_path, 'w') as f: + f.write("# Boundary nodes (fixed area)\n") + f.write(f"# Total: {len(boundary_nodes)} nodes\n") + for node in boundary_nodes: + f.write(f"v {node[0]:.6f} {node[1]:.6f} {node[2]:.6f}\n") + logging.info(f" 💾 Save boundary nodes (OBJpoint cloud) : {boundary_obj_path}") + + # 2c. All nodes (gray point cloud) for comparison. + all_obj_path = os.path.join(vis_dir, "all_nodes.obj") + with open(all_obj_path, 'w') as f: + f.write("# All nodes\n") + f.write(f"# Total: {len(all_nodes_cpu)} nodes\n") + for node in all_nodes_cpu: + f.write(f"v {node[0]:.6f} {node[1]:.6f} {node[2]:.6f}\n") + logging.info(f" 💾 Save all nodes (OBJpoint cloud) : {all_obj_path}") + + # ==================== 3. Save VTK data for ParaView ==================== + try: + vtk_path = os.path.join(vis_dir, "force_field.vtk") + with open(vtk_path, 'w') as f: + # VTK Header + f.write("# vtk DataFile Version 3.0\n") + f.write("Force field visualization\n") + f.write("ASCII\n") + f.write("DATASET UNSTRUCTURED_GRID\n") + + # Points + f.write(f"POINTS {len(all_nodes_cpu)} float\n") + for node in all_nodes_cpu: + f.write(f"{node[0]:.6f} {node[1]:.6f} {node[2]:.6f}\n") + + # Cells (vertices) + f.write(f"\nCELLS {len(all_nodes_cpu)} {len(all_nodes_cpu)*2}\n") + for i in range(len(all_nodes_cpu)): + f.write(f"1 {i}\n") + + # Cell types (1 = vertex) + f.write(f"\nCELL_TYPES {len(all_nodes_cpu)}\n") + for _ in range(len(all_nodes_cpu)): + f.write("1\n") + + # Point data (force vectors) + f.write(f"\nPOINT_DATA {len(all_nodes_cpu)}\n") + f.write("VECTORS force float\n") + for force in all_forces_cpu: + f.write(f"{force[0]:.6e} {force[1]:.6e} {force[2]:.6e}\n") + + # Scalar field: force magnitude + f.write("\nSCALARS force_magnitude float 1\n") + f.write("LOOKUP_TABLE default\n") + for force in all_forces_cpu: + mag = np.linalg.norm(force) + f.write(f"{mag:.6e}\n") + + # Scalar field: is_seat (0 or 1) + f.write("\nSCALARS is_seat int 1\n") + f.write("LOOKUP_TABLE default\n") + for is_seat in seat_mask_cpu: + f.write(f"{int(is_seat)}\n") + + logging.info(f" 💾 Save force field (VTK format, ParaView) : {vtk_path}") + except Exception as e: + logging.warning(f" ⚠️ Save VTK formatfailed: {e}") + + +def load_hunyuan_models(model_path: str = "tencent/Hunyuan3D-2.1", + subfolder: str = "hunyuan3d-shapegen", + use_safetensors: bool = True): + """Load the Hunyuan3D models (VAE, Flow Model, and Scheduler). + + Args: + model_path: Model path, either a Hugging Face ID or a local directory. + subfolder: Model subfolder name. + use_safetensors: Whether to load safetensors checkpoints. + + Returns: + (vae, flow_model, scheduler): the VAE, Flow Matching model, and scheduler. + """ + logging.info(f"🔧 loading Hunyuan3D-2.1model...") + logging.info(f" modelpath: {model_path}") + logging.info(f" subfolder: {subfolder}") + logging.info(f" modelformat: {'safetensors' if use_safetensors else 'checkpoint'}") + + try: + pipeline = Hunyuan3DDiTFlowMatchingPipeline.from_pretrained( + model_path, + subfolder=subfolder, + torch_dtype=torch.float16, + use_safetensors=use_safetensors + ) + + if pipeline is None: + raise ValueError("pipeline loading failed and returned None") + + logging.info(" ✅ pipeline loaded successfully") + + pipeline.to('cuda') + logging.info(" ✅ modelmoved to CUDA (dtype: fp16)") + + vae = pipeline.vae + flow_model = pipeline.model + scheduler = pipeline.scheduler + + return vae, flow_model, scheduler + + except Exception as e: + logging.error(f"\n❌ modelloadfailed: {e}") + logging.error(f"\nPossible fixes:") + logging.error(f"1. make sure Hunyuan3D is installed-2.1: cd Hunyuan3D-2.1 && pip install -e .") + logging.error(f"2. check network connectivity to huggingface.co") + logging.error(f"3. or download manually: git clone https://huggingface.co/tencent/Hunyuan3D-2") + import traceback + traceback.print_exc() + sys.exit(1) + + +def plot_history(history: dict, save_dir: str, filename: str = "optimization_metrics.png"): + + epochs = list(range(1, len(history["compliance"]) + 1)) + + # 2. Create the figure with a 2x2 grid + fig, axs = plt.subplots(2, 2, figsize=(14, 10)) + fig.suptitle("Optimization Metrics Evolution", fontsize=16, fontweight='bold') + + # --- Plot 1: Compliance --- + axs[0, 0].plot(epochs, history["compliance"], marker='o', color='#1f77b4', linewidth=2) + axs[0, 0].set_title("Compliance (Strain Energy)") + axs[0, 0].set_xlabel("Epoch") + axs[0, 0].grid(True, linestyle='--', alpha=0.7) + + # --- Plot 2: u_mean --- + axs[0, 1].plot(epochs, history["u_mean"], marker='s', color='#2ca02c', linewidth=2) + axs[0, 1].set_title("Mean Displacement (|u|_mean)") + axs[0, 1].set_xlabel("Epoch") + axs[0, 1].grid(True, linestyle='--', alpha=0.7) + + # --- Plot 3: c_relative_decrease --- + axs[1, 0].plot(epochs, history["c_relative_decrease"], marker='^', color='#d62728', linewidth=2) + axs[1, 0].set_title("Relative Compliance Decrease") + axs[1, 0].set_xlabel("Epoch") + axs[1, 0].grid(True, linestyle='--', alpha=0.7) + + # --- Plot 4: u_relative_decrease --- + axs[1, 1].plot(epochs, history["u_relative_decrease"], marker='v', color='#9467bd', linewidth=2) + axs[1, 1].set_title("Relative Displacement Decrease") + axs[1, 1].set_xlabel("Epoch") + axs[1, 1].grid(True, linestyle='--', alpha=0.7) + + # 3. Adjust layout to prevent text from overlapping + plt.tight_layout() + fig.subplots_adjust(top=0.92) # Leave space for the main super-title + + # 4. Save the figure + os.makedirs(save_dir, exist_ok=True) + full_path = os.path.join(save_dir, filename) + + plt.savefig(full_path, dpi=300, bbox_inches='tight') + plt.close(fig) + + logging.info(f" 📊 Plot successfully saved to: {full_path}") + + +def main(): + """Parse CLI arguments and run the optimization.""" + import argparse + + parser = argparse.ArgumentParser(description="Hunyuan3D physics optimization + shape-prior optimization") + + # Required arguments. + parser.add_argument("--latents", type=str, required=True, + help="Input latents file path (.pt)") + parser.add_argument("--out_folder", type=str, default="../out/hunyuan_opt", + help="Output folder path") + + # Model arguments. + parser.add_argument("--model_path", type=str, default="tencent/Hunyuan3D-2.1", + help="Model path (using v2.1)") + parser.add_argument("--subfolder", type=str, default="hunyuan3d-dit-v2-1", + help="Model subfolder") + parser.add_argument("--use_safetensors", action="store_true", + help="Use safetensors format (default: ckpt)") + + # Physical-simulation arguments. + parser.add_argument("--use_physics", action="store_true", + help="Enable physics-constrained optimization") + parser.add_argument("--res", type=int, default=16, + help="Voxel resolution (16/32/64)") + parser.add_argument("--youngs_modulus_scale", type=float, default=2.0, + help="Final Young's modulus multiplier (default 2x after the last projection)") + parser.add_argument("--compliance_threshold", type=float, default=None, + help="Target compliance threshold (None = automatic)") + parser.add_argument("--compliance_threshold_ratio", type=float, default=0.3, + help="Automatic threshold ratio (threshold = initial value × ratio)") + + # Optimization arguments. + parser.add_argument("--num_steps", type=int, default=300, + help="Number of optimization steps (pure SDS only; in physics mode it becomes outer_cycles * phys_steps_per_cycle automatically)") + parser.add_argument("--outer_cycles", type=int, default=100, + help="Number of outer cycles (each cycle = physics optimization + projection)") + parser.add_argument("--phys_steps_per_cycle", type=int, default=5, + help="Number of physics-optimization steps per outer cycle") + parser.add_argument("--lr", type=float, default=5e-3, + help="Learning rate (increase to 0.005 to help the mesh thicken faster) ") + parser.add_argument("--lagrange_max", type=float, default=10.0, + help="Maximum Lagrange multiplier (recommended: 5-20)") + parser.add_argument("--alm_rho_init", type=float, default=1.0, + help="ALM rhoinitial value") + parser.add_argument("--alm_rho_max", type=float, default=1000.0, + help="ALM rhoMax") + parser.add_argument("--alm_rho_increase_factor", type=float, default=2.0, + help="ALM rhogrowth factor") + parser.add_argument("--alm_rho_increase_patience", type=int, default=5, + help="ALM rhonumber of consecutive violation steps required before increasing") + parser.add_argument("--alm_scale_guard_ratio", type=float, default=0.95, + help="ALMscaling guard ratio(<=1), control the upper bound of the physics-gradient target=this ratio x clipping-threshold value") + parser.add_argument("--grad_clip_enabled", action="store_true", + help="Enable gradient clipping (disabled by default; otherwise only NaN/Inf checks are kept)") + parser.add_argument("--use_sgd", action="store_true", + help="Use SGD instead of Adam") + parser.add_argument("--force_config", type=str, default=None, + help="Path to the external-force JSON config (generated by the web UI)") + parser.add_argument("--force", type=float, nargs=3, action="append", default=None, + help="External force vector [fx fy fz] (N, Y-up coordinates; can be specified multiple times)") + parser.add_argument("--global_loading", action="store_true", + help="Use global uniform loading (disable local loading)") + parser.add_argument("--force_region_mode", type=str, default="top_percent", + choices=["top_percent", "height_ratio", "bbox"], + help="How to choose the local loading region") + parser.add_argument("--force_top_percent", type=float, default=0.05, + help="top_percent mode: select the highest-Y fraction") + parser.add_argument("--force_bbox", type=float, nargs=6, default=None, + help="bbox mode: x_min x_max y_min y_max z_min z_max (absolute coordinates)") + parser.add_argument("--force_bbox_ratio", type=float, nargs=6, default=None, + help="bbox mode (0-1): bbox relative to the node bounds") + parser.add_argument("--seat_height_min_ratio", type=float, default=0.3, + help="height_ratio mode: lower seat boundary (0-1)") + parser.add_argument("--seat_height_max_ratio", type=float, default=0.5, + help="height_ratio mode: upper seat boundary (0-1)") + + # SDS arguments. + parser.add_argument("--sds_weight", type=float, default=1.0, + help="SDS gradient weight (deprecated; use sds_weight_start and sds_weight_end instead)") + parser.add_argument("--sds_weight_start", type=float, default=10.0, + help="Initial SDS weight (linearly increased; 0.0001 is recommended to avoid disturbing physics optimization)") + parser.add_argument("--sds_weight_end", type=float, default=10.0, + help="Final SDS weight (linearly increased; 0.001 is recommended, about 1/10 of the physics gradient)") + parser.add_argument("--sds_timestep", type=float, default=0.1, + help="SDS timestep (recommended: 0.05-0.2)") + parser.add_argument("--sds_target_z0_ema_beta", type=float, default=0.9, + help="target_z0 EMA smoothing factor (larger means smoother)") + parser.add_argument("--deformed_mesh_interval", type=int, default=10, + help="Interval for saving deformed meshes (steps)") + parser.add_argument("--deformed_mesh_disp_min", type=float, default=0.0, + help="Minimum displacement for deformed-mesh color mapping (default 0.0)") + parser.add_argument("--deformed_mesh_disp_max", type=float, default=0.2, + help="Maximum displacement for deformed-mesh color mapping (<=0 enables per-step auto scaling)") + parser.add_argument("--guidance_scale", type=float, default=7.5, + help="CFG guidance scale (standard value: 7.5; larger means stronger image conditioning)") + parser.add_argument("--sds_projection_max_rel", type=float, default=0.0, + help="Maximum relative target_z0 projection deviation (0 = unlimited)") + parser.add_argument("--sds_use_uncond", action="store_true", + help="Use the unconditional branch (only takes effect when guidance_scale <= 1)") + + # Topology control. + parser.add_argument("--keep_all_components", action="store_true", + help="Keep all connected components (to avoid disappearing chair legs)") + parser.add_argument("--re_extract_interval", type=int, default=1, + help="Solid re-extraction interval (0 = disabled)") + + args = parser.parse_args() + + def _normalize_force_vectors(value): + if value is None: + return None + if isinstance(value, (list, tuple)) and len(value) > 0: + if isinstance(value[0], (list, tuple)): + candidates = value + else: + candidates = [value] + else: + return None + normalized = [] + for vec in candidates: + if not isinstance(vec, (list, tuple)) or len(vec) != 3: + continue + try: + normalized.append([float(v) for v in vec]) + except Exception: + continue + return normalized if normalized else None + + def _normalize_force_entry(entry): + if not isinstance(entry, dict): + return None + forces = _normalize_force_vectors(entry.get("forces")) + if forces is None: + forces = _normalize_force_vectors(entry.get("force")) + if forces is None: + return None + out = dict(entry) + if len(forces) > 1: + out["forces"] = forces + out["force"] = [float(sum(v[i] for v in forces)) for i in range(3)] + else: + out["force"] = forces[0] + out.pop("forces", None) + if "force_region_mode" in out: + out["force_region_mode"] = str(out["force_region_mode"]) + if "global_loading" in out: + out["global_loading"] = bool(out["global_loading"]) + if "force_top_percent" in out: + out["force_top_percent"] = float(out["force_top_percent"]) + if "seat_height_min_ratio" in out: + out["seat_height_min_ratio"] = float(out["seat_height_min_ratio"]) + if "seat_height_max_ratio" in out: + out["seat_height_max_ratio"] = float(out["seat_height_max_ratio"]) + if "force_bbox" in out and isinstance(out["force_bbox"], (list, tuple)) and len(out["force_bbox"]) == 6: + out["force_bbox"] = [float(v) for v in out["force_bbox"]] + elif "force_bbox" in out: + out.pop("force_bbox", None) + if "force_bbox_ratio" in out and isinstance(out["force_bbox_ratio"], (list, tuple)) and len(out["force_bbox_ratio"]) == 6: + out["force_bbox_ratio"] = [float(v) for v in out["force_bbox_ratio"]] + elif "force_bbox_ratio" in out: + out.pop("force_bbox_ratio", None) + return out + + # Load force configuration from JSON, typically exported from the web UI. + force_config_loaded = False + force_config_error = None + force_entries = None + if args.force_config: + raw_force_config = args.force_config + candidates = [] + if os.path.isabs(raw_force_config): + candidates.append(raw_force_config) + else: + candidates.append(raw_force_config) + script_dir = os.path.dirname(os.path.abspath(__file__)) + candidates.append(os.path.join(script_dir, raw_force_config)) + candidates.append(os.path.join(os.path.dirname(script_dir), raw_force_config)) + force_config_path = next((p for p in candidates if os.path.exists(p)), None) + if force_config_path is None: + force_config_error = f"Path does not exist; tried: {candidates}" + else: + args.force_config = force_config_path + try: + with open(force_config_path, "r") as f: + force_cfg = json.load(f) + if isinstance(force_cfg, dict): + cfg_forces = _normalize_force_vectors(force_cfg.get("forces")) + if cfg_forces is not None: + args.force = cfg_forces + else: + cfg_force = _normalize_force_vectors(force_cfg.get("force")) + if cfg_force is not None: + args.force = cfg_force + elif "force" in force_cfg or "forces" in force_cfg: + force_config_error = "force/forcesinvalid format" + if "global_loading" in force_cfg: + args.global_loading = bool(force_cfg["global_loading"]) + if "force_region_mode" in force_cfg: + args.force_region_mode = str(force_cfg["force_region_mode"]) + if "force_top_percent" in force_cfg: + args.force_top_percent = float(force_cfg["force_top_percent"]) + if "seat_height_min_ratio" in force_cfg: + args.seat_height_min_ratio = float(force_cfg["seat_height_min_ratio"]) + if "seat_height_max_ratio" in force_cfg: + args.seat_height_max_ratio = float(force_cfg["seat_height_max_ratio"]) + if "force_bbox" in force_cfg: + args.force_bbox = force_cfg["force_bbox"] + if "force_bbox_ratio" in force_cfg: + args.force_bbox_ratio = force_cfg["force_bbox_ratio"] + if "force_entries" in force_cfg: + raw_entries = force_cfg["force_entries"] + if isinstance(raw_entries, list): + normalized_entries = [] + for entry in raw_entries: + norm_entry = _normalize_force_entry(entry) + if norm_entry is not None: + normalized_entries.append(norm_entry) + if normalized_entries: + force_entries = normalized_entries + else: + force_config_error = "force_entries has no valid entries" + else: + force_config_error = "force_entriesinvalid format" + force_config_loaded = True + else: + force_config_error = f"force_configis not a dict: {type(force_cfg)}" + except Exception as e: + force_config_error = f"read failed: {e}" + + # Configure logging. force=True ensures this replaces any prior setup. + os.makedirs(args.out_folder, exist_ok=True) + log_file = os.path.join(args.out_folder, "optimization.log") + + # Remove any existing handlers. + for handler in logging.root.handlers[:]: + logging.root.removeHandler(handler) + + # Reconfigure logging. + logging.basicConfig( + level=logging.INFO, + format='%(asctime)s - %(levelname)s - %(message)s', + handlers=[ + logging.FileHandler(log_file, mode='w'), # Rewrite the log on each run. + logging.StreamHandler() + ], + force=True # Python 3.8+: force a full reconfiguration. + ) + + logging.info(f"🔧 logging configuration completed") + logging.info(f" - log file: {log_file}") + logging.info(f" - output mode: file + console") + if args.force_config: + if force_config_loaded: + logging.info(" ✅ force_configloaded") + logging.info(f" - path: {args.force_config}") + logging.info(f" - forces: {args.force}") + if force_entries: + logging.info(f" - force_entries: {len(force_entries)}") + logging.info(f" - global_loading: {args.global_loading}") + logging.info(f" - force_region_mode: {args.force_region_mode}") + logging.info(f" - force_top_percent: {args.force_top_percent}") + logging.info(f" - seat_height_min_ratio: {args.seat_height_min_ratio}") + logging.info(f" - seat_height_max_ratio: {args.seat_height_max_ratio}") + logging.info(f" - force_bbox: {args.force_bbox}") + logging.info(f" - force_bbox_ratio: {args.force_bbox_ratio}") + if force_config_error: + logging.warning(f" ⚠️ force_configsome fields are invalid: {force_config_error}") + else: + logging.warning(f" ⚠️ force_configloadfailed: {force_config_error}") + + # In physics mode, derive num_steps from outer_cycles and phys_steps_per_cycle. + if args.use_physics: + outer_cycles = max(1, int(args.outer_cycles)) + phys_steps_per_cycle = max(1, int(args.phys_steps_per_cycle)) + derived_num_steps = outer_cycles * phys_steps_per_cycle + if args.num_steps != derived_num_steps: + logging.info( + f" - num_stepsautomatically set: {args.num_steps} → {derived_num_steps} " + f"(outer_cycles={outer_cycles}, phys_steps_per_cycle={phys_steps_per_cycle})" + ) + args.num_steps = derived_num_steps + + # ==================== Save run metadata ==================== + # 1. Save the command line. + command_file = os.path.join(args.out_folder, "run_command.txt") + try: + with open(command_file, 'w') as f: + f.write("=" * 80 + "\n") + f.write("Command used (Command Used)\n") + f.write("=" * 80 + "\n\n") + f.write("Full command:\n") + f.write("python " + " ".join(sys.argv) + "\n\n") + + f.write("=" * 80 + "\n") + f.write("Arguments (Arguments)\n") + f.write("=" * 80 + "\n\n") + for arg, value in vars(args).items(): + f.write(f"{arg}: {value}\n") + + f.write("\n" + "=" * 80 + "\n") + f.write("Environment (Environment)\n") + f.write("=" * 80 + "\n\n") + f.write(f"Python: {sys.version}\n") + f.write(f"PyTorch: {torch.__version__}\n") + f.write(f"CUDA Available: {torch.cuda.is_available()}\n") + if torch.cuda.is_available(): + f.write(f"CUDA Version: {torch.version.cuda}\n") + f.write(f"GPU Count: {torch.cuda.device_count()}\n") + + logging.info(f" - saved command used : {command_file}") + except Exception as e: + logging.warning(f" ⚠️ Save Command usedfailed: {e}") + + # 2. Save a copy of the current script. + script_backup = os.path.join(args.out_folder, "viewer_hunyuan_web_alternate.py") + try: + current_script = os.path.abspath(__file__) + shutil.copy2(current_script, script_backup) + logging.info(f" - saved script copy : {script_backup}") + except Exception as e: + logging.warning(f" ⚠️ Save failed to save script copy: {e}") + + # Load latents and conditioning data. + logging.info(f"\n📂 loading input data...") + logging.info(f" - Latents: {args.latents}") + + data = torch.load(args.latents, map_location='cpu') + + # Extract latents. + if isinstance(data, dict) and 'latents' in data: + latents = data['latents'] + else: + latents = data + + logging.info(f" ✅ Latents shape: {latents.shape}") + + # Check conditioning data (image_embeds or image). + need_encode_cond = False + image_embeds = None + image = None + + if isinstance(data, dict): + if 'image' in data: + # New format: only the image was saved, so we need to re-encode it. + logging.info(f" - detected image data; re-encoding as conditional embeds") + image_array = data['image'] + image = Image.fromarray(image_array) + need_encode_cond = True + elif 'image_embeds' in data: + # Legacy format: embeddings are already saved. + logging.info(f" - using the saved conditional embeds") + image_embeds = data['image_embeds'] + need_encode_cond = False + elif 'cond' in data: + # Alternate format using a saved cond dict. + logging.info(f" - using the saved cond") + image_embeds = data['cond'] + need_encode_cond = False + else: + raise ValueError("latents.ptis missingimage, image_embedsor cond data") + else: + raise ValueError("latentsmust be a dictionary containing'latents'andconditioninformation dict") + + if image_embeds is not None: + if isinstance(image_embeds, dict): + logging.info(f" ✅ Cond keys: {list(image_embeds.keys())}") + else: + logging.info(f" ✅ Image embeds shape: {image_embeds.shape}") + + # Load models. + logging.info(f"\n🔧 loading Hunyuan3Dmodel...") + vae, flow_model, scheduler = load_hunyuan_models( + model_path=args.model_path, + subfolder=args.subfolder, + use_safetensors=args.use_safetensors + ) + + # ==================== Encode conditioning data if needed ==================== + if need_encode_cond: + logging.info("🎨 encoding conditional embeds from the image...") + + # Reload the full pipeline for condition encoding. + from hy3dgen.shapegen import Hunyuan3DDiTFlowMatchingPipeline + + pipeline = Hunyuan3DDiTFlowMatchingPipeline.from_pretrained( + args.model_path, + subfolder=args.subfolder, + torch_dtype=torch.float16, + use_safetensors=args.use_safetensors + ) + pipeline.to('cuda') + + with torch.no_grad(): + # Prepare the image. + cond_inputs = pipeline.prepare_image(image) + image_tensor = cond_inputs.pop('image') + + # Enable CFG so the encoded condition contains both branches. + cond_dict = pipeline.encode_cond( + image=image_tensor, + additional_cond_inputs=cond_inputs, + do_classifier_free_guidance=True, # Enable CFG. + dual_guidance=False, + ) + + # Save the condition dict. + image_embeds = cond_dict + + logging.info(f" ✅ condition encoding completed (CFG mode) ") + logging.info(f" - Cond keys: {list(cond_dict.keys()) if isinstance(cond_dict, dict) else 'tensor'}") + + # Resolve the compliance threshold. + if args.compliance_threshold is None: + compliance_threshold = 200.0 + logging.info(f" using the default compliance threshold: {compliance_threshold}") + else: + compliance_threshold = args.compliance_threshold + logging.info(f" using the custom compliance threshold: {compliance_threshold}") + + target_z0_update_interval = max(1, int(args.phys_steps_per_cycle)) + forces = None + normalized_forces = _normalize_force_vectors(args.force) + if normalized_forces: + forces = [{'external_force': vec} for vec in normalized_forces] + elif args.force is not None: + logging.warning(f" ⚠️ invalid external force vector; ignoring: {args.force}") + # Build the optimization config. + config = OptimizationConfig( + num_steps=args.num_steps, + lr=args.lr, + sds_timestep=args.sds_timestep, + sds_weight=args.sds_weight if args.use_physics else 1.0, # Keep backward compatibility. + sds_weight_start=args.sds_weight_start, # Dynamic weight schedule start. + sds_weight_end=args.sds_weight_end, # Dynamic weight schedule end. + guidance_scale=args.guidance_scale, # CFG guidance scale. + sds_projection_max_rel=args.sds_projection_max_rel, + sds_use_uncond=args.sds_use_uncond, + sds_target_z0_update_interval=target_z0_update_interval, + sds_target_z0_ema_beta=args.sds_target_z0_ema_beta, + deformed_mesh_interval=args.deformed_mesh_interval, + deformed_mesh_disp_min=args.deformed_mesh_disp_min, + deformed_mesh_disp_max=args.deformed_mesh_disp_max, + use_sgd=args.use_sgd, + grad_clip_enabled=args.grad_clip_enabled, + # Physical parameters. + res=args.res, + lagrange_max=args.lagrange_max, + compliance_threshold=compliance_threshold, + alm_rho_init=args.alm_rho_init, + alm_rho_max=args.alm_rho_max, + alm_rho_increase_factor=args.alm_rho_increase_factor, + alm_rho_increase_patience=args.alm_rho_increase_patience, + alm_scale_guard_ratio=args.alm_scale_guard_ratio, + youngs_modulus_scale=args.youngs_modulus_scale, + # Topology control. + one_cc_only=not args.keep_all_components, + re_extract_interval=args.re_extract_interval, + # Loads and load-region settings. + forces=forces, + force_entries=force_entries, + use_local_loading=not args.global_loading, + seat_height_min_ratio=args.seat_height_min_ratio, + seat_height_max_ratio=args.seat_height_max_ratio, + force_region_mode=args.force_region_mode, + force_top_percent=args.force_top_percent, + force_bbox=args.force_bbox, + force_bbox_ratio=args.force_bbox_ratio, + # Output path. + out_folder=args.out_folder, + ) + + # Create the optimizer. + optimizer = HunyuanSDSOptimizer( + latents=latents, + cond=image_embeds, + vae=vae, + flow_model=flow_model, + scheduler=scheduler, + config=config, + device='cuda' + ) + + # Prepare physics if requested. + final_step = args.num_steps + if args.use_physics: + logging.info(f"\n🔬 enable physics optimization mode") + logging.info(f" - Voxel resolution: {args.res}") + logging.info(f" - physics steps/cycle: {args.phys_steps_per_cycle}, outer cycles: {args.outer_cycles}") + logging.info(f" - projection noise: sds_timestep={args.sds_timestep}") + logging.info(f" - target_z0update interval: {target_z0_update_interval} (consistent with phys_steps_per_cycle)") + logging.info(f" - LagrangeMax: {args.lagrange_max}") + + try: + optimizer.extract_solid(step=-1) # Initial extraction. + optimizer.prepare_physical_simulation() + logging.info(f" ✅ physics simulationInitializationsucceeded") + except Exception as e: + logging.warning(f" ⚠️ warning: initial mesh extraction failed (this is normal, optimizationbe repaired during the optimization process) ") + logging.warning(f" error information: {str(e)[:100]}") + # Continue anyway: the key physical state is the occupancy field, not the mesh. + else: + logging.info(f"\n🎨 using pure SDS optimization mode") + + # Optimization loop. + optimization_mode = "Alternating Phys/Projection" if args.use_physics else "Pure SDS" + total_steps_hint = ( + int(args.outer_cycles) * (int(args.phys_steps_per_cycle) + 1) + if args.use_physics + else args.num_steps + ) + logging.info(f"\n🚀 start{optimization_mode}optimization ({total_steps_hint} steps)...") + + instance = args.latents.split("/")[-2] + print(f"Instance courante : {instance}") + + if args.use_physics: + lagrange_multiplier = 0.0 + rho = config.alm_rho_init + violation_count = 0 + + # Automatically set the compliance threshold when needed. + if config.compliance_threshold is None or config.compliance_threshold == 200.0: + logging.info(f" 📊 computation initial compliance threshold value...") + + max_retries = 10 + for attempt in range(max_retries): + # 1. Calcul de la compliance avec la force actuelle + initial_compliance, _, _, _ = optimizer.training_step( + 0, 0.0, 0.0, use_sds=False + ) + + logging.info(f" -> Tentative {attempt + 1} | Compliance initiale : {initial_compliance:.4e}") + + # 2. Vérification + if initial_compliance >= 5.0: + logging.info(" ✅ Compliance initiale suffisante. Suite de l'optimisation...") + break # On sort de la boucle, la force est bonne. + + logging.warning(" ⚠️ Compliance trop faible (< 5). Augmentation de la force Y...") + + # 3. Récupération et modification de la force dans le fichier JSON + config_path = f"output_force/hunyuan_gen/table_ago/{instance}/force_config.json" + try: + if os.path.exists(config_path): + with open(config_path, "r") as file: + force_data = json.load(file) + else: + logging.warning(f"Fichier {config_path} introuvable, création d'un dictionnaire par défaut.") + # Fallback au cas où le fichier n'existe pas encore + force_data = {"force": [0.0, -100000.0, 0.0]} + + old_force_y = force_data["force"][1] + force_data["force"][1] = old_force_y * 2 + + os.makedirs(os.path.dirname(config_path), exist_ok=True) + with open(config_path, "w") as file: + json.dump(force_data, file, indent=4) + + logging.info(f" 🔄 Force multipliée par 2 ({old_force_y} -> {force_data['force'][1]}) et sauvegardée.") + + # 4. Mise à jour de la configuration de l'optimizer SANS tout recharger + optimizer.config.forces = [{'external_force': force_data["force"]}] + + # 5. On demande au solveur FEM de redistribuer ces nouvelles forces sur les noeuds + optimizer.prepare_physical_simulation() + + except Exception as e: + logging.error(f"Erreur lors de la mise à jour de la force interne : {e}") + break # En cas d'erreur inattendue, on casse la boucle pour éviter de tourner à l'infini + else: + logging.error(f"❌ Impossible d'atteindre une compliance > 5 après {max_retries} tentatives.") + sys.exit(1) + + # --- ICI tu peux placer la suite de ton code d'optimisation --- + # La force est désormais réglée correctement dans l'optimizer. + +if __name__ == "__main__": + main() diff --git a/cfd_workflow_20261012/_seiler_ref/physiopt_new_scripts/viewer_hunyuan_web_alternate.py b/cfd_workflow_20261012/_seiler_ref/physiopt_new_scripts/viewer_hunyuan_web_alternate.py new file mode 100644 index 0000000000000000000000000000000000000000..09d56926a5a1215fffa2561e3455bfefe848f81e --- /dev/null +++ b/cfd_workflow_20261012/_seiler_ref/physiopt_new_scripts/viewer_hunyuan_web_alternate.py @@ -0,0 +1,3915 @@ +""" +Hunyuan3D-2.1 physical optimization + shape-prior optimization. +""" + +import os +import copy +# os.environ['TORCH_HOME'] = '/mnt/cvlab/scratch/cvlab/home/hantzhan/.torch' +import sys +import shutil + +# Add Hunyuan3D-2.1 to the Python path. +hunyuan_path = os.path.abspath(os.path.join(os.path.dirname(__file__), "../../Hunyuan3D-2.1")) +# Note: logging is not imported yet, so use print here if needed. +# Basic logging is configured near the top of the file after import. + +sys.path.append("..") + +import torch +import torch.nn.functional as F +import trimesh +import numpy as np +from PIL import Image +import argparse +import json +from typing import Tuple, Optional, List +from dataclasses import dataclass, field +import traceback +import logging + +# Configure logging here only conceptually; main() will reconfigure it to +# log to both the console and a file. +# Do not call basicConfig here so the main() configuration remains effective. +# logging.basicConfig(level=logging.INFO, format='%(levelname)s: %(message)s') + +# Physical-simulation imports. +PHYSIOPT_AVAILABLE = False +try: + from physiopt.utils.phys_utils import generate_hex + from physiopt.utils.grid_utils import filter_one_component + from physiopt.opt.field import occ_kernel + from physiopt.opt.forces import ForceConfig + PHYSIOPT_AVAILABLE = True + logging.info("✅ physics simulation moduleimportsucceeded") +except ImportError as e: + logging.warning(f"⚠️ warning: physics simulation moduleimportfailed: {e}") + logging.warning(" if you only run SDS optimization, you can ignore this warning") + PHYSIOPT_AVAILABLE = False + + def generate_hex(res, limits=[(-0.5, 0.5), (-0.5, 0.5), (-0.5, 0.5)], device="cuda", return_coords=False): + """Placeholder for hexahedral grid generation. + + Returns tensors in the same format as the real function. + """ + logging.warning(f"⚠️ warning: using placeholdergenerate_hex, please install the physiopt module") + return None, None + + def filter_one_component(mask, res): + """Placeholder for connected-component filtering. + + Args: + mask: Element mask [res*res*res] + res: Voxel resolution + """ + return mask + + def occ_kernel(sdf, res, beta): + """Placeholder for SDF-to-occupancy conversion.""" + return torch.sigmoid(-sdf * beta) + +# Warp physics-engine import. +try: + import warp as wp + wp.init() + WARP_AVAILABLE = True + logging.info("✅ Warp physics engineInitializationsucceeded") +except ImportError: + WARP_AVAILABLE = False + logging.warning("⚠️ warning: Warp physics enginenot installed, physics simulationwill be unavailable") + logging.warning(" Install: pip install warp-lang") + +# Hunyuan3D imports +try: + from hy3dgen.shapegen.models.autoencoders import ShapeVAE + from hy3dgen.shapegen import Hunyuan3DDiTFlowMatchingPipeline + from hy3dgen.shapegen.pipelines import export_to_trimesh +except ImportError as e: + logging.error(f"❌ failed to import Hunyuan3D modules: {e}") + logging.error(f"\nplease follow these steps to set upHunyuan3D-2.1:") + logging.error(f"1. cd {os.path.dirname(hunyuan_path)}") + logging.error(f"2. git clone https://github.com/Tencent/Hunyuan3D-2.git Hunyuan3D-2.1") + logging.error(f"3. cd Hunyuan3D-2.1") + logging.error(f"4. pip install -e .") + sys.exit(1) + + +@dataclass +class OptimizationConfig: + """Optimization config for physics + SDS.""" + # Physical-simulation parameters. + res: int = 32 # Voxel resolution (16/32/64), matching the reference code. + # Restored physical settings from the stable v90 configuration. + p_exponent: float = 1.0 # SIMP penalty exponent. + alpha_min: float = 0.01 # Minimum density, restored from v90. + volume_term: float = 1000000.0 # Volume-constraint weight, currently disabled. + occ_sdf_beta: float = 2.0 # Sigmoid-kernel beta, restored from v90. + one_cc_only: bool = False # Keep only the largest connected component. + + # SDS parameters. + # Use dynamic SDS weights so physics dominates early and aesthetics enters later. + sds_timestep: float = 0.1 # SDS timestep; smaller values preserve more detail. + sds_weight: float = 1.0 # SDS weight relative to the physical gradient. + sds_weight_start: float = 1e5 # 0.1 # 0.0001 # Initial SDS weight. + sds_weight_end: float = 1e5 # 1.0 # 0.001 # Final SDS weight. + guidance_scale: float = 7.5 # Standard CFG guidance scale for stronger image conditioning. + sds_projection_max_rel: float = 0.0 # Max relative target_z0 projection offset (0 = unlimited). + sds_use_uncond: bool = False # Use the unconditional branch when guidance_scale <= 1. + sds_target_z0_update_interval: int = 10 # target_z0 update interval; tied to phys_steps_per_cycle. + sds_target_z0_ema_beta: float = 0.9 # EMA smoothing coefficient; larger is smoother. + + lagrange_max: float = 50.0 # Max lambda. + compliance_threshold: float = 200.0 # Compliance threshold used for normalization. + alm_rho_init: float = 1.0 # Initial rho. + alm_rho_max: float = 1000.0 # Max rho. + alm_rho_increase_factor: float = 2.0 # Rho growth factor. + alm_rho_increase_patience: int = 5 # Number of consecutive violations before increasing rho. + alm_scale_guard_ratio: float = 0.95 # ALM scaling guard to stay below gradient clipping. + + # Topology control. + re_extract_interval: int = 5 # Re-extract the solid every N steps; 0 disables it. + + # Material properties. Values are aligned with the reference setup. + # youngs_modulus is already specified directly in Pa, so no unit conversion is needed. + youngs_modulus: float = 5e8 # 1e9 # Pa (= 1 GPa), restored from v90. + youngs_modulus_scale: float = 2.0 # Final multiplier after the last projection in alternating mode. + poissons_ratio: float = 0.3 # Poisson's ratio (dimensionless). + density: float = 650.0 # Material density (kg/m^3). + + ## Wood + # youngs_modulus: float = 9e9 # Pa (= 1 GPa), aligned with the reference code. + # poissons_ratio: float = 0.35 # Poisson's ratio (dimensionless), matches the reference. + # density: float = 400.0 # Material density (kg/m^3), matches the reference. + + ## PVG + # youngs_modulus: float = 3.25e9 # Pa (= 1 GPa), aligned with the reference code. + # poissons_ratio: float = 0.38 # Poisson's ratio (dimensionless), matches the reference. + # density: float = 1380.0 # Material density (kg/m^3), matches the reference. + + # Load conditions; supports multiple forces like config.json. + forces: List = None # List of ForceConfig objects. + # Multiple localized load entries, each with its own force and region settings. + force_entries: Optional[List[dict]] = None + + # Local-loading settings, e.g. to mimic a person sitting on a chair. + use_local_loading: bool = True # Use local loading instead of global uniform loading. + seat_height_min_ratio: float = 0.3 # Lower bound of the seat band as a height ratio. + seat_height_max_ratio: float = 0.5 # Upper bound of the seat band as a height ratio. + force_region_mode: str = "top_percent" # Load-region mode: top_percent / height_ratio / bbox. + force_top_percent: float = 0.05 # In top_percent mode, use the highest-Y fraction of nodes. + force_bbox: Optional[List[float]] = None # bbox mode: x_min x_max y_min y_max z_min z_max. + force_bbox_ratio: Optional[List[float]] = None # bbox mode in normalized node bounds [0, 1]. + + # Optimization parameters, restored from the stable v90 configuration. + lr: float = 0.001 # Learning rate. + num_steps: int = 100 # Number of optimization steps. + use_sgd: bool = False # Use SGD instead of Adam. + grad_clip_enabled: bool = False # Enable gradient clipping; off by default. + save_every: int = 10 # Save interval in steps. + deformed_mesh_interval: int = 10 # Save interval for deformed meshes. + deformed_mesh_disp_min: float = 0.0 # Minimum displacement for deformed-mesh color mapping. + deformed_mesh_disp_max: float = 0.2 # Maximum displacement for deformed-mesh color mapping. + + # Output path. + out_folder: str = "../out/hunyuan_opt" # Output directory. + + # Device. + device: str = "cuda" # Compute device. + + # Whether to enable physics optimization. + use_physics: bool = True # Enable physical-constraint optimization. + + def __post_init__(self): + # Set default loads in the Hunyuan Y-up coordinate system: + # X = right, Y = up, Z = forward. + if self.forces is None: + try: + from physiopt.opt.forces import ForceConfig + self.forces = [ + ForceConfig(external_force=[0.0, -100000.0, 0.0]) # 100 kN downward along Y. + # ForceConfig(external_force=[0.0, 0.0, -500.0]), # 500 N backward along Z. + ] + except ImportError: + # Fallback format if physiopt is unavailable; keep only the force vectors. + self.forces = [ + {'external_force': [0.0, -100000.0, 0.0]} # 100 kN downward along Y. + # {'external_force': [0.0, 0.0, -500.0]}, # Backward along Z. + ] + + +class HunyuanSDSOptimizer: + """Hunyuan3D SDS optimizer with differentiable physics support.""" + + def __init__( + self, + latents: torch.Tensor, + cond: dict, # Condition dict containing positive and negative branches. + vae: ShapeVAE, + flow_model: torch.nn.Module, + config: OptimizationConfig, + scheduler=None, + device: str = 'cuda' + ): + """ + Args: + latents: Initial latent tokens [1, N, D]. + cond: Condition dict returned by pipeline.encode_cond. + vae: Hunyuan3D VAE model. + flow_model: Hunyuan3D Flow Matching model. + scheduler: Hunyuan3D Flow Matching scheduler used to align target_z0. + config: Optimization config. + device: Compute device. + """ + self.device = device + self.config = config + + # Models. + self.vae = vae.to(device).eval() + self.flow_model = flow_model.to(device).eval() + if scheduler is not None: + try: + self.sds_scheduler = copy.deepcopy(scheduler) + except Exception: + self.sds_scheduler = scheduler + logging.warning("⚠️ Scheduler deepcopyfailed, already fallback to originalscheduler") + else: + self.sds_scheduler = None + + # Create a differentiable SDF query helper. + from hy3dgen.shapegen.models.autoencoders.differentiable_sdf_query import DifferentiableSDFQuery + self.sdf_query = DifferentiableSDFQuery( + vae=self.vae, + bounds=0.8, # Our coordinate range is [-0.8, 0.8]. + chunk_size=8192 # Batch query size. + ) + logging.info(f"✅ created differentiable SDF query helper") + + # Latent tokens are the variables being optimized. + # Use float32 instead of float16 to avoid numeric overflow. + self.latents = latents.clone().to(device).to(torch.float32).requires_grad_(True) + + logging.info(f" ⚠️ note: Latentsfloat32FP16value") + + # Move conditioning data to the target device recursively. + def to_device_recursive(obj): + if isinstance(obj, torch.Tensor): + return obj.to(device) + elif isinstance(obj, dict): + return {k: to_device_recursive(v) for k, v in obj.items()} + elif isinstance(obj, (list, tuple)): + return type(obj)(to_device_recursive(item) for item in obj) + else: + return obj + + self.cond = to_device_recursive(cond) + self._cond_warned_cfg_repeat = False + self._cond_warned_nocfg_slice = False + + # Optimizer selection. + if config.use_sgd: + self.optimizer = torch.optim.SGD([self.latents], lr=config.lr, momentum=0.0) + opt_name = "SGD" + else: + self.optimizer = torch.optim.Adam([self.latents], lr=config.lr, betas=(0.9, 0.999), eps=1e-8) + opt_name = "Adam" + + logging.info(f"✅ HunyuanSDSOptimizerInitializationcompleted (with differentiable physics support) ") + logging.info(f" - Latents shape: {self.latents.shape}") + logging.info(f" - Latents dtype: {self.latents.dtype} (optimized in float32)") + logging.info(f" - Device: {device}") + logging.info(f" - Optimizer: {opt_name}") + logging.info(f" - Learning rate: {config.lr}") + + # target_z0 EMA cache. + self.target_z0_ema = None + self.target_z0_last_velocity = None + self.target_z0_last_update = None + + def get_field(self, x: torch.Tensor, latents: torch.Tensor = None) -> torch.Tensor: + """Differentiable SDF query through the VAE geo_decoder. + + Args: + x: Query points [N, 3] in the range [-0.8, 0.8]^3. + latents: Optional latent tokens; defaults to self.latents. + + Returns: + sdf: SDF values [N] with gradient support. + """ + if latents is None: + latents = self.latents + + # Match the official pipeline: divide by scale_factor before decoding. + scale_factor = getattr(self.vae, "scale_factor", 1.0) + latents_scaled = latents / scale_factor + + # Convert to FP16 because the VAE expects FP16 inputs. + latents_fp16 = latents_scaled.to(torch.float16) + + # Decode with the VAE decoder while preserving gradients. + decoded_latents = self.vae.decode(latents_fp16) + + # Query the SDF through the differentiable helper. + # sdf_query calls geo_decoder internally, so keep FP16 to match VAE weights. + sdf = self.sdf_query( + decoded_latents, # Keep FP16 and let sdf_query handle the rest. + x, + return_occupancy=False # Return SDF instead of occupancy. + ) # [N] + + return sdf + + def _cond_batch_size(self, cond) -> Optional[int]: + if isinstance(cond, torch.Tensor): + return cond.shape[0] if cond.dim() >= 1 else None + if isinstance(cond, dict): + for v in cond.values(): + bsz = self._cond_batch_size(v) + if bsz is not None: + return bsz + if isinstance(cond, (list, tuple)): + for v in cond: + bsz = self._cond_batch_size(v) + if bsz is not None: + return bsz + return None + + def _cond_slice(self, cond, batch_slice: slice): + if isinstance(cond, torch.Tensor): + if cond.dim() >= 1 and cond.shape[0] >= batch_slice.stop: + return cond[batch_slice] + return cond + if isinstance(cond, dict): + return {k: self._cond_slice(v, batch_slice) for k, v in cond.items()} + if isinstance(cond, (list, tuple)): + return type(cond)(self._cond_slice(v, batch_slice) for v in cond) + return cond + + def _cond_repeat(self, cond, repeats: int): + if isinstance(cond, torch.Tensor): + if cond.dim() >= 1: + rep_shape = (repeats,) + (1,) * (cond.dim() - 1) + return cond.repeat(rep_shape) + return cond + if isinstance(cond, dict): + return {k: self._cond_repeat(v, repeats) for k, v in cond.items()} + if isinstance(cond, (list, tuple)): + return type(cond)(self._cond_repeat(v, repeats) for v in cond) + return cond + + def _get_cond_for_guidance(self, use_cfg: bool): + cond = self.cond + bsz = self._cond_batch_size(cond) + if use_cfg: + if bsz == 1: + if not self._cond_warned_cfg_repeat: + logging.warning("⚠️ guidance_scale>1 cond batch=1, already condCFG") + self._cond_warned_cfg_repeat = True + return self._cond_repeat(cond, 2) + if bsz is not None and bsz > 2: + return self._cond_slice(cond, slice(0, 2)) + return cond + # no-CFG + if bsz is not None and bsz >= 2: + if self.config.sds_use_uncond: + if not self._cond_warned_nocfg_slice: + logging.info("ℹ️ guidance_scale<=1, useno conditioncond[1:2]") + self._cond_warned_nocfg_slice = True + return self._cond_slice(cond, slice(1, 2)) + if not self._cond_warned_nocfg_slice: + logging.info("ℹ️ guidance_scale<=1, already usecond[0:1]batch") + self._cond_warned_nocfg_slice = True + return self._cond_slice(cond, slice(0, 1)) + if self.config.sds_use_uncond and bsz == 1 and not self._cond_warned_nocfg_slice: + logging.warning("⚠️ sds_use_uncond=1 cond batch=1, already fallback to conditself") + self._cond_warned_nocfg_slice = True + return cond + + def latents_to_mesh(self, latents: torch.Tensor, octree_res: int = 128) -> Optional[trimesh.Trimesh]: + """Decode latent tokens into a mesh. + + Args: + latents: Latent tokens [1, N, D] (float32). + octree_res: Octree resolution. 128 is faster; 256 is higher quality. + + Returns: + A trimesh.Trimesh object, or None on failure. + """ + with torch.no_grad(): + # Skip invalid latent tensors early. + if torch.isnan(latents).any() or torch.isinf(latents).any(): + logging.warning(" latents_to_mesh: latentscontains NaN or Inf, skip") + return None + + # Match the official pipeline by dividing by scale_factor first. + scale_factor = getattr(self.vae, "scale_factor", 1.0) + latents_scaled = latents / scale_factor + + # Decode in FP16 because the VAE expects FP16 inputs. + latents_fp16 = latents_scaled.to(torch.float16) + + try: + # VAE decode. + decoded_latents = self.vae.decode(latents_fp16) + + # Skip invalid decoded latents. + if torch.isnan(decoded_latents).any() or torch.isinf(decoded_latents).any(): + logging.warning(" latents_to_mesh: decoded_latentscontains NaN or Inf, skip") + return None + except Exception as e: + logging.debug(f" latents_to_mesh: VAE decodingfailed: {e}") + return None + + # Use an adaptive mc_level fallback if the default level fails. + try: + # First try the standard mc_level=0.0. + mesh = self.vae.latents2mesh( + decoded_latents, + output_type='trimesh', + bounds=1.01, + mc_level=0.0, + num_chunks=20000, + octree_resolution=octree_res, + mc_algo='mc', + enable_pbar=False + ) + mesh = export_to_trimesh(mesh)[0] + return mesh + + except ValueError as e: + error_msg = str(e) + if "Surface level must be within volume data range" in error_msg: + # Estimate a better mc_level from sampled SDF statistics. + logging.debug(f" latents_to_mesh: mc_level=0.0 failed, try an adaptive level...") + + try: + # Sample a coarse grid to estimate the SDF range. + grid_size = 32 + x = torch.linspace(-1.0, 1.0, grid_size, device=decoded_latents.device) + y = torch.linspace(-1.0, 1.0, grid_size, device=decoded_latents.device) + z = torch.linspace(-1.0, 1.0, grid_size, device=decoded_latents.device) + xx, yy, zz = torch.meshgrid(x, y, z, indexing='ij') + points = torch.stack([xx, yy, zz], dim=-1).reshape(-1, 3) # [N, 3] + + # query the SDF values. + sdf_values = self.get_field(points, latents=latents) + + # Compute basic statistics. + sdf_median = torch.median(sdf_values).item() + sdf_min = sdf_values.min().item() + sdf_max = sdf_values.max().item() + sdf_mean = sdf_values.mean().item() + + logging.debug(f" SDFstatistics: min={sdf_min:.4f}, max={sdf_max:.4f}, median={sdf_median:.4f}, mean={sdf_mean:.4f}") + + # No clear surface can be extracted if the SDF range is too small. + if abs(sdf_max - sdf_min) < 1e-4: + logging.debug(f" SDFrange is too small to extract a surface") + return None + + # Try several plausible candidate levels. + candidate_levels = [ + sdf_median, # Median. + sdf_mean, # Mean. + (sdf_min + sdf_max) / 2, # Midpoint of the range. + sdf_min + (sdf_max - sdf_min) * 0.3, # 30% point. + sdf_min + (sdf_max - sdf_min) * 0.7, # 70% point. + ] + + # Clamp all levels to the valid range. + valid_levels = [ + max(sdf_min + 0.001, min(sdf_max - 0.001, level)) + for level in candidate_levels + ] + + # Remove duplicates. + valid_levels = list(set(valid_levels)) + + logging.debug(f" try {len(valid_levels)} candidate levels: {[f'{l:.4f}' for l in valid_levels[:3]]}...") + + # Try each candidate level in order. + for i, adaptive_level in enumerate(valid_levels): + try: + mesh = self.vae.latents2mesh( + decoded_latents, + output_type='trimesh', + bounds=1.01, + mc_level=adaptive_level, + num_chunks=20000, + octree_resolution=octree_res, + mc_algo='mc', + enable_pbar=False + ) + mesh = export_to_trimesh(mesh)[0] + logging.info(f" ✅ uselevelsucceeded (level={adaptive_level:.4f}, attempt {i+1})") + return mesh + except (ValueError, RuntimeError) as level_error: + # Try the next level if this one fails. + if i < len(valid_levels) - 1: + continue + else: + # All candidate levels failed. + logging.debug(f" all candidate levels failed") + return None + + # No candidate succeeded. + return None + + except Exception as adaptive_error: + logging.debug(f" adaptive extraction failed: {type(adaptive_error).__name__}: {str(adaptive_error)[:50]}") + return None + + elif "No surface found" in error_msg: + logging.debug(f" latents_to_mesh: Marching cubesno surface found, skip") + return None + else: + logging.warning(f" latents_to_mesh: unknown ValueError: {error_msg}") + return None + + except RuntimeError as e: + error_msg = str(e) + if "No surface found" in error_msg or "Surface level" in error_msg: + logging.debug(f" latents_to_mesh: Marching cubesfailed, skip") + return None + else: + logging.warning(f" latents_to_mesh: RuntimeError: {error_msg}") + return None + + except Exception as e: + # Catch any other unexpected failure. + logging.warning(f" latents_to_mesh: unexpected exception: {type(e).__name__}: {e}") + return None + + def _filter_floating_components(self, mesh: trimesh.Trimesh) -> trimesh.Trimesh: + """Remove small floating fragments and keep only the largest component.""" + try: + components = mesh.split(only_watertight=False) + if len(components) <= 1: + return mesh + + face_counts = [len(comp.faces) for comp in components] + max_idx = int(np.argmax(face_counts)) + filtered = components[max_idx] + dropped = len(components) - 1 + + logging.info(f" 🧹 filter floating fragments: kept{len(filtered.faces)} faces, discarded{dropped} small components") + return filtered + except Exception as e: + logging.warning(f" failed to filter floating fragments: {type(e).__name__}: {str(e)[:100]}") + return mesh + + def _sample_displacement_to_vertices( + self, + vertices: np.ndarray, + nodes: np.ndarray, + displacement: np.ndarray, + ) -> np.ndarray: + """Sample the voxel-node displacement field onto mesh vertices by nearest neighbor.""" + try: + from scipy.spatial import cKDTree + tree = cKDTree(nodes) + _, idx = tree.query(vertices, k=1) + return displacement[idx] + except Exception as e: + try: + from sklearn.neighbors import NearestNeighbors + nn = NearestNeighbors(n_neighbors=1, algorithm="auto") + nn.fit(nodes) + idx = nn.kneighbors(vertices, return_distance=False).squeeze(1) + return displacement[idx] + except Exception as e2: + logging.warning(f" displacement sampling failed, fallback to zero displacement: {type(e).__name__}: {str(e)[:100]}") + logging.debug(f" secondaryError: {type(e2).__name__}: {str(e2)[:100]}") + return np.zeros_like(vertices) + + def _normalize_displacement_magnitude( + self, disp_mag: np.ndarray + ) -> Tuple[np.ndarray, float, float, bool]: + """Normalize displacement magnitude, optionally with a fixed range.""" + mag_max_cfg = getattr(self.config, "deformed_mesh_disp_max", None) + mag_min_cfg = getattr(self.config, "deformed_mesh_disp_min", None) + use_fixed = mag_max_cfg is not None and mag_max_cfg > 0.0 + if use_fixed: + mag_min = 0.0 if mag_min_cfg is None else float(mag_min_cfg) + mag_max = float(mag_max_cfg) + if mag_max <= mag_min: + use_fixed = False + if not use_fixed: + mag_min = float(disp_mag.min()) + mag_max = float(disp_mag.max()) + denom = max(1e-12, mag_max - mag_min) + norm = (disp_mag - mag_min) / denom + if use_fixed: + norm = np.clip(norm, 0.0, 1.0) + return norm, mag_min, mag_max, use_fixed + + def _make_displacement_colors(self, displacement: np.ndarray) -> np.ndarray: + """Map displacement magnitude to vertex colors (blue -> red).""" + disp_mag = np.linalg.norm(displacement, axis=1) + norm, _, _, _ = self._normalize_displacement_magnitude(disp_mag) + colors = np.stack([norm, np.zeros_like(norm), 1.0 - norm], axis=1) + return (colors * 255).astype(np.uint8) + + def _log_physical_quantities( + self, + u: torch.Tensor, + sigma: Optional[torch.Tensor], + ) -> None: + """Log displacement and von Mises stress statistics.""" + with torch.no_grad(): + u_max = None + u_avg = None + try: + u_mag = torch.norm(u, dim=1) + u_max = u_mag.max().item() + u_avg = u_mag.mean().item() + except Exception as e: + logging.warning( + f" ⚠️ displacement statistics failed: {type(e).__name__}: {str(e)[:100]}" + ) + + sigma_vm_max = None + sigma_vm_avg = None + if sigma is not None: + try: + if sigma.dim() == 2 and sigma.shape[1] >= 6: + s_xx = sigma[:, 0] + s_yy = sigma[:, 1] + s_zz = sigma[:, 2] + s_yz = sigma[:, 3] + s_xz = sigma[:, 4] + s_xy = sigma[:, 5] + mises_sq = 0.5 * ( + (s_xx - s_yy) ** 2 + + (s_yy - s_zz) ** 2 + + (s_zz - s_xx) ** 2 + + 6.0 * (s_xy ** 2 + s_yz ** 2 + s_xz ** 2) + ) + mises = torch.sqrt(torch.clamp(mises_sq, min=0.0)) + sigma_vm_max = mises.max().item() + sigma_vm_avg = mises.mean().item() + else: + logging.warning( + f" ⚠️ sigmashape does not match expectations, skip von Mises statistics: {tuple(sigma.shape)}" + ) + except Exception as e: + logging.warning( + f" ⚠️ von Mises statistics failed: {type(e).__name__}: {str(e)[:100]}" + ) + + if u_max is not None and u_avg is not None: + if sigma_vm_max is not None and sigma_vm_avg is not None: + logging.info( + f" physical metrics: u_max={u_max:.3e}, u_avg={u_avg:.3e}, " + f"sigma_vm_max={sigma_vm_max:.3e}, sigma_vm_avg={sigma_vm_avg:.3e}" + ) + else: + logging.info( + f" physical metrics: u_max={u_max:.3e}, u_avg={u_avg:.3e}" + ) + + def backward_step(self, sensitivity_density: torch.Tensor): + """Backpropagate with VJP, aligned with the reference code. + + Reference: viewer_deepsdf.py Line 148-183. + This uses torch.autograd.functional.vjp to propagate sensitivity to latents. + """ + def f(latents: torch.Tensor): + """ + Compute occupancy from a given latent tensor. + Aligned with viewer_deepsdf.py Line 155-173. + """ + # Query the SDF. + sdf = self.get_field(self.nodes, latents) + + # SDF → occupancy + from physiopt.opt.field import occ_kernel + occ = occ_kernel(sdf, self.config.res, self.config.occ_sdf_beta) + + # Element occupancy is the average over the 8 nodes. + occ_elem = occ[self.elements].mean(1) + + # Clamp by alpha_min if requested. + if self.config.alpha_min > 0.0: + occ_elem = torch.clamp(occ_elem, self.config.alpha_min) + + return occ_elem + + # VJP computations d occ / d latents^T times the sensitivity vector. + # Aligned with viewer_deepsdf.py Line 175-180. + try: + grad_latent = torch.autograd.functional.vjp( + f, + self.latents.clone().requires_grad_(True), + sensitivity_density, + )[1] + + # Validate the returned gradient. + if grad_latent is None: + logging.error(" ❌ VJP returned None!") + return + + grad_norm = torch.norm(grad_latent).item() + logging.info(f" VJP gradient: norm={grad_norm:.2e}") + + # Assign the gradient manually, matching the reference implementation. + self.latents.grad = grad_latent + + except Exception as e: + logging.error(f" ❌ VJP failed: {e}") + import traceback + traceback.print_exc() + + def prepare_physical_simulation(self): + """Prepare the physical simulation and FEM solver state. + + Initialization includes: + 1. Material properties + 2. Boundary conditions + 3. External forces + """ + if not WARP_AVAILABLE: + logging.warning("Warpnot installed, skipphysics simulation preparation") + return + + if not hasattr(self, 'nodes') or not hasattr(self, 'elements'): + logging.error("please call extract_solid() to extract the solid first") + return + + logging.info("prepare physical simulation...") + + # Initialize Warp. + wp.init() + + # Normalize device names such as "cuda" and "cuda:0". + if 'cuda' in self.device: + # Extract the device id when needed. + if ':' in self.device: + device_id = self.device.split(':')[-1] + warp_device = f"cuda:{device_id}" + else: + warp_device = "cuda:0" # default to cuda:0 + else: + warp_device = "cpu" + + wp.set_device(warp_device) + logging.info(f"Warpdevice: {warp_device}") + + # Material properties. + self.E = self.config.youngs_modulus # Young's modulus. + self.nu = self.config.poissons_ratio # Poisson's ratio. + self.rho = self.config.density # Density. + + # Boundary condition: fix bottom nodes using Hunyuan's Y-up frame. + y_coords = self.nodes[:, 1] + y_min = y_coords.min() + boundary_threshold = y_min + 0.05 # 0.2 # 0.05 # Bottom 5% band. + self.boundary_mask = y_coords < boundary_threshold + + logging.info(f" coordinate system: Y-up (Hunyuan-native), fix Y < {boundary_threshold:.3f}nodes") + + # Apply load locally instead of spreading it across all nodes. + # The default heuristic targets a seat-like region in the Y-up frame. + + # Compute the total force, giving priority to force_entries. + total_force = np.zeros(3, dtype=np.float32) + force_entries = getattr(self.config, "force_entries", None) + valid_force_entries = None + if force_entries: + valid_force_entries = [] + for entry in force_entries: + if not isinstance(entry, dict): + continue + entry_force = None + if "force" in entry: + try: + entry_force = np.array(entry["force"], dtype=np.float32) + except Exception: + entry_force = None + elif "forces" in entry and isinstance(entry["forces"], list): + try: + entry_force = np.sum( + np.array(entry["forces"], dtype=np.float32), axis=0 + ) + except Exception: + entry_force = None + if entry_force is None or entry_force.shape != (3,): + continue + valid_force_entries.append(entry) + total_force += entry_force + if valid_force_entries: + self.force_entries_preset = valid_force_entries + logging.info(f" force entries: {len(valid_force_entries)}") + else: + logging.warning(" ⚠️ force_entries has no valid entries, fallback to forces") + valid_force_entries = None + + if valid_force_entries is None: + for force_config in self.config.forces: + if hasattr(force_config, 'get_total_force'): + # ForceConfig object. + total_force += force_config.get_total_force() + elif isinstance(force_config, dict) and 'external_force' in force_config: + # Compatibility format using a plain dict. + total_force += np.array(force_config['external_force'], dtype=np.float32) + else: + logging.warning(f"unknown force format: {type(force_config)}") + + logging.info(f" sum of external forces (Y-up coordinates): {total_force}") + + # Choose the loading strategy from the config. + if valid_force_entries is not None: + # Multiple localized loads, each with its own region. + self._setup_local_loading(total_force) + elif self.config.use_local_loading: + # Preferred mode: local loading. + self._setup_local_loading(total_force) + else: + # Fallback mode: global uniform loading. + logging.info(f" ℹ️ using global uniform loading mode") + total_force_tensor = torch.from_numpy(total_force).float().to(self.device) + num_nodes = self.nodes.shape[0] + self.forces = total_force_tensor[None, :].repeat(num_nodes, 1) + logging.info(f" 💨 distributed the total force uniformly to{num_nodes}nodes") + + logging.info(f"boundary conditions: {self.boundary_mask.sum().item()}fixed nodes") + logging.info(f"material properties: E={self.E:.2e}, ν={self.nu}, ρ={self.rho}") + + def _setup_local_loading(self, total_force: np.ndarray): + """Set up local loading on the selected seat/contact region. + + The total force is distributed uniformly across the selected nodes so + that sum(forces) equals total_force. + + Args: + total_force: Total force vector [3] in the Y-up frame, in Newtons. + """ + # Cache the total force for later updates. + self.total_force_preset = torch.from_numpy(total_force).float().to(self.device) + + # Reuse the generic update routine for the initial setup. + self._update_forces(initial_setup=True) + + def _update_forces(self, initial_setup: bool = False): + """Update the force distribution for the current mesh state. + + Core logic: + 1. Re-identify contact nodes + 2. Spread the preset total force uniformly over those nodes + 3. Keep total force conserved + + Args: + initial_setup: Whether this is the first setup pass. + """ + if not hasattr(self, 'total_force_preset'): + logging.warning("No preset total force is set, so the force distribution cannot be updated") + return + + # Step 1: inspect the Y-coordinate distribution. + y_coords = self.nodes[:, 1] + num_nodes = self.nodes.shape[0] + + force_entries = getattr(self, "force_entries_preset", None) + if force_entries: + def _select_nodes_for_mode(mode, top_percent, min_ratio, max_ratio, bbox, bbox_ratio): + seat_mask = torch.zeros(num_nodes, dtype=torch.bool, device=self.device) + mode_used = mode + bbox_desc = None + + if mode_used not in ("top_percent", "height_ratio", "bbox", "global"): + logging.warning(f" ⚠️ invalid force_region_mode: {mode_used}, fallback to top_percent") + mode_used = "top_percent" + + if mode_used == "global": + seat_mask[:] = True + return seat_mask, mode_used, bbox_desc + + if mode_used == "bbox": + bbox_vals = None + if bbox is not None and len(bbox) == 6: + bbox_vals = [float(v) for v in bbox] + bbox_desc = "abs" + elif bbox_ratio is not None and len(bbox_ratio) == 6: + bbox_ratio_vals = [float(v) for v in bbox_ratio] + bounds_min = self.nodes.min(dim=0).values + bounds_max = self.nodes.max(dim=0).values + bbox_vals = [ + bounds_min[0].item() + bbox_ratio_vals[0] * (bounds_max[0] - bounds_min[0]).item(), + bounds_min[0].item() + bbox_ratio_vals[1] * (bounds_max[0] - bounds_min[0]).item(), + bounds_min[1].item() + bbox_ratio_vals[2] * (bounds_max[1] - bounds_min[1]).item(), + bounds_min[1].item() + bbox_ratio_vals[3] * (bounds_max[1] - bounds_min[1]).item(), + bounds_min[2].item() + bbox_ratio_vals[4] * (bounds_max[2] - bounds_min[2]).item(), + bounds_min[2].item() + bbox_ratio_vals[5] * (bounds_max[2] - bounds_min[2]).item(), + ] + bbox_desc = "ratio" + else: + logging.warning(" ⚠️ bbox mode did not provide a valid bbox, fallback to top_percent") + mode_used = "top_percent" + + if mode_used == "bbox" and bbox_vals is not None: + x0, x1 = sorted([bbox_vals[0], bbox_vals[1]]) + y0, y1 = sorted([bbox_vals[2], bbox_vals[3]]) + z0, z1 = sorted([bbox_vals[4], bbox_vals[5]]) + seat_mask = ( + (self.nodes[:, 0] >= x0) & (self.nodes[:, 0] <= x1) + & (self.nodes[:, 1] >= y0) & (self.nodes[:, 1] <= y1) + & (self.nodes[:, 2] >= z0) & (self.nodes[:, 2] <= z1) + ) + if seat_mask.sum().item() < 1: + logging.warning(" ⚠️ bbox region matched no nodes, fallback to top_percent") + mode_used = "top_percent" + else: + bbox_desc = f"{bbox_desc}: [{x0:.3f},{x1:.3f}]x[{y0:.3f},{y1:.3f}]x[{z0:.3f},{z1:.3f}]" + + if mode_used == "height_ratio": + y_min = y_coords.min().item() + y_max = y_coords.max().item() + y_range = max(1e-8, y_max - y_min) + if not (0.0 <= min_ratio < max_ratio <= 1.0): + logging.warning( + f" ⚠️ invalid height_ratio: min={min_ratio}, max={max_ratio}, fallback to top_percent" + ) + mode_used = "top_percent" + else: + seat_y_min = y_min + y_range * min_ratio + seat_y_max = y_min + y_range * max_ratio + seat_mask = (y_coords >= seat_y_min) & (y_coords <= seat_y_max) + if seat_mask.sum().item() < 1: + logging.warning(" ⚠️ height_ratio matched no nodes, fallback to top_percent") + mode_used = "top_percent" + + if mode_used == "top_percent": + top_percent = float(top_percent) + top_percent = max(0.0, min(1.0, top_percent)) + if top_percent <= 0.0: + top_percent = 0.05 + num_seat_nodes = max(1, int(num_nodes * top_percent)) + _, top_indices = torch.topk(y_coords, k=num_seat_nodes, largest=True) + seat_mask = torch.zeros(num_nodes, dtype=torch.bool, device=self.device) + seat_mask[top_indices] = True + + return seat_mask, mode_used, bbox_desc + + self.forces = torch.zeros((num_nodes, 3), dtype=torch.float32, device=self.device) + combined_mask = torch.zeros(num_nodes, dtype=torch.bool, device=self.device) + total_force = torch.zeros(3, dtype=torch.float32, device=self.device) + + for idx, entry in enumerate(force_entries): + if not isinstance(entry, dict): + continue + entry_label = entry.get("label") or entry.get("name") or f"{idx+1}" + entry_force = None + if "forces" in entry and isinstance(entry["forces"], list): + try: + entry_force = np.sum(np.array(entry["forces"], dtype=np.float32), axis=0) + except Exception: + entry_force = None + if entry_force is None and "force" in entry: + try: + entry_force = np.array(entry["force"], dtype=np.float32) + except Exception: + entry_force = None + if entry_force is None or entry_force.shape != (3,): + logging.warning(f" ⚠️ invalid force entry[{entry_label}], skip") + continue + + entry_force_tensor = torch.from_numpy(entry_force).float().to(self.device) + total_force += entry_force_tensor + + mode = str(entry.get("force_region_mode", self.config.force_region_mode)).lower() + if entry.get("global_loading") is True: + mode = "global" + + top_percent = entry.get("force_top_percent", self.config.force_top_percent) + min_ratio = entry.get("seat_height_min_ratio", self.config.seat_height_min_ratio) + max_ratio = entry.get("seat_height_max_ratio", self.config.seat_height_max_ratio) + bbox = entry.get("force_bbox", self.config.force_bbox) + bbox_ratio = entry.get("force_bbox_ratio", self.config.force_bbox_ratio) + + seat_nodes_mask, mode_used, bbox_desc = _select_nodes_for_mode( + mode, top_percent, min_ratio, max_ratio, bbox, bbox_ratio + ) + + num_seat_nodes = int(seat_nodes_mask.sum().item()) + if num_seat_nodes < 1: + logging.warning(f" ⚠️ entry[{entry_label}]matched no nodes, skip") + continue + + force_per_node = entry_force_tensor / num_seat_nodes + self.forces[seat_nodes_mask] += force_per_node + combined_mask |= seat_nodes_mask + + seat_y_values = y_coords[seat_nodes_mask] + seat_y_min = seat_y_values.min().item() + seat_y_max = seat_y_values.max().item() + seat_y_mean = seat_y_values.mean().item() + + if initial_setup: + if mode_used == "bbox": + logging.info(f" 🪑 contact surface[{entry_label}]: bbox ({bbox_desc})") + elif mode_used == "height_ratio": + logging.info( + f" 🪑 contact surface[{entry_label}]: height_ratio " + f"[{min_ratio:.2f}, {max_ratio:.2f}]" + ) + elif mode_used == "global": + logging.info(f" 🪑 contact surface[{entry_label}]: global") + else: + logging.info( + f" 🪑 contact surface[{entry_label}]: highest-Y {float(top_percent):.1%} nodes" + ) + logging.info( + f" 🪑 seat-node count[{entry_label}]: {num_seat_nodes}/{num_nodes} " + f"({num_seat_nodes/num_nodes:.1%})" + ) + logging.info( + f" 🪑 Y range[{entry_label}]: [{seat_y_min:.3f}, {seat_y_max:.3f}], " + f"mean: {seat_y_mean:.3f}" + ) + logging.info(f" 💺 force[{entry_label}]: {entry_force}") + logging.info(f" 💺 per node[{entry_label}]: {force_per_node.cpu().numpy()}") + + self.total_force_preset = total_force + actual_total_force = self.forces.sum(dim=0) + force_error = torch.norm(actual_total_force - total_force).item() + force_error_percent = (force_error / (torch.norm(total_force).item() + 1e-10)) * 100 + + if initial_setup: + logging.info( + f" ✅ total-force check: {actual_total_force.cpu().numpy()} " + f"(error: {force_error:.2e}, {force_error_percent:.3f}%)" + ) + if combined_mask.any(): + self._save_force_visualization( + combined_mask, total_force.cpu().numpy() + ) + else: + logging.debug( + f" 🔄 force update: loaded nodes {int(combined_mask.sum().item())}, " + f"total force error {force_error:.2e}" + ) + + self._last_num_seat_nodes = int(combined_mask.sum().item()) + return + + # Contact-region selection supports top_percent / height_ratio / bbox. + mode = str(getattr(self.config, "force_region_mode", "top_percent")).lower() + seat_nodes_mask = torch.zeros(num_nodes, dtype=torch.bool, device=self.device) + mode_used = mode + bbox_desc = None + if mode_used not in ("top_percent", "height_ratio", "bbox"): + logging.warning(f" ⚠️ invalid force_region_mode: {mode_used}, fallback to top_percent") + mode_used = "top_percent" + + if mode_used == "bbox": + bbox = getattr(self.config, "force_bbox", None) + bbox_ratio = getattr(self.config, "force_bbox_ratio", None) + bbox_vals = None + if bbox is not None and len(bbox) == 6: + bbox_vals = [float(v) for v in bbox] + bbox_desc = "abs" + elif bbox_ratio is not None and len(bbox_ratio) == 6: + bbox_ratio_vals = [float(v) for v in bbox_ratio] + bounds_min = self.nodes.min(dim=0).values + bounds_max = self.nodes.max(dim=0).values + bbox_vals = [ + bounds_min[0].item() + bbox_ratio_vals[0] * (bounds_max[0] - bounds_min[0]).item(), + bounds_min[0].item() + bbox_ratio_vals[1] * (bounds_max[0] - bounds_min[0]).item(), + bounds_min[1].item() + bbox_ratio_vals[2] * (bounds_max[1] - bounds_min[1]).item(), + bounds_min[1].item() + bbox_ratio_vals[3] * (bounds_max[1] - bounds_min[1]).item(), + bounds_min[2].item() + bbox_ratio_vals[4] * (bounds_max[2] - bounds_min[2]).item(), + bounds_min[2].item() + bbox_ratio_vals[5] * (bounds_max[2] - bounds_min[2]).item(), + ] + bbox_desc = "ratio" + else: + logging.warning(" ⚠️ bbox mode did not provide a valid bbox, fallback to top_percent") + mode_used = "top_percent" + + if mode_used == "bbox" and bbox_vals is not None: + x0, x1 = sorted([bbox_vals[0], bbox_vals[1]]) + y0, y1 = sorted([bbox_vals[2], bbox_vals[3]]) + z0, z1 = sorted([bbox_vals[4], bbox_vals[5]]) + seat_nodes_mask = ( + (self.nodes[:, 0] >= x0) & (self.nodes[:, 0] <= x1) + & (self.nodes[:, 1] >= y0) & (self.nodes[:, 1] <= y1) + & (self.nodes[:, 2] >= z0) & (self.nodes[:, 2] <= z1) + ) + if seat_nodes_mask.sum().item() < 1: + logging.warning(" ⚠️ bbox region matched no nodes, fallback to top_percent") + mode_used = "top_percent" + else: + bbox_desc = f"{bbox_desc}: [{x0:.3f},{x1:.3f}]x[{y0:.3f},{y1:.3f}]x[{z0:.3f},{z1:.3f}]" + + if mode_used == "height_ratio": + y_min = y_coords.min().item() + y_max = y_coords.max().item() + y_range = max(1e-8, y_max - y_min) + min_ratio = float(self.config.seat_height_min_ratio) + max_ratio = float(self.config.seat_height_max_ratio) + if not (0.0 <= min_ratio < max_ratio <= 1.0): + logging.warning( + f" ⚠️ invalid height_ratio: min={min_ratio}, max={max_ratio}, fallback to top_percent" + ) + mode_used = "top_percent" + else: + seat_y_min = y_min + y_range * min_ratio + seat_y_max = y_min + y_range * max_ratio + seat_nodes_mask = (y_coords >= seat_y_min) & (y_coords <= seat_y_max) + if seat_nodes_mask.sum().item() < 1: + logging.warning(" ⚠️ height_ratio matched no nodes, fallback to top_percent") + mode_used = "top_percent" + + if mode_used == "top_percent": + top_percent = float(getattr(self.config, "force_top_percent", 0.05)) + top_percent = max(0.0, min(1.0, top_percent)) + if top_percent <= 0.0: + top_percent = 0.05 + num_seat_nodes = max(1, int(num_nodes * top_percent)) + _, top_indices = torch.topk(y_coords, k=num_seat_nodes, largest=True) + seat_nodes_mask = torch.zeros(num_nodes, dtype=torch.bool, device=self.device) + seat_nodes_mask[top_indices] = True + + num_seat_nodes = int(seat_nodes_mask.sum().item()) + + # Step 3: gather region statistics. + seat_y_values = y_coords[seat_nodes_mask] + seat_y_min = seat_y_values.min().item() + seat_y_max = seat_y_values.max().item() + seat_y_mean = seat_y_values.mean().item() + + # Step 4: computation the per-node load with uniform distribution. + force_per_node = self.total_force_preset / num_seat_nodes + + # Initialize all node forces to zero. + self.forces = torch.zeros((num_nodes, 3), dtype=torch.float32, device=self.device) + + # Apply force only to the selected seat/contact nodes. + self.forces[seat_nodes_mask] = force_per_node + + # Step 5: verify total-force conservation. + actual_total_force = self.forces.sum(dim=0) + force_error = torch.norm(actual_total_force - self.total_force_preset).item() + force_error_percent = (force_error / torch.norm(self.total_force_preset).item()) * 100 + + # Logging. + if initial_setup: + if mode_used == "bbox": + logging.info(f" 🪑 contact-surface setup: bbox ({bbox_desc})") + elif mode_used == "height_ratio": + logging.info( + f" 🪑 contact-surface setup: height_ratio " + f"[{self.config.seat_height_min_ratio:.2f}, {self.config.seat_height_max_ratio:.2f}]" + ) + else: + logging.info( + f" 🪑 contact-surface setup: highest-Y {float(getattr(self.config, 'force_top_percent', 0.05)):.1%} nodes" + ) + logging.info(f" 🪑 seat-node count: {num_seat_nodes}/{num_nodes} ({num_seat_nodes/num_nodes:.1%})") + logging.info(f" 🪑 Y-coordinate range: [{seat_y_min:.3f}, {seat_y_max:.3f}], mean: {seat_y_mean:.3f}") + logging.info(f" 💺 preset total force: {self.total_force_preset.cpu().numpy()}") + logging.info(f" 💺 force per node: {force_per_node.cpu().numpy()}") + logging.info(f" ✅ total-force check: {actual_total_force.cpu().numpy()} (error: {force_error:.2e}, {force_error_percent:.3f}%)") + + # Estimate the equivalent pressure. + y_range = y_coords.max().item() - y_coords.min().item() + grid_spacing = y_range / self.config.res if y_range > 0 else 0.01 + estimated_area = num_seat_nodes * (grid_spacing ** 2) + if estimated_area > 0 and abs(self.total_force_preset[1].item()) > 0: + pressure_kpa = abs(self.total_force_preset[1].item()) / estimated_area / 1000 + logging.info(f" 📏 equivalent pressure: {pressure_kpa:.1f} kPa (contact area≈{estimated_area:.4f} m²)") + + if pressure_kpa < 5: + logging.warning(f" ⚠️ pressure is too small ({pressure_kpa:.1f} kPa < 5 kPa)") + elif pressure_kpa > 50: + logging.warning(f" ⚠️ pressure is too large ({pressure_kpa:.1f} kPa > 50 kPa)") + + # Save visualization data. + self._save_force_visualization(seat_nodes_mask, self.total_force_preset.cpu().numpy()) + else: + # Shorter logging during optimization. + logging.debug(f" 🔄 force update: seat nodes {num_seat_nodes}, per node {force_per_node.cpu().numpy()}, " + f"total force error {force_error:.2e}") + + # Watch for changes in the number of loaded nodes. + if hasattr(self, '_last_num_seat_nodes') and self._last_num_seat_nodes != num_seat_nodes: + logging.info(f" ⚠️ seat-node count changed: {self._last_num_seat_nodes} → {num_seat_nodes}") + + # Cache the current state for the next comparison. + self._last_num_seat_nodes = num_seat_nodes + + def extract_solid(self, step: int = -1): + """Extract the physical solid by querying the node SDF directly. + + This method rebuilds the FEM mesh from the current latents so topology + changes in the SDF field can be reflected by the simulation mesh. + + Args: + step: Current optimization step, used for logging. + """ + if not WARP_AVAILABLE: + logging.warning("Warpnot installed, unable toperformphysics simulation") + return + + # Re-check physiopt availability at runtime. + try: + from physiopt.utils.phys_utils import generate_hex as _generate_hex + from physiopt.utils.grid_utils import filter_one_component as _filter_one_component + from physiopt.opt.field import occ_kernel as _occ_kernel + generate_hex_func = _generate_hex + filter_one_component_func = _filter_one_component + occ_kernel_func = _occ_kernel + logging.info("✅ physioptmoduleruntime check succeeded") + except ImportError as e: + logging.error(f"physioptmodulenot installed: {e}") + logging.error("please make sure physiopt is installed correctly: cd /mnt/cvlab/scratch/cvlab/home/hantzhan/physiopt && pip install -e .") + return + + res = self.config.res + step_label = f"Step {step}" if step >= 0 else "Initialization" + logging.info(f"{'🔄' if step >= 0 else '🆕'} [{step_label}] generate/update a mesh at resolution {res} hexahedral mesh...") + + # Keep the previous mesh size for comparison. + old_num_nodes = len(self.nodes) if hasattr(self, 'nodes') else 0 + old_num_elements = len(self.elements) if hasattr(self, 'elements') else 0 + + # 1. Generate the full hexahedral grid. + full_nodes, full_elements = generate_hex_func( + res=res, + limits=[(-0.8, 0.8), (-0.8, 0.8), (-0.8, 0.8)], + device=self.device, + return_coords=False + ) + + if full_nodes is None or full_elements is None: + logging.error("failed to generate the hexahedral mesh") + return + + full_nodes = full_nodes.to(self.device).float() + full_elements = full_elements.to(self.device).long() + + logging.info(f"hexahedral mesh generated successfully: {full_nodes.shape[0]}nodes, {full_elements.shape[0]}elements") + + # 2. Query the SDF directly through get_field. + logging.info("query node SDF values...") + sdf = self.get_field(full_nodes) + + # Make sure the SDF is a 1D tensor [N]. + if sdf.dim() > 1: + logging.warning(f"⚠️ SDFYesmulti-dimensional tensor: {sdf.shape}, will be flattened to 1D") + sdf = sdf.squeeze() # remove all size-1 dimensions + if sdf.dim() > 1: + sdf = sdf.reshape(-1) # force-flatten to 1D + + logging.info(f" ✅ SDF query succeeded: range=[{sdf.min():.3f}, {sdf.max():.3f}]") + logging.info(f" nodescount: {full_nodes.shape[0]}, SDF count: {sdf.shape[0]}") + + # Verify that the SDF count matches the node count. + if sdf.shape[0] != full_nodes.shape[0]: + logging.error(f"❌ SDF count({sdf.shape[0]}) vs. node count ({full_nodes.shape[0]})do not match!") + return + + # 3. Convert SDF values to occupancy. + logging.info("convert the SDF into an occupancy field...") + occ = occ_kernel_func(sdf, res, self.config.occ_sdf_beta) + + # 4. Select solid elements using an SDF threshold instead of an + # occupancy threshold. The threshold is intentionally relaxed so thin + # structures such as chair legs are kept. + SDF_FILTER_VALUE = 2.0 / res + nodewise_mask = sdf <= SDF_FILTER_VALUE + + # Diagnostic SDF statistics. + sdf_inside = sdf[nodewise_mask] + sdf_outside = sdf[~nodewise_mask] + logging.info(f" SDF threshold: {SDF_FILTER_VALUE:.4f}") + logging.info(f" interior nodes: {nodewise_mask.sum().item()}/{len(sdf)} ({100*nodewise_mask.sum().item()/len(sdf):.1f}%)") + if len(sdf_inside) > 0: + logging.info(f" inner SDF range: [{sdf_inside.min():.4f}, {sdf_inside.max():.4f}]") + if len(sdf_outside) > 0: + logging.info(f" outside-SDF range: [{sdf_outside.min():.4f}, {sdf_outside.max():.4f}]") + + # Debug the element-index range. + max_elem_idx = full_elements.max().item() + num_nodes = full_nodes.shape[0] + logging.info(f" elementsindex range: [0, {max_elem_idx}], nodescount: {num_nodes}") + + if max_elem_idx >= num_nodes: + logging.error(f"❌ index out of bounds!maximum element index({max_elem_idx}) >= nodescount({num_nodes})") + logging.error(f" this may be a problem with generate_hex") + # Clamp indices to the valid range. + valid_mask = (full_elements >= 0) & (full_elements < num_nodes) + if not valid_mask.all(): + logging.warning(f" found{(~valid_mask).sum().item()} invalid indices; filtering elements") + # Keep only elements whose node indices are all valid. + valid_elements_mask = valid_mask.all(dim=1) + full_elements = full_elements[valid_elements_mask] + logging.info(f" element count after filtering: {full_elements.shape[0]}") + + # Keep an element if any of its nodes passes the threshold. + elementwise_mask = torch.any(nodewise_mask[full_elements], dim=1) + + num_solid_elements = elementwise_mask.sum().item() + logging.info(f"SDF thresholdfiltering: {num_solid_elements}/{len(elementwise_mask)} solid elements") + + if num_solid_elements == 0: + logging.error("No solid elements were found; please check the SDF or adjust the threshold") + return + + # 5. Optionally keep only one connected component. + if self.config.one_cc_only: + element_res = res - 1 + try: + num_before_filter = elementwise_mask.sum().item() + elementwise_mask = filter_one_component_func(elementwise_mask, element_res) + num_filtered_elements = elementwise_mask.sum().item() + num_removed = num_before_filter - num_filtered_elements + logging.info(f"connectivity filtering: {num_filtered_elements} elements kept (removed{num_removed} small components)") + if num_removed > num_filtered_elements * 0.1: + logging.warning(f" ⚠️ removed{num_removed}elements({100*num_removed/num_before_filter:.1f}%), may have filtered out important parts (such as chair legs) ") + logging.warning(f" Suggestion: check the SDF threshold or consider disabling one_cc_only") + except IndexError as e: + logging.warning(f"connectivity filteringfailed: {e}, using the original mask") + else: + logging.info("connectivity filteringdisabled, keep all connected components") + + # 6. Select the active elements and nodes. + selected_elements = full_elements[elementwise_mask] + selected_node_indices, selected_elements = torch.unique( + selected_elements, return_inverse=True + ) + + self.elements = selected_elements + self.nodes = full_nodes[selected_node_indices] + + # 7. Compute occupancy for the selected nodes used in the simulation. + coarse_sdf = sdf[selected_node_indices] + coarse_occ_nodes = occ_kernel_func( + coarse_sdf, self.config.res, self.config.occ_sdf_beta + ) + # Each element occupancy is the mean over its 8 nodes. + self.coarse_occ = coarse_occ_nodes[self.elements].mean(1) + + # Diagnostic statistics for mesh-size changes. + new_num_nodes = len(self.nodes) + new_num_elements = len(self.elements) + + if old_num_nodes > 0: + node_change = new_num_nodes - old_num_nodes + element_change = new_num_elements - old_num_elements + node_change_pct = (node_change / old_num_nodes) * 100 + element_change_pct = (element_change / old_num_elements) * 100 + + logging.info(f"✅ solid extraction completed:") + logging.info(f" nodes: {old_num_nodes} → {new_num_nodes} ({node_change:+d}, {node_change_pct:+.1f}%)") + logging.info(f" elements: {old_num_elements} → {new_num_elements} ({element_change:+d}, {element_change_pct:+.1f}%)") + + if node_change > 0: + logging.info(f" ✅ mesh expanded!added{node_change}nodes (chair legs may have thickened) ") + elif node_change < 0: + logging.warning(f" ⚠️ mesh shrank!removed{-node_change}nodes (chair legs may have become thinner) ") + else: + logging.info(f"✅ solid extraction succeeded: {new_num_nodes}nodes, {new_num_elements}elements") + + # 8. Recomputation the boundary mask because the node count may change. + y_coords = self.nodes[:, 1] + y_min = y_coords.min() + boundary_threshold = y_min + 0.05 # bottom 5% region + self.boundary_mask = y_coords < boundary_threshold + + num_boundary = self.boundary_mask.sum().item() + logging.debug(f" 🔧 boundary conditionsupdated: {num_boundary}fixed nodes (Y < {boundary_threshold:.3f})") + + def get_current_sds_weight(self, step: int) -> float: + """Return the current SDS weight by linear interpolation. + + Args: + step: Current optimization step. + + Returns: + The SDS weight interpolated from sds_weight_start to sds_weight_end. + """ + # Linear interpolation from sds_weight_start to sds_weight_end. + progress = min(1.0, step / max(1, self.config.num_steps - 1)) + current_weight = self.config.sds_weight_start + progress * (self.config.sds_weight_end - self.config.sds_weight_start) + return current_weight + + def _computation_target_z0_current(self, step: int) -> Tuple[torch.Tensor, torch.Tensor]: + """Compute the current target_z0 for one update.""" + noise_level = float(self.config.sds_timestep) + t = 1.0 - noise_level # Hunyuan3D-2.1 uses t=0 for noise and t=1 for data. + epsilon = torch.randn_like(self.latents) + + self.sds_scheduler.config.num_train_timesteps = 100 + if self.sds_scheduler is not None: + # Match the official Flow Matching noise process: + # x_t = (1 - sigma) * x0 + sigma * eps. + sigma_step = 1.0 / float(self.sds_scheduler.config.num_train_timesteps) + total_span = max(0.0, 1.0 - t) + num_steps = int(np.ceil(total_span / sigma_step)) + sigmas = np.linspace(t, 1.0, num_steps + 1, dtype=np.float32) + self.sds_scheduler.set_timesteps(sigmas=sigmas, device=self.device) + t_scheds = self.sds_scheduler.timesteps + t_sched0 = t_scheds[0] + t_model0 = (t_sched0 / self.sds_scheduler.config.num_train_timesteps).to(self.latents.dtype) + if step % max(1, int(self.config.sds_target_z0_update_interval)) == 0: + logging.info( + f" 🎯 target_z0/sigmaalign: noise={noise_level:.4f}, t_start={t:.4f}, " + f"t_sched={t_sched0.item():.2f}, t_model={t_model0.item():.6f}, " + f"steps={num_steps}, sigma_step={sigma_step:.4g}" + ) + else: + t_sched = None + z_t = (1 - t) * epsilon + t * self.latents + t_model = torch.tensor([t], device=self.device, dtype=self.latents.dtype) + + with torch.no_grad(): + if self.sds_scheduler is not None: + # Integrate over multiple small sigma steps from sigma=t to 0. + cond_for_model = self._get_cond_for_guidance(self.config.guidance_scale > 1.0) + t_sched0 = t_scheds[0] + t_sched_batch = t_sched0.reshape(1).expand(self.latents.shape[0]) + # Hunyuan3D convention: t=0 is noise and t=1 is data. + z_t = self.sds_scheduler.scale_noise(epsilon, t_sched_batch, noise=self.latents) + + z_curr = z_t + velocity = None + for i in range(len(t_scheds) - 1): + t_sched = t_scheds[i] + t_model = (t_sched / self.sds_scheduler.config.num_train_timesteps).to(self.latents.dtype) + z_t_fp16 = z_curr.to(torch.float16) + t_tensor = t_model.to(device=self.device, dtype=z_t_fp16.dtype) + + if self.config.guidance_scale > 1.0: + latent_model_input = torch.cat([z_t_fp16, z_t_fp16]) + timestep_input = t_tensor.expand(latent_model_input.shape[0]) + + velocity_pred_fp16 = self.flow_model( + latent_model_input, + timestep_input, + cond_for_model, + guidance=None, + ) + + velocity_cond_fp16, velocity_uncond_fp16 = velocity_pred_fp16.chunk(2) + velocity_fp16 = velocity_uncond_fp16 + self.config.guidance_scale * (velocity_cond_fp16 - velocity_uncond_fp16) + + if step % 10 == 0 and i == 0: + logging.debug( + f" CFG (SDS): guidance_scale={self.config.guidance_scale:.1f}, " + f"||v_cond||={torch.norm(velocity_cond_fp16).item():.3e}, " + f"||v_uncond||={torch.norm(velocity_uncond_fp16).item():.3e}" + ) + else: + velocity_fp16 = self.flow_model( + z_t_fp16, + t_tensor.expand(z_t_fp16.shape[0]), + cond_for_model, + guidance=None, + ) + + velocity = velocity_fp16.to(torch.float32) + z_curr = self.sds_scheduler.step(velocity, t_sched, z_curr).prev_sample + + target_z0_current = z_curr + else: + cond_for_model = self._get_cond_for_guidance(self.config.guidance_scale > 1.0) + z_t_fp16 = z_t.to(torch.float16) + t_tensor = t_model.to(device=self.device, dtype=z_t_fp16.dtype) + + if self.config.guidance_scale > 1.0: + latent_model_input = torch.cat([z_t_fp16, z_t_fp16]) + timestep_input = t_tensor.expand(latent_model_input.shape[0]) + + velocity_pred_fp16 = self.flow_model( + latent_model_input, + timestep_input, + cond_for_model, + guidance=None, + ) + + velocity_cond_fp16, velocity_uncond_fp16 = velocity_pred_fp16.chunk(2) + velocity_fp16 = velocity_uncond_fp16 + self.config.guidance_scale * (velocity_cond_fp16 - velocity_uncond_fp16) + + if step % 10 == 0: + logging.debug( + f" CFG (SDS): guidance_scale={self.config.guidance_scale:.1f}, " + f"||v_cond||={torch.norm(velocity_cond_fp16).item():.3e}, " + f"||v_uncond||={torch.norm(velocity_uncond_fp16).item():.3e}" + ) + else: + velocity_fp16 = self.flow_model( + z_t_fp16, + t_tensor.expand(z_t_fp16.shape[0]), + cond_for_model, + guidance=None, + ) + + velocity = velocity_fp16.to(torch.float32) + # Fallback: one forward-Euler step to t=1. + target_z0_current = z_t + (1.0 - t) * velocity + + # Optional trust region to keep target_z0 from moving too far away. + max_rel = float(getattr(self.config, "sds_projection_max_rel", 0.0)) + if max_rel > 0.0: + with torch.no_grad(): + diff = target_z0_current - self.latents + diff_norm = torch.norm(diff).item() + latents_norm = torch.norm(self.latents).item() + max_norm = max_rel * (latents_norm + 1e-8) + if diff_norm > max_norm and max_norm > 0.0: + scale = max_norm / (diff_norm + 1e-8) + target_z0_current = self.latents + diff * scale + if step % max(1, int(self.config.sds_target_z0_update_interval)) == 0: + logging.info( + f" 🧱 target_z0 projection limit: diff={diff_norm:.3e} → {max_norm:.3e} " + f"(rel={max_rel:.2f})" + ) + return target_z0_current, velocity + + def _get_target_z0(self, step: int) -> Tuple[torch.Tensor, Optional[torch.Tensor], bool]: + """Update target_z0 on schedule and smooth it with EMA.""" + update_interval = max(1, int(self.config.sds_target_z0_update_interval)) + do_update = self.target_z0_ema is None or step % update_interval == 0 + + if do_update: + target_z0_current, velocity = self._computation_target_z0_current(step) + target_z0_current = target_z0_current.detach() + + if self.target_z0_ema is None: + self.target_z0_ema = target_z0_current.clone() + diff_norm = 0.0 + else: + diff = target_z0_current - self.target_z0_ema + diff_norm = torch.norm(diff).item() + alpha = 1.0 - self.config.sds_target_z0_ema_beta + self.target_z0_ema = self.target_z0_ema + alpha * diff + + self.target_z0_last_velocity = velocity + self.target_z0_last_update = step + + if step % update_interval == 0: + logging.info( + f" 🧭 target_z0 EMAupdate: interval={update_interval}, " + f"beta={self.config.sds_target_z0_ema_beta:.2f}, diff_norm={diff_norm:.3e}" + ) + else: + velocity = self.target_z0_last_velocity + + return self.target_z0_ema, velocity, do_update + + def project_to_manifold(self, step: int) -> bool: + """Project the current latents back to the manifold by replacing them with target_z0.""" + with torch.no_grad(): + target_z0, _ = self._computation_target_z0_current(step) + if torch.isnan(target_z0).any() or torch.isinf(target_z0).any(): + logging.warning(" ⚠️ projection failed: target_z0 contains NaN/Inf") + return False + deviation = torch.norm(target_z0 - self.latents).item() + latents_norm = torch.norm(self.latents).item() + rel = deviation / (latents_norm + 1e-8) + logging.info(f" 🧭 projection deviation: {deviation:.3e} (rel={rel:.2%})") + self.latents.data.copy_(target_z0) + if self.latents.grad is not None: + self.latents.grad.zero_() + # Reset optimizer state to avoid stale momentum. + self.optimizer.state.clear() + # Sync the EMA cache with the projected state. + self.target_z0_ema = target_z0.detach().clone() + self.target_z0_last_velocity = None + self.target_z0_last_update = step + return True + + def training_step_sds(self, step: int) -> Tuple[float]: + """Run one SDS optimization step. + + Returns: + (recon_loss,) + """ + self.optimizer.zero_grad() + + # ==================== SDS loss (Rectified Flow) ==================== + t = self.config.sds_timestep + target_z0, velocity, _ = self._get_target_z0(step) + + # SDS gradient: grad = z_0 - target_z0. + # This pulls the current z_0 (self.latents) toward target_z0. + sds_gradient = self.latents - target_z0.detach() + recon_loss = torch.mean(sds_gradient ** 2) / 2 + + # Debug information. + with torch.no_grad(): + target_norm = torch.norm(target_z0).item() + current_norm = torch.norm(self.latents).item() + grad_norm = torch.norm(sds_gradient).item() + velocity_norm = torch.norm(velocity).item() if velocity is not None else 0.0 + + logging.info(f"📐 Step {step:3d} | SDS: ||z_0||={current_norm:.2e}, " + f"||target_z_0||={target_norm:.2e}, " + f"||v||={velocity_norm:.2e}, " + f"||∇||={grad_norm:.2e}, t={t:.2f}, loss={recon_loss.item():.6e}") + + # Backpropagation. + sds_gradient_scaled = self.config.sds_weight * sds_gradient + + # Guard against invalid gradients. + if torch.isnan(sds_gradient_scaled).any() or torch.isinf(sds_gradient_scaled).any(): + logging.error(f"❌ Error: SDS gradient contains NaN or Inf!") + logging.error(f" ||sds_gradient||: {grad_norm:.2e}") + logging.error(f" sds_weight: {self.config.sds_weight}") + logging.error(f" target_z0 range: [{target_z0.min().item():.2e}, {target_z0.max().item():.2e}]") + logging.error(f" latents range: [{self.latents.min().item():.2e}, {self.latents.max().item():.2e}]") + if velocity is not None: + logging.error(f" velocity range: [{velocity.min().item():.2e}, {velocity.max().item():.2e}]") + return (recon_loss.item(),) + + if self.latents.grad is not None: + self.latents.grad.zero_() + + self.latents.grad = sds_gradient_scaled + + # Optional gradient clipping. + if self.config.grad_clip_enabled: + grad_norm_total = torch.norm(self.latents.grad).item() + max_grad_norm = 100.0 # 1e5lower to100 + if grad_norm_total > max_grad_norm: + clip_factor = max_grad_norm / grad_norm_total + self.latents.grad *= clip_factor + logging.warning(f"⚠️ gradient clipping: {grad_norm_total:.4e} -> {max_grad_norm:.4e}") + + # Save the pre-update latents for diagnostics. + old_latents = self.latents.data.clone() + + # Re-check the gradient before the optimizer step. + if torch.isnan(self.latents.grad).any(): + logging.error(f"❌ Error: gradient contains NaN (optimizerupdatefront) !") + return (recon_loss.item(),) + + # Optimizer update. + self.optimizer.step() + + # Measure parameter change after the update. + param_change = torch.norm(self.latents.data - old_latents).item() + + # Validate the updated latents. + if torch.isnan(self.latents).any(): + logging.error(f"❌ Error: latents contain NaN (optimizerupdateback) !") + logging.error(f" gradient norm: {grad_norm_total:.4e}") + logging.error(f" Learning rate: {self.config.lr}") + logging.error(f" Param change: {param_change:.4e}") + logging.error(f" suggestion: this may be caused by Adam optimizer momentum") + logging.error(f" : 1) reset optimizer 2) Use SGD instead of Adam") + # Restore the previous value. + self.latents.data.copy_(old_latents) + # Clear optimizer momentum/state before retrying. + self.optimizer.state.clear() + logging.info(f" ✅ already reset optimizerStatus, will retry on the next step") + return (recon_loss.item(),) + + # Sanity-check the latent magnitude. + latents_max = torch.abs(self.latents).max().item() + if latents_max > 1000: + logging.warning(f"⚠️ warning: latent values are too large (max={latents_max:.2e})") + logging.warning(f" you may need to lower the learning rate or SDS timestep") + + logging.info(f"✏️ Step {step:3d} | Param change: {param_change:.4e}, max|z|: {latents_max:.2e}") + + return (recon_loss.item(),) + + def training_step_dual_lagrange_v2( + self, + step: int, + lagrange: float, + rho: float, + use_sds: bool = True, + save_step: Optional[int] = None, + ) -> Tuple[float, float, float]: + """Physics optimization. + + This follows the computation_phys_loss_grad flow from viewer_base.py: + 1. optimizer.zero_grad() + 2. with torch.no_grad(): prepare_solid() + solve() + 3. Compute sensitivities with the reference-style formula + 4. backward_step() via VJP + 5. Apply ALM weighting (lambda + rho[g]_+) + 6. optimizer.step() + + Reference: + physiopt/src/physiopt/vis/viewer_base.py Line 1297-1430 + """ + save_step_id = step if save_step is None else int(save_step) + + # ==================== Step 1: zero gradients ==================== + self.optimizer.zero_grad() + + # ==================== Step 2: update occupancy on the fixed topology ==================== + if step > 0: + logging.info(f"🔄 [Step {step}] update occupancy (mesh topology fixed) ...") + # Keep the previous occupancy for diagnostics. + old_occ = self.coarse_occ.clone() + + # Re-query the SDF and occupancy on the fixed mesh. + sdf = self.get_field(self.nodes) + from physiopt.opt.field import occ_kernel + occ = occ_kernel(sdf, self.config.res, self.config.occ_sdf_beta) + self.coarse_occ = occ[self.elements].mean(1) + + # Diagnose occupancy changes. + occ_change = self.coarse_occ - old_occ + occ_mean_change = occ_change.mean().item() + occ_increase_ratio = (occ_change > 0).float().mean().item() + + logging.info(f" occupancy range: [{self.coarse_occ.min():.3f}, {self.coarse_occ.max():.3f}]") + logging.info(f" occupancy change: mean={occ_mean_change:+.3e}, increase ratio={occ_increase_ratio:.1%}") + + # ==================== Step 3: physics simulation (with torch.no_grad) ==================== + # Aligned with the reference flow around Line 1317-1356. + with torch.no_grad(): + # 3.1 prepare_solid: apply SIMP scaling and build SolidGrid. + if self.config.alpha_min > 0.0: + self.coarse_occ = torch.clamp(self.coarse_occ, self.config.alpha_min) + + # Material SIMP scaling. + from torchfem.materials import IsotropicElasticity3D + from physiopt.opt.solid_grid import SolidGrid + + vectorized_material = IsotropicElasticity3D( + E=self.config.youngs_modulus, + nu=self.config.poissons_ratio, + rho=self.config.density, + ).vectorize(self.elements.shape[0]) + + vectorized_material.C *= ( + self.coarse_occ[:, None, None] ** self.config.p_exponent + ) + + # Create the SolidGrid solver state. + solid = SolidGrid(self.nodes, self.elements, vectorized_material) + solid.constraints[self.boundary_mask, :] = True + solid.forces = self.forces + + # 3.2 FEM solve. + logging.info(f"Step {step}: FEM solve...") + u, f_int, f_ext, sigma, _, _ = solid.solve(max_iter=1) + logging.info(f" |u|_mean={torch.abs(u).mean():.4e}") + self._log_physical_quantities(u, sigma) + + # Save the deformed mesh every N steps. + if self.config.deformed_mesh_interval > 0 and save_step_id % self.config.deformed_mesh_interval == 0: + try: + self.save_deformed_mesh(save_step_id, u) + except Exception as e: + logging.warning(f" ⚠️ error while saving the deformed mesh: {e}") + + # ==================== Step 4: sensitivity computation ==================== + # Strictly aligned with the reference flow around Line 1368-1399. + + # 4.1 Compute strain energy. We recover the unweighted energy by + # dividing out occ^p and keep strong numerical guards. + k0 = solid.k0() # occ^p * K_base after stiffness scaling. + u_j = u[self.elements].reshape(solid.n_elem, -1) + w_k_scaled = torch.einsum("...i, ...ij, ...j", u_j, k0, u_j) + + # Remove occ^p scaling to recover the base energy. + occ_power = torch.clamp( + self.coarse_occ ** self.config.p_exponent, + min=1e-6, # Avoid division by zero. + max=1.0 # Avoid overflow. + ) + + # Check again before division. + if torch.any(occ_power < 1e-6): + n_small = (occ_power < 1e-6).sum().item() + logging.warning(f" ⚠️ {n_small} elements have extremely small occ^p and were clamped to 1e-6") + + w_k_base = w_k_scaled / occ_power + + # Fall back if the recovered energy becomes invalid. + if torch.isnan(w_k_base).any() or torch.isinf(w_k_base).any(): + n_nan = torch.isnan(w_k_base).sum().item() + n_inf = torch.isinf(w_k_base).sum().item() + logging.error(f" ❌ w_k_baseabnormal: {n_nan} NaN, {n_inf} Inf") + logging.error(f" fall back to SIMP weightingw_k") + w_k_base = w_k_scaled + + # Use the recovered energy downstream. + compliance_mean = w_k_base.mean().item() + w_k = w_k_base # Downstream sensitivity uses the recovered energy. + + # Diagnostics. + logging.info(f" Compliance (true) ={compliance_mean:.2e}") + logging.info(f" w_k_base: max={w_k.max():.2e}, stress concentration={w_k.max()/(w_k.mean() + 1e-10):.1f}x") + + # ALM normalized constraint: g = D / D_thr - 1. + compliance_threshold = self.config.compliance_threshold if self.config.compliance_threshold is not None else 1.0 + g_raw = compliance_mean / (compliance_threshold + 1e-8) - 1.0 + g_pos = max(0.0, g_raw) + logging.info(f" constraint normalization: g={g_raw:+.3e}, [g]+={g_pos:.3e}, D_thr={compliance_threshold:.2e}") + + # Dynamic clip limit used by the ALM scaling guard. + base_max_grad = 1000.0 + lagrange_bonus = min((lagrange + rho * g_pos) * 10.0, 1000.0) + max_grad_norm = base_max_grad + lagrange_bonus + + # 4.3 Sensitivity formula aligned with the reference code: + # sensitivity = -p * occ^(p-1) * w_k + self.sensitivity_density = ( + -self.config.p_exponent + * self.coarse_occ ** (self.config.p_exponent - 1) + * w_k + ) + + # 4.4 Volume regularization is intentionally disabled here so the pure + # physics signal can be validated first. + if False and self.config.volume_term > 0.0: # Temporarily forced off. + # Initialize the reference volume on first use. + if not hasattr(self, 'init_volume'): + self.init_volume = self.coarse_occ.clone() + logging.info(f" record initial volume: sum={self.init_volume.sum().item():.2f}") + + # Volume sensitivity term. + sensitivity_volume = ( + self.config.volume_term + * (1.0 / self.config.res) ** 3 + * torch.ones_like(self.sensitivity_density) + ) + + # Choose the sign from the current volume change. + volume_sign = 1.0 if self.coarse_occ.sum() >= self.init_volume.sum() else -1.0 + sensitivity_volume *= volume_sign + + self.sensitivity_density += sensitivity_volume + + volume_ratio = self.coarse_occ.sum() / self.init_volume.sum() + logging.info(f" volume constraint: ratio={volume_ratio.item():.3f}, " + f"{'penalize' if volume_sign > 0 else 'encourage'}") + else: + logging.info(f" volume constraint: disabled (physicsoptimizationdominates) ") + + # Sensitivity diagnostics. + sens_norm = torch.norm(self.sensitivity_density).item() + sens_min = self.sensitivity_density.min().item() + sens_max = self.sensitivity_density.max().item() + logging.info(f" sensitivity: norm={sens_norm:.2e}, range=[{sens_min:.2e}, {sens_max:.2e}]") + + # ==================== Step 5: backward pass via VJP ==================== + self.backward_step(self.sensitivity_density) + + # ==================== Step 6: apply ALM weighting (lambda + rho[g]+) ==================== + if self.latents.grad is not None: + phys_grad_norm = torch.norm(self.latents.grad).item() + phys_grad_unscaled = self.latents.grad.clone() # Unscaled physics gradient for SDS comparisons. + + if g_pos > 0.0: + alm_scale_raw = (lagrange + rho * g_pos) / (compliance_threshold + 1e-8) + alm_scale = alm_scale_raw + guard_ratio = min(max(self.config.alm_scale_guard_ratio, 0.0), 1.0) + if phys_grad_norm > 0.0 and max_grad_norm > 0.0 and guard_ratio > 0.0: + alm_scale_guard = (max_grad_norm * guard_ratio) / (phys_grad_norm + 1e-8) + if alm_scale > alm_scale_guard: + logging.info( + f" 🔧 ALMscaling limit: raw={alm_scale_raw:.3e} -> {alm_scale_guard:.3e} " + f"(guard={guard_ratio:.2f}, max_grad={max_grad_norm:.1f})" + ) + alm_scale = alm_scale_guard + self.latents.grad *= alm_scale + else: + alm_scale = 0.0 + self.latents.grad.zero_() + + scaled_grad_norm = torch.norm(self.latents.grad).item() + logging.info( + f" physics gradient(ALM): {phys_grad_norm:.2e} → {scaled_grad_norm:.2e} " + f"(×scale={alm_scale:.3e}, λ={lagrange:.2f}, ρ={rho:.2f})" + ) + else: + phys_grad_unscaled = None + alm_scale = 0.0 + + # ==================== Step 7: shape loss toward target_z0 ==================== + + # 7.1 Compute the denoised target_z0. + import math + if use_sds: + target_z0, _, _ = self._get_target_z0(step) + else: + target_z0 = self.latents.detach() + + # Optionally validate and save a target_z0 mesh every 10 steps. + if use_sds: + self._maybe_save_target_z0_mesh(target_z0, save_step_id) + + # Shape loss is a simple MSE pulling latents toward target_z0. + shape_loss = torch.nn.functional.mse_loss(self.latents, target_z0.detach()) + + # 7.2 Decide whether shape loss is active this step. + current_sds_weight = self.get_current_sds_weight(step) if use_sds else 0.0 + use_sds_this_step = current_sds_weight > 0.0 + + if not use_sds_this_step: + logging.info(f" 🚫 Shape Loss disabled (physicsoptimizationmode) ") + weighted_sds = 0.0 + shape_grad_norm = 0.0 + else: + # Weighted shape loss. + weighted_shape_loss = current_sds_weight * shape_loss + + # Validate shape loss before backpropagating it. + if torch.isnan(shape_loss) or torch.isinf(shape_loss): + logging.error(f" ❌ Shape Loss contains NaN or Inf; skipping the shape constraint") + weighted_sds = 0.0 + shape_grad_norm = 0.0 + else: + # Backpropagate the shape loss into latents.grad. + weighted_shape_loss.backward() + + # Measure the shape-gradient norm for logging. + if self.latents.grad is not None and phys_grad_unscaled is not None: + # Isolate the shape part from the combined gradient. + shape_gradient = self.latents.grad - phys_grad_unscaled * alm_scale + shape_grad_norm = torch.norm(shape_gradient).item() + phys_grad_norm_current = torch.norm(phys_grad_unscaled * alm_scale).item() + shape_phys_ratio = shape_grad_norm / (phys_grad_norm_current + 1e-10) + + if shape_phys_ratio > 100.0: + logging.error(f" ❌ Shape gradient is too large (Shape/physics={shape_phys_ratio:.1f}x)!") + logging.error(f" consider lowering sds_weight_end: {self.config.sds_weight_end} → {self.config.sds_weight_end/100:.4f}") + elif shape_phys_ratio > 10.0: + logging.warning(f" ⚠️ Shape gradient is relatively large (Shape/physics={shape_phys_ratio:.1f}x)") + + # Compare the directions of physics and shape gradients. + cos_angle = (phys_grad_unscaled * shape_gradient).sum() / ( + torch.norm(phys_grad_unscaled) * torch.norm(shape_gradient) + 1e-10 + ) + angle_deg = torch.acos(torch.clamp(cos_angle, -1, 1)) * 180 / math.pi + direction = "same direction✅" if angle_deg < 90 else "opposite direction⚠️" + + logging.info(f" Shapegradient: norm={shape_grad_norm:.4e}, weight={current_sds_weight:.6f}") + logging.info(f" gradient direction: physics vs Shape = {angle_deg:.1f}° ({direction})") + elif self.latents.grad is not None: + shape_grad_norm = torch.norm(self.latents.grad).item() + logging.info(f" Shapegradient: norm={shape_grad_norm:.4e} (no physics gradient)") + else: + shape_grad_norm = 0.0 + + weighted_sds = weighted_shape_loss.item() + + # ==================== Step 8: combine losses and clip if needed ==================== + compliance_loss_item = compliance_mean + alm_penalty = lagrange * g_pos + 0.5 * rho * (g_pos ** 2) + total_loss = alm_penalty + weighted_sds + + # Log the combined loss terms. + if use_sds_this_step: + logging.info( + f" 📊 weighted loss: Compliance={compliance_loss_item:.4e}, g={g_raw:+.3e}, " + f"ALM={alm_penalty:.4e} (λ={lagrange:.2f}, ρ={rho:.2f}), " + f"Shape={weighted_sds:.4e} (×w={current_sds_weight:.6f}), Total={total_loss:.4e}" + ) + else: + logging.info( + f" 📊 weighted loss: Compliance={compliance_loss_item:.4e}, g={g_raw:+.3e}, " + f"ALM={alm_penalty:.4e} (λ={lagrange:.2f}, ρ={rho:.2f}), " + f"Shape=0.00e+00 (disabled), Total={total_loss:.4e}" + ) + + # Log gradient composition details. + if self.latents.grad is not None: + grad_norm = torch.norm(self.latents.grad).item() + + # Report each gradient contribution. + if phys_grad_unscaled is not None: + weighted_phys_grad_norm = torch.norm(phys_grad_unscaled * alm_scale).item() + logging.info(f" 🔍 gradient composition: Weighted Compliance Grad={weighted_phys_grad_norm:.4e} (ALM scale={alm_scale:.3e})") + + if use_sds_this_step and shape_grad_norm > 0: + logging.info(f" Scaled Shape Grad={shape_grad_norm:.4e} (Shape×w={current_sds_weight:.6f})") + if phys_grad_unscaled is not None: + grad_ratio = shape_grad_norm / (weighted_phys_grad_norm + 1e-10) + logging.info(f" ratio: Shape/Compliance = {grad_ratio:.4f} ({grad_ratio*100:.2f}%)") + + logging.info(f" Total Grad={grad_norm:.4e}") + + # Optional gradient clipping. + if self.latents.grad is not None: + grad_norm = torch.norm(self.latents.grad).item() + + if torch.isnan(self.latents.grad).any() or torch.isinf(self.latents.grad).any(): + logging.error(f"❌ the final gradient contains NaN or Inf!skip this steps") + return (compliance_loss_item, shape_loss.item(), total_loss) + + if self.config.grad_clip_enabled: + if grad_norm > max_grad_norm: + clip_factor = max_grad_norm / grad_norm + self.latents.grad = self.latents.grad * clip_factor + logging.info(f" ✂️ gradient clipping: {grad_norm:.4e} -> {max_grad_norm:.1f} (×{clip_factor:.3f})") + else: + logging.info(f" ✅ gradient not clipped: {grad_norm:.4e} (max={max_grad_norm:.1f})") + + # ==================== Step 9: optimizer step ==================== + + # Save the previous latents for diagnostics. + old_latents = self.latents.data.clone() + + self.optimizer.step() + + # Diagnose latent changes after the optimizer step. + with torch.no_grad(): + latents_change = torch.norm(self.latents.data - old_latents).item() + latents_norm = torch.norm(old_latents).item() + latents_change_percent = (latents_change / (latents_norm + 1e-10)) * 100 + max_latents_change = torch.abs(self.latents.data - old_latents).max().item() + + logging.info(f" 🔄 Latentschange: L2={latents_change:.4e} ({latents_change_percent:.3f}%), max={max_latents_change:.4e}") + + if latents_change < 1e-6: + logging.warning(f" ⚠️ latents almost did not change!the learning rate may be too small or the gradient may be too weak") + + # Return the scalar loss values. + return (compliance_loss_item, shape_loss.item(), total_loss) + + def training_step_dual_lagrange_old(self, step: int, lagrange: float) -> Tuple[float, float, float]: + """Run one legacy Dual Lagrange step (physical compliance + shape prior). + + Args: + step: Current step. + lagrange: Lagrange multiplier balancing physics and shape. + + Returns: + (compliance_loss, sds_loss, total_loss) + """ + if not WARP_AVAILABLE: + logging.error("Warpnot installed, unable torun legacy dual Lagrange optimization") + return (0.0, 0.0, 0.0) + + self.optimizer.zero_grad() + + # ==================== 1. Keep topology fixed ==================== + # Legacy experiments showed that re-extracting the mesh every step can + # introduce weak new elements and increase compliance. The safer path is + # to keep topology fixed and only refresh occupancy on existing nodes. + + if step > 0: # Step 0 already extracted the initial mesh. + # Do not re-extract the mesh here; update occupancy only. + # logging.debug(f"🔄 [Step {step}] Re-extract solid mesh...") + # self.extract_solid(step=step) # Disabled on purpose. + + # Re-query SDF and occupancy on the fixed node set. + logging.info(f"🔄 [Step {step}] update occupancy (meshtopology remains fixed) ...") + + # Keep the previous occupancy for diagnostics. + old_occ = self.coarse_occ.clone() + + sdf = self.get_field(self.nodes) # query the SDF using the current latents. + + from physiopt.opt.field import occ_kernel + occ = occ_kernel(sdf, self.config.res, self.config.occ_sdf_beta) + self.coarse_occ = occ[self.elements].mean(1) # Refresh occupancy. + + # Diagnose the occupancy update direction. + occ_change = self.coarse_occ - old_occ + occ_increase_ratio = (occ_change > 0).float().mean().item() + occ_mean_change = occ_change.mean().item() + + logging.info(f" SDFrange: [{sdf.min():.3f}, {sdf.max():.3f}]") + logging.info(f" Occupancyupdate: [{self.coarse_occ.min():.3f}, {self.coarse_occ.max():.3f}]") + logging.info(f" 🔍 occupancy change: mean={occ_mean_change:+.3e}, increase ratio={occ_increase_ratio:.1%}") + if occ_mean_change < 0: + logging.warning(f" ⚠️ occupancy mean decreased!the gradient direction may be wrong") + + # Mesh topology stays fixed: self.nodes and self.elements do not change. + + # ==================== 2. Check mesh state ==================== + if not hasattr(self, 'nodes') or not hasattr(self, 'elements'): + logging.error("please callextract_solid()Initializationmesh") + return (0.0, 0.0, 0.0) + + # ==================== 3. Validate mesh and occupancy state ==================== + # extract_solid() already computationd self.coarse_occ, so we only validate it here. + + if not hasattr(self, 'coarse_occ'): + logging.error("extract_solid()coarse_occ is not set, please check") + return (0.0, 0.0, 0.0) + + # Numerical-stability check. + if torch.isnan(self.coarse_occ).any() or torch.isinf(self.coarse_occ).any(): + logging.warning(f"Step {step}: Occupancycontains NaN or Inf, repairing") + adaptive_alpha_min = self.config.alpha_min + if self.config.res >= 64: + adaptive_alpha_min = max(self.config.alpha_min, 0.05) + self.coarse_occ = torch.nan_to_num(self.coarse_occ, nan=adaptive_alpha_min, + posinf=1.0, neginf=adaptive_alpha_min) + + logging.debug(f"Step {step}: Occupancyrange=[{self.coarse_occ.min():.3f}, {self.coarse_occ.max():.3f}]") + + # ==================== 4. Check loads and boundary conditions ==================== + # With fixed topology, forces and boundary_mask only need to be checked + # once instead of being rebuilt every step. + + if step == 0: + # First pass: make sure force and boundary-mask sizes match the mesh. + if not hasattr(self, 'forces') or self.forces.shape[0] != self.nodes.shape[0]: + logging.error(f"Forcesdo not match!forces.shape[0]={self.forces.shape[0] if hasattr(self, 'forces') else 'N/A'}, nodes.shape[0]={self.nodes.shape[0]}") + return (0.0, 0.0, 0.0) + + if not hasattr(self, 'boundary_mask') or self.boundary_mask.shape[0] != self.nodes.shape[0]: + logging.error(f"boundary mask dimensions do not match!") + return (0.0, 0.0, 0.0) + + logging.info(f" ✅ force and boundary-condition validation passed (stays unchanged throughout the entire optimization process) ") + + # For step > 0, forces and boundary_mask remain unchanged. + + # ==================== 5. Physics solve using the reference flow ==================== + try: + from physiopt.opt.solid_grid import SolidGrid # Use the original solver. + from torchfem.materials import IsotropicElasticity3D + + # ===== Material setup aligned with the reference code ===== + # Reference: viewer_base.py Line 481-494. + base_material = IsotropicElasticity3D( + E=self.config.youngs_modulus, + nu=self.config.poissons_ratio, + rho=self.config.density, + ) + vectorized_material = base_material.vectorize(self.elements.shape[0]) + + # Clamp occupancy in-place so downstream SIMP and sensitivity code + # all see the same value. + alpha_min = self.config.alpha_min if self.config.res < 64 else max(self.config.alpha_min, 0.05) + if alpha_min > 0.0: + self.coarse_occ = torch.clamp(self.coarse_occ, min=alpha_min) + + # Apply SIMP directly on the stiffness tensor C. + vectorized_material.C *= ( + self.coarse_occ[:, None, None] ** self.config.p_exponent + ) + + logging.info(f"Step {step}: material setup (Referencecode style) ") + logging.info(f" Occupancyrange: [{self.coarse_occ.min():.3f}, {self.coarse_occ.max():.3f}]") + logging.info(f" SIMPpenalty exponent p={self.config.p_exponent}") + + # Build SolidGrid. + solid = SolidGrid(self.nodes, self.elements, vectorized_material) + solid.constraints[self.boundary_mask, :] = True + solid.forces = self.forces + + # FEM solve. + logging.info("FEM solve (useoriginalSolidGrid) ...") + u, f_int, f_ext, sigma, _, _ = solid.solve(max_iter=1) + logging.info(f" solve completed: |u|={torch.abs(u).mean():.4e}") + self._log_physical_quantities(u, sigma) + + # Save deformed meshes every N steps. + if self.config.deformed_mesh_interval > 0 and step % self.config.deformed_mesh_interval == 0: + try: + self.save_deformed_mesh(step, u) + except Exception as e: + logging.warning(f" ⚠️ error while saving the deformed mesh: {e}") + + # ===== Compliance and sensitivity, aligned with the reference ===== + + k0 = solid.k0() + u_j = u[self.elements].reshape(solid.n_elem, -1) + w_k = torch.einsum("...i, ...ij, ...j", u_j, k0, u_j) # Element strain energy. + + # Inspect the strain-energy distribution. + w_k_mean = w_k.mean().item() + w_k_max = w_k.max().item() + w_k_std = w_k.std().item() + w_k_sum = w_k.sum().item() + + # Compliance should be w_k.sum() directly. The stiffness already + # includes occ^p, so a second scaling would be incorrect. + compliance_sum = w_k.sum() + compliance_mean = w_k.mean() + compliance = compliance_sum + + logging.info(f" compliance_sum={compliance_sum:.2e}, compliance_mean={compliance_mean:.2e}, |u|_mean={torch.abs(u).mean().item():.2e}") + logging.info(f" w_kdistribution: max={w_k_max:.2e}, std={w_k_std:.2e}, mean/max={w_k_mean/w_k_max:.3f}") + + if w_k_max > 10 * w_k_mean: + logging.warning(f" ⚠️ detected stress concentration!w_k_max/w_k_mean = {w_k_max/w_k_mean:.1f}x") + + compliance_loss = compliance + + # Sensitivity uses the reference negative sign. We start from the + # reference-style formula and then selectively boost the top 5% + # highest-strain-energy elements to keep stress concentrations from + # being overly suppressed in low-occupancy regions. + sensitivity_density = ( + -self.config.p_exponent + * self.coarse_occ ** (self.config.p_exponent - 1) + * w_k + ) + + # Boost sensitivity for the top 5% highest-strain-energy elements. + w_k_threshold_percentile = 95 + w_k_threshold = torch.quantile(w_k, w_k_threshold_percentile / 100.0) + stress_concentration_mask = w_k >= w_k_threshold + + if stress_concentration_mask.any(): + # Use a less attenuated sensitivity on stress-concentration elements. + eps = 1e-8 + enhanced_sensitivity = -self.config.p_exponent * w_k / (self.coarse_occ + eps) + + # Limit the enhancement to avoid exploding gradients. + base_sensitivity = sensitivity_density[stress_concentration_mask] + enhance_factor = enhanced_sensitivity[stress_concentration_mask] / (base_sensitivity + eps) + + # Clamp the enhancement factor into [1, 50]. + max_enhance_factor = 50.0 + enhance_factor_clamped = torch.clamp(enhance_factor, min=1.0, max=max_enhance_factor) + enhanced_sensitivity_safe = base_sensitivity * enhance_factor_clamped + + # Mix the boosted and base sensitivities. + sensitivity_density[stress_concentration_mask] = enhanced_sensitivity_safe + + n_enhanced = stress_concentration_mask.sum().item() + avg_enhance = enhance_factor_clamped.mean().item() + logging.info(f" 🎯 enhanced{n_enhanced}stress concentrationelements (top 5%) , mean enhancement{avg_enhance:.1f}x") + + # Adaptive volume regularization with a tolerance band. + if self.config.volume_term > 0.0: + # Record the initial volume on first use. + if not hasattr(self, 'init_volume'): + self.init_volume = self.coarse_occ.sum().item() + logging.info(f" 📊 record initial volume: {self.init_volume:.2f}") + + current_volume = self.coarse_occ.sum().item() + volume_ratio = current_volume / self.init_volume + volume_deviation = volume_ratio - 1.0 # >0 means above target, <0 means below target. + + # Do not penalize changes inside the tolerance band. + tolerance = self.config.volume_tolerance # +/- 5% + + if abs(volume_deviation) > tolerance: + # Penalize only the excess beyond the tolerance band. + excess = abs(volume_deviation) - tolerance + adaptive_weight = self.config.volume_term * (excess / tolerance) + + elem_volume = (1.0 / self.config.res) ** 3 + sensitivity_volume = ( + adaptive_weight + * elem_volume + * torch.ones_like(sensitivity_density) + ) + + # Positive sign penalizes excess volume; negative sign encourages growth. + volume_sign = 1.0 if volume_deviation > 0 else -1.0 + sensitivity_volume *= volume_sign + + # Add to the total sensitivity. + sensitivity_density += sensitivity_volume + + logging.info(f" 📊 volume constraintactivated: ratio={volume_ratio:.3f}, outside the tolerance range{excess*100:.1f}%, " + f"{'penalize' if volume_sign > 0 else 'encourage'}, adaptive weight={adaptive_weight:.1e}") + else: + # Inside the tolerance band, leave the physics gradient unchanged. + logging.info(f" 📊 volumewithin the tolerance range: ratio={volume_ratio:.3f} (tolerance±{tolerance*100:.0f}%)") + + # Sensitivity diagnostics. + sens_min = sensitivity_density.min().item() + sens_max = sensitivity_density.max().item() + sens_neg_ratio = (sensitivity_density < 0).float().mean().item() + logging.info(f" sensitivity: norm={torch.norm(sensitivity_density).item():.2e}, " + f"range=[{sens_min:.2e}, {sens_max:.2e}], negative-value ratio={sens_neg_ratio:.1%}") + logging.info(f" → negative sensitivity indicates'occcompliance' (expectedstress concentrationregion should be negative) ") + + # Push the physical sensitivity back to latents through VJP. + self.backward_step(sensitivity_density) + + # Scale the physics gradient by the Lagrange multiplier. + if self.latents.grad is not None: + phys_grad_norm_raw = torch.norm(self.latents.grad).item() + + if torch.isnan(self.latents.grad).any() or torch.isinf(self.latents.grad).any(): + logging.error(f"Step {step}: physics gradient contains NaN or Inf!") + logging.error(f" sensitivity_density: norm={sens_norm:.2e}") + logging.error(f" compliance: {compliance.item():.2e}") + # Clear the gradient and skip physics optimization for this step. + self.latents.grad = None + return (compliance_loss.item(), 0.0, compliance_loss.item()) + + # Keep the unscaled physics gradient for direction analysis. + phys_grad_unscaled = self.latents.grad.clone() + + self.latents.grad *= lagrange + phys_grad_norm_scaled = torch.norm(self.latents.grad).item() + + logging.info(f" physics gradient: norm={phys_grad_norm_raw:.4e} → {phys_grad_norm_scaled:.4e} (×λ={lagrange:.2f})") + else: + phys_grad_norm_scaled = 0.0 + + except Exception as e: + logging.error(f"FEM solvefailed: {e}") + import traceback + traceback.print_exc() + return (0.0, 0.0, 0.0) + + # ==================== 6. SDS shape-prior loss (with CFG) ==================== + t = self.config.sds_timestep + target_z0, _, _ = self._get_target_z0(step) + + # target_z0 should be the denoised "clean" latent. + # Formula: z_0 = z_t + t * v. + # Because Hunyuan3D defines velocity as v = z_0 - eps, target_z0 should + # stay close to the current latents when the velocity prediction is sound. + with torch.no_grad(): + deviation = torch.norm(target_z0 - self.latents).item() + latents_norm = torch.norm(self.latents).item() + relative_deviation = deviation / (latents_norm + 1e-8) + + if relative_deviation > 0.5: # Deviation above 50% is suspicious. + logging.warning(f" ⚠️ target_z0 deviation is too large: {relative_deviation:.1%} " + f"(||target_z_0 - latents||={deviation:.3e}, ||latents||={latents_norm:.3e})") + logging.warning(f" thismaySave target meshshape is abnormal") + + sds_gradient = self.latents - target_z0.detach() + sds_loss = torch.mean(sds_gradient ** 2) / 2 + + # Save a target_z0 mesh every 10 steps for guidance diagnostics. + if step % 10 == 0: + try: + # Validate target_z0 before exporting it. + with torch.no_grad(): + target_norm = torch.norm(target_z0).item() + target_max = torch.abs(target_z0).max().item() + target_has_nan = torch.isnan(target_z0).any().item() + target_has_inf = torch.isinf(target_z0).any().item() + + # Save only when target_z0 is numerically healthy. + if (not target_has_nan and not target_has_inf and + target_max < 100.0 and relative_deviation < 1.0): + # Detach completely to avoid gradient interference. + target_z0_clean = target_z0.detach().clone() + + # Print target_z0 statistics for diagnostics. + logging.info(f" 📊 target_z0 statistics:") + logging.info(f" - shape: {target_z0_clean.shape}") + logging.info(f" - range: [{target_z0_clean.min():.3e}, {target_z0_clean.max():.3e}]") + logging.info(f" - mean: {target_z0_clean.mean():.3e}, Std: {target_z0_clean.std():.3e}") + logging.info(f" - deviation from latents: {relative_deviation:.1%}") + + target_mesh = self.latents_to_mesh(target_z0_clean, octree_res=128) + if target_mesh is not None: + target_mesh_dir = os.path.join( + self.config.out_folder if hasattr(self.config, 'out_folder') + else "results/hunyuan_meshes", + "target_z0_meshes" + ) + os.makedirs(target_mesh_dir, exist_ok=True) + target_mesh_path = os.path.join(target_mesh_dir, f"target_z0_step_{step:04d}.obj") + target_mesh.export(target_mesh_path) + logging.info(f" 💾 Save target_z0 mesh (||z||={target_norm:.2e}): {target_mesh_path}") + else: + logging.debug(f" skipSave target_z0: marching cubesno surface found") + else: + logging.warning(f" ⚠️ skipSave target_z0: containsabnormal values " + f"(nan={target_has_nan}, inf={target_has_inf}, max={target_max:.2e})") + except (ValueError, RuntimeError) as e: + # Handle common marching-cubes failures explicitly. + error_msg = str(e) + if "Surface level must be within volume data range" in error_msg or "No surface found" in error_msg: + logging.debug(f" skipSave target_z0: SDFvalueoutside the valid range or has no surface") + else: + logging.warning(f" Save target_z0 meshfailed: {type(e).__name__}: {error_msg[:100]}") + except Exception as e: + # Catch any other export failure. + logging.warning(f" Save target_z0 meshfailed: {type(e).__name__}: {str(e)[:100]}") + + # Fully disable SDS here and keep only the physics update. + # The raw SDS gradient has been large enough to overwhelm the physics signal. + use_sds_this_step = False # ← force disabled! + + # Compute the scheduled SDS weight for the current step. + current_sds_weight = self.get_current_sds_weight(step) + + if not use_sds_this_step: + # Skip SDS gradients and keep only the physics gradient. + logging.info(f" 🚫 SDS fully disabled (physicsoptimizationmode) ") + # Still record the SDS loss even though it is not used for optimization. + weighted_sds = 0.0 # SDSdoes not participate in optimization for this step + sds_grad_norm = 0.0 + else: + logging.debug(f" ✅ useSDS gradient (weight={current_sds_weight:.4f})") + + # Add the SDS gradient to latents.grad. + sds_gradient_scaled = current_sds_weight * sds_gradient + + # Validate the SDS gradient before using it. + if torch.isnan(sds_gradient_scaled).any() or torch.isinf(sds_gradient_scaled).any(): + logging.error(f"Step {step}: SDS gradient contains NaN or Inf!") + logging.error(f" sds_weight={current_sds_weight} (dynamic)") + logging.error(f" sds_gradient range=[{sds_gradient.min():.2e}, {sds_gradient.max():.2e}]") + # Fall back to physics-only if the SDS gradient is invalid. + weighted_sds = 0.0 + sds_grad_norm = 0.0 + if self.latents.grad is None: + logging.error(" no physics gradient, unable to optimize") + return (compliance_loss.item(), sds_loss.item(), total_loss.item()) + else: + sds_grad_norm = torch.norm(sds_gradient_scaled).item() + weighted_sds = current_sds_weight * sds_loss + + # Key guard: make sure the SDS gradient does not dominate physics. + if self.latents.grad is not None: + phys_grad_norm_current = torch.norm(self.latents.grad).item() + sds_phys_ratio = sds_grad_norm / (phys_grad_norm_current + 1e-10) + + if sds_phys_ratio > 100.0: + logging.error(f" ❌ serious issue: SDS gradienttoo large!") + logging.error(f" SDS gradient / physics gradient = {sds_phys_ratio:.1f}x") + logging.error(f" SDScompletely overwhelms physics optimization, suggestion: ") + logging.error(f" 1. lowersds_weight_end: {self.config.sds_weight_end} → {self.config.sds_weight_end/100:.2f}") + logging.error(f" 2. usephysicsoptimization (sds_weight=0) ") + elif sds_phys_ratio > 10.0: + logging.warning(f" ⚠️ SDS gradient is relatively large (SDS/physics={sds_phys_ratio:.1f}x)") + logging.warning(f" consider lowering sds_weight_end {self.config.sds_weight_end/10:.2f}") + + # SDS gradient is valid, so add it to the total gradient. + if self.latents.grad is None: + self.latents.grad = sds_gradient_scaled + logging.info(f" SDS gradient: norm={sds_grad_norm:.4e} (no physics gradient)") + else: + # Log the gradient state before merging. + phys_grad_current = torch.norm(self.latents.grad).item() + logging.info(f" SDS gradient: norm={sds_grad_norm:.4e}") + + # Compare the directions of physics and SDS gradients. + cos_angle = (phys_grad_unscaled * sds_gradient_scaled).sum() / ( + torch.norm(phys_grad_unscaled) * torch.norm(sds_gradient_scaled) + 1e-10 + ) + angle_deg = torch.acos(torch.clamp(cos_angle, -1, 1)) * 180 / 3.14159 + direction = "same direction✅" if angle_deg < 90 else "opposite direction⚠️" + + logging.info(f" gradient direction: physics vs SDS = {angle_deg:.1f}° ({direction})") + logging.info(f" gradient merge: physics={phys_grad_current:.4e} + SDS={sds_grad_norm:.4e}") + + self.latents.grad += sds_gradient_scaled + + # ==================== 7. Combine losses ==================== + # Compute the weighted loss terms. + weighted_compliance = lagrange * compliance_loss + # weighted_sds is already set above based on use_sds_this_step. + total_loss = weighted_compliance + weighted_sds + + # Log the weighted losses. + if use_sds_this_step: + logging.info(f" 📊 weighted loss: Compliance={weighted_compliance:.4e} (×λ={lagrange:.2f}), " + f"SDS={weighted_sds:.4e} (×w={current_sds_weight:.4f}↑), Total={total_loss:.4e}") + else: + logging.info(f" 📊 weighted loss: Compliance={weighted_compliance:.4e} (×λ={lagrange:.2f}), " + f"SDS=0.00e+00 (fully disabled), Total={total_loss:.4e}") + + # Validate the final gradient. + if self.latents.grad is not None: + grad_norm = torch.norm(self.latents.grad).item() + + # Detailed logging of gradient composition. + logging.info(f" total gradient: norm={grad_norm:.4e}") + + if torch.isnan(self.latents.grad).any() or torch.isinf(self.latents.grad).any(): + logging.error(f"❌ the final gradient contains NaN or Inf!skip this steps") + return (compliance_loss.item(), sds_loss.item(), total_loss.item()) + + # Dynamic clipping: larger lambda allows larger gradients because + # the physical constraint becomes more important. + base_max_grad = 1000.0 # Raised from 200. + lagrange_bonus = min(lagrange * 10.0, 1000.0) # Raised from x3 to x10. + max_grad_norm = base_max_grad + lagrange_bonus + + # Check whether clipping is actually needed. + if grad_norm > max_grad_norm: + clip_factor = max_grad_norm / grad_norm + clip_loss_percent = (1 - clip_factor) * 100 + self.latents.grad = self.latents.grad * clip_factor + + # Warn if clipping removes more than half of the gradient. + if clip_loss_percent > 50: + logging.warning(f" ⚠️ gradient clipping loses too much information: {grad_norm:.4e} -> {max_grad_norm:.1f} " + f"(loss{clip_loss_percent:.1f}%gradient)") + else: + logging.info(f" ✂️ totalgradient clipping: {grad_norm:.4e} -> {max_grad_norm:.1f} " + f"(×{clip_factor:.3f}, λ={lagrange:.1f})") + else: + logging.info(f" ✅ total gradient not clipped: {grad_norm:.4e} (max={max_grad_norm:.1f}, λ={lagrange:.1f})") + else: + logging.error(f"❌ no gradients available; cannot optimize") + return (compliance_loss.item(), sds_loss.item(), total_loss.item()) + + # Save the current latents for diagnostics. + old_latents = self.latents.data.clone() + + # Update parameters. + self.optimizer.step() + + # Check whether the latents actually changed. + with torch.no_grad(): + latents_change = torch.norm(self.latents.data - old_latents).item() + latents_change_percent = (latents_change / (torch.norm(old_latents).item() + 1e-10)) * 100 + max_latents_change = torch.abs(self.latents.data - old_latents).max().item() + + # Check whether the SDF changed as well. + if hasattr(self, 'nodes') and self.nodes is not None: + try: + # Compare SDF values before and after the update. + old_sdf = self.get_field(self.nodes[:100], old_latents) # Sample 100 points. + new_sdf = self.get_field(self.nodes[:100], self.latents) + sdf_change = torch.norm(new_sdf - old_sdf).item() + sdf_max_change = torch.abs(new_sdf - old_sdf).max().item(); + + logging.info(f" 🔍 Latentschange: L2={latents_change:.4e} ({latents_change_percent:.3f}%), " + f"max={max_latents_change:.4e}") + logging.info(f" 🔍 SDF change: L2={sdf_change:.4e}, max={sdf_max_change:.4e}") + + if latents_change < 1e-6: + logging.warning(f" ⚠️ latents almost did not change!the learning rate may be too small or the gradient may be too weak") + if sdf_change < 1e-4: + logging.warning(f" ⚠️ SDFalmost no change!Meshthere will be no obvious change") + except Exception as e: + logging.debug(f" unable to computeSDF change: {e}") + + logging.info(f"🔄 Step {step:3d} | Compliance: {compliance_loss:.2e} (weighted: {weighted_compliance:.2e}), " + f"SDS: {sds_loss:.6e} (weighted: {weighted_sds:.6e}), Total: {total_loss:.2e}, λ={lagrange:.2f}") + logging.info(f" | Latents Δ: {latents_change:.4e} ({latents_change_percent:.3f}%), " + f"max Δ: {max_latents_change:.4e}") + + return (compliance_loss.item(), sds_loss.item(), total_loss.item()) + + + def save_mesh(self, step: int, output_dir: str = "results/hunyuan_meshes", high_quality: bool = False): + """Save the mesh decoded from the current latents. + + Args: + step: Current step. + output_dir: Output directory. + high_quality: Use higher-resolution decoding when True. + """ + os.makedirs(output_dir, exist_ok=True) + + try: + # Use 256 for final saves and 128 for faster intermediate saves. + octree_res = 256 if high_quality else 128 + mesh = self.latents_to_mesh(self.latents, octree_res=octree_res) + if mesh is None: + logging.warning(f" ⚠️ warning: Step {step} - Marching cubesno surface found, skipSave ") + return + + # Filter floating fragments on final exports. + if high_quality: + mesh = self._filter_floating_components(mesh) + + mesh_path = os.path.join(output_dir, f"step_{step:04d}.obj") + mesh.export(mesh_path) + quality_label = "256resolution" if high_quality else "128resolution" + logging.info(f" 💾 Save mesh ({quality_label}): {mesh_path}") + except Exception as e: + logging.warning(f" ⚠️ warning: Step {step} - Save meshfailed: {e}") + + + def _maybe_save_target_z0_mesh(self, target_z0: torch.Tensor, step_id: int, force: bool = False): + """Save a mesh decoded from target_z0 for diagnostics.""" + if (not force) and (step_id % 10 != 0): + return + + with torch.no_grad(): + deviation = torch.norm(target_z0 - self.latents).item() + latents_norm = torch.norm(self.latents).item() + relative_deviation = deviation / (latents_norm + 1e-8) + + if relative_deviation > 0.5: + logging.warning( + f" ⚠️ target_z0 deviation is too large: {relative_deviation:.1%} " + f"(||target_z0 - latents||={deviation:.3e}, ||latents||={latents_norm:.3e})" + ) + logging.warning(f" thismaySave target meshshape is abnormal") + + try: + target_norm = torch.norm(target_z0).item() + target_max = torch.abs(target_z0).max().item() + target_has_nan = torch.isnan(target_z0).any().item() + target_has_inf = torch.isinf(target_z0).any().item() + + # Save only when target_z0 looks numerically healthy. + if (not target_has_nan and not target_has_inf and + target_max < 100.0 and relative_deviation < 1.0): + target_z0_clean = target_z0.detach().clone() + + logging.info(f" 📊 target_z0 statistics:") + logging.info(f" - shape: {target_z0_clean.shape}") + logging.info(f" - range: [{target_z0_clean.min():.3e}, {target_z0_clean.max():.3e}]") + logging.info(f" - mean: {target_z0_clean.mean():.3e}, Std: {target_z0_clean.std():.3e}") + logging.info(f" - deviation from latents: {relative_deviation:.1%}") + + target_mesh = self.latents_to_mesh(target_z0_clean, octree_res=128) + if target_mesh is not None: + target_mesh_dir = os.path.join( + self.config.out_folder if hasattr(self.config, 'out_folder') + else "results/hunyuan_meshes", + "target_z0_meshes" + ) + os.makedirs(target_mesh_dir, exist_ok=True) + target_mesh_path = os.path.join(target_mesh_dir, f"target_z0_step_{step_id:04d}.obj") + target_mesh.export(target_mesh_path) + logging.info(f" 💾 Save target_z0 mesh (||z||={target_norm:.2e}): {target_mesh_path}") + else: + logging.debug(f" skipSave target_z0: marching cubesno surface found") + else: + logging.warning( + f" ⚠️ skipSave target_z0: containsabnormal values " + f"(nan={target_has_nan}, inf={target_has_inf}, max={target_max:.2e})" + ) + except (ValueError, RuntimeError) as e: + error_msg = str(e) + if "Surface level must be within volume data range" in error_msg or "No surface found" in error_msg: + logging.debug(f" skipSave target_z0: SDFvalueoutside the valid range or has no surface") + else: + logging.warning(f" Save target_z0 meshfailed: {type(e).__name__}: {error_msg[:100]}") + except Exception as e: + logging.warning(f" Save target_z0 meshfailed: {type(e).__name__}: {str(e)[:100]}") + + def save_final_target_z0_mesh(self, step_id: int): + """Force-save a target_z0 mesh at the final step.""" + try: + if self.target_z0_ema is not None: + target_z0 = self.target_z0_ema.detach().clone() + else: + target_z0, _ = self._computation_target_z0_current(step_id) + self._maybe_save_target_z0_mesh(target_z0, step_id, force=True) + except Exception as e: + logging.warning(f" ⚠️ failed to save the final target_z0: {type(e).__name__}: {str(e)[:100]}") + + def save_deformed_mesh(self, step: int, displacement: torch.Tensor, output_dir: str = None): + """Save the deformed mesh after the FEM solve. + + Args: + step: Current step. + displacement: FEM displacement field [num_nodes, 3]. + output_dir: Output directory, defaulting to config.out_folder/deformed_meshes. + """ + if output_dir is None: + if hasattr(self.config, 'out_folder'): + output_dir = os.path.join(self.config.out_folder, "deformed_meshes") + else: + output_dir = "results/deformed_meshes" + + os.makedirs(output_dir, exist_ok=True) + + try: + # Get original and deformed node positions. + original_nodes = self.nodes.detach().cpu().numpy() # [num_nodes, 3] + displacement_np = displacement.detach().cpu().numpy() # [num_nodes, 3] + deformed_nodes = original_nodes + displacement_np + + # Get element connectivity. + elements_np = self.elements.detach().cpu().numpy() # [num_elements, 8] + + # Save a VTK file for ParaView, including the displacement field. + vtk_path = os.path.join(output_dir, f"deformed_step_{step:04d}.vtk") + self._save_hex_mesh_vtk(deformed_nodes, elements_np, displacement_np, vtk_path, step) + + # Save OBJ/PLY using the decoded fine mesh and displacement colors. + decoded_mesh = self.latents_to_mesh(self.latents, octree_res=128) + if decoded_mesh is not None: + disp_vertices = self._sample_displacement_to_vertices( + decoded_mesh.vertices, original_nodes, displacement_np + ) + deformed_vertices = decoded_mesh.vertices + disp_vertices + colors = self._make_displacement_colors(disp_vertices) + + deformed_mesh = trimesh.Trimesh( + vertices=deformed_vertices, + faces=decoded_mesh.faces, + process=False, + ) + deformed_mesh.visual.vertex_colors = colors + + obj_path = os.path.join(output_dir, f"deformed_step_{step:04d}.obj") + ply_path = os.path.join(output_dir, f"deformed_step_{step:04d}.ply") + deformed_mesh.export(obj_path) + deformed_mesh.export(ply_path) + else: + # Fallback: export a surface mesh extracted from voxels. + obj_path = os.path.join(output_dir, f"deformed_step_{step:04d}.obj") + ply_path = os.path.join(output_dir, f"deformed_step_{step:04d}.ply") + self._save_surface_mesh_obj(deformed_nodes, elements_np, obj_path) + self._save_surface_mesh_ply(deformed_nodes, elements_np, displacement_np, ply_path) + + # Displacement statistics. + disp_mean = np.abs(displacement_np).mean() + disp_max = np.abs(displacement_np).max() + logging.info(f" 💾 saved deformed mesh : VTK={vtk_path.split('/')[-1]}, OBJ={obj_path.split('/')[-1]}, PLY={ply_path.split('/')[-1]}") + logging.debug(f" : mean={disp_mean:.4e}, max={disp_max:.4e}") + + except Exception as e: + logging.warning(f" ⚠️ Save deformed meshfailed (Step {step}): {e}") + + def save_final_deformed_mesh(self, step_id: int): + """Force-save the deformed mesh at the final step by solving FEM once more.""" + if not hasattr(self, 'nodes') or not hasattr(self, 'elements'): + logging.warning(" ⚠️ unable to save the finaldeformed mesh: missingnodes/elements") + return + if not hasattr(self, 'forces') or not hasattr(self, 'boundary_mask'): + logging.warning(" ⚠️ unable to save the finaldeformed mesh: missingforces/boundary_mask") + return + + try: + from torchfem.materials import IsotropicElasticity3D + from physiopt.opt.solid_grid import SolidGrid + from physiopt.opt.field import occ_kernel + + with torch.no_grad(): + # Refresh occupancy to match the current latents. + sdf = self.get_field(self.nodes) + occ = occ_kernel(sdf, self.config.res, self.config.occ_sdf_beta) + self.coarse_occ = occ[self.elements].mean(1) + + if self.config.alpha_min > 0.0: + self.coarse_occ = torch.clamp(self.coarse_occ, self.config.alpha_min) + + vectorized_material = IsotropicElasticity3D( + E=self.config.youngs_modulus, + nu=self.config.poissons_ratio, + rho=self.config.density, + ).vectorize(self.elements.shape[0]) + + vectorized_material.C *= ( + self.coarse_occ[:, None, None] ** self.config.p_exponent + ) + + solid = SolidGrid(self.nodes, self.elements, vectorized_material) + solid.constraints[self.boundary_mask, :] = True + solid.forces = self.forces + + logging.info(" 🧱 final deformed mesh: re-solve the FEM system to save ") + u, _, _, _, _, _ = solid.solve(max_iter=1) + self.save_deformed_mesh(step_id, u) + except Exception as e: + logging.warning(f" ⚠️ final deformed meshSave failed: {type(e).__name__}: {str(e)[:100]}") + + def _save_hex_mesh_vtk(self, nodes: np.ndarray, elements: np.ndarray, + displacement: np.ndarray, filename: str, step: int): + """Save a hexahedral mesh in VTK format.""" + num_nodes = nodes.shape[0] + num_elements = elements.shape[0] + + with open(filename, 'w') as f: + f.write("# vtk DataFile Version 3.0\n") + f.write(f"Deformed mesh at step {step}\n") + f.write("ASCII\n") + f.write("DATASET UNSTRUCTURED_GRID\n") + + # Node coordinates after deformation. + f.write(f"\nPOINTS {num_nodes} float\n") + for node in nodes: + f.write(f"{node[0]:.6f} {node[1]:.6f} {node[2]:.6f}\n") + + # Hexahedral cells. + f.write(f"\nCELLS {num_elements} {num_elements * 9}\n") + for elem in elements: + f.write(f"8 {elem[0]} {elem[1]} {elem[2]} {elem[3]} " + f"{elem[4]} {elem[5]} {elem[6]} {elem[7]}\n") + + # Cell type 12 = VTK_HEXAHEDRON. + f.write(f"\nCELL_TYPES {num_elements}\n") + for _ in range(num_elements): + f.write("12\n") + + # Displacement vector field. + f.write(f"\nPOINT_DATA {num_nodes}\n") + f.write("VECTORS displacement float\n") + for disp in displacement: + f.write(f"{disp[0]:.6e} {disp[1]:.6e} {disp[2]:.6e}\n") + + # Displacement magnitude scalar field. + f.write("\nSCALARS displacement_magnitude float 1\n") + f.write("LOOKUP_TABLE default\n") + for disp in displacement: + mag = np.linalg.norm(disp) + f.write(f"{mag:.6e}\n") + + def _save_surface_mesh_obj(self, nodes: np.ndarray, elements: np.ndarray, filename: str): + """Extract the surface from a hexahedral mesh and save it as OBJ.""" + # The six faces of a hexahedron. + hex_faces = [ + [0, 1, 2, 3], [4, 5, 6, 7], # Bottom, top. + [0, 1, 5, 4], [2, 3, 7, 6], # Front, back. + [0, 3, 7, 4], [1, 2, 6, 5], # Left, right. + ] + + # Collect faces that appear only once, i.e. surface faces. + face_count = {} + for elem in elements: + for face_indices in hex_faces: + face_nodes = tuple(sorted([elem[i] for i in face_indices])) + if face_nodes in face_count: + face_count[face_nodes] += 1 + else: + face_count[face_nodes] = 1 + + # Keep only surface faces. + surface_faces = [face for face, count in face_count.items() if count == 1] + + # Save OBJ. + with open(filename, 'w') as f: + f.write("# Deformed mesh surface\n") + for node in nodes: + f.write(f"v {node[0]:.6f} {node[1]:.6f} {node[2]:.6f}\n") + for face in surface_faces: + # OBJ indices are 1-based. + f.write(f"f {face[0]+1} {face[1]+1} {face[2]+1} {face[3]+1}\n") + + def _save_surface_mesh_ply(self, nodes: np.ndarray, elements: np.ndarray, + displacement: np.ndarray, filename: str): + """Save a colored surface mesh, where color encodes displacement magnitude.""" + # The six faces of a hexahedron. + hex_faces = [ + [0, 1, 2, 3], [4, 5, 6, 7], # Bottom, top. + [0, 1, 5, 4], [2, 3, 7, 6], # Front, back. + [0, 3, 7, 4], [1, 2, 6, 5], # Left, right. + ] + + # Collect faces that appear only once. + face_count = {} + for elem in elements: + for face_indices in hex_faces: + face_nodes = tuple(sorted([elem[i] for i in face_indices])) + if face_nodes in face_count: + face_count[face_nodes] += 1 + else: + face_count[face_nodes] = 1 + + # Keep only surface faces. + surface_faces = [face for face, count in face_count.items() if count == 1] + + # Map displacement magnitude to colors (blue -> red). + disp_mag = np.linalg.norm(displacement, axis=1) + norm, _, _, _ = self._normalize_displacement_magnitude(disp_mag) + colors = np.stack([norm, np.zeros_like(norm), 1.0 - norm], axis=1) + colors = (colors * 255).astype(np.uint8) + + # Save PLY with vertex colors. + with open(filename, 'w') as f: + f.write("ply\nformat ascii 1.0\n") + f.write(f"element vertex {len(nodes)}\n") + f.write("property float x\nproperty float y\nproperty float z\n") + f.write("property uchar red\nproperty uchar green\nproperty uchar blue\n") + f.write(f"element face {len(surface_faces)}\n") + f.write("property list uchar int vertex_indices\n") + f.write("end_header\n") + + for node, color in zip(nodes, colors): + f.write(f"{node[0]:.6f} {node[1]:.6f} {node[2]:.6f} " + f"{int(color[0])} {int(color[1])} {int(color[2])}\n") + + for face in surface_faces: + f.write(f"4 {face[0]} {face[1]} {face[2]} {face[3]}\n") + + def _save_force_visualization(self, seat_nodes_mask: torch.Tensor, total_force: np.ndarray): + """Save voxel-level load data for visualization and validation. + + This exports: + 1. NumPy (.npz) with full node/load data + 2. OBJ point clouds for quick inspection + 3. Optional VTK data for ParaView + + Args: + seat_nodes_mask: Mask of seat/contact nodes [num_nodes]. + total_force: Total force vector [3]. + """ + if not hasattr(self.config, 'out_folder'): + logging.warning(" out_folder is not set, skipSave loaded voxel") + return + + # Create the force_visualization subdirectory. + vis_dir = os.path.join(self.config.out_folder, "force_visualization") + os.makedirs(vis_dir, exist_ok=True) + + # ==================== 1. Save NumPy data (most complete format) ==================== + all_nodes_cpu = self.nodes.cpu().numpy() + all_forces_cpu = self.forces.cpu().numpy() + seat_mask_cpu = seat_nodes_mask.cpu().numpy() + + # Extract loaded nodes. + seat_nodes = all_nodes_cpu[seat_mask_cpu] + seat_forces = all_forces_cpu[seat_mask_cpu] + + npz_path = os.path.join(vis_dir, "force_nodes.npz") + np.savez( + npz_path, + # All node data. + all_nodes=all_nodes_cpu, + all_forces=all_forces_cpu, + # Loaded-node data. + seat_nodes=seat_nodes, + seat_forces=seat_forces, + seat_mask=seat_mask_cpu, + # Boundary-node data. + boundary_mask=self.boundary_mask.cpu().numpy() if hasattr(self, 'boundary_mask') else None, + # Metadata. + total_force=total_force, + num_seat_nodes=len(seat_nodes), + num_all_nodes=len(all_nodes_cpu), + ) + logging.info(f" 💾 Save load data (NumPy format) : {npz_path}") + + # ==================== 2. Save OBJ point clouds ==================== + # 2a. Loaded nodes (red point cloud). + seat_obj_path = os.path.join(vis_dir, "seat_nodes.obj") + with open(seat_obj_path, 'w') as f: + f.write("# Seat nodes (loaded area)\n") + f.write(f"# Total: {len(seat_nodes)} nodes\n") + f.write(f"# Force per node: {seat_forces[0] if len(seat_forces) > 0 else [0,0,0]}\n") + for node in seat_nodes: + f.write(f"v {node[0]:.6f} {node[1]:.6f} {node[2]:.6f}\n") + logging.info(f" 💾 Save seat nodes (OBJpoint cloud) : {seat_obj_path}") + + # 2b. Boundary nodes (blue point cloud). + if hasattr(self, 'boundary_mask'): + boundary_nodes = all_nodes_cpu[self.boundary_mask.cpu().numpy()] + boundary_obj_path = os.path.join(vis_dir, "boundary_nodes.obj") + with open(boundary_obj_path, 'w') as f: + f.write("# Boundary nodes (fixed area)\n") + f.write(f"# Total: {len(boundary_nodes)} nodes\n") + for node in boundary_nodes: + f.write(f"v {node[0]:.6f} {node[1]:.6f} {node[2]:.6f}\n") + logging.info(f" 💾 Save boundary nodes (OBJpoint cloud) : {boundary_obj_path}") + + # 2c. All nodes (gray point cloud) for comparison. + all_obj_path = os.path.join(vis_dir, "all_nodes.obj") + with open(all_obj_path, 'w') as f: + f.write("# All nodes\n") + f.write(f"# Total: {len(all_nodes_cpu)} nodes\n") + for node in all_nodes_cpu: + f.write(f"v {node[0]:.6f} {node[1]:.6f} {node[2]:.6f}\n") + logging.info(f" 💾 Save all nodes (OBJpoint cloud) : {all_obj_path}") + + # ==================== 3. Save VTK data for ParaView ==================== + try: + vtk_path = os.path.join(vis_dir, "force_field.vtk") + with open(vtk_path, 'w') as f: + # VTK Header + f.write("# vtk DataFile Version 3.0\n") + f.write("Force field visualization\n") + f.write("ASCII\n") + f.write("DATASET UNSTRUCTURED_GRID\n") + + # Points + f.write(f"POINTS {len(all_nodes_cpu)} float\n") + for node in all_nodes_cpu: + f.write(f"{node[0]:.6f} {node[1]:.6f} {node[2]:.6f}\n") + + # Cells (vertices) + f.write(f"\nCELLS {len(all_nodes_cpu)} {len(all_nodes_cpu)*2}\n") + for i in range(len(all_nodes_cpu)): + f.write(f"1 {i}\n") + + # Cell types (1 = vertex) + f.write(f"\nCELL_TYPES {len(all_nodes_cpu)}\n") + for _ in range(len(all_nodes_cpu)): + f.write("1\n") + + # Point data (force vectors) + f.write(f"\nPOINT_DATA {len(all_nodes_cpu)}\n") + f.write("VECTORS force float\n") + for force in all_forces_cpu: + f.write(f"{force[0]:.6e} {force[1]:.6e} {force[2]:.6e}\n") + + # Scalar field: force magnitude + f.write("\nSCALARS force_magnitude float 1\n") + f.write("LOOKUP_TABLE default\n") + for force in all_forces_cpu: + mag = np.linalg.norm(force) + f.write(f"{mag:.6e}\n") + + # Scalar field: is_seat (0 or 1) + f.write("\nSCALARS is_seat int 1\n") + f.write("LOOKUP_TABLE default\n") + for is_seat in seat_mask_cpu: + f.write(f"{int(is_seat)}\n") + + logging.info(f" 💾 Save force field (VTK format, ParaView) : {vtk_path}") + except Exception as e: + logging.warning(f" ⚠️ Save VTK formatfailed: {e}") + + # ==================== 4. Generate a Python visualization script ==================== + vis_script_path = os.path.join(vis_dir, "visualize_forces.py") + with open(vis_script_path, 'w') as f: + f.write("""#!/usr/bin/env python3 +\"""Visualize voxel load data + +Usage: + python visualize_forces.py + +Requirements: + pip install numpy matplotlib + +\""" +import numpy as np +import matplotlib.pyplot as plt +from mpl_toolkits.mplot3d import Axes3D + +# Load data. +data = np.load('force_nodes.npz') +all_nodes = data['all_nodes'] +seat_nodes = data['seat_nodes'] +seat_forces = data['seat_forces'] +total_force = data['total_force'] + +# Create the 3D figure. +fig = plt.figure(figsize=(15, 5)) + +# Subplot 1: all nodes (gray) + loaded nodes (red). +ax1 = fig.add_subplot(131, projection='3d') +ax1.scatter(all_nodes[:, 0], all_nodes[:, 1], all_nodes[:, 2], + c='lightgray', s=0.5, alpha=0.3, label='All nodes') +ax1.scatter(seat_nodes[:, 0], seat_nodes[:, 1], seat_nodes[:, 2], + c='red', s=5, alpha=1.0, label='Seat nodes (loaded)') +ax1.set_xlabel('X') +ax1.set_ylabel('Y (up)') +ax1.set_zlabel('Z') +ax1.set_title(f'Loaded Nodes\\n({len(seat_nodes)}/{len(all_nodes)} nodes)') +ax1.legend() + +# Subplot 2: Y distribution of loaded nodes. +ax2 = fig.add_subplot(132) +y_coords = seat_nodes[:, 1] +ax2.hist(y_coords, bins=30, color='red', alpha=0.7, edgecolor='black') +ax2.axvline(y_coords.min(), color='blue', linestyle='--', label=f'Y_min={y_coords.min():.3f}') +ax2.axvline(y_coords.max(), color='green', linestyle='--', label=f'Y_max={y_coords.max():.3f}') +ax2.set_xlabel('Y coordinate (height)') +ax2.set_ylabel('Number of nodes') +ax2.set_title('Seat Node Y Distribution') +ax2.legend() +ax2.grid(True, alpha=0.3) + +# Subplot 3: XZ force-vector layout in top view. +ax3 = fig.add_subplot(133) +ax3.scatter(seat_nodes[:, 0], seat_nodes[:, 2], c='red', s=10, alpha=0.5) +# Draw a sparse subset of force vectors to avoid clutter. +step = max(1, len(seat_nodes) // 50) +for i in range(0, len(seat_nodes), step): + node = seat_nodes[i] + force = seat_forces[i] + # Scale force vectors for visualization. + scale = 0.01 + ax3.arrow(node[0], node[2], force[0]*scale, force[2]*scale, + head_width=0.02, head_length=0.01, fc='blue', ec='blue', alpha=0.7) +ax3.set_xlabel('X') +ax3.set_ylabel('Z') +ax3.set_title(f'Top View (XZ plane)\\nForce: {total_force}') +ax3.axis('equal') +ax3.grid(True, alpha=0.3) + +plt.tight_layout() +plt.savefig('force_visualization.png', dpi=150, bbox_inches='tight') +logging.info("✅ image saved : force_visualization.png") +plt.show() + +# Print summary statistics. +logging.info("\\n" + "="*60) +logging.info("force voxel statistics") +logging.info("="*60) +logging.info(f"total node count: {len(all_nodes)}") +logging.info(f"loaded node count: {len(seat_nodes)} ({len(seat_nodes)/len(all_nodes)*100:.1f}%)") +logging.info(f"total: {total_force}") +logging.info(f"per nodeaverage force per node: {seat_forces.mean(axis=0)}") +logging.info(f"\\nY-coordinate range:") +logging.info(f" - min: {y_coords.min():.3f}") +logging.info(f" - max: {y_coords.max():.3f}") +logging.info(f" - mean: {y_coords.mean():.3f}") +logging.info(f" - height span: {y_coords.max() - y_coords.min():.3f}") +logging.info("="*60) +""") + os.chmod(vis_script_path, 0o755) # Add execute permission. + logging.info(f" 💾 Save visualization script: {vis_script_path}") + + # ==================== 5. Generate a README document ==================== + readme_path = os.path.join(vis_dir, "README.md") + with open(readme_path, 'w') as f: + f.write(f"""# Load Voxel Visualization Data + +Generated at: {np.datetime64('now')} + +## Statistics + +- **Total nodes**: {len(all_nodes_cpu)} +- **Loaded nodes**: {len(seat_nodes)} ({len(seat_nodes)/len(all_nodes_cpu)*100:.1f}%) +- **Total force**: {total_force} +- **Force per node**: {seat_forces[0] if len(seat_forces) > 0 else [0,0,0]} + +## Files + +### 1. NumPy format (recommended for analysis) + +- `force_nodes.npz`: contains the full dataset + - `all_nodes`: coordinates of all nodes [{len(all_nodes_cpu)}, 3] + - `all_forces`: force vectors on all nodes [{len(all_nodes_cpu)}, 3] + - `seat_nodes`: coordinates of loaded nodes [{len(seat_nodes)}, 3] + - `seat_forces`: force vectors on loaded nodes [{len(seat_nodes)}, 3] + - `seat_mask`: mask of loaded nodes [{len(all_nodes_cpu)}] + - `boundary_mask`: mask of boundary nodes [{len(all_nodes_cpu)}] + +**Example**: +```python +import numpy as np +data = np.load('force_nodes.npz') +seat_nodes = data['seat_nodes'] +print(f"Loaded nodes: {{len(seat_nodes)}}") +``` + +### 2. OBJ format (recommended for quick inspection) + +- `seat_nodes.obj`: loaded nodes (red point cloud) +- `boundary_nodes.obj`: boundary nodes (blue point cloud) +- `all_nodes.obj`: all nodes (gray point cloud) + +**Usage**: +1. Open in Meshlab: `meshlab seat_nodes.obj` +2. Or import the OBJ files into Blender +3. You can load multiple OBJ files together for comparison + +### 3. VTK format (recommended for professional visualization) + +- `force_field.vtk`: force-field data with vector information + +**Usage**: +1. Open in ParaView: `paraview force_field.vtk` +2. In ParaView: + - Use `Glyph` to visualize force vectors + - Color by `force_magnitude` to inspect strength + - Filter by `is_seat` to isolate the loaded region + +### 4. Visualization script + +- `visualize_forces.py`: Python visualization script + +**Usage**: +```bash +python visualize_forces.py +``` +""") + logging.info(f" 💾 Save README document: {readme_path}") + + # Print a short summary. + logging.info(f" ✅ force voxel data saved successfully!") + logging.info(f" - view directory: {vis_dir}") + logging.info(f" - quick visualization: cd {vis_dir} && python visualize_forces.py") + logging.info(f" - view in Meshlab: meshlab {os.path.join(vis_dir, 'seat_nodes.obj')}") + + +def load_hunyuan_models(model_path: str = "tencent/Hunyuan3D-2.1", + subfolder: str = "hunyuan3d-shapegen", + use_safetensors: bool = True): + """Load the Hunyuan3D models (VAE, Flow Model, and Scheduler). + + Args: + model_path: Model path, either a Hugging Face ID or a local directory. + subfolder: Model subfolder name. + use_safetensors: Whether to load safetensors checkpoints. + + Returns: + (vae, flow_model, scheduler): the VAE, Flow Matching model, and scheduler. + """ + logging.info(f"🔧 loading Hunyuan3D-2.1model...") + logging.info(f" modelpath: {model_path}") + logging.info(f" subfolder: {subfolder}") + logging.info(f" modelformat: {'safetensors' if use_safetensors else 'checkpoint'}") + + try: + pipeline = Hunyuan3DDiTFlowMatchingPipeline.from_pretrained( + model_path, + subfolder=subfolder, + torch_dtype=torch.float16, + use_safetensors=use_safetensors + ) + + if pipeline is None: + raise ValueError("pipeline loading failed and returned None") + + logging.info(" ✅ pipeline loaded successfully") + + pipeline.to('cuda') + logging.info(" ✅ modelmoved to CUDA (dtype: fp16)") + + vae = pipeline.vae + flow_model = pipeline.model + scheduler = pipeline.scheduler + + return vae, flow_model, scheduler + + except Exception as e: + logging.error(f"\n❌ modelloadfailed: {e}") + logging.error(f"\nPossible fixes:") + logging.error(f"1. make sure Hunyuan3D is installed-2.1: cd Hunyuan3D-2.1 && pip install -e .") + logging.error(f"2. check network connectivity to huggingface.co") + logging.error(f"3. or download manually: git clone https://huggingface.co/tencent/Hunyuan3D-2") + import traceback + traceback.print_exc() + sys.exit(1) + +def main(): + """Parse CLI arguments and run the optimization.""" + import argparse + + parser = argparse.ArgumentParser(description="Hunyuan3D physics optimization + shape-prior optimization") + + # Required arguments. + parser.add_argument("--latents", type=str, required=True, + help="Input latents file path (.pt)") + parser.add_argument("--out_folder", type=str, default="../out/hunyuan_opt", + help="Output folder path") + + # Model arguments. + parser.add_argument("--model_path", type=str, default="tencent/Hunyuan3D-2.1", + help="Model path (using v2.1)") + parser.add_argument("--subfolder", type=str, default="hunyuan3d-dit-v2-1", + help="Model subfolder") + parser.add_argument("--use_safetensors", action="store_true", + help="Use safetensors format (default: ckpt)") + + # Physical-simulation arguments. + parser.add_argument("--use_physics", action="store_true", + help="Enable physics-constrained optimization") + parser.add_argument("--res", type=int, default=16, + help="Voxel resolution (16/32/64)") + parser.add_argument("--youngs_modulus_scale", type=float, default=2.0, + help="Final Young's modulus multiplier (default 2x after the last projection)") + parser.add_argument("--compliance_threshold", type=float, default=None, + help="Target compliance threshold (None = automatic)") + parser.add_argument("--compliance_threshold_ratio", type=float, default=0.3, + help="Automatic threshold ratio (threshold = initial value × ratio)") + + # Optimization arguments. + parser.add_argument("--num_steps", type=int, default=300, + help="Number of optimization steps (pure SDS only; in physics mode it becomes outer_cycles * phys_steps_per_cycle automatically)") + parser.add_argument("--outer_cycles", type=int, default=100, + help="Number of outer cycles (each cycle = physics optimization + projection)") + parser.add_argument("--phys_steps_per_cycle", type=int, default=5, + help="Number of physics-optimization steps per outer cycle") + parser.add_argument("--lr", type=float, default=5e-3, + help="Learning rate (increase to 0.005 to help the mesh thicken faster) ") + parser.add_argument("--lagrange_max", type=float, default=10.0, + help="Maximum Lagrange multiplier (recommended: 5-20)") + parser.add_argument("--alm_rho_init", type=float, default=1.0, + help="ALM rhoinitial value") + parser.add_argument("--alm_rho_max", type=float, default=1000.0, + help="ALM rhoMax") + parser.add_argument("--alm_rho_increase_factor", type=float, default=2.0, + help="ALM rhogrowth factor") + parser.add_argument("--alm_rho_increase_patience", type=int, default=5, + help="ALM rhonumber of consecutive violation steps required before increasing") + parser.add_argument("--alm_scale_guard_ratio", type=float, default=0.95, + help="ALMscaling guard ratio(<=1), control the upper bound of the physics-gradient target=this ratio x clipping-threshold value") + parser.add_argument("--grad_clip_enabled", action="store_true", + help="Enable gradient clipping (disabled by default; otherwise only NaN/Inf checks are kept)") + parser.add_argument("--use_sgd", action="store_true", + help="Use SGD instead of Adam") + parser.add_argument("--force_config", type=str, default=None, + help="Path to the external-force JSON config (generated by the web UI)") + parser.add_argument("--force", type=float, nargs=3, action="append", default=None, + help="External force vector [fx fy fz] (N, Y-up coordinates; can be specified multiple times)") + parser.add_argument("--global_loading", action="store_true", + help="Use global uniform loading (disable local loading)") + parser.add_argument("--force_region_mode", type=str, default="top_percent", + choices=["top_percent", "height_ratio", "bbox"], + help="How to choose the local loading region") + parser.add_argument("--force_top_percent", type=float, default=0.05, + help="top_percent mode: select the highest-Y fraction") + parser.add_argument("--force_bbox", type=float, nargs=6, default=None, + help="bbox mode: x_min x_max y_min y_max z_min z_max (absolute coordinates)") + parser.add_argument("--force_bbox_ratio", type=float, nargs=6, default=None, + help="bbox mode (0-1): bbox relative to the node bounds") + parser.add_argument("--seat_height_min_ratio", type=float, default=0.3, + help="height_ratio mode: lower seat boundary (0-1)") + parser.add_argument("--seat_height_max_ratio", type=float, default=0.5, + help="height_ratio mode: upper seat boundary (0-1)") + + # SDS arguments. + parser.add_argument("--sds_weight", type=float, default=1.0, + help="SDS gradient weight (deprecated; use sds_weight_start and sds_weight_end instead)") + parser.add_argument("--sds_weight_start", type=float, default=10.0, + help="Initial SDS weight (linearly increased; 0.0001 is recommended to avoid disturbing physics optimization)") + parser.add_argument("--sds_weight_end", type=float, default=10.0, + help="Final SDS weight (linearly increased; 0.001 is recommended, about 1/10 of the physics gradient)") + parser.add_argument("--sds_timestep", type=float, default=0.1, + help="SDS timestep (recommended: 0.05-0.2)") + parser.add_argument("--sds_target_z0_ema_beta", type=float, default=0.9, + help="target_z0 EMA smoothing factor (larger means smoother)") + parser.add_argument("--deformed_mesh_interval", type=int, default=10, + help="Interval for saving deformed meshes (steps)") + parser.add_argument("--deformed_mesh_disp_min", type=float, default=0.0, + help="Minimum displacement for deformed-mesh color mapping (default 0.0)") + parser.add_argument("--deformed_mesh_disp_max", type=float, default=0.2, + help="Maximum displacement for deformed-mesh color mapping (<=0 enables per-step auto scaling)") + parser.add_argument("--guidance_scale", type=float, default=7.5, + help="CFG guidance scale (standard value: 7.5; larger means stronger image conditioning)") + parser.add_argument("--sds_projection_max_rel", type=float, default=0.0, + help="Maximum relative target_z0 projection deviation (0 = unlimited)") + parser.add_argument("--sds_use_uncond", action="store_true", + help="Use the unconditional branch (only takes effect when guidance_scale <= 1)") + + # Topology control. + parser.add_argument("--keep_all_components", action="store_true", + help="Keep all connected components (to avoid disappearing chair legs)") + parser.add_argument("--re_extract_interval", type=int, default=1, + help="Solid re-extraction interval (0 = disabled)") + + args = parser.parse_args() + + def _normalize_force_vectors(value): + if value is None: + return None + if isinstance(value, (list, tuple)) and len(value) > 0: + if isinstance(value[0], (list, tuple)): + candidates = value + else: + candidates = [value] + else: + return None + normalized = [] + for vec in candidates: + if not isinstance(vec, (list, tuple)) or len(vec) != 3: + continue + try: + normalized.append([float(v) for v in vec]) + except Exception: + continue + return normalized if normalized else None + + def _normalize_force_entry(entry): + if not isinstance(entry, dict): + return None + forces = _normalize_force_vectors(entry.get("forces")) + if forces is None: + forces = _normalize_force_vectors(entry.get("force")) + if forces is None: + return None + out = dict(entry) + if len(forces) > 1: + out["forces"] = forces + out["force"] = [float(sum(v[i] for v in forces)) for i in range(3)] + else: + out["force"] = forces[0] + out.pop("forces", None) + if "force_region_mode" in out: + out["force_region_mode"] = str(out["force_region_mode"]) + if "global_loading" in out: + out["global_loading"] = bool(out["global_loading"]) + if "force_top_percent" in out: + out["force_top_percent"] = float(out["force_top_percent"]) + if "seat_height_min_ratio" in out: + out["seat_height_min_ratio"] = float(out["seat_height_min_ratio"]) + if "seat_height_max_ratio" in out: + out["seat_height_max_ratio"] = float(out["seat_height_max_ratio"]) + if "force_bbox" in out and isinstance(out["force_bbox"], (list, tuple)) and len(out["force_bbox"]) == 6: + out["force_bbox"] = [float(v) for v in out["force_bbox"]] + elif "force_bbox" in out: + out.pop("force_bbox", None) + if "force_bbox_ratio" in out and isinstance(out["force_bbox_ratio"], (list, tuple)) and len(out["force_bbox_ratio"]) == 6: + out["force_bbox_ratio"] = [float(v) for v in out["force_bbox_ratio"]] + elif "force_bbox_ratio" in out: + out.pop("force_bbox_ratio", None) + return out + + # Load force configuration from JSON, typically exported from the web UI. + force_config_loaded = False + force_config_error = None + force_entries = None + if args.force_config: + raw_force_config = args.force_config + candidates = [] + if os.path.isabs(raw_force_config): + candidates.append(raw_force_config) + else: + candidates.append(raw_force_config) + script_dir = os.path.dirname(os.path.abspath(__file__)) + candidates.append(os.path.join(script_dir, raw_force_config)) + candidates.append(os.path.join(os.path.dirname(script_dir), raw_force_config)) + force_config_path = next((p for p in candidates if os.path.exists(p)), None) + if force_config_path is None: + force_config_error = f"Path does not exist; tried: {candidates}" + else: + args.force_config = force_config_path + try: + with open(force_config_path, "r") as f: + force_cfg = json.load(f) + if isinstance(force_cfg, dict): + cfg_forces = _normalize_force_vectors(force_cfg.get("forces")) + if cfg_forces is not None: + args.force = cfg_forces + else: + cfg_force = _normalize_force_vectors(force_cfg.get("force")) + if cfg_force is not None: + args.force = cfg_force + elif "force" in force_cfg or "forces" in force_cfg: + force_config_error = "force/forcesinvalid format" + if "global_loading" in force_cfg: + args.global_loading = bool(force_cfg["global_loading"]) + if "force_region_mode" in force_cfg: + args.force_region_mode = str(force_cfg["force_region_mode"]) + if "force_top_percent" in force_cfg: + args.force_top_percent = float(force_cfg["force_top_percent"]) + if "seat_height_min_ratio" in force_cfg: + args.seat_height_min_ratio = float(force_cfg["seat_height_min_ratio"]) + if "seat_height_max_ratio" in force_cfg: + args.seat_height_max_ratio = float(force_cfg["seat_height_max_ratio"]) + if "force_bbox" in force_cfg: + args.force_bbox = force_cfg["force_bbox"] + if "force_bbox_ratio" in force_cfg: + args.force_bbox_ratio = force_cfg["force_bbox_ratio"] + if "force_entries" in force_cfg: + raw_entries = force_cfg["force_entries"] + if isinstance(raw_entries, list): + normalized_entries = [] + for entry in raw_entries: + norm_entry = _normalize_force_entry(entry) + if norm_entry is not None: + normalized_entries.append(norm_entry) + if normalized_entries: + force_entries = normalized_entries + else: + force_config_error = "force_entries has no valid entries" + else: + force_config_error = "force_entriesinvalid format" + force_config_loaded = True + else: + force_config_error = f"force_configis not a dict: {type(force_cfg)}" + except Exception as e: + force_config_error = f"read failed: {e}" + + # Configure logging. force=True ensures this replaces any prior setup. + os.makedirs(args.out_folder, exist_ok=True) + log_file = os.path.join(args.out_folder, "optimization.log") + + # Remove any existing handlers. + for handler in logging.root.handlers[:]: + logging.root.removeHandler(handler) + + # Reconfigure logging. + logging.basicConfig( + level=logging.INFO, + format='%(asctime)s - %(levelname)s - %(message)s', + handlers=[ + logging.FileHandler(log_file, mode='w'), # Rewrite the log on each run. + logging.StreamHandler() + ], + force=True # Python 3.8+: force a full reconfiguration. + ) + + logging.info(f"🔧 logging configuration completed") + logging.info(f" - log file: {log_file}") + logging.info(f" - output mode: file + console") + if args.force_config: + if force_config_loaded: + logging.info(" ✅ force_configloaded") + logging.info(f" - path: {args.force_config}") + logging.info(f" - forces: {args.force}") + if force_entries: + logging.info(f" - force_entries: {len(force_entries)}") + logging.info(f" - global_loading: {args.global_loading}") + logging.info(f" - force_region_mode: {args.force_region_mode}") + logging.info(f" - force_top_percent: {args.force_top_percent}") + logging.info(f" - seat_height_min_ratio: {args.seat_height_min_ratio}") + logging.info(f" - seat_height_max_ratio: {args.seat_height_max_ratio}") + logging.info(f" - force_bbox: {args.force_bbox}") + logging.info(f" - force_bbox_ratio: {args.force_bbox_ratio}") + if force_config_error: + logging.warning(f" ⚠️ force_configsome fields are invalid: {force_config_error}") + else: + logging.warning(f" ⚠️ force_configloadfailed: {force_config_error}") + + # In physics mode, derive num_steps from outer_cycles and phys_steps_per_cycle. + if args.use_physics: + outer_cycles = max(1, int(args.outer_cycles)) + phys_steps_per_cycle = max(1, int(args.phys_steps_per_cycle)) + derived_num_steps = outer_cycles * phys_steps_per_cycle + if args.num_steps != derived_num_steps: + logging.info( + f" - num_stepsautomatically set: {args.num_steps} → {derived_num_steps} " + f"(outer_cycles={outer_cycles}, phys_steps_per_cycle={phys_steps_per_cycle})" + ) + args.num_steps = derived_num_steps + + # ==================== Save run metadata ==================== + # 1. Save the command line. + command_file = os.path.join(args.out_folder, "run_command.txt") + try: + with open(command_file, 'w') as f: + f.write("=" * 80 + "\n") + f.write("Command used (Command Used)\n") + f.write("=" * 80 + "\n\n") + f.write("Full command:\n") + f.write("python " + " ".join(sys.argv) + "\n\n") + + f.write("=" * 80 + "\n") + f.write("Arguments (Arguments)\n") + f.write("=" * 80 + "\n\n") + for arg, value in vars(args).items(): + f.write(f"{arg}: {value}\n") + + f.write("\n" + "=" * 80 + "\n") + f.write("Environment (Environment)\n") + f.write("=" * 80 + "\n\n") + f.write(f"Python: {sys.version}\n") + f.write(f"PyTorch: {torch.__version__}\n") + f.write(f"CUDA Available: {torch.cuda.is_available()}\n") + if torch.cuda.is_available(): + f.write(f"CUDA Version: {torch.version.cuda}\n") + f.write(f"GPU Count: {torch.cuda.device_count()}\n") + + logging.info(f" - saved command used : {command_file}") + except Exception as e: + logging.warning(f" ⚠️ Save Command usedfailed: {e}") + + # 2. Save a copy of the current script. + script_backup = os.path.join(args.out_folder, "viewer_hunyuan_web_alternate.py") + try: + current_script = os.path.abspath(__file__) + shutil.copy2(current_script, script_backup) + logging.info(f" - saved script copy : {script_backup}") + except Exception as e: + logging.warning(f" ⚠️ Save failed to save script copy: {e}") + + # Load latents and conditioning data. + logging.info(f"\n📂 loading input data...") + logging.info(f" - Latents: {args.latents}") + + data = torch.load(args.latents, map_location='cpu') + + # Extract latents. + if isinstance(data, dict) and 'latents' in data: + latents = data['latents'] + else: + latents = data + + logging.info(f" ✅ Latents shape: {latents.shape}") + + # Check conditioning data (image_embeds or image). + need_encode_cond = False + image_embeds = None + image = None + + if isinstance(data, dict): + if 'image' in data: + # New format: only the image was saved, so we need to re-encode it. + logging.info(f" - detected image data; re-encoding as conditional embeds") + image_array = data['image'] + image = Image.fromarray(image_array) + need_encode_cond = True + elif 'image_embeds' in data: + # Legacy format: embeddings are already saved. + logging.info(f" - using the saved conditional embeds") + image_embeds = data['image_embeds'] + need_encode_cond = False + elif 'cond' in data: + # Alternate format using a saved cond dict. + logging.info(f" - using the saved cond") + image_embeds = data['cond'] + need_encode_cond = False + else: + raise ValueError("latents.ptis missingimage, image_embedsor cond data") + else: + raise ValueError("latentsmust be a dictionary containing'latents'andconditioninformation dict") + + if image_embeds is not None: + if isinstance(image_embeds, dict): + logging.info(f" ✅ Cond keys: {list(image_embeds.keys())}") + else: + logging.info(f" ✅ Image embeds shape: {image_embeds.shape}") + + # Load models. + logging.info(f"\n🔧 loading Hunyuan3Dmodel...") + vae, flow_model, scheduler = load_hunyuan_models( + model_path=args.model_path, + subfolder=args.subfolder, + use_safetensors=args.use_safetensors + ) + + # ==================== Encode conditioning data if needed ==================== + if need_encode_cond: + logging.info("🎨 encoding conditional embeds from the image...") + + # Reload the full pipeline for condition encoding. + from hy3dgen.shapegen import Hunyuan3DDiTFlowMatchingPipeline + + pipeline = Hunyuan3DDiTFlowMatchingPipeline.from_pretrained( + args.model_path, + subfolder=args.subfolder, + torch_dtype=torch.float16, + use_safetensors=args.use_safetensors + ) + pipeline.to('cuda') + + with torch.no_grad(): + # Prepare the image. + cond_inputs = pipeline.prepare_image(image) + image_tensor = cond_inputs.pop('image') + + # Enable CFG so the encoded condition contains both branches. + cond_dict = pipeline.encode_cond( + image=image_tensor, + additional_cond_inputs=cond_inputs, + do_classifier_free_guidance=True, # Enable CFG. + dual_guidance=False, + ) + + # Save the condition dict. + image_embeds = cond_dict + + logging.info(f" ✅ condition encoding completed (CFG mode) ") + logging.info(f" - Cond keys: {list(cond_dict.keys()) if isinstance(cond_dict, dict) else 'tensor'}") + + # Resolve the compliance threshold. + if args.compliance_threshold is None: + compliance_threshold = 200.0 + logging.info(f" using the default compliance threshold: {compliance_threshold}") + else: + compliance_threshold = args.compliance_threshold + logging.info(f" using the custom compliance threshold: {compliance_threshold}") + + target_z0_update_interval = max(1, int(args.phys_steps_per_cycle)) + forces = None + normalized_forces = _normalize_force_vectors(args.force) + if normalized_forces: + forces = [{'external_force': vec} for vec in normalized_forces] + elif args.force is not None: + logging.warning(f" ⚠️ invalid external force vector; ignoring: {args.force}") + # Build the optimization config. + config = OptimizationConfig( + num_steps=args.num_steps, + lr=args.lr, + sds_timestep=args.sds_timestep, + sds_weight=args.sds_weight if args.use_physics else 1.0, # Keep backward compatibility. + sds_weight_start=args.sds_weight_start, # Dynamic weight schedule start. + sds_weight_end=args.sds_weight_end, # Dynamic weight schedule end. + guidance_scale=args.guidance_scale, # CFG guidance scale. + sds_projection_max_rel=args.sds_projection_max_rel, + sds_use_uncond=args.sds_use_uncond, + sds_target_z0_update_interval=target_z0_update_interval, + sds_target_z0_ema_beta=args.sds_target_z0_ema_beta, + deformed_mesh_interval=args.deformed_mesh_interval, + deformed_mesh_disp_min=args.deformed_mesh_disp_min, + deformed_mesh_disp_max=args.deformed_mesh_disp_max, + use_sgd=args.use_sgd, + grad_clip_enabled=args.grad_clip_enabled, + # Physical parameters. + res=args.res, + lagrange_max=args.lagrange_max, + compliance_threshold=compliance_threshold, + alm_rho_init=args.alm_rho_init, + alm_rho_max=args.alm_rho_max, + alm_rho_increase_factor=args.alm_rho_increase_factor, + alm_rho_increase_patience=args.alm_rho_increase_patience, + alm_scale_guard_ratio=args.alm_scale_guard_ratio, + youngs_modulus_scale=args.youngs_modulus_scale, + # Topology control. + one_cc_only=not args.keep_all_components, + re_extract_interval=args.re_extract_interval, + # Loads and load-region settings. + forces=forces, + force_entries=force_entries, + use_local_loading=not args.global_loading, + seat_height_min_ratio=args.seat_height_min_ratio, + seat_height_max_ratio=args.seat_height_max_ratio, + force_region_mode=args.force_region_mode, + force_top_percent=args.force_top_percent, + force_bbox=args.force_bbox, + force_bbox_ratio=args.force_bbox_ratio, + # Output path. + out_folder=args.out_folder, + ) + + # Create the optimizer. + optimizer = HunyuanSDSOptimizer( + latents=latents, + cond=image_embeds, + vae=vae, + flow_model=flow_model, + scheduler=scheduler, + config=config, + device='cuda' + ) + + # Prepare physics if requested. + final_step = args.num_steps + if args.use_physics: + logging.info(f"\n🔬 enable physics optimization mode") + logging.info(f" - Voxel resolution: {args.res}") + logging.info(f" - physics steps/cycle: {args.phys_steps_per_cycle}, outer cycles: {args.outer_cycles}") + logging.info(f" - projection noise: sds_timestep={args.sds_timestep}") + logging.info(f" - target_z0update interval: {target_z0_update_interval} (consistent with phys_steps_per_cycle)") + logging.info(f" - LagrangeMax: {args.lagrange_max}") + + try: + optimizer.extract_solid(step=-1) # Initial extraction. + optimizer.prepare_physical_simulation() + logging.info(f" ✅ physics simulationInitializationsucceeded") + except Exception as e: + logging.warning(f" ⚠️ warning: initial mesh extraction failed (this is normal, optimizationbe repaired during the optimization process) ") + logging.warning(f" error information: {str(e)[:100]}") + # Continue anyway: the key physical state is the occupancy field, not the mesh. + else: + logging.info(f"\n🎨 using pure SDS optimization mode") + + # Optimization loop. + optimization_mode = "Alternating Phys/Projection" if args.use_physics else "Pure SDS" + total_steps_hint = ( + int(args.outer_cycles) * (int(args.phys_steps_per_cycle) + 1) + if args.use_physics + else args.num_steps + ) + logging.info(f"\n🚀 start{optimization_mode}optimization ({total_steps_hint} steps)...") + + if args.use_physics: + lagrange_multiplier = 0.0 + rho = config.alm_rho_init + violation_count = 0 + + # Automatically set the compliance threshold when needed. + if config.compliance_threshold is None or config.compliance_threshold == 200.0: + logging.info(f" 📊 computationinitialcompliancethreshold value...") + try: + initial_compliance, _, _ = optimizer.training_step_dual_lagrange_v2( + 0, 0.0, 0.0, use_sds=False + ) + # Auto threshold: initial compliance times the requested ratio. + auto_threshold = initial_compliance * args.compliance_threshold_ratio + auto_threshold = min(auto_threshold, 100000.0) # Upper bound only. + compliance_threshold = auto_threshold + config.compliance_threshold = auto_threshold + logging.info( + f" ✅ Automatically set the threshold: {initial_compliance:.2e} × {args.compliance_threshold_ratio:.2f} " + f"= {compliance_threshold:.2e}" + ) + + # Warn when the structure already looks extremely stiff or too soft. + if initial_compliance < 0.01: # Already very stiff. + logging.warning(f" ⚠️ initial compliance is very small ({initial_compliance:.2e}), the structure may already be stiff enough!") + logging.warning(f" consider increasing the external force or using a softer material to create visible deformation") + logging.warning(f" current material: E={config.youngs_modulus:.2e} Pa, ν={config.poissons_ratio}") + elif initial_compliance > 1000.0: # Likely too soft. + logging.warning(f" ⚠️ initial compliance is very large ({initial_compliance:.2e}), the structure may be too soft!") + logging.warning(f" consider using a stiffer material or reducing the external force") + except Exception as e: + logging.warning(f" ⚠️ automatic computation failed, usethreshold value200: {e}") + compliance_threshold = 200.0 + else: + compliance_threshold = config.compliance_threshold + + logging.info(f"🎯 parameters:") + logging.info(f" - initial lambda: {lagrange_multiplier}") + logging.info(f" - initial rho: {rho}") + logging.info(f" - Compliancethreshold value: {compliance_threshold:.2e}") + logging.info(f" - λMax: {args.lagrange_max}") + logging.info(f" - ρMax: {config.alm_rho_max:.1e}") + logging.info(f" - rho growth: ×{config.alm_rho_increase_factor:.1f} (continuous violations{config.alm_rho_increase_patience} steps)") + logging.info(f" - ALMscaling guard ratio: {config.alm_scale_guard_ratio:.2f}") + logging.info(f" - gradient clipping: {'enabled' if config.grad_clip_enabled else 'disabled'}") + + outer_cycles = max(1, int(args.outer_cycles)) + phys_steps_per_cycle = max(1, int(args.phys_steps_per_cycle)) + total_steps = outer_cycles * (phys_steps_per_cycle + 1) + logging.info( + f"🔁 Alternating optimization: outer cycles={outer_cycles}, physics steps/cycle={phys_steps_per_cycle}, " + f"total steps(including projections)≈{total_steps}" + ) + base_youngs_modulus = float(config.youngs_modulus) + youngs_modulus_scale = float(config.youngs_modulus_scale) + youngs_modulus_target = base_youngs_modulus * youngs_modulus_scale + youngs_modulus_delta = (youngs_modulus_target - base_youngs_modulus) / outer_cycles + projection_count = 0 + logging.info( + f" - linearly increase Young's modulus: E0={base_youngs_modulus:.2e}, " + f"Δ/projection={youngs_modulus_delta:.2e}, E_final={youngs_modulus_target:.2e} " + f"(scale={youngs_modulus_scale:.2f}x)" + ) + global_step = 0 + phys_step_count = 0 + for cycle in range(outer_cycles): + logging.info(f"\n{'='*60}") + logging.info(f"Outer Cycle {cycle+1}/{outer_cycles}") + logging.info(f"{'='*60}") + + for inner in range(phys_steps_per_cycle): + step_id = global_step + phys_step = phys_step_count + logging.info(f"\nStep {step_id} | Phys {inner+1}/{phys_steps_per_cycle} (phys_step={phys_step})") + logging.info(f" 🧱 Young's modulus: E={optimizer.config.youngs_modulus:.2e} Pa") + + # Dynamic mesh re-extraction is intentionally disabled here. + # We keep the mesh fixed and refresh occupancy each step so FEM + # and backward_step see the same topology. + # if config.re_extract_interval > 0 and step > 0 and step % config.re_extract_interval == 0: + # logging.info(f" 🔄 Re-extract solid mesh to sync latents with FEM...") + # try: + # optimizer.extract_solid(step=step) + # optimizer.prepare_physical_simulation() + # except Exception as e: + # logging.warning(f" ⚠️ Re-extraction failed; keeping the old mesh: {str(e)[:100]}") + + # Physics optimization step with ALM. + compliance_loss, sds_loss, total_loss = optimizer.training_step_dual_lagrange_v2( + phys_step, lagrange_multiplier, rho, use_sds=True, save_step=step_id + ) + + # Normalized constraint: g = D / D_thr - 1. + violation = (compliance_loss / (compliance_threshold + 1e-8)) - 1.0 + g_pos = max(0.0, violation) + + # Update lambda and project it to the non-negative range. + lagrange_multiplier = max(0.0, lagrange_multiplier + rho * violation) + lagrange_multiplier = min(lagrange_multiplier, args.lagrange_max) + + # Increase rho after persistent violations. + if g_pos > 0.0: + violation_count += 1 + if violation_count >= config.alm_rho_increase_patience: + new_rho = min(rho * config.alm_rho_increase_factor, config.alm_rho_max) + if new_rho > rho: + rho = new_rho + logging.info(f" 🔧 rho increased: {rho:.2e} (continuous violations{config.alm_rho_increase_patience} steps)") + violation_count = 0 + else: + violation_count = 0 + + status = "❌ violating" if violation > 0 else "✅ within threshold" + + # Log a compact ALM summary. + logging.info( + f" 📊 Compliance (true) : {compliance_loss:.2e} vs threshold value{compliance_threshold:.2e} " + f"(g={violation:+.3e}, [g]+={g_pos:.3e}) {status}" + ) + logging.info(f" ⚖️ ALMStatus: λ={lagrange_multiplier:.4f} (max={args.lagrange_max}), ρ={rho:.2e}") + current_sds_weight = optimizer.get_current_sds_weight(phys_step) + if current_sds_weight > 0.0: + sds_percentage = (current_sds_weight * sds_loss) / (total_loss + 1e-10) * 100 + logging.info( + f" 🎨 Shape Loss: weight={current_sds_weight:.6f}, " + f"loss={sds_loss:.4e}, ratio={sds_percentage:.2f}%" + ) + else: + logging.info(f" 🎨 Shape Loss: disabled (weight is 0)") + + # Save only the first and last physics step of each outer cycle. + is_first_phys_step = inner == 0 + is_last_phys_step = inner == phys_steps_per_cycle - 1 + if is_first_phys_step or is_last_phys_step: + optimizer.save_mesh(step_id, args.out_folder) + + global_step += 1 + phys_step_count += 1 + + # Project back to the manifold by replacing latents with target_z0. + logging.info(f"\nStep {global_step} | Projection (E={optimizer.config.youngs_modulus:.2e} Pa)") + logging.info(" 🔮 manifold projection: add noise and compute target_z0, backreplace directlylatents") + projected = optimizer.project_to_manifold(step=global_step) + if not projected: + logging.warning(" ⚠️ projection failed, keep the physical result for this cycle") + else: + projection_count += 1 + new_E = base_youngs_modulus + youngs_modulus_delta * projection_count + new_E = min(new_E, youngs_modulus_target) + optimizer.config.youngs_modulus = new_E + if hasattr(optimizer, "E"): + optimizer.E = new_E + logging.info( + f" 🧱 Young's modulusupdate: E={new_E:.2e} " + f"(projection {projection_count}/{outer_cycles})" + ) + if global_step % 20 == 0: + projection_dir = os.path.join(args.out_folder, "projection_meshes") + os.makedirs(projection_dir, exist_ok=True) + optimizer.save_mesh(global_step, projection_dir) + global_step += 1 + + final_step = global_step + else: + # Pure SDS optimization. + for step in range(args.num_steps): + logging.info(f"\nStep {step}/{args.num_steps}") + optimizer.training_step_sds(step) + if step % 20 == 0: + optimizer.save_mesh(step, args.out_folder) + + # Save final results. + logging.info("\n✅ Optimization finished!save final results...") + optimizer.save_mesh(final_step, args.out_folder, high_quality=True) + if args.use_physics: + optimizer.save_final_target_z0_mesh(final_step) + optimizer.save_final_deformed_mesh(final_step) + + final_latents_path = os.path.join(args.out_folder, "optimized_latents.pt") + torch.save({ + 'latents': optimizer.latents.detach().cpu(), + 'cond': optimizer.cond, + }, final_latents_path) + logging.info(f"💾 save optimized latents: {final_latents_path}") + logging.info(f"\n✅ all files saved to: {args.out_folder}") + + if args.use_physics: + logging.info(f"\n📊 force visualization data:") + logging.info(f" - directory: {os.path.join(args.out_folder, 'force_visualization')}") + logging.info(f" - quick view: cd {os.path.join(args.out_folder, 'force_visualization')} && python visualize_forces.py") + + +if __name__ == "__main__": + main() diff --git a/cfd_workflow_20261012/_seiler_ref/physiopt_new_scripts/viewer_hunyuan_web_physiopt.py b/cfd_workflow_20261012/_seiler_ref/physiopt_new_scripts/viewer_hunyuan_web_physiopt.py new file mode 100644 index 0000000000000000000000000000000000000000..4c43c2a326f00432888f66617ef3d6331a3f133d --- /dev/null +++ b/cfd_workflow_20261012/_seiler_ref/physiopt_new_scripts/viewer_hunyuan_web_physiopt.py @@ -0,0 +1,4057 @@ +import os +import copy +# os.environ['TORCH_HOME'] = '/mnt/cvlab/scratch/cvlab/home/hantzhan/.torch' +import sys +import shutil + +# Add Hunyuan3D-2.1pathto the Python path +hunyuan_path = os.path.abspath(os.path.join(os.path.dirname(__file__), "../../Hunyuan3D-2.1")) +# note: logging is not imported yet here, so use print first +# base logging is configured near the top of the file after importing logging + +sys.path.append("..") + +import torch +import torch.nn.functional as F +import trimesh +import numpy as np +from PIL import Image +import argparse +import json +from typing import Tuple, Optional, List +from dataclasses import dataclass, field +import traceback +import logging + +# configure logging (temporarily only output to the console, mainthe main function will reconfigure it to also write to a file) +# note: do not call basicConfig here so the main function configuration takes effect +# logging.basicConfig(level=logging.INFO, format='%(levelname)s: %(message)s') + +# physics simulationrelated imports +PHYSIOPT_AVAILABLE = False +try: + from physiopt.utils.phys_utils import generate_hex + from physiopt.utils.grid_utils import filter_one_component + from physiopt.opt.field import occ_kernel + from physiopt.opt.forces import ForceConfig + PHYSIOPT_AVAILABLE = True + logging.info("✅ physics simulation moduleimportsucceeded") +except ImportError as e: + logging.warning(f"⚠️ warning: physics simulation moduleimportfailed: {e}") + logging.warning(" if you only run SDS optimization, you can ignore this warning") + PHYSIOPT_AVAILABLE = False + + def generate_hex(res, limits=[(-0.5, 0.5), (-0.5, 0.5), (-0.5, 0.5)], device="cuda", return_coords=False): + """Placeholder: generate the hexahedral grid + + Return data in the same format as the real function (PyTorch tensors) + """ + logging.warning(f"⚠️ warning: using placeholdergenerate_hex, please install the physiopt module") + return None, None + + def filter_one_component(mask, res): + """Placeholder: connected-component filtering + + Args: + mask: element mask [res*res*res] + res: Voxel resolution + """ + return mask + + def occ_kernel(sdf, res, beta): + """Placeholder: SDF-to-occupancy conversion""" + return torch.sigmoid(-sdf * beta) + +# Warp physics engineimport +try: + import warp as wp + wp.init() + WARP_AVAILABLE = True + logging.info("✅ Warp physics engineInitializationsucceeded") +except ImportError: + WARP_AVAILABLE = False + logging.warning("⚠️ warning: Warp physics enginenot installed, physics simulationwill be unavailable") + logging.warning(" Install: pip install warp-lang") + +# Hunyuan3D imports +try: + from hy3dgen.shapegen.models.autoencoders import ShapeVAE + from hy3dgen.shapegen import Hunyuan3DDiTFlowMatchingPipeline + from hy3dgen.shapegen.pipelines import export_to_trimesh +except ImportError as e: + logging.error(f"❌ failed to import Hunyuan3D modules: {e}") + logging.error(f"\nplease follow these steps to set upHunyuan3D-2.1:") + logging.error(f"1. cd {os.path.dirname(hunyuan_path)}") + logging.error(f"2. git clone https://github.com/Tencent/Hunyuan3D-2.git Hunyuan3D-2.1") + logging.error(f"3. cd Hunyuan3D-2.1") + logging.error(f"4. pip install -e .") + sys.exit(1) + + +@dataclass +class OptimizationConfig: + """Optimization config (physics optimization + SDS optimization)""" + # Physical-simulation parameters + res: int = 32 # Voxel resolution (16/32/64) - matching the reference code + # Physical-simulation parameters (fully restored from the stable v90 configuration) + p_exponent: float = 1.0 # SIMPpenalty exponent + alpha_min: float = 0.01 # minimum density - restored from v90 + volume_term: float = 1000000.0 # volume-constraint weight + occ_sdf_beta: float = 2.0 # Sigmoid kernelbetavalue - restored from v90 + one_cc_only: bool = True # keep only the largest connected component + + # SDS parameters + # 🔧 Enable SDS gradients to balance physics optimization and aesthetic optimization + # + # Strategy: use dynamic weights that linearly grow from small to large + # - early stage (Step0-100) : SDS weight, physics optimization dominates so the structure stiffens + # - late stage (Step100-300) : SDS weightincrease, aesthetic optimization joins in to preserve shape quality + # + # weight design: + # - start=0.0001: initialSDS, without disturbing physics optimization + # - end=0.001: finalSDS, about one tenth of the physics gradient + # - avoid letting SDS dominate: physics gradient~0.02, SDS gradient~2.6, SDS weight0.01 + sds_timestep: float = 0.1 # SDStimestep (valuekept) - matching the reference code + sds_weight: float = 1.0 # SDS weight (physics gradientweight) - thisfinalweight + sds_weight_start: float = 1e5 # 0.1 # 0.0001 # initialSDS weight (, without disturbing physics optimization) + sds_weight_end: float = 1e5 # 1.0 # 0.001 # finalSDS weight (, about one tenth of the physics gradient) + guidance_scale: float = 7.5 # 🔑 CFG guidance scale (value7.5, used to strengthen image conditioning) + sds_projection_max_rel: float = 0.0 # Maximum relative target_z0 projection deviation (0 = unlimited) + sds_use_uncond: bool = False # Use the unconditional branch (only takes effect when guidance_scale <= 1) + sds_target_z0_update_interval: int = 10 # target_z0update interval (consistent with phys_steps_per_cycle) + sds_target_z0_ema_beta: float = 0.9 # EMAsmoothing factor () + + # Augmented Lagrangian parameters + lagrange_max: float = 50.0 # λupper bound + compliance_threshold: float = 200.0 # Compliancethreshold value () + alm_rho_init: float = 1.0 # ρinitial value + alm_rho_max: float = 1000.0 # ρupper bound + alm_rho_increase_factor: float = 2.0 # rho growth factor + alm_rho_increase_patience: int = 5 # threshold on consecutive violating steps + alm_scale_guard_ratio: float = 0.95 # ALMscaling guard ratio (<=1, trigger gradient clipping) + + # topology control + re_extract_interval: int = 5 # Re-extract the solid every N steps (update topology); 0 disables it. Recommended: every 3-5 steps + + # material properties - 🔥 Key: match the reference codematerial properties + # ⚠️ unit note: youngs_modulus use Pa directly, no conversion is required + # Referenceuse MaterialConfig.E (GPa) * GPA_UNIT (1e9) = 1e9 Pa + # this 1e9 Pa, exactly matches the value used by the reference code + youngs_modulus: float = 5e8 # 1e9 # Pa (= 1 GPa) - restored v90 configuration + youngs_modulus_scale: float = 2.0 # physics+projectionfinal (after the last projection) + poissons_ratio: float = 0.3 # Poisson ratio (dimensionless) + density: float = 650.0 # material density (kg/m³) + + ## Wood + # youngs_modulus: float = 9e9 # Pa (= 1 GPa, match the reference code) + # poissons_ratio: float = 0.35 # Poisson ratio (dimensionless) - matching the reference code + # density: float = 400.0 # material density (kg/m³ = 1000 g/cm^3) - matching the reference code + + ## PVG + # youngs_modulus: float = 3.25e9 # Pa (= 1 GPa, match the reference code) + # poissons_ratio: float = 0.38 # Poisson ratio (dimensionless) - matching the reference code + # density: float = 1380.0 # material density (kg/m³ = 1000 g/cm^3) - matching the reference code + + # load conditions - support multiple forces (consistent with config.json) + forces: List = None # ForceConfigobject list + # multiple load entries, each with its own force vector and region settings + force_entries: Optional[List[dict]] = None + + # 🔧 : local-loading settings (to mimic a person sitting on a chair) + use_local_loading: bool = True # whether to use local loading instead of a globally uniform distribution + seat_height_min_ratio: float = 0.3 # lower seat-region boundary (relative to the total height, 0-1) + seat_height_max_ratio: float = 0.5 # upper seat-region boundary (relative to the total height, 0-1) + force_region_mode: str = "top_percent" # load-region selection: top_percent/height_ratio/bbox + force_top_percent: float = 0.05 # top_percentmode, use the fraction of highest-Y nodes + force_bbox: Optional[List[float]] = None # bboxmode: x_min x_max y_min y_max z_min z_max + force_bbox_ratio: Optional[List[float]] = None # bboxmode(0-1): nodesbounds + + # Optimization parameters (v90succeededconfig) + lr: float = 0.001 # Learning rate - v90stable value + num_steps: int = 100 # optimization steps + use_sgd: bool = False # Use SGD instead of Adam + grad_clip_enabled: bool = False # whether to enable gradient clipping (disabled) + save_every: int = 20 # save interval ( steps) + deformed_mesh_interval: int = 20 # Interval for saving deformed meshes (steps) + deformed_mesh_disp_min: float = 0.0 # deformed meshminimum displacement for color mapping + deformed_mesh_disp_max: float = 0.2 # deformed meshmaximum displacement for color mapping (<=0automatic) + + # output path + out_folder: str = "../out/hunyuan_opt" # Output folder path + + # device + device: str = "cuda" # computation device + + # whether to enable physics optimization + use_physics: bool = True # Enable physics-constrained optimization + + def __post_init__(self): + # Set default loads (using the Hunyuan coordinate system Y-up: Xright, Yup, Zfront) + if self.forces is None: + try: + from physiopt.opt.forces import ForceConfig + self.forces = [ + ForceConfig(external_force=[0.0, -100000.0, 0.0]) # Ydownward100kN (v90succeededconfig) + # ForceConfig(external_force=[0.0, 0.0, -500.0]), # Zbackward500N (frontpush/pull force) + ] + except ImportError: + # If physiopt is not installed, use the simplified version (containing only the force vectors, Y-up coordinate system) + self.forces = [ + {'external_force': [0.0, -100000.0, 0.0]} # Ydownward100kN + # {'external_force': [0.0, 0.0, -500.0]}, # Zbackward (push/pull force) + ] + + +class HunyuanSDSOptimizer: + """Hunyuan3D SDSoptimizer (with differentiable physics support) """ + + def __init__( + self, + latents: torch.Tensor, + cond: dict, # condition dictionary (including positive and negative branches) + vae: ShapeVAE, + flow_model: torch.nn.Module, + config: OptimizationConfig, + scheduler=None, + device: str = 'cuda' + ): + """ + Args: + latents: initial latent tokens [1, N, D] + cond: condition dictionary (returned by pipeline.encode_cond) + vae: Hunyuan3DVAE model + flow_model: Hunyuan3DFlow Matching model + scheduler: Hunyuan3DFlow Matching scheduler (aligntarget_z0computation) + config: optimization config + device: device + """ + self.device = device + self.config = config + + # model + self.vae = vae.to(device).eval() + self.flow_model = flow_model.to(device).eval() + if scheduler is not None: + try: + self.sds_scheduler = copy.deepcopy(scheduler) + except Exception: + self.sds_scheduler = scheduler + logging.warning("⚠️ Scheduler deepcopyfailed, already fallback to originalscheduler") + else: + self.sds_scheduler = None + + # 🔧 : Create a differentiable SDF query helper + from hy3dgen.shapegen.models.autoencoders.differentiable_sdf_query import DifferentiableSDFQuery + self.sdf_query = DifferentiableSDFQuery( + vae=self.vae, + bounds=0.8, # our coordinate range is[-0.8, 0.8] + chunk_size=8192 # batch query size + ) + logging.info(f"✅ created differentiable SDF query helper") + + # Latent tokens (the variables being optimized) + # Important: use float32 instead of float16 for optimization to avoid numerical overflow + self.latents = latents.clone().to(device).to(torch.float32).requires_grad_(True) + + logging.info(f" ⚠️ note: Latentsfloat32FP16value") + + # conditioning data (moved to the device recursively) + def to_device_recursive(obj): + if isinstance(obj, torch.Tensor): + return obj.to(device) + elif isinstance(obj, dict): + return {k: to_device_recursive(v) for k, v in obj.items()} + elif isinstance(obj, (list, tuple)): + return type(obj)(to_device_recursive(item) for item in obj) + else: + return obj + + self.cond = to_device_recursive(cond) + self._cond_warned_cfg_repeat = False + self._cond_warned_nocfg_slice = False + + # optimizer (supports SGD and Adam) + if config.use_sgd: + self.optimizer = torch.optim.SGD([self.latents], lr=config.lr, momentum=0.0) + opt_name = "SGD" + else: + self.optimizer = torch.optim.Adam([self.latents], lr=config.lr, betas=(0.9, 0.999), eps=1e-8) + opt_name = "Adam" + + logging.info(f"✅ HunyuanSDSOptimizerInitializationcompleted (with differentiable physics support) ") + logging.info(f" - Latents shape: {self.latents.shape}") + logging.info(f" - Latents dtype: {self.latents.dtype} (optimized in float32)") + logging.info(f" - Device: {device}") + logging.info(f" - Optimizer: {opt_name}") + logging.info(f" - Learning rate: {config.lr}") + + # target_z0 EMAcache + self.target_z0_ema = None + self.target_z0_last_velocity = None + self.target_z0_last_update = None + + def get_field(self, x: torch.Tensor, latents: torch.Tensor = None) -> torch.Tensor: + """differentiable SDF query (via the VAE geo_decoder) + + Args: + x: query-point coordinates [N, 3], in the range[-0.8, 0.8]³ + latents: optional latent tokens, defaulting to self.latents + + Returns: + sdf: SDFvalue [N], supports backpropagation! + """ + if latents is None: + latents = self.latents + + # Match the official pipeline: divide by scale_factor before decoding + scale_factor = getattr(self.vae, "scale_factor", 1.0) + latents_scaled = latents / scale_factor + + # convert to FP16 for the VAE (VAEexpects FP16) + latents_fp16 = latents_scaled.to(torch.float16) + + # 🔧 Key: decode latents with the VAE decoder + # note: Do not use torch.no_grad(); the gradients must be preserved! + decoded_latents = self.vae.decode(latents_fp16) + + # 🔧 use the differentiable SDF query helper + # note: sdf_queryinternally calls geo_decoder, so keep FP16 to match the VAE weights + sdf = self.sdf_query( + decoded_latents, # keep FP16, sdf_queryhandle + x, + return_occupancy=False # return SDF instead of occupancy + ) # [N] + + return sdf + + def _cond_batch_size(self, cond) -> Optional[int]: + if isinstance(cond, torch.Tensor): + return cond.shape[0] if cond.dim() >= 1 else None + if isinstance(cond, dict): + for v in cond.values(): + bsz = self._cond_batch_size(v) + if bsz is not None: + return bsz + if isinstance(cond, (list, tuple)): + for v in cond: + bsz = self._cond_batch_size(v) + if bsz is not None: + return bsz + return None + + def _cond_slice(self, cond, batch_slice: slice): + if isinstance(cond, torch.Tensor): + if cond.dim() >= 1 and cond.shape[0] >= batch_slice.stop: + return cond[batch_slice] + return cond + if isinstance(cond, dict): + return {k: self._cond_slice(v, batch_slice) for k, v in cond.items()} + if isinstance(cond, (list, tuple)): + return type(cond)(self._cond_slice(v, batch_slice) for v in cond) + return cond + + def _cond_repeat(self, cond, repeats: int): + if isinstance(cond, torch.Tensor): + if cond.dim() >= 1: + rep_shape = (repeats,) + (1,) * (cond.dim() - 1) + return cond.repeat(rep_shape) + return cond + if isinstance(cond, dict): + return {k: self._cond_repeat(v, repeats) for k, v in cond.items()} + if isinstance(cond, (list, tuple)): + return type(cond)(self._cond_repeat(v, repeats) for v in cond) + return cond + + def _get_cond_for_guidance(self, use_cfg: bool): + cond = self.cond + bsz = self._cond_batch_size(cond) + if use_cfg: + if bsz == 1: + if not self._cond_warned_cfg_repeat: + logging.warning("⚠️ guidance_scale>1 cond batch=1, already condCFG") + self._cond_warned_cfg_repeat = True + return self._cond_repeat(cond, 2) + if bsz is not None and bsz > 2: + return self._cond_slice(cond, slice(0, 2)) + return cond + # no-CFG + if bsz is not None and bsz >= 2: + if self.config.sds_use_uncond: + if not self._cond_warned_nocfg_slice: + logging.info("ℹ️ guidance_scale<=1, useno conditioncond[1:2]") + self._cond_warned_nocfg_slice = True + return self._cond_slice(cond, slice(1, 2)) + if not self._cond_warned_nocfg_slice: + logging.info("ℹ️ guidance_scale<=1, already usecond[0:1]batch") + self._cond_warned_nocfg_slice = True + return self._cond_slice(cond, slice(0, 1)) + if self.config.sds_use_uncond and bsz == 1 and not self._cond_warned_nocfg_slice: + logging.warning("⚠️ sds_use_uncond=1 cond batch=1, already fallback to conditself") + self._cond_warned_nocfg_slice = True + return cond + + def latents_to_mesh(self, latents: torch.Tensor, octree_res: int = 128) -> Optional[trimesh.Trimesh]: + """Decode latent tokens into a mesh + + Args: + latents: Latent tokens [1, N, D] (float32) + octree_res: OctreeResolution (128, faster; 256 is higher quality but slower) + + Returns: + trimesh.Trimeshobject; return None on failure + """ + with torch.no_grad(): + # Check whether latents contain invalid values + if torch.isnan(latents).any() or torch.isinf(latents).any(): + logging.warning(" latents_to_mesh: latentscontains NaN or Inf, skip") + return None + + # Match the official pipeline: divide by scale_factor before decoding + scale_factor = getattr(self.vae, "scale_factor", 1.0) + latents_scaled = latents / scale_factor + + # Convert to FP16 for VAE decoding (VAEexpects FP16) + latents_fp16 = latents_scaled.to(torch.float16) + + try: + # VAE decoding + decoded_latents = self.vae.decode(latents_fp16) + + # Check decoded latents + if torch.isnan(decoded_latents).any() or torch.isinf(decoded_latents).any(): + logging.warning(" latents_to_mesh: decoded_latentscontains NaN or Inf, skip") + return None + except Exception as e: + logging.debug(f" latents_to_mesh: VAE decodingfailed: {e}") + return None + + # 🔧 Key: Use an adaptive mc_level + # First try the default mc_level=0.0; if that fails, use the median SDF value + try: + # First attempt: use the standard mc_level=0.0 + mesh = self.vae.latents2mesh( + decoded_latents, + output_type='trimesh', + bounds=1.01, + mc_level=0.0, + num_chunks=20000, + octree_resolution=octree_res, + mc_algo='mc', + enable_pbar=False + ) + mesh = export_to_trimesh(mesh)[0] + return mesh + + except ValueError as e: + error_msg = str(e) + if "Surface level must be within volume data range" in error_msg: + # 🔧 Adaptive fallback: use the median SDF value as the new mc_level + logging.debug(f" latents_to_mesh: mc_level=0.0 failed, try an adaptive level...") + + try: + # use VAE geo_decoder to query the SDF field + # we need to sample points to estimate the SDF range + + # create a coarse grid to sample the SDF + grid_size = 32 + x = torch.linspace(-1.0, 1.0, grid_size, device=decoded_latents.device) + y = torch.linspace(-1.0, 1.0, grid_size, device=decoded_latents.device) + z = torch.linspace(-1.0, 1.0, grid_size, device=decoded_latents.device) + xx, yy, zz = torch.meshgrid(x, y, z, indexing='ij') + points = torch.stack([xx, yy, zz], dim=-1).reshape(-1, 3) # [N, 3] + + # query SDF values + sdf_values = self.get_field(points, latents=latents) + + # computation statistics + sdf_median = torch.median(sdf_values).item() + sdf_min = sdf_values.min().item() + sdf_max = sdf_values.max().item() + sdf_mean = sdf_values.mean().item() + + logging.debug(f" SDFstatistics: min={sdf_min:.4f}, max={sdf_max:.4f}, median={sdf_median:.4f}, mean={sdf_mean:.4f}") + + # If the SDF range is too small, there is probably no clear surface + if abs(sdf_max - sdf_min) < 1e-4: + logging.debug(f" SDFrange is too small to extract a surface") + return None + + # 🔑 Try multiple candidate levels (maymay) + candidate_levels = [ + sdf_median, # median (most common) + sdf_mean, # mean + (sdf_min + sdf_max) / 2, # range midpoint + sdf_min + (sdf_max - sdf_min) * 0.3, # 30% position + sdf_min + (sdf_max - sdf_min) * 0.7, # 70% position + ] + + # Make sure all levels fall within the valid range + valid_levels = [ + max(sdf_min + 0.001, min(sdf_max - 0.001, level)) + for level in candidate_levels + ] + + # Deduplicate + valid_levels = list(set(valid_levels)) + + logging.debug(f" try {len(valid_levels)} candidate levels: {[f'{l:.4f}' for l in valid_levels[:3]]}...") + + # Try each level in sequence + for i, adaptive_level in enumerate(valid_levels): + try: + mesh = self.vae.latents2mesh( + decoded_latents, + output_type='trimesh', + bounds=1.01, + mc_level=adaptive_level, + num_chunks=20000, + octree_resolution=octree_res, + mc_algo='mc', + enable_pbar=False + ) + mesh = export_to_trimesh(mesh)[0] + logging.info(f" ✅ uselevelsucceeded (level={adaptive_level:.4f}, attempt {i+1})") + return mesh + except (ValueError, RuntimeError) as level_error: + # This level also failed; try the next one + if i < len(valid_levels) - 1: + continue + else: + # All levels failed + logging.debug(f" all candidate levels failed") + return None + + # If execution reaches this point, none of the attempts succeeded + return None + + except Exception as adaptive_error: + logging.debug(f" adaptive extraction failed: {type(adaptive_error).__name__}: {str(adaptive_error)[:50]}") + return None + + elif "No surface found" in error_msg: + logging.debug(f" latents_to_mesh: Marching cubesno surface found, skip") + return None + else: + logging.warning(f" latents_to_mesh: unknown ValueError: {error_msg}") + return None + + except RuntimeError as e: + error_msg = str(e) + if "No surface found" in error_msg or "Surface level" in error_msg: + logging.debug(f" latents_to_mesh: Marching cubesfailed, skip") + return None + else: + logging.warning(f" latents_to_mesh: RuntimeError: {error_msg}") + return None + + except Exception as e: + # Catch all other exceptions () + logging.warning(f" latents_to_mesh: unexpected exception: {type(e).__name__}: {e}") + return None + + def _filter_floating_components(self, mesh: trimesh.Trimesh) -> trimesh.Trimesh: + """Filter floating mesh fragments and keep only the largest connected component""" + try: + components = mesh.split(only_watertight=False) + if len(components) <= 1: + return mesh + + face_counts = [len(comp.faces) for comp in components] + max_idx = int(np.argmax(face_counts)) + filtered = components[max_idx] + dropped = len(components) - 1 + + logging.info(f" 🧹 filter floating fragments: kept{len(filtered.faces)} faces, discarded{dropped} small components") + return filtered + except Exception as e: + logging.warning(f" failed to filter floating fragments: {type(e).__name__}: {str(e)[:100]}") + return mesh + + def _sample_displacement_to_vertices( + self, + vertices: np.ndarray, + nodes: np.ndarray, + displacement: np.ndarray, + ) -> np.ndarray: + """Sample the voxel-node displacement field onto mesh vertices (nearest neighbor)""" + try: + from scipy.spatial import cKDTree + tree = cKDTree(nodes) + _, idx = tree.query(vertices, k=1) + return displacement[idx] + except Exception as e: + try: + from sklearn.neighbors import NearestNeighbors + nn = NearestNeighbors(n_neighbors=1, algorithm="auto") + nn.fit(nodes) + idx = nn.kneighbors(vertices, return_distance=False).squeeze(1) + return displacement[idx] + except Exception as e2: + logging.warning(f" displacement sampling failed, fallback to zero displacement: {type(e).__name__}: {str(e)[:100]}") + logging.debug(f" secondaryError: {type(e2).__name__}: {str(e2)[:100]}") + return np.zeros_like(vertices) + + def _normalize_displacement_magnitude( + self, disp_mag: np.ndarray + ) -> Tuple[np.ndarray, float, float, bool]: + """Normalize displacement magnitude (optionally with a fixed range)""" + mag_max_cfg = getattr(self.config, "deformed_mesh_disp_max", None) + mag_min_cfg = getattr(self.config, "deformed_mesh_disp_min", None) + use_fixed = mag_max_cfg is not None and mag_max_cfg > 0.0 + if use_fixed: + mag_min = 0.0 if mag_min_cfg is None else float(mag_min_cfg) + mag_max = float(mag_max_cfg) + if mag_max <= mag_min: + use_fixed = False + if not use_fixed: + mag_min = float(disp_mag.min()) + mag_max = float(disp_mag.max()) + denom = max(1e-12, mag_max - mag_min) + norm = (disp_mag - mag_min) / denom + if use_fixed: + norm = np.clip(norm, 0.0, 1.0) + return norm, mag_min, mag_max, use_fixed + + def _make_displacement_colors(self, displacement: np.ndarray) -> np.ndarray: + """Map displacement magnitude to vertex colors (blue -> red)""" + disp_mag = np.linalg.norm(displacement, axis=1) + norm, _, _, _ = self._normalize_displacement_magnitude(disp_mag) + colors = np.stack([norm, np.zeros_like(norm), 1.0 - norm], axis=1) + return (colors * 255).astype(np.uint8) + + def _log_physical_quantities( + self, + u: torch.Tensor, + sigma: Optional[torch.Tensor], + ) -> None: + """Write displacement and Von Mises stress statistics to the log""" + with torch.no_grad(): + u_max = None + u_avg = None + try: + u_mag = torch.norm(u, dim=1) + u_max = u_mag.max().item() + u_avg = u_mag.mean().item() + except Exception as e: + logging.warning( + f" ⚠️ displacement statistics failed: {type(e).__name__}: {str(e)[:100]}" + ) + + sigma_vm_max = None + sigma_vm_avg = None + if sigma is not None: + try: + if sigma.dim() == 2 and sigma.shape[1] >= 6: + s_xx = sigma[:, 0] + s_yy = sigma[:, 1] + s_zz = sigma[:, 2] + s_yz = sigma[:, 3] + s_xz = sigma[:, 4] + s_xy = sigma[:, 5] + mises_sq = 0.5 * ( + (s_xx - s_yy) ** 2 + + (s_yy - s_zz) ** 2 + + (s_zz - s_xx) ** 2 + + 6.0 * (s_xy ** 2 + s_yz ** 2 + s_xz ** 2) + ) + mises = torch.sqrt(torch.clamp(mises_sq, min=0.0)) + sigma_vm_max = mises.max().item() + sigma_vm_avg = mises.mean().item() + else: + logging.warning( + f" ⚠️ sigmashape does not match expectations, skip von Mises statistics: {tuple(sigma.shape)}" + ) + except Exception as e: + logging.warning( + f" ⚠️ von Mises statistics failed: {type(e).__name__}: {str(e)[:100]}" + ) + + if u_max is not None and u_avg is not None: + if sigma_vm_max is not None and sigma_vm_avg is not None: + logging.info( + f" physical metrics: u_max={u_max:.3e}, u_avg={u_avg:.3e}, " + f"sigma_vm_max={sigma_vm_max:.3e}, sigma_vm_avg={sigma_vm_avg:.3e}" + ) + else: + logging.info( + f" physical metrics: u_max={u_max:.3e}, u_avg={u_avg:.3e}" + ) + + def backward_step(self, sensitivity_density: torch.Tensor): + """VJP backpropagation - strictly aligned with the reference code + + Reference: viewer_deepsdf.py Line 148-183 + + use torch.autograd.functional.vjp sensitivitybackpropagate to latents + """ + def f(latents: torch.Tensor): + """ + Given latents, computation occupancy + align viewer_deepsdf.py Line 155-173 + """ + # query the SDF + sdf = self.get_field(self.nodes, latents) + + # SDF → occupancy + from physiopt.opt.field import occ_kernel + occ = occ_kernel(sdf, self.config.res, self.config.occ_sdf_beta) + + # element occupancy (8nodesmean) + occ_elem = occ[self.elements].mean(1) + + # alpha_minclamp + if self.config.alpha_min > 0.0: + occ_elem = torch.clamp(occ_elem, self.config.alpha_min) + + return occ_elem + + # VJP: computation ∂occ/∂latents^T · sensitivity + # align viewer_deepsdf.py Line 175-180 + try: + grad_latent = torch.autograd.functional.vjp( + f, + self.latents.clone().requires_grad_(True), + sensitivity_density, + )[1] + + # checkgradient + if grad_latent is None: + logging.error(" ❌ VJP returned None!") + return + + grad_norm = torch.norm(grad_latent).item() + logging.info(f" VJP gradient: norm={grad_norm:.2e}") + + # gradient + # align viewer_deepsdf.py Line 182-183 + self.latents.grad = grad_latent + + except Exception as e: + logging.error(f" ❌ VJP failed: {e}") + import traceback + traceback.print_exc() + + def prepare_physical_simulation(self): + """prepare physical simulation (FEM solver setup) + + Initialization: + 1. Material properties (Young's modulus, Poisson ratio) + 2. Boundary conditions (fixed constraints) + 3. External forces (gravity, loads) + """ + if not WARP_AVAILABLE: + logging.warning("Warpnot installed, skipphysics simulation preparation") + return + + if not hasattr(self, 'nodes') or not hasattr(self, 'elements'): + logging.error("please call extract_solid() to extract the solid first") + return + + logging.info("prepare physical simulation...") + + # Initialize Warp + wp.init() + + # Set the Warp device (handle "cuda" and "cuda:0" format) + if 'cuda' in self.device: + # ifself.deviceYes "cuda" "cuda:0", extract the device ID + if ':' in self.device: + device_id = self.device.split(':')[-1] + warp_device = f"cuda:{device_id}" + else: + warp_device = "cuda:0" # default to cuda:0 + else: + warp_device = "cpu" + + wp.set_device(warp_device) + logging.info(f"Warpdevice: {warp_device}") + + # material properties + self.E = self.config.youngs_modulus # Young's modulus + self.nu = self.config.poissons_ratio # Poisson ratio + self.rho = self.config.density # density + + # Boundary conditions: fix the bottom nodes (Ymin, HunyuanuseY-up coordinate system) + y_coords = self.nodes[:, 1] + y_min = y_coords.min() + boundary_threshold = y_min + 0.05 # bottom 5% region + self.boundary_mask = y_coords < boundary_threshold + + logging.info(f" coordinate system: Y-up (Hunyuan-native), fix Y < {boundary_threshold:.3f}nodes") + + # ==================== External-force setup: local loading (to mimic a person sitting on a chair) ==================== + # + # ✅ Improvement: do not distribute the force uniformly to all nodes (unphysical) + # Instead, apply it only to the seat region as a localized surface load + # + # Principle: + # 1. Determine the seat height: usually near the middle of the object, Y ∈ [y_min + h*0.3, y_min + h*0.5] + # 2. Select the loaded nodes: nodes whose Y coordinate lies within the seat range + # 3. Distribute the total force: 1000Nsplit evenly across the seat nodes (Yesall nodes) + # + # Reference: in a real scene, human body weight(~600-800N)contacts the seat through the hips, + # contact areais about 0.04-0.06 m², pressureis about 10-20 kPa + + # Compute the total force (force_entriesfirst, HunyuanY-up coordinate system) + total_force = np.zeros(3, dtype=np.float32) + force_entries = getattr(self.config, "force_entries", None) + valid_force_entries = None + if force_entries: + valid_force_entries = [] + for entry in force_entries: + if not isinstance(entry, dict): + continue + entry_force = None + if "force" in entry: + try: + entry_force = np.array(entry["force"], dtype=np.float32) + except Exception: + entry_force = None + elif "forces" in entry and isinstance(entry["forces"], list): + try: + entry_force = np.sum( + np.array(entry["forces"], dtype=np.float32), axis=0 + ) + except Exception: + entry_force = None + if entry_force is None or entry_force.shape != (3,): + continue + valid_force_entries.append(entry) + total_force += entry_force + if valid_force_entries: + self.force_entries_preset = valid_force_entries + logging.info(f" force entries: {len(valid_force_entries)}") + else: + logging.warning(" ⚠️ force_entries has no valid entries, fallback to forces") + valid_force_entries = None + + if valid_force_entries is None: + for force_config in self.config.forces: + if hasattr(force_config, 'get_total_force'): + # ifYesForceConfig + total_force += force_config.get_total_force() + elif isinstance(force_config, dict) and 'external_force' in force_config: + # If it uses the dictionary format (compatibility mode) + total_force += np.array(force_config['external_force'], dtype=np.float32) + else: + logging.warning(f"unknown force format: {type(force_config)}") + + logging.info(f" sum of external forces (Y-up coordinates): {total_force}") + + # 🔧 KeyImprovement: choose the loading strategy based on the configuration + if valid_force_entries is not None: + # Multiple force entries: use local-loading logic, with an independent region for each entry + self._setup_local_loading(total_force) + elif self.config.use_local_loading: + # Strategy 1: local loading (recommended; more physically reasonable) + self._setup_local_loading(total_force) + else: + # Strategy 2: global uniform loading (original method, kept for comparison) + logging.info(f" ℹ️ using global uniform loading mode") + total_force_tensor = torch.from_numpy(total_force).float().to(self.device) + num_nodes = self.nodes.shape[0] + self.forces = total_force_tensor[None, :].repeat(num_nodes, 1) + logging.info(f" 💨 distributed the total force uniformly to{num_nodes}nodes") + + logging.info(f"boundary conditions: {self.boundary_mask.sum().item()}fixed nodes") + logging.info(f"material properties: E={self.E:.2e}, ν={self.nu}, ρ={self.rho}") + + def _setup_local_loading(self, total_force: np.ndarray): + """Set up local loading (applied only to the seat region) + + 🔧 Force-distribution strategy: + 1. Distribute the preset total force evenly over all points on the contact surface + 2. force on each point = total_force / num_seat_nodes + 3. preserve the total force: sum(forces) = total_force + + Args: + total_force: total force vector [3] (Y-up coordinate system, : N) + """ + # save the total force (for later updates) + self.total_force_preset = torch.from_numpy(total_force).float().to(self.device) + + # use the generic force-update function for the initial setup + self._update_forces(initial_setup=True) + + def _update_forces(self, initial_setup: bool = False): + """Update the force distribution based on the current mesh state + + 🔧 core logic: + 1. re-identify the contact nodes (top_percent / height_ratio / bbox) + 2. evenly distribute the preset total force across these nodes + 3. force_per_node = total_force / num_seat_nodes + 4. preserve the total force + + Args: + initial_setup: whether this is the initial setup (control log verbosity) + """ + if not hasattr(self, 'total_force_preset'): + logging.warning("No preset total force is set, so the force distribution cannot be updated") + return + + # Step1: analyze the Y-coordinate distribution of nodes + y_coords = self.nodes[:, 1] + num_nodes = self.nodes.shape[0] + + force_entries = getattr(self, "force_entries_preset", None) + if force_entries: + def _select_nodes_for_mode(mode, top_percent, min_ratio, max_ratio, bbox, bbox_ratio): + seat_mask = torch.zeros(num_nodes, dtype=torch.bool, device=self.device) + mode_used = mode + bbox_desc = None + + if mode_used not in ("top_percent", "height_ratio", "bbox", "global"): + logging.warning(f" ⚠️ invalid force_region_mode: {mode_used}, fallback to top_percent") + mode_used = "top_percent" + + if mode_used == "global": + seat_mask[:] = True + return seat_mask, mode_used, bbox_desc + + if mode_used == "bbox": + bbox_vals = None + if bbox is not None and len(bbox) == 6: + bbox_vals = [float(v) for v in bbox] + bbox_desc = "abs" + elif bbox_ratio is not None and len(bbox_ratio) == 6: + bbox_ratio_vals = [float(v) for v in bbox_ratio] + bounds_min = self.nodes.min(dim=0).values + bounds_max = self.nodes.max(dim=0).values + bbox_vals = [ + bounds_min[0].item() + bbox_ratio_vals[0] * (bounds_max[0] - bounds_min[0]).item(), + bounds_min[0].item() + bbox_ratio_vals[1] * (bounds_max[0] - bounds_min[0]).item(), + bounds_min[1].item() + bbox_ratio_vals[2] * (bounds_max[1] - bounds_min[1]).item(), + bounds_min[1].item() + bbox_ratio_vals[3] * (bounds_max[1] - bounds_min[1]).item(), + bounds_min[2].item() + bbox_ratio_vals[4] * (bounds_max[2] - bounds_min[2]).item(), + bounds_min[2].item() + bbox_ratio_vals[5] * (bounds_max[2] - bounds_min[2]).item(), + ] + bbox_desc = "ratio" + else: + logging.warning(" ⚠️ bbox mode did not provide a valid bbox, fallback to top_percent") + mode_used = "top_percent" + + if mode_used == "bbox" and bbox_vals is not None: + x0, x1 = sorted([bbox_vals[0], bbox_vals[1]]) + y0, y1 = sorted([bbox_vals[2], bbox_vals[3]]) + z0, z1 = sorted([bbox_vals[4], bbox_vals[5]]) + seat_mask = ( + (self.nodes[:, 0] >= x0) & (self.nodes[:, 0] <= x1) + & (self.nodes[:, 1] >= y0) & (self.nodes[:, 1] <= y1) + & (self.nodes[:, 2] >= z0) & (self.nodes[:, 2] <= z1) + ) + if seat_mask.sum().item() < 1: + logging.warning(" ⚠️ bbox region matched no nodes, fallback to top_percent") + mode_used = "top_percent" + else: + bbox_desc = f"{bbox_desc}: [{x0:.3f},{x1:.3f}]x[{y0:.3f},{y1:.3f}]x[{z0:.3f},{z1:.3f}]" + + if mode_used == "height_ratio": + y_min = y_coords.min().item() + y_max = y_coords.max().item() + y_range = max(1e-8, y_max - y_min) + if not (0.0 <= min_ratio < max_ratio <= 1.0): + logging.warning( + f" ⚠️ invalid height_ratio: min={min_ratio}, max={max_ratio}, fallback to top_percent" + ) + mode_used = "top_percent" + else: + seat_y_min = y_min + y_range * min_ratio + seat_y_max = y_min + y_range * max_ratio + seat_mask = (y_coords >= seat_y_min) & (y_coords <= seat_y_max) + if seat_mask.sum().item() < 1: + logging.warning(" ⚠️ height_ratio matched no nodes, fallback to top_percent") + mode_used = "top_percent" + + if mode_used == "top_percent": + top_percent = float(top_percent) + top_percent = max(0.0, min(1.0, top_percent)) + if top_percent <= 0.0: + top_percent = 0.05 + num_seat_nodes = max(1, int(num_nodes * top_percent)) + _, top_indices = torch.topk(y_coords, k=num_seat_nodes, largest=True) + seat_mask = torch.zeros(num_nodes, dtype=torch.bool, device=self.device) + seat_mask[top_indices] = True + + return seat_mask, mode_used, bbox_desc + + self.forces = torch.zeros((num_nodes, 3), dtype=torch.float32, device=self.device) + combined_mask = torch.zeros(num_nodes, dtype=torch.bool, device=self.device) + total_force = torch.zeros(3, dtype=torch.float32, device=self.device) + + for idx, entry in enumerate(force_entries): + if not isinstance(entry, dict): + continue + entry_label = entry.get("label") or entry.get("name") or f"{idx+1}" + entry_force = None + if "forces" in entry and isinstance(entry["forces"], list): + try: + entry_force = np.sum(np.array(entry["forces"], dtype=np.float32), axis=0) + except Exception: + entry_force = None + if entry_force is None and "force" in entry: + try: + entry_force = np.array(entry["force"], dtype=np.float32) + except Exception: + entry_force = None + if entry_force is None or entry_force.shape != (3,): + logging.warning(f" ⚠️ invalid force entry[{entry_label}], skip") + continue + + entry_force_tensor = torch.from_numpy(entry_force).float().to(self.device) + total_force += entry_force_tensor + + mode = str(entry.get("force_region_mode", self.config.force_region_mode)).lower() + if entry.get("global_loading") is True: + mode = "global" + + top_percent = entry.get("force_top_percent", self.config.force_top_percent) + min_ratio = entry.get("seat_height_min_ratio", self.config.seat_height_min_ratio) + max_ratio = entry.get("seat_height_max_ratio", self.config.seat_height_max_ratio) + bbox = entry.get("force_bbox", self.config.force_bbox) + bbox_ratio = entry.get("force_bbox_ratio", self.config.force_bbox_ratio) + + seat_nodes_mask, mode_used, bbox_desc = _select_nodes_for_mode( + mode, top_percent, min_ratio, max_ratio, bbox, bbox_ratio + ) + + num_seat_nodes = int(seat_nodes_mask.sum().item()) + if num_seat_nodes < 1: + logging.warning(f" ⚠️ entry[{entry_label}]matched no nodes, skip") + continue + + force_per_node = entry_force_tensor / num_seat_nodes + self.forces[seat_nodes_mask] += force_per_node + combined_mask |= seat_nodes_mask + + seat_y_values = y_coords[seat_nodes_mask] + seat_y_min = seat_y_values.min().item() + seat_y_max = seat_y_values.max().item() + seat_y_mean = seat_y_values.mean().item() + + if initial_setup: + if mode_used == "bbox": + logging.info(f" 🪑 contact surface[{entry_label}]: bbox ({bbox_desc})") + elif mode_used == "height_ratio": + logging.info( + f" 🪑 contact surface[{entry_label}]: height_ratio " + f"[{min_ratio:.2f}, {max_ratio:.2f}]" + ) + elif mode_used == "global": + logging.info(f" 🪑 contact surface[{entry_label}]: global") + else: + logging.info( + f" 🪑 contact surface[{entry_label}]: highest-Y {float(top_percent):.1%} nodes" + ) + logging.info( + f" 🪑 seat-node count[{entry_label}]: {num_seat_nodes}/{num_nodes} " + f"({num_seat_nodes/num_nodes:.1%})" + ) + logging.info( + f" 🪑 Y range[{entry_label}]: [{seat_y_min:.3f}, {seat_y_max:.3f}], " + f"mean: {seat_y_mean:.3f}" + ) + logging.info(f" 💺 force[{entry_label}]: {entry_force}") + logging.info(f" 💺 per node[{entry_label}]: {force_per_node.cpu().numpy()}") + + self.total_force_preset = total_force + actual_total_force = self.forces.sum(dim=0) + force_error = torch.norm(actual_total_force - total_force).item() + force_error_percent = (force_error / (torch.norm(total_force).item() + 1e-10)) * 100 + + if initial_setup: + logging.info( + f" ✅ total-force check: {actual_total_force.cpu().numpy()} " + f"(error: {force_error:.2e}, {force_error_percent:.3f}%)" + ) + if combined_mask.any(): + self._save_force_visualization( + combined_mask, total_force.cpu().numpy() + ) + else: + logging.debug( + f" 🔄 force update: loaded nodes {int(combined_mask.sum().item())}, " + f"total force error {force_error:.2e}" + ) + + self._last_num_seat_nodes = int(combined_mask.sum().item()) + return + + # 🔧 contact surface detection: support top_percent / height_ratio / bbox + mode = str(getattr(self.config, "force_region_mode", "top_percent")).lower() + seat_nodes_mask = torch.zeros(num_nodes, dtype=torch.bool, device=self.device) + mode_used = mode + bbox_desc = None + if mode_used not in ("top_percent", "height_ratio", "bbox"): + logging.warning(f" ⚠️ invalid force_region_mode: {mode_used}, fallback to top_percent") + mode_used = "top_percent" + + if mode_used == "bbox": + bbox = getattr(self.config, "force_bbox", None) + bbox_ratio = getattr(self.config, "force_bbox_ratio", None) + bbox_vals = None + if bbox is not None and len(bbox) == 6: + bbox_vals = [float(v) for v in bbox] + bbox_desc = "abs" + elif bbox_ratio is not None and len(bbox_ratio) == 6: + bbox_ratio_vals = [float(v) for v in bbox_ratio] + bounds_min = self.nodes.min(dim=0).values + bounds_max = self.nodes.max(dim=0).values + bbox_vals = [ + bounds_min[0].item() + bbox_ratio_vals[0] * (bounds_max[0] - bounds_min[0]).item(), + bounds_min[0].item() + bbox_ratio_vals[1] * (bounds_max[0] - bounds_min[0]).item(), + bounds_min[1].item() + bbox_ratio_vals[2] * (bounds_max[1] - bounds_min[1]).item(), + bounds_min[1].item() + bbox_ratio_vals[3] * (bounds_max[1] - bounds_min[1]).item(), + bounds_min[2].item() + bbox_ratio_vals[4] * (bounds_max[2] - bounds_min[2]).item(), + bounds_min[2].item() + bbox_ratio_vals[5] * (bounds_max[2] - bounds_min[2]).item(), + ] + bbox_desc = "ratio" + else: + logging.warning(" ⚠️ bbox mode did not provide a valid bbox, fallback to top_percent") + mode_used = "top_percent" + + if mode_used == "bbox" and bbox_vals is not None: + x0, x1 = sorted([bbox_vals[0], bbox_vals[1]]) + y0, y1 = sorted([bbox_vals[2], bbox_vals[3]]) + z0, z1 = sorted([bbox_vals[4], bbox_vals[5]]) + seat_nodes_mask = ( + (self.nodes[:, 0] >= x0) & (self.nodes[:, 0] <= x1) + & (self.nodes[:, 1] >= y0) & (self.nodes[:, 1] <= y1) + & (self.nodes[:, 2] >= z0) & (self.nodes[:, 2] <= z1) + ) + if seat_nodes_mask.sum().item() < 1: + logging.warning(" ⚠️ bbox region matched no nodes, fallback to top_percent") + mode_used = "top_percent" + else: + bbox_desc = f"{bbox_desc}: [{x0:.3f},{x1:.3f}]x[{y0:.3f},{y1:.3f}]x[{z0:.3f},{z1:.3f}]" + + if mode_used == "height_ratio": + y_min = y_coords.min().item() + y_max = y_coords.max().item() + y_range = max(1e-8, y_max - y_min) + min_ratio = float(self.config.seat_height_min_ratio) + max_ratio = float(self.config.seat_height_max_ratio) + if not (0.0 <= min_ratio < max_ratio <= 1.0): + logging.warning( + f" ⚠️ invalid height_ratio: min={min_ratio}, max={max_ratio}, fallback to top_percent" + ) + mode_used = "top_percent" + else: + seat_y_min = y_min + y_range * min_ratio + seat_y_max = y_min + y_range * max_ratio + seat_nodes_mask = (y_coords >= seat_y_min) & (y_coords <= seat_y_max) + if seat_nodes_mask.sum().item() < 1: + logging.warning(" ⚠️ height_ratio matched no nodes, fallback to top_percent") + mode_used = "top_percent" + + if mode_used == "top_percent": + top_percent = float(getattr(self.config, "force_top_percent", 0.05)) + top_percent = max(0.0, min(1.0, top_percent)) + if top_percent <= 0.0: + top_percent = 0.05 + num_seat_nodes = max(1, int(num_nodes * top_percent)) + _, top_indices = torch.topk(y_coords, k=num_seat_nodes, largest=True) + seat_nodes_mask = torch.zeros(num_nodes, dtype=torch.bool, device=self.device) + seat_nodes_mask[top_indices] = True + + num_seat_nodes = int(seat_nodes_mask.sum().item()) + + # Step3: get load-region statistics + seat_y_values = y_coords[seat_nodes_mask] + seat_y_min = seat_y_values.min().item() + seat_y_max = seat_y_values.max().item() + seat_y_mean = seat_y_values.mean().item() + + # Step4: computationthe force on each node (total force averaged across nodes) + # 🔑 : force_per_node = total_force / num_seat_nodes + force_per_node = self.total_force_preset / num_seat_nodes + + # Initializationinitialize all node forces to zero + self.forces = torch.zeros((num_nodes, 3), dtype=torch.float32, device=self.device) + + # apply forces only to seat nodes (mean) + self.forces[seat_nodes_mask] = force_per_node + + # Step5: total + actual_total_force = self.forces.sum(dim=0) + force_error = torch.norm(actual_total_force - self.total_force_preset).item() + force_error_percent = (force_error / torch.norm(self.total_force_preset).item()) * 100 + + # loggingoutput + if initial_setup: + if mode_used == "bbox": + logging.info(f" 🪑 contact-surface setup: bbox ({bbox_desc})") + elif mode_used == "height_ratio": + logging.info( + f" 🪑 contact-surface setup: height_ratio " + f"[{self.config.seat_height_min_ratio:.2f}, {self.config.seat_height_max_ratio:.2f}]" + ) + else: + logging.info( + f" 🪑 contact-surface setup: highest-Y {float(getattr(self.config, 'force_top_percent', 0.05)):.1%} nodes" + ) + logging.info(f" 🪑 seat-node count: {num_seat_nodes}/{num_nodes} ({num_seat_nodes/num_nodes:.1%})") + logging.info(f" 🪑 Y-coordinate range: [{seat_y_min:.3f}, {seat_y_max:.3f}], mean: {seat_y_mean:.3f}") + logging.info(f" 💺 preset total force: {self.total_force_preset.cpu().numpy()}") + logging.info(f" 💺 force per node: {force_per_node.cpu().numpy()}") + logging.info(f" ✅ total-force check: {actual_total_force.cpu().numpy()} (error: {force_error:.2e}, {force_error_percent:.3f}%)") + + # computationequivalent pressure + y_range = y_coords.max().item() - y_coords.min().item() + grid_spacing = y_range / self.config.res if y_range > 0 else 0.01 + estimated_area = num_seat_nodes * (grid_spacing ** 2) + if estimated_area > 0 and abs(self.total_force_preset[1].item()) > 0: + pressure_kpa = abs(self.total_force_preset[1].item()) / estimated_area / 1000 + logging.info(f" 📏 equivalent pressure: {pressure_kpa:.1f} kPa (contact area≈{estimated_area:.4f} m²)") + + if pressure_kpa < 5: + logging.warning(f" ⚠️ pressure is too small ({pressure_kpa:.1f} kPa < 5 kPa)") + elif pressure_kpa > 50: + logging.warning(f" ⚠️ pressure is too large ({pressure_kpa:.1f} kPa > 50 kPa)") + + # Save data + self._save_force_visualization(seat_nodes_mask, self.total_force_preset.cpu().numpy()) + else: + # optimizationduring the processlogging + logging.debug(f" 🔄 force update: seat nodes {num_seat_nodes}, per node {force_per_node.cpu().numpy()}, " + f"total force error {force_error:.2e}") + + # checknodeschange + if hasattr(self, '_last_num_seat_nodes') and self._last_num_seat_nodes != num_seat_nodes: + logging.info(f" ⚠️ seat-node count changed: {self._last_num_seat_nodes} → {num_seat_nodes}") + + # Save frontStatus (down) + self._last_num_seat_nodes = num_seat_nodes + + def extract_solid(self, step: int = -1): + """Extract the physical solid: usenodesSDF (alignviewer_deepsdf) + + ⚠️ Key: rebuilds the FEM mesh from the current latents! + + Why re-extraction is needed? + - as optimization progresses, latentschange → SDFchange → thicken / thin + - if, FEMmeshYes, + - : the mesh gets thicker visually but the physics does not respond → Compliance + + Key steps: + 1. generate the full hexahedral grid (fixedResolution) + 2. frontlatentsSDFvalue (update dynamically) + 3. occupancy + 4. SDF thresholdfilter solid elements + + Args: + step: frontoptimization steps (logging) + """ + if not WARP_AVAILABLE: + logging.warning("Warpnot installed, unable toperformphysics simulation") + return + + # re-check whether physiopt is available at runtime + try: + from physiopt.utils.phys_utils import generate_hex as _generate_hex + from physiopt.utils.grid_utils import filter_one_component as _filter_one_component + from physiopt.opt.field import occ_kernel as _occ_kernel + generate_hex_func = _generate_hex + filter_one_component_func = _filter_one_component + occ_kernel_func = _occ_kernel + logging.info("✅ physioptmoduleruntime check succeeded") + except ImportError as e: + logging.error(f"physioptmodulenot installed: {e}") + logging.error("please make sure physiopt is installed correctly: cd /mnt/cvlab/scratch/cvlab/home/hantzhan/physiopt && pip install -e .") + return + + res = self.config.res + step_label = f"Step {step}" if step >= 0 else "Initialization" + logging.info(f"{'🔄' if step >= 0 else '🆕'} [{step_label}] generate/update a mesh at resolution {res} hexahedral mesh...") + + # Save meshinformation () + old_num_nodes = len(self.nodes) if hasattr(self, 'nodes') else 0 + old_num_elements = len(self.elements) if hasattr(self, 'elements') else 0 + + # 1. hexahedral mesh () + full_nodes, full_elements = generate_hex_func( + res=res, + limits=[(-0.8, 0.8), (-0.8, 0.8), (-0.8, 0.8)], + device=self.device, + return_coords=False + ) + + if full_nodes is None or full_elements is None: + logging.error("failed to generate the hexahedral mesh") + return + + full_nodes = full_nodes.to(self.device).float() + full_elements = full_elements.to(self.device).long() + + logging.info(f"hexahedral mesh generated successfully: {full_nodes.shape[0]}nodes, {full_elements.shape[0]}elements") + + # 2. query the SDF (get_field, alignviewer_deepsdf) + logging.info("query node SDF values...") + sdf = self.get_field(full_nodes) + + # 🔧 Key: checkSDFshape, Yes1D [N] + if sdf.dim() > 1: + logging.warning(f"⚠️ SDFYesmulti-dimensional tensor: {sdf.shape}, will be flattened to 1D") + sdf = sdf.squeeze() # remove all size-1 dimensions + if sdf.dim() > 1: + sdf = sdf.reshape(-1) # force-flatten to 1D + + logging.info(f" ✅ SDF query succeeded: range=[{sdf.min():.3f}, {sdf.max():.3f}]") + logging.info(f" nodescount: {full_nodes.shape[0]}, SDF count: {sdf.shape[0]}") + + # SDF count vs. node count + if sdf.shape[0] != full_nodes.shape[0]: + logging.error(f"❌ SDF count({sdf.shape[0]}) vs. node count ({full_nodes.shape[0]})do not match!") + return + + # 3. SDFoccupancy + logging.info("convert the SDF into an occupancy field...") + occ = occ_kernel_func(sdf, res, self.config.occ_sdf_beta) + + # 4. SDF thresholdfilter solid elements (Yesoccupancythreshold value) + # Referenceviewer_deepsdf: nodewise_mask = sdf <= SDF_FILTER_VALUE + SDF_FILTER_VALUE = 1.0 / res + nodewise_mask = sdf <= SDF_FILTER_VALUE + + # Debug information: checkindex range + max_elem_idx = full_elements.max().item() + num_nodes = full_nodes.shape[0] + logging.info(f" elementsindex range: [0, {max_elem_idx}], nodescount: {num_nodes}") + + if max_elem_idx >= num_nodes: + logging.error(f"❌ index out of bounds!maximum element index({max_elem_idx}) >= nodescount({num_nodes})") + logging.error(f" this may be a problem with generate_hex") + # valid range + valid_mask = (full_elements >= 0) & (full_elements < num_nodes) + if not valid_mask.all(): + logging.warning(f" found{(~valid_mask).sum().item()} invalid indices; filtering elements") + # keptall nodeselements + valid_elements_mask = valid_mask.all(dim=1) + full_elements = full_elements[valid_elements_mask] + logging.info(f" element count after filtering: {full_elements.shape[0]}") + + # ifelementsnodescondition, keptelements + elementwise_mask = torch.any(nodewise_mask[full_elements], dim=1) + + num_solid_elements = elementwise_mask.sum().item() + logging.info(f"SDF thresholdfiltering: {num_solid_elements}/{len(elementwise_mask)} solid elements") + + if num_solid_elements == 0: + logging.error("No solid elements were found; please check the SDF or adjust the threshold") + return + + # 5. connectivity filtering (kept) + if self.config.one_cc_only: + element_res = res - 1 + try: + elementwise_mask = filter_one_component_func(elementwise_mask, element_res) + num_filtered_elements = elementwise_mask.sum().item() + logging.info(f"connectivity filtering: {num_filtered_elements} elements kept") + except IndexError as e: + logging.warning(f"connectivity filteringfailed: {e}, using the original mask") + + # 6. elementsandnodes (alignviewer_deepsdf) + selected_elements = full_elements[elementwise_mask] + selected_node_indices, selected_elements = torch.unique( + selected_elements, return_inverse=True + ) + + self.elements = selected_elements + self.nodes = full_nodes[selected_node_indices] + + # 7. computationnodesoccupancy (physics simulation) + coarse_sdf = sdf[selected_node_indices] + coarse_occ_nodes = occ_kernel_func( + coarse_sdf, self.config.res, self.config.occ_sdf_beta + ) + # elementsoccupancyYes8nodesMean + self.coarse_occ = coarse_occ_nodes[self.elements].mean(1) + + # 📊 information: meshchangestatistics + new_num_nodes = len(self.nodes) + new_num_elements = len(self.elements) + + if old_num_nodes > 0: + node_change = new_num_nodes - old_num_nodes + element_change = new_num_elements - old_num_elements + node_change_pct = (node_change / old_num_nodes) * 100 + element_change_pct = (element_change / old_num_elements) * 100 + + logging.info(f"✅ solid extraction completed:") + logging.info(f" nodes: {old_num_nodes} → {new_num_nodes} ({node_change:+d}, {node_change_pct:+.1f}%)") + logging.info(f" elements: {old_num_elements} → {new_num_elements} ({element_change:+d}, {element_change_pct:+.1f}%)") + + if node_change > 0: + logging.info(f" ✅ mesh expanded!added{node_change}nodes (chair legs may have thickened) ") + elif node_change < 0: + logging.warning(f" ⚠️ mesh shrank!removed{-node_change}nodes (chair legs may have become thinner) ") + else: + logging.info(f"✅ solid extraction succeeded: {new_num_nodes}nodes, {new_num_elements}elements") + + # 8. 🔑 Key: meshbackcomputationboundary conditions + # : nodeschange → boundary_maskdo not match + # : nodescomputationboundarymask + y_coords = self.nodes[:, 1] + y_min = y_coords.min() + boundary_threshold = y_min + 0.05 # bottom 5% region + self.boundary_mask = y_coords < boundary_threshold + + num_boundary = self.boundary_mask.sum().item() + logging.debug(f" 🔧 boundary conditionsupdated: {num_boundary}fixed nodes (Y < {boundary_threshold:.3f})") + + def get_current_sds_weight(self, step: int) -> float: + """computationfront stepsSDS weight (value) + + Args: + step: frontoptimization steps + + Returns: + frontSDS weight (sds_weight_startgrowthsds_weight_end) + """ + # value: sds_weight_start sds_weight_end + progress = min(1.0, step / max(1, self.config.num_steps - 1)) + current_weight = self.config.sds_weight_start + progress * (self.config.sds_weight_end - self.config.sds_weight_start) + return current_weight + + def _computation_target_z0_current(self, step: int) -> Tuple[torch.Tensor, torch.Tensor]: + """computationfronttarget_z0 () """ + noise_level = float(self.config.sds_timestep) + t = 1.0 - noise_level # Hunyuan3D-2.1: t=0, t=1data + epsilon = torch.randn_like(self.latents) + + if self.sds_scheduler is not None: + # alignFlow Matchingprocess: x_t = (1 - sigma) * x0 + sigma * eps + sigma_step = 1.0 / float(self.sds_scheduler.config.num_train_timesteps) + total_span = max(0.0, 1.0 - t) + num_steps = int(np.ceil(total_span / sigma_step)) + sigmas = np.linspace(t, 1.0, num_steps + 1, dtype=np.float32) + self.sds_scheduler.set_timesteps(sigmas=sigmas, device=self.device) + t_scheds = self.sds_scheduler.timesteps + t_sched0 = t_scheds[0] + t_model0 = (t_sched0 / self.sds_scheduler.config.num_train_timesteps).to(self.latents.dtype) + if step % max(1, int(self.config.sds_target_z0_update_interval)) == 0: + logging.info( + f" 🎯 target_z0/sigmaalign: noise={noise_level:.4f}, t_start={t:.4f}, " + f"t_sched={t_sched0.item():.2f}, t_model={t_model0.item():.6f}, " + f"steps={num_steps}, sigma_step={sigma_step:.4g}" + ) + else: + t_sched = None + z_t = (1 - t) * epsilon + t * self.latents + t_model = torch.tensor([t], device=self.device, dtype=self.latents.dtype) + + with torch.no_grad(): + if self.sds_scheduler is not None: + # steps sigma , sigma=t 0 + cond_for_model = self._get_cond_for_guidance(self.config.guidance_scale > 1.0) + t_sched0 = t_scheds[0] + t_sched_batch = t_sched0.reshape(1).expand(self.latents.shape[0]) + # Hunyuan3D: t=0, t=1data + z_t = self.sds_scheduler.scale_noise(epsilon, t_sched_batch, noise=self.latents) + + z_curr = z_t + velocity = None + for i in range(len(t_scheds) - 1): + t_sched = t_scheds[i] + t_model = (t_sched / self.sds_scheduler.config.num_train_timesteps).to(self.latents.dtype) + z_t_fp16 = z_curr.to(torch.float16) + t_tensor = t_model.to(device=self.device, dtype=z_t_fp16.dtype) + + if self.config.guidance_scale > 1.0: + latent_model_input = torch.cat([z_t_fp16, z_t_fp16]) + timestep_input = t_tensor.expand(latent_model_input.shape[0]) + + velocity_pred_fp16 = self.flow_model( + latent_model_input, + timestep_input, + cond_for_model, + guidance=None, + ) + + velocity_cond_fp16, velocity_uncond_fp16 = velocity_pred_fp16.chunk(2) + velocity_fp16 = velocity_uncond_fp16 + self.config.guidance_scale * (velocity_cond_fp16 - velocity_uncond_fp16) + + if step % 10 == 0 and i == 0: + logging.debug( + f" CFG (SDS): guidance_scale={self.config.guidance_scale:.1f}, " + f"||v_cond||={torch.norm(velocity_cond_fp16).item():.3e}, " + f"||v_uncond||={torch.norm(velocity_uncond_fp16).item():.3e}" + ) + else: + velocity_fp16 = self.flow_model( + z_t_fp16, + t_tensor.expand(z_t_fp16.shape[0]), + cond_for_model, + guidance=None, + ) + + velocity = velocity_fp16.to(torch.float32) + z_curr = self.sds_scheduler.step(velocity, t_sched, z_curr).prev_sample + + target_z0_current = z_curr + else: + cond_for_model = self._get_cond_for_guidance(self.config.guidance_scale > 1.0) + z_t_fp16 = z_t.to(torch.float16) + t_tensor = t_model.to(device=self.device, dtype=z_t_fp16.dtype) + + if self.config.guidance_scale > 1.0: + latent_model_input = torch.cat([z_t_fp16, z_t_fp16]) + timestep_input = t_tensor.expand(latent_model_input.shape[0]) + + velocity_pred_fp16 = self.flow_model( + latent_model_input, + timestep_input, + cond_for_model, + guidance=None, + ) + + velocity_cond_fp16, velocity_uncond_fp16 = velocity_pred_fp16.chunk(2) + velocity_fp16 = velocity_uncond_fp16 + self.config.guidance_scale * (velocity_cond_fp16 - velocity_uncond_fp16) + + if step % 10 == 0: + logging.debug( + f" CFG (SDS): guidance_scale={self.config.guidance_scale:.1f}, " + f"||v_cond||={torch.norm(velocity_cond_fp16).item():.3e}, " + f"||v_uncond||={torch.norm(velocity_uncond_fp16).item():.3e}" + ) + else: + velocity_fp16 = self.flow_model( + z_t_fp16, + t_tensor.expand(z_t_fp16.shape[0]), + cond_for_model, + guidance=None, + ) + + velocity = velocity_fp16.to(torch.float32) + # fallback: frontEuler stepst=1 + target_z0_current = z_t + (1.0 - t) * velocity + + # 🔧 projection: target_z0frontlatents + max_rel = float(getattr(self.config, "sds_projection_max_rel", 0.0)) + if max_rel > 0.0: + with torch.no_grad(): + diff = target_z0_current - self.latents + diff_norm = torch.norm(diff).item() + latents_norm = torch.norm(self.latents).item() + max_norm = max_rel * (latents_norm + 1e-8) + if diff_norm > max_norm and max_norm > 0.0: + scale = max_norm / (diff_norm + 1e-8) + target_z0_current = self.latents + diff * scale + if step % max(1, int(self.config.sds_target_z0_update_interval)) == 0: + logging.info( + f" 🧱 target_z0 projection limit: diff={diff_norm:.3e} → {max_norm:.3e} " + f"(rel={max_rel:.2f})" + ) + return target_z0_current, velocity + + def _get_target_z0(self, step: int) -> Tuple[torch.Tensor, Optional[torch.Tensor], bool]: + """updatetarget_z0, EMA""" + update_interval = max(1, int(self.config.sds_target_z0_update_interval)) + do_update = self.target_z0_ema is None or step % update_interval == 0 + + if do_update: + target_z0_current, velocity = self._computation_target_z0_current(step) + target_z0_current = target_z0_current.detach() + + if self.target_z0_ema is None: + self.target_z0_ema = target_z0_current.clone() + diff_norm = 0.0 + else: + diff = target_z0_current - self.target_z0_ema + diff_norm = torch.norm(diff).item() + alpha = 1.0 - self.config.sds_target_z0_ema_beta + self.target_z0_ema = self.target_z0_ema + alpha * diff + + self.target_z0_last_velocity = velocity + self.target_z0_last_update = step + + if step % update_interval == 0: + logging.info( + f" 🧭 target_z0 EMAupdate: interval={update_interval}, " + f"beta={self.config.sds_target_z0_ema_beta:.2f}, diff_norm={diff_norm:.3e}" + ) + else: + velocity = self.target_z0_last_velocity + + return self.target_z0_ema, velocity, do_update + + def project_to_manifold(self, step: int) -> bool: + """frontlatentsprojection (target_z0replace directly) """ + with torch.no_grad(): + target_z0, _ = self._computation_target_z0_current(step) + if torch.isnan(target_z0).any() or torch.isinf(target_z0).any(): + logging.warning(" ⚠️ projection failed: target_z0 contains NaN/Inf") + return False + deviation = torch.norm(target_z0 - self.latents).item() + latents_norm = torch.norm(self.latents).item() + rel = deviation / (latents_norm + 1e-8) + logging.info(f" 🧭 projection deviation: {deviation:.3e} (rel={rel:.2%})") + self.latents.data.copy_(target_z0) + if self.latents.grad is not None: + self.latents.grad.zero_() + # reset optimizerStatus, + self.optimizer.state.clear() + # stepsEMAcache + self.target_z0_ema = target_z0.detach().clone() + self.target_z0_last_velocity = None + self.target_z0_last_update = step + return True + + def training_step_sds(self, step: int) -> Tuple[float]: + """ stepsSDSoptimization + + Returns: + (recon_loss,) + """ + self.optimizer.zero_grad() + + # ==================== SDSloss (Rectified Flow) ==================== + t = self.config.sds_timestep + target_z0, velocity, _ = self._get_target_z0(step) + + # SDS gradient: ∇ = z_0 - target_z0 + # thisfront z_0 (self.latents) target_z0 + sds_gradient = self.latents - target_z0.detach() + recon_loss = torch.mean(sds_gradient ** 2) / 2 + + # Debug information + with torch.no_grad(): + target_norm = torch.norm(target_z0).item() + current_norm = torch.norm(self.latents).item() + grad_norm = torch.norm(sds_gradient).item() + velocity_norm = torch.norm(velocity).item() if velocity is not None else 0.0 + + logging.info(f"📐 Step {step:3d} | SDS: ||z_0||={current_norm:.2e}, " + f"||target_z_0||={target_norm:.2e}, " + f"||v||={velocity_norm:.2e}, " + f"||∇||={grad_norm:.2e}, t={t:.2f}, loss={recon_loss.item():.6e}") + + # Backpropagation + sds_gradient_scaled = self.config.sds_weight * sds_gradient + + # checkgradientYesNocontains NaN or Inf + if torch.isnan(sds_gradient_scaled).any() or torch.isinf(sds_gradient_scaled).any(): + logging.error(f"❌ Error: SDS gradient contains NaN or Inf!") + logging.error(f" ||sds_gradient||: {grad_norm:.2e}") + logging.error(f" sds_weight: {self.config.sds_weight}") + logging.error(f" target_z0 range: [{target_z0.min().item():.2e}, {target_z0.max().item():.2e}]") + logging.error(f" latents range: [{self.latents.min().item():.2e}, {self.latents.max().item():.2e}]") + if velocity is not None: + logging.error(f" velocity range: [{velocity.min().item():.2e}, {velocity.max().item():.2e}]") + return (recon_loss.item(),) + + if self.latents.grad is not None: + self.latents.grad.zero_() + + self.latents.grad = sds_gradient_scaled + + # gradient clipping (optional) + if self.config.grad_clip_enabled: + grad_norm_total = torch.norm(self.latents.grad).item() + max_grad_norm = 100.0 # 1e5lower to100 + if grad_norm_total > max_grad_norm: + clip_factor = max_grad_norm / grad_norm_total + self.latents.grad *= clip_factor + logging.warning(f"⚠️ gradient clipping: {grad_norm_total:.4e} -> {max_grad_norm:.4e}") + + # Save updatefrontlatentscomputationchange + old_latents = self.latents.data.clone() + + # checkgradient (Adamfront) + if torch.isnan(self.latents.grad).any(): + logging.error(f"❌ Error: gradient contains NaN (optimizerupdatefront) !") + return (recon_loss.item(),) + + # optimizerupdate + self.optimizer.step() + + # computationparameterschange (updateback - updatefront) + param_change = torch.norm(self.latents.data - old_latents).item() + + # checkNaNand + if torch.isnan(self.latents).any(): + logging.error(f"❌ Error: latents contain NaN (optimizerupdateback) !") + logging.error(f" gradient norm: {grad_norm_total:.4e}") + logging.error(f" Learning rate: {self.config.lr}") + logging.error(f" Param change: {param_change:.4e}") + logging.error(f" suggestion: this may be caused by Adam optimizer momentum") + logging.error(f" : 1) reset optimizer 2) Use SGD instead of Adam") + # updatefrontvalue + self.latents.data.copy_(old_latents) + # reset optimizerStatus (momentum) + self.optimizer.state.clear() + logging.info(f" ✅ already reset optimizerStatus, will retry on the next step") + return (recon_loss.item(),) + + # checklatentsrange (range) + latents_max = torch.abs(self.latents).max().item() + if latents_max > 1000: + logging.warning(f"⚠️ warning: latent values are too large (max={latents_max:.2e})") + logging.warning(f" you may need to lower the learning rate or SDS timestep") + + logging.info(f"✏️ Step {step:3d} | Param change: {param_change:.4e}, max|z|: {latents_max:.2e}") + + return (recon_loss.item(),) + + def training_step_phys_volume( + self, + step: int, + save_step: Optional[int] = None, + ) -> Tuple[float, float, float]: + """physicsoptimization + volume constraint (align ViewerBase optimization) + + Returns: + (compliance_loss, volume_loss, total_loss) + """ + save_step_id = step if save_step is None else int(save_step) + + # ==================== Step1: gradient ==================== + self.optimizer.zero_grad() + + # ==================== Step2: update occupancy (fixed) ==================== + if step > 0: + logging.info(f"🔄 [Step {step}] update occupancy (mesh topology fixed) ...") + old_occ = self.coarse_occ.clone() + sdf = self.get_field(self.nodes) + from physiopt.opt.field import occ_kernel + occ = occ_kernel(sdf, self.config.res, self.config.occ_sdf_beta) + self.coarse_occ = occ[self.elements].mean(1) + + occ_change = self.coarse_occ - old_occ + logging.info(f" occupancy range: [{self.coarse_occ.min():.3f}, {self.coarse_occ.max():.3f}]") + logging.info( + f" occupancy change: mean={occ_change.mean().item():+.3e}, " + f"increase ratio={(occ_change > 0).float().mean().item():.1%}" + ) + + # ==================== Step3: physics simulation (with torch.no_grad) ==================== + with torch.no_grad(): + if self.config.alpha_min > 0.0: + self.coarse_occ = torch.clamp(self.coarse_occ, self.config.alpha_min) + + from torchfem.materials import IsotropicElasticity3D + from physiopt.opt.solid_grid import SolidGrid + + vectorized_material = IsotropicElasticity3D( + E=self.config.youngs_modulus, + nu=self.config.poissons_ratio, + rho=self.config.density, + ).vectorize(self.elements.shape[0]) + + vectorized_material.C *= ( + self.coarse_occ[:, None, None] ** self.config.p_exponent + ) + + solid = SolidGrid(self.nodes, self.elements, vectorized_material) + solid.constraints[self.boundary_mask, :] = True + solid.forces = self.forces + + logging.info(f"Step {step}: FEM solve...") + u, f_int, f_ext, sigma, _, _ = solid.solve(max_iter=1) + logging.info(f" |u|_mean={torch.abs(u).mean():.4e}") + self._log_physical_quantities(u, sigma) + + if ( + self.config.deformed_mesh_interval > 0 + and save_step_id % self.config.deformed_mesh_interval == 0 + ): + try: + self.save_deformed_mesh(save_step_id, u) + except Exception as e: + logging.warning(f" ⚠️ error while saving the deformed mesh: {e}") + + # ==================== Step4: computationcompliancesensitivity ==================== + k0 = solid.k0() # occ^p * K_base (scaleback) + u_j = u[self.elements].reshape(solid.n_elem, -1) + w_k_scaled = torch.einsum("...i, ...ij, ...j", u_j, k0, u_j) + + # occ^pscaletrue (alternatealign) + occ_power = torch.clamp( + self.coarse_occ ** self.config.p_exponent, + min=1e-6, + max=1.0, + ) + if torch.any(occ_power < 1e-6): + n_small = (occ_power < 1e-6).sum().item() + logging.warning(f" ⚠️ {n_small} elements have extremely small occ^p and were clamped to 1e-6") + + w_k_base = w_k_scaled / occ_power + if torch.isnan(w_k_base).any() or torch.isinf(w_k_base).any(): + n_nan = torch.isnan(w_k_base).sum().item() + n_inf = torch.isinf(w_k_base).sum().item() + logging.error(f" ❌ w_k_baseabnormal: {n_nan} NaN, {n_inf} Inf") + logging.error(" fall back to SIMP weightingw_k") + w_k_base = w_k_scaled + + compliance_mean = w_k_base.mean().item() + w_k = w_k_base + w_k_max = w_k.max().item() + w_k_mean = w_k.mean().item() + logging.info(f" Compliance (true) ={compliance_mean:.2e}") + logging.info( + f" w_k_base: max={w_k_max:.2e}, stress concentration={w_k_max/(w_k_mean + 1e-10):.1f}x" + ) + + self.sensitivity_density = ( + -self.config.p_exponent + * self.coarse_occ ** (self.config.p_exponent - 1) + * w_k + ) + + # ==================== Step5: volume constraint ==================== + volume_loss = 0.0 + if self.config.volume_term > 0.0: + if not hasattr(self, "init_volume"): + self.init_volume = self.coarse_occ.clone() + logging.info(f" record initial volume: sum={self.init_volume.sum().item():.2f}") + + sensitivity_volume = ( + self.config.volume_term + * (1.0 / self.config.res) ** 3 + * torch.ones_like(self.sensitivity_density) + ) + volume_sign = ( + 1.0 + if self.coarse_occ.sum() >= self.init_volume.sum() + else -1.0 + ) + self.sensitivity_density += sensitivity_volume * volume_sign + volume_loss = self.coarse_occ.mean().item() + logging.info( + f" volume constraint: mean={volume_loss:.2e}, " + f"{'penalize' if volume_sign > 0 else 'encourage'}, " + f"weight={self.config.volume_term:.2e}" + ) + else: + logging.info(" volume constraint: disabled") + + # ==================== Step6: Backward ==================== + self.backward_step(self.sensitivity_density) + + # gradient clipping (optional) + if self.latents.grad is not None: + grad_norm = torch.norm(self.latents.grad).item() + if self.config.grad_clip_enabled: + max_grad_norm = 1000.0 + if grad_norm > max_grad_norm: + clip_factor = max_grad_norm / grad_norm + self.latents.grad *= clip_factor + logging.info( + f" ✂️ gradient clipping: {grad_norm:.4e} -> {max_grad_norm:.1f} " + f"(×{clip_factor:.3f})" + ) + else: + logging.error("❌ gradient, skip stepsoptimization") + return (compliance_mean, volume_loss, compliance_mean + volume_loss) + + # ==================== Step7: Optimizer step ==================== + old_latents = self.latents.data.clone() + self.optimizer.step() + + with torch.no_grad(): + latents_change = torch.norm(self.latents.data - old_latents).item() + latents_norm = torch.norm(old_latents).item() + change_pct = (latents_change / (latents_norm + 1e-10)) * 100 + max_change = torch.abs(self.latents.data - old_latents).max().item() + logging.info( + f" 🔄 Latentschange: L2={latents_change:.4e} ({change_pct:.3f}%), max={max_change:.4e}" + ) + if latents_change < 1e-6: + logging.warning(" ⚠️ latents almost did not change!the learning rate may be too small or the gradient may be too weak") + + total_loss = compliance_mean + volume_loss + return (compliance_mean, volume_loss, total_loss) + + def training_step_dual_lagrange_v2( + self, + step: int, + lagrange: float, + rho: float, + use_sds: bool = True, + save_step: Optional[int] = None, + ) -> Tuple[float, float, float]: + """already : kept, physicsoptimization+volume constraint. """ + logging.warning( + "training_step_dual_lagrange_v2 already : physicsoptimization+volume constraint" + ) + return self.training_step_phys_volume(step=step, save_step=save_step) + save_step_id = step if save_step is None else int(save_step) + + # ==================== Step1: gradient ==================== + self.optimizer.zero_grad() + + # ==================== Step2: update occupancy (fixed) ==================== + if step > 0: + logging.info(f"🔄 [Step {step}] update occupancy (mesh topology fixed) ...") + # Save occupancy + old_occ = self.coarse_occ.clone() + + # query the SDFandoccupancy + sdf = self.get_field(self.nodes) + from physiopt.opt.field import occ_kernel + occ = occ_kernel(sdf, self.config.res, self.config.occ_sdf_beta) + self.coarse_occ = occ[self.elements].mean(1) + + # occchange + occ_change = self.coarse_occ - old_occ + occ_mean_change = occ_change.mean().item() + occ_increase_ratio = (occ_change > 0).float().mean().item() + + logging.info(f" occupancy range: [{self.coarse_occ.min():.3f}, {self.coarse_occ.max():.3f}]") + logging.info(f" occupancy change: mean={occ_mean_change:+.3e}, increase ratio={occ_increase_ratio:.1%}") + + # ==================== Step3: physics simulation (with torch.no_grad) ==================== + # match the reference code Line 1317-1356 + with torch.no_grad(): + # 3.1 prepare_solid: SIMP + createSolidGrid + # align Line 474-498 + if self.config.alpha_min > 0.0: + self.coarse_occ = torch.clamp(self.coarse_occ, self.config.alpha_min) + + # materialSIMPscale + from torchfem.materials import IsotropicElasticity3D + from physiopt.opt.solid_grid import SolidGrid + + vectorized_material = IsotropicElasticity3D( + E=self.config.youngs_modulus, + nu=self.config.poissons_ratio, + rho=self.config.density, + ).vectorize(self.elements.shape[0]) + + vectorized_material.C *= ( + self.coarse_occ[:, None, None] ** self.config.p_exponent + ) + + # createSolidGrid + solid = SolidGrid(self.nodes, self.elements, vectorized_material) + solid.constraints[self.boundary_mask, :] = True + solid.forces = self.forces + + # 3.2 FEM solve + # align Line 1325-1328 + logging.info(f"Step {step}: FEM solve...") + u, f_int, f_ext, sigma, _, _ = solid.solve(max_iter=1) + logging.info(f" |u|_mean={torch.abs(u).mean():.4e}") + + # N stepsSave deformed mesh () + if self.config.deformed_mesh_interval > 0 and save_step_id % self.config.deformed_mesh_interval == 0: + try: + self.save_deformed_mesh(save_step_id, u) + except Exception as e: + logging.warning(f" ⚠️ error while saving the deformed mesh: {e}") + + # ==================== Step4: computationsensitivity ==================== + # align Line 1368-1399 + + # 4.1 computation (v90succeeded + enhancedvalue) + # + # Keyfound: + # - v90"true": Compliancedown98% ✓ + # - v94"SIMP": Complianceback ✗ + # + # : occ^pscale, value + # + k0 = solid.k0() # occ^p * K_base (scaleback) + u_j = u[self.elements].reshape(solid.n_elem, -1) + w_k_scaled = torch.einsum("...i, ...ij, ...j", u_j, k0, u_j) + + # occ^pscaletrue (v90) + # 🔧 value + occ_power = torch.clamp( + self.coarse_occ ** self.config.p_exponent, + min=1e-6, # Min + max=1.0 # Max + ) + + # frontcheck + if torch.any(occ_power < 1e-6): + n_small = (occ_power < 1e-6).sum().item() + logging.warning(f" ⚠️ {n_small} elements have extremely small occ^p and were clamped to 1e-6") + + w_k_base = w_k_scaled / occ_power + + # NaN + if torch.isnan(w_k_base).any() or torch.isinf(w_k_base).any(): + n_nan = torch.isnan(w_k_base).sum().item() + n_inf = torch.isinf(w_k_base).sum().item() + logging.error(f" ❌ w_k_baseabnormal: {n_nan} NaN, {n_inf} Inf") + logging.error(f" fall back to SIMP weightingw_k") + w_k_base = w_k_scaled + + # usetrue + compliance_mean = w_k_base.mean().item() + w_k = w_k_base # backsensitivitycomputationtrue + + # + logging.info(f" Compliance (true) ={compliance_mean:.2e}") + logging.info(f" w_k_base: max={w_k.max():.2e}, stress concentration={w_k.max()/(w_k.mean() + 1e-10):.1f}x") + + # ALMconstraint normalization: g = D/D_thr - 1 + compliance_threshold = self.config.compliance_threshold if self.config.compliance_threshold is not None else 1.0 + g_raw = compliance_mean / (compliance_threshold + 1e-8) - 1.0 + g_pos = max(0.0, g_raw) + logging.info(f" constraint normalization: g={g_raw:+.3e}, [g]+={g_pos:.3e}, D_thr={compliance_threshold:.2e}") + + # dynamicgradient clippingupper bound (ALMscale) + base_max_grad = 1000.0 + lagrange_bonus = min((lagrange + rho * g_pos) * 10.0, 1000.0) + max_grad_norm = base_max_grad + lagrange_bonus + + # 4.3 sensitivitycomputation (match the reference code Line 1379-1383) + # + # Reference: + # sensitivity = -p * occ^(p-1) * w_k + # + # (v90already ) : + # - Hunyuannegative (matching the reference code) + # - Compliancedown (1.67 → 0.046, down97%) + # + self.sensitivity_density = ( + -self.config.p_exponent + * self.coarse_occ ** (self.config.p_exponent - 1) + * w_k + ) + + # 4.4 volume constraint (disabledphysicsoptimization) + # + # issue: Referencevolume_term=1e6Hunyuandown + # : + # - volumesensitivity: 1e6 * 1e-6 = 1.0 + # - physicssensitivity: -p * occ^(p-1) * w_k ≈ 0.001 + # - : volume constraintdominates, physics (allelementssensitivity) + # + # : disabledvolume constraint, physicsoptimizationYesNo + # physicsoptimizationback, volume_term (1e3) + # + if False and self.config.volume_term > 0.0: # force disabled + # Initialization + if not hasattr(self, 'init_volume'): + self.init_volume = self.coarse_occ.clone() + logging.info(f" record initial volume: sum={self.init_volume.sum().item():.2f}") + + # volumesensitivity + sensitivity_volume = ( + self.config.volume_term + * (1.0 / self.config.res) ** 3 + * torch.ones_like(self.sensitivity_density) + ) + + # + volume_sign = 1.0 if self.coarse_occ.sum() >= self.init_volume.sum() else -1.0 + sensitivity_volume *= volume_sign + + self.sensitivity_density += sensitivity_volume + + volume_ratio = self.coarse_occ.sum() / self.init_volume.sum() + logging.info(f" volume constraint: ratio={volume_ratio.item():.3f}, " + f"{'penalize' if volume_sign > 0 else 'encourage'}") + else: + logging.info(f" volume constraint: disabled (physicsoptimizationdominates) ") + + # sensitivity + sens_norm = torch.norm(self.sensitivity_density).item() + sens_min = self.sensitivity_density.min().item() + sens_max = self.sensitivity_density.max().item() + logging.info(f" sensitivity: norm={sens_norm:.2e}, range=[{sens_min:.2e}, {sens_max:.2e}]") + + # ==================== Step5: Backward (VJP) ==================== + # align Line 1401 + self.backward_step(self.sensitivity_density) + + # ==================== Step6: ALMweight (λ + ρ[g]+) ==================== + if self.latents.grad is not None: + phys_grad_norm = torch.norm(self.latents.grad).item() + phys_grad_unscaled = self.latents.grad.clone() # Save scalephysics gradientSDS + + if g_pos > 0.0: + alm_scale_raw = (lagrange + rho * g_pos) / (compliance_threshold + 1e-8) + alm_scale = alm_scale_raw + guard_ratio = min(max(self.config.alm_scale_guard_ratio, 0.0), 1.0) + if phys_grad_norm > 0.0 and max_grad_norm > 0.0 and guard_ratio > 0.0: + alm_scale_guard = (max_grad_norm * guard_ratio) / (phys_grad_norm + 1e-8) + if alm_scale > alm_scale_guard: + logging.info( + f" 🔧 ALMscaling limit: raw={alm_scale_raw:.3e} -> {alm_scale_guard:.3e} " + f"(guard={guard_ratio:.2f}, max_grad={max_grad_norm:.1f})" + ) + alm_scale = alm_scale_guard + self.latents.grad *= alm_scale + else: + alm_scale = 0.0 + self.latents.grad.zero_() + + scaled_grad_norm = torch.norm(self.latents.grad).item() + logging.info( + f" physics gradient(ALM): {phys_grad_norm:.2e} → {scaled_grad_norm:.2e} " + f"(×scale={alm_scale:.3e}, λ={lagrange:.2f}, ρ={rho:.2f})" + ) + else: + phys_grad_unscaled = None + alm_scale = 0.0 + + # ==================== Step7: Shape Losscomputation (latentsandtarget_z0) ==================== + # Reference training_step_dual_lagrange_old Shape + + # 7.1 computationtarget_z0 (backlatent) + import math + if use_sds: + target_z0, _, _ = self._get_target_z0(step) + else: + target_z0 = self.latents.detach() + + # 🔍 andSave target_z0 mesh (10 steps) + if use_sds: + self._maybe_save_target_z0_mesh(target_z0, save_step_id) + + # computationShape Loss (MSE loss) : latentsandtarget_z0 + shape_loss = torch.nn.functional.mse_loss(self.latents, target_z0.detach()) + + # 7.2 YesNouseShape Loss + current_sds_weight = self.get_current_sds_weight(step) if use_sds else 0.0 + use_sds_this_step = current_sds_weight > 0.0 + + if not use_sds_this_step: + logging.info(f" 🚫 Shape Loss disabled (physicsoptimizationmode) ") + weighted_sds = 0.0 + shape_grad_norm = 0.0 + else: + # Shape Loss + weighted_shape_loss = current_sds_weight * shape_loss + + # checkShape Loss + if torch.isnan(shape_loss) or torch.isinf(shape_loss): + logging.error(f" ❌ Shape Loss contains NaN or Inf; skipping the shape constraint") + weighted_sds = 0.0 + shape_grad_norm = 0.0 + else: + # computationShape Lossgradientlatents.gradup + weighted_shape_loss.backward() + + # computationshapegradientnorm (logging) + if self.latents.grad is not None and phys_grad_unscaled is not None: + # shapegradient (total gradient - physics gradient) + shape_gradient = self.latents.grad - phys_grad_unscaled * alm_scale + shape_grad_norm = torch.norm(shape_gradient).item() + phys_grad_norm_current = torch.norm(phys_grad_unscaled * alm_scale).item() + shape_phys_ratio = shape_grad_norm / (phys_grad_norm_current + 1e-10) + + if shape_phys_ratio > 100.0: + logging.error(f" ❌ Shape gradient is too large (Shape/physics={shape_phys_ratio:.1f}x)!") + logging.error(f" consider lowering sds_weight_end: {self.config.sds_weight_end} → {self.config.sds_weight_end/100:.4f}") + elif shape_phys_ratio > 10.0: + logging.warning(f" ⚠️ Shape gradient is relatively large (Shape/physics={shape_phys_ratio:.1f}x)") + + # computationgradient direction + cos_angle = (phys_grad_unscaled * shape_gradient).sum() / ( + torch.norm(phys_grad_unscaled) * torch.norm(shape_gradient) + 1e-10 + ) + angle_deg = torch.acos(torch.clamp(cos_angle, -1, 1)) * 180 / math.pi + direction = "same direction✅" if angle_deg < 90 else "opposite direction⚠️" + + logging.info(f" Shapegradient: norm={shape_grad_norm:.4e}, weight={current_sds_weight:.6f}") + logging.info(f" gradient direction: physics vs Shape = {angle_deg:.1f}° ({direction})") + elif self.latents.grad is not None: + shape_grad_norm = torch.norm(self.latents.grad).item() + logging.info(f" Shapegradient: norm={shape_grad_norm:.4e} (no physics gradient)") + else: + shape_grad_norm = 0.0 + + weighted_sds = weighted_shape_loss.item() + + # ==================== Step8: lossandgradient clipping ==================== + compliance_loss_item = compliance_mean + alm_penalty = lagrange * g_pos + 0.5 * rho * (g_pos ** 2) + total_loss = alm_penalty + weighted_sds + + # lossinformation + if use_sds_this_step: + logging.info( + f" 📊 weighted loss: Compliance={compliance_loss_item:.4e}, g={g_raw:+.3e}, " + f"ALM={alm_penalty:.4e} (λ={lagrange:.2f}, ρ={rho:.2f}), " + f"Shape={weighted_sds:.4e} (×w={current_sds_weight:.6f}), Total={total_loss:.4e}" + ) + else: + logging.info( + f" 📊 weighted loss: Compliance={compliance_loss_item:.4e}, g={g_raw:+.3e}, " + f"ALM={alm_penalty:.4e} (λ={lagrange:.2f}, ρ={rho:.2f}), " + f"Shape=0.00e+00 (disabled), Total={total_loss:.4e}" + ) + + # gradient composition + if self.latents.grad is not None: + grad_norm = torch.norm(self.latents.grad).item() + + # computationgradient + if phys_grad_unscaled is not None: + weighted_phys_grad_norm = torch.norm(phys_grad_unscaled * alm_scale).item() + logging.info(f" 🔍 gradient composition: Weighted Compliance Grad={weighted_phys_grad_norm:.4e} (ALM scale={alm_scale:.3e})") + + if use_sds_this_step and shape_grad_norm > 0: + logging.info(f" Scaled Shape Grad={shape_grad_norm:.4e} (Shape×w={current_sds_weight:.6f})") + if phys_grad_unscaled is not None: + grad_ratio = shape_grad_norm / (weighted_phys_grad_norm + 1e-10) + logging.info(f" ratio: Shape/Compliance = {grad_ratio:.4f} ({grad_ratio*100:.2f}%)") + + logging.info(f" Total Grad={grad_norm:.4e}") + + # gradient clipping (optional) + if self.latents.grad is not None: + grad_norm = torch.norm(self.latents.grad).item() + + if torch.isnan(self.latents.grad).any() or torch.isinf(self.latents.grad).any(): + logging.error(f"❌ the final gradient contains NaN or Inf!skip this steps") + return (compliance_loss_item, shape_loss.item(), total_loss) + + if self.config.grad_clip_enabled: + if grad_norm > max_grad_norm: + clip_factor = max_grad_norm / grad_norm + self.latents.grad = self.latents.grad * clip_factor + logging.info(f" ✂️ gradient clipping: {grad_norm:.4e} -> {max_grad_norm:.1f} (×{clip_factor:.3f})") + else: + logging.info(f" ✅ gradient not clipped: {grad_norm:.4e} (max={max_grad_norm:.1f})") + + # ==================== Step9: Optimizer step ==================== + # align Line 1423 + + # Save latents + old_latents = self.latents.data.clone() + + self.optimizer.step() + + # latentschange + with torch.no_grad(): + latents_change = torch.norm(self.latents.data - old_latents).item() + latents_norm = torch.norm(old_latents).item() + latents_change_percent = (latents_change / (latents_norm + 1e-10)) * 100 + max_latents_change = torch.abs(self.latents.data - old_latents).max().item() + + logging.info(f" 🔄 Latentschange: L2={latents_change:.4e} ({latents_change_percent:.3f}%), max={max_latents_change:.4e}") + + if latents_change < 1e-6: + logging.warning(f" ⚠️ latents almost did not change!the learning rate may be too small or the gradient may be too weak") + + # lossvalue + return (compliance_loss_item, shape_loss.item(), total_loss) + + def training_step_dual_lagrange_old(self, step: int, lagrange: float) -> Tuple[float, float, float]: + """ stepsLegacy Dual Lagrangeoptimization (physics + shape) + + Args: + step: front steps + lagrange: Lagrange (physicsandshape) + + Returns: + (compliance_loss, sds_loss, total_loss) + """ + if not WARP_AVAILABLE: + logging.error("Warpnot installed, unable torun legacy dual Lagrange optimization") + return (0.0, 0.0, 0.0) + + self.optimizer.zero_grad() + + # ==================== 1. 🔑 Key: update occupancy, mesh!==================== + # + # 🚨 found: stepsmeshcompliance! + # + # Error (v78front) : + # Step 0: extract_solid() → initialmesh(19608 nodes, occ=[0.015, 1.0]) + # Step 1: extract_solid() → mesh(19667 nodes, +59) + # → nodes, occ≈0.015 (!) + # → SIMPpenalize 0.015^3 ≈ 0, 0 + # → thiselementsstress concentration, w_k_maxincrease + # → complianceYes!❌ + # + # (match the reference codeDeepSDF/TRELLIS) : + # Step 0: extract_solid() → initialmesh(19608 nodes), fixed + # Step 1-N: + # - fixed nodesupquery the SDF (latentsalready change) + # - computationoccupancy (nodesoccincrease) + # - occupancyFEMandsensitivitycomputation + # - mesh!✅ + # : occupancygrowth, no elements, compliancedown + # + # Reference: viewer_deepsdf.py mesh! + + if step > 0: # attempt 0 stepsalready Initialization + # 🔧 : mesh, update occupancy + # logging.debug(f"🔄 [Step {step}] extract the solidmesh...") + # self.extract_solid(step=step) # ❌ !thisoccelements + + # ✅ correct approach: frontnodesSDFandoccupancy + logging.info(f"🔄 [Step {step}] update occupancy (meshtopology remains fixed) ...") + + # Save occupancy + old_occ = self.coarse_occ.clone() + + sdf = self.get_field(self.nodes) # frontlatentsquery the SDF + + from physiopt.opt.field import occ_kernel + occ = occ_kernel(sdf, self.config.res, self.config.occ_sdf_beta) + self.coarse_occ = occ[self.elements].mean(1) # update occupancy + + # 🔍 : occupancychange + occ_change = self.coarse_occ - old_occ + occ_increase_ratio = (occ_change > 0).float().mean().item() + occ_mean_change = occ_change.mean().item() + + logging.info(f" SDFrange: [{sdf.min():.3f}, {sdf.max():.3f}]") + logging.info(f" Occupancyupdate: [{self.coarse_occ.min():.3f}, {self.coarse_occ.max():.3f}]") + logging.info(f" 🔍 occupancy change: mean={occ_mean_change:+.3e}, increase ratio={occ_increase_ratio:.1%}") + if occ_mean_change < 0: + logging.warning(f" ⚠️ occupancy mean decreased!the gradient direction may be wrong") + + # mesh: self.nodes, self.elements + + # ==================== 2. checkmeshStatus ==================== + if not hasattr(self, 'nodes') or not hasattr(self, 'elements'): + logging.error("please callextract_solid()Initializationmesh") + return (0.0, 0.0, 0.0) + + # ==================== 3. meshandoccupancyStatus ==================== + # extract_solid()already computationself.coarse_occ, this + + if not hasattr(self, 'coarse_occ'): + logging.error("extract_solid()coarse_occ is not set, please check") + return (0.0, 0.0, 0.0) + + # valuecheck + if torch.isnan(self.coarse_occ).any() or torch.isinf(self.coarse_occ).any(): + logging.warning(f"Step {step}: Occupancycontains NaN or Inf, repairing") + adaptive_alpha_min = self.config.alpha_min + if self.config.res >= 64: + adaptive_alpha_min = max(self.config.alpha_min, 0.05) + self.coarse_occ = torch.nan_to_num(self.coarse_occ, nan=adaptive_alpha_min, + posinf=1.0, neginf=adaptive_alpha_min) + + logging.debug(f"Step {step}: Occupancyrange=[{self.coarse_occ.min():.3f}, {self.coarse_occ.max():.3f}]") + + # ==================== 4. andboundary conditionscheck (mesh topology fixedbackno update) ==================== + # + # 🔑 Keychange: meshfixed, forcesandboundary_maskInitialization + # + # (v78) : stepsmesh → nodeschange → stepsupdateforces + # (v79+) : mesh topology fixed → nodes → forcesandboundary_mask + # + # optimizationStepcheck + + if step == 0: + # check: forcesandboundary_mask + if not hasattr(self, 'forces') or self.forces.shape[0] != self.nodes.shape[0]: + logging.error(f"Forcesdo not match!forces.shape[0]={self.forces.shape[0] if hasattr(self, 'forces') else 'N/A'}, nodes.shape[0]={self.nodes.shape[0]}") + return (0.0, 0.0, 0.0) + + if not hasattr(self, 'boundary_mask') or self.boundary_mask.shape[0] != self.nodes.shape[0]: + logging.error(f"boundary mask dimensions do not match!") + return (0.0, 0.0, 0.0) + + logging.info(f" ✅ force and boundary-condition validation passed (stays unchanged throughout the entire optimization process) ") + + # Step > 0: no update, forcesandboundary_mask + + # ==================== 5. physics simulation (useReference!) ==================== + try: + from physiopt.opt.solid_grid import SolidGrid # useoriginalsolve + from torchfem.materials import IsotropicElasticity3D + + # ===== useReferencematerial setup ===== + # Reference: viewer_base.py Line 481-494 + + # Step 1: creatematerial + # note: configcontainsmaterialparameters, YesMaterialConfig + base_material = IsotropicElasticity3D( + E=self.config.youngs_modulus, + nu=self.config.poissons_ratio, + rho=self.config.density, + ) + vectorized_material = base_material.vectorize(self.elements.shape[0]) + + # Step 2: clampoccupancy (match the reference code viewer_base.py Line 474-476) + # + # Referenceprepare_solidclampbackin-placeself.coarse_occ + # thisbackSIMPandsensitivitycomputationclampbackvalue + # + alpha_min = self.config.alpha_min if self.config.res < 64 else max(self.config.alpha_min, 0.05) + if alpha_min > 0.0: + self.coarse_occ = torch.clamp(self.coarse_occ, min=alpha_min) + + # Step 3: SIMP - C (match the reference code Line 486-488) + vectorized_material.C *= ( + self.coarse_occ[:, None, None] ** self.config.p_exponent + ) + + logging.info(f"Step {step}: material setup (Referencecode style) ") + logging.info(f" Occupancyrange: [{self.coarse_occ.min():.3f}, {self.coarse_occ.max():.3f}]") + logging.info(f" SIMPpenalty exponent p={self.config.p_exponent}") + + # Step 3: create SolidGrid (Referencecode style) + solid = SolidGrid(self.nodes, self.elements, vectorized_material) + solid.constraints[self.boundary_mask, :] = True + solid.forces = self.forces + + # Step 4: FEM solve (Referencecode style - viewer_base.py Line 1325) + logging.info("FEM solve (useoriginalSolidGrid) ...") + u, f_int, f_ext, sigma, _, _ = solid.solve(max_iter=1) + logging.info(f" solve completed: |u|={torch.abs(u).mean():.4e}") + + # Save deformed mesh (N steps) + if self.config.deformed_mesh_interval > 0 and step % self.config.deformed_mesh_interval == 0: + try: + self.save_deformed_mesh(step, u) + except Exception as e: + logging.warning(f" ⚠️ error while saving the deformed mesh: {e}") + + # ===== computation compliance andsensitivity (match the reference code) ===== + # Reference: viewer_base.py Line 1370-1383 + + k0 = solid.k0() + u_j = u[self.elements].reshape(solid.n_elem, -1) + w_k = torch.einsum("...i, ...ij, ...j", u_j, k0, u_j) # elements + + # 🔍 : checkdistribution + w_k_mean = w_k.mean().item() + w_k_max = w_k.max().item() + w_k_std = w_k.std().item() + w_k_sum = w_k.sum().item() + + # 🎯 Key: compliancew_k.sum(), scale! + # + # : already occ^pscale (Line 1210) , w_k = u^T * K(occ) * u already containsocc^p + # + # Error (v78) : compliance = (occ^p * w_k).sum() ← scale! + # → mesh(occ↑) → complianceincrease ❌ + # + # correct approach (match the reference code) : compliance = w_k.sum() + # → mesh(occ↑) → ↑ → ↓ → w_k↓ → compliance↓ ✅ + # + compliance_sum = w_k.sum() + compliance_mean = w_k.mean() + compliance = compliance_sum + + logging.info(f" compliance_sum={compliance_sum:.2e}, compliance_mean={compliance_mean:.2e}, |u|_mean={torch.abs(u).mean().item():.2e}") + logging.info(f" w_kdistribution: max={w_k_max:.2e}, std={w_k_std:.2e}, mean/max={w_k_mean/w_k_max:.3f}") + + if w_k_max > 10 * w_k_mean: + logging.warning(f" ⚠️ detected stress concentration!w_k_max/w_k_mean = {w_k_max/w_k_mean:.1f}x") + + compliance_loss = compliance + + # ===== sensitivitycomputation ===== + # + # � Key: usenegative (matching the reference code) ! + # + # Reference: + # sensitivity = -p * occ^(p-1) * w_k + # + # ⚠️ Key: latents → SDF → occupancy optimization + # + # gradient: + # 1. ∂L/∂occ = -w_k (negative, ) + # 2. ∂occ/∂sdf = -beta*sigmoid' < 0 (negative, occ=sigmoid(-sdf)) + # 3. ∂L/∂sdf = ∂L/∂occ × ∂occ/∂sdf = (-w_k) × (-) > 0 (!) + # 4. ∂L/∂latents = ∂L/∂sdf × ∂sdf/∂latents > 0 + # 5. latents -= lr * grad → latents + # 6. latents↓ → SDF↓ → occ↑ → material ✅ + # + # v71 ? + # - → ∂L/∂sdf < 0 → ∂L/∂latents < 0 + # - latents -= lr*grad → latentsincrease + # - latents↑ → SDF↑ → occ↓ → material → ❌ + # + # + # 🎯 sensitivity: final + # + # (v82 vs v83) : + # v82: sens=9.6e-02, compliance↑, stress concentration 【 -p*occ^(p-1)*w_k】 + # v83: sens=3.6e+00, compliance↑, 【 -p*w_k/occ】 + # + # : issue! + # + # : + # SIMP: dc/dρ = -p * ρ^(p-1) * u^T * K_base * u + # w_k = u^T * (ρ^p * K_base) * u (already scale) + # : u^T * K_base * u = w_k / ρ^p + # + # : dc/dρ = -p * ρ^(p-1) * (w_k / ρ^p) = -p * w_k / ρ + # Reference: dc/dρ = -p * ρ^(p-1) * w_k = -p * ρ^(2p-1) * w_k_base + # + # Keyfound: ReferenceYes**sensitivityfilter**! + # - density: ρ^(2p-1) = 0.05^5 ≈ 3e-7 () + # - density: ρ^(2p-1) ≈ 1 () + # → densityregion, "" + # + # Referenceissue: stress concentration (ifdensity) + # + # 🔧 : + # 1. useReference () + # 2. stress concentration (w_kelements) sensitivity (occ) + # 3. addedscale, preserve gradientsrange + # + # Reference, + sensitivity_density = ( + -self.config.p_exponent + * self.coarse_occ ** (self.config.p_exponent - 1) + * w_k + ) + + # 🔧 : elementsenhancedsensitivity (occ) + # stress concentration: w_ktop 5%elements + w_k_threshold_percentile = 95 + w_k_threshold = torch.quantile(w_k, w_k_threshold_percentile / 100.0) + stress_concentration_mask = w_k >= w_k_threshold + + if stress_concentration_mask.any(): + # stress concentration, usesensitivity + # : -p * w_k / occ (SIMP) + eps = 1e-8 + enhanced_sensitivity = -self.config.p_exponent * w_k / (self.coarse_occ + eps) + + # 🔧 : enhancedsensitivity, gradient + # computationenhanced: enhanced / base + base_sensitivity = sensitivity_density[stress_concentration_mask] + enhance_factor = enhanced_sensitivity[stress_concentration_mask] / (base_sensitivity + eps) + + # enhanced[1, 50]range (enhanced50) + max_enhance_factor = 50.0 + enhance_factor_clamped = torch.clamp(enhance_factor, min=1.0, max=max_enhance_factor) + enhanced_sensitivity_safe = base_sensitivity * enhance_factor_clamped + + # : stress concentrationenhanced (back) , Reference + sensitivity_density[stress_concentration_mask] = enhanced_sensitivity_safe + + n_enhanced = stress_concentration_mask.sum().item() + avg_enhance = enhance_factor_clamped.mean().item() + logging.info(f" 🎯 enhanced{n_enhanced}stress concentrationelements (top 5%) , mean enhancement{avg_enhance:.1f}x") + + # 🔧 Key: added****volume constraint + # + # v85issue: fixedvolume constraint (1e6) , : + # - volume constraintdominatesgradient (1.0 vs physics0.1) + # - optimizervolumeboundary (0.988-1.003) + # - Complianceunable todown (physics) + # + # : + # 1. lowerweight (1e6 → 1e4) + # 2. addedtolerance range (±5%) : changepenalize + # 3. outside the tolerance range, penalize () + if self.config.volume_term > 0.0: + # attempt record initial volume + if not hasattr(self, 'init_volume'): + self.init_volume = self.coarse_occ.sum().item() + logging.info(f" 📊 record initial volume: {self.init_volume:.2f}") + + current_volume = self.coarse_occ.sum().item() + volume_ratio = current_volume / self.init_volume + volume_deviation = volume_ratio - 1.0 # : >0indicatesviolating, <0indicates + + # 🔧 : tolerance rangepenalize + tolerance = self.config.volume_tolerance # ±5% + + if abs(volume_deviation) > tolerance: + # outside the tolerance range, penalize + # penalizeexceeds + excess = abs(volume_deviation) - tolerance # outside the tolerance range + adaptive_weight = self.config.volume_term * (excess / tolerance) # + + elem_volume = (1.0 / self.config.res) ** 3 + sensitivity_volume = ( + adaptive_weight + * elem_volume + * torch.ones_like(sensitivity_density) + ) + + # : volumeviolating → sensitivity (penalize) ; volume → negativesensitivity (encourage) + volume_sign = 1.0 if volume_deviation > 0 else -1.0 + sensitivity_volume *= volume_sign + + # addedtotalsensitivity + sensitivity_density += sensitivity_volume + + logging.info(f" 📊 volume constraintactivated: ratio={volume_ratio:.3f}, outside the tolerance range{excess*100:.1f}%, " + f"{'penalize' if volume_sign > 0 else 'encourage'}, adaptive weight={adaptive_weight:.1e}") + else: + # within the tolerance range, penalize + logging.info(f" 📊 volumewithin the tolerance range: ratio={volume_ratio:.3f} (tolerance±{tolerance*100:.0f}%)") + + # : sensitivity + sens_min = sensitivity_density.min().item() + sens_max = sensitivity_density.max().item() + sens_neg_ratio = (sensitivity_density < 0).float().mean().item() + logging.info(f" sensitivity: norm={torch.norm(sensitivity_density).item():.2e}, " + f"range=[{sens_min:.2e}, {sens_max:.2e}], negative-value ratio={sens_neg_ratio:.1%}") + logging.info(f" → negative sensitivity indicates'occcompliance' (expectedstress concentrationregion should be negative) ") + + # VJPBackpropagationphysicssensitivitylatents + self.backward_step(sensitivity_density) + + # 🔧 Key: checkscalephysics gradient (Lagrange) + if self.latents.grad is not None: + phys_grad_norm_raw = torch.norm(self.latents.grad).item() + + if torch.isnan(self.latents.grad).any() or torch.isinf(self.latents.grad).any(): + logging.error(f"Step {step}: physics gradient contains NaN or Inf!") + logging.error(f" sensitivity_density: norm={sens_norm:.2e}") + logging.error(f" compliance: {compliance.item():.2e}") + # gradient, skipphysicsoptimization + self.latents.grad = None + return (compliance_loss.item(), 0.0, compliance_loss.item()) + + # 🔑 : physics gradientLagrange! + # thiscomplianceautomaticphysics gradientweight + # lagrange → physics gradient → lowercompliance + # lagrange → physics gradient → shape + + # Save scalephysics gradient () + phys_grad_unscaled = self.latents.grad.clone() + + self.latents.grad *= lagrange + phys_grad_norm_scaled = torch.norm(self.latents.grad).item() + + logging.info(f" physics gradient: norm={phys_grad_norm_raw:.4e} → {phys_grad_norm_scaled:.4e} (×λ={lagrange:.2f})") + else: + phys_grad_norm_scaled = 0.0 + + except Exception as e: + logging.error(f"FEM solvefailed: {e}") + import traceback + traceback.print_exc() + return (0.0, 0.0, 0.0) + + # ==================== 6. SDSshapeloss (with CFG) ==================== + t = self.config.sds_timestep + target_z0, _, _ = self._get_target_z0(step) + + # 🔧 Key: target_z0 Yesback""latent + # : z_0 = z_t + t * v + # + # : Hunyuan3D velocity Yes v = z_0 - ε (data) + # Forward: z_t = (1-t)*z_0 + t*ε + # Inverse: z_0 = z_t + t*v = (1-t)*z_0 + t*ε + t*(z_0-ε) = z_0 ✅ + # 🔧 : target_z0 original latents (ifvelocity) + # if, velocity , target_z0 + with torch.no_grad(): + deviation = torch.norm(target_z0 - self.latents).item() + latents_norm = torch.norm(self.latents).item() + relative_deviation = deviation / (latents_norm + 1e-8) + + if relative_deviation > 0.5: # if50% + logging.warning(f" ⚠️ target_z0 deviation is too large: {relative_deviation:.1%} " + f"(||target_z_0 - latents||={deviation:.3e}, ||latents||={latents_norm:.3e})") + logging.warning(f" thismaySave target meshshape is abnormal") + + sds_gradient = self.latents - target_z0.detach() + sds_loss = torch.mean(sds_gradient ** 2) / 2 + + # 🔍 10 stepsSave target_z0mesh (SDS) + if step % 10 == 0: + try: + # checktarget_z0YesNoabnormal values + with torch.no_grad(): + target_norm = torch.norm(target_z0).item() + target_max = torch.abs(target_z0).max().item() + target_has_nan = torch.isnan(target_z0).any().item() + target_has_inf = torch.isinf(target_z0).any().item() + + # target_z0Save + if (not target_has_nan and not target_has_inf and + target_max < 100.0 and relative_deviation < 1.0): + # 🔧 Key: target_z0 detach, gradient + target_z0_clean = target_z0.detach().clone() + + # 📊 : target_z0 statisticsinformation + logging.info(f" 📊 target_z0 statistics:") + logging.info(f" - shape: {target_z0_clean.shape}") + logging.info(f" - range: [{target_z0_clean.min():.3e}, {target_z0_clean.max():.3e}]") + logging.info(f" - mean: {target_z0_clean.mean():.3e}, Std: {target_z0_clean.std():.3e}") + logging.info(f" - deviation from latents: {relative_deviation:.1%}") + + target_mesh = self.latents_to_mesh(target_z0_clean, octree_res=128) + if target_mesh is not None: + target_mesh_dir = os.path.join( + self.config.out_folder if hasattr(self.config, 'out_folder') + else "results/hunyuan_meshes", + "target_z0_meshes" + ) + os.makedirs(target_mesh_dir, exist_ok=True) + target_mesh_path = os.path.join(target_mesh_dir, f"target_z0_step_{step:04d}.obj") + target_mesh.export(target_mesh_path) + logging.info(f" 💾 Save target_z0 mesh (||z||={target_norm:.2e}): {target_mesh_path}") + else: + logging.debug(f" skipSave target_z0: marching cubesno surface found") + else: + logging.warning(f" ⚠️ skipSave target_z0: containsabnormal values " + f"(nan={target_has_nan}, inf={target_has_inf}, max={target_max:.2e})") + except (ValueError, RuntimeError) as e: + # ValueError and RuntimeError (marching cubes Error) + error_msg = str(e) + if "Surface level must be within volume data range" in error_msg or "No surface found" in error_msg: + logging.debug(f" skipSave target_z0: SDFvalueoutside the valid range or has no surface") + else: + logging.warning(f" Save target_z0 meshfailed: {type(e).__name__}: {error_msg[:100]}") + except Exception as e: + # Catch all other exceptions + logging.warning(f" Save target_z0 meshfailed: {type(e).__name__}: {str(e)[:100]}") + + # 🔧🔧🔧 Key: fully disabledSDS, use onlyphysicsoptimization + # : SDS gradientvalue (~2.6) , weight (0.0001) , physics gradient (~0.02) + # : physicsoptimization, physicsoptimizationbackSDS + use_sds_this_step = False # ← force disabled! + + # 🔧 computationfront stepsdynamicSDS weight (sds_weight_startgrowthsds_weight_end) + current_sds_weight = self.get_current_sds_weight(step) + + if not use_sds_this_step: + # skipSDS gradient, use onlyphysics gradient + logging.info(f" 🚫 SDS fully disabled (physicsoptimizationmode) ") + # addedSDS gradient, computationloss + weighted_sds = 0.0 # SDSdoes not participate in optimization for this step + sds_grad_norm = 0.0 + else: + logging.debug(f" ✅ useSDS gradient (weight={current_sds_weight:.4f})") + + # SDS gradientaddedlatents.grad + sds_gradient_scaled = current_sds_weight * sds_gradient + + # 🔧 checkSDS gradientYesNo + if torch.isnan(sds_gradient_scaled).any() or torch.isinf(sds_gradient_scaled).any(): + logging.error(f"Step {step}: SDS gradient contains NaN or Inf!") + logging.error(f" sds_weight={current_sds_weight} (dynamic)") + logging.error(f" sds_gradient range=[{sds_gradient.min():.2e}, {sds_gradient.max():.2e}]") + # skipSDS gradient, use onlyphysics gradient + weighted_sds = 0.0 + sds_grad_norm = 0.0 + if self.latents.grad is None: + logging.error(" no physics gradient, unable to optimize") + return (compliance_loss.item(), sds_loss.item(), total_loss.item()) + else: + sds_grad_norm = torch.norm(sds_gradient_scaled).item() + weighted_sds = current_sds_weight * sds_loss + + # 🔍 Keycheck: SDS gradientYesNotoo large (physics gradient) + if self.latents.grad is not None: + phys_grad_norm_current = torch.norm(self.latents.grad).item() + sds_phys_ratio = sds_grad_norm / (phys_grad_norm_current + 1e-10) + + if sds_phys_ratio > 100.0: + logging.error(f" ❌ serious issue: SDS gradienttoo large!") + logging.error(f" SDS gradient / physics gradient = {sds_phys_ratio:.1f}x") + logging.error(f" SDScompletely overwhelms physics optimization, suggestion: ") + logging.error(f" 1. lowersds_weight_end: {self.config.sds_weight_end} → {self.config.sds_weight_end/100:.2f}") + logging.error(f" 2. usephysicsoptimization (sds_weight=0) ") + elif sds_phys_ratio > 10.0: + logging.warning(f" ⚠️ SDS gradient is relatively large (SDS/physics={sds_phys_ratio:.1f}x)") + logging.warning(f" consider lowering sds_weight_end {self.config.sds_weight_end/10:.2f}") + + # SDS gradient, addedtotal gradient + if self.latents.grad is None: + self.latents.grad = sds_gradient_scaled + logging.info(f" SDS gradient: norm={sds_grad_norm:.4e} (no physics gradient)") + else: + # gradient mergefrontinformation + phys_grad_current = torch.norm(self.latents.grad).item() + logging.info(f" SDS gradient: norm={sds_grad_norm:.4e}") + + # 🔍 : checkphysics gradientandSDS gradient + cos_angle = (phys_grad_unscaled * sds_gradient_scaled).sum() / ( + torch.norm(phys_grad_unscaled) * torch.norm(sds_gradient_scaled) + 1e-10 + ) + angle_deg = torch.acos(torch.clamp(cos_angle, -1, 1)) * 180 / 3.14159 + direction = "same direction✅" if angle_deg < 90 else "opposite direction⚠️" + + logging.info(f" gradient direction: physics vs SDS = {angle_deg:.1f}° ({direction})") + logging.info(f" gradient merge: physics={phys_grad_current:.4e} + SDS={sds_grad_norm:.4e}") + + self.latents.grad += sds_gradient_scaled + + # ==================== 7. loss ==================== + # computationbackloss + weighted_compliance = lagrange * compliance_loss + # weighted_sds already up use_sds_this_step (skip0, use current_sds_weight * sds_loss) + total_loss = weighted_compliance + weighted_sds + + # backloss + if use_sds_this_step: + logging.info(f" 📊 weighted loss: Compliance={weighted_compliance:.4e} (×λ={lagrange:.2f}), " + f"SDS={weighted_sds:.4e} (×w={current_sds_weight:.4f}↑), Total={total_loss:.4e}") + else: + logging.info(f" 📊 weighted loss: Compliance={weighted_compliance:.4e} (×λ={lagrange:.2f}), " + f"SDS=0.00e+00 (fully disabled), Total={total_loss:.4e}") + + # checkfinalgradient + if self.latents.grad is not None: + grad_norm = torch.norm(self.latents.grad).item() + + # logging: gradient composition + logging.info(f" total gradient: norm={grad_norm:.4e}") + + if torch.isnan(self.latents.grad).any() or torch.isinf(self.latents.grad).any(): + logging.error(f"❌ the final gradient contains NaN or Inf!skip this steps") + return (compliance_loss.item(), sds_loss.item(), total_loss.item()) + + # dynamicgradient clipping: λ, gradient (physicsconstraint) + # + # ✅ : upper bound, lossgradientinformation + # + # issue: max_grad_norm=260, gradient=3300, 97%! + # : upper bound1000-2000, optimizerhandle + # + base_max_grad = 1000.0 # 2001000 + lagrange_bonus = min(lagrange * 10.0, 1000.0) # ×3×10 + max_grad_norm = base_max_grad + lagrange_bonus # λ=20, max=1200; λ=100, max=2000 + + # 🔍 : checkYesNo + if grad_norm > max_grad_norm: + clip_factor = max_grad_norm / grad_norm + clip_loss_percent = (1 - clip_factor) * 100 + self.latents.grad = self.latents.grad * clip_factor + + # warning: if>50%gradient, mayissue + if clip_loss_percent > 50: + logging.warning(f" ⚠️ gradient clipping loses too much information: {grad_norm:.4e} -> {max_grad_norm:.1f} " + f"(loss{clip_loss_percent:.1f}%gradient)") + else: + logging.info(f" ✂️ totalgradient clipping: {grad_norm:.4e} -> {max_grad_norm:.1f} " + f"(×{clip_factor:.3f}, λ={lagrange:.1f})") + else: + logging.info(f" ✅ total gradient not clipped: {grad_norm:.4e} (max={max_grad_norm:.1f}, λ={lagrange:.1f})") + else: + logging.error(f"❌ no gradients available; cannot optimize") + return (compliance_loss.item(), sds_loss.item(), total_loss.item()) + + # 🔍 : Save updatefrontlatents + old_latents = self.latents.data.clone() + + # updateparameters + self.optimizer.step() + + # 🔍 : checklatentsYesNo + with torch.no_grad(): + latents_change = torch.norm(self.latents.data - old_latents).item() + latents_change_percent = (latents_change / (torch.norm(old_latents).item() + 1e-10)) * 100 + max_latents_change = torch.abs(self.latents.data - old_latents).max().item() + + # checkSDFYesNo + if hasattr(self, 'nodes') and self.nodes is not None: + try: + # computationupdatefrontbackSDF change + old_sdf = self.get_field(self.nodes[:100], old_latents) # 100 + new_sdf = self.get_field(self.nodes[:100], self.latents) + sdf_change = torch.norm(new_sdf - old_sdf).item() + sdf_max_change = torch.abs(new_sdf - old_sdf).max().item(); + + logging.info(f" 🔍 Latentschange: L2={latents_change:.4e} ({latents_change_percent:.3f}%), " + f"max={max_latents_change:.4e}") + logging.info(f" 🔍 SDF change: L2={sdf_change:.4e}, max={sdf_max_change:.4e}") + + if latents_change < 1e-6: + logging.warning(f" ⚠️ latents almost did not change!the learning rate may be too small or the gradient may be too weak") + if sdf_change < 1e-4: + logging.warning(f" ⚠️ SDFalmost no change!Meshthere will be no obvious change") + except Exception as e: + logging.debug(f" unable to computeSDF change: {e}") + + logging.info(f"🔄 Step {step:3d} | Compliance: {compliance_loss:.2e} (weighted: {weighted_compliance:.2e}), " + f"SDS: {sds_loss:.6e} (weighted: {weighted_sds:.6e}), Total: {total_loss:.2e}, λ={lagrange:.2f}") + logging.info(f" | Latents Δ: {latents_change:.4e} ({latents_change_percent:.3f}%), " + f"max Δ: {max_latents_change:.4e}") + + return (compliance_loss.item(), sds_loss.item(), total_loss.item()) + + + def save_mesh(self, step: int, output_dir: str = "results/hunyuan_meshes", high_quality: bool = False): + """Save frontlatentsmesh + + Args: + step: front steps + output_dir: outputdirectory + high_quality: YesNouse (Resolution) , Trueuse256resolution + """ + os.makedirs(output_dir, exist_ok=True) + + try: + # finalSave use256resolution, Stepuse128resolution + octree_res = 256 if high_quality else 128 + mesh = self.latents_to_mesh(self.latents, octree_res=octree_res) + if mesh is None: + logging.warning(f" ⚠️ warning: Step {step} - Marching cubesno surface found, skipSave ") + return + + # finalSave filterfloating + if high_quality: + mesh = self._filter_floating_components(mesh) + + mesh_path = os.path.join(output_dir, f"step_{step:04d}.obj") + mesh.export(mesh_path) + quality_label = "256resolution" if high_quality else "128resolution" + logging.info(f" 💾 Save mesh ({quality_label}): {mesh_path}") + except Exception as e: + logging.warning(f" ⚠️ warning: Step {step} - Save meshfailed: {e}") + + def _maybe_save_target_z0_mesh(self, target_z0: torch.Tensor, step_id: int, force: bool = False): + """Save target_z0mesh () """ + if (not force) and (step_id % 10 != 0): + return + + with torch.no_grad(): + deviation = torch.norm(target_z0 - self.latents).item() + latents_norm = torch.norm(self.latents).item() + relative_deviation = deviation / (latents_norm + 1e-8) + + if relative_deviation > 0.5: + logging.warning( + f" ⚠️ target_z0 deviation is too large: {relative_deviation:.1%} " + f"(||target_z0 - latents||={deviation:.3e}, ||latents||={latents_norm:.3e})" + ) + logging.warning(f" thismaySave target meshshape is abnormal") + + try: + target_norm = torch.norm(target_z0).item() + target_max = torch.abs(target_z0).max().item() + target_has_nan = torch.isnan(target_z0).any().item() + target_has_inf = torch.isinf(target_z0).any().item() + + # target_z0Save + if (not target_has_nan and not target_has_inf and + target_max < 100.0 and relative_deviation < 1.0): + target_z0_clean = target_z0.detach().clone() + + logging.info(f" 📊 target_z0 statistics:") + logging.info(f" - shape: {target_z0_clean.shape}") + logging.info(f" - range: [{target_z0_clean.min():.3e}, {target_z0_clean.max():.3e}]") + logging.info(f" - mean: {target_z0_clean.mean():.3e}, Std: {target_z0_clean.std():.3e}") + logging.info(f" - deviation from latents: {relative_deviation:.1%}") + + target_mesh = self.latents_to_mesh(target_z0_clean, octree_res=128) + if target_mesh is not None: + target_mesh_dir = os.path.join( + self.config.out_folder if hasattr(self.config, 'out_folder') + else "results/hunyuan_meshes", + "target_z0_meshes" + ) + os.makedirs(target_mesh_dir, exist_ok=True) + target_mesh_path = os.path.join(target_mesh_dir, f"target_z0_step_{step_id:04d}.obj") + target_mesh.export(target_mesh_path) + logging.info(f" 💾 Save target_z0 mesh (||z||={target_norm:.2e}): {target_mesh_path}") + else: + logging.debug(f" skipSave target_z0: marching cubesno surface found") + else: + logging.warning( + f" ⚠️ skipSave target_z0: containsabnormal values " + f"(nan={target_has_nan}, inf={target_has_inf}, max={target_max:.2e})" + ) + except (ValueError, RuntimeError) as e: + error_msg = str(e) + if "Surface level must be within volume data range" in error_msg or "No surface found" in error_msg: + logging.debug(f" skipSave target_z0: SDFvalueoutside the valid range or has no surface") + else: + logging.warning(f" Save target_z0 meshfailed: {type(e).__name__}: {error_msg[:100]}") + except Exception as e: + logging.warning(f" Save target_z0 meshfailed: {type(e).__name__}: {str(e)[:100]}") + + def save_final_target_z0_mesh(self, step_id: int): + """force at the final step toSave target_z0 mesh () """ + try: + if self.target_z0_ema is not None: + target_z0 = self.target_z0_ema.detach().clone() + else: + target_z0, _ = self._computation_target_z0_current(step_id) + self._maybe_save_target_z0_mesh(target_z0, step_id, force=True) + except Exception as e: + logging.warning(f" ⚠️ failed to save the final target_z0: {type(e).__name__}: {str(e)[:100]}") + + def save_deformed_mesh(self, step: int, displacement: torch.Tensor, output_dir: str = None): + """Save FEM solvebackdeformed mesh + + Args: + step: front steps + displacement: FEM solve [num_nodes, 3] + output_dir: outputdirectory, useconfig.out_folder/deformed_meshes + """ + if output_dir is None: + if hasattr(self.config, 'out_folder'): + output_dir = os.path.join(self.config.out_folder, "deformed_meshes") + else: + output_dir = "results/deformed_meshes" + + os.makedirs(output_dir, exist_ok=True) + + try: + # originalnodespositionandbackposition + original_nodes = self.nodes.detach().cpu().numpy() # [num_nodes, 3] + displacement_np = displacement.detach().cpu().numpy() # [num_nodes, 3] + deformed_nodes = original_nodes + displacement_np + + # elements + elements_np = self.elements.detach().cpu().numpy() # [num_elements, 8] + + # Save VTK format (ParaView, contains) + vtk_path = os.path.join(output_dir, f"deformed_step_{step:04d}.vtk") + self._save_hex_mesh_vtk(deformed_nodes, elements_np, displacement_np, vtk_path, step) + + # Save OBJ/PLY (usedecodemesh, ) + decoded_mesh = self.latents_to_mesh(self.latents, octree_res=128) + if decoded_mesh is not None: + disp_vertices = self._sample_displacement_to_vertices( + decoded_mesh.vertices, original_nodes, displacement_np + ) + deformed_vertices = decoded_mesh.vertices + disp_vertices + colors = self._make_displacement_colors(disp_vertices) + + deformed_mesh = trimesh.Trimesh( + vertices=deformed_vertices, + faces=decoded_mesh.faces, + process=False, + ) + deformed_mesh.visual.vertex_colors = colors + + obj_path = os.path.join(output_dir, f"deformed_step_{step:04d}.obj") + ply_path = os.path.join(output_dir, f"deformed_step_{step:04d}.ply") + deformed_mesh.export(obj_path) + deformed_mesh.export(ply_path) + else: + # fallback: usemesh + obj_path = os.path.join(output_dir, f"deformed_step_{step:04d}.obj") + ply_path = os.path.join(output_dir, f"deformed_step_{step:04d}.ply") + self._save_surface_mesh_obj(deformed_nodes, elements_np, obj_path) + self._save_surface_mesh_ply(deformed_nodes, elements_np, displacement_np, ply_path) + + # displacement statistics + disp_mean = np.abs(displacement_np).mean() + disp_max = np.abs(displacement_np).max() + logging.info(f" 💾 saved deformed mesh : VTK={vtk_path.split('/')[-1]}, OBJ={obj_path.split('/')[-1]}, PLY={ply_path.split('/')[-1]}") + logging.debug(f" : mean={disp_mean:.4e}, max={disp_max:.4e}") + + except Exception as e: + logging.warning(f" ⚠️ Save deformed meshfailed (Step {step}): {e}") + + def save_final_deformed_mesh(self, step_id: int): + """force at the final step toSave deformed mesh (re-solveFEM) """ + if not hasattr(self, 'nodes') or not hasattr(self, 'elements'): + logging.warning(" ⚠️ unable to save the finaldeformed mesh: missingnodes/elements") + return + if not hasattr(self, 'forces') or not hasattr(self, 'boundary_mask'): + logging.warning(" ⚠️ unable to save the finaldeformed mesh: missingforces/boundary_mask") + return + + try: + from torchfem.materials import IsotropicElasticity3D + from physiopt.opt.solid_grid import SolidGrid + from physiopt.opt.field import occ_kernel + + with torch.no_grad(): + # update occupancyalignfrontlatents + sdf = self.get_field(self.nodes) + occ = occ_kernel(sdf, self.config.res, self.config.occ_sdf_beta) + self.coarse_occ = occ[self.elements].mean(1) + + if self.config.alpha_min > 0.0: + self.coarse_occ = torch.clamp(self.coarse_occ, self.config.alpha_min) + + vectorized_material = IsotropicElasticity3D( + E=self.config.youngs_modulus, + nu=self.config.poissons_ratio, + rho=self.config.density, + ).vectorize(self.elements.shape[0]) + + vectorized_material.C *= ( + self.coarse_occ[:, None, None] ** self.config.p_exponent + ) + + solid = SolidGrid(self.nodes, self.elements, vectorized_material) + solid.constraints[self.boundary_mask, :] = True + solid.forces = self.forces + + logging.info(" 🧱 final deformed mesh: re-solve the FEM system to save ") + u, _, _, _, _, _ = solid.solve(max_iter=1) + self.save_deformed_mesh(step_id, u) + except Exception as e: + logging.warning(f" ⚠️ final deformed meshSave failed: {type(e).__name__}: {str(e)[:100]}") + + def _save_hex_mesh_vtk(self, nodes: np.ndarray, elements: np.ndarray, + displacement: np.ndarray, filename: str, step: int): + """Save hexahedral meshVTK format""" + num_nodes = nodes.shape[0] + num_elements = elements.shape[0] + + with open(filename, 'w') as f: + f.write("# vtk DataFile Version 3.0\n") + f.write(f"Deformed mesh at step {step}\n") + f.write("ASCII\n") + f.write("DATASET UNSTRUCTURED_GRID\n") + + # node coordinates (back) + f.write(f"\nPOINTS {num_nodes} float\n") + for node in nodes: + f.write(f"{node[0]:.6f} {node[1]:.6f} {node[2]:.6f}\n") + + # + f.write(f"\nCELLS {num_elements} {num_elements * 9}\n") + for elem in elements: + f.write(f"8 {elem[0]} {elem[1]} {elem[2]} {elem[3]} " + f"{elem[4]} {elem[5]} {elem[6]} {elem[7]}\n") + + # (12 = VTK_HEXAHEDRON) + f.write(f"\nCELL_TYPES {num_elements}\n") + for _ in range(num_elements): + f.write("12\n") + + # + f.write(f"\nPOINT_DATA {num_nodes}\n") + f.write("VECTORS displacement float\n") + for disp in displacement: + f.write(f"{disp[0]:.6e} {disp[1]:.6e} {disp[2]:.6e}\n") + + # + f.write("\nSCALARS displacement_magnitude float 1\n") + f.write("LOOKUP_TABLE default\n") + for disp in displacement: + mag = np.linalg.norm(disp) + f.write(f"{mag:.6e}\n") + + def _save_surface_mesh_obj(self, nodes: np.ndarray, elements: np.ndarray, filename: str): + """hexahedral meshSave OBJ""" + # the 6 faces of the hexahedron + hex_faces = [ + [0, 1, 2, 3], [4, 5, 6, 7], # bottom face, top face + [0, 1, 5, 4], [2, 3, 7, 6], # front face, back face + [0, 3, 7, 4], [1, 2, 6, 5], # left face, right face + ] + + # collect surface faces (faces that appear only once) + face_count = {} + for elem in elements: + for face_indices in hex_faces: + face_nodes = tuple(sorted([elem[i] for i in face_indices])) + if face_nodes in face_count: + face_count[face_nodes] += 1 + else: + face_count[face_nodes] = 1 + + # keep only surface faces (appear once) + surface_faces = [face for face, count in face_count.items() if count == 1] + + # Save OBJ + with open(filename, 'w') as f: + f.write("# Deformed mesh surface\n") + for node in nodes: + f.write(f"v {node[0]:.6f} {node[1]:.6f} {node[2]:.6f}\n") + for face in surface_faces: + # OBJ1start + f.write(f"f {face[0]+1} {face[1]+1} {face[2]+1} {face[3]+1}\n") + + def _save_surface_mesh_ply(self, nodes: np.ndarray, elements: np.ndarray, + displacement: np.ndarray, filename: str): + """Save mesh (indicates) """ + # the 6 faces of the hexahedron + hex_faces = [ + [0, 1, 2, 3], [4, 5, 6, 7], # bottom face, top face + [0, 1, 5, 4], [2, 3, 7, 6], # front face, back face + [0, 3, 7, 4], [1, 2, 6, 5], # left face, right face + ] + + # collect surface faces (faces that appear only once) + face_count = {} + for elem in elements: + for face_indices in hex_faces: + face_nodes = tuple(sorted([elem[i] for i in face_indices])) + if face_nodes in face_count: + face_count[face_nodes] += 1 + else: + face_count[face_nodes] = 1 + + # keep only surface faces (appear once) + surface_faces = [face for face, count in face_count.items() if count == 1] + + # (->) + disp_mag = np.linalg.norm(displacement, axis=1) + norm, _, _, _ = self._normalize_displacement_magnitude(disp_mag) + colors = np.stack([norm, np.zeros_like(norm), 1.0 - norm], axis=1) + colors = (colors * 255).astype(np.uint8) + + # Save PLY (support) + with open(filename, 'w') as f: + f.write("ply\nformat ascii 1.0\n") + f.write(f"element vertex {len(nodes)}\n") + f.write("property float x\nproperty float y\nproperty float z\n") + f.write("property uchar red\nproperty uchar green\nproperty uchar blue\n") + f.write(f"element face {len(surface_faces)}\n") + f.write("property list uchar int vertex_indices\n") + f.write("end_header\n") + + for node, color in zip(nodes, colors): + f.write(f"{node[0]:.6f} {node[1]:.6f} {node[2]:.6f} " + f"{int(color[0])} {int(color[1])} {int(color[2])}\n") + + for face in surface_faces: + f.write(f"4 {face[0]} {face[1]} {face[2]} {face[3]}\n") + + def _save_force_visualization(self, seat_nodes_mask: torch.Tensor, total_force: np.ndarray): + """Save loaded voxeldata, visualization checks + + Save three formats: + 1. NumPy format (.npz) : contains all nodes and force information + 2. OBJ format: loaded nodespoint cloud (view in Meshlab) + 3. VTK format (optional) : for ParaView visualization + + Args: + seat_nodes_mask: seat nodesmask [num_nodes] + total_force: total force vector [3] + """ + if not hasattr(self.config, 'out_folder'): + logging.warning(" out_folder is not set, skipSave loaded voxel") + return + + # createforce_visualizationsubdirectory + vis_dir = os.path.join(self.config.out_folder, "force_visualization") + os.makedirs(vis_dir, exist_ok=True) + + # ==================== 1. Save NumPy format () ==================== + all_nodes_cpu = self.nodes.cpu().numpy() + all_forces_cpu = self.forces.cpu().numpy() + seat_mask_cpu = seat_nodes_mask.cpu().numpy() + + # extract loaded nodes + seat_nodes = all_nodes_cpu[seat_mask_cpu] + seat_forces = all_forces_cpu[seat_mask_cpu] + + npz_path = os.path.join(vis_dir, "force_nodes.npz") + np.savez( + npz_path, + # all node information + all_nodes=all_nodes_cpu, + all_forces=all_forces_cpu, + # loaded node information + seat_nodes=seat_nodes, + seat_forces=seat_forces, + seat_mask=seat_mask_cpu, + # boundary node information + boundary_mask=self.boundary_mask.cpu().numpy() if hasattr(self, 'boundary_mask') else None, + # metadata + total_force=total_force, + num_seat_nodes=len(seat_nodes), + num_all_nodes=len(all_nodes_cpu), + ) + logging.info(f" 💾 Save load data (NumPy format) : {npz_path}") + + # ==================== 2. Save OBJ format (point cloud, Meshlab) ==================== + # 2a. loaded nodes (red point cloud) + seat_obj_path = os.path.join(vis_dir, "seat_nodes.obj") + with open(seat_obj_path, 'w') as f: + f.write("# Seat nodes (loaded area)\n") + f.write(f"# Total: {len(seat_nodes)} nodes\n") + f.write(f"# Force per node: {seat_forces[0] if len(seat_forces) > 0 else [0,0,0]}\n") + for node in seat_nodes: + f.write(f"v {node[0]:.6f} {node[1]:.6f} {node[2]:.6f}\n") + logging.info(f" 💾 Save seat nodes (OBJpoint cloud) : {seat_obj_path}") + + # 2b. boundary nodes (blue point cloud) + if hasattr(self, 'boundary_mask'): + boundary_nodes = all_nodes_cpu[self.boundary_mask.cpu().numpy()] + boundary_obj_path = os.path.join(vis_dir, "boundary_nodes.obj") + with open(boundary_obj_path, 'w') as f: + f.write("# Boundary nodes (fixed area)\n") + f.write(f"# Total: {len(boundary_nodes)} nodes\n") + for node in boundary_nodes: + f.write(f"v {node[0]:.6f} {node[1]:.6f} {node[2]:.6f}\n") + logging.info(f" 💾 Save boundary nodes (OBJpoint cloud) : {boundary_obj_path}") + + # 2c. all nodes (gray point cloud, ) + all_obj_path = os.path.join(vis_dir, "all_nodes.obj") + with open(all_obj_path, 'w') as f: + f.write("# All nodes\n") + f.write(f"# Total: {len(all_nodes_cpu)} nodes\n") + for node in all_nodes_cpu: + f.write(f"v {node[0]:.6f} {node[1]:.6f} {node[2]:.6f}\n") + logging.info(f" 💾 Save all nodes (OBJpoint cloud) : {all_obj_path}") + + # ==================== 3. Save VTK format (ParaView, ) ==================== + try: + vtk_path = os.path.join(vis_dir, "force_field.vtk") + with open(vtk_path, 'w') as f: + # VTK Header + f.write("# vtk DataFile Version 3.0\n") + f.write("Force field visualization\n") + f.write("ASCII\n") + f.write("DATASET UNSTRUCTURED_GRID\n") + + # Points + f.write(f"POINTS {len(all_nodes_cpu)} float\n") + for node in all_nodes_cpu: + f.write(f"{node[0]:.6f} {node[1]:.6f} {node[2]:.6f}\n") + + # Cells (vertices) + f.write(f"\nCELLS {len(all_nodes_cpu)} {len(all_nodes_cpu)*2}\n") + for i in range(len(all_nodes_cpu)): + f.write(f"1 {i}\n") + + # Cell types (1 = vertex) + f.write(f"\nCELL_TYPES {len(all_nodes_cpu)}\n") + for _ in range(len(all_nodes_cpu)): + f.write("1\n") + + # Point data (force vectors) + f.write(f"\nPOINT_DATA {len(all_nodes_cpu)}\n") + f.write("VECTORS force float\n") + for force in all_forces_cpu: + f.write(f"{force[0]:.6e} {force[1]:.6e} {force[2]:.6e}\n") + + # Scalar field: force magnitude + f.write("\nSCALARS force_magnitude float 1\n") + f.write("LOOKUP_TABLE default\n") + for force in all_forces_cpu: + mag = np.linalg.norm(force) + f.write(f"{mag:.6e}\n") + + # Scalar field: is_seat (0 or 1) + f.write("\nSCALARS is_seat int 1\n") + f.write("LOOKUP_TABLE default\n") + for is_seat in seat_mask_cpu: + f.write(f"{int(is_seat)}\n") + + logging.info(f" 💾 Save force field (VTK format, ParaView) : {vtk_path}") + except Exception as e: + logging.warning(f" ⚠️ Save VTK formatfailed: {e}") + + # ==================== 4. generate a visualization script (Python) ==================== + vis_script_path = os.path.join(vis_dir, "visualize_forces.py") + with open(vis_script_path, 'w') as f: + f.write("""#!/usr/bin/env python3 +\"""visualize force voxel data + +Usage: + python visualize_forces.py + +Required packages: + pip install numpy matplotlib + +\""" +import numpy as np +import matplotlib.pyplot as plt +from mpl_toolkits.mplot3d import Axes3D + +# load data +data = np.load('force_nodes.npz') +all_nodes = data['all_nodes'] +seat_nodes = data['seat_nodes'] +seat_forces = data['seat_forces'] +total_force = data['total_force'] + +# create a 3D figure +fig = plt.figure(figsize=(15, 5)) + +# subplot1: all nodes (gray) + loaded nodes (red) +ax1 = fig.add_subplot(131, projection='3d') +ax1.scatter(all_nodes[:, 0], all_nodes[:, 1], all_nodes[:, 2], + c='lightgray', s=0.5, alpha=0.3, label='All nodes') +ax1.scatter(seat_nodes[:, 0], seat_nodes[:, 1], seat_nodes[:, 2], + c='red', s=5, alpha=1.0, label='Seat nodes (loaded)') +ax1.set_xlabel('X') +ax1.set_ylabel('Y (up)') +ax1.set_zlabel('Z') +ax1.set_title(f'Loaded Nodes\\n({len(seat_nodes)}/{len(all_nodes)} nodes)') +ax1.legend() + +# subplot2: loaded nodesYdistribution (height) +ax2 = fig.add_subplot(132) +y_coords = seat_nodes[:, 1] +ax2.hist(y_coords, bins=30, color='red', alpha=0.7, edgecolor='black') +ax2.axvline(y_coords.min(), color='blue', linestyle='--', label=f'Y_min={y_coords.min():.3f}') +ax2.axvline(y_coords.max(), color='green', linestyle='--', label=f'Y_max={y_coords.max():.3f}') +ax2.set_xlabel('Y coordinate (height)') +ax2.set_ylabel('Number of nodes') +ax2.set_title('Seat Node Y Distribution') +ax2.legend() +ax2.grid(True, alpha=0.3) + +# subplot3: force vectorsXZdistribution (top view) +ax3 = fig.add_subplot(133) +ax3.scatter(seat_nodes[:, 0], seat_nodes[:, 2], c='red', s=10, alpha=0.5) +# plotforce vectors (use only a subset, to avoid overcrowding) +step = max(1, len(seat_nodes) // 50) +for i in range(0, len(seat_nodes), step): + node = seat_nodes[i] + force = seat_forces[i] + # scaleforce vectorsfor visualization + scale = 0.01 + ax3.arrow(node[0], node[2], force[0]*scale, force[2]*scale, + head_width=0.02, head_length=0.01, fc='blue', ec='blue', alpha=0.7) +ax3.set_xlabel('X') +ax3.set_ylabel('Z') +ax3.set_title(f'Top View (XZ plane)\\nForce: {total_force}') +ax3.axis('equal') +ax3.grid(True, alpha=0.3) + +plt.tight_layout() +plt.savefig('force_visualization.png', dpi=150, bbox_inches='tight') +logging.info("✅ image saved : force_visualization.png") +plt.show() + +# print statistics +logging.info("\\n" + "="*60) +logging.info("force voxel statistics") +logging.info("="*60) +logging.info(f"total node count: {len(all_nodes)}") +logging.info(f"loaded node count: {len(seat_nodes)} ({len(seat_nodes)/len(all_nodes)*100:.1f}%)") +logging.info(f"total: {total_force}") +logging.info(f"per nodeaverage force per node: {seat_forces.mean(axis=0)}") +logging.info(f"\\nY-coordinate range:") +logging.info(f" - min: {y_coords.min():.3f}") +logging.info(f" - max: {y_coords.max():.3f}") +logging.info(f" - mean: {y_coords.mean():.3f}") +logging.info(f" - height span: {y_coords.max() - y_coords.min():.3f}") +logging.info("="*60) +""") + os.chmod(vis_script_path, 0o755) # add execute permission + logging.info(f" 💾 Save visualization script: {vis_script_path}") + + # ==================== 5. generate a README document ==================== + readme_path = os.path.join(vis_dir, "README.md") + with open(readme_path, 'w') as f: + f.write(f"""# loadedVoxeldata + +generated at: {np.datetime64('now')} + +## data statistics + +- **total node count**: {len(all_nodes_cpu)} +- **loaded node count**: {len(seat_nodes)} ({len(seat_nodes)/len(all_nodes_cpu)*100:.1f}%) +- **total**: {total_force} +- **force per node**: {seat_forces[0] if len(seat_forces) > 0 else [0,0,0]} + +## file descriptions + +### 1. NumPy format (recommended for data analysis) + +- `force_nodes.npz`: contains all data + - `all_nodes`: all node coordinates [{len(all_nodes_cpu)}, 3] + - `all_forces`: forces on all nodes [{len(all_nodes_cpu)}, 3] + - `seat_nodes`: loaded node coordinates [{len(seat_nodes)}, 3] + - `seat_forces`: forces on loaded nodes [{len(seat_nodes)}, 3] + - `seat_mask`: seat-node mask [{len(all_nodes_cpu)}] + - `boundary_mask`: boundary-node mask [{len(all_nodes_cpu)}] + +**Example**: +```python +import numpy as np +data = np.load('force_nodes.npz') +seat_nodes = data['seat_nodes'] +print(f"seat-node count: {{len(seat_nodes)}}") +``` + +### 2. OBJ format (recommended for quick viewing) + +- `seat_nodes.obj`: loaded nodes (red point cloud) +- `boundary_nodes.obj`: boundary nodes (blue point cloud) +- `all_nodes.obj`: all nodes (gray point cloud) + +**Usage**: +1. useMeshlab: `meshlab seat_nodes.obj` +2. useBlenderimportOBJfile +3. canloadOBJfileperform + +### 3. VTK format (recommended for professional visualization) + +- `force_field.vtk`: force fielddata (with a vector field) + +**Usage**: +1. open with ParaView: `paraview force_field.vtk` +2. In ParaView: + - "Glyph" visualize force vectors + - use "force_magnitude" color by force magnitude + - use "is_seat" use a filter to show the loaded region + +### 4. visualization script + +- `visualize_forces.py`: Python visualization script + +**Usage**: +```bash +python visualize_forces.py +``` +""") + logging.info(f" 💾 Save README document: {readme_path}") + + # totalinformation + logging.info(f" ✅ force voxel data saved successfully!") + logging.info(f" - view directory: {vis_dir}") + logging.info(f" - quick visualization: cd {vis_dir} && python visualize_forces.py") + logging.info(f" - view in Meshlab: meshlab {os.path.join(vis_dir, 'seat_nodes.obj')}") + + +def load_hunyuan_models(model_path: str = "tencent/Hunyuan3D-2.1", + subfolder: str = "hunyuan3d-shapegen", + use_safetensors: bool = True): + """loading Hunyuan3Dmodel (VAE, Flow ModelandScheduler) + + Args: + model_path: modelpath (huggingfacemodelIDpath) + subfolder: subfolder + use_safetensors: YesNousesafetensorsformat + + Returns: + (vae, flow_model, scheduler): VAE, Flow Matching modelandScheduler + """ + logging.info(f"🔧 loading Hunyuan3D-2.1model...") + logging.info(f" modelpath: {model_path}") + logging.info(f" subfolder: {subfolder}") + logging.info(f" modelformat: {'safetensors' if use_safetensors else 'checkpoint'}") + + try: + pipeline = Hunyuan3DDiTFlowMatchingPipeline.from_pretrained( + model_path, + subfolder=subfolder, + torch_dtype=torch.float16, + use_safetensors=use_safetensors + ) + + if pipeline is None: + raise ValueError("pipeline loading failed and returned None") + + logging.info(" ✅ pipeline loaded successfully") + + pipeline.to('cuda') + logging.info(" ✅ modelmoved to CUDA (dtype: fp16)") + + vae = pipeline.vae + flow_model = pipeline.model + scheduler = pipeline.scheduler + + return vae, flow_model, scheduler + + except Exception as e: + logging.error(f"\n❌ modelloadfailed: {e}") + logging.error(f"\nPossible fixes:") + logging.error(f"1. make sure Hunyuan3D is installed-2.1: cd Hunyuan3D-2.1 && pip install -e .") + logging.error(f"2. check network connectivity to huggingface.co") + logging.error(f"3. or download manually: git clone https://huggingface.co/tencent/Hunyuan3D-2") + import traceback + traceback.print_exc() + sys.exit(1) + +def main(): + """Main function: parse CLI arguments and run optimization""" + import argparse + + parser = argparse.ArgumentParser(description="Hunyuan3D physics optimization + shape-prior optimization") + + # required arguments + parser.add_argument("--latents", type=str, required=True, + help="Input latents file path (.pt)") + parser.add_argument("--out_folder", type=str, default="../out/hunyuan_opt", + help="Output folder path") + + # modelparameters + parser.add_argument("--model_path", type=str, default="tencent/Hunyuan3D-2.1", + help="Model path (using v2.1)") + parser.add_argument("--subfolder", type=str, default="hunyuan3d-dit-v2-1", + help="Model subfolder") + parser.add_argument("--use_safetensors", action="store_true", + help="Use safetensors format (default: ckpt)") + + # Physical-simulation parameters + parser.add_argument("--use_physics", action="store_true", + help="Enable physics-constrained optimization") + parser.add_argument("--res", type=int, default=16, + help="Voxel resolution (16/32/64)") + parser.add_argument("--youngs_modulus_scale", type=float, default=2.0, + help="Final Young's modulus multiplier (default 2x after the last projection)") + parser.add_argument("--compliance_threshold", type=float, default=None, + help="Target compliance threshold (None = automatic)") + parser.add_argument("--compliance_threshold_ratio", type=float, default=0.3, + help="Automatic threshold ratio (threshold = initial value × ratio)") + + # Optimization parameters + parser.add_argument("--num_steps", type=int, default=300, + help="Number of optimization steps (pure SDS only; in physics mode it becomes outer_cycles * phys_steps_per_cycle automatically)") + parser.add_argument("--outer_cycles", type=int, default=100, + help="Number of outer cycles (each cycle = physics optimization + projection)") + parser.add_argument("--phys_steps_per_cycle", type=int, default=5, + help="Number of physics-optimization steps per outer cycle") + parser.add_argument("--lr", type=float, default=5e-3, + help="Learning rate (increase to 0.005 to help the mesh thicken faster) ") + parser.add_argument("--lagrange_max", type=float, default=10.0, + help="Maximum Lagrange multiplier (recommended: 5-20)") + parser.add_argument("--alm_rho_init", type=float, default=1.0, + help="ALM rhoinitial value") + parser.add_argument("--alm_rho_max", type=float, default=1000.0, + help="ALM rhoMax") + parser.add_argument("--alm_rho_increase_factor", type=float, default=2.0, + help="ALM rhogrowth factor") + parser.add_argument("--alm_rho_increase_patience", type=int, default=5, + help="ALM rhonumber of consecutive violation steps required before increasing") + parser.add_argument("--alm_scale_guard_ratio", type=float, default=0.95, + help="ALMscaling guard ratio(<=1), control the upper bound of the physics-gradient target=this ratio x clipping-threshold value") + parser.add_argument("--grad_clip_enabled", action="store_true", + help="Enable gradient clipping (disabled by default; otherwise only NaN/Inf checks are kept)") + parser.add_argument("--use_sgd", action="store_true", + help="Use SGD instead of Adam") + parser.add_argument("--force_config", type=str, default=None, + help="Path to the external-force JSON config (generated by the web UI)") + parser.add_argument("--force", type=float, nargs=3, action="append", default=None, + help="External force vector [fx fy fz] (N, Y-up coordinates; can be specified multiple times)") + parser.add_argument("--global_loading", action="store_true", + help="Use global uniform loading (disable local loading)") + parser.add_argument("--force_region_mode", type=str, default="top_percent", + choices=["top_percent", "height_ratio", "bbox"], + help="How to choose the local loading region") + parser.add_argument("--force_top_percent", type=float, default=0.05, + help="top_percent mode: select the highest-Y fraction") + parser.add_argument("--force_bbox", type=float, nargs=6, default=None, + help="bbox mode: x_min x_max y_min y_max z_min z_max (absolute coordinates)") + parser.add_argument("--force_bbox_ratio", type=float, nargs=6, default=None, + help="bbox mode (0-1): bbox relative to the node bounds") + parser.add_argument("--seat_height_min_ratio", type=float, default=0.3, + help="height_ratio mode: lower seat boundary (0-1)") + parser.add_argument("--seat_height_max_ratio", type=float, default=0.5, + help="height_ratio mode: upper seat boundary (0-1)") + + # SDS parameters + parser.add_argument("--sds_weight", type=float, default=1.0, + help="SDS gradient weight (deprecated; use sds_weight_start and sds_weight_end instead)") + parser.add_argument("--sds_weight_start", type=float, default=10.0, + help="Initial SDS weight (linearly increased; 0.0001 is recommended to avoid disturbing physics optimization)") + parser.add_argument("--sds_weight_end", type=float, default=10.0, + help="Final SDS weight (linearly increased; 0.001 is recommended, about 1/10 of the physics gradient)") + parser.add_argument("--sds_timestep", type=float, default=0.1, + help="SDS timestep (recommended: 0.05-0.2)") + parser.add_argument("--sds_target_z0_ema_beta", type=float, default=0.9, + help="target_z0 EMA smoothing factor (larger means smoother)") + parser.add_argument("--deformed_mesh_interval", type=int, default=10, + help="Interval for saving deformed meshes (steps)") + parser.add_argument("--deformed_mesh_disp_min", type=float, default=0.0, + help="Minimum displacement for deformed-mesh color mapping (default 0.0)") + parser.add_argument("--deformed_mesh_disp_max", type=float, default=0.2, + help="Maximum displacement for deformed-mesh color mapping (<=0 enables per-step auto scaling)") + parser.add_argument("--guidance_scale", type=float, default=7.5, + help="CFG guidance scale (standard value: 7.5; larger means stronger image conditioning)") + parser.add_argument("--sds_projection_max_rel", type=float, default=0.0, + help="Maximum relative target_z0 projection deviation (0 = unlimited)") + parser.add_argument("--sds_use_uncond", action="store_true", + help="Use the unconditional branch (only takes effect when guidance_scale <= 1)") + + # topology control + parser.add_argument("--keep_all_components", action="store_true", + help="Keep all connected components (to avoid disappearing chair legs)") + parser.add_argument("--re_extract_interval", type=int, default=1, + help="Solid re-extraction interval (0 = disabled)") + + args = parser.parse_args() + + def _normalize_force_vectors(value): + if value is None: + return None + if isinstance(value, (list, tuple)) and len(value) > 0: + if isinstance(value[0], (list, tuple)): + candidates = value + else: + candidates = [value] + else: + return None + normalized = [] + for vec in candidates: + if not isinstance(vec, (list, tuple)) or len(vec) != 3: + continue + try: + normalized.append([float(v) for v in vec]) + except Exception: + continue + return normalized if normalized else None + + def _normalize_force_entry(entry): + if not isinstance(entry, dict): + return None + forces = _normalize_force_vectors(entry.get("forces")) + if forces is None: + forces = _normalize_force_vectors(entry.get("force")) + if forces is None: + return None + out = dict(entry) + if len(forces) > 1: + out["forces"] = forces + out["force"] = [float(sum(v[i] for v in forces)) for i in range(3)] + else: + out["force"] = forces[0] + out.pop("forces", None) + if "force_region_mode" in out: + out["force_region_mode"] = str(out["force_region_mode"]) + if "global_loading" in out: + out["global_loading"] = bool(out["global_loading"]) + if "force_top_percent" in out: + out["force_top_percent"] = float(out["force_top_percent"]) + if "seat_height_min_ratio" in out: + out["seat_height_min_ratio"] = float(out["seat_height_min_ratio"]) + if "seat_height_max_ratio" in out: + out["seat_height_max_ratio"] = float(out["seat_height_max_ratio"]) + if "force_bbox" in out and isinstance(out["force_bbox"], (list, tuple)) and len(out["force_bbox"]) == 6: + out["force_bbox"] = [float(v) for v in out["force_bbox"]] + elif "force_bbox" in out: + out.pop("force_bbox", None) + if "force_bbox_ratio" in out and isinstance(out["force_bbox_ratio"], (list, tuple)) and len(out["force_bbox_ratio"]) == 6: + out["force_bbox_ratio"] = [float(v) for v in out["force_bbox_ratio"]] + elif "force_bbox_ratio" in out: + out.pop("force_bbox_ratio", None) + return out + + # JSONloadexternal forceconfig (webexported from the web UI) + force_config_loaded = False + force_config_error = None + force_entries = None + if args.force_config: + raw_force_config = args.force_config + candidates = [] + if os.path.isabs(raw_force_config): + candidates.append(raw_force_config) + else: + candidates.append(raw_force_config) + script_dir = os.path.dirname(os.path.abspath(__file__)) + candidates.append(os.path.join(script_dir, raw_force_config)) + candidates.append(os.path.join(os.path.dirname(script_dir), raw_force_config)) + force_config_path = next((p for p in candidates if os.path.exists(p)), None) + if force_config_path is None: + force_config_error = f"Path does not exist; tried: {candidates}" + else: + args.force_config = force_config_path + try: + with open(force_config_path, "r") as f: + force_cfg = json.load(f) + if isinstance(force_cfg, dict): + cfg_forces = _normalize_force_vectors(force_cfg.get("forces")) + if cfg_forces is not None: + args.force = cfg_forces + else: + cfg_force = _normalize_force_vectors(force_cfg.get("force")) + if cfg_force is not None: + args.force = cfg_force + elif "force" in force_cfg or "forces" in force_cfg: + force_config_error = "force/forcesinvalid format" + if "global_loading" in force_cfg: + args.global_loading = bool(force_cfg["global_loading"]) + if "force_region_mode" in force_cfg: + args.force_region_mode = str(force_cfg["force_region_mode"]) + if "force_top_percent" in force_cfg: + args.force_top_percent = float(force_cfg["force_top_percent"]) + if "seat_height_min_ratio" in force_cfg: + args.seat_height_min_ratio = float(force_cfg["seat_height_min_ratio"]) + if "seat_height_max_ratio" in force_cfg: + args.seat_height_max_ratio = float(force_cfg["seat_height_max_ratio"]) + if "force_bbox" in force_cfg: + args.force_bbox = force_cfg["force_bbox"] + if "force_bbox_ratio" in force_cfg: + args.force_bbox_ratio = force_cfg["force_bbox_ratio"] + if "force_entries" in force_cfg: + raw_entries = force_cfg["force_entries"] + if isinstance(raw_entries, list): + normalized_entries = [] + for entry in raw_entries: + norm_entry = _normalize_force_entry(entry) + if norm_entry is not None: + normalized_entries.append(norm_entry) + if normalized_entries: + force_entries = normalized_entries + else: + force_config_error = "force_entries has no valid entries" + else: + force_config_error = "force_entriesinvalid format" + force_config_loaded = True + else: + force_config_error = f"force_configis not a dict: {type(force_cfg)}" + except Exception as e: + force_config_error = f"read failed: {e}" + + # set up logging (force=True make sure the previous config is overwritten) + os.makedirs(args.out_folder, exist_ok=True) + log_file = os.path.join(args.out_folder, "optimization.log") + + # clear all previous handlers + for handler in logging.root.handlers[:]: + logging.root.removeHandler(handler) + + # reconfigure logging + logging.basicConfig( + level=logging.INFO, + format='%(asctime)s - %(levelname)s - %(message)s', + handlers=[ + logging.FileHandler(log_file, mode='w'), # 'w' mode rewrites each time + logging.StreamHandler() + ], + force=True # Python 3.8+ support, force reconfiguration + ) + + logging.info(f"🔧 logging configuration completed") + logging.info(f" - log file: {log_file}") + logging.info(f" - output mode: file + console") + if args.force_config: + if force_config_loaded: + logging.info(" ✅ force_configloaded") + logging.info(f" - path: {args.force_config}") + logging.info(f" - forces: {args.force}") + if force_entries: + logging.info(f" - force_entries: {len(force_entries)}") + logging.info(f" - global_loading: {args.global_loading}") + logging.info(f" - force_region_mode: {args.force_region_mode}") + logging.info(f" - force_top_percent: {args.force_top_percent}") + logging.info(f" - seat_height_min_ratio: {args.seat_height_min_ratio}") + logging.info(f" - seat_height_max_ratio: {args.seat_height_max_ratio}") + logging.info(f" - force_bbox: {args.force_bbox}") + logging.info(f" - force_bbox_ratio: {args.force_bbox_ratio}") + if force_config_error: + logging.warning(f" ⚠️ force_configsome fields are invalid: {force_config_error}") + else: + logging.warning(f" ⚠️ force_configloadfailed: {force_config_error}") + + # ==================== Save run information ==================== + # 1. Save Command used + command_file = os.path.join(args.out_folder, "run_command.txt") + try: + with open(command_file, 'w') as f: + f.write("=" * 80 + "\n") + f.write("Command used (Command Used)\n") + f.write("=" * 80 + "\n\n") + f.write("Full command:\n") + f.write("python " + " ".join(sys.argv) + "\n\n") + + f.write("=" * 80 + "\n") + f.write("Arguments (Arguments)\n") + f.write("=" * 80 + "\n\n") + for arg, value in vars(args).items(): + f.write(f"{arg}: {value}\n") + + f.write("\n" + "=" * 80 + "\n") + f.write("Environment (Environment)\n") + f.write("=" * 80 + "\n\n") + f.write(f"Python: {sys.version}\n") + f.write(f"PyTorch: {torch.__version__}\n") + f.write(f"CUDA Available: {torch.cuda.is_available()}\n") + if torch.cuda.is_available(): + f.write(f"CUDA Version: {torch.version.cuda}\n") + f.write(f"GPU Count: {torch.cuda.device_count()}\n") + + logging.info(f" - saved command used : {command_file}") + except Exception as e: + logging.warning(f" ⚠️ Save Command usedfailed: {e}") + + # 2. Save current script copy + script_backup = os.path.join(args.out_folder, "viewer_hunyuan_web_physiopt.py") + try: + current_script = os.path.abspath(__file__) + shutil.copy2(current_script, script_backup) + logging.info(f" - saved script copy : {script_backup}") + except Exception as e: + logging.warning(f" ⚠️ Save failed to save script copy: {e}") + + # loadlatentsandcondition + logging.info(f"\n📂 loading input data...") + logging.info(f" - Latents: {args.latents}") + + data = torch.load(args.latents, map_location='cpu') + + # extract latents + if isinstance(data, dict) and 'latents' in data: + latents = data['latents'] + else: + latents = data + + logging.info(f" ✅ Latents shape: {latents.shape}") + + # check condition information (image_embedsimage) + need_encode_cond = False + image_embeds = None + image = None + + if isinstance(data, dict): + if 'image' in data: + # format: Save image, + logging.info(f" - detected image data; re-encoding as conditional embeds") + image_array = data['image'] + image = Image.fromarray(image_array) + need_encode_cond = True + elif 'image_embeds' in data: + # format: already embeds + logging.info(f" - using the saved conditional embeds") + image_embeds = data['image_embeds'] + need_encode_cond = False + elif 'cond' in data: + # format + logging.info(f" - using the saved cond") + image_embeds = data['cond'] + need_encode_cond = False + else: + raise ValueError("latents.ptis missingimage, image_embedsor cond data") + else: + raise ValueError("latentsmust be a dictionary containing'latents'andconditioninformation dict") + + if image_embeds is not None: + if isinstance(image_embeds, dict): + logging.info(f" ✅ Cond keys: {list(image_embeds.keys())}") + else: + logging.info(f" ✅ Image embeds shape: {image_embeds.shape}") + + # loadmodel + logging.info(f"\n🔧 loading Hunyuan3Dmodel...") + vae, flow_model, scheduler = load_hunyuan_models( + model_path=args.model_path, + subfolder=args.subfolder, + use_safetensors=args.use_safetensors + ) + + # ==================== encode condition (if needed) ==================== + if need_encode_cond: + logging.info("🎨 encoding conditional embeds from the image...") + + # reload the full pipeline for encoding + from hy3dgen.shapegen import Hunyuan3DDiTFlowMatchingPipeline + + pipeline = Hunyuan3DDiTFlowMatchingPipeline.from_pretrained( + args.model_path, + subfolder=args.subfolder, + torch_dtype=torch.float16, + use_safetensors=args.use_safetensors + ) + pipeline.to('cuda') + + with torch.no_grad(): + # prepare the image + cond_inputs = pipeline.prepare_image(image) + image_tensor = cond_inputs.pop('image') + + # 🔧 enable CFG: encode condition (including conditioned and unconditioned branches) + cond_dict = pipeline.encode_cond( + image=image_tensor, + additional_cond_inputs=cond_inputs, + do_classifier_free_guidance=True, # ✅ enable CFG + dual_guidance=False, + ) + + # save the cond dict + image_embeds = cond_dict + + logging.info(f" ✅ condition encoding completed (CFG mode) ") + logging.info(f" - Cond keys: {list(cond_dict.keys()) if isinstance(cond_dict, dict) else 'tensor'}") + + # Compliancethreshold valuekept only as a config field (the current optimization does not use ALM/threshold value) + compliance_threshold = args.compliance_threshold + + # SDSparametersphysicsoptimizationuse, keptconfigold parameters + target_z0_update_interval = 1 + forces = None + normalized_forces = _normalize_force_vectors(args.force) + if normalized_forces: + forces = [{'external_force': vec} for vec in normalized_forces] + elif args.force is not None: + logging.warning(f" ⚠️ invalid external force vector; ignoring: {args.force}") + # createconfig + config = OptimizationConfig( + num_steps=args.num_steps, + lr=args.lr, + sds_timestep=args.sds_timestep, + sds_weight=args.sds_weight if args.use_physics else 1.0, # kept for compatibility + sds_weight_start=args.sds_weight_start, # dynamic weight start value + sds_weight_end=args.sds_weight_end, # dynamic weight end value + guidance_scale=args.guidance_scale, # 🔑 added CFG guidance scale + sds_projection_max_rel=args.sds_projection_max_rel, + sds_use_uncond=args.sds_use_uncond, + sds_target_z0_update_interval=target_z0_update_interval, + sds_target_z0_ema_beta=args.sds_target_z0_ema_beta, + deformed_mesh_interval=args.deformed_mesh_interval, + deformed_mesh_disp_min=args.deformed_mesh_disp_min, + deformed_mesh_disp_max=args.deformed_mesh_disp_max, + use_sgd=args.use_sgd, + grad_clip_enabled=args.grad_clip_enabled, + # physicsparameters + res=args.res, + lagrange_max=args.lagrange_max, + compliance_threshold=compliance_threshold, + alm_rho_init=args.alm_rho_init, + alm_rho_max=args.alm_rho_max, + alm_rho_increase_factor=args.alm_rho_increase_factor, + alm_rho_increase_patience=args.alm_rho_increase_patience, + alm_scale_guard_ratio=args.alm_scale_guard_ratio, + youngs_modulus_scale=args.youngs_modulus_scale, + # topology control + one_cc_only=not args.keep_all_components, + re_extract_interval=args.re_extract_interval, + # external forces and load regions + forces=forces, + force_entries=force_entries, + use_local_loading=not args.global_loading, + seat_height_min_ratio=args.seat_height_min_ratio, + seat_height_max_ratio=args.seat_height_max_ratio, + force_region_mode=args.force_region_mode, + force_top_percent=args.force_top_percent, + force_bbox=args.force_bbox, + force_bbox_ratio=args.force_bbox_ratio, + # output path + out_folder=args.out_folder, + ) + + # createoptimizer + optimizer = HunyuanSDSOptimizer( + latents=latents, + cond=image_embeds, + vae=vae, + flow_model=flow_model, + scheduler=scheduler, + config=config, + device='cuda' + ) + + # physics simulation preparation + final_step = args.num_steps + if args.use_physics: + logging.info(f"\n🔬 physicsoptimization + volume constraint") + logging.info(f" - Voxel resolution: {args.res}") + logging.info(f" - optimization steps: {args.num_steps}") + logging.info(f" - volume-constraint weight: {config.volume_term:.2e}") + + try: + optimizer.extract_solid(step=-1) # initial extraction + optimizer.prepare_physical_simulation() + logging.info(f" ✅ physics simulationInitializationsucceeded") + except Exception as e: + logging.warning(f" ⚠️ warning: initial mesh extraction failed (this is normal, optimizationbe repaired during the optimization process) ") + logging.warning(f" error information: {str(e)[:100]}") + # meshfailed, still continue physics simulation + # the key of physics simulation is the occupancy field, not the mesh + else: + logging.info(f"\n🎨 using pure SDS optimization mode") + + # optimization loop + optimization_mode = "Phys+Volume" if args.use_physics else "Pure SDS" + total_steps_hint = args.num_steps + logging.info(f"\n🚀 start{optimization_mode}optimization ({total_steps_hint} steps)...") + + if args.use_physics: + for step in range(args.num_steps): + logging.info(f"\nStep {step}/{args.num_steps}") + optimizer.training_step_phys_volume(step) + if config.save_every > 0 and step % config.save_every == 0: + optimizer.save_mesh(step, args.out_folder) + final_step = max(0, args.num_steps - 1) + else: + # pure SDS optimization + for step in range(args.num_steps): + logging.info(f"\nStep {step}/{args.num_steps}") + optimizer.training_step_sds(step) + if step % 20 == 0: + optimizer.save_mesh(step, args.out_folder) + + # save final results + logging.info("\n✅ Optimization finished!save final results...") + optimizer.save_mesh(final_step, args.out_folder, high_quality=True) + if args.use_physics: + optimizer.save_final_deformed_mesh(final_step) + + final_latents_path = os.path.join(args.out_folder, "optimized_latents.pt") + torch.save({ + 'latents': optimizer.latents.detach().cpu(), + 'cond': optimizer.cond, + }, final_latents_path) + logging.info(f"💾 save optimized latents: {final_latents_path}") + logging.info(f"\n✅ all files saved to: {args.out_folder}") + + if args.use_physics: + logging.info(f"\n📊 force visualization data:") + logging.info(f" - directory: {os.path.join(args.out_folder, 'force_visualization')}") + logging.info(f" - quick view: cd {os.path.join(args.out_folder, 'force_visualization')} && python visualize_forces.py") + + +if __name__ == "__main__": + main() diff --git a/cfd_workflow_20261012/_seiler_ref/result_simu_inst.ipynb b/cfd_workflow_20261012/_seiler_ref/result_simu_inst.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..1f87b710b883705381dfc3949d33ab000496daa7 --- /dev/null +++ b/cfd_workflow_20261012/_seiler_ref/result_simu_inst.ipynb @@ -0,0 +1,240 @@ +{ + "cells": [ + { + "cell_type": "code", + "execution_count": 12, + "id": "9798773f", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "The autoreload extension is already loaded. To reload it, use:\n", + " %reload_ext autoreload\n" + ] + } + ], + "source": [ + "%matplotlib inline\n", + "%load_ext autoreload\n", + "%autoreload 2\n", + "\n", + "import os\n", + "import numpy as np\n", + "import glob\n", + "import pandas as pd\n", + "import sys\n", + "import trimesh\n", + "sys.path.insert(0, \"/scratch/cvlab/home/seiler/smoothSDF\")\n", + "from src import visualization as viz" + ] + }, + { + "cell_type": "code", + "execution_count": 13, + "id": "e6346faa", + "metadata": {}, + "outputs": [], + "source": [ + "\n", + "def get_Cd_sim(simdir, itercheck=2000, average=1000, load_always=False):\n", + " \"\"\"\n", + " Get the drag coefficient from the simulation directory.\n", + " \n", + " itercheck: int (optional)\n", + " If given, will verify if the max iteration is the given int.\n", + " average: int\n", + " If not None, will return the average Cd over the last `average` iters.\n", + " load_always: bool\n", + " If True, will load the data even if the simulation is not finished.\n", + " \n", + " If return value is negative, then an error has been raised:\n", + " -1: Unknown error.\n", + " -2: Experiment is not finished.\n", + " -3: Problem in loading the force coeff data.\n", + " \"\"\"\n", + " try:\n", + " if not os.path.isdir(os.path.join(simdir, \"postProcessing\")):\n", + " print(f\"{simdir} might not be finished (no 'postProcessing' folder).\")\n", + " return -2\n", + "\n", + " # Get data in tabular form\n", + " try:\n", + " # data = []\n", + " # with open(os.path.join(simdir, \"postProcessing/car/0/forceCoeffs.dat\")) as file:\n", + " # for line in file:\n", + " # if line[0] == '#':\n", + " # # The last commented line should correspond to column names\n", + " # names = line[1:].split()\n", + " # else:\n", + " # data.append(line.split())\n", + " # data = np.array(data).astype(float)\n", + "\n", + " search_pattern = os.path.join(simdir, \"postProcessing\", \"car\", \"*\", \"forceCoeffs.dat\")\n", + " file_paths = glob.glob(search_pattern)\n", + " all_data = []\n", + " names = []\n", + " for file_path in file_paths:\n", + " with open(file_path, 'r') as file:\n", + " for line in file:\n", + " if line.startswith('#'):\n", + " if \"Time\" in line:\n", + " names = line[1:].split()\n", + " elif line.strip():\n", + " all_data.append(line.split())\n", + " df = pd.DataFrame(all_data, columns=names, dtype=float)\n", + " df_clean = df.sort_values(by='Time').drop_duplicates(subset='Time', keep='last')\n", + " data = df_clean.to_numpy()\n", + " \n", + " if itercheck is not None and len(data)-1 < itercheck:\n", + " print(f\"WARNING ({simdir}): iteration number is incorrect ({len(data)-1}!={itercheck})!\")\n", + " if not load_always:\n", + " return -2\n", + " \n", + " except ValueError as err:\n", + " print(f\"Cannot load data from {simdir}: {err}\")\n", + " return -3\n", + "\n", + " # Extract the drag coeff (optionally average over the last iters)\n", + " col = names.index('Cd') if 'Cd' in names else 2\n", + " if average is not None:\n", + " cd = data[-average:, col].mean()\n", + " else:\n", + " cd = data[:, col]\n", + " return cd\n", + " \n", + " except Exception as err:\n", + " print(f\"Unknown exception for {simdir}: {err}\")\n", + " return -1" + ] + }, + { + "cell_type": "code", + "execution_count": 38, + "id": "19d427b6", + "metadata": {}, + "outputs": [], + "source": [ + "instance = \"292f6606c6072b96715e04edb8af9c53\"\n", + "# instance = \"1f191e0327ce54474cdd04162f008888\"" + ] + }, + { + "cell_type": "code", + "execution_count": 39, + "id": "19edad59", + "metadata": {}, + "outputs": [], + "source": [ + "init_drag = get_Cd_sim(f\"/scratch/cvlab/datasets/dataset_Olivier/ImprovedShapenetCars/{instance}\")" + ] + }, + { + "cell_type": "code", + "execution_count": 40, + "id": "2758ce28", + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "0.392302962892689" + ] + }, + "execution_count": 40, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "init_drag" + ] + }, + { + "cell_type": "code", + "execution_count": 36, + "id": "eb570788", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "/scratch/cvlab/home/seiler/smoothSDF/simulations_car/simulations/292f6606c6072b96715e04edb8af9c53/DFLOW_30_sim/ might not be finished (no 'postProcessing' folder).\n" + ] + } + ], + "source": [ + "method = [\"GD\", \"FMG\", \"DFLOW\", \"ICTM\", \"SGO\", \"OURS\"]\n", + "drag_list = []\n", + "mesh_list = []\n", + "title_list = []\n", + "for m in method:\n", + " mesh = trimesh.load(f\"/scratch/cvlab/home/seiler/smoothSDF/simulations_car/meshes/{instance}/{m}_30.obj\")\n", + " mesh_list.append(mesh)\n", + " drag = get_Cd_sim(f\"/scratch/cvlab/home/seiler/smoothSDF/simulations_car/simulations/{instance}/{m}_30_sim/\", average=1000)\n", + " drag_list.append(drag)\n", + " title_list.append(f\"{m}; {drag:1.2f}\")" + ] + }, + { + "cell_type": "code", + "execution_count": 37, + "id": "a266a09a", + "metadata": {}, + "outputs": [ + { + "data": { + "image/png": "iVBORw0KGgoAAAANSUhEUgAAA94AAAC/CAYAAAAILQRJAAAAOXRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjcuMSwgaHR0cHM6Ly9tYXRwbG90bGliLm9yZy/bCgiHAAAACXBIWXMAAA9hAAAPYQGoP6dpAACqJklEQVR4nO29d5icR5Xv/+0cJucojUYa5WRJONvYBhsMJlkmGOOADRgWFu414S5hF5N2uXuBJSy7LOC1MCZ5AdsYnHCSbRxlWZYsK4xGo5nR5Bx7erp7un5/zO+UTlfX2zMKY2lG5/M8/XT3G+pN5z11zqlTVS6llIIgCIIgCIIgCIIgCLOC+2SfgCAIgiAIgiAIgiD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pO444478KY3vQlFRUUIBAJYuHAhrrvuOrzyyisn7HqORw7j8Tg+8YlPYNOmTSguLkYgEEBtbS0+8IEPYMeOHdZ9hoaG8OlPfxpVVVVaDn/yk58clU49XRkeHsY3v/lNbNy4ETk5OQiHw1i1ahW+8IUvoKurK2170oVf+9rXHMt0uVy4+OKLU5YtWrQoRU/6/X7U1NTgIx/5CFpaWqzl7Ny5Ex/84Ae1HVZcXIx169bh4x//uKMsHA2//OUvsWHDBoRCIZSVleGjH/0oenp6ZrTv0fo0R+MvnWy8J/sEjofGxka84x3vwN69e3HRRRfhlltuQUVFBUZHR/HKK6/g9ttvx3e/+120tLSgqqoqZd/PfOYzOPPMM5FMJjE0NITdu3fj7rvvxk9/+lNcc8012LJlC/x+/zGfW39/Py644AJ0d3fjs5/9LKqrq/Gb3/wG73//+3H77bfjxhtvnLaMm2++Gbm5uXj3u9+N5cuXo7+/H1u2bMHb3vY2fOtb38JXvvIVve3AwADq6+vxlre8BTU1NQiFQjhw4ABuv/12/P73v8fzzz+PVatWHfP1CKl88IMfxNvf/va05XV1dSn/g8EgXnvtNWzbtg1nnnlmyrrt27dj586dCAaDiEajaWU99NBDuPrqqxGJRLB582Zcd911yMvLQ29vL5577jl85Stfwc9//nPs37//mK/j4MGDOO+88+D1evF//s//QV5eHn7+85/jrW99Kx588EFceumlGfefmJjAddddhzPOOANXX301amtr0dHRgf/6r//Cueeei1/+8pdpzldzczMuvvhijI6O4iMf+QiWLVuGoaEh7Nq1C21tbcd8LXMZkielFEZGRrB//37ce++9+OUvf4lLL70Uv//975Gfn5+2H+kxE9u20/HlL38Z3/72t3VlXVtbi87OTvzmN7/BlVdeieuuuw5btmyBx+MBAFxyySW46667sHXr1jS5f+KJJ+D1evHkk0+mHYcM3UsuueSoz3E6/uEf/gGtra248sorsXbtWoyNjeGuu+7CNddcg8cffxw///nPZ1TOLbfcgh/96Ee48sor8bnPfQ579+7Fj370I+zYsQOPPvoo3O4jMeu7774b733ve7F+/Xp85zvfwd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2H/7wh+Hz+bT8zAYHDx4EABQWFqYsX7JkCV577TU8++yzMyrnS1/6ElauXIkXX3xx2m2nk9N9+/ZhdHR0Rsc9Xp/maOr+14s563jv3r0bubm5qK2tTVlOyoR/xsfHj6rsdevWAcAxV6Tt7e0AkNavnC871r6sO3fuxN13340LL7ww7doB4OGHH0ZJSQkqKyvxxje+Ea+99hq+973v4brrrjum4wl2br31VpSUlKR8Pvaxj1m3Xb9+PTZu3IgtW7boZbfffjs2bdqkZY1z4MABTExMYP369WnrotFomnwnEoljuobZlNMHHngAL774Ij7wgQ+kVNjUH/1jH/sY+vv7cccdd+D222/XAS9+j4QpMumjm266KU0Ov/GNbxxV+bt37wYAbNy4MeN2mzZtAgC8+uqrehn1jeQDFG3dulUP/HLxxRenON702xwYZjZpb2/Hz372MyxevBgXXHDBjLanQYdMqqqq0Nvbi1gsprel5bZtgWN/h+Y6JFdOju+JhIKb5Fy1trbikUcesQY2j4XZfM7//M//jHg8jhtuuEEvKysrQ3FxMZ5//vk0+4XeNacB2YRU/vEf/xE+nw9XXXUVli1bhptuugk/+clPsHfv3rRtM8ns0NBQSr07ODiYtt+x6NCj4UTK4d69e1FSUoKKigqcddZZePjhh/GlL30pJWg/MDCA8fFx6/ECgQCKi4tPW/02Hbt370ZOTk7a+CeccDiMFStWoKmpacaOaCa4/9PU1IRf/epX+NrXvgav14urr746Zduvf/3rmJiYwPnnn49169bhE5/4BG6//XY0NTUd93lMJ6dKKb3NdByPTzOdv3SymLODqw0PD6O8vDxt+d69e7F27dqUZd/5znesA684kZubq49BLFq0aMYjOFKLk81wIyfkaFulAKCnpwebN29GKBTCbbfdZt3mnHPOwSOPPILx8XHs2bMHv/vd7zAwMIBEIgGvd84+7lOOm2++Ge973/tSltnkkbjpppvwmc98RhtLjz32GP793//dui3JHckh57bbbsOnP/3plGXbtm3DG97wBgBTDs3JltMDBw7guuuuQ1VVFb73ve+lrKOsgJycHDzxxBN6AMP3vOc9WLx4Mb785S/jhhtuSGkNPd2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RBxvQRAEQRAEQRAEQZhFxPEWBEEQBEEQBEEQhFnk/wMyU59BebTw6gAAAABJRU5ErkJggg==", + "text/plain": [ + "
" + ] + }, + "metadata": {}, + "output_type": "display_data" + } + ], + "source": [ + "fig = viz.plot_render(mesh_list, titles=title_list, max_cols=6, axis_on=False, h_pad=1, figsize=(10, 4))" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "85d554c6", + "metadata": {}, + "outputs": [], + "source": [] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "c1a8cfed", + "metadata": {}, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.10.6" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} diff --git a/cfd_workflow_20261012/_seiler_ref/result_simulations.ipynb b/cfd_workflow_20261012/_seiler_ref/result_simulations.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..ef994febfb323e83588a04a79baa54e3b9b4a321 --- /dev/null +++ b/cfd_workflow_20261012/_seiler_ref/result_simulations.ipynb @@ -0,0 +1,511 @@ +{ + "cells": [ + { + "cell_type": "code", + "execution_count": 1, + "id": "917dbeb5", + "metadata": {}, + "outputs": [], + "source": [ + "%matplotlib inline\n", + "%load_ext autoreload\n", + "%autoreload 2" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "id": "05b70bf2", + "metadata": {}, + "outputs": [], + "source": [ + "\n", + "import os\n", + "import numpy as np\n", + "import glob\n", + "import pandas as pd\n", + "import sys\n", + "sys.path.insert(0, \"/scratch/cvlab/home/seiler/smoothSDF\")\n", + "from src import visualization as viz\n" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "id": "6f50a2e1", + "metadata": {}, + "outputs": [], + "source": [ + "\n", + "def get_Cd_sim(simdir, itercheck=2000, average=1000, load_always=False):\n", + " \"\"\"\n", + " Get the drag coefficient from the simulation directory.\n", + " \n", + " itercheck: int (optional)\n", + " If given, will verify if the max iteration is the given int.\n", + " average: int\n", + " If not None, will return the average Cd over the last `average` iters.\n", + " load_always: bool\n", + " If True, will load the data even if the simulation is not finished.\n", + " \n", + " If return value is negative, then an error has been raised:\n", + " -1: Unknown error.\n", + " -2: Experiment is not finished.\n", + " -3: Problem in loading the force coeff data.\n", + " \"\"\"\n", + " try:\n", + " if not os.path.isdir(os.path.join(simdir, \"postProcessing\")):\n", + " print(f\"{simdir} might not be finished (no 'postProcessing' folder).\")\n", + " return -2\n", + "\n", + " # Get data in tabular form\n", + " try:\n", + " # data = []\n", + " # with open(os.path.join(simdir, \"postProcessing/car/0/forceCoeffs.dat\")) as file:\n", + " # for line in file:\n", + " # if line[0] == '#':\n", + " # # The last commented line should correspond to column names\n", + " # names = line[1:].split()\n", + " # else:\n", + " # data.append(line.split())\n", + " # data = np.array(data).astype(float)\n", + "\n", + " search_pattern = os.path.join(simdir, \"postProcessing\", \"car\", \"*\", \"forceCoeffs.dat\")\n", + " file_paths = glob.glob(search_pattern)\n", + " all_data = []\n", + " names = []\n", + " for file_path in file_paths:\n", + " with open(file_path, 'r') as file:\n", + " for line in file:\n", + " if line.startswith('#'):\n", + " if \"Time\" in line:\n", + " names = line[1:].split()\n", + " elif line.strip():\n", + " all_data.append(line.split())\n", + " df = pd.DataFrame(all_data, columns=names, dtype=float)\n", + " df_clean = df.sort_values(by='Time').drop_duplicates(subset='Time', keep='last')\n", + " data = df_clean.to_numpy()\n", + " \n", + " if itercheck is not None and len(data)-1 < itercheck:\n", + " print(f\"WARNING ({simdir}): iteration number is incorrect ({len(data)-1}!={itercheck})!\")\n", + " if not load_always:\n", + " return -2\n", + " \n", + " except ValueError as err:\n", + " print(f\"Cannot load data from {simdir}: {err}\")\n", + " return -3\n", + "\n", + " # Extract the drag coeff (optionally average over the last iters)\n", + " col = names.index('Cd') if 'Cd' in names else 2\n", + " if average is not None:\n", + " cd = data[-average:, col].mean()\n", + " else:\n", + " cd = data[:, col]\n", + " return cd\n", + " \n", + " except Exception as err:\n", + " print(f\"Unknown exception for {simdir}: {err}\")\n", + " return -1" + ] + }, + { + "cell_type": "code", + "execution_count": 11, + "id": "ab415585", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "WARNING (/scratch/cvlab/home/seiler/smoothSDF/simulations_car/simulations/1f191e0327ce54474cdd04162f008888/FMG_30_sim): iteration number is incorrect (0!=2000)!\n", + "/scratch/cvlab/datasets/dataset_Olivier/ImprovedShapenetCars/1552f1a6521bb54a4bb135bcd06914d might not be finished (no 'postProcessing' folder).\n", + "WARNING (/scratch/cvlab/home/seiler/smoothSDF/simulations_car/simulations/2fe4a878e34bd3bab8013668e30e23b0/FMG_30_sim): iteration number is incorrect (0!=2000)!\n", + "/scratch/cvlab/datasets/dataset_Olivier/ImprovedShapenetCars/300f9c418d6ec9f6473f10e6caaeca56 might not be finished (no 'postProcessing' folder).\n", + "\n", + "=== DRAG REDUCTION PER INSTANCE ===\n", + "Instance: 2236a1b9cde71eff13d31c5a107f3c4 | Init: 0.3929 | Opt: 0.3034 | Reduction: 22.78%\n", + "Instance: 20a3df3de67f309d8e35db9103756ad5 | Init: 0.4778 | Opt: 0.2578 | Reduction: 46.05%\n", + "Instance: 48862b67f5932cd4473f10e6caaeca56 | Init: 0.3664 | Opt: 0.3161 | Reduction: 13.75%\n", + "Instance: 292f6606c6072b96715e04edb8af9c53 | Init: 0.3923 | Opt: 0.2562 | Reduction: 34.69%\n", + "Instance: 4c6aa3e7a8130295b528c0abff96f586 | Init: 0.3618 | Opt: 0.2900 | Reduction: 19.85%\n", + "Instance: 4a423ae9a28afe3588cf40718544e7cc | Init: 0.5051 | Opt: 0.3235 | Reduction: 35.95%\n", + "Instance: 498b7c799350d1f7c4acded0fc8a9118 | Init: 0.3778 | Opt: 0.2720 | Reduction: 28.00%\n", + "Instance: 45ff3c9bc849f2e33a2844e8778fdc6 | Init: 0.3401 | Opt: 0.4559 | Reduction: -34.03%\n", + "Instance: 365af82203c96fbca92a4cdad802b45 | Init: 0.4045 | Opt: 0.3175 | Reduction: 21.51%\n", + "Instance: 1548f5fb0684d08c63155b8ebc275bd1 | Init: 0.4494 | Opt: 0.2697 | Reduction: 39.98%\n", + "Instance: 1660d6b7221223708a49a62fbc70ff9a | Init: 0.5605 | Opt: 0.2776 | Reduction: 50.47%\n", + "Instance: 1713a1ac8aedcc522b12ea83455b0f44 | Init: 0.5217 | Opt: 0.2866 | Reduction: 45.06%\n", + "Instance: 1e2f9cb6b33c92ea82381b04bbe0ce6d | Init: 0.3427 | Opt: 0.3655 | Reduction: -6.67%\n", + "Instance: 332ac5346c7d3c0f8e35db9103756ad5 | Init: 0.4533 | Opt: 0.2602 | Reduction: 42.59%\n", + "Instance: 3264f78bfc3bc58c9213ea6cb12e4e3c | Init: 0.4628 | Opt: 0.2822 | Reduction: 39.02%\n", + "Instance: 3bfa196d1b48f1e0c5dccef20baf829a | Init: 0.3750 | Opt: 0.2731 | Reduction: 27.16%\n", + "\n", + "=> Mean relative reduction: 26.63%\n", + "\n", + "\n", + "=> STD reduction: 21.02%\n", + "\n", + "=== FAILED INSTANCES ===\n", + "Instance: 1f191e0327ce54474cdd04162f008888 | Reason: Optimization failure (-2)\n", + "Instance: 1552f1a6521bb54a4bb135bcd06914d | Reason: Initial drag failure (-2)\n", + "Instance: 2fe4a878e34bd3bab8013668e30e23b0 | Reason: Optimization failure (-2)\n", + "Instance: 300f9c418d6ec9f6473f10e6caaeca56 | Reason: Initial drag failure (-2)\n" + ] + } + ], + "source": [ + "import numpy as np\n", + "\n", + "# --- 1. List definition ---\n", + "instance_list_1 = [\n", + " \"1f191e0327ce54474cdd04162f008888\", \"2236a1b9cde71eff13d31c5a107f3c4\",\n", + " \"20a3df3de67f309d8e35db9103756ad5\", \"48862b67f5932cd4473f10e6caaeca56\",\n", + " \"292f6606c6072b96715e04edb8af9c53\", \"4c6aa3e7a8130295b528c0abff96f586\",\n", + " \"4a423ae9a28afe3588cf40718544e7cc\", \"498b7c799350d1f7c4acded0fc8a9118\",\n", + " \"45ff3c9bc849f2e33a2844e8778fdc6\", \"365af82203c96fbca92a4cdad802b45\"\n", + "]\n", + "\n", + "instance_list_2 = [\n", + " \"1548f5fb0684d08c63155b8ebc275bd1\", \"1552f1a6521bb54a4bb135bcd06914d\",\n", + " \"1660d6b7221223708a49a62fbc70ff9a\", \"1713a1ac8aedcc522b12ea83455b0f44\",\n", + " \"1e2f9cb6b33c92ea82381b04bbe0ce6d\", \"2fe4a878e34bd3bab8013668e30e23b0\",\n", + " \"300f9c418d6ec9f6473f10e6caaeca56\", \"332ac5346c7d3c0f8e35db9103756ad5\",\n", + " \"3264f78bfc3bc58c9213ea6cb12e4e3c\", \"3bfa196d1b48f1e0c5dccef20baf829a\"\n", + "]\n", + "\n", + "instance_list = instance_list_1 + instance_list_2\n", + "\n", + "# --- 2. Path configuration ---\n", + "BASE_INIT_PATH = \"/scratch/cvlab/datasets/dataset_Olivier/ImprovedShapenetCars\"\n", + "SIM_FOLDER = \"/scratch/cvlab/home/seiler/smoothSDF/simulations_car/simulations\"\n", + "METHOD = \"FMG\"\n", + "THRESHOLD = 30\n", + "THRESHOLD_INDEX = 3\n", + "\n", + "# --- 3. Data processing ---\n", + "successful_instances = []\n", + "failed_instances = []\n", + "\n", + "\n", + "for inst in instance_list:\n", + " # Read initial drag\n", + " init_drag = get_Cd_sim(f\"{BASE_INIT_PATH}/{inst}\")\n", + " \n", + " # Check initial failure\n", + " if init_drag == -2:\n", + " failed_instances.append((inst, \"Initial drag failure (-2)\"))\n", + " continue\n", + " \n", + " # Read optimized drag\n", + " opt_drag = get_Cd_sim(f\"{SIM_FOLDER}/{inst}/{METHOD}_{THRESHOLD}_sim\")\n", + " \n", + " # Check optimization failure (includes -2 and other negative values)\n", + " if opt_drag < 0:\n", + " failed_instances.append((inst, f\"Optimization failure ({opt_drag})\"))\n", + " continue\n", + " \n", + " # Calculate reduction (in percentage) if everything is fine\n", + " reduction_pct = ((init_drag - opt_drag) / init_drag) * 100\n", + " successful_instances.append({\n", + " \"instance\": inst,\n", + " \"init\": init_drag,\n", + " \"opt\": opt_drag,\n", + " \"reduction\": reduction_pct\n", + " })\n", + "\n", + "# --- 4. Final outputs ---\n", + "print(\"\\n=== DRAG REDUCTION PER INSTANCE ===\")\n", + "reductions = []\n", + "\n", + "for data in successful_instances:\n", + " reductions.append(data[\"reduction\"])\n", + " print(f\"Instance: {data['instance']} | Init: {data['init']:.4f} | Opt: {data['opt']:.4f} | Reduction: {data['reduction']:.2f}%\")\n", + "\n", + "if reductions:\n", + " mean_reduction = np.mean(reductions)\n", + " std = np.std(reductions)\n", + " print(f\"\\n=> Mean relative reduction: {mean_reduction:.2f}%\\n\")\n", + " print(f\"\\n=> STD reduction: {std:.2f}%\\n\")\n", + "\n", + "else:\n", + " print(\"\\n=> No valid instance to calculate the mean.\\n\")\n", + "\n", + "print(\"=== FAILED INSTANCES ===\")\n", + "if failed_instances:\n", + " for inst, reason in failed_instances:\n", + " print(f\"Instance: {inst} | Reason: {reason}\")\n", + "else:\n", + " print(\"No failure detected.\")" + ] + }, + { + "cell_type": "code", + "execution_count": 8, + "id": "f045bf04", + "metadata": {}, + "outputs": [ + { + "data": { + "image/png": "iVBORw0KGgoAAAANSUhEUgAAA9YAAAMWCAYAAAAUAR4GAAAAOXRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjcuMSwgaHR0cHM6Ly9tYXRwbG90bGliLm9yZy/bCgiHAAAACXBIWXMAAA9hAAAPYQGoP6dpAAEAAElEQVR4nOx9d5hkRdX+e7unc0+e2ckzG2bzLrvswgKSEcmS1I+kggEExfBhBkT4iAqKqAQJoqB+IgifSJJFiUpOuyybZ3fSzk6OPZ2mu35/zO/Unltdt2dmZyNb7/P009031K177zlV5z116pQlhBAwMDAwMDAwMDAwMDAwMDDYLrh2d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TUNtTn86G+vh7f+ta30N3dvburp0UsFsM999yD0047DVOnTkUgEMD06dNxzjnnYPXq1RnHk4Na91mwYMG4rtnR0YEvfOEL2G+//VBUVAS/34/6+np86UtfwoYNGzKO3xv7DAAYHh6WNpVT2/zqq6/i1FNPRXV1NQKBAGbMmIELL7xQ2xZ0dXXhe9/7HubMmYNgMIjy8nIcc8wx+Nvf/qYte7x98uOPP44vfOELmDNnDkKhECorK3HsscfimWeemfxDcAANItDH7XZjypQp+OQnP4lXXnllp113R2AibbwO5Nxz+ng8Htvxy5cvx/77749wOIwlS5bgn//8Z0aZqVQKS5YswVe/+tUdco/bi+3pLx5++GF87GMfQygUQm5uLg4//HA89dRTky77+eefx9e+9jXMmTMHd911Fx588EGUlpbK/R9++CHOPfdcVFRUwOfzobq6GmeccQba29t33AP5/9hb5f3FF1/E1772NSxcuBB5eXkoLS3FoYceiv/93/+FEGLM888666wJ9Q2E8doQGzduxAknnIC8vDxMnz4dt912m7a8b3zjG1i0aBFGRkYmVA9CzvacdPnll6OoqAhLlizREluO5cuXIz8/H/fee69tdPXVV1/Fz3/+c8yYMQNLly7Nakh1dHTgoIMOwpYtW/CVr3wFCxYswAcffIA777wTL730Ev79738jGAzK45966incfvvtmDNnDhYtWoT//Oc/23ObE0Z1dTVuvPFGAMDQ0BBefvll3H///Xj66aexcuVKFBcX75J6jBfxeByf+9znsHjxYpx99tmYNm0a2tracNddd+GQQw7BAw88gM9+9rMZ5x1++OG46KKLbNvUxj0bEokETj31VDz//PM477zzcPHFF2NkZATr169HY2OjPG5wcBCnnHIKqqurccstt+CFF17AeeedhxkzZuDAAw+Uxz388MP417/+hVWrVm3HU9jx+O1vf4vbb78dp556Ks477zx4PB48//zzuPLKK/GXv/wFr732GgKBAICJv4OWlha0tbXhjDPOQHV1NXJycrBy5Urcfffd+POf/4z33nsPU6ZMsdXnmmuuwdVXX43jjz8e11xzDYLBIJqamrBixYpd+lyc4PP5cO+99wIAotEo3n77bdx///146qmn8NZbb2H27Nm7uYZ63H///fjyl7+Mgw46CD/84Q9RUFCALVu24OWXX8bIyAi8Xm/W81966SUcd9xxyM/Pxze+8Q2UlpZi+fLl+O///m98+OGHuPvuu+WxDz/8MC677DJ89atfxfz583HrrbfizDPPxDvvvAOXa5t/9JJLLsHRRx+N//qv/9pp950NE5F9YLSj+9jHPoacnBx873vfQ35+Pu655x4cf/zxePrpp3HsscduVz3WrVuH4eFhnHfeeaisrEQ6ncabb76J66+/Ho888gjeeOMNWz12FxYvXoxvf/vbAIDe3l48++yzuO222/Dcc8/hnXfeGVOGdjU2b96Miy66CIcddhi+9KUvobKyEg0NDbjzzjvx6KOP4plnnsHRRx+dcd4ZZ5yBM88807atoKBgXNfs7e3FunXrcNxxx6Gurg6BQADr16/Hb3/7Wzz88MN47bXXMG/ePAB7b58BAFdddRU6Ozsd9z/zzDM4+eSTMWPGDFx66aUoKSnBqlWrcPfdd+Ovf/0rVq5ciaqqKgCjJP1jH/sYmpubceGFF2K//fZDT08Pfve73+H000/HHXfcgUsuuUSWPd4+GQAuuugi5OXl4bTTTsPs2bPR09OD+++/HyeeeCKuu+46XHHFFTvnAQG48847EQ6HkUgk5L0/88wz+Oc//4kjjjhip113ezGRNt4JZ555Jurr6zO2r1ixAjfffDM++clPym2NjY047bTTcNhhh+ErX/kKHn30UZx66qlYvXo1amtr5XE///nP0dHRgZtuumnH3Oh2YqL9xU9+8hP84Ac/wP77749rr70WAPCHP/wBp5xyCh588EGcd95521328uXL5XlFRUW2ev7jH//A6aefjhkzZuAb3/gGysrK0NHRgVdffRUDAwMoKyvbKc9nb5P373//+2hpacEZZ5yBhQsXIhKJ4KGHHsK5556Lf/3rX7jnnnscz33iiSfwyCOPTLhfHq8NkU6nccYZZyAajeKmm27CqlWr8K1vfQvV1dX41Kc+Jct7/fXXcdddd+Hf//43cnK2iyIDYjuwceNG+Xv+/Pmirq7O8dijjz5au7+7u1v09vYKIYR48803BQDx4x//WFvGN7/5TQFA/OlPf7Jt/9Of/iQAiGuvvda2fevWrWJoaEgIIcTDDz8sAIj7779/zPvi2LRp04TOq6urE/Pnz8/Y/t///d8CgLjlllsmdP3x4Pzzzxfb+QqFEEIkk0nxwgsvZGzfunWrKC4uFlOmTBGpVMq2D4A4//zzt/uaQghx5ZVXCrfbLf71r39lPe6ZZ54RAMSmTZuEEEKkUikxdepUcfnll8tjent7RXl5ufjFL34xqTrtSLz55puir68vY/sVV1whAIhf/epXctv2vAMd/vKXvwgA4ic/+Ylt+/LlywUA8T//8z/bcSfbh2y6rOLII48UoVAoY/ttt90mAIhLL710B9dOiB//+Mc2udoerFq1Sni9XvGlL31JpNPp7Spj0aJFIhAI2NpTIYS46KKLBADx8ssvy21nn322OPLII+X/f/3rXwKAWLdundz2v//7vyI3N1c0NzdvV312BCYi+0II8ZnPfEa4XC7x7rvvym2Dg4OitrZWzJo1a7ufrRN++tOfCgDioYceGtfxE5GV559/XgAQzz///LjKBiBOPvnkjO2nn366ACAeeeSRcZUzERx55JFZ++ux0NXVZXtXBNKHpUuX2rZTPzre9mAieOONNwQAcckll8hte2uf8fbbbwu32y1+9rOfCQDia1/7WsYxxx13nPB4PKKzs9O2/Z577hEAxK233iq3kW2k3mNvb68IhUJi0aJFtu3j7ZOFEOKf//xnxrZIJCJmzZolPB6P6OnpGbMMIUZtpvHaEmTrqPf+t7/9TQAQp5xyyrjKmQjuv//+CemzDhNp4ycKKuOJJ56Q2+666y4RCAREJBIRQoy+l0AgIO6++255zMaNG0UwGBT/93//t93X3lGYSH+xdetW4fV6xYIFC0QikZDbE4mEWLBggSgsLBT9/f3bVbYQQnzhC1/Q2tPt7e2iqKhInHDCCbbrThT7gry/8MILYmRkxLYtlUqJI444QgAQK1eu1J43ODgoampqxNe//nVHLuWE8doQa9asybi/I444Qpx77rnyfyKREAsXLhTf+ta3xn19HbYrFHz69OljHkPzzZ5//nk0NjbKkAaaY1BUVDRuj/Xzzz+PQCCAs88+27b9rLPOgt/vx/3332/bXlZWhlAoNK6ydzY+/vGPAwDWr19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MDAhOuhYqclL5s7dy4efPBBzJkzByUlJXjwwQfx4IMP4itf+cqEy4rH4/D7/RmJulwuFwKBABoaGsZlFOwOkECqoSWf+9zncOmll6K+vh4//elP5dy/T3ziE3j88cdtx55zzjm45ZZbcMABB+CWW27BYYcdhjPPPFNrKL3xxhuYO3euJFLbi5aWFni9Xq3z45FHHkEwGERubi6mTJmCr3/96+Oet/jyyy9jcHAQS5cuxTe/+U3k5eXJuRiXX365jZwsXboUHo8HP/rRj9DY2Ijf//73eP/99/Gxj30MwOh8jt///ve45557bOGweypaWloAYNxhQ9neQSwWQ1dXF1paWvDss89KvTrppJPkMZFIBC+99BIOOugg3HfffaiqqkJubi7C4TDOPvvsjLlBK1aswKOPPopjjjkG1113HW666SbU1tbiBz/4wS6fi+WkN1deeSXOPvts5Obm4tprr8VNN92EYDCIz3zmM7j99tttx1522WW4/PLLUVtbi5/+9Kc4/fTT8bWvfS1DvwCgtbUVc+fOxec///lx1e/pp5/GnDlz8OKLL6K+vh7hcBjBYBAnnXSSttNTEY/HAcA2hYVA21577TW57ZBDDsEzzzyDp59+Gps2bcL//M//oKioSIbJf+c738H06dN3+5w5J+hkf8WKFYjH4zjkkEMyjj/44IMBwEasX3jhBbz00ks45ZRTcPPNN+Paa6+Fx+PBhRdeKKfgqBgeHkZXVxeamprw2GOP4fvf/z68Xm9GiPlEZGVnQyf7yWQSJ5xwAq655hoccsghuPXWW/GDH/wAH374IQ499FC89dZbtmOPP/543HvvvTjppJNw8803Y9asWTj22GPle+B47LHHMHfuXPz617/e7jqn02m0tbU5tm0/+9nPEAwGEQqFUFNTg6uuukrqwHiRTCbR1dWFtrY2vPzyyzjnnHMA2Nu8vbHPuPXWW7FmzZoxn//xxx+PwcFBnH/++Xj//ffR2tqKf/zjH/j2t7+NuXPn2gYejjnmGOTk5OCHP/whnnrqKbS0tGDlypX40pe+hL6+Plu49kT65GyYaP+2I+DUT9x999047rjjMDQ0hCuuuEJOO7zkkkvw3e9+13bsL37xC1x00UXw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zJl4/fXXtXOQdjbGkn1KrNTa2pqxj7bR8kEAcO655+KJJ57ARRddhCOOOALFxcVwu9146qmncOutt45LPo8//niUlZXhjjvukHN0dydKSkpssk/LlHzqU5/CqlWr5NIjQggsXLgQP//5zx3L4muu7gq88847+MQnPoH8/Hw8//zztnc1FmpqauB2uyeVG4XWT77vvvvwy1/+MqONI+yJfUY8Hsdll12Gk046CeXl5XI9bpL7/v5+bNiwASUlJSgoKEBTUxP++Mc/4tJLL81YjuYzn/kMLrnkErz44ov48pe/DGB0WaJQKGRLbAWM9ruHH344nn76aSQSCXi93u3uk3t6enDsscdizZo1+Nvf/qZNarajccQRR6CkpATAqK4EAgH86Ec/wtKlS3HiiScCgEzC9MADD8j6qxhPAt4dgcm28SpGRkbwwAMPoLi4GGeccca4zolEIrj44otxxRVXYM6cOfjPf/6DDz74AI899hjq6+uxZMkS/P73v8cf//jHSefmmQzGYysVFhbir3/9K9rb27Fu3TqEw2EsWrRIrqE+Z86c7S7bCdXV1VizZo2jfrzzzjsTKm8i2NvknRCLxXD66afjueeew3333addtvfb3/42ioqKcMYZZ8j2DxiV8UQigQ0bNiAUCjneEzBxG0KHb3zjG1i6dCkuuOACpNNp/O53v8OvfvUruZzZk08+ifvuu29CS5juNcQaGDXAeea3rVu34t1338WRRx6pTWiwu+H3+3HrrbfimGOOwY9//GO5ZuHMmTOxbt06HHzwwQiHw1nLmD59OtLpNNatW5dBGlavXr1D6rl582YcddRR6O/vx3PPPYf9999/QufHYjG0tLSMq5NYtmwZAGiT6NA2dR1mjttvvx2bNm3CU089ZTunpqZGHlNTU4Pm5ubx38BOwtVXX41rrrkG559/fsY67iom+w6A0ayHPT098n9ZWRlqa2vR3NyM4eFhm47onvWDDz6II444An/+859t5fJGb1fA5XLhtttuw7x58/Cd73xHZsCfOXMmnnnmGdTW1mLu3LlZy6COZM2aNZgxY4Zt34cffjip+lmWhQMOOAAvvfQSWlpabJ15PB5HZ2fnhBx9oVDIpjuPPPIIhBC2pEwq0uk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5eXn41re+hfb29hHHffjhh3C5XHj//ffHdO+7k9HqDxmEps+dd9454vjzzz8fb775Jq6++mosXrwYF198MQDg9ttvx/33349vfvObeOqpp3DvvfcCAO666y4cddRRKC0thdvtRmlpKY4++mg899xzu+ye91YdSieVzLYiVX2ZPXv2iOOffvppTJ8+HX6/H0cccQRWrlw54pi+vj5UVlbil7/85bjvaWezfv16nHXWWZgxY4as19OnT8eVV16JlpYWy/P++c9/4thjj0Vubi58Ph+mTp06on6M9VmOhddffx2XXXYZpk+fjkceeQSLFy9GYWHhuNJU0fPrdrsxefJkXHHFFUadbk8gHA7jsccew6JFi1BdXQ2v14uJEyfijDPOwNq1a0ccvzNkri5DTZ+tW7fK45cvX44vfOEL8Pv9mDFjBv70pz8Z0120aBFOPvnkHX4Wjh0+E8CNN95oFFg7wgUXXIDf/va3OP3003H22WfDbrejrq4ODQ0NOyX93Ynb7cbjjz8OAAiFQli+fDl+85vf4F//+heWLVuGadOmfcY5HMl7772Hu+++G5MmTcIBBxyA1157LeXx1157LfLy8jB//nz09PTs0DXPP/98PP300zj99NPxP//zP4jH4/jHP/6BK664Au+++y7+/Oc/AwAaGhqwaNEifOELX8DFF1+MZ599Fl/5ylewdu1aVFVVyfTuvvtutLW14bbbbtuh/IyXnVkfVAYGBnDppZfC7/cjGAyO2P+Pf/wDN910E04++WRcddVVyMrKwgcffIB7770Xf/rTn/Dhhx+ipKREHr9ixQrk5ubisssuQ1FREYLBIP75z3/i29/+Nt5++2088cQTO/0eiIcffhh+vx/RaBSffvopHn30Ubz00kt49dVXceSRR+6y6+4oV199NZqamnDaaadhzpw5GBgYwJ///GeceeaZeO211/DYY4/JY4UQWLRoEf7973/j1FNPxfe+9z20t7fjoYcewmGHHYb//ve/mDlz5piu39zcjB//+MeW7/7qq6/G008/jWuuuQbAsMHjcDhw//33y2N6e3vxve99DzfffDNqamp28EnsGKPVidtvvx0//vGPMW/ePOlE/f3vf49TTjkFixcvxllnnSWPTSQSOOmkk/Duu+/ivPPOw/e+9z0MDg7ij3/8I7797W9j7dq1uP3223conxdffDGOPfbYEdtfe+01/OY3v8GXv/zlHUo3Hb7//e/joIMOQiKRwJYtW/D444/j29/+Npqbm3HttdfusuuOh3Tb/8LCQixevNi47/LLL0coFMIJJ5ww6vX++Mc/4qyzzkJNTQ2uueYaZGZm4tlnn8V5552HpqampOd0zz334I477sBVV12FoqIi3Hbbbbjgggvwj3/8Qx4Ti8Vw4YUX4pJLLsGhhx6a/o3vZtKVKffccw8KCgqSth1wwAFJ/yORCN5++21cfvnl+OEPf5i0b8mSJZgzZw7uuOOOpO0ffPABqqur8aUvfQkFBQXo6urCM888g69+9av42c9+hhtuuGEH7yw1e6MOpTKazB6N0047DV/96leTtgUCgaT/S5cuxdlnn41vfOMbuOKKK/DEE0/g5JNPxvr165GVlSWPu+aaa1BYWIgrr7xyh+5lV9LU1ISWlhacdtppqKiogMPhwMcff4xHH30Uf/rTn7Bq1SoUFRUlnfPTn/4UN910E0444QT89Kc/hc/nQ2NjIz766CPjNdJ5lmNlyZIlAIAnn3wSeXl540rLiv333x8/+MEPAADd3d14+eWXcd999+GVV17BihUr4HK5dsl1d5T6+npcdNFF+MIXvoDvfOc7KCsrQ21tLR5++GE8++yzeOmll3D00UfL43eGzD3yyCON8qWlpQU/+tGPMG/ePJSXlwMA+vv7ccopp6CiogJ33nkn3njjDZx11lmYNGkSDjroIHnuM888g9deew2ffvrpjjyGYcQOsnz5cpGRkSHuuusuAUBcdtllO5qUePzxxwUA8bvf/W6H09iVABA/+clP0jp24cKFIjMzc8T2++67TwAQl19++U7OnRA/+clPBABRV1e3w2l0dnaK7u5uIYQQH3744aj3vHnzZvl71qxZYsKECWO63tatWwUAceqppyZtTyQS4gtf+IKw2Wyiq6tLCCHEI488IrxerxgYGBBCCDEwMCC8Xq949NFHk/Lj8/nE888/P6Z87Cx2Zn3QueKKK0R5ebm48sorBQDx4YcfJu3/5JNPREtLy4jzHnvsMQFA/OAHP0jrOl/60peEzWYzpmViwoQJ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455hj8/Oc/x2233Yaqqir8+Mc/3u3zcEmR14eNXH/99fjWt76FrKws3Hzzzbjtttvg8/nw9a9/HQ8++GDSsVdeeSWuvfZaVFVV4Ze//CVOPfVUXHbZZfj73/8+4npbt27FjBkzcO655+66mxoHkyZNwqRJk6TSX19fj82bN+Puu+/Gs88+i2uuuQZerxcAcNhhh6G7uxu33347Ghsbceutt6K7uxuHHXYYAOB3v/sdPvjgg6Thr7uTdOvDU089ha6uLpx77rm4//778X//939Yu3YtvvjFL+Ltt98ecTwNVzz++OOlITcWmpqaAADFxcXG/b29vejo6MDGjRvxwAMP4Mknn8TUqVMxefLkMV9rR7GqF48++iiOP/54BINBXHfddXKawqWXXoqrrroq6dh7770XF110ETweD2655Racd955uPPOOy3Lw4wZM6SStqOYnm0kEgEA6QBSoW1Lly5NK/2+vj5cfvnluPjii3HwwQdbHnfYYYfhkUcewapVq7Bq1So8/PDDOPzww2V+LrzwQvzf//2fUeDtStKpE+k8L3X+68EHH4xAIIBf/vKXeOaZZ6QxeM0112D58uVGY2DFihU49dRTcdhhh+HOO+/EEUccgV/96ldYtGjRqArZb37zGyQSibSMv53J0NAQGhsbpeAnli9fjgMPPBBvvfUWLr74Yjz44IM45ZRT8Ktf/QrHHXdckpGzdOlSHHvssdiwYQOuvvpqXHPNNVi2bJmlPDj33HMxY8aMpPlou4pgMIi//OUvmDBhAo477rhRjx9rOTnssMPwxz/+Ef/973+xfv163HHHHZgxY4Z8lhdffDG+/OUv45RTTtkJd7NrSFemEPvttx9ycnLg8Xhw+OGH49///nfS/osvvhj33HMPgOGhsYsXL8bixYsxY8YMLF68GAUFBZg+fbrcrhvzXV1daG9vx9q1a/Gzn/1MDusk5/fuYG/QocYrs4m77roLPp8PmZmZqKysxI033ijrAXHYYYdh1apVWLx4MRoaGnD99dfD5XJJI/q2225DKBTCz372sx3Ox+4iHA6jo6MDTU1NePnll+Xc/y996UvymIGBAbz11ls45JBD8MQTT6C8vBxZWVnw+/341re+hdbWVmPa6TxLAHjggQdgt9tx0UUX4cEHH8SFF16It99+GwsWLJCGLE1tOeKIIwBA1pfrrrtuZz8SI6Y6MDQ0hBNPPBE//elPcdhhh+Gee+7Bj3/8Y6xZswYLFixImt8/NDSEE044AY8//ji+9KUv4Y477sDUqVNx7LHHSp1G5bnnnsOMGTPSbodMJBIJtLS0WOqhKjtD5r755pvYtGkTTj/99CT5ecABB8DpdOKGG25AQ0MDfvvb32L16tVSX3rzzTfx29/+Fo899hjs9nHG9R5rF3dtba3w+XzitttuE0JsH26hD1MaGBgQBQUForCwUDQ1NY1IJx6PCyGEeP755wUAUVhYKHJycsQdd9wh/vrXv4rzzz9fABBHHXWUHOoihBDBYNCY1sKFC0V2dnbSkMLBwcGkc4mzzz5b2O120dzcnNY9YweGMbW3t4v29nbR2NgonnvuOTFhwgQBQPzzn/+Uxy5fvlwAENdcc82IdBYtWiSysrLkULV169YJm80mjjnmmKThV8uXLxc2m23EMCZ6L+kO71JJZyi4yo4MBRRieIjIgQceKADIj9PpFA899NCIY6+//npht9sFAGG328X1118vhBCira1N5Ofni1//+tdjvv7OIN36IIS57G7btk3k5+eLk046acS+2267TXi9XlFbWyuE2D5cLd1hZV//+tcFAPHqq68a9x9wwAHyudtsNnHcccclDakcjR0ZCr5+/XrR3t4utm7dKpYsWSL2228/AUA8+OCD8tjm5mbhdrvFGWecMSKd73//+8Jut8t8dnd3C5/PJ2bMmCGnCgghxJYtW0RmZqZx+BWAcQ152rp1qwgEAmLixIlJ7c2vfvUrAUDcc889SccPDAyI0tJSAUDcddddaV3jkksuESUlJaKnp0cIYT2Uft26dWLKlCnyPU6ZMkWsX79eCDE8LHzSpElicHBwh+91R0i3Tnz00UcCgFi0aNGINBYtWiQAiC9/+ctJ29966y0xderUpDYjKytLPPfccyPSoP36vu9///sCgPjjH/9oeQ/xeFxUVVUJv98v+vv707txsWNDwZ988knR3t4uWltbxbJly8TXvvY1AUB8/etfTzp+v/32E9OmTRsxfPnZZ58VAMRvfvMbue2www4TTqdTl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iGeffVace+65wm63jzA2L7300lHrBQUvufXWW6URrnPvvffuVMM6FAqJ4447TtjtdrF48WLjMR999JHYf//9k/K6cOFCcf311wsA4r777kt5jUgkImbOnCmOO+64pO2pDGudRCIhDj/8cPlu/vSnPwmPxyP+8Ic/iLfeektMnDhxhAd+ZzHWOtHV1SW++tWvJrXP1dXVMvDeaaedJo/96KOPhMfjkb0yxMDAgKipqRETJkxI6oUARgZHJAKBgDjwwAMt74NGe7z33ntp37sQO2ZY33jjjWLJkiXixRdfFDfeeKPweDzilFNOEZFIRB5LDqRUn2OOOUYIIcR7770nAMhRPSrU6/NZGdaffvqpACBOOOGEMV0jFAqJiy66SDgcDnm/hYWF0lEwb968UdP41re+JUfAvf/++8Jms4n7779fLF26VBx00EHGUUO7m7HWHytuuummEfrXeAxrnW9961uipKRkVBlN7As61Hhk9mjU19cLAMZRXDqPPPKIKCgoEO3t7aKvr08UFRWJCy64QCxfvlx85zvfEUVFRXt00D4hhFi9erVwuVxJToply5YJYHjEYjgcTjqeArelcpYSVs9yxYoV4uSTT5Yj3dRPTU1N0rG7w7A+5JBDxJIlS8TLL78sHn/8cTFz5kxRVFQkVqxYkXSs1+sdtQ6QETlt2jRRUVFhvOb++++/Uw3rZcuWiUAgIGpqaoyjlnV2VOaqUO/4rbfemvY5H3/8sXC5XOK1114TQghx4oknioMOOkgsXbpU3H///cJms41wZoxG2sttRSIRXHnllfjSl76EkpISbNq0CQDknKze3l5s2rQJBQUFYwqCVVFRAQDG4EulpaUAkgMYnHnmmXjxxRdx0UUX4cgjj0R+fj4yMjLwr3/9C/fcc0/SvLkrr7xSrs143XXXoaioCE6nEytWrMDVV1+dVtCDHSEjIyMpjPzXvvY1nHLKKbjoooswf/587LfffgAAIQRsNhv+/e9/WwYW2p1Bc3Ynjz76KDo7O/H1r389aTsFhnr//fexYsUKy7mwAwMDuOSSS3Dddddh+vTpePfdd/HJJ5/gueeew+TJkzF//nz89re/xR/+8AcZ6GJnMtb6EAwGceSRR2JgYAB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yZQp8Ph/y8/Nx3nnnGe2I3YVTXXHTTTfFhV29erV17u2333aM88wzz4w7tmDBAmRmZu729EciEfz+97/HvHnzUFBQgIyMDFRWVuK0007DzTffvNvvtzdI35WLrr76auTl5WH27Nno6OhI6ZrHHnss4dgRRxzheM33v/99Y0NJPPDAA7j88ssxZ84c/OxnP0MwGMRHH32EO++8E08//TSWL1+OYDAIAPjoo4/Q0dGBBx98cLeKCI7P58Of/vQnAEA4HMaSJUvw8MMP46WXXsLixYsxadKkPXLf0XD55ZcjKysLZ511FiZNmoS2tjY8/PDDOP3003HDDTfgmmuuscKGw2HMnz8fy5YtwyWXXIKjjz4atbW1uPfee/HGG29g0aJFKCkpcbzf5s2bcfnll+O4447DN77xDZSVlWHTpk2477778PTTT+Nf//oXTjjhBCv8ZZddhiVLluBXv/oVmpqacPPNNyM3Nxc//vGP4+L81a9+hUcffRTZ2dm7/yU5sKfLwjnnnJOQX3NycuL+H+k73bRpEzZt2oTbbrsNV155ZUpp3hXuu+++hIpY/31WrFiBRYsWobq6Gn//+99x9913W2V2XzM0NIRf/OIXeOaZZ/Z1UlLmgQcewB/+8Ie4Y88++yweeeSRfS6uR1pWvv71r+ORRx7Beeedh69+9atwu92ora1FXV1dQthXXnkFZ599Nqqrq/GDH/wAxcXFaGpqwvvvv4+uri4UFxdbYe+44w786Ec/wvz583HXXXehvr4et99+O95//30sWrRov8h/hx12mFXHtbe349VXX8Vdd92F119/HUuXLoXX693HKUzkiSeewF/+8hdMnz4dU6ZMwccffzziOF566SXce++9mDx5MmbNmoX33nvPNuz+3jZwUs37hYWFxvYBAK688kqEw2F89rOftY61tLTguuuuQ3FxMebMmWPsRCKi0SgWL16MY489FhdffDFCoRC2bNmChx9+GEceeST+9a9/4cQTT9zlZ9xdlJeX48YbbwQw3HHw9ttv4+GHH8bLL7+M5cuXIz8/fx+n0Jnt27fj5z//OTIzM9HT02MMc9VVV+Huu+/GOeecgx//+MdYvXo17r77bixbtgyvv/463G7nMa/6+no0NDT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C6XOvfcc+OO33333QqAeuKJJ3b53n//+98VAHXzzTdbx/7whz+ojIwM1dvbq5Qatu8yMjLU/fffb4XZuHGjCgQC6tlnn93le+8NRluOTAwMDKg333wz4fiOHTtUfn6+KioqUkNDQ9bxuro6o232zDPPKADq8ssvT0hzRkaGOumkk1JKz+5qL3Si0agqKipSX//619VVV12lgsGg6urqSjlOO40zGp566ikFQP3whz80nm9oaNit99tb7JIr+Pjx40d8jVIKXV1diMViScN2d3fje9/7Hr7zne9g3rx5tuG6urqQm5sLv98fd7ysrAwArJGHqqoqXHrppQCAE044wXKF2BucdNJJAID169cnnPu///s/HHfccQiFQggEAjjyyCONbq2xWAw33ngjxo0bB7/fj+nTp8e5g3EGBgawZs2alN2mTD3UgUAAZ555JgYGBrB27Vrr+MKFCwEMjxRwjjnmGEyYMAF/+9vfEIlEHO+Xn5+Pww47LOH41KlTMX369Di3+f7+fsRiMeTl5VnH8vLy4tylnnjiCbz33nu45557nB90D7GnywIw7CrT19dne34k73TBggWYP38+gOHfkcrCvpizEo1G8fjjj+P888/HUUcdhcMPPxwPPvjgHrnXmjVrsHHjxhFdc+211yIQCOC//uu/Ugo/ODiIm2++GVOnToXf70d+fj7OOeccLF++fFeSDGCna+h1112HF154wXKzLS0txU9/+tMEjx59vuCCBQvwyCOPAIh3GdsXcx5TLStKKdx4442YPXs2Lr74YgDDbYJSyhj+D3/4A9ra2vC73/0OHo8HfX19GBgYMIZ99tln0dfXh+9///tIS0uzjn/+85/H+PHj8fjjj8eFH0ndu6c5+eSTASS2Jf39/fjtb3+LadOmwe/3IycnB5///OeN7r3t7e341re+hYKCAgSDQSxYsABLliwx3q+zsxNr1qwxurKaGDNmzKhHEoqLi1PyGDgQ2gbOrrQTHPKE++Y3vxl3nKY8jIaioiL4/X60t7fHHV+zZg2++93vYtq0aZaNMmfOHCstexM7O0ophfvuuw9z5sxBIBBAZmYmTjjhBMtW4UQiEfz0pz9FWVkZMjIycMQRR+DVV1813q+vrw9r1qwxulU78cwzz+C5557DH/7wh7j6hfPXv/4VSin88Ic/jDv+rW99C4FAIKEOGgljx44FgLjfMhwOw+/3IxAIABi27/x+f1xZueKKK3D66afjrLPO2uV77w1GWo5ef/11nHrqqcjJyYHf78fMmTMTPLrS09Mtm4hTXFyM+fPno6mpCU1NTQCG21d6x7/+9a+t9vTNN9+0tY/Hjx+P448/Hm+88cY+nc7w/PPPo6mpCZdeeim+9rWvobe3F//3f/+32+8zknaDyjOVbx3dA9Y0x5qOrVq1Cj/84Q9RWlqKQCCAk046ydIvTz/9NGbPno2MjAxUVVXh/vvv38WnS429tnhZdnY2srOzkZGRgVNOOcV27gIA/OIXv8DQ0BB+85vfOMb52c9+FqtWrbJcabZu3Yqnn34a119/PebPn2+JxjvvvBOXX345gGFXkscee8zW3Wp3Q8Y8NwCAYZeGL33pSwiFQrj++utx0003IRAI4IILLsC9994bF/ZHP/oRrr76alRWVuJ3v/sdzj77bHzve9/Dc889l3C/bdu2YcqUKbjkkktGle76+noAiHOh7O/vBwCrguYEAgH09vbusoiIxWJoaGiIu19OTg4mT56MW2+9FWvXrsU777yDv/zlLzjmmGMAAK2trbjqqqtw0003YcyYMbt0333BSMrCbbfdhkAggGAwiIqKCvzqV7+yfodkmN7pNddcg6uvvhrA8DQAKguFhYWjeygDbW1taGlpifvjguef//wnWlparE6vr33ta3j33XfjOnN2F1OmTLGtvO0oKSnBVVddhXfeecdY1nS+8pWv4Oc//znKy8txyy234IorrsDChQtx9NFHj3oO40svvYSvf/3rOP3003HHHXdg1qxZuPXWW/G73/3O8bprrrnGcvei33p3ry+xu1m7di02btyIY445Btdffz3y8/ORlZWFnJwcXHHFFQnulS+99BKysrLQ0dGBww47DMFgEH6/H8cffzw++uijuLD0/9FHH51w36OOOgpr1qyJi38kde+extSWDAwM4LTTTsOvf/1rHH300bjjjjvw85//HKtWrcKxxx6LxYsXx4X97Gc/iz/96U/43Oc+h1tuuQUTJ07EySefbNX3nGeeeQZTpkzZL4SpzsHaNpjo6enB3//+d4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/12muvxf21tLQopZTasmWLcrvdCUb+2WefrUpKShKMvH0xx/qjjz5SSu1sgB588EGllLlO+s53vqMAxBl+/JkAqKamJsf7Ognriy66KCH8lVdeqQCo7u5u69jBIKwfe+wxq/7UO5zoWV566SXrGHWsfuUrX4kLS+/zwgsvtI6deOKJCkDcnDniv//7vxUAa72C3VX37i5Dafbs2eqDDz6ICzt79uw4IcL/vv71r6u0tDSrE+H0009XaWlpqrOzMy6OSCSisrKydst8RWJvCGulDpy2gTPSduKoo45Sbrdb1dXVJQ2birDu6elRr732mnrxxRfVXXfdpebNm6e++93vGoU0EQ6HVUtLi2publa/+c1vFAD16aefJk3PrghrU96vqamJG5xQSqlzzz1XhUIh1djYmJD3r7vuurhOMqqfeScbMWnSpFHXj++8845yuVzqL3/5i3XMTliPHz9eVVRUGOO5+OKLFQDV3t6e0n23bt2qXnvtNfXMM8+oX/3qV+qwww5Td955pzHsjh071Hvvvad27NhhHfvKV76ijj/+eBWLxVRdXZ0666yzVGlpqTryyCON8473J5zKEYnc119/PSFvvPbaa8YOGc66detUXl6eGjNmTEK7bSes29raVFFRkQqFQur+++9XmzZtUosWLVKnn366ZR9ff/31SZ9rV9qLI488MsHW+s9//mOF+c1vfqNcLldcZwINZPzkJz8xxrk35lgrpVR3d7e64YYb1MyZM60OawCqqKgowc51EtavvvpqXNilS5ca7QKllJo5c2bC2kO7k11aFXy0TJgwARdeeCH+/Oc/Y926dZg4cSIA4Oabb8aGDRvw7LPPJo0jFovhtNNOw+DgIN59911rXuH555+P/Px83HzzzfjiF79ozUvbG/j9fjz//PMAht1gH330Ubz22msJc2lXr14NpZRx6yGCVvfctGkTABjDTp061XaO0K7Q1taGU045Bdu3b8eLL75o/S5ETU0NXnzxRXzzm9/El770Jev4ueeeizlz5uC+++5DVlbWiO65ZMkSnHHGGSgrK8OLL76YMF8eGH6vc+bMsf4Ph8P49re/jZ///OeYOnUqbr75Zvz+97/Ho48+CpfLhYsvvhjBYDDlubH7EruyYMc111yDBx54A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9a/jjjvusITjhAkT0NzcjBNPPDHp3rfjx4/Hq6++iq6urriRk/7+fmzatMnq4T9QOdjahmg0ai0suadXa6aFg9ra2lBdXY2Ojg688MILuPjiixNWUX799df3aFp0/H4/7rjjDpx44om49tprrRV9J0yYgHXr1uGoo45K6rFD9fO6desSBi1odHNXqaurQywWszxodI444ggEg0FrUcR58+bh1VdfxaJFi+L2EY5EIvj4449HvbBkOBxOWLhK51e/+hWCwaC1RzDVq1RWXC4XysvLD5iyokMC0mkkV2fz5s1YsGABOjs78frrryfsAT0Sampq4tqXl19+GVlZWSkJxN3NQw89BJ/Ph0cffdTYRnz729/Ggw8+uF8Ia85RRx0FAEY7YH9nj64K3tvba9x+admyZXjyyScxZcoUy2AZN24cnnzyyYS/6667DgBwySWX4Mknn7RWMiRh98QTTyRsrUJbyTht1bW3mDBhAi666CK89tpr1ip0tIXM1VdfbewY4C4qX/jCF+ByuXD77bfHhV26dKmxgRvpdlvt7e045ZRTsHLlSvzjH/+wbRycuPrqq9Ha2oprrrkm7nhLSwvWrFmDzs7OuOPLli3DKaecgszMTCxcuDBlwTE0NIRvfetb+MY3voHjjjvOOl5WVha3Gvny5cv3i1EnzkjKAjDsoaETi8Xwy1/+EsDw9kB6PLvyTvcFDz74INLS0nD11Vfj/PPPT/j7wQ9+gMHBQTz66KO77Z67st0Wx+Vy4aabbkJHR4dxRVxqlG688ca4ntAVK1bgueeew3HHHbfPRg7J6ExmbO0vBAIBnHfeedixYweeeeaZuHP33XcfgPhVb6k+1QXA888/j23btsWFPeuss5CRkYF77rknrj59/vnnsWnTprjpFSOte/c0F198McaPH49bb70VXV1dAIbbxR07dtiOWPO25KyzzsLQ0BBuu+22uDD33XefFR9npNttjYTdHfeB3DbY8dxzz6G5uRkXX3wxPB7PqONrbm42jjLv2LEDTz75JDIzMy3RSaM8+qhOQ0PDPtlu64QTTsBnPvMZ/PnPf0ZtbS2A4bwfi8VsR1T1vA8At9xyS1yYZ5991ugGPpLtti677DKj7bpgwQIA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4Bb71rW/hrrvuwn//93/j//v//j+89tpr+OlPf4p///vfOPHEE5GVlYUtW7bgjTfegN/vj9tf9f7778f//M//oLa21toG7sknn0R1dXWCh9czzzyDyy67DNdee23cO7Tj008/tbY4evfddwEM/+bUofz9738f2dnZjnHX1dVZW2GuXLkSwHCnB42oXXzxxUZPnP2xbeCMJO8TqbqB33PPPejo6AAw3LFeV1dnxT1r1iyrE/aJJ57AnXfeiXPOOQfjxo2D1+vFunXr8Mgjj6C9vR1/+tOfrLm9oVAIp556Kh5//HFkZGRg3rx5qKurwx//+EeMGzfO2PG7p/nv//5vnHLKKbjhhhvw4IMP4vzzz8dll12Ge+65B0uXLsWZZ56JgoIC1NfX4/3338eGDRusdRI++9nP4vOf/zweeeQRtLW14bTTTsPGjRvxxz/+EdOnT8eKFSvi7rVo0SKccMIJuPTSS62BGjtmzZqFWbNmJRx/4YUXAAx3gvO1RmbMmGHVK+eeey4+97nPYfXq1bj77rsxf/78hHU8TjrpJNTV1cV1cnznO99BQ0MDTjzxRIwdOxaRSARLlizB3/72N4RCoYTOM2JwcBDf/OY3cfnll8dtOXjkkUdiwoQJuOSSS3DllVfi5ZdfRldXV9xaOvsDqZaj8vJy3HffffjmN7+JKVOmWPVGc3Mzli9fjmeffRarVq1CVVUVuru7ccIJJ2Dz5s34/ve/j7Vr1yZ0tpxyyikpec997nOfw/jx4zF16lS4XC68+uqrePbZZ3HGGWckDDztDf76178iHA7jvPPOsw1z3nnn4c9//jMeeeQR/PznP3eMb2BgwHrfOueeey6mTp06onbj9ddfx9VXX41TTz0Vxx57LEpKStDZ2Yk333wTzz33HEpLS/GjH/0o6XPud+zKimd2K2AD8ds8NTQ0qK9+9atq0qRJKhQKqfT0dFVRUaEuueQStXr16pTu5bQqeH9/v7r55pvVzJkzld/vV16vV02YMEH94he/SFjhcm9tt2XHl770JQUgbqXFF154QZ166qkqNzdXeb1eVV5erk477TR13333xV07NDSkbrjhBlVZWam8Xq+aNm2aevzxx40r5I10uy2735H+9NU8v/e976kJEyaojIwMFQqF1PHHHx+3EiaH0sfjoN/T6c+00u6mTZtUIBBQTz/9dMK5/v5+9aMf/UgVFxer4uJiddVVV6W8XcVo2VNl4U9/+pOaP3++Ki4uVh6PR2VmZqojjzxS3XvvvQkrGo/0ne6tVcH11VCVUuqee+5RANTdd9/tGMfll1+uAKh3333XNk4q03Z/fHcBYNe229JZvHixtXKlXicNDAyom266SU2ePFl5vV6Vm5urzjrrrJRWz1XKeVVwUz1kKv+mFcCHhobUj3/8YzVmzBhry5WR/Pa7i1TLClFbW6suuugiVVBQoDwej5o8ebK69dZbjSt607ufOHGi8nq9qrCwUF188cVx22xwHn74YTVz5kzl8/lUYWGhuuyyy+K2sSJGUvfasSurvOorshLRaFRVVlaqnJwca1ufgYEBddddd6m5c+da247V1NSoiy66yNpdgmhtbVVf//rXVV5engoEAmr+/Pnqo48+UvPnzx/1dlvJyiN/V3ZxJ6vLTO9wf20bOCPN+7RrwjHHHJM0bruVtIH47aIWL16svvKVr6iamhoVDAaVx+NR5eXl6sILL7TqWU5zc7P6xje+oUpLS5XP51PTp09X999//4hsqV1ZFXzatGm254866iiVnp6uNmzYYB179NFH1XHHHadCoZDy+Xxq7Nix6pxzzrG2bCX6+vqsvOD3+9W8efPUK6+8Yqwzd2W7LR2ndnBwcFDdeuutVn1VVlamrrrqqrgdHgj6fTn/93//p8444wxVXl6ufD6f8vv9atKkSerKK690XD3+5ptvVuXl5dZ2rpw1a9aoE044QWVmZqpp06ap559/fheees8y0nL0zjvvqLPPPlsVFhYqj8ejSktL1YIFC9Stt95q7ZZCeTTVesepTf6f//kfNW3aNBUMBlUwGFRz585V995774h2Itid7cXcuXNVenq6amtrs70+EomoUCikJk6c6Bin07sHoP76178qpUbWbtTW1qobbrhBLViwQJWXlyuv16sCgYCaOnWq+tGPfqQaGhriwjutCq63xU6/k6m92524lDrIVr7ZjbhcrpR76wXhYKaqqgoLFixI2nsvCEI8b775Jk444QQsXLjQcg8VhEOBzZs3Y9y4cX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+/3o7i4GEuXLsVjjz025NjRyp59lf1VXgDAb37zG5x//vmYPn06PB7PsM6E0fR3TjzyyCM44ogjEAqFEA6HcfTRR+OZZ54Zclx3dzeuuOIKFBYWoqioCF/60pes9eJvf/sbQqEQNm/ePKr72FuMpg0ppfDggw/ic5/7HCorKxEMBjF+/HicfvrpeOuttxyv0draim984xuorKxEeno6CgoKsHTp0pR9MAB8+9vf1vXVZGBgAOeccw42bNiAH/3oR3jggQdw9tln79pLsED9o+1v+vTpQ45ftGgRXC4XvvCFLwxbJu9z//CHP8DlcuHRRx/dbfdOvPrqqzj99NMxYcIE+P1+FBYWYv78+bj66qtRXV2926+3r7MrOtRocNKLRsPzzz+PL37xi1iwYAHS09P3ioFs1m+/34/Kykpcc801aGlp2aPXHgujeVdPP/20bgvBYBA5OTk47LDD8Itf/AJ9fX0jvqZTn2Dro55//nnMnTtXy9sXX3xxyDHxeByHHXYYvvzlL4/4Hjhpu3LSsmXLcOedd+L000/H+eefD6/Xi5deegnf+9738Je//AVvvvkmAoFA0oPQebm5ubt0oyZXXXXVPql8nHvuuTjllFOglEJDQwPuv/9+fP3rX8dHH32E3/72tx/37Q2hra0N69evx4knnoiKigoEAgFs2LABy5YtwyOPPII333wTM2fO1Me3trbiqKOOQmNjI77+9a+jrKwMDz30ED7zmc9g2bJluOSSS4a95i9+8Qt0d3cP2X7nnXfizTffxGmnnaa33Xbbbbj11lvxzW9+E4WFhbjllltw6aWX4qmnntLHDAwM4LLLLsMXv/hFHH744WN8I6OjtrYW9fX1OOuss1BWVoa0tDSsWrUKv/3tb/HnP/8Z77//PgoLC/XxmzZtwhFHHIG0tDR861vfQlZWFn73u9/hk5/8JJ599lkcf/zx+thYLIYTTjgBK1aswFVXXYUZM2bg2WefxZe//GXs2LEjyZMdjUbx2muv4corr8Q3vvENvV0phTPOOAPPPvsszjzzTFx11VVoamrCXXfdhcWLF+P1119P+n13J4ceeij+53/+Z8j2uXPnJn2/9957EQ6HEQgEsGzZMhx99NF75H52h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374IR544AH09/dr5Zb4zne+g0ceeQTnnXcevv71r6O0tBR/+tOf8M477+Cee+5JWkv67bffxtKlS3HxxRdb1wG+7777MDAwMOLR6rfffht33XUXXnvttaQ1TS+44ALce++9uOiii7BgwQLccsstWLp0qQ5525N86UtfQn19PT7xiU+goqICfX19WL58Of785z8jHA4P6bxuvvlmvPjiizjxxBPxta99DZmZmfjd736Huro6PP3000kjb5dddhl+//vf4+tf/zpqamowY8YMPPPMM3jsscfwve99DxMmTBjRPZ5yyimYNGkSZs6cCZfLheeeew6PP/44Tj311CFzT/YGf/rTn9Db24tzzjnH8ZhzzjkHf/jDH3DffffhO9/5Tsry+vv7ceONN1r3nX322Zg5cyYee+wxXHLJJfjBD36QtC7oaLnxxhvx17/+Fe+9996QfTfddBOef/55nHnmmfjyl7+MyspKvPrqq3j44YdxzDHHOIbx7g0OP/xwvPDCC/jJT36C8ePH65C3PcFo2sSGDRuwZMkSfPrTn8a0adOQm5uLuro6/OlPf8K6detw8cUX6+UagdHJnqOOOgrjxo3D//zP/6CmpgZlZWV4//338cADD2D27NlJxpXL5cLvf/97HHfccVi4cCG+8IUvYNasWWhvb8crr7yCk046CVddddUeeV8m+7K8AAbXnidDmcKDqf1lZ2frKTnA6Po7pzZ63XXXYcOGDVi4cCGysrLw3nvv4fe//z1KS0tTLhv317/+FS+88MKQ0dQLLrgAl156Ka655hqUlZXhRz/6Ec4777x9Kgx8NG2oq6sLS5cuRU1NDa666iqsW7duyHJOJ5xwgh4FzcnJwU9/+lNcccUVOPzww3HppZciFovh7rvvRiwWS1pqxrZUGjC4nOmWLVsc86J8HLS3t+Nvf/sbjj76aEfj9Oijj0ZhYSGWLVuW5Jx34q9//as1+mPy5Ml6SdIZM2agoqJi2PW6e3p6cOyxx2LWrFk46aSTMGXKFCilsHbtWtx///3o6+vDnXfeuU/Vw73BaHUoYPD9X3/99fjwww8xb948LF++HMuWLcP06dNx9dVXD3vNs846C7fddhtOOeUUXH755fD5fHj++eexcuVKq4Nt5c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IYyBhLYQQQgghhBBCHAMJayGEEEIIIYQQ4hhIWAshhBBCCCGEEMdAwloIIYQQQgghhDgGEtZCCCGEEEIIIcQxkLAWQgghhBBCCCGOgYS1EEIIIYQQQghxDCSshRBCCCGEEEKIYyBhLYQQQgghhBBCHAMJayGEEEIIIYQQ4hhIWAshhBBCCCGEEMdAwloIIYQQQgghhDgGEtZCCCGEEEIIIcQxkLAWQgghhBBCCCGOgYS1EEIIIYQQQghxDCSshRBCCCGEEEKIYyBhLYQQQgghhBBCHAMJayGEEEIIIYQQ4hhIWAshhBBCCCGEEMdAwloIIYQQQgghhDgGEtZCCCGEEEIIIcQxkLAWQgghhBBCCCGOgYS1EEIIIYQQQghxDCSshRBCCCGEEEKIYyBhLYQQQgghhBBCHAMJayGEEEIIIYQQ4hhIWAshhBBCCCGEEMdAwloIIYQQQgghhDgGEtZCCCGEEEIIIcQx+H890lhFuaLkdAAAAABJRU5ErkJggg==", + "text/plain": [ + "
" + ] + }, + "metadata": {}, + "output_type": "display_data" + } + ], + "source": [ + "import os\n", + "import trimesh\n", + "\n", + "# --- 1. Create a lookup dictionary from previous results ---\n", + "# This makes it easy to find the reduction % or specific failure status for each instance\n", + "instance_status = {}\n", + "\n", + "for data in successful_instances:\n", + " # Store the reduction rounded to 1 decimal place\n", + " instance_status[data[\"instance\"]] = f\"Red: {data['reduction']:.1f}%\"\n", + "\n", + "for inst, reason in failed_instances:\n", + " # Mark as specific failure type based on the 'reason' string saved earlier\n", + " if \"init\" in reason.lower():\n", + " instance_status[inst] = \"FAIL: No Init\"\n", + " else:\n", + " instance_status[inst] = \"FAIL: Sim\"\n", + "\n", + "# --- 2. Load meshes and generate titles ---\n", + "mesh_list = []\n", + "title_list = []\n", + "\n", + "for inst in instance_list:\n", + " mesh_path = f\"/scratch/cvlab/home/seiler/smoothSDF/simulations_car/meshes/{inst}/{METHOD}_{THRESHOLD}.obj\"\n", + " \n", + " try:\n", + " # Load the mesh\n", + " mesh = trimesh.load(mesh_path)\n", + " mesh_list.append(mesh)\n", + "\n", + " # Build the title: First 5 chars + Status\n", + " short_id = inst[:5]\n", + " status = instance_status.get(inst, \"UNKNOWN\")\n", + " title = f\"{short_id} | {status}\"\n", + " title_list.append(title)\n", + " \n", + " except Exception as e:\n", + " # If the file doesn't exist (e.g., because it failed and wasn't generated)\n", + " print(f\"Could not load mesh for {inst[:5]}: File not found or invalid.\")\n", + "\n", + "# --- 3. Render the grid ---\n", + "# Note: Ensure 'viz' is imported and defined in your environment before calling this\n", + "fig = viz.plot_render(mesh_list, titles=title_list, max_cols=5, axis_on=False, h_pad=1, figsize=(10, 8))" + ] + }, + { + "cell_type": "markdown", + "id": "09574bc9", + "metadata": {}, + "source": [ + "# Computing the error of the surrogate" + ] + }, + { + "cell_type": "code", + "execution_count": 35, + "id": "71b6cfb2", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "\n", + "=== ERREUR SURROGATE VS SIMULATION ===\n", + "Inst: 1f191 | Sim: 0.19250 | Surr: 0.17634 | SE: 0.016157\n", + "Inst: 2236a | Sim: 0.31097 | Surr: 0.21371 | SE: 0.097252\n", + "Inst: 20a3d | Sim: 0.30323 | Surr: 0.28921 | SE: 0.014013\n", + "Inst: 48862 | Sim: 0.28121 | Surr: 0.23523 | SE: 0.045980\n", + "Inst: 292f6 | Sim: 0.25348 | Surr: 0.23948 | SE: 0.013998\n", + "Inst: 4c6aa | Sim: 0.27129 | Surr: 0.25010 | SE: 0.021196\n", + "Inst: 4a423 | Sim: 0.30318 | Surr: 0.28168 | SE: 0.021499\n", + "Inst: 498b7 | Sim: 0.26374 | Surr: 0.22756 | SE: 0.036182\n", + "Inst: 45ff3 | Sim: 0.27601 | Surr: 0.19598 | SE: 0.080026\n", + "Inst: 365af | Sim: 0.24850 | Surr: 0.23657 | SE: 0.011929\n", + "Inst: 1548f | Sim: 0.27059 | Surr: 0.27909 | SE: 0.008497\n", + "WARNING (/scratch/cvlab/home/seiler/smoothSDF/simulations_car/simulations/1552f1a6521bb54a4bb135bcd06914d/SGO_30_sim): iteration number is incorrect (0!=2000)!\n", + "Inst: 1660d | Sim: 0.47129 | Surr: 0.29378 | SE: 0.177513\n", + "Inst: 1713a | Sim: 0.26496 | Surr: 0.28358 | SE: 0.018624\n", + "WARNING (/scratch/cvlab/home/seiler/smoothSDF/simulations_car/simulations/1e2f9cb6b33c92ea82381b04bbe0ce6d/SGO_30_sim): iteration number is incorrect (0!=2000)!\n", + "Inst: 2fe4a | Sim: 0.22222 | Surr: 0.25709 | SE: 0.034873\n", + "Inst: 300f9 | Sim: 0.34564 | Surr: 0.32091 | SE: 0.024729\n", + "Inst: 332ac | Sim: 0.34314 | Surr: 0.26667 | SE: 0.076473\n", + "WARNING (/scratch/cvlab/home/seiler/smoothSDF/simulations_car/simulations/3264f78bfc3bc58c9213ea6cb12e4e3c/SGO_30_sim): iteration number is incorrect (3!=2000)!\n", + "Inst: 3bfa1 | Sim: 0.27574 | Surr: 0.20663 | SE: 0.069110\n", + "\n", + "========================================\n", + "MEAN SQUARED ERROR (MSE) GLOBALE : 0.045179\n", + "========================================\n", + "\n" + ] + } + ], + "source": [ + "import json\n", + "import numpy as np\n", + "\n", + "# --- 1. Configuration des méthodes ---\n", + "methods_dict = {\n", + " \"GD\": \"optimization_base\",\n", + " \"FMG\": \"optimization_sdedit_3\",\n", + " \"DFLOW\": \"optimization_DFlow_test\",\n", + " \"ICTM\": \"optimization_ictm\",\n", + " \"SGO\": \"optimization_sds_1e-3\",\n", + " \"OURS\": \"optimization_base_fm_test_3\"\n", + "}\n", + "\n", + "method_folder = methods_dict[METHOD]\n", + "\n", + "# --- 2. Listes pour stocker les erreurs ---\n", + "squared_errors = []\n", + "\n", + "print(\"\\n=== ERREUR SURROGATE VS SIMULATION ===\")\n", + "\n", + "for inst in instance_list:\n", + " # Récupérer le drag de la simulation optimisée (la vérité terrain ici)\n", + " opt_drag_sim = get_Cd_sim(f\"{SIM_FOLDER}/{inst}/{METHOD}_{THRESHOLD}_sim\")\n", + " opt_drag_sim = opt_drag_sim - 0.15*opt_drag_sim\n", + " \n", + " # On ignore seulement si la simulation optimisée a crashé (drag < 0)\n", + " # Cela permet de garder les instances qui ont eu un init_drag = -2 mais un opt_drag valide\n", + " if opt_drag_sim < 0:\n", + " continue\n", + "\n", + " json_path = f\"/scratch/cvlab/home/seiler/smoothSDF/experiments/car/vecset_vae_256_8/optimization/{method_folder}/{inst}/history.json\"\n", + " \n", + " try:\n", + " # Lecture propre du JSON\n", + " with open(json_path, 'r') as f:\n", + " history = json.load(f)\n", + " \n", + " # Récupération de la valeur du surrogate\n", + " if METHOD in [\"FMG\", \"ICTM\"]:\n", + " print(inst)\n", + " arr = (history[\"volume\"][0] - np.array(history[\"volume\"])) / history[\"volume\"][0]\n", + " print(arr)\n", + " \n", + " # On récupère tous les indices qui dépassent 0.30\n", + " indices_valides = np.where(arr > 0.30)[0]\n", + " \n", + " if len(indices_valides) > 0:\n", + " # Si on a trouvé au moins une valeur, on prend la première\n", + " indice = indices_valides[0]\n", + " else:\n", + " # Sinon, on prend l'indice de la plus grande réduction de volume (le max)\n", + " indice = np.argmax(arr)\n", + " # On l'affiche (le print que tu as demandé)\n", + " print(f\"⚠️ Attention : seuil de 0.30 non atteint pour {inst}. On prend le max à l'indice {indice} (réduction : {arr[indice]:.3f})\")\n", + " \n", + " print(indice)\n", + " drag_surrogate = history[\"volume\"][indice]\n", + " else:\n", + " epoch_threshold = history[\"epoch\"][THRESHOLD_INDEX]\n", + " drag_surrogate = history[\"loss_track\"][epoch_threshold]\n", + " \n", + " # Calcul de l'erreur quadratique (Squared Error)\n", + " se = np.abs(opt_drag_sim - drag_surrogate)\n", + " squared_errors.append(se)\n", + " \n", + " # Affichage pour chaque instance (avec les 5 premiers caractères)\n", + " print(f\"Inst: {inst[:5]} | Sim: {opt_drag_sim:.5f} | Surr: {drag_surrogate:.5f} | SE: {se:.6f}\")\n", + " \n", + " except FileNotFoundError:\n", + " print(f\"Inst: {inst[:5]} | Fichier history.json introuvable.\")\n", + " except KeyError:\n", + " print(f\"Inst: {inst[:5]} | Clé manquante dans le JSON (vérifier THRESHOLD_INDEX).\")\n", + "\n", + "# --- 3. Calcul de la Mean Squared Error (MSE) ---\n", + "if squared_errors:\n", + " mse = np.mean(squared_errors)\n", + " print(\"\\n\" + \"=\"*40)\n", + " print(f\"MEAN SQUARED ERROR (MSE) GLOBALE : {mse:.6f}\")\n", + " print(\"=\"*40 + \"\\n\")\n", + "else:\n", + " print(\"\\n=> Aucune instance valide pour calculer la MSE.\")" + ] + }, + { + "cell_type": "code", + "execution_count": 36, + "id": "6af8358f", + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "0.008812" + ] + }, + "execution_count": 36, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "0.010285\n", + "\n", + "0.012642\n", + "\n", + "0.010461\n", + "\n", + "0.011178\n", + "\n", + "0.009072\n", + "\n", + "\n", + "0.008812" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "e5ffa006", + "metadata": {}, + "outputs": [], + "source": [ + "0.048413\n", + "\n", + "0.052580\n", + "\n", + "0.061052\n", + "\n", + "0.049593\n", + "\n", + "0.045179\n", + "\n", + "0.041774" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.10.6" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} diff --git a/cfd_workflow_20261012/_seiler_ref/setup_meshes.ipynb b/cfd_workflow_20261012/_seiler_ref/setup_meshes.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..e45cb04eb722a7ee2dbd95f816bebbb14b8aeb5c --- /dev/null +++ b/cfd_workflow_20261012/_seiler_ref/setup_meshes.ipynb @@ -0,0 +1,247 @@ +{ + "cells": [ + { + "cell_type": "code", + "execution_count": 27, + "id": "29166b96", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "The autoreload extension is already loaded. To reload it, use:\n", + " %reload_ext autoreload\n" + ] + } + ], + "source": [ + "%matplotlib inline\n", + "%load_ext autoreload\n", + "%autoreload 2" + ] + }, + { + "cell_type": "code", + "execution_count": 28, + "id": "56ef6f5e", + "metadata": {}, + "outputs": [], + "source": [ + "import shutil" + ] + }, + { + "cell_type": "code", + "execution_count": 43, + "id": "1568f037", + "metadata": {}, + "outputs": [], + "source": [ + "instance_list_1 = [\"1f191e0327ce54474cdd04162f008888\",\n", + " \"2236a1b9cde71eff13d31c5a107f3c4\",\n", + " \"20a3df3de67f309d8e35db9103756ad5\",\n", + " \"48862b67f5932cd4473f10e6caaeca56\",\n", + " \"292f6606c6072b96715e04edb8af9c53\",\n", + " \"4c6aa3e7a8130295b528c0abff96f586\",\n", + " \"4a423ae9a28afe3588cf40718544e7cc\",\n", + " \"498b7c799350d1f7c4acded0fc8a9118\",\n", + " \"45ff3c9bc849f2e33a2844e8778fdc6\",\n", + " \"365af82203c96fbca92a4cdad802b45\"]\n", + "\n", + "instance_list_2 = [\"1548f5fb0684d08c63155b8ebc275bd1\",\n", + " \"1552f1a6521bb54a4bb135bcd06914d\",\n", + " \"1660d6b7221223708a49a62fbc70ff9a\",\n", + " \"1713a1ac8aedcc522b12ea83455b0f44\",\n", + " \"1e2f9cb6b33c92ea82381b04bbe0ce6d\",\n", + " \"2fe4a878e34bd3bab8013668e30e23b0\",\n", + " \"300f9c418d6ec9f6473f10e6caaeca56\",\n", + " \"332ac5346c7d3c0f8e35db9103756ad5\",\n", + " \"3264f78bfc3bc58c9213ea6cb12e4e3c\",\n", + " \"3bfa196d1b48f1e0c5dccef20baf829a\"]\n", + "\n", + "methods_folder = [\"optimization_base\",\n", + " \"optimization_sdedit_3\",\n", + " \"optimization_DFlow_test\",\n", + " \"optimization_ictm\",\n", + " \"optimization_sds_1e-3\",\n", + " \"optimization_base_fm_test_3\"]\n", + "\n", + "methods_name = [\"GD\", \"FMG\", \"DFLOW\", \"ICTM\", \"SGO\", \"OURS\"]\n", + "\n", + "threshold = 30\n", + "threshold_list = [0, 10, 20, 30, 40, 50, 60]" + ] + }, + { + "cell_type": "code", + "execution_count": 44, + "id": "8bc8ed58", + "metadata": {}, + "outputs": [], + "source": [ + "import json" + ] + }, + { + "cell_type": "code", + "execution_count": 46, + "id": "067c75ae", + "metadata": {}, + "outputs": [], + "source": [ + "import shutil\n", + "import os\n", + "import numpy as np\n", + "\n", + "opt_folder = \"/scratch/cvlab/home/seiler/smoothSDF/experiments/car/vecset_vae_256_8/optimization\"\n", + "\n", + "instance_list = instance_list_2\n", + "for inst in instance_list:\n", + " for m, name in zip(methods_folder, methods_name):\n", + " mesh_folder = f\"{opt_folder}/{m}/{inst}/mesh\"\n", + "\n", + " if name in [\"FMG\", \"ICTM\"]:\n", + " history = json.load(open(f\"{opt_folder}/{m}/{inst}/history.json\"))\n", + " arr = (history[\"volume\"][0] - np.array(history[\"volume\"]))/history[\"volume\"][0]\n", + " indice = np.where(arr > 0.30)[0][0]\n", + " mesh_file = f\"{mesh_folder}/mesh_{threshold_list[indice]}.obj\"\n", + " else:\n", + " mesh_file = f\"{mesh_folder}/mesh_{threshold}.obj\"\n", + " \n", + " dest_folder = f\"/scratch/cvlab/home/seiler/smoothSDF/simulations_car/meshes/{inst}\"\n", + " dest_file = f\"{dest_folder}/{name}_{threshold}.obj\"\n", + " \n", + " # --- AJOUT : Création du dossier s'il n'existe pas ---\n", + " os.makedirs(dest_folder, exist_ok=True)\n", + " \n", + " shutil.copy(mesh_file, dest_file)\n", + "\n", + " if name == \"GD\":\n", + " mesh_file = f\"{mesh_folder}/mesh_0.obj\"\n", + " dest_file = f\"{dest_folder}/INIT_{threshold}.obj\"\n", + " shutil.copy(mesh_file, dest_file)\n", + " os.makedirs(f\"/scratch/cvlab/home/seiler/smoothSDF/simulations_car/simulations/{inst}\", exist_ok=True)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "d97124a3", + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "[0, 10, 20, 30, 40, 50, 60]" + ] + }, + "execution_count": 38, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "import numpy as np\n", + "\n", + "\n", + "arr = (history[\"volume\"][0] - np.array(history[\"volume\"]))/history[\"volume\"][0]\n", + "indices = np.where(arr > 0.30)[0][0]\n", + "threshold_list = [0, 10, 20, 30, 40, 50, 60]" + ] + }, + { + "cell_type": "code", + "execution_count": 60, + "id": "bd4154fb", + "metadata": {}, + "outputs": [ + { + "data": { + "image/png": "iVBORw0KGgoAAAANSUhEUgAAA8gAAAMWCAYAAAAtZq9dAAAAOXRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjcuMSwgaHR0cHM6Ly9tYXRwbG90bGliLm9yZy/bCgiHAAAACXBIWXMAAA9hAAAPYQGoP6dpAAEAAElEQVR4nOy9d5hlVZX//b05V9WtnKuru7q7mg50A5IchiCCoBIMoyMy6jvDYBoDOI46o4I6IubfYE6gjY4Og3FAFByiwABNB5rOVV0556qbw3n/KNfudXftc6saGjqtz/Pc5957wj77nLPDWmuvvbbDsiwLgiAIgiAIgiAIgnCS4zzaGRAEQRAEQRAEQRCEYwFRkAVBEARBEARBEAQBoiALgiAIgiAIgiAIAgBRkAVBEARBEARBEAQBgCjIgiAIgiAIgiAIggBAFGRBEARBEARBEARBACAKsiAIgiAIgiAIgiAAEAVZEARBEARBEARBEACIgiwIgiAIgiAIgiAIAERBfkHk83ncdNNNWL58OdxuNxwOx9HOkiAIgiAU5aabboLD4UBXV9fRzoogCILwEvKtb30L7e3t8Pl80u6/AERB/gu33HIL3vzmN2P58uVwOBxYtmyZ7bE//vGPcfPNN+PCCy/ED3/4Q2zevBkAsHfvXnzkIx/BRRddhLKyMjgcDtx000226QwPD+Pd7343mpqa4PV60dzcjA9+8IOYmppacOxTTz2FD3zgA3jlK1+JcDgMh8OBO+6448XdtCBo7Nu3D5/61Kdw9tlno6qqCpFIBBs3bsS///u/IxaLqeMsy8Kdd96Jt771rWhra0MwGERzczOuuOIK/N///d+CdPfu3YtrrrkGa9asQWlpKYLBINrb23HDDTdgcHDQNj/33HMPLr74YkSjUQSDQaxatQrvf//7X5J7FwQTS60TxN69e3HVVVchGo0iFArhvPPOw//+7/++qDw8+eSTeNOb3oS2tjZEIhFEIhGsW7cON998M6anp19U2oLwYonH40p2MrXPTzzxBK644go0NjYiEAhgxYoVuO6669DZ2bng2LGxMXz0ox9Fe3s7gsEgamtrcdFFF+E3v/mN8drZbBb/8R//gdNOOw2hUAilpaU47bTT8N3vfrfguN/+9rd417vehfb2doRCIdTX1+Piiy/Gfffdd2QegiDg8PuLu+66C+eeey5CoRAikQjOO+883HvvvS863QcffBDve9/70N7eju985zvYvHkzqqqq1P5du3bhbW97G+rq6uDz+dDY2Iirr74aw8PDR/aBHMe4j3YGjhU+8YlPoLy8HKeddppRQeXcf//9KC0txQ9+8IOC0eMnnngCX/3qV7FixQqcfvrpRYWikZERnHXWWRgYGMD111+PdevWYefOnfj2t7+NRx55BH/+858RDAbV8ffeey+++c1vor29Haeeeioef/zxF33PgqDzox/9CN/85jdxxRVX4JprroHH48GDDz6If/u3f8N//dd/4cknn0QgEEAqlcK1116LjRs34q1vfStaW1sxODiI73znOzjnnHPwk5/8BG9/+9tVun19fRgcHMTVV1+NxsZGuN1uPPfcc/je976Hn//859i2bRuqq6sL8nLzzTfjpptuwqWXXoqbb74ZwWAQPT092LFjx8v9WISTmKXWCQDo6OjAueeeC7fbjY9+9KMoLS3F97//fVx66aX4/e9/j4svvvgF5WHfvn2Ix+O45pprUF9fj3w+j6effhr//u//jv/+7//GU089pfIgCC83n/rUpzA6Omrcd9999+G1r30tVqxYgfe///2orKzE888/j+9973u4++678dxzz6GhoQHAvKJ97rnnore3F9dddx02bNiAiYkJ3HHHHbjqqqvwrW99C+95z3tU2ul0GldccQUefPBBXHPNNXj3u9+NbDaL/fv3o7u7uyAf//iP/4iSkhJceeWVWL16NSYmJnD77bfjsssuw+c+9zn867/+60v3gISThsPpL2699VZ87GMfw6ZNm/DZz34WAHDnnXfida97HTZv3oxrrrnmBaULzOspdF55eXlBHv/whz/gqquuwooVK/CBD3wANTU1GBkZwRNPPIGZmRnU1NS81I/p+MASLMuyrI6ODvV77dq1VktLi+2xF154oXH/+Pi4NTk5aVmWZT399NMWAOvTn/60MY0PfvCDFgDrZz/7WcH2n/3sZxYA67Of/WzB9qGhIWtubs6yLMu66667LADW7bffvuh9CcLh8PTTT1tTU1MLtv/rv/6rBcC67bbbLMuyrEwmYz300EMLjhsaGrIqKiqs6upqK5fLLXq9//qv/7IAWLfeemvB9vvvv98CYH3mM595gXciCEeGpdYJy7KsN7/5zZbT6bS2bt2qts3OzlrNzc3WqlWrrHw+f0Tz9sUvftECYP3iF79Y0vGf/vSnLQDWwYMHj2g+hJOXLVu2WC6Xy/rKV75iAbDe9773Fey/5JJLLI/HY42OjhZs//73v28BsL72ta+pbST/fP3rXy84dnJy0gqFQtapp55asP3f/u3fLJfLZf3v//7vovn805/+tGBbLBazVq1aZXk8HmtiYmLRNARhMZbaXwwNDVler9dat26dlU6n1XHpdNpat26dFY1Grenp6cNOl3jXu95lmVS84eFhq7y83HrNa15TcF1hIeJi/ReWL1++6DEPPfQQHA4HHnzwQXR3d8PhcMDhcOCd73wnAKC8vBxlZWVLut6DDz6IQCCAt771rQXb3/KWt8Dv9+P2228v2F5TU4NQKLSktAXhhXLGGWegtLR0wfa3vOUtAICdO3cCANxuN84///wFx9XU1OD888/HyMgIRkZGFr1eS0sLAGBycrJg++c//3lUV1fj4x//OABgbm4O+XzemMbAwABuvPFGbNy4EdFoFH6/H6eccgpuvfVW5HK5RfMgCMVYap2IxWL47W9/iwsuuAAbN25Ux4XDYfzDP/wD9u3bh6efflpt37NnD9773vdi7dq1iEQiCAaDOP300/GDH/xgyXmzqz/5fB633HILWltb4ff7sW7dOvz0pz9dcrqCsBRyuRyuu+46vOY1r8Eb3vAG4zEzMzPw+/2IRqMF2+vr6wGgQK6ZmZkp2EeUlpYiFAoVHBuLxfD//t//w5VXXokLL7wQlmVhdnbWNq8XXXTRgm3BYBCve93rkMlksHfv3kXuVhAWZ6n9xeOPP450Oq1GgwmPx4O3ve1tmJycLJhWsNR0u7q64HA4lA5BesoFF1wAAPjOd76DiYkJfPGLX4TH40E8HkcmkzkCd37iIQryYbBmzRps3rwZ7e3tqKysxObNm7F582Zcf/31h51WKpWC3+9fEODL6XQiEAigs7MTY2NjRyrrgvCi6OvrA4Alud709fXB6/UajUXJZBJjY2Po6+vDH//4R1V3Lr/8cnVMLBbDI488grPOOgs//OEP0dDQgEgkgnA4jLe+9a0L5sjs2LEDv/zlL3HRRRfhc5/7HL7whS+gubkZH/vYx/De9773Rdy1INij14kdO3YglUrhnHPOWXDs2WefDQAFCvJDDz2ERx55BK973evwpS99CZ/97Gfh8Xhw3XXX4ZZbbjFeMx6PY2xsDD09PfjVr36Ff/mXf4HX613gun3DDTfgE5/4BJqbm/HFL34RV111Fd73vvfht7/97RG5d0EAgK997WvYs2cPvvGNb9gec+mll2J2dhbveMc7sH37dvT39+MPf/gDbrzxRqxZs6ZgkOCiiy6C2+3Gxz/+cdx7773o6+vDc889h7//+7/H1NRUgRv0o48+itnZWZx++un44Ac/iJKSEpSUlKCqqgqf+MQnkM1ml3QPh9O3CcILRS9nqVQKAAqmUhK07cknnzzsdKuqqrB582acd955AKD0FKo79957L0pKSjA1NYWNGzciFArB7/fjvPPOK+ifBIiLtYnFXKzPP//8ovsta3EX6ze84Q0WgAJXPMuyrK1bt1oALADWli1bjOeKi7XwcpLNZq1zzjnHcrvd1p49e4oee88991gArGuvvda4/7bbblPlG4C1bNky68477yw4Ztu2bRYAq6qqyvL5fNanP/1p65e//KX14Q9/2HI6ndaaNWusWCymjo/H40bX1be//e2W0+m0BgYGXsBdC4I9pjrx3//93xYA61vf+taC459//nkLgPXxj39c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ZDK54DoArL/5m79R2zKZjPXZz37WWrlypRoh458f//jHS86PICyGXZ043BHk2dlZ68Ybb7SampoWlFkA1sMPP7xoXu67774FwR6vv/56C4B14MCBBcd/6EMfkhFk4UWzefNmy+FwWI8++qjaZjeCfM0111itra1WPB4v2P7tb3/bAmB9//vfV9vuu+8+y+l0Wr///e8Ljh0cHLRKS0utV77ylWrbl7/8ZQtAwTbiRz/6kW1dtKz5gKqnnnqq5ff7jcG7BOFIUUyGmpiYsN7whjcUyC3Lli1TAeyuvvrqF5SuZdmPIIfDYQuAdf/99y/Y19zcbFVXVx/G3Z3YyAjyUeTNb34z+vr6sHXrVjzyyCMYGBjAd77zHfT19cHtdqOtre1oZ1E4ibnpppvwuc99Du9617vwne98x/a4rq4uXHjhhZibm8P999+P9evXL/kaGzZswKZNm/Ctb31LbWtsbAQARKPRBaNxdXV1AAqDEt1www345Cc/idNOOw2333477r33Xtx///249dZbAcA2uJcgHC7F6gQFFurv719wHm2j5WwA4G1vexu++tWv4vLLL8dPf/pT3Hfffbj//vvx4Q9/GMDSyu2ll16KmpqagvojCC8lqVQKN9xwAy6//HLU1tbiwIEDOHDggFpWaXp6GgcOHMDU1BR6enrw05/+FK997WsXLEP25je/GQDw8MMPq2233norQqEQXvOa1xQcW1tbi/POOw9PPvkk0uk0gEP9RG1t7YI8mvoJYmJiAhdffDH27NmDX//618bgXYJwJFhMhopGo7j77rsxODiIRx55BM8++yw6OjpUX9Le3v6C0i3GYvXGVGdOVmQd5KOMy+UqiHg6NDSErVu34vzzzzdO3heEl4ObbroJN998M97xjncsWO+b09XVhQsuuADT09N44IEHsGnTpsO+ViKRwMTEhPpfU1OD5uZm9Pb2Ih6PF9QDCkjB10zevHkz/vqv/xo///nPC9I9cODAYedFEOxYrE6sX78ePp8PTzzxxIJzKdjKGWecAQCYmprC//zP/+Daa69dIOA88MADh5WvZDJZUH9oRYY9e/ZgxYoVBcfu2rXrsNIWBJ1EIoHR0VHcc889uOeeexbsv/POO3HnnXfiS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OAVr3gFuru78d3vfhetra0YHx8vuMbll1+OiooKnHPOOWhubsb09DQee+wx/OY3v0FjYyNuuukmdWx7ezve97734Rvf+AYuuugivPGNb8TIyAi+8Y1v4NRTT8XWrVtf2gcmnNB4PB686U1vWrC9q6sLALBixYqC/R/60Ifwla98BZs2bcJ1112H8vJy/PnPf8ZPf/pTrFixAv/wD/+gjv3EJz6B++67D29/+9vx0EMPYePGjejr68O3v/1tJJNJfP7zny+45m233YbzzjsPF198MT7wgQ+goqICv/jFL/DUU0/hU5/6FJqbm9Wxr371q/Hss8/ib//2bzE5OYk777yzIK1zzz1XeV8IwgvlcPqLT37yk9i/fz/OPPNMlJaW4tlnn8Xtt9+OhoYGJe+/kHSLcfHFF+Nv//Zv8Z//+Z+4/PLL8brXvQ7d3d247bbbUFdXV9CXnPQc3SnQxw7nn3++MVAKAOv8889fcKwpSBcFqbD78KBaqVTKeutb32otW7bM8vl8VjQatS655BLrvvvuM+bvwQcfLJr2gw8+eOQehnDSQoEdFqsLi5V1vUz+4he/sF772tdajY2Nls/ns/x+v7V69Wrr/e9/v9Xd3W3My+joqPXud7/bqqurszwej9Xa2mp94hOfsBKJRMFxsVjM+shHPmI1NzdbPp/Pamtrs2655RbrgQcekGB2wotmqXWC2LVrl3XFFVdYpaWlViAQsF75ylcaA6KMjo5af//3f2/V1dVZPp/PWrdunfW9733Puv322xfUn29961vWq171KlUXgsGgtX79eutjH/uYNTY2tiDtXC5nfe5zn7Oam5str9drrV271rrzzjutT3/60xKkS3hJsAvSlc/nre9973vWmWeeaYVCIcvtdlstLS3We9/7XmtkZGRBOs8++6z1xje+0aqurrZcLpdVVlZmXXrppbYyzvbt263Xv/71VmlpqeXz+ayNGzca2/zF+ivpJ4QjweH0F7/85S+tc845x4pGo5bP57NWrlxpffSjH7UmJydfVLr8eBOZTMb6whe+YK1atcryer1WVVWVde2111o9PT1H8Ekc/zgsS/PxEgRBEARBEARBEISTEJmDLAiCIAiCIAiCIAgQBVkQBEEQBEEQBE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w+//nPY/369YhEIqisrMS5556LO+64A5ZlveA8vvOd71T1y/RZuXLlC05bEJZCsXpy00032ZbNL3/5ywvSeuc734mHH34Y//Iv/4LNmzfj+uuvBwDceuutuO222/CWt7wFd9xxB77+9a8DAL7yla/gggsuQF1dHXw+H+rq6nDhhRfiV7/61Ut+38LJzd69e3HNNddgzZo1KC0tRTAYRHt7O2644QYMDg4az7nnnntw8cUXIxqNIhgMYtWqVQvqTFdXl22dWbdu3YvK84MPPoj3ve99aG9vx3e+8x1s3rwZVVVVLyrNEwH30c7AscanPvUpjI6Ovuh0/r//7//Dj3/8Y7zxjW/E29/+djidThw8eBDd3d1HIJeC8PJwpOoDJxaL4T3veQ/C4TDm5uYW7P/d736Hm266Ca997Wvxz//8z4hEInjqqafw9a9/HT//+c/x9NNPo7a2Vh3/7LPPIhqN4n3vex+qq6sxNzeHe+65B+9617vw6KOP4oc//OERzb9wclOsTtx666342Mc+hk2bNilj6J133onXve512Lx5M6655hp1bD6fx2WXXYbHH38c73jHO/BP//RPiMfj+M///E+8613vwu7du3Hrrbe+oDxef/31uPjiixds/9///V/cfvvteP3rX/+C0hWEpbKUvuNrX/saKisrC7adfvrpBf9TqRQeffRRvP/978dHPvKRgn33338/1q9fjy996UsF25966iksW7YMl19+OSorKzExMYG77roLb3jDG/CZz3wGn/zkJ1/EnQmCPX19fRgcHMTVV1+NxsZGuN1uPPfcc/je976Hn//859i2bRuqq6vV8TfffDNuuukmXHrppbj55psRDAbR09ODHTt2GNO/+uqr8YY3vKFgW1lZ2YvK8/333w8A+NGPfoTy8vIXldYJhSUotmzZYrlcLusrX/mKBcB63/ve94LS+cEPfmABsH7yk58c4RwKwsvHkaoPOh/60IeshoYG64YbbrAAWE8//XTB/p07d1qDg4MLzvv+979vAbBuvPHGJV3n8ssvtxwOhzEtQXghFKsTQ0NDltfrtdatW2el02m1PZ1OW+vWrbOi0ag1PT2ttj/++OMWAOtDH/pQwTVSqZTV2tpqlZaWFmwHYL3jHe94Ufm/5JJLLADWzp07X1Q6glCMxfqOT3/60xYA6+DBg4um1d3dbQGwPv3pTy/Y19raap1//vlLylMmk7E2bNhghcNhK5vNLukcQThS/Nd//ZcFwLr11lvVtvvvv98CYH3mM59Z9PyDBw/a1oMXy7ve9S5L1MGFiIv1X8jlcrjuuuvwmte8ZoF1hrN161a8+c1vRk1NDXw+H5qamvC3f/u36OjoAABYloVbbrkFp512Gq699loAwOzsrK273J49e/De974Xa9euRSQSQTAYxOmnn44f/OAHC44dGBjAjTfeiI0bNyIajcLv9+OUU07BrbfeKq6kwhFlKfXhj3/8I97ylrdg+fLlCAQCKCsrwyWXXIKHH37YNt1nnnkGt912G77+9a8jEokYj1m7dm3BCDHxlre8BQCwc+fOJd1DS0sLLMvC9PT0ko4XhGIsVicef/xxpNNpXHPNNfB4PGq7x+PB2972NkxOTuI3v/mN2j4zMwMAqK+vL0jH6/WisrISoVDImI8HHngAZ599NoLBIGpra/HBD37Q6Imh093drc5du3btku5ZEA6XpcpSxMzMDLLZrHHfO9/5TrS0tACYH2kjl9I77rgDDocDBw8exMMPP6y233TTTbbXcbvdaGhoQCwWQyaTeUH3JggvFCrHk5OTatvnP/95VFdX4+Mf/ziA+Sk3+Xx+0bSSySTi8XjRY37xi1/giiuuQHNzM3w+HyorK3HVVVcVjEyT2/btt98OAKoeXXDBBYd7eyckoiD/ha997WvYs2cPvvGNb9ge8z//8z84++yz8ac//QnveMc7cNttt+G6665DT0+PEtr37t2Ljo4OnHvuufjsZz+LiooKlJSUoKysDO9+97sXCDIPPfQQHnnkEbzuda/Dl770JXz2s5+Fx+PBddddh1tuuaXg2B07duCXv/wlLrroInzuc5/DF77wBTQ3N+NjH/sY3vve9x75hyKctCylPtxxxx2YmJjA3/3d3+G2227Dhz/8YezevRuvetWr8Oijjy44PpvN4rrrrsMll1yCN73pTYedp76+PgBATU2Ncf/09DTGxsawf/9+fOMb38CPfvQjrFq1Cm1tbYd9LUHQWaxOpFIpAEAwGFywj7Y9+eSTatuZZ56Jsr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pc889V33zm99Ud911l7rxxhv1kJnzzz8/b9iAzT57/vnnlc/nUx/4wAdytl911VUSYm1BJukC8P73vx8rV67Etdde63rMfffdh/HxcXzpS1/CsmXL8vZ7PAud8ZFIBAAwNjaG+++/X0+Uctlll0EphR//+Mf4zW9+g9e97nUAkBNGl0gkEIvFoJTSoao7duzAhg0bAADBYFAfm0qldDjGa17zGtxyyy144oknZPIV4aBZij4AubIbjUaRTCbh9Xrxile8IqenDAC6u7vxuc99Dp/+9KfR1tZ2wHm67rrrcOutt+Kaa67Bueeeaz3mv//7vzE7O4uhoSHcc889GBkZyQlnEoQXy1J0YsOGDbjgggtw11134ROf+ATe8573AFiItKCeMTMsjlY3eNOb3oQzzzwTk5OTuP7663HFFVfgrrvuwgUXXJBzfEdHBy655JKcbf/0T/+Eb37zm7jjjjvw9re/3Zq3+++/H/39/bj66qtRUlJyoLcvCEtiqXXHP/zDP+Rt+9u//VusX78eH/3oR3H55ZcfEjn9xS9+gUQigYGBAdx6662Ix+OIRCIyQ69w2LnkkkvQ2dmJaDSKbdu24e6778b4+Ljez32FG264QUf2XHrppSgrK8PnPvc5/PjHP8YHPvABAEBrayt+97vf5Vzj6quvxjXXXIMbbrgBP//5z3MmgST7TCmFSCSCVCqF2tpadHR04PHHHz+s937McIQd9CPOzTffrBzHUX/605/0Nlur55e//GUFQN13330F07vtttsUALVs2bK8fb///e8VAPWJT3xCb4tEIupjH/uYamlpyWltos9DDz2kj02n0+rzn/+8am9vV47j5B374x//+GAehSAsWR+UUqqrq0u97W1vUxUVFXmy6DhOzrHnn3++OuGEE3IiIpbag3zDDTcox3HU61//+pzzF+Of/umfVCgUUl1dXUs+RxBMDkQnJicn1Zvf/Oac8nnFihV6grlLL71UH/vMM8+oQCCgvvOd7+SkEYvFVFtbm1q+fHlOrwAAdckll1jzWFFRoU455RTXe6Doi0cfffSA7l0QlsqB6Ikbn/3sZ/PsrIPpQTZ5+9vfrhoaGtTk5OSSzxGEQ8HTTz+tfD6f+s///E+ll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/jta99La6++mps3LgRzc3NqKmpwXXXXYcrr7xSt/AQSik4joNQKITLLrsMP/3pT3HHHXdo4x8AvvOd7wDYbyR5vV59LmdoaMi6zJPX6807NhaL6VkeBeFgOBB92LVrF4B82f3tb3+bN77lDW94g24t5fzv//4vbr31Vnz5y1/GypUrUVZWpvf96Ec/wvve9z6ce+65uOuuu1xnHc1kMpiZmUF1dXXevm9961sAIL1mwovmQHTCjSeeeAI33ngjtmzZgle+8pV6+wknnIDf/va3+NGPfoRPfOITevv09DTuuusuVFZW5s3AvnPnTtx5550545Apgsgcm0z84Ac/gM/n08sOCsKh5kD0JJPJIBaLoby8POfYvXv34jvf+Q6qq6tx5plnvui80Dwu5hjm+fl5XH/99QCkThAOH8PDw9YI0gcffBDPPvtszhJKV155Jb7whS/ge9/7no4aBfJ9BWDBsTXtnGw2qzsk+PxDbr7FDTfcgOHhYb3klFCY49pBLi4uti43Q2Ftq1atytn/gx/8AJdffjnWr1+P9773vVi9ejXGxsZw33334dprr8XFF18MYGFtswceeABXXHEFPvzhD2PFihW49957cc899+Bd73qXLvxLS0tx4YUX4pZbbkEwGMSpp56Kvr4+fO9730NbWxsmJiZy8nX55Zfje9/7Ht72trfh/PPPx8jICH74wx9anQNBOFAORB/q6urQ0NCAj33sY+jt7UVzczOeeuop3HzzzdiwYQO2b9+uz1+9erV1qSVaGu3cc8/FKaecorfffffduPrqq1FWVoa3ve1tuP3223POKykp0c5ANBpFc3MzLr30Uqxfvx719fUYHh7GnXfeiSeeeALnnXcerrjiioN6LsLxy4HWEZ/+9Kexe/dunHbaaSgvL8fWrVtx0003YdmyZbj55ptz0viHf/gH/OQnP8E//dM/Yfv27TjrrLMwOTmJG264AUNDQ7j++uu1oUNs2LAB73znO/G+970P7e3tePDBB3Hbbbdhy5Ytep1wzuOPP47nnnsOb33rW6WeEA4bB6In09PTaGtrwyWXXIK1a9eisrISO3fuxI033ohoNIqf/exnOROSHii7d+/Gli1bcPnll6OjowNVVVUYGBjAz372M+zcuRNXXXWVXtZGEA41H/jABzA0NIRzzz0Xy5cvRyKRwJNPPomf//znKC0txXXXXaeP/cQnPoHbb78dH//4x7Fr1y6ceOKJ+POf/4yf/vSnOPfcc3PK9Pe9732YnZ3FmWeeiZaWFoyPj+P222/Hk08+iYsvvjhH/173utchFArhyiuvxIc+9CFUVlbi4Ycfxr333otVq1a5rjsuGBzB8c9HLYUmlnj88cfVxRdfrKqrq5XP51MtLS3qiiuuyFtOZs+ePeqKK65QNTU1qri4WHV2dqqvfe1rejkoYmxsTF199dWqsbFR+f1+tX79evX9739f3XTTTQqAevDBB/WxsVhMffzjH1etra3K7/er1atXqy9+8YvqgQceUADylkcQhEOBmz48/fTT6jWveY2qqKhQJSUlasuWLeqPf/zjkid8cJuki7a7fZYvX66PTSaT6mMf+5g69dRTVXV1tfJ6vaqiokKdddZZ6tvf/vYBTeolCEvFTSd+8YtfqDPOOENVVlYqv9+v2tvb1Sc+8Qk1NTVlTaerq0u9613vUsuWLVNFRUWqtLRUvepVr1K333573rEA1FVXXaXuv/9+ddppp6lAIKDq6urUhz70ITU7O2tN/33ve58CoH77298e9D0LwoFi05NEIqGuvvpqtX79elVRUaGKiopUQ0ODuuyyy9Tjjz/umsZSJ+kaGxtTH/zgB9XGjRtVZWWlKioqUtXV1er8889Xt9xyi3WpTEE4VPzP//yPev3rX6+am5uV3+9XgUBAdXR0qA996EOqr68v7/ixsTH1/ve/XzU2Nqri4mLV1tam/uVf/kXF4/Gc42688Ua1ZcsWVV9fr4qLi1VJSYl6xSteoa6//vo8v0IppR566CF11llnqZKSElVeXq4uuugitX37drVly5YcG0opmaTLDUcpow9eEARBEARBEARBEI5DjutZrAVBEARBEARBEASBEAdZEARBEARBEARBECAOsiAIgiAIgiAIgiAAEAdZEARBEARBEARBEACIgywIgiAIgiAIgiAIAMRBFgRBEARBEARBEAQA4iALgiAIgiAIgiAIAgBxkAVBEARBEARBEAQBgDjIgiAIgiAIgiAIggBAHGRBEARBEARBEARBACAOsiAIgiAIgiAIgiAAEAdZEARBEARBEARBEACIgywIgiAIgiAIgiAIAMRBFgRBEARBEARBEAQA4iALgiAIgiAIgiAIAgBxkAVBEARBEARBEAQBgDjIgiAIgiAIgiAIggBAHGRBEARBEARBEARBACAOsiAIgiAIgiAIgiAAEAdZEARBEARBEARBEACIgywIgiAIgiAIgiAIAMRBFgRBEARBEARBEAQA4iALgiAIgiAIgiAIAgBxkAVBEARBEARBEAQBgDjIgiAIgiAIgiAIggBAHGRBEARBEARBEARBACAOsiAIgiAIgiAIgiAAEAdZEARBEARBEARBEACIgywIgiAIgiAIgiAIAMRBFgRBEARBEARBEAQA4iALgiAIgiAIgiAIAgBxkAVBEARBEARBEAQBgDjIgiAIgiAIgiAIggBAHGRBEARBEARBEARBACAOsiAIgiAIgiAIgiAAEAdZEARBEARBEARBEACIgywIgiAIgiAIgiAIAMRBFgRBEARBEARBEAQA4iALgiAIgiAIgiAIAgBxkAVBEARBEARBEAQBgDjIgiAIgiAIgiAIggBAHGRBEARBEARBEARBACAOsiAIgiAIgiAIgiAAEAdZEARBEARBEARBEACIgywIgiAIgiAIgiAIAMRBFgRBEARBEARBEAQA4iALgiAIgiAIgiAIAgBxkAVBEARBEARBEAQBgDjIgiAIgiAIgiAIggBAHGRBEARBEARBEARBACAOsiAIgiAIgiAIgiAAEAdZEARBEARBEARBEACIgywIgiAIgiAIgiAIAMRBFgRBEARBEARBEAQA4iALgiAIgiAIgiAIAgBxkAVBEARBEARBEAQBgDjIgiAIgiAIgiAIggBAHGRBEARBEARBEARBACAOsiAIgiAIgiAIgiAAEAdZEARBEARBEARBEACIgywIgiAIgiAIgiAIAICiI50BQRAEQXgpyWaziEajiEQi6O3thVIqZ7/bf6UUHMfBihUrUFxcbD3WcRw4joPZ2VkMDg6isrISdXV1AICKigr4fD5MTExgfn4eABAIBFBWVpZzvscjbdeCIAiCcKRwlFm7C4IgLAG3osNxnJc4J4LgjlIKSinEYjEAwMDAAPr6+jA5OYlUKqXlNZvNIpvNYn5+Ht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dJCHWwkvCodSJvr4+de6556pvfvOb6q677lI33nijuvDCCxUAdf755+eEj7px/fXXKwDq05/+dM520i0JsRYOF4V04c4771QAVG1trSovL1df/epX1W233abe/e53KwDq7LPPVtlsVh9fUVGhQqGQCoVC6qqrrlK33Xab+trXvqa3P/vss/rYN7zhDQqAmpuby7vuP/7jPyoAaufOnUoppXbs2KEcx1Hnnntujj49+eSTynEcCbEWDikHGkZKwxA++9nPLnrsUkKst2/fnmMvlZeXq3/+539W6XQ657hoNJp37vz8vNqyZYsqKytbdJiDIBwohXRjcHBQ+f1+9Y53vCNv30c+8hHl8XhywrVt3HPPPQqAuvLKK3O2uw1l++Y3v6kAqG984xs522OxmGpsbFQA1HXXXbfofR0PyCRdL4IvfelLOf8vueQSXHHFFTjppJPwgQ98ALt379b70uk03ve+9+GCCy7A2972tkXTLi4uRmtrKy699FK88Y1vRCgUwn333Ycf/vCH8Hq9uOGGGw75/QjCwXIgOtHa2orf/e53OcdfffXVuOaaa3DDDTfg5z//Of7mb/7G9VqPPPIIrr32Wpx44om6x1gQjgYikQgAYGxsDPfffz/OP/98AMBll10GpRR+/OMf4ze/+Q1e97rX6ePn5+fxN3/zNzlL9G3evBnnnHMO/v3f/x3/8z//AwB6KILf78+7Lg3JoWPuuusuKKVw7bXX5oRjn3zyybjgggvw29/+9hDfuSAsnRtvvBEejycvzPPF0tbWhvvvvx+pVApdXV245ZZbMDMzg2QyiaKi/WYun8QukUggFotBKYULL7wQDz30EHbs2IENGzYckjwJwmLcdtttSCaTuPrqqzE+Pp6z741vfCO++c1v4oEHHtDRoia7d+/GlVdeiWXLluG6665b0jXf+c534j/+4z/wb//2bwiHwzj//PMxPj6Oz3zmMzoPhYa9HU9IiPUhor29HW9961vR1dWFXbt26e1f/vKX0dXVheuvv37RNLLZLF772tfikUcewf/+7//iXe96Fy6//HLccMMN+Md//EfceOONeOCBBw7nbQjCIcNNJ9z41Kc+BQC45557XI958skn8frXvx5NTU2455578sbqC8KRJBgMAgCWLVum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9nP/tZAMC73vUu3HrrrXpWUgp9++lPf5q31AeNTyu0RJQgHAkORCeAhcgJk2w2i3/9138FsDD2xkznggsuQElJCR588EG0tbUd4jsQhENDKBTCZZddhuHhYdxxxx05+77zne8AQM7MurQUlGmw//KXv8TAwEDOsRdffDGCwSC+/e1v5zSi/vKXv0RPT0/OuP03velNcBwHX//613OO3bp1qzgDwhHj7rvvxtjYGK688koUFxcfdHpjY2PWXt/h4WHceuutKCkpwbp16wBAj8VXxpJrQ0NDssyTcER461vfCr/fj8985jO6QYdD4+iJvr4+nHPOOZiensZvf/tbbN68+ZDl5Vvf+haeffZZfPSjH80Zq388Iz3I/8fNN9+Mvr4+AAuFbiqVwn/8x38AAJYvX64Nmd27d+N1r3sdLrnkErS3tyMcDuPpp5/Wk2h9//vf12mWl5fj8ssvz7tWTU0NgIXeBr7/xBNPxGWXXYbbb78dp5xyCt75znfqSbp++ctf4vTTTz/sra6CQBwOnQCA973vfZidncWZZ56JlpYWjI+P4/bbb8eTTz6Jiy++OEcn+vr6cMEFF2Bqagof+chH8Mgjj+CRRx7JSe/SSy+VAl04rCxVFwDgP//zP/HAAw/giiuuwIc//GGsWLEC9957L+655x68613vwplnnqmPPf/88/GOd7wDP/vZz3DRRRfhDW94A/r6+vCtb30LjY2NujEVAGpra/H5z38eH//4x/V5AwMDuO6669DZ2Yl/+Id/0Md2dnbigx/8IL797W/j3HPPxWWXXYbR0VF8+9vfxoknnoht27Yd3gcmHPMciE4QSw2v/va3v43p6WkACxOd9vX16bRPPPFE3Yj605/+FP/1X/+FSy+9FG1tbfD5fNi1axd+/OMfY2pqCjfeeKMel19aWooLL7wQt9xyC4LBIE499VT09fXhe9/7Htra2qwNt4LwYliqbjQ3N+M73/kO3vve92Lt2rW48sorsXz5coyNjWH79u2488478fzzz2PFihWIRCI455xz0Nvbiw9/+MPYuXMndu7cmXPdCy64YEnRehdddBFWrlyJE044AY7j4Le//S3uvPNOvP71r9fj8QXIMk/Eli1bcpYJ4B++xMDQ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rrbjvvvtWpbuWdkcQLjSqLRe2beNb3/oW3v3ud2PDhg2IRCLo7u7G29/+djzzzDOO6c/OzuL3fu/3sGHDBoRCITQ1NeHWW2/F448/7npfn/jEJ2BZFmKx2Kp9hUIB73znO3Hs2DH8z//5P3HPPffgHe94xyt/CYLAWKvttBac7KG18JOf/AS/+Zu/iWuuuQahUAiWZeGRRx45q/u6VPGd7xu4ULj77rvx5S9/GW9/+9vxa7/2a/D7/Xj44YfxB3/wB/inf/on/PznP0c4HAawksHonIaGhnNy/Y997GMoFArnJC1BOFtOnjyJsbEx/PIv/zI6Ozvh8/mwf/9+fP3rX8d3vvMdvPjii2hubgYADAwM4IYbboDP58Pv//7vIx6P4+/+7u/w5je/GQ888ADe+MY3qnRzuRxuv/127N27Fx/72MewZcsWPPDAA/it3/otTExMlHnys9ksHn/8cXz0ox/F7/3e76nttm3jl37pl/DAAw/gzjvvxMc+9jFMTU3hK1/5Cq6//no8+eST2Lp162v2roRLn7WUh2effRa9vb2444470NjYiNnZWdx77714xzvegc9//vP49Kc/rdJdS7sjCBca1ZaLbDaL9773vbjyyivx7ne/G319fRgbG8PXvvY1XH/99fiHf/gHvOc97ylLe2RkBLfccguWlpbwgQ98AP39/VhYWMC+fftw6tQpx3t68cUX8Zd/+ZeIxWJGp+vg4CAGBwfxxS9+ER/96EfP+TsRLm/W0lasBSd7aK383//7f/Htb38b27dvx5YtW/Diiy++4rQueWzBtm3bfu655+z5+flV2z/1qU/ZAOwvfelLatv73/9++1y+uh/84Ae2x+Ox/9f/+l82APvP//zPz1nagnAu+ad/+icbgP1nf/Znatt//I//0fZ4PPbevXvVtmQyaXd3d9v9/f12qVRS27/85S/bAOy//uu/Lkv3He94h+33++3h4WG1bWRkxAZgf+Yznyk79r777rMB2B/60IfKtg8MDNjhcNi+7bbbzsGTCkJlTOXBRD6ft6+44go7FovZhUJBbV9LuyMIFwt6ucjn8/Yjjzyy6rjx8XE7kUjYzc3NdrFYLNt300032Z2dnfbp06ervm6hULB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zn/scUqkUPvjBDypbCgDS6bSyr4LBILq6us7Z8wnCWllLW7EWnnvuObzpTW/Chg0b8Kd/+qfo6+tDOByGZVl497vfjVKpdM6udbkhAlnjs5/9LD73uc/hrrvuwje+8Y0yr7wbGzZsgGVZyOVyZeu+mpiYmEAmk8Hf/u3f4m//9m9X7f/TP/1T/Omf/inuvfdevOtd78J9992HpaUl3H///bj11lvLjp2ZmZEZ6YTXlHQ6jdnZWQArQjUYDOLpp59edRyFfO7evRvASljnVVddhb179yKbzZbl22effRa2batjq2XDhg3YsGGD+v7AAw+gtrYWN95445qfSxBeCbw8VDoOgPHYatqdhx56CKdPn8bdd9+9agb3P/iDPyj73t/fDwCyxqVw3jCVi+HhYdxyyy1YWFjAT3/6U8cIh2uvvRZf+9rX1GR1HNpGa8mOjIwglUrhda97nTGtjRs3Ytu2batmhBeE1xpTmRgcHEQulyvrRc5msxgcHKzK0f/tb38bxWIRDzzwQFk0aSqVkt7js0QGIjE+//nP43Of+xze+9734u67717TOK1EIoE77rgD//zP/1w2FoywbRtTU1MAVkKi77333lV/ND75fe97H+699141M7DX61VpcP7u7/4O4+Pjr+RRBcEVp3z18MMP48CBA2qG6lgshre97W145JFH8NJLL6njlpaW8I1vfAMbN27Etddeq7b/6q/+KpaXl/H1r3+9LN3//b//N3w+X1Xj8Z340pe+hAMHDuB3fud3ysZqCsLZUm15SKVSxoieYrGIL3/5ywDOzO5OVNvuOLUDP/7xj1eNM9u5cye2bduGu+++GwcPHlyVlp6GILwSqi0XwIqQvfXWWzE/P48f//jHrrOo33nnnaipqcG3vvWtsvI0NjaG73//++jv71eO0U984hNGe2rr1q0IhUK499578Vd/9Vfn6IkFwZ21lAkAWFxcxFe+8pWybV/5ylewuLiIO++8s+L1nNqFL3zhC9J7fJZID/K/8+Uvfxmf+cxn0N3djTe+8Y349re/Xba/paUFt99+u2saX/3qV3HTTTfhDW94A973vvdh165dKJVKGBwcxA9+8AO8733vw2c/+1nE43G8613vWnV+Y2MjgJVeOb7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AAUIKsUCgUCoVCoVAoFAoFACXICoVCoVAoFAqFQqFQAFCCrFAoFAqFQqFQKBQKBQAlyAqFQqFQKBQKhUKhUABQgqxQKBQKhUKhUCgUCgUAJcgKhUKhUCgUCoVCoVAAUIKsUCgUCoVCoVAoFAoFACXICoVCoVAoFAqFQqFQAFCCrFAoFAqFQqFQKBQKBQAlyAqFQqFQKBQKhUKhUABQgqxQKBQKhUKhUCgUCgUAJcgKhUKhUCgUCoVCoVAAUIKsUCgUCoVCoVAoFAoFACXICoVCoVAoFAqFQqFQAFCCrFAoFAqFQqFQKBQKBQAlyAqFQqFQKBQKhUKhUABQgqxQKBQKhUKhUCgUCgUAJcgKhUKhUCgUCoVCoVAAUIKsUCgUCoVCoVAoFAoFACXICoVCoVAoFAqFQqFQAFCCrFAoFAqFQqFQKBQKBQAlyAqFQqFQKBQKhUKhUABQgqxQKBQKhUKhUCgUCgUAJcgKhUKhUCgUCoVCoVAAUIKsUCgUCoVCoVAoFAoFACXICoVCoVAoFAqFQqFQAFCCrFAoFAqFQqFQKBQKBQAlyAqFQqFQKBQKhUKhUABQgqxQKBQKhUKhUCgUCgUAJcgKhUKhUCgUCoVCoVAAUIKsUCgUCoVCoVAoFAoFACXICoVCoVAoFAqFQqFQAFCCrFAoFAqFQqFQKBQKBQAlyAqFQqFQKBQKhUKhUABQgqxQKBQKhUKhUCgUCgUAJcgKhUKhUCgUCoVCoVAAUIKsUCgUCoVCoVAoFAoFACXICoVCoVAoFAqFQqFQAFCCrFAoFAqFQqFQKBQKBQAlyAqFQqFQKBQKhUKhUABQgqxQKBQKhUKhUCgUCgUAJcgKhUKhUCgUCoVCoVAAUIKsUCgUCoVCoVAoFAoFAOD/A1MINnuRPyi/AAAAAElFTkSuQmCC", + "text/plain": [ + "
" + ] + }, + "metadata": {}, + "output_type": "display_data" + } + ], + "source": [ + "import os\n", + "import trimesh\n", + "import sys\n", + "sys.path.insert(0, \"/scratch/cvlab/home/seiler/smoothSDF\")\n", + "from src import visualization as viz\n", + "\n", + "mesh_list = []\n", + "title_list = []\n", + "\n", + "METHOD = \"ICTM\"\n", + "THRESHOLD = 30\n", + "instance_list = instance_list_1 + instance_list_2\n", + "for inst in instance_list:\n", + " mesh_path = f\"/scratch/cvlab/home/seiler/smoothSDF/simulations_car/meshes/{inst}/{METHOD}_{THRESHOLD}.obj\"\n", + " \n", + " try:\n", + " # Load the mesh\n", + " mesh = trimesh.load(mesh_path)\n", + " mesh_list.append(mesh)\n", + "\n", + " # Build the title: First 5 chars + Status\n", + " short_id = inst[:5]\n", + " title = f\"{short_id}\"\n", + " title_list.append(title)\n", + " \n", + " except Exception as e:\n", + " # If the file doesn't exist (e.g., because it failed and wasn't generated)\n", + " print(f\"Could not load mesh for {inst[:5]}: File not found or invalid.\")\n", + "\n", + "# --- 3. Render the grid ---\n", + "# Note: Ensure 'viz' is imported and defined in your environment before calling this\n", + "fig = viz.plot_render(mesh_list, titles=title_list, max_cols=5, axis_on=False, h_pad=1, figsize=(10, 8))" + ] + }, + { + "cell_type": "code", + "execution_count": 26, + "id": "e568b363", + "metadata": {}, + "outputs": [], + "source": [ + "# car_1f191e0327ce54474cdd04162f008888_shape\n", + "# car_292f6606c6072b96715e04edb8af9c53_shape\n", + "# car_20a3df3de67f309d8e35db9103756ad5_shape" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "331610a0", + "metadata": {}, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.10.6" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} diff --git a/cfd_workflow_20261012/_seiler_ref/setup_sim_all.sh b/cfd_workflow_20261012/_seiler_ref/setup_sim_all.sh new file mode 100644 index 0000000000000000000000000000000000000000..11193f3a1081616d506d3d1c6ca153dd88811330 --- /dev/null +++ b/cfd_workflow_20261012/_seiler_ref/setup_sim_all.sh @@ -0,0 +1,51 @@ +#!/bin/bash + +# instances=("1f191e0327ce54474cdd04162f008888" "4a423ae9a28afe3588cf40718544e7cc" "4c6aa3e7a8130295b528c0abff96f586" "20a3df3de67f309d8e35db9103756ad5" "45ff3c9bc849f2e33a2844e8778fdc6" "292f6606c6072b96715e04edb8af9c53" "365af82203c96fbca92a4cdad802b45" "498b7c799350d1f7c4acded0fc8a9118" "2236a1b9cde71eff13d31c5a107f3c4" "48862b67f5932cd4473f10e6caaeca56") +# instances=("1548f5fb0684d08c63155b8ebc275bd1" "1552f1a6521bb54a4bb135bcd06914d" "1660d6b7221223708a49a62fbc70ff9a" "1713a1ac8aedcc522b12ea83455b0f44" "1e2f9cb6b33c92ea82381b04bbe0ce6d" "2fe4a878e34bd3bab8013668e30e23b0" "300f9c418d6ec9f6473f10e6caaeca56" "332ac5346c7d3c0f8e35db9103756ad5" "3264f78bfc3bc58c9213ea6cb12e4e3c" "3bfa196d1b48f1e0c5dccef20baf829a") + +instances=("1f191e0327ce54474cdd04162f008888" "4a423ae9a28afe3588cf40718544e7cc" "4c6aa3e7a8130295b528c0abff96f586" "20a3df3de67f309d8e35db9103756ad5" "45ff3c9bc849f2e33a2844e8778fdc6" "292f6606c6072b96715e04edb8af9c53" "365af82203c96fbca92a4cdad802b45" "498b7c799350d1f7c4acded0fc8a9118" "2236a1b9cde71eff13d31c5a107f3c4" "48862b67f5932cd4473f10e6caaeca56" "1548f5fb0684d08c63155b8ebc275bd1" "1552f1a6521bb54a4bb135bcd06914d" "1660d6b7221223708a49a62fbc70ff9a" "1713a1ac8aedcc522b12ea83455b0f44" "1e2f9cb6b33c92ea82381b04bbe0ce6d" "2fe4a878e34bd3bab8013668e30e23b0" "300f9c418d6ec9f6473f10e6caaeca56" "332ac5346c7d3c0f8e35db9103756ad5" "3264f78bfc3bc58c9213ea6cb12e4e3c" "3bfa196d1b48f1e0c5dccef20baf829a") +# methods=("GD" "FMG" "DFLOW" "ICTM" "SGO" "OURS") +methods=("DFLOW" "FMG" "ICTM") + + +THRESHOLD="30" +BASE_PATH="/scratch/cvlab/home/seiler/smoothSDF/simulations_car" + +for inst in "${instances[@]}"; do + INIT_IN="$BASE_PATH/meshes/$inst/INIT_${THRESHOLD}.obj" + INIT_OUT="$BASE_PATH/simulations/$inst/INIT_${THRESHOLD}_sim" + + # 1. Vérification pour INIT + if [ ! -f "$INIT_IN" ]; then + continue + fi + + if [ -d "$INIT_OUT" ]; then + echo "L'instance INIT existe déjà, skip : $INIT_OUT" + else + python3 setup_sim.py "$INIT_IN" "$INIT_OUT" -n car_olivier + fi + + PRE_OPT_MESH="$BASE_PATH/simulations/$inst/INIT_${THRESHOLD}_sim/constant/triSurface/car.stl" + + # 2. Vérification pour les méthodes (lancées en parallèle) + for name in "${methods[@]}"; do + MESH_IN="$BASE_PATH/meshes/$inst/${name}_${THRESHOLD}.obj" + SIM_OUT="$BASE_PATH/simulations/$inst/${name}_${THRESHOLD}_sim" + + if [ ! -f "$MESH_IN" ]; then + continue + fi + + if [ -d "$SIM_OUT" ]; then + echo "La simu existe déjà, skip : $name" + else + # Le "&" à la fin lance la commande en tâche de fond + python3 setup_sim.py "$MESH_IN" "$SIM_OUT" -n car_olivier -p "$PRE_OPT_MESH" & + echo "Lancé en parallèle : $name" + fi + done + + wait + echo "Toutes les simulations pour l'instance $inst sont terminées." +done \ No newline at end of file diff --git a/cfd_workflow_20261012/_seiler_ref/smoothSDF_scripts/cleanexpdir_light.py b/cfd_workflow_20261012/_seiler_ref/smoothSDF_scripts/cleanexpdir_light.py new file mode 100644 index 0000000000000000000000000000000000000000..1d50d0640626b97f409ac4b83dc7132301b98eef --- /dev/null +++ b/cfd_workflow_20261012/_seiler_ref/smoothSDF_scripts/cleanexpdir_light.py @@ -0,0 +1,78 @@ +""" +Script to clean experimental directories to reduce disk usage. +LIGHT version that only removes meshes and parts, not latents and poses. + +Subdirectories cleaned: +- generation/ +- reconstruction/ +- pc_encoder/ +""" + +import os +import sys +import shutil +import argparse + +sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..")) +from src import workspace as ws + + +def _empty_subdir(subdir): + if os.path.isdir(subdir): + shutil.rmtree(subdir, ignore_errors=True) + os.mkdir(subdir) # recreate the (emtpy) directory + +def _empty_subdir_light(subdir): + for item in os.listdir(subdir): # epoch subdirs + if os.path.isdir(os.path.join(subdir, item)): + for subitem in os.listdir(os.path.join(subdir, item)): # mesh/parts subdirs + if subitem in ["mesh", "meshes", "part", "parts"]: + _empty_subdir(os.path.join(subdir, item, subitem)) + +def clean_dir(expdir, rm_gen=True, rm_recon=True, rm_pcenc=True, rm_opt=True): + """Clean the experimental directory.""" + if rm_gen: + gen_dir = os.path.join(expdir, ws.GEN_DIR) + if os.path.isdir(gen_dir): + _empty_subdir_light(gen_dir) + + if rm_recon: + recon_dir = os.path.join(expdir, ws.RECON_DIR) + if os.path.isdir(recon_dir): + _empty_subdir_light(recon_dir) + + if rm_pcenc: + pcenc_dir = os.path.join(expdir, "pc_encoder") + if os.path.isdir(pcenc_dir): + _empty_subdir_light(pcenc_dir) + + if rm_opt: + opt_dir = os.path.join(expdir, "optimization") + if os.path.isdir(opt_dir): + for item in os.listdir(opt_dir): + if os.path.isdir(os.path.join(opt_dir, item)): + _empty_subdir_light(os.path.join(opt_dir, item)) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description="Clean the given simulation directories.") + # parser.add_argument('maindirs', nargs='+', help="directories to clean") + parser.add_argument('-g', '--no-gen', dest="rm_gen", action='store_false', help="don't clean generation/") + parser.add_argument('-r', '--no-recon', dest="rm_recon", action='store_false', help="don't clean reconstruction/") + parser.add_argument('-p', '--no-pcenc', dest="rm_pcenc", action='store_false', help="don't clean pc_encoder/") + + parser.add_argument('-x', '--exclude', nargs='*', default=[], help="directories to exclude from cleaning") + args = parser.parse_args() + args.exclude = set(x.strip('/') for x in args.exclude) + # args.maindirs = list(x.strip('/') for x in args.maindirs) + + # Take each argument as being a directory to clean + dir_to_clean = ["/scratch/cvlab/home/seiler/smoothSDF/experiments/vecset_ae_512_32", + "/scratch/cvlab/home/seiler/smoothSDF/experiments/vecset_ae_noisy_256_8"] + for maindir in dir_to_clean: + if os.path.isdir(maindir): + if maindir not in args.exclude: + clean_dir(maindir, False, args.rm_recon, False) + print(f"{maindir} cleaned.") + else: + print(f"{maindir} skipped.") \ No newline at end of file diff --git a/cfd_workflow_20261012/_seiler_ref/smoothSDF_scripts/compute_matrix_cf.py b/cfd_workflow_20261012/_seiler_ref/smoothSDF_scripts/compute_matrix_cf.py new file mode 100644 index 0000000000000000000000000000000000000000..e0992a440aac37519503335601839a331d207c67 --- /dev/null +++ b/cfd_workflow_20261012/_seiler_ref/smoothSDF_scripts/compute_matrix_cf.py @@ -0,0 +1,47 @@ +import json +import numpy as np +from tqdm.auto import tqdm +import torch +from chamferdist import ChamferDistance + +directory = "/scratch/cvlab/datasets/dataset_seiler/chair_partnet/samples" +json_path = "/scratch/cvlab/datasets/dataset_seiler/chair_partnet/splits/raw_train2419.json" +output_distance_path = "/scratch/cvlab/datasets/dataset_seiler/chair_partnet/distance_matrix/chamfer/distance_matrix_raw_train2419.npy" +output_instances_path = "/scratch/cvlab/datasets/dataset_seiler/chair_partnet/distance_matrix/chamfer/instances_distance_matrix_raw_train2419.json" + +with open(json_path, "r") as f: + instances = json.load(f) + +point_cloud_surface_dict = {} +for inst in tqdm(instances): + point_cloud_surface = np.load(f"{directory}/{inst}/surface.npy")[:, :3] + point_cloud_surface = np.random.permutation(point_cloud_surface)[:30000] + point_cloud_surface_dict[inst] = point_cloud_surface + +point_cloud_surface_dict_cuda = { + k: torch.tensor(v, dtype=torch.float32, device="cuda") + for k, v in point_cloud_surface_dict.items() +} +instances = list(point_cloud_surface_dict.keys()) +n = len(instances) +distance_matrix = np.zeros((n, n)) +batch_size = 64 +chamferDist = ChamferDistance() + +for i in tqdm(range(n), desc="Computing Chamfer distances"): + pc1 = point_cloud_surface_dict_cuda[instances[i]].unsqueeze(0) + j_indices = list(range(i+1, n)) + for j_start in range(0, len(j_indices), batch_size): + j_end = min(j_start + batch_size, len(j_indices)) + batch_js = j_indices[j_start:j_end] + pcs2_batch = torch.cat([point_cloud_surface_dict_cuda[instances[j]].unsqueeze(0) for j in batch_js], dim=0) + dists = chamferDist(pc1.expand(pcs2_batch.shape[0], -1, -1), pcs2_batch, batch_reduction=None, point_reduction="mean", bidirectional=True) + dists = dists.detach().cpu().numpy() + + for k, j in enumerate(batch_js): + distance_matrix[i, j] = dists[k] + distance_matrix[j, i] = dists[k] + +# np.save(output_distance_path, distance_matrix) +# with open(output_instances_path, "w") as f: +# json.dump(instances, f) diff --git a/cfd_workflow_20261012/_seiler_ref/smoothSDF_scripts/compute_matrix_cf_test.py b/cfd_workflow_20261012/_seiler_ref/smoothSDF_scripts/compute_matrix_cf_test.py new file mode 100644 index 0000000000000000000000000000000000000000..cbb0dae280076e607d8ee91fffa8e8fae0dd44d8 --- /dev/null +++ b/cfd_workflow_20261012/_seiler_ref/smoothSDF_scripts/compute_matrix_cf_test.py @@ -0,0 +1,58 @@ +import json +import torch +import numpy as np +from tqdm.auto import tqdm +from chamferdist import ChamferDistance + +device = "cuda" + +distance_matrix_directory = "/scratch/cvlab/datasets/dataset_seiler/chair_partnet/distance_matrix/chamfer" +distance_matrix = np.load(f"{distance_matrix_directory}/distance_matrix_raw_train2419.npy") +with open(f"{distance_matrix_directory}/instances_distance_matrix_raw_train2419.json", "r") as f: + instances_train = json.load(f) +split = "/scratch/cvlab/datasets/dataset_seiler/chair_partnet/splits/raw_valid484.json" +with open(split, "r") as f: + instances_valid = json.load(f) +sample_directory = "/scratch/cvlab/datasets/dataset_seiler/chair_partnet/samples" +chamferDist = ChamferDistance() + +# === Preload train clouds === +print("Loading train clouds...") +train_clouds = [] +for inst in tqdm(instances_train): + pts = np.load(f"{sample_directory}/{inst}/surface.npy")[:, :3] + pts = np.random.permutation(pts)[:30000] + train_clouds.append(torch.tensor(pts, dtype=torch.float32)) +train_clouds = torch.stack(train_clouds).to(device) + +# === Compute distances valid→train === +new_distances = [] +instances_valid = [instances_valid[0]] +for inst_valid in tqdm(instances_valid, desc="Valid instances"): + pts = np.load(f"{sample_directory}/{inst_valid}/surface.npy")[:, :3] + pts = np.random.permutation(pts)[:30000] + pts = torch.tensor(pts, dtype=torch.float32).unsqueeze(0).to(device) + + dists = [] + batch_size = 128 + for i in range(0, len(train_clouds), batch_size): + train_batch = train_clouds[i:i + batch_size] + dist = chamferDist(pts.repeat(len(train_batch), 1, 1), train_batch, + batch_reduction=None, point_reduction="mean", bidirectional=True) + dists.append(dist.detach().cpu()) + dists = torch.cat(dists).numpy() + new_distances.append(dists) + +new_distances = np.array(new_distances) # shape (N_valid, N_train) + +# === Extend matrix === +# Final size (N_train + N_valid, N_train + N_valid) +zeros_valid = np.zeros((len(instances_valid), len(instances_valid))) +distance_matrix_extended = np.block([ + [distance_matrix, new_distances.T], + [new_distances, zeros_valid] +]) + +# === Save === +# np.save(f"{distance_matrix_directory}/distance_matrix_test_extended.npy", distance_matrix_extended) +# print("✅ Saved extended matrix:", distance_matrix_extended.shape) diff --git a/cfd_workflow_20261012/_seiler_ref/smoothSDF_scripts/evaluate.py b/cfd_workflow_20261012/_seiler_ref/smoothSDF_scripts/evaluate.py new file mode 100644 index 0000000000000000000000000000000000000000..918f5d9f3abe45fa40539609d4ef2f3fbbf0d415 --- /dev/null +++ b/cfd_workflow_20261012/_seiler_ref/smoothSDF_scripts/evaluate.py @@ -0,0 +1,202 @@ +""" +Main evaluation script. + +Evaluate a set of shapes reconstructed with a deep implicit model. +""" + +import os +import os.path +import sys +import argparse +import logging +import json +import time + +import numpy as np +import trimesh + +sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..")) +from src import workspace as ws +from src.metrics import chamfer_distance, mesh_iou, image_consistency +from src.utils import configure_logging, set_seed + + +def parser(argv=None): + parser = argparse.ArgumentParser(description="Evaluate shapes reconstructed with a deep implicit model.") + + parser.add_argument("experiment", + nargs="?", + help="path to the experiment directory.", + default="experiments/vecset_ae" + ) + + # Evaluation arguments + parser.add_argument('--debug', action='store_true', help="increase verbosity to print debugging messages") + parser.add_argument('--load-epoch', default='latest', help="epoch to load, default to latest available") + parser.add_argument("--mesh-to-sdf", action='store_true', help="use the mesh-to-sdf package to compute the SDF and surface samples (useful for dirty meshes, e.g., unprocessed ShapeNet)") + parser.add_argument('--overwrite', action='store_true', help="overwrite shapes that are already evaluated") + parser.add_argument('-q', '--quiet', dest="verbose", action='store_false', help="disable verbosity and run in quiet mode") + parser.add_argument('--seed', type=int, default=0, help="initial seed for the RNGs (default=0)") + parser.add_argument('-s', '--split', help="split to evaluate, default to \"ValidSplit\" in specs file") + parser.add_argument('--suffix', type=str, default="", help="suffix to add to the reconstruction and evaluation directories") + parser.add_argument('-t', '--test', action='store_true', help="reconstruct the test set, otherwise reconstruct the validation set (--split override this)") + + # Chamfer-Distance + parser.add_argument('--cd-samples', type=int, default=30000, help="number of surface samples for chamfer distance (default=30000)") + parser.add_argument('--cd-no-square-dist', action='store_false', dest="cd_square_dist", help="do not use square distances for the chamfer-distance") + + # Mesh Intersection-over-Union + parser.add_argument('--iou-resolution', type=int, default=128, help="resolution of the grid for the mesh IoU (default=128)") + parser.add_argument('--iou-skip', action='store_true', help="skip the IoU computation, e.g., if meshes are dirty and need fast results") + + # Image Consistency + parser.add_argument('--ic-skip', action='store_true', help="skip the Image Consistency computation") + + args = parser.parse_args(argv) + + if args.mesh_to_sdf: + raise NotImplementedError("Would be too slow, probably better to pre-compute them.") + # from mesh_to_sdf import mesh_to_sdf, get_surface_point_cloud + os.environ['PYOPENGL_PLATFORM'] = 'egl' + + return args + + +def main(args=None): + # Initialization + if args is None: + args = parser() + set_seed(args.seed) + start_time = time.time() + + expdir = args.experiment + specs = ws.load_specs(expdir) + configure_logging(args, os.path.join(ws.get_log_dir(expdir), "evallog.txt")) + + logging.info(f"Command: python {' '.join(sys.argv)}") + logging.info("Date: " + time.strftime("%d %B %Y at %H:%M:%S (%Y%m%d-%H%M%S)")) + logging.info(f"Evaluating shapes in {expdir}.") + logging.info(f"arguments = {args}") + + # Data + if args.split is None: + args.split = specs["TestSplit"] if args.test or specs["ValidSplit"] is None else specs["ValidSplit"] + with open(args.split) as f: + instances = json.load(f) + n_shapes = len(instances) + datasource = os.path.join(specs["DataSource"], specs["SamplesDir"]) + logging.info(f"{n_shapes} shapes in {args.split} to evaluate.") + + # Resume from checkpoint + if args.load_epoch == 'latest': + args.load_epoch = ws.load_history(expdir)['epoch'] + + # Parameters and directories + if args.suffix: + args.suffix = "_" + args.suffix + load_epoch = str(args.load_epoch) + args.suffix + eval_dir = ws.get_eval_dir(expdir, load_epoch) + mesh_subdir = ws.get_recon_mesh_subdir(expdir, load_epoch) + os.makedirs(eval_dir, exist_ok=True) + + logging.info(f"Evaluating checkpoint from epoch={load_epoch}.") + + ## Evaluation metrics + results = {} + filenames = {} + metrics = [ + "chamfer", # Chamfer-Distance + "iou", # Mesh Intersection-over-Union + "ic", # Image Consistency + ] + for metric in metrics: + results[metric] = {} + filenames[metric] = os.path.join(eval_dir, metric+".json") + if os.path.isfile(filenames[metric]): + with open(filenames[metric]) as f: + results[metric].update(json.load(f)) + # Evaluation + for i, instance in enumerate(instances): + logging.info(f"Shape {i+1}/{n_shapes} ({instance})") + + # Reconstruction + recon_mesh_filename = os.path.join(mesh_subdir, instance + ".obj") + if not os.path.isfile(recon_mesh_filename): + logging.warning(f"no mesh found under {recon_mesh_filename}! Skipping...") + continue + try: + recon_mesh = trimesh.load(recon_mesh_filename) + except ValueError: # empty mesh + recon_mesh = trimesh.Trimesh() + + # Chamfer-Distance + if not args.overwrite and instance in results["chamfer"]: + logging.info(f"chamfer = {results['chamfer'][instance]} (existing)") + else: + # Load GT surface samples + gt_samples = np.load(os.path.join(datasource, instance, "surface.npy"))[:, :3] + gt_samples = np.random.permutation(gt_samples)[:args.cd_samples, :3] + + # Reconstruction surface samples + if not recon_mesh.is_empty: + recon_samples = recon_mesh.sample(args.cd_samples) + else: + recon_samples = np.zeros((0, 3)) + + # Chamfer-Distance + chamfer_val = chamfer_distance(gt_samples, recon_samples, square_dist=args.cd_square_dist) + import math + if math.isnan(chamfer_val): + logging.info(f"chamfer = {chamfer_val} skiping") + continue + results["chamfer"][instance] = float(chamfer_val) + logging.info(f"chamfer = {chamfer_val}") + + # Mesh Intersection-over-Union + if not args.overwrite and instance in results["iou"]: + logging.info(f"iou = {results['iou'][instance]} (existing)") + elif not args.iou_skip: + # Load GT mesh + gt_mesh = trimesh.load(os.path.join(specs['DataSource'], "meshes", instance+".obj")) + + # Mesh Intersection-over-Union + iou_val = mesh_iou(gt_mesh, recon_mesh, args.iou_resolution) + results["iou"][instance] = float(iou_val) + logging.info(f"iou = {iou_val}") + + # Image Consistency + if not args.overwrite and instance in results["ic"]: + logging.info(f"image consistency = {results['ic'][instance]} (existing)") + elif not args.ic_skip: + # Load GT mesh + gt_mesh = trimesh.load(os.path.join(specs['DataSource'], "meshes", instance+".obj")) + + # Compute Image Consistency + ic_val = image_consistency(gt_mesh, recon_mesh) + results["ic"][instance] = float(ic_val) + logging.info(f"image consistency = {ic_val}") + + # Save results + for metric in metrics: + with open(filenames[metric], "w") as f: + json.dump(results[metric], f, indent=2) + + # Average and median metrics + for metric in metrics: + all_values = list(results[metric].values()) + all_values = [v for v in all_values if not np.isnan(v)] + if len(all_values) == 0: + logging.info(f"Empty metric {metric} ({len(all_values)}/{len(instances)} shapes)") + continue + logging.info(f"Average {metric} = {np.mean(all_values)} ({len(all_values)}/{len(instances)} shapes)") + logging.info(f"Median {metric} = {np.median(all_values)} ({len(all_values)}/{len(instances)} shapes)") + + duration = time.time() - start_time + duration_msg = "{:.0f}h {:02.0f}min {:02.0f}s".format(duration // 3600, (duration // 60) % 60, duration % 60) + logging.info(f"End of evaluation after {duration_msg}.") + logging.info(f"Results saved in {expdir}.") + + +if __name__ == "__main__": + args = parser() + main(args) \ No newline at end of file diff --git a/cfd_workflow_20261012/_seiler_ref/smoothSDF_scripts/finetuning.py b/cfd_workflow_20261012/_seiler_ref/smoothSDF_scripts/finetuning.py new file mode 100644 index 0000000000000000000000000000000000000000..2ee46350865cb472cab0030a0a14d6281b80dfe8 --- /dev/null +++ b/cfd_workflow_20261012/_seiler_ref/smoothSDF_scripts/finetuning.py @@ -0,0 +1,197 @@ +""" +Main finetuning script. +""" + +import os +import os.path +import sys +import argparse +import logging +import json +import time + +import numpy as np +import torch +from torch.utils.data import DataLoader +from tqdm.auto import tqdm + +sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..")) +from src_optimization.optimization_function import get_opt_loss +from src import workspace as ws +from src.loss import get_loss_recon +from src.models import get_model +from src.utils import clamp_sdf, configure_logging, set_seed, get_device +from src.data import VoxelDataset + + +def parser(argv=None): + parser = argparse.ArgumentParser( + description="Finetuned model with optimization objective." + ) + parser.add_argument("experiment", nargs="?", default="experiments/deepsdf_2419") + parser.add_argument("finetuning_name", nargs="?", default="test_1epoch_10iter") + parser.add_argument("--debug", action="store_true") + parser.add_argument("-i", "--iters", type=int, default=1) + parser.add_argument("--load-epoch", default="latest") + parser.add_argument("--lr-obj", type=float, default=1e-2) + parser.add_argument("--lr-finetuning", type=float, default=5e-4) + parser.add_argument("--voxel-resolution", type=int, default=32) + parser.add_argument("--seed", type=int, default=0) + parser.add_argument("--batch-size", type=int, default=16) + parser.add_argument("--m-iter", type=int, default=10) + + args = parser.parse_args(argv) + return args + + +def main(args=None): + # Initialization + if args is None: + args = parser() + set_seed(args.seed) + device = get_device() + start_time = time.time() + + expdir = args.experiment + specs = ws.load_specs(expdir) + specs_opt = specs["Optimization"] + device = specs.get("Device", get_device()) + configure_logging(args, os.path.join(ws.get_log_dir(expdir), "reconlog.txt")) + + logging.info(f"Command: python {' '.join(sys.argv)}") + logging.info("Date: " + time.strftime("%d %B %Y at %H:%M:%S (%Y%m%d-%H%M%S)")) + logging.info(f"Fintuning model in {expdir}. (on {device})") + logging.info(f"arguments = {args}") + + # Data + voxel_dataset = VoxelDataset( + specs["DataSource"], + specs["TrainSplit"], + args.voxel_resolution, + return_idx=True, + ) + n_shape = len(voxel_dataset) + logging.info(f"{n_shape} shapes.") + dataloader = DataLoader( + voxel_dataset, + batch_size=args.batch_size, + shuffle=True, + num_workers=os.cpu_count(), + pin_memory=True, + ) + clampD = specs.get("ClampingDistance", None) + + # Model + latent_dim = specs["LatentDim"] + model = get_model( + specs.get("Network"), + **specs.get("NetworkSpecs"), + latent_dim=latent_dim, + num_latents=n_shape, + ).to(device) + model.train() + logging.info( + f"Model has {sum([x.nelement() for x in model.parameters()]):,} parameters." + ) + + # Loss + loss_recon = get_loss_recon(specs["ReconLoss"], reduction="none").to(device) + loss_opt = get_opt_loss(specs_opt["OptimizationType"]) + + # Resume from checkpoint + if args.load_epoch == "latest": + args.load_epoch = ws.load_history(expdir)["epoch"] + ws.load_model(expdir, model, args.load_epoch) + ws.load_latents(expdir, model.latents, args.load_epoch) + logging.info(f"Loaded checkpoint from epoch={args.load_epoch}.") + + # Parameters and directories + os.makedirs(os.path.join(expdir, "finetuning"), exist_ok=True) + os.makedirs(os.path.join(expdir, "finetuning", args.finetuning_name), exist_ok=True) + + # Optimizers + optimizer_obj = torch.optim.SGD( + model.latents.parameters(), lr=args.lr_obj + ) + optimizer_finetuning = torch.optim.SGD( + model.net.parameters(), lr=args.lr_finetuning + ) + + history = {"recon_error": [], "recon_opt_erro": [], "opt_obj": []} + + for e in range(args.iters): + time_epoch = time.time() + + epoch_recon_init = [] + epoch_opt_obj_steps = [[] for _ in range(args.m_iter)] + epoch_recon_opt_steps = [[] for _ in range(args.m_iter)] + + for index, xyz, sdf_gt in tqdm(dataloader): + index = index.to(device) + xyz = torch.flatten(xyz, start_dim=1, end_dim=-2).to(device) + sdf_gt = torch.flatten(sdf_gt, start_dim=1, end_dim=-1).to(device) + + with torch.no_grad(): + sdf_pred = model(index, xyz).squeeze() + if clampD is not None and clampD > 0.0: + sdf_pred = clamp_sdf(sdf_pred, clampD, ref = sdf_gt) + sdf_gt_clamp = clamp_sdf(sdf_gt, clampD) + + recon_init = loss_recon(sdf_pred, sdf_gt_clamp).mean() + epoch_recon_init.append(recon_init.item()) + z_init = model.latents(index).clone() + + for i in range(args.m_iter): + # 1. Optimize latent ONLY + optimizer_obj.zero_grad() + for p in model.net.parameters(): + p.requires_grad_(False) + opt_obj = loss_opt(xyz, model, index) + opt_obj.backward() + optimizer_obj.step() + for p in model.net.parameters(): + p.requires_grad_(True) + epoch_opt_obj_steps[i].append(opt_obj.item()) + + # 2. Optimize network ONLY + optimizer_finetuning.zero_grad() + for p in model.latents.parameters(): + p.requires_grad_(False) + s_hat = model(index, xyz).squeeze() + if clampD is not None and clampD > 0.0: + s_hat = clamp_sdf(s_hat, clampD, ref = sdf_gt) + sdf_pred = clamp_sdf(sdf_pred, clampD, ref = sdf_gt) + recon = loss_recon(s_hat, sdf_pred).mean() + recon.backward() + optimizer_finetuning.step() + for p in model.latents.parameters(): + p.requires_grad_(True) + epoch_recon_opt_steps[i].append(recon.item()) + + with torch.no_grad(): + model.latents.z.weight[index] = z_init + + history["recon_error"].append(np.mean(epoch_recon_init)) + avg_opt_obj_per_step = [np.mean(step_vals) for step_vals in epoch_opt_obj_steps] + avg_recon_opt_per_step = [np.mean(step_vals) for step_vals in epoch_recon_opt_steps] + history["opt_obj"].append(avg_opt_obj_per_step) + history["recon_opt_erro"].append(avg_recon_opt_per_step) + + logging.info(f"Epoch {e}, {time.time() - time_epoch:.1f}s/epoch)") + + ws.save_model(expdir, model.net, args.load_epoch, finetuning=args.finetuning_name) + history.update(vars(args)) + with open(os.path.join(expdir, "finetuning", args.finetuning_name, "history.json"), 'w') as f: + json.dump(history, f, indent=4) + + duration = time.time() - start_time + duration_msg = "{:.0f}h {:02.0f}min {:02.0f}s".format( + duration // 3600, (duration // 60) % 60, duration % 60 + ) + logging.info(f"End of finetuning after {duration_msg}.") + logging.info(f"Results saved in {os.path.join(expdir, 'finetuning', args.finetuning_name)}.") + + +if __name__ == "__main__": + args = parser() + main(args) diff --git a/cfd_workflow_20261012/_seiler_ref/smoothSDF_scripts/reconstruct.py b/cfd_workflow_20261012/_seiler_ref/smoothSDF_scripts/reconstruct.py new file mode 100644 index 0000000000000000000000000000000000000000..677ca7cda9a23131df6861124dd76bc1c9f3958a --- /dev/null +++ b/cfd_workflow_20261012/_seiler_ref/smoothSDF_scripts/reconstruct.py @@ -0,0 +1,219 @@ +""" +Main reconstruction script. + +Reconstruct a set of shapes with a deep implicit model. +""" + +import os +import os.path +import sys +import argparse +import logging +import json +import time + +import numpy as np +import torch +from torch.utils.data import DataLoader + +sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..")) +from src.train_utils import compute_init_pca +from src.models.sdf_models import VDeepSDF +from src import workspace as ws +from src.loss import get_loss_recon +from src.mesh import create_mesh +from src.models import get_model +from src.reconstruct import reconstruct +from src.utils import clamp_sdf, configure_logging, set_seed, get_device +from src.data import SurfaceDataset, VoxelDataset + + + +def parser(argv=None): + parser = argparse.ArgumentParser( + description="Reconstruct shapes with an implicit model." + ) + parser.add_argument("experiment", nargs="?", default="experiments/vecset_ae_noisy_256_8") + parser.add_argument("--debug", action="store_true") + parser.add_argument("-i", "--iters", type=int, default=1000) + parser.add_argument("--load-epoch", default="latest") + parser.add_argument( "--lr", type=float, default=1e-3) + parser.add_argument("--max-norm", action="store_true") + parser.add_argument("-n", "--n-samples", type=int, default=8000) + parser.add_argument("--overwrite", action="store_false") + parser.add_argument("-q", "--quiet", dest="verbose", action="store_false") + parser.add_argument("-r", "--resolution", type=int, default=256) + parser.add_argument("-init-std", type=float, default=0.001) + parser.add_argument("--seed", type=int, default=0) + parser.add_argument("-s", "--split") + parser.add_argument("--suffix", type=str, default="") + parser.add_argument("-t", "--test", action="store_true") + args = parser.parse_args(argv) + + return args + + +def main(args=None): + # Initialization + if args is None: + args = parser() + set_seed(args.seed) + device = get_device() + start_time = time.time() + + expdir = args.experiment + specs = ws.load_specs(expdir) + device = specs.get("Device", get_device()) + configure_logging(args, os.path.join(ws.get_log_dir(expdir), "reconlog.txt")) + + logging.info(f"Command: python {' '.join(sys.argv)}") + logging.info("Date: " + time.strftime("%d %B %Y at %H:%M:%S (%Y%m%d-%H%M%S)")) + logging.info(f"Reconstructing shapes in {expdir}. (on {device})") + logging.info(f"arguments = {args}") + + # Data + if args.split is None: + args.split = ( + specs["TestSplit"] + if args.test or specs["ValidSplit"] is None + else specs["ValidSplit"] + ) + # if args.split is None: + # args.split = "/scratch/cvlab/datasets/dataset_seiler/car_partnet/splits/test10.json" + + with open(args.split) as f: + instances = json.load(f) + n_shapes = len(instances) + n_samples = args.n_samples + datasource = os.path.join(specs["DataSource"], specs["SamplesDir"]) + # datasource = os.path.join("/scratch/cvlab/datasets/dataset_seiler/car_partnet", specs["SamplesDir"]) + samplefile = specs["SamplesFile"] + + logging.info(f"{n_shapes} shapes in {args.split} to reconstruct.") + + # Model + latent_dim = specs["LatentDim"] + model = get_model( + specs.get("Network"), + **specs.get("NetworkSpecs"), + latent_dim=latent_dim, + num_latents=1, + ).to(device) + model.set_requires_grad(False) + logging.info( + f"Model has {sum([x.nelement() for x in model.net.parameters()]):,} parameters." + ) + + # Loss + loss_recon = get_loss_recon(specs["ReconLoss"], reduction="none").to(device) + latent_reg_lambda = specs.get("LatentRegLambda", None) + kl_lambda = specs.get("KlLossLambda", None) + + # Resume from checkpoint + if args.load_epoch == "latest": + args.load_epoch = ws.load_history(expdir)["epoch"] + ws.load_model(expdir, model.net, args.load_epoch) + model.latents.init_std = args.init_std + logging.info(f"Loaded checkpoint from epoch={args.load_epoch}.") + + pca = pca_norm = all_latent_init = None + + # Init via PCA + if specs.get("InitPCA"): + _, pca, pca_norm = compute_init_pca(specs, clamp_pca=specs.get("ClampPCA"), normalize=specs.get("NormalizePCA")) + ds = VoxelDataset(specs["DataSource"], args.split, resolution=64, return_idx=False, return_grads=False) + + data = np.stack([ds[i][1].flatten() for i in range(len(ds))]) + if specs.get("ClampPCA"): + data = clamp_sdf(torch.tensor(data).float(), clampD=specs.get("ClampingDistance")).numpy() + all_latent_init = torch.tensor(pca.transform(data) / pca_norm).to(device) + + # Init via File + if (path := specs.get("TestInitLatent")): + all_latent_init = torch.tensor(np.load(path)).to(device) + + # Init via Encoder + if specs.get("EncodeInitLatent"): + model.eval() + loader = DataLoader(SurfaceDataset(specs["DataSource"], args.split, specs.get("PointCloudSample", 2048)), batch_size=1, shuffle=False) + # loader = DataLoader(SurfaceDataset("/scratch/cvlab/datasets/dataset_seiler/car_partnet", args.split, specs.get("PointCloudSample", 2048)), batch_size=1, shuffle=False) + with torch.no_grad(): + latents = [] + for b in loader: + out = model.encode(b.to(device).float()) + if isinstance(out, tuple): + out = out[-1] + latents.append(out) + all_latent_init = torch.cat(latents) + + # Parameters and directories + if args.suffix: + args.suffix = "_" + args.suffix + clampD = specs["ClampingDistance"] + load_epoch = str(args.load_epoch) + args.suffix + latent_subdir = ws.get_recon_latent_subdir(expdir, load_epoch) + mesh_subdir = ws.get_recon_mesh_subdir(expdir, load_epoch) + os.makedirs(latent_subdir, exist_ok=True) + os.makedirs(mesh_subdir, exist_ok=True) + logvar_init = specs.get("NetworkSpecs").get("logvar_init_value", None) + + # Reconstruction + for i, instance in enumerate(instances): + logging.info(f"Shape {i + 1}/{n_shapes} ({instance})") + if ( + not args.overwrite + and os.path.isfile(os.path.join(latent_subdir, instance + ".pth")) + and os.path.isfile(os.path.join(mesh_subdir, instance + ".obj")) + ): + logging.info("already existing, skipping...") + continue + + # Load sdf data + filename = os.path.join(datasource, instance, samplefile) + npz = np.load(filename) + + latent_init = all_latent_init[i:i+1] if all_latent_init is not None else None + out = reconstruct( + model=model, + sdf_data=npz, + n_iters=args.iters, + n_samples=n_samples, + lr=args.lr, + loss_fn_recon=loss_recon, + latent_reg=latent_reg_lambda, + kl_lambda=kl_lambda, + logvar_init=logvar_init, + latent_init=latent_init, + clampD=clampD, + ) + err, latent = out[0], out[1] + logging.info(f"Final error={err:.6f}, latent norm = {latent.norm():.4f}") + + # Reconstruct the mesh + model_forward = {"return_mu": True} if isinstance(model, VDeepSDF) else {} + mesh = create_mesh( + model, + torch.tensor([0], dtype=torch.long).to(device), + N=args.resolution, + max_batch=32**3, + verbose=args.verbose, + device=device, + **model_forward, + ) + + # Save results + torch.save(latent, os.path.join(latent_subdir, instance + ".pth")) + mesh.export(os.path.join(mesh_subdir, instance + ".obj")) + torch.cuda.empty_cache() # release unused GPU memory + + duration = time.time() - start_time + duration_msg = "{:.0f}h {:02.0f}min {:02.0f}s".format( + duration // 3600, (duration // 60) % 60, duration % 60 + ) + logging.info(f"End of reconstruction after {duration_msg}.") + logging.info(f"Results saved in {expdir}.") + + +if __name__ == "__main__": + args = parser() + main(args) diff --git a/cfd_workflow_20261012/_seiler_ref/smoothSDF_scripts/train.py b/cfd_workflow_20261012/_seiler_ref/smoothSDF_scripts/train.py new file mode 100644 index 0000000000000000000000000000000000000000..f968f00760d0573371e92f01624f0b70897b9b77 --- /dev/null +++ b/cfd_workflow_20261012/_seiler_ref/smoothSDF_scripts/train.py @@ -0,0 +1,388 @@ +""" +Training script for shape INR reconstruction (DeepSDF / VDeepSDF + optional GAN) +""" + +import os +import sys +import argparse +import logging +import time +from multiprocessing import cpu_count + +import numpy as np +import torch +from tqdm.auto import trange + + +sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..")) +from src.train_utils import ( + build_models_optimizers, + load_data, + load_setup_checkpointing, + prepare_experiment, + # reconstruct_and_render_test_shapes, + render_metric_training_meshes, + setup_wandb, + train_one_epoch, +) +from src import workspace as ws +from src.loss import get_loss_recon +from src.utils import unwrap_model + + +# WANDB +try: + import wandb + WANDB_AVAILABLE = True +except ImportError: + WANDB_AVAILABLE = False + print("WandB not available. Install with: pip install wandb") + + +# ---------------------- +# Argument Parser +# ---------------------- +def get_parser(argv=None): + parser = argparse.ArgumentParser( + description="Train an implicit neural representation model." + ) + parser.add_argument( + "experiment", nargs="?", default="experiments/car_drivernet/vecset_test" + ) + parser.add_argument("--debug", action="store_true") + parser.add_argument("--load-epoch", type=int, default=None) + parser.add_argument("--no-resume", action="store_true") + parser.add_argument("--no-test", action="store_true") + parser.add_argument("-q", "--quiet", dest="verbose", action="store_false") + parser.add_argument("--reset", action="store_true") + parser.add_argument("--seed", type=int, default=0) + parser.add_argument("--workers", type=int, default=16) + parser.add_argument("--use-wandb", action="store_true") + return parser.parse_args(argv) + + +def main(args=None): + if args is None: + args = get_parser() + + # Experiment Setup + expdir, device, specs = prepare_experiment(args) + logging.info(f"Running experiment {expdir} on device {device}") + args.workers = min(args.workers, cpu_count()) + start_time = time.time() + + # Data Loading + dataloader, len_dataset, voxel_resolution, voxel_gradient = load_data(specs, args) + logging.info(f"{len_dataset} shapes in training dataset.") + logging.info(f"{args.workers} worker processes created.") + + # Model and Optimizer + ( + model, + model_discriminator, + optimizer, + scheduler, + optimizer_discriminator, + scheduler_discriminator, + use_gan, + pca, + pca_norm + ) = build_models_optimizers(specs, len_dataset, device) + model_name = type(model).__name__ + logging.info( + f"{model_name} model" + ) + logging.info( + f"{model.latents.num_embeddings} shapes encode in {model.latents.set_size} latent vectors of size {model.latents.latent_dim}." + ) + + # Setup multi gpu if needed + if torch.cuda.device_count() > 1: + logging.info(f"Using {torch.cuda.device_count()} GPUs with DataParallel.") + model = torch.nn.DataParallel(model) + if model_discriminator is not None: + model_discriminator = torch.nn.DataParallel(model_discriminator) + + # Load and setup checkpointing + history, snapshot_epochs, render_frequency, log_frequency = ( + load_setup_checkpointing( + args, + specs, + expdir, + unwrap_model(model), + optimizer, + scheduler, + model_discriminator=unwrap_model(model_discriminator), + ) + ) + n_epochs = specs.get("NumEpochs", None) + if history["epoch"] == n_epochs: + logging.info("Training already done.") + logging.info(f"Results saved in {expdir}.") + return + + if WANDB_AVAILABLE & args.use_wandb: + wandb_run = setup_wandb(args, specs, expdir, unwrap_model(model)) + else: + wandb_run = None + logging.info("WandB disabled or not available.") + + # Training hyperparametres + loss_recon = get_loss_recon(specs["ReconLoss"], reduction="none").to(device) + latent_reg_lambda = specs.get("LatentRegLambda", None) + kl_lambda = specs.get("KlLossLambda", None) + anneal_epochs = specs.get("AnnealEpochs", 1) + lipschitz_lambda = specs.get("LipschitzLambda", None) + eikonal_lambda = specs.get("EikonalLossLambda", None) + volume_lambda = specs.get("VolumeLossLambda", None) + adv_lambda = specs.get("AdvLossLambda", None) + r1_gamma = specs.get("R1LossGamma", None) + clampD = specs.get("ClampingDistance", None) + noise_std_latent = specs.get("StdNoiseLatent", None) + + # Build history to track + base_losses = { + "DeepSDF": ["loss_total", "loss_rec", "loss_reg"], + "VDeepSDF": ["loss_total", "loss_rec", "loss_kl"], + "VecSetVAE": ["loss_total", "loss_rec", "loss_kl"], + "VecSetAE": ["loss_total", "loss_rec", "loss_reg"], + + } + base_norms = { + "DeepSDF": ["lat_norm"], + "VDeepSDF": ["mu_norm", "logvar_mean"], + "VecSetVAE": ["lat_norm"], + "VecSetAE": ["lat_norm"], + } + model_type = type(unwrap_model(model)).__name__ + loss_names = base_losses.get(model_type) + norm_names = base_norms.get(model_type) + if use_gan: + loss_names += ["loss_adv", "loss_discriminator", "loss_r1"] + if lipschitz_lambda: + loss_names.append("loss_lipschitz") + if volume_lambda: + loss_names.append("loss_volume") + if eikonal_lambda and eikonal_lambda > 0: + loss_names.append("loss_eik") + extras = ["lr", "lr_lat", "CD_train_mean", "CD_val_mean"] + for key in loss_names + norm_names + extras: + history.setdefault(key, []) + + # Training + for epoch in trange(history["epoch"] + 1, n_epochs + 1): + time_epoch = time.time() + + # Run one epoch + running_losses = train_one_epoch( + model, + dataloader, + optimizer, + device, + epoch, + loss_recon, + clampD=clampD, + noise_std_latent=noise_std_latent, + eikonal_lambda=eikonal_lambda, + latent_reg_lambda=latent_reg_lambda, + kl_lambda=kl_lambda, + lipschitz_lambda=lipschitz_lambda, + volume_lambda=volume_lambda, + adv_lambda=adv_lambda, + r1_gamma=r1_gamma, + anneal_epochs_kl=anneal_epochs, + use_gan=use_gan, + voxel_resolution=voxel_resolution, + voxel_gradient=voxel_gradient, + optimizer_discriminator=optimizer_discriminator, + model_discriminator=model_discriminator, + ) + + # Update scheduler + if scheduler is not None: + scheduler.step() + if scheduler_discriminator is not None: + scheduler_discriminator.step() + + # Update epoch count + history["epoch"] += 1 + + # Update running losses + for name, value in running_losses.items(): + history[name].append(value) + + # Update learning rates + param_groups = optimizer.state_dict()["param_groups"] + history["lr"].append(param_groups[0]["lr"]) + history["lr_lat"].append(0 if len(param_groups) else param_groups[1]["lr"]) + + # Update latent norms depending on model type + lat_norms = unwrap_model(model).latents.norms + if model_type in ["DeepSDF", "VecSetVAE", "VecSetAE"]: + history["lat_norm"].append(lat_norms.detach().mean().cpu().item()) + elif model_type == "VDeepSDF": + for key in ("mu_norm", "logvar_mean"): + if key in lat_norms: + history[key].append(lat_norms[key].detach().mean().cpu().item()) + + # Log all keys in history that are lists with at least one value + if wandb_run is not None: + log_data = { + k: v[-1] for k, v in history.items() if isinstance(v, list) and v + } + wandb.log(log_data, step=epoch) + + # Renders + if render_frequency is not None: + if (epoch % render_frequency == 0) or (epoch == n_epochs): + meshes, renders, cd_train_mean = render_metric_training_meshes( + model, dataloader.dataset, specs, expdir, epoch + ) + history["CD_train_mean"].append(cd_train_mean) + if wandb_run is not None: + wandb.log( + { + "training_renders": [ + wandb.Image( + render, + caption=f"Train Shape {dataloader.dataset.instances[i]}", + ) + for i, render in enumerate(renders) + ] + }, + step=epoch, + ) + wandb.log( + {"CD_train_mean": history["CD_train_mean"][-1]}, step=epoch + ) + + # Snapshot + if epoch in snapshot_epochs: + ws.save_experiment( + expdir, + epoch, + unwrap_model(model).net, + unwrap_model(model).latents, + optimizer, + scheduler, + unwrap_model(model_discriminator), + ) + + # Checkpoint in case of a bug that requires relaunching the run + if epoch % log_frequency == 0: + ws.save_history(expdir, history) + checkpoint = ws.build_checkpoint( + epoch, + unwrap_model(model).net, + unwrap_model(model).latents, + optimizer, + scheduler, + unwrap_model(model_discriminator), + ) + ws.save_checkpoint(expdir, checkpoint) + del checkpoint + + # Print log at each epoch + msg = f"Epoch {epoch}/{n_epochs}:" + for name in running_losses: + msg += f"{name}={history[name][-1]:.6f} - " + msg = msg[:-3] + f" ({time.time() - time_epoch:.1f}s/epoch)" + logging.info(msg) + + # End of training save final history + experiments + last_epoch = history["epoch"] + checkpoint = ws.build_checkpoint( + last_epoch, + unwrap_model(model).net, + unwrap_model(model).latents, + optimizer, + scheduler, + unwrap_model(model_discriminator), + ) + ws.save_checkpoint(expdir, checkpoint) + ws.save_history(expdir, history) + ws.save_experiment( + expdir, + last_epoch, + unwrap_model(model).net, + unwrap_model(model).latents, + optimizer, + scheduler, + unwrap_model(model_discriminator), + ) + torch.cuda.empty_cache() + + # # Final test reconstruction + # logvar_init = specs.get("NetworkSpecs").get("logvar_init_value", None) + # if not args.no_test: + # for sname, split_file in zip( + # ["valid", "test"], [specs["ValidSplit"], specs["TestSplit"]] + # ): + # if split_file is not None: + # meshes, renders, cd_val_mean, latent, test_instances = ( + # reconstruct_and_render_test_shapes( + # unwrap_model(model), + # split_file, + # specs, + # sname, + # loss_recon, + # latent_reg_lambda=latent_reg_lambda, + # kl_lambda=kl_lambda, + # logvar_init=logvar_init, + # clampD=clampD, + # device="cuda", + # num_test_shapes=8, + # pca_init=pca, + # pca_norm=pca_norm + # ) + # ) + + # # Save renders, mesh and latent + # ws.save_renders(expdir, renders, str(history["epoch"]) + "_" + sname) + # latent_subdir = ws.get_recon_latent_subdir(expdir, history["epoch"]) + # mesh_subdir = ws.get_recon_mesh_subdir(expdir, history["epoch"]) + # os.makedirs(latent_subdir, exist_ok=True) + # os.makedirs(mesh_subdir, exist_ok=True) + # for i, instance in enumerate(test_instances): + # torch.save( + # latent[i : i + 1], + # os.path.join(latent_subdir, instance + ".pth"), + # ) + # meshes[i].export(os.path.join(mesh_subdir, instance + ".obj")) + # history["CD_val_mean"].append(float(np.mean(cd_val_mean))) + + # # Wandb test render and log + # if wandb_run is not None: + # wandb.log( + # { + # f"{sname}_renders": [ + # wandb.Image( + # render, + # caption=f"{sname.capitalize()} Shape {test_instances[i]}", + # ) + # for i, render in enumerate(renders) + # ] + # }, + # step=epoch, + # ) + # wandb.log( + # { + # "CD_val_mean": history["CD_val_mean"][-1], + # }, + # step=epoch, + # ) + torch.cuda.empty_cache() + + if wandb_run is not None: + wandb.finish() + + duration = time.time() - start_time + duration_msg = "{:.0f}h {:02.0f}min {:02.0f}s".format( + duration // 3600, (duration // 60) % 60, duration % 60 + ) + logging.info(f"End of training after {duration_msg}.") + logging.info(f"Results saved in {expdir}.") + + +if __name__ == "__main__": + main() diff --git a/cfd_workflow_20261012/_seiler_ref/smoothSDF_scripts/train_flow_matching.py b/cfd_workflow_20261012/_seiler_ref/smoothSDF_scripts/train_flow_matching.py new file mode 100644 index 0000000000000000000000000000000000000000..a91865faf90c88403281ddfa4d594b5533189c7f --- /dev/null +++ b/cfd_workflow_20261012/_seiler_ref/smoothSDF_scripts/train_flow_matching.py @@ -0,0 +1,357 @@ +import argparse +import copy +import json +import logging +import os +import sys +import time +from pathlib import Path +from typing import Dict + +import torch +import torch.nn as nn +from torch.utils.data import TensorDataset, DataLoader +from tqdm.auto import trange + +sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..")) + +from src.models.sdf_models import DeepSDF, VDeepSDF +from src.models.vecset_models import VecSetAE, VecSetVAE + +from src.optimizer import get_optimizer, get_scheduler +from src.mesh import create_mesh +import src.workspace as ws +from src import visualization as viz +from src.models import get_model +from src.models.flow_matching import LatentFlowMatchingModel +from src.models.flow_matching_vecset import FlowMatchingVecSet +from src.utils import get_device, set_seed +from src_optimization.utils import uniform_grid_3d +from src_optimization.optimization_function import get_Aref_init, get_opt_loss + +LOG_FORMAT = "%(asctime)s - %(levelname)s - %(message)s" +logging.basicConfig(level=logging.INFO, format=LOG_FORMAT) + + +def parser(argv=None): + parser = argparse.ArgumentParser(description="Optimize shapes with an implicit model.") + parser.add_argument("experiment", nargs="?", default="experiments/car_drivernet/deepsdf") + parser.add_argument("finetuned", nargs="?", default=None) + parser.add_argument( "--load-epoch", type=int, default=2000, help="Epoch of DeepSDF to load") + parser.add_argument("--cfg", action="store_true", help="Enable Classifier-Free Guidance") + parser.add_argument("--use_ema", action="store_true", help="Enable Exponential Moving Average") + parser.add_argument("-q", "--quiet", dest="verbose", action="store_false") + parser.add_argument("-r", "--resolution", type=int, default=128) + parser.add_argument("--seed", type=int, default=0) + parser.add_argument("-s", "--split", type=str, default="TrainSplit") + parser.add_argument("--suffix", type=str, default="") + parser.add_argument("-t", "--test", action="store_true") + return parser.parse_args(argv) + + +def rk4_step(model_fn, x: torch.Tensor, t: float, dt: float) -> torch.Tensor: + """ + Performs a single Runge-Kutta 4 integration step. + model_fn should be a callable that takes (x, t_tensor) and returns velocity. + """ + n_samples = x.shape[0] + device = x.device + + def get_t(scalar_t): + return torch.full((n_samples,), scalar_t, device=device) + + # k1 + t1 = get_t(t) + k1 = model_fn(x, t1) + + # k2 + x2 = x + 0.5 * dt * k1 + t2 = get_t(t + 0.5 * dt) + k2 = model_fn(x2, t2) + + # k3 + x3 = x + 0.5 * dt * k2 + t3 = get_t(t + 0.5 * dt) + k3 = model_fn(x3, t3) + + # k4 + x4 = x + dt * k3 + t4 = get_t(t + dt) + k4 = model_fn(x4, t4) + + return x + (dt / 6.0) * (k1 + 2 * k2 + 2 * k3 + k4) + +class EMA: + def __init__(self, model, decay=0.9999): + self.decay = decay + self.shadow = copy.deepcopy(model) + self.shadow.requires_grad_(False) + + def update(self, model): + with torch.no_grad(): + for s_param, param in zip(self.shadow.parameters(), model.parameters()): + if param.requires_grad: + s_param.data.mul_(self.decay).add_(param.data, alpha=1 - self.decay) + +def train( + args, + specs, + loader, + model_flow: nn.Module, + device: torch.device, + history_path: Path, + model_save_path: str, +): + optimizer = get_optimizer([model_flow], + type=specs["Optimizer"].pop("Type"), + lrs=specs["Optimizer"].pop("LearningRates"), + kwargs=specs["Optimizer"]) + + scheduler = get_scheduler(optimizer, **specs["LearningRateSchedule"]) + + ema = None + if args.use_ema: + logging.info("EMA enabled (decay=0.9999)") + ema = EMA(model_flow, decay=0.9999) + else: + logging.info("EMA disabled") + + loss_fn = nn.MSELoss() + history = {"loss": []} + model_flow.train() + + logging.info("Starting training...") + progress_bar = trange(specs["NumEpochs"], desc="Training") + + for _ in progress_bar: + for data in loader: + x1 = data[0].to(device) + batch_size = x1.shape[0] + + # adapter le t shape + x0 = torch.randn_like(x1) + t = torch.rand(batch_size, 1).to(device) + t = t.view(t.shape[0], *([1] * (x0.ndim - 1))) + xt = (1 - t) * x0 + t * x1 + ut = x1 - x0 + + optimizer.zero_grad() + + if args.cfg: + cond = data[1].to(device) + if cond.ndim == 1: + cond = cond.view(-1, 1) + v_pred = model_flow(xt, t.squeeze(), cond, cond_drop_prob=0.1) + else: + v_pred = model_flow(xt, t.squeeze()) + + loss = loss_fn(v_pred, ut) + loss.backward() + + optimizer.step() + + if args.use_ema and ema is not None: + ema.update(model_flow) + + current_loss = loss.item() + history["loss"].append(current_loss) + progress_bar.set_postfix({"loss": f"{current_loss:.6f}"}) + if scheduler is not None: + scheduler.step() + + if args.use_ema and ema is not None: + torch.save(ema.shadow.state_dict(), model_save_path) + logging.info(f"EMA Model saved to {model_save_path}") + else: + torch.save(model_flow.state_dict(), model_save_path) + logging.info(f"Standard Model saved to {model_save_path}") + + with open(history_path, "w") as f: + json.dump(history, f, indent=4) + + +def generate_and_visualize( + args, + model_flow: nn.Module, + model: nn.Module, + specs: Dict, + output_dir: Path, + device: torch.device, + xyz_grid: torch.Tensor, +): + """ + Handles inference, mesh generation using RK4 solver, and plotting. + """ + n_samples = 8 + n_steps = 30 + dt = 1.0 / n_steps + mesh_step = 5 + + if args.cfg: + cond_list = specs["FlowMatching"]["cfg_goal"] + guidance_scale = 1.0 + else: + cond_list = [None] + + model_flow.eval() + + for cond_val in cond_list: + logging.info(f"Generating samples for condition: {cond_val}") + + if isinstance(model, (VecSetAE, VecSetVAE)): + x = torch.randn(n_samples, specs["NetworkSpecs"]["num_latents_set"], specs["LatentDim"]).to(device) + else: + x = torch.randn(n_samples, specs["LatentDim"]).to(device) + cond_tensor = None + if args.cfg and cond_val is not None: + cond_tensor = torch.tensor([[cond_val] for _ in range(n_samples)]).to(device) + + def model_step_fn(x_curr, t_curr): + if args.cfg: + return model_flow.sample_cfg( + x_curr, t_curr, cond_tensor, guidance_scale=guidance_scale + ) + return model_flow(x_curr, t_curr) + + mesh_list = [[] for _ in range(n_samples)] + for i in trange(n_steps, desc="Integration Steps"): + t_current = i / n_steps + x = rk4_step(model_step_fn, x, t_current, dt) + if (i + 1) % mesh_step == 0: + model.latents.reset_embedding(n_samples, x) + + for idx in range(n_samples): + mesh = create_mesh( + model, + torch.tensor(idx).to(device), + N=args.resolution, + max_batch=32**3, + device=device, + ) + mesh_list[idx].append(mesh) + + torch.cuda.empty_cache() + mesh_list_final = [m for sample_meshes in mesh_list for m in sample_meshes] + titles = [ + f"Step {(i + 1) * mesh_step}" for i in range(n_steps // mesh_step) + ] + row_titles = None + if args.cfg: + specs_opt = specs.get("Optimization", {}) + opt_name = specs_opt.get("OptimizationType", "optimization") + opt_fn = get_opt_loss(specs_opt, device=device) + opt_fn_args = specs_opt.get("OptimizationArgs", {}) + model.latents.reset_embedding(n_samples, x) + cond_gen = [] + for i in trange(n_samples): + idx_sample = torch.tensor([i]).to(device) + if (opt_name == "min_drag"): + opt_fn_args["Aref_init"] = get_Aref_init(model, idx_sample, device) + out = opt_fn(xyz_grid, model, idx_sample, device=device, value_only=True, **opt_fn_args) + if isinstance(out, tuple): + out = out[-1] + cond_gen.append(out.item()) + row_titles = [f"{v:0.2e}" for v in cond_gen] + plot_filename = ( + f"generate_shape_{cond_val}.png" if args.cfg else "generate_shape.png" + ) + output_path = output_dir / plot_filename + viz.plot_render( + mesh_list_final, + titles=titles, + full_backfaces=True, + max_cols=n_steps // mesh_step, + axis_on=False, + row_titles=row_titles, + ).savefig(output_path, bbox_inches="tight", pad_inches=0.2) + logging.info(f"Saved visualization to {output_path}") + + +def main(): + args = parser() + set_seed(args.seed) + start_time = time.time() + + # Paths and Device + expdir = Path(args.experiment) + specs = ws.load_specs(str(expdir)) + flow_matching_specs = specs["FlowMatching"] + device = specs.get("Device", get_device()) + + logging.info(f"Training Flow Matching model for {expdir} on {device}") + + # Output Directory + subdir = "flow_matching/cfg" if args.cfg else "flow_matching/base" + if args.suffix != "": + subdir += f"_{args.suffix}" + flow_matching_folder = expdir / subdir + flow_matching_folder.mkdir(parents=True, exist_ok=True) + logging.info(f"Output folder: {flow_matching_folder}") + + # Model and Latent + split_path = specs[args.split] + with open(split_path, "r") as f: + split = json.load(f) + + model = get_model( + specs.get("Network"), + **specs.get("NetworkSpecs"), + latent_dim=specs["LatentDim"], + num_latents=len(split), + ).to(device) + ws.load_model(str(expdir), model.net, args.load_epoch, finetuning=args.finetuned) + ws.load_latents(str(expdir), model.latents, args.load_epoch) + model.set_requires_grad(False) + latents = model.latents.z.weight.detach().clone() + + # Initialize Flow Model + if isinstance(model, (DeepSDF, VDeepSDF)): + model_flow = LatentFlowMatchingModel(input_dim=specs["LatentDim"], hidden_dim=512).to(device) + elif isinstance(model, (VecSetAE, VecSetVAE)): + model_flow = FlowMatchingVecSet(n_latents=specs.get("NetworkSpecs").get("num_latents_set"), + channels=specs["LatentDim"]).to(device) + latents = latents.view(-1, specs.get("NetworkSpecs").get("num_latents_set"), specs["LatentDim"]) + + # Data + xyz_grid = uniform_grid_3d(32).unsqueeze(0).to(device) + + if args.cfg: + specs_opt = specs.get("Optimization", {}) + opt_name = specs_opt.get("OptimizationType", "optimization") + opt_fn = get_opt_loss(specs_opt, device=device) + opt_fn_args = specs.get("FlowMatching").get("CfgCondArgs", {}) + cond_list = [] + for i in trange(len(split)): + idx_sample = torch.tensor([i]).to(device) + if (opt_name == "min_drag"): + opt_fn_args["Aref_init"] = get_Aref_init(model, idx_sample, device) + out = opt_fn(xyz_grid, model, idx_sample, device=device, value_only=True, **opt_fn_args) + if isinstance(out, tuple): + out = out[-1] + cond_list.append(out.item()) + cond_tensor = torch.tensor(cond_list).to(device) + + if args.cfg: + dataset = TensorDataset(latents, cond_tensor) + else: + dataset = TensorDataset(latents) + + loader = DataLoader(dataset, batch_size=flow_matching_specs["BatchSize"], shuffle=True, num_workers=0, drop_last=True) + + # Train + flow_matching_specs = specs["FlowMatching"] + train(args, flow_matching_specs, loader, model_flow, device, flow_matching_folder / "history.json", flow_matching_folder / "model_flow.pt") + + # Generate & Visualize + generate_and_visualize( + args, model_flow, model, specs, flow_matching_folder, device, xyz_grid + ) + + duration = time.time() - start_time + logging.info( + f"End of optimization. Total time: {duration // 3600:.0f}h {(duration // 60) % 60:.0f}m" + ) + + +if __name__ == "__main__": + main() diff --git a/cfd_workflow_20261012/_seiler_ref/smoothSDF_scripts/train_flow_matching_2.py b/cfd_workflow_20261012/_seiler_ref/smoothSDF_scripts/train_flow_matching_2.py new file mode 100644 index 0000000000000000000000000000000000000000..6e81d193e00ec5a1e9a73b77f06bb270db409d21 --- /dev/null +++ b/cfd_workflow_20261012/_seiler_ref/smoothSDF_scripts/train_flow_matching_2.py @@ -0,0 +1,360 @@ +import argparse +import json +import logging +import os +import sys +import time +from pathlib import Path +from typing import Dict + +import numpy as np +import torch +import torch.nn as nn +import torch.optim as optim +from torch.utils.data import TensorDataset, DataLoader +from tqdm.auto import trange + +sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..")) + +from src.mesh import create_mesh +import src.workspace as ws +from src import visualization as viz +from src.models import get_model +from src.models.flow_matching import LatentFlowMatchingModel +from src.utils import get_device, set_seed +from src_optimization.utils import uniform_grid_3d +from src_optimization.optimization_function import compute_volume + +LOG_FORMAT = "%(asctime)s - %(levelname)s - %(message)s" +logging.basicConfig(level=logging.INFO, format=LOG_FORMAT) + + +def parser(argv=None): + parser = argparse.ArgumentParser(description="Optimize shapes with an implicit model (Method C - VE).") + parser.add_argument("experiment", nargs="?", default="experiments/deepsdf_2419") + parser.add_argument("finetuned", nargs="?", default=None) + parser.add_argument("-i", "--iters", type=int, default=50000, help="Training iterations") + parser.add_argument("--load-epoch", type=int, default=2000, help="Epoch of DeepSDF to load") + parser.add_argument("--lr", type=float, default=1e-4, help="Learning rate") + parser.add_argument("--batchsize", type=int, default=512, help="Batch size") + parser.add_argument("--cfg", action="store_false", help="Enable Classifier-Free Guidance") + parser.add_argument("-q", "--quiet", dest="verbose", action="store_false") + parser.add_argument("-r", "--resolution", type=int, default=128) + parser.add_argument("--seed", type=int, default=0) + parser.add_argument("-s", "--split", type=str, default="TrainSplit") + parser.add_argument("--suffix", type=str, default="") + parser.add_argument("-t", "--test", action="store_true") + # Nouveaux arguments pour le Variance Exploding (Method C) + parser.add_argument("--sigma-max", type=float, default=1.0, help="Max noise level") + parser.add_argument("--sigma-min", type=float, default=0.002, help="Min noise level") + return parser.parse_args(argv) + + +def get_preconditioned_input(x_noisy, sigma, sigma_data): + """ + Apply preconditioning: x_in = x_noisy / sqrt(sigma^2 + data_std^2) + """ + s_in = sigma.view(-1, 1) + + c_in = 1 / (s_in.pow(2) + sigma_data**2).sqrt() + + return x_noisy * c_in + + +def train( + args, + loader: DataLoader, + model_flow: nn.Module, + device: torch.device, + history_path: Path, + model_save_path: str, + latents_std: float +): + """ + Training loop for Method (c) / Variance Exploding. + """ + optimizer = optim.Adam(model_flow.parameters(), lr=args.lr) + loss_fn = nn.MSELoss() + + history = {"loss": []} + model_flow.train() + + logging.info("Starting training (Method C - Variance Exploding)...") + progress_bar = trange(args.iters, desc="Training") + + data_iter = iter(loader) + + # Paramètres pour le sampling log-normal de sigma (comme dans EDM) + P_mean = -1.2 + np.log(latents_std) + P_std = 1.2 + + for _ in progress_bar: + try: + data = next(data_iter) + except StopIteration: + data_iter = iter(loader) + data = next(data_iter) + + x_clean = data[0].to(device) + batch_size = x_clean.shape[0] + + # 1. Sample Sigma (Log-Normal distribution) + # On couvre mieux les différentes échelles de bruit qu'avec une distribution uniforme + rnd_normal = torch.randn((batch_size,), device=device) + sigma = (rnd_normal * P_std + P_mean).exp() + + # 2. Add Noise: z_s = x + s * epsilon + noise = torch.randn_like(x_clean) + x_noisy = x_clean + sigma.view(-1, 1) * noise + + # 3. Preconditioning Input + # On évite de donner des valeurs géantes au réseau + net_input = get_preconditioned_input(x_noisy, sigma, latents_std) + + # 4. Noise Conditioning + # On conditionne le réseau avec log(sigma) / 4 pour que ce soit proche de N(0,1) + sigma_cond = sigma.log() / 4.0 + + optimizer.zero_grad() + + # Prediction + if args.cfg: + cond = data[1].to(device) + if cond.ndim == 1: + cond = cond.view(-1, 1) + # Le modèle prédit EPSILON (le bruit) + pred_noise = model_flow(net_input, sigma_cond, cond, cond_drop_prob=0.1) + else: + pred_noise = model_flow(net_input, sigma_cond) + + # 5. Loss: Target is pure noise (epsilon) + # Note: L'équation (c) dit u = s*epsilon. + # Si le réseau apprend epsilon, alors u_hat = s * pred_noise. + loss = loss_fn(pred_noise, noise) + + loss.backward() + optimizer.step() + + current_loss = loss.item() + history["loss"].append(current_loss) + progress_bar.set_postfix({"loss": f"{current_loss:.6f}"}) + + with open(history_path, "w") as f: + json.dump(history, f, indent=4) + + torch.save(model_flow.state_dict(), model_save_path) + logging.info(f"Model saved to {model_save_path}") + + +def generate_and_visualize( + args, + model_flow: nn.Module, + model: nn.Module, + specs: Dict, + output_dir: Path, + device: torch.device, + xyz_grid: torch.Tensor, + latents_std: float +): + """ + Inference using Method (c) update rule (Euler step on sigmas). + z_{i-1} = z_i + (s_{i-1} - s_i) * pred_noise + """ + n_samples = 8 + n_steps = 30 + mesh_step = 5 + + # Schedule de sigma: décroissance exponentielle de sigma_max à 0 + # C'est plus adapté pour le débruitage que le temps linéaire + indices = torch.arange(n_steps + 1, dtype=torch.float64, device=device) + rho = 1.0 # Hyperparamètre EDM classique + step_indices = (indices / n_steps) ** (1 / rho) + sigmas = args.sigma_max ** (1 - step_indices) * args.sigma_min ** step_indices + # On s'assure que le dernier sigma est bien 0 pour "atterrir" sur l'image propre + sigmas[-1] = 0.0 + + if args.cfg: + cond_list = [0.01, 0.03, 0.05, 0.1] + guidance_scale = 2.5 # Un peu plus élevé pour la méthode (c) + else: + cond_list = [None] + + model_flow.eval() + + with torch.no_grad(): + for cond_val in cond_list: + logging.info(f"Generating samples for condition: {cond_val}") + + # Initialisation: Bruit pur mis à l'échelle par sigma_max + # z_start = x_mean + sigma_max * noise. Si x_mean approx 0, alors : + x = torch.randn(n_samples, specs["LatentDim"]).to(device) * args.sigma_max + + cond_tensor = None + if args.cfg and cond_val is not None: + cond_tensor = torch.tensor([cond_val]).to(device) + + mesh_list = [[] for _ in range(n_samples)] + + # Boucle de génération + for i in trange(n_steps, desc="Sampling Steps"): + sigma_cur = sigmas[i] + sigma_next = sigmas[i + 1] + + # Conditionnement pour le réseau + # Attention au broadcasting des scalaires + sigma_input = torch.full((n_samples,), sigma_cur, device=device) + sigma_cond = sigma_input.log() / 4.0 + + # Preconditioning de l'input actuel + x_in = get_preconditioned_input(x, sigma_input, latents_std) + + # Prédiction du modèle + if args.cfg: + # sample_cfg doit gérer le scaling w en interne + # pred_noise = uncond + w * (cond - uncond) + pred_noise = model_flow.sample_cfg( + x_in, sigma_cond, cond_tensor, guidance_scale=guidance_scale + ) + else: + pred_noise = model_flow(x_in, sigma_cond) + + # Étape de mise à jour (Method C / Euler VE) + # d = x_i - x_{i-1} approx (sigma_i - sigma_{i-1}) * epsilon + # x_{i-1} = x_i + (sigma_{i-1} - sigma_i) * epsilon + dt = sigma_next - sigma_cur # Négatif car on diminue le bruit + + # Update: x <- x + (sigma_next - sigma_cur) * pred_noise + # C'est l'équivalent de l'équation (c) simplifiée + x = x + dt * pred_noise + + # Visualisation intermédiaire + if (i + 1) % mesh_step == 0: + model.latents.reset_embedding(n_samples, x) + for idx in range(n_samples): + try: + mesh = create_mesh( + model, + torch.tensor(idx).to(device), + N=args.resolution, + max_batch=32**3, + device=device, + ) + mesh_list[idx].append(mesh) + except Exception as e: + logging.warning(f"Mesh generation failed at step {i}: {e}") + + torch.cuda.empty_cache() + + # --- Visualisation finale --- + mesh_list_final = [m for sample_meshes in mesh_list for m in sample_meshes if m is not None] + + # Protection contre les listes vides si la génération de mesh échoue + if not mesh_list_final: + logging.warning("No meshes were generated.") + continue + + titles = [f"Step {(i + 1) * mesh_step}" for i in range(n_steps // mesh_step)] + + row_titles = None + if args.cfg: + vol_gen = [] + model.latents.reset_embedding(n_samples, x) + for i in range(n_samples): + try: + vol = compute_volume(xyz_grid, model, torch.tensor([i]).to(device)) + vol_gen.append(vol.item()) + except: + vol_gen.append(0.0) + row_titles = [f"{v:0.2e}" for v in vol_gen] + + plot_filename = ( + f"generate_shape_{cond_val}.png" if args.cfg else "generate_shape.png" + ) + output_path = output_dir / plot_filename + + try: + viz.plot_render( + mesh_list_final, + titles=titles, + full_backfaces=True, + max_cols=n_steps // mesh_step, + axis_on=False, + row_titles=row_titles, + ).savefig(output_path, bbox_inches="tight", pad_inches=0.2) + logging.info(f"Saved visualization to {output_path}") + except Exception as e: + logging.error(f"Failed to plot: {e}") + + +def main(): + args = parser() + set_seed(args.seed) + start_time = time.time() + + expdir = Path(args.experiment) + specs = ws.load_specs(str(expdir)) + device = specs.get("Device", get_device()) + + logging.info(f"Training Flow Matching (Method C) for {expdir} on {device}") + + subdir = "flow_matching/cfg_idempotence" if args.cfg else "flow_matching/base_idempotence" + flow_matching_folder = expdir / subdir + flow_matching_folder.mkdir(parents=True, exist_ok=True) + logging.info(f"Output folder: {flow_matching_folder}") + + # Load Model & Latents + split_path = specs[args.split] + with open(split_path, "r") as f: + split = json.load(f) + + model = get_model( + specs.get("Network"), + **specs.get("NetworkSpecs"), + latent_dim=specs["LatentDim"], + num_latents=len(split), + ).to(device) + ws.load_model(str(expdir), model, args.load_epoch, finetuning=args.finetuned) + ws.load_latents(str(expdir), model.latents, args.load_epoch) + model.set_requires_grad(False) + latents = model.latents.z.weight.detach().clone() + latents_std = latents.std().item() + + # Data + xyz_grid = uniform_grid_3d(32).unsqueeze(0).to(device) + if args.cfg: + cond_list = [] + logging.info("Computing volumes for conditioning...") + for i in trange(len(split)): + vol = compute_volume(xyz_grid, model, torch.tensor([i]).to(device)) + cond_list.append(vol.item()) + cond_tensor = torch.tensor(cond_list).to(device) + dataset = TensorDataset(latents, cond_tensor) + else: + dataset = TensorDataset(latents) + + loader = DataLoader( + dataset, batch_size=args.batchsize, shuffle=True, num_workers=0, drop_last=True + ) + + # Initialize Flow Model + # Le modèle prédit l'output de même dim que l'input + model_flow = LatentFlowMatchingModel( + input_dim=specs["LatentDim"], hidden_dim=512 + ).to(device) + + # Train + train(args, loader, model_flow, device, flow_matching_folder / "history.json", flow_matching_folder / "model_flow.pt", latents_std) + + # Generate + generate_and_visualize( + args, model_flow, model, specs, flow_matching_folder, device, xyz_grid, latents_std + ) + + duration = time.time() - start_time + logging.info( + f"End of optimization. Total time: {duration // 3600:.0f}h {(duration // 60) % 60:.0f}m" + ) + + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/cfd_workflow_20261012/_seiler_ref/surrogates_code/lib.py b/cfd_workflow_20261012/_seiler_ref/surrogates_code/lib.py new file mode 100644 index 0000000000000000000000000000000000000000..5ccb303bbaf53e927b6b4241ff00252a8a919775 --- /dev/null +++ b/cfd_workflow_20261012/_seiler_ref/surrogates_code/lib.py @@ -0,0 +1,288 @@ +""" +Various utilities and helper functions&definitions. + +NOTE: I kinda put everything here. +""" + +import os, os.path +import sys +import json +import time +import random +import shutil + +from IPython.display import HTML, display +import numpy as np +from PIL import Image +import matplotlib.pyplot as plt +from tqdm.auto import tqdm +import trimesh +from scipy.spatial import KDTree +import torch +import torch.nn as nn +import torch.nn.functional as F +from torch_geometric.data import Data, Dataset +from torch_geometric.loader import DataLoader +import torch_geometric.nn as nng + +sys.path.insert(0, "../smoothSDF") +from src import visualization as viz +from src.mesh import create_mesh, create_parts, SdfGridFiller, convert_sdf_grid_to_mesh +from src.utils import (get_color_mesh, get_device, get_color_parts, get_sdf_mesh, + make_grid) + + +V_MEAN = 0.030388213749921067 +V_STD = 0.020040641709521783 +DATADIR = "/scratch/cvlab/datasets/dataset_seiler/chair_partnet" + +######################################################################################################################## +# Workspace +######################################################################################################################## + +_SUBDIRS = ['model', 'log', 'optimizer'] + +def build_experiment_dir(expdir, exist_ok=True): + """Create the experimental sub-directories.""" + for subdir in _SUBDIRS: + os.makedirs(os.path.join(expdir, subdir), exist_ok=exist_ok) + +def reset_experiment_dir(expdir, ignore_errors=True): + """Reset the experimental directory.""" + for subdir in _SUBDIRS: + shutil.rmtree(os.path.join(expdir, subdir), ignore_errors=ignore_errors) + if os.path.isfile(os.path.join(expdir, "checkpoint.pth")): + os.remove(os.path.join(expdir, "checkpoint.pth")) + build_experiment_dir(expdir) + + + +######################################################################################################################## +# GCNN Surrogate Model +######################################################################################################################## + +from torch import Tensor + +class MLP(torch.nn.Module): + r"""A multi-layer perception (MLP) model. + + Args: + channel_list (List[int]): List of input, intermediate and output + channels. :obj:`len(channel_list) - 1` denotes the number of layers + of the MLP. + dropout (float, optional): Dropout probability of each hidden + embedding. (default: :obj:`0.`) + batch_norm (bool, optional): If set to :obj:`False`, will not make use + of batch normalization. (default: :obj:`True`) + relu_first (bool, optional): If set to :obj:`True`, ReLU activation is + applied before batch normalization. (default: :obj:`False`) + """ + def __init__(self, channel_list, dropout = 0., + batch_norm = True, relu_first = False): + super().__init__() + assert len(channel_list) >= 2 + self.channel_list = channel_list + self.dropout = dropout + self.relu_first = relu_first + + self.lins = torch.nn.ModuleList() + for dims in zip(self.channel_list[:-1], self.channel_list[1:]): + self.lins.append(nng.Linear(*dims)) + + self.norms = torch.nn.ModuleList() + for dim in zip(self.channel_list[1:-1]): + self.norms.append(nn.BatchNorm1d(dim, track_running_stats = True) if batch_norm else nn.Identity()) + + self.reset_parameters() + + def reset_parameters(self): + for lin in self.lins: + lin.reset_parameters() + for norm in self.norms: + if hasattr(norm, 'reset_parameters'): + norm.reset_parameters() + + def forward(self, x: Tensor) -> Tensor: + """""" + x = self.lins[0](x) + for lin, norm in zip(self.lins[1:], self.norms): + if self.relu_first: + x = x.relu_() + x = norm(x) + if not self.relu_first: + x = x.relu_() + x = F.dropout(x, p = self.dropout, training = self.training) + x = lin.forward(x) + return x + + def __repr__(self) -> str: + return f'{self.__class__.__name__}({str(self.channel_list)[1:-1]})' + + +class GraphSAGE(nn.Module): + def __init__(self, model_parameters={ + "nb_hidden_layers":3, # number of graph convolutions + "size_hidden_layers":64, + "nb_hidden_layers2":0, # number of graph convolutions (2nd block, if needed) + "size_hidden_layers2":64, + "bn_bool":True, + "residual":False, + "encoder_hidden_size":64, # encoder is per-node MLP + "encoder_hidden_layers":2, + "decoder_hidden_size":64, # decoder is per-node MLP + "decoder_hidden_layers":2, + "latent_size":8, + "encoder_input_size":6, + "decoder_output_size":1, + "scalar_decoder":True, # MLP on pooled nodes for scalar pred + "scalar_decoder_size":64, + "scalar_decoder_layers":2, + "scalar_decoder_output_size":1} + ): + super().__init__() + + self.nb_hidden_layers = model_parameters["nb_hidden_layers"] + self.size_hidden_layers = model_parameters["size_hidden_layers"] + self.nb_hidden_layers2 = model_parameters["nb_hidden_layers2"] + self.size_hidden_layers2 = model_parameters["size_hidden_layers2"] + self.bn_bool = model_parameters["bn_bool"] + self.activation = nn.ReLU() + self.scalar_decoder = model_parameters["scalar_decoder"] + self.residual = model_parameters["residual"] + + encoder_params = [model_parameters["encoder_input_size"]] + [model_parameters["encoder_hidden_size"] for _ in range(model_parameters["encoder_hidden_layers"])] + [model_parameters["latent_size"]] + + self.encoder = MLP(encoder_params, batch_norm = False) + + self.in_layer = nng.SAGEConv( + in_channels = encoder_params[-1], + out_channels = self.size_hidden_layers + ) + + self.hidden_layers = nn.ModuleList() + for n in range(self.nb_hidden_layers - 1): + self.hidden_layers.append(nng.SAGEConv( + in_channels = self.size_hidden_layers, + out_channels = self.size_hidden_layers + )) + if self.nb_hidden_layers2 > 0: + self.hidden_inter = nng.Linear(self.size_hidden_layers, self.size_hidden_layers2) + self.hidden_layers.append(nng.SAGEConv( + in_channels = self.size_hidden_layers, + out_channels = self.size_hidden_layers2 + )) + for n in range(self.nb_hidden_layers2 - 1): + self.hidden_layers.append(nng.SAGEConv( + in_channels = self.size_hidden_layers2, + out_channels = self.size_hidden_layers2 + )) + + + self.out_layer = nng.SAGEConv( + in_channels = (self.size_hidden_layers if self.nb_hidden_layers2 == 0 else self.size_hidden_layers2), + out_channels = model_parameters["latent_size"] + ) + + if self.bn_bool: + self.bn = nn.ModuleList() + for n in range(self.nb_hidden_layers): + self.bn.append(nn.BatchNorm1d(self.size_hidden_layers, track_running_stats = False)) + if self.nb_hidden_layers2 > 0: + for n in range(self.nb_hidden_layers2): + self.bn.append(nn.BatchNorm1d(self.size_hidden_layers2, track_running_stats = False)) + + if self.scalar_decoder: + self.scalar_branch = [] + self.scalar_branch.append(nn.Linear(model_parameters["latent_size"], model_parameters["scalar_decoder_size"])) + self.scalar_branch.append(nn.ReLU(inplace=True)) + for _ in range(model_parameters["scalar_decoder_layers"] - 1): + self.scalar_branch.append(nn.Linear(model_parameters["scalar_decoder_size"], model_parameters["scalar_decoder_size"])) + self.scalar_branch.append(nn.ReLU(inplace=True)) + self.scalar_branch.append(nn.Linear(model_parameters["scalar_decoder_size"], model_parameters["scalar_decoder_output_size"])) + self.scalar_branch = nn.Sequential(*self.scalar_branch) + + + def forward(self, data): + z, edge_index = data.x , data.edge_index.type(torch.int64) + z = self.encoder(z) + + z = self.in_layer(z, edge_index) + if self.bn_bool: + z = self.bn[0](z) + z = self.activation(z) + + for n in range(self.nb_hidden_layers + self.nb_hidden_layers2 - 1): + if self.residual: + z_residual = z + z = self.hidden_layers[n](z, edge_index) + if self.bn_bool: + z = self.bn[n + 1](z) + z = self.activation(z) + if self.residual: + z = z + (z_residual if z_residual.shape[-1] == z.shape[-1] else self.hidden_inter(z_residual)) + + z = self.out_layer(z, edge_index) + + if self.scalar_decoder: + zs = nng.pool.global_mean_pool(z, data.batch) + zs = self.scalar_branch(zs) + return zs + + + +######################################################################################################################## +# Data +######################################################################################################################## + +def surface_preprocess(mesh, device='cpu', edge_attr=False, exact_normals=False, verts=None): + face_normals = torch.tensor(mesh.face_normals, dtype=torch.float32)#.to(device) + edges = torch.tensor(mesh.edges)#.to(device) + faces = torch.tensor(mesh.faces)#.to(device) + + if edge_attr: + if exact_normals: + edge_normals = torch.stack([torch.mean( + face_normals[torch.where(((faces == edge[0]).any(axis=1) & (faces == edge[1]).any(axis=1)))[0]], axis=0) for + edge in edges]).cpu().numpy() + else: + # Alternative way of taking average of vertices normals (which are average of face normals) + edge_normals = mesh.vertex_normals[mesh.edges].mean(1) + edges_features = np.concatenate([mesh.vertices[mesh.edges[:, 1]] - mesh.vertices[mesh.edges[:, 0]], edge_normals], + axis=1) + edges_features = torch.tensor(edges_features, dtype=torch.float32) + else: + edges_features = None + + if verts is None: + verts = torch.tensor(mesh.vertices, dtype=torch.float32) + x = torch.tensor(np.concatenate([mesh.vertices, mesh.vertex_normals], axis=1), dtype=torch.float32) + else: + x = torch.cat([verts, torch.tensor(mesh.vertex_normals).float().to(verts.device)], dim=1) + data_object = Data(x=x, edge_index=edges.T, edge_attr=edges_features) + return data_object.to(device) + + +class MeshDataset(Dataset): + def __init__(self, datadir, instances, return_volume=True, resolution=None): + super().__init__() + self.datadir = datadir + self.instances = instances + self.return_volume = return_volume + self.res = resolution + + with open("/scratch/cvlab/datasets/dataset_seiler/chair_partnet/volume/volumes.json", 'r') as f: + volumes = json.load(f) + + self.meshes = [] + self.volumes = [] + for instance in tqdm(instances): + mesh = trimesh.load(os.path.join(datadir, "meshes", instance + ".obj")) + self.meshes.append(surface_preprocess(mesh)) + v_standardized = (volumes[instance] - V_MEAN) / V_STD + self.volumes.append(v_standardized) + + def __len__(self): + return len(self.meshes) + + def __getitem__(self, idx): + return self.meshes[idx], self.volumes[idx] diff --git a/cfd_workflow_20261012/_seiler_ref/surrogates_code/train_surrogate.py b/cfd_workflow_20261012/_seiler_ref/surrogates_code/train_surrogate.py new file mode 100644 index 0000000000000000000000000000000000000000..3b97dfe2f6fe75278c4bebe641084649fabae027 --- /dev/null +++ b/cfd_workflow_20261012/_seiler_ref/surrogates_code/train_surrogate.py @@ -0,0 +1,225 @@ +""" +Main training script for the surrogate GCNN. +""" + +import os +import os.path +import sys +import json +import time +import logging +import argparse +from multiprocessing import cpu_count + +import torch +import torch.nn as nn +from torch_geometric.loader import DataLoader +import wandb + +sys.path.insert(0, os.path.join(os.path.dirname(__file__), "../smoothSDF")) +from src import workspace as ws +from src.utils import get_device, set_seed, configure_logging +from src.train_utils import setup_wandb + +from lib import ( + DATADIR, + reset_experiment_dir, build_experiment_dir, + GraphSAGE, MeshDataset, +) + +device = get_device() + + +def parser(argv=None): + """Parse the arguments.""" + parser = argparse.ArgumentParser(description="Train a deep implicit representation network with part supervision.") + + parser.add_argument("experiment", nargs="?", default="experiments/surr_1000") + parser.add_argument('--debug', action='store_true', help="increase verbosity to print debugging messages") + parser.add_argument('--no-resume', action='store_true', help="do not resume the experiment if existing and start form epoch 0") + parser.add_argument('--no-test', action='store_true', help="do not perform final test reconstruction") + parser.add_argument('-q', '--quiet', dest="verbose", action='store_false', help="disable verbosity and run in quiet mode") + parser.add_argument('--reset', action='store_true', help="force a reset of the experimental directory") + parser.add_argument('--seed', type=int, default=0, help="initial seed for the RNGs (default=0)") + parser.add_argument('--workers', type=int, default=16, help="number of worker subprocesses preparing batches (use 0 to load in the main process)") + + # Specific for surrogate training + parser.add_argument('--no-preload', action='store_false', dest="preload", help="do not preload the data on CPU (slower but less memory usage)") + + args = parser.parse_args(argv) + + return args + + +@torch.no_grad() +def validate_model(model, dataloader_test, device, criterion): + model.eval() + total_val_loss = 0 + with torch.no_grad(): + for batch in dataloader_test: + data = batch[0].to(device) + volume = batch[1].to(device) + output = model(data) + val_loss = criterion(output.view(-1), volume.view(-1)) + total_val_loss += val_loss.item() + return {'val_loss': total_val_loss / len(dataloader_test)} + + +def main(args=None): + # Initialization + if args is None: + args = parser() + num_workers = min(args.workers, cpu_count()) + set_seed(args.seed) + start_time = time.time() + + expdir = args.experiment + specs = ws.load_specs(expdir) + device = specs.get("Device", get_device()) + if args.reset: + reset_experiment_dir(expdir) + else: + build_experiment_dir(expdir) + configure_logging(args, os.path.join(ws.get_log_dir(expdir), "trainlog.txt")) + + wandb_run = setup_wandb(args, specs, expdir) + + logging.info(f"Command: python {' '.join(sys.argv)}") + logging.info(f"Date: " + time.strftime("%d %B %Y at %H:%M:%S (%Y%m%d-%H%M%S)")) + logging.info(f"Running experiment in {expdir}. (on {device})") + logging.info(f"arguments = {args}") + + ## Data + resolution = specs["Resolution"] + batch_size = specs.get("BatchSize", 8) + valid_frequency = specs.get("ValidFrequency", 10) + + with open(os.path.join(DATADIR, "splits", "raw_train2419.json"), "r") as f: + train_instances = json.load(f) + with open(os.path.join(DATADIR, "splits", "raw_valid484.json"), "r") as f: + test_instances = json.load(f) + + dataset_train = MeshDataset(DATADIR, train_instances[:1000], return_volume=True, resolution=resolution) + dataset_test = MeshDataset(DATADIR, test_instances[:200], return_volume=True, resolution=resolution) + len_dataset = len(dataset_train) + dataloader_train = DataLoader(dataset_train, batch_size=batch_size, shuffle=True, num_workers=num_workers) + dataloader_test = DataLoader(dataset_test, batch_size=batch_size, shuffle=False, num_workers=num_workers) + + logging.info(f"{len_dataset} shapes in training dataset.") + if valid_frequency is not None: + logging.info(f"{len(dataset_test)} shapes in validation dataset.") + logging.info(f"{num_workers} worker processes created.") + + ## Model + model_parameters = specs["ModelParameters"] + model = GraphSAGE(model_parameters=model_parameters).to(device) + logging.info(f"Model has {sum(x.nelement() for x in model.parameters()):,} parameters.") + + ## Loss and optimizer + n_epochs = specs['NumEpochs'] + criterion = nn.MSELoss() + optimizer = torch.optim.Adam(model.parameters(), lr=specs["LearningRate"]) + scheduler = specs.get("Scheduler", None) + if scheduler is not None and scheduler.lower() == "step": + scheduler = torch.optim.lr_scheduler.StepLR(optimizer, step_size=n_epochs//4, gamma=0.5) + + ## Resume from checkpoint + history = {'epoch': 0} + if not args.no_resume: + if os.path.isfile(os.path.join(expdir, "checkpoint.pth")): + checkpoint = torch.load(os.path.join(expdir, "checkpoint.pth")) + model.load_state_dict(checkpoint['model_state_dict']) + optimizer.load_state_dict(checkpoint['optimizer_state_dict']) + if scheduler is not None: + scheduler.load_state_dict(checkpoint['scheduler_state_dict']) + history = torch.load(os.path.join(expdir, "log", "history.pth")) + ws.clip_history(history, checkpoint['epoch']) + del checkpoint + + if history['epoch'] > 0: + logging.info(f"Loaded checkpoint from epoch={history['epoch']}.") + + ## Training loop + log_frequency = specs.get("LogFrequency", 10) + for k in ['train_loss', 'val_loss']: + if k not in history: + history[k] = [] + for epoch in range(history['epoch']+1, n_epochs+1): + model.train() + total_loss = 0 + time_epoch = time.time() + for ibatch, batch in enumerate(dataloader_train): + data = batch[0].to(device) + volume = batch[1].to(device) + optimizer.zero_grad() + output = model(data) + loss = criterion(output.view(-1), volume.view(-1)) + loss.backward() + optimizer.step() + total_loss += loss.item() + optimizer.zero_grad() + if scheduler is not None: + scheduler.step() + + logging.info(f"Epoch {epoch+1}/{n_epochs}, Training Loss: {total_loss/len(dataloader_train):.6f}" + \ + f" ({time.time() - time_epoch:.2f}s)") + history['train_loss'].append(total_loss / len(dataloader_train)) + history['epoch'] += 1 + + # Validation + if valid_frequency is not None and epoch % valid_frequency == 0: + val_metrics = validate_model(model, dataloader_test, device, criterion) + logging.info(f"Epoch {epoch+1}/{n_epochs}, Validation Loss: {val_metrics['val_loss']:.6f}") + history['val_loss'].append(val_metrics['val_loss']) + + # WandB + if wandb_run is not None: + wandb.log({f"loss/train": history['train_loss'][-1]}, step=epoch) + if valid_frequency is not None and epoch % valid_frequency == 0: + wandb.log({f"loss/valid": history['val_loss'][-1]}, step=epoch) + + # Checkpoint + if epoch % log_frequency == 0: + torch.save(model.state_dict(), os.path.join(expdir, "model", f"model_{epoch}.pth")) + torch.save(optimizer.state_dict(), os.path.join(expdir, "optimizer", f"optimizer_{epoch}.pth")) + if scheduler is not None: + torch.save(scheduler.state_dict(), os.path.join(expdir, "optimizer", f"scheduler_{epoch}.pth")) + torch.save(history, os.path.join(expdir, "log", "history.pth")) + checkpoint = {'epoch': epoch} + checkpoint['model_state_dict'] = model.state_dict() + checkpoint['optimizer_state_dict'] = optimizer.state_dict() + checkpoint['scheduler_state_dict'] = scheduler.state_dict() if scheduler is not None else None + torch.save(checkpoint, os.path.join(expdir, "checkpoint.pth")) + del checkpoint + + # End of training + last_epoch = history['epoch'] + torch.save(model.state_dict(), os.path.join(expdir, "model", f"model_{last_epoch}.pth")) + torch.save(optimizer.state_dict(), os.path.join(expdir, "optimizer", f"optimizer_{last_epoch}.pth")) + if scheduler is not None: + torch.save(scheduler.state_dict(), os.path.join(expdir, "optimizer", f"scheduler_{last_epoch}.pth")) + torch.save(history, os.path.join(expdir, "log", "history.pth")) + checkpoint = {'epoch': last_epoch} + checkpoint['model_state_dict'] = model.state_dict() + checkpoint['optimizer_state_dict'] = optimizer.state_dict() + checkpoint['scheduler_state_dict'] = scheduler.state_dict() if scheduler is not None else None + torch.save(checkpoint, os.path.join(expdir, "checkpoint.pth")) + torch.cuda.empty_cache() # release unused GPU memory + + # Final validation + val_metrics = validate_model(model, dataloader_test, device, criterion) + logging.info(f"Final Validation Loss: {val_metrics['val_loss']:.6f}") + torch.cuda.empty_cache() + + if wandb_run is not None: + wandb.finish() + + duration = time.time() - start_time + duration_msg = "{:.0f}h {:02.0f}min {:02.0f}s".format(duration // 3600, (duration // 60) % 60, duration % 60) + logging.info(f"End of training after {duration_msg}.") + logging.info(f"Results saved in {expdir}.") + + +if __name__ == "__main__": + args = parser() + main(args=None) \ No newline at end of file