Skip to main content

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.11.

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.11"

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.

Metadata

Release files for tfgt 1.0.13

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for tfgt 1.0.13
File Size Uploaded
tfgt-1.0.13.tar.gz 11.3 MB Details

Built distribution (wheel)

Table of built distributions (wheels) for tfgt 1.0.13
File Interpreter ABI Platform
tfgt-1.0.13-py3-none-any.whl Python 3 none any Details

Total release size: 22.6 MB

Release files / tfgt-1.0.13.tar.gz

Download URL tfgt-1.0.13.tar.gz
Size 11.3 MB
Tags Source
SHA-256 checksum
How to use checksums
dd1c1c787a6bf1fdbaf5678aaf36574c1c53059dca4ebfa5864ef953e9f49f61
BLAKE2b-256 checksum
How to use checksums
f520686de0c3e21276d544bf69ed733069d839de5fd95004d691f0e863c2de37
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.13.12

Release files / tfgt-1.0.13-py3-none-any.whl

Download URL tfgt-1.0.13-py3-none-any.whl
Size 11.3 MB
Tags Python 3
SHA-256 checksum
How to use checksums
d7af25ed706ddaa2ea94a490a8b3c2a3340c67b9326f9c6b4d47d3603c1f33ba
BLAKE2b-256 checksum
How to use checksums
c45dfe870197f14774ffb5b7f69b55d545a87dceb8b1e3492dde26528d925f7c
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.13.12

Release history Release notifications | RSS feed

This release

1.0.13 This release

2 release files

1.0.9

2 release files

1.0.8

2 release files

1.0.7

2 release files

1.0.6

2 release files

1.0.5

2 release files

1.0.3

2 release files

1.0.1

2 release files

1.0.0

2 release files

0.4.0

2 release files

0.3.2

2 release files

0.3.1

2 release files

0.3.0

2 release files

0.2.0

2 release files

0.1.0

2 release files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page