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

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

Added in right-stripping of any annotations included in curly braces "{...}" on the
end of any input lines in NASA Ames.

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