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

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

Various changes to get DCIP data writing cleanly to CSV files.

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        while len(collector.unused_vars) > 0:
110            collector = nappy.nc_interface.na_content_collector.NAContentCollector(collector.unused_vars, 
111                                        self.global_attributes, requested_ffi=self.requested_ffi,
112                                        )
113            collector.collectNAContent()           
114            self.output_message += collector.output_message
115
116            # Append to list if more variables were captured
117            if collector.found_na == True: 
118                na_dict_list.append((collector.na_dict, collector.var_ids))
119
120        self.na_dict_list = na_dict_list
121        self.converted = True
122
123        return self.na_dict_list
124
125    def _convertSingletonVars(self, variables):
126        """
127        Loops through variables to convert singleton variables (i.e. Masked Arrays/Numeric Arrays)
128        to proper CDMS variables. Then code won't break when asking for rank attribute later.
129        Returns a list of CDMS variable objects
130        """
131        vars = []
132
133        for variable in variables:
134            var_obj = variable
135
136            # If singleton variable then convert into proper CDMS variables so code doesn't break later
137            if not hasattr(var_obj, "rank"):
138                var_metadata = var_obj.attributes       
139                var_value = var_obj
140                var_obj = cdms.createVariable(N.array(var_obj), 
141                id=nappy.cdms_utils.var_utils.getBestName(var_metadata).replace(" ", "_"), 
142                                   attributes=var_metadata)
143                var_obj.value = var_obj._data[0]                 
144               
145            vars.append(var_obj)
146
147        return vars
148
149    def _reorderVars(self, variables):
150        """
151        Returns a reordered list of variables. Any that have the attribute
152        "nasa_ames_var_number" get ordered first in the list (according to numbering).
153        """
154        # Set up a long list (longer than number of vars)
155        if len(variables) > var_limit:
156            raise Exception("Can only handle converting less than " + `var_limit` + " variables in any batch.")
157
158        # Collect up those that are ordered and unordered
159        ordered_vars = [None] * var_limit
160        unordered_vars = []
161        for var in variables:
162            var_metadata = var.attributes
163            if hasattr(var_metadata, "nasa_ames_var_number"):
164                num = var_metadata.nasa_ames_var_number
165                ordered_vars[num] = var
166            else:
167                unordered_vars.append(var)
168   
169        vars = []
170        # Clear any None values in ordered_vars and place in final vars list
171        for var in ordered_vars + unordered_vars:
172            if var != None: vars.append(var)
173           
174        return vars
175
Note: See TracBrowser for help on using the repository browser.