ophanimus 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.
- ophanimus-0.1.0/LICENSE +201 -0
- ophanimus-0.1.0/PKG-INFO +439 -0
- ophanimus-0.1.0/README.md +405 -0
- ophanimus-0.1.0/pyproject.toml +46 -0
- ophanimus-0.1.0/setup.cfg +4 -0
- ophanimus-0.1.0/src/ophanimus/__init__.py +3 -0
- ophanimus-0.1.0/src/ophanimus/_dtype.py +16 -0
- ophanimus-0.1.0/src/ophanimus/algorithms/__init__.py +8 -0
- ophanimus-0.1.0/src/ophanimus/algorithms/clustering.py +91 -0
- ophanimus-0.1.0/src/ophanimus/algorithms/frechet_mean.py +55 -0
- ophanimus-0.1.0/src/ophanimus/algorithms/interpolation.py +73 -0
- ophanimus-0.1.0/src/ophanimus/algorithms/kernels.py +119 -0
- ophanimus-0.1.0/src/ophanimus/algorithms/knn.py +87 -0
- ophanimus-0.1.0/src/ophanimus/algorithms/pga.py +94 -0
- ophanimus-0.1.0/src/ophanimus/algorithms/regression.py +122 -0
- ophanimus-0.1.0/src/ophanimus/algorithms/time_series.py +75 -0
- ophanimus-0.1.0/src/ophanimus/manifold_selection.py +548 -0
- ophanimus-0.1.0/src/ophanimus/manifolds/__init__.py +19 -0
- ophanimus-0.1.0/src/ophanimus/manifolds/hyperboloid.py +159 -0
- ophanimus-0.1.0/src/ophanimus/manifolds/poincare.py +126 -0
- ophanimus-0.1.0/src/ophanimus/manifolds/so3.py +127 -0
- ophanimus-0.1.0/src/ophanimus/manifolds/spd.py +146 -0
- ophanimus-0.1.0/src/ophanimus/manifolds/sphere.py +114 -0
- ophanimus-0.1.0/src/ophanimus.egg-info/PKG-INFO +439 -0
- ophanimus-0.1.0/src/ophanimus.egg-info/SOURCES.txt +34 -0
- ophanimus-0.1.0/src/ophanimus.egg-info/dependency_links.txt +1 -0
- ophanimus-0.1.0/src/ophanimus.egg-info/requires.txt +11 -0
- ophanimus-0.1.0/src/ophanimus.egg-info/top_level.txt +1 -0
- ophanimus-0.1.0/tests/test_algorithms.py +167 -0
- ophanimus-0.1.0/tests/test_dtype.py +173 -0
- ophanimus-0.1.0/tests/test_manifold_selection.py +129 -0
- ophanimus-0.1.0/tests/test_manifolds_hyperboloid.py +76 -0
- ophanimus-0.1.0/tests/test_manifolds_poincare.py +64 -0
- ophanimus-0.1.0/tests/test_manifolds_so3.py +55 -0
- ophanimus-0.1.0/tests/test_manifolds_spd.py +53 -0
- ophanimus-0.1.0/tests/test_manifolds_sphere.py +67 -0
ophanimus-0.1.0/LICENSE
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for describing the origin of the Work and
|
|
141
|
+
reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Support. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or support.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright 2026 Nicholas Fleischhauer
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
ophanimus-0.1.0/PKG-INFO
ADDED
|
@@ -0,0 +1,439 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: ophanimus
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Riemannian manifold primitives and geodesic algorithms
|
|
5
|
+
Author: Nicholas Fleischhauer
|
|
6
|
+
License-Expression: Apache-2.0
|
|
7
|
+
Project-URL: Homepage, https://github.com/Unobtainiumrock/ophanimus
|
|
8
|
+
Project-URL: Repository, https://github.com/Unobtainiumrock/ophanimus
|
|
9
|
+
Project-URL: Issues, https://github.com/Unobtainiumrock/ophanimus/issues
|
|
10
|
+
Keywords: riemannian,manifold,hyperbolic,geodesic,embedding,poincare,lorentz
|
|
11
|
+
Classifier: Development Status :: 3 - Alpha
|
|
12
|
+
Classifier: Intended Audience :: Science/Research
|
|
13
|
+
Classifier: Intended Audience :: Developers
|
|
14
|
+
Classifier: Operating System :: OS Independent
|
|
15
|
+
Classifier: Programming Language :: Python :: 3
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
19
|
+
Classifier: Topic :: Scientific/Engineering :: Mathematics
|
|
20
|
+
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
|
|
21
|
+
Requires-Python: >=3.10
|
|
22
|
+
Description-Content-Type: text/markdown
|
|
23
|
+
License-File: LICENSE
|
|
24
|
+
Requires-Dist: numpy>=1.24
|
|
25
|
+
Requires-Dist: scipy>=1.11
|
|
26
|
+
Provides-Extra: dev
|
|
27
|
+
Requires-Dist: ruff; extra == "dev"
|
|
28
|
+
Requires-Dist: mypy; extra == "dev"
|
|
29
|
+
Requires-Dist: build; extra == "dev"
|
|
30
|
+
Requires-Dist: twine; extra == "dev"
|
|
31
|
+
Provides-Extra: test
|
|
32
|
+
Requires-Dist: pytest>=7; extra == "test"
|
|
33
|
+
Dynamic: license-file
|
|
34
|
+
|
|
35
|
+
# Ophanimus
|
|
36
|
+
|
|
37
|
+
**Riemannian manifold primitives and geodesic algorithms** — pure geometry, no retrieval stack, no vector DB, no training loops for text embeddings.
|
|
38
|
+
|
|
39
|
+
## Install
|
|
40
|
+
|
|
41
|
+
```bash
|
|
42
|
+
pip install . # or: pip install -e . for development
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
Import the **`ophanimus`** package (PyPI name: `ophanimus`).
|
|
46
|
+
|
|
47
|
+
```python
|
|
48
|
+
from ophanimus.manifolds import poincare, hyperboloid
|
|
49
|
+
from ophanimus.algorithms import geodesic_regression
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
Layout follows the standard **`src/`** layout so the package is what gets installed, not stray repo files.
|
|
53
|
+
|
|
54
|
+
## Structure
|
|
55
|
+
|
|
56
|
+
```
|
|
57
|
+
├── pyproject.toml
|
|
58
|
+
├── src/
|
|
59
|
+
│ └── ophanimus/
|
|
60
|
+
│ ├── manifolds/ # Riemannian manifold primitives
|
|
61
|
+
│ │ ├── sphere.py # Unit sphere S^n
|
|
62
|
+
│ │ ├── poincare.py # Poincaré ball D^n (variable curvature)
|
|
63
|
+
│ │ ├── hyperboloid.py # Hyperboloid H^n (Lorentz model)
|
|
64
|
+
│ │ ├── so3.py # Rotation group SO(3)
|
|
65
|
+
│ │ └── spd.py # Symmetric positive definite matrices Sym+_n
|
|
66
|
+
│ ├── algorithms/ # Downstream tasks using manifold primitives
|
|
67
|
+
│ │ ├── frechet_mean.py # Manifold centroid
|
|
68
|
+
│ │ ├── regression.py # Geodesic regression
|
|
69
|
+
│ │ ├── clustering.py # Manifold k-means
|
|
70
|
+
│ │ ├── knn.py # Geodesic k-nearest neighbors
|
|
71
|
+
│ │ ├── interpolation.py # Geodesic interpolation
|
|
72
|
+
│ │ ├── pga.py # Principal geodesic analysis
|
|
73
|
+
│ │ ├── kernels.py # Manifold-aware kernels
|
|
74
|
+
│ │ └── time_series.py # Velocity comparison via parallel transport
|
|
75
|
+
│ └── manifold_selection.py # Distance matrix construction + geometry selection
|
|
76
|
+
├── notes.md # Background theory notes
|
|
77
|
+
└── TODO.md
|
|
78
|
+
```
|
|
79
|
+
|
|
80
|
+
Each manifold module exposes four primitives:
|
|
81
|
+
- `exp_map(p, v)` — walk from point p along tangent vector v
|
|
82
|
+
- `log_map(p, q)` — tangent vector at p pointing toward q (inverse of exp_map)
|
|
83
|
+
- `distance(p, q)` — geodesic distance between two points
|
|
84
|
+
- `parallel_transport(v, p, q)` — slide tangent vector v from p's tangent space to q's
|
|
85
|
+
|
|
86
|
+
## Geodesic Regression
|
|
87
|
+
|
|
88
|
+
`ophanimus/algorithms/regression.py` provides `geodesic_regression(X, Y, exp_map, log_map, distance, parallel_transport)` which fits the model:
|
|
89
|
+
|
|
90
|
+
```
|
|
91
|
+
ŷ_i = Exp_p(x_i · v)
|
|
92
|
+
```
|
|
93
|
+
|
|
94
|
+
This is the manifold analogue of `y = p + x·v`. It works with any manifold — just pass in the three primitives:
|
|
95
|
+
|
|
96
|
+
```python
|
|
97
|
+
from ophanimus.manifolds import sphere
|
|
98
|
+
from ophanimus.algorithms import geodesic_regression
|
|
99
|
+
|
|
100
|
+
p, v, losses = geodesic_regression(X, Y,
|
|
101
|
+
sphere.exp_map, sphere.log_map, sphere.distance, sphere.parallel_transport)
|
|
102
|
+
```
|
|
103
|
+
|
|
104
|
+
## Hyperboloid vs Poincaré: Engine vs Dashboard
|
|
105
|
+
|
|
106
|
+
We have two models of hyperbolic space: the **Hyperboloid** (Lorentz model) in
|
|
107
|
+
`hyperboloid.py` and the **Poincaré ball** in `poincare.py`. They represent the
|
|
108
|
+
same underlying geometry — the same way a Mercator map and a globe represent
|
|
109
|
+
the same Earth.
|
|
110
|
+
|
|
111
|
+
**The Hyperboloid is the engine.** Use it for computation — gradient descent,
|
|
112
|
+
optimization, training. Its formulas are numerically stable everywhere because
|
|
113
|
+
there's no boundary singularity. The Poincaré ball's conformal factor
|
|
114
|
+
`2/(1-||x||^2)` explodes as points approach the boundary; the hyperboloid has
|
|
115
|
+
no such problem.
|
|
116
|
+
|
|
117
|
+
**The Poincaré ball is the dashboard.** Use it for visualization, interpretation,
|
|
118
|
+
and passing results to other systems. It's bounded (everything fits in a disc/ball),
|
|
119
|
+
making it natural for humans to look at and reason about.
|
|
120
|
+
|
|
121
|
+
In practice: train on the hyperboloid, convert to Poincaré for display.
|
|
122
|
+
|
|
123
|
+
### Converting between models
|
|
124
|
+
|
|
125
|
+
```python
|
|
126
|
+
from ophanimus.manifolds.hyperboloid import from_poincare, to_poincare
|
|
127
|
+
|
|
128
|
+
# Hyperboloid (n+1 dims) -> Poincaré ball (n dims)
|
|
129
|
+
p = to_poincare(x) # x[0] is the time component, x[1:] are spatial
|
|
130
|
+
|
|
131
|
+
# Poincaré ball (n dims) -> Hyperboloid (n+1 dims)
|
|
132
|
+
x = from_poincare(p) # prepends the time component
|
|
133
|
+
```
|
|
134
|
+
|
|
135
|
+
The formulas:
|
|
136
|
+
```
|
|
137
|
+
Hyperboloid -> Poincaré: p_i = x_i / (1 + x_0)
|
|
138
|
+
Poincaré -> Hyperboloid: x_0 = (1 + ||p||^2) / (1 - ||p||^2)
|
|
139
|
+
x_i = 2*p_i / (1 - ||p||^2)
|
|
140
|
+
```
|
|
141
|
+
|
|
142
|
+
Points near the Poincaré boundary (||p|| -> 1) map to large x_0 on the
|
|
143
|
+
hyperboloid — they're "high up" on the sheet, far from the origin. The
|
|
144
|
+
center of the Poincaré ball (p = 0) maps to the base of the hyperboloid
|
|
145
|
+
(x = [1, 0, 0, ...]).
|
|
146
|
+
|
|
147
|
+
## Learning Curvature for Poincaré Embeddings
|
|
148
|
+
|
|
149
|
+
The Poincaré ball has a curvature parameter `c` (where K = -c) that controls how aggressively the space expands outward. All four functions in `poincare.py` accept `c` as an optional parameter (defaults to 1.0):
|
|
150
|
+
|
|
151
|
+
```python
|
|
152
|
+
from ophanimus.manifolds import poincare
|
|
153
|
+
|
|
154
|
+
# Fixed curvature
|
|
155
|
+
d = poincare.distance(u, v, c=2.0)
|
|
156
|
+
q = poincare.exp_map(p, tangent, c=2.0)
|
|
157
|
+
```
|
|
158
|
+
|
|
159
|
+
### Making c learnable
|
|
160
|
+
|
|
161
|
+
To learn c alongside p and v in geodesic regression, wrap the Poincaré operations with a shared c and differentiate through it. The idea: c is a scalar parameter in the loss function, so gradient descent can tune it just like any other weight.
|
|
162
|
+
|
|
163
|
+
```python
|
|
164
|
+
import numpy as np
|
|
165
|
+
from ophanimus.manifolds import poincare
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
def learn_curvature(X, Y, lr=1e-3, lr_c=1e-4, steps=1000):
|
|
169
|
+
"""Geodesic regression with learnable Poincaré curvature.
|
|
170
|
+
|
|
171
|
+
Jointly optimizes base point p, tangent direction v, and
|
|
172
|
+
curvature c via Riemannian gradient descent.
|
|
173
|
+
"""
|
|
174
|
+
N = len(Y)
|
|
175
|
+
c = 1.0 # initial curvature
|
|
176
|
+
|
|
177
|
+
# Initialize p at Fréchet mean
|
|
178
|
+
p = Y[0].copy().astype(np.float64)
|
|
179
|
+
for _ in range(50):
|
|
180
|
+
tangents = [poincare.log_map(p, Y[i], c) for i in range(N)]
|
|
181
|
+
mean_t = np.mean(tangents, axis=0)
|
|
182
|
+
if np.linalg.norm(mean_t) < 1e-10:
|
|
183
|
+
break
|
|
184
|
+
p = poincare.exp_map(p, mean_t, c)
|
|
185
|
+
|
|
186
|
+
# Initialize v via tangent-space OLS
|
|
187
|
+
tangents = [poincare.log_map(p, Y[i], c) for i in range(N)]
|
|
188
|
+
W = np.array(tangents)
|
|
189
|
+
x_sq = np.dot(X, X)
|
|
190
|
+
v = np.tensordot(X, W, axes=([0], [0])) / x_sq if x_sq > 1e-15 else np.zeros_like(p)
|
|
191
|
+
|
|
192
|
+
for step in range(steps):
|
|
193
|
+
# Forward pass
|
|
194
|
+
Y_hat = [poincare.exp_map(p, X[i] * v, c) for i in range(N)]
|
|
195
|
+
loss = np.mean([poincare.distance(Y[i], Y_hat[i], c) ** 2 for i in range(N)])
|
|
196
|
+
|
|
197
|
+
# Gradient for c via finite differences
|
|
198
|
+
eps = 1e-6
|
|
199
|
+
Y_hat_plus = [poincare.exp_map(p, X[i] * v, c + eps) for i in range(N)]
|
|
200
|
+
loss_plus = np.mean([poincare.distance(Y[i], Y_hat_plus[i], c + eps) ** 2 for i in range(N)])
|
|
201
|
+
grad_c = (loss_plus - loss) / eps
|
|
202
|
+
|
|
203
|
+
# Tangent-space gradients for p and v
|
|
204
|
+
errors = [poincare.log_map(p, Y[i], c) - X[i] * v for i in range(N)]
|
|
205
|
+
grad_v = -np.mean([X[i] * errors[i] for i in range(N)], axis=0)
|
|
206
|
+
grad_p = -np.mean(errors, axis=0)
|
|
207
|
+
|
|
208
|
+
# Update all three parameters
|
|
209
|
+
v = v - lr * grad_v
|
|
210
|
+
p = poincare.exp_map(p, -lr * grad_p, c)
|
|
211
|
+
c = max(1e-6, c - lr_c * grad_c) # clamp c > 0
|
|
212
|
+
|
|
213
|
+
return p, v, c
|
|
214
|
+
```
|
|
215
|
+
|
|
216
|
+
Key details:
|
|
217
|
+
|
|
218
|
+
- **Separate learning rate for c** (`lr_c`): curvature changes affect the entire geometry, so it typically needs a smaller step size than p and v to stay stable.
|
|
219
|
+
- **Finite-difference gradient for c**: we compute `dL/dc ≈ (L(c+ε) - L(c)) / ε`. This is simple and works well since c is a single scalar. For a production system you could derive the analytic gradient instead.
|
|
220
|
+
- **Clamping `c > 0`**: curvature must stay positive (negative curvature space). As c approaches 0, the space flattens to Euclidean — which is a valid outcome if your data isn't hierarchical.
|
|
221
|
+
- **What c learns**: high c (steep curvature) if the data has deep hierarchy with exponential branching. Low c (gentle curvature) if the structure is shallow. Near-zero c if the data is essentially flat.
|
|
222
|
+
|
|
223
|
+
## Defining New Manifolds
|
|
224
|
+
|
|
225
|
+
To add a new manifold to `src/ophanimus/manifolds/`, you need to derive and implement the same three primitives: `exp_map`, `log_map`, and `distance`. This follows a four-step pipeline from differential geometry.
|
|
226
|
+
|
|
227
|
+
### Step 1: Define the Space and the Metric
|
|
228
|
+
|
|
229
|
+
A Riemannian manifold starts with a set of points and a **metric** g_p(u, v) — an inner product on the tangent space at each point p. The metric defines what "length" and "angle" mean in your space.
|
|
230
|
+
|
|
231
|
+
The metric is what makes each manifold unique. For example, the Poincare disk and flat 2D Euclidean space are both sets of 2D points. The only difference is that the Poincare disk uses a metric that inflates distances near the boundary. Change the metric, change the entire geometry.
|
|
232
|
+
|
|
233
|
+
For a new manifold, write down g_p(u, v) explicitly. Everything else follows from it.
|
|
234
|
+
|
|
235
|
+
### Step 2: Derive the Geodesic Equation
|
|
236
|
+
|
|
237
|
+
Geodesics (shortest paths) are found by minimizing the curve length integral under your metric:
|
|
238
|
+
|
|
239
|
+
```
|
|
240
|
+
L(gamma) = integral of sqrt(g(gamma'(t), gamma'(t))) dt
|
|
241
|
+
```
|
|
242
|
+
|
|
243
|
+
Applying the Euler-Lagrange equations from calculus of variations gives the **geodesic equation**:
|
|
244
|
+
|
|
245
|
+
```
|
|
246
|
+
gamma''_k + sum_ij Gamma^k_ij gamma'_i gamma'_j = 0
|
|
247
|
+
```
|
|
248
|
+
|
|
249
|
+
The Christoffel symbols Gamma^k_ij are computed directly from derivatives of your metric g. This is the ODE that governs "straight-line" motion in your space.
|
|
250
|
+
|
|
251
|
+
### Step 3: Solve for the Exponential Map (Forward: IVP)
|
|
252
|
+
|
|
253
|
+
The exp map is an **initial value problem**: place a particle at point p with velocity v and solve the geodesic ODE forward to t=1.
|
|
254
|
+
|
|
255
|
+
```
|
|
256
|
+
gamma(0) = p, gamma'(0) = v --> Exp_p(v) = gamma(1)
|
|
257
|
+
```
|
|
258
|
+
|
|
259
|
+
For simple manifolds (sphere, hyperbolic space), this ODE has a closed-form solution — that's where formulas like `cos(||v||) p + sin(||v||) v/||v||` come from. For complex manifolds where no closed form exists, use a numerical ODE solver (e.g. Runge-Kutta via `scipy.integrate.solve_ivp`).
|
|
260
|
+
|
|
261
|
+
### Step 4: Invert for the Logarithmic Map (Backward: BVP)
|
|
262
|
+
|
|
263
|
+
The log map is a **boundary value problem**: given start p and end q, find the initial velocity v that makes the geodesic hit q at t=1.
|
|
264
|
+
|
|
265
|
+
```
|
|
266
|
+
gamma(0) = p, gamma(1) = q --> Log_p(q) = gamma'(0)
|
|
267
|
+
```
|
|
268
|
+
|
|
269
|
+
The norm of the resulting vector ||Log_p(q)|| equals the geodesic distance d(p, q), which is the error signal used in geodesic regression.
|
|
270
|
+
|
|
271
|
+
For simple manifolds this also has a closed form. For complex ones, use a BVP solver (e.g. `scipy.integrate.solve_bvp`) or shooting methods.
|
|
272
|
+
|
|
273
|
+
### Adding a new manifold to this codebase
|
|
274
|
+
|
|
275
|
+
1. Create `src/ophanimus/manifolds/your_manifold.py`
|
|
276
|
+
2. Implement `exp_map(p, v)`, `log_map(p, q)`, `distance(p, q)` following the steps above
|
|
277
|
+
3. Register the submodule in `manifolds/__init__.py` (see existing entries)
|
|
278
|
+
4. It will work immediately with `geodesic_regression`:
|
|
279
|
+
|
|
280
|
+
```python
|
|
281
|
+
from ophanimus.manifolds import your_manifold
|
|
282
|
+
p, v, losses = geodesic_regression(X, Y, your_manifold.exp_map, your_manifold.log_map, your_manifold.distance)
|
|
283
|
+
```
|
|
284
|
+
|
|
285
|
+
### When you can't solve analytically
|
|
286
|
+
|
|
287
|
+
If your metric produces a geodesic equation with no closed-form solution, implement exp_map and log_map numerically:
|
|
288
|
+
|
|
289
|
+
```python
|
|
290
|
+
from scipy.integrate import solve_ivp, solve_bvp
|
|
291
|
+
|
|
292
|
+
def exp_map(p, v):
|
|
293
|
+
# Solve geodesic ODE as IVP: gamma(0)=p, gamma'(0)=v
|
|
294
|
+
def geodesic_ode(t, state):
|
|
295
|
+
pos, vel = state[:n], state[n:]
|
|
296
|
+
accel = -christoffel_contraction(pos, vel) # your Gamma terms
|
|
297
|
+
return np.concatenate([vel, accel])
|
|
298
|
+
|
|
299
|
+
sol = solve_ivp(geodesic_ode, [0, 1], np.concatenate([p, v]))
|
|
300
|
+
return sol.y[:n, -1] # position at t=1
|
|
301
|
+
```
|
|
302
|
+
|
|
303
|
+
This makes the framework extensible to any Riemannian manifold, even exotic ones where the geometry is too complex for pen-and-paper solutions.
|
|
304
|
+
|
|
305
|
+
## Manifold Selection
|
|
306
|
+
|
|
307
|
+
`ophanimus/manifold_selection.py` helps you determine which geometry fits your data best. The full pipeline takes raw data through to a geometry recommendation:
|
|
308
|
+
|
|
309
|
+
```
|
|
310
|
+
Raw Data ──► Clean ──► Distance Matrix ──► select_manifold() ──► Recommendation
|
|
311
|
+
| |
|
|
312
|
+
(from graph, features, v
|
|
313
|
+
or similarity scores) Use that manifold's
|
|
314
|
+
exp/log/distance for
|
|
315
|
+
downstream work
|
|
316
|
+
(regression, clustering,
|
|
317
|
+
nearest neighbors, etc.)
|
|
318
|
+
```
|
|
319
|
+
|
|
320
|
+
### Building the Distance Matrix
|
|
321
|
+
|
|
322
|
+
Everything starts from a pairwise distance matrix — an NxN table that says "how far apart are these two things?" without assuming any geometry. How you build it depends on what your raw data looks like:
|
|
323
|
+
|
|
324
|
+
**From feature vectors** (embeddings, sensor readings, tabular data):
|
|
325
|
+
```python
|
|
326
|
+
from ophanimus.manifold_selection import distance_from_features
|
|
327
|
+
D = distance_from_features(X, metric="cosine") # or "euclidean", "correlation"
|
|
328
|
+
```
|
|
329
|
+
|
|
330
|
+
**From a graph** (social network, taxonomy, knowledge graph):
|
|
331
|
+
```python
|
|
332
|
+
from ophanimus.manifold_selection import distance_from_graph
|
|
333
|
+
D = distance_from_graph(adj_matrix, weighted=False) # BFS shortest paths
|
|
334
|
+
```
|
|
335
|
+
|
|
336
|
+
**From a similarity matrix** (co-occurrence, transition probabilities, ratings):
|
|
337
|
+
```python
|
|
338
|
+
from ophanimus.manifold_selection import distance_from_similarity
|
|
339
|
+
D = distance_from_similarity(S, method="neglog") # or "subtract", "inverse"
|
|
340
|
+
```
|
|
341
|
+
|
|
342
|
+
### The choice of distance conversion matters
|
|
343
|
+
|
|
344
|
+
The way you convert raw data into distances is not neutral — it changes what geometry the pipeline will recommend. The same similarity matrix can point to different geometries depending on the conversion:
|
|
345
|
+
|
|
346
|
+
- **"subtract"** (`d = max(S) - S`): Linear transform. Preserves rank ordering but treats the similarity scale as uniform. Use as a safe default.
|
|
347
|
+
- **"inverse"** (`d = 1/S`): Nonlinear. Heavily penalizes low-similarity pairs, pushing them far apart. Use when low similarity should mean very distant.
|
|
348
|
+
- **"neglog"** (`d = -log(S)`): Makes distances additive. If S contains transition probabilities, the distance from A to C via B equals d(A,B) + d(B,C). This is exactly how tree distances work, so neglog will reveal hierarchical structure that subtract would miss.
|
|
349
|
+
|
|
350
|
+
If you are unsure, run `select_manifold` with multiple conversions. If the recommendation is consistent across methods, trust it. If it flips (e.g. neglog says "poincare" but subtract says "euclidean"), that is telling you the geometry is ambiguous at that scale — the conversion is shaping the result more than the data is.
|
|
351
|
+
|
|
352
|
+
Similarly for feature-based distances: cosine ignores magnitude (good for text embeddings where a long document and short document about the same topic should be similar), Euclidean cares about magnitude (good for physical measurements), and correlation removes the per-point baseline (good for time series patterns).
|
|
353
|
+
|
|
354
|
+
### Cleaning Before Building Distances
|
|
355
|
+
|
|
356
|
+
Before constructing the distance matrix:
|
|
357
|
+
- **Remove NaN/inf/duplicates** from feature matrices.
|
|
358
|
+
- **Subsample if N > ~2000** — the distance matrix is O(N^2), and the embedding step is expensive. 500-2000 points is usually enough to detect the underlying geometry.
|
|
359
|
+
- **Check connectivity for graphs** — `distance_from_graph` returns `inf` for unreachable pairs. Either cap these at a large finite value or analyze connected components separately.
|
|
360
|
+
- **Normalize if using cosine** — zero vectors produce NaN in cosine distance.
|
|
361
|
+
|
|
362
|
+
### What select_manifold Returns
|
|
363
|
+
|
|
364
|
+
```python
|
|
365
|
+
from ophanimus.manifold_selection import select_manifold
|
|
366
|
+
|
|
367
|
+
result = select_manifold(D, dim=10)
|
|
368
|
+
```
|
|
369
|
+
|
|
370
|
+
The function runs two stages:
|
|
371
|
+
|
|
372
|
+
**Stage 1 — Gromov delta-hyperbolicity** (no embedding needed): Tests how "tree-like" your distance matrix is by sampling quadruples of points and checking the four-point condition. `delta_relative < 0.1` means the data is strongly hierarchical and hyperbolic geometry is indicated. `delta_relative > 0.25` means the data is not tree-like.
|
|
373
|
+
|
|
374
|
+
**Stage 2 — Competitive embedding**: Embeds the distance matrix into Euclidean, Sphere, and Poincare at the same dimension, then measures distortion for each. Uses two metrics:
|
|
375
|
+
- **Stress**: normalized RMSE of distance errors. Single number, lower = better fit.
|
|
376
|
+
- **Distortion ratios**: per-pair `d_embedded / d_original`. The max ratio is the worst-case multiplicative distortion. The variance tells you whether distortion is uniform or concentrated on specific pairs.
|
|
377
|
+
|
|
378
|
+
The result includes a ranking by stress and a recommended geometry:
|
|
379
|
+
```python
|
|
380
|
+
print(result["recommendation"]) # "poincare"
|
|
381
|
+
print(result["gromov"]["delta_relative"]) # 0.04 (tree-like)
|
|
382
|
+
print(result["ranking"]) # ["poincare", "euclidean", "sphere"]
|
|
383
|
+
for geom in result["ranking"]:
|
|
384
|
+
r = result["embeddings"][geom]
|
|
385
|
+
print(f" {geom}: stress={r['stress']:.4f}, ratio_var={r['ratio_variance']:.4f}")
|
|
386
|
+
```
|
|
387
|
+
|
|
388
|
+
## Downstream Tasks
|
|
389
|
+
|
|
390
|
+
Once you have a geometry recommendation and can embed into it, a family of
|
|
391
|
+
algorithms becomes available. They all follow the same pattern: take the
|
|
392
|
+
Euclidean version, replace Euclidean operations with manifold primitives.
|
|
393
|
+
|
|
394
|
+
```
|
|
395
|
+
┌───────────────────────┐
|
|
396
|
+
│ Manifold Primitives │
|
|
397
|
+
│ exp, log, distance, │
|
|
398
|
+
│ parallel_transport │
|
|
399
|
+
└──────────┬────────────┘
|
|
400
|
+
│
|
|
401
|
+
┌───────────┬───────────┼───────────┬──────────────┐
|
|
402
|
+
v v v v v
|
|
403
|
+
┌───────────┐ ┌────────┐ ┌────────┐ ┌─────────┐ ┌─────────────┐
|
|
404
|
+
│ Fréchet │ │Geodesic│ │ k-NN │ │ PGA │ │ Kernels │
|
|
405
|
+
│ Mean │ │Regression│ │ │ (PCA) │ │ (GP, SVM) │
|
|
406
|
+
└─────┬─────┘ └────────┘ └────────┘ └─────────┘ └─────────────┘
|
|
407
|
+
│
|
|
408
|
+
┌─────┴─────┐
|
|
409
|
+
│ k-Means │
|
|
410
|
+
│ Clustering│
|
|
411
|
+
└───────────┘
|
|
412
|
+
```
|
|
413
|
+
|
|
414
|
+
All downstream tasks live in `ophanimus/algorithms/`:
|
|
415
|
+
|
|
416
|
+
```
|
|
417
|
+
ophanimus/algorithms/
|
|
418
|
+
├── frechet_mean.py # Manifold centroid (used by regression + clustering)
|
|
419
|
+
├── regression.py # Geodesic regression
|
|
420
|
+
├── clustering.py # Manifold k-means (Fréchet mean per cluster)
|
|
421
|
+
├── knn.py # Geodesic k-nearest neighbors
|
|
422
|
+
├── interpolation.py # Walk along geodesics between points
|
|
423
|
+
├── pga.py # Principal geodesic analysis (manifold PCA)
|
|
424
|
+
├── kernels.py # Geodesic distance kernels (for GP, SVM, KDE)
|
|
425
|
+
└── time_series.py # Compare velocities via parallel transport
|
|
426
|
+
```
|
|
427
|
+
|
|
428
|
+
Each algorithm takes manifold primitives as arguments, so they work with
|
|
429
|
+
any geometry:
|
|
430
|
+
|
|
431
|
+
```python
|
|
432
|
+
from ophanimus.algorithms.clustering import kmeans
|
|
433
|
+
from ophanimus.manifolds import poincare
|
|
434
|
+
|
|
435
|
+
labels, centers = kmeans(points, k=5,
|
|
436
|
+
exp_map=poincare.exp_map,
|
|
437
|
+
log_map=poincare.log_map,
|
|
438
|
+
distance=poincare.distance)
|
|
439
|
+
```
|