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

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

Cleaned up some of the data files and improved unit tests and comparison code.

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   
95
96def modifyNADictCopy(indict, v_new, start, end, ivol, nvol):
97    """
98    Returns a copy of a dictionary with some modifications.
99    """
100    newDict = {}
101    for key,value in indict.items(): 
102        if key == "X":
103            newlist = indict["X"][start:end]
104            newDict["X"] = newlist
105        elif key == "V":
106            newDict["V"] = v_new
107        elif key == "IVOL":
108            newDict["IVOL"] = ivol
109        elif key == "NVOL":
110            newDict["NVOL"] = nvol
111        else:
112            newDict[key] = value
113    return newDict
114
115
116def getVersion():
117    """
118    Gets config dict for version.
119    """
120    version = parse_config.getConfigDict()["main"]["version"]
121    return version
122
123
124def getDebug():
125    """
126    Returns true or false for DEBUG status.
127    """
128    DEBUG = parse_config.getConfigDict()["main"]["DEBUG"]
129    return eval(DEBUG)
130
131
132def makeDictFromCommaSepString(s):
133    """
134    Reads in comma-separated list and converts to dictionary of successive
135    keyword,value pairs.
136    """
137    if s.count(",") % 2 == 0:
138        raise Exception("Must provide even number of items in argument of commas-separated pairs of values: " + s)
139
140    d = {}
141    items = value.split(",")
142    while len(items) > 0:
143        d[items[0]] = items[1]
144        items = items[2:] 
145    return d
146
147def getAnnotation(item, annotation, delimiter = ',   '):
148    """
149    Returns the annotation string for a given NASA Ames item.
150    """
151   
152    dict = parse_config.getAnnotationsConfigDict()
153    if annotation: return dict[item] + delimiter
154    else: return ''
155
156def annotateLines(item_name, annotate, delimiter, lines):
157    """
158    Takes item_name to look up, delimiter and item to render and returns full line.
159    """
160
161    #print "Incoming lines are", lines
162    split_lines = lines.splitlines(1)
163    output = ""
164    for line in split_lines:
165        output = output + annotateLine(item_name, annotate, delimiter, line)
166
167    #print "Outgoing lines are", output
168    return output
169   
170def annotateLine(item_name, annotate, delimiter, line):
171    """
172    Takes item_name to look up, delimiter and item to render and returns full line.
173    """
174
175    if annotate:
176        annotation = getAnnotation(item_name, annotate, delimiter = delimiter)
177        line = "%s%s" % (annotation, line)
178        return line
179    else:
180        return line
Note: See TracBrowser for help on using the repository browser.