-
Notifications
You must be signed in to change notification settings - Fork 26
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
[c++/python] SOMAGeometryDataFrame
basic write
#3687
Open
XanthosXanthopoulos
wants to merge
14
commits into
main
Choose a base branch
from
xan/geometry-dataframe-mq
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+717
−247
Open
Changes from all commits
Commits
Show all changes
14 commits
Select commit
Hold shift + click to select a range
564b702
Add transformer pipeline
XanthosXanthopoulos da8d15e
Update transformer implementation
XanthosXanthopoulos 4f905d3
Add helper methods to manipulate arrow table children
XanthosXanthopoulos 4f7c5f2
Use transformer in geometry dataframe
XanthosXanthopoulos e59d825
Fix memory leaks
XanthosXanthopoulos 24d4d1c
Update transformer implementation
XanthosXanthopoulos b994ad4
Change signature of helper methods, fix arrow release callbacks
XanthosXanthopoulos e50994b
Update usage location of transformers, helper method to deserialize c…
XanthosXanthopoulos 5b55e1e
Python implementation of transformers
XanthosXanthopoulos f4b988b
Update geometry dataframe write and add unit tests
XanthosXanthopoulos 529d9ba
Add write test
XanthosXanthopoulos 1136af0
lint fixes
XanthosXanthopoulos abb8f09
Address review comments
XanthosXanthopoulos 0498c61
Remove duplicate function call
XanthosXanthopoulos File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -8,7 +8,7 @@ | |
from __future__ import annotations | ||
|
||
import warnings | ||
from typing import Any, Sequence, Tuple, Union | ||
from typing import Any, Sequence, Tuple, Union, cast | ||
|
||
import pyarrow as pa | ||
import somacore | ||
|
@@ -17,7 +17,10 @@ | |
|
||
from tiledbsoma._tdb_handles import GeometryDataFrameWrapper | ||
from tiledbsoma.options._soma_tiledb_context import _validate_soma_tiledb_context | ||
from tiledbsoma.options._tiledb_create_write_options import TileDBCreateOptions | ||
from tiledbsoma.options._tiledb_create_write_options import ( | ||
TileDBCreateOptions, | ||
TileDBWriteOptions, | ||
) | ||
|
||
from . import _arrow_types, _util | ||
from . import pytiledbsoma as clib | ||
|
@@ -35,7 +38,7 @@ | |
_revise_domain_for_extent, | ||
) | ||
from ._exception import SOMAError, map_exception_for_create | ||
from ._read_iters import TableReadIter | ||
from ._read_iters import ManagedQuery, TableReadIter | ||
from ._spatial_dataframe import SpatialDataFrame | ||
from ._spatial_util import ( | ||
coordinate_space_from_json, | ||
|
@@ -311,6 +314,17 @@ | |
|
||
# Data operations | ||
|
||
def __len__(self) -> int: | ||
"""Returns the number of rows in the geometry dataframe.""" | ||
return self.count | ||
|
||
@property | ||
def count(self) -> int: | ||
"""Returns the number of rows in the geometry dataframe.""" | ||
self._check_open_read() | ||
# if is it in read open mode, then it is a GeometryDataFrameWrapper | ||
return cast(GeometryDataFrameWrapper, self._handle).count | ||
|
||
def read( | ||
self, | ||
coords: options.SparseDFCoords = (), | ||
|
@@ -343,7 +357,19 @@ | |
Lifecycle: | ||
Experimental. | ||
""" | ||
raise NotImplementedError() | ||
del batch_size # Currently unused. | ||
_util.check_unpartitioned(partitions) | ||
self._check_open_read() | ||
|
||
# TODO: batch_size | ||
return TableReadIter( | ||
array=self, | ||
coords=coords, | ||
column_names=column_names, | ||
result_order=_util.to_clib_result_order(result_order), | ||
value_filter=value_filter, | ||
platform_config=platform_config, | ||
) | ||
|
||
def read_spatial_region( | ||
self, | ||
|
@@ -414,7 +440,71 @@ | |
Lifecycle: | ||
Experimental. | ||
""" | ||
raise NotImplementedError() | ||
_util.check_type("values", values, (pa.Table,)) | ||
|
||
write_options: Union[TileDBCreateOptions, TileDBWriteOptions] | ||
sort_coords = None | ||
if isinstance(platform_config, TileDBCreateOptions): | ||
raise ValueError( | ||
"As of TileDB-SOMA 1.13, the write method takes " | ||
"TileDBWriteOptions instead of TileDBCreateOptions" | ||
) | ||
write_options = TileDBWriteOptions.from_platform_config(platform_config) | ||
sort_coords = write_options.sort_coords | ||
|
||
clib_dataframe = self._handle._handle | ||
|
||
for batch in values.to_batches(): | ||
mq = ManagedQuery(self, None) | ||
mq._handle.set_array_data(batch) | ||
mq._handle.submit_write(sort_coords or False) | ||
|
||
if write_options.consolidate_and_vacuum: | ||
clib_dataframe.consolidate_and_vacuum() | ||
|
||
return self | ||
|
||
# Write helpers with automatic transformations | ||
|
||
def from_outlines( | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Should I know what an 'outline' is? |
||
self, | ||
values: Union[pa.RecordBatch, pa.Table], | ||
*, | ||
platform_config: options.PlatformConfig | None = None, | ||
) -> Self: | ||
"""Writes the data from an Arrow table to the persistent object | ||
applying a data transformation to transform the given outline | ||
of each polygon to the appropriate WKB encoded polygon. | ||
|
||
Geometry data provided are expected to be a list of point coordinates | ||
per polygon in the form of [x0, y0, x1, y1, ..., x0, y0] and will | ||
be converted automatically to a list of WKB encoded polygons. | ||
|
||
Args: | ||
values: An Arrow table containing all columns, including | ||
the index columns. The schema for the values must match | ||
the schema for the ``DataFrame``. `soma_geometry` column | ||
should contain lists of floating point numbers which are | ||
the point coordinates of the outline of each polygon in | ||
the form [x0, y0, x1, y1, ..., x0, y0]. | ||
|
||
Returns: ``self``, to enable method chaining. | ||
|
||
""" | ||
|
||
outline_transformer = clib.OutlineTransformer( | ||
coordinate_space_to_json(self._coord_space) | ||
) | ||
|
||
for batch in values.to_batches(): | ||
self.write( | ||
clib.TransformerPipeline(batch) | ||
.transform(outline_transformer) | ||
.asTable(), | ||
platform_config=platform_config, | ||
) | ||
|
||
return self | ||
|
||
# Metadata operations | ||
|
||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,88 @@ | ||
/** | ||
* @file transformer.cc | ||
* | ||
* @section LICENSE | ||
* | ||
* Licensed under the MIT License. | ||
* Copyright (c) TileDB, Inc. and The Chan Zuckerberg Initiative Foundation | ||
* | ||
* @section DESCRIPTION | ||
* | ||
* This file defines the TransformerPipeline, Transformer and derived classes | ||
* bindings. | ||
*/ | ||
|
||
#include <pybind11/numpy.h> | ||
#include <pybind11/pybind11.h> | ||
#include <pybind11/pytypes.h> | ||
#include <pybind11/stl.h> | ||
#include <pybind11/stl_bind.h> | ||
|
||
#include "common.h" | ||
|
||
namespace libtiledbsomacpp { | ||
|
||
namespace py = pybind11; | ||
using namespace py::literals; | ||
using namespace tiledbsoma; | ||
|
||
void load_transformers(py::module& m) { | ||
py::class_<TransformerPipeline>(m, "TransformerPipeline") | ||
.def(py::init([](py::handle py_batch) { | ||
ArrowSchema arrow_schema; | ||
ArrowArray arrow_array; | ||
uintptr_t arrow_schema_ptr = (uintptr_t)(&arrow_schema); | ||
uintptr_t arrow_array_ptr = (uintptr_t)(&arrow_array); | ||
py_batch.attr("_export_to_c")(arrow_array_ptr, arrow_schema_ptr); | ||
|
||
auto array = std::make_unique<ArrowArray>(arrow_array); | ||
auto schema = std::make_unique<ArrowSchema>(arrow_schema); | ||
|
||
return TransformerPipeline(std::move(array), std::move(schema)); | ||
})) | ||
.def( | ||
"transform", | ||
[](TransformerPipeline& pipeline, | ||
std::shared_ptr<Transformer> transformer) | ||
-> TransformerPipeline& { | ||
return pipeline.transform(transformer); | ||
}) | ||
.def("asTable", [](TransformerPipeline& pipeline) { | ||
auto pa = py::module::import("pyarrow"); | ||
auto pa_table_from_arrays = pa.attr("Table").attr("from_arrays"); | ||
auto pa_array_import = pa.attr("Array").attr("_import_from_c"); | ||
auto pa_schema_import = pa.attr("Schema").attr("_import_from_c"); | ||
|
||
auto [array, schema] = pipeline.asTable(); | ||
|
||
py::list array_list; | ||
py::list names; | ||
|
||
for (int64_t i = 0; i < schema->n_children; ++i) { | ||
// Should happen before pyarrow array construction because | ||
// py::capsule get ownership of the memory | ||
names.append(std::string(schema->children[i]->name)); | ||
|
||
auto pa_array = pa_array_import( | ||
py::capsule(array->children[i]), | ||
py::capsule(schema->children[i])); | ||
|
||
array_list.append(pa_array); | ||
} | ||
|
||
return pa_table_from_arrays(array_list, names); | ||
}); | ||
|
||
py::class_<Transformer, std::shared_ptr<Transformer>>(m, "Transformer"); | ||
py::class_< | ||
OutlineTransformer, | ||
Transformer, | ||
std::shared_ptr<OutlineTransformer>>(m, "OutlineTransformer") | ||
.def(py::init([](std::string coord_space) { | ||
auto coordinate_space = SOMACoordinateSpace::from_string( | ||
coord_space); | ||
|
||
return std::make_shared<OutlineTransformer>(coordinate_space); | ||
})); | ||
} | ||
} // namespace libtiledbsomacpp |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This is very convenient! But (AFAIK) not implemented for the other dataframe classes.
Might be worth doing for the other dataframe classes (as a separate PR).