source: DPPP/kml/csml2kml/python/buildPointSeries.py @ 3245

Subversion URL: http://proj.badc.rl.ac.uk/svn/ndg/DPPP/kml/csml2kml/python/buildPointSeries.py@3245
Revision 3245, 4.7 KB checked in by mkochan, 13 years ago (diff)

Created a prototype KML convertor for PointSeries?, which creates a document with features placed on globe and associated balloons with graph plots. Graphs are at the moment stored as local files only.

Line 
1from cElementTree import ElementTree, Element, SubElement
2from pylab import *
3from datetime import datetime, timedelta
4import re
5
6import csml
7
8def getElapsedDays(time_step):
9    matchObject = re.match("(\d+)\-(\d+)\-(\d+)T(\d+):(\d+):(\d+)", time_step)
10    str_tuple = matchObject.groups()
11    (Y, M, D, h, m, s) = map(int, str_tuple)
12    dt = datetime(Y, M, D, h, m, s)
13    epoch_start = datetime(1900, 1, 1)
14    time_delta = dt - epoch_start
15    elapsed_days = float(time_delta.days) + float(time_delta.seconds) / float(24*60*60)
16    return elapsed_days
17
18def buildFeatureElement(feature,lon,lat,noSamples):
19
20    placemarkElement = Element('Placemark')
21    SubElement(placemarkElement, 'name').text = feature.description.CONTENT
22    SubElement(placemarkElement, 'open').text = '0'
23    SubElement(placemarkElement, 'visibility').text = '0'
24    SubElement(placemarkElement, 'styleUrl').text = '#basic_style'
25
26    lookAtElement = SubElement(placemarkElement, 'LookAt')
27    SubElement(lookAtElement, 'longitude').text = str(lon)
28    SubElement(lookAtElement, 'latitude').text = str(lat)
29
30    pointElement = SubElement(placemarkElement, 'Point')
31    SubElement(pointElement, 'coordinates').text = '%f,%f,%f' % (lon, lat, 0.)
32
33    extendedDataElement = SubElement(placemarkElement, 'ExtendedData')
34    dataElement = SubElement(extendedDataElement, 'Data')
35    dataElement.set('name', 'no_samples')
36    SubElement(dataElement, 'value').text = (str(noSamples))
37
38    dataElement = SubElement(extendedDataElement, 'Data')
39    dataElement.set('name', 'feature_id')
40    SubElement(dataElement, 'value').text = (feature.id)
41
42    return placemarkElement
43
44# Auxiliary function, indents XML
45def indentXML(elem, level=0):
46    i = "\n" + level * "  "
47    if len(elem):
48        if not elem.text or not elem.text.strip():
49            elem.text = i + "  "
50        for child in elem:
51            indentXML(child, level+1)
52        if not child.tail or not child.tail.strip():
53            child.tail = i
54        if not elem.tail or not elem.tail.strip():
55            elem.tail = i
56    else:
57        if level and (not elem.tail or not elem.tail.strip()):
58            elem.tail = i
59
60ds=csml.parser.Dataset()
61ds.parse('../pointseries/exampleps.xml')
62
63kmlDocumentElement=Element('Document')
64SubElement(kmlDocumentElement, 'name').text=ds.name.CONTENT
65SubElement(kmlDocumentElement, 'open').text='0'
66
67styleElement = SubElement(kmlDocumentElement, 'Style')
68styleElement.set('id', 'basic_style')
69iconStyleElement = SubElement(styleElement, 'IconStyle')
70SubElement(iconStyleElement, 'scale').text = '1.2'
71iconElement = SubElement(iconStyleElement, 'Icon')
72SubElement(iconElement, 'href').text = 'http://maps.google.com/mapfiles/kml/shapes/target.png'
73
74balloonStyleText = '''
75Number of samples: <b>$[no_samples].</b><br>
76<img src="./psplot_$[feature_id].png"><br>
77'''
78
79ballonStyleElement = SubElement(styleElement, 'BalloonStyle')
80SubElement(ballonStyleElement, 'text').text = balloonStyleText
81
82for feature in ds.featureCollection.featureMembers:
83    (lon, lat) = map(float, feature.location.CONTENT.split())
84    print 'Feature "%s" (%s) at: (%f,%f)' % (feature.id, feature.description.CONTENT, lon, lat)
85   
86    times=feature.value.pointSeriesDomain.timePositionList.CONTENT.split()
87    print 'All times (%s of them): '% len(times)
88    print times
89
90    elapsed_times = map(getElapsedDays, times)
91    print 'All times (%s of them) as days since 1 Jan 1900: '% len(elapsed_times)
92    print elapsed_times
93
94    # We may need to do this for bodc data (i.e. not inline data)
95    # vals=feature.value.rangeSet.valueArray.valueComponent.insertedExtract.components.getDataFromChunks(0,19)
96   
97    #but for inline data:
98    ql = feature.value.rangeSet.quantityList
99    vals = map(float, ql.CONTENT.split())
100    print 'Measurement values (%s of them):\n%s' % (len(vals), repr(vals))
101
102    uom=ql.uom.title()
103    if ql.uom.islower():
104        uom = uom.lower()
105    if ql.uom.isupper():
106        uom = uom.upper()
107    print 'Units of measurement: %s' % uom
108
109    plot(elapsed_times, vals, '-', lw=2)
110
111    xlabel('Time since start [days]')
112    ylabel('Values [%s]' % uom)
113    title('Plot of "%s" (%s)' % (feature.id, feature.description.CONTENT))
114    grid(True)
115
116    savefig('../output/psplot_%s.png' % feature.id)
117
118    show()
119    clf()
120    close()
121
122    placemarkElement = buildFeatureElement(feature, lon, lat, len(vals))
123    kmlDocumentElement.append(placemarkElement)
124
125# Attach the Document element as a subelement of the root 'kml' element
126kmlRootElement=Element('kml', xmlns='http://earth.google.com/kml/2.2')
127kmlRootElement.append(kmlDocumentElement)
128indentXML(kmlRootElement)
129
130# Write the KML document to a file
131tree = ElementTree(kmlRootElement)       
132f = open('../output/psexample.kml', 'w')
133tree.write(f)
134f.close()
Note: See TracBrowser for help on using the repository browser.