mapteksdk.labs.blocks module

Implementation for sparse block model objects.

SparseBlockModel should be moved into data/blocks.py once the implementation has been finished and appropriate tests have been written. Or deleted.

class SparseBlockModel(object_id=None, lock_type=LockType.READWRITE, x_res=0, y_res=0, z_res=0, x_count=0, y_count=0, z_count=0)

Bases: mapteksdk.data.base.Topology, mapteksdk.data.primitives.block_properties.BlockProperties

Sparse Block Model Class. This is similar to a dense block model, however it allows for ‘holes’ in the model - there can be regions within the extent of the model which do not contain a block.

This allows for more compact storage for block models where a large proportion of the blocks do not contain data as blocks which do not contain data do not need to be stored. For block models in which most blocks contain data, a dense block model will provide more efficient storage.

Parameters
  • x_res (double) – The x resolution.

  • y_res (double) – The y resolution.

  • z_res (double) – The z resolution.

  • x_count (int) – The x count of blocks.

  • y_count (int) – The y count of blocks.

  • z_count (int) – The z count of blocks.

See also

DenseBlockModel

Block model which does not allow holes.

Notes

Parameters are only required for new block models.

classmethod static_type()

Return the type of sparse block model as stored in a Project.

This can be used for determining if the type of an object is a sparse block model.

property block_count

Returns the number of blocks in the block model.

save()

Save the changes made to the object.

Generally a user does not need to call this function because it is called automatically at the end of a with block using Project.new() or Project.edit().

attribute_names()

Returns a list containing the names of all object-level attributes. Use this to iterate over the object attributes.

Returns

List containing the attribute names.

Return type

list

Examples

Iterate over all object attributes of the object stared at “target” and print their values.

>>> from mapteksdk.project import Project
>>> project = Project()
>>> with project.read("target") as read_object:
...     for name in read_object.attribute_names():
...         print(name, ":", read_object.get_attribute(name))
property block_attributes

Access block attributes.

block_model.block_attributes[“Blocktastic”] will return the block attribute called “Blocktastic”.

Returns

Access to the block attributes.

Return type

PrimitiveAttributes

property block_centroids

The centroids of the blocks. This is represented as an ndarray of shape (block_count, 3) of the form: [[x1, y1, z1], [x2, y2, z2], …, [xN, yN, zN]] Where N is the block_count.

property block_colours

The colour of the blocks, represented as a ndarray of shape (block_count, 4) with each row i representing the colour of the ith block in the model in the form [Red, Green, Blue, Alpha].

When setting block colours, you may omit the Alpha component.

property block_resolution

The resolution of the block model.

This is the x_res, y_res and z_res values used when creating the model in an array. Once the block model has been created, these values cannot be changed.

property block_selection

The block selection represented as an ndarray of bools with shape: (block_count,). True indicates the block is selected; False indicates it is not selected.

Notes

In mapteksdk version 1.0, block_selection returned a 3D ndarray. To get the same functionality, see block_selection_3d property of dense block models.

property block_sizes

The block sizes represented as an ndarray of shape (block_count, 3). Each row represents the size of one block in the form [x, y, z] where x, y and z are positive numbers.

This means that the extent for the block with index i is calculated as: (block_centroids[i] - block_sizes[i] / 2, block_centroids[i] + block_sizes[i] / 2)

Notes

For DenseBlockModels, all block_sizes are the same.

property block_to_grid_index

An ndarray containing the mapping of the blocks to the row, column and slice their centroid lies within. This has shape (N, 3) where N is the block_count and each item is of the form [column, row, slice].

This means that the column, row and slice of the block centred at block_centroids[i] is block_to_grid_index[i].

For DenseBlockModels, there is only one block per grid cell and thus each item of the block_to_grid_index will be unique.

property block_visibility

The block visibility represented as an ndarray of bools with shape: (block_count,). True indicates the block is visible, False indicates it is not visible.

Notes

In mapteksdk version 1.0 block_visibility returned a 3D ndarray. To get the same functionality, see block_visibility_3d property of dense block models.

close()

Closes the object and saves the changes to the Project, preventing any further changes.

property column_count

The number of columns in the underlying block model.

This can be thought of as the number of blocks in the X direction (assuming no rotation is made). This can only be set by the block model’s constructor.

convert_to_block_coordinates(world_coordinates)

Converts points in world coordinates to points in block coordinates.

The block coordinate system for a particular model is defined such that [0, 0, 0] is the centre of the block in row 0, column 0 and slice 0. The X axis is aligned with the columns, the Y axis is aligned with the rows and the Z axis is aligned with the slices of the model. This makes the centre of the primary block in column i, row j and slice k to be: [x_res * i, y_res * j, z_res * k].

This function performs no error checking that the points lies within the model.

Parameters

world_coordinates (array_like) – Points in world coordinates to convert to block coordinates.

Returns

Numpy array containing world_coordinates converted to be in block_coordinates.

Return type

numpy.ndarray

Raises

ValueError – If world_coordinates has an invalid shape.

Notes

If a block model has origin = [0, 0, 0] and has not been rotated, then the block and world coordinate systems are identical.

Block models of differing size, origin or rotation will have different block coordinate systems.

convert_to_world_coordinates(block_coordinates)

Converts points in block coordinates to points in world coordinates.

This is the inverse of the transformation performed by convert_to_block_coordinates.

Parameters

block_coordinates (array_like) – Points in block coordinates to convert to world coordinates.

Returns

Numpy array containing block_coordinates converted to world_coordinates.

Return type

numpy.ndarray

Raises

ValueError – If block_coordinates has an invalid shape.

Notes

Block models of differing size, origin or rotation will have different block coordinate systems.

property coordinate_system

The coordinate system the points of this object are in.

Warning

Setting this property does not change the points. This is only a label stating the coordinate system the points are in.

Notes

If the object has no coordinate system, this will be None.

Changes are done directly in the project and will not be undone if an error occurs.

Examples

Creating an edge network and setting the coordinate system to be WGS84. Note that setting the coordinate system does not change the points. It is only stating which coordinate system the points are in.

>>> from pyproj import CRS
>>> from mapteksdk.project import Project
>>> from mapteksdk.data import Polygon
>>> project = Project()
>>> with project.new("cad/rectangle", Polygon) as new_edges:
...     # Coordinates are in the form [longitude, latitude]
...     new_edges.points = [[112, 9], [112, 44], [154, 44], [154, 9]]
...     new_edges.coordinate_system = CRS.from_epsg(4326)

Often a standard map projection is not convenient or accurate for a given application. In such cases a local transform can be provided to allow coordinates to be specified in a more convenient system. The below example defines a local transform where the origin is translated 1.2 degrees north and 2.1 degree east, points are scaled to be twice as far from the horizontal origin and the coordinates are rotated 45 degrees clockwise about the horizontal_origin. Note that the points of the polygon are specified in the coordinate system after the local transform has been applied.

>>> import math
>>> from pyproj import CRS
>>> from mapteksdk.project import Project
>>> from mapteksdk.data import Polygon, CoordinateSystem, LocalTransform
>>> project = Project()
>>> transform = LocalTransform(
...     horizontal_origin = [1.2, 2.1],
...     horizontal_scale_factor = 2,
...     horizontal_rotation = math.pi / 4)
>>> system = CoordinateSystem(CRS.from_epsg(20249), transform)
>>> with project.new("cad/rectangle_transform", Polygon) as new_edges:
...     new_edges.points = [[112, 9], [112, 44], [154, 44], [154, 9]]
...     new_edges.coordinate_system = system

See also

mapteksdk.data.coordinate_systems.CoordinateSystem

Allows for a coordinate system to be defined with an optional local transform.

property created_date

The date and time (in UTC) of when this object was created.

Returns

The date and time the object was created. 0:0:0 1/1/1970 if the operation failed.

Return type

datetime.datetime

delete_all_attributes()

Delete all object attributes attached to an object.

This only deletes object attributes and has no effect on PrimitiveAttributes.

Raises

RuntimeError – If all attributes cannot be deleted.

delete_attribute(attribute)

Deletes a single object-level attribute.

Deleting a non-existent object attribute will not raise an error.

Parameters

attribute (str) – Name of attribute to delete.

Returns

True if the object attribute existed and was deleted; False if the object attribute did not exist.

Return type

bool

Raises

RuntimeError – If the attribute cannot be deleted.

delete_block_attribute(attribute_name)

Delete a block attribute.

Parameters

attribute_name (str) – The name of attribute to delete.

Raises

Exception – If the object is opened in read-only mode.

dissociate_raster(raster)

Removes the raster from the object.

This is done directly on the Project and will not be undone if an error occurs.

Parameters

raster (ObjectID or Raster) – The raster to dissociate.

Returns

True if the raster was successfully dissociated from the object, False if the raster was not associated with the object.

Return type

bool

Raises

TypeError – If raster is not a Raster.

Notes

This only removes the association between the Raster and the object, it does not clear the registration information from the Raster.

Examples

Dissociate the first raster found on a picked object.

>>> from mapteksdk.project import Project
>>> from mapteksdk import operations
>>> project = Project()
>>> oid = operations.object_pick(
...     support_label="Pick an object to remove a raster from.")
... with project.edit(oid) as data_object:
...     report = f"There were no raster to remove from {oid.path}"
...     for index in data_object.rasters:
...         data_object.dissociate_raster(data_object.rasters[index])
...         report = f"Removed raster {index} from {oid.path}"
...         break
... # Now that the raster is dissociated and the object is closed,
... # the raster can be associated with a different object.
... operations.write_report("Remove Raster", report)
property extent

The axes aligned bounding extent of the object.

get_attribute(name)

Returns the value for the attribute with the specified name.

Parameters

name (str) – The name of the object attribute to get the value for.

Returns

The value of the object attribute name. For dtype = datetime.datetime this is an integer representing the number of milliseconds since 1st Jan 1970. For dtype = datetime.date this is a tuple of the form: (year, month, day).

Return type

any

Raises

KeyError – If there is no object attribute called name.

Warning

In the future this function may be changed to return datetime.datetime and datetime.date objects instead of the current representation for object attributes of type datetime.datetime or datetime.date.

get_attribute_type(name)

Returns the type of the attribute with the specified name.

Parameters

name (str) – Name of the attribute whose type should be returned.

Returns

The type of the object attribute name.

Return type

type

Raises

KeyError – If there is no object attribute called name.

get_colour_map()

Return the ID of the colour map object currently associated with this object.

Returns

The ID of the colour map object or null object ID if there is no colour map.

Return type

ObjectID

grid_index(start, stop=None)

Generates a boolean index for accessing block properties by row, column and slice instead of by block. The boolean index will include all subblocks between primary block start (inclusive) and primary block stop (exclusive), or all subblocks within primary block start if stop is not specified.

Parameters
  • start (array_like or int) – An array_like containing three elements - [column, row, slice]. The returned boolean index will include all blocks in a greater column, row and slice. If this is an integer, that integer is interpreted as the column, row and slice.

  • end (array_like or int) – An array_like containing three elements - [column, row, slice]. If None (Default) this is start + 1 (The resulting index will contain all blocks within primary block start). If not None, the boolean index will include all blocks between start (inclusive) and end (exclusive). If this is an integer, that integer is interpreted as the column, row and slice index.

Returns

A boolean index into the block property arrays. This is an array of booleans of shape (block_count,). If element i is True then subblock i is within the range specified by start and stop. If False it is not within that range.

Return type

ndarray

Raises
  • TypeError – If start or stop are invalid types.

  • ValueError – If start or stop are incorrect shapes.

Examples

These examples require a block model to be at “blockmodels/target”

This example selects all subblocks within the primary block in column 0, row 0 and slice 0:

>>> from mapteksdk.project import Project
>>> project = Project()
>>> with project.edit("blockmodels/target") as edit_model:
...     index = edit_model.grid_index([0, 0, 0])
...     edit_model.block_selection[index] = True

By passing two values to grid index, it is possible to operate on all subblocks within a range of subblocks. This example passes [0, 2, 2] and [4, 5, 6] meaning all subblocks which have 0 <= column < 4 and 2 <= row < 5 and 2 <= slice < 6 will be selected by grid_index. By passing this index to block visibility, all subblocks within those primary blocks are made invisible.

>>> from mapteksdk.project import Project
>>> project = Project()
>>> with project.edit("blockmodels/target") as edit_model:
...     index = edit_model.grid_index([0, 2, 2], [4, 5, 6])
...     edit_model.block_visibility[index] = False
property id

Object ID that uniquely references this object in the project.

Returns

The unique id of this object.

Return type

ObjectID

property lock_type

Indicates whether operating in read-only or read-write mode.

Returns

The type of lock.

Return type

LockType

property modified_date

The date and time (in UTC) of when this object was last modified.

Returns

The date and time this object was last modified. 0:0:0 1/1/1970 if the operation failed.

Return type

datetime.datetime

property origin

The origin of the block model represented as a point.

Setting the origin will translate the entire block model to be centred around the new origin.

Notes

For DenseBlockModels the resulting changes to the block_centroids will not occur until save is called. For SubblockedBlockModels the resulting changes to the block_centroids are immediately available, however changing the origin of such a model is slower.

Examples

Changing the origin will change the block model centroids, in this case by translating them by 1 unit in the X direction, 2 units in the Y direction and 3 units in the Z direction. Note that as this is a DenseBlockModel, the model needs to be saved (in this case via closing ending the with block) before the changes to the centroids will occur.

>>> from mapteksdk.project import Project
>>> from mapteksdk.data import DenseBlockModel
>>> project = Project()
>>> with project.new("blockmodels/model", DenseBlockModel(
...         x_res=2, y_res=3, z_res=4,
...         x_count=2, y_count=2, z_count=2)) as new_model:
...     new_model.origin = [1, 2, 3]
>>> with project.edit("blockmodels/model") as edit_model:
...     print(edit_model.block_centroids)
[[1, 2, 3], [3, 2, 3], [1, 5, 3], [3, 5, 3], [1, 2, 7], [3, 2, 7],
[1, 5, 7], [3, 5, 7]]
property rasters

A dictionary of raster indices and Object IDs of the raster images currently associated with this object.

The keys are the raster ids and the values are the Object IDs of the associated rasters. Note that all raster ids are integers however they may not be consecutive - for example, an object may have raster ids 0, 1, 5 and 200.

Notes

Rasters with higher indices appear on top of rasters with lower indices. The maximum possible raster id is 255.

Removing a raster from this dictionary will not remove the raster association from the object. Use dissociate_raster to do this.

Examples

Iterate over all rasters on an object and invert the colours. Note that this will fail if there is no object at the path “target” and it will do nothing if no rasters are associated with the target.

>>> from mapteksdk.project import Project
>>> project = Project()
>>> with project.read("target") as read_object:
...     for raster in read_object.rasters.values():
...         with project.edit(raster) as edit_raster:
...             edit_raster.pixels[:, :3] = 255 - edit_raster.pixels[:, :3]
property row_count

The number of rows in the underlying block model.

This can be thought of as the number of blocks in the Y direction (assuming no rotation is made). This can only be set by the block model’s constructor.

save_block_attribute(attribute_name, data)

Create a new block attribute with the specified name and associate the specified data.

Parameters
  • attribute_name (str) – The name of attribute.

  • data (array_like) – Data for the associated attribute. This should be a ndarray of shape (block_count,). The ith entry in this array is the value of this primitive attribute for the ith block.

Raises
  • Exception – If the object is opened in read-only mode.

  • ValueError – If the type of the attribute is not supported.

set_attribute(name, dtype, data)

Sets the value for the object attribute with the specified name. This will overwrite any existing attribute with the specified name.

Parameters
  • name (str) – The name of the object attribute for which the value should be set.

  • dtype (type) – The type of data to assign to the attribute. This should be a type from the ctypes module or datetime.datetime or datetime.date. Passing bool is equivalent to passing ctypes.c_bool. Passing str is equivalent to passing ctypes.c_char_p. Passing int is equivalent to passing ctypes.c_int16. Passing float is equivalent to passing ctypes.c_double.

  • data (any) – The value to assign to object attribute name. For dtype = datetime.datetime this can either be a datetime object or timestamp which will be passed directly to datetime.utcfromtimestamp(). For dtype = datetime.date this can either be a date object or a tuple of the form: (year, month, day).

Raises
  • ValueError – If dtype is an unsupported type.

  • TypeError – If value is an inappropriate type for object attribute name.

  • RuntimeError – If a different error occurs.

Warning

Object attributes are saved separately from the object itself - any changes made by this function (assuming it does not raise an error) will be saved even if save() is not called (for example, due to an error being raised by another function).

Examples

Create an object attribute on an object at “target” and then read its value.

>>> import ctypes
>>> from mapteksdk.project import Project
>>> project = Project()
>>> with project.edit("target") as edit_object:
...     edit_object.set_attribute("count", ctypes.c_int16, 0)
... with project.read("target") as read_object:
...     print(read_object.get_attribute("count"))
0
property slice_count

The number of slices in the underlying block model.

This can be thought of as the number of blocks in the Z direction (assuming no rotation is made). This can only be set by the block model’s constructor.