Skip to main content

pytexgen

PyPI version Python License: GPL v2 Platform

pytexgen packages the TexGen textile geometry engine for Python and adds a portable numpy/torch voxelization path for modern simulation workflows.

TexGen is the open-source geometric textile modelling software developed at the University of Nottingham. This project keeps the core TexGen modelling API available from Python while making the package easier to install, test, and use across Windows, Linux, and macOS.

Version 1.2.0 Highlights

  • Direct voxel data handoff with VoxelGridData.to("numpy" | "torch"), save_npz(...), load_npz(...), save_npy_dir(...), and load_npy_dir(...).
  • Prepared .ptgb geometry caches and bounded batch voxelization to raw material, orientation, and C21 arrays.
  • 2x2 weave tetrahedral mesh and small numpy/scipy FEM example scripts.
  • Root build.sh, build.bat, and build.ps1 helpers for uv-based local builds and installs.

What This Project Adds

Area Contribution Practical impact
Python packaging pyproject.toml + scikit-build-core build path Users can install with normal pip workflows instead of hand-driving CMake/SWIG
Stable wheel builds Pre-generated Python/Core.py and Python/Core_wrap.cxx Normal builds do not require a local SWIG install
Cross-platform defaults GUI, renderer, OpenMP, native CPU flags, and p4est are off by default Fewer Windows/MSVC/MinGW, OpenMP runtime, and older-CPU build failures
Python voxel backend pytexgen.gpu_voxelizer.voxelize_textile(...) OpenMP-free structured voxel output through numpy or torch
Direct solver handoff pytexgen.gpu_voxelizer.voxelize_textile_data(...) Return numpy arrays or torch tensors without writing/parsing Abaqus files
GPU-ready path Optional backend="torch" with CUDA/MPS/CPU devices Larger voxel grids can use torch acceleration without changing the TexGen C++ core
Batch voxelization prepare_geometry(...) and voxelize_files_batch(...) Reuse mmap-ready geometry and stream bounded production outputs
Lightweight adaptive output adaptive=True numpy mode Exploratory non-uniform C3D8R voxel meshes without compiling p4est
Performance pruning Conservative AABB candidate pruning Skips yarn/translation candidates that cannot intersect the current voxel chunk
Tetra/FEM examples script/tetgen_2d_weave_tetra.py, script/tet_fem_solve.py End-to-end mesh generation, C3D4 export, PNG preview, and scipy sparse FEM smoke solve
Local build helpers build.sh, build.bat, build.ps1 Create/use a uv virtual environment, install build dependencies, compile, and install pytexgen
Verification tools Backend tests and a synthetic benchmark script Easier to check numpy, torch, adaptive, and pruning behavior after changes

The goal is not to replace the TexGen C++ engine. The goal is to keep the official modelling surface usable while moving fragile optional acceleration and adaptive-mesh dependencies behind portable Python or opt-in build paths.

Installation

pip install pytexgen

The base package depends only on numpy. Install extras when you want torch, tqdm progress bars, or the example scripts:

pip install pytexgen              # TexGen bindings + numpy voxel backend
pip install "pytexgen[gpu]"       # add torch backend support
pip install "pytexgen[progress]"  # add tqdm progress bars
pip install "pytexgen[examples]"  # add scipy/matplotlib for example scripts

For CUDA, install a torch wheel that matches your Python version, GPU driver, and CUDA runtime first, then install pytexgen. The gpu extra intentionally does not pin a CUDA wheel because PyTorch publishes different packages for different CUDA runtimes.

Check the install:

import pytexgen

print(pytexgen.__version__)
print(pytexgen.CTextile)

Quick Start

Create and save a plain weave:

from pytexgen import *

weave = CTextileWeave2D(4, 4, 5.0, 2.0, False)

weave.SwapPosition(0, 3)
weave.SwapPosition(1, 2)
weave.SwapPosition(2, 1)
weave.SwapPosition(3, 0)

weave.SetYarnWidths(4.0)
weave.SetYarnHeights(0.8)
weave.AssignDefaultDomain()

name = AddTextile(weave)
SaveToXML("plain_weave.tg3", name, OUTPUT_STANDARD)
DeleteTextile(name)

Generate a classic TexGen rectangular voxel mesh:

from pytexgen import *

textile = CTextileWeave2D(2, 2, 1.0, 0.2, True)
textile.SwapPosition(0, 1)
textile.SwapPosition(1, 0)
textile.SetYarnWidths(0.8)
textile.SetYarnHeights(0.1)
textile.AssignDefaultDomain()

voxels = CRectangularVoxelMesh("CPeriodicBoundaries")
voxels.SaveVoxelMesh(
    textile,
    "mesh_cpp.inp",
    64, 64, 32,
    True,
    True,
    5,
    0,
)

Use the portable numpy/torch voxelizer instead:

from pytexgen import *
from pytexgen.gpu_voxelizer import voxelize_textile

textile = CTextileWeave2D(2, 2, 1.0, 0.2, True)
textile.SwapPosition(0, 1)
textile.SwapPosition(1, 0)
textile.SetYarnWidths(0.8)
textile.SetYarnHeights(0.1)
textile.AssignDefaultDomain()

info = voxelize_textile(
    textile,
    nx=64, ny=64, nz=32,
    out_inp="mesh_numpy.inp",
    backend="numpy",
    workers=4,
    aabb_pruning=True,
)

print(info["backend"], len(info["yarn_id"]))

The default structured path is now the OpenMP-free numpy backend. Numpy parallelism is chunk based: the default chunk_voxels=8192 gives a 40x40x40 grid eight classification tasks, and info["workers"] reports the effective worker count after chunk-count clamping. Set progress=True to show tqdm bars for classification and .inp writing; the package imports tqdm lazily so normal installs do not require it.

Return structured voxel data directly in memory for another solver, with optional .npz or directory-based .npy persistence:

from pytexgen.gpu_voxelizer import VoxelGridData, voxelize_textile_data

data = voxelize_textile_data(
    textile,
    nx=64, ny=64, nz=64,
    backend="numpy",
    workers=4,
)

yarn_grid = data.grid              # shape: (nz, ny, nx)
material_grid = data.material_id() # matrix=0, yarns=1..N
flat_yarn_ids = data.yarn_id       # ix + iy*nx + iz*nx*ny order
data.save_npz("voxel_data.npz")
data.save_npy_dir("voxel_data_npy")

loaded = VoxelGridData.load_npz("voxel_data.npz")
mmap_loaded = VoxelGridData.load_npy_dir("voxel_data_npy", mmap_mode="r")

Use .npz for a compact single-file artifact. Use save_npy_dir(...) when large training runs should avoid zip decompression overhead or memory-map individual arrays such as yarn_id, orientation1, and orientation2.

For anisotropic solvers, request per-voxel yarn directions:

data = voxelize_textile_data(
    textile,
    nx=64, ny=64, nz=64,
    backend="numpy",
    output="numpy",
    include_orientations=True,
)

orientation1 = data.orientation1  # yarn tangent, shape: (nz, ny, nx, 3)
orientation2 = data.orientation2  # yarn up vector, shape: (nz, ny, nx, 3)

Build a sparse, fully GPU-resident material direction and stiffness field in one call:

from pytexgen.material_fields import (
    isotropic_stiffness_c21,
    orthotropic_stiffness_c21,
    save_material_field_bundle,
    voxelize_textile_material_fields,
)

matrix_c21 = isotropic_stiffness_c21(E=3.5e9, nu=0.35)
yarn_c21 = orthotropic_stiffness_c21(
    150e9, 10e9, 10e9, 0.25, 0.25, 0.30, 5e9, 5e9, 3.8e9
)
data, stiffness = voxelize_textile_material_fields(
    textile,
    nx=128, ny=128, nz=128,
    backend="torch", device="cuda", output="backend",
    matrix_stiffness=matrix_c21,
    default_yarn_stiffness=yarn_c21,
    yarn_stiffness_by_id={3: 1.1 * yarn_c21},
)

dense_c21 = stiffness.to_dense_c21()  # (Nz, Ny, Nx, 21)
acdm_c66 = stiffness.to_acdm()        # (1, 6, 6, Nz, Ny, Nx)
save_material_field_bundle("material_fields", data.sparse_orientation, stiffness)

Engineering-Voigt order is (xx, yy, zz, yz, xz, xy). C21 stores the row-major upper triangle: (C11,C12,C13,C14,C15,C16,C22,C23,C24,C25,C26,C33,C34,C35,C36,C44,C45,C46,C55,C56,C66). Matrix voxels share one matrix_c21 and have no direction entry. Dense views are created only when requested. Saving transfers CUDA tensors to CPU; keep output="backend" during computation to avoid an earlier copy.

Batch Voxelization

Keep .tg3 as the editable model and prepare a memory-mappable .ptgb cache for repeated production runs:

from pytexgen.batch import MaterialSpec, prepare_geometry, voxelize_files_batch

prepare_geometry("models/plain.tg3", "prepared/plain.ptgb")

materials = MaterialSpec(
    matrix_c21=matrix_c21,
    default_yarn_c21=yarn_c21,
    unit="Pa",
)
report = voxelize_files_batch(
    ["prepared/plain.ptgb", "models/twill.tg3"],
    resolution=(128, 128, 128),
    output_dir="voxel_output",
    fields=("material_id", "orientation", "stiffness_c21"),
    materials=materials,
    device="cuda",
    dtype="float32",
    batch_size="auto",
    memory_budget_bytes=12 << 30,
)

Each input produces one directory containing metadata.json and uncompressed .npy arrays. Shapes are (Nz, Ny, Nx), (Nz, Ny, Nx, 3, 3), and (Nz, Ny, Nx, 21) respectively. PTGB v1 stores only flattened geometry needed for voxelization; it is not a replacement for an editable TG3 model. GPU work is streamed one geometry at a time while bounded background writers overlap the result transfer and disk output.

Use torch when an accelerator is available:

from pytexgen.gpu_voxelizer import voxelize_textile

info = voxelize_textile(
    textile,
    nx=128, ny=128, nz=64,
    out_inp="mesh_torch.inp",
    backend="torch",
    device="cuda",  # also supports "mps" or "cpu"
)

Create a lightweight adaptive numpy mesh:

from pytexgen.gpu_voxelizer import voxelize_textile

info = voxelize_textile(
    textile,
    nx=16, ny=16, nz=8,
    out_inp="mesh_adaptive_numpy.inp",
    backend="numpy",
    adaptive=True,
    adaptive_levels=2,
)

Adaptive numpy mode writes non-uniform Abaqus C3D8R cells. It does not produce p4est-style 2:1 balancing or hanging-node constraint equations, so keep using a p4est-enabled COctreeVoxelMesh build when a downstream FEM workflow requires those guarantees.

Backend Choices

Path Entry point Dependencies Best use
TexGen C++ structured voxels CRectangularVoxelMesh.SaveVoxelMesh(...) bundled TexGen core Reference-compatible structured output
Python numpy backend voxelize_textile(..., backend="numpy") numpy Portable CPU voxelization without OpenMP
Python direct data backend voxelize_textile_data(...) numpy, optional torch In-memory yarn/material grids and .npz handoff without .inp
Python torch backend voxelize_textile(..., backend="torch") torch CUDA/MPS/torch CPU acceleration for larger grids
Python adaptive numpy backend voxelize_textile(..., adaptive=True) numpy Lightweight non-uniform exploratory meshes
TexGen p4est octree COctreeVoxelMesh.SaveVoxelMesh(...) local p4est/sc build Full p4est-style adaptive octree workflows

See the source repository's docs/voxel_backends.md for backend limits, p4est build notes, and benchmark commands.

Core TexGen API

The package re-exports the SWIG-generated TexGen core API at the pytexgen package level:

from pytexgen import CTextile, CTextileWeave2D, CYarn, CNode, XYZ
from pytexgen import CSectionEllipse, CYarnSectionConstant
from pytexgen import CRectangularVoxelMesh, SaveToXML, ReadFromXML

Common API families:

Family Examples
Textiles CTextile, CTextileWeave2D, CShearedTextileWeave2D, CTextileWeave3D, CTextileOrthogonal, CTextileLayerToLayer
Yarn geometry CYarn, CNode, XYZ, XY, CInterpolationCubic, CInterpolationBezier
Sections CSectionEllipse, CSectionLenticular, CSectionRectangle, CSectionPolygon, CSectionPowerEllipse
Domains CDomainPlanes, AssignDefaultDomain, GetDefaultDomain
Mesh/export CRectangularVoxelMesh, CShearedVoxelMesh, CStaggeredVoxelMesh, CRotatedVoxelMesh, CTetgenMesh, CSurfaceMesh
IO AddTextile, DeleteTextile, SaveToXML, ReadFromXML

Compatibility With Upstream TexGen

This repository is based on the official TexGen C++ codebase and keeps the main Python modelling interface close to the upstream SWIG interface.

Intentional differences in the default pip/wheel build:

  • COctreeVoxelMesh is not exposed by default because it depends on p4est/sc.
  • The GUI, renderer, cascade export, examples, and documentation targets are not part of the core Python wheel.
  • OpenMP and architecture-native compiler flags are opt-in rather than default.
  • SWIG regeneration is opt-in; generated wrappers are committed for normal installs.

These defaults reduce fragile compile-time dependencies. If your project needs the official p4est octree path, build locally with p4est/sc libraries and -DTEXGEN_REGENERATE_SWIG=ON.

Building From Source

Prerequisites:

  • Python 3.9+
  • CMake 3.17+
  • A C++11 compiler
  • scikit-build-core

Install from a checkout:

git clone https://github.com/yufangjie1643/pytexgen.git
cd pytexgen
pip install -e .

Build a wheel:

pip install build
python -m build

Useful CMake options:

Option Default Description
BUILD_PYTHON_INTERFACE ON Build Python bindings
BUILD_RENDERER OFF Build the OpenGL renderer
BUILD_GUI OFF Build the wxWidgets GUI
BUILD_SHARED OFF Build shared libraries instead of static wheel libraries
TEXGEN_ENABLE_OPENMP OFF Enable optional C++ OpenMP loops
TEXGEN_ENABLE_NATIVE_OPTIMIZATIONS OFF Enable local CPU flags such as -march=native
TEXGEN_REGENERATE_SWIG OFF Regenerate Core.py and Core_wrap.cxx from Python/Core.i
TEXGEN_INSTALL_WORKFLOW_EXTENSIONS OFF Install source-only solver, training, and experimental mesher modules

SWIG is only required when TEXGEN_REGENERATE_SWIG=ON. The published wheel keeps this last option off so its Python API remains focused on textile geometry, meshing, voxelization, and material fields.

Testing And Benchmarks

Backend smoke tests:

python test_gpu_voxelizer_backends.py

Synthetic pruning benchmark:

python bench_gpu_voxelizer_backends.py --resolution 32 --yarn-grid 4 --workers 4

Torch/CUDA benchmark when torch is installed:

python bench_gpu_voxelizer_backends.py --include-torch --device cuda

Project Layout

Core/                    TexGen C++ geometry, textile, mesh, and export code
Python/Core.i            SWIG interface
Python/Core.py           committed SWIG Python proxy
Python/Core_wrap.cxx      committed SWIG C++ wrapper
TexGen/gpu_voxelizer.py   portable numpy/torch voxelization backend
TexGen/material_fields.py sparse orientation and stiffness fields
TexGen/batch.py           PTGB preparation and batch voxelization
src/pytexgen/             installed Python package
docs/voxel_backends.md    backend selection and p4est notes
pyproject.toml            Python packaging and wheel build configuration

Attribution

TexGen was originally developed by Louise Brown and collaborators at the University of Nottingham Composites Research Group. For academic use, please cite the original TexGen project:

Lin, H., Brown, L.P. and Long, A.C. (2011). Modelling and Simulating Textile Structures using TexGen. Advanced Materials Research, Vols. 331, pp 44-47.

License

This project is licensed under the GNU General Public License v2.0 or later. See the source repository LICENSE file for details.

Metadata

Release files for pytexgen 1.2.0

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

Source distribution (sdist)

Source distribution for pytexgen 1.2.0
File Size Uploaded Provenance Actions
pytexgen-1.2.0.tar.gz 3.8 MB Without provenance Details for pytexgen-1.2.0.tar.gz

Built distributions (wheels)

Table of built distributions (wheels) for pytexgen 1.2.0
File Actions
pytexgen-1.2.0-cp314-cp314-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl CPython 3.14 CPython 3.14 Linux glibc 2.27+ x86-64, Linux glibc 2.28+ x86-64 Details for pytexgen-1.2.0-cp314-cp314-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl
pytexgen-1.2.0-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.whl CPython 3.13 CPython 3.13 Linux glibc 2.17+ x86-64 Details for pytexgen-1.2.0-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.whl
pytexgen-1.2.0-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.whl CPython 3.12 CPython 3.12 Linux glibc 2.17+ x86-64 Details for pytexgen-1.2.0-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.whl
pytexgen-1.2.0-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.whl CPython 3.11 CPython 3.11 Linux glibc 2.17+ x86-64 Details for pytexgen-1.2.0-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.whl
pytexgen-1.2.0-cp310-cp310-manylinux2014_x86_64.manylinux_2_17_x86_64.whl CPython 3.10 CPython 3.10 Linux glibc 2.17+ x86-64 Details for pytexgen-1.2.0-cp310-cp310-manylinux2014_x86_64.manylinux_2_17_x86_64.whl
pytexgen-1.2.0-cp39-cp39-manylinux2014_x86_64.manylinux_2_17_x86_64.whl CPython 3.9 CPython 3.9 Linux glibc 2.17+ x86-64 Details for pytexgen-1.2.0-cp39-cp39-manylinux2014_x86_64.manylinux_2_17_x86_64.whl

Total release size: 18.6 MB

Release files / pytexgen-1.2.0.tar.gz

Download URL pytexgen-1.2.0.tar.gz
Size 3.8 MB
Tags Source
SHA-256 checksum
How to use checksums
a6d56d4c0d34079eaca13466fd31f01d8518528d2c12f1ba9574155fb26d6498
BLAKE2b-256 checksum
How to use checksums
4179092a281bbc2112f211969f376d114b649874cb30161bf855079a0097cea1
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.13.14

Release files / pytexgen-1.2.0-cp314-cp314-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl

Download URL pytexgen-1.2.0-cp314-cp314-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl
Size 2.5 MB
Tags CPython 3.14 Linux glibc 2.27+ x86-64 Linux glibc 2.28+ x86-64
SHA-256 checksum
How to use checksums
c644c65c818de8ae9d207d9606ad81b87a8ec8714b340517294d12306ea7a574
BLAKE2b-256 checksum
How to use checksums
b4c9ac9d1f71383445d045910707f43689beb012574a285c14c6f5a06c6d45b0
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.13.14

Release files / pytexgen-1.2.0-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.whl

Download URL pytexgen-1.2.0-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.whl
Size 2.5 MB
Tags CPython 3.13 Linux glibc 2.17+ x86-64
SHA-256 checksum
How to use checksums
7603ee3d520b955672ffa485e6729b5272661eccab56cf99253eb9280b08206e
BLAKE2b-256 checksum
How to use checksums
eabda4f844fa427fea9dbf04834fdcb42bcc457897c37ab12e9f215546553468
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.13.14

Release files / pytexgen-1.2.0-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.whl

Download URL pytexgen-1.2.0-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.whl
Size 2.5 MB
Tags CPython 3.12 Linux glibc 2.17+ x86-64
SHA-256 checksum
How to use checksums
d1139b9e60c186c8420be2e3a5989a4ab4333c0adc6e9bd31e5c9ee151f3fda2
BLAKE2b-256 checksum
How to use checksums
d762c95beaf9bb13f904a5986fc392888d545f0c72e4f9c5224b29aa07b4abd2
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.13.14

Release files / pytexgen-1.2.0-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.whl

Download URL pytexgen-1.2.0-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.whl
Size 2.5 MB
Tags CPython 3.11 Linux glibc 2.17+ x86-64
SHA-256 checksum
How to use checksums
76aab17a6fc935b5bb789fd94b7c89504b2f52911004148eebe80ae29fa03129
BLAKE2b-256 checksum
How to use checksums
c4938247be05fe6bd3325e58d552deb530c23aa87681292ab3a56722ae2586e4
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.13.14

Release files / pytexgen-1.2.0-cp310-cp310-manylinux2014_x86_64.manylinux_2_17_x86_64.whl

Download URL pytexgen-1.2.0-cp310-cp310-manylinux2014_x86_64.manylinux_2_17_x86_64.whl
Size 2.5 MB
Tags CPython 3.10 Linux glibc 2.17+ x86-64
SHA-256 checksum
How to use checksums
a6fca38706dbe6f98d9cb49716484a18d778104e9578312fb2e90945537b3404
BLAKE2b-256 checksum
How to use checksums
8b8f65ee59993c904839f84c94e0962755e2cb8419e321ece1c84acd89877f47
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.13.14

Release files / pytexgen-1.2.0-cp39-cp39-manylinux2014_x86_64.manylinux_2_17_x86_64.whl

Download URL pytexgen-1.2.0-cp39-cp39-manylinux2014_x86_64.manylinux_2_17_x86_64.whl
Size 2.5 MB
Tags CPython 3.9 Linux glibc 2.17+ x86-64
SHA-256 checksum
How to use checksums
0edb28b453b246a9ff4dfcd5f67e94d20448ba7ec8a082fff123e12ea3e6a326
BLAKE2b-256 checksum
How to use checksums
75618328959ae67579ecbca36f13142e3d01db4c4b1cf5ca9b1633a3fb4aa970
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.13.14

Security for pytexgen 1.2.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

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