StackFast / sf_subset_functions.py
sf_subset_functions.py
Raw
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 sf_special_utils as sf_utils
import python_idl_funcs as pidl_funcs

#**********************************************ALL Subset analysis files*******************************************
def src_image_copier(i):
	src_id=sources_id[i]
	os.popen('cp '+results_dir+"EXP_MAP/*"+str(src_id)+"*.fits "+subs_namey+"EXP_MAP/.")
	os.popen('cp '+results_dir+"STACK_IMGS/*"+str(src_id)+"*.fits "+subs_namey+"STACK_IMGS/.")
	return

def find_subset_ids(subset):
	sources_file=ascii.read(results_dir+"sources_data.txt")
	if "DEC" in subset.colnames:
		dec_key="DEC"
	else:
		dec_key="Dec"
	c1=ac.SkyCoord(sources_file['sources_ra'].data*u.degree, sources_file['sources_dec'].data*u.degree, frame="icrs")
	#c1=ac.SkyCoord(sources_ra*u.degree, sources_dec*u.degree, frame="icrs")
	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")
	idx, d2d, d3d = c2.match_to_catalog_sky(c1)
	exact_match=np.where(d2d==0)[0]
	#return idx,sources_file['sources_id'].data[idx],sources_file[idx]
	#return idx,sources_file[idx]
	return idx[exact_match],sources_file[idx[exact_match]]

def sf_extract_photons_subset(save_fits=True,save_as_ascii=False):
	'''
	Uses source index matches with the main set
	to grad all relevant photon information. It is fast
	because we don't open up individual observations to extract photon infomation.
	'''
	global spldirs
	#check if the main list of sources is broken up into chunks (then loop over all splitsamples)
	if len(spldirs)>0:#
		for splsamp in spldirs:#splsamp_dirs:
			extr=extraction_stacked_file.split('/')[-1]
			all_evts=fits.open(splsamp+extr)
			all_evts=all_evts[1].data
			all_evts=Table(all_evts)

			min_maxx=ascii.read(splsamp+"/min_max.txt")
			start_num,end_num=min_maxx["min"].data[0],min_maxx["max"].data[0]
			
			rel_ra_dec=np.where(np.logical_and(sources_id>=start_num, sources_id<end_num))[0]
			rel_ids=sources_id[rel_ra_dec]

			right_inds=np.where(all_evts['time'].flatten()>0)[0]
			all_evts=all_evts[right_inds]

			print("starting match", splsamp)
			tt=time.time()

			source_id = all_evts['iid'].data

			
			ig,ind_start,idx=np.intersect1d(rel_ids,source_id,return_indices=True)
			necessary_iids=source_id[idx]
			
			if len(ind_start)>0:
				

				sorted_id,id0=np.unique(source_id,return_index=True)
				#print("id0",id0)
				ig,ind_start,ind2=np.intersect1d(source_id,necessary_iids,return_indices=True)
				ig,ind_end,ind_ig=np.intersect1d(id0,ind_start,return_indices=True)

				if id0[ind_end[-1]]<id0[-1]: 
					ind1_end=id0[ind_end+1]
				else:
					ind1_end=id0[ind_end[:-1]+1]
					ind1_end=np.concatenate((ind1_end,np.array([len(source_id)])))

				
				bool_inds=np.array([])
				for indi_start,indi_end in zip(ind_start,ind1_end):
					bool_inds=np.concatenate((bool_inds,np.arange(indi_start,indi_end)))
				
				bool_inds=bool_inds.astype(int)
				if 'right_sources' in locals():
					right_sources=vstack([right_sources,all_evts[bool_inds]])
				else:
					right_sources=all_evts[bool_inds]
	else:

		all_evts=fits.open(extraction_stacked_file)
		all_evts=all_evts[1].data
		all_evts=Table(all_evts)

		right_inds=np.where(all_evts['time'].flatten()>0)[0]
		stacked_event=all_evts[right_inds]

		
		source_id= stacked_event['iid'].data
		sorted_id,id0=np.unique(source_id,return_index=True)


		#To create bool_inds
		matches,ind1_start,ind2=np.intersect1d(source_id,sources_id,return_indices=True)
		matches,ind_interm,ind2=np.intersect1d(id0,ind1_start,return_indices=True)
		
		if ind_interm[-1]+1<len(id0): #i.e. if the last matched id is not the last object in the main sample
			ind1_end=id0[ind_interm+1]
		else:
			ind1_end=id0[ind_interm[:-1]+1]
			ind1_end=np.concatenate((ind1_end,np.array([len(source_id)])))

		bool_inds=np.array([])
		
		for ind_start,ind_end in zip(ind1_start,ind1_end):
			bool_inds=np.concatenate((bool_inds,np.arange(ind_start,ind_end)))

		bool_inds=bool_inds.astype(int)
		right_sources=stacked_event[bool_inds]

	#find duplicates within subset so that they can be counted one time:
	dupis=np.logical_and(right_sources["obsid"].data==0,right_sources["time"]>0)
	dups,non_dups=np.where(dupis)[0],np.where(~dupis)[0]
	#print("dupis",dupis)

	if np.any(dupis):
		duplicate_evt_tags,non_dup_evt_tags=right_sources["evt_tag"].data[dups],right_sources["evt_tag"].data[non_dups]
		#match evt_tags - how many duplicates don't appear again?
		not_dup_anymore=np.setdiff1d(duplicate_evt_tags,non_dup_evt_tags)
		#find first instance of match to this no-longer-duplicate objects the in duplicate_evt_tags
		matched_ids,ind_of_first,ignore=np.intersect1d(duplicate_evt_tags,not_dup_anymore,return_indices=True)
		inds_in_big_table=dups[ind_of_first]
		right_duplicate_obsids=(duplicate_evt_tags[ind_of_first]).astype(int)
		right_sources["obsid"].data[inds_in_big_table]=right_duplicate_obsids

	
	right_sources.sort('iid')
	print("Length of extracted photon list:",len(right_sources))
	hdu = fits.BinTableHDU(data=right_sources)
	#hdu.header["BOXSIZE"]=boxsize
	save_names=extraction_interm.split("/")[-1]
	save_names=save_names.split(".")
	hdu.writeto(subs_namey+save_names[0]+"_subset."+save_names[1],overwrite=True)

	return 0

def sf_new_prepare_data_subset(sf_calc=True,#R90_FRACS,sf_calc=True,
						set_bg_files=True,set_bg_fileh=True,
						set_rmax=True, set_badid=True,fits_file_name=None):
	''' 
	sf_new_prepare data calls sf_obs_exposure
	with stack_out and exp_out as output
	'''
	global boxsize,flag_all,source_id,ra,dec,x,y,old_x,old_y,energy,source_ra,source_dec,ph_obsid ,test_obsid, spldirs
	boxsize=float(outp_boxsize.value)

	sky_name='/analysis/057.exp.bin1.fits.gz'
	det_name='/analysis/exp.bin1.fits.gz'
	if not hasattr(boxsize, '__len__'):
		boxsize=100.

	
	try:
		test_input=ascii.read(subs_namey+"obsid_pointing_files.txt")
	except:
		test_input=ascii.read(pointing_file_name)#obs_pointing_file)

	test_obsid=test_input["obsid"].data
	obs_ra=test_input["rapnt"].data
	obs_dec=test_input["decpnt"].data
	obs_roll=test_input["roll"].data
	#test_str=[str(i) for i in test_obsid]
	badid=[]
	
	good_bg_fileh_names=[]

	if not set_rmax:
		rmax=100.
	
	if fits_file_name!=None:
		stack_file=fits_file_name
		hdul = fits.open(stack_file)
	else:
		save_names=extraction_interm.split("/")[-1]
		save_names=save_names.split(".")#extraction_stacked_file.split(".")
		stack_file=subs_namey+save_names[0]+"_subset."+save_names[1]
		
		hdul = fits.open(stack_file)
		
		stacked_event=hdul[1].data
		

	source_id,ra,dec,x,y,old_x,old_y,energy,source_ra,source_dec,ph_obsid = stacked_event['iid'],stacked_event['ra'],\
																	  stacked_event['dec'],stacked_event['x'],\
																	  stacked_event['y'],stacked_event['old_x'],\
																	  stacked_event['old_y'],stacked_event['energy'],\
																	  stacked_event['ira'],stacked_event['idec'],\
																	  stacked_event['obsid']

	
	test_obsid=np.unique(ph_obsid)
	#ignore obsid of duplicates:
	zero_obs=np.where(test_obsid>0)[0]
	test_obsid=test_obsid[zero_obs]
	
	'''
	sets it so id0 is now the *first* photon in the list associated with
	each id
	'''
	sorted_id,id0=np.unique(source_id,return_index=True)
	id0=np.sort(id0)

	
	nphv=np.concatenate((np.diff(id0),np.array([len(source_id)-id0[-1]])))
	
	'''
	set the number of photons to zero where there are no photons 
	(energy == 0)
	'''
	e0 = np.where(energy[id0]==0)[0]
	nphv[e0] = 0

	#get the vectors for each input:
	idv = source_id[id0]
	#if you have already done it can step over
	if sf_calc:

		save_names=exp_file.split("/")[-1]
		save_names=save_names.split(".")
		
		global appropriate_tab
		appropriate_tab=idv#np.unique(source_id)
		
		if len(spldirs)>0:#splsamp_dirs:
			appropriate_tab,ind1_start,ind2=np.intersect1d(source_id,sources_id,return_indices=True)
			#print("matched sources ids",appropriate_tab)
			spldirs=np.unique(sources_links[ind2])
			with closing(Pool(processes=PROC_NUM)) as pool:
				resu=pool.map(sf_cut_relevant_sf_calc_parts,spldirs)#splsamp_dirs)
				pool.terminate()
			
			right_sources=vstack(resu)
			right_sources.sort("source_id")
			
		else:
			right_sources=sf_cut_relevant_sf_calc_parts()

		hdu = fits.BinTableHDU(data=right_sources)

		save_names=exp_file.split("/")[-1]
		save_names=save_names.split(".")
		hdu.writeto(subs_namey+save_names[0]+"_subset."+save_names[1],overwrite=True)
		
	
	mdist = np.full(len(ra),-99.)
	with closing(Pool(processes=PROC_NUM)) as pool:
		resu=pool.map(sf_utils.calculate_mdists,np.ndarray.tolist(np.arange(len(test_obsid))))#np.ndarray.tolist(arg_appro))

	#print("resu[:,0],resu[:,1]",resu[:1])
	#for mdists,inds in zip(resu[:,0],resu[:,1]):
	for mem in resu:
		mdist[mem[1]]=mem[0]#mdists
	dist = np.sqrt(x**2+y**2)
	#print("mdist",mdist)


	r90=sf_utils.calculate_r90(mdist)#1.5+(9.*(mdist/10.)**1.9)
	bad=np.zeros(len(mdist))

	#if set_badid:
	if len(badid)>0:
		for i in np.arange(len(badid)):
			bad_photon_indices=np.where(ph_obsid==badid[i])[0]
			bad[bad_photon_indices]=1
	
	save_names=prepare_file_name.split("/")[-1]
	save_names=save_names.split(".")
	with open(subs_namey+save_names[0]+"_subset."+save_names[1], 'wb') as f:
		pickle.dump([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,stacked_event['flux_from_soft'],\
					 stacked_event['flux_from_hard']], f)
	return 

#cut up sf_calc:
def sf_cut_relevant_sf_calc_parts(dir_num=None):
	#Table([np.unique(source_id)],names=["source_id"])
	#print("appropriate_tab",appropriate_tab)
	if not dir_num:
		exp_outf=fits.open(exp_file)
		exp_out=exp_outf[1].data
		exp_out=Table(exp_out)
		exp_outf=0
		#split_samp_num=0
	else:
		exp_name=exp_file.split("/")[-1]
		exp_outf=fits.open(dir_num+exp_name)
		exp_out=exp_outf[1].data
		exp_out=Table(exp_out)
		exp_outf=0		
		#split_samp_num=int(dir_num.split("splitsample_")[-1][:-1])

	#To create bool_inds
	matches,ind1_start,ind2=np.intersect1d(exp_out["source_id"].data,appropriate_tab,return_indices=True)
	#print("matches",exp_out["source_id"].data[ind1_start])
	uniqs_ignore,id0ss=np.unique(exp_out["source_id"].data,return_index=True)
	id0ss=np.sort(id0ss)
	matches,ind_interm,ind2=np.intersect1d(id0ss,ind1_start,return_indices=True)
	
	if ind_interm[-1]+1<len(id0ss):
		ind1_end=id0ss[ind_interm+1]
	else:
		ind1_end=id0ss[ind_interm[:-1]+1]

	bool_inds=np.array([])
	for ind_start,ind_end in zip(ind1_start,ind1_end):
		bool_inds=np.concatenate((bool_inds,np.arange(ind_start,ind_end)))


	#now take care of the last elements ind_interm[:-1]
	if ind_interm[-1]+1==len(id0ss):
		bool_inds=np.concatenate((bool_inds,np.arange(id0ss[ind_interm[-1]],len(exp_out["source_id"].data))))#np.array([id0ss[ind_interm[-1]]])))

	bool_inds=bool_inds.astype(int)
	
	#block below to test if we are getting the right sources for boolean
	right_sources=exp_out[bool_inds]
	right_sources["source_obs_ind_old"]=right_sources["source_obs_ind"]
	#right_sources["source_obs_ind"]=source_obs_ind

	#sources_obs_ind fix
	uniqui_sources,change_ind=np.unique(right_sources["source_id"].data,return_index=True)
	comms,src_oobss_ins,discard_ind=np.intersect1d(appropriate_tab,uniqui_sources,return_indices=True)
	#print("unique sources and src_oobss_ins",len(uniqui_sources),len(src_oobss_ins))
	change_ind=np.concatenate((change_ind,np.array([len(right_sources)-1])))
	for i in np.arange(len(change_ind)-1):
		right_sources["source_obs_ind"][change_ind[i]:change_ind[i+1]+1]=src_oobss_ins[i]
	return right_sources

def download_all_subset_info(samp_num):
	#is an old session defined?
	old_sess_name=define_old_sess.value
	for num_subsamp in samp_num:
		all_subsam_=glob.glob(old_sess_name+'subsample_'+str(num_subsamp) + os.path.sep)
		#print(old_sess_name+'subsample_'+str(num_subsamp),all_subsam_)
		if all_subsam_:
			for subsamp in all_subsam_:
				any_readme=glob.glob(subsamp+"ReadMe.txt")
				#print(any_readme,subsamp+"ReadMe.txt")
				if any_readme:
					print("Processing ",subsamp)
					fl=open(any_readme[0])
					subset_info= fl.readline()
					print(subsamp, subset_info)
					curr_file=glob.glob(subsamp+"FINAL_stackdata_individual_columns_*fits")
					if curr_file:
						name_now="FINAL_stackdata_individual_columns_"+subset_info[:-4]+".fits"
						os.system("mv "+curr_file[0]+" "+subsamp+"/"+name_now)
						files.download(subsamp+"/"+name_now)
					curr_file=glob.glob(subsamp+"FINAL_stackdata_subset*.fits")
					if curr_file:
						name_now="FINAL_stackdata_"+subset_info[:-4]+".fits"
						os.system("mv "+curr_file[0]+" "+subsamp+"/"+name_now)
						files.download(subsamp+"/"+name_now) 
	return

#set parameter routines
def sf_new_set_parameters_subset(create_srcimages=False, run_background=True,\
						  softe_new=np.array([500.,2000.]),harde_new=np.array([2000., 7000.]),\
						  mdistmax=1e9,lim=np.array([-1,200]),\
						  r90_frac=1.,min_exp_frac=0.0):
	'''
	incomplete:
	where do these variables comes from
	use_bgh, ~bad, exclude_list?
	also what are we saving?
	save the variables i need do_stack

	also where were all the mdistmax, bad etc coming from?
	in exp_out:
	obsid, max_det_exp, source_obs_ind, source_obs_obs, source_obs_mdist, $
		  source_obs_r90, source_obs_srcrad, R90_FRACS, source_obs_exp_sky, $
		  source_obs_exp_det, source_obs_bgh, source_obs_bgs, $ 
		  source_obs_exp_sky_var, source_obs_exp_det_var, filename=exp_file

	in stack_out:
	stack_file,boxsize,id,ra,dec,x,y,old_x,old_y,energy,source_ra, $
		 source_dec, mdist, r90, badid, bad, dist, id0, idv,  $
		 nphv, ph_obsid, filename=save_name

	*********SAVE THIS FILE, but what variables?************
	'''
	#needs to read in stack_idl_file and exp_file
	#f=fits.open(stack_file)
	#stack_out=f[1].data
	#sources_file=ascii.read(sources_file_name)

	global boxsize 
	boxsize=float(outp_boxsize.value)

	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)

	
	use_bgh = len(exp_out["source_obs_bgh"].data)>0#1 
	use_bgs = len(exp_out["source_obs_bgs"].data)>0#1
	use_exp = ~(use_bgs or use_bgh)

	#print("spldirs and create srcimages",spldirs, create_srcimages)
	if len(spldirs)>0 and create_srcimages:
		experimental_sf_create_src_imgs(x,y,energy,source_id,
										idv,id0,exp_out["source_obs_ind"],
										exp_out["source_obs_obs"],sources_id,#file["sources_id"],
										sources_ra,sources_dec,boxsize)
										#sources_file["sources_ra"],sources_file["sources_dec"],
										#boxsize)

	if run_background:
		i_srcph_bgaper,srcph_bgfrac,\
		bg_in_srcaper_soft,bg_in_srcaper_hard,bg_in_srcaper_soft_flux,bg_in_srcaper_hard_flux=sf_perform_background(mdistmax,softe_new,harde_new,r90_frac)

		

	'''
	Run the old parameter output routine
	Define three main array sizes, (photon-source, source-obs, source)
	and make blank arrays for each size'''

	n_photon_source_matches = len(x)#len(stack_out["x"].data)
	n_source_obs_matches = len(exp_out["source_obs_ind"].data)
	print("exp out length",n_source_obs_matches)
	n_sources = len(id0)#len(stack_out["id0"].data)

	#most likely don't need these blank lists - delete after defining everything else
	photon_source_int_blank=np.zeros(n_photon_source_matches).astype(int)
	photon_source_float_blank=np.zeros(n_photon_source_matches)
	source_obs_double_blank=np.zeros(n_photon_source_matches)
	source_obs_int_blank=np.zeros(n_photon_source_matches).astype(int)
	source_int_blank=np.zeros(n_sources).astype(int)
	sources_float_blank=np.zeros(n_sources)

	obs_obsids=np.array(np.unique(ph_obsid))
	srcph_srcids = source_id
	src_srcids = idv#stack_out["idv"].data
	srcph_obsids = ph_obsid#stack_out["obsid"].data
	srcobs_srcids = np.array(exp_out["source_id"])#idv[exp_out["source_obs_ind"].data]
	srcobs_obsids = np.array(exp_out["source_obs_obs"])

	#srcobs_soids=np.array([str(np.round(i,4))+" "+str(int(j)) for i,j in zip(srcobs_srcids,srcobs_obsids)])
	#srcph_soids = np.array([str(np.round(i,4))+" "+str(int(j)) for i,j in zip(source_id,ph_obsid)])
	srcobs_soids=np.array([str(i)+" "+str(int(j)) for i,j in zip(srcobs_srcids,srcobs_obsids)])
	srcph_soids = np.array([str(i,)+" "+str(int(j)) for i,j in zip(source_id,ph_obsid)])

	'''
	Index array initialization: sf_gen_indarrays is used to generate
	index arrays used to communicate data between source-lengt,
	srcobs-length, and srcph-length arrays
	'''
	sp2s_sorted, sp2s_starts, sp2s_nums,sp2s_indices=sf_gen_indarrays(srcph_srcids,src_srcids)

	sp2o_sorted, sp2o_starts, sp2o_nums,sp2o_indices=sf_gen_indarrays(srcph_obsids,obs_obsids)
	#print("srcobs_srcids",srcobs_srcids)
	#print("src_srcids",src_srcids)

	so2s_sorted, so2s_starts, so2s_nums,so2s_indices=sf_gen_indarrays(srcobs_srcids,src_srcids)
	#print("so2s_starts",so2s_starts)

	so2o_sorted, so2o_starts, so2o_nums,so2o_indices=sf_gen_indarrays(srcobs_obsids,obs_obsids)

	sp2so_sorted, sp2so_starts, sp2so_nums,sp2so_indices=sf_gen_indarrays(srcph_soids,srcobs_soids)
	#initialize source-length data arrays; to be computed later
	srcradv,r90v=np.zeros(n_sources),np.zeros(n_sources)
	srcareav,obsidv,mdistv=np.zeros(n_sources),np.zeros(n_sources),np.zeros(n_sources)

	#initialize exposure calculation arrays; to be computed later
	src_exp_sky,src_exp_det,src_area_exp_sky=np.zeros(n_sources),np.zeros(n_sources),\
											 np.zeros(n_sources)

	src_area_exp_det,src_bg_ctss,src_bg_cths=np.zeros(n_sources),np.zeros(n_sources),\
											 np.zeros(n_sources)

	#initialize filter arrays; to be computed later
	i_src_valid_mdist=np.zeros(n_sources).astype(int)
	i_srcph_non_excluded = photon_source_int_blank + 1
	i_src_idlist = np.zeros(n_sources).astype(int)

	#Compute srcrad, the source radius in pixels from r90 (arcseconds)
	srcrad_in = (r90 * r90_frac) / 0.492

	#Set a hard minimum of srcrad of 3 pixels (RCH 11/21/13)
	srcrad=np.clip(srcrad_in,3,None)

	'''Compute photons-per-source (nph), photons-per-source in source
	aperture (nph_src), and photons-per-source in background aperture
	(nph_bg) at source-length, and srcph-length'''
	i_srcph_srcaper = (dist<=srcrad)

	#Compute id_step, used for binning/ drawing the histograms later 
	#don't calculate it here as it will be calculated in the sf_newstack_id step
	id_step=0#np.min(np.diff(idv))

	'''
	Part 3: Specific aperture radius is applied to the exposure data;
	if necessary, interpolation will be used on the r90 fractions
	these hold the exposure information for srcobs pairs
	'''
	srcobs_exp_sky,srcobs_exp_det=np.zeros(n_photon_source_matches),np.zeros(n_photon_source_matches)
	srcobs_bgh,srcobs_bgs=np.zeros(n_photon_source_matches),np.zeros(n_photon_source_matches)

	#these store the variance in the exposure time
	srcobs_exp_det_var,srcobs_exp_sky_var=np.zeros(n_photon_source_matches),np.zeros(n_photon_source_matches)

	'''R90_FRACS is from make_stack_list, r90_frac is the actual fractions
	ind_frac indicates whether we have exposure calculated for this r90, or we have to interpolate'''
	ind_frac = np.where(R90_FRACS==r90_frac)[0]
	
	if len(ind_frac)>0:
		srcobs_exp_sky = exp_out["source_obs_exp_sky"][:, ind_frac]
		srcobs_exp_det = exp_out["source_obs_exp_det"][:, ind_frac]
		srcobs_exp_det_var = exp_out["source_obs_exp_det_var"][:, ind_frac]
		srcobs_exp_sky_var = exp_out["source_obs_exp_sky_var"][:, ind_frac]

		if use_bgh:
			srcobs_bgh = exp_out["source_obs_bgh"][:, ind_frac]
		if use_bgs:
			srcobs_bgs = exp_out["source_obs_bgs"][:, ind_frac]
	else:
		for i in np.arange(len(source_obs_ind)):
			source_obs_exp_interp=interp1d(R90_FRACS,exp_out["source_obs_exp_sky"][i,:])
			srcobs_exp_sky[i]=source_obs_exp_interp(r90_frac)
			source_obs_det_interp=interp1d(R90_FRACS,exp_out["source_obs_exp_det"][i,:])
			srcobs_exp_det[i]=source_obs_det_interp(r90_frac)
			
			if use_bgs:
				source_obs_bgs_interp=interp1d(R90_FRACS,exp_out["source_obs_bgs"][i,:])
				srcobs_bgs[i]=source_obs_bgs_interp(r90_frac)

			if use_bgh:
				source_obs_bgh_interp=interp1d(R90_FRACS,exp_out["source_obs_bgh"][i,:])
				srcobs_bgh[i]=source_obs_bgh_interp(r90_frac)

	#weight background by flux count:
	srcobs_bgs_flux,srcobs_bgh_flux=srcobs_bgs*exp_out["flux_c_soft"],srcobs_bgh*exp_out["flux_c_hard"]

	'''Part 4: Generate exposure filters
	
	With the srcobs-length exposure calculations, we can now compute a
	couple more filter arrays'''

	if min_exp_frac==0:
		igood_obs_exp = (srcobs_exp_det>0).astype(int)
	else:
		igood_obs_exp = (srcobs_exp_det>pidl_funcs.avoid_nans((min_exp_frac*exp_out["max_det_exp"]),so2o_indices)).astype(int)
	#print("igood_obs_exp",i_good_obs_exp)
	#print("igood_obs_exp",len(igood_obs_exp),len(sp2so_indices))
	#print("sp2so_indices",pidl_funcs.avoid_nans(igood_obs_exp,sp2so_indices))
	igood_exp = (energy==0).astype(int)+((energy!=0).astype(int))*pidl_funcs.avoid_nans(igood_obs_exp,sp2so_indices)
	#print("igood_exp",len(np.where(igood_exp>0)[0]))
	#igood_obs_exp[sp2so_indices]

	#check to see if any of the exposures produced NaNs
	#what is going on here:
	#inans = np.where(source_obs_exp_sky[:,0]!=source_obs_exp_sky[:,0])[0]
	#TA: inans is uncertain where we are trying to find a nan
	inans = np.where(np.isnan(exp_out["source_obs_exp_sky"][:,0]))[0]
	#print("inans",exp_out["source_obs_exp_sky"][inans,0])
	if len(inans)>0:
		badobsids=srcobs_obsids[inans]
		badobsid_uniq = np.unique(badobsids)
		n_badobs = len(badobsid_uniq)

		for kk in np.arange(n_badobs):
			#Zero out the exposure for the bad obsids
			ibadexp=np.where(srcph_obsids==badobsid_uniq[kk])[0]
			igood_exp[ibadexp]=0

			#Zero out the counts for the bad obsids
			i_srcph_srcaper[ibadexp]=0
			i_srcph_bgaper[ibadexp]=0

			ibadobs=np.where(srcobs_obsids==badobsid_uniq[kk])[0]
			igood_obs_exp[ibadobs]=0

	igood_obs_mdist = (exp_out["source_obs_mdist"].flatten()<mdistmax).astype(int)
	
	igood_mdist = (energy==0).astype(int)+((energy!=0).astype(int))*pidl_funcs.avoid_nans(igood_obs_mdist,sp2so_indices)
	temp=pidl_funcs.avoid_nans(igood_obs_mdist,sp2so_indices)[10271:10408]
	

	igood_obs_all   = igood_obs_exp.flatten()*igood_obs_mdist
	
	igood_all = igood_exp*igood_mdist #igood_mdist 
	

	bad_var = srcobs_exp_det_var.flatten()[(srcobs_exp_det.flatten()<pidl_funcs.avoid_nans(min_exp_frac*exp_out["max_det_exp"],so2o_indices))]
	#bad_var = srcobs_exp_det_var[(srcobs_exp_det<(min_exp_frac * max_det_exp)[so2o_indices])]
	mean_bad_var = np.mean((bad_var<1.).astype(int)*bad_var)

	#Moved from STAGE 2 to STAGE 5 -- ADG 03/31/17
	src_nph = nphv
	src_nph_src = np.zeros(len(src_nph))
	src_nph_bg  = np.zeros(len(src_nph))

	for iv in np.arange(len(id0)):
		if src_nph[iv]>0:
			id0iv=id0[iv] + np.arange(src_nph[iv])
			src_nph_src[iv] = np.sum(i_srcph_srcaper[id0iv])
			src_nph_bg[iv] = np.sum(i_srcph_bgaper[id0iv])

	
	srcph_nph = pidl_funcs.avoid_nans(src_nph,sp2s_indices) #src_nph[sp2s_indices]
	srcph_nph_src = pidl_funcs.avoid_nans(src_nph_src,sp2s_indices)#src_nph_src[sp2s_indices]
	srcph_nph_bg = pidl_funcs.avoid_nans(src_nph_bg,sp2s_indices)#src_nph_bh[sp2s_indices]

	#Compute filter arrays:
	#Energy band filters
	i_srcph_softe = np.logical_and(energy>softe_new[0],energy<=softe_new[1]) # selects soft-band photons
	i_srcph_harde = np.logical_and(energy>harde_new[0],energy<=harde_new[1]) # selects hard-band photons

	#Valid data filters, srcph-length
	i_srcph_matched_srcobs = pidl_funcs.avoid_nans(~np.isnan(so2s_starts),sp2s_indices)#(so2s_starts!=np.nan)[sp2s_indices]	# selects valid obsid
	i_srcph_valid_mdist	= np.logical_and(mdist<mdistmax,mdist>0.) # selects valid mdist
	i_srcph_good_obsid	 = ~bad.astype(bool)							# selects good obsids

	i_srcph_valid_lim	  = (srcph_nph_src>=lim[0])

	#Valid data filters, source-length
	i_src_matched_srcobs  = (~np.isnan(so2s_starts))  # selects sources with source-obs matches
	i_src_good_obsid	  = i_srcph_good_obsid[id0]  # selects sources from non-bad obsids

	i_src_valid_lim	   = (src_nph_src>=lim[0])

	#Part 5: Exclude sources on the exclude list
	if exclude_list!="NA":

		'''exclude the photons around certain user input sources from the stack
		updated to fix excision of .sav RCH 7 Aug 2013'''
		fits_file=stack_file.split('.')[0]+".fits"
		print("fits file",fits_file)

		inexclude=exclude_sources(exclude_list, fits_file,x,y,i_srcph_non_excluded)
								  #stack_out["old_x"].data, stack_out["old_y"].data,
								  #i_srcph_non_excluded)


		source_obs_exp=update_exposure(exclude_list,fits_file,source_ra[id0],source_dec[id0],
									   exp_out["source_obs_ind"].flatten(),
									   exp_out["source_obs_srcrad"].flatten(),
									   np.zeros(len(exp_out["source_obs_srcrad"].flatten())))

		if use_bgh:
			srcobs_bgh=update_exposure(exclude_list, fits_file, source_ra[id0], source_dec[id0],
									   exp_out["source_obs_ind"].flatten(),
									   exp_out["source_obs_srcrad"].flatten(),
									   np.zeros(len(exp_out["source_obs_srcrad"].flatten())))

		if use_bgs:
			srcobs_bgs=update_exposure(exclude_list, fits_file, source_ra[id0], source_dec[id0],
									   exp_out["source_obs_ind"].flatten(),
									   exp_out["source_obs_srcrad"].flatten(),
									   np.zeros(len(exp_out["source_obs_srcrad"].flatten())))
			

	'''
	Part 6: For-Loop Iterating Over Sources
	Information that is stored for multiple source-obs pairs is
	concatenated into a single value for each source
	added to optimize searching for each individual source in source_obs_ind
	'''
	hist_obs_ind_max = np.max(exp_out["source_obs_ind"].flatten())
	hist_source_obs_ind,rev_src_ind,ed=pidl_funcs.hist_nd(exp_out["source_obs_ind"].flatten(),-0.5,hist_obs_ind_max+0.5, 1)

	
	len_id0=len(id0)#len(exp_out["source_obs_ind"].flatten())#
	#k=0
	#while rev_src_ind[k]<=rev_src_ind[k+1]:
	for k in np.arange(len_id0):
		if (rev_src_ind[k]!=rev_src_ind[k+1]) and (rev_src_ind[k]!=len(rev_src_ind)):
			ind = rev_src_ind[rev_src_ind[k]:rev_src_ind[k+1]]
			src_exp_sky[k] = np.sum(srcobs_exp_sky[ind].flatten()*igood_obs_all[ind])
			
			src_exp_det[k] = np.sum(srcobs_exp_det[ind].flatten()*igood_obs_all[ind])


			if use_bgs:
				src_bg_ctss[k]=np.sum(srcobs_bgs[ind])

			if use_bgh:
				src_bg_cths[k]=np.sum(srcobs_bgh[ind])

			if np.any((igood_obs_all[ind]).astype(bool)):
				indg=ind[(igood_obs_all[ind]).astype(bool)]

				'''
				get the minimum value for mdistv/r90v/srcradv in the case
				of multiple observations'''
				mdistv[k] = np.median(exp_out["source_obs_mdist"].flatten()[indg])
				r90v[k]   = np.median(exp_out["source_obs_r90"].flatten()[indg])
				srcradv[k] = r90v[k]/0.492 

				indg_min = indg[(indg==np.min(indg))]
				obsidv[k] = srcobs_obsids[indg_min[0]]
				#get the total area if detected in multiple exposures
				srcareav[k] = np.sum(np.pi*(exp_out["source_obs_srcrad"].flatten()[indg]*\
									 r90_frac*igood_obs_all[indg]*0.492)**2.)
				src_area_exp_sky[k] = np.sum(srcobs_exp_sky[indg]*igood_obs_all[indg]*\
											 np.pi*(exp_out["source_obs_srcrad"].flatten()[indg]*r90_frac*\
											 0.492)**2.)
				src_area_exp_det[k] = np.sum(srcobs_exp_det[indg]*igood_obs_all[indg]*\
											 np.pi*(exp_out["source_obs_srcrad"].flatten()[indg]*r90_frac*\
											 0.492)**2.)

	
	i_src_valid_mdist = np.logical_and(mdistv<mdistmax,mdistv>0)
	iuse = i_srcph_matched_srcobs*i_srcph_valid_mdist*i_srcph_good_obsid*i_srcph_valid_lim*\
		   i_srcph_non_excluded*igood_all
	
	i_src_valid = i_src_valid_mdist*i_src_good_obsid*i_src_valid_lim*i_src_matched_srcobs

	#RELOAD FILE FOR do_stack - need to save these variables
	#save all variables as a pickle

	save_names=parameter_outfile.split("/")[-1]
	save_names=save_names.split(".")
	with open(subs_namey+save_names[0]+"_subset."+save_names[1], 'wb') as f:  # Python 3: open(..., 'wb')
		pickle.dump([i_srcph_softe, i_srcph_harde, i_srcph_srcaper, i_srcph_bgaper,\
					 i_src_valid_lim, i_src_valid_mdist, i_src_good_obsid,\
					 i_src_matched_srcobs, iuse, i_src_valid, i_flux_from_soft, i_flux_from_hard,\
					 src_nph_src, src_nph,\
					 use_bgs, use_bgh, src_bg_ctss, src_bg_cths, src_area_exp_det,\
					 src_area_exp_sky, src_exp_sky, src_exp_det, srcradv, mdistv,\
					 obsidv, source_id, id0, idv, x,y, id_step], f)#src_bg_ctss_flux,src_bg_cths_flux,\
	
	return

#do stack
def sf_newstack_id_subset(idlist,ind_cts=True):

	global boxsize 
	boxsize=float(outp_boxsize.value)

	#reload file all the variables from the parameter part as a pickle
	save_names=parameter_outfile.split("/")[-1]
	save_names=save_names.split(".")
	with open(subs_namey+save_names[0]+"_subset."+save_names[1], 'rb') as f:
		i_srcph_softe, i_srcph_harde, i_srcph_srcaper, i_srcph_bgaper,\
		i_src_valid_lim, i_src_valid_mdist, i_src_good_obsid,\
		i_src_matched_srcobs, iuse, i_src_valid, i_flux_from_soft, i_flux_from_hard,\
		src_nph_src, src_nph,\
		use_bgs, use_bgh, src_bg_ctss, src_bg_cths, src_area_exp_det,\
		src_area_exp_sky, src_exp_sky, src_exp_det, srcradv, mdistv,\
		obsidv, source_id, id0, idv, x,y, id_step = pickle.load(f)
		#obsidv, srcs_bg, srch_bg, srcs_bg_obs, srch_bg_obs, sid, id0,\#src_bg_ctss_flux,src_bg_cths_flux,\


	save_names=background_save_file.split("/")[-1]
	save_names=save_names.split(".")
	with open(subs_namey+save_names[0]+"_subset."+save_names[1], 'rb') as f:
		i_srcph_bgaper,srcph_bgfrac,bg_in_srcaper_soft,bg_in_srcaper_hard,bg_in_srcaper_soft_flux,bg_in_srcaper_hard_flux=pickle.load(f)

	'''
	This part is done in sf_perform_background, and the information is contained in
	i_srcph_bgaper,i_srcph_srcaper
	For each photon:
	Identify its energy bin
	Identify whether it is within r90
	AND
	Identify if it is on the outskirts of the region (> 1.2 r90 and within the stacked box)
	'''

	'''
	This part is done by sf_new_parameters:
	For each source/obsid combination:
	If it is in a good obsid
	If the exposure time is longer than the minimum
	If the source is within the maximum off-axis angle that we set
	Whether it is "valid" by some definition
	'''

	'''
	For each source/obsid combination:
	Use the background and/or exposure maps to determine:
	Exposure time (done in srcobs_exp_det_var,srcobs_exp_sky_var)
	Average background level ('source_obs_bgh','source_obs_bgs')
	'''

	'''
	#what we need to do here:
	For each source:
	We add and/or average all this together
	Total source counts in each energy band
	Average exposure time
	The average background rate in each energy band
	
	For each photon:
	Apply booleans on the levels of all the photons so we can chop and change the individual photons
	'''
	#what is the final output from this code supposed to be?
	#what does each final output variable mean? I am not sure what I am building towards.


	#okay let's go over all the lines here
	#print("lengths",len(bg_in_srcaper_soft),len(bg_in_srcaper_hard))
	#Create the arrays to calculate where bright sources are.
	#totbg=reloaded_file["bg_in_srcaper_soft"].data+reloaded_file["bg_in_srcaper_hard"].data
	totbg=bg_in_srcaper_soft+bg_in_srcaper_hard
	totsrc=src_nph_src
	i_bright_src=(totsrc<170000) #WHY 170000
	#print("i_bright_src",i_bright_src, totsrc)

	i_ph_bright_src=np.zeros(len(source_id))
	#print("len(id0)",len(id0))
	for n in np.arange(len(id0)):
		#i_ph_bright_src[id0[n]:(id0[n+1]-1)]=i_bright_src[n]
		#print("id0[n]:id0[n+1]",id0[n],id0[n+1])
		if n+1<len(id0):
			i_ph_bright_src[int(id0[n]):int(id0[n+1])]=i_bright_src[n]
		else:
			i_ph_bright_src[int(id0[n]):]=i_bright_src[n]

	i_srcph_idlist=np.zeros(len(source_id))
	i_src_idlist = np.zeros(len(id0))

	'''Part 7: match inputted idlist to main source lists
	this matches the input id list with the full list'''

	#if outputting everything, include the indices of the input vectors
	if ind_cts:
		ind_ctsv  = np.zeros(len(idlist))
		ind_intv  = np.zeros(len(idlist))
		ind_inv   = np.zeros(len(id0))
		#ind_in	= np.zeros(len(source_id))
		ind_match = np.full(len(idlist),-1)#np.zeros(len(sid))#np.zeros(len(idlist))
		ind_ctss,ind_ctss_flux  = np.zeros(len(idlist)),np.zeros(len(idlist))
		ind_cths,ind_cths_flux  = np.zeros(len(idlist)),np.zeros(len(idlist))
		ind_srcs_flux,ind_srch_flux = np.zeros(len(idlist)),np.zeros(len(idlist))
		ind_ctsb  = np.zeros(len(idlist))
		ind_cthb  = np.zeros(len(idlist))

		ind_bgss  = np.zeros(len(idlist))#np.zeros(len(sid))#
		ind_bghs  = np.zeros(len(idlist))#np.zeros(len(sid))#np.zeros(len(idlist))

		ind_bgss_det = np.zeros(len(idlist))
		ind_bgss_sky = np.zeros(len(idlist))

		ind_bghs_det = np.zeros(len(idlist))
		ind_bghs_sky = np.zeros(len(idlist))

		ind_exp_sky = np.zeros(len(idlist))#np.zeros(len(sid))#np.zeros(len(idlist))
		ind_exp_det = np.zeros(len(idlist))#np.zeros(len(sid))#np.zeros(len(idlist))

		ind_ilim   = np.zeros(len(idlist)) + 1 #np.zeros(len(sid))+1#np.zeros(len(idlist)) + 1 # added +1 to allow for sources with no photons
		ind_imdist = np.zeros(len(idlist)) + 1 #np.zeros(len(sid))+1#np.zeros(len(idlist))+ 1
		ind_igood  = np.zeros(len(idlist)) + 1 #np.zeros(len(sid))+1#np.zeros(len(idlist)) + 1 
		ind_iobs   = np.zeros(len(idlist)) + 1 #np.zeros(len(sid))+1#np.zeros(len(idlist)) + 1
		ind_istack = np.zeros(len(idlist)) + 1 #np.zeros(len(sid))+1#np.zeros(len(idlist)) + 1
		ind_srcrad = np.zeros(len(idlist))#np.zeros(len(sid))#np.zeros(len(idlist))
		ind_mdist  = np.zeros(len(idlist))#np.zeros(len(sid))#np.zeros(len(idlist))
		ind_obsid  = np.zeros(len(idlist))#np.zeros(len(sid))#np.zeros(len(idlist))

	'''these are used to match more efficiently source ids (matching
	split into whole & fractional part)'''

	idv_whole = np.floor(source_id[id0])
	id_whole = np.floor(source_id)#np.floor(idlist)
	list_whole = np.floor(idlist)
	id_frac = source_id - id_whole
	idv_frac = source_id[id0] - idv_whole
	list_frac = idlist - list_whole
	idv_whole_vals = np.unique(idv_whole)


	if len(idv)>1:
		id_step=np.diff(idv) # id_step not calculated correctly when 0 event source list encountered
		id_step=np.min(id_step[np.where(id_step>0.)[0]])
	else:
		#what difference does it make how we divide up the id bins if there is only 1 ID
		id_step=1.
	

	for k in np.arange(len(idv_whole_vals)):

		indv_whole=np.where(idv_whole==idv_whole_vals[k])[0]
		#this is just a very convoluted way to get np.array(len(inlist)):
		ind_whole=np.where(id_whole==idv_whole_vals[k])[0]
		ind_list_whole=np.where(list_whole==idv_whole_vals[k])[0]

		idv_curr_frac  = idv_frac[indv_whole]
		id_curr_frac   = id_frac[ind_whole]
		list_curr_frac = list_frac[ind_list_whole]

		hist_bin = id_step
		histmin  = np.min(list_curr_frac) - (hist_bin/2.)
		histmax  = np.max(list_curr_frac) + (hist_bin/2.)
		

		'''For the actual matching create histograms with equal sizes for
		both lists'''
		#print("histmin,max",histmin,histmax,hist_bin,len(ind_whole),np.max(ind_whole),len(idlist))
		hist_id,rev_id,ed = pidl_funcs.hist_nd(id_curr_frac, histmin, histmax, hist_bin)
		hist_idv,rev_idv,ed = pidl_funcs.hist_nd(idv_curr_frac, histmin, histmax, hist_bin)
		hist_idlist,rev_idlist,ed = pidl_funcs.hist_nd(list_curr_frac, histmin, histmax, hist_bin)

		#get the indices of the bins in the histogram where we have a match
		index_r = np.where(np.logical_and((hist_id!=0), (hist_idlist!=0)))[0]
		index_rv = np.where(np.logical_and((hist_idv!=0), (hist_idlist!=0)))[0]

		'''convert from indices of the bins to indices of the lists
		(see help for histogram with /reverse_indices)'''
		bin_start = rev_id[index_r]
		bin_end = rev_id[index_r + 1]
		bin_size = bin_end-bin_start

		match_indices=np.zeros(np.sum(bin_size))
		bin_start_idlist = rev_idlist[index_r]
		index_match = 0

		for ind in np.arange(len(bin_start)):
			if bin_size[ind]<=0:
				continue

			match_indices[index_match:index_match+bin_size[ind]] = bin_start[ind] + np.arange(bin_size[ind])
			index_match += bin_size[ind]

		#stores the indices in id where there is a match
		#print("match indices",match_indices)
		matches = rev_id[(match_indices).astype(int)]

		#do the same for distinct sources
		bin_startv	 = rev_idv[index_rv]
		bin_endv	   = rev_idv[index_rv+1]
		bin_sizev	  = bin_endv - bin_startv
		match_indicesv = np.zeros(np.sum(bin_sizev))
		index_matchv   = 0

		bin_startlist = rev_idlist[index_rv]
		bin_endlist   = rev_idlist[index_rv+1]

		for indv in np.arange(len(bin_startv)):
			if bin_sizev[indv]==0:
				continue

			if bin_sizev[indv]>1:
				print('Duplicate ID match found, stopping')

			match_indicesv[index_matchv] = bin_startv[indv]

			if ind_cts:
				ind_inv[indv_whole[rev_idv[ (match_indicesv[ index_matchv]).astype(int)]]]=\
							ind_list_whole[rev_idlist[bin_startlist[indv]]]

				ind_match[ind_list_whole[rev_idlist[ bin_startlist[indv]]]]=\
							indv_whole[rev_idv[(match_indicesv[index_matchv]).astype(int)]]

			index_matchv+=bin_sizev[indv]

		#stores the indices in idv where there is a match
		matchesv = rev_idv[(match_indicesv).astype(int)]
		
		#print("ind_match",ind_match)

		if len(matches)<len(ind_list_whole):
			print("No ID match found for ", len(ind_list_whole)-len(matches),"elements")

		i_srcph_idlist[ind_whole[(matches).astype(int)]] = 1
		i_src_idlist[indv_whole[(matchesv).astype(int)]] = 1

	'''this variable encompasses all the binary arrays that go into the
	stacking output in calculating ctss and ctsb, etc.
	i_srcph_within_mdist = mdist le 6.'''
	iuse = iuse*i_srcph_idlist*i_ph_bright_src #* i_srcph_within_mdist
	i_src_valid = i_src_valid*i_src_idlist*i_bright_src
	

	#Part 8: Perparing Final Output
	maxph = np.max(src_nph_src*i_src_valid)
	

	if maxph>0:

		#ctss stands for counts in the soft energy band in the source aperture
		ctss = np.sum(i_srcph_softe * i_srcph_srcaper * iuse)
		#counts in the soft energy band in the background aperture
		ctsb = np.sum(i_srcph_softe * i_srcph_bgaper * iuse)
		#counts in hard energy band in the source aperture
		cths = np.sum( i_srcph_harde * i_srcph_srcaper * iuse)
		#counts in the hard energy band in the background aperture
		cthb = np.sum(i_srcph_harde * i_srcph_bgaper * iuse)

		#nsrc=0
		nsrc=np.sum(i_src_valid)
		use_bgs=True
		frac_soft=0.5
		frac_hard=1.-frac_soft


		#print("use_bgs, use_bgh",use_bgs,use_bgh)
		#calculate background counts
		if use_bgh and use_bgs:
			srcs_bg=np.sum(src_bg_ctss * i_src_valid)
			srch_bg=np.sum(src_bg_cths * i_src_valid)
		elif use_bgh:
			#if using a single exposure map, assign weights to soft and hard rates
			srcs_bg = frac_soft*np.sum(src_bg_cths * i_src_valid)
			srch_bg = frac_hard*np.sum(src_bg_cths * i_src_valid)
		elif use_bgs:
			srcs_bg=frac_soft*np.sum(src_bg_ctss * i_src_valid)
			srch_bh=frac_hard*np.sum(src_bg_ctss * i_src_valid)
		else:
			srcs_bg_det = (softbgrate_det/(3600.**2.)) * np.sum(src_area_exp_det * i_src_valid)
			srcs_bg_sky = (softbgrate_sky/(3600.**2.)) * np.sum(src_area_exp_sky * i_src_valid)
			srch_bg_det = (hardbgrate_det/(3600.**2.)) * np.sum(src_area_exp_det * i_src_valid)
			srch_bg_sky = (hardbgrate_sky/(3600.**2.)) * np.sum(src_area_exp_sky * i_src_valid)

			srcs_bg = srcs_bg_det + srcs_bg_sky
			srch_bg = srch_bg_det + srch_bg_sky

		#compute indices - moved here from earlier in stack_id - SG 08/07
		indices=np.arange(np.max(src_nph))

		#make arrays to say how many source and background photons you have
		#print("idlist",idlist)
		if ind_cts:
			imatch=np.where(ind_match!=-1)[0]
			imatchi=ind_match[imatch]

			for ivi in np.arange(len(idlist)):

				iv = ind_match[ivi]
				#print("ivi",ivi, iv, ind_match[ivi], idlist[ivi])

				if iv==-1:
					ind_ctss[ivi] = 0.
					ind_cths[ivi] = 0.
				else:
					iv=iv.astype(int)
					if src_nph[iv]>0:
						id0iv = id0[iv] + indices[0:src_nph[iv]]
						
						ind_ctss[ivi] = np.sum(i_srcph_srcaper[id0iv]*i_srcph_softe[id0iv]*iuse[id0iv])
						#print("ind ctss",i_srcph_srcaper[id0iv],i_srcph_softe[id0iv],iuse[id0iv])
						ind_cths[ivi] = np.sum(i_srcph_srcaper[id0iv]*i_srcph_harde[id0iv]*iuse[id0iv])
						##this is for flux
						ind_ctss_flux[ivi] = np.sum(i_flux_from_soft[id0iv]*i_srcph_srcaper[id0iv]*i_srcph_softe[id0iv]*iuse[id0iv])
						ind_cths_flux[ivi] = np.sum(i_flux_from_soft[id0iv]*i_srcph_srcaper[id0iv]*i_srcph_harde[id0iv]*iuse[id0iv])
						ind_ctsb[ivi] = np.sum(i_srcph_bgaper[id0iv]*i_srcph_softe[id0iv]*iuse[id0iv])
						ind_cthb[ivi] = np.sum(i_srcph_bgaper[id0iv]*i_srcph_harde[id0iv]*iuse[id0iv])
						

			#background from separate bg maps
			imatch=imatch.astype(int)
			imatchi=imatchi.astype(int)
			
			if use_bgh and use_bgs:
				ind_bgss[imatch] = src_bg_ctss[imatchi]
				ind_bghs[imatch] = src_bg_cths[imatchi]
			elif use_bgh:
				#background from a single map with weights
				ind_bgss[imatch] = frac_soft * src_bg_cths[imatchi]
				ind_bghs[imatch] = frac_hard * src_bg_cths[imatchi]
			elif use_bgs:
				ind_bgss[imatch] = frac_soft * src_bg_ctss[imatchi]
				ind_bghs[imatch] = frac_hard * src_bg_ctss[imatchi]
			else:
				'''AVERAGE background calculated from exposure
				calculate the detector and sky background separately, for calibration'''
				ind_bgss_sky[imatch] = (softbgrate_sky * src_area_exp_sky[imatchi]) / (3600.**2.)
				ind_bgss_det[imatch] = (softbgrate_det * src_area_exp_det[imatchi]) / (3600.**2.)
				ind_bghs_sky[imatch] = (hardbgrate_sky * src_area_exp_sky[imatchi]) / (3600.**2.)
				ind_bghs_det[imatch] = (hardbgrate_det * src_area_exp_det[imatchi]) / (3600.**2.)

				ind_bgss[imatch] = ind_bgss_sky[imatch] + ind_bgss_det[imatch]
				ind_bghs[imatch] = ind_bghs_sky[imatch] + ind_bghs_det[imatch]

			ind_exp_sky[imatch] = src_exp_sky[imatchi]
			ind_exp_det[imatch] = src_exp_det[imatchi]

			#now tell whether the inputs are within all the criteria
			ind_ilim[imatch]   = i_src_valid_lim[imatchi]
			ind_imdist[imatch] = i_src_valid_mdist[imatchi]
			ind_igood[imatch]  = i_src_good_obsid[imatchi]
			ind_iobs[imatch]   = i_src_matched_srcobs[imatchi]
			ind_srcrad[imatch] = srcradv[imatchi]
			ind_mdist[imatch]  = mdistv[imatchi]
			ind_obsid[imatch]  = obsidv[imatchi]
			#print("imatch",len(imatch),max(imatch))
			ind_istack[imatch] = i_src_valid_mdist[imatchi] * i_src_valid_lim[imatchi] * \
								 i_src_good_obsid[imatchi] * i_src_idlist[imatchi] * \
								 i_src_matched_srcobs[imatchi]

			'''Fix the NaNs in the exposure arrays from sources not
			included in the stacks'''
			#print("ind_exp_sky",ind_exp_sky)
			inans=np.where(np.isnan(ind_exp_sky))[0]
			ind_exp_sky[inans]=0.
			inans=np.where(np.isnan(ind_exp_det))[0]
			ind_exp_det[inans]=0.

			exp_sky_tot = np.sum( ind_exp_sky * ind_istack)
			exp_det_tot = np.sum( ind_exp_det * ind_istack)

		else:
			exp_sky_tot=0
			exp_det_tot=0

	if ind_cts:

		'''NaNs from sources not in field of view are a problem. So
		just set them to zero'''
		inans=np.where(np.isnan(bg_in_srcaper_soft))[0]
		bg_in_srcaper_soft[inans]=0.
		bg_in_srcaper_hard[inans]=0.

		#Now calculate the total backgrounds for all of the valid sources
		ifoo=np.where((i_src_valid).astype(bool))[0]
		srcs_bg_obs = np.sum(bg_in_srcaper_soft[ifoo])#*0.9
		srch_bg_obs = np.sum(bg_in_srcaper_hard[ifoo])#*0.95
		#and rewrite the old variables
		srcs_bg=srcs_bg_obs
		srch_bg=srch_bg_obs

		
	else:
		srcs_bg, srch_bg, srcs_bg_obs, srch_bg_obs = 0.,0.,0.,0.

	#substract background (regardless of how it was computed)
	srcs	 = ctss - srcs_bg #this is net_cts = src_cts - bg_cts * (src_area) / (bg_area)
	#print("ctss, srcs_bg",ctss, srcs_bg)
	srch	 = cths - srch_bg
	
	if srcs<=0:
		hr=(srch-srcs_bg_obs)/(srch+srcs)
	elif srch<=0:
		hr=(srch_bg_obs-srcs_bg_obs)/(srch_bg_obs+srcs)
	else:
		hr=(srch-srcs_bg_obs)/(srch+srcs)

	if nsrc==0:
		rates	   = 0.
		rateh	   = 0.
		fluxs	   = 0.
		fluxh	   = 0.
		exp_sky_avg = 0
		exp_det_avg = 0
	else:
		rates	   = srcs / nsrc#srcs_obs / nsrc
		rateh	   = srch / nsrc #srch_obs / nsrc
		#this is flux = net_cts * src_conversion / total_sky_exp
		fluxs	   = np.sum(srcs) / np.sum(exp_sky_tot) #np.sum(srcs_obs) / np.sum(exp_sky_tot)
		fluxh	   = np.sum(srch) / np.sum(exp_sky_tot) #np.sum(srch_obs) / np.sum(exp_sky_tot)
		exp_sky_avg = exp_sky_tot / nsrc
		exp_det_avg = exp_det_tot / nsrc


	#Poisson errors in the rate (Gehrels, 1986)
	errrates = (np.sqrt( ctss + 0.75) + 1.) / nsrc
	errrateh = (np.sqrt( cths + 0.75) + 1.) / nsrc
	print("fluxs,fluxh",fluxs,fluxh)

	#Poisson errors in the flux
	errfluxs = errrates/rates * fluxs
	errfluxh = errrateh/rateh * fluxh

	#find ctss for each individual source:
	indsy=np.where(i_src_valid)[0]
	ind_rates,ind_rateh,ind_ctspss,ind_ctspsh=np.full(len(ind_bghs),-99.),np.full(len(ind_bghs),-99.),np.full(len(ind_bghs),-99.),np.full(len(ind_bghs),-99.)
	ind_soft_flux,ind_hard_flux=np.full(len(ind_bghs),-99.),np.full(len(ind_bghs),-99.)
	ind_errrates,ind_errrateh,ind_errctspss,ind_errctspsh=np.full(len(ind_bghs),-99.),np.full(len(ind_bghs),-99.),np.full(len(ind_bghs),-99.),np.full(len(ind_bghs),-99.)
	
	#the ind_rates and ind_ctss are as long as the source list, the bg_in_srcaper,i_src_valid is the same length as the number of soruces with matches
	ig1,need_ind,ig2=np.intersect1d(sources_id,idv,return_indices=True)
	#for iss in np.arange(len(idv)):
	#if i_src_valid[iss]:
	#ind_rates[need_ind[indsy]] = np.clip(ind_ctss[need_ind[indsy]] - bg_in_srcaper_soft[indsy],None,None)
	#ind_rateh[need_ind[indsy]] = np.clip(ind_cths[need_ind[indsy]] - bg_in_srcaper_hard[indsy],None,None)
	ind_rates[need_ind[indsy]] = ind_ctss[need_ind[indsy]] - bg_in_srcaper_soft[indsy]
	ind_rateh[need_ind[indsy]] = ind_cths[need_ind[indsy]] - bg_in_srcaper_hard[indsy]
	ind_errrates[need_ind[indsy]] = (np.sqrt(abs(ind_ctss[need_ind[indsy]]) + 0.75) + 1.) 
	ind_errrateh[need_ind[indsy]] = (np.sqrt(abs(ind_cths[need_ind[indsy]]) + 0.75) + 1.) 
	ind_ctspss[need_ind[indsy]] = ind_rates[need_ind[indsy]]/ind_exp_sky[need_ind[indsy]]
	ind_ctspsh[need_ind[indsy]] = ind_rateh[need_ind[indsy]]/ind_exp_sky[need_ind[indsy]]
	ind_errctspss[need_ind[indsy]] = ind_errrates[need_ind[indsy]]/abs(ind_rates[need_ind[indsy]]) * ind_ctspss[need_ind[indsy]]
	ind_errctspsh[need_ind[indsy]] = ind_errrateh[need_ind[indsy]]/abs(ind_rateh[need_ind[indsy]]) * ind_ctspsh[need_ind[indsy]]

	ind_soft_flux[need_ind[indsy]] = (ind_ctss_flux[need_ind[indsy]] - bg_in_srcaper_soft_flux[indsy])/ind_exp_sky[need_ind[indsy]]
	ind_hard_flux[need_ind[indsy]] = (ind_cths_flux[need_ind[indsy]] - bg_in_srcaper_hard_flux[indsy])/ind_exp_sky[need_ind[indsy]]
	
	
	#Part 9: Final Output
	#writing output
	'''This is the part of the code in which the output data which has
		already been computed is actually placed into rout, and printed'''

	ni = 1
	varso = ['net_ctss', 'net_cths', 'ctsb', 'cthb', 'srcs', 'srch', 'hr', 'nsrc', 'rates',\
			 'rateh', 'errrates', 'errrateh', 'count_per_ss', 'count_per_sh', 'errcntpss', 'errcntpsh']
	varso=['out_'+i for i in varso]
	
	
	
	all_src_len=1
	data = Table([np.full(all_src_len,ctss), np.full(all_src_len,cths), np.full(all_src_len,ctsb),\
				 np.full(all_src_len,cthb), np.full(all_src_len,srcs), np.full(all_src_len,srch),
				 np.full(all_src_len,hr), np.full(all_src_len,nsrc), np.full(all_src_len,rates),\
			  	 np.full(all_src_len,rateh), np.full(all_src_len,errrates),\
			  	 np.full(all_src_len,errrateh), np.full(all_src_len,fluxs),\
			  	 np.full(all_src_len,fluxh), np.full(all_src_len,errfluxs),\
			  	 np.full(all_src_len,errfluxh)],
			  	 names=varso)
	
	if ind_cts:
		#put everything inside the data structure
		ind_vars =  ["ID",'cts_w_bg_s', 'cts_w_bg_h', 'ctsb', 'cthb', "net_count_s",  "net_count_h", "err_netc_s", "err_netc_h", 
					 'cnt_ps_s', 'cnt_ps_h', 'err_cnt_ps_s', 'err_cnt_ps_h', 
					 "soft_flux","hard_flux",
					 'bgss', 'bghs','srcs_flux','srch_flux',
					 'bgss_sky', 'bgss_det', 'bghs_sky', 'bghs_det',
					 'srcrad', 'mdist', 'obsid', 'istack', 'igood',
					 'ilim', 'imdist', 'exp_det', 'exp_sky', 'match']
		ind_vars=['ind_'+i for i in ind_vars]
		
		data2 = Table([sources_id,ind_ctss, ind_cths, ind_ctsb, ind_cthb, ind_rates,ind_rateh,
					   ind_errrates,ind_errrateh,ind_ctspss,ind_ctspsh,
					   ind_errctspss,ind_errctspsh,ind_soft_flux,ind_hard_flux,
					   ind_bgss, ind_bghs,ind_srcs_flux,ind_srch_flux,
					   ind_bgss_sky, ind_bgss_det, ind_bghs_sky, ind_bghs_det,
					   ind_srcrad, ind_mdist, ind_obsid, ind_istack, ind_igood,
					   ind_ilim, ind_imdist, ind_exp_det, ind_exp_sky, ind_match], 
					   names=ind_vars)
		#data=hstack([data, data2])


	#print out the results:
	if "sublist" in locals():
		if len(sublist)!=0:
			#Find the photons associated with the objects in sublist
			i_imgstack = iuse*0.
			for tt in np.arange(len(sublist)):
				igd=np.where(id==sublist[tt])[0]
				if len(igd)>0:
					i_imgstack[igd]=1
	else:
		i_imgstack=iuse*0+1

	#Now output the stacked images:
	if len(stacked_outimage)!=0:

		save_names=stacked_outimage.split("/")[-1]
		file_0=save_names.split(".")[0]


		iplot=np.where(iuse*i_srcph_softe*i_imgstack)[0]
		res,rev_indo,ed=pidl_funcs.hist_nd(np.array([x[iplot],y[iplot]]),[(-1.)*boxsize/2.,(-1.)*boxsize/2.],
							 [boxsize/2.,boxsize/2.],[1,1])
		szres=res.shape
		xcnt=int((szres[0]+1.)/2.)
		ycnt=int((szres[1]+1.)/2.)
		subres=res[xcnt-15:xcnt+15,ycnt-15:ycnt+15]

		#write fits file
		hdu_new=fits.PrimaryHDU(subres)
		hdu_new.writeto(subs_namey+file_0+'_05_2.fits',overwrite=True)


		#Write fits file
		iplot=np.where(iuse*i_srcph_harde*i_imgstack)[0]
		res,rev_indo,ed=pidl_funcs.hist_nd(np.array([x[iplot],y[iplot]]),[(-1.)*boxsize/2.,(-1.)*boxsize/2.],
							 [boxsize/2.,boxsize/2.],[1,1])
		szres=res.shape
		xcnt=int((szres[0]+1.)/2.)
		ycnt=int((szres[1]+1.)/2.)
		subres=res[xcnt-15:xcnt+15,ycnt-15:ycnt+15]
		hdu_new=fits.PrimaryHDU(subres)
		hdu_new.writeto(subs_namey+file_0+'_2_7.fits',overwrite=True)

	return data,data2

def sf_perform_background_multiprocess_matrix_subset(n):
	#phtons in a source per obsid
	if n<(nsrcs-1):#id0[n]<id0[-1]:#n<(nsrcs-1):
		obsid_src=ph_obsid[id0[n]:(id0[n+1])]
		phots_src=np.full(len(obsid_src),1)#[id0[n]:(id0[n+1])]=1
		theta_rel=theta[id0[n]:(id0[n+1])]
		dist_rel=dist[id0[n]:(id0[n+1])]
		i_flux_from_soft_rel=i_flux_from_soft[id0[n]:(id0[n+1])]
		i_flux_from_hard_rel=i_flux_from_hard[id0[n]:(id0[n+1])]
		ph_obsid_rel=ph_obsid[id0[n]:(id0[n+1])]
		mdist_rel=mdist[id0[n]:(id0[n+1])]
		srcrad_rel=srcrad[id0[n]:(id0[n+1])]
		loenergy_rel=loenergy[id0[n]:(id0[n+1])]
		hienergy_rel=hienergy[id0[n]:(id0[n+1])]
		energy_rel=energy[id0[n]:(id0[n+1])]

	else:
		#phots_src[id0[n]:]=1
		obsid_src=ph_obsid[id0[n]:]
		phots_src=np.full(len(obsid_src),1)
		theta_rel=theta[id0[n]:]
		dist_rel=dist[id0[n]:]
		i_flux_from_soft_rel=i_flux_from_soft[id0[n]:]
		i_flux_from_hard_rel=i_flux_from_hard[id0[n]:]
		ph_obsid_rel=ph_obsid[id0[n]:]
		mdist_rel=mdist[id0[n]:]
		srcrad_rel=srcrad[id0[n]:]
		loenergy_rel=loenergy[id0[n]:]
		hienergy_rel=hienergy[id0[n]:]
		energy_rel=energy[id0[n]:]

	bkg_frac,bg_in_srcaper_soft,bg_in_srcaper_hard=1.,0,0
	bg_in_srcaper_soft_flux,bg_in_srcaper_hard_flux=0,0
	t11=time.time()

	obsid_src_uniq=np.unique(obsid_src)
	
	for m in np.arange(len(obsid_src_uniq)):
		#find all the phorons within this obsid:
		foo_obsid=(ph_obsid_rel==obsid_src_uniq[m])
		phots_src_obsid=phots_src*(foo_obsid).astype(int)

		obsid_mdist=mdist_rel[np.where((phots_src_obsid).astype(bool))[0]]
		obsid_mdist=obsid_mdist[0]

		if obsid_mdist<mdistmaxi:
			obsid_src_rad=srcrad_rel[np.where(phots_src_obsid)[0]]
			obsid_src_rad=obsid_src_rad[0] #all r90s are the same for a source in a single obsid
			#print("i_bg_phots_src_obsid", obsid_src_rad)#, dist)

			i_bg_phots_src_obsid=np.logical_and(dist_rel>(obsid_src_rad*1.3),dist_rel <=boxsize/2.)

			bgphots_src_obsid=phots_src_obsid*i_bg_phots_src_obsid #background photons for this obsid

			theta_to_bin_map=np.digitize(theta_rel,np.arange(0,361,30))-1
			#Rows for bins and columns for photons
			theta_to_bin_map=np.tile(theta_to_bin_map,12).reshape(12,len(theta_to_bin_map)).T==np.arange(12)
			separate_bins=np.full(len(theta_rel),1)*theta_to_bin_map.T
			#only picks out the background phots using bgphots_src_obsid
			ireg=np.sum(((bgphots_src_obsid).astype(bool)*separate_bins).astype(int),axis=1)
			#greater than 2 std and also has more than two photons
			ibad_bg=np.logical_and(ireg>(np.median(ireg)+(2.*np.std(ireg))),ireg>2)
			ibad_bg=np.where(ibad_bg)[0] #everything okay up to here


			if len(ibad_bg)>0:

				#thet_condition=np.sum(theta_to_bin_map[:,ibad_bg],axis=0).astype(bool)
				thet_condition=np.sum(theta_to_bin_map[:,ibad_bg],axis=1).astype(bool)
				i_bg_phots_src_obsid[np.where(thet_condition)]=0

				#bkg_frac[n]=(12.-len(ibad_bg))/12.
				bkg_frac=(12.-len(ibad_bg))/12.
				
			theta_to_bin_map=0
			src_area=np.pi*obsid_src_rad**2
			bkg_area=np.pi*((boxsize/2.)**2-(obsid_src_rad*1.3)**2)
			#print("bkg area",bkg_area, bkg_frac[n], bkg_area/bkg_frac[n])
			
			bg_in_srcaper_soft+=np.sum(bgphots_src_obsid*loenergy_rel*i_bg_phots_src_obsid)*src_area/(bkg_area/bkg_frac)
			bg_in_srcaper_hard+=np.sum(bgphots_src_obsid*hienergy_rel*i_bg_phots_src_obsid)*src_area/(bkg_area/bkg_frac)
			bg_in_srcaper_soft_flux+=np.sum(bgphots_src_obsid*loenergy_rel*i_bg_phots_src_obsid*i_flux_from_soft_rel)*src_area/(bkg_area/bkg_frac)
			bg_in_srcaper_hard_flux+=np.sum(bgphots_src_obsid*hienergy_rel*i_bg_phots_src_obsid*i_flux_from_hard_rel)*src_area/(bkg_area/bkg_frac)	
		else:
			i_bg_phots_src_obsid=np.full(len(dist_rel),False)

	
	return i_bg_phots_src_obsid,bkg_frac,bg_in_srcaper_soft,bg_in_srcaper_hard,bg_in_srcaper_soft_flux,bg_in_srcaper_hard_flux, n