Changeset 3549


Ignore:
Timestamp:
29/02/08 16:08:03 (12 years ago)
Author:
mkochan
Message:

Wrote code for generating a hierarchy of KML files (with kml:NetworkLinks) and directories.

Location:
DPPP/kml/csml2kml/python/csml2kml/csml2kml
Files:
3 edited

Legend:

Unmodified
Added
Removed
  • DPPP/kml/csml2kml/python/csml2kml/csml2kml/KML.py

    r3545 r3549  
     1import os 
     2import sys 
    13from cElementTree import ElementTree, Element, SubElement, XML 
    24 
     
    4648    def save(self, outputFilename): 
    4749        ''' 
    48         Save the document to file <code>outputFilename</code>. 
     50        Save the document to file <code>outputFilename</code> (full path). 
    4951        ''' 
    5052 
    51         # Auxiliary function, indents XML 
    5253        def _indentXML(elem, level=0): 
     54            '''Auxiliary function, indents XML''' 
    5355            i = "\n" + level * "  " 
    5456            if len(elem): 
     
    6567                    elem.tail = i 
    6668 
    67         # Build the Document element 
    68         documentElement = self.build() 
    69  
    70         # Attach the Document element as a subelement of a root 'kml' element 
    71         rootElement=Element('kml', xmlns='http://earth.google.com/kml/2.2') 
    72         rootElement.append(documentElement) 
    73         _indentXML(rootElement) 
    74  
    75         # Write the KML document to a file 
    76         elementTree = ElementTree(rootElement)        
    77         kmlFile = open(outputFilename, 'w') 
    78         elementTree.write(kmlFile) 
    79         kmlFile.close() 
     69        def _save(filename): 
     70            '''Builds and saves the document in the KML format into the file filename.''' 
     71 
     72            # Build the Document element 
     73            documentElement = self.build() 
     74 
     75            # Attach the Document element as a subelement of a root 'kml' element 
     76            rootElement=Element('kml', xmlns='http://earth.google.com/kml/2.2') 
     77            rootElement.append(documentElement) 
     78            _indentXML(rootElement) 
     79 
     80            # Write the KML document to a file 
     81            elementTree = ElementTree(rootElement)        
     82            kmlFile = open(filename, 'w') 
     83            elementTree.write(kmlFile) 
     84            kmlFile.close() 
     85 
     86        # Check the suffix of outputFilename, and depending on suffix, either save the document 
     87        # directly to a KML file, or save it packed in a KMZ file. 
     88        suffix = outputFilename[-3:].lower() 
     89        if suffix == 'kml': 
     90            _save(outputFilename) 
     91        elif suffix == 'kmz': 
     92            raise NotImplementError('Needs re-testing') 
     93            ##shortOutputFilename = outputFilename.split('/')[-1]          # separate out the short filename 
     94            ##outputDir = outputFilename[:-(len(shortOutputFilename)+1)]   # separate out the directory name 
     95            ##_save(outputDir + '/doc.kml') 
     96            ##os.system('zip -q %s %s/doc.kml' % (outputFilename, outputDir)) 
     97            ##os.remove(outputDir + '/doc.kml') 
     98        else: 
     99            raise ValueError('Wrong file suffix, only "kml" and "kmz" allowed.') 
    80100 
    81101class KMLStyle(KMLElement): 
     
    290310 
    291311class KMLNetworkLink(KMLElement): 
    292     def __init__(self): 
    293         pass 
    294  
    295     def build(self): 
    296         pass 
     312 
     313    def __init__(self, name, url, visible = True): 
     314        self.name = name 
     315        self.url = url 
     316        self.visible = visible 
     317 
     318    def build(self): 
     319        networkLinkElement = Element('NetworkLink') 
     320 
     321        SubElement(networkLinkElement, 'name').text = self.name 
     322 
     323        if self.visible: 
     324            SubElement(networkLinkElement, 'visibility').text = '1' 
     325        else: 
     326            SubElement(networkLinkElement, 'visibility').text = '0' 
     327 
     328        linkElement = SubElement(networkLinkElement, 'Link') 
     329        SubElement(linkElement, 'href').text = self.url 
     330 
     331        return networkLinkElement 
  • DPPP/kml/csml2kml/python/csml2kml/csml2kml/WMSCapabilities.py

    r3542 r3549  
    33from pylab import dates     # a very good date/time module from matplotviz -- allows years < 1970 
    44from KML import * 
    5  
    6 # [TODO] 
    7 #        * Resolve maxDirDepth 
    85 
    96wmsXmlNamespace = 'http://www.opengis.net/wms' 
     
    4744        raise NotImplementedError('Use the wmsLayerFactory() function instead.') 
    4845 
    49     def toKML(self, wmsRequestConfigElement, viewTypes): 
    50         # ignore wmsRequestConfigElement, viewTypess 
    51         kmlLayerFolder = KMLFolder(self.title, [], opened = False, visible = False) 
     46    def toKML(self, wmsRequestConfigElement, viewTypes, parentDir, parentDirUrl): 
     47 
     48        title_ = self.title.replace(' ', '_')  # self.title underscored 
     49        dir = parentDir + '/' + title_ 
     50        dirUrl = parentDirUrl + '/' + title_ 
     51        filename = dir + '.kml' 
     52        fileUrl = dirUrl + '.kml' 
     53 
     54        # create directory currentDir 
     55        os.mkdir(dir) 
     56 
     57        kmlDocument = KMLDocument(self.title, []) 
    5258        for childWmsLayer in self.children: 
    53             kmlLayerFolder.children.append( childWmsLayer.toKML(wmsRequestConfigElement, viewTypes) ) 
    54         return kmlLayerFolder 
     59            kmlDocument.elements.append(  
     60                childWmsLayer.toKML(wmsRequestConfigElement, viewTypes, dir, dirUrl)  
     61                ) 
     62        kmlDocument.save(filename) 
     63     
     64        return KMLNetworkLink(self.title, fileUrl) 
    5565 
    5666class BottomWMSLayer(WMSLayer): 
     
    98108        return self._parseName()[4] 
    99109 
    100     def toKML(self, wmsRequestConfigElement, viewTypes): 
     110    def toKML(self, wmsRequestConfigElement, viewTypes, parentDir, parentDirUrl): 
    101111        ''' 
    102112        @param viewTyps: A list of View classes (but not instances), which define what kinds of view we are going  
    103113                         to use to look at the data. 
     114                         ... 
    104115        @return:         A KML.KMLFolder object representing a <kml:Folder> element with lots of <kml:GroundOverlay> 
    105116                         elements, each standing for a different time segment. 
     
    343354class WMSLayersConvertor: 
    344355     
    345     def __init__(self, topWmsLayer, wmsRequestConfigElement, baseKmlOutputDirectory, maxDirDepth): 
     356    def __init__(self, topWmsLayer, wmsRequestConfigElement, baseKmlOutputDirectory, baseKmlOutputUrl): 
    346357        self.topWmsLayer = topWmsLayer 
    347358        self.wmsRequestConfigElement = wmsRequestConfigElement 
    348359        self.baseKmlOutputDirectory = baseKmlOutputDirectory 
    349         self.maxDirDepth = maxDirDepth 
     360        self.baseKmlOutputUrl = baseKmlOutputUrl 
    350361         
    351362    def convert(self): 
    352  
    353         def _convertToKML(wmsLayer, parentLayersStack): 
    354             ''' 
    355             @param parentLayersStack: an immutable list (acting as a stack) with the WMSLayer objects that have 
    356             been passed through. 
    357             @return: a KMLFolder object containing a folder structure (including the backtrack from the parentLayersStack) 
    358             with the KML representation of wmsLayer at the bottom. 
    359             ''' 
    360             viewTypes = [ViewWholeTimecourse, ViewSplittedByMonth, ViewSplittedByPeriod] 
    361             layerKmlFolder = wmsLayer.toKML(self.wmsRequestConfigElement, viewTypes) 
    362  
    363             # Backtrack through parentLayersStack in order to include the upper folders in the KML structure as well 
    364             # (that way it is much easier to see in Google Earth where we are): 
    365             if len(parentLayersStack) == 0: 
    366                 return layerKmlFolder 
    367             else: 
    368                 childKmlFolder = layerKmlFolder 
    369                 while len(parentLayersStack) > 0: 
    370                     stackKmlLayer = parentLayersStack.pop() 
    371                     kmlFolder = KMLFolder(stackKmlLayer.title, [], visible = False, opened = False) 
    372                     kmlFolder.children.append(childKmlFolder) 
    373                     childKmlFolder = kmlFolder 
    374                 return kmlFolder 
    375  
    376         def _convertToFile(wmsLayer, parentLayersStack, parentDir): 
    377  
    378             # Convert the current layer into a KML document 
    379             topKmlFolder = _convertToKML(wmsLayer, parentLayersStack) 
    380  
    381             # Create a KML document with no styles 
    382             kmlDocument = KMLDocument(topKmlFolder.name, [])             
    383  
    384             # Replace the uppermost KMLFolder object with a KMLDocument object 
    385             kmlDocument.elements = topKmlFolder.children 
    386  
    387             # Save the KML document 
    388             dockmlFilename = parentDir + '/doc.kml' 
    389             kmzFilename = parentDir + '/' + wmsLayer.title.replace(' ', '_') + '.kmz' 
    390             kmlDocument.save(dockmlFilename) 
    391             quietZipCommand = 'zip -q ' + ' "' + kmzFilename + '" "' + dockmlFilename + '"' 
    392             os.system(quietZipCommand) 
    393             os.remove(dockmlFilename) 
    394             print 'Saved file "%s"' % kmzFilename 
    395  
    396         def _convertToDirectory(wmsLayer, parentLayersStack, parentDir, currentLevel): 
    397             '''recursive''' 
    398             if currentLevel < self.maxDirDepth and not isinstance(wmsLayer, BottomWMSLayer): 
    399                 currentDir = parentDir + '/' + wmsLayer.title.replace(' ', '_') 
    400                 os.mkdir(currentDir) 
    401                 print 'Created directory "%s"' % currentDir 
    402                 for childWmsLayer in wmsLayer.children: 
    403                     _convertToDirectory(childWmsLayer, parentLayersStack + [wmsLayer], currentDir, currentLevel+1) 
    404             elif currentLevel == self.maxDirDepth or isinstance(wmsLayer, BottomWMSLayer): 
    405                 _convertToFile(wmsLayer, parentLayersStack, parentDir) 
    406             else: 
    407                 pass 
    408  
    409         _convertToDirectory(self.topWmsLayer, [], self.baseKmlOutputDirectory, 0) 
     363        viewTypes = [ViewWholeTimecourse, ViewSplittedByMonth, ViewSplittedByPeriod] 
     364        self.topWmsLayer.toKML(self.wmsRequestConfigElement, viewTypes, self.baseKmlOutputDirectory, self.baseKmlOutputUrl) 
  • DPPP/kml/csml2kml/python/csml2kml/csml2kml/tests/testWMSCapabilities.py

    r3541 r3549  
    66 
    77configElementTree = ElementTree() 
    8 configElementTree.parse('../../../../testdata/ar4.conf.xml') 
     8configElementTree.parse('../../../../testdata/obs.conf.xml') 
    99wmsRequestConfigElement = configElementTree.getroot().find('WMSRequest') 
    1010 
     
    2121 
    2222wmsLayersConvertor = WMSLayersConvertor( 
    23     wmsCapabilities.topWmsLayer, wmsRequestConfigElement, '../../../../output/wms-ar4', 2 
     23    wmsCapabilities.topWmsLayer, wmsRequestConfigElement, '../../../../output/wms-obs2', 'http://bond.badc.rl.ac.uk' 
    2424    ) 
    2525wmsLayersConvertor.convert() 
Note: See TracChangeset for help on using the changeset viewer.