cereja.array
Copyright (c) 2019 The Cereja Project
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
- class cereja.array.Matrix(values)[source]
Bases:
objectMatrix manipulation tool similar to numpy array.
This class provides basic linear algebra and matrix operations, including arithmetic operations, dot product, reshape and determinant calculation.
- Parameters:
values – Sequence of values to initialize the matrix. Can be a nested list, tuple, or any iterable sequence.
- shape
Tuple representing the matrix dimensions.
Examples
>>> m = Matrix([[1, 2], [3, 4]]) >>> m.shape (2, 2) >>> m.mean() 2.5
- static arange(*args)[source]
Create a matrix from a numeric range.
- Parameters:
*args – Arguments passed to range() (start, stop, step).
- Returns:
New Matrix with sequential values.
Examples
>>> Matrix.arange(5) Matrix([0, 1, 2, 3, 4]) >>> Matrix.arange(1, 10, 2) Matrix([1, 3, 5, 7, 9])
- argmax()[source]
Return the index of the maximum value in the flattened matrix.
- Returns:
Index of the maximum element.
- property cols
Return the matrix columns.
For one-dimensional matrices, returns the values list itself. For multi-dimensional matrices, computes and caches the columns.
- copy()[source]
Create a shallow copy of the matrix.
- Returns:
New Matrix instance with the same values.
- determinant()[source]
Compute the matrix determinant.
- Returns:
Numeric value of the determinant.
- Raises:
ValueError – If the matrix is not square.
- dot(other)[source]
Compute the dot product with another matrix.
- Parameters:
other – Matrix or sequence for multiplication.
- Returns:
New Matrix resulting from the dot product.
- Raises:
ValueError – If the dimensions are not compatible.
- flatten()[source]
Return a flattened (1D) version of the matrix.
- Returns:
New one-dimensional Matrix.
- reshape(shape)[source]
Reshape the matrix to a new form.
- Parameters:
shape (
Tuple[int,...]) – Tuple with the new dimensions.- Returns:
New Matrix with the specified shape.
- Raises:
ValueError – If the total number of elements is not compatible.
- property shape
Return the shape (dimensions) of the matrix.
- sqrt()[source]
Compute the square root of each element.
- Returns:
New Matrix with square roots.
- Raises:
ValueError – If there are negative values.
- std()[source]
Compute the population standard deviation.
- Returns:
Standard deviation of the elements.
- to_list()[source]
Convert the matrix to a native Python list.
- Returns:
List with the matrix values.
- property values
Return the internal matrix values.
- cereja.array.apply_proportional_mask(positions, mask_size, original_size=None)[source]
Applies a proportional mask to a list of positions and returns an array (list of lists) representing the mask, where each index of the main list corresponds to a row.
- Parameters:
positions (List[Tuple[int, int]]) – List of tuples representing positions (x, y) on the original scale.
mask_size (Tuple[int, int]) – Mask size (columns, rows), where columns is the number of columns and rows is the number of rows.
original_size (Optional[Tuple[int, int]]) – Original image size (width, height). If not provided, it will be calculated based on positions.
- Returns:
Matrix resulting from the proportional application of the mask, where each index represents a row.
- Return type:
List[List[int]]
- cereja.array.array_gen(shape, v=None)[source]
Generates array based on passed shape
e.g: >>> array_gen(shape=(2, 2, 3)) [[[0.0, 0.0, 0.0], [0.0, 0.0, 0.0]], [[0.0, 0.0, 0.0], [0.0, 0.0, 0.0]]]
>>>array_gen(shape=(1, 3, 2, 1, 1)) [[[[[0.0]], [[0.0]]], [[[0.0]], [[0.0]]], [[[0.0]], [[0.0]]]]]
>>> array_gen(shape=(2, 1, 1),v=['hail','pythonics!']) [[['hail']], [['pythonics!']]]
>>> shape = (2, 1, 1) >>> array_gen(shape, v = flatten(array_randn(shape))) [[[0.43022826643029777]], [[0.5697717335697022]]]
- Parameters:
shape (
Tuple[int,...]) – it’s the shape of arrayv (
Union[Sequence[Any],Any]) – sequence or Any obj that allows insertion of values
- Return type:
List[Union[float,Any]]- Returns:
Sequence -> List[Union[float, Any]]
- cereja.array.array_randn(shape, *args, **kwargs)[source]
Responsible for creating matrix in the requested form. All values are random and their sum is equal to 1 ( default) or the value sent in parameter (to)
- Parameters:
shape (
Tuple[int,...]) – it’s the shape of arrayargs – Arguments that will be passed on to the auxiliary function rand_n: _from: Number = 0., to: Number = 1., n: int = 1
- Return type:
List[Union[float,Any]]- Returns:
array with shape that you _requests
e.g:
>>> array = array_randn((1,2,3,4)) [[[[0.2592981659911938, -0.12315716616964649, 0.82133729291841, -0.25879078816834644], [1.3629594254754838, -3.774314741021747, 5.274492839788345, -11.601343746754297], [3.604096666087614, -27.650903465459855, 19.296830893462964, -58.83686412036615]], [[69.41859240028415, -179.33687885859996, 361.42747499197384, -610.1513132786013], [1072.0398936663296, -894.6318240273097, 1448.8891836211283, -4183.174313279926], [8139.152167926057, -12466.659181206918, 24595.19100297986, -17279.53844619006]]]]
>>>sum(flatten(array)) 1.0
>>> cj_randn = array_randn((4,4), _from = 0, to = 20) [[10.290409563999265, -10.551079712904698, 2.901380773471479, -27.545318358270105], [11.611327651418236, -29.461575728235626, 108.82486378444688, -72.92672196142121], [166.27689950355855, -400.36353360213354, 575.2273799798464, -1362.4824677079241], [2689.652915457324, -4310.834087972777, 4834.662753875761, -2165.28314554616]]
>>> sum(flatten(cj_randn)) 20.0
- cereja.array.determinant(sequence)[source]
Calculate the determinant of a square matrix.
This function is inteded specifically for use with an (nxn) martix and may reject non-square matricies
- cereja.array.flatten(sequence, depth=-1, return_shapes=False, **kwargs)[source]
Flattens arrays of values regardless of their shape and depth.
This function recursively flattens nested sequences to a specified depth level, with support for various sequence types including lists, tuples, sets, and custom objects with ‘tolist’ or ‘to_list’ methods (like numpy arrays or Matrix objects).
- Parameters:
sequence (
Union[Sequence[Any],Matrix]) – The sequence of values to be flattened. Can be a nested list, tuple, set, Matrix object, or any object with ‘tolist’/’to_list’ methods.depth (
Optional[int]) – Maximum flattening depth. -1 means completely flatten (default). A value of 0 returns the original sequence, 1 flattens one level, etc.return_shapes – If True, returns a tuple containing both the flattened array and a dictionary mapping depth levels to the shapes at each level.
**kwargs – Additional keyword arguments. Supports ‘max_recursion’ as an alias for the depth parameter.
- Returns:
- If return_shapes
is False, returns the flattened list. If True, returns a tuple containing the flattened list and a dictionary of shapes at each depth level.
- Return type:
- Raises:
AssertionError – If the sequence is not a valid sequence type.
TypeError – If depth is not an integer value.
Exception – If the sequence cannot be copied.
Examples
>>> sequence = [[1, 2, 3], [], [[2, [3], 4], 6]] >>> flatten(sequence) [1, 2, 3, 2, 3, 4, 6] >>> flatten(sequence, depth=2) [1, 2, 3, 2, [3], 4, 6] >>> flatten([[1, 2], [3, 4]], return_shapes=True) ([1, 2, 3, 4], {0: [2], 1: [2, 2]})
- cereja.array.get_min_max(values)[source]
- Return type:
Tuple[Any,...]- Parameters:
values (List[Any])
- cereja.array.get_shape(sequence)[source]
Get the shape (dimensions and sizes) of a nested sequence (like a list or tuple).
If the sequence is empty or not uniform (e.g., sub-sequences have different lengths), returns None for the dimension(s) where uniformity breaks.
Parameters: sequence (Sequence): A sequence of values, possibly nested.
Returns: Tuple[Union[int, None], …]: A tuple representing the size of each dimension of the sequence.
- Return type:
Tuple[Optional[int],...]- Parameters:
sequence (Sequence)
- cereja.array.prod(sequence, start=1)[source]
Calculate the product of all the elements in the input iterable.
The default start value for the product is 1.
This function is intended specifically for use with numeric values and may reject non-numeric types.
- Parameters:
sequence (
Sequence[Union[int,float,complex]]) – Is a sequence of numbers.start – is a number
- Return type:
Union[int,float,complex]- Returns:
- cereja.array.rand_n(_from=0.0, to=1.0, n=1)[source]
All values are random and their sum is equal to 1 (default) or the value sent in parameter (to)
- Parameters:
_from (
Union[int,float,complex]) – start in numberto (
Union[int,float,complex]) – stop in numbern (
int) – n is length of array
- Return type:
Union[float,List[float]]- Returns:
Sequence of floats
>>> array = rand_n(_from = 10, to=15, n = 3) [13.638625715965802, 1.3384682252134166, 0.022906058820781894]
>>>sum(flatten(array)) 15
- cereja.array.remove_duplicate_items(items)[source]
remove duplicate items in an item list or duplicate items list of list
e.g usage: >>> remove_duplicate_items([1,2,1,2,1]) [1, 2] >>> remove_duplicate_items([‘hi’, ‘hi’, ‘ih’]) [‘hi’, ‘ih’]
- Return type:
Any- Parameters:
items (list | None)
>>> remove_duplicate_items([['hi'], ['hi'], ['ih']]) [['hi'], ['ih']] >>> remove_duplicate_items([[1,2,1,2,1], [1,2,1,2,1], [1,2,1,2,3]]) [[1, 2, 1, 2, 1], [1, 2, 1, 2, 3]]