Metadata-Version: 2.2
Name: torch-diffsim
Version: 0.2.0
Summary: a very minimal paralllelizable physics simulator supporting differentiation entirely in torch.
Author-email: Rishit Dagli <rishit.dagli@gmail.com>
License: MIT
Project-URL: Homepage, https://github.com/Rishit-Dagli/torch-diffsim
Project-URL: Documentation, https://rishit-dagli.github.io/torch-diffsim/
Project-URL: Repository, https://github.com/Rishit-Dagli/torch-diffsim
Keywords: physics,simulation,differentiable,pytorch,neo-hookean
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Science/Research
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.8
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: Topic :: Scientific/Engineering :: Physics
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Requires-Python: >=3.8
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: torch>=2.0.0
Requires-Dist: numpy>=1.20.0
Requires-Dist: polyscope>=1.3.0
Requires-Dist: meshio>=5.0.0
Requires-Dist: scipy>=1.7.0
Requires-Dist: matplotlib>=3.5.0
Provides-Extra: ipc
Requires-Dist: ipctk<1.7,>=1.6; extra == "ipc"
Provides-Extra: dev
Requires-Dist: pytest>=7.0.0; extra == "dev"
Requires-Dist: black>=22.0.0; extra == "dev"
Requires-Dist: ruff>=0.1.0; extra == "dev"

https://github.com/user-attachments/assets/e7d80ce7-af74-4deb-bb5a-aa3f93bb7a6d

# ⚙️ torch-diffsim

![PyPI](https://img.shields.io/pypi/v/torch-diffsim?style=flat-square)

Documentation is hosted at: https://rishit-dagli.github.io/torch-diffsim/

Checkout the [Deepwiki: torch-diffsim](https://deepwiki.com/Rishit-dagli/torch-diffsim) for an in-depth conceptual description.

torch-diffsim is an extremely minimal parallelizable differentiable finite element (FEM) simulator written entirely in PyTorch. It uses a semi-implicit (symplectic Euler) integrator, a stable Neo-Hookean material model, and smooth barrier-based contact. All operations preserve gradients to enable optimization of materials and states.

## Install


```bash
pip install torch-diffsim

# IPC backend
pip install "torch-diffsim[ipc]"

# or from source
git clone https://github.com/Rishit-dagli/torch-diffsim
cd torch-diffsim
pip install -e .
```

## Quick start: suspend a soft bunny

```python
from pathlib import Path

import torch
from diffsim import SemiImplicitSolver, Simulator, StableNeoHookean, TetrahedralMesh

device = "cuda" if torch.cuda.is_available() else "cpu"
source = TetrahedralMesh.from_file(
    Path("assets/tetmesh/stanford_bunny.msh"), device=device
)
mesh = TetrahedralMesh(
    source.vertices + source.vertices.new_tensor([0.0, 0.60, 0.0]),
    source.tetrahedra,
    device=device,
)
sim = Simulator(
    mesh,
    StableNeoHookean(youngs_modulus=2e5, poissons_ratio=0.4),
    SemiImplicitSolver(dt=0.002, damping=0.996, substeps=6),
    density=1000.0,
    device=device,
)
support = torch.where(
    mesh.vertices[:, 1] >= torch.quantile(mesh.vertices[:, 1], 0.96)
)[0]
sim.set_fixed_vertices(support)

for _ in range(500):
    sim.step()
```

Run `python examples/suspended_bunny.py` to see the fixed points, rest pose,
deformation, von Mises stress, and equivalent Green strain.

<p align="center">
  <img src="https://raw.githubusercontent.com/Rishit-Dagli/torch-diffsim/main/docs/source/_static/assets/suspended_bunny.gif" width="900">
</p>

## Quick start: train through the simulator

Here one `torch.nn.Module` learns feedback across four combinations of
ear-tip target and initial impulse. Adam differentiates the exact mean loss
through all 48 FEM steps in every condition.

```python
import torch
from examples.train_neural_controller import (
    EarController,
    build_problem,
    rollout,
)

device = "cuda" if torch.cuda.is_available() else "cpu"
torch.manual_seed(8)
if torch.cuda.is_available():
    torch.cuda.manual_seed_all(8)
problem = build_problem(device)
controller = EarController().to(device)
optimizer = torch.optim.Adam(controller.parameters(), lr=0.018)

for _ in range(12):
    optimizer.zero_grad()
    for target_distance, initial_velocity in problem["training_conditions"]:
        result = rollout(
            problem,
            controller,
            steps=48,
            target_distance=target_distance,
            initial_tip_velocity=initial_velocity,
        )
        (result["loss"] / len(problem["training_conditions"])).backward()
    torch.nn.utils.clip_grad_norm_(controller.parameters(), 1.0)
    optimizer.step()
```

The example retains the best policy, fits the constant baseline on the
same training set, and records both held-out trajectories:

```bash
python examples/train_neural_controller.py --plot neural_bunny.png
```

<p align="center">
  <img src="https://raw.githubusercontent.com/Rishit-Dagli/torch-diffsim/main/docs/source/_static/assets/neural_bunny.gif" width="900">
</p>

## Learn more

- User Guide and API: https://torch-diffsim.github.io
- Examples: see the `examples/` directory
- How it works: simulation and differentiation details in the docs

## Citation

If you use torch-diffsim in academic work, please include a citation or link to the project repository.

```bibtex
@misc{torch-diffsim,
  title  = {torch-diffsim},
  author = {Rishit Dagli},
  year   = {2025},
  howpublished = {\url{https://github.com/Rishit-dagli/torch-diffsim}}
}
```


