mplusa 0.0.1__tar.gz → 0.0.3__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.
- {mplusa-0.0.1/src/mplusa.egg-info → mplusa-0.0.3}/PKG-INFO +22 -8
- {mplusa-0.0.1 → mplusa-0.0.3}/README.md +17 -5
- {mplusa-0.0.1 → mplusa-0.0.3}/pyproject.toml +3 -2
- mplusa-0.0.3/src/mplusa/maxplus.py +200 -0
- mplusa-0.0.3/src/mplusa/minplus.py +200 -0
- mplusa-0.0.3/src/mplusa/utils.py +5 -0
- {mplusa-0.0.1 → mplusa-0.0.3/src/mplusa.egg-info}/PKG-INFO +22 -8
- {mplusa-0.0.1 → mplusa-0.0.3}/src/mplusa.egg-info/SOURCES.txt +1 -0
- mplusa-0.0.1/src/mplusa/maxplus.py +0 -161
- mplusa-0.0.1/src/mplusa/minplus.py +0 -161
- {mplusa-0.0.1 → mplusa-0.0.3}/LICENSE +0 -0
- {mplusa-0.0.1 → mplusa-0.0.3}/setup.cfg +0 -0
- {mplusa-0.0.1 → mplusa-0.0.3}/src/mplusa/__init__.py +0 -0
- {mplusa-0.0.1 → mplusa-0.0.3}/src/mplusa.egg-info/dependency_links.txt +0 -0
- {mplusa-0.0.1 → mplusa-0.0.3}/src/mplusa.egg-info/requires.txt +0 -0
- {mplusa-0.0.1 → mplusa-0.0.3}/src/mplusa.egg-info/top_level.txt +0 -0
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
Metadata-Version: 2.
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
2
|
Name: mplusa
|
|
3
|
-
Version: 0.0.
|
|
3
|
+
Version: 0.0.3
|
|
4
4
|
Summary: A library for calculations in tropical and arctic semirings.
|
|
5
|
-
Author-email:
|
|
5
|
+
Author-email: Maksymilian Wiekiera <maksymilian3563@gmail.com>
|
|
6
6
|
License: Copyright (c) 2025 Maksymilian Wiekiera
|
|
7
7
|
|
|
8
8
|
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
@@ -23,46 +23,60 @@ License: Copyright (c) 2025 Maksymilian Wiekiera
|
|
|
23
23
|
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
24
24
|
SOFTWARE.
|
|
25
25
|
Project-URL: homepage, https://github.com/Hadelekw/mplusa
|
|
26
|
+
Project-URL: documentation, https://hadelekw.github.io/mplusa-docs.html
|
|
26
27
|
Classifier: Programming Language :: Python :: 3
|
|
27
28
|
Classifier: Operating System :: OS Independent
|
|
28
29
|
Requires-Python: >=3.11
|
|
29
30
|
Description-Content-Type: text/markdown
|
|
30
31
|
License-File: LICENSE
|
|
31
32
|
Requires-Dist: numpy>=2.2.3
|
|
33
|
+
Dynamic: license-file
|
|
32
34
|
|
|
33
35
|
# MPlusA
|
|
34
36
|
---
|
|
35
|
-
**MPlusA** is a small Python library for tropical algebra (also known as
|
|
37
|
+
**MPlusA** is a small Python library for tropical algebra (also known as (min, +) and (max, +) algebra). It provides the definitions of basic operations on numbers and NumPy arrays, as well as a basic implementation of tropical polynomials.
|
|
36
38
|
|
|
37
39
|
Any improvements or fixes are always welcome.
|
|
38
40
|
|
|
39
41
|
## How to use
|
|
40
|
-
After having installed the library one can import one of the two modules the package consists of (`minplus` and `maxplus`) and use the full array of its capabilities. The functions are essentially the same between the modules.
|
|
42
|
+
After having installed the library one can import one of the two modules the package consists of (`minplus` and `maxplus`) and use the full array of its capabilities. The functions are essentially the same between the modules.
|
|
41
43
|
|
|
42
44
|
**`add(*args) -> Real`**
|
|
43
45
|
Tropical addition. Essentially an alias for Python's `min` function.
|
|
46
|
+
|
|
44
47
|
**`mult(*args) -> Real`**
|
|
45
48
|
Tropical multiplication. Essentially an alias for Python's `sum` function.
|
|
49
|
+
|
|
46
50
|
**`add_matrices(A : np.ndarray, B : np.ndarray) -> np.ndarray`**
|
|
47
51
|
Tropical addition of NumPy arrays. The summed matrices have to be of the same shape.
|
|
52
|
+
|
|
48
53
|
**`mult_matrices(A : np.ndarray, B : np.ndarray) -> np.ndarray`**
|
|
49
54
|
Tropical multiplication of NumPy arrays. The multiplied matrices have to be of sizes MxN and NxP and their order matters. The result is of shape MxP.
|
|
55
|
+
|
|
50
56
|
**`modulo(a : Real, t : int) -> Real`**
|
|
51
57
|
Tropical modulo operator. It can be understood as the difference between the number $a$ and $t^k$ where $k$ is the largest integer that satisfies $a \geq t^k$.
|
|
58
|
+
|
|
52
59
|
**`modulo_matrices(A : np.ndarray, b : np.ndarray) -> np.ndarray`**
|
|
53
60
|
Tropical modulo operator for NumPy arrays. The input matrices should be of size MxN and Mx1. The result is an MxN matrix.
|
|
61
|
+
|
|
54
62
|
**`power(a : real, k : int) -> Real`**
|
|
55
63
|
Tropical power operator. Applies the multiplication k times.
|
|
64
|
+
|
|
56
65
|
**`power_matrix(A : np.ndarray, k : int) -> np.ndarray`**
|
|
57
66
|
Tropical power operator for NumPy arrays. It multiplies the matrix k times.
|
|
67
|
+
|
|
58
68
|
**`unit_matrix(width : int, height : int) -> np.ndarray`**
|
|
59
69
|
Creates a tropical unit matrix of given width and height.
|
|
70
|
+
|
|
60
71
|
**`star(A : np.ndarray) -> np.ndarray`**
|
|
61
|
-
Definition of
|
|
72
|
+
Definition of an unary operator of unique to tropical algebra, usually denoted as $\mathbf{A}^*$. It returns the value to which an infinite recursive sum of matrices converges. The input matrix has to be square and the series created in the process of calculating the value needs to be convergent.
|
|
73
|
+
|
|
62
74
|
**`Polynomial(*coefficients)`**
|
|
63
|
-
This is a class that implements basic single-variable tropical polynomials. Calling an object of this class allows to take a value the polynomial takes at a given point
|
|
75
|
+
This is a class that implements basic single-variable tropical polynomials. Calling an object of this class allows to take a value the polynomial takes at a given point.
|
|
76
|
+
|
|
77
|
+
For the full list of capabilities, refer to the [documentation](https://hadelekw.github.io/mplusa-docs.html)
|
|
64
78
|
|
|
65
|
-
|
|
79
|
+
## Example code
|
|
66
80
|
```
|
|
67
81
|
import numpy as np
|
|
68
82
|
from mplusa import minplus
|
|
@@ -1,36 +1,48 @@
|
|
|
1
1
|
# MPlusA
|
|
2
2
|
---
|
|
3
|
-
**MPlusA** is a small Python library for tropical algebra (also known as
|
|
3
|
+
**MPlusA** is a small Python library for tropical algebra (also known as (min, +) and (max, +) algebra). It provides the definitions of basic operations on numbers and NumPy arrays, as well as a basic implementation of tropical polynomials.
|
|
4
4
|
|
|
5
5
|
Any improvements or fixes are always welcome.
|
|
6
6
|
|
|
7
7
|
## How to use
|
|
8
|
-
After having installed the library one can import one of the two modules the package consists of (`minplus` and `maxplus`) and use the full array of its capabilities. The functions are essentially the same between the modules.
|
|
8
|
+
After having installed the library one can import one of the two modules the package consists of (`minplus` and `maxplus`) and use the full array of its capabilities. The functions are essentially the same between the modules.
|
|
9
9
|
|
|
10
10
|
**`add(*args) -> Real`**
|
|
11
11
|
Tropical addition. Essentially an alias for Python's `min` function.
|
|
12
|
+
|
|
12
13
|
**`mult(*args) -> Real`**
|
|
13
14
|
Tropical multiplication. Essentially an alias for Python's `sum` function.
|
|
15
|
+
|
|
14
16
|
**`add_matrices(A : np.ndarray, B : np.ndarray) -> np.ndarray`**
|
|
15
17
|
Tropical addition of NumPy arrays. The summed matrices have to be of the same shape.
|
|
18
|
+
|
|
16
19
|
**`mult_matrices(A : np.ndarray, B : np.ndarray) -> np.ndarray`**
|
|
17
20
|
Tropical multiplication of NumPy arrays. The multiplied matrices have to be of sizes MxN and NxP and their order matters. The result is of shape MxP.
|
|
21
|
+
|
|
18
22
|
**`modulo(a : Real, t : int) -> Real`**
|
|
19
23
|
Tropical modulo operator. It can be understood as the difference between the number $a$ and $t^k$ where $k$ is the largest integer that satisfies $a \geq t^k$.
|
|
24
|
+
|
|
20
25
|
**`modulo_matrices(A : np.ndarray, b : np.ndarray) -> np.ndarray`**
|
|
21
26
|
Tropical modulo operator for NumPy arrays. The input matrices should be of size MxN and Mx1. The result is an MxN matrix.
|
|
27
|
+
|
|
22
28
|
**`power(a : real, k : int) -> Real`**
|
|
23
29
|
Tropical power operator. Applies the multiplication k times.
|
|
30
|
+
|
|
24
31
|
**`power_matrix(A : np.ndarray, k : int) -> np.ndarray`**
|
|
25
32
|
Tropical power operator for NumPy arrays. It multiplies the matrix k times.
|
|
33
|
+
|
|
26
34
|
**`unit_matrix(width : int, height : int) -> np.ndarray`**
|
|
27
35
|
Creates a tropical unit matrix of given width and height.
|
|
36
|
+
|
|
28
37
|
**`star(A : np.ndarray) -> np.ndarray`**
|
|
29
|
-
Definition of
|
|
38
|
+
Definition of an unary operator of unique to tropical algebra, usually denoted as $\mathbf{A}^*$. It returns the value to which an infinite recursive sum of matrices converges. The input matrix has to be square and the series created in the process of calculating the value needs to be convergent.
|
|
39
|
+
|
|
30
40
|
**`Polynomial(*coefficients)`**
|
|
31
|
-
This is a class that implements basic single-variable tropical polynomials. Calling an object of this class allows to take a value the polynomial takes at a given point
|
|
41
|
+
This is a class that implements basic single-variable tropical polynomials. Calling an object of this class allows to take a value the polynomial takes at a given point.
|
|
42
|
+
|
|
43
|
+
For the full list of capabilities, refer to the [documentation](https://hadelekw.github.io/mplusa-docs.html)
|
|
32
44
|
|
|
33
|
-
|
|
45
|
+
## Example code
|
|
34
46
|
```
|
|
35
47
|
import numpy as np
|
|
36
48
|
from mplusa import minplus
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
[project]
|
|
2
2
|
name = "mplusa"
|
|
3
|
-
version = "0.0.
|
|
3
|
+
version = "0.0.3"
|
|
4
4
|
authors = [
|
|
5
|
-
{name="Maksymilian
|
|
5
|
+
{name="Maksymilian Wiekiera", email="maksymilian3563@gmail.com"}
|
|
6
6
|
]
|
|
7
7
|
description = "A library for calculations in tropical and arctic semirings."
|
|
8
8
|
readme = "README.md"
|
|
@@ -18,3 +18,4 @@ license = {file="LICENSE"}
|
|
|
18
18
|
|
|
19
19
|
[project.urls]
|
|
20
20
|
homepage = "https://github.com/Hadelekw/mplusa"
|
|
21
|
+
documentation = "https://hadelekw.github.io/mplusa-docs.html"
|
|
@@ -0,0 +1,200 @@
|
|
|
1
|
+
import numpy as np
|
|
2
|
+
|
|
3
|
+
import math
|
|
4
|
+
import string
|
|
5
|
+
|
|
6
|
+
from . import utils
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def add(*args) -> float:
|
|
10
|
+
if math.inf in args:
|
|
11
|
+
raise ValueError('Value out of domain.')
|
|
12
|
+
return max(args)
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def mult(*args) -> float:
|
|
16
|
+
if math.inf in args:
|
|
17
|
+
raise ValueError('Value out of domain.')
|
|
18
|
+
return sum(args) if -math.inf not in args else -math.inf
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def power(a : float,
|
|
22
|
+
k : int) -> float:
|
|
23
|
+
return mult(*[a for _ in range(k)])
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def modulo(a : float,
|
|
27
|
+
t : int) -> float:
|
|
28
|
+
if a < 0 or t < 0:
|
|
29
|
+
raise ValueError('The modulo operator is only defined for positive numbers.')
|
|
30
|
+
if a == -math.inf:
|
|
31
|
+
return -math.inf
|
|
32
|
+
if a == 0:
|
|
33
|
+
return 0
|
|
34
|
+
if t == -math.inf or t == 0:
|
|
35
|
+
return a
|
|
36
|
+
return a - (a // t) * t
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def add_matrices(A : np.ndarray,
|
|
40
|
+
B : np.ndarray) -> np.ndarray:
|
|
41
|
+
if A.shape != B.shape:
|
|
42
|
+
raise ValueError('Given matrices have different shapes.')
|
|
43
|
+
result = np.copy(A)
|
|
44
|
+
shape = A.shape
|
|
45
|
+
for i in range(shape[0]):
|
|
46
|
+
for j in range(shape[1]):
|
|
47
|
+
result[i, j] = add(result[i, j], B[i, j])
|
|
48
|
+
return result
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def mult_matrices(A : np.ndarray,
|
|
52
|
+
B : np.ndarray) -> np.ndarray:
|
|
53
|
+
if A.shape[1] != B.shape[0]:
|
|
54
|
+
raise ValueError('Given matrices are not of MxN and NxP shapes.')
|
|
55
|
+
result = np.zeros((A.shape[0], B.shape[1]))
|
|
56
|
+
for i in range(A.shape[0]):
|
|
57
|
+
for j in range(B.shape[1]):
|
|
58
|
+
result[i, j] = add(*[mult(A[i, k], B[k, j]) for k in range(A.shape[1])])
|
|
59
|
+
return result
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def power_matrix(A : np.ndarray,
|
|
63
|
+
k : int) -> np.ndarray:
|
|
64
|
+
if np.any(np.diagonal(A) != 0):
|
|
65
|
+
raise ValueError('Matrix contains non-zero values on the diagonal.')
|
|
66
|
+
if k == 0:
|
|
67
|
+
result = unit_matrix(A.shape[0], A.shape[1])
|
|
68
|
+
else:
|
|
69
|
+
result = A.copy()
|
|
70
|
+
for _ in range(k):
|
|
71
|
+
result = mult_matrices(A, result)
|
|
72
|
+
return result
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def modulo_matrices(A : np.ndarray,
|
|
76
|
+
b : np.ndarray) -> np.ndarray:
|
|
77
|
+
if b.shape[1] != 1:
|
|
78
|
+
raise ValueError('Given matrix b is not a vertical vector of shape Mx1')
|
|
79
|
+
if A.shape[0] != b.shape[0]:
|
|
80
|
+
raise ValueError('Given matrix b does not have an Mx1 shape against the MxN matrix A.')
|
|
81
|
+
if np.any(A < 0) or np.any(b < 0):
|
|
82
|
+
raise ValueError('Given matrices contain negative values.')
|
|
83
|
+
result = np.zeros(A.shape)
|
|
84
|
+
for i in range(A.shape[0]):
|
|
85
|
+
for j in range(A.shape[1]):
|
|
86
|
+
result[i, j] = modulo(A[i, j], b[i])
|
|
87
|
+
return result
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def unit_matrix(width : int,
|
|
91
|
+
height : int) -> np.ndarray:
|
|
92
|
+
result = np.eye(width, height)
|
|
93
|
+
result[result == 0] = -math.inf
|
|
94
|
+
result[result == 1] = 0
|
|
95
|
+
return result
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def kleene_star(A : np.ndarray,
|
|
99
|
+
iterations : int = 1000) -> np.ndarray:
|
|
100
|
+
if A.shape[0] != A.shape[1]:
|
|
101
|
+
raise ValueError('Matrix is not square.')
|
|
102
|
+
series = [
|
|
103
|
+
unit_matrix(A.shape[0], A.shape[1]),
|
|
104
|
+
A.copy()
|
|
105
|
+
]
|
|
106
|
+
for _ in range(iterations):
|
|
107
|
+
series.append(add_matrices(series[-1], mult_matrices(series[-1], series[-2])))
|
|
108
|
+
return series[-1]
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
class MultivariatePolynomial:
|
|
112
|
+
""" An implementation of an arctic polynomial with multiple variables. """
|
|
113
|
+
|
|
114
|
+
def __init__(self, coefficients : np.ndarray) -> None:
|
|
115
|
+
self.coefficients = coefficients
|
|
116
|
+
self.dimensions = len(self.coefficients.shape) + 1
|
|
117
|
+
self._symbols = string.ascii_lowercase
|
|
118
|
+
|
|
119
|
+
def __call__(self, *variables : float) -> float:
|
|
120
|
+
if len(variables) != self.dimensions - 1:
|
|
121
|
+
raise ValueError('The amount of variables and coefficients differs.')
|
|
122
|
+
result = [-math.inf]
|
|
123
|
+
for indices, coefficient in np.ndenumerate(self.coefficients):
|
|
124
|
+
powers = []
|
|
125
|
+
for variable_index, i in enumerate(indices):
|
|
126
|
+
powers.append(power(variables[variable_index], i))
|
|
127
|
+
result.append(mult(coefficient, *powers))
|
|
128
|
+
result = add(*result)
|
|
129
|
+
return float(result)
|
|
130
|
+
|
|
131
|
+
def __str__(self) -> str:
|
|
132
|
+
result = ''
|
|
133
|
+
for indices, coefficient in np.ndenumerate(self.coefficients):
|
|
134
|
+
if coefficient.is_integer():
|
|
135
|
+
result += '(' + str(int(coefficient))
|
|
136
|
+
elif coefficient > -math.inf:
|
|
137
|
+
result += '(' + str(coefficient)
|
|
138
|
+
else:
|
|
139
|
+
result += '(-∞'
|
|
140
|
+
for variable_index, i in enumerate(indices):
|
|
141
|
+
if i > 1:
|
|
142
|
+
result += ' * ' + self._symbols[variable_index] + '^' + str(i)
|
|
143
|
+
elif i == 1:
|
|
144
|
+
result += ' * ' + self._symbols[variable_index]
|
|
145
|
+
result += ') + '
|
|
146
|
+
return result[:-3]
|
|
147
|
+
|
|
148
|
+
def get_hyperplanes(self) -> list:
|
|
149
|
+
""" Returns a list of coefficients of a linear equation for every hyperplane building the polynomial. """
|
|
150
|
+
result = []
|
|
151
|
+
for indices, coefficient in np.ndenumerate(self.coefficients):
|
|
152
|
+
if coefficient == -math.inf:
|
|
153
|
+
continue
|
|
154
|
+
hyperplane = [float(coefficient)]
|
|
155
|
+
hyperplane.extend(indices)
|
|
156
|
+
hyperplane.append(1) # The coefficient of the last dimension (e.g. Z in 3D)
|
|
157
|
+
result.append(
|
|
158
|
+
list(
|
|
159
|
+
map(
|
|
160
|
+
lambda x: int(x) if x.is_integer() else float(x),
|
|
161
|
+
hyperplane
|
|
162
|
+
)
|
|
163
|
+
)
|
|
164
|
+
)
|
|
165
|
+
return result
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
class Polynomial(MultivariatePolynomial):
|
|
169
|
+
""" An implementation of a tropical polynomial with a single variable. """
|
|
170
|
+
|
|
171
|
+
def __init__(self, *coefficients) -> None:
|
|
172
|
+
for value in coefficients:
|
|
173
|
+
if not isinstance(value, float|int) or value == math.inf:
|
|
174
|
+
raise ValueError('Coefficient value out of domain.')
|
|
175
|
+
super().__init__(np.array(coefficients))
|
|
176
|
+
|
|
177
|
+
def get_line_intersections(self) -> list:
|
|
178
|
+
""" Returns a list of intersection points for the lines building the polynomial. """
|
|
179
|
+
result = []
|
|
180
|
+
lines = self.get_hyperplanes() # Hyperplanes are lines in this case
|
|
181
|
+
for line in lines: # Change the form of the equation to a + bx from a + bx + cy
|
|
182
|
+
line.pop()
|
|
183
|
+
lines = filter(lambda x: len(x) == 2, utils.powerset(lines))
|
|
184
|
+
for line_1, line_2 in lines:
|
|
185
|
+
point = [(line_2[0] - line_1[0]) / (line_1[1] - line_2[1])]
|
|
186
|
+
point.append(line_1[0] + line_1[1] * point[0])
|
|
187
|
+
result.append(tuple(point))
|
|
188
|
+
result = list(filter(lambda point: round(point[1], 8) == round(self(point[0]), 8), result)) # Filter out the points not belonging to the polynomial
|
|
189
|
+
return result
|
|
190
|
+
|
|
191
|
+
def get_roots(self) -> tuple:
|
|
192
|
+
""" Returns lists of roots of the polynomial and of their respective ranks (amount of monomials attaining the value). """
|
|
193
|
+
result = {}
|
|
194
|
+
points = self.get_line_intersections()
|
|
195
|
+
for point in points:
|
|
196
|
+
if not point[0] in result:
|
|
197
|
+
result[point[0]] = 1
|
|
198
|
+
else:
|
|
199
|
+
result[point[0]] += 1
|
|
200
|
+
return list(result.keys()), list(result.values())
|
|
@@ -0,0 +1,200 @@
|
|
|
1
|
+
import numpy as np
|
|
2
|
+
|
|
3
|
+
import math
|
|
4
|
+
import string
|
|
5
|
+
|
|
6
|
+
from . import utils
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def add(*args) -> float:
|
|
10
|
+
if -math.inf in args:
|
|
11
|
+
raise ValueError('Value out of domain.')
|
|
12
|
+
return min(args)
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def mult(*args) -> float:
|
|
16
|
+
if -math.inf in args:
|
|
17
|
+
raise ValueError('Value out of domain.')
|
|
18
|
+
return sum(args) if math.inf not in args else math.inf
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def power(a : float,
|
|
22
|
+
k : int) -> float:
|
|
23
|
+
return mult(*[a for _ in range(k)])
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def modulo(a : float,
|
|
27
|
+
t : int) -> float:
|
|
28
|
+
if a < 0 or t < 0:
|
|
29
|
+
raise ValueError('The modulo operator is only defined for positive numbers.')
|
|
30
|
+
if a == math.inf:
|
|
31
|
+
return math.inf
|
|
32
|
+
if a == 0:
|
|
33
|
+
return 0
|
|
34
|
+
if t == math.inf or t == 0:
|
|
35
|
+
return a
|
|
36
|
+
return a - (a // t) * t
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def add_matrices(A : np.ndarray,
|
|
40
|
+
B : np.ndarray) -> np.ndarray:
|
|
41
|
+
if A.shape != B.shape:
|
|
42
|
+
raise ValueError('Given matrices have different shapes.')
|
|
43
|
+
result = np.copy(A)
|
|
44
|
+
shape = A.shape
|
|
45
|
+
for i in range(shape[0]):
|
|
46
|
+
for j in range(shape[1]):
|
|
47
|
+
result[i, j] = add(result[i, j], B[i, j])
|
|
48
|
+
return result
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def mult_matrices(A : np.ndarray,
|
|
52
|
+
B : np.ndarray) -> np.ndarray:
|
|
53
|
+
if A.shape[1] != B.shape[0]:
|
|
54
|
+
raise ValueError('Given matrices are not of MxN and NxP shapes.')
|
|
55
|
+
result = np.zeros((A.shape[0], B.shape[1]))
|
|
56
|
+
for i in range(A.shape[0]):
|
|
57
|
+
for j in range(B.shape[1]):
|
|
58
|
+
result[i, j] = add(*[mult(A[i, k], B[k, j]) for k in range(A.shape[1])])
|
|
59
|
+
return result
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def power_matrix(A : np.ndarray,
|
|
63
|
+
k : int) -> np.ndarray:
|
|
64
|
+
if np.any(np.diagonal(A) != 0):
|
|
65
|
+
raise ValueError('Matrix contains non-zero values on the diagonal.')
|
|
66
|
+
if k == 0:
|
|
67
|
+
result = unit_matrix(A.shape[0], A.shape[1])
|
|
68
|
+
else:
|
|
69
|
+
result = A.copy()
|
|
70
|
+
for _ in range(k):
|
|
71
|
+
result = mult_matrices(A, result)
|
|
72
|
+
return result
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def modulo_matrices(A : np.ndarray,
|
|
76
|
+
b : np.ndarray) -> np.ndarray:
|
|
77
|
+
if b.shape[1] != 1:
|
|
78
|
+
raise ValueError('Given matrix b is not a vertical vector of shape Mx1')
|
|
79
|
+
if A.shape[0] != b.shape[0]:
|
|
80
|
+
raise ValueError('Given matrix b does not have an Mx1 shape against the MxN matrix A.')
|
|
81
|
+
if np.any(A < 0) or np.any(b < 0):
|
|
82
|
+
raise ValueError('Given matrices contain negative values.')
|
|
83
|
+
result = np.zeros(A.shape)
|
|
84
|
+
for i in range(A.shape[0]):
|
|
85
|
+
for j in range(A.shape[1]):
|
|
86
|
+
result[i, j] = modulo(A[i, j], b[i])
|
|
87
|
+
return result
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def unit_matrix(width : int,
|
|
91
|
+
height : int) -> np.ndarray:
|
|
92
|
+
result = np.eye(width, height)
|
|
93
|
+
result[result == 0] = math.inf
|
|
94
|
+
result[result == 1] = 0
|
|
95
|
+
return result
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def kleene_star(A : np.ndarray,
|
|
99
|
+
iterations : int = 1000) -> np.ndarray:
|
|
100
|
+
if A.shape[0] != A.shape[1]:
|
|
101
|
+
raise ValueError('Matrix is not square.')
|
|
102
|
+
series = [
|
|
103
|
+
unit_matrix(A.shape[0], A.shape[1]),
|
|
104
|
+
A.copy()
|
|
105
|
+
]
|
|
106
|
+
for _ in range(iterations):
|
|
107
|
+
series.append(add_matrices(series[-1], mult_matrices(series[-1], series[-2])))
|
|
108
|
+
return series[-1]
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
class MultivariatePolynomial:
|
|
112
|
+
""" An implementation of a tropical polynomial with multiple variables. """
|
|
113
|
+
|
|
114
|
+
def __init__(self, coefficients : np.ndarray) -> None:
|
|
115
|
+
self.coefficients = coefficients
|
|
116
|
+
self.dimensions = len(self.coefficients.shape) + 1
|
|
117
|
+
self._symbols = string.ascii_lowercase
|
|
118
|
+
|
|
119
|
+
def __call__(self, *variables : float) -> float:
|
|
120
|
+
if len(variables) != self.dimensions - 1:
|
|
121
|
+
raise ValueError('The amount of variables and coefficients differs.')
|
|
122
|
+
result = [math.inf]
|
|
123
|
+
for indices, coefficient in np.ndenumerate(self.coefficients):
|
|
124
|
+
powers = []
|
|
125
|
+
for variable_index, i in enumerate(indices):
|
|
126
|
+
powers.append(power(variables[variable_index], i))
|
|
127
|
+
result.append(mult(coefficient, *powers))
|
|
128
|
+
result = add(*result)
|
|
129
|
+
return float(result)
|
|
130
|
+
|
|
131
|
+
def __str__(self) -> str:
|
|
132
|
+
result = ''
|
|
133
|
+
for indices, coefficient in np.ndenumerate(self.coefficients):
|
|
134
|
+
if coefficient.is_integer():
|
|
135
|
+
result += '(' + str(int(coefficient))
|
|
136
|
+
elif coefficient < math.inf:
|
|
137
|
+
result += '(' + str(coefficient)
|
|
138
|
+
else:
|
|
139
|
+
result += '(∞'
|
|
140
|
+
for variable_index, i in enumerate(indices):
|
|
141
|
+
if i > 1:
|
|
142
|
+
result += ' * ' + self._symbols[variable_index] + '^' + str(i)
|
|
143
|
+
elif i == 1:
|
|
144
|
+
result += ' * ' + self._symbols[variable_index]
|
|
145
|
+
result += ') + '
|
|
146
|
+
return result[:-3]
|
|
147
|
+
|
|
148
|
+
def get_hyperplanes(self) -> list:
|
|
149
|
+
""" Returns a list of coefficients of a linear equation for every hyperplane building the polynomial. """
|
|
150
|
+
result = []
|
|
151
|
+
for indices, coefficient in np.ndenumerate(self.coefficients):
|
|
152
|
+
if coefficient == math.inf:
|
|
153
|
+
continue
|
|
154
|
+
hyperplane = [float(coefficient)]
|
|
155
|
+
hyperplane.extend(indices)
|
|
156
|
+
hyperplane.append(1) # The coefficient of the last dimension (e.g. Z in 3D)
|
|
157
|
+
result.append(
|
|
158
|
+
list(
|
|
159
|
+
map(
|
|
160
|
+
lambda x: int(x) if x.is_integer() else float(x),
|
|
161
|
+
hyperplane
|
|
162
|
+
)
|
|
163
|
+
)
|
|
164
|
+
)
|
|
165
|
+
return result
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
class Polynomial(MultivariatePolynomial):
|
|
169
|
+
""" An implementation of a tropical polynomial with a single variable. """
|
|
170
|
+
|
|
171
|
+
def __init__(self, *coefficients) -> None:
|
|
172
|
+
for value in coefficients:
|
|
173
|
+
if not isinstance(value, float|int) or value == -math.inf:
|
|
174
|
+
raise ValueError('Coefficient value out of domain.')
|
|
175
|
+
super().__init__(np.array(coefficients))
|
|
176
|
+
|
|
177
|
+
def get_line_intersections(self) -> list:
|
|
178
|
+
""" Returns a list of intersection points for the lines building the polynomial. """
|
|
179
|
+
result = []
|
|
180
|
+
lines = self.get_hyperplanes() # Hyperplanes are lines in this case
|
|
181
|
+
for line in lines: # Change the form of the equation to a + bx from a + bx + cy
|
|
182
|
+
line.pop()
|
|
183
|
+
lines = filter(lambda x: len(x) == 2, utils.powerset(lines))
|
|
184
|
+
for line_1, line_2 in lines:
|
|
185
|
+
point = [(line_2[0] - line_1[0]) / (line_1[1] - line_2[1])]
|
|
186
|
+
point.append(line_1[0] + line_1[1] * point[0])
|
|
187
|
+
result.append(tuple(point))
|
|
188
|
+
result = list(filter(lambda point: round(point[1], 8) == round(self(point[0]), 8), result)) # Filter out the points not belonging to the polynomial
|
|
189
|
+
return result
|
|
190
|
+
|
|
191
|
+
def get_roots(self) -> tuple:
|
|
192
|
+
""" Returns lists of roots of the polynomial and of their respective ranks (amount of monomials attaining the value). """
|
|
193
|
+
result = {}
|
|
194
|
+
points = self.get_line_intersections()
|
|
195
|
+
for point in points:
|
|
196
|
+
if not point[0] in result:
|
|
197
|
+
result[point[0]] = 1
|
|
198
|
+
else:
|
|
199
|
+
result[point[0]] += 1
|
|
200
|
+
return list(result.keys()), list(result.values())
|
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
Metadata-Version: 2.
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
2
|
Name: mplusa
|
|
3
|
-
Version: 0.0.
|
|
3
|
+
Version: 0.0.3
|
|
4
4
|
Summary: A library for calculations in tropical and arctic semirings.
|
|
5
|
-
Author-email:
|
|
5
|
+
Author-email: Maksymilian Wiekiera <maksymilian3563@gmail.com>
|
|
6
6
|
License: Copyright (c) 2025 Maksymilian Wiekiera
|
|
7
7
|
|
|
8
8
|
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
@@ -23,46 +23,60 @@ License: Copyright (c) 2025 Maksymilian Wiekiera
|
|
|
23
23
|
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
24
24
|
SOFTWARE.
|
|
25
25
|
Project-URL: homepage, https://github.com/Hadelekw/mplusa
|
|
26
|
+
Project-URL: documentation, https://hadelekw.github.io/mplusa-docs.html
|
|
26
27
|
Classifier: Programming Language :: Python :: 3
|
|
27
28
|
Classifier: Operating System :: OS Independent
|
|
28
29
|
Requires-Python: >=3.11
|
|
29
30
|
Description-Content-Type: text/markdown
|
|
30
31
|
License-File: LICENSE
|
|
31
32
|
Requires-Dist: numpy>=2.2.3
|
|
33
|
+
Dynamic: license-file
|
|
32
34
|
|
|
33
35
|
# MPlusA
|
|
34
36
|
---
|
|
35
|
-
**MPlusA** is a small Python library for tropical algebra (also known as
|
|
37
|
+
**MPlusA** is a small Python library for tropical algebra (also known as (min, +) and (max, +) algebra). It provides the definitions of basic operations on numbers and NumPy arrays, as well as a basic implementation of tropical polynomials.
|
|
36
38
|
|
|
37
39
|
Any improvements or fixes are always welcome.
|
|
38
40
|
|
|
39
41
|
## How to use
|
|
40
|
-
After having installed the library one can import one of the two modules the package consists of (`minplus` and `maxplus`) and use the full array of its capabilities. The functions are essentially the same between the modules.
|
|
42
|
+
After having installed the library one can import one of the two modules the package consists of (`minplus` and `maxplus`) and use the full array of its capabilities. The functions are essentially the same between the modules.
|
|
41
43
|
|
|
42
44
|
**`add(*args) -> Real`**
|
|
43
45
|
Tropical addition. Essentially an alias for Python's `min` function.
|
|
46
|
+
|
|
44
47
|
**`mult(*args) -> Real`**
|
|
45
48
|
Tropical multiplication. Essentially an alias for Python's `sum` function.
|
|
49
|
+
|
|
46
50
|
**`add_matrices(A : np.ndarray, B : np.ndarray) -> np.ndarray`**
|
|
47
51
|
Tropical addition of NumPy arrays. The summed matrices have to be of the same shape.
|
|
52
|
+
|
|
48
53
|
**`mult_matrices(A : np.ndarray, B : np.ndarray) -> np.ndarray`**
|
|
49
54
|
Tropical multiplication of NumPy arrays. The multiplied matrices have to be of sizes MxN and NxP and their order matters. The result is of shape MxP.
|
|
55
|
+
|
|
50
56
|
**`modulo(a : Real, t : int) -> Real`**
|
|
51
57
|
Tropical modulo operator. It can be understood as the difference between the number $a$ and $t^k$ where $k$ is the largest integer that satisfies $a \geq t^k$.
|
|
58
|
+
|
|
52
59
|
**`modulo_matrices(A : np.ndarray, b : np.ndarray) -> np.ndarray`**
|
|
53
60
|
Tropical modulo operator for NumPy arrays. The input matrices should be of size MxN and Mx1. The result is an MxN matrix.
|
|
61
|
+
|
|
54
62
|
**`power(a : real, k : int) -> Real`**
|
|
55
63
|
Tropical power operator. Applies the multiplication k times.
|
|
64
|
+
|
|
56
65
|
**`power_matrix(A : np.ndarray, k : int) -> np.ndarray`**
|
|
57
66
|
Tropical power operator for NumPy arrays. It multiplies the matrix k times.
|
|
67
|
+
|
|
58
68
|
**`unit_matrix(width : int, height : int) -> np.ndarray`**
|
|
59
69
|
Creates a tropical unit matrix of given width and height.
|
|
70
|
+
|
|
60
71
|
**`star(A : np.ndarray) -> np.ndarray`**
|
|
61
|
-
Definition of
|
|
72
|
+
Definition of an unary operator of unique to tropical algebra, usually denoted as $\mathbf{A}^*$. It returns the value to which an infinite recursive sum of matrices converges. The input matrix has to be square and the series created in the process of calculating the value needs to be convergent.
|
|
73
|
+
|
|
62
74
|
**`Polynomial(*coefficients)`**
|
|
63
|
-
This is a class that implements basic single-variable tropical polynomials. Calling an object of this class allows to take a value the polynomial takes at a given point
|
|
75
|
+
This is a class that implements basic single-variable tropical polynomials. Calling an object of this class allows to take a value the polynomial takes at a given point.
|
|
76
|
+
|
|
77
|
+
For the full list of capabilities, refer to the [documentation](https://hadelekw.github.io/mplusa-docs.html)
|
|
64
78
|
|
|
65
|
-
|
|
79
|
+
## Example code
|
|
66
80
|
```
|
|
67
81
|
import numpy as np
|
|
68
82
|
from mplusa import minplus
|
|
@@ -1,161 +0,0 @@
|
|
|
1
|
-
import math
|
|
2
|
-
import numpy as np
|
|
3
|
-
from numbers import Real
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
def add(*args) -> Real:
|
|
7
|
-
return max(args)
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
def mult(*args) -> Real:
|
|
11
|
-
return sum(args) if -math.inf not in args else -math.inf
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
def add_matrices(A : np.ndarray,
|
|
15
|
-
B : np.ndarray) -> np.ndarray:
|
|
16
|
-
if A.shape != B.shape:
|
|
17
|
-
raise ValueError(
|
|
18
|
-
'Maxplus.add_matrices: given matrices ' +\
|
|
19
|
-
'are of different shape (A: {}, B: {}).'.format(A.shape, B.shape)
|
|
20
|
-
)
|
|
21
|
-
result = np.copy(A)
|
|
22
|
-
shape = A.shape
|
|
23
|
-
for i in range(shape[0]):
|
|
24
|
-
for j in range(shape[1]):
|
|
25
|
-
result[i, j] = add(result[i, j], B[i, j])
|
|
26
|
-
return result
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
def mult_matrices(A : np.ndarray,
|
|
30
|
-
B : np.ndarray) -> np.ndarray:
|
|
31
|
-
if A.shape[1] != B.shape[0]:
|
|
32
|
-
raise ValueError(
|
|
33
|
-
'Maxplus.mult_matrices: given matrices ' +\
|
|
34
|
-
'are of shapes not given as MxN and NxP (A: {}, B: {}).'.format(
|
|
35
|
-
A.shape, B.shape
|
|
36
|
-
)
|
|
37
|
-
)
|
|
38
|
-
result = np.zeros((A.shape[0], B.shape[1]))
|
|
39
|
-
for i in range(A.shape[0]):
|
|
40
|
-
for j in range(B.shape[1]):
|
|
41
|
-
result[i, j] = add(*[mult(A[i, k], B[k, j]) for k in range(A.shape[1])])
|
|
42
|
-
return result
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
def modulo(a : Real,
|
|
46
|
-
t : int) -> Real:
|
|
47
|
-
if a == -math.inf:
|
|
48
|
-
return -math.inf
|
|
49
|
-
if a == 0:
|
|
50
|
-
return 0
|
|
51
|
-
if t == -math.inf or t == 0:
|
|
52
|
-
return a
|
|
53
|
-
return a - (a // t) * t
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
def modulo_matrices(A : np.ndarray,
|
|
57
|
-
b : np.ndarray) -> np.ndarray:
|
|
58
|
-
if b.shape[1] != 1:
|
|
59
|
-
raise ValueError(
|
|
60
|
-
'Maxplus.modulo_matrices: given matrix b ' +\
|
|
61
|
-
'is not a properly formated vector (has shape of {}).'.format(
|
|
62
|
-
b.shape
|
|
63
|
-
)
|
|
64
|
-
)
|
|
65
|
-
if A.shape[0] != b.shape[0]:
|
|
66
|
-
raise ValueError(
|
|
67
|
-
'Maxplus.modulo_matrices: given matrix b ' +\
|
|
68
|
-
'does not have an Mx1 shape against MxN matrix A (A: {}, b: {}).'.format(
|
|
69
|
-
A.shape, b.shape
|
|
70
|
-
)
|
|
71
|
-
)
|
|
72
|
-
if np.any(A < 0) or np.any(b < 0):
|
|
73
|
-
raise ValueError(
|
|
74
|
-
'Maxplus.modulo_matrices: matrices contain negative values.'
|
|
75
|
-
)
|
|
76
|
-
result = np.zeros(A.shape)
|
|
77
|
-
for i in range(A.shape[0]):
|
|
78
|
-
for j in range(A.shape[1]):
|
|
79
|
-
result[i, j] = modulo(A[i, j], b[i])
|
|
80
|
-
return result
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
def power(a : Real,
|
|
84
|
-
k : int) -> Real:
|
|
85
|
-
return mult(*[a for _ in range(k)])
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
def power_matrix(A : np.ndarray,
|
|
89
|
-
k : int) -> np.ndarray:
|
|
90
|
-
if np.any(np.diagonal(A) != 0):
|
|
91
|
-
raise ValueError(
|
|
92
|
-
'Maxplus.power_matrix: matrix contains non-zero values on diagonal.'
|
|
93
|
-
)
|
|
94
|
-
if k == 0:
|
|
95
|
-
result = unit_matrix(A.shape[0], A.shape[1])
|
|
96
|
-
else:
|
|
97
|
-
result = A.copy()
|
|
98
|
-
for _ in range(k):
|
|
99
|
-
result = mult_matrices(A, result)
|
|
100
|
-
return result
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
def unit_matrix(width : int,
|
|
104
|
-
height : int) -> np.ndarray:
|
|
105
|
-
if width < 0 or height < 0:
|
|
106
|
-
raise ValueError(
|
|
107
|
-
'Maxplus.unit_matrix: invalid width or height.'
|
|
108
|
-
)
|
|
109
|
-
result = np.eye(width, height)
|
|
110
|
-
result[result == 0] = -math.inf
|
|
111
|
-
result[result == 1] = 0
|
|
112
|
-
return result
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
def star(A : np.ndarray,
|
|
116
|
-
iterations : int = 1000,
|
|
117
|
-
eps : float = 0.001) -> np.ndarray:
|
|
118
|
-
if A.shape[0] != A.shape[1]:
|
|
119
|
-
raise ValueError(
|
|
120
|
-
'Maxplus.star: matrix is not square.'
|
|
121
|
-
)
|
|
122
|
-
series = [
|
|
123
|
-
unit_matrix(A.shape[0], A.shape[1]),
|
|
124
|
-
A.copy()
|
|
125
|
-
]
|
|
126
|
-
for i in range(2, iterations):
|
|
127
|
-
series.append(add_matrices(series[-1], series[-2]))
|
|
128
|
-
# Very basic check if the series is convergent.
|
|
129
|
-
if abs(np.max(series[-1] - series[-2])) < eps:
|
|
130
|
-
break
|
|
131
|
-
else:
|
|
132
|
-
raise ValueError(
|
|
133
|
-
'Maxplus.star: the series for this matrix is not convergent ' +\
|
|
134
|
-
'(within the limits of iterations and decimal places).'
|
|
135
|
-
)
|
|
136
|
-
return series[-1]
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
class Polynomial:
|
|
140
|
-
""" A simple implementation of a single-variable arctic polynomial. """
|
|
141
|
-
|
|
142
|
-
def __init__(self, *coefficients) -> None:
|
|
143
|
-
for value in coefficients:
|
|
144
|
-
if not isinstance(value, Real) or value == math.inf:
|
|
145
|
-
raise ValueError(
|
|
146
|
-
'Maxplus.Polynomial.__init__: coefficient value out of domain.'
|
|
147
|
-
)
|
|
148
|
-
self.coefficients = coefficients[::-1]
|
|
149
|
-
|
|
150
|
-
def __call__(self, x : float) -> float:
|
|
151
|
-
return add(*[mult(coefficient, power(x, i)) for i, coefficient in enumerate(self.coefficients)])
|
|
152
|
-
|
|
153
|
-
def get_hypersurface(self) -> list[float]:
|
|
154
|
-
result = []
|
|
155
|
-
candidates = [c2 - c1 for c1, c2 in zip(self.coefficients[1:], self.coefficients[:-1])]
|
|
156
|
-
for candidate in candidates:
|
|
157
|
-
if not isinstance(candidate, Real) or candidate == math.inf:
|
|
158
|
-
continue
|
|
159
|
-
if abs(self(candidate) - self(candidate - 1)) != abs(self(candidate) - self(candidate + 1)):
|
|
160
|
-
result.append(candidate)
|
|
161
|
-
return result
|
|
@@ -1,161 +0,0 @@
|
|
|
1
|
-
import math
|
|
2
|
-
import numpy as np
|
|
3
|
-
from numbers import Real
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
def add(*args) -> Real:
|
|
7
|
-
return min(args)
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
def mult(*args) -> Real:
|
|
11
|
-
return sum(args) if math.inf not in args else math.inf
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
def add_matrices(A : np.ndarray,
|
|
15
|
-
B : np.ndarray) -> np.ndarray:
|
|
16
|
-
if A.shape != B.shape:
|
|
17
|
-
raise ValueError(
|
|
18
|
-
'Minplus.add_matrices: given matrices ' +\
|
|
19
|
-
'are of different shape (A: {}, B: {}).'.format(A.shape, B.shape)
|
|
20
|
-
)
|
|
21
|
-
result = np.copy(A)
|
|
22
|
-
shape = A.shape
|
|
23
|
-
for i in range(shape[0]):
|
|
24
|
-
for j in range(shape[1]):
|
|
25
|
-
result[i, j] = add(result[i, j], B[i, j])
|
|
26
|
-
return result
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
def mult_matrices(A : np.ndarray,
|
|
30
|
-
B : np.ndarray) -> np.ndarray:
|
|
31
|
-
if A.shape[1] != B.shape[0]:
|
|
32
|
-
raise ValueError(
|
|
33
|
-
'Minplus.mult_matrices: given matrices ' +\
|
|
34
|
-
'are of shapes not given as MxN and NxP (A: {}, B: {}).'.format(
|
|
35
|
-
A.shape, B.shape
|
|
36
|
-
)
|
|
37
|
-
)
|
|
38
|
-
result = np.zeros((A.shape[0], B.shape[1]))
|
|
39
|
-
for i in range(A.shape[0]):
|
|
40
|
-
for j in range(B.shape[1]):
|
|
41
|
-
result[i, j] = add(*[mult(A[i, k], B[k, j]) for k in range(A.shape[1])])
|
|
42
|
-
return result
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
def modulo(a : Real,
|
|
46
|
-
t : int) -> Real:
|
|
47
|
-
if a == math.inf:
|
|
48
|
-
return math.inf
|
|
49
|
-
if a == 0:
|
|
50
|
-
return 0
|
|
51
|
-
if t == math.inf or t == 0:
|
|
52
|
-
return a
|
|
53
|
-
return a - (a // t) * t
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
def modulo_matrices(A : np.ndarray,
|
|
57
|
-
b : np.ndarray) -> np.ndarray:
|
|
58
|
-
if b.shape[1] != 1:
|
|
59
|
-
raise ValueError(
|
|
60
|
-
'Minplus.modulo_matrices: given matrix b ' +\
|
|
61
|
-
'is not a properly formated vector (has shape of {}).'.format(
|
|
62
|
-
b.shape
|
|
63
|
-
)
|
|
64
|
-
)
|
|
65
|
-
if A.shape[0] != b.shape[0]:
|
|
66
|
-
raise ValueError(
|
|
67
|
-
'Minplus.modulo_matrices: given matrix b ' +\
|
|
68
|
-
'does not have an Mx1 shape against MxN matrix A (A: {}, b: {}).'.format(
|
|
69
|
-
A.shape, b.shape
|
|
70
|
-
)
|
|
71
|
-
)
|
|
72
|
-
if np.any(A < 0) or np.any(b < 0):
|
|
73
|
-
raise ValueError(
|
|
74
|
-
'Minplus.modulo_matrices: matrices contain negative values.'
|
|
75
|
-
)
|
|
76
|
-
result = np.zeros(A.shape)
|
|
77
|
-
for i in range(A.shape[0]):
|
|
78
|
-
for j in range(A.shape[1]):
|
|
79
|
-
result[i, j] = modulo(A[i, j], b[i])
|
|
80
|
-
return result
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
def power(a : Real,
|
|
84
|
-
k : int) -> Real:
|
|
85
|
-
return mult(*[a for _ in range(k)])
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
def power_matrix(A : np.ndarray,
|
|
89
|
-
k : int) -> np.ndarray:
|
|
90
|
-
if np.any(np.diagonal(A) != 0):
|
|
91
|
-
raise ValueError(
|
|
92
|
-
'Minplus.power_matrix: matrix contains non-zero values on diagonal.'
|
|
93
|
-
)
|
|
94
|
-
if k == 0:
|
|
95
|
-
result = unit_matrix(A.shape[0], A.shape[1])
|
|
96
|
-
else:
|
|
97
|
-
result = A.copy()
|
|
98
|
-
for _ in range(k):
|
|
99
|
-
result = mult_matrices(A, result)
|
|
100
|
-
return result
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
def unit_matrix(width : int,
|
|
104
|
-
height : int) -> np.ndarray:
|
|
105
|
-
if width < 0 or height < 0:
|
|
106
|
-
raise ValueError(
|
|
107
|
-
'Minplus.unit_matrix: invalid width or height.'
|
|
108
|
-
)
|
|
109
|
-
result = np.eye(width, height)
|
|
110
|
-
result[result == 0] = math.inf
|
|
111
|
-
result[result == 1] = 0
|
|
112
|
-
return result
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
def star(A : np.ndarray,
|
|
116
|
-
iterations : int = 1000,
|
|
117
|
-
eps : float = 0.001) -> np.ndarray:
|
|
118
|
-
if A.shape[0] != A.shape[1]:
|
|
119
|
-
raise ValueError(
|
|
120
|
-
'Minplus.star: matrix is not square.'
|
|
121
|
-
)
|
|
122
|
-
series = [
|
|
123
|
-
unit_matrix(A.shape[0], A.shape[1]),
|
|
124
|
-
A.copy()
|
|
125
|
-
]
|
|
126
|
-
for i in range(2, iterations):
|
|
127
|
-
series.append(add_matrices(series[-1], series[-2]))
|
|
128
|
-
# Very basic check if the series is convergent.
|
|
129
|
-
if abs(np.max(series[-1] - series[-2])) < eps:
|
|
130
|
-
break
|
|
131
|
-
else:
|
|
132
|
-
raise ValueError(
|
|
133
|
-
'Minplus.star: the series for this matrix is not convergent ' +\
|
|
134
|
-
'(within the limits of iterations and decimal places).'
|
|
135
|
-
)
|
|
136
|
-
return series[-1]
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
class Polynomial:
|
|
140
|
-
""" A simple implementation of a single-variable tropical polynomial. """
|
|
141
|
-
|
|
142
|
-
def __init__(self, *coefficients) -> None:
|
|
143
|
-
for value in coefficients:
|
|
144
|
-
if not isinstance(value, Real) or value == -math.inf:
|
|
145
|
-
raise ValueError(
|
|
146
|
-
'Minplus.Polynomial.__init__: coefficient value out of domain.'
|
|
147
|
-
)
|
|
148
|
-
self.coefficients = coefficients[::-1]
|
|
149
|
-
|
|
150
|
-
def __call__(self, x : float) -> float:
|
|
151
|
-
return add(*[mult(coefficient, power(x, i)) for i, coefficient in enumerate(self.coefficients)])
|
|
152
|
-
|
|
153
|
-
def get_hypersurface(self) -> list[float]:
|
|
154
|
-
result = []
|
|
155
|
-
candidates = [c2 - c1 for c1, c2 in zip(self.coefficients[1:], self.coefficients[:-1])]
|
|
156
|
-
for candidate in candidates:
|
|
157
|
-
if not isinstance(candidate, Real) or candidate == -math.inf:
|
|
158
|
-
continue
|
|
159
|
-
if abs(self(candidate) - self(candidate - 1)) != abs(self(candidate) - self(candidate + 1)):
|
|
160
|
-
result.append(candidate)
|
|
161
|
-
return result
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|