Data-Model¶
The Plums data-model module implements the data-model described in Data-Model.
User documentation¶
The actual data-model composition is exposed here.
It consists of 2 categories of classes:
Container classes: They are mainly descriptor classes in that they only serve to aggregates instances of various other classes in a semantic fashion with no actual functional purpose.
Type classes: They encode actual type information and a functional part which controls the way they are constructed and manipulated.
Container classes¶
-
class
plums.commons.data.data.DataPoint(tiles, annotation, id=None, **properties)[source]¶ Bases:
plums.commons.data.mixin.PropertyContainer,plums.commons.data.mixin.IdentifiedMixInData model class which aggregates a
Tileand anAnnotation, as well as additional properties.- Parameters
tiles (OrderedDict[
Tile]) – The data-point’s tiles as an ordered mapping (SeeTileCollection).annotation (
Annotation) – The data-point’s annotation.id (str) – Optional. Default to a random UUID4. An id to store along the instance.
**properties (Any) – Additional properties to store alongside the
DataPoint.
-
tiles¶ The stored data-point’s tiles as an ordered mapping.
- Type
TileCollection
-
annotation¶ The stored data-point’s annotation
- Type
Annotation
-
class
plums.commons.data.data.Annotation(record_collection, mask_collection=None, id=None, **properties)[source]¶ Bases:
plums.commons.data.mixin.PropertyContainer,plums.commons.data.mixin.IdentifiedMixInData model class which aggregates a
RecordCollectionand anMaskCollection, as well as additional properties.- Parameters
record_collection (
RecordCollection) – The annotation’s record collection.mask_collection (
MaskCollection) – The annotation’s mask collection.id (str) – Optional. Default to a random UUID4. An id to store along the instance.
**properties (Any) – Additional properties to store alongside the
DataPoint.
-
record_collection¶ The stored annotation’s record collection.
- Type
RecordCollection
-
mask_collection¶ The stored annotation’s mask collection.
- Type
MaskCollection
-
class
plums.commons.data.tile.TileCollection(*tiles, **named_tiles)[source]¶ Bases:
collections.OrderedDictAn ordered dictionary-like collection of
Tile.It is effectively a subclass of
OrderedDictwith a friendlier constructor.Named
Tilecan be added either as item tuples (in an ordered dictionary fashion) or as keyword argument, note that ordered keyword arguments where introduced in python 3.6 and using those in python 3.5 would result in a random ordering. Thus, to avoid hard to track mistake, aValueErrorwill be raised if one attempts to do so.Anonymous
Tilecan be added as position arguments, in which case atile_<n>name will be added to fit in the dictionary, where n is the currentTileindex position.- Parameters
- Raises
ValueError – If attempting to use keyword arguments on python \(<=\) 3.5.
TypeError – If any provided tile in not a
Tile-like object.
-
property
iloc¶ Access stored tiles through their insert positions.
-
class
plums.commons.data.record.RecordCollection(*records, id=None, taxonomy=None)[source]¶ Bases:
plums.commons.data.base.GeoInterfacedData model class which aggregates multiple
Recordtogether.It also implement list accessors and
append()to easily edit and access theRecordCollection.- Parameters
*records (
Record) –Recordinstances to aggregate.id (str) – Optional. Default to a random UUID4. An id to store along the instance.
taxonomy (
Taxonomy) – Optional. Default toNone. ATaxonomydescribing the range of possible values one may expect as labels in the enclosedRecord. If not provided a new implicit, “flat”Taxonomywill be constructed on the go.
-
property
taxonomy¶ The range of possible label values in the enclosed
Recordand their relationships.Warning
The setter will iterate over all enclosed
Recordto assess that the proposedTaxonomyis compatible with theRecordCollection. This might be a slow operation.- Raises
ValueError – If trying to set a
Taxonomyincompatible with the enclosedrecords.
New in version 0.2.0.
- Type
Taxonomy
-
get(max_depth=None)[source]¶ Get
Recordand cap theirlabelsto a maximum depth.See also
The label
get_labels()method which handles the lifting.- Parameters
Optional. Default to
None.- Returns
The
Recordlabels as a tuple ofLabel.- Return type
(
Label, )- Raises
ValueError – If a
max_depthis provided althoughtaxonomyis alsoNone.IndexError – If
indexis out ofrecordsrange.
New in version 0.2.0.
-
append(record)[source]¶ Append a
Recordto the stored records list.- Parameters
record (
Record) – ARecordto append to the collection.- Raises
ValueError – If trying to append a
Recordincompatible with the enclosedtaxonomy.
-
class
plums.commons.data.mask.MaskCollection(*masks)[source]¶ Bases:
objectData model class which aggregates multiple
Masktogether.It also implement a index and name handy access to stored
Mask.Examples
>>> rm = RasterMask(image, 'raster-data') >>> vm = VectorMask([[[0, 0], [0, 1], [1, 1], [0, 0]]], 'vector-data') >>> mc = MaskCollection(rm, vm) >>> mc[0] == rm True >>> mc[1] == vm True >>> mc['vector-data'] == vm True >>> mc['raster-data'] == rm True
- Parameters
*masks (
Mask) –Maskinstances to aggregate.
Type classes¶
Tile classes¶
-
class
plums.commons.data.tile.Tile(array_data)[source]¶ Bases:
plums.commons.data.base.ArrayInterfacedUtility class which wraps an
ArrayInterfacedand forward its__array_interface__.It is not intended to be instantiated as such but rather subclassed (like
TileWrapper) or used to check whether an particular instance validates as aTile.Because it registers
PIL.Image.Imageas a virtual subclasses, this implies that only subclasses ofTile(such asTileWrapper) or PillowImageare considered validTile.- Parameters
array_data (
ArrayInterfaced) – AnArrayInterfacedinstance to wrap.
-
class
plums.commons.data.tile.TileWrapper(array_data, filename=None, **properties)[source]¶ Bases:
plums.commons.data.mixin.PropertyContainer,plums.commons.data.tile.TileA wrapper around a Numpy
ndarraywhich forwards its__array_interface__.It accepts any instance which have an
__array_interface__and a shape property as a validndarray(see_Array).The properties it exposes mimic some Pillow
Imageproperties which make this class useful to wrap images opened with different library (like OpenCV) and make them usable in places where one would expect a PillowImagewith useful metadata.Transformation into an actual Pillow
Imagecan be done with:def as_pillow_image(tile_wrapper): pillow_image = PIL.Image.fromarray(np.asarray(tile_wrapper)) pillow_image.filename = tile_wrapper.filename pillow_image.info.update(tile_wrapper.info) return pillow_image
- Parameters
Record classes¶
-
class
plums.commons.data.record.Record(coordinates, labels, confidence=None, id=None, taxonomy=None, **properties)[source]¶ Bases:
plums.commons.data.mixin.PropertyContainer,plums.commons.data.base.GeoInterfacedData model class which represents a
Record.It implements the
__geo_interface__and represents itself as a GeoJSON Feature.- Parameters
coordinates (list, tuple) – A GeoJSON-valid coordinate sequence describing the
Recordshape.confidence (float) – Optional. Default to None. A
Recordconfidence score.id (str) – Optional. Default to a random UUID4. An id to store along the instance.
**properties (Any) – Additional properties to store alongside the
VectorMask.
-
taxonomy¶ If not
None, aTaxonomythrough whichlabelswill be looked up.Important
The optionally attached
taxonomyis only used to fetchlabelsand any discrepancies between the taxonomy and the stored labels will be silently swallowed unless theRecordand itsTaxonomyare part of aRecordCollection. This is because aRecordby itself is assumed to be context-agnostic and the ability to attach to ataxonomyis an implementation convenience but not a part of the data-model.New in version 0.2.0.
- Type
Taxonomy
-
properties¶ Additional properties stored alongside the
Record.Warning
The
propertiesattribute does not corresponds to the GeoJSON representation properties which also include thelabelsand theconfidencescore.- Type
-
property
labels¶ The
Recordlabels as a tuple ofLabel.If a
Taxonomyis attached to theRecord, theLabelreturned are fetched through the attachedTaxonomy.Changed in version 0.2.0.
- Type
(
Label, )
-
property
type¶ Either “Point” or “Polygon”, it is computed according to the
coordinatesstructure.- Type
-
get_labels(max_depth=None)[source]¶ Get the record
labelsand optionally cap them to a maximum depth.Hint
The way max_depth provided are interpreted depends on what was provided:
If an integer, the whole
Taxonomyis taken into account and0corresponds to__root__whereas1corresponds to theTaxonomytrue-roots.If a dictionary, the corresponding true-root sub-trees are taken into account and
0corresponds to the true-root whereas1is the first level underneath it.
- Parameters
Optional. Default to
None.- Returns
The
Recordlabels as a tuple ofLabel.- Return type
(
Label, )- Raises
ValueError – If a
max_depthis provided althoughtaxonomyis alsoNone.
New in version 0.2.0.
Mask classes¶
-
class
plums.commons.data.mask.VectorMask(coordinates, name, id=None, **properties)[source]¶ Bases:
plums.commons.data.base.GeoInterfaced,plums.commons.data.mask.MaskData model class which represents a
VectorMask.It implements the
__geo_interface__and represents itself as a GeoJSON Feature.- Parameters
Developper documentation¶
Some internal classes used for interface-checking and semantic typing and base classes for the data model implementation.
-
class
plums.commons.data.mixin.PropertyContainer(*args, **properties)[source]¶ Bases:
plums.commons.data.mixin.SlottedDictUtility class which swallows every key-word arguments provided and exposes them as attributes.
- Parameters
**properties (Any) – Properties which are stored in
propertiesand exposed as attributes.
-
class
plums.commons.data.base.ArrayInterfaced[source]¶ Bases:
objectAbstract base class which checks for the
__array_interface__property.Implement a subclass hook to check for the presence of the
__array_interface__property and mark as a virtual subclass ofArrayInterfacedclasses which implement the interface.Examples
>>> class MockArrayInterfaced(object): ... @property ... def __array_interface__(self): ... # This passes the inheritance test although this ... # __array_interface__ implementation is invalid ... return None >>> isinstance(MockArrayInterfaced(), ArrayInterfaced) True
-
class
plums.commons.data.base.GeoInterfaced(*args, **kwargs)[source]¶ Bases:
plums.commons.data.mixin.IdentifiedMixInAbstract class which checks for the
__geo_interface__property and provides a__geo_interface__.Implement a subclass hook to check for the presence of the
__geo_interface__property and mark as a virtual subclass ofGeoInterfacedclasses which implement the interface.- Parameters
id (str) – Optional. Default to a random UUID4. An id to store along the instance.
Examples
>>> class MockGeoInterfaced(object): ... @property ... def __geo_interface__(self): ... # This actually is a valid GeoJSON mapping ... return {'type': 'FeatureCollection', 'features': []} >>> isinstance(MockGeoInterfaced(), GeoInterfaced) True
-
class
plums.commons.data.Mask(name, id=None, **properties)[source]¶ Bases:
plums.commons.data.mixin.PropertyContainer,plums.commons.data.mixin.IdentifiedMixInUtility class which implements a generic template of a
Mask.It is not intended to be instantiated as such but rather subclassed (like
VectorMaskorRasterMask) or to type-test.- Parameters
Implementation helpers¶
-
class
plums.commons.data.mixin.PropertyContainer(*args, **properties)[source]¶ Bases:
plums.commons.data.mixin.SlottedDictUtility class which swallows every key-word arguments provided and exposes them as attributes.
- Parameters
**properties (Any) – Properties which are stored in
propertiesand exposed as attributes.
-
class
plums.commons.data.mixin.SlottedDictMeta(name, bases, namespace, **kwargs)[source]¶ Bases:
abc.ABCMetaAdd the attribute __all_slots__ to a class.
__all_slots__ is a set that contains all unique slots of a class, including the ones that are inherited from parents.
-
class
plums.commons.data.mixin.SlottedDict[source]¶ Bases:
objectBase class which enables both
__slots__and__dict__for mix-in classes.
-
class
plums.commons.data.mixin.IdentifiedMixIn(*args, **kwargs)[source]¶ Bases:
plums.commons.data.mixin.SlottedDictMix In class to add a unique identifier and the ability to manually provide it in the constructor.
- Parameters
id (str) – Optional. Default to a random UUID4. An id to store along the instance.
-
class
plums.commons.data.mixin.PropertyContainer(*args, **properties)[source]¶ Bases:
plums.commons.data.mixin.SlottedDictUtility class which swallows every key-word arguments provided and exposes them as attributes.
- Parameters
**properties (Any) – Properties which are stored in
propertiesand exposed as attributes.
-
class
plums.commons.data.base._Array[source]¶ Bases:
objectAbstract base class which checks for both the
__array_interface__and the shape properties.Implement a subclass hook to check for the presence of the
__array_interface__and the shape properties and mark as a virtual subclass of_Arrayclasses which implement the interface.Examples
>>> class MockArray(object): ... @property ... def __array_interface__(self): ... # This passes the inheritance test although this ... # __array_interface__ implementation is invalid ... return None ... ... @property ... def shape(self): ... # This passes the inheritance test although this ... # shape implementation is invalid ... return None >>> isinstance(MockArray(), _Array) True