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

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

Got 2010 to 2110 working.

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