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

Subversion URL: http://proj.badc.rl.ac.uk/svn/ndg/nappy/trunk/nappy/utils/common_utils.py@5369
Revision 5369, 6.3 KB checked in by astephen, 11 years ago (diff)

replaced prints

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