From c0908b4299f1d8e99de56a0562482d760c127742 Mon Sep 17 00:00:00 2001 From: Niklas Birk Date: Sat, 16 Mar 2024 15:48:37 +0100 Subject: [PATCH] Initial matrix mpi --- src/matrix.py | 18 +++++++++--------- src/matrix_mpi.py | 38 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 47 insertions(+), 9 deletions(-) create mode 100644 src/matrix_mpi.py diff --git a/src/matrix.py b/src/matrix.py index 660b707..9e37544 100644 --- a/src/matrix.py +++ b/src/matrix.py @@ -219,32 +219,32 @@ class Matrix: def __rmul__(self, other): return self * other - def __norm_frobenius__(self): + def __abs_sum__(self): rows = self.__shape__[0] cols = self.__shape__[1] abs_sum = 0 for i in range(rows): for j in range(cols): abs_sum += abs(self.__data__[i][j]) ** 2 - return math.sqrt(abs_sum) + return abs_sum - def __norm_colsum__(self): + def __col_sums__(self): rows = self.__shape__[0] cols = self.__shape__[1] col_sums = [0] * cols for j in range(cols): for i in range(rows): col_sums[j] += abs(self.__data__[i][j]) - return max(col_sums) + return col_sums - def __norm_rowsum__(self): + def __row_sums__(self): rows = self.__shape__[0] cols = self.__shape__[1] row_sums = [0] * rows for i in range(rows): for j in range(cols): row_sums[i] += abs(self.__data__[i][j]) - return max(row_sums) + return row_sums def norm(self, f: str = "frobenius"): """ @@ -258,11 +258,11 @@ class Matrix: :return: the norm as a number """ if f == "frobenius": - norm = self.__norm_frobenius__() + norm = math.sqrt(self.__abs_sum__()) elif f == "col sum": - norm = self.__norm_colsum__() + norm = max(self.__col_sums__()) elif f == "row sum": - norm = self.__norm_rowsum__() + norm = max(self.__row_sums__()) else: raise ValueError(f"Parameter f must be either \"frobenius\", \"row sum\" or \"col sum\"") return norm diff --git a/src/matrix_mpi.py b/src/matrix_mpi.py new file mode 100644 index 0000000..49eb7b1 --- /dev/null +++ b/src/matrix_mpi.py @@ -0,0 +1,38 @@ +import numpy +from mpi4py import MPI + +from matrix import Matrix + + +class MatrixMPI: + __comm__ = MPI.COMM_WORLD + __size__ = __comm__.Get_size() + __rank__ = __comm__.Get_rank() + + __matrix__: Matrix = None + __chunk__: list = None + + def __init__(self, data=None, shape=None, structure=None, model=None, offset=None, n=None): + self.__matrix__ = Matrix(data=data, shape=shape, structure=structure, model=model, offset=offset, n=n) + + total_amount_of_rows = self.__matrix__.shape()[0] + chunks = numpy.array_split(list(range(total_amount_of_rows)), self.__size__) + self.__chunk__ = chunks[self.__rank__].tolist() + + def __str__(self): + return str(self.__matrix__) + + def get_rank_data(self): + rows = len(self.__chunk__) + cols = self.__matrix__.shape()[1] + return Matrix(self.__matrix__[self.__chunk__], (rows, cols)) + + def transpose(self): + return self.__matrix__.transpose() + + def T(self): + return self.transpose() + + +mpi_matrix = MatrixMPI(list(range(1, 25)), (12, 2)) +print(mpi_matrix.transpose())