StackFast / StackFast.py
StackFast.py
Raw
#!/usr/bin/env python
from pydrive.auth import GoogleAuth
from pydrive.drive import GoogleDrive
from google.colab import auth
from oauth2client.client import GoogleCredentials
from google.colab import files
from urllib.error import HTTPError
import matplotlib.pyplot as plt
# Authenticate and create the PyDrive client.
auth.authenticate_user()
gauth = GoogleAuth()
gauth.credentials = GoogleCredentials.get_application_default()
drive = GoogleDrive(gauth)
from IPython.display import display
from ipywidgets import Checkbox, interact, interactive, fixed, interact_manual, IntSlider,Layout
import ipywidgets as widgets
import matplotlib.patches as patches
from scipy.spatial import ConvexHull

from astropy.io import fits,ascii
import astropy
import gc
import numpy as np
import os
import time
import copy
import gzip
import sys
import pickle
import shutil
import statistics as stats
import glob
from multiprocessing import Pool
from contextlib import closing
from matplotlib import path
from scipy.interpolate import interp1d
from astropy import units as u
import astropy.coordinates as ac
#from shapely.geometry import Point, Polygon
np.set_printoptions(threshold=sys.maxsize)
from astropy.table import Table, vstack, hstack,Column, join

import warnings
warnings.filterwarnings("ignore", category=DeprecationWarning) 

import warnings
warnings.filterwarnings("ignore",category=RuntimeWarning)

#import the stackfast utils/functions
import sf_main_set_functions as main_set_funcs
import sf_subset_functions as subset_funcs
import sf_special_utils as sf_utils
import inside_polygon_check as sf_polycheck

#******************************************static global variables******************************************
R90_FRACS = np.array([.25, .5, .75, 1., 1.25, 1.5])
BAD_OBS=[1671,15129,15304]
RADEG = 180./np.pi
PI2=np.pi/2.
PROC_NUM=4
RESULTS_DIR_MAIN="/content/drive/MyDrive/stackfast_sessions/"#'/content/stackfast'
CONTAINER_INFO="https://storage.googleapis.com/all_chandra_data/"
DIRECTORY_ADDRESS=ascii.read(CONTAINER_INFO+'directory_LINK_LIST_fixed_cycle_info.txt')
CYC_INFO=ascii.read(CONTAINER_INFO+"chandra_soft_hard_to_flux_count_cycle.txt")
DIR_OBSID_LIST=(DIRECTORY_ADDRESS["obsid"].data).astype(int)
LINK_LIST=DIRECTORY_ADDRESS["link"].data

#if this is the first ever StackFast run
#create a new main directory:
if not glob.glob(RESULTS_DIR_MAIN):
	os.mkdir(RESULTS_DIR_MAIN)

#******************************************dynamic global variables******************************************
match_exists=[]
global results_dir
results_dir="/content/drive/MyDrive/stackfast_sessions/"


#******************************************initiate session set-up (pre-analysis)****************************
'''
the three functions/widgets below starts the first session
and prompts user to input if they want to start a new session
or use a previous one
'''
initiate_new_session=widgets.Text()
def fnew(Session):
	'''
	initiate session that would ask
	the user if they want to start from 
	a previous session saved in the drive.
	'''
	initiate_new_session.value=str(Session)

def initiate_session_0():
	'''
	The initiate session functions call of the widgets 
	and takes user inputs to find the correct directory and locate the 
	input files already provided.
	'''
	a=interact(fnew, Session=[("Start New Session"),("Continue Old Session")])

#find all directories saved to the drive:
find_all_sf_files=glob.glob(RESULTS_DIR_MAIN+"StackFast_*"+ os.path.sep)

#proceed if there are no files
if not find_all_sf_files:
	print("Proceed to next step!")

'''
set up widget that lists all previous sessions in a dropdown menu
if previous sessions exist (these will be called in initiate_session_* functions)
'''
define_old_sess=widgets.Text()

def fnew6(Session):
	define_old_sess.value=str(Session)

def choose_old_session(old_sess):
	a=interact(fnew6, Session=old_sess)

'''
Allow the user to input a description of the dataset 
in a textbox
'''
define_new_sess=widgets.Text()
def fnew7(Describe):
	define_new_sess.value=Describe

def Sess_def():
	'''
	Allow the user to add a text description
	of the data set. This will be saved in a readme.txt
	in the session directory.
	'''
	a=interact(fnew7, Describe="This dataset is...")

#second initiate session function:
def initiate_session_1():
	'''
	This function looks at the input from initiate_session_0.
	If the user wants to start a new session, it creates a new directory
	and asks for a input set of RA and Dec. If the user wants to continue a 
	previous session, if there is more than one prevous session, it
	uses a drop down widget and asks the user to input which previous session.
	If there was only one saved session, it changes the results_dir
	to point to that session.
	'''
	global results_dir,need_to_upload,find_all_sf_files
	find_all_sf_files=glob.glob(RESULTS_DIR_MAIN+"StackFast_*"+ os.path.sep)
	need_to_upload=False
	if initiate_new_session.value=="Start New Session" or not find_all_sf_files:
		n = 1
		while glob.glob(RESULTS_DIR_MAIN+"StackFast_"+str(n)):
			n+=1
		#this part checks if we are already in a StackFast directory which does not have ra_dec_input.csv 
		#because that would really be a new session
		#it changes directory only if a ra_dec_ does not exist in the current results dir
		if "StackFast_" not in results_dir:
			results_dir=results_dir+"StackFast_"+str(n)
		elif not glob.glob(results_dir+"/ra_dec_input.csv"):
			need_to_upload=True
			if 'main_or_subsample.value' in locals():
				main_or_subsample.value="Analyze Full Sample"
		else:
			results_dir=RESULTS_DIR_MAIN+"StackFast_"+str(n)
		print("Saving all data to "+results_dir)
		os.mkdir(results_dir)
		need_to_upload=True
	else:
		if len(find_all_sf_files)>1:
			choose_old_session(find_all_sf_files)
		elif not glob.glob(find_all_sf_files[0]+"/ra_dec_input.csv"):
			results_dir=find_all_sf_files[0]
			need_to_upload=True
		else:
			print("Please proceed to next step!")
	if need_to_upload:
		upload_init_files()
	return

def upload_init_files():
	'''
	this function is called in initiate_session_1 to upload the
	RA and Dec of a new set of objects. It calls on Sess_def to ask
	for a description of the dataset.
	'''
	global results_dir
	print("Please upload a csv file containing RA, Dec columns (could be zipped),\
		   and briefly describe about this session for future reference:")
	Sess_def()
	uploaded = files.upload()
	filename_= list(uploaded)[0]
	os.system("mv "+filename_+" "+results_dir+"/ra_dec_input.csv")
	#print("moved "+filename_+" "+results_dir+"/ra_dec_input.csv")

'''
The following functions+widgets allow the user to define
if they want to analyse the main set of subset of positions.
The subset can be defined using StackFast, or uploaded by the user.
'''
main_or_subsample=widgets.Text()
def fnew3(Sample):
	main_or_subsample.value=str(Sample)

def initiate_session_interm():
	'''
	This function is caled in initiate_session_2. It is a drop-down menu
	that allows the user to tell SF if they want to analyse a subset,
	and how they would like to define this set of objects.
	'''
	global results_dir
	if need_to_upload:
		main_or_subsample.value=="Analyze Full Sample"
		print("Please continue to next step!")
	else:
		a=interact(fnew3, Sample=[("Analyze Full Sample"),
								  ("Analyze Subset (Use Existing)"),
								  ("Analyze Subset (Define New Subset)"),
								  ("Analyze Subset (Upload New)"),
								  ("Upload Multiple Subsets"),
								  ("Stack All Existing Subsets")])

def initiate_session_2():
	'''
	Checks that all the necessary inputs are present in the 
	results_dir, and calls on initiate_session_interm
	to get input on whether to analyse main set or subset.
	'''
	global results_dir, interm_init, find_all_sf_files
	interm_init=True
	flag=True
	if need_to_upload:
		with open(results_dir+'/ReadMe.txt', 'w') as file:
			file.write(define_new_sess.value)	
			flag=False
	if initiate_new_session.value=="Continue Old Session":
		if len(find_all_sf_files)==1:
			results_dir=find_all_sf_files[0]
			print("Using session saved in: "+results_dir)
		else:
			results_dir=define_old_sess.value
			print("Using session saved in: "+results_dir)
	#print("Saving files in"+results_dir)
	if not glob.glob(results_dir+"/ra_dec_input.csv"):
		upload_init_files()
		interm_init=False
		flag=True
		#os.chdir(results_dir)
	if initiate_new_session.value=="Continue Old Session":
		if interm_init:
			initiate_session_interm()
		flag=False 
	if flag:
		print("Please continue to next step!")
	return

'''
for a very large sample, the user might want to split the sample up
the next three functions+widgets allows this option.
'''
#combine split samples:
yes_no=widgets.Text()
def fnew9(Combine):
	yes_no.value=str(Combine)

def yes_no_func():
	a=interact(fnew9, Combine=["Yes","No"])

outp_split=widgets.Text()
def fnew10(Split_Size):
	outp_split.value=str(Split_Size)

'''
the following three functions+widgets make a list of columns
so the user can define a subset within StackFast.
These functions are called in initiate_session_3.
If using multiple columns to bin subsets,
user should upload a list of RA, Dec.
'''
#make list of columns
chosen_cut_column=widgets.Text()
def colchoose(Column):
	chosen_cut_column.value=str(Column)

def which_column_for_cut(colnmss):
	a=interact(colchoose, Column=colnmss)#samps)

def return_datatypes(inp_tab):
	'''
	this assists initiate_session_3 understand if the user wants
	to use text or number to define a subset
	'''
	dtyp=str(inp_tab.dtype)
	dtyp=dtyp[1:-1]
	dtyp=dtyp.split('),')
	data_types=[]
	for i in dtyp:
		bleh=i.split("', '")[1]
		data_types.append(bleh.split("'")[0])
	#print('data_types',data_types,len(data_types))
	return data_types

'''
the following functions are also called in initiate_session_3.
They allow the user to input description of a new subset which is being uploaded,
or create a list of dropdown list containing old subsets, which the user 
might want to reanalyse.
'''
define_new_subsamp=widgets.Text()
def fnew5(Describe):
	define_new_subsamp.value=Describe

def Subsamp_def():
	a=interact(fnew5, Describe="Conditions...")

define_old_samp=widgets.Text()
def fnew4(Subsample):
	define_old_samp.value=str(Subsample)

def choose_old_sample(subsamp_dirs):
	a=interact(fnew4, Subsample=subsamp_dirs)

def subs_dir(sub_samp):
	'''
	this function allows the code to access the name of the current subset.
	It exists because we do not set the name of the subset as a global variable,
	and only set it if the user wants to analyse a subset.
	'''
	global results_dir
	return results_dir+"subsample_"+str(sub_samp)+"/"


def initiate_session_3():
	'''
	This function takes in input about whether the user wants to analyse a subset,
	and how the user might want to define/upload the subset. It calls on functions above to 
	help the user define/upload subset data. Multiple subsets can also be uploaded,
	and the function guides the user through necessary steps.
	'''
	global results_dir
	global subs_namey
	cond1=initiate_new_session.value=="Start New Session"
	cond2=(initiate_new_session.value=="Continue Old Session" and not (glob.glob(results_dir+"sources_data.txt") or\
		glob.glob(results_dir+"/splitsample_*")))
	#cond3=(initiate_new_session.value=="Continue Old Session" and main_or_subsample.value=="Analyze Full Sample")
	#if it is a new session, or an old session but sources file has not been created yet or is we are analysing a subset
	if cond1 or cond2: #or cond3
		test_input=ascii.read(results_dir+"/ra_dec_input.csv")
		if len(test_input)>1000:
			a=interact(fnew10, Split_Size=(1000,200000,1000))
		test_input=0
	#if cond3:
	#	#check if split samples already exists, if not, we have to read test_input:
	#	if 
	if initiate_new_session.value=="Start New Session" or\
	   main_or_subsample.value=="Analyze Full Sample" or\
	   not interm_init:
		print("Please proceed to next step!")
	elif main_or_subsample.value=="Analyze Subset (Upload New)":
		print("Please upload a csv file containing two columns: RA, Dec of subsample")
		sub_samp=1
		while glob.glob(subs_dir(sub_samp)):
			sub_samp+=1
		os.mkdir(subs_dir(sub_samp))
		subs_namey=subs_dir(sub_samp)
		uploaded = files.upload()
		filename_= list(uploaded)[0]#.keys()
		os.system("mv "+filename_+" "+subs_namey+"/ra_dec_input.csv")
		Subsamp_def()
		print("Please proceed to next step!")
	elif main_or_subsample.value=="Analyze Subset (Define New Subset)":
		print("For a very complex condition, uploading the ra, dec of the subset after making \n\
				all the cuts manually may be easier.")
		#SubsetNew: Find all the colnames from the original file ra_dec_input.csv
		if define_old_sess.value:
			splsamp_dirs=glob.glob(define_old_sess.value+'splitsample_*' + os.path.sep)
		else:
			stackfasts=glob.glob(RESULTS_DIR_MAIN+"StackFast_*"+ os.path.sep)
			if len(stackfasts)==1:
				splsamp_dirs=glob.glob(stackfasts[0]+'splitsample_*' + os.path.sep)
			else:
				splsamp_dirs=[]
				#print("Please rerun previous steps to chose a session.")
				#return
		if splsamp_dirs:
			test_input=ascii.read(splsamp_dirs[0]+"ra_dec_input.csv")
		else:
			test_input=ascii.read(results_dir+"/ra_dec_input.csv")
		inp_coln=test_input.colnames
		inp_dtypes=return_datatypes(test_input)
		which_column_for_cut(inp_coln)
		Subsamp_def()
	elif main_or_subsample.value=="Analyze Subset (Use Existing)":
		#SubsetNew: Look at how many subsets there are and ask for which subset to use from dropdown
		subsamp_dirs=glob.glob(results_dir+'subsample_*' + os.path.sep)
		if subsamp_dirs:
			if len(subsamp_dirs)>1:
				choose_old_sample(subsamp_dirs)
			else:	
				print("Please proceed to next step!")
		else:
			print("No existing subset files found, please rerun previous step, and\
				   define/upload a new subset.")
	elif main_or_subsample.value=="Upload Multiple Subsets":
		#SubsetNew: Look at how many subsets there are and ask for which subset to use from dropdown
		mult_sub=glob.glob(results_dir+'multiple_subsamples' + os.path.sep)
		print("Please upload all subsample files (must contain RA, Dec) in:", results_dir+"multiple_subsamples")
		if not mult_sub:
			#os.system("rm -r "+mult_sub[0])
			os.mkdir(results_dir+"multiple_subsamples")
		else:
			print("Please remember to delete previous subsamples from the multiple_subsamples\
				   directory if you do not want them to be re-processed.")
		print("Please note that the name of input files will be saved in the read_me.txt\
			  files in each subsample directory for future reference.")
	else:
		print("Please proceed to next step!")
	return

'''
Dec is sometimes defined as DEC by the user, this global variable 
adjusts how dec is called according to the initial input file.
'''
global dec_key
dec_key="Dec"

'''
The following two functions are called in initiate_session_4,
and they allow the user to make cuts using the range of data
in a column (in the initial input table) of their choice.
'''
def choose_from_text(col_vals):
	global colval_selectmultiple
	colval_selectmultiple = widgets.SelectMultiple(options=col_vals,\
		value=[col_vals[0]],\
		description='Selection:')
	display(columns_selectmultiple)

def choose_from_num(col_vals, desc_name, dtinfo):
	global colval_selectmultiple
	if dtinfo=="i":
		separate,prec=1,"X"
	else:
		separate,prec=0.001,'.3f'
	mini,maxi=np.min(col_vals),np.max(col_vals)
	colval_selectmultiple = widgets.FloatRangeSlider(
		value=[mini, maxi],
		min=mini, max=maxi, step=separate,
		description=desc_name+":",
		readout_format=prec,
	)
	display(colval_selectmultiple)

def return_all_col_vals(all_dir):
	'''
	function to help splitsamples using multiprocessing
	(it was possible to loop over each directory but this is faster)
	this is called in initiate_session_4
	'''
	test_input=ascii.read(all_dir+"ra_dec_input.csv")
	#all_colval=#np.concatenate((all_colval,test_input[chosen_cut_column.value].data))
	return test_input[chosen_cut_column.value].data


def initiate_session_4():
	'''
	If the user wants to analyse the full sample, this function 
	allows the user to split the sample up into smaller sets for photon extraction
	so that the ram is not overwhelmed (google gives us a 12 GB limit).
	If the user wants to analyse subsets, no splitting is necessary as photon
	extraction from observations occur only when the main set is analysed.
	If the user wants to define a subset within StackFast, this function uses the 
	input from initiate_session_3 to identify which column to use to make the cut,
	and uses choose_from_text or choose_from_num columns to help the user define the subset.
	'''
	global subs_namey, num_of_splits, match_exists, dec_key
	match_exists=[]
	if main_or_subsample.value=="Analyze Full Sample" or initiate_new_session.value=="Start New Session":
		#Sets up main sample for analysis, by splitting the sample if necessary
		splsamp_dirs=glob.glob(results_dir+'/splitsample_*' + os.path.sep)
		if not splsamp_dirs and outp_split.value!="":
			max_split_length=round(int(outp_split.value)/1000)*1000
			print("Max Split length:", max_split_lengt                               h)
			test_input=ascii.read(results_dir+"/ra_dec_input.csv")
			if "DEC" in test_input.colnames:
				dec_key="DEC"
			if len(test_input)>max_split_length:
				num_of_splits=np.ceil(len(test_input)/max_split_length)
				for i in np.arange(num_of_splits):
					'''
					if results_dir[-1]!="/":
						os.mkdir(results_dir+"/splitsample_"+str(int(i)))
						split_sec=test_input[int(i*num_of_splits):int((i+1)*num_of_splits)]
						ascii.write(split_sec,results_dir+"/splitsample_"+str(int(i))+"/ra_dec_input.csv")
						split_sec=0
					else:
					'''
					if i<(num_of_splits-1):
						split_sec=test_input[int(i*max_split_length):int((i+1)*max_split_length)]
						print("sectioning:", i, int(i*max_split_length),int((i+1)*max_split_length))
					else:
						split_sec=test_input[int(i*max_split_length):]
						print("sectioning:", i, int(i*max_split_length), "and the rest")
					obsid_list=sf_utils.find_relevant_obsid(split_sec["RA"].data,split_sec[dec_key].data,False)
					if obsid_list:
						os.mkdir(results_dir+"/splitsample_"+str(int(i)))
						match_exists.append(results_dir+"/splitsample_"+str(int(i)))
						ascii.write(split_sec,results_dir+"/splitsample_"+str(int(i))+"/ra_dec_input.csv")
					split_sec=0
				test_input=0			
				match_exists=np.unique(np.array(match_exists)).tolist()
			else:
				match_exists=-1
		else:
			match_exists=glob.glob(results_dir+'/splitsample_*' + os.path.sep)
		if match_exists!=-1:
			if len(match_exists)>1:
				print("Match exists with Chandra Archive for "+str(len(match_exists))+" split samples. Combine?")
				yes_no_func()
			elif len(match_exists)==0: #means there is no need for splitsamples
				print("Analysing full sample together.")#("No matches were found within Chandra footprint.")
			else:
				print("Only one subset has matches, saved in: "+match_exists[0])
	elif main_or_subsample.value=="Analyze Subset (Define New Subset)":
		splsamp_dirs=glob.glob(define_old_sess.value+'splitsample_*' + os.path.sep)
		if splsamp_dirs:
			test_input=ascii.read(splsamp_dirs[0]+"ra_dec_input.csv")
			inp_coln=test_input.colnames
			inp_dtypes=return_datatypes(test_input)
			rel_col=np.where(np.array(inp_coln)==chosen_cut_column.value)[0]
			rel_dtype=inp_dtypes[rel_col[0]]
			with closing(Pool(processes=PROC_NUM)) as pool:
				resu=pool.map(return_all_col_vals,splsamp_dirs)
				pool.terminate()
			all_colval=resu[0]#np.array([])
			for all_vals in resu[1:]:
				all_colval=np.concatenate((all_colval,all_vals))
		else:
			test_input=ascii.read(results_dir+"/ra_dec_input.csv")
			inp_coln=test_input.colnames
			inp_dtypes=return_datatypes(test_input)
			#make toggle bars
			rel_col=np.where(np.array(inp_coln)==chosen_cut_column.value)[0]
			rel_dtype=inp_dtypes[rel_col[0]]
			all_colval=test_input[chosen_cut_column.value].data
		print("Define criterion:")
		if rel_dtype[1]=="U":
			choose_from_text(np.unique(all_colval))
		elif rel_dtype[1]=="i" or rel_dtype[1]=="f":
			choose_from_num(all_colval, chosen_cut_column.value, rel_dtype[1])
		#make a new directory to store subset information
		sub_samp=1
		while glob.glob(subs_dir(sub_samp)):
			sub_samp+=1
		os.mkdir(subs_dir(sub_samp))
		subs_namey=subs_dir(sub_samp)
		with open(subs_namey+'ReadMe.txt', 'w') as file:
			file.write(define_new_subsamp.value)
	elif main_or_subsample.value=="Analyze Subset (Use Existing)":
		subsamp_dirs=glob.glob(results_dir+'subsample_*' + os.path.sep)
		if len(subsamp_dirs)>1:
			subs_namey=define_old_samp.value
		else:
			subs_namey=subsamp_dirs[0]
	elif main_or_subsample.value=="Analyze Subset (Upload New)":
		with open(subs_namey+'ReadMe.txt', 'w') as file:
			file.write(define_new_subsamp.value)
	elif main_or_subsample.value=="Upload Multiple Subsets":
		newly_uploaded_files=glob.glob(results_dir+"/multiple_subsamples/*")
		#make all the subsample directories:
		if newly_uploaded_files:
			sub_samp=1
			while glob.glob(subs_dir(sub_samp)):
				sub_samp+=1
			for i in np.arange(len(newly_uploaded_files)):
				new_subsample_dir=subs_dir(sub_samp+i)
				os.mkdir(new_subsample_dir)
				os.system("mv "+newly_uploaded_files[i]+" "+new_subsample_dir+"/ra_dec_input.csv")
				read_me_file=newly_uploaded_files[i].split("/")[-1]
				with open(new_subsample_dir+'ReadMe.txt', 'w') as file:
					file.write(read_me_file)
			subs_namey=subs_dir(sub_samp)
		else:
			print("No sumsample RA, Dec files found.")

	print("Please proceed to next step!")
	return

#************************************Final set-up***********************************************

#these widgets help the user set up 
#outp_create_event_dir=widgets.Text()
outp_create_obsid_pointing_file=widgets.Text()
outp_extract_photons=widgets.Text()
outp_prepare_data=widgets.Text()
outp_create_srcimages=widgets.Text()
outp_set_params=widgets.Text()
outp_do_stack=widgets.Text()
outp_boxsize = widgets.Text()
outp_mdistmax = widgets.Text()
outp_src_vis=widgets.Text()


def f1_update(Box_Size,Max_Angle,Create_ObsID_Pointing_File,
	   Extract_Photons,
	   Prepare_Data):#,Create_Source_Images):
	#for split samples - only allows photon extraction and some steps of preparation
	#for very large sample, either the user can combine everything to analyse everything together
	#in initiate_session_3, or they can extract all the photons once
	#and then use subsets for analysis
	outp_boxsize.value=str(Box_Size)
	outp_mdistmax.value=str(Max_Angle)
	outp_create_obsid_pointing_file.value=str(Create_ObsID_Pointing_File)
	outp_extract_photons.value=str(Extract_Photons)
	outp_prepare_data.value=str(Prepare_Data)
	#outp_create_srcimages.value=str(Create_Source_Images)

def f1(Box_Size,Max_Angle,Create_ObsID_Pointing_File,
	   Extract_Photons,
	   Prepare_Data,
	   Create_Source_Images,
	   Set_Parameters,
	   Stack):
	'''
	all the steps - for cases where we don't use split samples
	'''
	outp_boxsize.value=str(Box_Size)
	outp_mdistmax.value=str(Max_Angle)
	outp_create_obsid_pointing_file.value=str(Create_ObsID_Pointing_File)
	outp_extract_photons.value=str(Extract_Photons)
	outp_prepare_data.value=str(Prepare_Data)
	outp_create_srcimages.value=str(Create_Source_Images)
	outp_set_params.value=str(Set_Parameters)
	outp_do_stack.value=str(Stack)



def choose_split_sample(splsamp_dirs):
	global define_split_samp
	print("Note that if 'All' is selected along with several other directories, \nonly \
			the specifically selected directories will be used.")
	splsamp_dirs.insert(0, "All")
	test_layout = Layout(width='47%')
	define_split_samp = widgets.SelectMultiple(options=splsamp_dirs,\
		value=[splsamp_dirs[0]],layout=test_layout,\
		description='Choose Split Samples:')
	display(define_split_samp)


def initiate_StackFast():
	'''
	uses the three widgets above to get user input about which steps to run.
	This is the last bit of set-up.
	'''
	global results_dir,yes_no,flag_all
	flag_all=True
	#this first part takes care of split samples if one is dealing with the full sample:
	if main_or_subsample.value=="Analyze Full Sample":
		#if "splitsample_" in results_dir:
		#	results_dir=results_dir.split("/splitsample_")[0]
		if define_old_sess.value:
			splsamp_dirs=glob.glob(define_old_sess.value+'splitsample_*' + os.path.sep)
		else:
			stackfasts=glob.glob(RESULTS_DIR_MAIN+"StackFast_*"+ os.path.sep)
			if len(stackfasts)==1:
				splsamp_dirs=glob.glob(stackfasts[0]+'splitsample_*' + os.path.sep)
			else:
				#print("Please rerun previous steps to chose a session.")
				#return
				splsamp_dirs=[]
		#splsamp_dirs=glob.glob(results_dir+'/splitsample_*' + os.path.sep)
		if splsamp_dirs:
			flag_all=False
			if len(match_exists)>1:
				if yes_no.value=="Yes":
					if not glob.glob(results_dir+"/combined"):
						os.mkdir(results_dir+"/combined")
					if not glob.glob(results_dir+"/combined/ra_dec_input.csv"):
						big_obj=ascii.read(match_exists[0]+"/ra_dec_input.csv")
						print("added", match_exists[0])
						for matched_obs in match_exists[1:]:
							small_obj=ascii.read(matched_obs+"/ra_dec_input.csv")
							print("added", matched_obs)
							big_obj=vstack([small_obj,big_obj])	
						ascii.write(big_obj,results_dir+"/combined/ra_dec_input.csv",delimiter=",")
						big_obj=0
				else:
					choose_split_sample(splsamp_dirs)
	elif main_or_subsample.value=="Analyze Subset (Define New Subset)":
		if define_old_sess.value:
			splsamp_dirs=glob.glob(define_old_sess.value+'splitsample_*' + os.path.sep)
		else:
			stackfasts=glob.glob(RESULTS_DIR_MAIN+"StackFast_*"+ os.path.sep)
			if len(stackfasts)==1:
				splsamp_dirs=glob.glob(stackfasts[0]+'splitsample_*' + os.path.sep)
			else:
				splsamp_dirs=[]
				#print("Please rerun previous steps to chose a session.")
				#return
		#splsamp_dirs=glob.glob(define_old_sess.value+'splitsample_*' + os.path.sep)
		if not splsamp_dirs:
			input_dir=select_a_subsample(results_dir)
			#ascii.write(input_dir,subs_namey+"ra_dec_input.csv",overwrite=True)
		else:
			t11=time.time()
			with closing(Pool(processes=PROC_NUM)) as pool:
				resu=pool.map(select_a_subsample,splsamp_dirs)
				pool.terminate()
			input_dir=vstack(resu) #(spldir)
			print("Input from split samples:",len(input_dir)," in time:",time.time()-t11)
		ascii.write(input_dir,subs_namey+"ra_dec_input.csv",overwrite=True)
	if flag_all:
		print("To save time, only re-run steps which have not been completed before for this session/subset.")
		print("Note that the Create_Source_Images step creates source cutout images for each source and obsid, along with exposure maps.")
		print("It does not affect stacking, and it can be a time and memory consuming step, so the user may wish to skip this step.")
		a=interact(f1, Box_Size=(25,200,25),
				   Max_Angle=(3,11,0.5),
				   Create_ObsID_Pointing_File=True,
				   Extract_Photons=True,
				   Prepare_Data=True,
				   Create_Source_Images=False,
				   Set_Parameters=True,
				   Stack=True)
	else:
		a=interact(f1_update, Box_Size=(25,200,25),
			   	Max_Angle=(3,11,0.5),
			   	Create_ObsID_Pointing_File=False,
			   	Extract_Photons=False,
			   	Prepare_Data=False)	
		Create_Source_Images=False
		Set_Parameters=False
		Stack=False
		outp_create_srcimages.value=str(Create_Source_Images)
		outp_set_params.value=str(Set_Parameters)
		outp_do_stack.value=str(Stack)	

def select_a_subsample(target_folder):
	test_input=ascii.read(target_folder+"ra_dec_input.csv")
	inp_coln=test_input.colnames
	inp_dtypes=return_datatypes(test_input)
	#make toggle bars
	rel_col=np.where(np.array(inp_coln)==chosen_cut_column.value)[0]
	rel_dtype=inp_dtypes[rel_col[0]]
	if isinstance(colval_selectmultiple.value[0],str):
		#conditions on text - iterate maybe
		#print("it is text",colval_selectmultiple.value)
		where=np.logical_or(test_input[chosen_cut_column.value].data==colval_selectmultiple.value[0],
							test_input[chosen_cut_column.value].data==colval_selectmultiple.value[1])
		for i in np.arange(len(colval_selectmultiple.value)-2):
			where=np.logical_or(where,test_input[chosen_cut_column.value].data==colval_selectmultiple.value[i+2])
		rel_row_inds=np.where(where)
	else:
		#conditions over a numerical column
		#print("it is number",colval_selectmultiple.value)
		ranges=np.logical_and(test_input[chosen_cut_column.value].data>=colval_selectmultiple.value[0],
							  test_input[chosen_cut_column.value].data<=colval_selectmultiple.value[1])
		rel_row_inds=np.where(ranges)
	input_dir=test_input[rel_row_inds]
	return input_dir

#************************************ANALYSIS***********************************************

def StackFast():
	'''
	This function calls on StackFast_real, where the steps chosen by the user,
	such as extraction of photons, preparation of data, stacking, etc takes place.
	This step takes into account whether the user is going to use splitsample 
	(which is just photon extraction in chunks because the main sample is too large),
	subset, or the main set at once, and sets some gobal variables up before calling
	StackFast_real.
	'''
	global results_dir, define_split_samp, subs_namey
	if define_old_sess.value:
		splsamp_dirs=glob.glob(define_old_sess.value+'splitsample_*' + os.path.sep)
	else:
		stackfasts=glob.glob(RESULTS_DIR_MAIN+"StackFast_*"+ os.path.sep)
		if len(stackfasts)==1:
			splsamp_dirs=glob.glob(stackfasts[0]+'splitsample_*' + os.path.sep)
		else:
			#print("Please rerun previous steps to chose a session.")
			#return
			splsamp_dirs=[]
	#splsamp_dirs=glob.glob(define_old_sess.value+'splitsample_*' + os.path.sep)
	if splsamp_dirs and yes_no.value=="Yes":
		results_dir=define_old_sess.value+"combined"
		all_filees=ascii.read(splsamp_dirs[0]+"ra_dec_input.csv")
		for restf in splsamp_dirs[1:]:
			bl_files=ascii.read(restf+"ra_dec_input.csv")
			all_filees=vstack([all_filees,bl_files])
		bl_files=0
		ascii.write(all_filees,results_dir+"/ra_dec_input.csv")
		print("Results saved to: ", results_dir)
		ress=StackFast_real()
		return ress
	elif splsamp_dirs and main_or_subsample.value=="Analyze Full Sample":
		if len(splsamp_dirs)==1:
			results_dir=splsamp_dirs[0][:-1]
			print("Results saved to: ", results_dir)
			ress=StackFast_real()
			return ress
			#print(define_split_samp.value)
		elif len(define_split_samp.value)==1 and define_split_samp.value[0]=="All":
			overall=[]
			for samp in splsamp_dirs:
				results_dir=samp[:-1]
				print("Results saved to: ", results_dir)
				ress=StackFast_real()
				overall.append(ress)
			try:
				return vstack(overall)
			except:
				return
		else:
			all_dirs=define_split_samp.value
			overall=[]
			for aa in all_dirs:
				if aa!="All":
					results_dir=aa[:-1]
					print("Results saved to: ", results_dir)
					ress=StackFast_real()
					if len(all_dirs)>1:
						overall.append(ress)
			if len(all_dirs)>1:
				return vstack(overall)
			else:
				return ress
	elif main_or_subsample.value=="Upload Multiple Subsets":
		print("Note that the plotting functions below only show plots from the last subsample \
			processed by StackFast.")
		print("After processing all subsamples, choose a specific subsample from the \n\
			dropdown menu above and run through all the steps to use the plotting functions shown below.")
		all_subsamples=glob.glob(results_dir+'subsample_*' + os.path.sep)
		#match
		match_name=np.where(np.array(all_subsamples)==subs_namey)[0][0]
		iter_over=all_subsamples[match_name:]
		for subss in iter_over:
			subs_namey=subss
			ress=StackFast_real()
	elif main_or_subsample.value=="Stack All Existing Subsets":
		print("Note that the plotting functions below only show plots from the last \
			subsample processed by StackFast.")
		print("After processing all subsamples, choose a specific subsample from the \n\
			dropdown menu above and run through all the steps to use the plotting functions shown below.")
		all_subsamples=glob.glob(results_dir+'subsample_*' + os.path.sep)
		for subss in all_subsamples:
			subs_namey=subss
			ress=StackFast_real()
	else:
		ress=StackFast_real()
		return ress

def reset_split_samples():
	global define_old_sess
	splsamp_dirs=glob.glob(define_old_sess.value+'splitsample_*' + os.path.sep)
	for obj in splsamp_dirs:
		os.system("rm -r "+obj)
	return

def sources_file_maker_multip(spldir):
	'''
	called by StackFast_real in case splitsamples are being used.
	'''
	#global sources_id, sources_ra, sources_dec
	sources_file=ascii.read(spldir+"sources_data.txt")
	c1=ac.SkyCoord(sources_file['sources_ra'].data*u.degree, sources_file['sources_dec'].data*u.degree, frame="icrs")
	idx, d2d, d3d = c2.match_to_catalog_sky(c1)
	blah=np.where(d2d==0)[0]
	idx=idx[blah]
	print("From:",spldir, "num of sources", len(sources_file[idx]))
	need=sources_file[idx]
	need["spldir"]=np.full(len(need),spldir)
	return need#sources_file_now

def StackFast_real():
	'''
	All the analysis happens in this step, but it calls on other functions
	for each step of the analysis. Because of indexing conventions, 
	and the fact that photons are not actually extracted from Chandra observation
	for subsets (they are taken from the results of the main set)
	the functions used to process the subsets are different from the functions
	used to study the main set. This function is a little bit on the longer side
	because there are two code-blocks, one for the main set, and one for subsets.
	'''
	#time the code
	tot_stack_time=time.time()

	#define global variables
	global boxsize 
	global mdistmax_glob
	global use_subset, dec_key
	global pointing_file_name,sources_file_name,exp_file,prepare_file_name
	global photon_extraction_results_dir,extraction_interm,extraction_stacked_file
	global image_dir,exp_dir,background_save_file,exclude_list,parameter_outfile
	global stacked_outimage,allstack_output_file,final_stacked_fits_file,final_stacked_all_columns
	global extract_indices_save_name,sources_data_subset,results_dir,match_exists,spldirs

	#name the result files:
	pointing_file_name=results_dir+"/obsid_pointing_files.txt"
	sources_file_name=results_dir+'/sources_data.txt'
	exp_file=results_dir+"/calc_expo_results.fits"
	prepare_file_name=results_dir+"/prepared_data.pkl"
	photon_extraction_results_dir=results_dir[:-1]
	extraction_interm= results_dir+"/all_stacked_evt_interm.fits"
	extraction_stacked_file = results_dir+'/all_stacked_evt.fits'
	image_dir=results_dir+'/STACK_IMGS'
	exp_dir=results_dir+'/EXP_MAP'
	background_save_file=results_dir+"/background_save.txt"
	exclude_list="NA"
	parameter_outfile=results_dir+"/parameter_data.pkl"
	stacked_outimage=results_dir+'/FINAL_allXsrc.fits'
	#allstack_output_file=results_dir+'/FINAL_allstack_output.txt'
	final_stacked_fits_file=results_dir+"/FINAL_stackdata.fits"
	final_stacked_ind_columns=results_dir+"/FINAL_stackdata_individual_columns.fits"
	extract_indices_save_name=results_dir+"/extract_subset_indices.txt"
	sources_data_subset="sources_data_subset.txt"
	#sub_samp=1

	#extract global variables from the widgets
	boxsize=float(outp_boxsize.value)
	mdistmax_glob=float(outp_mdistmax.value)
	create_obsid_pointing_file= outp_create_obsid_pointing_file.value=="True"
	extract_photons= outp_extract_photons.value=="True"
	prepare_data= outp_prepare_data.value=="True"
	create_srcimages= outp_create_srcimages.value=="True"
	set_params= outp_set_params.value=="True"
	do_stack= outp_do_stack.value=="True"
	
	#the variable below is crucial as the code has to take different 
	#routes based on whether or not we are analysing a subset
	use_subset= "Subset" in main_or_subsample.value
	use_main_set=~use_subset
	
	#Final check for input positions
	find_csvs=glob.glob(results_dir+"/ra_dec_input.csv")
	if not find_csvs:
		print("No full sample .csv file found, please run previous steps \nand upload\
		 a two column csv file containing RA, Dec (additional columns can also be used for binning).")
		return
	else:
		if create_obsid_pointing_file and not use_subset:
			'''
			This step connects each source with all the relevant obsids in which the source appears.
			It is quick because we already have the polygons corresponding to each obsid in a .csv file.
			'''
			print("input files",results_dir+"/ra_dec_input.csv")
			initial_positional_info=ascii.read(results_dir+"/ra_dec_input.csv")
			if "DEC" in initial_positional_info.colnames:
				dec_key="DEC"
			else:
				dec_key="Dec"
			source_ra=initial_positional_info["RA"].data
			source_dec=initial_positional_info[dec_key].data
			if "splitsample_" in results_dir:
				quick_check=results_dir.split("splitsample_")[0]
				quick_check=ascii.read(quick_check+"splitsample_0/ra_dec_input.csv")
				max_split_length=len(quick_check)
				start_num=int(results_dir.split("splitsample_")[-1])*max_split_length
			else:
				start_num=0
			obsid_list=sf_utils.find_relevant_obsid(source_ra,source_dec,True)
			create_sources_data_file(source_ra,source_dec,start_num)
			if not obsid_list:
				print("No source falls within Chandra archival footprint for sample \n at "+results_dir)
				return

		global sources_file, sources_id, sources_ra, sources_dec, exp_out, sources_links

		if use_main_set:
			'''
			This step of the if statement is to do initial analysis (not subset analysis).
			The else statement goes into analysing subsets. Subsets should only be done after
			the main set has been analysed completely. If splitting sets into chunks,
			since the splitting is done by length and therefore randomly, it only allows users
			to extract photons and prepare source-obsid pairs (so sf_extract and sf_prepare) steps
			and not subsdequent stacking steps. The stacking should be done in subsets in
			bins of interesting sources, not randomly divided chunks.
			'''
			sources_file=ascii.read(sources_file_name)
			sources_id=sources_file['sources_id'].data
			sources_ra=sources_file['sources_ra'].data
			sources_dec=sources_file['sources_dec'].data
			sf_polycheck.make_all_region_files()

			obs_point=ascii.read(results_dir+"/obsid_pointing_files.txt")

			if extract_photons:
				t1=time.time()
				print("Starting photon extraction...")
				'''
				sf_extract_photons opens each observation
				on which any sources were found for the input set. 
				Then using the coordinates and IDL's histnd function,
				which TTA converted to python, it finds all the photons
				associated with any source falling on that observation.
				The final result is making a list of photons, associated
				with each source and obsid, using which the source and
				background fluxes will be calculated in subsequent steps.
				'''
				main_set_funcs.sf_extract_photons(obs_point["obsid"].data,save_fits=True)
				print("Photons extraction time:",time.time()-t1)

			if prepare_data or set_params:
				t1=time.time()
				print("Starting data preparation...")
				'''
				prepare file step makes pairs of source and obsid,
				calculates R90 (radius encircling 90% energy), source and background
				aperture for each source-obsic pair and does aperture photometry
				'''
				main_set_funcs.sf_new_prepare_data(sf_calc=prepare_data)
				print("Data preparation time:",time.time()-t1)

			if set_params:
				t1=time.time()
				exp_outf=fits.open(exp_file)
				exp_out=exp_outf[1].data
				exp_out=Table(exp_out)
				exp_outf=0
				print("Starting parameter setup...")
				'''
				This step sets up booleans (variables starting with i_* are booleans for list of photons
				created in sf_extract_* step, and ind_* are for individual source pairs).
				These booleans take into account bad observations, problematic areas in the map,
				photons tagged as source photons, photons tagged as background photons etc,
				to calculate final photon fluxes. This lists of booleans make the final stacking 
				very fast.

				This step also creates source images if the user specified image cutouts should be made
				not recommended unless it is necessary, because it can be time consuming
				'''
				main_set_funcs.sf_new_set_parameters(create_srcimages=create_srcimages,mdistmax=mdistmax_glob)
				print("Parameter setup time:",time.time()-t1)

			if do_stack:
				t1=time.time()
				print("Starting stacking...")
				'''
				Final stacking step using all the booleans from the previous step.
				Returns astropy table of photon fluxes, source and background counts,
				and actual fluxes, for each input source.
				'''
				stackdata,res=main_set_funcs.sf_newstack_id(sources_id,ind_cts=True)
				print("Stacking time:",time.time()-t1)

				#write one more table as fits file with columns from res (read above) and from sources id

				hdu = fits.BinTableHDU(data=res)
				hdu.writeto(final_stacked_ind_columns,overwrite=True)
				hdu = fits.BinTableHDU(data=stackdata)
				hdu.writeto(final_stacked_fits_file,overwrite=True)
				print("Sample output:")
				print(stackdata[:np.minimum(len(stackdata),10)])
				#files.download(final_stacked_fits_file) 
				print("Total stacking time:", time.time()-tot_stack_time)
				return res#stackdata
			else:
				return 0

		else:	
			'''
			If stacking a subset, first make sure all the necessary subdirectories,
			for example to store stacked images, are created in the subset directory.
			It is slightly different to grab photon information if the main sample was 
			split into chunks, so 
			'''
			print("Using Subset:")
			t11=time.time()
			global subset#appropriate_ids, subset
			image_dir=subs_namey+'STACK_IMGS'
			exp_dir=subs_namey+'EXP_MAP'
			
			if define_old_sess.value:
				splsamp_dirs=glob.glob(define_old_sess.value+'splitsample_*' + os.path.sep)
			else:
				stackfasts=glob.glob(RESULTS_DIR_MAIN+"StackFast_*"+ os.path.sep)
				if len(stackfasts)==1:
					#splsamp_dirs keeps track of whether or not the main sample
					#is split into chunks
					splsamp_dirs=glob.glob(stackfasts[0]+'splitsample_*' + os.path.sep)
				else:
					splsamp_dirs=[]
			if not glob.glob(subs_namey+sources_data_subset):
				subset=ascii.read(subs_namey+"ra_dec_input.csv")
				if "DEC" in subset.colnames:
					dec_key="DEC"
				else:
					dec_key="Dec"
				
				if not splsamp_dirs:
					'''
					find_subset_ids() fetches the index number of the objects
					in the subset from the main set, for quick photon extraction
					from the main set results
					'''
					idx,sources_file=subset_funcs.find_subset_ids(subset)
					sources_file.sort("sources_id")
					sources_id=sources_file['sources_id'].data
					sources_ra=sources_file['sources_ra'].data
					sources_dec=sources_file['sources_dec'].data
					ascii.write(sources_file,subs_namey+sources_data_subset,overwrite=True)
					spldirs=[]
				else:
					'''
					if the main sample was split up, we use multiprocessing to go
					through all the split samples to produce the source_id list
					and there is an additional column listing which splitsample_directory
					the object belongs to
					'''
					global c2
					try:
						c2=ac.SkyCoord(subset["ra"]*u.degree,subset["dec"]*u.degree,frame="icrs")
					except KeyError:
						c2=ac.SkyCoord(subset["RA"]*u.degree,subset[dec_key]*u.degree,frame="icrs")
					with closing(Pool(processes=PROC_NUM)) as pool:
						resu=pool.map(sources_file_maker_multip,splsamp_dirs)
						pool.terminate()
					sources_file_now=vstack(resu) #(spldir)
					sorted_id,id0=np.unique(sources_file_now['sources_id'].data,return_index=True)
					sources_file_now=sources_file_now[id0]
					sources_id=sources_file_now['sources_id'].data
					sources_ra=sources_file_now['sources_ra'].data
					sources_dec=sources_file_now['sources_dec'].data
					sources_links=sources_file_now['spldir'].data
					spldirs=np.unique(sources_file_now['spldir'].data)
					ascii.write(sources_file_now,subs_namey+sources_data_subset,overwrite=True)
			else:
				'''
				if a sources_id file already existed, read in sources_id, ra and dec
				for subset  sources
				'''
				sources_file=ascii.read(subs_namey+sources_data_subset)
				sources_file.sort("sources_id")
				sources_id=sources_file['sources_id'].data
				sources_ra=sources_file['sources_ra'].data
				sources_dec=sources_file['sources_dec'].data
				if splsamp_dirs:
					sources_links=sources_file['spldir'].data
					spldirs=np.unique(sources_links)
				else:
					spldirs=[]

			#step below is for diagnotic purposes - if the user wants to check
			#some observations manually, we produce DS9 region files in StackFast
			#to plot all source positions on the observation
			make_all_region_files()
			if create_obsid_pointing_file:
				pointing_file_name=subs_namey+"obsid_pointing_files.txt"
				'''
				makes list of relevant obsids, with information such as 
				pointing center, roll angle, exposure time
				'''
				obsid_list=sf_utils.find_relevant_obsid(sources_ra,sources_dec,True)
				if not obsid_list:
					print("No matches.")
					return		
			print("Done creating source id pointing file in",time.time()-t11)

			if extract_photons:
				t1=time.time()
				print("Starting photon extraction...")
				'''
				function below uses ID matches with the main set
				to grab all relevant photon information (they were already 
				extracted when the main set was analysed). It is fast
				because we don't open up individual observations to extract
				photon infomation.
				'''
				subset_funcs.sf_extract_photons_subset(save_fits=True)
				print("Photons extraction time:",time.time()-t1)

			if prepare_data or set_params:
				t1=time.time()
				print("Starting data preparation...")
				'''
				prepare file step makes pairs of source and obsid,
				calculates R90 (radius encircling 90% energy), source and background
				aperture for each source-obsic pair and does aperture photometry
				'''
				subset_funcs.sf_new_prepare_data_subset(sf_calc=prepare_data)
				print("Data preparation time:",time.time()-t1)

			if set_params:
				t1=time.time()
				save_names=exp_file.split("/")[-1]
				save_names=save_names.split(".")
				#exp_file=results_dir+"/calc_expo_results.fits"
				exp_outf=fits.open(subs_namey+save_names[0]+"_subset."+save_names[1])
				exp_out=exp_outf[1].data
				exp_out=Table(exp_out)
				exp_outf=0

				print("Starting parameter setup...")
				'''
				This step sets up booleans (variables starting with i_* are booleans for list of photons
				created in sf_extract_* step, and ind_* are for individual source pairs).
				These booleans take into account bad observations, problematic areas in the map,
				photons tagged as source photons, photons tagged as background photons etc,
				to calculate final photon fluxes. This lists of booleans make the final stacking 
				very fast.

				This step also creates source images if the user specified image cutouts should be made
				not recommended unless it is necessary, because it can be time consuming
				'''
				subset_funcs.sf_new_set_parameters_subset(create_srcimages=create_srcimages, mdistmax=mdistmax_glob)
				print("Parameter setup time:",time.time()-t1)

			if not len(spldirs)>0 and create_srcimages:
				'''
				This step just copies over source images into the subset
				directory from the main_set directory. For cases
				where we split up the main sample, source images are 
				not created in the original run and will be created in the
				sf_new_set_parameters_subset step.
				'''
				srcimage_exists=glob.glob(results_dir+"EXP_MAP")
				if srcimage_exists:
					os.mkdir(subs_namey+"EXP_MAP")
					os.mkdir(subs_namey+"STACK_IMGS")
					num_source=np.arange(len(sources_id))
					with closing(Pool(processes=PROC_NUM)) as pool:
						resu=pool.map(subset_funcs.src_image_copier,num_source)
						pool.terminate()
				else:
					print("Please create original source images to be copied.")

			if do_stack:
				t1=time.time()
				print("Starting stacking...")
				'''
				Final stacking step using all the booleans from the previous step.
				Returns astropy table of photon fluxes, source and background counts,
				and actual fluxes, for each input source.
				'''
				stackdata,res=subset_funcs.sf_newstack_id_subset(sources_id,ind_cts=True)
				print("Stacking time:",time.time()-t1)

				#write one more table as fits file with columns from res (read above) and from sources id
				#same thing in fits file:
				hdu = fits.BinTableHDU(data=res)
				save_names=final_stacked_ind_columns.split("/")[-1]
				save_names=save_names.split(".")
				hdu.writeto(subs_namey+save_names[0]+"_subset."+save_names[1],overwrite=True)
				
				hdu = fits.BinTableHDU(data=stackdata)
				save_names=final_stacked_fits_file.split("/")[-1]
				save_names=save_names.split(".")
				hdu.writeto(subs_namey+save_names[0]+"_subset."+save_names[1],overwrite=True)
				print("Sample output:")
				print(stackdata[:np.minimum(len(stackdata),10)])
				#files.download(final_stacked_fits_file) 
				print("Total subset stacking time:", time.time()-tot_stack_time)
				print("Download all stacked info by running sf.download_all_subset_info(array_containing_subsample_numbers)")
				return res#stackdata
			else:
				return 0


def download_result_file():
	files.download(final_stacked_fits_file) 
	files.download(final_stacked_all_columns) 
	return 


def create_sources_data_file(src_ra,src_dec,start_num=0):
	'''
	assigns index numbers to each source based on order in input file
	'''
	sources_id=1.+(start_num+np.arange(0,len(src_ra),1.))/10000000.
	ascii.write([src_ra,src_dec,sources_id],sources_file_name,
			names=('sources_ra','sources_dec','sources_id'),overwrite=True)
	if "splitsample_" in sources_file_name:
		split_min_max=sources_file_name.split("/")[-2]
		ascii.write([[np.min(sources_id)],[np.max(sources_id)],[results_dir+split_min_max]],results_dir+"/min_max.txt",
					names=["min","max","sampdir"],overwrite=True)
	return


#**********************************************Visualizing Final Outputs*******************************************

def select_source_to_visualize(output_tab):
	#print(type(output_tab))
	if not isinstance(output_tab,astropy.table.table.Table):
		print("Please input the result from previous step as the only argument.")
		return
	elif len(output_tab)==0:
		print("No sources found.")
		return
	else:
		a=interact(vis_id_val, Source_ID=output_tab["ind_ID"].data)

def vis_id_val(Source_ID):
	outp_src_vis.value=str(Source_ID)

def plot_relevant_photons(r90_frac=1.,rad_given=3.0,plot_second=False):
	sourceid=float(outp_src_vis.value)
	print(sourceid)
	
	gc.collect()
	if use_subset:
		save_names=extraction_interm.split("/")[-1]
		save_names=save_names.split(".")
		hdul = fits.open(subs_namey+save_names[0]+"_subset."+save_names[1])
		event_head=hdul[1].header
		boxsize = float(outp_boxsize.value)#event_head['BOXSIZE']
		stacked_event=hdul[1].data
		save_names=prepare_file_name.split("/")[-1]
		save_names=save_names.split(".")
		with open(subs_namey+save_names[0]+"_subset."+save_names[1], 'rb') as f:
			stack_file,boxsize,source_id,ra,dec,x,y,old_x,old_y,\
			energy,source_ra,source_dec,mdist,r90,badid,bad,dist,\
			id0,idv,nphv,ph_obsid,i_flux_from_soft,i_flux_from_hard = pickle.load(f)
	else:
		hdul = fits.open(extraction_stacked_file)
		event_head=hdul[1].header
		boxsize = float(outp_boxsize.value)#event_head['BOXSIZE']
		stacked_event=hdul[1].data
		with open(prepare_file_name, 'rb') as f:
			stack_file,boxsize,source_id,ra,dec,x,y,old_x,old_y,\
			energy,source_ra,source_dec,mdist,r90,badid,bad,dist,\
			id0,idv,nphv,ph_obsid,i_flux_from_soft,i_flux_from_hard = pickle.load(f)

	right_inds=np.where(stacked_event['time'].flatten()>0)[0]
	stacked_event=stacked_event[right_inds]
	find_source=np.where(stacked_event["iid"].data==sourceid)[0]
	#print("stacked_event[find_source]", stacked_event[find_source])
	stacked_event_rel=stacked_event[find_source]
	#print("find source",find_source, type(find_source))

	#print all stacked photons for this object
	if len(find_source)>0:
		plt.figure()
		plt.title("Source: "+str(sourceid)+\
				  " All photons")

		xs,ys=stacked_event_rel["x"],stacked_event_rel["y"]
		soft_ind=np.where(np.logical_and(stacked_event_rel["energy"]>500,
										 stacked_event_rel["energy"]<=2000))[0]
		plt.scatter(xs[soft_ind], ys[soft_ind], color="red",marker="X",s=2, label="Soft band")
		hard_ind=np.where(np.logical_and(stacked_event_rel["energy"]>2000,
										 stacked_event_rel["energy"]<=7000))[0]
		plt.scatter(xs[hard_ind], ys[hard_ind], color="blue",marker="X",s=1, label="Hard band")
		plt.axis('equal')
		plt.xlim(-boxsize/2,boxsize/2)
		plt.ylim(-boxsize/2,boxsize/2)
		sec=str(sourceid).split('.')
		plt.legend()
		#plt.savefig(results_dir+"/src_"+sec[0]+"_"+sec[1]+"_obsid_"+str(each_obs["source_obs_obs"])+".pdf")
		plt.show()

		r90_rel=r90[find_source]

		exp_outf=fits.open(exp_file)
		exp_out=exp_outf[1].data
		relevant_exp=np.where(exp_out["source_id"]==sourceid)[0]

		for each_obs in exp_out[relevant_exp]:
			#read in observation
			
			stack_ind=np.where(stacked_event_rel["obsid"]==each_obs["source_obs_obs"])[0]
			if len(stack_ind)>0:
				plt.figure()
				plt.title("Source: "+str(sourceid)+\
						  " Obsid: "+str(each_obs["source_obs_obs"]))
				r90=r90_rel[stack_ind]
				#print all the photons:
				#pick correct obsid
				#draw a circle around exp_out["source_x"][relevant_exp],exp_out["source_y"][relevant_exp]
				#each_obs["source_x"],each_obs["source_y"]
				#rel_rad=each_obs["source_obs_srcrad"]*r90_frac*0.492
				#print("r90",r90[0],r90_frac)
				srcrad_in = (r90 * r90_frac) / 0.492

				#Set a hard minimum of srcrad of 3 pixels (RCH 11/21/13)
				rel_rads=np.clip(srcrad_in,3,None)
				#print("rel_rads",rel_rads,rad_given)
				
				#for rel_rad in rel_rads:
				circle=patches.Circle((0,0),rel_rads[0],facecolor=None,\
								edgecolor='blue',linestyle='dotted',\
								linewidth='1.',fill=False,label="Source aperture")
				plt.gca().add_patch(circle)
				circle=patches.Circle((0,0),1.3*rel_rads[0],facecolor=None,\
								edgecolor='green',linestyle='dotted',\
								linewidth='1.',fill=False,label="Background aperture")
				plt.gca().add_patch(circle)
				circle=patches.Circle((0,0),boxsize/2.,facecolor=None,\
								edgecolor='green',linestyle='dotted',\
								linewidth='1.',fill=False)
				plt.gca().add_patch(circle)
				#plt.plot(circle)
				if plot_second:
					circle=patches.Circle((0,0),rad_given,facecolor=None,\
										edgecolor='green',linestyle='dotted',\
										linewidth='0.5',fill=False)
					plt.gca().add_patch(circle)
				#plt.plot(circle)

				right_obs=np.where(stacked_event_rel["obsid"]==each_obs["source_obs_obs"])[0]
				xs,ys=stacked_event_rel["x"][right_obs],stacked_event_rel["y"][right_obs]
				soft_ind=np.where(np.logical_and(stacked_event_rel["energy"][right_obs]>500,
												 stacked_event_rel["energy"][right_obs]<=2000))[0]
				plt.scatter(xs[soft_ind], ys[soft_ind], color="red",marker="X",s=2, label="Soft band")
				hard_ind=np.where(np.logical_and(stacked_event_rel["energy"][right_obs]>2000,
												 stacked_event_rel["energy"][right_obs]<=7000))[0]
				plt.scatter(xs[hard_ind], ys[hard_ind], color="blue",marker="X",s=1, label="Hard band")
				plt.axis('equal')
				plt.xlim(-boxsize/2,boxsize/2)
				plt.ylim(-boxsize/2,boxsize/2)
				sec=str(sourceid).split('.')
				plt.legend()
				#plt.savefig(results_dir+"/src_"+sec[0]+"_"+sec[1]+"_obsid_"+str(each_obs["source_obs_obs"])+".pdf")
				plt.show()
			else:
				print("Obsid: "+str(each_obs["source_obs_obs"])+" does not have any photons within box.")
	else:
		print("No matches for this source.")
	return