def testFIR(self): smooth = np.array([0.25, 0.5, 0.25]) d = np.arange(10) filtered = fir(d, smooth, zero_edge=False) print d, '--', smooth, '(keep edge) -->', filtered self.assertTrue(np.all( filtered == d)) filtered = fir(d, smooth, zero_edge=True) print d, '--', smooth, '-->', filtered self.assertEquals(0, filtered[9]) d = np.zeros(10) d[5] = 10 filtered = fir(d, smooth) print d, '--', smooth, '-->', filtered self.assertEquals(5.0, filtered[5]) d = np.zeros(10) d[5:10] = np.ones(5) filtered = fir(d, smooth) print d, '--', smooth, '-->', filtered self.assertEquals(0.0, filtered[3]) self.assertEquals(0.25, filtered[4]) self.assertEquals(0.75, filtered[5]) self.assertEquals(1.0, filtered[6]) diff = np.array([-0.5, 0, 0.5]) filtered = fir(d, diff) print d, '--', diff, '-->', filtered
def ncwrite(fn, data, varname, dims=None, attrs=None, gattrs=None, largefile=False): """ Write a netCDF data file from an array. :param: fn: (*string*) netCDF data file path. :param data: (*array_like*) A numeric array variable of any dimensionality. :param varname: (*string*) Variable name. :param dims: (*list of dimensions*) Dimension list. :param attrs: (*dict*) Variable attributes. :param gattrs: (*dict*) Global attributes. :param largefile: (*boolean*) Create netCDF as large file or not. """ if dims is None: if isinstance(data, NDArray): dims = [] for s in data.shape: dimvalue = np.arange(s) dimname = 'dim' + str(len(dims)) dims.append(dimension(dimvalue, dimname)) else: dims = data.dims #New netCDF file ncfile = addfile(fn, 'c', largefile=largefile) #Add dimensions ncdims = [] for dim in dims: ncdims.append(ncfile.adddim(dim.getShortName(), dim.getLength())) #Add global attributes ncfile.addgroupattr('Conventions', 'CF-1.6') ncfile.addgroupattr('Tools', 'Created using meteothink') if not gattrs is None: for key in gattrs: ncfile.addgroupattr(key, gattrs[key]) #Add dimension variables dimvars = [] wdims = [] for dim, midim in zip(ncdims, dims): dimtype = midim.getDimType() dimname = dim.getShortName() if dimtype == DimensionType.T: var = ncfile.addvar(dimname, 'int', [dim]) var.addattr('units', 'hours since 1900-01-01 00:00:0.0') var.addattr('long_name', 'Time') var.addattr('standard_name', 'time') var.addattr('axis', 'T') tvar = var elif dimtype == DimensionType.Z: var = ncfile.addvar(dimname, 'float', [dim]) var.addattr('axis', 'Z') elif dimtype == DimensionType.Y: var = ncfile.addvar(dimname, 'float', [dim]) var.addattr('axis', 'Y') elif dimtype == DimensionType.X: var = ncfile.addvar(dimname, 'float', [dim]) var.addattr('axis', 'X') else: var = None if not var is None: dimvars.append(var) wdims.append(midim) #Add variable var = ncfile.addvar(varname, data.dtype, ncdims) if attrs is None: var.addattr('name', varname) else: for key in attrs: var.addattr(key, attrs[key]) #Create netCDF file ncfile.create() #Write variable data for dimvar, dim in zip(dimvars, wdims): if dim.getDimType() == DimensionType.T: sst = datetime.datetime(1900, 1, 1) tt = miutil.nums2dates(dim.getDimValue()) hours = [] for t in tt: hours.append((t - sst).total_seconds() // 3600) ncfile.write(dimvar, np.array(hours)) else: ncfile.write(dimvar, np.array(dim.getDimValue())) ncfile.write(var, data) #Close netCDF file ncfile.close()
def imshow(self, *args, **kwargs): """ Display an image on the 3D axes. :param x: (*array_like*) Optional. X coordinate array. :param y: (*array_like*) Optional. Y coordinate array. :param z: (*array_like*) 2-D or 3-D (RGB) z value array. :param levs: (*array_like*) Optional. A list of floating point numbers indicating the level curves to draw, in increasing order. :param cmap: (*string*) Color map string. :param colors: (*list*) If None (default), the colormap specified by cmap will be used. If a string, like ‘r’ or ‘red’, all levels will be plotted in this color. If a tuple of matplotlib color args (string, float, rgb, etc), different levels will be plotted in different colors in the order specified. :returns: (*RasterLayer*) RasterLayer created from array data. """ n = len(args) cmap = plotutil.getcolormap(**kwargs) fill_value = kwargs.pop('fill_value', -9999.0) xaxistype = None isrgb = False if n <= 2: if isinstance(args[0], (list, tuple)): isrgb = True rgbdata = args[0] if isinstance(rgbdata[0], np.NDArray): x = np.arange(0, rgbdata[0].shape[1]) y = np.arange(0, rgbdata[0].shape[0]) else: x = rgbdata[0].dimvalue(1) y = rgbdata[0].dimvalue(0) elif args[0].ndim > 2: isrgb = True rgbdata = args[0] if isinstance(rgbdata, np.NDArray): x = np.arange(0, rgbdata.shape[1]) y = np.arange(0, rgbdata.shape[0]) else: x = rgbdata.dimvalue(1) y = rgbdata.dimvalue(0) else: a = args[0] if isinstance(a, DimArray): y = a.dimvalue(0) x = a.dimvalue(1) else: yn, xn = a.shape x = np.arange(xn) y = np.arange(yn) args = args[1:] elif n <= 4: x = args[0] y = args[1] a = args[2] if isinstance(a, (list, tuple)): isrgb = True rgbdata = a elif a.ndim > 2: isrgb = True rgbdata = a else: args = args[3:] offset = kwargs.pop('offset', 0) zdir = kwargs.pop('zdir', 'z') interpolation = kwargs.pop('interpolation', None) if isrgb: if isinstance(rgbdata, (list, tuple)): rgbd = [] for d in rgbdata: rgbd.append(d.asarray()) rgbdata = rgbd else: rgbdata = rgbdata.asarray() x = plotutil.getplotdata(x) y = plotutil.getplotdata(y) graphics = GraphicFactory.createImage(x, y, rgbdata, offset, zdir, interpolation) ls = None else: if len(args) > 0: level_arg = args[0] if isinstance(level_arg, int): cn = level_arg ls = LegendManage.createImageLegend(a._array, cn, cmap) else: if isinstance(level_arg, np.NDArray): level_arg = level_arg.aslist() ls = LegendManage.createImageLegend( a._array, level_arg, cmap) else: ls = plotutil.getlegendscheme(args, a.min(), a.max(), **kwargs) ls = ls.convertTo(ShapeTypes.Image) plotutil.setlegendscheme(ls, **kwargs) if zdir == 'xy': sepoint = kwargs.pop('sepoint', [0, 0, 1, 1]) else: sepoint = None graphics = GraphicFactory.createImage(x._array, y._array, a._array, ls, offset, zdir, sepoint, interpolation) visible = kwargs.pop('visible', True) if visible: self.add_graphic(graphics) return graphics
def contourf(self, *args, **kwargs): """ Plot filled contours. :param x: (*array_like*) Optional. X coordinate array. :param y: (*array_like*) Optional. Y coordinate array. :param z: (*array_like*) 2-D z value array. :param levs: (*array_like*) Optional. A list of floating point numbers indicating the level curves to draw, in increasing order. :param cmap: (*string*) Color map string. :param colors: (*list*) If None (default), the colormap specified by cmap will be used. If a string, like ‘r’ or ‘red’, all levels will be plotted in this color. If a tuple of matplotlib color args (string, float, rgb, etc), different levels will be plotted in different colors in the order specified. :param smooth: (*boolean*) Smooth countour lines or not. :returns: (*VectoryLayer*) Contour VectoryLayer created from array data. """ n = len(args) cmap = plotutil.getcolormap(**kwargs) fill_value = kwargs.pop('fill_value', -9999.0) offset = kwargs.pop('offset', 0) xaxistype = None if n <= 2: a = args[0] if isinstance(a, DimArray): y = a.dimvalue(0) x = a.dimvalue(1) else: yn, xn = a.shape x = np.arange(xn) y = np.arange(yn) args = args[1:] elif n <= 4: x = args[0] y = args[1] a = args[2] args = args[3:] if len(args) > 0: level_arg = args[0] if isinstance(level_arg, int): cn = level_arg ls = LegendManage.createLegendScheme(a.min(), a.max(), cn, cmap) else: if isinstance(level_arg, np.NDArray): level_arg = level_arg.aslist() ls = LegendManage.createLegendScheme(a.min(), a.max(), level_arg, cmap) else: ls = LegendManage.createLegendScheme(a.min(), a.max(), cmap) ls = ls.convertTo(ShapeTypes.Polygon) edge = kwargs.pop('edge', None) if edge is None: kwargs['edge'] = False else: kwargs['edge'] = edge plotutil.setlegendscheme(ls, **kwargs) smooth = kwargs.pop('smooth', True) zdir = kwargs.pop('zdir', 'z') if zdir == 'xy': sepoint = kwargs.pop('sepoint', [0, 0, 1, 1]) igraphic = GraphicFactory.createContourPolygons(x._array, y._array, a._array, offset, zdir, ls, smooth, \ sepoint) else: igraphic = GraphicFactory.createContourPolygons( x._array, y._array, a._array, offset, zdir, ls, smooth) visible = kwargs.pop('visible', True) if visible: self.add_graphic(igraphic) return igraphic