fxtensor-salmon 0.2.2__tar.gz → 1.2.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.
- fxtensor_salmon-1.2.0/PKG-INFO +515 -0
- fxtensor_salmon-1.2.0/README.md +486 -0
- {fxtensor_salmon-0.2.2 → fxtensor_salmon-1.2.0}/pyproject.toml +23 -1
- fxtensor_salmon-1.2.0/src/fxtensor_salmon/__init__.py +3 -0
- fxtensor_salmon-1.2.0/src/fxtensor_salmon/core.py +113 -0
- fxtensor_salmon-1.2.0/src/fxtensor_salmon/discopy.py +362 -0
- fxtensor_salmon-1.2.0/src/fxtensor_salmon/io.py +75 -0
- fxtensor_salmon-1.2.0/src/fxtensor_salmon/operations.py +239 -0
- fxtensor_salmon-1.2.0/src/fxtensor_salmon/profile.py +62 -0
- fxtensor_salmon-1.2.0/src/fxtensor_salmon/special.py +78 -0
- fxtensor_salmon-1.2.0/src/fxtensor_salmon.egg-info/PKG-INFO +515 -0
- {fxtensor_salmon-0.2.2 → fxtensor_salmon-1.2.0}/src/fxtensor_salmon.egg-info/SOURCES.txt +10 -1
- fxtensor_salmon-1.2.0/src/fxtensor_salmon.egg-info/requires.txt +8 -0
- fxtensor_salmon-1.2.0/tests/test_axioms.py +173 -0
- fxtensor_salmon-1.2.0/tests/test_discopy.py +169 -0
- {fxtensor_salmon-0.2.2 → fxtensor_salmon-1.2.0}/tests/test_fxtensor.py +142 -1
- fxtensor_salmon-1.2.0/tests/test_inference.py +173 -0
- fxtensor_salmon-0.2.2/PKG-INFO +0 -307
- fxtensor_salmon-0.2.2/README.md +0 -283
- fxtensor_salmon-0.2.2/src/fxtensor_salmon/__init__.py +0 -398
- fxtensor_salmon-0.2.2/src/fxtensor_salmon.egg-info/PKG-INFO +0 -307
- fxtensor_salmon-0.2.2/src/fxtensor_salmon.egg-info/requires.txt +0 -1
- {fxtensor_salmon-0.2.2 → fxtensor_salmon-1.2.0}/LICENSE +0 -0
- {fxtensor_salmon-0.2.2 → fxtensor_salmon-1.2.0}/setup.cfg +0 -0
- {fxtensor_salmon-0.2.2 → fxtensor_salmon-1.2.0}/src/fxtensor_salmon.egg-info/dependency_links.txt +0 -0
- {fxtensor_salmon-0.2.2 → fxtensor_salmon-1.2.0}/src/fxtensor_salmon.egg-info/top_level.txt +0 -0
|
@@ -0,0 +1,515 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: fxtensor_salmon
|
|
3
|
+
Version: 1.2.0
|
|
4
|
+
Summary: Markov Tensor Module
|
|
5
|
+
Author-email: Tadachika Oki <sakesnare@gmail.com>
|
|
6
|
+
License: Copyright 2025 Tadachika Oki
|
|
7
|
+
|
|
8
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
|
9
|
+
|
|
10
|
+
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
|
|
11
|
+
|
|
12
|
+
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
|
13
|
+
|
|
14
|
+
Project-URL: Homepage, https://github.com/salmonsnare/fxtensor-salmon
|
|
15
|
+
Classifier: Programming Language :: Python :: 3
|
|
16
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
17
|
+
Classifier: Operating System :: OS Independent
|
|
18
|
+
Classifier: Topic :: Scientific/Engineering :: Mathematics
|
|
19
|
+
Requires-Python: >=3.8
|
|
20
|
+
Description-Content-Type: text/markdown
|
|
21
|
+
License-File: LICENSE
|
|
22
|
+
Requires-Dist: numpy>=1.20.0
|
|
23
|
+
Provides-Extra: dev
|
|
24
|
+
Requires-Dist: pytest; extra == "dev"
|
|
25
|
+
Requires-Dist: ruff; extra == "dev"
|
|
26
|
+
Provides-Extra: discopy
|
|
27
|
+
Requires-Dist: discopy<2,>=1.2; extra == "discopy"
|
|
28
|
+
Dynamic: license-file
|
|
29
|
+
|
|
30
|
+
# FXTensor
|
|
31
|
+
|
|
32
|
+
FXTensor is a Python library for tensor-based computations, particularly suited for modeling probabilistic systems and processes inspired by category theory. It leverages NumPy for efficient numerical computations. The library primarily supports labeled indices for enhanced readability while maintaining compatibility with unlabeled numeric indices.
|
|
33
|
+
|
|
34
|
+
## Core Concepts
|
|
35
|
+
|
|
36
|
+
An FXTensor is defined by its `profile` and `data`, with optional string labels to make tensors more intuitive and meaningful.
|
|
37
|
+
|
|
38
|
+
- **Profile**: A pair `[domain, codomain]` specifying the dimensions of input (domain) and output (codomain) indices. For labeled tensors, e.g., `[[['a', 'b']], [['x', 'y', 'z']]]` represents a 2x3 matrix with labeled rows and columns. For unlabeled tensors, `[[2], [3]]` specifies dimensions numerically.
|
|
39
|
+
- **Labels (Optional)**: String labels can be assigned to each dimension, enhancing interpretability. For example, input axis labeled `['a', 'b']` and output axis labeled `['x', 'y', 'z']`. Unlabeled tensors have `labels` set to `None`.
|
|
40
|
+
- **Data**: A NumPy array holding the tensor’s values. Its shape must match the total number of dimensions in the profile (`len(domain) + len(codomain)`).
|
|
41
|
+
|
|
42
|
+
## Usage Examples
|
|
43
|
+
|
|
44
|
+
### Basic Example: Labeled Tensor
|
|
45
|
+
|
|
46
|
+
```python
|
|
47
|
+
import numpy as np
|
|
48
|
+
from fxtensor_salmon import FXTensor
|
|
49
|
+
|
|
50
|
+
# Create a 2x3 matrix with string labels
|
|
51
|
+
profile = [[['a', 'b']], [['x', 'y', 'z']]]
|
|
52
|
+
data = np.array([
|
|
53
|
+
[0.1, 0.2, 0.7], # a -> x, y, z
|
|
54
|
+
[0.3, 0.3, 0.4] # b -> x, y, z
|
|
55
|
+
])
|
|
56
|
+
tensor = FXTensor(profile, data=data)
|
|
57
|
+
|
|
58
|
+
# Access elements using labels
|
|
59
|
+
assert tensor.get_label_index(0, 'a') == 0 # Index of label 'a' on input axis
|
|
60
|
+
assert tensor.get_index_label(1, 2) == 'z' # Label at index 2 on output axis
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
### Unlabeled Tensor
|
|
64
|
+
|
|
65
|
+
```python
|
|
66
|
+
# Create a 2x3 matrix with numeric indices
|
|
67
|
+
profile = [[2], [3]]
|
|
68
|
+
data = np.array([
|
|
69
|
+
[0.1, 0.2, 0.7],
|
|
70
|
+
[0.3, 0.3, 0.4]
|
|
71
|
+
])
|
|
72
|
+
tensor = FXTensor(profile, data=data)
|
|
73
|
+
assert tensor.labels == (None, None) # No labels
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
### Creating Tensor from Strands
|
|
77
|
+
|
|
78
|
+
```python
|
|
79
|
+
# Create a tensor from labeled strands
|
|
80
|
+
profile = [[['a', 'b']], [['x', 'y', 'z']]]
|
|
81
|
+
strands = {
|
|
82
|
+
"[[['a']], [['x']]]": 0.1,
|
|
83
|
+
"[[['a']], [['y']]]": 0.2,
|
|
84
|
+
"[[['a']], [['z']]]": 0.7,
|
|
85
|
+
"[[['b']], [['x']]]": 0.3,
|
|
86
|
+
"[[['b']], [['y']]]": 0.3,
|
|
87
|
+
"[[['b']], [['z']]]": 0.4
|
|
88
|
+
}
|
|
89
|
+
tensor = FXTensor.from_strands(profile, strands)
|
|
90
|
+
assert tensor.labels == ([['a', 'b']], [['x', 'y', 'z']])
|
|
91
|
+
```
|
|
92
|
+
|
|
93
|
+
### Labeled Tensor Composition
|
|
94
|
+
|
|
95
|
+
```python
|
|
96
|
+
# P(Y|X) where X={a,b}, Y={x,y}
|
|
97
|
+
tensor1 = FXTensor(
|
|
98
|
+
[[['a', 'b']], [['x', 'y']]],
|
|
99
|
+
data=np.array([
|
|
100
|
+
[0.2, 0.8], # a -> x, y
|
|
101
|
+
[0.6, 0.4] # b -> x, y
|
|
102
|
+
])
|
|
103
|
+
)
|
|
104
|
+
|
|
105
|
+
# P(Z|Y) where Y={x,y}, Z={p,q}
|
|
106
|
+
tensor2 = FXTensor(
|
|
107
|
+
[[['x', 'y']], [['p', 'q']]],
|
|
108
|
+
data=np.array([
|
|
109
|
+
[0.3, 0.7], # x -> p, q
|
|
110
|
+
[0.9, 0.1] # y -> p, q
|
|
111
|
+
])
|
|
112
|
+
)
|
|
113
|
+
|
|
114
|
+
# Composition: P(Z|X) = P(Y|X) ; P(Z|Y)
|
|
115
|
+
result = tensor1.composition(tensor2)
|
|
116
|
+
assert result.labels == ([['a', 'b']], [['p', 'q']])
|
|
117
|
+
assert np.allclose(result.data, [
|
|
118
|
+
[0.2*0.3 + 0.8*0.9, 0.2*0.7 + 0.8*0.1], # a -> p, q
|
|
119
|
+
[0.6*0.3 + 0.4*0.9, 0.6*0.7 + 0.4*0.1], # b -> p, q
|
|
120
|
+
])
|
|
121
|
+
```
|
|
122
|
+
|
|
123
|
+
### Labeled Tensor Product
|
|
124
|
+
|
|
125
|
+
```python
|
|
126
|
+
# P(X) where X={a,b}
|
|
127
|
+
tensor1 = FXTensor(
|
|
128
|
+
[[], [['a', 'b']]],
|
|
129
|
+
data=np.array([0.3, 0.7])
|
|
130
|
+
)
|
|
131
|
+
|
|
132
|
+
# P(Y) where Y={x,y,z}
|
|
133
|
+
tensor2 = FXTensor(
|
|
134
|
+
[[], [['x', 'y', 'z']]],
|
|
135
|
+
data=np.array([0.2, 0.3, 0.5])
|
|
136
|
+
)
|
|
137
|
+
|
|
138
|
+
# Tensor product: P(X,Y) = P(X) ⊗ P(Y)
|
|
139
|
+
result = tensor1.tensor_product(tensor2)
|
|
140
|
+
assert result.labels == (None, [['a', 'b'], ['x', 'y', 'z']])
|
|
141
|
+
assert np.allclose(result.data, np.outer(
|
|
142
|
+
np.array([0.3, 0.7]),
|
|
143
|
+
np.array([0.2, 0.3, 0.5]),
|
|
144
|
+
))
|
|
145
|
+
```
|
|
146
|
+
|
|
147
|
+
## Simple Example: Weather Forecast (Labeled)
|
|
148
|
+
|
|
149
|
+
Model a weather system with states “Sunny” or “Rainy.”
|
|
150
|
+
|
|
151
|
+
- **State Tensor**: Represents today’s weather probability with labels. If today is certainly sunny, the state is `[1, 0]`.
|
|
152
|
+
|
|
153
|
+
```python
|
|
154
|
+
weather_states = ['Sunny', 'Rainy']
|
|
155
|
+
sunny_today = FXTensor([[], [weather_states]], data=np.array([1, 0]))
|
|
156
|
+
```
|
|
157
|
+
|
|
158
|
+
- **Process Tensor**: Represents a weather forecast as a labeled Markov kernel.
|
|
159
|
+
|
|
160
|
+
```python
|
|
161
|
+
forecast_matrix = np.array([
|
|
162
|
+
[0.8, 0.2], # Sunny -> Sunny: 0.8, Rainy: 0.2
|
|
163
|
+
[0.4, 0.6] # Rainy -> Sunny: 0.4, Rainy: 0.6
|
|
164
|
+
])
|
|
165
|
+
forecast_tensor = FXTensor([[weather_states], [weather_states]], data=forecast_matrix)
|
|
166
|
+
```
|
|
167
|
+
|
|
168
|
+
- **Composition**: Predict tomorrow’s weather by composing today’s state with the forecast.
|
|
169
|
+
|
|
170
|
+
```python
|
|
171
|
+
sunny_tomorrow = sunny_today.composition(forecast_tensor)
|
|
172
|
+
sunny_idx = sunny_tomorrow.get_label_index(0, 'Sunny')
|
|
173
|
+
p_sunny = sunny_tomorrow.data[sunny_idx] # 0.8
|
|
174
|
+
```
|
|
175
|
+
|
|
176
|
+
## Advanced Example: Multidimensional System (Labeled)
|
|
177
|
+
|
|
178
|
+
Model **Season** (Spring, Summer, Other) and **Weather** (Sunny, Rainy) given **Location** (Urban, Rural).
|
|
179
|
+
|
|
180
|
+
`conditionalization` and `jointification` require a **state** (empty domain). `marginalization` also works on a kernel.
|
|
181
|
+
|
|
182
|
+
### Kernel: P(Season, Weather | Location)
|
|
183
|
+
|
|
184
|
+
Profile `[[['Urban', 'Rural']], [['Spring', 'Summer', 'Other'], ['Sunny', 'Rainy']]]`, data shape `(2, 3, 2)`. Each location’s block sums to 1.
|
|
185
|
+
|
|
186
|
+
```python
|
|
187
|
+
location_labels = ['Urban', 'Rural']
|
|
188
|
+
season_labels = ['Spring', 'Summer', 'Other']
|
|
189
|
+
weather_labels = ['Sunny', 'Rainy']
|
|
190
|
+
process_data = np.array([
|
|
191
|
+
[[0.2, 0.1], [0.3, 0.1], [0.2, 0.1]], # Urban
|
|
192
|
+
[[0.1, 0.2], [0.2, 0.2], [0.1, 0.2]], # Rural
|
|
193
|
+
])
|
|
194
|
+
process_tensor = FXTensor(
|
|
195
|
+
[[location_labels], [season_labels, weather_labels]],
|
|
196
|
+
data=process_data,
|
|
197
|
+
)
|
|
198
|
+
|
|
199
|
+
# P(Season | Location) by summing out Weather
|
|
200
|
+
season_tensor = process_tensor.marginalization(start_B=2)
|
|
201
|
+
assert season_tensor.labels == ([['Urban', 'Rural']], [['Spring', 'Summer', 'Other']])
|
|
202
|
+
assert np.allclose(season_tensor.data, [
|
|
203
|
+
[0.3, 0.4, 0.3],
|
|
204
|
+
[0.3, 0.4, 0.3],
|
|
205
|
+
])
|
|
206
|
+
```
|
|
207
|
+
|
|
208
|
+
### Joint state: P(Location, Season, Weather)
|
|
209
|
+
|
|
210
|
+
A state has an empty domain. Split the last axis with `conditionalization(3)` to get `P(Weather | Location, Season)`.
|
|
211
|
+
|
|
212
|
+
```python
|
|
213
|
+
joint_data = np.array([
|
|
214
|
+
[[0.08, 0.04], [0.12, 0.04], [0.08, 0.04]], # Urban, total 0.4
|
|
215
|
+
[[0.06, 0.12], [0.12, 0.12], [0.06, 0.12]], # Rural, total 0.6
|
|
216
|
+
])
|
|
217
|
+
joint = FXTensor(
|
|
218
|
+
[[], [location_labels, season_labels, weather_labels]],
|
|
219
|
+
data=joint_data,
|
|
220
|
+
)
|
|
221
|
+
|
|
222
|
+
cond_tensor = joint.conditionalization(concat_start_index=3)
|
|
223
|
+
assert cond_tensor.labels == (
|
|
224
|
+
[['Urban', 'Rural'], ['Spring', 'Summer', 'Other']],
|
|
225
|
+
[['Sunny', 'Rainy']],
|
|
226
|
+
)
|
|
227
|
+
assert cond_tensor.is_markov()
|
|
228
|
+
assert np.allclose(cond_tensor.data, [
|
|
229
|
+
[[2/3, 1/3], [0.75, 0.25], [2/3, 1/3]],
|
|
230
|
+
[[1/3, 2/3], [0.50, 0.50], [1/3, 2/3]],
|
|
231
|
+
])
|
|
232
|
+
```
|
|
233
|
+
|
|
234
|
+
### Jointification of two states
|
|
235
|
+
|
|
236
|
+
Both arguments must be states. Empty-domain labels appear as `None`.
|
|
237
|
+
|
|
238
|
+
```python
|
|
239
|
+
location_state = FXTensor([[], [location_labels]], data=np.array([0.6, 0.4]))
|
|
240
|
+
traffic_labels = ['Low', 'High']
|
|
241
|
+
traffic_state = FXTensor([[], [traffic_labels]], data=np.array([0.7, 0.3]))
|
|
242
|
+
joint_state = location_state.jointification(traffic_state)
|
|
243
|
+
assert joint_state.labels == (None, [['Urban', 'Rural'], ['Low', 'High']])
|
|
244
|
+
assert np.allclose(joint_state.data, [
|
|
245
|
+
[0.42, 0.18],
|
|
246
|
+
[0.28, 0.12],
|
|
247
|
+
])
|
|
248
|
+
```
|
|
249
|
+
|
|
250
|
+
### Key Method Applications
|
|
251
|
+
|
|
252
|
+
#### `from_json(json_data)`
|
|
253
|
+
|
|
254
|
+
Creates a tensor from JSON data, loading profile and data to instantiate an FXTensor.
|
|
255
|
+
|
|
256
|
+
```python
|
|
257
|
+
json_data = {
|
|
258
|
+
"profile": [[['a', 'b']], [['x', 'y']]],
|
|
259
|
+
"data": [[0.2, 0.8], [0.6, 0.4]]
|
|
260
|
+
}
|
|
261
|
+
tensor = FXTensor.from_json(json_data)
|
|
262
|
+
assert tensor.labels == ([['a', 'b']], [['x', 'y']])
|
|
263
|
+
```
|
|
264
|
+
|
|
265
|
+
#### `from_strands(profile, strands)`
|
|
266
|
+
|
|
267
|
+
Creates a tensor from strands (sparse string representations of non-zero elements).
|
|
268
|
+
|
|
269
|
+
```python
|
|
270
|
+
profile = [[['a', 'b']], [['x', 'y', 'z']]]
|
|
271
|
+
strands = {
|
|
272
|
+
"[[['a']], [['x']]]": 0.1,
|
|
273
|
+
"[[['a']], [['y']]]": 0.2,
|
|
274
|
+
"[[['a']], [['z']]]": 0.7,
|
|
275
|
+
"[[['b']], [['x']]]": 0.3,
|
|
276
|
+
"[[['b']], [['y']]]": 0.3,
|
|
277
|
+
"[[['b']], [['z']]]": 0.4
|
|
278
|
+
}
|
|
279
|
+
tensor = FXTensor.from_strands(profile, strands)
|
|
280
|
+
assert tensor.labels == ([['a', 'b']], [['x', 'y', 'z']])
|
|
281
|
+
```
|
|
282
|
+
|
|
283
|
+
#### `identity_tensor(list_x)`
|
|
284
|
+
|
|
285
|
+
Creates an identity tensor for the given dimensions, supporting labeled or numeric inputs.
|
|
286
|
+
|
|
287
|
+
```python
|
|
288
|
+
labels = [['a', 'b']]
|
|
289
|
+
id_tensor = FXTensor.identity_tensor(labels)
|
|
290
|
+
assert id_tensor.labels == ([['a', 'b']], [['a', 'b']])
|
|
291
|
+
```
|
|
292
|
+
|
|
293
|
+
#### `copy_tensor(list_x, n=2)`
|
|
294
|
+
|
|
295
|
+
Creates a diagonal copy morphism `X → X^{⊗ n}`. `n=0` is discard, `n=1` is identity.
|
|
296
|
+
|
|
297
|
+
```python
|
|
298
|
+
copy = FXTensor.copy_tensor([2])
|
|
299
|
+
assert copy.profile == [[2], [2, 2]]
|
|
300
|
+
assert np.array_equal(copy.data, [
|
|
301
|
+
[[1, 0],
|
|
302
|
+
[0, 0]],
|
|
303
|
+
[[0, 0],
|
|
304
|
+
[0, 1]],
|
|
305
|
+
])
|
|
306
|
+
|
|
307
|
+
labeled_copy = FXTensor.copy_tensor([['a', 'b']])
|
|
308
|
+
assert labeled_copy.labels == ([['a', 'b']], [['a', 'b'], ['a', 'b']])
|
|
309
|
+
```
|
|
310
|
+
|
|
311
|
+
#### `unit_tensor(dims)`
|
|
312
|
+
|
|
313
|
+
Creates a unit state tensor (all-ones vector) for the given dimensions.
|
|
314
|
+
|
|
315
|
+
```python
|
|
316
|
+
dims = [2, 3]
|
|
317
|
+
unit = FXTensor.unit_tensor(dims)
|
|
318
|
+
assert unit.profile == [[], dims]
|
|
319
|
+
assert np.all(unit.data == 1)
|
|
320
|
+
```
|
|
321
|
+
|
|
322
|
+
#### `delta_tensor(dims)`
|
|
323
|
+
|
|
324
|
+
Creates a delta tensor (identity matrix) for the given dimensions, used for copying.
|
|
325
|
+
|
|
326
|
+
```python
|
|
327
|
+
dims = [2]
|
|
328
|
+
delta = FXTensor.delta_tensor(dims)
|
|
329
|
+
assert delta.profile == [[dims], [dims]]
|
|
330
|
+
```
|
|
331
|
+
|
|
332
|
+
## DisCoPy integration
|
|
333
|
+
|
|
334
|
+
`fxtensor-salmon` can convert labeled tensors to [DisCoPy](https://discopy.org) `Tensor` / `Box` values and interpret `discopy.markov` diagrams (Copy, Discard, Swap, Id) as `FXTensor` morphisms. This extra requires Python 3.10+ and is installed with:
|
|
335
|
+
|
|
336
|
+
```shell
|
|
337
|
+
pip install fxtensor-salmon[discopy]
|
|
338
|
+
```
|
|
339
|
+
|
|
340
|
+
Each profile factor is one wire. Unlabeled tensors map to `Dim`; labels are stored on Markov type names and restored when converting a `Box` back.
|
|
341
|
+
|
|
342
|
+
```python
|
|
343
|
+
from discopy.markov import Copy, Discard, Id, Swap, Ty
|
|
344
|
+
from fxtensor_salmon import FXTensor
|
|
345
|
+
from fxtensor_salmon.discopy import FXTensorFunctor, from_tensor, to_box, to_tensor
|
|
346
|
+
|
|
347
|
+
kernel = FXTensor(
|
|
348
|
+
[[2], [2]],
|
|
349
|
+
data=np.array([[0.8, 0.2], [0.4, 0.6]]),
|
|
350
|
+
)
|
|
351
|
+
assert from_tensor(to_tensor(kernel)) == kernel
|
|
352
|
+
|
|
353
|
+
weather = ['Sunny', 'Rainy']
|
|
354
|
+
forecast = FXTensor([[weather], [weather]], data=np.array([[0.8, 0.2], [0.4, 0.6]]))
|
|
355
|
+
box = to_box(forecast, name="forecast")
|
|
356
|
+
|
|
357
|
+
x, y = Ty('x'), Ty('y')
|
|
358
|
+
F = FXTensorFunctor({x: 2, y: 3}, {})
|
|
359
|
+
assert F(Copy(x)) == FXTensor.copy_tensor([2])
|
|
360
|
+
assert F(Discard(x)) == FXTensor.exclamation([2])
|
|
361
|
+
assert F(Swap(x, y)) == FXTensor.swap([2], [3])
|
|
362
|
+
assert F(Id(x)) == FXTensor.identity_tensor([2])
|
|
363
|
+
```
|
|
364
|
+
|
|
365
|
+
## Theoretical Background: Relation to Markov Categories
|
|
366
|
+
|
|
367
|
+
The `fxtensor-salmon` library is designed based on the **Markov Category**, a framework for categorical probability theory.
|
|
368
|
+
|
|
369
|
+
### Markov Category Basics
|
|
370
|
+
|
|
371
|
+
- **Objects**: State spaces, represented in `FXTensor` as `domain` or `codomain` (e.g., `[['Urban', 'Rural']]` or `[[2]]`).
|
|
372
|
+
- **Morphisms**: Markov kernels (probabilistic transitions), represented by `FXTensor` instances with profile and data.
|
|
373
|
+
|
|
374
|
+
### Markov Category Operations
|
|
375
|
+
|
|
376
|
+
| Method | Role | When to use |
|
|
377
|
+
|---|---|---|
|
|
378
|
+
| `composition` | Sequential composition `A→B` then `B→C` | Wire processes in series, or apply a kernel to a state |
|
|
379
|
+
| `tensor_product` | Monoidal product | Place independent systems side by side |
|
|
380
|
+
| `marginalization` | Discard a suffix of the outputs | Sum out axes you no longer need |
|
|
381
|
+
| `conditionalization` | Joint state → kernel | Split a joint distribution into a conditional (states only) |
|
|
382
|
+
| `partial_composition` | Compose only some output wires | Keep a prefix of the outputs and feed the suffix into another kernel |
|
|
383
|
+
| `jointification` | Joint of two states | Combine two independent states (states only) |
|
|
384
|
+
| `conditional` | Kernel `A → X ⊗ Y` → `A ⊗ X → Y` | Conditionalize a kernel (generalizes `conditionalization`) |
|
|
385
|
+
| `bayesian_inversion` | `f: X → Y` and prior `I → X` → `f†: Y → X` | Bayesian update / posterior kernel |
|
|
386
|
+
| `exclamation` | Discard morphism `X → I` | Build an all-ones discarding tensor |
|
|
387
|
+
| `copy_tensor` | Copy morphism `X → X^{⊗ n}` | Deterministic copy / diagonal (`n=0` is discard) |
|
|
388
|
+
| `delta_tensor` | Identity (alias of `identity_tensor`) | Build an identity kernel |
|
|
389
|
+
|
|
390
|
+
#### `composition` — sequential wiring
|
|
391
|
+
|
|
392
|
+
Use when the codomain of `f` matches the domain of `g`. Same numbers as the labeled example above: `P(Z|X) = P(Y|X) ; P(Z|Y)`.
|
|
393
|
+
|
|
394
|
+
```python
|
|
395
|
+
result = tensor1.composition(tensor2)
|
|
396
|
+
assert np.allclose(result.data, [[0.78, 0.22], [0.54, 0.46]])
|
|
397
|
+
```
|
|
398
|
+
|
|
399
|
+
#### `tensor_product` — independent systems in parallel
|
|
400
|
+
|
|
401
|
+
Use to put two morphisms (or two states) next to each other without coupling.
|
|
402
|
+
|
|
403
|
+
```python
|
|
404
|
+
px = FXTensor([[], [['a', 'b']]], data=np.array([0.3, 0.7]))
|
|
405
|
+
py = FXTensor([[], [['x', 'y', 'z']]], data=np.array([0.2, 0.3, 0.5]))
|
|
406
|
+
pxy = px.tensor_product(py)
|
|
407
|
+
assert pxy.labels == (None, [['a', 'b'], ['x', 'y', 'z']])
|
|
408
|
+
assert np.allclose(pxy.data, [[0.06, 0.09, 0.15], [0.14, 0.21, 0.35]])
|
|
409
|
+
```
|
|
410
|
+
|
|
411
|
+
#### `marginalization` — drop a suffix of the outputs
|
|
412
|
+
|
|
413
|
+
Use `start_B` (1-based) as the first codomain axis to sum out. A state with profile `[[], [2, 3]]` and `start_B=2` keeps the first axis.
|
|
414
|
+
|
|
415
|
+
```python
|
|
416
|
+
state = FXTensor([[], [2, 3]], data=np.array([
|
|
417
|
+
[0.1, 0.2, 0.3],
|
|
418
|
+
[0.15, 0.05, 0.2],
|
|
419
|
+
]))
|
|
420
|
+
marginal = state.marginalization(2)
|
|
421
|
+
assert marginal.profile == [[], [2]]
|
|
422
|
+
assert np.allclose(marginal.data, [0.6, 0.4])
|
|
423
|
+
```
|
|
424
|
+
|
|
425
|
+
#### `conditionalization` — joint state to a kernel
|
|
426
|
+
|
|
427
|
+
Use only on a state. `concat_start_index` (1-based) is the first axis of the new codomain. A zero slice stays zero.
|
|
428
|
+
|
|
429
|
+
```python
|
|
430
|
+
joint_state = FXTensor([[], [2, 2]], data=np.array([[0.1, 0.2], [0.0, 0.0]]))
|
|
431
|
+
kernel = joint_state.conditionalization(2)
|
|
432
|
+
assert kernel.profile == [[2], [2]]
|
|
433
|
+
assert kernel.is_markov()
|
|
434
|
+
assert np.allclose(kernel.data, [[1/3, 2/3], [0.0, 0.0]])
|
|
435
|
+
```
|
|
436
|
+
|
|
437
|
+
#### `partial_composition` — compose only the trailing outputs
|
|
438
|
+
|
|
439
|
+
For `f: A → B ⊗ C` and `g: C → D`, `f.partial_composition(g, 2)` keeps `B` and composes on `C`, giving `A → B ⊗ D`.
|
|
440
|
+
|
|
441
|
+
```python
|
|
442
|
+
f = FXTensor([[2], [2, 2]], data=np.array([
|
|
443
|
+
[[1.0, 0.0], [0.0, 1.0]],
|
|
444
|
+
[[0.0, 1.0], [1.0, 0.0]],
|
|
445
|
+
]))
|
|
446
|
+
g = FXTensor([[2], [2]], data=np.array([
|
|
447
|
+
[0.2, 0.8],
|
|
448
|
+
[0.6, 0.4],
|
|
449
|
+
]))
|
|
450
|
+
partial = f.partial_composition(g, 2)
|
|
451
|
+
assert partial.profile == [[2], [2, 2]]
|
|
452
|
+
assert np.allclose(partial.data, [
|
|
453
|
+
[[0.2, 0.8], [0.6, 0.4]],
|
|
454
|
+
[[0.6, 0.4], [0.2, 0.8]],
|
|
455
|
+
])
|
|
456
|
+
```
|
|
457
|
+
|
|
458
|
+
`concat_start_index=1` composes on the whole codomain (the case covered by the tests).
|
|
459
|
+
|
|
460
|
+
#### `jointification` — two states into one joint
|
|
461
|
+
|
|
462
|
+
Same numbers as the tensor product of states; both domains must be empty.
|
|
463
|
+
|
|
464
|
+
```python
|
|
465
|
+
px = FXTensor([[], [['a', 'b']]], data=np.array([0.3, 0.7]))
|
|
466
|
+
py = FXTensor([[], [['x', 'y', 'z']]], data=np.array([0.2, 0.3, 0.5]))
|
|
467
|
+
joint_xy = px.jointification(py)
|
|
468
|
+
assert joint_xy.labels == (None, [['a', 'b'], ['x', 'y', 'z']])
|
|
469
|
+
assert np.allclose(joint_xy.data, [[0.06, 0.09, 0.15], [0.14, 0.21, 0.35]])
|
|
470
|
+
```
|
|
471
|
+
|
|
472
|
+
#### `bayesian_inversion` — posterior kernel
|
|
473
|
+
|
|
474
|
+
For a prior `p: I → X` and a kernel `f: X → Y`, `f.bayesian_inversion(p)` returns `f†: Y → X` with `f†(x|y) = p(x) f(y|x) / Σ p(x') f(y|x')` (Cho & Jacobs). It satisfies `p ; copy ; (id ⊗ f) = p ; f ; copy ; (f† ⊗ id)`. Outputs with zero evidence stay zero.
|
|
475
|
+
|
|
476
|
+
```python
|
|
477
|
+
health = ['Sick', 'Healthy']
|
|
478
|
+
result = ['Positive', 'Negative']
|
|
479
|
+
prior = FXTensor([[], [health]], data=np.array([0.01, 0.99]))
|
|
480
|
+
test = FXTensor([[health], [result]], data=np.array([[0.9, 0.1], [0.05, 0.95]]))
|
|
481
|
+
posterior = test.bayesian_inversion(prior)
|
|
482
|
+
assert posterior.labels == ([result], [health])
|
|
483
|
+
assert np.isclose(posterior.data[0, 0], 2 / 13) # P(Sick | Positive)
|
|
484
|
+
```
|
|
485
|
+
|
|
486
|
+
#### `conditional` — conditionalize a kernel
|
|
487
|
+
|
|
488
|
+
`f.conditional(k)` turns `f: A → X ⊗ Y` into `A ⊗ X → Y`, where `k` (1-based) is the first codomain axis of `Y`. On a state it equals `conditionalization(k)`.
|
|
489
|
+
|
|
490
|
+
```python
|
|
491
|
+
f = FXTensor([[['a']], [['x0', 'x1'], ['y0', 'y1']]], data=np.array([[[0.1, 0.3], [0.2, 0.4]]]))
|
|
492
|
+
c = f.conditional(2)
|
|
493
|
+
assert c.labels == ([['a'], ['x0', 'x1']], [['y0', 'y1']])
|
|
494
|
+
assert np.allclose(c.data, [[[0.25, 0.75], [1/3, 2/3]]])
|
|
495
|
+
```
|
|
496
|
+
|
|
497
|
+
### Probabilistic Properties
|
|
498
|
+
|
|
499
|
+
- `is_markov()`: Verifies if the tensor satisfies the normalization condition (sum of outputs equals 1 or 0). States (empty domain) always return `False`; check `np.isclose(state.data.sum(), 1)` for a normalized state.
|
|
500
|
+
- `is_deterministic()`: True if every codomain slice is a point mass (one-hot), i.e. `f ; copy = copy ; (f ⊗ f)`. Zero slices are not deterministic.
|
|
501
|
+
- Labeled tensors enable intuitive interpretation via `get_label_index` and `get_index_label`.
|
|
502
|
+
|
|
503
|
+
## Testing
|
|
504
|
+
|
|
505
|
+
Tests are implemented in `tests/test_fxtensor.py` using `pytest`.
|
|
506
|
+
|
|
507
|
+
```bash
|
|
508
|
+
pytest
|
|
509
|
+
```
|
|
510
|
+
|
|
511
|
+
## References
|
|
512
|
+
- [1] [檜山正幸のキマイラ飼育記 (はてなBlog), マルコフ圏 A First Look -- 圏論的確率論の最良の定式化](https://m-hiyama.hatenablog.com/entry/2020/06/09/154044)
|
|
513
|
+
- [2] [檜山正幸のキマイラ飼育記 (はてなBlog), マルコフ圏におけるテンソル計算の手順とコツ](https://m-hiyama.hatenablog.com/entry/2021/04/05/153325)
|
|
514
|
+
- [3] [K. Cho and B. Jacobs, Disintegration and Bayesian Inversion via String Diagrams (arXiv:1709.00322)](https://arxiv.org/abs/1709.00322)
|
|
515
|
+
- [4] [T. Fritz, A synthetic approach to Markov kernels, conditional independence and theorems on sufficient statistics (arXiv:1908.07021)](https://arxiv.org/abs/1908.07021)
|