def rastervals_in_unit(unit, lon_min, lat_min, cellsize, data, view='y-x+'): # For some reason it is MUCH faster to do it this way. if isinstance(unit, geometry.multipolygon.MultiPolygon): return np.hstack([rastervals_in_unit(g,lon_min,lat_min,cellsize,data,view) for g in unit.geoms]) llc = unit.bounds[:2] urc = unit.bounds[2:] lon_min_in = int((llc[0]-lon_min)/cellsize) lon_max_in = int((urc[0]-lon_min)/cellsize)+1 lat_min_in = int((llc[1]-lat_min)/cellsize) lat_max_in = int((urc[1]-lat_min)/cellsize)+1 data_boxed_ = grid_convert(data,view,'x+y+')[lon_min_in:lon_max_in+1,lat_min_in:lat_max_in+1] flat_shape = (-1,)+data_boxed_.shape[2:] data_boxed = data_boxed_.reshape(flat_shape) lon_boxed = np.arange(lon_min_in, lon_max_in+1)*cellsize + lon_min lat_boxed = np.arange(lat_min_in, lat_max_in+1)*cellsize + lat_min mlon_boxed, mlat_boxed = np.meshgrid(lon_boxed, lat_boxed) mlon_boxed = grid_convert(mlon_boxed,'y+x+','x+y+') mlat_boxed = grid_convert(mlat_boxed,'y+x+','x+y+') p=[geom.Point(*pair) for pair in zip(mlon_boxed.ravel(), mlat_boxed.ravel())] if isinstance(unit, geometry.polygon.Polygon): p_in = set(iterops.contains(geometry.polygon.Polygon(unit.exterior.coords), p, True)) for hole in unit.interiors: p_in -= set(iterops.contains(geometry.polygon.Polygon(hole.coords), p, True)) else: p_in = iterops.contains(unit, p, True) i_in = [p.index(p_in_) for p_in_ in p_in] out = data_boxed[i_in] return out
def exportAscii2(lon, lat, data, filename, view="y-x+"): "Exports longitude and latitude vectors and a data masked array to ascii." data = grid_convert(data, view, "y-x+") if data.shape != (len(lat), len(lon)): raise ValueError, "Data is wrong shape" data.fill_value = np.asscalar(np.array(-9999).astype(data.dtype)) header = { "ncols": len(lon), "nrows": len(lat), "cellsize": lon[1] - lon[0], "xllcorner": lon.min(), "yllcorner": lat.min(), "NODATA_value": data.fill_value, } exportAscii(data.filled(), filename, header, True - data.mask)
def export_flt(lon, lat, data, filename, view="y-x+"): "filename should have no extension; the '.hdr' and '.flt' extensions will be added automatically." data = grid_convert(data, view, "y-x+") if data.shape != (len(lat), len(lon)): raise ValueError, "Data is wrong shape" data.fill_value = np.asscalar(np.array(-9999).astype(data.dtype)) header = { "ncols": len(lon), "nrows": len(lat), "cellsize": lon[1] - lon[0], "xllcorner": lon.min(), "yllcorner": lat.min(), "NODATA_value": data.fill_value, "byteorder": "LSBFIRST", } hfile = file(filename + ".hdr", "w") for k, v in header.iteritems(): hfile.write("%s\t%s\r\n" % (k, v)) hfile.close() dfile = npfile(filename + ".flt", order="C", endian="<", permission="w") dfile.write_array(data.filled().astype("float32")) dfile.close()