[Numpy-discussion] Help making better use of numpy array functions

mdekauwe mdekauwe at gmail.com
Thu Nov 26 11:33:03 EST 2009


Yep that will do nicely, code becomes

import sys, os, glob
import numpy as np

def averageEightDays(files, numrows, numcols, year, doy):
	""" Read in 8 files at a time, sum the valid LST, keep a count of 
		the valid pixels and average the result every 8days. """
	
	nodatavalue =  -999.0
	
	# break the files up into chunks of 8
	filenames = glob.glob(os.path.join(path, files))
	filenames.sort()
	filenamesList = [filenames[n:n+8] for n in xrange(0, len(filenames), 8)]
	for fchunk in filenamesList:
		# fill with nodata values, in case there are less than 8 days
		data8days = np.ones((8, numrows, numcols), dtype=np.float32) * -999.0 
		avg8days = np.zeros((numrows, numcols), dtype=np.float32)
		for day in xrange(len(fchunk)):
			fname = fchunk[day]
			try:
				f = open(fname, 'rb')
			except IOError:
				print "Cannot open outfile for read", fname
				sys.exit(1)
			data8days[day] = np.fromfile(f, dtype=np.float32).reshape(numrows,
numcols)
		# build an array (ndays, nrow, ncols) of True and False for the pixel
count
		# when these are summed we get the relative contributions
		weights = data8days > nodatavalue
		# np.average doesn't accept a weight of zero, COMMENT ME 
		weights[0] |= (weights.sum(axis=0) == 0) 
		pixelCount = weights.sum(axis=0)
		avg8days = np.average(data8days, axis=0, weights=weights)
		doy += 8
		#print year,':',doy
		
		outfile = "lst_8day1030am_" + str(year) + str(doy) + ".gra"
		write_outputs(outfile, avg8days)
		outfile = "pixelcount_8day1030am_" + str(year) + str(doy) + ".gra"
		write_outputs(outfile, pixelCount)

def write_outputs(outfile, data):
	opath = "/users/eow/mgdk/research/HOFF_plots/LST/8dayLST"
	try:
		of = open(os.path.join(opath, outfile), 'wb')
	except IOError:
		print "Cannot open outfile for write", outfile
		sys.exit(1)
	
	# empty stuff
	data.tofile(of)
	of.close()
	
	
if __name__ == "__main__":

	numrows = 332
	numcols = 667
	path = "/users/eow/mgdk/research/HOFF_plots/LST/gridded_03/"
	
	averageEightDays('lst_scr_2006*.gra', numrows, numcols, year=2006, doy=122)
	averageEightDays('lst_scr_2007*.gra', numrows, numcols, year=2007, doy=122)


-- 
View this message in context: http://old.nabble.com/Help-making-better-use-of-numpy-array-functions-tp26503657p26531909.html
Sent from the Numpy-discussion mailing list archive at Nabble.com.




More information about the NumPy-Discussion mailing list