source: nappy/branches/nappy-eggable/nappy/utils/common_utils.py @ 5138

Subversion URL: http://proj.badc.rl.ac.uk/svn/ndg/nappy/branches/nappy-eggable/nappy/utils/common_utils.py@5138
Revision 5138, 6.3 KB checked in by spascoe, 11 years ago (diff)

Merging changes in the nappy package from trunk

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 parse_config
15
16
17def getNAFileClass(ffi):
18    """
19    Returns class for an FFI.
20    """
21    mod = "nappy.na_file.na_file_" + `ffi`
22    cls = "NAFile" + `ffi`
23    exec "import %s" % mod
24    return eval("%s.%s" % (mod, cls))
25   
26
27def readFFI(filename):
28    """
29    Function to read the top line of a NASA Ames file to extract
30    the File Format Index (FFI) and return it as an integer.
31    """
32    topline = open(filename).readline()
33    return int(topline.split()[-1])
34
35
36def chooseFFI(na_dict):
37    """
38    Function to choose the appropriate FFI based on the contents of the
39    'na_dict' dictionary object that holds NASA Ames internal variables.
40    """
41    d = na_dict
42
43    if d["NIV"] > 4:      # More than 4 independent variables not allowed
44        raise Exception("NASA Ames cannot write more than 4 independent variables.")
45
46    elif d["NIV"] == 4:     # 4 independent variables
47        return 4010
48
49    elif d["NIV"] == 3:     # 3 independent variables
50        return 3010
51
52    elif d["NIV"] == 2:    # 2 independent variables
53        if type(d["X"][0][0]) == type("string"):
54            # 2160 - the  independent unbounded variable is a character string
55            return 2160
56        elif type(d["X"][0][1]) == type([1,2]) and len(d["X"][0][1]) > 1:
57            # 2110 - one independent variable changes length and the values are specified
58            return 2110
59        elif type(d["X"][0][1]) == type([1,2]) and len(d["X"][0][1]) == 1:
60            # 2310 - one indepenent variable changes length but only the first value is specifically stated
61            return 2310
62        else:           
63            # 2010 - Straightforward 2-D variables
64            return 2010
65
66    elif d["NIV"] == 1:   # 1 independent variable
67        if not d.has_key("NAUXV"):
68            # 1001 - No auxiliary variables
69            return 1001
70        elif d.has_key("NVPM"):
71            # 1020 - Implied values for independent variable
72            return 1020
73        else:
74            # 1010 - Auxiliary variables included
75            return 1010
76    else:
77        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.")
78
79
80def getFileNameWithNewExtension(input_file, format):
81    """
82    Takes an input_file name and applies new extension to it by:
83    (i) replacing initial extension if there is one, OR
84    (ii) just appending new extension.
85    """
86    base_name = input_file
87    last_four = base_name[-4:]
88    found = last_four.find(".")
89    if found > -1:
90        idx = len(base_name) + found
91        base_name = base_name[:idx]
92    return base_name + "." + format
93
94
95def modifyNADictCopy(indict, v_new, start, end, ivol, nvol):
96    """
97    Returns a copy of a dictionary with some modifications.
98    """
99    newDict = {}
100    for key,value in indict.items(): 
101        if key == "X":
102            newlist = indict["X"][start:end]
103            newDict["X"] = newlist
104        elif key == "V":
105            newDict["V"] = v_new
106        elif key == "IVOL":
107            newDict["IVOL"] = ivol
108        elif key == "NVOL":
109            newDict["NVOL"] = nvol
110        else:
111            newDict[key] = value
112    return newDict
113
114
115def getVersion():
116    """
117    Gets config dict for version.
118    """
119    version = parse_config.getConfigDict()["main"]["version"]
120    return version
121
122
123def getDebug():
124    """
125    Returns true or false for DEBUG status.
126    """
127    DEBUG = parse_config.getConfigDict()["main"]["DEBUG"]
128    return eval(DEBUG)
129
130
131def getDefault(item):
132    """
133    Returns value of item from 'main' config file section.
134    """
135    value =  parse_config.getConfigDict()["main"][item]
136    return value
137
138
139def makeDictFromCommaSepString(s):
140    """
141    Reads in comma-separated list and converts to dictionary of successive
142    keyword,value pairs.
143    """
144    if s.count(",") % 2 == 0:
145        raise Exception("Must provide even number of items in argument of commas-separated pairs of values: " + s)
146
147    d = {}
148    items = s.split(",")
149    while len(items) > 0:
150        d[items[0]] = items[1]
151        items = items[2:] 
152    return d
153
154
155def makeListFromCommaSepString(s):
156    """
157    Reads in comma-separated list and converts to list of successive
158    keyword,value pairs.
159    """
160    if s.count(",") % 2 == 0:
161        raise Exception("Must provide even number of items in argument of commas-separated pairs of values: " + s)
162
163    l = []
164    items = s.split(",")
165    while len(items) > 0:
166        l.append((items[0], items[1]))
167        items = items[2:]
168    return l
169
170
171def getAnnotation(item, annotation, delimiter=None, count=None):
172    """
173    Returns the annotation string for a given NASA Ames item.
174    """
175    if delimiter == None:
176        delimiter = getDefault("default_delimiter") 
177    dict = parse_config.getAnnotationsConfigDict()
178
179    if count == None:
180        count_string = ""
181    else:
182        count_string = " %s" % count
183   
184    if annotation:
185        return "%s%s%s" % (dict[item], count_string, delimiter)
186    else:
187        return ""
188#    if annotation: return dict[item] + delimiter
189#    else: return ''
190
191
192def annotateLines(item_name, annotate, delimiter, lines):
193    """
194    Takes item_name to look up, delimiter and item to render and returns full line.
195    """
196
197    #print "Incoming lines are", lines
198    split_lines = lines.splitlines(1)
199    output = ""
200
201    count = 1
202    for line in split_lines:
203        output = output + annotateLine(item_name, annotate, delimiter, line, count)
204        count += 1
205
206    #print "Outgoing lines are", output
207    return output
208
209   
210def annotateLine(item_name, annotate, delimiter, line, count=None):
211    """
212    Takes item_name to look up, delimiter and item to render and returns full line.
213    """
214
215    if annotate:
216        annotation = getAnnotation(item_name, annotate, delimiter=delimiter, count=count)
217        line = "%s%s" % (annotation, line)
218        return line
219    else:
220        return line
221
222
223def stripQuotes(s):
224    "Strips extra quotes"
225    if type(s) != type("string"): s  = str(s)
226    if s[0] in ("'", '"'): s = s[1:]
227    if s[-1] in ("'", '"'): s = s[:-1]
228    return s
Note: See TracBrowser for help on using the repository browser.