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

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

Getting NC to NA working but needs nappy_api.py to be changed!

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.cdms_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 = nappy.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.getDebug() 
39
40class NAContentCollector(nappy.na_file.na_core.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
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
512                    if spec_comm_flag == None:
513                        SCOM = ["###NASA Ames Special Comments follow###"] + rank_zero_vars_string
514                        SCOM.append("Additional Variable Attributes defined in the source file and not translated elsewhere:")
515                        SCOM.append("###Variable attributes from source (NetCDF) file follow###")
516                        varflag = "using" 
517
518                    SCOM.append("\tVariable %s: %s" % (var.id, name))
519                    SCOM.append("\t\t%s = %s" % (scom, value))
520
521        if var_comm_flag == 1: 
522            SCOM.append("###Variable attributes from source (NetCDF) file end###")
523        if spec_comm_flag == 1:
524            SCOM.append("###NASA Ames Special Comments end###")
525
526        # Strip out empty lines (or returns)
527        NCOM_cleaned = []
528        SCOM_cleaned = []
529
530        for c in NCOM:
531            if c.strip() not in ("", " ", "  "):
532                # Replace new lines within one attribute with a newline and tab so easier to read
533                lines = c.split("\n")
534                for line in lines:
535                    if line != lines[0]: 
536                        line = "\t" + line
537                    NCOM_cleaned.append(line)
538                       
539        for c in SCOM:
540            if c.strip() not in ("", " ", "  "):               
541                        # Replace new lines within one attribute with a newline and tab so easier to read
542                lines = c.split("\n")
543                for line in lines:
544                    if line != lines[0]: 
545                        line = "\t" + line
546                    SCOM_cleaned.append(line)
547                   
548        self.na_dict["NCOM"] = NCOM_cleaned
549        self.na_dict["NNCOML"] = len(self.na_dict["NCOM"])
550        self.na_dict["SCOM"] = SCOM_cleaned
551        self.na_dict["NSCOML"] = len(self.na_dict["SCOM"])
552        return
553
554
555    def _defineGeneralHeader(self, header_items={}):
556        """
557        Defines known header items and overwrites any with header_items
558        key/value pairs.
559        """
560        # Check if DATE field previously known in NASA Ames file
561        time_now = time.strftime("%Y %m %d", time.localtime(time.time())).split()
562        if not self.na_dict.has_key("RDATE"):
563            self.na_dict["RDATE"] = time_now
564       
565        if self.ax0.isTime():
566            # Get first date in list
567            try:
568                (unit, start_date) = re.match("(\w+)\s+?since\s+?(\d+-\d+-\d+)", self.ax0.units).groups()           
569                comptime = cdtime.s2c(start_date)
570                first_day = comptime.add(self.na_dict["X"][0][0], getattr(cdtime, unit.capitalize()))
571                self.na_dict["DATE"] = str(first_day).split(" ")[0].replace("-", " ").split()
572            except:
573                msg = "Nappy Warning: Could not get the first date in the file. You will need to manually edit the output file."
574                print msg
575                self.output_message.append(msg)
576                self.na_dict["DATE"] = ("DATE", "NOT", "KNOWN")
577        else: 
578            if not self.na_dict.has_key("DATE"):
579                msg = "Nappy Warning: Could not get the first date in the file. You will need to manually edit the output file."
580                print msg
581                self.output_message.append(msg)
582                self.na_dict["DATE"] = ("DATE", "NOT", "KNOWN")
583            else:
584                pass # i.e. use existing DATE
585
586        self.na_dict["IVOL"] = 1
587        self.na_dict["NVOL"] = 1
588        for key in header_items.keys():
589             self.na_dict[key] = header_items[key]
Note: See TracBrowser for help on using the repository browser.