%matplotlib inline

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

"""
Explanation: PyHRM - High Resolution Melt Analysis in Python
Introduction
Hosted at https://github.com/liuyigh/PyHRM 
Please read a very nice introduction provided by Kapa BioSystems to understand, prepare and troubleshoot
http://www.kapabiosystems.com/document/introduction-high-resolution-melt-analysis-guide/
Import Python modules for analysis
End of explanation
"""


df = pd.read_csv('Sample-HRM-p50-genotyping.csv')
plt.plot(df.iloc[:, 0],df.iloc[:,1:])
plt.show()

"""
Explanation: Read and Plot Melting Data
Go to GitHub to view the format of data file. Basically, it's a CSV file exported from CFX manager data analysis melting curve data "RFU" table (Right click to export to CSV). Open with Excel, delet the empty column. First column "Temperature", each of following columns represent a sample well.
End of explanation
"""


df_melt=df.loc[(df.iloc[:,0]>75) & (df.iloc[:,0]<88)]
df_data=df_melt.iloc[:,1:]
plt.plot(df_melt.iloc[:, 0],df_data)
plt.show()

"""
Explanation: Select melting range
Based on the plot above, select a range of temperature.
End of explanation
"""


df_norm= (df_data - df_data.min()) / (df_data.max()-df_data.min())*100
plt.plot(df_melt.iloc[:, 0],df_norm)
plt.show()

"""
Explanation: Normalizing
End of explanation
"""


dfdt = df_norm.diff()
plt.plot(df_melt.iloc[:,[0]],dfdt)
plt.show()

dfdtWithTemp = pd.concat([df_melt.iloc[:,[0]],dfdt],axis=1)
meltTempList = dfdtWithTemp.set_index('Temperature').idxmin()

"""
Explanation: Melting Temp
End of explanation
"""


dfdif = df_norm.sub(df_norm['J14'],axis=0)
plt.plot(df_melt.iloc[:, 0],dfdif)
plt.show()

"""
Explanation: Calculate and Show Diff Plot
End of explanation
"""


import sklearn.cluster as sc
from IPython.display import display

mat = dfdif.T
hc = sc.KMeans(n_clusters=3)
hc.fit(mat)

labels = hc.labels_
results = pd.DataFrame([dfdif.T.index,labels])
display(results.loc[:0,results.iloc[1]==0])
display(results.loc[:0,results.iloc[1]==1])
display(results.loc[:0,results.iloc[1]==2])

"""
Explanation: Clustering
Use KMeans module from SciKit-Learn to cluster your sample into three groups (WT, KO, HET). Be careful, your samples may have less than three groups. So always check the diff plots first.
End of explanation
"""


