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

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

More fixes to nappy to get all DCIP stuff writing properly.

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 cdms2 as cdms
30    import numpy as N
31except:
32    try:
33        import cdms
34        import Numeric as N
35    except:
36        raise Exception("Could not import third-party software. Nappy requires the CDMS and Numeric packages to be installed to convert to CDMS and NetCDF.")
37
38cdms.setAutoBounds("off") 
39
40# Define global variables
41var_limit = 5000 # surely never going to get this many vars in a file!
42
43DEBUG = nappy.utils.getDebug() 
44
45class CDMSToNA:
46    """
47    Converts CDMS objects to NASA Ames file dictionaries.
48    """
49
50    def __init__(self, cdms_variables, global_attributes=[], na_items_to_override={}, 
51                 only_return_file_names=False, requested_ffi=None,
52                 ):
53        """
54        Sets up instance variables.     
55        """
56        self.cdms_variables = cdms_variables
57        self.global_attributes = global_attributes
58        self.na_items_to_override = na_items_to_override
59        self.only_return_file_names = only_return_file_names
60        self.requested_ffi = requested_ffi
61
62        self.converted = False
63        self.output_message = []
64   
65    def convert(self):
66        """
67        Reads the CDMS objects and convert to a set of dictionaries that
68        provide the structure for a NA File object.
69        Returns [(na_dict, var_ids), (na_dict, var_ids), ....]
70        All these na_dict dictionaries can be readily written to a NA File object.
71
72        Note that NASA Ames is not as flexible as NetCDF so you cannot just send any
73        set of variables to write to a NASA Ames file. Essentially there is one
74        multi-dimensional structure and all variables must be defined against it.
75
76        Otherwise variables must be auxiliary variables within that structure (i.e. only
77        defined once per the least changing dimension.
78        """
79        if self.converted == True:
80            return self.na_dict_list
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 list
89        collector = nappy.nc_interface.na_content_collector.NAContentCollector(variables, 
90                                        self.global_attributes, requested_ffi=self.requested_ffi,
91                                        )
92        collector.collectNAContent()
93
94        # Return if no files returned
95        if collector.found_na == False:
96            msg = "\nNo files created after variables parsed."
97            if DEBUG: print msg
98            self.output_message.append(msg)
99            return
100
101        # NOTE: collector has attributes: na_dict, var_ids, unused_vars
102
103        # Set up a list to collect multiple calls to content collector
104        na_dict_list = []
105        na_dict_list.append((collector.na_dict, collector.var_ids))
106
107        # If there are variables that were not captured (i.e. unused) by NAContentCollector then loop through these
108        # in attempt to convert all to a set of na_dicts
109        print "\n\nUNUSED VARS:", collector.unused_vars
110        while len(collector.unused_vars) > 0:
111            collector = nappy.nc_interface.na_content_collector.NAContentCollector(collector.unused_vars, 
112                                        self.global_attributes, requested_ffi=self.requested_ffi,
113                                        )
114            collector.collectNAContent()           
115            self.output_message += collector.output_message
116
117            # Append to list if more variables were captured
118            if collector.found_na == True: 
119                na_dict_list.append((collector.na_dict, collector.var_ids))
120
121        self.na_dict_list = na_dict_list
122        self.converted = True
123
124        return self.na_dict_list
125
126    def _convertSingletonVars(self, variables):
127        """
128        Loops through variables to convert singleton variables (i.e. Masked Arrays/Numeric Arrays)
129        to proper CDMS variables. Then code won't break when asking for rank attribute later.
130        Returns a list of CDMS variable objects
131        """
132        vars = []
133
134        for variable in variables:
135            var_obj = variable
136
137            # If singleton variable then convert into proper CDMS variables so code doesn't break later
138            if not hasattr(var_obj, "rank"):
139                var_metadata = var_obj.attributes       
140                var_value = var_obj
141                var_obj = cdms.createVariable(N.array(var_obj), 
142                id=nappy.cdms_utils.var_utils.getBestName(var_metadata).replace(" ", "_"), 
143                                   attributes=var_metadata)
144                var_obj.value = var_obj._data[0]                 
145               
146            vars.append(var_obj)
147
148        return vars
149
150    def _reorderVars(self, variables):
151        """
152        Returns a reordered list of variables. Any that have the attribute
153        "nasa_ames_var_number" get ordered first in the list (according to numbering).
154        """
155        # Set up a long list (longer than number of vars)
156        if len(variables) > var_limit:
157            raise Exception("Can only handle converting less than " + `var_limit` + " variables in any batch.")
158
159        # Collect up those that are ordered and unordered
160        ordered_vars = [None] * var_limit
161        unordered_vars = []
162        for var in variables:
163            var_metadata = var.attributes
164            if hasattr(var_metadata, "nasa_ames_var_number"):
165                num = var_metadata.nasa_ames_var_number
166                ordered_vars[num] = var
167            else:
168                unordered_vars.append(var)
169   
170        vars = []
171        # Clear any None values in ordered_vars and place in final vars list
172        for var in ordered_vars + unordered_vars:
173            if var != None: vars.append(var)
174           
175        return vars
176
Note: See TracBrowser for help on using the repository browser.