def format_axis(axis, name=None, force=True, recreate=False, format_subaxes=True, nodef=True, mode='warn', **kwargs): """Format a MV2 axis according to its generic name :Params: - **axis**: A :mod:`numpy` or :mod:`MV2` variabe. - **name**: Single or list of generic axis names. It should be one of those listed by :attr:`CF_AXIS_SPECS`.If None, it is guessed with :func:`match_known_axis`. - **force**, optional: Overwrite attributes in all cases. - **nodef**, optional: Remove location specification when it refers to the default location (:attr:`DEFAULT_LOCATION`). - **axes2d_<param>**, optional: <param> is passed to :func:`~vacumm.misc.grid.misc.create_axes2d` for 2D axes. - **recreate**, optional: Force recreation of axes using either - Other parameters are passed as attributes. :Examples: >>> axis1d = format_axis(array1d, 'lon') >>> axis2d = format_axis(array2d, 'lon_u', axes2d_iid = 'xi', axes2d_jid = 'xi', recreate=True) """ # Guess best generic name from a list if name is None: return axis if isinstance(name, (list, tuple)): for nm in name: if match_obj(axis, nm): name = nm break # Check specs if name is None: # guess it name = match_known_axis(axis) if not name: if mode == 'warn': warn("Can't guess CF axis name") return axis elif mode == 'silent': return axis else: raise KeyError("Variable does not match any CF axis") elif name not in CF_AXIS_SPECS: if mode == 'warn': warn("Generic axis name not found '%s'." % name) return axis elif mode == 'silent': return axis else: raise KeyError( "Generic axis name not found '%s'. Please choose one of: %s" % (name, ', '.join(CF_AXIS_SPECS.keys()))) specs = CF_AXIS_SPECS[name] # - merge kwargs and specs for key, val in kwargs.items(): if val is None or key not in specs: continue # Check type if not isinstance(val, list) and isinstance(specs[key], list): val = [val] # Set specs[key] = val del kwargs[key] # Always a MV2 axis (1D or 2D) axis._oldid = axis.id kwaxed2d = kwfilter(kwargs, 'axes2d_') if not isaxis(axis) or recreate: if len(axis.shape) == 1: axis = cdms2.createAxis(axis) else: xy = specs['axis'].lower() kwaxed2d[xy] = axis axis = create_axes2d(**kwaxed2d) return axis axis2d = len(axis.shape) == 2 # Apply specs # - merge kwargs and specs for key, val in kwargs.items(): if val is None or key not in specs: continue # Check type if not isinstance(val, list) and isinstance(specs[key], list): val = [val] # Set specs[key] = val del kwargs[key] # - remove default location if nodef: for att in 'id', 'long_name', 'standard_name': # sname = stype+'s' if att not in specs: continue if get_loc(specs[att], att) == DEFAULT_LOCATION: specs[att] = [no_loc_single(specs[att][0], att)] # - id if force or axis.id.startswith('variable_') or axis.id.startswith('axis_'): axis.id = specs['id'][0] # - attributes for att, val in cf2atts(specs, exclude=['axis'] if axis2d else None, **kwargs).items(): if force or not getattr(axis, att, ''): setattr(axis, att, val) # - store cf name axis._vacumm_cf_name = axis.id # Sub-axes for 2D axes if axis2d and format_subaxes: format_axis(axis.getAxis(-1), specs['iaxis']) format_axis(axis.getAxis(-2), specs['jaxis']) return axis
result.append(('AssertEqual', (coord2slice(lon1d, lon=slice(3, 6)), slice(3, 6, None)))) result.append(('AssertEqual', (coord2slice(lon1d, lat=(6, 8)), slice(0, 10, 1)))) result.append(('AssertEqual', (coord2slice(lon1d, lon=(60, 70)), None))) # Rect grid grid = create_grid((0, 10.), (20, 30.)) result.append(('AssertEqual', (coord2slice(grid, lon=(0., 3.5), lat=slice(3, 5)), (slice(0, 4, 1), slice(3, 5, None), None)))) result.append(('AssertEqual', (coord2slice(grid, lat=(21,21, 'ccb')), (slice(0, 10, 1), slice(1, 2, 1), None)))) # 2D axis lon2d = N.empty((10, 10.)) for i in xrange(10): lon2d[i] = lon1d[:]+i lat2d = N.resize((N.arange(10)+20), (10, 10)).T lon2d, lat2d = create_axes2d(lon2d, lat2d) kw = dict(show=False) plot(lon2d, lat2d, lon2d, 'lon2d', figfiles, figfile, lon=(2, 4), **kw) plot(lon2d, lat2d, lon2d, 'lon2d', figfiles, figfile, lon=(2, 4), lat=slice(0, 2), **kw) plot(lon2d, lat2d, lat2d, 'lat2d', figfiles, figfile, lat=(22, 26.6,'ccb'), **kw) # Curv grid grid = create_grid(lon2d, lat2d) plot(lon2d, lat2d, grid, 'grid', figfiles, figfile, lon=(8, 11, 'cc'), lat=(21.9, 26., 'cc'), **kw) plot(lon2d, lat2d, grid, 'grid', figfiles, figfile, lon=slice(2, 5), lat=(23.4, 23.6, 'ccb'), **kw) res = coord2slice(grid,lon=(8,8,'ccb'),lat=(24,24,'ccb')) result.append(('AssertEqual', (res[:2], (slice(3, 6, 1), slice(4, 5, 1))))) result.append(('AssertEqual', (coord2slice(grid,lon=(8,8,'ccb'),lat=(24,24,'ccb'), mode='a').tolist(), [[4, 4, 4], [3, 4, 5]])))
def format_axis(axis, name, force=True, recreate=False, format_subaxes=True, nodef=True, **kwargs): """Format a MV2 axis according to its generic name :Params: - **var**: A :mod:`numpy` or :mod:`MV2` variabe. - **name**: Single or list of generic axis names. It should be one of those listed by :attr:`GENERIC_AXIS_NAMES`. - **force**, optional: Overwrite attributes in all cases. - **nodef**, optional: Remove location specification when it refers to the default location (:attr:`DEFAULT_LOCATION`). - **axes2d_<param>**, optional: <param> is passed to :func:`~vacumm.misc.grid.misc.create_axes2d` for 2D axes. - **recreate**, optional: Force recreation of axes using either - Other parameters are passed as attributes. :Examples: >>> axis1d = format_axis(array1d, 'lon') >>> axis2d = format_axis(array2d, 'lon_u', axes2d_iid = 'xi', axes2d_jid = 'xi', recreate=True) """ # Guess best generic name from a list if name is None: return axis if isinstance(name, (list, tuple)): for nm in name: if match_obj(axis, nm): name = nm break # Check specs if name not in GENERIC_AXIS_NAMES: raise KeyError("Generic axis name not found '%s'. Please choose one of: %s"%( name, ', '.join(GENERIC_AXIS_NAMES))) specs = AXIS_SPECS[name] # - merge kwargs and specs for key, val in kwargs.items(): if val is None or key not in specs: continue # Check type if not isinstance(val, list) and isinstance(specs[key], list): val = [val] # Set specs[key] = val del kwargs[key] # Always a MV2 axis (1D or 2D) axis._oldid = axis.id kwaxed2d = kwfilter(kwargs, 'axes2d_') if not isaxis(axis) or recreate: if len(axis.shape)==1: axis = cdms2.create_axis(axis) else: xy = specs['axis'].lower() kwaxed2d[xy] = axis axis = create_axes2d(**kwaxed2d) return axis axis2d = len(axis.shape)==2 # Apply specs # - merge kwargs and specs for key, val in kwargs.items(): if val is None or key not in specs: continue # Check type if not isinstance(val, list) and isinstance(specs[key], list): val = [val] # Set specs[key] = val del kwargs[key] # - remove default location if nodef: for stype in 'name', 'long_name', 'standard_name': sname = stype+'s' if sname not in specs: continue if get_loc(specs[sname], stype)==DEFAULT_LOCATION: specs[sname] = [no_loc_single(specs[sname][0], stype)] # - id if force or axis.id.startswith('variable_') or axis.id.startswith('axis_'): axis.id = specs['names'][0] # - attributes for att, val in cf2atts(specs, exclude=['axis'] if axis2d else None, **kwargs).items(): if force or not getattr(axis, att, ''): setattr(axis, att, val) # - store cf name axis._vacumm_cf_name = axis.id # Sub-axes for 2D axes if axis2d and format_subaxes: format_axis(axis.getAxis(-1), specs['iaxis'][0]) format_axis(axis.getAxis(-2), specs['jaxis'][0]) return axis