source: nappy/trunk/nappy/nc_interface/na_content_collector.py @ 3351

Subversion URL: http://proj.badc.rl.ac.uk/svn/ndg/nappy/trunk/nappy/nc_interface/na_content_collector.py@3351
Revision 3351, 24.6 KB checked in by astephen, 13 years ago (diff)
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
15import os
16import time
17import string
18import re
19
20# Import from nappy package
21from nappy.na_error import na_error
22import nappy.utils
23import nappy.utils.axis_utils
24import nappy.cdms_utils.var_utils
25import nappy.utils.common_utils
26import nappy.na_file.na_core
27
28nc_to_na_map = utils.getConfigDict()["nc_to_na_map"]
29
30# Import external packages (if available)
31if sys.platform.find("win") > -1:
32    raise na_error.NAPlatformError("Windows does not support CDMS. CDMS is required to convert to CDMS objects and NetCDF.")
33try:
34    import cdms, Numeric
35except:
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
41class NAContentCollector(NACore):
42    """
43    Class to build a NASA Ames File object from a set of
44    CDMS variables and global attributes (optional).
45    """
46   
47    def __init__(self, variables, global_attributes={}):
48        """
49        Sets up instance variables and calls appropriate methods to
50        generate sections of NASA Ames file object.
51
52        Input arguments are:
53          * variables - list/tuple of actual CDMS variables
54          * global_attributes - dictionary of user-defined globals to include.
55
56        Typical usage:
57        >>> x = NAContentCollector(["temp", "precip"])
58        >>> x.collectNAContent()
59        >>> print x.na_dict, x.var_ids, x.unused_vars
60        """
61        self.output_message = []
62        self.na_dict = {}
63        self.vars = variables
64
65        # Note that self.var_ids will be a list containing:
66        #    [ordered_vars,  auxiliary_vars,   rank_zero_vars]
67        self.var_ids = None
68        self.globals = global_attributes       
69        self.rank_zero_vars = []
70        self.rank_zero_var_ids = []
71
72
73    def collectNAContent(self):
74        """
75        Collect NASA Ames content. Save the contents to the following instance
76        attributes:
77         * self.na_dict
78         * self.var_ids
79         * self.unused_vars
80        """
81        (self.ordered_vars, aux_vars) = self._analyseVariables()
82        if self.ordered_vars == None:
83            self.unused_vars = []
84        else:
85            self.var_ids = [[var.id for var in self.ordered_vars],
86                            [var.id for var in aux_vars], 
87                            self.rank_zero_var_ids]
88            self.na_dict["NLHEAD"] = "-999"
89            self._defineNAVars(self.ordered_vars)
90            self._defineNAaux_vars(aux_vars)
91            self._defineNAGlobals()
92            self._defineNAComments()
93            self._defineGeneralHeader()
94            # Quick fudge to cope with 1001 issue
95            if self.na_dict["FFI"] == 1001: 
96                self.na_dict["X"] = self.na_dict["X"][0]
97
98    def analyseVariables(self):
99        """
100        Method to examine the content of CDMS variables to return
101        a tuple of two lists containing variables and auxiliary variables
102        for the NASA Ames file object.
103        Variables not compatible with the first file are put in self.unused_vars
104        """
105        self.unused_vars = []
106
107        highest_rank = -1
108        best_var = None
109        count = 0
110
111        # Need to get highest ranked variable (most dimensions) so that we can work out FFI
112        for var in self.vars:
113            msg = "Analysing: %s" % var.id
114            print msg
115            self.output_message.append(msg)
116            count = count + 1
117            # get rank
118            rank = var.rank()
119
120            # Deal with singleton variables
121            if rank == 0: 
122                self.rank_zero_vars.append(var)
123                self.rank_zero_var_ids.append(var.id)
124                continue
125           
126            # Update highest if highest found or if equals highest with bigger size
127            if rank > highest_rank or (rank == highest_rank and var.size() > best_var.size()):
128                highest_rank = rank
129                best_var = var
130                best_var_index = count
131                print "WARNING WARNING WARNING....CHANGED CODE HERE from len(var.flat) to var.size() which should be quicker!!!"
132
133        # If all are zero ranked variables or no vars identified/found then we cannot write any to NASA Ames and return (None, None)
134        if len(self.rank_zero_vars) == len(self.vars) or best_var == None: 
135            print "No usable variables found." 
136            return (None, None)
137
138        # Now start to sort the variables into main and auxiliary
139        vars_for_na = [best_var]
140        aux_vars_for_na = []
141        shape = best_var.shape
142        number_of_dims = len(shape)
143        self.na_dict["NIV"] = number_of_dims
144        # Get the FFI
145        self.na_dict["FFI"] = self._decideFileFormatIndex(number_of_dims)
146        # Get the axes for the main variable being used
147        best_var_axes = best_var.getAxisList()
148       
149        # Get other variable info
150        rest_of_the_vars = self.vars[:best_var_index - 1] + self.vars[best_var_index:]
151
152        for var in rest_of_the_vars:
153
154            if var.id in self.rank_zero_var_ids: continue
155
156            # What to do with variables that have different number of dimensions or different shape
157            if len(var.shape) != number_of_dims or var.shape != shape: 
158                # Could it be an auxiliary variable?
159                if len(var.shape) != 1: 
160                    self.unused_vars.append(var)
161                    continue
162
163                first_axis = var.getAxis(0)
164
165                if nappy.cdms_utils.axis_utils.areAxesIdentical(best_var_axes[0], first_axis) == False: 
166                    self.unused_vars.append(var)
167                    continue
168
169                # I think it is an auxiliary variable
170                aux_vars_for_na.append(var) 
171                # Also put it in unused var bin because auxiliary vars might be useful later on in there own right
172                self.unused_vars.append(var)
173            else:
174                this_var_axes = var.getAxisList()
175
176                # Loop through dimensions
177                for i in range(number_of_dims):           
178                    if nappy.cdms_utils.axis_utils.areAxesIdentical(best_var_axes[i], this_var_axes[i]) == False:
179                        self.unused_vars.append(var)
180                        continue
181
182                # OK, I think the current variable is compatible to write with the best variable along with a NASA Ames file
183                vars_for_na.append(var)
184               
185        # Send vars_for_na AND aux_vars_for_na to a method to check if they have previously been mapped
186        # from NASA Ames. In which case we'll write them back in the order they were initially read from the input file.
187        (vars_for_na, aux_vars_for_na) = self._reorderVarsIfPreviouslyNA(vars_for_na, aux_vars_for_na)
188        return (vars_for_na, aux_vars_for_na)
189
190
191    def _reorderVarsIfPreviouslyNA(vars_for_na, aux_vars_for_na):
192        """
193        Re-order if they previously came from NASA Ames files (i.e. including the
194        attribute 'nasa_ames_var_number'). Return re-ordered or unchanged pair of
195        (vars_for_na, aux_vars_for_na).
196        """
197        # THIS SHOULD REALLY BE DONE IN A LOOP
198        # First do the main variables
199        ordered_vars = [None] * 1000 # Make a long list to put vars in
200        # Create a list of other variables to collect up any that are not labelled as nasa ames variables
201        other_vars = []
202        for var in vars_for_na:
203            if hasattr(var, "nasa_ames_var_number"):
204                ordered_vars[var.nasa_ames_var_number[0]] = var
205            else:
206                other_vars.append(var)
207
208        # Remake vars_for_na now in new order and clean out any that are "None"
209        vars_for_na = []
210        for var in ordered_vars:
211            if var != None: 
212                vars_for_na.append(var)
213
214        vars_for_na = vars_for_na + other_vars
215
216        # Now re-order the Auxiliary variables if they previously came from NASA
217        ordered_aux_vars = [None] * 1000
218        other_aux_vars = []
219
220        for var in aux_vars_for_na:
221            if hasattr(var, "nasa_ames_aux_var_number"):
222                ordered_aux_vars[var.nasa_ames_aux_var_number[0]] = var
223            else:
224                other_aux_vars.append(var)
225
226        # Remake aux_vars_for_na now in order
227        aux_vars_for_na = []
228        for var in ordered_aux_vars:
229            if var != None: 
230                aux_vars_for_na.append(var)
231
232        aux_vars_for_na = aux_vars_for_na + other_aux_vars     
233        return (vars_for_na, aux_vars_for_na)
234
235
236    def _decideFileFormatIndex(self, number_of_dims):
237        """
238        Based on the number of dimensions and the NASA Ames dictionary return
239        the File Format Index.
240        """
241        if number_of_dims in (2,3,4):
242            ffi = 10 + (number_of_dims * 1000)
243        elif number_of_dims > 4:
244            raise Exception("Cannot write variables defined against greater than 4 axes in NASA Ames format.")
245        else:
246            if len(aux_vars_for_na) > 0 or (self.na_dict.has_key("NAUXV") and self.na_dict["NAUXV"] > 0):
247                ffi = 1010
248            else:
249                ffi = 1001
250        return ffi
251
252
253    def _defineNAVars(self, vars):
254        """
255        Method to define NASA Ames file object variables and their
256        associated metadata.
257        """
258        self.na_dict["NV"] = len(vars)
259        self.na_dict["VNAME"] = []
260        self.na_dict["VMISS"] = []
261        self.na_dict["VSCAL"] = []
262        self.na_dict["V"] = []
263
264        for var in vars:
265            name = nappy.cdms_utils.var_utils.getBestName(var)
266            self.na_dict["VNAME"].append(name)
267            miss = nappy.cdms_utils.var_utils.getMissingValue(var)
268            if type(miss) not in (type(1.2), type(1), type(1L)): 
269                miss = miss[0]
270            self.na_dict["VMISS"].append(miss)
271            self.na_dict["VSCAL"].append(1)
272            # Populate the variable list with the array
273            self.na_dict["V"].append(var._data)
274
275            if not self.na_dict.has_key("X"):
276                self.na_dict["NXDEF"] = []
277                self.na_dict["NX"] = []
278
279                # Create independent variable information
280                self.ax0 = var.getAxis(0)
281                self.na_dict["X"] = [self.ax0[:].tolist()]
282                self.na_dict["XNAME"] = [nappy.cdms_utils.var_utils.getBestName(self.ax0)]
283                if len(self.ax0) == 1:
284                    self.na_dict["DX"] = [0]
285                else:
286                    incr = self.ax0[1] - self.ax0[0]
287                    # Set default increment as gap between first two
288                    self.na_dict["DX"] = [incr]
289                    # Now overwrite it as zero if non-uniform interval in axis
290                    for i in range(1, len(self.ax0)):
291                        if (self.ax0[i] - self.ax0[i - 1]) != incr:
292                            self.na_dict["DX"] = [0]
293                            break
294
295                # Now add the rest of the axes to the self.na_dict objects
296                for axis in var.getAxisList()[1:]:
297                    self._appendAxisDefinition(axis)
298
299
300    def _defineNAaux_vars(self, aux_vars):
301        """
302        Method to define NASA Ames file object auxiliary variables and their
303        associated metadata.
304        """
305        self.na_dict["NAUXV"] = len(aux_vars)
306        self.na_dict["ANAME"] = []
307        self.na_dict["AMISS"] = []
308        self.na_dict["ASCAL"] = []
309        self.na_dict["A"] = []
310
311        for var in aux_vars:
312            name = nappy.cdms_utils.var_utils.getBestName(var)
313            self.na_dict["ANAME"].append(name)
314            miss = nappy.cdms_utils.var_utils.getMissingValue(var)
315            if type(miss) != type(1.1):  miss = miss[0]
316            self.na_dict["AMISS"].append(miss)
317            self.na_dict["ASCAL"].append(1)
318            # Populate the variable list with the array
319            self.na_dict["A"].append(var._data)
320
321    def _appendAxisDefinition(self, axis):
322        """
323        Method to create the appropriate NASA Ames file object
324        items associated with an axis (independent variable in
325        NASA Ames). It appends to the various self.na_dict containers.
326        """
327        length = len(axis)
328        self.na_dict["NX"].append(length)
329        self.na_dict["XNAME"].append(nappy.cdms_utils.var_utils.getBestName(axis))
330        # If only one item in axis values
331        if length < 2:
332            self.na_dict["DX"].append(0)
333            self.na_dict["NXDEF"].append(length)
334            self.na_dict["X"].append(axis[:].tolist())       
335            return
336   
337        incr = axis[1] - axis[0]
338        for i in range(1, length):
339            if (axis[i] - axis[i - 1]) != incr:
340                self.na_dict["DX"].append(0)
341                self.na_dict["NXDEF"].append(length)
342                self.na_dict["X"].append(axis.tolist())
343                break
344        else: # If did not break out of the loop
345            max_length = length
346            if length > 3: max_length = 3
347                self.na_dict["DX"].append(incr)
348                self.na_dict["NXDEF"].append(max_length)
349                self.na_dict["X"].append(axis[:max_length])
350
351
352    def _defineNAGlobals(self):
353        """
354        Maps CDMS (NetCDF) global attributes into NASA Ames Header fields.
355        """
356        # Check if we should add to it with locally set rules
357        local_attributes = nappy.utils.getConfigDict()["local_attributes"]
358        for att, value in local_attributes.items():
359            if not nc_to_na_map.has_key(att):
360                nc_to_na_map[key] = value
361
362        self.extra_comments = [[],[],[]]  # Normal comments, special comments, other comments
363        convention_or_reference_comments = []
364
365        for key in self.globals.keys():
366            if key != "first_valid_date_of_data" and type(self.globals[key]) \
367                                       not in (type("s"), type(1.1), type(1)):
368                continue
369
370            # Loop through keys of header/comment items to map
371            if key in nc_to_na_map.keys():
372                if key == "history":
373                    time_string = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.time()))
374                    history = "History:\t%s - Converted to NASA Ames format using nappy-%s.\n\t%s" % \
375                                                 (time_string, version.version, self.globals[key])
376                    history = history.split("\n") 
377                    self.history = []
378                    for h in history:
379                        if h[:8] != "History:" and h[:1] != "\t": 
380                            h = "\t" + h
381                        self.history.append(h) 
382                   
383                elif key == "institution":
384                    # If fields came from NA then extract appropriate fields.
385                    match = re.match(r"(.*)\s+\(ONAME from NASA Ames file\);\s+(.*)\s+\(ORG from NASA Ames file\)\.", 
386                             self.globals[key])
387                    if match:
388                        self.na_dict["ONAME"] = match.groups()[0]
389                        self.na_dict["ORG"] = match.groups()[1]
390                    else:
391                        self.na_dict["ONAME"] = self.globals[key]
392                        self.na_dict["ORG"] = self.globals[key]           
393                    # NOTE: should probably do the following search and replace on all string lines
394                    self.na_dict["ONAME"] = self.na_dict["ONAME"].replace("\n", "  ")
395                    self.na_dict["ORG"] = self.na_dict["ORG"].replace("\n", "  ")
396                                   
397                elif key == "comment":
398                    # Need to work out if they are actually comments from NASA Ames in the first place
399                    comment_lines = self.globals[key].split("\n")
400                    normal_comments = []
401                    normal_comm_flag = None
402                    special_comments = []
403                    special_comm_flag = None
404
405                    for line in comment_lines:
406                        if line.find("###NASA Ames Special Comments follow###") > -1:
407                            special_comm_flag = 1
408                        elif line.find("###NASA Ames Special Comments end###") > -1:
409                            special_comm_flag = None
410                        elif line.find("###NASA Ames Normal Comments follow###") > -1:
411                            normal_comm_flag = 1
412                        elif line.find("###NASA Ames Normal Comments end###") > -1:
413                            normal_comm_flag = None     
414                        elif special_comm_flag == 1:
415                            special_comments.append(line)
416                        elif normal_comm_flag == 1:
417                            normal_comments.append(line)
418                        elif line.find("###Data Section begins on the next line###") > -1:
419                            pass
420                        else:
421                            normal_comments.append(line)           
422                   
423                    self.extra_comments = [special_comments, normal_comments, []]                   
424                                   
425                elif key == "first_valid_date_of_data":
426                    self.na_dict["DATE"] = self.globals[key]
427               
428                elif key in ("Conventions", "references"):
429                    #convention_or_reference_comments.append("%s:   %s" % (key, self.globals[key]))
430                    self.extra_comments[2].append("%s:   %s" % (key, self.globals[key]))
431                else:
432                    self.na_dict[nc_to_na_map[key]] = self.globals[key]
433            else:
434                self.extra_comments[2].append("%s:   %s" % (key, self.globals[key]))
435        return
436
437
438    def _defineNAComments(self, normal_comments=[], special_comments=[]):
439        """
440        Defines the Special and Normal comments sections in the NASA Ames file
441        object - including information gathered from the defineNAGlobals method.
442        """
443       
444        if hasattr(self, "ncom"):  normal_comments = self.ncom + normal_comments
445
446        NCOM = []
447        for ncom in normal_comments:
448            NCOM.append(ncom)
449
450        if len(NCOM) > 0:   NCOM.append("")
451       
452        if len(self.extra_comments[2]) > 0:
453            for excom in self.extra_comments[2]:
454                NCOM.append(excom)
455       
456        if len(self.extra_comments[1]) > 0: 
457            NCOM.append("Additional Global Attributes defined in the source file and not translated elsewhere:")
458            for excom in self.extra_comments[1]:
459                NCOM.append(excom)
460
461        if hasattr(self, "history"):
462            for h in self.history:
463                NCOM.append(h)
464       
465        if len(NCOM) > 0:
466            NCOM.insert(0, "###NASA Ames Normal Comments follow###")
467            NCOM.append("")
468            NCOM.append("###NASA Ames Normal Comments end###")
469            NCOM.append("###Data Section begins on the next line###")
470
471        spec_comm_flag = None
472        SCOM = []
473        special_comments = self.extra_comments[0]
474        if len(special_comments) > 0: 
475            SCOM = ["###NASA Ames Special Comments follow###"]
476
477            spec_comm_flag = 1
478        for scom in special_comments:
479            SCOM.append(scom)
480
481        used_var_atts = ("id",  "missing_value", "fill_value", "units", 
482                   "nasa_ames_var_number", "nasa_ames_aux_var_number")
483        var_comm_flag = None
484
485        # Create a string for the Special comments to hold rank-zero vars
486        rank_zero_vars_string = []
487        for var in self.rank_zero_vars:
488            rank_zero_vars_string.append("\tVariable %s: %s" % (var.id, nappy.cdms_utils.var_utils.getBestName(var)))
489
490        for att in var.attributes.keys():
491            value = var.attributes[att]
492            if type(value) in (type("s"), type(1.0), type(1)):
493                rank_zero_vars_string.append("\t\t%s = %s" % (att, var.attributes[att]))
494       
495        if len(rank_zero_vars_string) > 0:
496            rank_zero_vars_string.insert(0, "###Singleton Variables defined in the source file follow###")
497            rank_zero_vars_string.append("###Singleton Variables defined in the source file end###")
498
499        for var in self.ordered_vars:
500            varflag = "unused"
501            name = nappy.cdms_utils.var_utils.getBestName(var)
502
503            for scom,value in var.attributes.items():
504                if type(value) in (type([]), type(Numeric.array([0]))) and len(value) == 1:
505                    value = value[0]
506
507                if type(value) in (type("s"), type(1.1), type(1)) and scom not in used_var_atts:
508                    if varflag == "unused":
509                        if var_comm_flag == None:
510                            var_comm_flag = 1
511                                    if spec_comm_flag == None:
512                                            SCOM = ["###NASA Ames Special Comments follow###"] + rank_zero_vars_string
513                            SCOM.append("Additional Variable Attributes defined in the source file and not translated elsewhere:")
514                            SCOM.append("###Variable attributes from source (NetCDF) file follow###")
515                        varflag = "using" 
516                        SCOM.append("\tVariable %s: %s" % (var.id, name))
517                    SCOM.append("\t\t%s = %s" % (scom, value))
518
519        if var_comm_flag == 1:  SCOM.append("###Variable attributes from source (NetCDF) file end###")
520        if spec_comm_flag == 1:
521            SCOM.append("###NASA Ames Special Comments end###")
522
523        # Strip out empty lines (or returns)
524        NCOM_cleaned = []
525        SCOM_cleaned = []
526
527        for c in NCOM:
528            if c.strip() not in ("", " ", "  "):
529                # Replace new lines within one attribute with a newline and tab so easier to read
530                lines = c.split("\n")
531                for line in lines:
532                    if line != lines[0]: 
533                        line = "\t" + line
534                    NCOM_cleaned.append(line)
535                       
536        for c in SCOM:
537            if c.strip() not in ("", " ", "  "):               
538                        # Replace new lines within one attribute with a newline and tab so easier to read
539                lines = c.split("\n")
540                for line in lines:
541                    if line != lines[0]: 
542                        line = "\t" + line
543                    SCOM_cleaned.append(line)
544                   
545        self.na_dict["NCOM"] = NCOM_cleaned
546        self.na_dict["NNCOML"] = len(self.na_dict["NCOM"])
547        self.na_dict["SCOM"] = SCOM_cleaned
548        self.na_dict["NSCOML"] = len(self.na_dict["SCOM"])
549        return
550
551
552    def _defineGeneralHeader(self, header_items={}):
553        """
554        Defines known header items and overwrites any with header_items
555        key/value pairs.
556        """
557        # Check if DATE field previously known in NASA Ames file
558        time_now = time.strftime("%Y %m %d", time.localtime(time.time())).split()
559        if not self.na_dict.has_key("RDATE"):
560            self.na_dict["RDATE"] = time_now
561       
562        if self.ax0.isTime():
563            # Get first date in list
564            try:
565                (unit, start_date) = re.match("(\w+)\s+?since\s+?(\d+-\d+-\d+)", self.ax0.units).groups()           
566                comptime = cdtime.s2c(start_date)
567                first_day = comptime.add(self.na_dict["X"][0][0], getattr(cdtime, unit.capitalize()))
568                self.na_dict["DATE"] = string.replace(str(first_day).split(" ")[0], "-", " ").split()
569            except:
570                msg = "Nappy Warning: Could not get the first date in the file. You will need to manually edit the output file."
571                print msg
572                self.output_message.append(msg)
573                self.na_dict["DATE"] = ("DATE", "NOT", "KNOWN")
574        else: 
575            if not self.na_dict.has_key("DATE"):
576                msg = "Nappy Warning: Could not get the first date in the file. You will need to manually edit the output file."
577            print msg
578            self.output_message.append(msg)
579                self.na_dict["DATE"] = ("DATE", "NOT", "KNOWN")
580
581        self.na_dict["IVOL"] = 1
582        self.na_dict["NVOL"] = 1
583        for key in header_items.keys():
584             self.na_dict[key] = header_items[key]
585        return
Note: See TracBrowser for help on using the repository browser.