source: trunk/libIGCM/libIGCM_post/xios_parser.py @ 1416

Last change on this file since 1416 was 1413, checked in by sdipsl, 7 years ago
  • being able to manage dr2xml_${compname}.xml files for IPSLCM6.0.13 and CMIP6
  • Property svn:executable set to *
  • Property svn:keywords set to Revision Date Author
File size: 9.0 KB
Line 
1#! /usr/bin/env python
2# coding: utf-8
3
4#**************************************************************
5# Author: Sebastien Denvil
6# Contact: Sebastien.Denvil__at__ipsl.jussieu.fr
7# $Revision::                                         $ Revision of last commit
8# $Author::                                           $ Author of last commit
9# $Date::                                             $ Date of last commit
10# IPSL (2006)
11#  This software is governed by the CeCILL licence see libIGCM/libIGCM_CeCILL.LIC
12#
13#**************************************************************
14
15import os, pwd, sys, traceback, argparse
16import xml.etree.ElementTree as ET
17#import readline, rlcompleter
18#readline.parse_and_bind("tab: complete")
19
20indent = 0
21currentDepth = 0
22ignoreElems = []
23fromField=[]
24fromFile=[]
25
26def dump(args):
27    """Dump XIOS xmls files."""
28    # Read and dump xios_def_xml
29    for inputFile in args.file:       
30        # Read the file_def_xml
31        print '\nReading %s \n|' % (inputFile)
32        try:
33            tree = ET.parse(inputFile)
34        except:
35            print "Parse error. Please fix so that it can be parsed."
36            traceback.print_exc(file=sys.stdout)
37            return
38        root=tree.getroot()
39        # Call the recursive print
40        printRecur(root)
41
42def tsquery(args):
43    """query timeseries related parameters from an XIOS xml file."""
44    if args.verbosity >= 1: print 'Reading timeseries_def_xml=',args.file[0]
45    try:
46        tree = ET.parse(args.file[0])
47    except:
48        print "Parse error. Please fix so that it can be parsed."
49        traceback.print_exc(file=sys.stdout)
50        return
51    root=tree.getroot()
52    if args.verbosity >= 3: print root.tag, root.attrib
53    findTimeSeries(root)
54       
55def printRecur(root):
56    """Recursively prints the tree."""
57    global indent
58    global currentDepth
59    if root.tag in ignoreElems:
60        return
61    print ' '*indent + '|--> %s: %s' % (root.tag, root.attrib)
62    currentDepth += 1
63    indent += 4
64    if currentDepth <= args.depth or args.depth == None:
65        for elem in list(root):
66            printRecur(elem)
67    currentDepth -= 1
68    indent -= 4
69
70def findTimeSeries(root):
71    """Recursively find and list field tag with "timeseries", "id", "output_freq" and enable=.TRUE. attribute."""
72    if root.tag == 'file' and root.attrib.get('timeseries'):
73        if root.attrib.get('enabled') == '.TRUE.':
74            print 'output_freq=%-5s,id=%s' % (root.attrib.get('output_freq'), root.attrib.get('id'))
75    elif root.tag == 'file' and root.attrib.get('uuid_name'):
76        print 'output_freq=%-5s,name=%85s' % (root.attrib.get('output_freq'), root.attrib.get('name'))
77    else:
78        for elem in list(root):
79            findTimeSeries(elem)
80   
81def findField(root):
82    """Recursively find and list field tag with "id" or "field_ref" attribute."""
83    global fromField
84    global fromFile
85    if root.tag in ignoreElems:
86        return   
87    if root.tag == 'field' and root.attrib.get('id'):
88        fromField.append(root.attrib.get('id'))
89    elif root.tag == 'field' and root.attrib.get('field_ref'):
90        fromFile.append(root.attrib.get('field_ref'))
91    else:
92        for elem in list(root):
93            findField(elem)
94
95def findFieldToRemove(root, fieldToRemove):
96    """Recursively find tag having a field_ref in fieldToRemove."""
97    if args.verbosity >= 3 and root.tag == 'file' and root.attrib.get('id'):
98        print '\nFIELDS FROM FILE_DEF with id', root.attrib.get('id')
99    for field in root.findall('field'):
100        if args.verbosity >= 3: print 'field_ref=', field.attrib.get('field_ref')
101        if field.attrib.get('field_ref') in fieldToRemove:
102            if args.correction:
103                if args.verbosity >= 2: print 'removing ', field.attrib.get('field_ref')
104                root.remove(field)
105            else:
106                if args.verbosity >= 2: print 'To be removed ', field.attrib.get('field_ref')
107    for elem in list(root):
108        findFieldToRemove(elem, fieldToRemove)
109       
110def check(args):
111    global fromFile
112    exitCode=0
113    # Read the field_def_xml
114    if args.verbosity >= 1: print '\nReading field_def_xml=',args.field[0]
115    try:
116        tree = ET.parse(args.field[0])
117    except:
118        print 'Parse error with %s. Please fix so that it can be parsed.' % (args.field[0])
119        traceback.print_exc(file=sys.stdout)
120        return
121    root=tree.getroot()
122    if args.verbosity >= 3: print root.tag, root.attrib, '\n'
123    # Build a list of field.id from field_def
124    findField(root)
125
126    # Loop over file_def files
127    for inputFile in args.file:       
128        # Read the file_def_xml
129        if args.verbosity >= 1: print '\nReading file_def_xml=',inputFile
130        try:
131            tree = ET.parse(inputFile)
132        except:
133            print "Parse error. Please fix so that it can be parsed."
134            traceback.print_exc(file=sys.stdout)
135            return
136        root=tree.getroot()
137        fromFile=[]
138        if args.verbosity >= 3: print root.tag, root.attrib, '\n'
139
140        # Build a list of field_ref from file_def
141        findField(root)
142        #print '4. fromFile=', fromFile
143       
144        # Compare the two lists. fromField must be a superset of fromFile.
145        if set(fromField).issuperset(set(fromFile)):
146            if args.verbosity >= 1: print '\nALL GOOD with %s' % (inputFile)
147            if args.verbosity >= 3: print 'fromField=', fromField
148            if args.verbosity >= 3: print 'fromFile=', fromFile
149        else:
150            if args.verbosity >= 1: print '\nTROUBLE AHEAD with %s' % (inputFile)
151            if args.verbosity >= 3: print ', '.join(sorted(list(set(fromFile)-set(fromField))))
152            # Identify fields in fromFile but not in fromField
153            fieldToRemove=list(set(fromFile)-set(fromField))
154            if args.verbosity >= 3: print 'fieldToRemove=', fieldToRemove
155            #
156            # And now locate and remove them if the modify command has been called
157            findFieldToRemove(root, fieldToRemove)
158            # Final steps
159            if args.correction: tree.write('modified.'+inputFile)
160            if not len(fieldToRemove) == 0 and not args.correction:
161                exitCode=1
162    # The end
163    sys.exit(exitCode)
164
165def showtime(args):
166    """
167    prints table of formatted text format options
168    """
169    for style in xrange(6):
170        for fg in xrange(30,36):
171            s1 = ''
172            for bg in xrange(40,46):
173                format = ';'.join([str(style), str(fg), str(bg)])
174                s1 += '\x1b[%sm %s \x1b[0m' % (format, pwd.getpwuid(os.getuid())[4]+' is on fire')
175            print s1
176        print '\n'
177   
178if __name__ == '__main__':
179
180    try:
181        # Create the top-level parser
182        parser = argparse.ArgumentParser(description='XIOS2 xml files tooling and ironsmith')
183        subparsers = parser.add_subparsers(description='Dump, check or modify xios xml files')
184
185        # create the parser for the "dump" command
186        parser_dump = subparsers.add_parser('dump',help='Dump the xml content without all the xml\'s ironsmith')
187        parser_dump.add_argument('-d', '--depth', type=int, default=None, help='How deep do we go. Full tree by default')
188        parser_dump.add_argument('file', nargs='+', help='XIOS xml file(s) to dump')
189        parser_dump.set_defaults(func=dump)
190
191        # create the parser for the "tsquery" command
192        parser_check = subparsers.add_parser('tsquery', help='query timeseries related parameters from an xml file')
193        parser_check.add_argument('--file', nargs=1, required=True, help='XIOS xml timeseries_def type')
194        parser_check.set_defaults(func=tsquery)
195       
196        # create the parser for the "check" command
197        parser_check = subparsers.add_parser('check', help='Check consistency between field_def and file_def files')
198        parser_check.add_argument('--field', nargs=1, required=True, help='XIOS xml field_def type')
199        parser_check.add_argument('--file', nargs='+', required=True, help='XIOS xml file_def type')
200        parser_check.set_defaults(func=check, correction=False)
201       
202        # create the parser for the "modify" command
203        parser_check = subparsers.add_parser('modify', help='Will make sure field_def is a superset of file_def')
204        parser_check.add_argument('--field', nargs=1, required=True, help='XIOS xml field_def type')
205        parser_check.add_argument('--file', nargs='+', required=True, help='XIOS xml file_def type')
206        parser_check.set_defaults(func=check, correction=True)
207
208        # create the parser for the "modify" command
209        parser_check = subparsers.add_parser('showtime', help='Just want to make sure you feel good today')
210        parser_check.set_defaults(func=showtime)
211       
212        # Each possible option
213        parser.add_argument('-v', '--verbosity', action='count', default=0)
214
215        # Parse the args.
216        args = parser.parse_args()
217
218        # And call whatever function was selected
219        args.func(args)
220    except KeyboardInterrupt:
221        print "Shutdown requested...exiting"
222    except Exception:
223        traceback.print_exc(file=sys.stdout)
224    sys.exit(0)
Note: See TracBrowser for help on using the repository browser.