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

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

Brand new API but not yet fixed to work.

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 getFileNameWithNewExtension(input_file, format):
80    """
81    Takes an input_file name and applies new extension to it by:
82    (i) replacing initial extension if there is one, OR
83    (ii) just appending new extension.
84    """
85    base_name = input_file
86    last_four = base_name[-4:]
87    found = last_four.find(".")
88    if found > -1:
89        idx = len(base_name) + found
90        base_name = base_name[:idx]
91    return base_name + "." + format
92
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 = nappy.utils.parse_config.getConfigDict()["main"]["version"]
120    return version
121
122def getDebug():
123    """
124    Returns true or false for DEBUG status.
125    """
126    DEBUG = nappy.utils.parse_config.getConfigDict()["main"]["DEBUG"]
127    return eval(DEBUG)
128
129
130def makeDictFromCommaSepString(s):
131    """
132    Reads in comma-separated list and converts to dictionary of successive
133    keyword,value pairs.
134    """
135    if s.count(",") % 2 == 0:
136        raise Exception("Must provide even number of items in argument of commas-separated pairs of values: " + s)
137
138    d = {}
139    items = value.split(",")
140    while len(items) > 0:
141        d[items[0]] = items[1]
142        items = items[2:] 
143    return d
144
145def getAnnotation(item, annotation, delimiter = ',   '):
146    """
147    Returns the annotation string for a given NASA Ames item.
148    """
149   
150    dict = nappy.utils.parse_config.getAnnotationsConfigDict()
151    if annotation: return dict[item] + delimiter
152    else: return ''
153
154def annotateLines(item_name, annotate, delimiter, lines):
155    """
156    Takes item_name to look up, delimiter and item to render and returns full line.
157    """
158
159    #print "Incoming lines are", lines
160    split_lines = lines.splitlines(1)
161    output = ""
162    for line in split_lines:
163        output = output + annotateLine(item_name, annotate, delimiter, line)
164
165    #print "Outgoing lines are", output
166    return output
167   
168def annotateLine(item_name, annotate, delimiter, line):
169    """
170    Takes item_name to look up, delimiter and item to render and returns full line.
171    """
172
173    if annotate:
174        annotation = getAnnotation(item_name, annotate, delimiter = delimiter)
175        line = "%s%s" % (annotation, line)
176        return line
177    else:
178        return line
Note: See TracBrowser for help on using the repository browser.