## 2019-06-26 QL ** create to run 100 boostrap for AbsPCC ###
#######################################################################################################

import numpy as np 
import pandas as pd 
import sys
import random
from scipy import stats as st 
import networkx as nx
import time 

#######################################################################################################

## df is the expression data set, rows are the genes and columns are samples, like different experiment
def absPCC(df, x, directory, fn):
	fw = open(r"./" + directory + "/" + fn + "_"+str(x)+".txt", "w")
	start_time = time.time()
	
	for i in range(df.shape[0]):
		A = df.iloc[i,1:]
		for j in range(i+1, df.shape[0]):
			B = df.iloc[j,1:]
			p = round(abs(st.pearsonr(A, B)[0]), 3)
			fw.write(str(df.iloc[i, 0])+"\t" + str(df.iloc[j, 0]) +"\t"+str(p) + "\n")
			fw.flush()
	fw.close()
	print ("---%s seconds --" % (time.time() - start_time))

#######################################################################################################

#### calculate threshold ###
# df is the result network with three columns: node1, node2, edge weight 
def threshold(x, directory, fn):
	df = pd.read_csv("./" + directory + "/" + fn + "_"+str(x)+".txt", header = None, sep = "\t")
	weight = df.iloc[:, 2].tolist()
	thre = round(sum(weight)*1.0/len(weight), 3)
	print (thre)
	f = open("./" + directory + "/threshold_" + str(x) + ".txt", "w")
	f.write(str(thre))
	f.close()

def threshold_cut(x, directory, fn, thre):
	df = pd.read_csv("./" + directory + "/" + fn + "_"+str(x)+".txt", header = None, sep= "\t")
	df.columns = ["V1", "V2", "E"]
	df = df.loc[df['E'] > thre]
	return (df)


def threshold1(x, directory, fn, df):
	weight = df.iloc[:, 2].tolist()
	thre = sum(weight)*1.0/len(weight)
	print (thre)
	f = open("./" + directory + "/threshold_" + str(x) + ".txt", "w")
	f.write(str(thre))
	f.close()

#######################################################################################################

### random shuffle the  data ###
def Rand_EXP(df, axis=0):     
	df1 = df.apply(np.random.permutation, axis=axis)
	return (df1)

#####################################################################################################

## Bootstrap data ###
## k: # of samples to choose, total 183 in our case;  
## i: seed number
## df1 is the boostraped expression data set 
def Bootstrap(df, k, i):
	random.seed(i)
	col_ind = [random.randint(1, df.shape[1]-1) for _ in range(k)]
	col = df.columns.tolist()
	col = col[0:1] + [col[x] for x in col_ind]
	df1 = df[col]
	df1.columns = range(len(col))
	return (df1) 

#######################################################################################################
## DPI ###
def DPI(edgelist):
	edgelist.columns = ['V1', 'V2', 'E']
	G = nx.from_pandas_edgelist(edgelist, 'V1', 'V2', 'E')
	G1 = nx.from_pandas_edgelist(edgelist, 'V1', 'V2', 'E')
	cycls_3 = [c for c in nx.cycle_basis(G) if len(c)==3]
	for i in cycls_3:
		A = G1.get_edge_data(i[0], i[1])['E']
		B = G1.get_edge_data(i[0], i[2])['E']
		C = G1.get_edge_data(i[1], i[2])['E']
		if A == min(A, B, C):
			try:
				G.remove_edge(i[0], i[1])
			except:
				continue
		if B == min(A, B, C):
			try:
				G.remove_edge(i[0], i[2])
			except:
				continue
		if C == min(A, B, C):
			try:
				G.remove_edge(i[1], i[2])
			except:
				continue
	edgelist_DPI = nx.to_pandas_edgelist(G)
	return (edgelist_DPI)

## matrix to edgelist ##
def MatrixToList(geneID, mat, directory, x, fn):

	fw = open(r"./" + directory + "/" + fn + "_"+str(x)+".txt", "w")
	for i in range(mat.shape[0]):
		for j in range(i, mat.shape[1]):
			fw.write(str(geneID[i])+"\t" + str(geneID[j]) +"\t"+ str(mat[i, j]) + "\n")
			fw.flush()	
	fw.close()

#######################################################################################################
