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

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