matrices.MatrixABC
- class matrices.MatrixABC[source]
Bases:
ABC
,Generic
Abstract base class for 2-dimensional matrix types.
- __init__(*args, **kwargs)[source]
Initialise a new Matrix/FrozenMatrix instance.
- Parameters:
data (MatrixABC[T] | Sequence[T] | Sequence[Sequence[T]]) – The initial data for the matrix. This can be another
MatrixT
instance, a sequence of values, or a sequence of a sequence of values. This argument is required, but you can simply pass an empty sequence (e.g.[]
) to have the matrix filled with default instead.shape (tuple[int, int]) – The shape the matrix should have, as a tuple specifying
(rows, cols)
. This argument is required if data is a flat sequence. If data is a sequence of sequences or anotherMatrixT
, then shape will be inferred if it is not provided, or data will be reshaped to shape if it is provided and doesn’t presently conform to shape.default (T) – A keyword-only argument specifying the default value for matrix cells. This will be used to fill in the value for cells which do not have one assigned, are deleted, newly inserted, etc. It is also used as in evaluating the truthiness of a
MatrixT
(aMatrixT
isTrue
if at least one of its cells’ values is not equal to default). The default argument is required unless data is of typeMatrixT
, in which case it will be inferred if not explicity specified.args (Any)
kwargs (Any)
Methods
__init__
(*args, **kwargs)Initialise a new Matrix/FrozenMatrix instance.
appendcol
(data)Appends a column with values data to the right of the matrix.
appendrow
(data)Appends a row with values data at the bottom of the matrix.
asdict
()Returns the matrix data as a dictionary with coordinates as key.
aslist
(*[, by])Returns the matrix data as a list of lists.
copy
()Returns a copy of the matrix object.
empty
()Returns
False
if at least one value in theflip
(*[, by])Flips a matrix vertically or horizontally.
fliph
()Flips a matrix horizontally (by columns).
flipv
()Flips a matrix vertically (by rows).
foreach
(func, *args, **kwargs)Applies func to each cell in the matrix.
get
(row_or_key[, col])Return an item or submatrix based on row and colum indices.
insertcol
(index, data)Inserts a column with values data before index.
insertrow
(index, data)Inserts a row with values data before index.
items
(*[, by])Returns a list of key--value pairs for all cells in the matrix.
keys
(*[, by])Returns a list of keys for all cells in the matrix.
map
(func, *args, **kwargs)Applies func to each cell in the matrix and stores the return value of func as the new cell value.
matadd
(other)Adds two matrices.
matmul
(other)Multiplies two matrices.
matsub
(other)Subtracts two matrices.
prependcol
(data)Prepends a column with values data to the right of the matrix.
prependrow
(data)Prepends a row with values data at the bottom of the matrix.
removecol
(index)Remove the column at index.
removerow
(index)Removes the row at index.
resize
(rows_or_shape[, cols])Grows or shrinks a matrix.
scaladd
(scalar)Adds scalar to the value of each cell in the matrix.
scalmul
(scalar)Multiplies the value of each cell in the matrix with scalar.
scalsub
(scalar)Subtracts scalar from the value of each cell in the matrix.
submatrix
(rows, cols)Return a submatrix bounded by rows and cells.
swapcols
(a_index, b_index)Swaps the two columns at indices a_index and b_index.
swaprows
(a_index, b_index)Swaps the two rows at indices a_index and b_index.
Transposes the rows and columns of the matrix.
values
(*[, by])Returns a flat list of the matrix's values.
Attributes
Returns the default value for the matrix.
Returns the shape of the matrix.
- __init__(*args, **kwargs)[source]
Initialise a new Matrix/FrozenMatrix instance.
- Parameters:
data (MatrixABC[T] | Sequence[T] | Sequence[Sequence[T]]) – The initial data for the matrix. This can be another
MatrixT
instance, a sequence of values, or a sequence of a sequence of values. This argument is required, but you can simply pass an empty sequence (e.g.[]
) to have the matrix filled with default instead.shape (tuple[int, int]) – The shape the matrix should have, as a tuple specifying
(rows, cols)
. This argument is required if data is a flat sequence. If data is a sequence of sequences or anotherMatrixT
, then shape will be inferred if it is not provided, or data will be reshaped to shape if it is provided and doesn’t presently conform to shape.default (T) – A keyword-only argument specifying the default value for matrix cells. This will be used to fill in the value for cells which do not have one assigned, are deleted, newly inserted, etc. It is also used as in evaluating the truthiness of a
MatrixT
(aMatrixT
isTrue
if at least one of its cells’ values is not equal to default). The default argument is required unless data is of typeMatrixT
, in which case it will be inferred if not explicity specified.args (Any)
kwargs (Any)
- appendcol(data)[source]
Appends a column with values data to the right of the matrix.
This is equivalent to
m.insertcol(len(m), data)
.data must be a sequence with length at least matching the number of rows in the matrix. Unused values will be ignored.
Modifies the matrix in-situ and returns self if the matrix is mutable, otherwise returns an expanded copy of the matrix.
- Parameters:
data (
Sequence
[~T
]) – The data to be inserted into the new column.- Return type:
Self
- Returns:
its own
Matrix
instance if mutable, a copy of theFrozenMatrix
instance if immutable.
- appendrow(data)[source]
Appends a row with values data at the bottom of the matrix.
This is equivalent to
m.insertrow(len(m), data)
.data must be a sequence with length at least matching the number of columns in the matrix. Unused values will be ignored.
Modifies the matrix in-situ and returns self if the matrix is mutable, otherwise returns an expanded copy of the matrix.
- Parameters:
data (
Sequence
[~T
]) – The data to be inserted into the new row.- Return type:
Self
- Returns:
its own
Matrix
instance if mutable, a copy of theFrozenMatrix
instance if immutable.
- asdict()[source]
Returns the matrix data as a dictionary with coordinates as key.
The returned dictionary’s keys are tuples of the form
(row, column)
.For example, the matrix:
0 1 2 ┌ ┐ 0 │ 1 2 3 │ 1 │ 4 5 6 │ └ ┘
will be returned as a dict of the form:
{ (0, 0): 1, (0, 1): 2, (0, 2): 3, (1, 0): 4, (1, 1): 5, (1, 2): 6 }
- Return type:
dict
[tuple
[int
,int
],~T
]- Returns:
A dictionary with coordinates as keys and cell values as values.
- aslist(*, by='row')[source]
Returns the matrix data as a list of lists.
If by is
"row"
(the default), then the returned list of lists is in the format rows[columns]. If by is"col"
then the returned list is in the format columns[rows].For example, the matrix:
0 1 2 ┌ ┐ 0 │ 1 2 3 │ 1 │ 4 5 6 │ └ ┘
will be returned as a list of the form:
[ [1, 2, 3], [4, 5, 6] ]
Note that this is different from invoking
list(m)
on a matrix, which does not return a list of list with the matrix’s values, but rather a list of(row, col)
index pairs for each cell, equivalent to callingkeys()
on a matrix object.- Parameters:
by (
Union
[Literal
['row'
],Literal
['col'
]]) – Specifies whether to build the list row-wise or column-wise.- Return type:
list
[list
[~T
]]- Returns:
A list containing one list for each row/column, depending on the direction indicated by the by argument.
- abstract flip(*, by='row')[source]
Flips a matrix vertically or horizontally.
Effectively reverses the order of the matrix’s rows or columns.
Whether the flipping is applied to the rows or columns is specified by the keyword-only argument by. The default is
"row"
, which flips the matrix vertically.m.flip()
andm.flip(by="row")
are equivalent tom.flipv()
.m.flip(by="column")
is equivalent tom.fliph()
.- Parameters:
by (
Union
[Literal
['row'
],Literal
['col'
]]) – Whether to flop row-wise or column-wise, must be one of the literal strings"row"
(the default) or"col"
.- Return type:
Self
- Returns:
its own
Matrix
instance if mutable, a copy of theFrozenMatrix
instance if immutable.
- fliph()[source]
Flips a matrix horizontally (by columns).
This effectively reverses the order of the columns of the matrix.
This has the effect of turning a matrix such as:
0 1 2 ┌ ┐ 0 │ 1 2 3 │ 1 │ 4 5 6 │ └ ┘
into the matrix:
0 1 2 ┌ ┐ 0 │ 3 2 1 │ 1 │ 6 5 4 │ └ ┘
Modifies the matrix in-situ if the matrix is mutable, otherwise returns a copy of the matrix with the order of columns reversed.
- Return type:
Self
- Returns:
its own
Matrix
instance if mutable, a copy of theFrozenMatrix
instance if immutable.
- flipv()[source]
Flips a matrix vertically (by rows).
This effectively reverses the order of the rows of the matrix.
This has the effect of turning a matrix such as:
0 1 2 ┌ ┐ 0 │ 1 2 3 │ 1 │ 4 5 6 │ 2 │ 7 8 9 │ └ ┘
into the matrix:
0 1 2 ┌ ┐ 0 │ 7 8 9 │ 1 │ 4 5 6 │ 2 │ 1 2 3 │ └ ┘
Modifies the matrix in-situ if the matrix is mutable, otherwise returns a copy of the matrix with the order of rows reversed.
- Return type:
Self
- Returns:
its own
Matrix
instance if mutable, a copy of theFrozenMatrix
instance if immutable.
- foreach(func, *args, **kwargs)[source]
Applies func to each cell in the matrix.
Any additional args or kwargs passed after func will be passed as arguments to func.
The return value of func will be ignored. To mutate the values of each cell in-situ based on the return value, use
map()
instead.- Example:
>>> print(m) ┌ ┐ │ 1 2 3 │ │ 4 5 6 │ └ ┘ >>> m.foreach(lambda a: print(a**2, end=", ")) 1, 4, 9, 16, 25, 36,
- Parameters:
func (
Callable
[…,~V
]) – A callable accepting at least one argument (namely the value of each cell as the matrix is being iterated over).args (Any)
kwargs (Any)
- Return type:
Union
[Self
,MatrixABC
[~V
]]- Returns:
its own
Matrix
instance or a copy of theFrozenMatrix
instance.
- get(row_or_key, col=None)[source]
Return an item or submatrix based on row and colum indices.
Can be invoked as either
get((row, col))
orget(row, col)
.Returns the value of a cell if both rows and cols are integers which together reference a unique cell. Returns a submatrix if either rows, cols or both are slice objects or tuples of integers with several row/column indices.
- Parameters:
row_or_key (
Union
[slice
,int
,tuple
[int
, …],tuple
[Union
[slice
,int
,tuple
[int
, …]],Union
[slice
,int
,tuple
[int
, …]]]]) – The row index or row indices (as a tuple or slice) of the row(s) to be returned, or a tuple with(row, col)
argument values if col is omitted.col (
Union
[slice
,int
,tuple
[int
, …],None
]) – The column index or column indices (as a tuple or slice) of the column(s) to be returned.
- Return type:
Union
[~T
,Self
]- Returns:
The value of the matrix cell if both row and col are integers refering to a single cell, otherwise a submatrix covering the are selected by row and col.
- abstract insertcol(index, data)[source]
Inserts a column with values data before index.
data must be a sequence with length at least matching the number of rows in the matrix. Unused values will be ignored.
Modifies the matrix in-situ if the matrix is mutable, otherwise returns an expanded copy of the matrix.
- Parameters:
index (
int
) – The colmn index before which the new column should be inserted.data (
Sequence
[~T
]) – The data to be inserted into the new column.
- Return type:
Self
- Returns:
its own
Matrix
instance or a copy of theFrozenMatrix
instance.
- abstract insertrow(index, data)[source]
Inserts a row with values data before index.
data must be a sequence with length at least matching the number of columns in the matrix. Unused values will be ignored.
Modifies the matrix in-situ if the matrix is mutable, otherwise returns an expanded copy of the matrix.
- Parameters:
index (
int
) – The row index before which the new row should be inserted.data (
Sequence
[~T
]) – The data to be inserted into the new row.
- Return type:
Self
- Returns:
its own
Matrix
instance or a copy of theFrozenMatrix
instance.
- items(*, by='row')[source]
Returns a list of key–value pairs for all cells in the matrix.
Each item in the returned list is a tuple of the form
((row, col), value)
.This is useful for iteration over a matrix where the row and column indices should be kept track of. For example, if the row and column index don’t need to be unpacked
>>> m = Matrix([[1, 2], [3, 4]], default=0) >>> for key, value in m.items(): ... print(f"{key}: {value}") ... (0, 0): 1 (0, 1): 2 (1, 0): 3 (1, 1): 4
If the row and key values should be unpacked this can be achieved by further tuple unpacking
>>> for (row, col), val in m.items(): ... print(f"{row}, {col}: {val}") ... 0, 0: 1 0, 1: 2 1, 0: 3 1, 1: 4
- Parameters:
by (
Union
[Literal
['row'
],Literal
['col'
]]) – The direction in which the matrix values should be serialised into a flat sequence, row-wise or column-wise.- Return type:
list
[tuple
[tuple
[int
,int
],~T
]]- Returns:
A list with pairs of the matrix’s keys and corresponding values.
- keys(*, by='row')[source]
Returns a list of keys for all cells in the matrix.
The list contains tuples with the coordinates in the form
(row, col)
. These are sorted by row first if by is set to"row"
(the default), and they are sorted by column first if by is set to"col"
.- Parameters:
by (
Union
[Literal
['row'
],Literal
['col'
]]) – Whether to sort the keys row-wise or column-wise.- Return type:
list
[tuple
[int
,int
]]- Returns:
A list of tuples with coordinates for each cell, sorted as indicated by the by argument.
- abstract map(func, *args, **kwargs)[source]
Applies func to each cell in the matrix and stores the return value of func as the new cell value.
Any additional args or kwargs passed after func will be passed as parameters to func.
This will mutate the values of each cell in-situ based on the return value of func. To apply func without affecting the values store in the matrix, use
foreach()
instead.Returns the original matrix with func applied in-situ if the matrix is mutable, otherwise returns a copy of the matrix with func applied.
- Example:
>>> m = Matrix([[1, 2, 3], [4, 5, 6]], default=0) >>> print(m) 0 1 2 ┌ ┐ 0 │ 1 2 3 │ 1 │ 4 5 6 │ └ ┘ >>> print(m.map(lambda a: a**2)) 0 1 2 ┌ ┐ 0 │ 1 4 9 │ 1 │ 16 25 36 │ └ ┘
- Parameters:
func (
Callable
[…,~V
]) – A callable accepting at least one argument (namely the value of each cell as the matrix is being iterated over).args (Any) – Additional positional arguments to be passed to func.
kwargs (Any) – Additional keyword arguments to be passed to func.
- Return type:
Union
[Self
,MatrixABC
[~V
]]- Returns:
its own
Matrix
instance if mutable, a copy of theFrozenMatrix
instance if immutable.
- matadd(other)[source]
Adds two matrices.
The other matrix must have the same shape as the matrix to which it is added.
Returns a new matrix of the same shape as the original matrix.
- Parameters:
other (
MatrixABC
[~V
]) – TheMatrix
orFrozenMatrix
to be added to this one.- Return type:
Union
[Self
,MatrixABC
[~V
]]- Returns:
a copy of the
Matrix
orFrozenMatrix
instance with other added.
- matmul(other)[source]
Multiplies two matrices.
The other matrix’s shape must be the inverse of the matrix to which it applies. For example, if we have a matrix of shape (2, 3), it can only be multiplied with a matrix of the shape (3, 2).
Returns a new matrix of shape (k, n), where k is the number of rows of the original matrix and n is the number of columns of the other matrix.
- Parameters:
other (
MatrixABC
[~V
]) – TheMatrix
orFrozenMatrix
to be multiplied with this one.- Return type:
Union
[Self
,MatrixABC
[~V
]]- Returns:
a copy of the
Matrix
orFrozenMatrix
instance with other multiplied into it.
- matsub(other)[source]
Subtracts two matrices.
The other matrix must have the same shape as the matrix from which it is subtracted.
Returns a new matrix of the same shape as the original matrix.
- Parameters:
other (
MatrixABC
[~V
]) – TheMatrix
orFrozenMatrix
to be subtracted from this one.- Return type:
Union
[Self
,MatrixABC
[~V
]]- Returns:
a copy of the
Matrix
orFrozenMatrix
instance with other subtracted.
- prependcol(data)[source]
Prepends a column with values data to the right of the matrix.
This is equivalent to
m.insertcol(0, data)
.data must be a sequence with length at least matching the number of columns in the matrix. Unused values will be ignored.
Modifies the matrix in-situ if the matrix is mutable, otherwise returns an expanded copy of the matrix.
- Parameters:
data (
Sequence
[~T
]) – The data to be inserted into the new column.- Return type:
Self
- Returns:
its own
Matrix
instance or a copy of theFrozenMatrix
instance.
- prependrow(data)[source]
Prepends a row with values data at the bottom of the matrix.
This is equivalent to
m.insertrow(0, data)
.data must be a sequence with length at least matching the number of rows in the matrix. Unused values will be ignored.
Modifies the matrix in-situ if the matrix is mutable, otherwise returns an expanded copy of the matrix.
- Parameters:
data (
Sequence
[~T
]) – The data to be inserted into the new row.- Return type:
Self
- Returns:
its own
Matrix
instance or a copy of theFrozenMatrix
instance.
- abstract removecol(index)[source]
Remove the column at index.
Caution
The column is removed completely from the matrix, and the matrix’s shape will be altered. Calling this function does not merely reset the values of items in the targeted column to their default!
- Parameters:
index (
int
) – The index of the column to be removed.- Return type:
Self
- Returns:
its own
Matrix
instance if mutable, a copy of theFrozenMatrix
instance if immutable.
- abstract removerow(index)[source]
Removes the row at index.
Caution
The row is removed completely from the matrix, and the matrix’s shape will be altered. Calling this function does not merely reset the values of items in the targeted row to their default!
- Parameters:
index (
int
) – The index of the row to be removed.- Return type:
Self
- Returns:
its own
Matrix
instance if mutable, a copy of theFrozenMatrix
instance if immutable.
- abstract resize(rows_or_shape, cols=None)[source]
Grows or shrinks a matrix.
Grows or shrinks a matrix depending on whether the new shape supplied is greater or smaller in any dimension; does nothing if the new shape is identical to the original shape.
Where the new shape adds new rows or columns, the new cells are populated by the matrix’s default value.
Where the new shape removes rows or columns, the values of the removed cells will be lost.
Modifies the matrix in-situ if it is mutable, otherwise returns a resized copy of the matrix.
Can be called either with the positional-only argument shape as
- resize(shape: tuple[int, int]) Self [source]
- Parameters:
rows_or_shape (int | tuple[int, int])
cols (int | None)
- Return type:
Self
or with two integer arguments for rows and cols as
- resize(rows: int, cols: int) Self [source]
- Parameters:
rows_or_shape (int | tuple[int, int])
cols (int | None)
- Return type:
Self
- Parameters:
shape (tuple[int, int]) – A tuple with the sizes for (rows, columns) that the resized matrix should have.
rows – The number of rows the resized matrix should have.
cols (
Optional
[int
]) – The number of columns the resized matrix should have.rows_or_shape (int | tuple[int, int])
- Return type:
Self
- Returns:
its own
Matrix
instance or a copy of theFrozenMatrix
instance.
- scaladd(scalar)[source]
Adds scalar to the value of each cell in the matrix.
Returns a copy of the matrix with the scalar addition applied.
- Parameters:
scalar (
~V
) – The scalar to be added to each cell’s value.- Return type:
Union
[Self
,MatrixABC
[~V
]]- Returns:
a copy of the
Matrix
orFrozenMatrix
instance with scalar added to its cell values.
- scalmul(scalar)[source]
Multiplies the value of each cell in the matrix with scalar.
Returns a copy of the matrix with the scalar multiplication applied.
- Parameters:
scalar (
~V
) – The scalar to be subtracted from each cell’s value.- Return type:
Union
[Self
,MatrixABC
[~V
]]- Returns:
a copy of the
Matrix
orFrozenMatrix
instance with scalar multiplied into each cell’s values.
- scalsub(scalar)[source]
Subtracts scalar from the value of each cell in the matrix.
Returns a copy of the matrix with the scalar subtraction applied.
- Parameters:
scalar (
~V
) – The scalar to be subtracted from each cell’s value.- Return type:
Union
[Self
,MatrixABC
[~V
]]- Returns:
a copy of the
Matrix
orFrozenMatrix
instance with scalar subtracted from its cell values.
- submatrix(rows, cols)[source]
Return a submatrix bounded by rows and cells.
- Return type:
Self
- Parameters:
rows (matrices._types.IndexT)
cols (matrices._types.IndexT)
- abstract swapcols(a_index, b_index)[source]
Swaps the two columns at indices a_index and b_index.
Modifies the matrix in-situ if the matrix is mutable, otherwise returns a copy with the two columns swapped.
- Parameters:
a_index (
int
) – The index of the first column to be swapped.b_index (
int
) – The index of the second column, which a_index should be swapped with.
- Return type:
Self
- Returns:
its own
Matrix
instance or a copy of theFrozenMatrix
instance.
- abstract swaprows(a_index, b_index)[source]
Swaps the two rows at indices a_index and b_index.
Modifies the matrix in-situ if the matrix is mutable, otherwise returns a copy with the two rows swapped.
- Parameters:
a_index (
int
) – The index of the first row to be swapped.b_index (
int
) – The index of the second row, which a_index should be swapped with.
- Return type:
Self
- Returns:
its own
Matrix
instance or a copy of theFrozenMatrix
instance.
- abstract transpose()[source]
Transposes the rows and columns of the matrix.
This has the effect of turning a matrix such as:
0 1 2 ┌ ┐ 0 │ 1 2 3 │ 1 │ 4 5 6 │ └ ┘
into the matrix:
0 1 ┌ ┐ 0 │ 1 4 │ 1 │ 2 5 │ 2 │ 3 6 │ └ ┘
Modifies the matrix in-situ if it is mutable, otherwise returns a transposed copy of the matrix.
- Return type:
Self
- Returns:
its own
Matrix
instance if mutable, a copy of theFrozenMatrix
instance if immutable.
- values(*, by='row')[source]
Returns a flat list of the matrix’s values.
By default, the returned list will be sequenced row by row. For example, the matrix:
0 1 2 ┌ ┐ 0 │ 1 2 3 │ 1 │ 4 5 6 │ └ ┘
will be returned as the list:
[1, 2, 3, 4, 5, 6]
This behaviour can be modified by passing the literal
"column"
as the keyword-only argument by, such thatm.values(by="column")
would return:[1, 4, 2, 5, 3, 6]
- Parameters:
by (
Union
[Literal
['row'
],Literal
['col'
]]) – The direction in which the matrix values should be serialised into a flat sequence, row-wise or column-wise.- Return type:
list
[~T
]- Returns:
A list with the matrix’s values.
- property default: T
Returns the default value for the matrix.
- Return type:
~T
- property shape: tuple[int, int]
Returns the shape of the matrix.
- Return type:
tuple
[int
,int
]