Metadata-Version: 2.4
Name: tfgt
Version: 1.0.3
Summary: Topological Free-energy Gradient Theory toolkit for topology-force, topology optimization, and topological free-gradient solving.
Home-page: https://github.com/panguojun/tfgt
Author: Pan Guojun
Author-email: Pan Guojun <18858146@qq.com>
License-Expression: MIT
Project-URL: Homepage, https://github.com/panguojun/tfgt
Project-URL: Repository, https://github.com/panguojun/tfgt
Project-URL: Documentation, https://github.com/panguojun/tfgt#readme
Project-URL: Bug Reports, https://github.com/panguojun/tfgt/issues
Keywords: fluid,topology,navier-stokes,thermodynamics,free-energy,optimization,layout,scientific-computing,numpy
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: Science/Research
Classifier: Topic :: Scientific/Engineering :: Physics
Classifier: Topic :: Scientific/Engineering :: Mathematics
Classifier: Topic :: Scientific/Engineering :: Information Analysis
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Operating System :: OS Independent
Requires-Python: >=3.9
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: numpy>=1.22
Requires-Dist: matplotlib>=3.7
Provides-Extra: dev
Requires-Dist: build>=1.2.0; extra == "dev"
Requires-Dist: pytest>=8.0.0; extra == "dev"
Requires-Dist: twine>=5.0.0; extra == "dev"
Dynamic: author
Dynamic: home-page
Dynamic: license-file
Dynamic: requires-python

# 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:

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

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

```text
f_xi = -grad_xi(F_top)
```

For design and layout optimization, the practical update is:

```text
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:

```text
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

```bash
pip install tfgt
```

Install a specific version:

```bash
python -m pip install "tfgt==1.0.3"
```

Install from source:

```bash
pip install .
```

Verify the installed version:

```bash
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.

```python
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.

```python
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.

```python
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.

```python
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.

```python
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.

```python
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:

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

Equivalent console command after installation:

```bash
tfgt-research-nspp --output ./nspp_outputs
```

Fast smoke test from a source checkout:

```bash
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:

```text
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.

```python
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:

```bash
pip install -e .[dev]
```

Run tests:

```bash
pytest -q
```

Build distributions:

```bash
python -m build
```

Validate distributions:

```bash
python -m twine check dist/*
```

Run the topology optimization quickstart:

```bash
python examples/topo_opt_quickstart.py
```

Run external validation scripts:

```bash
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.
