<gh_stars>0
import os,sys,os.path,numpy as np,copy
import contratio as crat
import astropy.io.fits as pyfits
import scipy.ndimage as nd,matplotlib.pyplot as plt
sys.path.append('/Users/awallace/Documents/pynrm/')
import stats
nameList = sys.argv[4:len(sys.argv)]
if len(sys.argv)<4:
    print('Useage: crat_all_images.py data_directory_location plot_directory num_cals_per_target object_name (with spaces)')
    sys.exit()
#Combine name into single string
name = ''
if len(nameList)>1:
    for ii in range(0,len(nameList)):
        name+=nameList[ii]
        if ii<len(nameList)-1:
            name+=' '
else:
	name = nameList[0]
#Remove Spaces From Object Name
objNoSpaces = name.split(' ')
objName = ''.join(objNoSpaces)
if sys.argv[1][0]=='/':
	dataDir = sys.argv[1]
else:
	dataDir = os.getcwd()+'/'+sys.argv[1]
if sys.argv[2][0]=='/':
	plotDir = sys.argv[2]
else:
	plotDir = os.getcwd()+'/'+sys.argv[2]

objDir = plotDir+'/'+objName
if not os.path.isdir(objDir):
	os.makedirs(objDir)
outfiles = []
#cycle through all existing data files
for year in range(11,20):
	for month in range(1,13):
		for day in range(1,32):
			directory = '%02d'%(year,)+'%02d'%(month,)+'%02d'%(day,)
			rawDir = dataDir+'/'+directory
			cubeDir = rawDir+'_cubes'
			if not os.path.isfile(rawDir+'/blockinfo.txt'):
				continue
			if not os.path.isdir(cubeDir):
				continue
			lineNums = []
			all_elements = []
			elements = []
			cal_els = []
			tgt_cubes = []
			cal_cubes = []
			total = -1
			allDirs = []
			infoFile = open(rawDir+'/blockinfo.txt','r')
			mm = 0
			count = 0
			#Only proceed if the given object was observed on this particular night
			for line1 in infoFile:
				if name in line1:
					count+=1
			if count<1:
				continue
			allDirs.append(rawDir)
			infoFile = open(rawDir+'/blockinfo.txt','r')
			#Find line and frame numbers where the name appears
			for line in infoFile:
				mm+=1
				if mm==1:
					continue
				total+=1
				entry = line.split(' ')
				newEntry = []
				for nn in range(0,len(entry)):
					if not entry[nn]=='':
						newEntry.append(entry[nn])
				#Find object name
				cubeFile = cubeDir+'/cube'+str(int(entry[0]))+'.fits'
				if os.path.isfile(cubeFile) and pyfits.getheader(cubeFile)['OBJECT']==name:
					elements.append([int(entry[0]),rawDir])
					lineNums.append([total,rawDir])
				all_elements.append([int(entry[0]),rawDir])
			#Create target cube list
			for ii in range(0,len(elements)):
				cubeDir = elements[ii][1]+'_cubes'
				tgt_cubes.append(cubeDir+'/cube'+str(elements[ii][0])+'.fits')

			#Find calibrators from objects nearby in the list.  Go one step in both directions and add frame to
			#list of calibrators.
			els = [ii for ii,jj in enumerate(tgt_cubes) if cubeDir in jj]
			#print(lineNums)
			numCals = int(sys.argv[3])*len(els)
			for kk in els:
				ii = lineNums[kk][0]
				jj = lineNums[kk][0]
				cubeDir = elements[kk][1]+'_cubes'
				while ii>=0 or jj<len(all_elements):
					if ii>=0 and os.path.isfile(cubeDir+'/cube'+str(all_elements[ii][0])+'.fits'):
						header = pyfits.getheader(cubeDir+'/cube'+str(all_elements[ii][0])+'.fits')
						if not all_elements[ii][1]==rawDir:
							break
						if not header['OBJECT']==name:
							cal_els.append(all_elements[ii])
						ii-=1
					elif not os.path.isfile(cubeDir+'/cube'+str(all_elements[ii][0])+'.fits'):
						ii-=1
					if len(cal_els)>=int(sys.argv[3])*(kk+1):
						break
					if jj<len(all_elements) and os.path.isfile(cubeDir+'/cube'+str(all_elements[jj][0])+'.fits'):
						header = pyfits.getheader(cubeDir+'/cube'+str(all_elements[jj][0])+'.fits')
						if not all_elements[jj][1]==rawDir:
							continue
						if not header['OBJECT']==name:
							cal_els.append(all_elements[jj])
						jj+=1
					elif jj>=len(all_elements) or not os.path.isfile(cubeDir+'/cube'+str(all_elements[jj][0])+'.fits'):
						jj+=1
					if len(cal_els)>=int(sys.argv[3])*(kk+1):
						break
			tgt_ims = []
			cal_ims = []
			pas = []
			#Make sure there are no duplicates
			cal_els.sort()
			new_els = []
			for ii in range(0,len(cal_els)):
				if ii==0:
					new_els.append(cal_els[ii])
				elif not cal_els[ii]==cal_els[ii-1]:
					new_els.append(cal_els[ii])
			cal_els = new_els
			#Create target cube list
			new_cubes = []
			tgt_els = []
			for ii in range(0,len(tgt_cubes)):
				cube = pyfits.getdata(tgt_cubes[ii])
				pa = pyfits.getdata(tgt_cubes[ii],1)['pa']
				for jj in range(0,len(cube)):
					image = cube[jj]
					if (np.max(image)-np.mean(image))/np.std(image)>19:
						tgt_ims.append(image)
						pas.append(pa[jj])
						new_cubes.append(tgt_cubes[ii])
						tgt_els.append(jj)
			#Create calibrator list
			cal_objects = []
			for ii in range(0,len(cal_els)):
				cubeDir = cal_els[ii][1]+'_cubes'
				cal_cubes.append(cubeDir+'/cube'+str(cal_els[ii][0])+'.fits')
				cube = pyfits.getdata(cal_cubes[ii])
				num = 0
				for jj in range(0,len(cube)):
					image = cube[jj]
					if (np.max(image)-np.mean(image))/np.std(image)>19:
						num+=1
				for jj in range(0,len(cube)):
					image = cube[jj]
					cal = [pyfits.getheader(cal_cubes[ii])['OBJECT'],cubeDir+'/cube'+str(cal_els[ii][0])+'.fits',str(num),str(jj)]
					if (np.max(image)-np.mean(image))/np.std(image)>19:
						cal_ims.append(image)
						cal_objects.append(cal)

			tgt_ims = np.array(tgt_ims)
			cal_ims = np.array(cal_ims)
			all_ims = []
			#Restructure tgt_cubes vector so there is an entry for each image
			#When this is stored in the FITS file, it shows where each image came from
			tgt_cubes = new_cubes
			#Store target and calibration images in one file
			tempFile = plotDir+'/temp.fits'
			header = pyfits.getheader(tgt_cubes[0])
			radec = [header['RA'],header['DEC']]
			hdu1 = pyfits.PrimaryHDU(tgt_ims, header)
			hdu2 = pyfits.ImageHDU(cal_ims)
			col1 = pyfits.Column(name='pa', format='E', array=pas)
			col2 = pyfits.Column(name='cal_objects', format='A40', array=[row[0] for row in cal_objects])
			col3 = pyfits.Column(name='cal_cubes', format='A200', array=[row[1] for row in cal_objects])
			col4 = pyfits.Column(name='cal_lengths', format='A40', array=[row[2] for row in cal_objects])
			col5 = pyfits.Column(name='cal_els', format='A40', array=[row[3] for row in cal_objects])
			col6 = pyfits.Column(name='tgt_cubes', format='A200', array=tgt_cubes)
			col7 = pyfits.Column(name='tgt_els', format='E', array=tgt_els)
			hdu3 = pyfits.BinTableHDU.from_columns(pyfits.ColDefs([col1,col2,col3,col4,col5,col6,col7]))
			hdulist = pyfits.HDUList([hdu1,hdu2,hdu3])
			hdulist.writeto(tempFile, clobber=True)
			#Create contrast ratio plots (one crat file for each night this object was observed)
			crat_file = crat.best_psf_subtract(tempFile,plotDir)
			#Clean up and rename crat file to something unique
			os.system('rm -rf '+tempFile)
			os.system('mv '+crat_file+' crat'+str(year)+str(month)+str(day)+'.fits')
			outfiles.append('crat'+str(year)+str(month)+str(day)+'.fits')

crat_ims = []
pas = []
cal_objects = []
cal_cubes = []
cal_lengths = []
cal_elements = []
tgt_cubes = []
oldHeader = pyfits.getheader(outfiles[0])
sizes = []
tgt_elements = []
#Extract information from crat files creating image array
for ii in range(0,len(outfiles)):
	infile = outfiles[ii]
	ims = pyfits.getdata(infile)
	extra = pyfits.getdata(infile,1)
	for jj in range(0,len(ims)):
		crat_ims.append(ims[jj])
		sizes.append(ims[jj].shape[0])
		pas.append(extra['pa'][jj])
		cal_objects.append(extra['cal_objects'][jj])
		cal_cubes.append(extra['cal_cubes'][jj])
		cal_elements.append(extra['cal_elements'][jj])
		tgt_cubes.append(extra['tgt_cubes'][jj])
		tgt_elements.append(extra['tgt_elements'][jj])
	os.system('rm -rf '+infile)
bigSize = max(sizes)
#Make all crat images same size by zooming out if necessary
for ii in range(0,len(crat_ims)):
	if crat_ims[ii].shape[0]==bigSize:
		continue
	smallSize = crat_ims[ii].shape[0]
	newArray = np.zeros((bigSize,bigSize))
	newArray[bigSize//2-smallSize//2:bigSize//2+smallSize//2,bigSize//2-smallSize//2:bigSize//2+smallSize//2] = crat_ims[ii]
	crat_ims[ii] = newArray

dates = []
#Create array showing the date each image was taken
for ii in range(0,len(tgt_cubes)):
	for jj in range(0,len(tgt_cubes[ii])-11):
		if tgt_cubes[ii][jj:jj+11]=='_cubes/cube':
			break
	dateString = tgt_cubes[ii][jj-6:jj]
	months = 'JANFEBMARAPRMAYJUNJULAUGSEPOCTNOVDEC'
	date = str(int(dateString[4:6])) + '-' + months[3*(int(dateString[2:4])-1):3*int(dateString[2:4])] + '-20' + dateString[0:2]
	dates.append(date)

#Store all crat information in one file
sz = crat_ims[0].shape[0]
header = pyfits.Header(oldHeader)
header['CRVAL1']=header['RA']
header['CRVAL2']=header['DEC']
header['CRPIX1']=sz//2
header['CRPIX2']=sz//2
header['CDELT1']=-1./(3600*1024)
header['CDELT2']=1./(3600*1024)
header['CTYPE1']='RA---TAN'
header['CTYPE2']='DEC--TAN'
header['CD1_1']=-0.01/3600.
header['CD2_2']=0.01/3600.
header['CD1_2']=0
header['CD2_1']=0
header['OBJECT']=oldHeader['OBJECT']
hdu = pyfits.PrimaryHDU(crat_ims,header)
col1 = pyfits.Column(name='pa', format='E', array=pas)
col2 = pyfits.Column(name='cal_objects', format='A40', array=cal_objects)
col3 = pyfits.Column(name='cal_cubes', format='A200', array=cal_cubes)
col4 = pyfits.Column(name='cal_elements', format='E', array=cal_elements)
col5 = pyfits.Column(name='tgt_cubes', format='A200', array=tgt_cubes)
col6 = pyfits.Column(name='tgt_indices', format='E', array=tgt_elements)
col7 = pyfits.Column(name='observation_dates', format='A40', array=dates)
hdu2 = pyfits.BinTableHDU.from_columns(pyfits.ColDefs([col1,col2,col3,col4,col5,col6,col7]))
hdulist = pyfits.HDUList([hdu,hdu2])
hdulist.writeto(crat_file,clobber=True)
crat_im = pyfits.getdata(crat_file)
pas = pyfits.getdata(crat_file,1)['pa']
#Take average over frames
result = np.mean(crat_im,axis=0)
oldSize = pyfits.getdata(tgt_cubes[0]).shape[1]
"""newPA = np.mean(pas)
#Set up rotation angle so image is approximately aligned
#Make sure north is never more than 45 degrees from vertical
newRot = newPA
while newRot>180:
    newRot-=360
while newRot<-180:
    newRot+=360
newRot = 90-newRot
while newRot>45 or newRot<-45:
    if newRot<0:
        newRot+=90
    elif newRot>0:
        newRot-=90

result = nd.rotate(result,newRot,reshape=True)
size = result.shape[0]
sz = pyfits.getdata(tgt_cubes[0]).shape[1]
#Resize the result so it is the same size as original image
result = result[size//2-sz//2:size//2+sz//2,size//2-sz//2:size//2+sz//2]"""
#Store average plot in FITS file
hdu = pyfits.PrimaryHDU(result)
#costerm = np.cos(np.radians(newRot))*0.01/3600.
#sinterm = np.sin(np.radians(newRot))*0.01/3600.
header = pyfits.getheader(tgt_cubes[0])
hdu.header = header
hdu.header['CRVAL1']=radec[0]
hdu.header['CRVAL2']=radec[1]
hdu.header['CTYPE1']='RA---TAN'
hdu.header['CTYPE2']='DEC--TAN'
hdu.header['CRPIX1']=sz//2
hdu.header['CRPIX2']=sz//2
hdu.header['CD1_1']=-0.01/3600.
hdu.header['CD2_2']=0.01/3600.
hdu.header['CD1_2']=0
hdu.header['CD2_1']=0
hdu.header['OBJECT']=name
#hdu.header['RADECSYS']='FK5'
hdulist = pyfits.HDUList([hdu])
hdulist.writeto(objDir+'/ave_crat_'+objName+'_'+str(oldSize)+'.fits', clobber=True)
#Find weighted mean
mean_im = stats.weighted_mean(crat_im)
std_im = stats.bootstrap(crat_im,100)
std_im[np.where(std_im==0)] = 1e9
significance = mean_im/std_im

"""mean_im = nd.rotate(mean_im,newRot,reshape=True)
size = mean_im.shape[0]
mean_im = mean_im[size//2-sz//2:size//2+sz//2,size//2-sz//2:size//2+sz//2]
"""
hdu2 = pyfits.PrimaryHDU(mean_im)
hdu2.header = hdu.header
hdulist = pyfits.HDUList([hdu2])
hdulist.writeto(objDir+'/weighted_mean_'+objName+'_'+str(oldSize)+'.fits', clobber=True)
"""significance = nd.rotate(significance,newRot,reshape=True)
size = significance.shape[0]
significance = significance[size//2-sz//2:size//2+sz//2,size//2-sz//2:size//2+sz//2]"""
#significance[np.where(significance>100*np.median(significance))] = 0
#significance[np.where(np.isnan(significance))] = 0
hdu3 = pyfits.PrimaryHDU(significance)
hdu3.header = hdu.header
hdulist = pyfits.HDUList([hdu3])
hdulist.writeto(objDir+'/significance_'+objName+'_'+str(oldSize)+'.fits', clobber=True)


import pandas as pd
from scipy.stats import ttest_ind
from sklearn.svm import SVC
from sklearn.feature_selection import RFECV

def read_data(path):
    """
    reads the csv data

    Args:
    path - path to the csv file

    Returns:
    A pandas dataframe and its labels
    """

    data = pd.read_csv(path)
    data.set_index("index",inplace = True)
    labels = data.pop("labels")
    return data, labels

def get_DEG(p_value, dataset, labels, log_FC):
    """
    Finds differentially expressed genes with the given p_value and fold_change using independent t-test

    Args:
    p_value - int value for specifying the p value for stastical significance
    dataset - csv dataset on which the differential expression analysis is to be performed
    fold_change - int value depicting fold change

    Returns:
    A pandas dataframe containing genes that are differentially expressed with given p value and fold change
    """

    dataset['labels'] = labels
    groups = dataset.groupby("labels")
    normal_sample = groups.get_group("normal")
    tumor_sample = groups.get_group("tumor")
    tumor_sample = tumor_sample.drop(["labels"], axis = 1)
    normal_sample = normal_sample.drop(["labels"], axis = 1)

    columns = normal_sample.columns
    print(columns)
    t_data = []
    for i in range(0,(len(columns)-1)):
        a = normal_sample[columns[i]]
        b = tumor_sample[columns[i]]
        # T-test
        t,p = ttest_ind(a,b)
        if p<p_value:
            t_data.append(columns[i])

    p_data = pd.DataFrame(dataset, columns = t_data)
    p_data["samples"] = labels

    #for fold change
    group = p_data.groupby("samples")
    norm_sample = group.get_group("normal")
    tumr_sample = group.get_group("tumor")
    tumr_sample.drop("samples", axis = 1, inplace = True)
    norm_sample.drop("samples", axis = 1, inplace = True)

    fold = []
    for i in tumr_sample.columns:
        f = tumr_sample[i].mean() - norm_sample[i].mean()
        if f < -(log_FC) or f >(log_FC):
            fold.append(i)
    deg = pd.DataFrame(dataset, columns = fold)
    return deg

def svc_rfe_cv(dataset, label):
    """
    Performing recursive feature elimination using support vector classifier with 10 fold cross validation

    Args:
    dataset - training data
    label - trainig data labels

    Returns:
    A  list of most informative columns according to SVC_RFE
    """
    estimator = SVC(kernel="linear")
    selector = RFECV(estimator, min_features_to_select=100, step=1, cv = 10)
    selector = selector.fit(dataset, label)
    training_data = dataset[dataset.columns[selector.get_support()]]

    return training_data

if __name__ == '__main__':
    save_data_path = "E:/project"
    read_data_path = "E:/project/gene_data.csv"
    print("\nReading data\n")
    data,labels = read_data(read_data_path)
    data['labels'] = labels
    print("\nPerforming Differential expression analysis using independent t__test\n")
    deg_data = get_DEG(0.0001,data,labels, 1)
    print(f"\nDataset shape{deg_data.shape}\nPerforming recursive feature eliminiation using SVC\n")
    print(deg_data.columns,"\n")
    print("\nNull values in data: ",deg_data.isnull().values.any(),"\nNull values in Labels: ", labels.isnull().values.any())
    training_data = svc_rfe_cv(deg_data, labels)
    training_data['labels'] = labels
    print(f"\nDataset shape{training_data.shape}\nSaving data...\n")
    training_data.to_csv(f"{save_data_path}/training_data.csv", index = True)
    print("Done")


<reponame>terasakisatoshi/pythonCodes<filename>fourierAnalysis/from_scratch/get_fourier.py
import numpy as np
from matplotlib import pyplot as plt
from scipy import integrate

Pi=np.pi
T=2*Pi
N= 50

target_func=None
fourier_series=None

def getVarName( var, symboltable, error=None ) :
    """
    Return a var's name as a string.\nThis funciton require a symboltable(returned value of globals() or locals()) in the name space where you search the var's name.\nIf you set error='exception', this raise a ValueError when the searching failed.
    """
    for k,v in symboltable.items() :
        if id(v) == id(var) :
            return k
    else :
        if error == "exception" :
            raise ValueError("Undefined function is mixed in subspace?")
        else:
            return error

def step_func(xs):
	return np.where(xs<0,0,1)

def linear(xs,a=1):
	return a*xs

def plot_func(funcs,func_name="function"):
	fig,ax=plt.subplots()
	for func in funcs:
		xs=np.linspace(-T/2,T/2,5000)
		ys=func[0](xs)
		ax.plot(xs,ys,label=func[1])
	ax.legend()
	ax.set_title("target_func (= "+func_name+" ) and its fourier series")
	plt.savefig(func_name+".png")
	plt.show()

def get_fourier(func,func_name):
	ts=np.linspace(-T/2,T/2,5000)
	A0=integrate.simps((lambda t:func(t)/T)(ts),ts)
	As=np.array([integrate.simps((lambda t:2*func(t)*np.cos(2*n*Pi*t/T)/T)(ts),ts) for n in range(1,N)],dtype=np.float64)
	Bs=np.array([integrate.simps((lambda t:2*func(t)*np.sin(2*n*Pi*t/T)/T)(ts),ts) for n in range(1,N)],dtype=np.float64)
	Explicit_Bs=np.array([(1-(-1)**n)/(n*Pi) for n in range(1,N)])
	print(Explicit_Bs)
	cos_part=lambda t : np.array([np.cos(2*n*Pi*t/T) for n in range(1,N)],dtype=np.float64)
	sin_part=lambda t : np.array([np.sin(2*n*Pi*t/T) for n in range(1,N)],dtype=np.float64)

	global target_func,fourier_series
	target_func=func
	fourier_series=lambda t: A0+As.dot(cos_part(t))+Bs.dot(sin_part(t))
	plot_func([(func,getVarName(func,globals())) for func in [func,fourier_series]],func_name)

def main():
	get_fourier(step_func,getVarName(step_func,globals()))
	get_fourier(linear,getVarName(linear,globals()))
if __name__ == '__main__':
	main()


<filename>1018/Course Material/1018_2.py<gh_stars>0
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Oct 18 20:53:35 2017

@author: sitibanc
"""
import numpy as np
import random
from sklearn import datasets
from scipy import stats

def kmeans(sample, K, max_iter):
    N = sample.shape[0]                 # N筆資料
    D = sample.shape[1]                 # 每筆資料有N維
    C = np.zeros((K, D))                # K個中心點
    L = np.zeros((N, 1))                # Label (data屬於哪一個cluster)
    L1 = np.zeros((N, 1))               # 重新分群計算出的label
    dist = np.zeros((N, K))

    # Random select center
    idx = random.sample(range(N), K)
    C = sample[idx, :]
    iteration = 0

    while iteration <= max_iter:
        for i in range(K):
            #以整個矩陣做運算，求與C（中心點）距離
            # np.tile() --> 垂直Repeat C[i, :] N次，水平repeat 1次
            dist[:, i] = np.sum((sample - np.tile(C[i, :], (N, 1))) ** 2 , 1)
            # 取距離最短者的input為其label
            L1 = np.argmin(dist, 1)
            # 若分群後各群成員不再改變（已分完，所屬cluster已定），則跳出迴圈
            if iteration > 0 and np.array_equal(L, L1):
                break
            # Update Label L
            L = L1
            # 計算重新分群後的新center
            for i in range(K):
                # 取出屬於第i群者的index
                idx = np.nonzero(L == i)[0]    # np.nonzero()亦即True
                if len(idx) > 0:
                    C[i, :] = np.mean(sample[idx, :], 0)    # 沿垂直方向(0)計算平均
        iteration += 1
        # Calcuate wicd（within cluster distance, 群內每筆資料與群中心的距離）
        wicd = np.sum(np.sqrt(np.sum((sample - C[L, :]) ** 2 , 1)))
    return C, L, wicd

# Practice 3 : Iris Dataset Clustering Using K-Means
data = datasets.load_iris()
feature = data.data
center, label, wicd = kmeans(feature, 3, 1000)
# Calculate Error Rate
error = 0
for i in range(len(label)):
    if i < 50:
        mode = stats.mode(label[:50])
        if label[i] != mode[0][0]:
            error += 1
    elif i < 100:
        mode = stats.mode(label[50:100])
        if label[i] != mode[0][0]:
            error += 1
    else:
        mode = stats.mode(label[100:])
        if label[i] != mode[0][0]:
            error += 1
print('Error rate :', error / len(label))


<filename>pyradar/Libs/receivers/envelope_detector.py
"""
Project: RadarBook
File: envelope_detector.py
Created by: <NAME>
On: 9/18/2018
Created with: PyCharm

Copyright (C) 2019 Artech House (<EMAIL>)
This file is part of Introduction to Radar Using Python and MATLAB
and can not be copied and/or distributed without the express permission of Artech House.
"""
from scipy.signal import hilbert

def envelope(if_signal):
    """
    Calculate the amplitude envelope of the IF signal.
    :param if_signal: The signal at IF.
    :return: The amplitude envelope.
    """
    return abs(hilbert(if_signal))


<reponame>igherzog/hawc_hal
from hawc_hal.healpix_handling.flat_sky_to_healpix import _parse_coord_system, _convert_world_coordinates, ORDER
from hawc_hal.special_values import UNSEEN
import healpy as hp
import numpy as np
import six
from scipy.ndimage import map_coordinates

from astropy import units as u

def image_to_healpix(data, wcs_in, coord_system_out,
                     nside, pixels_id, order='bilinear', nested=False,
                     fill_value=UNSEEN, pixels_to_be_zeroed=None, full=False):

    npix = hp.nside2npix(nside)

    # Look up lon, lat of pixels in output system and convert colatitude theta
    # and longitude phi to longitude and latitude.
    theta, phi = hp.pix2ang(nside, pixels_id, nested)

    lon_out = np.degrees(phi)
    lat_out = 90. - np.degrees(theta)

    # Convert between celestial coordinates
    coord_system_out = _parse_coord_system(coord_system_out)

    with np.errstate(invalid='ignore'):
        lon_in, lat_in = _convert_world_coordinates(lon_out, lat_out, (coord_system_out, u.deg, u.deg), wcs_in)

    # Look up pixels in input system
    yinds, xinds = wcs_in.wcs_world2pix(lon_in, lat_in, 0)

    # Interpolate

    if isinstance(order, six.string_types):
        order = ORDER[order]

    healpix_data_ = map_coordinates(data, [xinds, yinds],
                                    order=order,
                                    mode='constant', cval=fill_value)

    if not full:

        # Return partial map
        return healpix_data_

    else:

        # Return full healpix map

        healpix_data = np.full(npix, fill_value)

        healpix_data[pixels_id] = healpix_data_

        if pixels_to_be_zeroed is not None:

            healpix_data[pixels_to_be_zeroed] = np.where(np.isnan(healpix_data[pixels_to_be_zeroed]),
                                                         0.0,
                                                         healpix_data[pixels_to_be_zeroed])

        return healpix_data


import arrayfire as af
import cupy as np
import numpy
import scipy.sparse as sp
import warnings
import numbers
from numpy.core.numeric import ComplexWarning
from inspect import signature, isclass, Parameter
from af_type_utils import typemap

from sklearn.utils.validation import _deprecate_positional_args
from sklearn._config import get_config as _get_config

def check_consistent_length(*arrays):
    """Check that all arrays have consistent first dimensions.

    Checks whether all objects in arrays have the same shape or length.

    Parameters
    ----------
    *arrays : list or tuple of input objects.
        Objects that will be checked for consistent length.
    """

    lengths = [_num_samples(X) for X in arrays if X is not None]
    uniques = np.unique(lengths)
    if len(uniques) > 1:
        raise ValueError("Found input variables with inconsistent numbers of"
                         " samples: %r" % [int(l) for l in lengths])

def _safe_accumulator_op(op, x, *args, **kwargs):
    """
    This function provides numpy accumulator functions with a float64 dtype
    when used on a floating point input. This prevents accumulator overflow on
    smaller floating point dtypes.
    Parameters
    ----------
    op : function
        A numpy accumulator function such as np.mean or np.sum
    x : numpy array
        A numpy array to apply the accumulator function
    *args : positional arguments
        Positional arguments passed to the accumulator function after the
        input x
    **kwargs : keyword arguments
        Keyword arguments passed to the accumulator function
    Returns
    -------
    result : The output of the accumulator function passed to this function
    """
    if np.issubdtype(x.dtype, np.floating) and x.dtype.itemsize < 8:
        result = op(x, *args, **kwargs, dtype=np.float64)
    else:
        result = op(x, *args, **kwargs)
    return result

def _determine_key_type(key, accept_slice=True):
    """Determine the data type of key.

    Parameters
    ----------
    key : scalar, slice or array-like
        The key from which we want to infer the data type.

    accept_slice : bool, default=True
        Whether or not to raise an error if the key is a slice.

    Returns
    -------
    dtype : {'int', 'str', 'bool', None}
        Returns the data type of key.
    """
    err_msg = ("No valid specification of the columns. Only a scalar, list or "
               "slice of all integers or all strings, or boolean mask is "
               "allowed")

    dtype_to_str = {int: 'int', str: 'str', bool: 'bool', np.bool_: 'bool'}
    array_dtype_to_str = {'i': 'int', 'u': 'int', 'b': 'bool', 'O': 'str',
                          'U': 'str', 'S': 'str'}

    if key is None:
        return None
    if isinstance(key, tuple(dtype_to_str.keys())):
        try:
            return dtype_to_str[type(key)]
        except KeyError:
            raise ValueError(err_msg)
    if isinstance(key, slice):
        if not accept_slice:
            raise TypeError(
                'Only array-like or scalar are supported. '
                'A Python slice was given.'
            )
        if key.start is None and key.stop is None:
            return None
        key_start_type = _determine_key_type(key.start)
        key_stop_type = _determine_key_type(key.stop)
        if key_start_type is not None and key_stop_type is not None:
            if key_start_type != key_stop_type:
                raise ValueError(err_msg)
        if key_start_type is not None:
            return key_start_type
        return key_stop_type
    if isinstance(key, (list, tuple)):
        unique_key = set(key)
        key_type = {_determine_key_type(elt) for elt in unique_key}
        if not key_type:
            return None
        if len(key_type) != 1:
            raise ValueError(err_msg)
        return key_type.pop()
    if hasattr(key, 'dtype'):
        try:
            return array_dtype_to_str[key.dtype.kind]
        except KeyError:
            raise ValueError(err_msg)
    raise ValueError(err_msg)

def _array_indexing(array, key, key_dtype, axis):
    """Index an array or scipy.sparse consistently across NumPy version."""
    if isinstance(key, tuple):
        key = list(key)
    afkey = af.interop.from_ndarray(key) #TODO: replace w/arrayfire keys
    return array[afkey, :] if axis == 0 else array[:, afkey]

def _safe_indexing(X, indices, *, axis=0):
    """Return rows, items or columns of X using indices.

    .. warning::

        This utility is documented, but **private**. This means that
        backward compatibility might be broken without any deprecation
        cycle.

    Parameters
    ----------
    X : array-like, sparse-matrix, list, pandas.DataFrame, pandas.Series
        Data from which to sample rows, items or columns. `list` are only
        supported when `axis=0`.
    indices : bool, int, str, slice, array-like
        - If `axis=0`, boolean and integer array-like, integer slice,
          and scalar integer are supported.
        - If `axis=1`:
            - to select a single column, `indices` can be of `int` type for
              all `X` types and `str` only for dataframe. The selected subset
              will be 1D, unless `X` is a sparse matrix in which case it will
              be 2D.
            - to select multiples columns, `indices` can be one of the
              following: `list`, `array`, `slice`. The type used in
              these containers can be one of the following: `int`, 'bool' and
              `str`. However, `str` is only supported when `X` is a dataframe.
              The selected subset will be 2D.
    axis : int, default=0
        The axis along which `X` will be subsampled. `axis=0` will select
        rows while `axis=1` will select columns.

    Returns
    -------
    subset
        Subset of X on axis 0 or 1.

    Notes
    -----
    CSR, CSC, and LIL sparse matrices are supported. COO sparse matrices are
    not supported.
    """
    if indices is None:
        return X

    if axis not in (0, 1):
        raise ValueError(
            "'axis' should be either 0 (to index rows) or 1 (to index "
            " column). Got {} instead.".format(axis)
        )

    indices_dtype = _determine_key_type(indices)

    if axis == 0 and indices_dtype == 'str':
        raise ValueError(
            "String indexing is not supported with 'axis=0'"
        )

    if axis == 1 and X.ndim != 2:
        raise ValueError(
            "'X' should be a 2D NumPy array, 2D sparse matrix or pandas "
            "dataframe when indexing the columns (i.e. 'axis=1'). "
            "Got {} instead with {} dimension(s).".format(type(X), X.ndim)
        )

    if axis == 1 and indices_dtype == 'str' and not hasattr(X, 'loc'):
        raise ValueError(
            "Specifying the columns using strings is only supported for "
            "pandas DataFrames"
        )

    if hasattr(X, "iloc"):
        return _pandas_indexing(X, indices, indices_dtype, axis=axis)
    elif hasattr(X, "shape"):
        return _array_indexing(X, indices, indices_dtype, axis=axis)
    else:
        return _list_indexing(X, indices, indices_dtype)

def _assert_all_finite(X, allow_nan=False, msg_dtype=None):
    """Like assert_all_finite, but only for ndarray."""
    # validation is also imported in extmath

    if _get_config()['assume_finite']:
        return
    X = np.asanyarray(X)
    # First try an O(n) time, O(1) space solution for the common case that
    # everything is finite; fall back to O(n) space np.isfinite to prevent
    # false positives from overflow in sum method. The sum is also calculated
    # safely to reduce dtype induced overflows.
    is_float = X.dtype.kind in 'fc'
    if is_float and (np.isfinite(_safe_accumulator_op(np.sum, X))):
        pass
    elif is_float:
        msg_err = "Input contains {} or a value too large for {!r}."
        if (allow_nan and np.isinf(X).any() or
                not allow_nan and not np.isfinite(X).all()):
            type_err = 'infinity' if allow_nan else 'NaN, infinity'
            raise ValueError(
                    msg_err.format
                    (type_err,
                     msg_dtype if msg_dtype is not None else X.dtype)
            )
    # for object dtype data, we only check for NaNs (GH-13254)
    elif X.dtype == np.dtype('object') and not allow_nan:
        if _object_dtype_isnan(X).any():
            raise ValueError("Input contains NaN")

def _ensure_no_complex_data(array):
    if hasattr(array, 'dtype') and array.dtype is not None \
            and hasattr(array.dtype, 'kind') and array.dtype.kind == "c":
        raise ValueError("Complex data not supported\n"
                         "{}\n".format(array))

def _num_samples(x):
    """Return number of samples in array-like x."""
    message = 'Expected sequence or array-like, got %s' % type(x)
    if hasattr(x, 'fit') and callable(x.fit):
        # Don't get num_samples from an ensembles length!
        raise TypeError(message)

    if not hasattr(x, '__len__') and not hasattr(x, 'shape'):
        if hasattr(x, '__array__'):
            x = np.asarray(x)
        else:
            raise TypeError(message)

    if hasattr(x, 'shape') and x.shape is not None:
        if len(x.shape) == 0:
            raise TypeError("Singleton array %r cannot be considered"
                            " a valid collection." % x)
        # Check that shape is returning an integer or default to len
        # Dask dataframes may not return numeric shape[0] value
        if isinstance(x.shape[0], numbers.Integral):
            return x.shape[0]

    try:
        return len(x)
    except TypeError:
        raise TypeError(message)

@_deprecate_positional_args
def check_array(array, accept_sparse=False, *, accept_large_sparse=True,
                dtype="numeric", order=None, copy=False, force_all_finite=True,
                ensure_2d=True, allow_nd=False, ensure_min_samples=1,
                ensure_min_features=1, estimator=None):

    """Input validation on an array, list, sparse matrix or similar.

    By default, the input is checked to be a non-empty 2D array containing
    only finite values. If the dtype of the array is object, attempt
    converting to float, raising on failure.

    Parameters
    ----------
    array : object
        Input object to check / convert.

    accept_sparse : string, boolean or list/tuple of strings (default=False)
        String[s] representing allowed sparse matrix formats, such as 'csc',
        'csr', etc. If the input is sparse but not in the allowed format,
        it will be converted to the first listed format. True allows the input
        to be any format. False means that a sparse matrix input will
        raise an error.

    accept_large_sparse : bool (default=True)
        If a CSR, CSC, COO or BSR sparse matrix is supplied and accepted by
        accept_sparse, accept_large_sparse=False will cause it to be accepted
        only if its indices are stored with a 32-bit dtype.

        .. versionadded:: 0.20

    dtype : string, type, list of types or None (default="numeric")
        Data type of result. If None, the dtype of the input is preserved.
        If "numeric", dtype is preserved unless array.dtype is object.
        If dtype is a list of types, conversion on the first type is only
        performed if the dtype of the input is not in the list.

    order : 'F', 'C' or None (default=None)
        Whether an array will be forced to be fortran or c-style.
        When order is None (default), then if copy=False, nothing is ensured
        about the memory layout of the output array; otherwise (copy=True)
        the memory layout of the returned array is kept as close as possible
        to the original array.

    copy : boolean (default=False)
        Whether a forced copy will be triggered. If copy=False, a copy might
        be triggered by a conversion.

    force_all_finite : boolean or 'allow-nan', (default=True)
        Whether to raise an error on np.inf, np.nan, pd.NA in array. The
        possibilities are:

        - True: Force all values of array to be finite.
        - False: accepts np.inf, np.nan, pd.NA in array.
        - 'allow-nan': accepts only np.nan and pd.NA values in array. Values
          cannot be infinite.

        .. versionadded:: 0.20
           ``force_all_finite`` accepts the string ``'allow-nan'``.

        .. versionchanged:: 0.23
           Accepts `pd.NA` and converts it into `np.nan`

    ensure_2d : boolean (default=True)
        Whether to raise a value error if array is not 2D.

    allow_nd : boolean (default=False)
        Whether to allow array.ndim > 2.

    ensure_min_samples : int (default=1)
        Make sure that the array has a minimum number of samples in its first
        axis (rows for a 2D array). Setting to 0 disables this check.

    ensure_min_features : int (default=1)
        Make sure that the 2D array has some minimum number of features
        (columns). The default value of 1 rejects empty datasets.
        This check is only enforced when the input data has effectively 2
        dimensions or is originally 1D and ``ensure_2d`` is True. Setting to 0
        disables this check.

    estimator : str or estimator instance (default=None)
        If passed, include the name of the estimator in warning messages.

    Returns
    -------
    array_converted : object
        The converted and validated array.
    """
    # store reference to original array to check if copy is needed when
    # function returns
    array_orig = array
    #import pdb;pdb.set_trace()
    return array #TMP todo: perform checks for af::array

    # store whether originally we wanted numeric dtype
    dtype_numeric = isinstance(dtype, str) and dtype == "numeric"

    dtype_orig = getattr(array, "dtype", None)
    if not hasattr(dtype_orig, 'kind'):
        # not a data type (e.g. a column named dtype in a pandas DataFrame)
        dtype_orig = None

    # check if the object contains several dtypes (typically a pandas
    # DataFrame), and store them. If not, store None.
    dtypes_orig = None
    has_pd_integer_array = False
    if hasattr(array, "dtypes") and hasattr(array.dtypes, '__array__'):
        # throw warning if columns are sparse. If all columns are sparse, then
        # array.sparse exists and sparsity will be perserved (later).
        with suppress(ImportError):
            from pandas.api.types import is_sparse
            if (not hasattr(array, 'sparse') and
                    array.dtypes.apply(is_sparse).any()):
                warnings.warn(
                    "pandas.DataFrame with sparse columns found."
                    "It will be converted to a dense numpy array."
                )

        dtypes_orig = list(array.dtypes)
        # pandas boolean dtype __array__ interface coerces bools to objects
        for i, dtype_iter in enumerate(dtypes_orig):
            if dtype_iter.kind == 'b':
                dtypes_orig[i] = np.dtype(np.object)
            elif dtype_iter.name.startswith(("Int", "UInt")):
                # name looks like an Integer Extension Array, now check for
                # the dtype
                with suppress(ImportError):
                    from pandas import (Int8Dtype, Int16Dtype,
                                        Int32Dtype, Int64Dtype,
                                        UInt8Dtype, UInt16Dtype,
                                        UInt32Dtype, UInt64Dtype)
                    if isinstance(dtype_iter, (Int8Dtype, Int16Dtype,
                                               Int32Dtype, Int64Dtype,
                                               UInt8Dtype, UInt16Dtype,
                                               UInt32Dtype, UInt64Dtype)):
                        has_pd_integer_array = True

        if all(isinstance(dtype, np.dtype) for dtype in dtypes_orig):
            dtype_orig = np.result_type(*dtypes_orig)

    if dtype_numeric:
        if dtype_orig is not None and dtype_orig.kind == "O":
            # if input is object, convert to float.
            dtype = np.float64
        else:
            dtype = None

    if isinstance(dtype, (list, tuple)):
        if dtype_orig is not None and dtype_orig in dtype:
            # no dtype conversion required
            dtype = None
        else:
            # dtype conversion required. Let's select the first element of the
            # list of accepted types.
            dtype = dtype[0]

    if has_pd_integer_array:
        # If there are any pandas integer extension arrays,
        array = array.astype(dtype)

    if force_all_finite not in (True, False, 'allow-nan'):
        raise ValueError('force_all_finite should be a bool or "allow-nan"'
                         '. Got {!r} instead'.format(force_all_finite))

    if estimator is not None:
        if isinstance(estimator, str):
            estimator_name = estimator
        else:
            estimator_name = estimator.__class__.__name__
    else:
        estimator_name = "Estimator"
    context = " by %s" % estimator_name if estimator is not None else ""

    # When all dataframe columns are sparse, convert to a sparse array
    if hasattr(array, 'sparse') and array.ndim > 1:
        # DataFrame.sparse only supports `to_coo`
        array = array.sparse.to_coo()

    if sp.issparse(array):
        _ensure_no_complex_data(array)
        array = _ensure_sparse_format(array, accept_sparse=accept_sparse,
                                      dtype=dtype, copy=copy,
                                      force_all_finite=force_all_finite,
                                      accept_large_sparse=accept_large_sparse)
    else:
        # If np.array(..) gives ComplexWarning, then we convert the warning
        # to an error. This is needed because specifying a non complex
        # dtype to the function converts complex to real dtype,
        # thereby passing the test made in the lines following the scope
        # of warnings context manager.
        with warnings.catch_warnings():
            try:
                warnings.simplefilter('error', ComplexWarning)
                if dtype is not None and np.dtype(dtype).kind in 'iu':
                    # Conversion float -> int should not contain NaN or
                    # inf (numpy#14412). We cannot use casting='safe' because
                    # then conversion float -> int would be disallowed.
                    array = np.asarray(array, order=order)
                    if array.dtype.kind == 'f':
                        _assert_all_finite(array, allow_nan=False,
                                           msg_dtype=dtype)
                    array = array.astype(dtype, casting="unsafe", copy=False)
                else:
                    array = np.asarray(array, order=order, dtype=dtype)
            except ComplexWarning:
                raise ValueError("Complex data not supported\n"
                                 "{}\n".format(array))

        # It is possible that the np.array(..) gave no warning. This happens
        # when no dtype conversion happened, for example dtype = None. The
        # result is that np.array(..) produces an array of complex dtype
        # and we need to catch and raise exception for such cases.
        _ensure_no_complex_data(array)

        if ensure_2d:
            # If input is scalar raise error
            if array.ndim == 0:
                raise ValueError(
                    "Expected 2D array, got scalar array instead:\narray={}.\n"
                    "Reshape your data either using array.reshape(-1, 1) if "
                    "your data has a single feature or array.reshape(1, -1) "
                    "if it contains a single sample.".format(array))
            # If input is 1D raise error
            if array.ndim == 1:
                raise ValueError(
                    "Expected 2D array, got 1D array instead:\narray={}.\n"
                    "Reshape your data either using array.reshape(-1, 1) if "
                    "your data has a single feature or array.reshape(1, -1) "
                    "if it contains a single sample.".format(array))

        # in the future np.flexible dtypes will be handled like object dtypes
        #if dtype_numeric and np.issubdtype(array.dtype, np.flexible):
            #warnings.warn(
                #"Beginning in version 0.22, arrays of bytes/strings will be "
                #"converted to decimal numbers if dtype='numeric'. "
                #"It is recommended that you convert the array to "
                #"a float dtype before using it in scikit-learn, "
                #"for example by using "
                #"your_array = your_array.astype(np.float64).",
                #FutureWarning, stacklevel=2)

        # make sure we actually converted to numeric:
        if dtype_numeric and array.dtype.kind == "O":
            array = array.astype(np.float64)
        if not allow_nd and array.ndim >= 3:
            raise ValueError("Found array with dim %d. %s expected <= 2."
                             % (array.ndim, estimator_name))

        if force_all_finite:
            _assert_all_finite(array,
                               allow_nan=force_all_finite == 'allow-nan')

    if ensure_min_samples > 0:
        n_samples = _num_samples(array)
        if n_samples < ensure_min_samples:
            raise ValueError("Found array with %d sample(s) (shape=%s) while a"
                             " minimum of %d is required%s."
                             % (n_samples, array.shape, ensure_min_samples,
                                context))

    if ensure_min_features > 0 and array.ndim == 2:
        n_features = array.shape[1]
        if n_features < ensure_min_features:
            raise ValueError("Found array with %d feature(s) (shape=%s) while"
                             " a minimum of %d is required%s."
                             % (n_features, array.shape, ensure_min_features,
                                context))

    if copy and np.may_share_memory(array, array_orig):
        array = np.array(array, dtype=dtype, order=order)

    return array

@_deprecate_positional_args
def check_X_y(X, y, accept_sparse=False, *, accept_large_sparse=True,
              dtype="numeric", order=None, copy=False, force_all_finite=True,
              ensure_2d=True, allow_nd=False, multi_output=False,
              ensure_min_samples=1, ensure_min_features=1, y_numeric=False,
              estimator=None):
    """Input validation for standard estimators.

    Checks X and y for consistent length, enforces X to be 2D and y 1D. By
    default, X is checked to be non-empty and containing only finite values.
    Standard input checks are also applied to y, such as checking that y
    does not have np.nan or np.inf targets. For multi-label y, set
    multi_output=True to allow 2D and sparse y. If the dtype of X is
    object, attempt converting to float, raising on failure.

    Parameters
    ----------
    X : nd-array, list or sparse matrix
        Input data.

    y : nd-array, list or sparse matrix
        Labels.

    accept_sparse : string, boolean or list of string (default=False)
        String[s] representing allowed sparse matrix formats, such as 'csc',
        'csr', etc. If the input is sparse but not in the allowed format,
        it will be converted to the first listed format. True allows the input
        to be any format. False means that a sparse matrix input will
        raise an error.

    accept_large_sparse : bool (default=True)
        If a CSR, CSC, COO or BSR sparse matrix is supplied and accepted by
        accept_sparse, accept_large_sparse will cause it to be accepted only
        if its indices are stored with a 32-bit dtype.

        .. versionadded:: 0.20

    dtype : string, type, list of types or None (default="numeric")
        Data type of result. If None, the dtype of the input is preserved.
        If "numeric", dtype is preserved unless array.dtype is object.
        If dtype is a list of types, conversion on the first type is only
        performed if the dtype of the input is not in the list.

    order : 'F', 'C' or None (default=None)
        Whether an array will be forced to be fortran or c-style.

    copy : boolean (default=False)
        Whether a forced copy will be triggered. If copy=False, a copy might
        be triggered by a conversion.

    force_all_finite : boolean or 'allow-nan', (default=True)
        Whether to raise an error on np.inf, np.nan, pd.NA in X. This parameter
        does not influence whether y can have np.inf, np.nan, pd.NA values.
        The possibilities are:

        - True: Force all values of X to be finite.
        - False: accepts np.inf, np.nan, pd.NA in X.
        - 'allow-nan': accepts only np.nan or pd.NA values in X. Values cannot
          be infinite.

        .. versionadded:: 0.20
           ``force_all_finite`` accepts the string ``'allow-nan'``.

        .. versionchanged:: 0.23
           Accepts `pd.NA` and converts it into `np.nan`

    ensure_2d : boolean (default=True)
        Whether to raise a value error if X is not 2D.

    allow_nd : boolean (default=False)
        Whether to allow X.ndim > 2.

    multi_output : boolean (default=False)
        Whether to allow 2D y (array or sparse matrix). If false, y will be
        validated as a vector. y cannot have np.nan or np.inf values if
        multi_output=True.

    ensure_min_samples : int (default=1)
        Make sure that X has a minimum number of samples in its first
        axis (rows for a 2D array).

    ensure_min_features : int (default=1)
        Make sure that the 2D array has some minimum number of features
        (columns). The default value of 1 rejects empty datasets.
        This check is only enforced when X has effectively 2 dimensions or
        is originally 1D and ``ensure_2d`` is True. Setting to 0 disables
        this check.

    y_numeric : boolean (default=False)
        Whether to ensure that y has a numeric type. If dtype of y is object,
        it is converted to float64. Should only be used for regression
        algorithms.

    estimator : str or estimator instance (default=None)
        If passed, include the name of the estimator in warning messages.

    Returns
    -------
    X_converted : object
        The converted and validated X.

    y_converted : object
        The converted and validated y.
    """
    #import pdb; pdb.set_trace()
    if y is None:
        raise ValueError("y cannot be None")

    X = check_array(X, accept_sparse=accept_sparse,
                    accept_large_sparse=accept_large_sparse,
                    dtype=dtype, order=order, copy=copy,
                    force_all_finite=force_all_finite,
                    ensure_2d=ensure_2d, allow_nd=allow_nd,
                    ensure_min_samples=ensure_min_samples,
                    ensure_min_features=ensure_min_features,
                    estimator=estimator)
    if multi_output:
        y = check_array(y, accept_sparse='csr', force_all_finite=True,
                        ensure_2d=False, dtype=None)
    else:
        y = column_or_1d(y, warn=True)
        _assert_all_finite(y)
    npdtype = typemap(y.dtype())
    if y_numeric and npdtype == 'O':
        y = y.astype(af.Dype.f64)

    check_consistent_length(X, y)

    return X, y

@_deprecate_positional_args
def column_or_1d(y, *, warn=False):
    """ Ravel column or 1d numpy array, else raises an error

    Parameters
    ----------
    y : array-like

    warn : boolean, default False
       To control display of warnings.

    Returns
    -------
    y : array

    """
    #y = np.asarray(y)
    #shape = np.shape(y)
    shape = y.dims()
    if len(shape) == 1:
        #return np.ravel(y)
        return af.flat(y)
    if len(shape) == 2 and shape[1] == 1:
        if warn:
            warnings.warn("A column-vector y was passed when a 1d array was"
                          " expected. Please change the shape of y to "
                          "(n_samples, ), for example using ravel().",
                          DataConversionWarning, stacklevel=2)
        #return np.ravel(y)
        return af.flat(y)

    raise ValueError(
        "y should be a 1d array, "
        "got an array of shape {} instead.".format(shape))

@_deprecate_positional_args
def check_is_fitted(estimator, attributes=None, *, msg=None, all_or_any=all):
    """Perform is_fitted validation for estimator.

    Checks if the estimator is fitted by verifying the presence of
    fitted attributes (ending with a trailing underscore) and otherwise
    raises a NotFittedError with the given message.

    This utility is meant to be used internally by estimators themselves,
    typically in their own predict / transform methods.

    Parameters
    ----------
    estimator : estimator instance.
        estimator instance for which the check is performed.

    attributes : str, list or tuple of str, default=None
        Attribute name(s) given as string or a list/tuple of strings
        Eg.: ``["coef_", "estimator_", ...], "coef_"``

        If `None`, `estimator` is considered fitted if there exist an
        attribute that ends with a underscore and does not start with double
        underscore.

    msg : string
        The default error message is, "This %(name)s instance is not fitted
        yet. Call 'fit' with appropriate arguments before using this
        estimator."

        For custom messages if "%(name)s" is present in the message string,
        it is substituted for the estimator name.

        Eg. : "Estimator, %(name)s, must be fitted before sparsifying".

    all_or_any : callable, {all, any}, default all
        Specify whether all or any of the given attributes must exist.

    Returns
    -------
    None

    Raises
    ------
    NotFittedError
        If the attributes are not found.
    """
    if isclass(estimator):
        raise TypeError("{} is a class, not an instance.".format(estimator))
    if msg is None:
        msg = ("This %(name)s instance is not fitted yet. Call 'fit' with "
               "appropriate arguments before using this estimator.")

    if not hasattr(estimator, 'fit'):
        raise TypeError("%s is not an estimator instance." % (estimator))

    if attributes is not None:
        if not isinstance(attributes, (list, tuple)):
            attributes = [attributes]
        attrs = all_or_any([hasattr(estimator, attr) for attr in attributes])
    else:
        attrs = [v for v in vars(estimator)
                 if v.endswith("_") and not v.startswith("__")]

    if not attrs:
        raise NotFittedError(msg % {'name': type(estimator).__name__})

def check_random_state(seed):
    """Turn seed into a np.random.RandomState instance

    Parameters
    ----------
    seed : None | int | instance of RandomState
        If seed is None, return the RandomState singleton used by np.random.
        If seed is an int, return a new RandomState instance seeded with seed.
        If seed is already a RandomState instance, return it.
        Otherwise raise ValueError.
    """
    if seed is None or seed is np.random:
        return np.random.mtrand._rand
    if isinstance(seed, numbers.Integral):
        return np.random.RandomState(seed)
    if isinstance(seed, np.random.RandomState):
        return seed
    raise ValueError('%r cannot be used to seed a numpy.random.RandomState'
                     ' instance' % seed)


from torchvision.datasets import ImageFolder
import torch
from torch.utils.data import Dataset, ConcatDataset, Subset
import os
import numpy as np
import scipy.io
from PIL import Image

# Code Snippets by https://github.com/zrsmithson/Stanford-dogs/blob/master/data/stanford_dogs_data.py

class StanfordDogs(Dataset):
    def __init__(self,
                 train,
                 cropped,
                 split_seed=42,
                 transform=None,
                 root='data/stanford_dogs'):

        self.image_path = os.path.join(root, 'Images')
        dataset = ImageFolder(root=self.image_path, transform=None)
        self.dataset = dataset
        self.cropped = cropped
        self.root = root

        self.annotations_folder = os.path.join(self.root, 'Annotation')
        self.breeds = os.listdir(self.image_path)

        self.classes = [cls.split('-', 1)[-1] for cls in self.dataset.classes]
        self.class_to_idx = {cls: i for i, cls in enumerate(self.classes)}
        self.idx_to_class = {i: cls for i, cls in enumerate(self.classes)}

        self.targets = self.dataset.targets
        self.name = 'stanford_dogs'

        split_train = scipy.io.loadmat(os.path.join(self.root, 'train_list.mat'))['annotation_list']
        labels_train = scipy.io.loadmat(os.path.join(self.root, 'train_list.mat'))['labels']
        split_test = scipy.io.loadmat(os.path.join(self.root, 'test_list.mat'))['annotation_list']
        labels_test = scipy.io.loadmat(os.path.join(self.root, 'test_list.mat'))['labels']

        split = [item[0][0] for item in split_train] + [item[0][0] for item in split_test]
        labels = [item[0]-1 for item in labels_train] + [item[0]-1 for item in labels_test]

        if self.cropped:
            self._breed_annotations = [[(annotation, box, idx)
                                        for box in self.get_boxes(os.path.join(self.annotations_folder, annotation))]
                                        for annotation, idx in zip(split, labels)]
            self._flat_breed_annotations = [t[0] for t in self._breed_annotations]
            self.targets = [t[-1][-1] for t in self._breed_annotations]
            self._flat_breed_images = [(annotation+'.jpg', box, idx) for annotation, box, idx in self._flat_breed_annotations]
        else:
            self._breed_images = [(annotation+'.jpg', idx) for annotation, idx in zip(split, labels)]
            self.targets = [t[-1] for t in self._breed_images]
            self._flat_breed_images = self._breed_images

        self.transform = transform
        indices = list(range(len(self.dataset)))
        np.random.seed(split_seed)
        np.random.shuffle(indices)
        training_set_size = int(0.9 * len(self.dataset))
        train_idx = indices[:training_set_size]
        test_idx = indices[training_set_size:]

        if train:
            self.dataset = np.array(self._flat_breed_images, dtype=object)[train_idx].tolist()
            self.targets = np.array(self.targets)[train_idx].tolist()
        else:
            self.dataset = np.array(self._flat_breed_images, dtype=object)[test_idx].tolist()
            self.targets = np.array(self.targets)[test_idx].tolist()

    def __len__(self):
        return len(self.dataset)

    def __getitem__(self, idx):
        # im, _ = self.dataset[idx]
        image_name, target = self.dataset[idx][0], self.dataset[idx][-1]
        image_path = os.path.join(self.image_path, image_name)
        im = Image.open(image_path).convert('RGB')

        if self.cropped:
            im = im.crop(self.dataset[idx][1])
        if self.transform:
            return self.transform(im), target
        else:
            return im, target

    def get_boxes(self, path):
        import xml.etree.ElementTree
        e = xml.etree.ElementTree.parse(path).getroot()
        boxes = []
        for objs in e.iter('object'):
            boxes.append([int(objs.find('bndbox').find('xmin').text),
                          int(objs.find('bndbox').find('ymin').text),
                          int(objs.find('bndbox').find('xmax').text),
                          int(objs.find('bndbox').find('ymax').text)])
        return boxes


<filename>hdn/utils/image_aug.py
import cv2
import numpy as np
import random
from scipy.stats import norm
import matplotlib.pyplot as plt
def generate_spot_light_mask(mask_size,
                             position=None,
                             max_brightness=255,
                             min_brightness=0,
                             mode="gaussian",
                             linear_decay_rate=None,
                             speedup=False):
    """
    Generate decayed light mask generated by spot light given position, direction. Multiple spotlights are accepted.
    Args:
        mask_size: tuple of integers (w, h) defining generated mask size
        position: list of tuple of integers (x, y) defining the center of spotlight light position,
                  which is the reference point during rotating
        max_brightness: integer that max brightness in the mask
        min_brightness: integer that min brightness in the mask
        mode: the way that brightness decay from max to min: linear or gaussian
        linear_decay_rate: only valid in linear_static mode. Suggested value is within [0.2, 2]
        speedup: use `shrinkage then expansion` strategy to speed up vale calculation
    Return:
        light_mask: ndarray in float type consisting value from max_brightness to min_brightness. If in 'linear' mode
                    minimum value could be smaller than given min_brightness.
    """
    if position is None:
        position = [(random.randint(0, mask_size[0]), random.randint(0, mask_size[1]))]
    if linear_decay_rate is None:
        if mode == "linear_static":
            linear_decay_rate = random.uniform(0.25, 1)
    assert mode in ["linear", "gaussian"], \
        "mode must be linear_dynamic, linear_static or gaussian"
    mask = np.zeros(shape=(mask_size[1], mask_size[0]), dtype=np.float32)
    if mode == "gaussian":
        mu = np.sqrt(mask.shape[0]**2+mask.shape[1]**2)
        dev = mu / 3.5
        mask = _decay_value_radically_norm_in_matrix(mask_size, position, max_brightness, min_brightness, dev)
    mask = np.asarray(mask, dtype=np.uint8)
    # add median blur
    mask = cv2.medianBlur(mask, 5)
    mask = 255 - mask
    # cv2.imshow("mask", mask)
    # cv2.waitKey(0)
    return mask

def _decay_value_radically_norm_in_matrix(mask_size, centers, max_value, min_value, dev):
    """
    _decay_value_radically_norm function in matrix format
    """
    center_prob = norm.pdf(0, 0, dev)
    x_value_rate = np.zeros((mask_size[1], mask_size[0]))
    for center in centers:
        coord_x = np.arange(mask_size[0])
        coord_y = np.arange(mask_size[1])
        xv, yv = np.meshgrid(coord_x, coord_y)
        dist_x = xv - center[0]
        dist_y = yv - center[1]
        dist = np.sqrt(np.power(dist_x, 2) + np.power(dist_y, 2))
        x_value_rate += norm.pdf(dist, 0, dev) / center_prob
    mask = x_value_rate * (max_value - min_value) + min_value
    mask[mask > 255] = 255
    return mask

def _decay_value_radically_norm(x, centers, max_value, min_value, dev):
    """
    Calculate point value decayed from center following Gaussian decay. If multiple centers are given, value
    from each center sums up while limiting the accumulated value into [0, 255]
    NOTE: assuming light at each center is identical: same brightness and same decay rate
    """
    center_prob = norm.pdf(0, 0, dev)
    x_value_rate = 0
    for center in centers:
        distance = np.sqrt((center[0]-x[0])**2 + (center[1]-x[1])**2)
        x_value_rate += norm.pdf(distance, 0, dev) / center_prob
    x_value = x_value_rate * (max_value - min_value) + min_value
    x_value = 255 if x_value > 255 else x_value
    return x_value

def add_spot_light(image, light_position=None, max_brightness=255, min_brightness=0,
                   mode='gaussian', linear_decay_rate=None, transparency=None):
    """
    Add mask generated from spot light to given image
    """
    # min_brightness = 0
    # max_brightness = 128
    if transparency is None:
        transparency = random.uniform(0.1, 1.0)
    # if transparency is None:
    frame = image
    height, width, _ = frame.shape
    hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
    mask = generate_spot_light_mask(mask_size=(width, height),
                                    position=light_position,
                                    max_brightness=max_brightness,
                                    min_brightness=min_brightness,
                                    mode=mode,
                                    linear_decay_rate=linear_decay_rate)
    hsv[:, :, 2] = hsv[:, :, 2] * transparency + mask * (1 - transparency)
    frame = cv2.cvtColor(hsv, cv2.COLOR_HSV2BGR)
    frame[frame > 255] = 255
    frame = np.asarray(frame, dtype=np.uint8)
    return frame

def addImage(img1, img, alpha=0.9, beta=0.1, gamma=0):
    h, w, _ = img1.shape
    img2 = cv2.resize(img, (w,h), interpolation=cv2.INTER_AREA)
    #alpha，beta，gamma
    # alpha = 0.9
    # beta = 1-alpha
    # gamma = 0
    img_add = cv2.addWeighted(img1, alpha, img2, beta, gamma)
    return img_add


import numpy as np
from uncertainties import ufloat
from scipy import optimize
import matplotlib.pyplot as plt

print("---------------einzelspalt---------------")
dx1, i1 = np.genfromtxt("python/einzelspalt.txt", unpack=True)
dsg = 0.325  # abstand schirm gitter in meter
g = 0.075e-3  # in meter
λ = 635e-9  # in meter
dx1 = dx1*10**(-3) # in Metern
mdx1 = 0.024 # Verschiebung Hauptmaxima in Meter
phi = np.arctan((dx1-mdx1)/dsg)
i1 = i1/0.78
phi1 = np.linspace(0.019,0.030)
phi2 = np.arctan((phi1-mdx1)/dsg)

def fitfunc2(phi, A, b):
    return (A**2*b**2*(np.sinc(b*np.sin(phi)/λ))**2)

params, covariance_matrix = optimize.curve_fit(fitfunc2, phi, i1, p0=[1000, 1e-3])
errors = np.sqrt(np.diag(covariance_matrix))
print('A =', params[0], '+-', errors[0])
print('b =', params[1], '+-', errors[1])

plt.plot(dx1, i1, "g.", label="Messdaten")
plt.plot(phi1, fitfunc2(phi2, *params), label="Fitfunktion")
plt.xlabel(r'$x\:/\:\si{\meter}$')
plt.ylabel(r'$I\:/\:\si{\ampere}$')
plt.legend()
plt.grid()
plt.xlim(0.019,0.030)
plt.ylim(0,1.1)
plt.savefig('build/einzelspalt1.pdf')
plt.clf()


# -*- coding: utf-8 -*-
#
# This module defines several normalized lineshapes for 1D and 2D spectroscopy
#
import numpy
from scipy import special

from .. import REAL
from .. import COMPLEX

###############################################################################
#
#    1D absorptive lineshapes
#
###############################################################################

def gaussian(omega, cent, delta):
    """Normalized Gaussian line shape

    """
    return numpy.sqrt(numpy.log(2.0)/numpy.pi)\
                     *numpy.exp(-numpy.log(2.0)*((omega-cent)/delta)**2) \
                     /delta

def lorentzian(omega, cent, gamma):
    """Normalized Lorenzian line shape

    """
    return (gamma/numpy.pi)/((omega-cent)**2 + gamma**2)

def lorentzian_im(omega, cent, gamma):
    """Imaginary part of a normalized Lorenzian line shape

    """
    return 1j*((omega-cent)/numpy.pi)/((omega-cent)**2 + gamma**2)

def voigt(omega, cent, delta, gamma=0.0):
    """Normalized Voigt line shape for absorption

    """
    z = (omega - cent + 1j*gamma)*numpy.sqrt(numpy.log(2.0))/delta

    return numpy.sqrt(numpy.log(2.0))*\
                      numpy.real(special.wofz(z)) \
                      /(numpy.sqrt(numpy.pi)*delta)

def cvoigt(omega, cent, delta, gamma=0.0):
    """Complex normalized Voigt line shape

    """
    a = (delta**2)/(4.0*numpy.log(2))
    z = (gamma - 1j*(omega - cent))/(2.0*numpy.sqrt(a))

    return numpy.real(special.erfcx(z))*numpy.sqrt(numpy.pi/a)/2.0

###############################################################################
#
#    2D lineshapes
#
###############################################################################

def gaussian2D(omega1, cent1, delta1, omega2, cent2, delta2, corr=0.0):
    """Two-dimensional complex Gaussian lineshape

    """
    gamma1 = 0.0
    gamma2 = 0.0
    return voigt2D(omega1, cent1, delta1, gamma1,
                   omega2, cent2, delta2, gamma2, corr=corr)

def voigt2D(omega1, cent1, delta1, gamma1,
            omega2, cent2, delta2, gamma2, corr=0.0):
    """Two-dimensional complex Voigt lineshape

    """
    if corr == 0.0:

        N1 = omega1.shape[0]
        N2 = omega2.shape[0]

        dat1 = cvoigt(omega1, cent1, delta1, gamma1)
        dat2 = cvoigt(omega2, cent2, delta2, gamma2)

        data = numpy.zeros((N1, N2), dtype=COMPLEX)

        for k in range(N1):
            data[:, k] = dat1[k]*dat2[:]

    else:

        raise Exception("Not implemented yet")

    return data

def lorentzian2D(omega1, cent1, gamma1, omega2, cent2, gamma2, corr=0.0):
    """Two-dimensional complex Lorentzian lineshape

    """

    if corr == 0.0:

        N1 = omega1.shape[0]
        N2 = omega2.shape[0]

        dat1 = lorentzian(omega1, cent1, gamma1) + \
               lorentzian_im(omega1, cent1, gamma1)
        dat2 = lorentzian(omega2, cent2, gamma2) + \
               lorentzian_im(omega2, cent2, gamma2)

        data = numpy.zeros((N1, N2), dtype=COMPLEX)

        for k in range(N1):
            data[k, :] = dat1[k]*dat2[:]

    else:

        raise Exception("Not implemented yet")

    return data


<gh_stars>1-10
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import matplotlib.colors as colors
import matplotlib.cm as cm
from matplotlib import rcParams
from mpl_toolkits.axes_grid1 import make_axes_locatable
from scipy.special import erf,erfinv
from scipy.interpolate import griddata,interp2d
from scipy.stats import truncnorm
import sys
import os

rcParams.update({'font.size': 26})
rcParams.update({'mathtext.fontset': 'cm'})

def colorbar(mappable,orient):
    last_axes = plt.gca()
    ax = mappable.axes
    fig1 = ax.figure
    divider = make_axes_locatable(ax)
    if orient == 'right':
        cax = divider.append_axes("right", size="5%", pad=0.05)
        cbar = fig1.colorbar(mappable, cax=cax,orientation='vertical')
        cbar.ax.yaxis.set_ticks_position('right')
    else:
        cax = divider.append_axes("top", size="5%", pad=0.05)
        cbar = fig1.colorbar(mappable, cax=cax,orientation='horizontal')
        cbar.ax.xaxis.set_ticks_position('top')
    cbar.set_ticks([10,100])
    cbar.set_ticklabels(['10','100'])
    cbar.ax.tick_params(which='major',axis='both', direction='out',length = 12.0, width = 8.0,labelsize=fs)
    cbar.ax.tick_params(which='minor',axis='both', direction='out',length = 6.0, width = 4.0,labelsize=fs)
    plt.sca(last_axes)
    return cbar

G = 4.*np.pi**2
M_st = int(sys.argv[1])
if M_st == 0:
    M_A = 1.2
    ymax = [45,45,65,65]
elif M_st == 1:
    M_A = 1.
    ymax = [30,30,50,50]
else:
    M_A = 0.8
    ymax = [20,20,30,30]

e_p = 0.
i_m = 0. # change to i_m = 180. for retrograde moons
m_p = 3.0035e-6 #Earth mass
Q_p = 10.
k2_p = 0.299
R_p = 4.26352e-5 #Earth Radius in AU
T = 1e10 #Moon lifetime in yr

data_dir = "../data/Fig11/"
fname = data_dir + "MC_sample_%1.2f.txt" % M_A

cmap = cm.nipy_spectral_r
vmin = 10
vmax = 5500
my_cmap=cm.get_cmap(cmap)
norm = colors.LogNorm(vmin,vmax)
cmmapable =cm.ScalarMappable(norm,my_cmap)
cmmapable.set_array(range(0,1))
cmap.set_under('w')

fs = 'x-large'
width = 10.
aspect = 2.
ms = 6.
lw = 5

fig = plt.figure(figsize=(aspect*width,width),dpi=300)
ax1 = fig.add_subplot(221)
ax2 = fig.add_subplot(222)
ax3 = fig.add_subplot(223)
ax4 = fig.add_subplot(224)

data_MC = np.genfromtxt(fname,delimiter=',',comments='#')
ax_list = [ax1,ax2,ax3,ax4]
sublbl = ['a','b','c','d']

for m in range(0,2):
    if m ==1:
        i_m = 180
    else:
        i_m = 0

    host = ['A','B']
    color = ['k','r']
    for k in range(0,2):
        ax = ax_list[2*m+k]

        set_cut = np.where(np.logical_and(np.abs(data_MC[:,0]-k)<1e-6,np.abs(data_MC[:,1]-i_m)<1e-6))[0]
        xbins = np.arange(0.001,0.1005,0.0005)

        ybins = np.arange(0.1,ymax[2*m+k]+0.1,0.1)
        h,xedges,yedges = np.histogram2d(data_MC[set_cut,2],data_MC[set_cut,3],bins=[xbins,ybins])
        CS = ax.pcolormesh(xedges[:-1],yedges[:-1],h.T,vmin=vmin,vmax=vmax,cmap=cmap,norm=norm)

        ax.minorticks_on()
        ax.tick_params(which='major',axis='both', direction='out',length = 12.0, width = 8.0,labelsize=fs)
        ax.tick_params(which='minor',axis='both', direction='out',length = 6.0, width = 4.0)

        ax.set_xlim(0.001,0.1)
        ax.set_ylim(0.1,ymax[2*m+k]+10)
        ax.set_xscale('log')
        ax.set_yscale('log')

        ax.set_yticks([1,10])
        ax.set_yticklabels(['1','10'])
        ax.set_xticks([0.001,0.01,0.1])
        ax.set_xticklabels(['0.001','0.01','0.1'])
        if m==0:
            ax.text(0.99,0.9,"prograde" , color='k',fontsize='large',weight='bold',horizontalalignment='right',transform=ax.transAxes)
        else:
            ax.set_xlabel("$a_{\\rm p}/a_{\\rm bin}$",fontsize=fs)
            ax.text(0.99,0.9,"retrograde" , color='k',fontsize='large',weight='bold',horizontalalignment='right',transform=ax.transAxes)
        ax.text(0.02,0.88,sublbl[2*m+k], color='k',fontsize='x-large',weight='bold',horizontalalignment='left',transform=ax.transAxes)

        if k == 0:
            ax.set_ylabel("TTV (min)",fontsize=fs)
        if 2*m+k == 0:
            ax.text(0.5,1.05,"Star A" , color='k',fontsize='large',weight='bold',horizontalalignment='center',transform=ax.transAxes)
        elif 2*m+k == 1:
            ax.text(0.5,1.05,"Star B" , color='k',fontsize='large',weight='bold',horizontalalignment='center',transform=ax.transAxes)
        if (2*m+k) < 2:
            ax.set_xticklabels([])

color_label = 'Number of Systems'
cax = fig.add_axes([0.92,0.11,0.015,0.77])
cbar=plt.colorbar(cmmapable,cax=cax,orientation='vertical')
cbar.set_label(color_label,fontsize=fs)

cbar.set_ticks([10,100,1000])
cbar.set_ticklabels(['10','100','1000'])
cbar.ax.tick_params(which='major',axis='both', direction='out',length = 12.0, width = 8.0,labelsize=fs)
cbar.ax.tick_params(which='minor',axis='both', direction='out',length = 6.0, width = 4.0,labelsize=fs)

fig.subplots_adjust(hspace=0.1)
fig.savefig("../Figs/Fig11_MonteCarlo.png",bbox_inches='tight',dpi=300)
plt.close()


import tensorflow as tf
from buildModel.hyperparameters import *
from scipy.signal import gaussian
import numpy as np
"""
All tensor objects will be defined as global variables.
Any source can access to these values for restoring or
saving or training tensors.
"""
def tensorSummaries(tensor,name):
    with tf.name_scope(name):
        mean = tf.reduce_mean(tensor)
        tf.summary.scalar('mean', mean)
        with tf.name_scope('stddev'):
            stddev = tf.sqrt(tf.reduce_mean(tf.square(tensor - mean)))
        tf.summary.scalar('stddev', stddev)
        tf.summary.scalar('max', tf.reduce_max(tensor))
        tf.summary.scalar('min', tf.reduce_min(tensor))
        tf.summary.histogram('histogram', tensor)

def wrapTensorToTensorboard():
    pass

############# Loss & Dropout probability  ##############################
is_train_step = tf.placeholder(tf.bool)
loss_weight = tf.placeholder(tf.float32)
class_threshold = tf.placeholder(tf.float32)
p_dropout = tf.placeholder(tf.float32)

############################### INPUT ##################################
input_data_train = tf.placeholder(tf.float32, shape=(batch_size, target_size, 1), name="trainingData")
input_data_eval = tf.placeholder(tf.float32, shape=(batch_size, target_size, 1), name="testData")

label_data_train = tf.placeholder(tf.float32, shape=(batch_size, 1, target_size))
label_data_eval = tf.placeholder(tf.float32, shape=(batch_size, 1, target_size))

input_ref_data_train = tf.placeholder(tf.float32, shape=(batch_size, target_size, 1), name="TrainRefData")
input_ref_data_eval = tf.placeholder(tf.float32, shape=(batch_size, target_size, 1), name="TestRefData")

smoothing_filter = tf.constant(gaussian(filter_size_b,50)/np.sum(gaussian(filter_size_b,50)),tf.float32, shape=[filter_size_b,1,1], name='smoothing_filter')

###################### STEM FOR REFGENEDEPTH ###########################
conv1_ref_weight = tf.get_variable("Conv_REF_1", shape=[3, 1, conv1_ref_features], initializer= tf.contrib.layers.variance_scaling_initializer(factor=1.0, mode='FAN_AVG',uniform='True'))

############################ STEM Layer  ###############################
conv1_weight = tf.get_variable("Conv_STEM1", shape=[5, 1, conv1_features], initializer= tf.contrib.layers.variance_scaling_initializer(factor=1.0, mode='FAN_AVG',uniform='True'))
conv2_weight = tf.get_variable("Conv_STEM2", shape=[3, conv1_features, conv2_features], initializer= tf.contrib.layers.variance_scaling_initializer(factor=1.0, mode='FAN_AVG',uniform='True'))
conv1_bias = tf.get_variable("Conv_STEM1_bias", shape=[conv1_features], initializer= tf.contrib.layers.variance_scaling_initializer(factor=1.0, mode='FAN_AVG',uniform='True'))
conv2_bias = tf.get_variable("Conv_STEM2_bias", shape=[conv2_features], initializer= tf.contrib.layers.variance_scaling_initializer(factor=1.0, mode='FAN_AVG',uniform='True'))

############################ Inception 1 ###############################
layer1_width = conv2_features + conv1_ref_features
conv1a_weight = tf.get_variable("Conv_1A", shape=[4, layer1_width, conv1a_features], initializer= tf.contrib.layers.variance_scaling_initializer(factor=1.0, mode='FAN_AVG',uniform='True'))
conv1b_weight = tf.get_variable("Conv_1B", shape=[3, layer1_width, conv1b_features], initializer= tf.contrib.layers.variance_scaling_initializer(factor=1.0, mode='FAN_AVG',uniform='True'))
conv1c_weight = tf.get_variable("Conv_1C", shape=[2, layer1_width, conv1c_features], initializer= tf.contrib.layers.variance_scaling_initializer(factor=1.0, mode='FAN_AVG',uniform='True'))
convMax1_weight = tf.get_variable("Conv_max_W1", shape=[2, layer1_width, convMax1_features], initializer= tf.contrib.layers.variance_scaling_initializer(factor=1.0, mode='FAN_AVG',uniform='True'))
convAvg1_weight = tf.get_variable("Conv_avg_W1", shape=[2, layer1_width, convAvg1_features], initializer= tf.contrib.layers.variance_scaling_initializer(factor=1.0, mode='FAN_AVG',uniform='True'))

conv1a_bias = tf.get_variable("conv1a_bias", shape=[conv1a_features], initializer= tf.contrib.layers.variance_scaling_initializer(factor=1.0, mode='FAN_AVG',uniform='True'))
conv1b_bias = tf.get_variable("conv2b_bias", shape=[conv1b_features], initializer= tf.contrib.layers.variance_scaling_initializer(factor=1.0, mode='FAN_AVG',uniform='True'))
conv1c_bias = tf.get_variable("conv3c_bias", shape=[conv1c_features], initializer= tf.contrib.layers.variance_scaling_initializer(factor=1.0, mode='FAN_AVG',uniform='True'))

############################ Inception 2 ###############################
layer2_width = conv1a_features + conv1b_features + conv1c_features + (layer1_width*2)
conv2a_weight = tf.get_variable("Conv_2A", shape=[4, layer2_width, conv2a_features], initializer= tf.contrib.layers.variance_scaling_initializer(factor=1.0, mode='FAN_AVG',uniform='True'))
conv2b_weight = tf.get_variable("Conv_2B", shape=[3, layer2_width, conv2b_features], initializer= tf.contrib.layers.variance_scaling_initializer(factor=1.0, mode='FAN_AVG',uniform='True'))
conv2c_weight = tf.get_variable("Conv_2C", shape=[2, layer2_width, conv2c_features], initializer= tf.contrib.layers.variance_scaling_initializer(factor=1.0, mode='FAN_AVG',uniform='True'))
convMax2_weight = tf.get_variable("Conv_max_W2", shape=[2, layer2_width, convMax2_features], initializer= tf.contrib.layers.variance_scaling_initializer(factor=1.0, mode='FAN_AVG',uniform='True'))
convAvg2_weight = tf.get_variable("Conv_avg_W2", shape=[2, layer2_width, convAvg2_features], initializer= tf.contrib.layers.variance_scaling_initializer(factor=1.0, mode='FAN_AVG',uniform='True'))

############################ Inception 3 ###############################
layer3_width = conv2a_features + conv2b_features + (layer2_width *2 ) + conv2c_features
conv3a_weight = tf.get_variable("Conv_3A", shape=[5, layer3_width, conv3a_features],initializer= tf.contrib.layers.variance_scaling_initializer(factor=1.0, mode='FAN_AVG',uniform='True'))
conv3b_weight = tf.get_variable("Conv_3B", shape=[4, layer3_width, conv3b_features],initializer= tf.contrib.layers.variance_scaling_initializer(factor=1.0, mode='FAN_AVG',uniform='True'))
conv3c_weight = tf.get_variable("Conv_3C", shape=[3, layer3_width, conv3c_features],initializer= tf.contrib.layers.variance_scaling_initializer(factor=1.0, mode='FAN_AVG',uniform='True'))

############################ Inception 4 ###############################
layer4_width = conv3a_features + conv3b_features + conv3c_features + layer3_width
conv4a_weight = tf.get_variable("Conv_4A", shape=[4, layer4_width, conv4a_features], initializer= tf.contrib.layers.variance_scaling_initializer(factor=1.0, mode='FAN_AVG',uniform='True'))
conv4b_weight = tf.get_variable("Conv_4B", shape=[3, layer4_width, conv4b_features], initializer= tf.contrib.layers.variance_scaling_initializer(factor=1.0, mode='FAN_AVG',uniform='True'))
conv4c_weight = tf.get_variable("Conv_4C", shape=[2, layer4_width, conv4c_features],initializer= tf.contrib.layers.variance_scaling_initializer(factor=1.0, mode='FAN_AVG',uniform='True'))

############################ Inception 5 ###############################
layer5_width = conv4a_features + conv4b_features + conv4c_features +layer4_width
conv5a_weight = tf.get_variable("Conv_5A", shape=[4, layer5_width, conv5a_features],initializer= tf.contrib.layers.variance_scaling_initializer(factor=1.0, mode='FAN_AVG',uniform='True'))
conv5b_weight = tf.get_variable("Conv_5B", shape=[3, layer5_width, conv5b_features],initializer= tf.contrib.layers.variance_scaling_initializer(factor=1.0, mode='FAN_AVG',uniform='True'))
conv5c_weight = tf.get_variable("Conv_5C", shape=[2, layer5_width, conv5c_features],initializer= tf.contrib.layers.variance_scaling_initializer(factor=1.0, mode='FAN_AVG',uniform='True'))

############################ Inception 6  ###############################
layer6_width = conv5a_features + conv5b_features + conv5c_features +layer5_width
conv6a_weight = tf.get_variable("Conv_6A", shape=[10, layer6_width, conv6a_features],initializer= tf.contrib.layers.variance_scaling_initializer(factor=1.0, mode='FAN_AVG',uniform='True'))
conv6b_weight = tf.get_variable("Conv_6B", shape=[8, layer6_width, conv6b_features],initializer= tf.contrib.layers.variance_scaling_initializer(factor=1.0, mode='FAN_AVG',uniform='True'))
conv6c_weight = tf.get_variable("Conv_6C", shape=[6, layer6_width, conv6c_features],initializer= tf.contrib.layers.variance_scaling_initializer(factor=1.0, mode='FAN_AVG',uniform='True'))
conv6d_weight = tf.get_variable("Conv_6D", shape=[5, layer6_width, conv6d_features],initializer= tf.contrib.layers.variance_scaling_initializer(factor=1.0, mode='FAN_AVG',uniform='True'))

############################ Inception 6  ###############################
layer7_width = conv6a_features + conv6b_features + conv6c_features + conv6d_features
conv7a_weight = tf.get_variable("Conv_7A", shape=[10, layer7_width, conv7a_features],initializer= tf.contrib.layers.variance_scaling_initializer(factor=1.0, mode='FAN_AVG',uniform='True'))
conv7b_weight = tf.get_variable("Conv_7B", shape=[8, layer7_width, conv7b_features],initializer= tf.contrib.layers.variance_scaling_initializer(factor=1.0, mode='FAN_AVG',uniform='True'))
conv7c_weight = tf.get_variable("Conv_7C", shape=[6, layer7_width, conv7c_features],initializer= tf.contrib.layers.variance_scaling_initializer(factor=1.0, mode='FAN_AVG',uniform='True'))
conv7d_weight = tf.get_variable("Conv_7D", shape=[5, layer7_width, conv7d_features],initializer= tf.contrib.layers.variance_scaling_initializer(factor=1.0, mode='FAN_AVG',uniform='True'))

############################ Fully Connected ###############################
layer_full_width = conv7a_features + conv7b_features + conv7c_features + conv7d_features#conv6a_features + conv6b_features + conv6c_features + conv6d_features
resulting_width = 1

final_conv_size = resulting_width * ( layer_full_width )
full1_weight = tf.get_variable("Full_W1", shape=[final_conv_size, fully_connected_size1],initializer= tf.contrib.layers.variance_scaling_initializer(factor=1.0, mode='FAN_AVG',uniform='True'))
full2_weight = tf.get_variable("Full_W2", shape=[fully_connected_size1, fully_connected_size2], initializer= tf.contrib.layers.variance_scaling_initializer(factor=1.0, mode='FAN_AVG',uniform='True'))

############################ Output ###############################
output_weight = tf.get_variable("Full_Output", shape=[fully_connected_size2, threshold_division], initializer= tf.contrib.layers.variance_scaling_initializer(factor=1.0, mode='FAN_AVG',uniform='True'))
output_bias = tf.Variable(tf.truncated_normal([threshold_division], stddev=0.1, dtype=tf.float32))

def peakPredictConvModel(input_data_depth, input_data_ref, test=False, smoothing=True, normalize=False, eps=0.00001):
    """
    Define structure of convolution model.
    It will return two final output tensor.
     1. Sub output tensor for training steps
     2. Final output tensor for training and test steps
    :param logger:
    :param input_data:
    :return: Tensor of the output layer
    """
    input_data_depth = input_data_depth + init_depth

    if smoothing:
        depth_tensor_max = tf.nn.pool(input_data_depth, [filter_size_a], strides=[1], padding='SAME', pooling_type='MAX')
        depth_tensor_smooth = tf.nn.conv1d(depth_tensor_max, smoothing_filter, stride=1, padding='SAME')
        input_data_depth = depth_tensor_smooth

    if normalize:
        depth_mean, depth_var = tf.nn.moments(input_data_depth, [1])
        input_data_depth = (input_data_depth -  depth_mean)/tf.sqrt(depth_var + eps)

    #Stem of read depth data
    conv1 = tf.nn.conv1d(input_data_depth, conv1_weight, stride=1, padding='SAME')
    conv1 = tf.contrib.layers.batch_norm(conv1, is_training=is_train_step, data_format='NHWC', decay=0.9, zero_debias_moving_mean=True)
    conv1 = tf.nn.relu(conv1)
    print("Stem 1 : {}".format(conv1.shape))

    conv2 = tf.nn.conv1d(conv1, conv2_weight, stride=1, padding='SAME')
    conv2 = tf.contrib.layers.batch_norm(conv2, is_training=is_train_step, data_format='NHWC', decay=0.9, zero_debias_moving_mean=True)
    conv2 = tf.nn.relu(conv2)
    max_pool1 = tf.nn.pool(conv2, [max_pool_size_stem], strides=[max_pool_size_stem],
            padding='SAME', pooling_type='MAX')
    print("Stem 2 : {}".format(max_pool1.shape))

    #Stem of ref gene data
    conv1_ref = tf.nn.conv1d(input_data_ref, conv1_ref_weight, stride=1, padding='SAME')
    conv1_ref = tf.contrib.layers.batch_norm(conv1_ref, is_training=is_train_step, data_format="NHWC", decay=0.9, zero_debias_moving_mean=True)
    conv1_ref = tf.nn.relu(conv1_ref)
    max_pool1_ref = tf.nn.pool(conv1_ref, [max_pool_size_stem], strides=[max_pool_size_stem],
            padding='SAME', pooling_type='MAX')
    print("Stem_Ref 1 : {}".format(max_pool1_ref.shape))

    input_concat = tf.concat([max_pool1, max_pool1_ref],axis = 2) #max_pool1
    print("Stem_concat : {}".format(input_concat.shape))

    # Inception modules 1 to 6
    concat1 = concatLayer_A(input_concat, conv1a_weight, convMax1_weight, conv1b_weight, convAvg1_weight, conv1c_weight, 2)

    concat2 = concatLayer_A(concat1, conv2a_weight, convMax2_weight, conv2b_weight, convAvg2_weight, conv2c_weight, 2)

    concat3 = concatLayer_B(concat2, conv3a_weight, conv3b_weight, conv3c_weight, 3)
    concat3 = concat3 + tf.nn.pool(tf.concat([concat1 for x in range(4)], axis=2), [6], strides=[6], pooling_type='AVG', padding='SAME')

    concat4 = concatLayer_B(concat3, conv4a_weight, conv4b_weight, conv4c_weight, 2)

    concat5 = concatLayer_B(concat4, conv5a_weight, conv5b_weight, conv5c_weight, 2)
    concat5 = concat5 + tf.nn.pool(tf.concat([concat3 for x in range(3)], axis=2), [4], strides=[4], pooling_type='AVG', padding='SAME')

    concat6 = concatLayer_C(concat5, conv6a_weight, conv6b_weight, conv6c_weight, conv6d_weight, 5)

    concat7 = concatLayer_C(concat6, conv7a_weight, conv7b_weight, conv7c_weight, conv7d_weight, 5)
    concat7 = concat7 + tf.nn.pool(tf.concat([concat5 for x in range(2)], axis=2), [25], strides=[25], pooling_type='AVG', padding='SAME')

    concat7 = tf.nn.pool(concat7, [5], strides=[5], padding='SAME', pooling_type='AVG')
    print("Final Avg pool : {}".format(concat7.shape))

    final_conv_shape = concat7.get_shape().as_list()
    final_shape = final_conv_shape[1] * final_conv_shape[2]
    flat_output = tf.reshape(concat7, [final_conv_shape[0] , final_shape])

    fully_connected1 = tf.matmul(flat_output, full1_weight)
    fully_connected1 = tf.contrib.layers.batch_norm(fully_connected1,is_training=is_train_step, decay=0.9, zero_debias_moving_mean=True)
    fully_connected1 = tf.nn.relu(fully_connected1)
    print("Fully connected A :{}".format(fully_connected1.shape))

    fully_connected2 = tf.matmul(fully_connected1, full2_weight)
    fully_connected2 = tf.contrib.layers.batch_norm(fully_connected2,is_training=is_train_step, decay=0.9, zero_debias_moving_mean=True)
    fully_connected2 = tf.nn.relu(fully_connected2)
    print("Fully connected B :{}".format(fully_connected2.shape))

    final_threshold_output = tf.matmul(fully_connected2, output_weight)
    final_threshold_output = tf.add(final_threshold_output, output_bias)
    print("Threshold Output :{}".format(final_threshold_output.shape))

    return final_threshold_output

def concatLayer_B(source_layer, conv1_w, conv2_w, conv3_w, pooling_size):
    """
    Define concat layer which like Inception module.
    :param source_layer:
    :param conv1_w:
    :param conv2_w:
    :param conv1_b:
    :param conv2_b:
    :param pooling_size:
    :return:
    """
    conv1 = tf.nn.conv1d(source_layer, conv1_w, stride=pooling_size, padding='SAME')
    conv1 = tf.contrib.layers.batch_norm(conv1, is_training=is_train_step, data_format='NHWC', decay=0.9, zero_debias_moving_mean=True)
    conv1 = tf.nn.relu(conv1)

    conv2 = tf.nn.conv1d(source_layer, conv2_w, stride=pooling_size, padding='SAME')
    conv2 = tf.contrib.layers.batch_norm(conv2, is_training=is_train_step, data_format='NHWC', decay=0.9, zero_debias_moving_mean=True)
    conv2 = tf.nn.relu(conv2)

    conv3 = tf.nn.conv1d(source_layer, conv3_w, stride=pooling_size, padding='SAME')
    conv3 = tf.contrib.layers.batch_norm(conv3, is_training=is_train_step, data_format='NHWC', decay=0.9, zero_debias_moving_mean=True)
    conv3 = tf.nn.relu(conv3)

    max_pool = tf.nn.pool(source_layer, [pooling_size], strides=[pooling_size],
            padding='SAME', pooling_type='MAX')

    concat = tf.concat([conv1, conv2, conv3,  max_pool], axis=2)
    print("Concat Type A :{}".format(concat.shape))
    return concat

def concatLayer_C(source_layer, conv1_w, conv2_w, conv3_w, conv4_w, pooling_size):
    """
    Define concat layer which like Inception module.
    :param source_layer:
    :param conv1_w:
    :param conv_max_w:
    :param conv2_w:
    :param conv_avg_w:
    :param conv1_b:
    :param conv_max_b:
    :param conv2_b:
    :param conv_avg_b:
    :param pooling_size:
    :return:
    """
    conv1 = tf.nn.conv1d(source_layer, conv1_w, stride=pooling_size, padding='SAME')
    conv1 = tf.contrib.layers.batch_norm(conv1, is_training=is_train_step, data_format='NHWC', decay=0.9, zero_debias_moving_mean=True)
    conv1 = tf.nn.relu(conv1)

    conv2 = tf.nn.conv1d(source_layer, conv2_w, stride=pooling_size, padding='SAME')
    conv2 = tf.contrib.layers.batch_norm(conv2, is_training=is_train_step, data_format='NHWC', decay=0.9, zero_debias_moving_mean=True)
    conv2 = tf.nn.relu(conv2)

    conv3 = tf.nn.conv1d(source_layer, conv3_w, stride=pooling_size, padding='SAME')
    conv3 = tf.contrib.layers.batch_norm(conv3, is_training=is_train_step, data_format='NHWC', decay=0.9, zero_debias_moving_mean=True)
    conv3 = tf.nn.relu(conv3)

    conv4 = tf.nn.conv1d(source_layer, conv4_w, stride=pooling_size, padding='SAME')
    conv4 = tf.contrib.layers.batch_norm(conv4, is_training=is_train_step, data_format='NHWC', decay=0.9, zero_debias_moving_mean=True)
    conv4 = tf.nn.relu(conv4)

    concat = tf.concat([conv1, conv2, conv3, conv4], axis=2)
    print("Concat Type C :{}".format(concat.shape))
    return concat

def concatLayer_A(source_layer, conv1_w, conv_max_w, conv2_w, conv_avg_w, conv3_w, pooling_size):
    """
    Define concat layer which like Inception module.
    :param source_layer:
    :param pooling_size:
    :return:
    """
    conv1 = tf.nn.conv1d(source_layer, conv1_w, stride=2, padding='SAME')
    conv1 = tf.contrib.layers.batch_norm(conv1, is_training=is_train_step, data_format='NHWC', decay=0.9, zero_debias_moving_mean=True)
    conv1 = tf.nn.relu(conv1)

    conv2 = tf.nn.conv1d(source_layer, conv2_w, stride=2, padding='SAME')
    conv2 = tf.contrib.layers.batch_norm(conv2, is_training=is_train_step, data_format='NHWC', decay=0.9, zero_debias_moving_mean=True)
    conv2 = tf.nn.relu(conv2)

    conv3 = tf.nn.conv1d(source_layer, conv3_w, stride=2, padding='SAME')
    conv3 = tf.contrib.layers.batch_norm(conv3, is_training=is_train_step, data_format='NHWC', decay=0.9, zero_debias_moving_mean=True)
    conv3 = tf.nn.relu(conv3)

    max_pool = tf.nn.pool(source_layer, [pooling_size], strides=[pooling_size,],
            padding='SAME', pooling_type='MAX')

    avg_pool = tf.nn.pool(source_layer, [pooling_size], strides=[pooling_size,],
            padding='SAME', pooling_type='AVG')

    concat = tf.concat([conv1, avg_pool, conv2, max_pool, conv3], axis=2)
    print("Concat Type A :{}".format(concat.shape))
    return concat

def generateOutput(threshold_tensor, depth_tensor, div=10, input_size=12000, batch_size_in=batch_size, smoothing=True, normalize=False, t=1, eps=0.00001):
    """
    It generate
    :param threshold_tensor: This tensor represents read-depth thresholds which have size of 'div'
    :param depth_tensor: This tensor represents
    :param div:
    :return:
    """
    depth_tensor = depth_tensor + init_depth

    if smoothing:
        depth_tensor_max = tf.nn.pool(depth_tensor, [filter_size_a], strides=[1], padding='SAME', pooling_type='MAX')
        depth_tensor_smooth = tf.nn.conv1d(depth_tensor_max, smoothing_filter, stride=1, padding='SAME')
        depth_tensor = depth_tensor_smooth

    if normalize:
        depth_mean, depth_var = tf.nn.moments(depth_tensor, [1])
        depth_tensor = (depth_tensor -  depth_mean)/tf.sqrt(depth_var + eps)
        #depth_max = tf.reduce_max(depth_tensor)
        #depth_tensor = ((depth_tensor - depth_mean)/(depth_max + 0.00001))*100

    depth_tensor = tf.reshape(depth_tensor,[batch_size_in ,div, input_size//div])
    threshold_tensor = tf.reshape(threshold_tensor,[batch_size_in,div,1])
    print("depth tensor :{}".format(depth_tensor.shape))
    print("threshold tensor :{}".format(threshold_tensor.shape))

    result_tensor = tf.subtract(depth_tensor, threshold_tensor, name="results")
    print("result tensor before:{}".format(result_tensor.shape))
    result_tensor = tf.reshape(result_tensor,[batch_size_in, 1, input_size])
    print("result tensor after:{}\n".format(result_tensor.shape))

    if not (t == 1):
        result_tensor = result_tensor * t

    return result_tensor

def aggregatedLoss(label_data_train, prediction_before_sigmoid):
    """
    """
    loss_a = tf.reduce_mean(tf.nn.top_k(tf.nn.weighted_cross_entropy_with_logits(targets=label_data_train, logits=prediction_before_sigmoid,
        pos_weight=tf.maximum(1.,(loss_weight))), k = topK_set_a).values)
    tf.summary.scalar("Top_{}_Loss".format(topK_set_a),loss_a)

    loss_b = tf.reduce_mean(tf.nn.top_k(tf.nn.weighted_cross_entropy_with_logits(targets=label_data_train, logits=prediction_before_sigmoid,
        pos_weight=tf.maximum(1.,(loss_weight))), k = 750).values)
    tf.summary.scalar("Top_{}_Loss".format(topK_set_b),loss_b)

    return loss_a

######################## Tensor graph for training steps #################################
model_output  = peakPredictConvModel(input_data_train, input_ref_data_train)
prediction_before_sigmoid = generateOutput(model_output, input_data_train, div=threshold_division, smoothing=True)
prediction = tf.nn.sigmoid(prediction_before_sigmoid)
loss = aggregatedLoss(label_data_train, prediction_before_sigmoid)
#loss = topKAverageLoss(label_data_train, prediction_before_sigmoid)

update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS)
with tf.control_dependencies(update_ops):
    optimizer = tf.train.AdamOptimizer(learning_rate)
    train_step = optimizer.minimize(loss)

####################### Tensor graph for test steps ######################################
test_model_output = peakPredictConvModel(input_data_eval, input_ref_data_eval)
test_prediction = tf.nn.sigmoid(generateOutput(test_model_output, input_data_eval, div=threshold_division, smoothing=True))


from flask import Flask, render_template, Response
import cv2
import pygame
import numpy as np
from keras.models import load_model
from statistics import mode
from utils.datasets import get_labels
from utils.inference import detect_faces
from utils.inference import draw_text
from utils.inference import draw_bounding_box
from utils.inference import apply_offsets
from utils.inference import load_detection_model
from utils.preprocessor import preprocess_input

# Create Flask Entity Instant
app = Flask(__name__)

# parameters for loading data and images
emotion_model_path = './models/emotion_model.hdf5'
emotion_labels = get_labels('fer2013')

# hyper-parameters for bounding boxes shape
frame_window = 10
emotion_offsets = (20, 40)

# loading models
face_cascade = cv2.CascadeClassifier('./models/haarcascade_frontalface_default.xml')
emotion_classifier = load_model(emotion_model_path)

# getting input model shapes for inference
emotion_target_size = emotion_classifier.input_shape[1:3]

# starting lists for calculating modes
emotion_window = []

cap = cv2.VideoCapture(0)

pygame.mixer.init(16000, -16, 1, 2048)

music_sad = "music/sad.mp3"   # mp3 or mid file
music_angry = "music/angry.mp3"
music_happy = "music/happy.mp3"

def playmusic(soundfile):
    if not pygame.mixer.music.get_busy():
        pygame.mixer.music.stop()
        pygame.mixer.music.load(soundfile)
        pygame.mixer.music.play()
        pygame.mixer.music.fadeout(10000)

def gen(video):
    while True:
        success, bgr_image = cap.read()

        gray_image = cv2.cvtColor(bgr_image, cv2.COLOR_BGR2GRAY)
        rgb_image = cv2.cvtColor(bgr_image, cv2.COLOR_BGR2RGB)

        faces = face_cascade.detectMultiScale(gray_image, scaleFactor=1.1, minNeighbors=5,
                minSize=(30, 30), flags=cv2.CASCADE_SCALE_IMAGE)

        for face_coordinates in faces:

            x1, x2, y1, y2 = apply_offsets(face_coordinates, emotion_offsets)
            gray_face = gray_image[y1:y2, x1:x2]
            try:
                gray_face = cv2.resize(gray_face, (emotion_target_size))
            except:
                continue

            gray_face = preprocess_input(gray_face, True)
            gray_face = np.expand_dims(gray_face, 0)
            gray_face = np.expand_dims(gray_face, -1)
            emotion_prediction = emotion_classifier.predict(gray_face)
            emotion_probability = np.max(emotion_prediction)
            emotion_label_arg = np.argmax(emotion_prediction)
            emotion_text = emotion_labels[emotion_label_arg]
            emotion_window.append(emotion_text)

            if len(emotion_window) > frame_window:
                emotion_window.pop(0)
            try:
                emotion_mode = mode(emotion_window)
            except:
                continue

            if emotion_text == 'angry':
                playmusic(music_angry)
                color = emotion_probability * np.asarray((255, 0, 0))
            elif emotion_text == 'sad':
                playmusic(music_sad)
                color = emotion_probability * np.asarray((0, 0, 255))
            elif emotion_text == 'happy':
                playmusic(music_happy)
                color = emotion_probability * np.asarray((255, 255, 0))
            elif emotion_text == 'surprise':
                color = emotion_probability * np.asarray((0, 255, 255))
            else:
                color = emotion_probability * np.asarray((0, 255, 0))

            color = color.astype(int)
            color = color.tolist()

            draw_bounding_box(face_coordinates, rgb_image, color)
            draw_text(face_coordinates, rgb_image, emotion_mode,
                    color, 0, -45, 1, 1)

        bgr_image = cv2.cvtColor(rgb_image, cv2.COLOR_RGB2BGR)

        # flask 에서 image 재처리
        ret, jpeg = cv2.imencode('.jpg',bgr_image)
        frame = jpeg.tobytes()
        yield (b'--frame\r\n' b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n\r\n')
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break
    cap.release()

@app.route('/')
def index():
    return render_template("index.html")
@app.route('/run')
def run():
    return render_template("generic.html")

@app.route('/video_feed')
def video_feed():
    global cap
    return Response(gen(cap), mimetype='multipart/x-mixed-replace; boundary=frame')

if __name__ == "__main__":
    #app.run(host='0.0.0.0', port=9900, debug=True)
    app.run(debug=True)
    # host 등을 직접 지정하고 싶다면
    # app.run(host="127.0.0.1", port="5000", debug=True)