Skip to main content

Topological Free-energy Gradient Theory toolkit for topology-force, topology optimization, and topological free-gradient solving.

Project description

TFGT

TFGT (tfgt) is a Python package for projected topology-state free-energy modeling, topology-gradient optimization, and solver-assisted geometry/layout generation.

Current release: 1.0.3.

Positioning

TFGT provides computational tools for working with free-energy gradients in declared state spaces:

  • topology-state coordinates projected from flow or structural observations;
  • design fields used in topology optimization;
  • semantic or engineering layout variables used in geometry generation.

The central modeling pattern is:

state/design coordinate -> free energy -> projected gradient -> constrained update

For a reduced topology-state coordinate xi, the core identity is:

f_xi = -grad_xi(F_top)

For design and layout optimization, the practical update is:

x_next = projection(x - eta * lambda_top * grad(E(x)))

The package also includes NS++ helper functions that can use an equivalent projected forcing channel in declared numerical experiments:

f_eq = -lambda_top * grad(F_top)
rho * Du/Dt = -grad(p) + div(tau) + f_eq

This is a model-level computational channel. It should be calibrated and validated for the specific projection, scale, mobility, and observable being studied.

Installation

pip install tfgt

Install a specific version:

python -m pip install "tfgt==1.0.3"

Install from source:

pip install .

Verify the installed version:

python -c "import tfgt; print(tfgt.__version__)"

Core Concepts

Free-Energy Fields

tfgt.energy builds scalar free-energy fields from thermal, concentration, phase, velocity, pressure, and synthetic seed fields. These fields can be used for diagnostics, projected forces, or optimization objectives.

import numpy as np
from tfgt import build_free_energy_field, gaussian_seed

temperature = gaussian_seed((64, 64), center=(0.45, 0.50), sigma=0.18)
concentration = gaussian_seed((64, 64), center=(0.60, 0.55), sigma=0.22)

F_top = build_free_energy_field(
    temperature=temperature,
    concentration=concentration,
)

print(F_top.shape)

Projected Topological Force

topological_force computes the negative gradient of a scalar free-energy field. In reduced or declared physical models, this can be interpreted as an equivalent projected drive.

import numpy as np
from tfgt import TFGTParameters, topological_force, topological_activity_index

x = np.linspace(-1.0, 1.0, 64)
y = np.linspace(-1.0, 1.0, 64)
xx, yy = np.meshgrid(x, y, indexing="ij")
F_top = np.exp(-6.0 * (xx**2 + yy**2))

params = TFGTParameters()
force = topological_force(
    F_top,
    lambda_top=params.lambda0,
    spacing=(x[1] - x[0], y[1] - y[0]),
)

print(force.shape)
print(topological_activity_index(F_top, lambda_top=params.lambda0))

NS++ Helper RHS

nspp_rhs and nspp_acceleration provide a compact way to evaluate a Navier-Stokes-style right-hand side with an equivalent topology-gradient channel.

import numpy as np
from tfgt import TFGTParameters, nspp_rhs

n = 32
x = np.linspace(-1.0, 1.0, n)
xx, yy = np.meshgrid(x, x, indexing="ij")
F_top = np.exp(-6.0 * (xx * xx + yy * yy))

velocity = np.zeros((2, n, n), dtype=float)
zero = np.zeros_like(velocity)
params = TFGTParameters()

rhs = nspp_rhs(
    velocity=velocity,
    rho=1.0,
    pressure_gradient=zero,
    tau_divergence=zero,
    f_top=F_top,
    lambda_top=params.lambda0,
    spacing=x[1] - x[0],
)

print(rhs.shape)

Topology Optimization

TopologyOptimizer is a general projected-gradient optimizer for design fields or topology fields. It supports bounds, optional volume-fraction projection, static gradients, and dynamic gradients recomputed during iteration.

import numpy as np
from tfgt import (
    LayoutEnergyWeights,
    TopologyOptConfig,
    TopologyOptimizer,
    layout_free_energy,
    layout_free_energy_gradient,
)

n = 64
rng = np.random.default_rng(7)
design0 = rng.uniform(0.05, 0.20, size=(n, n))

obstacle = np.zeros((n, n), dtype=float)
obstacle[20:45, 28:36] = 1.0

source = np.zeros((n, n), dtype=float)
target = np.zeros((n, n), dtype=float)
source[8:12, 8:12] = 1.0
target[52:56, 52:56] = 1.0

weights = LayoutEnergyWeights(length=0.02, smooth=0.18, obstacle=5.0, terminal=3.0)
config = TopologyOptConfig(step_size=0.08, max_iters=250, volume_fraction=0.22)

result = TopologyOptimizer(config).optimize(
    design0,
    energy_fn=lambda x: layout_free_energy(
        x,
        obstacle_mask=obstacle,
        source_mask=source,
        target_mask=target,
        weights=weights,
    ),
    grad_fn=lambda x: layout_free_energy_gradient(
        x,
        obstacle_mask=obstacle,
        source_mask=source,
        target_mask=target,
        weights=weights,
    ),
)

print(result.final_energy)
print(float(np.mean(result.design)))

This optimizer is a general free-energy topology optimizer. Full industrial structural compliance optimization requires coupling it to an external FEM stiffness/adjoint solver.

2D Free-Energy Spatial Layout

FreeEnergySpatialSolver2D solves generic 2D spatial distribution problems using explainable free-energy terms:

  • boundary legality;
  • object clearance and overlap avoidance;
  • obstacle keep-out;
  • target attraction;
  • role/category sectors;
  • topology links;
  • mass balance and compactness;
  • local alignment and even distribution;
  • optional grid snapping.
from tfgt.layout import (
    AlignmentGroup2D,
    FreeEnergyLayout2DConfig,
    FreeEnergySpatialSolver2D,
    RoleSector2D,
    SpatialBounds2D,
    SpatialItem2D,
    SpatialLink2D,
    SpatialObstacle2D,
)

items = [
    SpatialItem2D("A", size=(8.0, 4.0), role="left"),
    SpatialItem2D("B", size=(6.0, 4.0), role="middle"),
    SpatialItem2D("C", radius=2.5, role="right"),
]

solver = FreeEnergySpatialSolver2D(
    SpatialBounds2D((80.0, 40.0), margin=2.0),
    items,
    obstacles=[SpatialObstacle2D("keepout", (34.0, 14.0), (10.0, 12.0), margin=1.0)],
    links=[SpatialLink2D("A", "B", weight=1.0), SpatialLink2D("B", "C", weight=1.0)],
    sectors=[
        RoleSector2D("left", (2.0, 2.0), (24.0, 36.0)),
        RoleSector2D("middle", (28.0, 2.0), (24.0, 36.0)),
        RoleSector2D("right", (54.0, 2.0), (24.0, 36.0)),
    ],
    alignment_groups=[
        AlignmentGroup2D(
            "main-row",
            ("A", "B", "C"),
            axis="y",
            distribution_axis="x",
            distribution_weight=1.0,
        )
    ],
    config=FreeEnergyLayout2DConfig(iterations=120, restarts=3, global_gap=1.0),
)

result = solver.optimize()
print(result.energy)
print(result.positions)

This solver is useful for flowcharts, wiring diagrams, engineering layouts, pipe-rack cross-sections, panel layouts, and other AI-assisted geometry tasks where semantic intent must be projected into legal 2D geometry.

Semantic Geometry Solver

TopologicalFreeGradientSolver converts semantic constraints into geometric updates through a free-energy gradient.

from tfgt import (
    SemanticGeometryConfig,
    SemanticGeometryConstraint,
    TopologicalFreeGradientSolver,
)

solver = TopologicalFreeGradientSolver(
    constraints=(
        SemanticGeometryConstraint("separate", "train_a", "train_b", distance=8.0, weight=2.0),
        SemanticGeometryConstraint("inside", "panel", "control_zone", weight=3.0),
    ),
    zones={
        "control_zone": ((20.0, 0.0, 0.0), (30.0, 10.0, 10.0)),
    },
    config=SemanticGeometryConfig(step_size=0.4, max_iters=80, lambda_top=1.0),
)

result = solver.solve(
    {
        "train_a": (5.0, 1.0, 5.0),
        "train_b": (8.0, 1.0, 5.0),
        "panel": (10.0, 1.0, 5.0),
    }
)

print(result.final_energy)
print(result.positions)

See docs/TOPOLOGICAL_FREE_GRADIENT_SOLVER.md for additional API details.

Engineering Layout And Routing

The tfgt.layout package also includes:

  • SpatialLayoutOptimizer: 2D equipment layout optimizer;
  • SpatialLayout3DOptimizer: 3D box-equipment layout optimizer;
  • orthogonal_route: grid-based orthogonal route search;
  • PHG export helpers for layout visualization pipelines.

These components are intended for solver-assisted layout generation where occupancy, obstacle, route, connection, access, load, and alignment constraints must be checked explicitly.

Research Reproduction

The bundled tfgt.research_nspp module contains reproduction scripts for controlled vortex-state closure experiments.

Run the reproduction entry point:

python -m tfgt.research_nspp --output ./nspp_outputs

Equivalent console command after installation:

tfgt-research-nspp --output ./nspp_outputs

Fast smoke test from a source checkout:

python tools/nspp_quick_review_test.py

The research module provides reproducible numerical diagnostics for declared vortex-state tasks. It should be interpreted within its stated scope and negative controls.

Public API

Common top-level imports include:

  • TFGTParameters: canonical parameter container;
  • TFGTModel: high-level model wrapper for NS++ helpers;
  • build_free_energy_field, build_flow_free_energy_field, gaussian_seed;
  • topological_force, gradient_nd, laplacian_nd;
  • nspp_rhs, nspp_acceleration;
  • TopologyOptimizer, TopologyOptConfig, TopologyOptResult;
  • layout_free_energy, layout_free_energy_gradient;
  • normalize_design_gradient, blended_topology_gradient;
  • TopologicalFreeGradientSolver;
  • SemanticGeometryConstraint, SemanticGeometryConfig;
  • FreeEnergySpatialSolver2D and its 2D layout dataclasses;
  • SpatialLayoutOptimizer, SpatialLayout3DOptimizer;
  • orthogonal_route;
  • ComplexEnergy, simulate_complex_energy, step_complex_energy;
  • vorticity_2d, helicity_density_3d, enstrophy_2d;
  • topological_activity_index, compare_baseline_vs_topology.

Package Structure

  • tfgt.core: constants, field operators, topology-gradient helpers, metrics, validation;
  • tfgt.energy: free-energy builders and complex-energy models;
  • tfgt.flow: NS++ RHS helpers and reduced flow models;
  • tfgt.optimization: topology optimization objectives and solvers;
  • tfgt.layout: 2D/3D layout, routing, and visualization export helpers;
  • tfgt.geometry: semantic-to-geometry free-gradient solvers;
  • tfgt.research_nspp: vortex-state reproduction scripts;
  • tfgt.structure: structural-topology extension namespace.

Complex Energy / Structural Topology Phase

The package includes a reduced model for complex free/topology energy:

E_complex = E_free + i E_topo
F_complex = F_geo  + i F_topo

In this model:

  • E_free is the real geometric/free-energy channel;
  • E_topo is the structural-topology energy channel;
  • F_geo acts in physical configuration space;
  • F_topo acts in topology phase space;
  • topology phase accumulates after a yield/activation threshold;
  • sector transitions cross sector-dependent topology energy gaps;
  • free-energy-to-topology-energy conversion produces entropy.
import numpy as np
from tfgt import (
    ComplexEnergyConfig,
    ComplexEnergyState,
    StructuralTopologySector,
    simulate_complex_energy,
)

sectors = (
    StructuralTopologySector("elastic", phase_threshold=0.25, energy_gap=0.0),
    StructuralTopologySector("plastic", phase_threshold=0.75, energy_gap=1.5),
)
config = ComplexEnergyConfig(
    yield_displacement=1.0,
    topology_coupling=3.0,
    dissipation_fraction=0.25,
    dt=0.1,
)

history = simulate_complex_energy(
    ComplexEnergyState(displacement=np.array([0.0])),
    sectors,
    config,
    steps=25,
    external_displacement_rate=np.array([1.0]),
)

print(history[-1].energy.sector)
print(history[-1].energy.complex_value)
print(history[-1].energy.entropy)

Development

Install development dependencies:

pip install -e .[dev]

Run tests:

pytest -q

Build distributions:

python -m build

Validate distributions:

python -m twine check dist/*

Run the topology optimization quickstart:

python examples/topo_opt_quickstart.py

Run external validation scripts:

python external_tests/run_external_validation.py

Scientific And Engineering Scope

TFGT is a solver-oriented toolkit. It supplies free-energy builders, projected gradient channels, topology optimization kernels, and geometry/layout solvers.

Use it with explicit state definitions, constraints, calibration data, and falsifiable benchmarks. In physical flow problems, distinguish clearly between physical-space fields, topology-state coordinates, design variables, mobility models, and observable projections.

The package does not replace Navier-Stokes solvers, FEM solvers, CFD validation, or domain-specific engineering checks.

Chinese Philosophy

See docs/PHILOSOPHY_zh-CN.md.

License

MIT License.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

tfgt-1.0.5.tar.gz (154.9 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

tfgt-1.0.5-py3-none-any.whl (142.7 kB view details)

Uploaded Python 3

File details

Details for the file tfgt-1.0.5.tar.gz.

File metadata

  • Download URL: tfgt-1.0.5.tar.gz
  • Upload date:
  • Size: 154.9 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.13.0

File hashes

Hashes for tfgt-1.0.5.tar.gz
Algorithm Hash digest
SHA256 d05d30ce2868b9f3a5501b8b40f0ee9727c35d515ca4c36733a24afd57a49fe3
MD5 0bc05227cf5273c5d47997eaab806cda
BLAKE2b-256 f4955a70a5dba15e5ec3f609e5a9813f1a42312fe28ef7037d8cf5d09da9ef19

See more details on using hashes here.

File details

Details for the file tfgt-1.0.5-py3-none-any.whl.

File metadata

  • Download URL: tfgt-1.0.5-py3-none-any.whl
  • Upload date:
  • Size: 142.7 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.13.0

File hashes

Hashes for tfgt-1.0.5-py3-none-any.whl
Algorithm Hash digest
SHA256 4c0a99b7bf8063eadd20be004d455a845064ca7201cf0371ac7ed23a0409cbe6
MD5 05d6d3064c1ecc96a86638026364540e
BLAKE2b-256 e22f253356c2a694e1185521ed8d6b187a563c350291ccd2ef0225125d120d13

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page