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

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

First major re-factor.

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"""
6general.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(naDict):
36    """
37    Function to choose the appropriate FFI based on the contents of the
38    'naDict' dictionary object that holds NASA Ames internal variables.
39    """
40    d = naDict
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 openNAFile(filename, mode="r", naDict=None, spacer="    ", floatFormat="%8.3f"):
80    """
81    Function wrapper around the NASA Ames File classes. Any NASA Ames
82    file can be opened through this function and the appropriate read or
83    write NASA Ames File class instance is returned.
84    """
85    if mode == "r":
86        ffi = readFFI(filename)
87        return apply(getNAFileClass(ffi), (filename, mode))
88
89    elif mode == "w":
90        if naDict.has_key('FFI') and type(naDict['FFI']) == type(3):
91            ffi = naDict['FFI']
92        else:
93            ffi = chooseFFI(naDict)
94            naDict['FFI'] = ffi
95            print "\nFormat identified as:", ffi   
96        return apply(getNAFileClass(ffi), (filename,), {"mode":mode, "naDict":naDict, "spacer":spacer, "floatFormat":floatFormat})
97    else:
98        raise Exception("File mode not recognised '" + mode + "'.")
99   
100
101def getVersion():
102    """
103    Gets config dict for version.
104    """
105    version = nappy.utils.parse_config.getConfigDict()["DEFAULT"]["version"]
106    return version
Note: See TracBrowser for help on using the repository browser.