Density-Bridged Level-Set Method for smooth-boundary topology optimization
A FEniCSx framework that couples the density and level-set fields through a differentiable, volume-constrained mapping — giving you the global search speed of SIMP with the clean, additive-manufacturing-friendly boundaries of the level-set method.
Important
This repository is no longer maintained because we are progressing on another work that includes a refactored version of this repository. Issues here will be solved, but not in this repository.
The new work is currently private and scheduled to be published in Jan. 2027. If you want new functions or have questions, you can ask us on the issue page.
Our manuscript has been submitted to Structural Multidisciplinary Optimization for review.
- What is DB-LSM?
- Highlights
- Results at a glance
- Repository structure
- Module reference
- Installation
- Quick start
- Usage tutorial
- Performance notes: the linear solver
- Building the documentation
- Citing DB-LSM
- License and contact
Density-based topology optimization (SIMP) is fast and explores the design space aggressively, but it produces gray transition regions, staircase boundaries and checkerboards that need heavy post-processing. The level-set method (LSM) produces clean, smooth interfaces and handles topological merging naturally, but it converges slowly, cannot nucleate holes on its own, and reacts strongly to the initial condition. DB-LSM is built on a simple observation:
The density field converges to a sound topology even from a discrete, level-set-like initialization. So the density field can be used as a carrier that drives the level-set field.
The bridge is a differentiable, volume-constrained mapping
| Symbol | Meaning |
|---|---|
| Dynamic scale parameter, found by bisection so that |
|
| Steepness; continued from |
|
| Threshold parameter, fixed by the volume fraction | |
| Prescribed target volume fraction | |
| Small exclusion margin keeping the volume w.r.t. |
Because
Fig. 1 — The volume-constraint mapping. (a) density from a direct level-set initialization, (b) mapped density ℋ(φ, α, β, γ) from the normalized level set, (c) the mapping sensitivity ∂ℋ/∂φ, which is concentrated in a narrow band around the interface.
Fig. 2 — The mapping function at α = 0.6. It is Heaviside-like with ℋ(0) = Vf, so the level-set zero iso-surface is pinned to the target density and the interface does not drift.
The second ingredient is sensitivity transfer. Given
or through the chain rule,
Finally, an adaptive three-stage scheduler wraps everything:
stage 1: DENSITY stage 2: HEURISTIC stage 3: LEVEL_SET
(density-bridged (compare DB vs. H-J (Hamilton–Jacobi
global exploration) by OIA, switch freely) boundary refinement)
with plateau detection,
Fig. 3 — Cantilever benchmark (100×50 mesh, Vf = 0.4). Both density-bridged variants reach a lower compliance faster than SIMP and classical LSM, with reinitialization spikes kept bounded.
-
Fast. Per-iteration cost is
$1.35%$ above classical SIMP in 3D and 45–62 % below classical LSM on the 2D cantilever benchmark — while producing fundamentally smoother boundaries. -
Volume-constrained by construction. The mapping solves for
$\alpha$ by bisection every iteration, so the mapped density satisfies$\int \mathcal{H} = V_f|D|$ without a penalty term. - Seamless scheme switching. Density-bridged and Hamilton–Jacobi updates share one objective, so the framework can compare them and switch mid-run using the objective improvement asymmetry (OIA) metric instead of a fixed schedule.
- Budget-aware results. The last stage is a boundary-refinement stage, so you get a usable, smooth geometry at almost any iteration cap — see Fig. 6.
-
Four methods, one interface.
DensityLSMOptimProblem(DB-LSM),LevelSetOptimProblem(LSM),ODELSMProblem(ODE-LSD), andSIMPOptimProblem(SIMP) share the same benchmark and output conventions, making apples-to-apples comparison trivial. -
Built for dataset generation. Clean boundaries, a stable
.npybest-result format, STL/VTP export, and a 2D/3D lattice-connection benchmark suite aimed at generating structural datasets.
Fig. 10 — Extracted compliance of DB-LSM, SIMP, LSM and ODE-LSD across six target volume fractions on the 2D lattice-connection problem.
cellgen is the library; everything else exists to drive it, test it, or document it.
DB-LSM/
├── cellgen/ # ★ the library — FEniCSx topology optimization
│ ├── problems/ # optimization problems: DB-LSM, LSM, ODE-LSM, SIMP
│ ├── drivers/ # DensityLSMDriver: stage loop, OIA comparison, nucleation
│ ├── schedulers/ # three-stage scheduler + plateau detector (pure Python)
│ ├── backend/ # optimizer backends: OC, MMA, MMA-bridged, LSM, ODE-LSM
│ ├── filters/ # Helmholtz, distance, tanh projection, threshold projection, Allen–Cahn
│ ├── top/ # math core: level-set↔density casting, velocity extension, H-J update
│ ├── sdf/ # reinitialization, normalization, SDF blending
│ ├── optim/ # OC / MMA numerics, OptimizationHistory (pure NumPy)
│ ├── metrics/ # mnd, gsr, TAI, OIA
│ ├── materials/ # MaterialProperty, StructuralSteel
│ ├── mechanics.py # strain/stress/UFL forms, SIMP interpolation
│ ├── interfaces/ # Protocol contracts between layers
│ ├── utils/ # meshes, volumes, Heaviside/Dirac, LU solvers, L2 projection, H¹
│ ├── io/ # STL / VTP / VTU export, mesh→SDF
│ ├── plot/ # contour + PyVista visualization
│ ├── postprocessing/ # consistent-density compliance, floating-island removal
│ ├── benchmarks/ # problem initializers (geometry, BCs, φ₀, masks)
│ ├── cells/ # strut/TPMS unit cells, meshing, lattice database
│ └── homo/ # numerical homogenization + visualization (needs dolfinx_mpc)
│
├── demos/ # ★ problem definitions per benchmark — 10 families
│ ├── cantilever_beam/ # 2D cantilever (DB-LSM / LSM / ODE-LSM / SIMP)
│ ├── catilever_bridged_test/ # bottom-loaded cantilever — standalone runnable
│ ├── cantilever_3d/ # 3D cantilever
│ ├── mbb_beam/ # half MBB beam
│ ├── L_bracket/ # L-bracket
│ ├── square_2d/ # quarter square under biaxial tension — standalone runnable
│ ├── gripper/ # 2D compliant gripper (custom objective: displacement maximization)
│ ├── cell_conn/ # 2D/3D heterogeneous lattice connection
│ ├── plate_support_3d/ # 3D plate support
│ └── alcoa_aerocraft_bracket/ # 3D Alcoa aircraft bracket (engineering case)
│
├── archives/ # ⚠ reference only: historical run scripts + saved results.
│ │ # Contains the `sol_*.py` runners that actually execute most demos,
│ │ # plus the CSV/NPY results quoted in the manuscript. DO NOT MODIFY.
│ ├── Cantilever_example/ # 2D cantilever: DB-LSM(OC/MMA), LSM, ODE-LSM, SIMP, comparisons
│ ├── Cantilever_3d_example/ # 3D cantilever runs
│ ├── L_bracket_example/ # L-bracket: all methods, different filter radii
│ ├── MBB_example/ # MBB beam runs
│ ├── Alcoa_bracket_3d_example/
│ ├── plate_support_3d/
│ ├── gripper_2d/
│ ├── single_cell_conn_2d/ # lattice connection, 2D
│ ├── single_cell_conn_3d/ # lattice connection, 3D (3×3, 5×5)
│ └── cell_dataset_generation_2d/ # dataset generation scripts
│
├── tests/ # test & validation scripts (need FEniCSx + PyVista)
│ ├── top/ # casting, ground structure, Allen–Cahn, SIMP utils
│ ├── schedulers/ # pure-Python scheduler tests (safe to run anywhere)
│ ├── filters/ sdf/ utils/ io/ mechanics/ homo/ optim/ benchmarks/ ...
│ └── README.md
│
├── docs/ # Sphinx documentation
│ ├── source/ # RST API stubs + conf.py
│ ├── proofs/OC_Asymptotic_Proof.pdf # derivation behind the OC asymptotic update
│ └── Makefile, make.bat
│
├── works/ # scratch / exploratory scripts
│ ├── scripts/mapping_function.py # standalone plot of the mapping H(φ)
│ ├── scripts/illustration_of_init_cond.py
│ ├── mbb_beam_examples/DBLSM/more_holes.py
│ └── slepc_test.py # SLEPc eigensolver smoke test (not TO)
│
├── reports/ # slide deck + figure dump for internal reports
├── backup/ # legacy code kept for reference (not imported anywhere)
│
├── assets/readme/ # down-sampled figures used by this README
├── AGENTS.md # contributor/agent orientation notes
├── CITATION.cff # machine-readable citation metadata
├── TRUSS_Documentation.md # legacy note on generateTRUSS (see backup/, not wired up)
├── requirements.txt # documentation tooling + optional third-party libs
└── README.md
Fig. 11 — Code architecture of the framework. Dashed = element-wise transfer, dotted = gradient-based transfer, dash-dot = LSM (Hamilton–Jacobi) update. The Problem owns the physics and the objective, the Backend owns the design-space update, the Scheduler owns the stage transitions, the β schedule, plateau detection and the reinitialize/compare/stop signals, and the Driver coordinates all of them.
The dependency direction is strictly bottom-up, which is what keeps the pieces testable:
| Layer | Packages | Responsibility |
|---|---|---|
| L0 — foundations | utils, materials, mechanics, interfaces, metrics, optim, sdf |
Mesh measures, Heaviside/Dirac kernels, linear solvers, material model, UFL forms, quality metrics, pure-NumPy optimizers, level-set reinitialization |
| L1 — kernels | top, filters |
The density bridge (level_set_to_density), velocity extension, H-J update, and all spatial regularization |
| L2 — backends | backend |
Turn an ObjectiveResult into a new design field: OC, MMA, MMA-bridged (level-set space), LSM, ODE-LSM |
| L3 — orchestration | schedulers, drivers, problems |
Stage/beta/plateau logic, the DB-LSM loop and OIA comparison, and the physics-owning problem classes |
| L4 — setup & output | benchmarks, cells, homo, io, plot, postprocessing, demos |
Problem initialization, unit-cell geometry, homogenization, export and visualization |
A run therefore flows: benchmarks.initialize_* → problems.*OptimProblem → problem.solve() →
drivers.DensityLSMDriver.run() → top.level_set_to_density → backend.*.update() →
schedulers.DensityLSMScheduler.step() → optim.OptimizationHistory + XDMF snapshots.
Every public name listed below is importable from the package or submodule shown.
The four problem classes. They own the FEM state solve, the filters, metric logging and file output;
subclasses only implement compute_displacement(mu, lmbda).
| Class | File | What it does |
|---|---|---|
DensityLSMOptimProblem + DensityLSMProblemConfig
|
problems/density_levelset_problem.py |
DB-LSM. Owns forward_cast (φ→ρ), optim_target (filter → FEM → update_level_set, log_epoch, and the whole XDMF/history/best-result pipeline. solve() builds a DensityLSMDriver and runs it. |
LevelSetOptimProblem + LevelSetProblemConfig
|
problems/level_set_problem.py |
Classical LSM baseline: shape sensitivity |
ODELSMProblem + ODELSMProblemConfig
|
problems/odelsm_problem.py |
ODE-driven level-set density method (ODE-LSD) baseline: |
SIMPOptimProblem + SIMPOptimProblemConfig
|
problems/simp_problem.py |
Classical SIMP baseline with OC or MMA and optional projection filter. |
DensityLSMBestResult (J, phi, rho, mnd, solid_frac, target_vol_frac, step_type,
iter_num) is the sample snapshot written by store_best_result.
| Item | What it does |
|---|---|
DensityLSMDriver |
The central coordinator. run() iterates: reinitialize (if signalled) → forward_cast → optim_target → update via the selected scheme → scheduler.step() → log_epoch(). Handles should_reinitialize, should_compare, should_stop. |
DensityLSMDriverConfig |
Frozen dataclass for loop-level knobs: oia_switch_tolerance=-0.02, compare_min_interval=5, use_early_stop=False, and the hole-nucleation block (hole_nucleation, nucleation_phi_lim=0.98, nucleation_depth=-0.15, nucleation_factor=1.3, nucleation_top_frac=0.02, nucleation_interval=5, …). |
DensityLSMProblemProtocol, DensityLSMConfigProtocol |
typing.Protocol contracts — the driver never imports problems, which keeps the dependency graph acyclic. |
DensityLSMOptimTargetResult |
NamedTuple (rho_filtered, J, dJ_drho, beta) returned by optim_target. |
| Item | What it does |
|---|---|
DensityLSMScheduler |
step(step_type, objective) returns a SchedulerDecision(stage, plateau, mean_relative_change, objective_cv, should_reinitialize, should_compare, should_stop). |
SchedulerStage |
DENSITY → HEURISTIC → LEVEL_SET, split by density_iteration_prop / heuristic_prop (defaults 30 % / 35 %). |
DensityLSMSchedulerConfig |
max_iterations, use_HJ_steps, *_reinit_interval, compare_interval, both stage proportions, plateau thresholds, β schedule (beta_init, beta_second, beta_max), force_switch_threshold, stop_plateau_count. |
PlateauDetector |
Sliding-window stagnation test: plateau when |
| Class | Design field | Sensitivity transfer | Notes |
|---|---|---|---|
OCBackend |
|
element-wise |
OCBackendConfig; updates optim.optimization_criteria
|
MMADensityBackend |
element-wise | MMA in density space with a volume constraint | |
MMABridgedBackend |
gradient-based | MMA in the level-set space (backend_type="mma-bridged") |
|
LSMBackend |
|
shape sensitivity |
Pre-compiled Hamilton–Jacobi advection use_hilbertian_extension=True by default |
ODELSMBackend |
|
|
ObjectiveResult(value, gradient) is the common currency, and the OptimBackend Protocol declares
backend_type ∈ {density, density_bridged, level_set} and solver_type ∈ {ndarray, Function}.
| Function | What it does |
|---|---|
level_set_to_density(phi, V_rho, vol_frac, rho_min, rho_max, beta, tol, elem_mask) |
The bridge. Interpolates φ to DG0, bisects for α so that ForwardCastResult(rho, drho_dphi, meta) with meta = {alpha, beta, method, volume_fraction_phi}. |
rho_from_phi / rho_from_phi_drv
|
The mapping |
phi_from_rho |
Inverse mapping — used only to derive bounds. |
density_to_level_set |
Inverse cast. Deprecated; DB-LSM never maps density back. |
compute_velocity_field(...) |
Normal velocity from the shape sensitivity, with the volume-correction Lagrange multiplier and either the Hilbertian extension (default) or a mass-matrix solve. |
update_level_set(phi0, V_n, w, g, dt) |
Hamilton–Jacobi update |
solve_hilbertian_velocity(...) |
|
create_ground_structure / create_connection_level
|
Ground-structure node-pair generation for lattice connections. |
| Class / function | What it does |
|---|---|
HelmholtzFilter |
Implicit density filter: |
DistanceBasedFilter |
Cone filter filter_type="element" (volume-weighted, DG0) or "node" (CG1, no volume weight) |
ThresholdProjectionFilter |
The TPF from the paper: eta = vol_frac to keep the zero iso-surface intact. |
ProjectionFilter / tanh_projection
|
Standard tanh projection, |
AllenCahnFilter |
Phase-field sharpening |
normalize_levelset(phi, h_min, factor, nodal_mask) (reinitialize then clip into reinitialize_level_set, reinitialize_sdf (fast marching, structured meshes only), blend_sdf,
dof_array_to_grid, compute_max_deviation, compute_gradient_variance.
Always normalize φ before calling
level_set_to_density/density_to_level_set.
| Package / module | Key API | Purpose |
|---|---|---|
cellgen.mechanics |
strain, stress_u, stress_e, strain_energy, strain_energy_density, mises_stress, mises_strain, effective_stress_u/e, lame_params, effective_lame_params
|
UFL constitutive helpers. Signature convention is (mu, lmbda) — shear modulus first. |
cellgen.materials |
MaterialProperty, StructuralSteel
|
Isotropic linear elasticity. Supply any consistent pair among (E,ν), (λ,μ), (E,μ), (λ,ν), (μ,ν), (E,λ) — the rest are derived and consistency-checked. Also elasticity_tensor_viogt, elasticity_tensor_c4. |
cellgen.interfaces |
DensityDisplacementInterface |
Protocol requiring mat, msh, design_mask, compute_displacement(mu, lmbda). |
cellgen.metrics |
mnd, gsr, topology_activity_index, oia
|
Mean non-discreteness |
cellgen.optim |
optimization_criteria, monotone_bisection_search_phi, MMASolver, MMAConfig, OptimizationHistory
|
OC Lagrange multiplier search (asymptotic or bisection), MMA subproblem wrapper (mmapy), and the per-iteration history container. |
cellgen.utils |
Region, transform_region_points, element_volumes, nodal_volumes, element_centroids, min_mesh_size, volume_fraction_phi, node_mask_from_elem_mask, is_dg0_space, is_cg1_space, heaviside*, dirac_delta*, smoothed_sign_function, sigmoid, solve_linear_problem, LinearSolver, solve_l2_projection, CachedL2Projector, Hilbertian_product, Hilbertian_norm, finite_difference, scale_mesh*
|
The true base layer: mesh measures, smoothed Heaviside/Dirac kernels, linear solvers, L2 projection, |
| Package | Key API | Purpose |
|---|---|---|
cellgen.io |
export_stl, export_level_set_surface, extract_level_set_surface, export_function_mesh, load_mesh_from_file, sdf_grid_from_mesh |
Iso-surface extraction (native contour or marching cubes with a padded exterior so the surface closes at the domain boundary) → .stl / .vtp / .ply / .obj; fields → .vtu; triangle mesh → SDF volume. |
cellgen.plot |
save_levelset_contour_2d, save_threshold_contour_2d, plot_function_pv, ImplicitPlotter |
Headless PNG writers (Matplotlib Agg) and interactive PyVista views. |
cellgen.postprocessing |
consist_density, final_structural_strain_energy |
Re-filter and re-project a density field so compliance is reported on a consistent field — use this when comparing methods fairly. |
| Package | Key API | Purpose |
|---|---|---|
cellgen.benchmarks |
initialize_cantilever_example_mid, initialize_cantilever_example_bottom, initialize_cantilever_3d, initialize_mbb_beam_example, initialize_L_bracket, initialize_square_problem_2d, initialize_gripper_2d, initialize_plate_support_3d, initialize_alcoa_bracket_3d, initialize_cell_conn_2d/3d, initialize_holes
|
Build mesh, material, spaces V1 (CG1 level set) / V2 (displacement), initial φ₀, Dirichlet BCs, tagged load measure(s) and design masks. Returning (mat, msh, V1, V2, phi0, bcs, ds_load) is the common contract. |
cellgen.cells |
StrutCell, TPMSCell, BaseCell, build_strut_levelset, build_cell_density, StrutLatticeDatabase
|
Strut/TPMS unit-cell geometry: point+connectivity definitions, capsule-SDF sampling, periodic gmsh meshing, and a picklable lattice database (STRUT_SPECS_2D, STRUT_SPECS_3D). |
cellgen.homo |
CellHomogenization, HomogenizationVisualizer
|
Periodic homogenization of a unit cell → effective elasticity tensor dolfinx_mpc.
|
cellgen.homoand thecell_connbenchmarks needdolfinx_mpc.cellgen/__init__.pyguards that import and printsdolfinx_mpc is unavailable, cell connection benchmark would be unaccessableinstead of failing.
Each folder defines a Problem subclass per method. Only 5 files are directly runnable — the rest
are library modules, executed by the sol_*.py runners in archives/.
| Folder | Benchmark | Runnable directly? |
|---|---|---|
square_2d/ |
Quarter square, biaxial tension, |
✅ square_2d_DBLSM.py (runs both oc and mma-bridged), square_2d_SIMP.py
|
catilever_bridged_test/ |
Bottom-loaded 2D cantilever, |
✅ cantilever_btm_DBLSM.py, cantilever_btm_SIMP.py
|
mbb_beam/ |
Half MBB beam, |
✅ mbb_beam_SIMP.py (DB-LSM via archives/MBB_example/) |
cantilever_beam/ |
1.0 × 0.5 cantilever, |
via archives/Cantilever_example/*/sol_*.py
|
cantilever_3d/ |
3D cantilever, |
via archives/Cantilever_3d_example/*/sol_*.py
|
L_bracket/ |
L-bracket, |
via archives/L_bracket_example/*/sol_*.py
|
gripper/ |
2D compliant gripper (displacement maximization) | via archives/gripper_2d/gripper_simp/sol_*.py
|
cell_conn/ |
2D/3D lattice connection (periodic BCs) | via archives/single_cell_conn_2d/ and _3d/
|
plate_support_3d/ |
3D plate support, |
via archives/plate_support_3d/sol_*.py
|
alcoa_aerocraft_bracket/ |
3D Alcoa bracket, 120k hex | via archives/Alcoa_bracket_3d_example/
|
DB-LSM is not a pip-installable package — it is a source tree that expects FEniCSx and its neighbours to be provisioned in the environment (typically conda, often under WSL).
Install FEniCSx 0.10 (the version used for all timings in the manuscript) via conda-forge:
conda create -n dblsm -c conda-forge fenics-dolfinx=0.10 mpich pyvista matplotlib scipy tqdm
conda activate dblsm# Lattice-cell meshing, SDF, export, homogenization visualization
conda install -c conda-forge gmsh python-gmsh meshio trimesh scikit-fmm scikit-image seaborn sympy
pip install mesh_to_sdf mmapy pyinstrumentrequirements.txt only lists the documentation toolchain plus a few optional libraries. It is not
a complete runtime manifest.
| Library | Needed for |
|---|---|
dolfinx_mpc |
cellgen.homo, cellgen.benchmarks.cell_conn_2d/3d, all of demos/cell_conn/ |
slepc4py |
only works/slepc_test.py (eigen-solver demo, unrelated to topology optimization) |
mmapy |
the MMA backends (mma, mma-bridged) |
mesh_to_sdf, trimesh |
cellgen.io.tri_mesh_sdf |
There is no setup.py / pyproject.toml; cellgen is imported from the source tree. The repo ships a
.env for VS Code (PYTHONPATH=${PYTHONPATH}:., OMP_NUM_THREADS=4), and .vscode/tasks.json
provides a 4-rank MPI task. From a shell:
cd /path/to/DB-LSM
export PYTHONPATH=.Under WSL/conda always export
PYTHONPATHto the project root, otherwiseimport cellgenfails.
The fastest honest smoke test is the quarter-square benchmark, which runs both density backends:
cd /path/to/DB-LSM
export PYTHONPATH=.
python demos/square_2d/square_2d_DBLSM.pyIt chdirs into its own folder, so the outputs land next to the script:
demos/square_2d/
├── square_2d_dbslm_oc_results/
│ ├── square_2d_dbslm_oc.xdmf # per-iteration rho, phi, elem_mask
│ └── square_2d_dbslm_oc_history.csv # one row per iteration
└── square_2d_dbslm_mma_bridged_results/
├── square_2d_dbslm_mma_bridged.xdmf
└── square_2d_dbslm_mma_bridged_history.csv
Two more standalone scripts: demos/mbb_beam/mbb_beam_SIMP.py (SIMP baseline) and
demos/catilever_bridged_test/cantilever_btm_DBLSM.py (bottom-loaded cantilever, DB-LSM).
Open the .xdmf in ParaView to watch ρ and φ evolve. To run anything 3D, use MPI (the 3D demos are
library modules, so drive them through their archived runners):
mpirun -n 4 bash -c "PYTHONPATH=. python archives/plate_support_3d/sol_plate3d_DBLSM_oc.py"Every DB-LSM script is four steps: initialize a benchmark → subclass the problem → build a config →
call solve().
from dolfinx import fem
import ufl
from cellgen.problems import DensityLSMOptimProblem, DensityLSMProblemConfig
from cellgen.drivers import DensityLSMDriverConfig
from cellgen.benchmarks import initialize_cantilever_example_mid
from cellgen.mechanics import strain, stress_e
from cellgen.utils import LinearSolver
# ---- 1. Problem definition -------------------------------------------------
class MyCantilever(DensityLSMOptimProblem):
"""Only compute_displacement is mandatory."""
def __init__(self, config: DensityLSMProblemConfig):
mat, msh, V1, V2, phi0, bcs, ds_load = initialize_cantilever_example_mid(
L=1.0, H=0.5, elx=100, ely=50, hole_x=6, hole_y=4
)
V0 = fem.functionspace(msh, ("DG", 0)) # density space
super().__init__(mat=mat, msh=msh, V0=V0, V1=V1, phi0=phi0, config=config)
self.V2, self.bcs, self.ds_load = V2, bcs, ds_load
self.traction = fem.Constant(msh, (0.0, -1.5e6))
# cache the assembly/factorization of the stiffness operator
self._mu, self._lmbda = fem.Function(V0), fem.Function(V0)
u, v = ufl.TrialFunction(V2), ufl.TestFunction(V2)
a = ufl.inner(
stress_e(self._mu, self._lmbda, strain(u)), strain(v)
) * ufl.dx
L = ufl.inner(self.traction, v) * self.ds_load
self._solver = LinearSolver(comm=msh.comm, a=a, bcs=bcs)
self.L_form = fem.form(L)
self.u_sol = fem.Function(V2)
def compute_displacement(self, mu: fem.Function, lmbda: fem.Function):
self._mu.x.array[:] = mu.x.array[:]
self._lmbda.x.array[:] = lmbda.x.array[:]
self._solver.solve(L_form=self.L_form, u=self.u_sol)
return self.u_sol
# ---- 2. Configuration ------------------------------------------------------
cfg = DensityLSMProblemConfig(
vol_frac=0.4,
max_iterations=100,
backend_type="mma-bridged", # density-bridged + gradient transfer
result_dir="my_run/",
history_filename="history.csv",
)
# ---- 3. Solve --------------------------------------------------------------
problem = MyCantilever(cfg)
phi = problem.solve(driver_config=DensityLSMDriverConfig())problem.solve() internally creates the DensityLSMDriver, opens the XDMF file, runs the staged
loop, writes history.csv, and (optionally) stores the best result.
Two extension points you will occasionally override beyond compute_displacement:
optim_target(rho, return_sens=True)— return a custom objective and gradient (see the gripper, which maximizes output displacement instead of minimizing compliance:demos/gripper/gripper_dblsm.py).initialize_density()— only relevant for the SIMP problem; used by the Alcoa, cell-connection and plate-support demos to respect a design mask.
Fig. 12 — The cantilever benchmark shown in the paper: a 2.0 m × 1.0 m domain on a 100×50 mesh, fixed at the left edge, with traction τ = 1.5×106 N/m applied at mid-height on the right edge. The code example above uses the half-scale geometry (L=1.0, H=0.5), which is dimensionally equivalent.
DensityLSMProblemConfig is the single knob panel. Grouped by concern:
Physics and volume
| Field | Default | Notes |
|---|---|---|
vol_frac |
(required) | Target eta and the mapping's |
penalty |
3.0 |
SIMP exponent |
rho_min / rho_max
|
1e-3 / 1.0
|
Weaker material bound / physical density cap |
Filters and regularization
| Field | Default | Notes |
|---|---|---|
apply_density_filter, density_filter_radius
|
True, 1.5
|
Cone filter on ρ, radius in units of |
apply_proj_filter, proj_filter_beta
|
True, 5.0
|
Threshold projection; keep β small, large values create spurious holes |
apply_sensitivity_filter, sensitivity_filter_radius, sensitivity_filter_p
|
True, 2.0, 1.25
|
Node filter on the shape sensitivity for the H-J stage |
apply_helmholtz_filter, helmholtz_filter_alpha
|
False, 0.1
|
Off by default — see pitfalls |
apply_allen_chain_filter, allen_chain_filter_*
|
True, 0.6 / 1.0 / 0.1 / 1
|
Phase-field sharpening, H-J stage only |
norm_factor |
5.0 |
|
strict_boundary_mask |
False |
Fix φ at boundary-adjacent dofs |
Scheduler and stage control (mirrors DensityLSMSchedulerConfig)
| Field | Default | Notes |
|---|---|---|
max_iterations |
100 |
Total budget — this is your "iteration budget" knob |
use_HJ_steps |
True |
False ⇒ pure density-bridged updates with a linear β ramp, no stage switching |
density_iteration_prop / heuristic_prop |
0.30 / 0.35 |
Stage 1 / stage 2 shares; stage 3 gets the rest |
density_reinit_interval / level_set_reinit_interval |
10 / 3 |
Reinit cadence per active scheme |
beta_init / beta_second / beta_max |
8 / 100 / 100 |
β continuation endpoints |
plateau_window, plateau_mean_threshold, plateau_cv_threshold |
10, 5e-3, 0.10 |
Stagnation test |
force_switch_threshold |
0.90 |
Force the switch to the level-set stage at this fraction of the budget |
Density backend
| Field | Default | Notes |
|---|---|---|
backend_type |
"mma-bridged" |
"oc" | "mma" | "mma-bridged"
|
mma_asyinit, mma_asydecr, mma_move
|
0.5, 0.7, 0.1
|
MMA asymptotes and move limit |
mma_auxiliary_penalty, mma_auxiliary_penalty_sq, mma_log_constraint
|
1e6, 1.0, False
|
Auxiliary penalty controls how fast the solid fraction relaxes to |
Level-set backend
| Field | Default | Notes |
|---|---|---|
lsm_backend_type |
"lsm" |
"lsm" (Hamilton–Jacobi) or "odelsm"
|
mu_lsm |
0.1 |
|
use_hilbertian_extension |
True |
Hilbertian velocity extension (recommended) |
velocity_factor, volume_penalty
|
1.0, 10.0
|
H-J time step scale and volume-correction weight |
Output
| Field | Default | Notes |
|---|---|---|
result_dir |
"density_lsm_optim_results/" |
Relative to the process CWD, not the script |
result_filename |
"density_lsm_optim.xdmf" |
Per-iteration rho, phi, elem_mask (+ displacement if enabled) |
history_filename |
"history.csv" |
One row per iteration |
store_best_result, best_sample_vf_tol, best_result_filename |
False, 0.025, "dblsm_best_result.npy" |
Sample the best level-set-stage state within a volume tolerance |
save_best_result_plot, write_displacement, compute_consist_compliance |
False |
Serial-only plots, displacement snapshots, consistent-compliance column |
Loop-level behaviour lives in a separate object, DensityLSMDriverConfig, passed to solve():
from cellgen.drivers import DensityLSMDriverConfig
problem.solve(driver_config=DensityLSMDriverConfig(
oia_switch_tolerance=-0.02, # switch when OIA drops below this
compare_min_interval=5, # at least N steps between trial comparisons
use_early_stop=False, # stop when the scheduler says so
hole_nucleation=False, # topological-derivative nucleation (element transfer only)
))backend_type |
Solver | Sensitivity transfer | When to use |
|---|---|---|---|
"oc" |
Optimality criteria | element-wise ( |
Cheapest. The L-bracket and 2D lattice-connection results use this. No interior hole nucleation — pair with hole_nucleation=True or a good initial hole layout. |
"mma" |
MMA, density space | element-wise | MMA convergence control but still element transfer. |
"mma-bridged" |
MMA, level-set space | gradient-based ( |
Recommended default. Robust, and the gradient transfer preserves intrinsic hole nucleation once gradient clipping is applied. All 3D cases use this. |
lsm_backend_type picks what runs in the final refinement stage: "lsm" (Hamilton–Jacobi, default) or
"odelsm" (reuses the ODE-LSD update inside the DB-LSM loop).
Rule of thumb from the manuscript: use OC + element transfer for 2D problems with a reasonable initial hole layout, and MMA + gradient transfer for 3D or hard problems where the initial condition is poor.
The scheduler divides max_iterations into three stages and emits a SchedulerDecision each step:
| Stage | Iterations | Active scheme | What happens |
|---|---|---|---|
1 — DENSITY |
first density_iteration_prop |
always density-bridged | Global exploration at fixed beta_init. Hole nucleation is allowed here if enabled. |
2 — HEURISTIC |
next heuristic_prop |
compares DB vs. H-J | β is ramped linearly toward beta_second. On a plateau (or every compare_interval), a trial step of the inactive scheme is evaluated and OIA decides whether to switch. |
3 — LEVEL_SET |
remainder | always H-J | Boundary refinement at high β; Allen–Cahn sharpening active. Committed permanently once entered (on plateau, or forced at force_switch_threshold). |
Early stopping is available via stop_plateau_count consecutive plateaus, but it is off by default
(use_early_stop=False) — deliberately, because the framework is designed to produce good geometry at
any budget rather than to run to convergence.
Signals you can rely on in logs: stage, method (density / level_set), plateau, beta,
mean_rc (mean relative objective change), cv (objective coefficient of variation).
history.csv — one row per iteration. Column names:
iteration, convergence, volume_fraction, strain_energy, vol_frac_change, mnd,
avg_material_move, beta, target_gradient, gsr, interface_area, tai,
plateau, mean_rc, cv, delta_t, solid_frac, method
| Column | Meaning |
|---|---|
strain_energy |
The objective |
volume_fraction |
Mean mapped density over the design mask |
solid_frac |
True solid fraction of the level set, vol_frac
|
mnd |
Mean non-discreteness, |
gsr |
Gray-scale ratio: fraction of elements strictly between void and solid |
beta |
Current mapping steepness |
plateau, mean_rc, cv
|
Plateau flag and the two statistics behind it |
delta_t |
Wall-clock seconds for the iteration |
method |
density or level_set — which scheme produced this step |
Quick-check with pandas:
import pandas as pd
h = pd.read_csv("demos/square_2d/square_2d_dbslm_oc_results/square_2d_dbslm_oc_history.csv")
print(h[["iteration", "method", "beta", "strain_energy", "solid_frac", "mnd"]].tail(10))
print("stage switches:", h.loc[h["method"].ne(h["method"].shift()), ["iteration", "method"]])*.xdmf — the time series. Each step contains rho (DG0), phi (CG1) and elem_mask; add
write_displacement=True to also store the displacement field.
dblsm_best_result.npy (with store_best_result=True) — a DensityLSMBestResult payload:
J, phi, rho, mnd, solid_frac, target_vol_frac, step_type, iter_num.
from cellgen.io import extract_level_set_surface, export_stl, export_function_mesh
# watertight iso-surface of phi = 0 -> STL for printing / CAD
export_stl(phi, filename="cantilever.stl", level_set_value=0.0, grid_resolution=120)
# or get the PyVista object first, to inspect or transform it
surface = extract_level_set_surface(phi, level_set_value=0.0, grid_resolution=120)
print(surface.n_points, "vertices", surface.n_cells, "faces")
# dump the raw field on the native mesh
export_function_mesh(phi, filename="phi.vtu", field_name="phi")Headless PNG snapshots (useful inside batch scripts):
from cellgen.plot import save_levelset_contour_2d
save_levelset_contour_2d(
msh=problem.msh, phi=phi,
title="DB-LSM result", output_path="result.png", dpi=300,
)extract_level_set_surface pads the domain with an artificial void layer by default
(pad_boundary=True), so the iso-surface closes cleanly where the structure meets the boundary —
important for STL export.
Most demos/ modules are library definitions. The ready-made runners live in archives/ and are
executed from the repo root (they chdir themselves and import demos.*):
export PYTHONPATH=.
# 2D cantilever — every method, same geometry
python archives/Cantilever_example/dblsm_mma_drv_trans_full/sol_mma_bridged.py # DB-LSM, MMA+grad
python archives/Cantilever_example/dblsm_oc_density_only/sol_density_only.py # DB-LSM, OC+elem
python archives/Cantilever_example/levelset_method/sol_levelset.py # classical LSM
python archives/Cantilever_example/odelsm_cantilever/sol_odelsm.py # ODE-LSD
python archives/Cantilever_example/simp_oc/sol_cantilever_top.py # SIMP
# 3D cantilever
python archives/Cantilever_3d_example/oc_dblsm_3d/sol_dblsm_3d_oc.py
python archives/Cantilever_3d_example/mma_dblsm_3d/sol_dblsm_3d_mma_bridge.py
python archives/Cantilever_3d_example/simp_cantilever_3d/sol_3d_SIMP.py
# Engineering case (heaviest: 120k hex, run under MPI)
mpirun -n 4 bash -c "PYTHONPATH=. python archives/Alcoa_bracket_3d_example/sol_alcoa_bracket_3d_dblsm.py"Each runner is a ~20-line file: build a config, instantiate the demo class, call solve(). Copy one
and edit it to sweep parameters — that is the intended workflow, since there is no CLI.
Comparing reported compliance fairly. Different methods report config.compute_consist_compliance=True adds a consist_compliance column, or call
cellgen.postprocessing.final_structural_strain_energy on a saved result.
Element-based transfer suppresses interior motion via the boundary factor
problem.solve(driver_config=DensityLSMDriverConfig(
hole_nucleation=True,
nucleation_phi_lim=0.98, # only deep-solid elements are candidates
nucleation_depth=-0.15, # phi assigned to nucleated elements
nucleation_top_frac=0.02, # nucleate on the worst 2% of candidates
nucleation_interval=5,
min_nucleation_iter=5,
))Nucleation is skipped this way for gradient-based transfer: it already nucleates holes on its own, and extra nucleation can slow convergence or degrade the result (see Fig. 7).
Subclass and override optim_target. The gripper demos are the reference implementation — they solve
an adjoint problem to maximize output displacement instead of minimizing compliance:
from cellgen.drivers import DensityLSMOptimTargetResult
class MyGripper(DensityLSMOptimProblem):
def optim_target(self, rho, return_sens=True):
...
return DensityLSMOptimTargetResult(rho_filtered, J, dJ_drho, beta)See demos/gripper/gripper_dblsm.py.
3D problems work unchanged — the same config, larger meshes. Run them with mpirun; PyVista/Matplotlib
output is gated on msh.comm.size == 1, so in parallel runs rely on the XDMF series and reload it
serially afterwards.
demos/cell_conn/ requires two StrutCell objects plus periodic constraints from dolfinx_mpc:
from cellgen.cells import StrutCell
from cellgen.benchmarks import initialize_cell_conn_2d
from cellgen.utils import RegionRunners: archives/single_cell_conn_2d/sol_cell_conn_dblsm.py (2D) and
archives/single_cell_conn_3d/DBLSM_result/sol_Octet_Kelvin_DBLSM_3x3.py (3D). These are the scripts
used to generate the structural dataset in the manuscript.
cfg = DensityLSMProblemConfig(
vol_frac=0.3, max_iterations=120, backend_type="mma-bridged",
store_best_result=True,
start_best_sample_iter=10, # ignore early level-set steps
best_sample_vf_tol=0.025, # reject samples off the volume target
best_result_filename="sample.npy",
result_dir="dataset/sample_0001/",
)Read it back with result = np.load("sample.npy", allow_pickle=True).item(), which returns the
DensityLSMBestResult (φ, ρ and metadata).
-
demos/is mostly a problem catalogue. 24 of 29 modules only define a class; running them directly writes nothing. Use thearchives/**/sol_*.pyrunners, or instantiate +solve()yourself. -
result_diris relative to the process CWD. Standalone demos and archive runners bothchdirfirst. If you launch from elsewhere, you will not find your output. -
Always normalize φ before casting.
normalize_levelset(phi, h_min, factor)keeps φ in$[-1,1]$ ;level_set_to_densitywarns when$\max\lvert\phi\rvert > 1.1$ . -
Never use
dolfinx's defaultLinearProblem.solve()for the state solve — see below. -
HelmholtzFilteris currently latent-broken when enabled: it requires abcsargument that the two problem call sites do not pass. It is off by default (apply_helmholtz_filter=False), so the default path is unaffected. UseDistanceBasedFilterfor density filtering. -
dolfinx_mpcis optional.import cellgenprints a warning and skipshomowhen it is missing; onlycell_connbenchmarks and homogenization need it. -
gripperpackage export is incomplete.demos/gripper/__init__.pyexports onlyGripperSIMPProblem; importGripperDBLSMProblemfromdemos.gripper.gripper_dblsm. -
works/mbb_beam_examples/DBLSM/more_holes.pyhas a stale import path intoarchives; the correct import isfrom demos.mbb_beam import MBBDensityLSMProblem. -
demos/catilever_bridged_test/has no__init__.py(note the repo's spelling) — intentional, it is not part of thedemospackage, so you cannot import it asdemos.catilever_bridged_test.*. -
Experimental / legacy modules that are not wired into the main path:
cellgen/top/ground_structure.py(unstructured helpers marked Unchecked),cellgen/top/lsm_density.density_to_level_set(deprecated),cellgen/sdf/mesh_gen_2d.py,cellgen/filters/distance_filters.BinomialSensitivityFilter,cellgen/postprocessing/floating_struct_removal.py, and everything inbackup/.TRUSS_Documentation.mddocumentsgenerateTRUSS, which now only exists inbackup/conn/.
Do not use dolfinx's default LinearProblem.solve() to write compute_displacement — the default
Krylov settings are unsuitable here. Either configure PETSc explicitly:
problem = LinearProblem(
a, L, bcs=self.bcs, petsc_options_prefix="fem",
petsc_options={"ksp_type": "preonly", "pc_type": "lu"}
)or use the cached solver shipped with the package, which is what every demo does:
from cellgen.utils import solve_linear_problem
u = fem.Function(self.V2) # container of result
solve_linear_problem(a, L, u, bcs=self.bcs)For repeated solves with a fixed operator, reuse the factorization:
from cellgen.utils import LinearSolver
solver = LinearSolver(comm=msh.comm, a=a, bcs=self.bcs)
solver.solve(L_form=L_form, u=u) # factorizes once, reuses afterwardsReference timings from the manuscript (2D cantilever, FEniCSx 0.10, Intel Xeon Platinum 8368Q):
| Method | s / iteration |
|---|---|
| SIMP (OC) | 0.034 |
| SIMP (MMA) | 0.090 |
| DB-LSM (OC + element transfer) | 0.049 |
| DB-LSM (MMA + gradient transfer) | 0.070 |
| Classical LSM | 0.128 |
The API reference is generated with Sphinx + autodoc from the cellgen docstrings.
docs/source/ holds conf.py plus the pre-generated RST stubs, and docs/proofs/ holds a derivation.
pip install -r requirements.txt # Sphinx, myst-parser, pydata-sphinx-themerequirements.txt is documentation-first — it does not install the FEniCSx runtime, so install that
separately (see Installation). autodoc imports cellgen to introspect it, and
cellgen/__init__.py pulls in cellgen.mechanics, which does from dolfinx import fem at module
level — so FEniCSx must be importable to build the docs. autodoc_mock_imports only stubs the
optional extras (gmsh, cellgen.top, microgen, cadquery, OCP).
cd docs
make htmlconf.py does not modify sys.path, but the Makefile exports PYTHONPATH to the repository root
itself, so no manual environment setup is required. The html target depends on apidoc, so the RST
stubs are regenerated before the HTML is built.
The result lands in docs/build/html/ (gitignored) — open docs/build/html/index.html.
docs/make.bat is a thin sphinx-build wrapper that neither regenerates the stubs nor sets
PYTHONPATH, so on Windows run the two steps explicitly:
cd docs
$env:PYTHONPATH = ".."
sphinx-apidoc -f -o source ../cellgen ../cellgen/tests ../microgen
sphinx-build -M html source build(PowerShell's PYTHONPATH=.. make html form does not work — that is POSIX shell syntax. If you have
GNU make available, e.g. via WSL or Git Bash, make html is the simplest route.)
cd docs
make apidocThis runs sphinx-apidoc -f -o source ../cellgen "../cellgen/tests" "../microgen": -f overwrites
stale stubs, and the exclusions keep only the main package documented.
If the package layout changes substantially, refresh from the repository root instead:
PYTHONPATH=. sphinx-nested-apidoc -f -o docs/source cellgen cellgen/tests microgendocs/proofs/OC_Asymptotic_Proof.pdfcontains the derivation behind the OC asymptotic update implemented incellgen/optim/oc.py.docs/source/conf.pystill carries the legacy project name (project = 'TopoCellGeneration'), so the rendered site title does not yet read "DB-LSM".- Because
cellgen.topis inautodoc_mock_imports, that subpackage's API is not introspected — the level-set/density casting reference has to be read from the source or this README.
Xue, Y., Yang, W., Zhao, Z., and Chen, S. — A density-bridged level-set framework for smooth-boundary topology optimization. Submitted to Structural and Multidisciplinary Optimization (under review).
@article{xueDensityBridgedLevelSet2026,
title = {A density-bridged level-set framework for smooth-boundary topology optimization},
author = {Xue, Yinwu and Yang, Weizhu and Zhao, Zhenan and Chen, Shikun},
journal = {Structural and Multidisciplinary Optimization},
note = {Under review},
year = {2026}
}The manuscript abstract states the code is open-sourced at https://github.com/FRIEDparrot/DB-LSM.
CITATION.cff provides machine-readable metadata; GitHub's "Cite this repository" button reads it.
The archived software has a persistent concept DOI,
10.5281/zenodo.24718198, which resolves to the latest
version (currently v1.0.3, version DOI 10.5281/zenodo.24718199).
@software{parrotDBLSM,
title = {{DB-LSM}: Density-Bridged Level-Set Method},
author = {Parrot, Fried},
year = {2026},
url = {https://github.com/FRIEDparrot/DB-LSM},
doi = {10.5281/zenodo.24718198},
version = {1.0.3},
license = {AGPL-3.0-only},
organization = {Northwestern Polytechnical University}
}DB-LSM stands on the following work; these are the references the implementation follows most closely.
| Contribution | Reference |
|---|---|
| Level-set method for structural topology optimization | Wang, Wang & Guo (2003) — CMAME 192:227–246 |
| Level-set + sensitivity analysis | Allaire, Jouve & Toader (2004) — JCP 194:363–393 |
| SIMP material distribution | Bendsøe (1989) — Struct. Optim. 1:193–202 |
| Density method → level-set via cut elements (closest predecessor) | Andreasen, Elingaard & Aage (2020) — SMO 62:685–707 |
| ODE-driven level-set density method (ODE-LSD baseline) | Liu et al. (2021) — CMAME 387:114159 |
| Density/sensitivity filters | Bourdin (2001) — IJNME 50:2143–2158; Sigmund (2001) — SMO 21:120–127 |
| Threshold projection | Wang, Lazarov & Sigmund (2011) — SMO 43:767–784 |
| Hilbertian velocity extension | De Gournay (2006) — SIAM J. Control Optim. 45:343–367 |
| Topological derivative for hole nucleation | Burger, Hackl & Ring (2004) — JCP 194:344–362 |
| RBF-parametric level sets (alternative LSM family) | Wang & Wang (2005) — IJNME |
| Level-set methods review | van Dijk et al. (2013) — SMO |
| Multilattice embedding (application motivation) | Sanders, Pereira & Paulino (2021) — Sci. Adv. 7:eabf4838 |
| FEniCSx / DOLFINx | Baratta et al. (2023) |
The full bibliography (including the Allen–Cahn and TopCut references) is in the manuscript's
DB_LSM.bib.
Released under the GNU Affero General Public License v3.0 — see LICENSE. AGPL means network use counts as distribution: if you run a modified DB-LSM as a service, you must offer the source.
- Author: Fried Parrot (Yinwu Xue) — Northwestern Polytechnical University
- Email: friedparrot@mail.nwpu.edu.cn
- ORCID: 0009-0008-2937-2509
- Issues: https://github.com/FRIEDparrot/DB-LSM/issues
Bug reports and questions are still answered here even though active development has moved on — see the notice at the top.





