def post_processing_func(dbname, tablename, dbschema, emitn, energy0, iamp, eamp, main_folder,wr_fr,ip,seed):
	'''runs the post-processing analysis'''

	#os.chdir(main_folder)

	twiss = read_twiss(main_folder,seed,ip)

	beta_star = twiss['betx']
	beta_stary = twiss['bety']
	alpha_x = twiss['alfx']
	alpha_y = twiss['alfy']
	
	sigmax,sigmay, sigmapx,sigmapy, gamma_rel, beta_rel = calc_beam_params(emitn, energy0, twiss['betx'],twiss['bety'],twiss['alfx'],twiss['alfy'])

	closorb = [twiss['x'], twiss['xp'],twiss['y'],twiss['yp']]


	iturn = 0		#raw_input('Insert the starting point turn number:\t')
	eturn = 100000 	#raw_input('Insert the end point turn number:\t')
	
	ic = read_6D_coordinates_for_specific_turn(dbname, tablename, 0)
	npart = len(ic['x'])

	print 'Particles tracked = ', npart

	os.system('mkdir %s/plots' %main_folder)
	plots_folder = '%s/plots' %main_folder

	lost = []
	tbt_current_loss = []
	turns = np.arange(int(iturn),int(eturn)+int(wr_fr),int(wr_fr))

	for i in turns:

		if i == 0:

			ic['x'] = ic['x'] - closorb[0] #np.mean(ic['x'])
			ic['xp'] = ic['xp']- closorb[1] #np.mean(ic['xp'])
			ic['y'] = ic['y'] - closorb[2] #np.mean(ic['y'])
			ic['yp'] = ic['yp']- closorb[3] #np.mean(ic['yp'])
				
			gd = gaussian(ic['x'],ic['y'],sigmax)

			u0 = invariant_coordinates_trasf(ic['x'],ic['xp'],ic['y'],ic['yp'],beta_star,beta_stary,alpha_x,alpha_y)
			Jx0 = action(u0, 'X', 'Px', beta_star)
			Jy0 = action(u0, 'Y', 'Py', beta_stary)

			c = copy.deepcopy(ic)

		else:

			c6d = read_6D_coordinates_for_specific_turn(dbname, tablename, i)
			c = copy.deepcopy(c6d)
			
			c['x'] = c['x'] - closorb[0] #np.mean(ic['x'])
			c['xp'] = c['xp'] - closorb[1] #np.mean(ic['xp'])
			c['y'] = c['y'] - closorb[2] #np.mean(ic['y'])
			c['yp'] = c['yp'] - closorb[3] #np.mean(ic['yp'])
		
		temp = npart - 1
 
		pindex = ic['partID'] - 1

		if (len(c['x']) < temp):

			plost = temp-len(c['x'])
			lost.append(plost)

			nindex = c['partID'] - 1
			ilost = list(set(pindex) - set(nindex))
			tbt_current_loss.append(sum(gd[ilost]))
			pindex = nindex
			temp = len(c['x']) - 1

		else:
			lost.append(0)
			tbt_current_loss.append(0)
		print '@turn ', i,': ', len(c['x']),' particles survived'

		
		print 'the survived particles are: ', c['partID']
		

		u = invariant_coordinates_trasf(c['x'],c['xp'],c['y'],c['yp'],beta_star,beta_stary,alpha_x,alpha_y)
		Jx = action(u, 'X', 'Px', beta_star)
		Jy = action(u, 'Y', 'Py', beta_stary)
		
		# normalise phase space units to be in sigma, sigma_p
		c['x'] = c['x']/sigmax
		c['y'] = c['y']/sigmay
		c['xp'] = c['xp']/sigmapx
		c['yp'] = c['yp']/sigmapy
		
		
		if i in [0,1000,10000,100000]:

			variables_list = [[c['x'],c['y']],[c['x'],c['xp']],[c['y'],c['yp']], [Jx, Jy]]
			#variables_list = [[u['X'],u['Y']],[u['X'],u['Px']],[u['Y'],u['Py']], [Jx, Jy]]
		
			label_list = [[r'$x [\sigma]$',r'$y [\sigma]$'],
			[r'$x [\sigma]$',r'$x^\prime [\sigma_{p}]$'],
			[r'$y [\sigma]$',r'$y^\prime [\sigma_{p}]$'],
			[r'$J_{x}$',r'$J_{y}$'],
			]
		
			titles_list = [' ',' ',' ',' '] 
		
			fig = beam_scatter_final_comparison(variables_list, label_list, titles_list, i, gd[c['partID']-1])
		
			fname ='t%s_%d.png' %(dbname,i)
			
			print 'Saving frame', fname
			fig.savefig('%s/%s' %(plots_folder,fname))

	print 'Particles survived after 10e5 turns = ', len(c['x'])
	lost = np.array(lost)




	#energyvar = relative_energy(en0,en,ic['x'],ic['y'],c['partID'],sigmax,sigmay)
	#energyvar.savefig('relative_energy_variation')

	actionvar = relative_action(Jx0, Jy0, Jx, Jy, ic['x'], ic['y'], c['partID'], sigmax,sigmay)
	actionvar.savefig('%s/relative_action_variation.png' %plots_folder)

	lost_particles_indexes = list(set(ic['partID'])-set(c['partID']))

	if  lost_particles_indexes != []:

		lvia = lossvsiaction(ic['partID'],c['partID'],Jx0,Jy0, dbname, tablename)
		lvia.savefig('%s/loss_vs_ic.png' %plots_folder)
	
		absorbed = simple_absorption_plot(lost,npart, turns)
		absorbed.savefig("%s/absorbedparts.png" %plots_folder)

		currentloss = turn_by_turn_lost_current(tbt_current_loss, turns)
		currentloss.savefig('%s/turn_by_turn_lost_current.png' %plots_folder)
		
		#ae = action_evolution(lost_particles_indexes)
		#ae.savefig('%s/action_evolution.png' %plots_folder)
		
	backup_file(plots_folder,main_folder)
def simulations_launcher_func(emitn,energy0,deltap0,ip,seed,sig0,iamp,eamp,n_samples,n_parts,wr_fr,SixTrack_folder,forts_folder,fort_n_list,main_folder,folder_name):

	start_time = datetime.datetime.now().time()
	
	print '\n\n ======= START OF USER INPUT GENERATION AND JOB LAUNCHER ====== \n\n'
	
	
	
	
	
	assert n_samples % n_parts == 0.0
	
	twiss = read_twiss(main_folder,seed,ip)
	sigmax,sigmay, sigmapx,sigmapy, gamma_rel, beta_rel = calc_beam_params(emitn, energy0, twiss['betx'],twiss['bety'], twiss['alfx'], twiss['alfy'])
	
	
	print 'Next step: generating uniform distribution of ',n_samples
	
	print 'distributed between ', iamp, 'and ', eamp, ' mm of radius'
	
	x, y = uniform_distribution_generator(n_samples,iamp,eamp,sigmax,sigmay,twiss['x'],twiss['y'])
	
	print 'Uniform distribution generated.'

	
	

	print 'Next step: calculating the Gaussian and storing its values in a file'
	
	gd = gaussian(x, y, sigmax)
	
	#gaussian_to_file(gd, filename)
	
	#print 'Gaussian distribution stored in ', filename, '.txt'
	
	
	
	
	
	print 'Next step: generation of the fort.13 with the desidered initial conditions'
	
	#---------
	xp, yp, sig, deltap, energy = initialize_coordinates(n_samples,twiss['xp'],twiss['yp'],energy0)
	
	iter_num = int(n_samples/n_parts) # number of iterations
	
	n_file = np.arange(iter_num) # folder number
	
	main_folder = main_folder + '/data'

	for i in range(iter_num): #loop to launch SixTrack jobs in parallel, one every 30 particles i.c.s
		ii = i*n_parts
		ie = (i+1)*n_parts
		sub_folder = folder_name + str(i)
		relpath = make_folder(main_folder, sub_folder)
		write_to_file(x[ii:ie],y[ii:ie],xp[ii:ie],yp[ii:ie],sig[ii:ie],deltap[ii:ie],energy[ii:ie],int(n_parts),relpath)
		copy_SixTrack(relpath,SixTrack_folder)
		copy_forts(relpath,forts_folder,fort_n_list)
		home = launch_jobs(relpath, SixTrack_folder)
		print ('job %s launched' %relpath)
	
	#----------
	
	print 'Launched ', iter_num, 'jobs, as shown here:\n'
	
	os.chdir(home)
	
	os.system('bjobs')
	
	
	print datetime.datetime.now().time(),': bsub run. Returning to home directory.'
	
	
	
	
	
	end_time = datetime.datetime.now().time()
	
	print 'This script was launched at ',start_time,' and terminated at',end_time
	
	
	print '\n ======= END OF USER INPUT GENERATION AND JOB LAUNCHER ====== \n\n'