def multiply(m1, m2, n, routine=multiplication.strassen): assert m1.nCols == n and m1.nRows % n == 0 and m2.nRows == n and m2.nCols % n == 0 or m2.nCols == n and m2.nRows % n == 0 and m1.nRows == n and m1.nCols % n == 0 if m1.nRows > m1.nCols: c = list( routine(matrix.Submatrix(m1, i * n, 0, n, n), matrix.Submatrix(m2, 0, j * n, n, n)) for i in range(m1.nRows / n) for j in range(m2.nCols / n)) return matrix.Matrix( list(concatenate(c, m1.nRows / n, m2.nCols / n, n, n)), m1.nRows, m2.nCols) else: return sum((routine(matrix.Submatrix(m1, 0, i * n, n, n), matrix.Submatrix(m2, i * n, 0, n, n)) for i in range(m1.nCols / n)), matrix.empty(n, n))
def diag(ins): if isinstance(ins, matrix.Matrix): min = ins.m if ins.m < ins.n else ins.n temp = [] for x in xrange(1, min+1): temp.append(str(ins.get(x,x))) ret = matrix.Matrix(';'.join(temp)) elif isinstance(ins, list): ret = zeros(len(ins)) for x in xrange(1, ret.m+1): ret.set(x, x, ins[x-1]) else: print >> sys.stderr, 'ERROR the parameter must be a matrix or list.' ret = None return ret
def multiply(m1, m2, n, routine=multiplication.strassen): assert m1.nCols == n and m1.nRows % n == 0 and m2.nRows == n and m2.nCols % n == 0 or m2.nCols == n and m2.nRows % n == 0 and m1.nRows == n and m1.nCols % n == 0 if m1.nRows > m1.nCols: c = list( routine(matrix.Submatrix(m1, i * n, 0, n, n), matrix.Submatrix(m2, 0, j * n, n, n)) for i in range(m1.nRows / n) for j in range(m2.nCols / n)) return matrix.Matrix( list(concatenate(c, m1.nRows / n, m2.nCols / n, n, n)), m1.nRows, m2.nCols) else: return sum((routine(matrix.Submatrix(m1, 0, i * n, n, n), matrix.Submatrix(m2, i * n, 0, n, n)) for i in range(m1.nCols / n)), matrix.empty(n, n)) def random_array(n, m, p=0): return [random.randint(p, m) for x in range(n)] if __name__ == '__main__': n = 8 k = 10 m1 = matrix.Matrix(random_array(n * n * k, 10), n * k, n) m2 = matrix.Matrix(random_array(n * n * k, 10), n, n * k) assert multiply(m1, m2, n) == m1 * m2 assert multiply(m2, m1, n) == m2 * m1
def custom(m, n, elem): row = [str(elem)] * n raw_matrix = ';'.join([','.join(row)] * m) ret = matrix.Matrix(raw_matrix) return ret
from __future__ import print_function from matrix import multiplication, matrix import benchmark.inputs import benchmark.profiler if __name__ == '__main__': n = 8 m1 = matrix.Matrix(benchmark.inputs.random_array(pow(2, n * 2), 100, -100), pow(2, n), pow(2, n)) m2 = matrix.Matrix(benchmark.inputs.random_array(pow(2, n * 2), 100, -100), pow(2, n), pow(2, n)) p = benchmark.profiler.profile #print(m1*m2) r = [ p(multiplication.strassen, m1, m2), p(multiplication.divide_and_conquer, m1, m2), p(multiplication.simple, m1, m2) ] #print(r)