#NEWLINE# def check_symmetric( array , tol = 1e-10 , raise_warning = True , raise_exception = False ) : #NEWLINE# #INDENT# 'Make sure that array is 2D, square and symmetric.\n\n    If the array is not symmetric, then a symmetrized version is returned.\n    Optionally, a warning or exception is raised if the matrix is not\n    symmetric.\n\n    Parameters\n    ----------\n    array : nd-array or sparse matrix\n        Input object to check / convert. Must be two-dimensional and square,\n        otherwise a ValueError will be raised.\n    tol : float\n        Absolute tolerance for equivalence of arrays. Default = 1E-10.\n    raise_warning : boolean (default=True)\n        If True then raise a warning if conversion is required.\n    raise_exception : boolean (default=False)\n        If True then raise an exception if array is not symmetric.\n\n    Returns\n    -------\n    array_sym : ndarray or sparse matrix\n        Symmetrized version of the input array, i.e. the average of array\n        and array.transpose(). If sparse, then duplicate entries are first\n        summed and zeros are eliminated.\n    ' #NEWLINE# if ( ( array . ndim != 2 ) or ( array . shape [ 0 ] != array . shape [ 1 ] ) ) : #NEWLINE# #INDENT# raise ValueError ( 'array must be 2-dimensional and square. shape = {0}' . format ( array . shape ) ) #NEWLINE# #UNINDENT# if sp . issparse ( array ) : #NEWLINE# #INDENT# diff = ( array - array . T ) #NEWLINE# if ( diff . format not in [ 'csr' , 'csc' , 'coo' ] ) : #NEWLINE# #INDENT# diff = diff . tocsr ( ) #NEWLINE# #UNINDENT# symmetric = np . all ( ( abs ( diff . data ) < tol ) ) #NEWLINE# #UNINDENT# else : #NEWLINE# #INDENT# symmetric = np . allclose ( array , array . T , atol = tol ) #NEWLINE# #UNINDENT# if ( not symmetric ) : #NEWLINE# #INDENT# if raise_exception : #NEWLINE# #INDENT# raise ValueError ( 'Array must be symmetric' ) #NEWLINE# #UNINDENT# if raise_warning : #NEWLINE# #INDENT# warnings . warn ( 'Array is not symmetric, and will be converted to symmetric by average with its transpose.' ) #NEWLINE# #UNINDENT# if sp . issparse ( array ) : #NEWLINE# #INDENT# conversion = ( 'to' + array . format ) #NEWLINE# array = getattr ( ( 0.5 * ( array + array . T ) ) , conversion ) ( ) #NEWLINE# #UNINDENT# else : #NEWLINE# #INDENT# array = ( 0.5 * ( array + array . T ) ) #NEWLINE# #UNINDENT# #UNINDENT# return array