source: nappy/trunk/nappy/nc_interface/cdms_to_na.py @ 3405

Subversion URL: http://proj.badc.rl.ac.uk/svn/ndg/nappy/trunk/nappy/nc_interface/cdms_to_na.py@3405
Revision 3405, 6.6 KB checked in by astephen, 12 years ago (diff)

Got some of the code actually working!

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"""
6cdms_to_na.py
7=============
8
9Holds the class CDMSToNA that converts a set of CDMS variables and global attributes.
10
11"""
12
13# Imports from python standard library
14import sys
15
16# Import from nappy package
17import nappy
18from nappy.na_error import na_error
19import nappy.utils
20import nappy.utils.common_utils
21import nappy.cdms_utils.var_utils
22import nappy.na_file.na_core
23import nappy.nc_interface.na_content_collector
24
25# Import external packages (if available)
26if sys.platform.find("win") > -1:
27    raise na_error.NAPlatformError("Windows does not support CDMS. CDMS is required to convert to CDMS objects and NetCDF.")
28try:
29    import cdms, Numeric
30except:
31    raise Exception("Could not import third-party software. Nappy requires the CDMS and Numeric packages to be installed to convert to CDMS and NetCDF.")
32
33cdms.setAutoBounds("off") 
34
35# Define global variables
36permitted_overwrite_metadata = ("DATE",  "RDATE", "ANAME", "MNAME",
37           "ONAME", "ORG", "SNAME", "VNAME")
38items_as_lists = ["DATE", "RDATE", "ANAME", "VNAME"]
39var_limit = 5000 # surely never going to get this many vars in a file!
40
41DEBUG = nappy.utils.getDebug() 
42
43class CDMSToNA:
44    """
45    Converts CDMS objects to NASA Ames file dictionaries.
46    """
47
48    def __init__(self, cdms_variables, global_atts={}, na_items_to_override={}, 
49                 only_return_file_names=False):
50        """
51        Sets up instance variables.     
52        """
53        self.cdms_variables = cdms_variables
54        self.global_atts = global_atts
55        self.na_items_to_override = na_items_to_override
56        self.only_return_file_names = only_return_file_names
57        self.converted = False
58        self.output_message = []
59   
60    def convert(self):
61        """
62        Reads the CDMS objects and convert to a set of dictionaries that
63        provide the structure for a NA File object.
64        Returns [(na_dict, var_ids), (na_dict, var_ids), ....]
65        All these na_dict dictionaries can be readily written to a NA File object.
66
67        Note that NASA Ames is not as flexible as NetCDF so you cannot just send any
68        set of variables to write to a NASA Ames file. Essentially there is one
69        multi-dimensional structure and all variables must be defined against it.
70
71        Otherwise variables must be auxiliary variables within that structure (i.e. only
72        defined once per the least changing dimension.
73        """
74        if self.converted == True:
75            print "Already converted to NA dictionary objects."
76            return self.na_dict_list
77       
78        msg = "Reading data from: %s\n" % self.nc_file
79        if DEBUG: print msg
80        self.output_message.append(msg)
81
82        # Convert any singleton variables to CDMS variables
83        variables = self._convertSingletonVars(self.cdms_variables)
84
85        # Re-order variables if they have the attribute "nasa_ames_var_number" which means they came from a NASA Ames file originally
86        variables = self._reorderVars(variables)
87
88        # Make first call to collector class that creates NA dict from CDMS variables and global atts dicts
89        collector = NAContentCollector(variables, self.global_atts)
90        collected_dict = collector.collectNAContent()
91        # NOTE: collected_dict has attributes: na_dict, var_ids, unused_vars
92
93        # Return if no files returned
94        if collected.var_ids == None:
95            msg = "\nNo files created after variables parsed."
96            if DEBUG: print msg
97            self.output_message.append(msg)
98            return 
99
100        # Set up a list to collect multiple calls to content collector
101        na_dict_list = []
102        na_dict_list.append((collected_dict.na_dict, collected_dict.var_ids))
103
104        # If there are variables that were not captured (i.e. unused) by NAContentCollector then loop through these
105        # in attempt to convert all to a set of na_dicts
106        while len(collector.unused_vars) > 0:
107            collector = NAContentCollector(collector.unused_vars, self.global_atts)
108            collected_dict = collector.collectNAContent()           
109            self.output_message += collector.output_message
110            # Append to list if more variables were captured
111            if collector.var_ids != None: 
112                na_dict_list.append((collected_dict.na_dict, collected_dict.var_ids))
113
114        self.na_dict_list = na_dict_list
115        self.converted = True
116        return self.na_dict_list
117
118    def _convertSingletonVars(self, variables):
119        """
120        Loops through variables to convert singleton variables (i.e. Masked Arrays/Numeric Arrays)
121        to proper CDMS variables. Then code won't break when asking for rank attribute later.
122        Returns a list of CDMS variable objects
123        """
124        vars = []
125
126        for variable in variables:
127            var_obj = variable
128
129            # If singleton variable then convert into proper CDMS variables so code doesn't break later
130            if not hasattr(var_obj, "rank"):
131                var_metadata = var_obj.attributes       
132                var_value = var_obj
133                var_obj = cdms.createVariable(Numeric.array(var_obj), 
134                id=nappy.cdms_utils.var_utils.getBestName(var_metadata).replace(" ", "_"), 
135                                   attributes=var_metadata)
136                var_obj.value = var_obj._data[0]                 
137               
138            vars.append(var_obj)
139            return vars
140
141    def _reorderVars(self, variables):
142        """
143        Returns a reordered list of variables. Any that have the attribute
144        "nasa_ames_var_number" get ordered first in the list (according to numbering).
145        """
146        # Set up a long list (longer than number of vars)
147        if len(variables) > var_limit:
148            raise Exception("Can only handle converting less than " + `var_limit` + " variables in any batch.")
149
150        # Collect up those that are ordered and unordered
151        ordered_vars = [None] * var_limit
152        unordered_vars = []
153        for var in variables:
154            var_metadata = var.attributes
155            if hasattr(var_metadata, "nasa_ames_var_number"):
156                num = var_metadata.nasa_ames_var_number
157                ordered_vars[num] = var
158            else:
159                unordered_vars.append(var)
160   
161        vars = []
162        # Clear any None values in ordered_vars and place in final vars list
163        for var in ordered_vars + unordered_vars:
164            if var != None: vars.append(var)
165           
166        return vars
167
Note: See TracBrowser for help on using the repository browser.