Skip to content

matrix.py

Helper methods for working with matrices.

To create matrices:

from pymwp.matrix import init_matrix, identity_matrix

To compute matrix sum and product:

from pymwp.matrix import matrix_prod, matrix_sum

Other utility methods:

from pymwp.matrix import equals, fixpoint, show, resize, encode, decode

decode(matrix)

Converts matrix of dictionaries to a matrix of polynomials.

Primary use case of this function is for restoring a matrix of polynomials from a file (assuming encode was used to generate that file).

Parameters:

Name Type Description Default
matrix List[List[List[dict]]]

matrix to decode

required

Raises:

Type Description
TypeError

If the matrix value is not iterable

AttributeError

If the matrix elements are not valid encoded polynomials.

Returns:

Type Description
List[List[Polynomial]]

Decoded matrix of polynomials.

Source code in pymwp/matrix.py
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
def decode(matrix: List[List[List[dict]]]) -> List[List[Polynomial]]:
    """Converts matrix of dictionaries to a matrix of polynomials.

    Primary use case of this function is for restoring a matrix of
     polynomials from a file (assuming [encode](matrix.md#pymwp.matrix.encode)
     was used to generate that file).

    Arguments:
        matrix: matrix to decode

    Raises:
        TypeError: If the matrix value is not iterable
        AttributeError: If the matrix elements are not
            valid encoded polynomials.

    Returns:
        Decoded matrix of polynomials.
    """
    return [[
        Polynomial(*[Monomial(
            scalar=monomial["scalar"],
            deltas=monomial["deltas"])
            for monomial in polynomial])
        for polynomial in row]
        for (i, row) in enumerate(matrix)]

encode(matrix)

Converts a matrix of polynomials to a matrix of dictionaries.

This function is useful when preparing to write a matrix of polynomials to a file. The same matrix can later be restored using matrix decode.

Parameters:

Name Type Description Default
matrix List[List[Polynomial]]

matrix to encode

required

Raises:

Type Description
AttributeError

If the matrix does not contain polynomials.

Returns:

Type Description
List[List[List[dict]]]

Encoded matrix.

Source code in pymwp/matrix.py
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
def encode(matrix: List[List[Polynomial]]) -> List[List[List[dict]]]:
    """Converts a matrix of polynomials to a matrix of dictionaries.

    This function is useful when preparing to write a matrix of polynomials to
    a file. The same matrix can later be restored using matrix
    [decode](matrix.md#pymwp.matrix.decode).

    Arguments:
        matrix: matrix to encode

    Raises:
        AttributeError: If the matrix does not contain polynomials.

    Returns:
        Encoded matrix.
    """
    return [[
        [mono.to_dict() for mono in polynomial.list]
        for polynomial in row]
        for (i, row) in enumerate(matrix)]

equals(matrix1, matrix2)

Determine if two matrices are equal.

This function performs element-wise equality comparisons on values of two matrices. The two matrices must be the same size. For any two matrices of different size the result is always False.

This function can evaluate values that are comparable by equals == operator.

Parameters:

Name Type Description Default
matrix1 List[List[Any]]

first matrix.

required
matrix2 List[List[Any]]

second matrix.

required

Raises:

Type Description
TypeError

If the matrix value is not iterable

Returns:

Type Description
bool

True if matrices are equal element-wise and False otherwise.

Source code in pymwp/matrix.py
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
def equals(matrix1: List[List[Any]], matrix2: List[List[Any]]) -> bool:
    """Determine if two matrices are equal.

    This function performs element-wise equality comparisons on values of
    two matrices. The two matrices must be the same size. For any two matrices
    of different size the result is always `False`.

    This function can evaluate values that are comparable by equals `==`
    operator.

    Arguments:
        matrix1: first matrix.
        matrix2: second matrix.

    Raises:
        TypeError: If the matrix value is not iterable

    Returns:
        `True` if matrices are equal element-wise and `False` otherwise.
    """
    # equal size
    if [len(row) for row in matrix1] != [len(row) for row in matrix2]:
        return False

    # element-wise comparison
    for row_index, column in enumerate(matrix1):
        for col_index, value in enumerate(column):
            if matrix2[row_index][col_index] != value:
                return False

    return True

fixpoint(matrix)

Computes the star operation \(1 + M + M^2 + M^3 + …\)

This function assumes provided input is a square matrix.

Parameters:

Name Type Description Default
matrix List[List[Any]]

for which to compute fixpoint

required

Returns:

Type Description
List[List[Any]]

\(M^*\)

Source code in pymwp/matrix.py
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
def fixpoint(matrix: List[List[Any]]) -> List[List[Any]]:
    """Computes the star operation $1 + M + M^2 + M^3 + …$

    This function assumes provided input is a square matrix.

    Arguments:
        matrix: for which to compute fixpoint

    Returns:
        $M^*$
    """
    _1_ = identity_matrix(len(matrix))
    previous = matrix
    next_matrix = matrix
    result = matrix_sum(_1_, matrix)

    while not equals(previous, result):
        previous = result
        next_matrix = matrix_prod(next_matrix, matrix)  # M^2, M^3, M^4....
        result = matrix_sum(result, next_matrix)

    return result

identity_matrix(size)

Create identity matrix of specified size.

Example:

Generate 5 x 5 size identity matrix:

identity_matrix(5)

# generates:
#
# [[+m, +o, +o, +o, +o],
#  [+o, +m, +o, +o, +o],
#  [+o, +o, +m, +o, +o],
#  [+o, +o, +o, +m, +o],
#  [+o, +o, +o, +o, +m]]

Parameters:

Name Type Description Default
size int

matrix size

required

Returns:

Type Description
List[list]

New identity matrix.

Source code in pymwp/matrix.py
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
def identity_matrix(size: int) -> List[list]:
    """Create identity matrix of specified size.

    Example:

    Generate 5 x 5 size identity matrix:

    ```python
    identity_matrix(5)

    # generates:
    #
    # [[+m, +o, +o, +o, +o],
    #  [+o, +m, +o, +o, +o],
    #  [+o, +o, +m, +o, +o],
    #  [+o, +o, +o, +m, +o],
    #  [+o, +o, +o, +o, +m]]
    ```

    Arguments:
        size: matrix size

    Returns:
        New identity matrix.
    """
    return [[UNIT if i == j else ZERO
             for j in range(size)] for i in range(size)]

init_matrix(size, init_value=None)

Create empty matrix of specified size.

Example:

Generate 5 x 5 size zero-matrix

init_matrix(5)

# generates:
#
# [[+o, +o, +o, +o, +o],
#  [+o, +o, +o, +o, +o],
#  [+o, +o, +o, +o, +o],
#  [+o, +o, +o, +o, +o],
#  [+o, +o, +o, +o, +o]]

Parameters:

Name Type Description Default
size int

matrix size

required
init_value Optional[Any]

value to place at each index. If not provided, will default to 0-polynomial.

None

Returns:

Type Description
List[list]

Initialized matrix.

Source code in pymwp/matrix.py
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
def init_matrix(size: int, init_value: Optional[Any] = None) -> List[list]:
    """Create empty matrix of specified size.

    Example:

    Generate 5 x 5 size zero-matrix

    ```python
    init_matrix(5)

    # generates:
    #
    # [[+o, +o, +o, +o, +o],
    #  [+o, +o, +o, +o, +o],
    #  [+o, +o, +o, +o, +o],
    #  [+o, +o, +o, +o, +o],
    #  [+o, +o, +o, +o, +o]]
    ```

    Arguments:
        size: matrix size
        init_value: value to place at each index. If not provided,
            will default to 0-polynomial.

    Returns:
        Initialized matrix.
    """
    value = init_value if init_value is not None else ZERO
    return [[value for _ in range(size)] for _ in range(size)]

matrix_prod(matrix1, matrix2)

Compute the product of two polynomial matrices.

Parameters:

Name Type Description Default
matrix1 List[List[Polynomial]]

first polynomial matrix.

required
matrix2 List[List[Polynomial]]

second polynomial matrix.

required

Returns:

Type Description
List[List[Polynomial]]

new matrix that represents the product of the two inputs.

Source code in pymwp/matrix.py
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
def matrix_prod(
        matrix1: List[List[Polynomial]], matrix2: List[List[Polynomial]]
) -> List[List[Polynomial]]:
    """Compute the product of two polynomial matrices.

    Arguments:
        matrix1: first polynomial matrix.
        matrix2: second polynomial matrix.

    Returns:
        new matrix that represents the product of the two inputs.
    """

    return [[

        reduce(lambda total, k:
               total + (matrix1[i][k] * matrix2[k][j]),
               range(len(matrix1)), ZERO)

        for j in range(len(matrix2))]
        for i in range(len(matrix1))]

matrix_sum(matrix1, matrix2)

Compute the sum of two matrices.

Parameters:

Name Type Description Default
matrix1 List[List[Any]]

first matrix.

required
matrix2 List[List[Any]]

second matrix.

required

Returns:

Type Description
List[List[Any]]

new matrix that represents the sum of the two inputs.

Source code in pymwp/matrix.py
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
def matrix_sum(
        matrix1: List[List[Any]], matrix2: List[List[Any]]
) -> List[List[Any]]:
    """Compute the sum of two matrices.

    Arguments:
        matrix1: first matrix.
        matrix2: second matrix.

    Returns:
        new matrix that represents the sum of the two inputs.
    """

    return [[matrix1[i][j] + matrix2[i][j]
             for j in range(len(matrix1))]
            for i in range(len(matrix1))]

resize(matrix, new_size)

Create a new matrix of polynomials of specified size.

The resized matrix is initialized as an identity matrix then filled with values from the original matrix.

Parameters:

Name Type Description Default
matrix List[List[Polynomial]]

original matrix

required
new_size int

width/height of new matrix

required

Returns:

Type Description
List[List[Polynomial]]

New matrix of specified size, filled with values from the original matrix.

Source code in pymwp/matrix.py
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
def resize(matrix: List[List[Polynomial]], new_size: int) \
        -> List[List[Polynomial]]:
    """Create a new matrix of polynomials of specified size.

    The resized matrix is initialized as an identity matrix
    then filled with values from the original matrix.

    Arguments:
        matrix: original matrix
        new_size: width/height of new matrix

    Returns:
        New matrix of specified size, filled with values from
            the original matrix.
    """

    res = identity_matrix(new_size)
    bound = min(new_size, len(matrix))

    for i in range(bound):
        for j in range(bound):
            res[i][j] = matrix[i][j]
    return res

show(matrix, **kwargs)

Pretty print a matrix at the screen.

Using the keyword arguments it is possible display additional text before or after the matrix.

Example:

Display matrix only:

my_matrix = identity_matrix(3)
show(my_matrix)

# displays:
#
# ['  +m', '  +o', '  +o']
# ['  +o', '  +m', '  +o']
# ['  +o', '  +o', '  +m']

Display matrix and some extra text before it

my_matrix = identity_matrix(3)
header = '|   x1   |   x2  |  x3 |'
show(my_matrix, prefix=header)

# displays:
#
# |   x1   |   x2  |  x3 |
# ['  +m', '  +o', '  +o']
# ['  +o', '  +m', '  +o']
# ['  +o', '  +o', '  +m']

Parameters:

Name Type Description Default
matrix List[List[Any]]

the matrix to display.

required

Kwargs:

  • prefix (str): display some text before displaying matrix
  • postfix (str): display some text after displaying matrix

Raises:

Type Description
TypeError

If the matrix is not iterable (type list of lists)

Source code in pymwp/matrix.py
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
def show(matrix: List[List[Any]], **kwargs) -> None:
    """Pretty print a matrix at the screen.

    Using the keyword arguments it is possible display additional text
    before or after the matrix.

    Example:

    Display matrix only:

    ```python
    my_matrix = identity_matrix(3)
    show(my_matrix)

    # displays:
    #
    # ['  +m', '  +o', '  +o']
    # ['  +o', '  +m', '  +o']
    # ['  +o', '  +o', '  +m']
    ```

    Display matrix and some extra text before it

    ```python
    my_matrix = identity_matrix(3)
    header = '|   x1   |   x2  |  x3 |'
    show(my_matrix, prefix=header)

    # displays:
    #
    # |   x1   |   x2  |  x3 |
    # ['  +m', '  +o', '  +o']
    # ['  +o', '  +m', '  +o']
    # ['  +o', '  +o', '  +m']
    ```

    Arguments:
        matrix: the matrix to display.

    Kwargs:

    - `prefix` (`str`): display some text before displaying matrix
    - `postfix` (`str`): display some text after displaying matrix

    Raises:
        TypeError: If the matrix is not iterable (type list of lists)
    """
    if 'prefix' in kwargs:
        print(kwargs['prefix'])
    for row in matrix:
        print([str(r) for r in row])
    if 'postfix' in kwargs:
        print(kwargs['postfix'])
    print(' ')