
import numpy as np
from matplotlib.pyplot import plot, subplots, tight_layout, gca, show, close, clf, gcf 
import array
   
def my_range(start, end, step):
    while start <= end:
        yield start
        start += step


def insol(solar_constant_i,max_tilt,num_lat_zones):
	""" determine insolation as function of latitude band
	"""
	
	days_in_year = 365.0               # averaging interval and period for insolation
	hours_in_day= 24.0
	zonal_degrees = 360.0	
	
	zonal_width = 90./num_lat_zones # number degrees in each zone
	lats = np.arange(zonal_width/2.,90.-zonal_width/2.+0.1,zonal_width) # midpoint of each zone
	lats_rad = lats*np.pi/180.	# midpoint of each zone (in radians) 
	delta_rad = (np.pi/2.)/num_lat_zones/2. # half number radians in each zone  
	lats_frac = np.sin(lats_rad+delta_rad) - np.sin(lats_rad-delta_rad) # fraction of the surface of sphere in each latitudesitude zone
	
	#  daily rotation of Earth reduces solar constant by distributing the sun
	#  energy all along a zonal band

	total_solar = 0.0
   
	for hour in range(1,int(hours_in_day)+1):
		noon_angle = zonal_degrees * hour / hours_in_day
		for longitude in range(1,int(zonal_degrees)+1):
			sun_angle = longitude - noon_angle
			total_solar = total_solar + solar_constant_i* max(0.0, np.cos(np.pi/180.0*sun_angle))

	solar_constant = total_solar/(hours_in_day * zonal_degrees)

	#-------------------------------------------------------------------------- 
	# initialize insolation to zero

	insolation=[0.0]*int(num_lat_zones)
 
	# accumulate normalized insolation through a year
  
	for day in range(1,int(days_in_year)+1):
		tilt = max_tilt * np.cos(2.0*np.pi*day/days_in_year)
		for j in range(0,int(num_lat_zones)):
			zenith = min (lats[j]+ tilt,90.0)
			insolation[j] = insolation [j] + np.cos(zenith*np.pi/180.)


	# average unnormalized insolation over one year

	insolation[:] = [x * (solar_constant/days_in_year) for x in insolation]

	avg_insolation = sum(lats_frac*insolation)
	# disp(['Average Insolation is ' num2str(avg_insolation) ' Watts/m^2']);

	return lats,lats_frac,insolation	
	
def solve_temp(solar_mult,temp,lats,lats_frac,insolation,num_lat_zones,F,A,B,albedo_ice,albedo_land,temp_critical):
	""" solve for latitudinal temperature profile
	given the solar constant multiplier
	"""

	#--------------------------------------------------------------------------
	# display initial albedos and temps
	
	# plots_initial (lats, albedo, temp);                             
	#--------------------------------------------------------------------------
  
	#--------------------------------------------------------------------------  
  
	# set up iterations

	step_num = 1                 # loop counter
	max_temp_diff = 1.0E6        # using large value insures loop executes once
	tol_temp_diff = 0.05         # max temp change before ending iteration
	max_steps = 100              # max steps during iteration before stopping
  
	#--------------------------------------------------------------------------

	# iterative loop for static temperature distribution
	# until maximum temperature change is less than tolerance

	while step_num < max_steps  and max_temp_diff > tol_temp_diff:
		temp_old = temp
		step_num = step_num + 1

		# albedo is either land albedo (T > temp_critical) or ice (T < temp_critical) 
		albedo = [0.0]*int(num_lat_zones)
		
		for j in range(0,int(num_lat_zones)):
			if temp_old[j] > temp_critical:
				albedo[j] = albedo_land
			else:
				albedo[j] = albedo_ice
		albedo=np.array(albedo)
		# update temperature
		temp_avg = sum(lats_frac*temp)
		
		temp = ([x * solar_mult for x in insolation]*(1.-albedo) + F*temp_avg - A)/(B+F) 
		max_temp_diff = max(abs(temp_old-temp))
			
		#--------------------------------------------------------------------------
  
	return temp_avg,temp,albedo

  
