def corr_nearest(corr, threshold=1e-15, n_fact=100):
 k_vars = corr.shape[0]
 if (k_vars != corr.shape[1]):
  raise ValueError('matrix is not square')
 diff = np.zeros(corr.shape)
 x_new = corr.copy()
 diag_idx = np.arange(k_vars)
 for ii in range(int((len(corr) * n_fact))):
  x_adj = (x_new - diff)
  (x_psd, clipped) = clip_evals(x_adj, value=threshold)
  if (not clipped):
   x_new = x_psd
   break
  diff = (x_psd - x_adj)
  x_new = x_psd.copy()
  x_new[(diag_idx, diag_idx)] = 1
 else:
  import warnings
  warnings.warn(iteration_limit_doc, IterationLimitWarning)
 return x_new

def corr_nearest ( corr , threshold = 1e-15 , n_fact = 100 ) : k_vars = corr . shape [ 0 ] if ( k_vars != corr . shape [ 1 ] ) : raise ValueError ( 'matrix is not square' ) diff = np . zeros ( corr . shape ) x_new = corr . copy ( ) diag_idx = np . arange ( k_vars ) for ii in range ( int ( ( len ( corr ) * n_fact ) ) ) : x_adj = ( x_new - diff ) ( x_psd , clipped ) = clip_evals ( x_adj , value = threshold ) if ( not clipped ) : x_new = x_psd break diff = ( x_psd - x_adj ) x_new = x_psd . copy ( ) x_new [ ( diag_idx , diag_idx ) ] = 1 else : import warnings warnings . warn ( iteration_limit_doc , IterationLimitWarning ) return x_new
find the nearest correlation matrix that is positive semi-definite .