selection.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517
  1. """selection is a module for defining and using selections via Python. It provides
  2. a convenience layer to provide functionality provided by the underlying C++ classes.
  3. A simple example::
  4. from paraview.selection import *
  5. # Create a new sphere proxy on the active connection and register it
  6. # in the sources group.
  7. sphere = Sphere(ThetaResolution=16, PhiResolution=32)
  8. # Show the sphere
  9. Show(sphere)
  10. # Select cells falling inside a rectangle defined by two points on a diagonal,
  11. # (300, 400) and (600, 800).
  12. SelectSurfaceCells(Rectangle=[300, 400, 600, 800])
  13. # Add cells on processor 0 with ids 1 and 2 to the current selection.
  14. SelectIDs(IDs=[0, 1, 0, 2], FieldType='CELL', Source=sphere, Modifier='ADD')
  15. # Remove cells on processor 0 with ids 4 and 5 from the current selection.
  16. SelectIDS(IDs=[0, 4, 0, 5], FieldType='CELL', Source=sphere, Modifier='SUBTRACT')
  17. # Extract the currently extracted cells
  18. es = ExtractSelection()
  19. Show(es)
  20. """
  21. # ==============================================================================
  22. #
  23. # Program: ParaView
  24. # Module: selection.py
  25. #
  26. # Copyright (c) Kitware, Inc.
  27. # All rights reserved.
  28. # See Copyright.txt or http://www.paraview.org/HTML/Copyright.html for details.
  29. #
  30. # This software is distributed WITHOUT ANY WARRANTY; without even
  31. # the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
  32. # PURPOSE. See the above copyright notice for more information.
  33. #
  34. # ==============================================================================
  35. from __future__ import absolute_import, division, print_function
  36. import paraview
  37. from paraview import servermanager as sm
  38. import paraview.simple
  39. class SelectionProxy(sm.Proxy):
  40. """ Special proxy wrapper type for Selections.
  41. """
  42. def __init__(self, **args):
  43. super(SelectionProxy, self).__init__(**args)
  44. def _createSelection(proxyname, **args):
  45. """ Utility function to create a selection source. Basically a factory function
  46. that creates a proxy of a given name and hands off keyword arguments to the newly
  47. created proxy.
  48. """
  49. session = sm.ActiveConnection.Session
  50. pxm = sm.ProxyManager(session)
  51. proxy = pxm.NewProxy('sources', proxyname)
  52. s = SelectionProxy(proxy=proxy)
  53. for name, value in args.items():
  54. # Warning: this will add only the attributes initially passed in when creating the proxy.
  55. s.add_attribute(name, value)
  56. s.SetPropertyWithName(name, value)
  57. return s
  58. def _collectSelectionPorts(selectedReps, selectionSources, SelectBlocks=False, Modifier=None):
  59. """ Utility to collect all the selection output ports from a list of selected representations
  60. and sources. Selects blocks instead of cells if the SelectBlocks option is True.
  61. The Modifier can be used to modify the currently existing selection through one of the values
  62. 'ADD', 'SUBTRACT', 'TOGGLE' or None if the new selection should replace the existing one.
  63. """
  64. outputPorts = []
  65. if not selectedReps or selectedReps.GetNumberOfItems() <= 0:
  66. return outputPorts
  67. if not selectionSources or selectionSources.GetNumberOfItems() <= 0:
  68. return outputPorts
  69. if selectedReps.GetNumberOfItems() != selectionSources.GetNumberOfItems():
  70. return outputPorts
  71. for i in range(0, selectedReps.GetNumberOfItems()):
  72. repr = selectedReps.GetItemAsObject(i)
  73. selectionSource = selectionSources.GetItemAsObject(i)
  74. if not repr:
  75. continue
  76. # Ensure selected representation is registered with the proxy manager
  77. pxm = repr.GetSessionProxyManager()
  78. if not pxm:
  79. return
  80. # Get the output port from the representation input
  81. inputProperty = repr.GetProperty("Input")
  82. selectedDataSource = inputProperty.GetProxy(0)
  83. portNumber = inputProperty.GetOutputPortForConnection(0)
  84. outputPort = selectedDataSource.GetOutputPort(portNumber)
  85. prevAppendSelections = selectedDataSource.GetSelectionInput(portNumber)
  86. # Convert block selection from index-based selection
  87. from paraview.modules.vtkRemotingViews import vtkSMSelectionHelper
  88. import paraview.vtk as vtk
  89. if SelectBlocks:
  90. dinfo = selectedDataSource.GetDataInformation()
  91. targetContentType = vtk.vtkSelectionNode.BLOCK_SELECTORS if dinfo.DataSetTypeIsA(
  92. "vtkPartitionedDataSetCollection") else vtk.vtkSelectionNode.BLOCKS
  93. selectionSource = vtkSMSelectionHelper.ConvertSelectionSource(targetContentType, selectionSource,
  94. selectedDataSource, portNumber)
  95. # create an append-selections proxy with the selection source as the only input
  96. newAppendSelections = vtkSMSelectionHelper.NewAppendSelectionsFromSelectionSource(selectionSource)
  97. # Handle selection modifier
  98. if Modifier == 'ADD':
  99. vtkSMSelectionHelper.AddSelection(prevAppendSelections, newAppendSelections)
  100. elif Modifier == 'SUBTRACT':
  101. vtkSMSelectionHelper.SubtractSelection(prevAppendSelections, newAppendSelections)
  102. elif Modifier == 'TOGGLE':
  103. vtkSMSelectionHelper.ToggleSelection(prevAppendSelections, newAppendSelections)
  104. else:
  105. vtkSMSelectionHelper.IgnoreSelection(prevAppendSelections, newAppendSelections)
  106. selectedDataSource.SetSelectionInput(portNumber, newAppendSelections, outputPort.GetPortIndex())
  107. if SelectBlocks:
  108. # A new selection proxy was allocated when converting to a block
  109. # selection, so we need to delete unregister it for garbage collection
  110. selectionSource.UnRegister(None)
  111. newAppendSelections.UnRegister(None)
  112. # Add output port to list of ports and return it
  113. outputPorts.append(outputPort)
  114. return outputPorts
  115. def _surfaceSelectionHelper(rectOrPolygon, view, type, Modifier=None):
  116. """ Selects mesh elements on a surface
  117. - rectOrPolygon - represents either a rectangle or polygon. If a rectangle, consists of a list
  118. containing the bottom left (x1, y1) and top right (x2, y2) corner of a rectangle defining the
  119. selection region in the format [x1, y1, x2, y2]. If a polygon, list of points defining the
  120. polygon in x-y pairs (e.g., [x1, y1, x2, y2, x3, y3,...])
  121. - view - the view in which to make the selection
  122. - type - the type of mesh element: 'POINT', 'CELL', or 'BLOCK'
  123. - Modifier - 'ADD', 'SUBTRACT', 'TOGGLE', or None to define whether and how the selection
  124. should modify the existing selection.
  125. """
  126. if not view.SMProxy.IsA('vtkSMRenderViewProxy'):
  127. return
  128. # ensure the view has rendered so that the selection is valid
  129. paraview.simple.Render(view)
  130. if len(rectOrPolygon) == 0:
  131. rectOrPolygon = [0, 0, view.ViewSize[0], view.ViewSize[1]]
  132. from paraview.vtk import vtkCollection, vtkIntArray
  133. selectedReps = vtkCollection()
  134. selectionSources = vtkCollection()
  135. if type.startswith('POLYGON'):
  136. polygon = vtkIntArray()
  137. polygon.SetNumberOfComponents(2)
  138. for component in rectOrPolygon:
  139. polygon.InsertNextValue(component)
  140. if type == 'POINT':
  141. view.SelectSurfacePoints(rectOrPolygon, selectedReps, selectionSources, 0)
  142. elif type == 'CELL' or type == 'BLOCK':
  143. view.SelectSurfaceCells(rectOrPolygon, selectedReps, selectionSources, 0)
  144. elif type == 'FRUSTUM_POINTS':
  145. view.SelectFrustumPoints(rectOrPolygon, selectedReps, selectionSources, 0)
  146. elif type == 'FRUSTUM_CELLS':
  147. view.SelectFrustumCells(rectOrPolygon, selectedReps, selectionSources, 0)
  148. elif type == 'POLYGON_POINTS':
  149. view.SelectPolygonPoints(polygon, selectedReps, selectionSources, 0)
  150. elif type == 'POLYGON_CELLS':
  151. view.SelectPolygonCells(polygon, selectedReps, selectionSources, 0)
  152. else:
  153. raise RuntimeError("Invalid type %s" % type)
  154. _collectSelectionPorts(selectedReps, selectionSources, type == 'BLOCK', Modifier)
  155. paraview.simple.Render(view)
  156. def SelectSurfacePoints(Rectangle=[], Polygon=[], View=None, Modifier=None):
  157. """Select visible points within a rectangular or polygon region.
  158. - Rectangle - list containing bottom left (x1, y1) and top right (x2, y2) corner of a
  159. rectangle defining the selection region in the format [x1, y1, x2, y2]. Defined in pixels.
  160. If not empty, the Polygon parameter must be empty or None.
  161. - Polygon - list of 2D points defining a polygon in which visible points should be selected,
  162. e.g., [x1, y1, x2, y2, ..., xn, yn]. Defined in pixels. If not empty, the Rectangle parameter
  163. must be empty or None.
  164. - View - the view in which to perform the selection. If None, uses the current active view.
  165. - Modifier - 'ADD', 'SUBTRACT', 'TOGGLE', or None to define whether and how the selection
  166. should modify the existing selection.
  167. """
  168. if not View:
  169. View = paraview.simple.GetActiveView()
  170. if Rectangle and Polygon:
  171. raise RuntimeError("Can only have one of Rectangle or Polygon named parameters set.")
  172. elif Rectangle:
  173. return _surfaceSelectionHelper(Rectangle, View, 'POINT', Modifier)
  174. elif Polygon:
  175. return _surfaceSelectionHelper(Polygon, View, 'POLYGON_POINTS', Modifier)
  176. else:
  177. raise RuntimeError("Need to set either the Rectangle or Polygon named parameters.")
  178. return None
  179. def SelectSurfaceCells(Rectangle=[], Polygon=[], View=None, Modifier=None):
  180. """Select visible cells within a rectangular or polygon region.
  181. - Rectangle - list containing bottom left (x1, y1) and top right (x2, y2) corner of a
  182. rectangle defining the selection region in the format [x1, y1, x2, y2]. Defined in pixels.
  183. If not empty, the Polygon parameter must be empty or None.
  184. - Polygon - list of 2D points defining a polygon in which visible points should be selected,
  185. e.g., [x1, y1, x2, y2, ..., xn, yn]. Defined in pixels. If not empty, the Rectangle parameter
  186. must be empty or None.
  187. - View - the view in which to perform the selection. If None, uses the current active view.
  188. - Modifier - 'ADD', 'SUBTRACT', 'TOGGLE', or None to define whether and how the selection
  189. should modify the existing selection.
  190. """
  191. if not View:
  192. View = paraview.simple.GetActiveView()
  193. if Rectangle and Polygon:
  194. raise RuntimeError("Can only have one of Rectangle or Polygon named parameters set.")
  195. if Rectangle:
  196. return _surfaceSelectionHelper(Rectangle, View, 'CELL', Modifier)
  197. elif Polygon:
  198. return _surfaceSelectionHelper(Polygon, View, 'POLYGON_CELLS', Modifier)
  199. else:
  200. raise RuntimeError("")
  201. def SelectSurfaceBlocks(Rectangle=[], View=None, Modifier=None):
  202. """Select visible blocks within a rectangular region.
  203. - Rectangle - list containing bottom left (x1, y1) and top right (x2, y2) corner of a
  204. rectangle defining the selection region in the format [x1, y1, x2, y2]. Defined in pixels.
  205. - View - the view in which to perform the selection. If None, uses the current active view.
  206. - Modifier - 'ADD', 'SUBTRACT', 'TOGGLE', or None to define whether and how the selection
  207. should modify the existing selection.
  208. """
  209. if not View:
  210. View = paraview.simple.GetActiveView()
  211. if not Modifier:
  212. # Clear the current selection - work around default behavior or utility function, which is
  213. # to add blocks.
  214. ClearSelection()
  215. # need to trigger render since otherwise the representation for the
  216. # selection that was just cleared may not have updated.
  217. paraview.simple.Render(View)
  218. return _surfaceSelectionHelper(Rectangle, View, 'BLOCK', Modifier)
  219. def SelectPointsThrough(Rectangle=[], View=None, Modifier=None):
  220. """Select all points within a rectangular region regardless of their visibility.
  221. - Rectangle - list containing bottom left (x1, y1) and top right (x2, y2) corner of a
  222. rectangle defining the selection region in the format [x1, y1, x2, y2]. Defined in pixels.
  223. - View - the view in which to perform the selection. If None, uses the current active view.
  224. """
  225. if not View:
  226. View = paraview.simple.GetActiveView()
  227. return _surfaceSelectionHelper(Rectangle, View, 'FRUSTUM_POINTS', Modifier)
  228. def SelectCellsThrough(Rectangle=[], View=None, Modifier=None):
  229. """Select all cells within a rectangular region regardless of their visibility.
  230. - Rectangle - list containing bottom left (x1, y1) and top right (x2, y2) corner of a
  231. rectangle defining the selection region in the format [x1, y1, x2, y2]. Defined in pixels.
  232. - View - the view in which to perform the selection. If None, uses the current active view.
  233. """
  234. if not View:
  235. View = paraview.simple.GetActiveView()
  236. return _surfaceSelectionHelper(Rectangle, View, 'FRUSTUM_CELLS', Modifier)
  237. def _selectIDsHelper(proxyname, IDs=[], FieldType='POINT', ContainingCells=False, Source=None, Modifier=None):
  238. """Selects IDs of a given field type.
  239. - proxyname - name of the selection proxy to instantiate
  240. - IDs - list of IDs of attribute types to select.
  241. - FieldType - type of attribute to select, e.g., 'POINT', 'CELL'
  242. - ContainingCells - if True and FieldType is 'POINT', select the cells containing the
  243. points corresponding to the given IDs.
  244. - Source - If not None, specifies the sources whose elements should be selected by ID.
  245. - Modifier - 'ADD', 'SUBTRACT', 'TOGGLE', or None to define whether and how the selection
  246. should modify the existing selection.
  247. """
  248. if not Source:
  249. Source = paraview.simple.GetActiveSource()
  250. repr = paraview.simple.GetRepresentation(Source)
  251. import paraview.vtk as vtk
  252. reprCollection = vtk.vtkCollection()
  253. reprCollection.AddItem(repr.SMProxy)
  254. selection = _createSelection(proxyname, IDs=IDs, FieldType=FieldType, ContainingCells=ContainingCells)
  255. if selection:
  256. selectionCollection = vtk.vtkCollection()
  257. selectionCollection.AddItem(selection.SMProxy)
  258. _collectSelectionPorts(reprCollection, selectionCollection, Modifier=Modifier)
  259. Source.UpdateVTKObjects()
  260. paraview.simple.RenderAllViews()
  261. def SelectGlobalIDs(IDs=[], FieldType='POINT', ContainingCells=False, Source=None, Modifier=None):
  262. """Select attributes by global IDs.
  263. - IDs - list of IDs of attribute types to select. Defined as a list of global IDs.
  264. - FieldType - type of attribute to select, e.g., 'POINT', 'CELL'
  265. - ContainingCells - if True and FieldType is 'POINT', select the cells containing the
  266. points corresponding to the given IDs.
  267. - Source - If not None, specifies the sources whose elements should be selected by ID.
  268. - Modifier - 'ADD', 'SUBTRACT', 'TOGGLE', or None to define whether and how the selection
  269. should modify the existing selection.
  270. """
  271. _selectIDsHelper('GlobalIDSelectionSource', **locals())
  272. def SelectPedigreeIDs(IDs=[], FieldType='POINT', ContainingCells=False, Source=None, Modifier=None):
  273. """Select attributes by Pedigree IDs.
  274. - IDs - list of IDs of attribute types to select. Defined as (domain, ID) pairs
  275. interleaved in a single list.
  276. - FieldType - type of attribute to select, e.g., 'POINT', 'CELL'
  277. - ContainingCells - if True and FieldType is 'POINT', select the cells containing the
  278. points corresponding to the given IDs.
  279. - Source - If not None, specifies the sources whose elements should be selected by ID.
  280. - Modifier - 'ADD', 'SUBTRACT', 'TOGGLE', or None to define whether and how the selection
  281. should modify the existing selection.
  282. """
  283. _selectIDsHelper('PedigreeIDSelectionSource', **locals())
  284. def SelectIDs(IDs=[], FieldType='POINT', ContainingCells=False, Source=None, Modifier=None):
  285. """Select attributes by attribute IDs.
  286. - IDs - list of IDs of attribute types to select. Defined as (process number, attribute ID) pairs
  287. interleaved in a single list. For multiblock datasets, this will select attributes on all
  288. blocks of the provided (processor number, attribute ID) pairs
  289. - FieldType - type of attribute to select, e.g., 'POINT', 'CELL'
  290. - ContainingCells - if True and FieldType is 'POINT', select the cells containing the
  291. points corresponding to the given IDs.
  292. - Source - If not None, specifies the sources whose elements should be selected by ID.
  293. - Modifier - 'ADD', 'SUBTRACT', 'TOGGLE', or None to define whether and how the selection
  294. should modify the existing selection.
  295. """
  296. _selectIDsHelper('IDSelectionSource', **locals())
  297. def SelectCompositeDataIDs(IDs=[], FieldType='POINT', ContainingCells=False, Source=None, Modifier=None):
  298. """Select attributes by composite attribute IDs.
  299. - IDs - list of IDs of attribute types to select. Defined as 3-tuples of
  300. (flat block index, process number, attribute ID) interleaved in a single list.
  301. - FieldType - type of attribute to select, e.g., 'POINT', 'CELL'
  302. - ContainingCells - if True and FieldType is 'POINT', select the cells containing the
  303. points corresponding to the given IDs.
  304. - Source - If not None, specifies the sources whose elements should be selected by ID.
  305. - Modifier - 'ADD', 'SUBTRACT', 'TOGGLE', or None to define whether and how the selection
  306. should modify the existing selection.
  307. """
  308. selectIDsHelper('CompositeDataIDSelectionSource', **locals())
  309. def SelectHierarchicalDataIDs(IDs=[], FieldType='POINT', ContainingCells=False, Source=None, Modifier=None):
  310. """Select attributes by hierarchical data IDs.
  311. - IDs - list of IDs of attribute types to select. Defined as 3-tuples of
  312. (level, index, attribute ID) interleaved in a single list.
  313. - FieldType - type of attribute to select, e.g., 'POINT', 'CELL'
  314. - ContainingCells - if True and FieldType is 'POINT', select the cells containing the
  315. points corresponding to the given IDs.
  316. - Source - If not None, specifies the sources whose elements should be selected by ID.
  317. - Modifier - 'ADD', 'SUBTRACT', 'TOGGLE', or None to define whether and how the selection
  318. should modify the existing selection.
  319. """
  320. _selectIDsHelper('HierarchicalDataIDSelectionSource', **locals())
  321. def SelectThresholds(Thresholds=[], ArrayName='', FieldType='POINT', Source=None, Modifier=None):
  322. """Select attributes in a source by thresholding on values in an associated array.
  323. - Thresholds - list of lower and upper threshold bounds. Attributes with associated
  324. values in the selected array between any set of bounds will be selected.
  325. - ArrayName - name of the array to threshold.
  326. - FieldType - atttribute to select, e.g., 'POINT' or 'CELL'
  327. - Source - if not set, then the selection will be on the active source
  328. """
  329. if not Source:
  330. Source = paraview.simple.GetActiveSource()
  331. repr = paraview.simple.GetRepresentation(Source)
  332. import paraview.vtk as vtk
  333. reprCollection = vtk.vtkCollection()
  334. reprCollection.AddItem(repr.SMProxy)
  335. selection = _createSelection('ThresholdSelectionSource', Thresholds=Thresholds, ArrayName=ArrayName,
  336. FieldType=FieldType)
  337. if selection:
  338. selectionCollection = vtk.vtkCollection()
  339. selectionCollection.AddItem(selection.SMProxy)
  340. _collectSelectionPorts(reprCollection, selectionCollection, Modifier=Modifier)
  341. Source.UpdateVTKObjects()
  342. def SelectLocation(Locations=[], Source=None, Modifier=None):
  343. """Select points by location.
  344. - Locations - list of x, y, z points to select.
  345. - Source - if not set, then the selection will be on the active source
  346. """
  347. if not Source:
  348. Source = paraview.simple.GetActiveSource()
  349. repr = paraview.simple.GetRepresentation(Source)
  350. import paraview.vtk as vtk
  351. reprCollection = vtk.vtkCollection()
  352. reprCollection.AddItem(repr.SMProxy)
  353. selection = _createSelection('LocationSelectionSource', Locations=Locations, FieldType='POINT')
  354. if selection:
  355. selectionCollection = vtk.vtkCollection()
  356. selectionCollection.AddItem(selection.SMProxy)
  357. _collectSelectionPorts(reprCollection, selectionCollection, Modifier=Modifier)
  358. Source.UpdateVTKObjects()
  359. def QuerySelect(QueryString='', FieldType='POINT', Source=None, InsideOut=False):
  360. """Selection by query expression.
  361. - QueryString - string with NumPy-like boolean expression defining which attributes are selected
  362. - FieldType - atttribute to select, e.g., 'POINT' or 'CELL'
  363. - Source - if not set, then the selection will be on the active source
  364. - InsideOut - Invert the selection so that attributes that do not satisfy the expression are
  365. selected instead of elements that do
  366. """
  367. if not Source:
  368. Source = paraview.simple.GetActiveSource()
  369. repr = paraview.simple.GetRepresentation(Source)
  370. import paraview.vtk as vtk
  371. reprCollection = vtk.vtkCollection()
  372. reprCollection.AddItem(repr.SMProxy)
  373. # convert FieldType to ElementType. Eventually, all public API should change
  374. # to accepting ElementType but we'll do that after all selection sources use
  375. # ElementType consistently.
  376. ftype = vtk.vtkSelectionNode.GetFieldTypeFromString(FieldType)
  377. if ftype == vtk.vtkSelectionNode.NUM_FIELD_TYPES:
  378. raise ValueError("Invalid FieldType '%s'" % FieldType)
  379. ElementType = vtk.vtkSelectionNode.ConvertSelectionFieldToAttributeType(ftype)
  380. selection = _createSelection('SelectionQuerySource', ElementType=ElementType,
  381. QueryString=QueryString, InsideOut=InsideOut)
  382. if selection:
  383. selectionCollection = vtk.vtkCollection()
  384. selectionCollection.AddItem(selection.SMProxy)
  385. _collectSelectionPorts(reprCollection, selectionCollection)
  386. Source.UpdateVTKObjects()
  387. def ClearSelection(Source=None):
  388. """ Clears the selection on the source passed in to the source parameter
  389. or the active source if no source is provided.
  390. """
  391. if Source == None:
  392. Source = paraview.simple.GetActiveSource()
  393. Source.SMProxy.SetSelectionInput(0, None, 0)