source: nappy/trunk/nappy/cdms_utils/var_utils.py @ 3331

Subversion URL: http://proj.badc.rl.ac.uk/svn/ndg/nappy/trunk/nappy/cdms_utils/var_utils.py@3349
Revision 3331, 2.3 KB checked in by astephen, 12 years ago (diff)
Line 
1#!/usr/bin/env python
2#   Copyright (C) 2004 CCLRC & NERC( Natural Environment Research Council ).
3#   This software may be distributed under the terms of the
4#   Q Public License, version 1.0 or later. http://ndg.nerc.ac.uk/public_docs/QPublic_license.txt
5
6"""
7var_utils.py
8=============
9
10Holds utilities involving CDMS variable objects.
11
12"""
13
14
15print "MERGE var_utils.py with other parts of cdms_utils in DDP libraries and Theo code"
16
17# Imports from python standard library
18
19# Import external packages
20import cdms
21
22cdms.setAutoBounds("off") 
23
24
25def compareVariables(var1, var2):
26    """
27    Compares two cdms variables to see if they are defined on identical
28    axes. Returns 1 if true, 0 if not.
29    """
30    try:
31        for i in range(len(var1.getAxisList())):
32            ax1 = var1.getAxis(i)
33            ax2 = var2.getAxis(i)       
34            if compareAxes(ax1, ax2) == 0:
35                return 0
36    except:
37        return 0
38    return 1
39
40
41def getBestName(var): 
42    """
43    Returns the most appropriate variable name for a NASA Ames header.
44    """
45    name = None
46    att_order = ("id", "shortname", "name", "title", "standard_name", "long_name")
47    # Deal with object that has attributes
48    for att in att_order:
49        if hasattr(var, att):   name = getattr(var, att)
50   
51    # Deal with object that has dictionary lookup - not sure why we do both
52    if hasattr(var, "has_key"):
53        for att in att_order:
54            if var.has_key(att):   name = var[att]
55
56    if hasattr(var, "units") and not re.match("^\s+$", var.units): 
57        units = var.units.strip()
58        name = "%s (%s)" % (name, units)   
59
60        if name.count("(%s)" % units) > 1:
61            name = name.replace("(%s)" % units, "")
62            name = "%s (%s)" % (name, units)
63       
64    if name[-2:] == "()": name = name[:-2]
65    return name
66
67
68def getMissingValue(var):
69    """
70    Returns the missing value or defaults to 1.E20.
71    """
72    miss = None
73    if hasattr(var, "missing_value"):  miss = var.missing_value
74    if hasattr(var, "_fill_value"):    miss = var._fill_value
75    if hasattr(var, "_FillValue"):     miss = var._FillValue
76
77    if miss == None:
78        try:
79            miss = var.getMissing()
80        except:
81            miss = 1.E20
82
83    return miss
84
85
Note: See TracBrowser for help on using the repository browser.