

import numpy as np #for all numerical computations
import pandas as pd #similar to dataframe in R
import scipy as sp #scientific computations (includes stats)
import matplotlib.pyplot as plt #plotting 
import scipy.io as sio
import cvxpy as cp # convex optimization
import random
import sys
import time
import gc
import math

def deterministic_SPCA(data, s, l):
    
    from sklearn.utils.extmath import randomized_svd
    
    UZ, SigZ, VTZ =randomized_svd(Z, n_components=l)
    print("SVD done") 
    #----------------------------------------
    #deterministic spca
    #----------------------------------------

    col_normsq= np.linalg.norm(VTZ,axis=0)**2
    max_ids= col_normsq.argsort()[-s:][::-1]

    idx=np.where(col_normsq < col_normsq[max_ids[s-1]])[0]

    VTZ_R=VTZ.copy()
    VTZ_R[np.ix_(range(VTZ.shape[0]),idx)]=0

    U, Sig, VT= randomized_svd(np.matmul(np.diag(SigZ),VTZ_R), n_components=1)
    y_dspca= VT[0]
    
    # Calculate f (y)
    f_dspca=np.sum(np.square(np.matmul(data,y_dspca)))/np.linalg.norm(data, 2)**2 

    #---------------end of dspca-------------------------

    print("dspca done!")
    return y_dspca, f_dspca