source: nappy/trunk/nappy/utils/common_utils.py @ 3519

Subversion URL: http://proj.badc.rl.ac.uk/svn/ndg/nappy/trunk/nappy/utils/common_utils.py@3519
Revision 3519, 6.2 KB checked in by ckilburn, 12 years ago (diff)

Annotation

Line 
1#    Copyright (C) 2004 CCLRC & NERC( Natural Environment Research Council ).
2#    This software may be distributed under the terms of the
3#    Q Public License, version 1.0 or later. http://ndg.nerc.ac.uk/public_docs/QPublic_license.txt
4
5"""
6common_utils.py
7===============
8
9Functions and classes commonly used in nappy.
10
11"""
12
13# Imports from local package
14import nappy.utils.parse_config
15
16def getNAFileClass(ffi):
17    """
18    Returns class for an FFI.
19    """
20    mod = "nappy.na_file.na_file_" + `ffi`
21    cls = "NAFile" + `ffi`
22    exec "import %s" % mod
23    return eval("%s.%s" % (mod, cls))
24   
25
26def readFFI(filename):
27    """
28    Function to read the top line of a NASA Ames file to extract
29    the File Format Index (FFI) and return it as an integer.
30    """
31    topline = open(filename).readline()
32    return int(topline.split()[-1])
33
34
35def chooseFFI(na_dict):
36    """
37    Function to choose the appropriate FFI based on the contents of the
38    'na_dict' dictionary object that holds NASA Ames internal variables.
39    """
40    d = na_dict
41
42    if d["NIV"] > 4:      # More than 4 independent variables not allowed
43        raise Exception("NASA Ames cannot write more than 4 independent variables.")
44
45    elif d["NIV"] == 4:     # 4 independent variables
46        return 4010
47
48    elif d["NIV"] == 3:     # 3 independent variables
49        return 3010
50
51    elif d["NIV"] == 2:    # 2 independent variables
52        if type(d["X"][0][0]) == type("string"):
53            # 2160 - the  independent unbounded variable is a character string
54            return 2160
55        elif type(d["X"][0][1]) == type([1,2]) and len(d["X"][0][1]) > 1:
56            # 2110 - one independent variable changes length and the values are specified
57            return 2110
58        elif type(d["X"][0][1]) == type([1,2]) and len(d["X"][0][1]) == 1:
59            # 2310 - one indepenent variable changes length but only the first value is specifically stated
60            return 2310
61        else:           
62            # 2010 - Straightforward 2-D variables
63            return 2010
64
65    elif d["NIV"] == 1:   # 1 independent variable
66        if not d.has_key("NAUXV"):
67            # 1001 - No auxiliary variables
68            return 1001
69        elif d.has_key("NVPM"):
70            # 1020 - Implied values for independent variable
71            return 1020
72        else:
73            # 1010 - Auxiliary variables included
74            return 1010
75    else:
76        raise Exception("Could not resolve the dictionary object to create a suitable NASA Ames File Format Index (FFI). Please modify the contents and try again.")
77   
78
79def modifyNADictCopy(indict, v_new, start, end, ivol, nvol):
80    """
81    Returns a copy of a dictionary with some modifications.
82    """
83    newDict = {}
84    for key,value in indict.items(): 
85        if key == "X":
86            newlist = indict["X"][start:end]
87            newDict["X"] = newlist
88        elif key == "V":
89            newDict["V"] = v_new
90        elif key == "IVOL":
91            newDict["IVOL"] = ivol
92        elif key == "NVOL":
93            newDict["NVOL"] = nvol
94        else:
95            newDict[key] = value
96    return newDict
97
98
99def getVersion():
100    """
101    Gets config dict for version.
102    """
103    version = nappy.utils.parse_config.getConfigDict()["main"]["version"]
104    return version
105
106def getDebug():
107    """
108    Returns true or false for DEBUG status.
109    """
110    DEBUG = nappy.utils.parse_config.getConfigDict()["main"]["DEBUG"]
111    return eval(DEBUG)
112
113
114def makeDictFromCommaSepString(s):
115    """
116    Reads in comma-separated list and converts to dictionary of successive
117    keyword,value pairs.
118    """
119    if s.count(",") % 2 == 0:
120        raise Exception("Must provide even number of items in argument of commas-separated pairs of values: " + s)
121
122    d = {}
123    items = value.split(",")
124    while len(items) > 0:
125        d[items[0]] = items[1]
126        items = items[2:] 
127    return d
128
129def getAnnotation(item, annotation, delimiter = ',   '):
130    """
131    Returns the annotation string for a given NASA Ames item.
132    """
133
134    dict = {"NLHEAD_FFI" : "Number of header lines and NASA Ames sub-format code",
135            "ONAME" : "Name of data creator",
136            "ORG" : "Institute of data creator",
137            "SNAME" : "Instrument or model",
138            "MNAME" : "Project name",
139            "IVOL_NVOL" : "Volume number and total number of files",
140            "DATE_RDATE" : "Starting data of data and file creation date",
141            "DX" : "Interval between coordinate variable values (zero if not used)",
142            "XNAME" : "Name of coordinate variable [i.e. axis] (with units)",
143            "NV" : "Number of variables at each point (i.e. defined against both axes)",
144            "VSCAL" : "Scaling factors for each variable",
145            "VMISS" : "Missing values for each variable",
146            "VNAME" : "Name of variable (with units)",
147            "NAUXV" : "Number of auxiliary variables (variables defined with one value)",
148            "ASCAL" : "Scale factors for each auxiliary variable",
149            "AMISS" : "Missing values for each auxiliary variable",
150            "ANAME" : "Name of auxiliary variable [long name in square brackets] (with units)",
151            "NSCOML" : "Number of lines of special comments",
152            "SCOM" : "Special comments line",
153            "NNCOML" : "Number of lines of normal comments",
154            "NCOM" : "Normal comments line",
155            "Data" : "Data",
156            }
157
158    dict = nappy.utils.parse_config.getAnnotationsConfigDict()
159    if annotation: return dict[item] + delimiter
160    else: return ''
161
162def annotateLines(item_name, annotate, delimiter, lines):
163    """
164    Takes item_name to look up, delimiter and item to render and returns full line.
165    """
166
167    print "Incoming lines are", lines
168    split_lines = lines.splitlines(1)
169    output = ""
170    for line in split_lines:
171        output = output + annotateLine(item_name, annotate, delimiter, line)
172
173    print "Outgoing lines are", output
174    return output
175   
176def annotateLine(item_name, annotate, delimiter, line):
177    """
178    Takes item_name to look up, delimiter and item to render and returns full line.
179    """
180
181    if annotate:
182        annotation = getAnnotation(item_name, annotate, delimiter = delimiter)
183        line = "%s%s" % (annotation, line)
184        return line
185    else:
186        return line
Note: See TracBrowser for help on using the repository browser.