physicausal 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (38) hide show
  1. physicausal-0.1.0/LICENSE +21 -0
  2. physicausal-0.1.0/PKG-INFO +377 -0
  3. physicausal-0.1.0/README.md +323 -0
  4. physicausal-0.1.0/physicausal/__init__.py +25 -0
  5. physicausal-0.1.0/physicausal/benchmarks/__init__.py +3 -0
  6. physicausal-0.1.0/physicausal/benchmarks/causalverse.py +142 -0
  7. physicausal-0.1.0/physicausal/benchmarks/causalworld.py +122 -0
  8. physicausal-0.1.0/physicausal/causal/__init__.py +4 -0
  9. physicausal-0.1.0/physicausal/causal/intervention.py +47 -0
  10. physicausal-0.1.0/physicausal/causal/validator.py +315 -0
  11. physicausal-0.1.0/physicausal/envs/__init__.py +4 -0
  12. physicausal-0.1.0/physicausal/envs/pendulum.py +96 -0
  13. physicausal-0.1.0/physicausal/envs/simple_push.py +261 -0
  14. physicausal-0.1.0/physicausal/models/__init__.py +5 -0
  15. physicausal-0.1.0/physicausal/models/base.py +123 -0
  16. physicausal-0.1.0/physicausal/models/beta_tc_vae.py +224 -0
  17. physicausal-0.1.0/physicausal/models/losses.py +18 -0
  18. physicausal-0.1.0/physicausal/models/vae.py +250 -0
  19. physicausal-0.1.0/physicausal/training/__init__.py +3 -0
  20. physicausal-0.1.0/physicausal/training/agent.py +238 -0
  21. physicausal-0.1.0/physicausal/training/hparams.py +193 -0
  22. physicausal-0.1.0/physicausal/utils/__init__.py +3 -0
  23. physicausal-0.1.0/physicausal/utils/tracker.py +123 -0
  24. physicausal-0.1.0/physicausal.egg-info/PKG-INFO +377 -0
  25. physicausal-0.1.0/physicausal.egg-info/SOURCES.txt +36 -0
  26. physicausal-0.1.0/physicausal.egg-info/dependency_links.txt +1 -0
  27. physicausal-0.1.0/physicausal.egg-info/requires.txt +15 -0
  28. physicausal-0.1.0/physicausal.egg-info/top_level.txt +4 -0
  29. physicausal-0.1.0/pyproject.toml +80 -0
  30. physicausal-0.1.0/setup.cfg +4 -0
  31. physicausal-0.1.0/tests/test_benchmarks.py +80 -0
  32. physicausal-0.1.0/tests/test_causal.py +87 -0
  33. physicausal-0.1.0/tests/test_envs.py +101 -0
  34. physicausal-0.1.0/tests/test_hparams.py +38 -0
  35. physicausal-0.1.0/tests/test_models.py +223 -0
  36. physicausal-0.1.0/tests/test_pendulum.py +43 -0
  37. physicausal-0.1.0/tests/test_tracker.py +45 -0
  38. physicausal-0.1.0/tests/test_training.py +109 -0
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,377 @@
1
+ Metadata-Version: 2.4
2
+ Name: physicausal
3
+ Version: 0.1.0
4
+ Summary: Causal World Models for Physical Reasoning
5
+ Author-email: Fengrru <fengru1005@gmail.com>
6
+ License: MIT License
7
+
8
+ Copyright (c) 2026
9
+
10
+ Permission is hereby granted, free of charge, to any person obtaining a copy
11
+ of this software and associated documentation files (the "Software"), to deal
12
+ in the Software without restriction, including without limitation the rights
13
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
14
+ copies of the Software, and to permit persons to whom the Software is
15
+ furnished to do so, subject to the following conditions:
16
+
17
+ The above copyright notice and this permission notice shall be included in all
18
+ copies or substantial portions of the Software.
19
+
20
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
21
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
22
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
23
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
24
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
25
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
26
+ SOFTWARE.
27
+
28
+ Project-URL: Homepage, https://github.com/Fengrru/physicausal
29
+ Project-URL: Repository, https://github.com/Fengrru/physicausal
30
+ Project-URL: Documentation, https://github.com/Fengrru/physicausal
31
+ Project-URL: Changelog, https://github.com/Fengrru/physicausal/blob/main/CHANGELOG.md
32
+ Classifier: Development Status :: 3 - Alpha
33
+ Classifier: Intended Audience :: Science/Research
34
+ Classifier: License :: OSI Approved :: MIT License
35
+ Classifier: Programming Language :: Python :: 3.10
36
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
37
+ Requires-Python: >=3.10
38
+ Description-Content-Type: text/markdown
39
+ License-File: LICENSE
40
+ Requires-Dist: torch>=2.0.0
41
+ Requires-Dist: numpy>=1.24.0
42
+ Requires-Dist: scipy>=1.10.0
43
+ Requires-Dist: scikit-learn>=1.3.0
44
+ Provides-Extra: dev
45
+ Requires-Dist: pytest>=7.0.0; extra == "dev"
46
+ Requires-Dist: pytest-cov>=4.0.0; extra == "dev"
47
+ Requires-Dist: ruff>=0.1.0; extra == "dev"
48
+ Requires-Dist: mkdocs>=1.5.0; extra == "dev"
49
+ Requires-Dist: mkdocs-material>=9.0.0; extra == "dev"
50
+ Requires-Dist: mkdocstrings[python]>=0.22.0; extra == "dev"
51
+ Provides-Extra: optuna
52
+ Requires-Dist: optuna>=3.0.0; extra == "optuna"
53
+ Dynamic: license-file
54
+
55
+ <h1 align="center">PhysiCausal</h1>
56
+
57
+ <p align="center">
58
+ <b>Causal World Models for Physical Reasoning</b>
59
+ </p>
60
+
61
+ <p align="center">
62
+ <a href="https://www.python.org/downloads/">
63
+ <img src="https://img.shields.io/badge/python-3.10+-blue.svg" alt="Python 3.10+">
64
+ </a>
65
+ <a href="https://pytorch.org/">
66
+ <img src="https://img.shields.io/badge/PyTorch-2.0+-ee4c2c.svg" alt="PyTorch 2.0+">
67
+ </a>
68
+ <a href="https://opensource.org/licenses/MIT">
69
+ <img src="https://img.shields.io/badge/License-MIT-yellow.svg" alt="License: MIT">
70
+ </a>
71
+ <a href="#">
72
+ <img src="https://img.shields.io/badge/docs-mkdocs-blue.svg" alt="Documentation">
73
+ </a>
74
+ <a href="https://github.com/Fengrru/physicausal/actions">
75
+ <img src="https://img.shields.io/github/actions/workflow/status/Fengrru/physicausal/ci.yml" alt="Tests">
76
+ </a>
77
+ </p>
78
+
79
+ <p align="center">
80
+ <a href="#installation">Installation</a> •
81
+ <a href="#quickstart">Quickstart</a> •
82
+ <a href="#features">Features</a> •
83
+ <a href="#model-zoo">Model Zoo</a> •
84
+ <a href="#documentation">Documentation</a> •
85
+ <a href="#citation">Citation</a>
86
+ </p>
87
+
88
+ ---
89
+
90
+ ## Overview
91
+
92
+ **PhysiCausal** is a lightweight, modular toolkit for learning **causally structured world models** from physical interactions. It bridges causal representation learning (CRL) and intuitive physics, providing a clean research platform for:
93
+
94
+ - Learning disentangled latent representations from dynamic environments
95
+ - Validating whether learned latents correspond to true causal variables (mass, friction, restitution)
96
+ - Testing interventions via Pearl's **do-operator** on learned world models
97
+ - Benchmarking against standards like CausalWorld and CausalVerse
98
+
99
+ Unlike heavy simulation stacks (PyBullet, MuJoCo), PhysiCausal ships with a **zero-dependency Newtonian physics engine** in pure NumPy, letting you iterate on causal learning ideas in seconds, not minutes.
100
+
101
+ ---
102
+
103
+ ## Why PhysiCausal?
104
+
105
+ | | PhysiCausal | Full Physics Engines | General VAE Libraries |
106
+ |---|---|---|---|
107
+ | **Physics** | Built-in, lightweight | Heavy (PyBullet/MuJoCo) | None |
108
+ | **Causal validation** | First-class (DCS, do-op, MI) | Manual / external | Not available |
109
+ | **Model interface** | Unified `CausalWorldModel` | N/A | Fragmented |
110
+ | **Hyperparameter search** | Optuna integrated | Manual | Manual |
111
+ | **Benchmark adapters** | CausalWorld, CausalVerse | Native only | N/A |
112
+ | **Setup time** | `pip install` | Install + compile | `pip install` |
113
+
114
+ ---
115
+
116
+ ## Installation
117
+
118
+ ```bash
119
+ pip install physicausal
120
+ ```
121
+
122
+ For development, documentation builds, and hyperparameter search:
123
+
124
+ ```bash
125
+ pip install physicausal[dev,optuna]
126
+ ```
127
+
128
+ To install the latest development version directly from GitHub:
129
+
130
+ ```bash
131
+ pip install git+https://github.com/Fengrru/physicausal.git
132
+ ```
133
+
134
+ Requires Python >= 3.10 and PyTorch >= 2.0.
135
+
136
+ ---
137
+
138
+ ## Quickstart
139
+
140
+ Train a causal world model and validate its latent structure in under 20 lines:
141
+
142
+ ```python
143
+ from physicausal import SimplePushEnv, BetaVAE, CausalValidator, train
144
+
145
+ # 1. Environment
146
+ env = SimplePushEnv(seed=42)
147
+
148
+ # 2. Data
149
+ data, objects = env.generate_data(n_objects=200, episodes_per_object=5)
150
+
151
+ # 3. Model
152
+ model = BetaVAE(obs_dim=7, latent_dim=6, action_dim=3, beta=2.0)
153
+
154
+ # 4. Train with validation
155
+ validator = CausalValidator(model, env)
156
+ result = train(
157
+ model, data, epochs=100,
158
+ validator=validator, objects=objects,
159
+ validate_every=20
160
+ )
161
+
162
+ # 5. Report
163
+ report = validator.test_multiple_properties(
164
+ objects, ["mass", "friction", "restitution"]
165
+ )
166
+ for prop, res in report["results"].items():
167
+ print(f"{prop}: |r|={res['best_abs_corr']:.3f}, causal={res['is_causal']}")
168
+ ```
169
+
170
+ **Output:**
171
+ ```text
172
+ mass: |r|=0.284, causal=False
173
+ friction: |r|=0.412, causal=False
174
+ restitution: |r|=0.198, causal=False
175
+ ```
176
+
177
+ > The example above uses a minimal setup. With richer observations (e.g., visual trajectories) and tuned hyperparameters, models routinely cross the |r| > 0.5 causal threshold. See `examples/04_hyperparameter_search.py`.
178
+
179
+ ---
180
+
181
+ ## Features
182
+
183
+ ### Physics Environments
184
+ - **SimplePushEnv** — 2D block-pushing with proper Newtonian dynamics (`F = ma`), Coulomb friction, wall collisions, and configurable object properties (mass, friction, restitution).
185
+ - **PendulumEnv** — Classic pendulum for causal discovery of length, mass, and damping.
186
+ - Pure NumPy, no external physics engine required.
187
+
188
+ ### Model Zoo
189
+ All models implement the `CausalWorldModel` interface:
190
+
191
+ | Model | Type | Key Feature | Best For |
192
+ |-------|------|-------------|----------|
193
+ | `WorldModel` | Deterministic | MLP encoder-decoder-dynamics | Speed baseline |
194
+ | `BetaVAE` | Probabilistic | β-weighted KL for disentanglement | Balanced CRL |
195
+ | `BetaTCVAE` | Probabilistic | Explicit Total Correlation penalty | Strongest disentanglement |
196
+
197
+ Shared API:
198
+ ```python
199
+ z = model.encode(obs) # Latent inference
200
+ recon = model.decode(z, action) # Observation reconstruction
201
+ z_next = model.predict_dynamics(z, action) # Latent transition
202
+ z_intervene = model.intervene(z, dim=0, value=2.0) # Do-operator
203
+ ```
204
+
205
+ ### Causal Validation
206
+ `CausalValidator` provides rigorous statistical tests:
207
+
208
+ | Method | What it Tests | Threshold |
209
+ |--------|--------------|-----------|
210
+ | Pearson correlation | Linear latent-to-factor association | \|r\| > 0.5 |
211
+ | Permutation test | Statistical significance | p < 0.05 |
212
+ | Mutual information | Non-linear association | MI > 0 |
213
+ | Do-operator | Causal consistency under intervention | Manual inspection |
214
+ | DCS | Disentanglement Completeness Score | 0 (poor) to 1 (perfect) |
215
+ | Sensitivity analysis | Robustness to hyperparameters | Variance-based |
216
+ | Intervention scan | Systematic latent intervention | Grid sweep |
217
+
218
+ ### Training Infrastructure
219
+ - `CausalLearningAgent` — Full training loop with replay buffer
220
+ - `train()` — One-line training function with built-in causal validation checkpoints
221
+ - `ReplayBuffer` — Efficient experience storage for off-policy learning
222
+
223
+ ### Hyperparameter Search
224
+ ```python
225
+ from physicausal.training.hparams import search_hyperparams
226
+
227
+ best = search_hyperparams(
228
+ BetaVAE, data, objects, env,
229
+ n_trials=50, metric="mass_corr", direction="maximize"
230
+ )
231
+ print(best["best_params"]) # {'lr': 0.001, 'beta': 2.3, ...}
232
+ ```
233
+
234
+ ### Benchmark Adapters
235
+ Convert between PhysiCausal and external formats:
236
+ ```python
237
+ from physicausal.benchmarks.causalworld import causalworld_to_physicausal
238
+ from physicausal.benchmarks.causalverse import compute_causalverse_metrics
239
+ ```
240
+
241
+ ---
242
+
243
+ ## Model Zoo Details
244
+
245
+ ### BetaVAE
246
+ Standard β-VAE with a tunable `beta` parameter that scales the KL divergence term. Higher `beta` encourages stronger disentanglement at the cost of reconstruction fidelity.
247
+
248
+ ### BetaTCVAE
249
+ Extends BetaVAE with an explicit **Total Correlation (TC)** penalty:
250
+
251
+ ```
252
+ TC(z) = KL(q(z) || prod_i q(z_i))
253
+ ```
254
+
255
+ By penalizing TC directly, BetaTCVAE pushes the aggregate posterior toward factorization, often yielding cleaner latent-to-factor mappings than BetaVAE alone.
256
+
257
+ ### Extending
258
+ Add your own model by subclassing `CausalWorldModel`:
259
+
260
+ ```python
261
+ from physicausal.models.base import CausalWorldModel
262
+
263
+ class MyModel(CausalWorldModel):
264
+ def encode(self, obs): ...
265
+ def decode(self, z, action): ...
266
+ def predict_dynamics(self, z, action): ...
267
+ def intervene(self, z, dim, value): ...
268
+ ```
269
+
270
+ ---
271
+
272
+ ## Project Structure
273
+
274
+ ```
275
+ physicausal/
276
+ ├── envs/ # Physics environments
277
+ │ └── simple_push.py
278
+ ├── models/ # Causal world models
279
+ │ ├── base.py # CausalWorldModel ABC
280
+ │ ├── vae.py # WorldModel, BetaVAE
281
+ │ └── beta_tc_vae.py # BetaTCVAE
282
+ ├── causal/ # Validation & metrics
283
+ │ ├── validator.py # CausalValidator suite
284
+ │ └── intervention.py
285
+ ├── training/ # Training engine
286
+ │ ├── agent.py # Agent, ReplayBuffer, train()
287
+ │ └── hparams.py # Optuna search
288
+ ├── benchmarks/ # External format adapters
289
+ │ ├── causalworld.py
290
+ │ └── causalverse.py
291
+ └── utils/ # Shared utilities
292
+ ```
293
+
294
+ ---
295
+
296
+ ## Examples
297
+
298
+ | Example | Description |
299
+ |---------|-------------|
300
+ | `01_quickstart.py` | Train your first causal world model |
301
+ | `02_model_comparison.py` | Compare WorldModel vs BetaVAE vs BetaTCVAE |
302
+ | `03_intervention_analysis.py` | Deep dive into do-operator interventions |
303
+ | `04_hyperparameter_search.py` | Automatic tuning with Optuna |
304
+
305
+ Run any example:
306
+ ```bash
307
+ python examples/01_quickstart.py
308
+ ```
309
+
310
+ ---
311
+
312
+ ## Documentation
313
+
314
+ Full documentation is built with **MkDocs Material** and includes:
315
+
316
+ - Getting Started (installation, quickstart)
317
+ - User Guide (concepts, environments, models, validation, training, hyperparameters)
318
+ - API Reference (auto-generated via mkdocstrings)
319
+ - Development (contributing, changelog)
320
+
321
+ Build locally:
322
+ ```bash
323
+ mkdocs serve
324
+ ```
325
+
326
+ ---
327
+
328
+ ## Testing
329
+
330
+ ```bash
331
+ pytest tests/ -v --cov=physicausal
332
+ ```
333
+
334
+ 53 tests covering environments, models, causal validation, training, and benchmarks.
335
+
336
+ ---
337
+
338
+ ## Known Limitations & Roadmap
339
+
340
+ **Current limitations:**
341
+ - SimplePushEnv uses low-dimensional state observations; visual input is not yet supported.
342
+ - Best reported mass correlation (~0.28) remains below the causal threshold on the minimal setup; richer observations or visual encoders are expected to cross |r| > 0.5.
343
+ - Additional physics environments (collision, stacking) are planned beyond SimplePushEnv and PendulumEnv.
344
+
345
+ **Roadmap:**
346
+ - [ ] Visual encoder backend (CNN-based observations)
347
+ - [ ] Additional physics environments (collision, stacking, rope)
348
+ - [ ] Integration with CausalWorld gym API
349
+ - [ ] Pre-trained model zoo releases
350
+ - [ ] Interactive Colab notebooks
351
+
352
+ ---
353
+
354
+ ## Citation
355
+
356
+ If you use PhysiCausal in your research, please cite:
357
+
358
+ ```bibtex
359
+ @software{physicausal2024,
360
+ title = {PhysiCausal: Causal World Models for Physical Reasoning},
361
+ author = {PhysiCausal Contributors},
362
+ year = {2024},
363
+ url = {https://github.com/Fengrru/physicausal}
364
+ }
365
+ ```
366
+
367
+ ---
368
+
369
+ ## Contributing
370
+
371
+ We welcome contributions! Please see [CONTRIBUTING.md](CONTRIBUTING.md) and [CODE_OF_CONDUCT.md](CODE_OF_CONDUCT.md) for guidelines.
372
+
373
+ ---
374
+
375
+ ## License
376
+
377
+ MIT License — see [LICENSE](LICENSE) for details.