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

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

Fixed defaults for delimiter and float format so read from nappy.ini config file.

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 'mrain' 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 = value.split(",")
149    while len(items) > 0:
150        d[items[0]] = items[1]
151        items = items[2:] 
152    return d
153
154
155def getAnnotation(item, annotation, delimiter=None):
156    """
157    Returns the annotation string for a given NASA Ames item.
158    """
159    if delimiter == None:
160        delimiter = getDefault("default_delimiter") 
161    dict = parse_config.getAnnotationsConfigDict()
162    if annotation: return dict[item] + delimiter
163    else: return ''
164
165
166def annotateLines(item_name, annotate, delimiter, lines):
167    """
168    Takes item_name to look up, delimiter and item to render and returns full line.
169    """
170
171    #print "Incoming lines are", lines
172    split_lines = lines.splitlines(1)
173    output = ""
174    for line in split_lines:
175        output = output + annotateLine(item_name, annotate, delimiter, line)
176
177    #print "Outgoing lines are", output
178    return output
179   
180def annotateLine(item_name, annotate, delimiter, line):
181    """
182    Takes item_name to look up, delimiter and item to render and returns full line.
183    """
184
185    if annotate:
186        annotation = getAnnotation(item_name, annotate, delimiter = delimiter)
187        line = "%s%s" % (annotation, line)
188        return line
189    else:
190        return line
Note: See TracBrowser for help on using the repository browser.