-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmatrixAnalysis.py
More file actions
98 lines (76 loc) · 3.25 KB
/
matrixAnalysis.py
File metadata and controls
98 lines (76 loc) · 3.25 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
import numpy as np
import matplotlib.pyplot as plt
from scipy.io import mmread
from scipy.sparse.linalg import norm
from Utility import Utility
def compute_condition_number(matrix):
"""
Function to compute the condition number for sparse matrices.
"""
try:
cond_number = np.linalg.cond(matrix.toarray()) # Convert to dense array for condition number
print(f'Condition Number: {cond_number:.2e}')
return cond_number
except Exception as e:
print(f"Error in computing condition number: {e}")
return None
def plot_sparsity_pattern(matrix, title):
"""
Function to plot the sparsity pattern of the matrix and display its sparsity index.
Parameters:
- matrix: The sparse matrix to plot the sparsity pattern for.
- title: The title for the plot.
"""
# Calculate sparsity index
total_elements = matrix.shape[0] * matrix.shape[1]
zero_elements = total_elements - matrix.nnz # Number of zero elements
sparsity_index = 1 - zero_elements / total_elements
# Update title with sparsity index
title_with_sparsity = f"{title}\nSparsity Index: {sparsity_index:.4f}"
plt.figure(figsize=(8, 8))
plt.spy(matrix, markersize=0.0001) # Set marker size for better granularity
plt.title(title_with_sparsity)
plt.show()
def plot_value_distribution(matrix, title):
"""
Function to plot the distribution of values in the matrix.
"""
plt.figure(figsize=(3, 5))
# Extract non-zero values and calculate zero counts
zero_count = matrix.shape[0] * matrix.shape[1] - matrix.nnz
non_zero_values = matrix.data
# Plot histogram for non-zero values
plt.hist(non_zero_values, bins=20, color='blue', alpha=0.7, label='Non-Zero Values')
# Calculate the width of the bins to align zero count bar properly
bin_width = (max(non_zero_values) - min(non_zero_values)) / 20 if non_zero_values.size > 0 else 1
zero_bar_position = min(non_zero_values) - bin_width # Position the zero value bar just before the first bin
# Add a bar for zero values
plt.bar(zero_bar_position, zero_count, width=bin_width, color='red', alpha=0.7, label='Zero Values')
plt.title(title)
plt.xlabel('Value')
plt.ylabel('Frequency')
plt.legend()
# Remove x-axis ticks and labels
plt.xticks([])
plt.show()
def main():
"""
Main function to execute analysis and plot graphs for each matrix.
"""
PATH = 'matrici'
# Get list of matrix file paths
matrix_files = Utility.get_matrix_paths(PATH)
for i, matrix_file in enumerate(matrix_files):
# Read each matrix
A = Utility.read(matrix_file)
if A is not None:
matrix_name = matrix_file.split('/')[-1].split('.')[0] # Extract the matrix name from the filename
print(f"Analyzing matrix: {matrix_name}")
# Calculate and print the condition number
compute_condition_number(A)
# Plot the sparsity pattern of the matrix
plot_sparsity_pattern(A, f'Sparsity Pattern of Matrix {matrix_name}')
# Plot the distribution of the non-zero values of the matrix
plot_value_distribution(A, f'Distribution of Non-Zero Values in Matrix {matrix_name}')
if __name__ == "__main__":
main()