jiahuimbzuai/CoQuIR huggingface dataset:
//  [python]
def compute_projected_matrix(self):
        """
        To pre-compute the matrix for projecting onto subspace

        Uses:
            self.
            P_BC_C: dict for each dimension with the evalualted polynomial values for the boundary conditions (including continuity).
                    np.array([number of boundary conditions, number of coefficients])

        Modifies:
            self.
            proj_mat: matrix used in projecting solutions onto the subspace that adheres to the BCs
                    In each dimension is a 2D np.array
        """

        P_BC_C = self.P_BC_C

        # initialise
        proj_mat = dict()

        # Loop for each dimension
        for key in P_BC_C.keys():
            # number of boundary conditions
            nBCs = int(P_BC_C[key].shape[0])
            # matrix for the boundary condition polynomial matrix
            P_BC_mat = sp.matrix(P_BC_C[key])
            # identity matrix
            eye_mat = sp.matrix(np.identity(nBCs))

            # Compute the projected matrix and convert to a np array
            # proj_mat[key] = np.array(P_BC_mat.T*(np.linalg.inv(P_BC_mat*P_BC_mat.T)*eye_mat))
            # pm_1 = np.array(P_BC_mat.T*(np.linalg.inv(P_BC_mat*P_BC_mat.T)*eye_mat))
            mat = P_BC_mat*P_BC_mat.T
            mat_inv = sp.linalg.pinv(mat)

            proj_mat[key] = np.array(P_BC_mat.T*(sp.matrix(mat_inv)*eye_mat))

        self.proj_mat = proj_mat
//  [python]
def dynamics(self,y,t, u):
        th1,th2,dth1,dth2 = y
        u = np.array(u).reshape(2,1)
        f = np.zeros(4)
        g = self.g
        l1 = self.l1
        l2 = self.l2
        m1 = self.m1
        m2 = self.m2
        c2 = np.cos(th2)
        s2 = np.sin(th2)
        M = np.zeros((2,2))
        M[0,0] = m1*l1**2+m2*(l1**2+2*l1*l2*c2+l2**2)
        M[0,1] = m2*(l1*l2*c2+l2**2)
        M[1,0] = m2*(l1*l2*c2+l2**2)
        M[1,1] = m2*l2**2
        C = np.zeros((2,1))
        C[0,0] = -m2*l1*l2*s2*(2*dth1*dth2+dth2**2)
        C[1,0] = m2*l1*l2*dth1**2*s2
        G = np.zeros((2,1))
        G[0,0] = (m1+m2)*l1*g*np.cos(th1)+m2*g*l2*np.cos(th1+th2)
        G[1,0] = m2*g*l2*np.cos(th1+th2)
        Minv = scipy.linalg.pinv2(M)
        ddth = np.dot(Minv,(u-C-G)).reshape(-1)
        f[0] = dth1
        f[1] = dth2
        f[2] = ddth[0]
        f[3] = ddth[1]
        return f
//  [python]
def dynamics(self,y,t, u):
        th1,th2,dth1,dth2 = y
        u = np.array(u).reshape(2,1)
        f = np.zeros(4)
        g = self.g
        l1 = self.l1
        l2 = self.l2
        m1 = self.m1
        m2 = self.m2
        c2 = np.cos(th2)
        s2 = np.sin(th2)
        M = np.zeros((2,2))
        M[0,0] = m1*l1**2+m2*(l1**2+2*l1*l2*c2+l2**2)
        M[0,1] = m2*(l1*l2*c2+l2**2)
        M[1,0] = m2*(l1*l2*c2+l2**2)
        M[1,1] = m2*l2**2
        C = np.zeros((2,1))
        C[0,0] = -m2*l1*l2*s2*(2*dth1*dth2+dth2**2)
        C[1,0] = m2*l1*l2*dth1**2*s2
        G = np.zeros((2,1))
        G[0,0] = (m1+m2)*l1*g*np.cos(th1)+m2*g*l2*np.cos(th1+th2)
        G[1,0] = m2*g*l2*np.cos(th1+th2)
        Minv = scipy.linalg.pinv(M)
        ddth = np.dot(Minv,(u-C-G)).reshape(-1)
        f[0] = dth1
        f[1] = dth2
        f[2] = ddth[0]
        f[3] = ddth[1]
        return f
//  [python]
def invert_L1_norm(R, Alpha, y, max_iter=100, smoothing_facor=0.0):

    ifg = np.zeros(y.shape, np.float32)
    if smoothing_facor > 0:
        ifg = np.concatenate([y, ifg], dtype=np.float32).flatten()
        G = np.concatenate([R, Alpha], dtype=np.float32)
    else:
        ifg[:] = y[:]
    W = np.eye((ifg.shape[0]), dtype=np.float32)
    inv_Q = linalg.pinv2(np.linalg.multi_dot([G.T, W, G])).astype(np.float32)
    Coef = np.linalg.multi_dot([G.T, W, ifg]).astype(np.float32)
    X = np.matmul(inv_Q, Coef).astype(np.float32)

    res = np.abs(ifg - np.matmul(G, X)).astype(np.float32)
    res[res < 1e-5] = 1e-5
    res1 = np.empty(res.shape, dtype=np.float32)
    res2 = np.empty(res.shape, dtype=np.float32)
    res1[:] = res[:]
    res2[:] = 1
    diff_res = np.max(np.abs(res1 - res2))

    for ii in range(max_iter):
        if diff_res <= 1e-3:
            break
        res1[:] = res2[:]
        W = np.diag(1/res.flatten())
        W = W / np.max(W)
        inv_Q = linalg.pinv2(np.linalg.multi_dot([G.T, W, G])).astype(np.float32)
        Coef = np.linalg.multi_dot([G.T, W, ifg]).astype(np.float32)
        X = np.matmul(inv_Q, Coef).astype(np.float32)
        res = np.abs(ifg - np.matmul(G, X)).astype(np.float32)
        res[res < 1e-5] = 1e-5
        res2[:] = res[:]
        diff_res = np.max(np.abs(res1 - res2))
        if np.any(np.isnan(res)):
            break
    e1 = np.sum(res)

    X = X.reshape(-1, 1)
    return X, e1
//  [python]
def invert_L1_norm(R, Alpha, y, max_iter=100, smoothing_facor=0.0):

    ifg = np.zeros(y.shape, np.float32)
    if smoothing_facor > 0:
        ifg = np.concatenate([y, ifg], dtype=np.float32).flatten()
        G = np.concatenate([R, Alpha], dtype=np.float32)
    else:
        ifg[:] = y[:]
    W = np.eye((ifg.shape[0]), dtype=np.float32)
    inv_Q = linalg.pinv(np.linalg.multi_dot([G.T, W, G])).astype(np.float32)
    Coef = np.linalg.multi_dot([G.T, W, ifg]).astype(np.float32)
    X = np.matmul(inv_Q, Coef).astype(np.float32)

    res = np.abs(ifg - np.matmul(G, X)).astype(np.float32)
    res[res < 1e-5] = 1e-5
    res1 = np.empty(res.shape, dtype=np.float32)
    res2 = np.empty(res.shape, dtype=np.float32)
    res1[:] = res[:]
    res2[:] = 1
    diff_res = np.max(np.abs(res1 - res2))

    for ii in range(max_iter):
        if diff_res <= 1e-3:
            break
        res1[:] = res2[:]
        W = np.diag(1/res.flatten())
        W = W / np.max(W)
        inv_Q = linalg.pinv(np.linalg.multi_dot([G.T, W, G])).astype(np.float32)
        Coef = np.linalg.multi_dot([G.T, W, ifg]).astype(np.float32)
        X = np.matmul(inv_Q, Coef).astype(np.float32)
        res = np.abs(ifg - np.matmul(G, X)).astype(np.float32)
        res[res < 1e-5] = 1e-5
        res2[:] = res[:]
        diff_res = np.max(np.abs(res1 - res2))
        if np.any(np.isnan(res)):
            break
    e1 = np.sum(res)

    X = X.reshape(-1, 1)
    return X, e1
//  [python]
def inverse(self):
    return s.pinv(self._Sigma)
//  [python]
def inverse(self):
    return la.pinv(self._Sigma)
//  [python]
def __init__(self, X, compute_inv=False):
        if X.shape[0] < X.shape[1]:
            raise AssertionError("X should have more rows than columns.")
        self.X_pinv = np.linalg.pinv(X)
        if compute_inv:
            XtX = np.matmul(X.transpose(), X)
            if not np.isfinite(np.linalg.cond(XtX)):
                raise AssertionError("X^t * X should always be invertible.")
            self.XtX_inv = scipy.linalg.inv(XtX)
        else:
            self.XtX_inv = None
//  [python]
def __init__(self, X, compute_inv=False):
        if X.shape[0] < X.shape[1]:
            raise AssertionError("X should have more rows than columns.")
        self.X_pinv = scipy.linalg.pinv(X)
        if compute_inv:
            XtX = np.matmul(X.transpose(), X)
            if not np.isfinite(np.linalg.cond(XtX)):
                raise AssertionError("X^t * X should always be invertible.")
            self.XtX_inv = scipy.linalg.inv(XtX)
        else:
            self.XtX_inv = None
//  [python]
def mat_mult_benchmark(nparams, nsamples):
    # create data
    X = 100.0 * np.random.rand(nsamples, nparams) - 50.0
    X[:,0] = 1.0
    X_pinv = np.linalg.pinv(X)
    X_pinv_32 = X_pinv.astype(np.float32, copy=True)
    y = 100.0 * np.random.rand(nsamples) - 50.0
    # do least squares
    tls = time.time()
    beta = scipy.linalg.lstsq(X, y)
    tls = time.time() - tls
    # use pinv with dot
    tdot = time.time()
    beta = np.dot(X_pinv, y)
    tdot = time.time() - tdot
    # use pinv with matmul
    tmatmul = time.time()
    beta = np.matmul(X_pinv, y)
    tmatmul = time.time() - tmatmul
    # use pinv with matmul and float32
    tmatmul32 = time.time()
    y_32 = y.astype(np.float32, copy=True)
    beta = np.matmul(X_pinv_32, y_32)
    tmatmul32 = time.time() - tmatmul32
    # print results
    print("pinv-dot: ", tls/tdot, "x; pinv-matmul: ", tls/tmatmul,
          "x; pinv-matmul32:", tls/tmatmul32, "x")
//  [python]
def mat_mult_benchmark(nparams, nsamples):
    # create data
    X = 100.0 * np.random.rand(nsamples, nparams) - 50.0
    X[:,0] = 1.0
    X_pinv = scipy.linalg.pinv(X)
    X_pinv_32 = X_pinv.astype(np.float32, copy=True)
    y = 100.0 * np.random.rand(nsamples) - 50.0
    # do least squares
    tls = time.time()
    beta = scipy.linalg.lstsq(X, y)
    tls = time.time() - tls
    # use pinv with dot
    tdot = time.time()
    beta = np.dot(X_pinv, y)
    tdot = time.time() - tdot
    # use pinv with matmul
    tmatmul = time.time()
    beta = np.matmul(X_pinv, y)
    tmatmul = time.time() - tmatmul
    # use pinv with matmul and float32
    tmatmul32 = time.time()
    y_32 = y.astype(np.float32, copy=True)
    beta = np.matmul(X_pinv_32, y_32)
    tmatmul32 = time.time() - tmatmul32
    # print results
    print("pinv-dot: ", tls/tdot, "x; pinv-matmul: ", tls/tmatmul,
          "x; pinv-matmul32:", tls/tmatmul32, "x")
//  [python]
def get_trafo_matrix_mvn(dimension, params, cov_type):
    """
    Return the transformation matrix to apply to the data, in order to remove moments.
    """

    test_block=multivariate_normal.mvn_block(dimension,cov_type=cov_type)

    pars=test_block._obtain_usable_flow_params(params, cov_type, extra_inputs=torch.from_numpy(params).unsqueeze(0))

    lower_trig, _=matrix_fns.obtain_lower_triangular_matrix_and_logdet(dimension, single_log_diagonal_entry=pars[0], log_diagonal_entries=pars[1], lower_triangular_entries=pars[2], cov_type=cov_type)

    lower_trig=lower_trig[0].numpy()

   
    predicted_matrix=numpy.matmul(lower_trig, lower_trig.T)

    inverse_predicted=numpy.linalg.pinv(predicted_matrix)
    
    l, sigma, r=scipy.linalg.svd(inverse_predicted)

    ## return "sqrt" of covariance matrix
    return numpy.sqrt(sigma)*r
//  [python]
def get_trafo_matrix_mvn(dimension, params, cov_type):
    """
    Return the transformation matrix to apply to the data, in order to remove moments.
    """

    test_block=multivariate_normal.mvn_block(dimension,cov_type=cov_type)

    pars=test_block._obtain_usable_flow_params(params, cov_type, extra_inputs=torch.from_numpy(params).unsqueeze(0))

    lower_trig, _=matrix_fns.obtain_lower_triangular_matrix_and_logdet(dimension, single_log_diagonal_entry=pars[0], log_diagonal_entries=pars[1], lower_triangular_entries=pars[2], cov_type=cov_type)

    lower_trig=lower_trig[0].numpy()

   
    predicted_matrix=numpy.matmul(lower_trig, lower_trig.T)

    inverse_predicted=scipy.linalg.pinv(predicted_matrix)
    
    l, sigma, r=scipy.linalg.svd(inverse_predicted)

    ## return "sqrt" of covariance matrix
    return numpy.sqrt(sigma)*r
//  [python]
def get_loss_fn_mvn(target_matrix, cov_type):

    dim=target_matrix.shape[0]

    

    def compute_matching_distance(a):
       
        test_block=multivariate_normal.mvn_block(dim,cov_type=cov_type)

        pars=test_block._obtain_usable_flow_params(a, cov_type, extra_inputs=torch.from_numpy(a).unsqueeze(0))

        lower_trig, _=matrix_fns.obtain_lower_triangular_matrix_and_logdet(dim, single_log_diagonal_entry=pars[0], log_diagonal_entries=pars[1], lower_triangular_entries=pars[2], cov_type=cov_type)

        lower_trig=lower_trig[0].numpy()

        predicted_matrix=numpy.matmul(lower_trig, lower_trig.T)
        
        ## it seems when the target data has larger variance than the unit gaussian, it is much faster to just take the reverse KL    
        #inverse_predicted=scipy.linalg.pinv(predicted_matrix)
        #forward_kl=0.5*(numpy.trace(numpy.matmul(inverse_predicted, target_matrix))+numpy.linalg.slogdet(predicted_matrix)[1]-numpy.linalg.slogdet(target_matrix)[1]-dim)

        ## inverse

        inverse_target=numpy.linalg.pinv(target_matrix)
    
        reverse_kl=0.5*(numpy.trace(numpy.matmul(inverse_target, predicted_matrix))-numpy.linalg.slogdet(predicted_matrix)[1]+numpy.linalg.slogdet(target_matrix)[1]-dim)

        return reverse_kl
        
    return compute_matching_distance
//  [python]
def get_loss_fn_mvn(target_matrix, cov_type):

    dim=target_matrix.shape[0]

    

    def compute_matching_distance(a):
       
        test_block=multivariate_normal.mvn_block(dim,cov_type=cov_type)

        pars=test_block._obtain_usable_flow_params(a, cov_type, extra_inputs=torch.from_numpy(a).unsqueeze(0))

        lower_trig, _=matrix_fns.obtain_lower_triangular_matrix_and_logdet(dim, single_log_diagonal_entry=pars[0], log_diagonal_entries=pars[1], lower_triangular_entries=pars[2], cov_type=cov_type)

        lower_trig=lower_trig[0].numpy()

        predicted_matrix=numpy.matmul(lower_trig, lower_trig.T)
        
        ## it seems when the target data has larger variance than the unit gaussian, it is much faster to just take the reverse KL    
        #inverse_predicted=scipy.linalg.pinv(predicted_matrix)
        #forward_kl=0.5*(numpy.trace(numpy.matmul(inverse_predicted, target_matrix))+numpy.linalg.slogdet(predicted_matrix)[1]-numpy.linalg.slogdet(target_matrix)[1]-dim)

        ## inverse

        inverse_target=scipy.linalg.pinv(target_matrix)
    
        reverse_kl=0.5*(numpy.trace(numpy.matmul(inverse_target, predicted_matrix))-numpy.linalg.slogdet(predicted_matrix)[1]+numpy.linalg.slogdet(target_matrix)[1]-dim)

        return reverse_kl
        
    return compute_matching_distance
//  [python]
def _initParams_fast(self):
		""" 
		initialize the gp parameters
			1) project Y on the known factor X0 -> Y0
				average variance of Y0 is used to initialize the variance explained by X0
			2) considers the residual Y1 = Y-Y0 (this equivals to regress out X0)
			3) perform PCA on cov(Y1) and considers the first k PC for initializing X
			4) the variance of all other PCs is used to initialize the noise
			5) the variance explained by interaction is set to a small random number 
		"""
		Xd = SP.linalg.pinv(self.X0)
		Y0 = self.X0.dot(Xd.dot(self.Y))
		Y1 = self.Y-Y0
		YY = SP.cov(Y1)
		S,U = LA.eigh(YY)
		X = U[:,-self.k:]*SP.sqrt(S[-self.k:])
		a = SP.array([SP.sqrt(Y0.var(0).mean())])
		b = 1e-3*SP.randn(1)
		c = SP.array([SP.sqrt((YY-SP.dot(X,X.T)).diagonal().mean())])
		# gp hyper params
		params = limix.CGPHyperParams()
		if self.interaction:
			params['covar'] = SP.concatenate([a,X.reshape(self.N*self.k,order='F'),SP.ones(1),b])
		else:
			params['covar'] = SP.concatenate([a,X.reshape(self.N*self.k,order='F')])
		params['lik'] = c
		return params
//  [python]
def _initParams_fast(self):
		""" 
		initialize the gp parameters
			1) project Y on the known factor X0 -> Y0
				average variance of Y0 is used to initialize the variance explained by X0
			2) considers the residual Y1 = Y-Y0 (this equivals to regress out X0)
			3) perform PCA on cov(Y1) and considers the first k PC for initializing X
			4) the variance of all other PCs is used to initialize the noise
			5) the variance explained by interaction is set to a small random number 
		"""
		Xd = LA.pinv(self.X0)
		Y0 = self.X0.dot(Xd.dot(self.Y))
		Y1 = self.Y-Y0
		YY = SP.cov(Y1)
		S,U = LA.eigh(YY)
		X = U[:,-self.k:]*SP.sqrt(S[-self.k:])
		a = SP.array([SP.sqrt(Y0.var(0).mean())])
		b = 1e-3*SP.randn(1)
		c = SP.array([SP.sqrt((YY-SP.dot(X,X.T)).diagonal().mean())])
		# gp hyper params
		params = limix.CGPHyperParams()
		if self.interaction:
			params['covar'] = SP.concatenate([a,X.reshape(self.N*self.k,order='F'),SP.ones(1),b])
		else:
			params['covar'] = SP.concatenate([a,X.reshape(self.N*self.k,order='F')])
		params['lik'] = c
		return params
//  [python]
def test_schwarz_gold(self):
        np.random.seed(0)

        cases = []
        cases.append(poisson((4,), format='csr'))
        cases.append(poisson((4, 4), format='csr'))
        A = poisson((8, 8), format='csr')
        A.data[0] = 10.0
        A.data[1] = -0.5
        A.data[3] = -0.5
        cases.append(A)

        temp = np.random.rand(1, 1)
        cases.append(csr_matrix(temp.T.dot(temp)))

        temp = np.random.rand(2, 2)
        cases.append(csr_matrix(temp.T.dot(temp)))

        temp = np.random.rand(4, 4)
        cases.append(csr_matrix(temp.T.dot(temp)))

        # reference implementation
        def gold(A, x, b, iterations, sweep='forward'):
            A = csr_matrix(A)
            n = A.shape[0]

            # Default is point-wise iteration with each subdomain a point's
            # neighborhood in the matrix graph
            subdomains =\
                [A.indices[A.indptr[i]:A.indptr[i+1]] for i in range(n)]

            # extract each subdomain's block from the matrix
            subblocks = []
            for i in range(len(subdomains)):
                blkA = (A[subdomains[i], :]).tocsc()
                blkA = blkA[:, subdomains[i]].toarray()
                blkAinv = np.linalg.pinv(blkA)
                subblocks.append(blkAinv)

            if sweep == 'forward':
                indices = np.arange(len(subdomains))
            elif sweep == 'backward':
                indices = np.arange(len(subdomains)-1, -1, -1)
            elif sweep == 'symmetric':
                indices1 = np.arange(len(subdomains))
                indices2 = np.arange(len(subdomains)-1, -1, -1)
                indices = np.concatenate((indices1, indices2))

            # Multiplicative Schwarz iterations
            for _j in range(iterations):
                for i in indices:
                    si = subdomains[i]
                    x[si] = np.dot(subblocks[i], (b[si] - A[si, :]*x)) + x[si]

            return x

        for A in cases:

            b = np.random.rand(A.shape[0], 1)
            x = np.random.rand(A.shape[0], 1)

            x_copy = x.copy()
            schwarz(A, x, b, iterations=1, sweep='forward')
            assert_almost_equal(x, gold(A, x_copy, b, iterations=1,
                                        sweep='forward'))

            x_copy = x.copy()
            schwarz(A, x, b, iterations=1, sweep='backward')
            assert_almost_equal(x, gold(A, x_copy, b, iterations=1,
                                        sweep='backward'))

            x_copy = x.copy()
            schwarz(A, x, b, iterations=1, sweep='symmetric')
            assert_almost_equal(x, gold(A, x_copy, b, iterations=1,
                                        sweep='symmetric'))
//  [python]
def test_schwarz_gold(self):
        np.random.seed(0)

        cases = []
        cases.append(poisson((4,), format='csr'))
        cases.append(poisson((4, 4), format='csr'))
        A = poisson((8, 8), format='csr')
        A.data[0] = 10.0
        A.data[1] = -0.5
        A.data[3] = -0.5
        cases.append(A)

        temp = np.random.rand(1, 1)
        cases.append(csr_matrix(temp.T.dot(temp)))

        temp = np.random.rand(2, 2)
        cases.append(csr_matrix(temp.T.dot(temp)))

        temp = np.random.rand(4, 4)
        cases.append(csr_matrix(temp.T.dot(temp)))

        # reference implementation
        def gold(A, x, b, iterations, sweep='forward'):
            A = csr_matrix(A)
            n = A.shape[0]

            # Default is point-wise iteration with each subdomain a point's
            # neighborhood in the matrix graph
            subdomains =\
                [A.indices[A.indptr[i]:A.indptr[i+1]] for i in range(n)]

            # extract each subdomain's block from the matrix
            subblocks = []
            for i in range(len(subdomains)):
                blkA = (A[subdomains[i], :]).tocsc()
                blkA = blkA[:, subdomains[i]].toarray()
                blkAinv = scipy.linalg.pinv(blkA)
                subblocks.append(blkAinv)

            if sweep == 'forward':
                indices = np.arange(len(subdomains))
            elif sweep == 'backward':
                indices = np.arange(len(subdomains)-1, -1, -1)
            elif sweep == 'symmetric':
                indices1 = np.arange(len(subdomains))
                indices2 = np.arange(len(subdomains)-1, -1, -1)
                indices = np.concatenate((indices1, indices2))

            # Multiplicative Schwarz iterations
            for _j in range(iterations):
                for i in indices:
                    si = subdomains[i]
                    x[si] = np.dot(subblocks[i], (b[si] - A[si, :]*x)) + x[si]

            return x

        for A in cases:

            b = np.random.rand(A.shape[0], 1)
            x = np.random.rand(A.shape[0], 1)

            x_copy = x.copy()
            schwarz(A, x, b, iterations=1, sweep='forward')
            assert_almost_equal(x, gold(A, x_copy, b, iterations=1,
                                        sweep='forward'))

            x_copy = x.copy()
            schwarz(A, x, b, iterations=1, sweep='backward')
            assert_almost_equal(x, gold(A, x_copy, b, iterations=1,
                                        sweep='backward'))

            x_copy = x.copy()
            schwarz(A, x, b, iterations=1, sweep='symmetric')
            assert_almost_equal(x, gold(A, x_copy, b, iterations=1,
                                        sweep='symmetric'))
//  [python]
def niqe(inputImgData):

    patch_size = 96
    module_path = dirname(__file__)

    # TODO: memoize
    params = scipy.io.loadmat(
        join(module_path, 'niqe_image_params.mat'))
    pop_mu = np.ravel(params["pop_mu"])
    pop_cov = params["pop_cov"]

    if inputImgData.ndim == 3:
        inputImgData = cv2.cvtColor(inputImgData, cv2.COLOR_BGR2GRAY)
    M, N = inputImgData.shape

    # assert C == 1, "niqe called with videos containing %d channels. Please supply only the luminance channel" % (C,)
    assert M > (patch_size*2+1), "niqe called with small frame size, requires > 192x192 resolution video using current training parameters"
    assert N > (patch_size*2+1), "niqe called with small frame size, requires > 192x192 resolution video using current training parameters"

    feats = get_patches_test_features(inputImgData, patch_size)
    sample_mu = np.mean(feats, axis=0)
    sample_cov = np.cov(feats.T)

    X = sample_mu - pop_mu
    covmat = ((pop_cov+sample_cov)/2.0)
    pinvmat = scipy.linalg.pinv2(covmat)
    niqe_score = np.sqrt(np.dot(np.dot(X, pinvmat), X))

    return niqe_score
//  [python]
def niqe(inputImgData):

    patch_size = 96
    module_path = dirname(__file__)

    # TODO: memoize
    params = scipy.io.loadmat(
        join(module_path, 'niqe_image_params.mat'))
    pop_mu = np.ravel(params["pop_mu"])
    pop_cov = params["pop_cov"]

    if inputImgData.ndim == 3:
        inputImgData = cv2.cvtColor(inputImgData, cv2.COLOR_BGR2GRAY)
    M, N = inputImgData.shape

    # assert C == 1, "niqe called with videos containing %d channels. Please supply only the luminance channel" % (C,)
    assert M > (patch_size*2+1), "niqe called with small frame size, requires > 192x192 resolution video using current training parameters"
    assert N > (patch_size*2+1), "niqe called with small frame size, requires > 192x192 resolution video using current training parameters"

    feats = get_patches_test_features(inputImgData, patch_size)
    sample_mu = np.mean(feats, axis=0)
    sample_cov = np.cov(feats.T)

    X = sample_mu - pop_mu
    covmat = ((pop_cov+sample_cov)/2.0)
    pinvmat = scipy.linalg.pinv(covmat)
    niqe_score = np.sqrt(np.dot(np.dot(X, pinvmat), X))

    return niqe_score
//  [python]
def Make_Canonical_form_symmetric(Tn,lam):
    ## We assume uniforma iMPS and left-right symmetry     
    ## Calculate left dominant eigen vector only

    chi = Tn.shape[0]

    Tn_L = np.tensordot(np.diag(lam),Tn,(1,0))
    def vL(v):
        v_new = np.tensordot(np.tensordot(v.reshape(chi,chi),Tn_L,(0,0)),Tn_L.conj(),([0,1],[0,1]))

        return v_new.reshape(chi**2)

    if chi > 1:    
        T_mat = spr_linalg.LinearOperator((chi**2,chi**2),matvec=vL)
        eig_val_L,eig_vec_L = spr_linalg.eigs(T_mat,k=1)
    else:
        eig_vec_L = np.ones(1)
        eig_val_L = vL(eig_vec_L)
        
    UL, sL, VTL = linalg.svd(np.real(eig_vec_L).reshape(chi,chi),full_matrices=False)

    Y = np.dot(UL,np.diag(np.sqrt(sL)))

    U, lam_new, VT = linalg.svd(np.dot(np.dot(Y.T,np.diag(lam)),Y.conj()),full_matrices=False)

    lam_factor = np.sqrt(np.sum(lam_new**2)) 
    lam_new /= lam_factor ## normalization

    Y_inv = linalg.pinv(Y)
    X_inv = Y_inv.conj()
    Tn_new = np.tensordot(np.tensordot(np.dot(VT,X_inv),Tn,(1,0)),np.dot(Y_inv.T,U),(2,0))

    ## normalization to be dominant eigen value = 1
    Tn_new /= np.sqrt(np.real(eig_val_L))/lam_factor
                
    return Tn_new,lam_new,eig_val_L
//  [python]
def update_with_A(self, x, mu, epsilon_mu, is_uncertain):
        """
        Franzese, Giovanni, et al. "ILoSA: Interactive learning of stiffness and attractors." 
        2021 IEEE/RSJ International Conference on Intelligent Robots and Systems (IROS). IEEE, 2021.
        """
        x = x.reshape(1, -1)
        if is_uncertain:
            # region of uncertainty - add new point
            corrected_output=np.add(mu, np.array(epsilon_mu).reshape(1, -1))
            corrected_output = np.clip(corrected_output, self.y_lim[0], self.y_lim[1]) 
            self.Y = np.concatenate((self.Y, corrected_output), axis=0)
            self.update_K_inv(x)
            self.X = np.concatenate((self.X, x), axis=0)
        else:
            # known region - correct existing data
            corrected_output = np.array(epsilon_mu).reshape(1, -1)
            k_star_ = self.kernel_(self.X, x)
            A_inv_ = np.clip(np.linalg.pinv(np.matmul(np.transpose(k_star_), self.K_inv)), -1, 1)
            self.Y= np.clip((self.Y+ (corrected_output * A_inv_)).reshape(-1, np.size(mu)), self.y_lim[0], self.y_lim[1])
//  [python]
def update_with_A(self, x, mu, epsilon_mu, is_uncertain):
        """
        Franzese, Giovanni, et al. "ILoSA: Interactive learning of stiffness and attractors." 
        2021 IEEE/RSJ International Conference on Intelligent Robots and Systems (IROS). IEEE, 2021.
        """
        x = x.reshape(1, -1)
        if is_uncertain:
            # region of uncertainty - add new point
            corrected_output=np.add(mu, np.array(epsilon_mu).reshape(1, -1))
            corrected_output = np.clip(corrected_output, self.y_lim[0], self.y_lim[1]) 
            self.Y = np.concatenate((self.Y, corrected_output), axis=0)
            self.update_K_inv(x)
            self.X = np.concatenate((self.X, x), axis=0)
        else:
            # known region - correct existing data
            corrected_output = np.array(epsilon_mu).reshape(1, -1)
            k_star_ = self.kernel_(self.X, x)
            A_inv_ = np.clip(scipy.linalg.pinv(np.matmul(np.transpose(k_star_), self.K_inv)), -1, 1)
            self.Y= np.clip((self.Y+ (corrected_output * A_inv_)).reshape(-1, np.size(mu)), self.y_lim[0], self.y_lim[1])
//  [python]
def mahalanobis(x):
    """Compute the Mahalanobis Distance between each row of x and the data
    """
    x_minus_mu = x - np.mean(x)
    cov = np.cov(x.T)  # creates a square matrix 
    try:  # if matrix matrix is not invertible use pinv
        inv_covmat = sp.linalg.inv(cov)   
    except:
        inv_covmat = sp.linalg.pinv(cov)
    results = []
    x_minus_mu = np.array(x_minus_mu)
    for i in range(np.shape(x)[0]):
        cur_data = x_minus_mu[i, :]
        results.append(np.dot(np.dot(x_minus_mu[i, :], inv_covmat), x_minus_mu[i, :].T))
    return np.array(results)
//  [python]
def mahalanobis(x):
    """Compute the Mahalanobis Distance between each row of x and the data
    """
    x_minus_mu = x - np.mean(x)
    cov = np.cov(x.T)  # creates a square matrix 
    try:  # if matrix matrix is not invertible use pinv
        inv_covmat = sp.linalg.inv(cov)   # DH old line: inv_covmat = sp.linalg.inv(cov) ||| new line: inv_covmat = sp.linalg.pinv(cov)
    except:
        inv_covmat = sp.linalg.pinv(cov)
    results = []
    x_minus_mu = np.array(x_minus_mu)
    for i in range(np.shape(x)[0]):
        cur_data = x_minus_mu[i, :]
        results.append(np.dot(np.dot(x_minus_mu[i, :], inv_covmat), x_minus_mu[i, :].T))
    return np.array(results)
//  [python]
def _ols(X, Y, rcond=1e-08):
    '''Perform OLS fit, return weight estimates
    '''
    return np.dot(s.pinv(X, rcond=rcond), Y)
//  [python]
def _ols(X, Y, rcond=1e-08):
    '''Perform OLS fit, return weight estimates
    '''
    return np.dot(LA.pinv(X, rcond=rcond), Y)
//  [python]
def __init__(self, initial_state, A, B, tau):
        super().__init__(initial_state=initial_state)
        self.A = A
        self.Bh = s.pinv(B)
        self.tau = tau
//  [python]
def __init__(self, initial_state, A, B, tau):
        super().__init__(initial_state=initial_state)
        self.A = A
        self.Bh = sla.pinv(B)
        self.tau = tau
//  [python]
def niqe(inputImgData):
    patch_size = 96
    module_path = dirname(__file__)

    # TODO: memoize
    params = scipy.io.loadmat(join(module_path, 'data', 'niqe_image_params.mat'))
    pop_mu = np.ravel(params["pop_mu"])
    pop_cov = params["pop_cov"]

    M, N = inputImgData.shape

    # assert C == 1, "niqe called with videos containing %d channels. Please supply only the luminance channel" % (C,)
    assert M > (
                patch_size * 2 + 1), "niqe called with small frame size, requires > 192x192 resolution video using current training parameters"
    assert N > (
                patch_size * 2 + 1), "niqe called with small frame size, requires > 192x192 resolution video using current training parameters"

    feats = get_patches_test_features(inputImgData, patch_size)
    sample_mu = np.mean(feats, axis=0)
    sample_cov = np.cov(feats.T)

    X = sample_mu - pop_mu
    covmat = ((pop_cov + sample_cov) / 2.0)
    pinvmat = np.linalg.pinv(covmat)
    niqe_score = np.sqrt(np.dot(np.dot(X, pinvmat), X))

    return niqe_score
//  [python]
def niqe(inputImgData):
    patch_size = 96
    module_path = dirname(__file__)

    # TODO: memoize
    params = scipy.io.loadmat(join(module_path, 'data', 'niqe_image_params.mat'))
    pop_mu = np.ravel(params["pop_mu"])
    pop_cov = params["pop_cov"]

    M, N = inputImgData.shape

    # assert C == 1, "niqe called with videos containing %d channels. Please supply only the luminance channel" % (C,)
    assert M > (
                patch_size * 2 + 1), "niqe called with small frame size, requires > 192x192 resolution video using current training parameters"
    assert N > (
                patch_size * 2 + 1), "niqe called with small frame size, requires > 192x192 resolution video using current training parameters"

    feats = get_patches_test_features(inputImgData, patch_size)
    sample_mu = np.mean(feats, axis=0)
    sample_cov = np.cov(feats.T)

    X = sample_mu - pop_mu
    covmat = ((pop_cov + sample_cov) / 2.0)
    pinvmat = scipy.linalg.pinv(covmat)
    niqe_score = np.sqrt(np.dot(np.dot(X, pinvmat), X))

    return niqe_score
//  [python]
def initialize(self, design):
        """Construct instance."""
        # PLEASE don't assume we have a constant...
        # TODO: handle case for noconstant regression
        self.design = design
        self.whitened_design = self.whiten(self.design)
        self.calc_beta = s.pinv(self.whitened_design)
        self.normalized_cov_beta = np.dot(
            self.calc_beta, np.transpose(self.calc_beta)
        )
        self.df_total = self.whitened_design.shape[0]

        eps = np.abs(self.design).sum() * np.finfo(np.float64).eps
        self.df_model = matrix_rank(self.design, eps)
        self.df_residuals = self.df_total - self.df_model
//  [python]
def initialize(self, design):
        """Construct instance."""
        # PLEASE don't assume we have a constant...
        # TODO: handle case for noconstant regression
        self.design = design
        self.whitened_design = self.whiten(self.design)
        self.calc_beta = spl.pinv(self.whitened_design)
        self.normalized_cov_beta = np.dot(
            self.calc_beta, np.transpose(self.calc_beta)
        )
        self.df_total = self.whitened_design.shape[0]

        eps = np.abs(self.design).sum() * np.finfo(np.float64).eps
        self.df_model = matrix_rank(self.design, eps)
        self.df_residuals = self.df_total - self.df_model
//  [python]
def ComputeDampingAndFrequency(self):
        """
        Compute the damping and frequencies of the complex exponentials

        """
        # Assemble the Hankel matrix Y from the samples X
        Y = np.empty((self.N - self.L, self.L + 1), dtype=self.X.dtype)
        for i in range(self.N - self.L):
            for j in range(self.L + 1):
                Y[i, j] = self.X[i + j]

        # Compute the SVD of the Hankel matrix
        self.U, self.s, self.VT = la.svd(Y)

        # Estimate the modal order M based on the singular values
        self.EstimateModelOrder()

        # Filter the right singular vectors of the Hankel matrix based on M
        Vhat = self.VT[: self.M, :]
        self.V1T = Vhat[:, :-1]
        self.V2T = Vhat[:, 1:]

        # Compute the pseudoinverse of V1T
        self.V1inv = la.pinv(self.V1T)

        # Form A matrix from V1T and V2T to reduce to eigenvalue problem
        # Jan's method -- recorded in the original Aviation paper
        # A = self.V1inv.dot(self.V2T)

        # GJK method - should only be an M x M system. No eigenvalues
        # of very small value.
        A = self.V2T.dot(self.V1inv)

        # Solve eigenvalue problem to obtain poles
        self.lam, self.W, self.V = la.eig(A, left=True, right=True)

        # Compute damping and freqency
        s = np.log(self.lam[: self.M]) / self.dt
        self.damp = s.real
        self.freq = s.imag

        # force the damping of zero frequency mode to something that
        # won't affect the KS aggregation
        for i in range(self.damp.size):
            if abs(self.freq[i]) < 1e-7:
                self.damp[i] = -99999.0

        return
//  [python]
def savitzky_golay_filter(X, order, degree):
    # Calculate vandermonde matrix.
    rng = np.arange(-order, order + 1, dtype='float64')
    s = np.vander(rng)[:, ::-1]
    S = s[:, :degree + 1]
    r, = scipy.linalg.qr(S, mode='r')[:degree + 1]
    inv_r = np.linalg.pinv(r)
    g = np.dot(S, np.dot(inv_r, inv_r.T)).astype('float64')

    filtered = np.zeros_like(X)

    for i in range(1, X.shape[0]):
        if i < order:
            window = np.zeros((order, X.shape[1]))
            window[-i:] = X[:i]
        else:
            window = X[i - order:i]

        filtered[i] = np.dot(g[:order, 0].T, window) * 2

    return filtered
//  [python]
def savitzky_golay_filter(X, order, degree):
    # Calculate vandermonde matrix.
    rng = np.arange(-order, order + 1, dtype='float64')
    s = np.vander(rng)[:, ::-1]
    S = s[:, :degree + 1]
    r, = scipy.linalg.qr(S, mode='r')[:degree + 1]
    inv_r = scipy.linalg.pinv(r)
    g = np.dot(S, np.dot(inv_r, inv_r.T)).astype('float64')

    filtered = np.zeros_like(X)

    for i in range(1, X.shape[0]):
        if i < order:
            window = np.zeros((order, X.shape[1]))
            window[-i:] = X[:i]
        else:
            window = X[i - order:i]

        filtered[i] = np.dot(g[:order, 0].T, window) * 2

    return filtered
//  [python]
def jacobian_vp(V, V_plus, U, f, Polybasis, eta, minmax, X):
    M, N = V.shape
    m, n = U.shape
    Gradient = Polybasis.get_poly_grad(eta)
    sub = (minmax[1,:]-minmax[0,:]).T
    vectord = np.reshape(2.0/sub,(n,1))
    # Initialize the tensor
    J = np.zeros((M, m, n))
    # Obtain the derivative of this tensor
    dV = np.zeros((m, n, M, N))
    for l in range(0, n):
        for j in range(0, N):
            current = Gradient[l].T
            if n == 1:
                current = Gradient.T
            dV[:,l,:,j] = np.asscalar(vectord[l])*(X.T*current[:,j])

    # Get the P matrix
    P = np.identity(M)-np.matmul(V,V_plus)
    V_minus = np.linalg.pinv(V)

    # Calculate entries for the tensor
    for j in range(0,m):
        for k in range(0,n):
            temp1 = np.linalg.multi_dot([P,dV[j,k,:,:],V_minus])
            J[:, j, k]=(-np.matmul((temp1+temp1.T),f)).reshape((M,))  # Eqn 15

    return J
//  [python]
def jacobian_vp(V, V_plus, U, f, Polybasis, eta, minmax, X):
    M, N = V.shape
    m, n = U.shape
    Gradient = Polybasis.get_poly_grad(eta)
    sub = (minmax[1,:]-minmax[0,:]).T
    vectord = np.reshape(2.0/sub,(n,1))
    # Initialize the tensor
    J = np.zeros((M, m, n))
    # Obtain the derivative of this tensor
    dV = np.zeros((m, n, M, N))
    for l in range(0, n):
        for j in range(0, N):
            current = Gradient[l].T
            if n == 1:
                current = Gradient.T
            dV[:,l,:,j] = np.asscalar(vectord[l])*(X.T*current[:,j])

    # Get the P matrix
    P = np.identity(M)-np.matmul(V,V_plus)
    V_minus = scipy.linalg.pinv(V)

    # Calculate entries for the tensor
    for j in range(0,m):
        for k in range(0,n):
            temp1 = np.linalg.multi_dot([P,dV[j,k,:,:],V_minus])
            J[:, j, k]=(-np.matmul((temp1+temp1.T),f)).reshape((M,))  # Eqn 15

    return J
//  [python]
def penrose_potential(graph : nx.Graph,mass : np.ndarray):
	rho = mass.reshape(1,-1)
	L = nx.laplacian_matrix(graph)
	L_inv = np.linalg.pinv(L.todense())
	return L_inv.dot(mass)
//  [python]
def penrose_potential(graph : nx.Graph,mass : np.ndarray):
	rho = mass.reshape(1,-1)
	L = nx.laplacian_matrix(graph)
	L_inv = scipy.linalg.pinv(L.todense())
	return L_inv.dot(mass)
//  [python]
def fit_lq1(pp):
    """ fit_lq1(points) -> t_max, [a,b,c]
    
    Fit quadratic polynom to three points in 1D. If more than three 
    points are given, the result is the least squares solution.
    
    points can be a 2D ndarray object, resulting in a general
    solution. If only 3 values are given (as list of numpy array),
    the point locations are assumed at t=(-1,0,1).
    
    """
    if isinstance(pp, np.ndarray) and pp.ndim == 2:
        # Arbitraty position of values. Apply general approach
        
        # Prepare A
        A = PointSet(3)
        for x in pp[:,0]:
            A.append(x**2, x, 1)
        Ai = np.linalg.pinv(np.matrix(A))
        # Prepare B
        B = np.matrix(pp[:,1])
        # Solve
        X = Ai * B.T
        # Find extreme
        P = X.A.ravel().tolist()    
        x = -0.5 * P[1]/P[0]   
        # Done
        return x, P
    
    else:
        # Values defined at fixed positions (-1,0,1)
        
        # Make suitable form multiplication
        B = np.matrix(pp[0:3]).transpose()
        # Solve    
        X = _precalculated_Ai1 * B    
        # Find extreme
        P = X.A.ravel().tolist()    
        x = -0.5 * P[1]/P[0]   
        # done
        return x, P
//  [python]
def fit_lq1(pp):
    """ fit_lq1(points) -> t_max, [a,b,c]
    
    Fit quadratic polynom to three points in 1D. If more than three 
    points are given, the result is the least squares solution.
    
    points can be a 2D ndarray object, resulting in a general
    solution. If only 3 values are given (as list of numpy array),
    the point locations are assumed at t=(-1,0,1).
    
    """
    if isinstance(pp, np.ndarray) and pp.ndim == 2:
        # Arbitraty position of values. Apply general approach
        
        # Prepare A
        A = PointSet(3)
        for x in pp[:,0]:
            A.append(x**2, x, 1)
        Ai = scipy.linalg.pinv(np.matrix(A))
        # Prepare B
        B = np.matrix(pp[:,1])
        # Solve
        X = Ai * B.T
        # Find extreme
        P = X.A.ravel().tolist()    
        x = -0.5 * P[1]/P[0]   
        # Done
        return x, P
    
    else:
        # Values defined at fixed positions (-1,0,1)
        
        # Make suitable form multiplication
        B = np.matrix(pp[0:3]).transpose()
        # Solve    
        X = _precalculated_Ai1 * B    
        # Find extreme
        P = X.A.ravel().tolist()    
        x = -0.5 * P[1]/P[0]   
        # done
        return x, P
//  [python]
def pinv(x):
    return np.linalg.pinv(x, 1e-6)
//  [python]
def pinv(x):
    #return np.linalg.pinv(x, max(x.shape) * np.spacing(np.linalg.norm(x)))
    #return scipy.linalg.pinv(x, max(x.shape) * np.spacing(np.linalg.norm(x)))
    return scipy.linalg.pinv(x, 1e-6)
//  [python]
def niqe(inputImgData):
    patch_size = 96
    module_path = dirname(__file__)

    # TODO: memoize
    params = scipy.io.loadmat(join(module_path, 'niqe_image_params.mat'))
    pop_mu = np.ravel(params["pop_mu"])
    pop_cov = params["pop_cov"]

    M, N = inputImgData.shape

    # assert C == 1, "niqe called with videos containing %d channels. Please supply only the luminance channel" % (C,)
    assert M > (
                patch_size * 2 + 1), "niqe called with small frame size, requires > 192x192 resolution video using current training parameters"
    assert N > (
                patch_size * 2 + 1), "niqe called with small frame size, requires > 192x192 resolution video using current training parameters"

    feats = get_patches_test_features(inputImgData, patch_size)
    sample_mu = np.mean(feats, axis=0)
    sample_cov = np.cov(feats.T)

    X = sample_mu - pop_mu
    covmat = ((pop_cov + sample_cov) / 2.0)
    pinvmat = scipy.linalg.pinv2(covmat)
    niqe_score = np.sqrt(np.dot(np.dot(X, pinvmat), X))

    return niqe_score
//  [python]
def niqe(inputImgData):
    patch_size = 96
    module_path = dirname(__file__)

    # TODO: memoize
    params = scipy.io.loadmat(join(module_path, 'niqe_image_params.mat'))
    pop_mu = np.ravel(params["pop_mu"])
    pop_cov = params["pop_cov"]

    M, N = inputImgData.shape

    # assert C == 1, "niqe called with videos containing %d channels. Please supply only the luminance channel" % (C,)
    assert M > (
                patch_size * 2 + 1), "niqe called with small frame size, requires > 192x192 resolution video using current training parameters"
    assert N > (
                patch_size * 2 + 1), "niqe called with small frame size, requires > 192x192 resolution video using current training parameters"

    feats = get_patches_test_features(inputImgData, patch_size)
    sample_mu = np.mean(feats, axis=0)
    sample_cov = np.cov(feats.T)

    X = sample_mu - pop_mu
    covmat = ((pop_cov + sample_cov) / 2.0)
    pinvmat = scipy.linalg.pinv(covmat)
    niqe_score = np.sqrt(np.dot(np.dot(X, pinvmat), X))

    return niqe_score
//  [python]
def matrixPower(A, n):
        """
        Compute the matrix power of A using the exponent n. The computation simply
        evaluated the eigendecomposition of A and then powers the eigenvalue
        matrix accordingly.
        
        Warning: if at least one eigen-value is negative, n should be an integer.
        """
        Parameter.checkClass(A, numpy.ndarray)
        tol = 10**-10

        lmbda, V = scipy.linalg.eig(A)
        lmbda[numpy.abs(lmbda) <= tol] = 0
        lmbda[numpy.abs(lmbda) > tol] = lmbda[numpy.abs(lmbda) > tol]**n
        
        if n >= 0: 
            return (V*lmbda).dot(numpy.linalg.inv(V))
        else: 
            A = numpy.linalg.pinv(A)
            n = numpy.abs(n)
            lmbda, V = scipy.linalg.eig(A)
            lmbda[numpy.abs(lmbda) > tol] = lmbda[numpy.abs(lmbda) > tol]**n
            return (V*lmbda).dot(numpy.linalg.inv(V))
//  [python]
def matrixPower(A, n):
        """
        Compute the matrix power of A using the exponent n. The computation simply
        evaluated the eigendecomposition of A and then powers the eigenvalue
        matrix accordingly.
        
        Warning: if at least one eigen-value is negative, n should be an integer.
        """
        Parameter.checkClass(A, numpy.ndarray)
        tol = 10**-10

        lmbda, V = scipy.linalg.eig(A)
        lmbda[numpy.abs(lmbda) <= tol] = 0
        lmbda[numpy.abs(lmbda) > tol] = lmbda[numpy.abs(lmbda) > tol]**n
        
        if n >= 0: 
            return (V*lmbda).dot(numpy.linalg.inv(V))
        else: 
            A = scipy.linalg.pinv(A)
            n = numpy.abs(n)
            lmbda, V = scipy.linalg.eig(A)
            lmbda[numpy.abs(lmbda) > tol] = lmbda[numpy.abs(lmbda) > tol]**n
            return (V*lmbda).dot(numpy.linalg.inv(V))
//  [python]
def niqe(inputImgData):

    patch_size = 96
    module_path = dirname(__file__)

    # TODO: memoize
    params = scipy.io.loadmat(join(module_path, "niqe_image_params.mat"))
    pop_mu = np.ravel(params["pop_mu"])
    pop_cov = params["pop_cov"]

    if inputImgData.ndim == 3:
        inputImgData = cv2.cvtColor(inputImgData, cv2.COLOR_BGR2GRAY)
    M, N = inputImgData.shape

    assert M > (
        patch_size * 2 + 1
    ), "niqe called with small frame size, requires " \
       "> 192x192 resolution video using current training parameters"
    assert N > (
        patch_size * 2 + 1
    ), "niqe called with small frame size, requires > 192x192 " \
       "resolution video using current training parameters"

    feats = get_patches_test_features(inputImgData, patch_size)
    sample_mu = np.mean(feats, axis=0)
    sample_cov = np.cov(feats.T)

    X = sample_mu - pop_mu
    covmat = (pop_cov + sample_cov) / 2.0
    pinvmat = scipy.linalg.pinv(covmat)
    niqe_score = np.sqrt(np.dot(np.dot(X, pinvmat), X))

    return niqe_score
//  [python]
def getStdDevForParams(self):
        # type: () -> (np._ArrayLike[float])
        # this might not be working correctly
        if self.opt['useAPriori']:
            tauDiff = self.model.tauMeasured - self.tauEstimated
        else:
            tauDiff = self.tauEstimated

        if self.opt['floatingBase']: fb = 6
        else: fb = 0

        # get relative standard deviation of measurement and modeling error \sigma_{rho}^2
        r = self.data.num_used_samples * (self.model.num_dofs + fb)
        rho = np.square(sla.norm(tauDiff))
        sigma_rho = rho / (r - self.model.num_base_params)

        # get standard deviation \sigma_{x} (of the estimated parameter vector x)
        C_xx = sigma_rho * (sla.pinv(np.dot(self.model.YBase.T, self.model.YBase)))
        sigma_x = np.diag(C_xx)

        # get relative standard deviation
        p_sigma_x = np.sqrt(sigma_x)
        for i in range(0, p_sigma_x.size):
            if self.model.xBase[i] != 0:
                p_sigma_x[i] /= np.abs(self.model.xBase[i])

        return p_sigma_x
//  [python]
def least_squares(mat, y):
    return la.pinv2(mat.conjugate().transpose().dot(mat)).dot(
        mat.conjugate().transpose().dot(y))
//  [python]
def least_squares(mat, y):
    return la.pinv(mat.conjugate().transpose().dot(mat)).dot(
        mat.conjugate().transpose().dot(y))
//  [python]
def _build_information(self):
        """Build the inverse of hessian of the log likelihood at theta_
        """
        lag_time = float(self.lag_time)

        # only the "active set" of variables not at the bounds of the
        # feasible set.
        inds = np.where(self.theta_ != 0)[0]

        hessian = _ratematrix.hessian(
            self.theta_, self.countsmat_, t=lag_time, inds=inds)

        self.information_ = np.zeros((len(self.theta_), len(self.theta_)))
        self.information_[np.ix_(inds, inds)] = scipy.linalg.pinv(-hessian)