Generating a random sparse hermitian matrix in Python

1.5k Views Asked by At

I'd like to find a way to generate random sparse hermitian matrices in Python, but don't really know how to do so efficiently. How would I go about doing this?

Obviously, there are slow, ugly ways to do this, but since I'm going to be doing this a lot, I'd like if there was a faster way to do it.

Is there an easy way to calculate the density of the matrix? It's the parameter that I'd be using to compare two factorisation algorithms. It's defined as $$ d = \frac{\mathrm{nnz}}{n^2} $$ where $\mathrm{nnz}$ is defined as the number of nonzero entries in the matrix and $n$ is its number of rows or columns (hence $n^2$ is the number of elements in the matrix).

EDIT

Calculating the density should be easy:

density = np.count_nonzero(A)/n**2

should do the trick.

2

There are 2 best solutions below

3
On BEST ANSWER

This generates a random mask with of a given size n and density dens, you just need to apply it to a dense matrix of your choice

import numpy as np
np.random.seed(0)

n = 300
dens = 0.2
mask = np.array([np.random.choice([True, False], n, p = [dens, 1 - dens]) for i in range(n)])

print(np.count_nonzero(mask) / n**2)

The result of this is

>>> 0.20224444444444445

To force the result to be Hermitian just use

$$ H = \frac{1}{2}(A + A^*) $$

2
On

When I apply the $M[$mask$]$, I only get the values of $M$ where True is defined in mask. How do I get the sparse matrix $M$ (where false$=0$, True=real value).

(I think we are following the same course ;))