def balance_matrix(A):
if len(A.shape) != <NUM_LIT:2> or (A.shape[<NUM_LIT:0>] != A.shape[<NUM_LIT:1>]):<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>N = A.shape[<NUM_LIT:0>] <EOL>gebal = sp.linalg.lapack.get_lapack_funcs('<STR_LIT>',(A,))<EOL>bA, lo, hi, pivscale, info = gebal(A, permute=True, scale=True,overwrite_a=False)<EOL>if info < <NUM_LIT:0>:<EOL><INDENT>raise ValueError('<STR_LIT>' % -info)<EOL><DEDENT>def perm_matr(D, c1,c2):<EOL><INDENT>"""<STR_LIT>"""<EOL>i1 = c1-<NUM_LIT:1>; i2 = c2-<NUM_LIT:1> <EOL>P = np.eye(D);<EOL>P[i1,i1] = <NUM_LIT:0.0>; P[i2,i2] = <NUM_LIT:0.0>; <EOL>P[i1,i2] = <NUM_LIT:1.0>; P[i2,i1] = <NUM_LIT:1.0><EOL>return P<EOL><DEDENT>P = np.eye(N) <EOL>if (hi != N-<NUM_LIT:1>): <EOL><INDENT>for k in range(N-<NUM_LIT:1>,hi,-<NUM_LIT:1>):<EOL><INDENT>new_perm = perm_matr(N, k+<NUM_LIT:1>, pivscale[k])<EOL>P = np.dot(P,new_perm)<EOL><DEDENT><DEDENT>if (lo != <NUM_LIT:0>):<EOL><INDENT>for k in range(<NUM_LIT:0>,lo,<NUM_LIT:1>):<EOL><INDENT>new_perm = perm_matr(N, k+<NUM_LIT:1>, pivscale[k])<EOL>P = np.dot(P,new_perm)<EOL><DEDENT><DEDENT>D = pivscale.copy()<EOL>D[<NUM_LIT:0>:lo] = <NUM_LIT:1.0>; D[hi+<NUM_LIT:1>:N] = <NUM_LIT:1.0> <EOL>T = np.dot(P,np.diag(D)) <EOL>T_inv = np.dot(np.diag(D**(-<NUM_LIT:1>)),P.T)<EOL>return bA.copy(), T, T_inv<EOL>
Balance matrix, i.e. finds such similarity transformation of the original
matrix A:  A = T * bA * T^{-1}, where norms of columns of bA and of rows of bA
are as close as possible. It is usually used as a preprocessing step in
eigenvalue calculation routine. It is useful also for State-Space models.

See also:
    [1] Beresford N. Parlett and Christian Reinsch (1969). Balancing
        a matrix for calculation of eigenvalues and eigenvectors.
        Numerische Mathematik, 13(4): 293-304.

Input:
----------------------
A: square matrix
    Matrix to be balanced

Output:
----------------
    bA: matrix
        Balanced matrix

    T: matrix
        Left part of the similarity transformation

    T_inv: matrix
        Right part of the similarity transformation.