DAS_2023_1/alexandrov_dmitrii_lab_6/matrix.py

110 lines
3.3 KiB
Python

import numpy as np
import time
from concurrent.futures import ProcessPoolExecutor
benchmark = {}
matrix = []
# int переполняется
det = 0.0
# ручной метод - от размера матриц ~15 и выше может случайно винду
def get_determinant_usr_implementation(input_m):
if input_m.size == 4:
return input_m[0, 0] * input_m[1, 1] - input_m[0, 1] * input_m[1, 0]
r_det = [0] * input_m.size
for i in range(input_m.shape[0]):
r_det[i] = input_m[0, i]
if r_det[i] != 0:
if i % 2 == 1:
r_det[i] = r_det[i] * -1
r_det[i] = r_det[i] * get_determinant_usr_implementation(
np.delete(np.delete(input_m, 0, axis=0), i, axis=1))
return sum(r_det)
def get_determinant_component_usr_implementation(input_m, col):
r_det = float(input_m[0, col])
if r_det == 0:
return r_det
if col % 2 == 1:
r_det = r_det * -1
return r_det * get_determinant_usr_implementation(np.delete(np.delete(input_m, 0, axis=0), col, axis=1))
def get_determinant_component(input_m, col):
r_det = float(input_m[0, col])
if r_det == 0:
return r_det
if col % 2 == 1:
r_det = r_det * -1
return r_det * np.linalg.det(np.delete(np.delete(input_m, 0, axis=0), col, axis=1))
def calculate_determinant_parallel(size, proc_num):
global matrix
global det
if proc_num > 61:
proc_num = 61
matrix = np.random.randint(10, size=(size, size))
start_time = time.time()
with ProcessPoolExecutor(max_workers=proc_num) as executor:
if size <= 10:
components = [executor.submit(get_determinant_component_usr_implementation, matrix, i) for i in range(size)]
else:
components = [executor.submit(get_determinant_component, matrix, i) for i in range(size)]
res = [fut.result() for fut in components]
det = sum(res)
return time.time() - start_time
def do_research():
benchmark['size=2, proc_num=1: '] = calculate_determinant_parallel(2, 1)
benchmark['size=5, proc_num=1: '] = calculate_determinant_parallel(5, 1)
benchmark['size=10, proc_num=1: '] = calculate_determinant_parallel(10, 1)
benchmark['size=2, proc_num=10: '] = calculate_determinant_parallel(2, 10)
benchmark['size=5, proc_num=10: '] = calculate_determinant_parallel(5, 10)
benchmark['size=10, proc_num=10: '] = calculate_determinant_parallel(10, 10)
benchmark['size=2, proc_num=100: '] = calculate_determinant_parallel(2, 100)
benchmark['size=5, proc_num=100: '] = calculate_determinant_parallel(5, 100)
benchmark['size=10, proc_num=100: '] = calculate_determinant_parallel(10, 100)
print(benchmark)
if __name__ == '__main__':
do_research()
def get_results(size, proc_num):
global matrix
global det
res = "time: "
res = res + str(calculate_determinant_parallel(size, proc_num))
res = res + "<br/>"
for i in range(size):
res = res + "<p>"
for a in range(size):
res = res + str(matrix[i][a]) + ", "
res = res + "</p>"
res = res + "<br/><p>" + str(det) + "</p>"
return res
def get_benchmark():
global benchmark
if len(benchmark) == 0:
do_research()
res = ''
for key, val in benchmark.items():
res = res + "<p>" + key + str(val) + "</p>"
return res