import pandas as pd
import numpy as np
from sklearn.decomposition import PCA
from sklearn import preprocessing
import matplotlib.pyplot as plt

dataset = pd.read_csv('MC_8Core.csv',index_col=0,decimal=',')  # costruisci dataset da csv

print(dataset.head())
print(dataset.shape)

scaled_data = preprocessing.scale(dataset) #normalizza trasposta del dataset

pca=PCA() #crea oggetto PCA
pca.fit(scaled_data) #fa la pca
pca_data = pca.transform(scaled_data) #prendi Coordinate PCA dai dati normalizzati

##PLOT

#SCREE PLOT
per_var = np.round(pca.explained_variance_ratio_* 100, decimals=1)
labels = ['PC' + str(x) for x in range(1, len(per_var)+1)]

plt.bar(x=range(1,len(per_var)+1), height=per_var, tick_label=labels)
plt.ylabel('Percentage of Explained Variance')
plt.xlabel('Principal Component')
plt.title('Scree Plot')
plt.show()

#the following code makes a fancy looking plot using PC1 and PC2
pca_df = pd.DataFrame(pca_data,index=dataset.index, columns=labels)
 
plt.scatter(pca_df.PC1, pca_df.PC2)
plt.title('My PCA Graph')
plt.xlabel('PC1 - {0}%'.format(per_var[0]))
plt.ylabel('PC2 - {0}%'.format(per_var[1]))
 
for sample in pca_df.index:
    plt.annotate(sample, (pca_df.PC1.loc[sample], pca_df.PC2.loc[sample]))
 
plt.show()


## get the name of the top 10 measurements (disturbi) that contribute
## most to pc1.
## first, get the loading scores
loading_scores = pd.Series(pca.components_[0], index=dataset.columns)
## now sort the loading scores based on their magnitude
sorted_loading_scores = loading_scores.abs().sort_values(ascending=False)

# get the names of the top 10 genes
top_metrics = sorted_loading_scores.index.values

## print the gene names and their scores (and +/- sign)
print(loading_scores[top_metrics])
