Example #1
0
def main(year, dx=100000, snowType='SRLD', extraStr='v11'):

    xptsG, yptsG, latG, lonG, proj = cF.create_grid(dxRes=dx)
    print(xptsG)
    print(yptsG)

    dxStr = str(int(dx / 1000)) + 'km'
    print(dxStr)

    #region_mask, xptsI, yptsI = cF.get_region_mask_pyproj(anc_data_path, proj, xypts_return=1)
    #region_maskG = griddata((xptsI.flatten(), yptsI.flatten()), region_mask.flatten(), (xptsG, yptsG), method='nearest')

    #xptsDays, yptsDays, oibdates, snowDays= cF.read_icebridge_snowdepths(proj, oib_data_path, year)
    xptsDays, yptsDays, _, _, snowDays, oibdates = cF.getSTOSIWIGyear_proj(
        proj, oib_data_path + '/stosiwig/', snowType, year)

    for x in range(len(oibdates)):
        # Loop through dates of each flight. I want to keep separate to compre to the daily NESOSIM data.
        oib_dayG = bin_oib(dx, xptsDays[x], yptsDays[x], xptsG, yptsG,
                           snowDays[x])
        cF.plot_gridded_cartopy(
            lonG,
            latG,
            oib_dayG,
            proj=ccrs.NorthPolarStereo(central_longitude=-45),
            out=figure_path + '/OIB/' + oibdates[x] + dxStr + snowType +
            extraStr,
            date_string=oibdates[x],
            month_string='',
            varStr='OIB snow depth ',
            units_lab=r'm',
            minval=0,
            maxval=0.6,
            cmap_1=plt.cm.viridis)

        oib_dayG.dump(forcing_save_path + dxStr + '/OIB/' + str(year) + '/' +
                      oibdates[x] + dxStr + snowType + extraStr)

    arr = np.hstack(xptsDays)

    oib_daysG = cF.bin_oib(dx, np.hstack(xptsDays), np.hstack(yptsDays), xptsG,
                           yptsG, np.hstack(snowDays))

    cF.plot_gridded_cartopy(lonG,
                            latG,
                            oib_daysG,
                            proj=ccrs.NorthPolarStereo(central_longitude=-45),
                            out=figure_path + '/OIB/' + str(year) + dxStr +
                            snowType + extraStr,
                            date_string=str(year),
                            month_string='',
                            varStr='OIB snow depth ',
                            units_lab=r'm',
                            minval=0,
                            maxval=0.6,
                            cmap_1=plt.cm.viridis)
def main(year, dx=100000, extraStr='v11'):

    xptsG, yptsG, latG, lonG, proj = cF.create_grid(dxRes=dx)
    #print(xptsG)
    #print(yptsG)

    dxStr = str(int(dx / 1000)) + 'km'
    #print(dxStr)

    files = glob(forcing_save_path + dxStr + '/OIB/' + str(year) + '/' + '*' +
                 dxStr + extraStr + '')
    print(files)
    oibdates = [file[-16:-8] for file in files]

    print(oibdates)
    for x in range(len(oibdates)):
        # Loop through dates of each flight. I want to keep separate to compre to the daily NESOSIM data.

        try:
            oib_dayG1 = np.load(forcing_save_path + dxStr + '/OIB/' +
                                str(year) + '/' + oibdates[x] + dxStr +
                                'GSFC' + extraStr,
                                allow_pickle=True)
            oib_dayG2 = np.load(forcing_save_path + dxStr + '/OIB/' +
                                str(year) + '/' + oibdates[x] + dxStr +
                                'SRLD' + extraStr,
                                allow_pickle=True)
            oib_dayG3 = np.load(forcing_save_path + dxStr + '/OIB/' +
                                str(year) + '/' + oibdates[x] + dxStr + 'JPL' +
                                extraStr,
                                allow_pickle=True)

            oib_dayGC = np.median((oib_dayG1, oib_dayG2, oib_dayG3), axis=0)
            cF.plot_gridded_cartopy(
                lonG,
                latG,
                oib_dayGC,
                proj=ccrs.NorthPolarStereo(central_longitude=-45),
                out=figure_path + '/OIB/' + oibdates[x] + dxStr + 'MEDIAN' +
                extraStr,
                date_string=str(year),
                month_string='',
                varStr='OIB snow depth MEDIAN',
                units_lab=r'm',
                minval=0,
                maxval=0.6,
                cmap_1=plt.cm.viridis)

            oib_dayGC.dump(forcing_save_path + dxStr + '/OIB/' + str(year) +
                           '/' + oibdates[x] + dxStr + 'MEDIAN' + extraStr)
        except:
            print('All thre algs dont exist for this date:', oibdates[x])
Example #3
0
#region_maskG = griddata((xptsI.flatten(), yptsI.flatten()), region_mask.flatten(), (xptsG, yptsG), method='nearest')

xptsDays, yptsDays, oibdates, snowDays = cF.read_icebridge_snowdepths(
    proj, oib_data_path, year)

for x in range(len(oibdates)):
    # Loop through dates of each flight. I want to keep separate to compre to the daily NESOSIM data.
    oib_dayG = cF.bin_oib(xptsDays[x], yptsDays[x], xptsG, yptsG, snowDays[x])

    cF.plot_gridded_cartopy(lonG,
                            latG,
                            oib_dayG,
                            proj=ccrs.NorthPolarStereo(central_longitude=-45),
                            out=figure_path + '/OIB/' + oibdates[x] + dxStr +
                            extraStr,
                            date_string=oibdates[x],
                            month_string='',
                            varStr='OIB snow depth ',
                            units_lab=r'm',
                            minval=0,
                            maxval=0.6,
                            cmap_1=plt.cm.viridis)

    oib_dayG.dump(forcing_save_path + dxStr + '/OIB/' + str(year) + '/' +
                  oibdates[x] + dxStr + extraStr)

arr = np.hstack(xptsDays)

oib_daysG = bin_oib(np.hstack(xptsDays), np.hstack(yptsDays), xptsG, yptsG,
                    np.hstack(snowDays))
Example #4
0
def main(yearT,
         extraStr='v11_1',
         dx=100000,
         data_path=reanalysis_raw_path + 'ERA5/',
         out_path=forcing_save_path + 'Temp/ERA5/',
         fig_path=figure_path + 'Temp/ERA5/',
         anc_data_path='../../anc_data/'):

    xptsG, yptsG, latG, lonG, proj = cF.create_grid(dxRes=dx)
    print(xptsG)
    print(yptsG)

    dxStr = str(int(dx / 1000)) + 'km'
    print(dxStr)

    if not os.path.exists(out_path):
        os.makedirs(out_path)

    if not os.path.exists(fig_path):
        os.makedirs(fig_path)

    region_mask, xptsI, yptsI, _, _ = cF.get_region_mask_pyproj(anc_data_path,
                                                                proj,
                                                                xypts_return=1)
    region_maskG = griddata((xptsI.flatten(), yptsI.flatten()),
                            region_mask.flatten(), (xptsG, yptsG),
                            method='nearest')

    varStr = 't2m'

    xptsM, yptsM, temp2mYear = get_ERA5_temps(proj, data_path, yearT)

    hotdays_duration = xr.apply_ufunc(get_cumulative_hotdays,
                                      temp2mYear['t2m'].compute(),
                                      input_core_dims=[["time"]],
                                      vectorize=True)

    print(xptsM.flatten().shape)
    print(yptsM.flatten().shape)
    print(temp2mYear)
    print(hotdays_duration.values.flatten().shape)

    t2mdurG = griddata((xptsM.flatten(), yptsM.flatten()),
                       hotdays_duration.values.flatten(), (xptsG, yptsG),
                       method='linear')
    #t2mdurG[where(region_maskG>10)]=0.
    #t2mdur=t2mdur.astype('f2')

    cF.plot_gridded_cartopy(lonG,
                            latG,
                            t2mdurG,
                            proj=ccrs.NorthPolarStereo(central_longitude=-45),
                            out=fig_path + '/duration' + str(yearT) + extraStr,
                            date_string=str(yearT),
                            extra=extraStr,
                            varStr='hot days',
                            units_lab=r'>0',
                            minval=0,
                            maxval=100,
                            cmap_1=plt.cm.viridis)

    #monthStr='%02d' %(month+1)
    t2mdurG.dump(out_path + '/ERA5_duration' + dxStr + '-' + str(yearT) +
                 extraStr)
Example #5
0
def main(year,
         startMonth=8,
         endMonth=11,
         dx=100000,
         extraStr='v11_1',
         data_path=reanalysis_raw_path + 'ERA5/',
         out_path=forcing_save_path + 'Precip/ERA5/',
         fig_path=figure_path + 'Precip/ERA5/',
         anc_data_path='../../anc_data/'):

    xptsG, yptsG, latG, lonG, proj = cF.create_grid(dxRes=dx)
    print(xptsG)
    print(yptsG)

    dxStr = str(int(dx / 1000)) + 'km'
    print(dxStr)

    region_mask, xptsI, yptsI, _, _ = cF.get_region_mask_pyproj(anc_data_path,
                                                                proj,
                                                                xypts_return=1)
    region_maskG = griddata((xptsI.flatten(), yptsI.flatten()),
                            region_mask.flatten(), (xptsG, yptsG),
                            method='nearest')

    varStr = 'sf'

    if not os.path.exists(fig_path):
        os.makedirs(fig_path)

    yearT = year

    numDays = cF.getLeapYr(year)
    if (numDays > 365):
        monIndex = [0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366]
    else:
        monIndex = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365]

    if not os.path.exists(out_path + '/' + str(year)):
        os.makedirs(out_path + '/' + str(year))

    startDay = monIndex[startMonth]

    if (endMonth > 11):
        endDay = monIndex[endMonth + 1 - 12] + monIndex[-1] - 1
    else:
        endDay = monIndex[endMonth + 1]

    calc_weights = 1  # start as one to calculate weightings then gets set as zero for future files

    for dayT in range(startDay, endDay):

        dayStr = '%03d' % dayT
        month = np.where(dayT - np.array(monIndex) >= 0)[0][-1]
        monStr = '%02d' % (month + 1)
        dayinmonth = dayT - monIndex[month]
        print('Precip day:', dayT, dayinmonth)

        #in  kg/m2 per day
        xptsM, yptsM, lonsM, latsM, Precip = cF.get_ERA5_precip_days_pyproj(
            proj,
            data_path,
            str(yearT),
            monStr,
            dayinmonth,
            lowerlatlim=30,
            varStr=varStr)

        # if it's the first day, calculate weights
        if calc_weights == 1:
            # calculate Delaunay triangulation interpolation weightings for first file of the year
            print('calculating interpolation weightings')
            ptM_arr = np.array([xptsM.flatten(), yptsM.flatten()]).T
            tri = Delaunay(ptM_arr)  # delaunay triangulation
            calc_weights = 0

        # grid using linearNDInterpolator with triangulation calculated above
        # (faster than griddata but produces identical output)
        interp = LinearNDInterpolator(tri, Precip.flatten())
        PrecipG = interp((xptsG, yptsG))

        cF.plot_gridded_cartopy(
            lonG,
            latG,
            PrecipG,
            proj=ccrs.NorthPolarStereo(central_longitude=-45),
            out=fig_path + '/ERA5' + varStr + dxStr + '-' + str(yearT) + '_d' +
            dayStr + extraStr,
            date_string=str(yearT),
            month_string=str(dayT),
            extra=extraStr,
            varStr='ERA5 snowfall ',
            units_lab=r'kg/m2',
            minval=0,
            maxval=10,
            cmap_1=plt.cm.viridis)

        PrecipG.dump(out_path + str(yearT) + '/ERA5' + varStr + dxStr + '-' +
                     str(yearT) + '_d' + dayStr + extraStr)
Example #6
0
def main(yearT,
         extraStr='v11_1',
         dx=100000,
         data_path=reanalysis_raw_path + 'ERA5/',
         out_path=forcing_save_path + 'InitialConditions/ERA5/',
         fig_path=figure_path + 'InitialConditions/ERA5/',
         anc_data_path='../../anc_data/'):

    xptsG, yptsG, latG, lonG, proj = cF.create_grid(dxRes=dx)
    print(xptsG)
    print(yptsG)

    dxStr = str(int(dx / 1000)) + 'km'
    print(dxStr)

    if not os.path.exists(out_path):
        os.makedirs(out_path)

    if not os.path.exists(fig_path):
        os.makedirs(fig_path)

    region_mask, xptsI, yptsI, _, _ = cF.get_region_mask_pyproj(anc_data_path,
                                                                proj,
                                                                xypts_return=1)
    region_maskG = griddata((xptsI.flatten(), yptsI.flatten()),
                            region_mask.flatten(), (xptsG, yptsG),
                            method='nearest')

    reanalysis = 'ERA5'
    varStr = 't2m'

    iceconc_path = forcing_save_path + '/IceConc/CDR/'
    temp_path = forcing_save_path + '/Temp/ERA5/'

    t2mdurGAll = []
    for y in range(1980, 1991 + 1, 1):
        if (y == 1987):
            continue
        t2mdurGT = np.load(temp_path + 'duration' + dxStr + '-' + str(y) +
                           extraStr,
                           allow_pickle=True)
        t2mdurGAll.append(t2mdurGT)

    t2mdurGclim = ma.mean(t2mdurGAll, axis=0)
    print(t2mdurGclim.shape)
    w99 = cF.getWarren(lonG, latG, 7)

    for yearT in range(2021, 2021 + 1, 1):
        if (yearT == 1987):
            continue

        t2mdurGT = np.load(temp_path + 'duration' + dxStr + '-' + str(yearT) +
                           extraStr,
                           allow_pickle=True)
        print(t2mdurGT.shape)
        W99yrT = w99 * (t2mdurGclim / t2mdurGT)
        W99yrT[np.where(latG < 70)] = 0
        W99yrT[np.where(region_maskG > 8.2)] = 0
        W99yrT[np.where(region_maskG <= 7.8)] = 0
        W99yrT[np.where(W99yrT < 0)] = 0
        W99yrT[np.where(W99yrT > 10)] = 10

        day = 226
        dayStr = str(day)  #226 is middle of August

        iceConcDayG = np.load(iceconc_path + str(yearT) + '/iceConcG_CDR' +
                              dxStr + '-' + str(yearT) + '_d' + dayStr +
                              extraStr,
                              allow_pickle=True)
        W99yrT[np.where(iceConcDayG < 0.15)] = 0

        W99yrT = gaussian_filter(W99yrT, sigma=1)

        # Convert to meters
        W99yrT = W99yrT / 100.

        cF.plot_gridded_cartopy(
            lonG,
            latG,
            W99yrT,
            proj=ccrs.NorthPolarStereo(central_longitude=-45),
            out=fig_path + '/initial_conditions' + str(yearT) + dxStr +
            extraStr,
            date_string=str(yearT),
            extra=extraStr,
            varStr='Snow depth ',
            units_lab=r'm',
            minval=0,
            maxval=0.12,
            cmap_1=plt.cm.viridis)

        W99yrT.dump(out_path + 'ICsnow' + dxStr + '-' + str(yearT) + extraStr)
Example #7
0
def main(year, startMonth=3, endMonth=3, extraStr='v11_1', dx=100000, data_path=cdr_raw_path, out_path=forcing_save_path, fig_path=figure_path+'IceConc/CDR/', anc_data_path='../../anc_data/'):
		
	xptsG, yptsG, latG, lonG, proj = cF.create_grid(dxRes=dx)
	print(xptsG)
	print(yptsG)

	dxStr=str(int(dx/1000))+'km'
	print(dxStr)

	region_mask, xptsI, yptsI, lonsI, latsI = cF.get_region_mask_pyproj(anc_data_path, proj, xypts_return=1)
	region_maskG = griddata((xptsI.flatten(), yptsI.flatten()), region_mask.flatten(), (xptsG, yptsG), method='nearest')

	product='CDR'

	numDaysYr=cF.getLeapYr(year)
	if (numDaysYr>365):
		monIndex = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
	else:
		monIndex = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]

	if not os.path.exists(out_path+'/'+str(year)):
		os.makedirs(out_path+'/'+str(year))

	if not os.path.exists(fig_path):
		os.makedirs(fig_path)
		
	calc_weights = 1 # start as one to calculate weightings then gets set as zero for future files

	for month in range(startMonth, endMonth+1):
		print(month)
		mstr='%02d' %(month+1)
		# Get pole hole	
		pmask=cF.get_pmask(year, month)

		numDays=monIndex[month]
		
		# should return array with nans not masked as needed for regridding.
		for x in range(numDays):
			dayT=sum(monIndex[0:month])+x
			daySumStr='%03d' %(dayT)
			dayMonStr='%02d' %(x+1)
			print('day month string', dayMonStr)
			
			try:
				# Try final first
				fileT=glob(data_path+'/final/'+str(year)+'/'+mstr+'/*'+str(year)+mstr+dayMonStr+'*.nc')[0]
				print(data_path+'/final/'+str(year)+'/'+mstr+'/*'+str(year)+mstr+dayMonStr+'*.nc')
				print('final data')
			except:
				try:
					# Try nrt
					fileT=glob(data_path+'/nrt/'+str(year)+'/'+mstr+'/*'+str(year)+mstr+dayMonStr+'*.nc')[0]
					print(data_path+'/nrt/'+str(year)+'/'+mstr+'/*'+str(year)+mstr+dayMonStr+'*.nc')
					print('nrt data')
				except:	
					try:
						dayMonStr='%03d' %(dayT-1)
						fileT=glob(data_path+'/final/'+str(year)+'/'+mstr+'/*'+str(year)+mstr+dayMonStr+'*.nc')[0]
						print(data_path+'/final/'+str(year)+'/'+mstr+'/*'+str(year)+mstr+dayMonStr+'*.nc')
						print('previous day final data')
					except:
						try:
							dayMonStr='%03d' %(dayT+1)
							fileT=glob(data_path+'/final/'+str(year)+'/'+mstr+'/*'+str(year)+mstr+dayMonStr+'*.nc')[0]
							print(data_path+'/final/'+str(year)+'/'+mstr+'/*'+str(year)+mstr+dayMonStr+'*.nc')
							print('following day final data')
						except:
							print('no conc')
							# previously was pass but this meant it would just use the previous loop data below
							continue

			iceConcDay = cF.getCDRconcproj(fileT, mask=0, maxConc=1, lowerConc=1)
			print(iceConcDay.shape)

			# if it's the first day, calculate weights
			if calc_weights == 1:

				# calculate Delaunay triangulation interpolation weightings for first file of the year
				print('calculating interpolation weightings')

				# Use region mask which is on the same grid!
				ptM_arr = np.array([xptsI.flatten(),yptsI.flatten()]).T
				tri = Delaunay(ptM_arr) # delaunay triangulation
				calc_weights = 0

			
			iceConcDay[np.where(region_mask>10)]=np.nan

			#iceConcDayG = griddata((xpts0.flatten(), ypts0.flatten()), iceConcDay.flatten(), (xptsG, yptsG), method='linear')
			# grid using linearNDInterpolator with triangulation calculated above 
			# (faster than griddata but produces identical output)
			interp = LinearNDInterpolator(tri,iceConcDay.flatten())
			iceConcDayG = interp((xptsG,yptsG))

			iceConcDayG[np.where(iceConcDayG<0.15)]=0
			iceConcDayG[np.where(iceConcDayG>1)]=1

			iceConcDayG[np.where(region_maskG>10)]=np.nan

			cF.plot_gridded_cartopy(lonG, latG, iceConcDayG, proj=ccrs.NorthPolarStereo(central_longitude=-45), out=fig_path+'iceConcG_-'+str(year)+mstr+dayMonStr+dxStr+extraStr, 
				date_string=str(year), month_string=mstr+dayMonStr, extra=extraStr, varStr='CDR ice conc', units_lab='', minval=0, maxval=1, cmap_1=plt.cm.viridis)
		
			iceConcDayG.dump(out_path+str(year)+'/iceConcG_CDR'+dxStr+'-'+str(year)+'_d'+daySumStr+extraStr)
Example #8
0
def main(year1, month1, day1, year2, month2, day2, outPathT='.', forcingPathT='.', anc_data_pathT='../anc_data/', figPathT='../Figures/', 
	precipVar='ERA5', windVar='ERA5', driftVar='OSISAF', concVar='CDR', icVar='ERAI', densityTypeT='variable', 
	outStr='', extraStr='', IC=2, windPackFactorT=0.1, windPackThreshT=5., leadLossFactorT=0.1, atmLossFactorT=2.2e-8, dynamicsInc=1, leadlossInc=1, 
	windpackInc=1, atmlossInc=0, saveData=1, plotBudgets=1, plotdaily=1, saveFolder='', dx=50000,scaleCS=False):
	""" 

	Main model function

	Args:
		The various model configuration parameters

	"""

	#------- Create map projection
	xptsG, yptsG, latG, lonG, proj = cF.create_grid(dxRes=dx)
	nx=xptsG.shape[0]
	ny=xptsG.shape[1]

	dxStr=str(int(dx/1000))+'km'
	print(nx, ny, dxStr)

	# Assign some global parameters
	global dataPath, forcingPath, outPath, ancDataPath
	
	outPath=outPathT+dxStr+'/'
	forcingPath=forcingPathT+dxStr+'/'
	ancDataPath=anc_data_pathT
	print('OutPath:', outPath)
	print('forcingPath:', forcingPath)
	print('ancDataPath:', ancDataPath)

	# Assign density of the two snow layers
	global snowDensityFresh, snowDensityOld, minSnowD, minConc, leadLossFactor, atmLossFactor, windPackThresh, windPackFactor, deltaT
	snowDensityFresh=200. # density of fresh snow layer
	snowDensityOld=350. # density of old snow layer
	minSnowD=0.02 # minimum snow depth for a density estimate
	minConc=0.15 # mask budget values with a concentration below this value

	deltaT=60.*60.*24. # time interval (seconds in a day)

	region_mask, xptsI, yptsI = cF.get_region_mask_pyproj(anc_data_pathT, proj, xypts_return=1)
	region_maskG = griddata((xptsI.flatten(), yptsI.flatten()), region_mask.flatten(), (xptsG, yptsG), method='nearest')

	leadLossFactor=leadLossFactorT # Snow loss to leads coefficient
	windPackThresh=windPackThreshT # Minimum winds needed for wind packing
	windPackFactor=windPackFactorT # Fraction of snow packed into old snow layer
	atmLossFactor=atmLossFactorT # Snow loss to atmosphere coefficient

	#---------- Current year
	yearCurrent=year1
	
	#--------- Get time period info
	startDay, numDays, numDaysYear1, dateOut= cF.getDays(year1, month1, day1, year2, month2, day2)
	print (startDay, numDays, numDaysYear1, dateOut)

	# make this into a small function
	dates=[]
	for x in range(0, numDays):
		#print x
		date = datetime.datetime(year1, month1+1, day1+1) + datetime.timedelta(x)
		#print (int(date.strftime('%Y%m%d')))
		dates.append(int(date.strftime('%Y%m%d')))
	#print(dates)
	
	CSstr = ''
	if scaleCS:
		# load scaling factors; assumes scaling factors are in same directory as NESOSIM.py
		monthlyScalingFactors = xr.open_dataset('{}scale_coeffs_{}_{}_v2.nc'.format(ancDataPath, precipVar, dxStr))['scale_factors']
		CSstr = 'CSscaled'

	#------ create output strings and file paths -----------
	saveStr= precipVar+CSstr+'sf'+windVar+'winds'+driftVar+'drifts'+concVar+'sic'+'rho'+densityTypeT+'_IC'+str(IC)+'_DYN'+str(dynamicsInc)+'_WP'+str(windpackInc)+'_LL'+str(leadlossInc)+'_AL'+str(atmlossInc)+'_WPF'+str(windPackFactorT)+'_WPT'+str(windPackThreshT)+'_LLF'+str(leadLossFactorT)+'-'+dxStr+extraStr+outStr+'-'+dateOut
	saveStrNoDate=precipVar+CSstr+'sf'+windVar+'winds'+driftVar+'drifts'+concVar+'sic'+'rho'+densityTypeT+'_IC'+str(IC)+'_DYN'+str(dynamicsInc)+'_WP'+str(windpackInc)+'_LL'+str(leadlossInc)+'_AL'+str(atmlossInc)+'_WPF'+str(windPackFactorT)+'_WPT'+str(windPackThreshT)+'_LLF'+str(leadLossFactorT)+'-'+dxStr+extraStr+outStr
	
	print ('Saving to:', saveStr)
	 #'../../DataOutput/'

	savePath=outPath+saveFolder+'/'+saveStrNoDate
	# Declare empty arrays for compiling budgets
	if not os.path.exists(savePath+'/budgets/'):
		os.makedirs(savePath+'/budgets/')
	if not os.path.exists(savePath+'/final/'):
		os.makedirs(savePath+'/final/')

	global figpath
	figpath=figPathT+'/Diagnostic/'+dxStr+'/'+saveStrNoDate+'/'
	if not os.path.exists(figpath):
		os.makedirs(figpath)
	if not os.path.exists(figpath+'/daily_snow_depths/'):
		os.makedirs(figpath+'/daily_snow_depths/')

	precipDays, iceConcDays, windDays, tempDays, snowDepths, density, snowDiv, snowAdv, snowAcc, snowOcean, snowWindPack, snowWindPackLoss, snowWindPackGain, snowLead, snowAtm = genEmptyArrays(numDays, nx, ny)

	print('IC:', IC)
	if (IC>0):
		if (IC==1):
			# August Warren climatology snow depths
			ICSnowDepth = np.load(forcingPath+'InitialConditions/AugSnow'+dxStr, allow_pickle=True)
			print('Initialize with August Warren climatology')
		
		elif (IC==2):
			# Petty initiail conditions
			try:
				ICSnowDepth = np.load(forcingPath+'InitialConditions/'+icVar+'/ICsnow'+dxStr+'-'+str(year1)+extraStr, allow_pickle=True)
				print('Initialize with new v1.1 scaled initial conditions')
				print(np.amax(ICSnowDepth))
			except:
				print('No initial conditions file available')

		iceConcDayG, precipDayG, driftGdayG, windDayG, tempDayG =loadData(year1, startDay, precipVar, windVar, concVar, driftVar, dxStr, extraStr)
		ICSnowDepth[np.where(iceConcDayG<minConc)]=0

		#--------Split the initial snow depth over both layers
		snowDepths[0, 0]=ICSnowDepth*0.5
		snowDepths[0, 1]=ICSnowDepth*0.5

	#pF.plotSnow(m, xptsG, yptsG, densityT, date_string=str(startDay-1), out=figpath+'/Snow/2layer/densityD'+driftP+extraStr+reanalysisP+varStr+'_sy'+str(year1)+'d'+str(startDay)+outStr+'T0', units_lab=r'kg/m3', minval=180, maxval=360, base_mask=0, norm=0, cmap_1=cm.viridis)

	# Loop over days 
	for x in range(numDays-1):	
		day = x+startDay
		
		if (day>=numDaysYear1):
			# If day goes beyond the number of days in initial year, jump to the next year
			day=day-numDaysYear1
			yearCurrent=year2
		
		print ('Day of year:', day)
		print ('Date:', dates[x])
		
		#-------- Load daily data 
		iceConcDayG, precipDayG, driftGdayG, windDayG, tempDayG =loadData(yearCurrent, day, precipVar, windVar, concVar, driftVar, dxStr, extraStr)
		
		#-------- Apply CloudSat scaling if used
		if scaleCS:
			currentMonth = doyToMonth(day, yearCurrent) # get current month
			scalingFactor = monthlyScalingFactors.loc[currentMonth,:,:] # get scaling factor for current month
			# apply scaling to current day's precipitation
			precipDayG = applyScaling(precipDayG, scalingFactor,scaling_type='mul').values

		#-------- Calculate snow budgets
		calcBudget(xptsG, yptsG, snowDepths, iceConcDayG, precipDayG, driftGdayG, windDayG, tempDayG,
			density, precipDays, iceConcDays, windDays, tempDays, snowAcc, snowOcean, snowAdv, 
			snowDiv, snowLead, snowAtm, snowWindPackLoss, snowWindPackGain, snowWindPack, region_maskG, dx, x, day,
			densityType=densityTypeT, dynamicsInc=dynamicsInc, leadlossInc=leadlossInc, windpackInc=windpackInc, atmlossInc=atmlossInc)
		
		if (plotdaily==1):
			cF.plot_gridded_cartopy(lonG, latG, snowDepths[x+1, 0]+snowDepths[x+1, 1], proj=ccrs.NorthPolarStereo(central_longitude=-45), date_string='', out=figpath+'daily_snow_depths/snowTot_'+saveStrNoDate+str(x), units_lab='m', varStr='Snow depth', minval=0., maxval=0.6)
	
	#------ Load last data 
	iceConcDayG, precipDayG, _, windDayG, tempDayG =loadData(yearCurrent, day+1, precipVar, windVar, concVar, driftVar, dxStr, extraStr)
	precipDays[x+1]=precipDayG
	iceConcDays[x+1]=iceConcDayG
	windDays[x+1]=windDayG
	tempDays[x+1]=tempDayG
	
	if (saveData==1):
		# Output snow budget terms to netcdf datafiles
		cF.OutputSnowModelRaw(savePath, saveStr, snowDepths, density, precipDays, iceConcDays, windDays, snowAcc, snowOcean, snowAdv, snowDiv, snowLead, snowAtm, snowWindPack)
		cF.OutputSnowModelFinal(savePath, 'NESOSIMv11_'+dateOut, lonG, latG, xptsG, yptsG, snowDepths[:, 0]+snowDepths[:, 1], (snowDepths[:, 0]+snowDepths[:, 1])/iceConcDays, density, iceConcDays, precipDays, windDays, tempDays, dates)

	if (plotBudgets==1):
		# Plot final snow budget terms 
		cF.plot_budgets_cartopy(lonG, latG, precipDayG, windDayG, snowDepths[x+1], snowOcean[x+1], snowAcc[x+1], snowDiv[x+1], \
		snowAdv[x+1], snowLead[x+1], snowAtm[x+1], snowWindPack[x+1], snowWindPackLoss[x+1], snowWindPackGain[x+1], density[x+1], dates[-1], figpath, totalOutStr=saveStr)