Is your feature request related to a problem? Please describe.
I am doing Markov modelling for SAR/QSAR analysis of chemical compounds and would need sorted markov matrices.
I suggest to sort the Markov matrix according to the most stable state. Something like with better memory management:
def sort_markov_matrix(markov_matrix):
"""Takes in random markov matrix
returns sorted markov matrix
Args:
markov_matrix (np.array): unsorted matrix
Returns:
(np.array): sorted Markov matrix
"""
b = markov_matrix.copy()
for i in range(len(markov_matrix)):
ref1 = markov_matrix[i,i]
for j in range(i+1, len(markov_matrix)):
ref2 = markov_matrix[j, j]
if ref2 > ref1:
markov_matrix[i, :] = b[j, :]
markov_matrix[j, :] = b[i, :]
b = markov_matrix.copy()
for k in range(len(markov_matrix)):
markov_matrix[k,i] = b[k, j]
markov_matrix[k,j] = b[k, i]
b = markov_matrix.copy()
return markov_matrix
Test with
def test_sort():
a = np.array([[0.8, 0.1, 0.05, 0.05],[0.005, 0.9, 0.03, 0.015], [0.1, 0.2, 0.4, 0.3],[0.01, 0.02, 0.03, 0.94]])
sorted_a = sort_markov_matrix(a)
assert np.array_equal(sorted_a[0,:], np.array([0.94, 0.02, 0.01, 0.03])) == True, str(sorted_a[0,:])
assert np.array_equal(sorted_a[1,:], np.array([0.015,0.9, 0.005, 0.03])) == True, str(sorted_a[1,:])
assert np.array_equal(sorted_a[2,:], np.array([0.05, 0.1, 0.8, 0.05])) == True, str(sorted_a[2,:])
assert np.array_equal(sorted_a[3,:], np.array([0.3, 0.2, 0.1, 0.4])) == True, str(sorted_a[3,:])
What do you think?