Loading [MathJax]/extensions/tex2jax.js
DM_shape_file_write.py
1 ## @package python.demo.DM_shape_file_write
2 #
3 # \brief create a polygon shape file with an used-defined attribute table.
4 #
5 # Since shape files require at least one attribute column, the shape export class automatically adds an
6 # id attribute column if no user-defined attribute mapping (setAttributeMapping) is applied. Furthermore, the
7 # export class can optionally fill a attribute column with ascending numbers (starting from 0) by specifying
8 # the corresponding column index using 'idCounterIdx' in setAttributeMapping
9 #
10 from opals import pyDM
11 
12 # Create polygon and layout factory objects
13 pf = pyDM.PolygonFactory()
14 lf = pyDM.AddInfoLayoutFactory()
15 lf.addColumn(pyDM.ColumnSemantic.Id) # internal shape object identifier. It's automatically set by the shape export
16 lf.addColumn(pyDM.ColumnType.uint32, "_RegionId") # user-defined attribute "_RegionId" (type unsigned int)
17 layout = lf.getLayout()
18 
19 filename = "export_test.shp"
20 
21 def create_window(xmin, ymin, xmax, ymax):
22  pf.addPoint(xmin, ymin)
23  pf.addPoint(xmax, ymin)
24  pf.addPoint(xmax, ymax)
25  pf.addPoint(xmin, ymax)
26  pf.closePart()
27  return pf.getPolygon()
28 
29 
30 def set_attribute(obj, value):
31  obj.setAddInfoView(layout, False)
32  obj.info().set(1, value)
33 
34 
35 # Create table definition for the shape file
36 # Option 1: Based on layout (and optionally remove the leading underscore of user-defined attributes)
37 tableDef = pyDM.ShapeTableDefinition(layout, removeLeadingUnderscore=True)
38 # Option 2: Explicitly define name, type, width and decimals (for floating point types only) for each column
39 # as four lists. Note: the with entries needs to be appropriately set for ALL data types. Also, make
40 # sure that all lists have the same len.
41 tableDef2 = pyDM.ShapeTableDefinition(names=["Id", "RegionId"], types=[pyDM.ColumnType.uint32, pyDM.ColumnType.int32],
42  widths=[4, 8], decimals=[0, 0])
43 
44 # Create shape export with the
45 print(f"Open shape file '{filename}'")
46 exp = pyDM.ExportShape(filename)
47 exp.setAttributeMapping(layout, tableDef, idCounterIdx=0) # use attribute column 0 as automatically filled counter
48 
49 print("Write two polygons")
50 # output polygon windows 1
51 poly1 = create_window(0,0,10,10)
52 set_attribute(poly1, 30)
53 exp.write(poly1)
54 
55 # output polygon windows 2
56 poly2 = create_window(30,20,50,25)
57 set_attribute(poly2, 35)
58 exp.write(poly2)
59 
60 #close shape file
61 print("Close shape file")
62 exp.close()
63 
64 print("Done")