-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathpython_filter_generator.py
More file actions
371 lines (276 loc) · 10.9 KB
/
python_filter_generator.py
File metadata and controls
371 lines (276 loc) · 10.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
# See blog for details: https://blog.kitware.com/easy-customization-of-the-paraview-python-programmable-filter-property-panel/
import os
import sys
import inspect
import textwrap
def escapeForXmlAttribute(s):
# http://www.w3.org/TR/2000/WD-xml-c14n-20000119.html#charescaping
# In character data and attribute values, the character information items "<" and "&" are represented by "<" and "&" respectively.
# In attribute values, the double-quote character information item (") is represented by """.
# In attribute values, the character information items TAB (#x9), newline (#xA), and carriage-return (#xD) are represented by "	", "
", and "
" respectively.
s = s.replace('&', '&') # Must be done first!
s = s.replace('<', '<')
s = s.replace('>', '>')
s = s.replace('"', '"')
s = s.replace('\r', '
')
s = s.replace('\n', '
')
s = s.replace('\t', '	')
return s
def getScriptPropertiesXml(info):
e = escapeForXmlAttribute
requestData = e(info['RequestData'])
requestInformation = e(info['RequestInformation'])
requestUpdateExtent = e(info['RequestUpdateExtent'])
if requestData:
requestData = '''
<StringVectorProperty
name="Script"
command="SetScript"
number_of_elements="1"
default_values="%s"
panel_visibility="advanced">
<Hints>
<Widget type="multi_line"/>
</Hints>
<Documentation>This property contains the text of a python program that
the programmable source runs.</Documentation>
</StringVectorProperty>''' % requestData
if requestInformation:
requestInformation = '''
<StringVectorProperty
name="InformationScript"
label="RequestInformation Script"
command="SetInformationScript"
number_of_elements="1"
default_values="%s"
panel_visibility="advanced">
<Hints>
<Widget type="multi_line" />
</Hints>
<Documentation>This property is a python script that is executed during
the RequestInformation pipeline pass. Use this to provide information
such as WHOLE_EXTENT to the pipeline downstream.</Documentation>
</StringVectorProperty>''' % requestInformation
if requestUpdateExtent:
requestUpdateExtent = '''
<StringVectorProperty
name="UpdateExtentScript"
label="RequestUpdateExtent Script"
command="SetUpdateExtentScript"
number_of_elements="1"
default_values="%s"
panel_visibility="advanced">
<Hints>
<Widget type="multi_line" />
</Hints>
<Documentation>This property is a python script that is executed during
the RequestUpdateExtent pipeline pass. Use this to modify the update
extent that your filter ask up stream for.</Documentation>
</StringVectorProperty>''' % requestUpdateExtent
return '\n'.join([requestData, requestInformation, requestUpdateExtent])
def getPythonPathProperty():
return '''
<StringVectorProperty command="SetPythonPath"
name="PythonPath"
number_of_elements="1"
panel_visibility="advanced">
<Documentation>A semi-colon (;) separated list of directories to add to
the python library search path.</Documentation>
</StringVectorProperty>'''
def getFilterPropertyXml(propertyInfo, propertyName):
e = escapeForXmlAttribute
propertyValue = propertyInfo[propertyName]
propertyLabel = propertyName.replace('_', ' ')
if isinstance(propertyValue, list):
numberOfElements = len(propertyValue)
assert numberOfElements > 0
propertyType = type(propertyValue[0])
defaultValues = ' '.join([str(v) for v in propertyValue])
else:
numberOfElements = 1
propertyType = type(propertyValue)
defaultValues = str(propertyValue)
if propertyType is bool:
defaultValues = defaultValues.replace('True', '1').replace('False', '0')
return '''
<IntVectorProperty
name="%s"
label="%s"
initial_string="%s"
command="SetParameter"
animateable="1"
default_values="%s"
number_of_elements="%s">
<BooleanDomain name="bool" />
<Documentation></Documentation>
</IntVectorProperty>''' % (propertyName, propertyLabel, propertyName, defaultValues, numberOfElements)
if propertyType is int:
return '''
<IntVectorProperty
name="%s"
label="%s"
initial_string="%s"
command="SetParameter"
animateable="1"
default_values="%s"
number_of_elements="%s">
<Documentation></Documentation>
</IntVectorProperty>''' % (propertyName, propertyLabel, propertyName, defaultValues, numberOfElements)
if propertyType is float:
return '''
<DoubleVectorProperty
name="%s"
label="%s"
initial_string="%s"
command="SetParameter"
animateable="1"
default_values="%s"
number_of_elements="%s">
<Documentation></Documentation>
</DoubleVectorProperty>''' % (propertyName, propertyLabel, propertyName, defaultValues, numberOfElements)
if propertyType is str:
return '''
<StringVectorProperty
name="%s"
label="%s"
initial_string="%s"
command="SetParameter"
animateable="1"
default_values="%s"
number_of_elements="%s">
<Documentation></Documentation>
</StringVectorProperty>''' % (propertyName, propertyLabel, propertyName, defaultValues, numberOfElements)
raise Exception('Unknown property type: %r' % propertyType)
def getFilterPropertiesXml(info):
propertyInfo = info['Properties']
xml = [getFilterPropertyXml(propertyInfo, name) for name in sorted(propertyInfo.keys())]
return '\n\n'.join(xml)
def getNumberOfInputs(info):
return info.get('NumberOfInputs', 1)
def getInputPropertyXml(info):
numberOfInputs = getNumberOfInputs(info)
if not numberOfInputs:
return ''
inputDataType = info.get('InputDataType', 'vtkDataObject')
inputDataTypeDomain = ''
if inputDataType:
inputDataTypeDomain = ' <DataTypeDomain name="input_type">\n'
if isinstance(inputDataType, list):
for dt in inputDataType:
inputDataTypeDomain = inputDataTypeDomain + ' <DataType value="%s"/>\n' % dt
else:
inputDataTypeDomain = inputDataTypeDomain + ' <DataType value="%s"/>\n' % inputDataType
inputDataTypeDomain = inputDataTypeDomain + '</DataTypeDomain>'
inputPropertyAttributes = 'command="SetInputConnection"'
if numberOfInputs > 1:
inputPropertyAttributes = '''\
clean_command="RemoveAllInputs"
command="AddInputConnection"
multiple_input="1"'''
inputPropertyXml = '''
<InputProperty
name="Input"
%s>
<ProxyGroupDomain name="groups">
<Group name="sources"/>
<Group name="filters"/>
</ProxyGroupDomain>
%s
</InputProperty>''' % (inputPropertyAttributes, inputDataTypeDomain)
return inputPropertyXml
def getOutputDataSetTypeXml(info):
outputDataType = info.get('OutputDataType', '')
typeMap = {
'' : 8, # same as input
'vtkPolyData' : 0,
'vtkStructuredGrid' : 2,
'vtkRectilinearGrid' : 3,
'vtkUnstructuredGrid' : 4,
'vtkImageData' : 6,
'vtkUniformGrid' : 10,
'vtkMultiBlockDataSet' : 13,
'vtkHierarchicalBoxDataSet' : 15,
'vtkTable' : 19
}
typeValue = typeMap[outputDataType]
return '''
<!-- Output data type: "%s" -->
<IntVectorProperty command="SetOutputDataSetType"
default_values="%s"
name="OutputDataSetType"
number_of_elements="1"
panel_visibility="never">
<Documentation>The value of this property determines the dataset type
for the output of the programmable filter.</Documentation>
</IntVectorProperty>''' % (outputDataType or 'Same as input', typeValue)
def getProxyGroup(info):
if not info.has_key("Group"):
return 'sources' if getNumberOfInputs(info) == 0 else 'filters'
else: return info["Group"]
def generatePythonFilter(info):
e = escapeForXmlAttribute
proxyName = info['Name']
proxyLabel = info['Label']
shortHelp = e(info['Help'])
longHelp = e(info['Help'])
extraXml = info.get('ExtraXml', '')
proxyGroup = getProxyGroup(info)
inputPropertyXml = getInputPropertyXml(info)
outputDataSetType = getOutputDataSetTypeXml(info)
scriptProperties = getScriptPropertiesXml(info)
filterProperties = getFilterPropertiesXml(info)
outputXml = '''\
<ServerManagerConfiguration>
<ProxyGroup name="%s">
<SourceProxy name="%s" class="vtkPythonProgrammableFilter" label="%s">
<Documentation
long_help="%s"
short_help="%s">
</Documentation>
%s
%s
%s
%s
%s
</SourceProxy>
</ProxyGroup>
</ServerManagerConfiguration>
''' % (proxyGroup, proxyName, proxyLabel, longHelp, shortHelp, inputPropertyXml,
filterProperties, extraXml, outputDataSetType, scriptProperties)
return textwrap.dedent(outputXml)
def replaceFunctionWithSourceString(namespace, functionName, allowEmpty=False):
func = namespace.get(functionName)
if not func:
if allowEmpty:
namespace[functionName] = ''
return
else:
raise Exception('Function %s not found in input source code.' % functionName)
if not inspect.isfunction(func):
raise Exception('Object %s is not a function object.' % functionName)
lines = inspect.getsourcelines(func)[0]
if len(lines) <= 1:
raise Exception('Function %s must not be a single line of code.' % functionName)
# skip first line (the declaration) and then dedent the source code
sourceCode = textwrap.dedent(''.join(lines[1:]))
namespace[functionName] = sourceCode
def generatePythonFilterFromFiles(scriptFile, outputFile):
namespace = {}
execfile(scriptFile, namespace)
# gv = {}
# code = compile(open(scriptFile).read(), scriptFile, 'exec')
# exec(code, gv, namespace)
replaceFunctionWithSourceString(namespace, 'RequestData')
replaceFunctionWithSourceString(namespace, 'RequestInformation', allowEmpty=True)
replaceFunctionWithSourceString(namespace, 'RequestUpdateExtent', allowEmpty=True)
xmlOutput = generatePythonFilter(namespace)
open(outputFile, 'w').write(xmlOutput)
def main():
if len(sys.argv) != 3:
print('Usage: %s <python input filename> <xml output filename>' % sys.argv[0])
sys.exit(1)
inputScript = sys.argv[1]
outputFile = sys.argv[2]
generatePythonFilterFromFiles(inputScript, outputFile)
if __name__ == '__main__':
main()