[GRASS-SVN] r60897 - sandbox/krejcmat/src

svn_grass at osgeo.org svn_grass at osgeo.org
Fri Jun 20 09:05:27 PDT 2014


Author: martinl
Date: 2014-06-20 09:05:27 -0700 (Fri, 20 Jun 2014)
New Revision: 60897

Modified:
   sandbox/krejcmat/src/mdgrass.py
   sandbox/krejcmat/src/r.info.iso.py
   sandbox/krejcmat/src/v.info.iso.py
Log:
minor clean up

Modified: sandbox/krejcmat/src/mdgrass.py
===================================================================
--- sandbox/krejcmat/src/mdgrass.py	2014-06-20 15:54:48 UTC (rev 60896)
+++ sandbox/krejcmat/src/mdgrass.py	2014-06-20 16:05:27 UTC (rev 60897)
@@ -6,65 +6,68 @@
 
 PURPOSE:   Library for creating ISO metadata for GRASS GIS
 
-COPYRIGHT: (C) 2007 Matej Krejci, and by the GRASS Development Team
+COPYRIGHT: (C) 2014 Matej Krejci, and by the GRASS Development Team
 
            This program is free software under the GNU General Public
            License (>=v2). Read the file COPYING that comes with GRASS
            for details.
 """
 
+import os
+import sys
+import getpass # whoami for linux and  ms-win
+import StringIO
+
+from subprocess import PIPE
+from datetime import date, datetime
+
+
 from owslib.iso import *
 from lxml import etree
-from jinja2 import Environment, FileSystemLoader
+from jinja2 import Environment, FileSystemLoader           # TODO: remove this dependency?
 
-import os
-import sys
 from grass.pygrass.modules.shortcuts import general as g
 from grass.pygrass.gis import Mapset
 from grass.pygrass import raster
 from grass.pygrass.modules import Module
-from grass.script import parse_key_val
-from subprocess import PIPE
-from datetime import date,datetime
-import getpass # whoami for linux and  ms-win
-from grass.script import parser
+
+from grass.script import parse_key_val, parser
 from grass.script import core as grass
-import StringIO
-import subprocess as sub
 
-
 class GrassMD():
     def __init__(self, map, type):
 
-        self.map = map                    #name of choosen map by user
-        self.type = type                  #typ of map representation(cell, vector, r3)
-        self.isMapExist()                 #function to check if map exist
-        self.md_grass = {}                #dict with metadata from r.info v.info  except "r.info flag=h"        
-        self.md_abstract = ''             #create abstract from self.md_grass - key: source1, source2 and descriptio etc.
-        self.md_vinfo_h = ''              #v.info flag=h" - parse
-        self.gisenv_grass = grass.gisenv()#dict with gisenv information
-        self.schema_type='_md_GRASS.xml'  #postfix of output xml file (variables)
+        self.map = map                    # name of choosen map by user
+        self.type = type                  # typ of map representation(cell, vector, r3)
+        self.isMapExist()                 # function to check if map exist
+        
+        self.md_grass = {}                # dict with metadata from r.info v.info  except "r.info flag=h"        
+        self.md_abstract = ''             # create abstract from self.md_grass - key: source1, source2 and descriptio etc.
+        self.md_vinfo_h = ''              # v.info flag=h" - parse
+        
+        self.gisenv_grass = grass.gisenv()# dict with gisenv information
+        
+        self.schema_type='_md_GRASS.xml'  # postfix of output xml file (variables)
         self.dirpath = os.path.dirname(os.path.realpath(__file__))
-        self.md = MD_Metadata()            #metadata object from OWSLIB ( for define md values)
-        self.template = None               #path to file with xml templates
+        self.md = MD_Metadata()            # metadata object from OWSLIB ( for define md values)
         
+        self.template = None               # path to file with xml templates
+        
         if self.type == "cell":
             self.parseRast()
         elif self.type == "vector":
             self.parseVect()
-        elif self.type == "r3??":
-            #TODO   
-            self.parseRast3D()
-            
-            
+        elif self.type == "g3dcell":
+            self.parseRast3D() # TODO
+                        
     def isMapExist(self):
         '''Check if is the map in working mapset'''    
         self.mapset = grass.find_file(self.map, self.type)['mapset']
         if not self.mapset:
-            grass.fatal(_("Map <%s> doesn't exist"), self.map)
+            grass.fatal(_("Map <%s> not found"), self.map)
                    
     def readXML(self,xml_file):
-        '''create instance of metadata(owslib) from xml file'''
+        '''Create instance of metadata(owslib) from xml file'''
         self.md = MD_Metadata(etree.parse(xml_file))
         
     def parseRast3D(self):
@@ -74,11 +77,11 @@
         '''Read metadata from v.info
         #self.md_grass dictionary of metadata from v.info '''
         
-        #parse md from v.info flags=-g -e -t
+        # parse md from v.info -get (basic metadata)
         vinfo = Module('v.info', self.map, flags='get', quiet = True, stdout_=PIPE)
         self.md_grass = parse_key_val(vinfo.outputs.stdout)
         
-        #parse md from v.info flag h (history of map in grass)
+        # parse md from v.info flag -h (history of map in grass)
         rinfo_h = Module('v.info', self.map, flags='h', quiet = True, stdout_=PIPE)
         md_h_grass = rinfo_h.outputs.stdout
         buf = StringIO.StringIO(md_h_grass)
@@ -89,19 +92,18 @@
             line = buf.readline().splitlines()
         buf.close()
         
-        #change grass generated date format to iso format
-        #if date format is diverse from standard, use them
+        # change grass generated date format to iso format
+        # if date format is diverse from standard, use them
         self._createISODate('source_date')
             
     def _createISODate(self, key):
         '''Function for convert grass-generated date to iso format
            if the format of date is different to grass-generated format - use them and print warning  '''
-        
         try:
             date = datetime.strptime(self.md_grass[key], '%a %b %d %H:%M:%S %Y')
             self.md_grass['dateofcreation'] = date.strftime('%Y-%m-%d')
         except:
-            grass.warning('date of creation: unknown date format')
+            grass.warning(_('date of creation: unknown date format'))
             self.md_grass['dateofcreation'] = self.md_grass[key]
                                 
     def parseRast(self):
@@ -112,10 +114,10 @@
         rinfo = Module('r.info', self.map, flags='gre', quiet = True, stdout_=PIPE)
         self.md_grass = parse_key_val(rinfo.outputs.stdout)
                    
-        #convert date to iso format
+        # convert date to iso format
         self._createISODate('date')
             
-        #create abstract
+        # create abstract
         if self.md_grass['description'] != '""':
             self.md_abstract = self.md_grass['description'] + '\n'
         if self.md_grass['source1'] != '""':
@@ -125,7 +127,6 @@
         self.md_abstract += 'Total cells: '+ self.md_grass['cells']
         self.md_abstract += 'A range of values: min: ' + self.md_grass['min'] + '  max: ' + self.md_grass['max']
         
-
     def createGrassInspireISO(self):
         '''Create valid INSPIRE profile and fill it as much as possible by GRASS metadata. Missing values is $NULL
         -create basic md profile and add INSPIRE mandatory attributes
@@ -155,7 +156,9 @@
         self.md.identification.keywords.append(kw)
         # Conformity/Title 
         self.md.dataquality.conformancetitle.pop() #remove value from basic profile
-        self.md.dataquality.conformancetitle.append('Commission Regulation (EU) No 1089/2010 of 23 November 2010 implementing Directive 2007/2/EC of the European Parliament and of the Council as regards interoperability of spatial data sets and services')
+        self.md.dataquality.conformancetitle.append('Commission Regulation (EU) No 1089/2010 of 23 November 2010 implementing '
+                                                    'Directive 2007/2/EC of the European Parliament and of the Council as regards '
+                                                    'interoperability of spatial data sets and services')
         
         # Conformity/Date 
         self.md.dataquality.conformancedate.append(n)
@@ -180,9 +183,9 @@
         '''
         
         n = '$NULL'
-        #jinja templates
+        # jinja templates
         self.template = 'data/grassBasicISOTemplate.xml'
-        #OWSLib md object 
+        # OWSLib md object 
         self.md.identification = MD_DataIdentification()
         self.md.dataquality = DQ_DataQuality()
         self.md.distribution = MD_Distribution()
@@ -210,11 +213,11 @@
         self.md.identification.identtype = 'dataset'
         
         # Identification/Unique Resource Identifier 
-        #TODO GENERATOR
+        # TODO GENERATOR
         self.md.identifier = '286c0725-146e-4533-b1bf-d6e367f6c342' 
         self.md.identification.uricode.append('286c0725-146e-4533-b1bf-d6e367f6c342')
         
-        #Geographic/BB
+        # Geographic/BB
         self.md.identification.extent.boundingBox.minx = self.md_grass['south']
         self.md.identification.extent.boundingBox.maxx = self.md_grass['north']
         self.md.identification.extent.boundingBox.miny = self.md_grass['west']
@@ -231,7 +234,7 @@
         val.type = 'creation'
         self.md.identification.date.append(val)
 
-        #different metadata sources for vector and raster 
+        # Different metadata sources for vector and raster 
         if self.type == 'cell':
             # Identification/Resource Abstract 
             self.md.identification.abstract = self.md_abstract
@@ -267,12 +270,12 @@
             xml_out_name = str(self.map) + self.schema_type
         if not xml_out_name.lower().endswith('.xml'):
             xml_out_name +='.xml'
-        #if path is None, use lunch. dir
-        #TODO change default folder to mapset location
+        # if path is None, use lunch. dir
+        # TODO change default folder to mapset location
         if not path:
             path = os.path.join(self.dirpath,xml_out_name)
         else:
-            path = os.path.join(path,xml_out_name)
+            path = os.path.join(path, xml_out_name)
 
         #generate xml using jinja tempaltes
         env = Environment(loader=FileSystemLoader(self.dirpath))
@@ -281,17 +284,17 @@
         iso_xml = template.render(md=self.md)
         xml_file = xml_out_name
         
-        #write xml to flat file
+        # write xml to flat file
         try:
             xml_file = open(path, "w")
             xml_file.write(iso_xml)
             xml_file.close()
-            Module('g.message', message='metadata exported: \n\
-                                         %s'%(str(path)))
+            grass.message(_('Metadata exported: %s') % (str(path)))
         except IOError as e:
             print "I/O error({0}): {1}".format(e.errno, e.strerror)
-            grass.fatal('error: cannot write xml file')
-        return  path
+            grass.fatal(_('Unable to write xml file'))
+
+        return path
     
     def validate_inspire(self):
         '''function for validation INSPIRE XML file'''

Modified: sandbox/krejcmat/src/r.info.iso.py
===================================================================
--- sandbox/krejcmat/src/r.info.iso.py	2014-06-20 15:54:48 UTC (rev 60896)
+++ sandbox/krejcmat/src/r.info.iso.py	2014-06-20 16:05:27 UTC (rev 60897)
@@ -27,20 +27,19 @@
 #% answer: basic
 #%end
 
-#%option G_OPT_R_MAP
-#% key: mdout
-#% label: Name of output metadata file
+#%option G_OPT_F_OUTPUT
+#% label: Name for output metadata file
 #% required: no
 #%end
 
 #%option G_OPT_M_DIR 
 #% key: destination
-#% label: Path to destination folder
+#% label: Path to destination directory
 #% required: no
 #%end
 
 from grass.script import parser
-from mdgrass import  *
+from mdgrass import *
 
 def main():
 
@@ -53,8 +52,7 @@
         mdout = None
     else:
         mdout=options['mdout']    
-  
-  
+    
     md = GrassMD(options['map'], 'cell')        
     if options['profil']=='inspire':
         md.createGrassInspireISO()
@@ -64,8 +62,9 @@
     else:    
         md.createGrassBasicISO()
         md.saveXML(destination,mdout)
-    
 
+    return 0
+
 if __name__ == "__main__":
     options, flags = parser()
-    main()
+    sys.exit(main())

Modified: sandbox/krejcmat/src/v.info.iso.py
===================================================================
--- sandbox/krejcmat/src/v.info.iso.py	2014-06-20 15:54:48 UTC (rev 60896)
+++ sandbox/krejcmat/src/v.info.iso.py	2014-06-20 16:05:27 UTC (rev 60897)
@@ -27,20 +27,20 @@
 #% answer: basic
 #%end
 
-#%option G_OPT_V_MAP
-#% key: mdout
-#% label: Name of output metadata file
+#%option G_OPT_F_OUTPUT
+#% label: Name for output metadata file
 #% required: no
 #%end
 
 #%option G_OPT_M_DIR 
 #% key: destination
-#% label: Path to destination folder
+#% label: Path to destination directory
 #% required: no
 #%end
 
 from grass.script import parser
 from mdgrass import  *
+
 def main():
 
     if not options['destination']:
@@ -53,18 +53,19 @@
     else:
         mdout=options['mdout']   
     
-    #create instance of metadata in owslib
+    # create instance of metadata in owslib
     md = GrassMD(options['map'], 'vector') 
            
     if options['profil']=='inspire':
         md.createGrassInspireISO()
         xml_file=md.saveXML(options['destination'],options['mdout'])
         md.readXML(xml_file)
-        print md.validate_inspire()
     else:    
         md.createGrassBasicISO()
         md.saveXML(options['destination'],options['mdout'])
     
+    return 0
+
 if __name__ == "__main__":
     options, flags = parser()
-    main()
+    sys.exit(main())



More information about the grass-commit mailing list