mplusa 0.0.2__py3-none-any.whl → 0.0.4__py3-none-any.whl

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/maxplus.py DELETED
@@ -1,179 +0,0 @@
1
- import math
2
- import numpy as np
3
- from numbers import Real
4
-
5
-
6
- def add(*args) -> Real:
7
- if math.inf in args:
8
- raise ValueError(
9
- 'Maxplus.add: value out of domain.'
10
- )
11
- return max(args)
12
-
13
-
14
- def mult(*args) -> Real:
15
- if math.inf in args:
16
- raise ValueError(
17
- 'Maxplus.add: value out of domain.'
18
- )
19
- return sum(args) if -math.inf not in args else -math.inf
20
-
21
-
22
- def add_matrices(A : np.ndarray,
23
- B : np.ndarray) -> np.ndarray:
24
- if A.shape != B.shape:
25
- raise ValueError(
26
- 'Maxplus.add_matrices: given matrices ' +\
27
- 'are of different shape (A: {}, B: {}).'.format(A.shape, B.shape)
28
- )
29
- result = np.copy(A)
30
- shape = A.shape
31
- for i in range(shape[0]):
32
- for j in range(shape[1]):
33
- result[i, j] = add(result[i, j], B[i, j])
34
- return result
35
-
36
-
37
- def mult_matrices(A : np.ndarray,
38
- B : np.ndarray) -> np.ndarray:
39
- if A.shape[1] != B.shape[0]:
40
- raise ValueError(
41
- 'Maxplus.mult_matrices: given matrices ' +\
42
- 'are of shapes not given as MxN and NxP (A: {}, B: {}).'.format(
43
- A.shape, B.shape
44
- )
45
- )
46
- result = np.zeros((A.shape[0], B.shape[1]))
47
- for i in range(A.shape[0]):
48
- for j in range(B.shape[1]):
49
- result[i, j] = add(*[mult(A[i, k], B[k, j]) for k in range(A.shape[1])])
50
- return result
51
-
52
-
53
- def modulo(a : Real,
54
- t : int) -> Real:
55
- if a < 0 or t < 0:
56
- raise ValueError(
57
- 'Maxplus.modulo: modulo operation is only defined for positive numbers.'
58
- )
59
- if a == -math.inf:
60
- return -math.inf
61
- if a == 0:
62
- return 0
63
- if t == -math.inf or t == 0:
64
- return a
65
- return a - (a // t) * t
66
-
67
-
68
- def modulo_matrices(A : np.ndarray,
69
- b : np.ndarray) -> np.ndarray:
70
- if b.shape[1] != 1:
71
- raise ValueError(
72
- 'Maxplus.modulo_matrices: given matrix b ' +\
73
- 'is not a vertical vector of shape Mx1 (has shape of {}).'.format(
74
- b.shape
75
- )
76
- )
77
- if A.shape[0] != b.shape[0]:
78
- raise ValueError(
79
- 'Maxplus.modulo_matrices: given matrix b ' +\
80
- 'does not have an Mx1 shape against MxN matrix A (A: {}, b: {}).'.format(
81
- A.shape, b.shape
82
- )
83
- )
84
- if np.any(A < 0) or np.any(b < 0):
85
- raise ValueError(
86
- 'Maxplus.modulo_matrices: matrices contain negative values.'
87
- )
88
- result = np.zeros(A.shape)
89
- for i in range(A.shape[0]):
90
- for j in range(A.shape[1]):
91
- result[i, j] = modulo(A[i, j], b[i])
92
- return result
93
-
94
-
95
- def power(a : Real,
96
- k : int) -> Real:
97
- return mult(*[a for _ in range(k)])
98
-
99
-
100
- def power_matrix(A : np.ndarray,
101
- k : int) -> np.ndarray:
102
- if np.any(np.diagonal(A) != 0):
103
- raise ValueError(
104
- 'Maxplus.power_matrix: matrix contains non-zero values on the diagonal.'
105
- )
106
- if k == 0:
107
- result = unit_matrix(A.shape[0], A.shape[1])
108
- else:
109
- result = A.copy()
110
- for _ in range(k):
111
- result = mult_matrices(A, result)
112
- return result
113
-
114
-
115
- def unit_matrix(width : int,
116
- height : int) -> np.ndarray:
117
- if width < 0 or height < 0:
118
- raise ValueError(
119
- 'Maxplus.unit_matrix: invalid width or height.'
120
- )
121
- result = np.eye(width, height)
122
- result[result == 0] = -math.inf
123
- result[result == 1] = 0
124
- return result
125
-
126
-
127
- def star(A : np.ndarray,
128
- iterations : int = 1000,
129
- eps : float = 0.001) -> np.ndarray:
130
- if A.shape[0] != A.shape[1]:
131
- raise ValueError(
132
- 'Maxplus.star: matrix is not square.'
133
- )
134
- series = [
135
- unit_matrix(A.shape[0], A.shape[1]),
136
- A.copy()
137
- ]
138
- for i in range(2, iterations):
139
- series.append(add_matrices(series[-1], series[-2]))
140
- # Very basic check if the series is convergent.
141
- if abs(np.max(series[-1] - series[-2])) < eps:
142
- break
143
- else:
144
- raise ValueError(
145
- 'Maxplus.star: the series for this matrix is not convergent ' +\
146
- '(within the limits of iterations and decimal places).'
147
- )
148
- return series[-1]
149
-
150
-
151
- class Polynomial:
152
- """ A simple implementation of a single-variable arctic polynomial. """
153
-
154
- def __init__(self, *coefficients) -> None:
155
- for value in coefficients:
156
- if not isinstance(value, Real) or value == math.inf:
157
- raise ValueError(
158
- 'Maxplus.Polynomial.__init__: coefficient value out of domain.'
159
- )
160
- self.coefficients = coefficients[::-1]
161
-
162
- def __call__(self, x : float) -> float:
163
- return add(*[mult(coefficient, power(x, i)) for i, coefficient in enumerate(self.coefficients)])
164
-
165
- def get_lines(self) -> list[tuple[float]]:
166
- """ Returns the a and b values of standard linear functions building the polynomial in form of y = ax + b. """
167
- return [(a, b) for a, b in enumerate(self.coefficients) if b > -math.inf]
168
-
169
- def get_hypersurface(self) -> list[float]:
170
- lines = self.get_lines()
171
- result = []
172
- for (a, c) in lines:
173
- for (b, d) in lines:
174
- if a == b or c == d:
175
- continue
176
- x = (d - c) / (a - b)
177
- if a * x + c == self(x):
178
- result.append(x)
179
- return list(set(result))
mplusa/minplus.py DELETED
@@ -1,179 +0,0 @@
1
- import math
2
- import numpy as np
3
- from numbers import Real
4
-
5
-
6
- def add(*args) -> Real:
7
- if -math.inf in args:
8
- raise ValueError(
9
- 'Minplus.add: value out of domain.'
10
- )
11
- return min(args)
12
-
13
-
14
- def mult(*args) -> Real:
15
- if -math.inf in args:
16
- raise ValueError(
17
- 'Minplus.mult: value out of domain.'
18
- )
19
- return sum(args) if math.inf not in args else math.inf
20
-
21
-
22
- def add_matrices(A : np.ndarray,
23
- B : np.ndarray) -> np.ndarray:
24
- if A.shape != B.shape:
25
- raise ValueError(
26
- 'Minplus.add_matrices: given matrices ' +\
27
- 'are of different shape (A: {}, B: {}).'.format(A.shape, B.shape)
28
- )
29
- result = np.copy(A)
30
- shape = A.shape
31
- for i in range(shape[0]):
32
- for j in range(shape[1]):
33
- result[i, j] = add(result[i, j], B[i, j])
34
- return result
35
-
36
-
37
- def mult_matrices(A : np.ndarray,
38
- B : np.ndarray) -> np.ndarray:
39
- if A.shape[1] != B.shape[0]:
40
- raise ValueError(
41
- 'Minplus.mult_matrices: given matrices ' +\
42
- 'are of shapes not given as MxN and NxP (A: {}, B: {}).'.format(
43
- A.shape, B.shape
44
- )
45
- )
46
- result = np.zeros((A.shape[0], B.shape[1]))
47
- for i in range(A.shape[0]):
48
- for j in range(B.shape[1]):
49
- result[i, j] = add(*[mult(A[i, k], B[k, j]) for k in range(A.shape[1])])
50
- return result
51
-
52
-
53
- def modulo(a : Real,
54
- t : int) -> Real:
55
- if a < 0 or t < 0:
56
- raise ValueError(
57
- 'Minplus.modulo: modulo operation is only defined for positive numbers.'
58
- )
59
- if a == math.inf:
60
- return math.inf
61
- if a == 0:
62
- return 0
63
- if t == math.inf or t == 0:
64
- return a
65
- return a - (a // t) * t
66
-
67
-
68
- def modulo_matrices(A : np.ndarray,
69
- b : np.ndarray) -> np.ndarray:
70
- if b.shape[1] != 1:
71
- raise ValueError(
72
- 'Minplus.modulo_matrices: given matrix b ' +\
73
- 'is not a vertical vector of shape Mx1 (has shape of {}).'.format(
74
- b.shape
75
- )
76
- )
77
- if A.shape[0] != b.shape[0]:
78
- raise ValueError(
79
- 'Minplus.modulo_matrices: given matrix b ' +\
80
- 'does not have an Mx1 shape against MxN matrix A (A: {}, b: {}).'.format(
81
- A.shape, b.shape
82
- )
83
- )
84
- if np.any(A < 0) or np.any(b < 0):
85
- raise ValueError(
86
- 'Minplus.modulo_matrices: matrices contain negative values.'
87
- )
88
- result = np.zeros(A.shape)
89
- for i in range(A.shape[0]):
90
- for j in range(A.shape[1]):
91
- result[i, j] = modulo(A[i, j], b[i])
92
- return result
93
-
94
-
95
- def power(a : Real,
96
- k : int) -> Real:
97
- return mult(*[a for _ in range(k)])
98
-
99
-
100
- def power_matrix(A : np.ndarray,
101
- k : int) -> np.ndarray:
102
- if np.any(np.diagonal(A) != 0):
103
- raise ValueError(
104
- 'Minplus.power_matrix: matrix contains non-zero values on the diagonal.'
105
- )
106
- if k == 0:
107
- result = unit_matrix(A.shape[0], A.shape[1])
108
- else:
109
- result = A.copy()
110
- for _ in range(k):
111
- result = mult_matrices(A, result)
112
- return result
113
-
114
-
115
- def unit_matrix(width : int,
116
- height : int) -> np.ndarray:
117
- if width < 0 or height < 0:
118
- raise ValueError(
119
- 'Minplus.unit_matrix: invalid width or height.'
120
- )
121
- result = np.eye(width, height)
122
- result[result == 0] = math.inf
123
- result[result == 1] = 0
124
- return result
125
-
126
-
127
- def star(A : np.ndarray,
128
- iterations : int = 1000,
129
- eps : float = 0.001) -> np.ndarray:
130
- if A.shape[0] != A.shape[1]:
131
- raise ValueError(
132
- 'Minplus.star: matrix is not square.'
133
- )
134
- series = [
135
- unit_matrix(A.shape[0], A.shape[1]),
136
- A.copy()
137
- ]
138
- for i in range(2, iterations):
139
- series.append(add_matrices(series[-1], series[-2]))
140
- # Very basic check if the series is convergent.
141
- if abs(np.max(series[-1] - series[-2])) < eps:
142
- break
143
- else:
144
- raise ValueError(
145
- 'Minplus.star: the series for this matrix is not convergent ' +\
146
- '(within the limits of iterations and decimal places).'
147
- )
148
- return series[-1]
149
-
150
-
151
- class Polynomial:
152
- """ A simple implementation of a single-variable tropical polynomial. """
153
-
154
- def __init__(self, *coefficients) -> None:
155
- for value in coefficients:
156
- if not isinstance(value, Real) or value == -math.inf:
157
- raise ValueError(
158
- 'Minplus.Polynomial.__init__: coefficient value out of domain.'
159
- )
160
- self.coefficients = coefficients[::-1]
161
-
162
- def __call__(self, x : float) -> float:
163
- return add(*[mult(coefficient, power(x, i)) for i, coefficient in enumerate(self.coefficients)])
164
-
165
- def get_lines(self) -> list[tuple[float]]:
166
- """ Returns the a and b values of standard linear functions building the polynomial in form of y = ax + b. """
167
- return [(a, b) for a, b in enumerate(self.coefficients) if b < math.inf]
168
-
169
- def get_hypersurface(self) -> list[float]:
170
- lines = self.get_lines()
171
- result = []
172
- for (a, c) in lines:
173
- for (b, d) in lines:
174
- if a == b or c == d:
175
- continue
176
- x = (d - c) / (a - b)
177
- if a * x + c == self(x):
178
- result.append(x)
179
- return list(set(result))
@@ -1,94 +0,0 @@
1
- Metadata-Version: 2.2
2
- Name: mplusa
3
- Version: 0.0.2
4
- Summary: A library for calculations in tropical and arctic semirings.
5
- Author-email: "Maksymilian W." <maksymilian3563@gmail.com>
6
- License: Copyright (c) 2025 Maksymilian Wiekiera
7
-
8
- Permission is hereby granted, free of charge, to any person obtaining a copy
9
- of this software and associated documentation files (the "Software"), to deal
10
- in the Software without restriction, including without limitation the rights
11
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
12
- copies of the Software, and to permit persons to whom the Software is
13
- furnished to do so, subject to the following conditions:
14
-
15
- The above copyright notice and this permission notice shall be included in all
16
- copies or substantial portions of the Software.
17
-
18
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
21
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
22
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
23
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
24
- SOFTWARE.
25
- Project-URL: homepage, https://github.com/Hadelekw/mplusa
26
- Classifier: Programming Language :: Python :: 3
27
- Classifier: Operating System :: OS Independent
28
- Requires-Python: >=3.11
29
- Description-Content-Type: text/markdown
30
- License-File: LICENSE
31
- Requires-Dist: numpy>=2.2.3
32
-
33
- # MPlusA
34
- ---
35
- **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
-
37
- Any improvements or fixes are always welcome.
38
-
39
- ## 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. The list below is a full list of the library's capabilities.
41
-
42
- **`add(*args) -> Real`**
43
- Tropical addition. Essentially an alias for Python's `min` function.
44
-
45
- **`mult(*args) -> Real`**
46
- Tropical multiplication. Essentially an alias for Python's `sum` function.
47
-
48
- **`add_matrices(A : np.ndarray, B : np.ndarray) -> np.ndarray`**
49
- Tropical addition of NumPy arrays. The summed matrices have to be of the same shape.
50
-
51
- **`mult_matrices(A : np.ndarray, B : np.ndarray) -> np.ndarray`**
52
- 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.
53
-
54
- **`modulo(a : Real, t : int) -> Real`**
55
- 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$.
56
-
57
- **`modulo_matrices(A : np.ndarray, b : np.ndarray) -> np.ndarray`**
58
- Tropical modulo operator for NumPy arrays. The input matrices should be of size MxN and Mx1. The result is an MxN matrix.
59
-
60
- **`power(a : real, k : int) -> Real`**
61
- Tropical power operator. Applies the multiplication k times.
62
-
63
- **`power_matrix(A : np.ndarray, k : int) -> np.ndarray`**
64
- Tropical power operator for NumPy arrays. It multiplies the matrix k times.
65
-
66
- **`unit_matrix(width : int, height : int) -> np.ndarray`**
67
- Creates a tropical unit matrix of given width and height.
68
-
69
- **`star(A : np.ndarray) -> np.ndarray`**
70
- Definition of a unique operator of 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.
71
-
72
- **`Polynomial(*coefficients)`**
73
- 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, it also implements function `get_hypersurface` which returns a list of its roots.
74
-
75
- ### Example code
76
- ```
77
- import numpy as np
78
- from mplusa import minplus
79
-
80
- # Basic operators
81
- s = minplus.add(10, 6, 4, 13) # -> 4
82
- p = minplus.mult(10, 5, 8) # -> 23
83
- mod = minplus.modulo(p, s) # -> 3
84
-
85
- # NumPy arrays
86
- A = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
87
- B = np.array([[9, 8, 7], [6, 5, 4], [3, 2, 1]])
88
- S = minplus.add_matrices(A, B) # -> [[1, 2, 3], [4, 5, 4], [3, 2, 1]]
89
- P = minplus.mult_matrices(A, B) # -> [[6, 5, 4], [9, 8, 7], [12, 11, 10]]
90
- ```
91
-
92
- ## Bibliography
93
- 1. A. Obuchowicz, K. A. D'Souza, Z. A. Banaszak. *An Algebraic Approach to Modelling and Performance Optimisation of a Traffic Route System*. International Journal of Applied Mathematics and Computer Science, vol. 8, no. 2, pp. 335-365, June 1998.
94
- 2. D. Speyer, B. Sturmfels. "*Tropical Mathematics*". Mathematics Magazine, vol. 82, no. 3, pp. 163-173, June 2009, doi: https://doi.org/10.4169%2F193009809x468760.
@@ -1,8 +0,0 @@
1
- mplusa/__init__.py,sha256=8D1JvAZfjHkQ1DOqrxLyXWMEfROgGwf8Y41-rSX51cY,44
2
- mplusa/maxplus.py,sha256=UnFh0lfbvarUfDHH7JQpQY5KC0_IP9uzgYYnbOkd3CY,5461
3
- mplusa/minplus.py,sha256=uNsvTNjjlMO4_zuFI5S2z2HP07AKWXnCWOItw2fE5Js,5460
4
- mplusa-0.0.2.dist-info/LICENSE,sha256=x1S-x_tM1tAmndGsdQKT4DU9LnstfQRgS4befak4XdA,1063
5
- mplusa-0.0.2.dist-info/METADATA,sha256=2JhnKWBWTaO2dDThFq7DdlUfbCsLMObmVr2O49qqlsE,5100
6
- mplusa-0.0.2.dist-info/WHEEL,sha256=52BFRY2Up02UkjOa29eZOS2VxUrpPORXg1pkohGGUS8,91
7
- mplusa-0.0.2.dist-info/top_level.txt,sha256=W5b7P8CkZ-DB3-2K0Rcf0T0tpEuWLCbZBaVgrd7FEcM,7
8
- mplusa-0.0.2.dist-info/RECORD,,