def find_good_scaling_capacity(G, file_traffic, max_value=1., min_value=0., step=-0.1, target=0.015):
	"""
	This function scales down uniformly the capacities of all sectors of G 
	in order to meet the target of fraction of flights rejected.

	Parameters
	----------
	G: hybrid network
	file_traffic: string
		full path of file with traffic to use to infer capacities
	max_value: float, optional
		maximum scale value.
	min_value: float, optional
		minimum scale value
	step: float, optional
		step of scale value for the search.
	target: float, optional
		Target of fraction of flight rejected.

	Returns
	-------
	cap: float
		scale factor which meets the target
	frac: float
		exact fraction of flights rejected with this target
	H: hybrid network
		with modified value of capacities.
	
	"""
	
	caps = np.arange(max_value, min_value, step)
	last_ratio = None

	# Sweep the scaling factor
	for i, cap in enumerate(caps):
		with silence(True):
			H = deepcopy(G)
			trajs, stats = generate_traffic(H, file_traffic=file_traffic, capacity_factor=cap, put_sectors=True,
										remove_flights_after_midnight=True)
			# Get the fraction of flights rejected
			ratio = stats['rejected_flights']/float(stats['flights'])
		#print "ratio:", ratio
		# If the fraction is over the target, it is our value.
		if ratio>=target:
			break
		last_ratio = ratio

	# Refinement
	if ratio!=last_ratio and i!=0:
		cap = cap - (ratio - target)*(cap - caps[i-1])/(ratio - last_ratio)

	with silence(True):
		H = deepcopy(G)
		trajs, stats = generate_traffic(H, file_traffic=file_traffic, capacity_factor=cap, put_sectors=True,
											remove_flights_after_midnight=True)
				# Get the fraction of flights rejected
		ratio = stats['rejected_flights']/float(stats['flights'])

	return cap, ratio, H
def find_good_scaling_capacity(G, file_traffic, silent=True, max_value=1., min_value=0., step=-0.1, target=0.015, **paras_control):
	caps = np.arange(max_value, min_value, step)
	last_ratio = None
	for i, cap in enumerate(caps):
		with silence(silent):
			H = deepcopy(G)
			trajs, stats = generate_traffic(H, file_traffic=file_traffic, capacity_factor=cap, put_sectors=True,
										remove_flights_after_midnight=True, **paras_control)
			ratio = stats['rejected_flights']/float(stats['flights'])
		#print "cap=", cap, "; ratio=", ratio
		if ratio>=target:
			break
		last_ratio = ratio

	if ratio!=last_ratio and i!=0:
		#cap = (cap + caps[i-1])/2.
		cap = cap - (ratio - target)*(cap - caps[i-1])/(ratio - last_ratio)

	return cap, stats['rejected_flights']/float(stats['flights']), H
				for x, y in boundary:
					f.write(str(x) + '\t' + str(y) + '\n')

			print "Finding best capacity factor..."
			capacity_factor, rejected_flights, H = find_good_scaling_capacity(G, _result_dir + "/networks/" + name_G + '_flights_selected.pic', target=target_rejected_flights)
			print "Found best capacity factor:", capacity_factor, "(rejected fraction", rejected_flights, "of flights)"
			#print "Capacities:", {n:H.node[n]['capacity'] for n in H.nodes()}

			write_down_capacities(H, save_file=_result_dir + '/trajectories/capacities/' + G.name + '_capacities_rec_rej' + str(target_rejected_flights) + '_new.dat')
			#print "Capacities saved as", _result_dir + '/trajectories/capacities/' + G.name + '_capacities_rec_rej' + str(target_rejected_flights) + '_new.dat' 
			
			if zone in targets_eff_per_ACC.keys():
				for eff_target in targets_eff_per_ACC[zone]:
					for i in range(n_iter):
						counter(i, n_iter, message="Doing simulations...")
						name_results = name_sim(name_G) + '_eff_' + str(eff_target) + '_rej' + str(target_rejected_flights) + '_new_' + str(i) + '.dat'
						with silence(True):
							trajs, stats = generate_traffic(deepcopy(G), save_file=_result_dir + '/trajectories/M1/' + name_results,
												record_stats_file=_result_dir + '/trajectories/M1/' + name_results.split('.dat')[0] + '_stats.dat',
												file_traffic=_result_dir + "/networks/" + name_G + '_flights_selected.pic',
												put_sectors=True,
												remove_flights_after_midnight=True,
												capacity_factor=capacity_factor,
												rectificate={'eff_target':eff_target, 'inplace':False, 'hard_fixed':False, 'remove_nodes':True, 'resample_trajectories':True}
												)

							#trajs_rec, eff, G, groups_rec = rectificate_trajectories_network(trajs, eff_target,	deepcopy(G), inplace=False)
					#print "Ratio rejected:", stats['rejected_flights']/float(stats['flights'])
		
			print 
			print 
			with open(result_dir + '/trajectories/bounds/' + G.name + '_bound_latlon.dat', 'w') as f:
				for x, y in boundary:
					f.write(str(x) + '\t' + str(y) + '\n')

			# --------------------------------------------------------------------------------------

			paras_control = {'bootstrap_mode':True, 'bootstrap_only_time':True, 'ACtot':ACtot}
			#print "Finding best capacity factor..."
			#capacity_factor, rejected_flights, H = find_good_scaling_capacity(G, result_dir + "/networks/" + name_G + '_flights_selected.pic', 
			#	target=target_rejected_flights,  silent=True, **paras_control)
			#print "Found best capacity factor:", capacity_factor, "(rejected fraction", rejected_flights, "of flights)"
			
			write_down_capacities(G, save_file=result_dir + '/trajectories/capacities/' + G.name + '_capacities_no_target_rej.dat')
			
			for i in range(n_iter):
				counter(i, n_iter, message="Doing simulations...")
				name_results = name_sim(name_G) + '_rej' + str(target_rejected_flights) + '_ACtot' + str(ACtot) + '_' + str(i) + '.dat'
				
				with silence(True):

					trajs, stats = generate_traffic(deepcopy(G), save_file= result_dir + '/trajectories/M1/' + name_results,
										record_stats_file=result_dir + '/trajectories/M1/' + name_results.split('.dat')[0] + '_stats.dat',
										file_traffic=result_dir + "/networks/" + name_G + '_flights_selected.pic',
										put_sectors=True,
										remove_flights_after_midnight=True,
										capacity_factor=1.,
										**paras_control)
				#print "Ratio rejected:", stats['rejected_flights']/float(stats['flights'])
		
			print 
			print 
sys.path.insert(1, '../..')
sys.path.insert(1, '../../abm_strategic')
import pickle
import os 
from os.path import join as jn

from abm_strategic.simulationO import generate_traffic
from abm_strategic import result_dir, main_dir
#result_dir = jn(main_dir, 'tests', 'example')

if __name__ == '__main__':
	with open(jn(result_dir, 'networks', 'Example.pic'), 'r') as f:
		G = pickle.load(f) 

	os.system('mkdir -p ' + jn(result_dir, 'trajectories', 'M1'))
	save_file = jn(result_dir, 'trajectories', 'M1', 'trajectories_example.dat')
	paras_file = jn(main_dir, 'abm_strategic', 'my_paras.py')

	trajectories = generate_traffic(G, 	paras_file=paras_file,
										save_file=save_file, 
										# file_traffic=file_traffic, 
										# coordinates=True,
										# put_sectors=True, 
										# save_file_capacities=save_file_capacities,
										# capacity_factor=0.05,
										# remove_flights_after_midnight=True,
										# record_stats_file='../trajectories/M1/trajectories_stats.dat'
										# rectificate={'eff_target':0.99, 'inplace':False, 'hard_fixed':False, 'remove_nodes':True, 'resample_trajectories':True},
										# storymode=False,
										# ACtot=4000
										)