diff --git a/testbed/Textualize__textual/.coveragerc b/testbed/Textualize__textual/.coveragerc new file mode 100644 index 0000000000000000000000000000000000000000..d16dd221a08769ff14945ff00e549fceacb2f018 --- /dev/null +++ b/testbed/Textualize__textual/.coveragerc @@ -0,0 +1,9 @@ +[run] +omit = + +[report] +exclude_lines = + pragma: no cover + if TYPE_CHECKING: + if __name__ == "__main__": + @overload diff --git a/testbed/Textualize__textual/.gitignore b/testbed/Textualize__textual/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..4580aac9a01c29944bec729c9c3f1febad06f5a5 --- /dev/null +++ b/testbed/Textualize__textual/.gitignore @@ -0,0 +1,118 @@ +*.ipynb +.pytype +.DS_Store +.vscode +.idea +mypy_report +docs/build +docs/source/_build +tools/*.txt +playground/ + +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] +*$py.class + +# C extensions +*.so + +# Distribution / packaging +.Python +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +wheels/ +*.egg-info/ +.installed.cfg +*.egg +MANIFEST + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*.cover +.hypothesis/ +.pytest_cache/ + +# Translations +*.mo +*.pot + +# Django stuff: +*.log +local_settings.py +db.sqlite3 + +# Flask stuff: +instance/ +.webassets-cache + +# Scrapy stuff: +.scrapy + +# Sphinx documentation +docs/_build/ + +# PyBuilder +target/ + +# Jupyter Notebook +.ipynb_checkpoints + +# pyenv +.python-version + +# celery beat schedule file +celerybeat-schedule + +# SageMath parsed files +*.sage.py + +# Environments +.env +.venv +env/ +venv/ +ENV/ +env.bak/ +venv.bak/ + +# Spyder project settings +.spyderproject +.spyproject + +# Rope project settings +.ropeproject + +# mkdocs documentation +/site + +# mypy +.mypy_cache/ + +# Snapshot testing report output directory +tests/snapshot_tests/output diff --git a/testbed/Textualize__textual/.pre-commit-config.yaml b/testbed/Textualize__textual/.pre-commit-config.yaml new file mode 100644 index 0000000000000000000000000000000000000000..9e507b1e261bf7531e53157d4992efc18ed0b485 --- /dev/null +++ b/testbed/Textualize__textual/.pre-commit-config.yaml @@ -0,0 +1,16 @@ +# See https://pre-commit.com for more information +# See https://pre-commit.com/hooks.html for more hooks +repos: +- repo: https://github.com/pre-commit/pre-commit-hooks + rev: v4.3.0 + hooks: + - id: trailing-whitespace + - id: end-of-file-fixer + - id: check-yaml + args: ['--unsafe'] +- repo: https://github.com/psf/black + rev: 22.3.0 + hooks: + - id: black + exclude: ^tests/ +exclude: ^tests/snapshot_tests diff --git a/testbed/Textualize__textual/CHANGELOG.md b/testbed/Textualize__textual/CHANGELOG.md new file mode 100644 index 0000000000000000000000000000000000000000..4e679a7499451f7bf268065f0fa1420d375d265d --- /dev/null +++ b/testbed/Textualize__textual/CHANGELOG.md @@ -0,0 +1,106 @@ +# Change Log + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](http://keepachangelog.com/) +and this project adheres to [Semantic Versioning](http://semver.org/). + +## [0.2.0] - Unreleased + +### Added + +- CSS support +- Too numerous to mention + +## [0.1.15] - 2022-01-31 + +### Added + +- Added Windows Driver + +## [0.1.14] - 2022-01-09 + +### Changed + +- Updated Rich dependency to 11.X + +## [0.1.13] - 2022-01-01 + +### Fixed + +- Fixed spurious characters when exiting app +- Fixed increasing delay when exiting + +## [0.1.12] - 2021-09-20 + +### Added + +- Added geometry.Spacing + +### Fixed + +- Fixed calculation of virtual size in scroll views + +## [0.1.11] - 2021-09-12 + +### Changed + +- Changed message handlers to use prefix handle\_ +- Renamed messages to drop the Message suffix +- Events now bubble by default +- Refactor of layout + +### Added + +- Added App.measure +- Added auto_width to Vertical Layout, WindowView, an ScrollView +- Added big_table.py example +- Added easing.py example + +## [0.1.10] - 2021-08-25 + +### Added + +- Added keyboard control of tree control +- Added Widget.gutter to calculate space between renderable and outside edge +- Added margin, padding, and border attributes to Widget + +### Changed + +- Callbacks may be async or non-async. +- Event handler event argument is optional. +- Fixed exception in clock example https://github.com/willmcgugan/textual/issues/52 +- Added Message.wait() which waits for a message to be processed +- Key events are now sent to widgets first, before processing bindings + +## [0.1.9] - 2021-08-06 + +### Added + +- Added hover over and mouse click to activate keys in footer +- Added verbosity argument to Widget.log + +### Changed + +- Simplified events. Remove Startup event (use Mount) +- Changed geometry.Point to geometry.Offset and geometry.Dimensions to geometry.Size + +## [0.1.8] - 2021-07-17 + +### Fixed + +- Fixed exiting mouse mode +- Fixed slow animation + +### Added + +- New log system + +## [0.1.7] - 2021-07-14 + +### Changed + +- Added functionality to calculator example. +- Scrollview now shows scrollbars automatically +- New handler system for messages that doesn't require inheritance +- Improved traceback handling diff --git a/testbed/Textualize__textual/LICENSE b/testbed/Textualize__textual/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..3a4399759e40dba1d833698e2d585f2e81f0c695 --- /dev/null +++ b/testbed/Textualize__textual/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2021 Will McGugan + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/testbed/Textualize__textual/Makefile b/testbed/Textualize__textual/Makefile new file mode 100644 index 0000000000000000000000000000000000000000..429996c68d4afb4fcbf0e74a83fb6ac872ce8519 --- /dev/null +++ b/testbed/Textualize__textual/Makefile @@ -0,0 +1,18 @@ +test: + pytest --cov-report term-missing --cov=textual tests/ -vv +unit-test: + pytest --cov-report term-missing --cov=textual tests/ -vv -m "not integration_test" +test-snapshot-update: + pytest --cov-report term-missing --cov=textual tests/ -vv --snapshot-update +typecheck: + mypy src/textual +format: + black src +format-check: + black --check src +docs-serve: + mkdocs serve +docs-build: + mkdocs build +docs-deploy: + mkdocs gh-deploy diff --git a/testbed/Textualize__textual/README.md b/testbed/Textualize__textual/README.md new file mode 100644 index 0000000000000000000000000000000000000000..16a5c89ebb3818b6fc452fb9909adda9a154b622 --- /dev/null +++ b/testbed/Textualize__textual/README.md @@ -0,0 +1,112 @@ +# Textual + +![Textual splash image](./imgs/textual.png) + +Textual is a Python framework for creating interactive applications that run in your terminal. + +
+ ๐ŸŽฌ Code browser +
+ + This is the [code_browser.py](./examples/code_browser.py) example which clocks in at 61 lines (*including* docstrings and blank lines). + + https://user-images.githubusercontent.com/554369/189394703-364b5caa-97e0-45db-907d-7b1620d6411f.mov + +
+ + +## About + +Textual adds interactivity to [Rich](https://github.com/Textualize/rich) with a Python API inspired by modern development development. + +On modern terminal software (installed by default on most systems), Textual apps can use **16.7 million** colors with mouse support and smooth flicker-free animation. A powerful layout engine and re-usable components makes it possible to build apps that rival the desktop and web experience. + +## Compatibility + +Textual runs on Linux, macOS, and Windows. Textual requires Python 3.7 or above. + +## Installing + +Install Textual via pip: + +``` +pip install textual[dev] +``` + +The addition of `[dev]` installs Textual development tools. + + +## Reference commands + +The `textual` command has a few sub-commands to preview Textual styles. + +
+ ๐ŸŽฌ Easing reference +
+ +This is the *easing* reference which demonstrates the easing parameter on animation, with both movement and opacity. You can run it with the following command: + +```bash +textual easing +``` + +https://user-images.githubusercontent.com/554369/189485538-31e794ff-61d7-4faf-902a-6e90a9d76e5b.mov + +
+ +
+ ๐ŸŽฌ Borders reference +
+ +This is the borders reference which demonstrates some of the borders styles in Textual. You can run it with the following command: + +```bash +textual borders +``` + + +https://user-images.githubusercontent.com/554369/189485735-cb2b4135-caee-46d7-a118-66cd7ed9eef5.mov + + + +
+ +## Examples + +The Textual repository comes with a number of examples you can experiment with or use as a template for your own projects. + +
+ ๐Ÿ“ท Calculator +
+ +This is [calculator.py](./examples/calculator.py) which demonstrates Textual grid layouts. + +![calculator screenshot](./imgs/calculator.svg) +
+ +
+ ๐Ÿ“ท Code browser +
+ + This is [code_browser.py](./examples/code_browser.py) which demonstrates the directory tree widget. + +![code browser screenshot](./imgs/codebrowser.svg) + +
+ + +
+ ๐Ÿ“ท Stopwatch +
+ + This is the Stopwatch example from the tutorial. + +### Light theme + +![stopwatch light screenshot](./imgs/stopwatch_light.svg) + +### Dark theme + +![stopwatch dark screenshot](./imgs/stopwatch_dark.svg) + +
diff --git a/testbed/Textualize__textual/custom_theme/main.html b/testbed/Textualize__textual/custom_theme/main.html new file mode 100644 index 0000000000000000000000000000000000000000..810469c9ffa43764f5de73b0f5016c514cd719dc --- /dev/null +++ b/testbed/Textualize__textual/custom_theme/main.html @@ -0,0 +1,5 @@ +{% extends "base.html" %} + +{% block extrahead %} + +{% endblock %} diff --git a/testbed/Textualize__textual/docs.md b/testbed/Textualize__textual/docs.md new file mode 100644 index 0000000000000000000000000000000000000000..63c47ed6a6c79b603c845c4eacccaf4992b50643 --- /dev/null +++ b/testbed/Textualize__textual/docs.md @@ -0,0 +1,18 @@ +# Documentation Workflow + +* Ensure you're inside a *Python 3.10+* virtual environment +* Run the live-reload server using `mkdocs serve` from the project root +* Create new pages by adding new directories and Markdown files inside `docs/*` + +## Commands + +- `mkdocs serve` - Start the live-reloading docs server. +- `mkdocs build` - Build the documentation site. +- `mkdocs -h` - Print help message and exit. + +## Project layout + + mkdocs.yml # The configuration file. + docs/ + index.md # The documentation homepage. + ... # Other markdown pages, images and other files. diff --git a/testbed/Textualize__textual/docs/CNAME b/testbed/Textualize__textual/docs/CNAME new file mode 100644 index 0000000000000000000000000000000000000000..a3d735267c9ae9998a2846e34d6963233688a641 --- /dev/null +++ b/testbed/Textualize__textual/docs/CNAME @@ -0,0 +1 @@ +textual.textualize.io diff --git a/testbed/Textualize__textual/e2e_tests/sandbox_basic_test.py b/testbed/Textualize__textual/e2e_tests/sandbox_basic_test.py new file mode 100644 index 0000000000000000000000000000000000000000..6cd87ddac1901fe72798acb4544cfa25fdddfe6b --- /dev/null +++ b/testbed/Textualize__textual/e2e_tests/sandbox_basic_test.py @@ -0,0 +1,55 @@ +from __future__ import annotations + +import shlex +import sys +import subprocess +import threading +from pathlib import Path + +target_script_name = "basic" +script_time_to_live = 2.0 # in seconds + +if len(sys.argv) > 1: + target_script_name = sys.argv[1] +if len(sys.argv) > 2: + script_time_to_live = float(sys.argv[2]) + +e2e_root = Path(__file__).parent / "test_apps" + +completed_process = None + + +def launch_sandbox_script(python_file_name: str) -> None: + global completed_process + + command = f"{sys.executable} {shlex.quote(python_file_name)}.py" + print(f"Launching command '{command}'...") + try: + completed_process = subprocess.run( + command, shell=True, check=True, capture_output=True, cwd=str(e2e_root) + ) + except subprocess.CalledProcessError as err: + print(f"Process error: {err.stderr}") + raise + + +thread = threading.Thread( + target=launch_sandbox_script, args=(target_script_name,), daemon=False +) +thread.start() + +print( + f"Launching Python script in a sub-thread; we'll wait for it for {script_time_to_live} seconds..." +) +thread.join(timeout=script_time_to_live) +print("The wait is over.") + +process_still_running = completed_process is None +process_was_able_to_run_without_errors = process_still_running + +if process_was_able_to_run_without_errors: + print("Python script is still running :-)") +else: + print("Python script is no longer running :-/") + +sys.exit(0 if process_was_able_to_run_without_errors else 1) diff --git a/testbed/Textualize__textual/e2e_tests/test_apps/basic.css b/testbed/Textualize__textual/e2e_tests/test_apps/basic.css new file mode 100644 index 0000000000000000000000000000000000000000..88de0d53538d74e8d8788c043c665baa99d7e2b2 --- /dev/null +++ b/testbed/Textualize__textual/e2e_tests/test_apps/basic.css @@ -0,0 +1,250 @@ +/* CSS file for basic.py */ + + + + * { + transition: color 300ms linear, background 300ms linear; +} + + +*:hover { + /* tint: 30% red; + /* outline: heavy red; */ +} + +App > Screen { + + background: $background; + color: $text; + layers: base sidebar; + layout: vertical; + overflow: hidden; +} + +#tree-container { + overflow-y: auto; + height: 20; + margin: 1 2; + background: $surface; + padding: 1 2; +} + +DirectoryTree { + padding: 0 1; + height: auto; + +} + + + + +DataTable { + /*border:heavy red;*/ + /* tint: 10% green; */ + /* text-opacity: 50%; */ + padding: 1; + margin: 1 2; + height: 24; +} + +#sidebar { + background: $panel; + color: $text; + dock: left; + width: 30; + margin-bottom: 1; + offset-x: -100%; + + transition: offset 500ms in_out_cubic; + layer: sidebar; +} + +#sidebar.-active { + offset-x: 0; +} + +#sidebar .title { + height: 1; + background: $primary-background-darken-1; + color: $text; + border-right: wide $background; + content-align: center middle; +} + +#sidebar .user { + height: 8; + background: $panel-darken-1; + color: $text; + border-right: wide $background; + content-align: center middle; +} + +#sidebar .content { + background: $panel-darken-2; + color: $text; + border-right: wide $background; + content-align: center middle; +} + + + + +Tweet { + height:12; + width: 100%; + margin: 0 2; + + margin:0 2; + background: $panel; + color: $text; + layout: vertical; + /* border: outer $primary; */ + padding: 1; + border: wide $panel; + overflow: auto; + /* scrollbar-gutter: stable; */ + align-horizontal: center; + box-sizing: border-box; + +} + + +.scrollable { + overflow-x: auto; + overflow-y: scroll; + margin: 1 2; + height: 24; + align-horizontal: center; + layout: vertical; +} + +.code { + height: auto; + +} + + +TweetHeader { + height:1; + background: $accent; + color: $text; +} + +TweetBody { + width: 100%; + background: $panel; + color: $text; + height: auto; + padding: 0 1 0 0; +} + +Tweet.scroll-horizontal TweetBody { + width: 350; +} + +.button { + background: $accent; + color: $text; + width:20; + height: 3; + /* border-top: hidden $accent-darken-3; */ + border: tall $accent-darken-2; + /* border-left: tall $accent-darken-1; */ + + + /* padding: 1 0 0 0 ; */ + + transition: background 400ms in_out_cubic, color 400ms in_out_cubic; + +} + +.button:hover { + background: $accent-lighten-1; + color: $text; + width: 20; + height: 3; + border: tall $accent-darken-1; + /* border-left: tall $accent-darken-3; */ + + + + +} + +#footer { + color: $text; + background: $accent; + height: 1; + + content-align: center middle; + dock:bottom; +} + + +#sidebar .content { + layout: vertical +} + +OptionItem { + height: 3; + background: $panel; + border-right: wide $background; + border-left: blank; + content-align: center middle; +} + +OptionItem:hover { + height: 3; + color: $text; + background: $primary-darken-1; + /* border-top: hkey $accent2-darken-3; + border-bottom: hkey $accent2-darken-3; */ + text-style: bold; + border-left: outer $secondary-darken-2; +} + +Error { + width: 100%; + height:3; + background: $error; + color: $text; + border-top: tall $error-darken-2; + border-bottom: tall $error-darken-2; + + padding: 0; + text-style: bold; + align-horizontal: center; +} + +Warning { + width: 100%; + height:3; + background: $warning; + color: $text; + border-top: tall $warning-darken-2; + border-bottom: tall $warning-darken-2; + + text-style: bold; + align-horizontal: center; +} + +Success { + width: 100%; + + height:auto; + box-sizing: border-box; + background: $success; + color: $text; + + border-top: hkey $success-darken-2; + border-bottom: hkey $success-darken-2; + + text-style: bold ; + + align-horizontal: center; +} + + +.horizontal { + layout: horizontal +} diff --git a/testbed/Textualize__textual/e2e_tests/test_apps/basic.py b/testbed/Textualize__textual/e2e_tests/test_apps/basic.py new file mode 100644 index 0000000000000000000000000000000000000000..4b44a4f6ebe69365b097be5f88adf99daa105350 --- /dev/null +++ b/testbed/Textualize__textual/e2e_tests/test_apps/basic.py @@ -0,0 +1,236 @@ +from rich.console import RenderableType + +from rich.syntax import Syntax +from rich.text import Text + +from textual.app import App, ComposeResult +from textual.reactive import Reactive +from textual.widget import Widget +from textual.widgets import Static, DataTable, DirectoryTree, Header, Footer +from textual.containers import Container + +CODE = ''' +from __future__ import annotations + +from typing import Iterable, TypeVar + +T = TypeVar("T") + + +def loop_first(values: Iterable[T]) -> Iterable[tuple[bool, T]]: + """Iterate and generate a tuple with a flag for first value.""" + iter_values = iter(values) + try: + value = next(iter_values) + except StopIteration: + return + yield True, value + for value in iter_values: + yield False, value + + +def loop_last(values: Iterable[T]) -> Iterable[tuple[bool, T]]: + """Iterate and generate a tuple with a flag for last value.""" + iter_values = iter(values) + try: + previous_value = next(iter_values) + except StopIteration: + return + for value in iter_values: + yield False, previous_value + previous_value = value + yield True, previous_value + + +def loop_first_last(values: Iterable[T]) -> Iterable[tuple[bool, bool, T]]: + """Iterate and generate a tuple with a flag for first and last value.""" + iter_values = iter(values) + try: + previous_value = next(iter_values) + except StopIteration: + return + first = True + for value in iter_values: + yield first, False, previous_value + first = False + previous_value = value + yield first, True, previous_value +''' + + +lorem_short = """Lorem ipsum dolor sit amet, consectetur adipiscing elit. In velit liber a a a, volutpat nec hendrerit at, faucibus in odio. Aliquam hendrerit nibh sed quam volutpat maximus. Nullam suscipit convallis lorem quis sodales. In tristique lobortis ante et dictum. Ut at finibus ipsum.""" +lorem = ( + lorem_short + + """ In urna dolor, placerat et mi facilisis, congue sollicitudin massa. Phasellus felis turpis, cursus eu lectus et, porttitor malesuada augue. Sed feugiat volutpat velit, sollicitudin fringilla velit bibendum faucibus. Lorem ipsum dolor sit amet, consectetur adipiscing elit. In velit libero, volutpat nec hendrerit at, faucibus in odio. Aliquam hendrerit nibh sed quam volutpat maximus. Nullam suscipit convallis lorem quis sodales. In tristique lobortis ante et dictum. Ut at finibus ipsum. In urna dolor, placerat et mi facilisis, congue sollicitudin massa. Phasellus felis turpis, cursus eu lectus et, porttitor malesuada augue. Sed feugiat volutpat velit, sollicitudin fringilla velit bibendum faucibus. """ +) + +lorem_short_text = Text.from_markup(lorem_short) +lorem_long_text = Text.from_markup(lorem * 2) + + +class TweetHeader(Widget): + def render(self) -> RenderableType: + return Text("Lorem Impsum", justify="center") + + +class TweetBody(Widget): + short_lorem = Reactive(False) + + def render(self) -> Text: + return lorem_short_text if self.short_lorem else lorem_long_text + + +class Tweet(Widget): + pass + + +class OptionItem(Widget): + def render(self) -> Text: + return Text("Option") + + +class Error(Widget): + def render(self) -> Text: + return Text("This is an error message", justify="center") + + +class Warning(Widget): + def render(self) -> Text: + return Text("This is a warning message", justify="center") + + +class Success(Widget): + def render(self) -> Text: + return Text("This is a success message", justify="center") + + +class BasicApp(App): + """A basic app demonstrating CSS""" + + CSS_PATH = "basic.css" + + def on_load(self): + """Bind keys here.""" + self.bind("s", "toggle_class('#sidebar', '-active')", description="Sidebar") + self.bind("d", "toggle_dark", description="Dark mode") + self.bind("q", "quit", description="Quit") + self.bind("f", "query_test", description="Query test") + + def compose(self): + yield Header() + + table = DataTable() + self.scroll_to_target = Tweet(TweetBody()) + + yield Container( + Tweet(TweetBody()), + Widget( + Static( + Syntax(CODE, "python", line_numbers=True, indent_guides=True), + classes="code", + ), + classes="scrollable", + ), + table, + Widget(DirectoryTree("~/"), id="tree-container"), + Error(), + Tweet(TweetBody(), classes="scrollbar-size-custom"), + Warning(), + Tweet(TweetBody(), classes="scroll-horizontal"), + Success(), + Tweet(TweetBody(), classes="scroll-horizontal"), + Tweet(TweetBody(), classes="scroll-horizontal"), + Tweet(TweetBody(), classes="scroll-horizontal"), + Tweet(TweetBody(), classes="scroll-horizontal"), + Tweet(TweetBody(), classes="scroll-horizontal"), + ) + yield Widget( + Widget(classes="title"), + Widget(classes="user"), + OptionItem(), + OptionItem(), + OptionItem(), + Widget(classes="content"), + id="sidebar", + ) + yield Footer() + + table.add_column("Foo", width=20) + table.add_column("Bar", width=20) + table.add_column("Baz", width=20) + table.add_column("Foo", width=20) + table.add_column("Bar", width=20) + table.add_column("Baz", width=20) + table.zebra_stripes = True + for n in range(100): + table.add_row(*[f"Cell ([b]{n}[/b], {col})" for col in range(6)]) + + def on_mount(self): + self.sub_title = "Widget demo" + + async def on_key(self, event) -> None: + await self.dispatch_key(event) + + def action_toggle_dark(self): + self.dark = not self.dark + + def action_query_test(self): + query = self.query("Tweet") + self.log(query) + self.log(query.nodes) + self.log(query) + self.log(query.nodes) + + query.set_styles("outline: outer red;") + + query = query.exclude(".scroll-horizontal") + self.log(query) + self.log(query.nodes) + + # query = query.filter(".rubbish") + # self.log(query) + # self.log(query.first()) + + async def key_q(self): + await self.shutdown() + + def key_x(self): + self.panic(self.tree) + + def key_escape(self): + self.app.bell() + + def key_t(self): + # Pressing "t" toggles the content of the TweetBody widget, from a long "Lorem ipsum..." to a shorter one. + tweet_body = self.query("TweetBody").first() + tweet_body.short_lorem = not tweet_body.short_lorem + + def key_v(self): + self.get_child(id="content").scroll_to_widget(self.scroll_to_target) + + def key_space(self): + self.bell() + + +if __name__ == "__main__": + app = BasicApp() + app.run(quit_after=2) + + # from textual.geometry import Region + # from textual.color import Color + + # print(Region.intersection.cache_info()) + # print(Region.overlaps.cache_info()) + # print(Region.union.cache_info()) + # print(Region.split_vertical.cache_info()) + # print(Region.__contains__.cache_info()) + # from textual.css.scalar import Scalar + + # print(Scalar.resolve_dimension.cache_info()) + + # from rich.style import Style + # from rich.cells import cached_cell_len + + # print(Style._add.cache_info()) + + # print(cached_cell_len.cache_info()) diff --git a/testbed/Textualize__textual/examples/README.md b/testbed/Textualize__textual/examples/README.md new file mode 100644 index 0000000000000000000000000000000000000000..0463bd2ebacb45aadd1a0c35e26a0ad93ab3bb27 --- /dev/null +++ b/testbed/Textualize__textual/examples/README.md @@ -0,0 +1,10 @@ +# Textual Examples + +This directory contains example Textual applications. + +To run them, navigate to the examples directory and enter `python` followed buy the name of the Python file. + +``` +cd textual/examples +python pride.py +``` diff --git a/testbed/Textualize__textual/imgs/calculator.svg b/testbed/Textualize__textual/imgs/calculator.svg new file mode 100644 index 0000000000000000000000000000000000000000..dbe6a88415437f880ab030c6d2cb9077323694af --- /dev/null +++ b/testbed/Textualize__textual/imgs/calculator.svg @@ -0,0 +1,172 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + CalculatorApp + + + + + + + + + + + + +0 + + + +โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–” + AC  +/-  %  รท  +โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ– + +โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–” + 7  8  9  ร—  +โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ– + +โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–” + 4  5  6  -  +โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ– + +โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–” + 1  2  3  +  +โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ– + +โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–” + 0  .  =  +โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ–โ– + + + + diff --git a/testbed/Textualize__textual/mkdocs.yml b/testbed/Textualize__textual/mkdocs.yml new file mode 100644 index 0000000000000000000000000000000000000000..68aef278a40b3fe51c25c5cb07f43ea6487d1df8 --- /dev/null +++ b/testbed/Textualize__textual/mkdocs.yml @@ -0,0 +1,197 @@ +site_name: Textual +site_url: https://textual.textualize.io/ +repo_url: https://github.com/textualize/textual/ +edit_uri: edit/css/docs/ + +nav: + - Introduction: + - "index.md" + - "getting_started.md" + - "tutorial.md" + - Guide: + - "guide/index.md" + - "guide/devtools.md" + - "guide/app.md" + - "guide/styles.md" + - "guide/CSS.md" + - "guide/queries.md" + - "guide/layout.md" + - "guide/events.md" + - "guide/input.md" + - "guide/actions.md" + - "guide/reactivity.md" + - "guide/widgets.md" + - "guide/animation.md" + - "guide/screens.md" + - How to: + - "how-to/index.md" + - "how-to/animation.md" + - "how-to/mouse-and-keyboard.md" + - "how-to/scroll.md" + - Events: + - "events/index.md" + - "events/blur.md" + - "events/descendant_blur.md" + - "events/descendant_focus.md" + - "events/enter.md" + - "events/focus.md" + - "events/hide.md" + - "events/key.md" + - "events/leave.md" + - "events/load.md" + - "events/mount.md" + - "events/mouse_capture.md" + - "events/click.md" + - "events/mouse_down.md" + - "events/mouse_move.md" + - "events/mouse_release.md" + - "events/mouse_scroll_down.md" + - "events/mouse_scroll_up.md" + - "events/mouse_up.md" + - "events/paste.md" + - "events/resize.md" + - "events/screen_resume.md" + - "events/screen_suspend.md" + - "events/show.md" + - Styles: + - "styles/index.md" + - "styles/align.md" + - "styles/background.md" + - "styles/border.md" + - "styles/box_sizing.md" + - "styles/color.md" + - "styles/content_align.md" + - "styles/display.md" + - "styles/dock.md" + - "styles/grid.md" + - "styles/height.md" + - "styles/layer.md" + - "styles/layers.md" + - "styles/layout.md" + - "styles/margin.md" + - "styles/max_height.md" + - "styles/max_width.md" + - "styles/min_height.md" + - "styles/min_width.md" + - "styles/offset.md" + - "styles/opacity.md" + - "styles/outline.md" + - "styles/overflow.md" + - "styles/padding.md" + - "styles/scrollbar.md" + - "styles/scrollbar_gutter.md" + - "styles/scrollbar_size.md" + - "styles/text_align.md" + - "styles/text_style.md" + - "styles/text_opacity.md" + - "styles/tint.md" + - "styles/visibility.md" + - "styles/width.md" + - Widgets: + - "widgets/button.md" + - "widgets/data_table.md" + - "widgets/footer.md" + - "widgets/header.md" + - "widgets/index.md" + - "widgets/input.md" + - "widgets/static.md" + - "widgets/tree_control.md" + - Reference: + - "reference/app.md" + - "reference/button.md" + - "reference/color.md" + - "reference/containers.md" + - "reference/dom_node.md" + - "reference/events.md" + - "reference/footer.md" + - "reference/geometry.md" + - "reference/header.md" + - "reference/index.md" + - "reference/message_pump.md" + - "reference/message.md" + - "reference/query.md" + - "reference/reactive.md" + - "reference/screen.md" + - "reference/static.md" + - "reference/timer.md" + - "reference/widget.md" + + +markdown_extensions: + - attr_list + - pymdownx.emoji: + emoji_index: !!python/name:materialx.emoji.twemoji + emoji_generator: !!python/name:materialx.emoji.to_svg + - md_in_html + - admonition + - def_list + - meta + + - toc: + permalink: true + baselevel: 1 + - pymdownx.keys + - pymdownx.tasklist: + custom_checkbox: true + - pymdownx.highlight: + anchor_linenums: true + - pymdownx.inlinehilite + - pymdownx.superfences: + custom_fences: + - name: textual + class: textual + format: !!python/name:textual._doc.format_svg + - name: rich + class: rich + format: !!python/name:textual._doc.rich + - pymdownx.inlinehilite + - pymdownx.superfences + - pymdownx.snippets + - pymdownx.tabbed: + alternate_style: true + - pymdownx.snippets + - markdown.extensions.attr_list + +theme: + name: material + custom_dir: custom_theme + features: + - navigation.tabs + - navigation.indexes + - navigation.tabs.sticky + - content.code.annotate + palette: + - media: "(prefers-color-scheme: light)" + scheme: default + accent: purple + toggle: + icon: material/weather-sunny + name: Switch to dark modeTask was destroyed but it is pending! + - media: "(prefers-color-scheme: dark)" + scheme: slate + primary: black + toggle: + icon: material/weather-night + name: Switch to light mode + +plugins: + +- search: +- autorefs: +- mkdocstrings: + default_handler: python + handlers: + python: + options: + show_source: false + filters: + - "!^_" + - "^__init__$" + - "!^can_replace$" + + watch: + - src/textual + + +extra_css: + - stylesheets/custom.css diff --git a/testbed/Textualize__textual/mypy.ini b/testbed/Textualize__textual/mypy.ini new file mode 100644 index 0000000000000000000000000000000000000000..c61bcf0ace324bb1f51a68cec8b23b931edd72ea --- /dev/null +++ b/testbed/Textualize__textual/mypy.ini @@ -0,0 +1,16 @@ +[mypy] + +[mypy-pygments.*] +ignore_missing_imports = True + +[mypy-IPython.*] +ignore_missing_imports = True + +[mypy-commonmark.*] +ignore_missing_imports = True + +[mypy-colorama.*] +ignore_missing_imports = True + +[mypy-ipywidgets.*] +ignore_missing_imports = True diff --git a/testbed/Textualize__textual/notes/README.md b/testbed/Textualize__textual/notes/README.md new file mode 100644 index 0000000000000000000000000000000000000000..4577ddf9bbd62d18fa6d3c51e38158c69a47be50 --- /dev/null +++ b/testbed/Textualize__textual/notes/README.md @@ -0,0 +1,3 @@ +# Developer notes + +These are notes made by the developer, and _not_ to be considered documentation. diff --git a/testbed/Textualize__textual/notes/snapshot_testing.md b/testbed/Textualize__textual/notes/snapshot_testing.md new file mode 100644 index 0000000000000000000000000000000000000000..651adfb10f30407fb238f8af26d40b67b8bd943d --- /dev/null +++ b/testbed/Textualize__textual/notes/snapshot_testing.md @@ -0,0 +1,43 @@ +# Snapshot Testing + + +## What is snapshot testing? + +Some tests that run for Textual are snapshot tests. +When you first run a snapshot test, a screenshot of an app is taken and saved to disk. +Next time you run it, another screenshot is taken and compared with the original one. + +If the screenshots don't match, it means something has changed. +It's up to you to tell the test system whether that change is expected or not. + +This allows us to easily catch regressions in how Textual outputs to the terminal. + +Snapshot tests run alongside normal unit tests. + +## How do I write a snapshot test? + +1. Inject the `snap_compare` fixture into your test. +2. Pass in the path to the file which contains the Textual app. + +```python +def test_grid_layout_basic_overflow(snap_compare): + assert snap_compare("docs/examples/guide/layout/grid_layout2.py") +``` + +`snap_compare` can take additional arguments such as `press`, which allows +you to simulate key presses etc. +See the signature of `snap_compare` for more info. + +## A snapshot test failed, what do I do? + +When a snapshot test fails, a report will be created on your machine, and you +can use this report to visually compare the output from your test with the historical output for that test. + +This report will be visible at the bottom of the terminal after the `pytest` session completes, +or, if running in CI, it will be available as an artifact attached to the GitHub Actions summary. + +If you're happy that the new output of the app is correct, you can run `pytest` with the +`--snapshot-update` flag. This flag will update the snapshots for any test that is executed in the run, +so to update a snapshot for a single test, run only that test. + +With your snapshot on disk updated to match the new output, running the test again should result in a pass. diff --git a/testbed/Textualize__textual/poetry.lock b/testbed/Textualize__textual/poetry.lock new file mode 100644 index 0000000000000000000000000000000000000000..e420e1682e8f5cdee67670cb8714c1a452720b71 --- /dev/null +++ b/testbed/Textualize__textual/poetry.lock @@ -0,0 +1,1249 @@ +[[package]] +name = "aiohttp" +version = "3.8.3" +description = "Async http client/server framework (asyncio)" +category = "main" +optional = false +python-versions = ">=3.6" + +[package.dependencies] +aiosignal = ">=1.1.2" +async-timeout = ">=4.0.0a3,<5.0" +asynctest = {version = "0.13.0", markers = "python_version < \"3.8\""} +attrs = ">=17.3.0" +charset-normalizer = ">=2.0,<3.0" +frozenlist = ">=1.1.1" +multidict = ">=4.5,<7.0" +typing-extensions = {version = ">=3.7.4", markers = "python_version < \"3.8\""} +yarl = ">=1.0,<2.0" + +[package.extras] +speedups = ["aiodns", "brotli", "cchardet"] + +[[package]] +name = "aiosignal" +version = "1.2.0" +description = "aiosignal: a list of registered asynchronous callbacks" +category = "main" +optional = false +python-versions = ">=3.6" + +[package.dependencies] +frozenlist = ">=1.1.0" + +[[package]] +name = "async-timeout" +version = "4.0.2" +description = "Timeout context manager for asyncio programs" +category = "main" +optional = false +python-versions = ">=3.6" + +[package.dependencies] +typing-extensions = {version = ">=3.6.5", markers = "python_version < \"3.8\""} + +[[package]] +name = "asynctest" +version = "0.13.0" +description = "Enhance the standard unittest package with features for testing asyncio libraries" +category = "main" +optional = false +python-versions = ">=3.5" + +[[package]] +name = "attrs" +version = "22.1.0" +description = "Classes Without Boilerplate" +category = "main" +optional = false +python-versions = ">=3.5" + +[package.extras] +dev = ["coverage[toml] (>=5.0.2)", "hypothesis", "pympler", "pytest (>=4.3.0)", "mypy (>=0.900,!=0.940)", "pytest-mypy-plugins", "zope.interface", "furo", "sphinx", "sphinx-notfound-page", "pre-commit", "cloudpickle"] +docs = ["furo", "sphinx", "zope.interface", "sphinx-notfound-page"] +tests = ["coverage[toml] (>=5.0.2)", "hypothesis", "pympler", "pytest (>=4.3.0)", "mypy (>=0.900,!=0.940)", "pytest-mypy-plugins", "zope.interface", "cloudpickle"] +tests_no_zope = ["coverage[toml] (>=5.0.2)", "hypothesis", "pympler", "pytest (>=4.3.0)", "mypy (>=0.900,!=0.940)", "pytest-mypy-plugins", "cloudpickle"] + +[[package]] +name = "black" +version = "22.8.0" +description = "The uncompromising code formatter." +category = "dev" +optional = false +python-versions = ">=3.6.2" + +[package.dependencies] +click = ">=8.0.0" +mypy-extensions = ">=0.4.3" +pathspec = ">=0.9.0" +platformdirs = ">=2" +tomli = {version = ">=1.1.0", markers = "python_full_version < \"3.11.0a7\""} +typed-ast = {version = ">=1.4.2", markers = "python_version < \"3.8\" and implementation_name == \"cpython\""} +typing-extensions = {version = ">=3.10.0.0", markers = "python_version < \"3.10\""} + +[package.extras] +colorama = ["colorama (>=0.4.3)"] +d = ["aiohttp (>=3.7.4)"] +jupyter = ["ipython (>=7.8.0)", "tokenize-rt (>=3.2.0)"] +uvloop = ["uvloop (>=0.15.2)"] + +[[package]] +name = "cached-property" +version = "1.5.2" +description = "A decorator for caching properties in classes." +category = "dev" +optional = false +python-versions = "*" + +[[package]] +name = "certifi" +version = "2022.9.24" +description = "Python package for providing Mozilla's CA Bundle." +category = "dev" +optional = false +python-versions = ">=3.6" + +[[package]] +name = "cfgv" +version = "3.3.1" +description = "Validate configuration and produce human readable error messages." +category = "dev" +optional = false +python-versions = ">=3.6.1" + +[[package]] +name = "charset-normalizer" +version = "2.1.1" +description = "The Real First Universal Charset Detector. Open, modern and actively maintained alternative to Chardet." +category = "main" +optional = false +python-versions = ">=3.6.0" + +[package.extras] +unicode_backport = ["unicodedata2"] + +[[package]] +name = "click" +version = "8.1.2" +description = "Composable command line interface toolkit" +category = "main" +optional = false +python-versions = ">=3.7" + +[package.dependencies] +colorama = {version = "*", markers = "platform_system == \"Windows\""} +importlib-metadata = {version = "*", markers = "python_version < \"3.8\""} + +[[package]] +name = "colorama" +version = "0.4.5" +description = "Cross-platform colored terminal text." +category = "main" +optional = false +python-versions = ">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*, !=3.4.*" + +[[package]] +name = "colored" +version = "1.4.3" +description = "Simple library for color and formatting to terminal" +category = "dev" +optional = false +python-versions = "*" + +[[package]] +name = "commonmark" +version = "0.9.1" +description = "Python parser for the CommonMark Markdown spec" +category = "main" +optional = false +python-versions = "*" + +[package.extras] +test = ["flake8 (==3.7.8)", "hypothesis (==3.55.3)"] + +[[package]] +name = "coverage" +version = "6.5.0" +description = "Code coverage measurement for Python" +category = "dev" +optional = false +python-versions = ">=3.7" + +[package.extras] +toml = ["tomli"] + +[[package]] +name = "distlib" +version = "0.3.6" +description = "Distribution utilities" +category = "dev" +optional = false +python-versions = "*" + +[[package]] +name = "filelock" +version = "3.8.0" +description = "A platform independent file lock." +category = "dev" +optional = false +python-versions = ">=3.7" + +[package.extras] +docs = ["furo (>=2022.6.21)", "sphinx (>=5.1.1)", "sphinx-autodoc-typehints (>=1.19.1)"] +testing = ["covdefaults (>=2.2)", "coverage (>=6.4.2)", "pytest (>=7.1.2)", "pytest-cov (>=3)", "pytest-timeout (>=2.1)"] + +[[package]] +name = "frozenlist" +version = "1.3.1" +description = "A list-like structure which implements collections.abc.MutableSequence" +category = "main" +optional = false +python-versions = ">=3.7" + +[[package]] +name = "ghp-import" +version = "2.1.0" +description = "Copy your docs directly to the gh-pages branch." +category = "dev" +optional = false +python-versions = "*" + +[package.dependencies] +python-dateutil = ">=2.8.1" + +[package.extras] +dev = ["twine", "markdown", "flake8", "wheel"] + +[[package]] +name = "griffe" +version = "0.22.2" +description = "Signatures for entire Python programs. Extract the structure, the frame, the skeleton of your project, to generate API documentation or find breaking changes in your API." +category = "dev" +optional = false +python-versions = ">=3.7" + +[package.dependencies] +cached-property = {version = "*", markers = "python_version < \"3.8\""} + +[package.extras] +async = ["aiofiles (>=0.7,<1.0)"] + +[[package]] +name = "identify" +version = "2.5.6" +description = "File identification library for Python" +category = "dev" +optional = false +python-versions = ">=3.7" + +[package.extras] +license = ["ukkonen"] + +[[package]] +name = "idna" +version = "3.4" +description = "Internationalized Domain Names in Applications (IDNA)" +category = "main" +optional = false +python-versions = ">=3.5" + +[[package]] +name = "importlib-metadata" +version = "4.13.0" +description = "Read metadata from Python packages" +category = "main" +optional = false +python-versions = ">=3.7" + +[package.dependencies] +typing-extensions = {version = ">=3.6.4", markers = "python_version < \"3.8\""} +zipp = ">=0.5" + +[package.extras] +docs = ["sphinx (>=3.5)", "jaraco.packaging (>=9)", "rst.linker (>=1.9)", "furo", "jaraco.tidelift (>=1.4)"] +perf = ["ipython"] +testing = ["pytest (>=6)", "pytest-checkdocs (>=2.4)", "pytest-flake8", "flake8 (<5)", "pytest-cov", "pytest-enabler (>=1.3)", "packaging", "pyfakefs", "flufl.flake8", "pytest-perf (>=0.9.2)", "pytest-black (>=0.3.7)", "pytest-mypy (>=0.9.1)", "importlib-resources (>=1.3)"] + +[[package]] +name = "iniconfig" +version = "1.1.1" +description = "iniconfig: brain-dead simple config-ini parsing" +category = "dev" +optional = false +python-versions = "*" + +[[package]] +name = "jinja2" +version = "3.0.3" +description = "A very fast and expressive template engine." +category = "dev" +optional = false +python-versions = ">=3.6" + +[package.dependencies] +MarkupSafe = ">=2.0" + +[package.extras] +i18n = ["Babel (>=2.7)"] + +[[package]] +name = "markdown" +version = "3.3.7" +description = "Python implementation of Markdown." +category = "dev" +optional = false +python-versions = ">=3.6" + +[package.dependencies] +importlib-metadata = {version = ">=4.4", markers = "python_version < \"3.10\""} + +[package.extras] +testing = ["coverage", "pyyaml"] + +[[package]] +name = "markupsafe" +version = "2.1.1" +description = "Safely add untrusted strings to HTML/XML markup." +category = "dev" +optional = false +python-versions = ">=3.7" + +[[package]] +name = "mergedeep" +version = "1.3.4" +description = "A deep merge function for ๐Ÿ." +category = "dev" +optional = false +python-versions = ">=3.6" + +[[package]] +name = "mkdocs" +version = "1.4.0" +description = "Project documentation with Markdown." +category = "dev" +optional = false +python-versions = ">=3.7" + +[package.dependencies] +click = ">=7.0" +ghp-import = ">=1.0" +importlib-metadata = {version = ">=4.3", markers = "python_version < \"3.10\""} +Jinja2 = ">=2.11.1" +Markdown = ">=3.2.1,<3.4" +mergedeep = ">=1.3.4" +packaging = ">=20.5" +PyYAML = ">=5.1" +pyyaml-env-tag = ">=0.1" +typing-extensions = {version = ">=3.10", markers = "python_version < \"3.8\""} +watchdog = ">=2.0" + +[package.extras] +i18n = ["babel (>=2.9.0)"] + +[[package]] +name = "mkdocs-autorefs" +version = "0.4.1" +description = "Automatically link across pages in MkDocs." +category = "dev" +optional = false +python-versions = ">=3.7" + +[package.dependencies] +Markdown = ">=3.3" +mkdocs = ">=1.1" + +[[package]] +name = "mkdocs-material" +version = "8.5.6" +description = "Documentation that simply works" +category = "dev" +optional = false +python-versions = ">=3.7" + +[package.dependencies] +jinja2 = ">=3.0.2" +markdown = ">=3.2" +mkdocs = ">=1.4.0" +mkdocs-material-extensions = ">=1.0.3" +pygments = ">=2.12" +pymdown-extensions = ">=9.4" +requests = ">=2.26" + +[[package]] +name = "mkdocs-material-extensions" +version = "1.0.3" +description = "Extension pack for Python Markdown." +category = "dev" +optional = false +python-versions = ">=3.6" + +[[package]] +name = "mkdocstrings" +version = "0.19.0" +description = "Automatic documentation from sources, for MkDocs." +category = "dev" +optional = false +python-versions = ">=3.7" + +[package.dependencies] +Jinja2 = ">=2.11.1" +Markdown = ">=3.3" +MarkupSafe = ">=1.1" +mkdocs = ">=1.2" +mkdocs-autorefs = ">=0.3.1" +mkdocstrings-python = {version = ">=0.5.2", optional = true, markers = "extra == \"python\""} +pymdown-extensions = ">=6.3" + +[package.extras] +crystal = ["mkdocstrings-crystal (>=0.3.4)"] +python = ["mkdocstrings-python (>=0.5.2)"] +python-legacy = ["mkdocstrings-python-legacy (>=0.2.1)"] + +[[package]] +name = "mkdocstrings-python" +version = "0.7.1" +description = "A Python handler for mkdocstrings." +category = "dev" +optional = false +python-versions = ">=3.7" + +[package.dependencies] +griffe = ">=0.11.1" +mkdocstrings = ">=0.19" + +[[package]] +name = "msgpack" +version = "1.0.4" +description = "MessagePack serializer" +category = "main" +optional = true +python-versions = "*" + +[[package]] +name = "multidict" +version = "6.0.2" +description = "multidict implementation" +category = "main" +optional = false +python-versions = ">=3.7" + +[[package]] +name = "mypy" +version = "0.982" +description = "Optional static typing for Python" +category = "dev" +optional = false +python-versions = ">=3.7" + +[package.dependencies] +mypy-extensions = ">=0.4.3" +tomli = {version = ">=1.1.0", markers = "python_version < \"3.11\""} +typed-ast = {version = ">=1.4.0,<2", markers = "python_version < \"3.8\""} +typing-extensions = ">=3.10" + +[package.extras] +dmypy = ["psutil (>=4.0)"] +python2 = ["typed-ast (>=1.4.0,<2)"] +reports = ["lxml"] + +[[package]] +name = "mypy-extensions" +version = "0.4.3" +description = "Experimental type system extensions for programs checked with the mypy typechecker." +category = "dev" +optional = false +python-versions = "*" + +[[package]] +name = "nanoid" +version = "2.0.0" +description = "A tiny, secure, URL-friendly, unique string ID generator for Python" +category = "main" +optional = false +python-versions = "*" + +[[package]] +name = "nodeenv" +version = "1.7.0" +description = "Node.js virtual environment builder" +category = "dev" +optional = false +python-versions = ">=2.7,!=3.0.*,!=3.1.*,!=3.2.*,!=3.3.*,!=3.4.*,!=3.5.*,!=3.6.*" + +[[package]] +name = "packaging" +version = "21.3" +description = "Core utilities for Python packages" +category = "dev" +optional = false +python-versions = ">=3.6" + +[package.dependencies] +pyparsing = ">=2.0.2,<3.0.5 || >3.0.5" + +[[package]] +name = "pathspec" +version = "0.10.1" +description = "Utility library for gitignore style pattern matching of file paths." +category = "dev" +optional = false +python-versions = ">=3.7" + +[[package]] +name = "platformdirs" +version = "2.5.2" +description = "A small Python module for determining appropriate platform-specific dirs, e.g. a \"user data dir\"." +category = "dev" +optional = false +python-versions = ">=3.7" + +[package.extras] +docs = ["furo (>=2021.7.5b38)", "proselint (>=0.10.2)", "sphinx-autodoc-typehints (>=1.12)", "sphinx (>=4)"] +test = ["appdirs (==1.4.4)", "pytest-cov (>=2.7)", "pytest-mock (>=3.6)", "pytest (>=6)"] + +[[package]] +name = "pluggy" +version = "1.0.0" +description = "plugin and hook calling mechanisms for python" +category = "dev" +optional = false +python-versions = ">=3.6" + +[package.dependencies] +importlib-metadata = {version = ">=0.12", markers = "python_version < \"3.8\""} + +[package.extras] +dev = ["pre-commit", "tox"] +testing = ["pytest", "pytest-benchmark"] + +[[package]] +name = "pre-commit" +version = "2.20.0" +description = "A framework for managing and maintaining multi-language pre-commit hooks." +category = "dev" +optional = false +python-versions = ">=3.7" + +[package.dependencies] +cfgv = ">=2.0.0" +identify = ">=1.0.0" +importlib-metadata = {version = "*", markers = "python_version < \"3.8\""} +nodeenv = ">=0.11.1" +pyyaml = ">=5.1" +toml = "*" +virtualenv = ">=20.0.8" + +[[package]] +name = "py" +version = "1.11.0" +description = "library with cross-python path, ini-parsing, io, code, log facilities" +category = "dev" +optional = false +python-versions = ">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*, !=3.4.*" + +[[package]] +name = "pygments" +version = "2.13.0" +description = "Pygments is a syntax highlighting package written in Python." +category = "main" +optional = false +python-versions = ">=3.6" + +[package.extras] +plugins = ["importlib-metadata"] + +[[package]] +name = "pymdown-extensions" +version = "9.6" +description = "Extension pack for Python Markdown." +category = "dev" +optional = false +python-versions = ">=3.7" + +[package.dependencies] +markdown = ">=3.2" + +[[package]] +name = "pyparsing" +version = "3.0.9" +description = "pyparsing module - Classes and methods to define and execute parsing grammars" +category = "dev" +optional = false +python-versions = ">=3.6.8" + +[package.extras] +diagrams = ["railroad-diagrams", "jinja2"] + +[[package]] +name = "pytest" +version = "7.1.3" +description = "pytest: simple powerful testing with Python" +category = "dev" +optional = false +python-versions = ">=3.7" + +[package.dependencies] +attrs = ">=19.2.0" +colorama = {version = "*", markers = "sys_platform == \"win32\""} +importlib-metadata = {version = ">=0.12", markers = "python_version < \"3.8\""} +iniconfig = "*" +packaging = "*" +pluggy = ">=0.12,<2.0" +py = ">=1.8.2" +tomli = ">=1.0.0" + +[package.extras] +testing = ["argcomplete", "hypothesis (>=3.56)", "mock", "nose", "pygments (>=2.7.2)", "requests", "xmlschema"] + +[[package]] +name = "pytest-aiohttp" +version = "1.0.4" +description = "Pytest plugin for aiohttp support" +category = "dev" +optional = false +python-versions = ">=3.7" + +[package.dependencies] +aiohttp = ">=3.8.1" +pytest = ">=6.1.0" +pytest-asyncio = ">=0.17.2" + +[package.extras] +testing = ["coverage (==6.2)", "mypy (==0.931)"] + +[[package]] +name = "pytest-asyncio" +version = "0.19.0" +description = "Pytest support for asyncio" +category = "dev" +optional = false +python-versions = ">=3.7" + +[package.dependencies] +pytest = ">=6.1.0" +typing-extensions = {version = ">=3.7.2", markers = "python_version < \"3.8\""} + +[package.extras] +testing = ["coverage (>=6.2)", "hypothesis (>=5.7.1)", "flaky (>=3.5.0)", "mypy (>=0.931)", "pytest-trio (>=0.7.0)"] + +[[package]] +name = "pytest-cov" +version = "2.12.1" +description = "Pytest plugin for measuring coverage." +category = "dev" +optional = false +python-versions = ">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*, !=3.4.*" + +[package.dependencies] +coverage = ">=5.2.1" +pytest = ">=4.6" +toml = "*" + +[package.extras] +testing = ["fields", "hunter", "process-tests", "six", "pytest-xdist", "virtualenv"] + +[[package]] +name = "python-dateutil" +version = "2.8.2" +description = "Extensions to the standard Python datetime module" +category = "dev" +optional = false +python-versions = "!=3.0.*,!=3.1.*,!=3.2.*,>=2.7" + +[package.dependencies] +six = ">=1.5" + +[[package]] +name = "pyyaml" +version = "6.0" +description = "YAML parser and emitter for Python" +category = "dev" +optional = false +python-versions = ">=3.6" + +[[package]] +name = "pyyaml-env-tag" +version = "0.1" +description = "A custom YAML tag for referencing environment variables in YAML files. " +category = "dev" +optional = false +python-versions = ">=3.6" + +[package.dependencies] +pyyaml = "*" + +[[package]] +name = "requests" +version = "2.28.1" +description = "Python HTTP for Humans." +category = "dev" +optional = false +python-versions = ">=3.7, <4" + +[package.dependencies] +certifi = ">=2017.4.17" +charset-normalizer = ">=2,<3" +idna = ">=2.5,<4" +urllib3 = ">=1.21.1,<1.27" + +[package.extras] +socks = ["PySocks (>=1.5.6,!=1.5.7)"] +use_chardet_on_py3 = ["chardet (>=3.0.2,<6)"] + +[[package]] +name = "rich" +version = "12.6.0" +description = "Render rich text, tables, progress bars, syntax highlighting, markdown and more to the terminal" +category = "main" +optional = false +python-versions = ">=3.6.3,<4.0.0" + +[package.dependencies] +commonmark = ">=0.9.0,<0.10.0" +pygments = ">=2.6.0,<3.0.0" +typing-extensions = {version = ">=4.0.0,<5.0", markers = "python_version < \"3.9\""} + +[package.extras] +jupyter = ["ipywidgets (>=7.5.1,<8.0.0)"] + +[[package]] +name = "six" +version = "1.16.0" +description = "Python 2 and 3 compatibility utilities" +category = "dev" +optional = false +python-versions = ">=2.7, !=3.0.*, !=3.1.*, !=3.2.*" + +[[package]] +name = "syrupy" +version = "3.0.2" +description = "Pytest Snapshot Test Utility" +category = "dev" +optional = false +python-versions = ">=3.7,<4" + +[package.dependencies] +colored = ">=1.3.92,<2.0.0" +pytest = ">=5.1.0,<8.0.0" + +[[package]] +name = "time-machine" +version = "2.8.2" +description = "Travel through time in your tests." +category = "dev" +optional = false +python-versions = ">=3.7" + +[package.dependencies] +python-dateutil = "*" + +[[package]] +name = "toml" +version = "0.10.2" +description = "Python Library for Tom's Obvious, Minimal Language" +category = "dev" +optional = false +python-versions = ">=2.6, !=3.0.*, !=3.1.*, !=3.2.*" + +[[package]] +name = "tomli" +version = "2.0.1" +description = "A lil' TOML parser" +category = "dev" +optional = false +python-versions = ">=3.7" + +[[package]] +name = "typed-ast" +version = "1.5.4" +description = "a fork of Python 2 and 3 ast modules with type comment support" +category = "dev" +optional = false +python-versions = ">=3.6" + +[[package]] +name = "typing-extensions" +version = "4.3.0" +description = "Backported and Experimental Type Hints for Python 3.7+" +category = "main" +optional = false +python-versions = ">=3.7" + +[[package]] +name = "urllib3" +version = "1.26.12" +description = "HTTP library with thread-safe connection pooling, file post, and more." +category = "dev" +optional = false +python-versions = ">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*, !=3.4.*, !=3.5.*, <4" + +[package.extras] +brotli = ["brotlicffi (>=0.8.0)", "brotli (>=1.0.9)", "brotlipy (>=0.6.0)"] +secure = ["pyOpenSSL (>=0.14)", "cryptography (>=1.3.4)", "idna (>=2.0.0)", "certifi", "urllib3-secure-extra", "ipaddress"] +socks = ["PySocks (>=1.5.6,!=1.5.7,<2.0)"] + +[[package]] +name = "virtualenv" +version = "20.16.5" +description = "Virtual Python Environment builder" +category = "dev" +optional = false +python-versions = ">=3.6" + +[package.dependencies] +distlib = ">=0.3.5,<1" +filelock = ">=3.4.1,<4" +importlib-metadata = {version = ">=4.8.3", markers = "python_version < \"3.8\""} +platformdirs = ">=2.4,<3" + +[package.extras] +docs = ["proselint (>=0.13)", "sphinx (>=5.1.1)", "sphinx-argparse (>=0.3.1)", "sphinx-rtd-theme (>=1)", "towncrier (>=21.9)"] +testing = ["coverage (>=6.2)", "coverage-enable-subprocess (>=1)", "flaky (>=3.7)", "packaging (>=21.3)", "pytest (>=7.0.1)", "pytest-env (>=0.6.2)", "pytest-freezegun (>=0.4.2)", "pytest-mock (>=3.6.1)", "pytest-randomly (>=3.10.3)", "pytest-timeout (>=2.1)"] + +[[package]] +name = "watchdog" +version = "2.1.9" +description = "Filesystem events monitoring" +category = "dev" +optional = false +python-versions = ">=3.6" + +[package.extras] +watchmedo = ["PyYAML (>=3.10)"] + +[[package]] +name = "yarl" +version = "1.8.1" +description = "Yet another URL library" +category = "main" +optional = false +python-versions = ">=3.7" + +[package.dependencies] +idna = ">=2.0" +multidict = ">=4.0" +typing-extensions = {version = ">=3.7.4", markers = "python_version < \"3.8\""} + +[[package]] +name = "zipp" +version = "3.8.1" +description = "Backport of pathlib-compatible object wrapper for zip files" +category = "main" +optional = false +python-versions = ">=3.7" + +[package.extras] +docs = ["sphinx", "jaraco.packaging (>=9)", "rst.linker (>=1.9)", "jaraco.tidelift (>=1.4)"] +testing = ["pytest (>=6)", "pytest-checkdocs (>=2.4)", "pytest-flake8", "pytest-cov", "pytest-enabler (>=1.3)", "jaraco.itertools", "func-timeout", "pytest-black (>=0.3.7)", "pytest-mypy (>=0.9.1)"] + +[extras] +dev = ["aiohttp", "click", "msgpack"] + +[metadata] +lock-version = "1.1" +python-versions = "^3.7" +content-hash = "84203bb5193474eb9204f4f808739cb25e61f02a38d0062ea2ea71d3703573c1" + +[metadata.files] +aiohttp = [] +aiosignal = [ + {file = "aiosignal-1.2.0-py3-none-any.whl", hash = "sha256:26e62109036cd181df6e6ad646f91f0dcfd05fe16d0cb924138ff2ab75d64e3a"}, + {file = "aiosignal-1.2.0.tar.gz", hash = "sha256:78ed67db6c7b7ced4f98e495e572106d5c432a93e1ddd1bf475e1dc05f5b7df2"}, +] +async-timeout = [ + {file = "async-timeout-4.0.2.tar.gz", hash = "sha256:2163e1640ddb52b7a8c80d0a67a08587e5d245cc9c553a74a847056bc2976b15"}, + {file = "async_timeout-4.0.2-py3-none-any.whl", hash = "sha256:8ca1e4fcf50d07413d66d1a5e416e42cfdf5851c981d679a09851a6853383b3c"}, +] +asynctest = [ + {file = "asynctest-0.13.0-py3-none-any.whl", hash = "sha256:5da6118a7e6d6b54d83a8f7197769d046922a44d2a99c21382f0a6e4fadae676"}, + {file = "asynctest-0.13.0.tar.gz", hash = "sha256:c27862842d15d83e6a34eb0b2866c323880eb3a75e4485b079ea11748fd77fac"}, +] +attrs = [] +black = [] +cached-property = [ + {file = "cached-property-1.5.2.tar.gz", hash = "sha256:9fa5755838eecbb2d234c3aa390bd80fbd3ac6b6869109bfc1b499f7bd89a130"}, + {file = "cached_property-1.5.2-py2.py3-none-any.whl", hash = "sha256:df4f613cf7ad9a588cc381aaf4a512d26265ecebd5eb9e1ba12f1319eb85a6a0"}, +] +certifi = [] +cfgv = [ + {file = "cfgv-3.3.1-py2.py3-none-any.whl", hash = "sha256:c6a0883f3917a037485059700b9e75da2464e6c27051014ad85ba6aaa5884426"}, + {file = "cfgv-3.3.1.tar.gz", hash = "sha256:f5a830efb9ce7a445376bb66ec94c638a9787422f96264c98edc6bdeed8ab736"}, +] +charset-normalizer = [] +click = [ + {file = "click-8.1.2-py3-none-any.whl", hash = "sha256:24e1a4a9ec5bf6299411369b208c1df2188d9eb8d916302fe6bf03faed227f1e"}, + {file = "click-8.1.2.tar.gz", hash = "sha256:479707fe14d9ec9a0757618b7a100a0ae4c4e236fac5b7f80ca68028141a1a72"}, +] +colorama = [ + {file = "colorama-0.4.5-py2.py3-none-any.whl", hash = "sha256:854bf444933e37f5824ae7bfc1e98d5bce2ebe4160d46b5edf346a89358e99da"}, + {file = "colorama-0.4.5.tar.gz", hash = "sha256:e6c6b4334fc50988a639d9b98aa429a0b57da6e17b9a44f0451f930b6967b7a4"}, +] +colored = [] +commonmark = [ + {file = "commonmark-0.9.1-py2.py3-none-any.whl", hash = "sha256:da2f38c92590f83de410ba1a3cbceafbc74fee9def35f9251ba9a971d6d66fd9"}, + {file = "commonmark-0.9.1.tar.gz", hash = "sha256:452f9dc859be7f06631ddcb328b6919c67984aca654e5fefb3914d54691aed60"}, +] +coverage = [] +distlib = [] +filelock = [] +frozenlist = [] +ghp-import = [ + {file = "ghp-import-2.1.0.tar.gz", hash = "sha256:9c535c4c61193c2df8871222567d7fd7e5014d835f97dc7b7439069e2413d343"}, + {file = "ghp_import-2.1.0-py3-none-any.whl", hash = "sha256:8337dd7b50877f163d4c0289bc1f1c7f127550241988d568c1db512c4324a619"}, +] +griffe = [] +identify = [] +idna = [] +importlib-metadata = [] +iniconfig = [ + {file = "iniconfig-1.1.1-py2.py3-none-any.whl", hash = "sha256:011e24c64b7f47f6ebd835bb12a743f2fbe9a26d4cecaa7f53bc4f35ee9da8b3"}, + {file = "iniconfig-1.1.1.tar.gz", hash = "sha256:bc3af051d7d14b2ee5ef9969666def0cd1a000e121eaea580d4a313df4b37f32"}, +] +jinja2 = [ + {file = "Jinja2-3.0.3-py3-none-any.whl", hash = "sha256:077ce6014f7b40d03b47d1f1ca4b0fc8328a692bd284016f806ed0eaca390ad8"}, + {file = "Jinja2-3.0.3.tar.gz", hash = "sha256:611bb273cd68f3b993fabdc4064fc858c5b47a973cb5aa7999ec1ba405c87cd7"}, +] +markdown = [ + {file = "Markdown-3.3.7-py3-none-any.whl", hash = "sha256:f5da449a6e1c989a4cea2631aa8ee67caa5a2ef855d551c88f9e309f4634c621"}, + {file = "Markdown-3.3.7.tar.gz", hash = "sha256:cbb516f16218e643d8e0a95b309f77eb118cb138d39a4f27851e6a63581db874"}, +] +markupsafe = [ + {file = "MarkupSafe-2.1.1-cp310-cp310-macosx_10_9_universal2.whl", hash = "sha256:86b1f75c4e7c2ac2ccdaec2b9022845dbb81880ca318bb7a0a01fbf7813e3812"}, + {file = "MarkupSafe-2.1.1-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:f121a1420d4e173a5d96e47e9a0c0dcff965afdf1626d28de1460815f7c4ee7a"}, + {file = "MarkupSafe-2.1.1-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:a49907dd8420c5685cfa064a1335b6754b74541bbb3706c259c02ed65b644b3e"}, + {file = "MarkupSafe-2.1.1-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:10c1bfff05d95783da83491be968e8fe789263689c02724e0c691933c52994f5"}, + {file = "MarkupSafe-2.1.1-cp310-cp310-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:b7bd98b796e2b6553da7225aeb61f447f80a1ca64f41d83612e6139ca5213aa4"}, + {file = "MarkupSafe-2.1.1-cp310-cp310-musllinux_1_1_aarch64.whl", hash = "sha256:b09bf97215625a311f669476f44b8b318b075847b49316d3e28c08e41a7a573f"}, + {file = "MarkupSafe-2.1.1-cp310-cp310-musllinux_1_1_i686.whl", hash = "sha256:694deca8d702d5db21ec83983ce0bb4b26a578e71fbdbd4fdcd387daa90e4d5e"}, + {file = "MarkupSafe-2.1.1-cp310-cp310-musllinux_1_1_x86_64.whl", hash = "sha256:efc1913fd2ca4f334418481c7e595c00aad186563bbc1ec76067848c7ca0a933"}, + {file = "MarkupSafe-2.1.1-cp310-cp310-win32.whl", hash = "sha256:4a33dea2b688b3190ee12bd7cfa29d39c9ed176bda40bfa11099a3ce5d3a7ac6"}, + {file = "MarkupSafe-2.1.1-cp310-cp310-win_amd64.whl", hash = "sha256:dda30ba7e87fbbb7eab1ec9f58678558fd9a6b8b853530e176eabd064da81417"}, + {file = "MarkupSafe-2.1.1-cp37-cp37m-macosx_10_9_x86_64.whl", hash = "sha256:671cd1187ed5e62818414afe79ed29da836dde67166a9fac6d435873c44fdd02"}, + {file = "MarkupSafe-2.1.1-cp37-cp37m-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:3799351e2336dc91ea70b034983ee71cf2f9533cdff7c14c90ea126bfd95d65a"}, + {file = "MarkupSafe-2.1.1-cp37-cp37m-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:e72591e9ecd94d7feb70c1cbd7be7b3ebea3f548870aa91e2732960fa4d57a37"}, + {file = "MarkupSafe-2.1.1-cp37-cp37m-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:6fbf47b5d3728c6aea2abb0589b5d30459e369baa772e0f37a0320185e87c980"}, + {file = "MarkupSafe-2.1.1-cp37-cp37m-musllinux_1_1_aarch64.whl", hash = "sha256:d5ee4f386140395a2c818d149221149c54849dfcfcb9f1debfe07a8b8bd63f9a"}, + {file = "MarkupSafe-2.1.1-cp37-cp37m-musllinux_1_1_i686.whl", hash = "sha256:bcb3ed405ed3222f9904899563d6fc492ff75cce56cba05e32eff40e6acbeaa3"}, + {file = "MarkupSafe-2.1.1-cp37-cp37m-musllinux_1_1_x86_64.whl", hash = "sha256:e1c0b87e09fa55a220f058d1d49d3fb8df88fbfab58558f1198e08c1e1de842a"}, + {file = "MarkupSafe-2.1.1-cp37-cp37m-win32.whl", hash = "sha256:8dc1c72a69aa7e082593c4a203dcf94ddb74bb5c8a731e4e1eb68d031e8498ff"}, + {file = "MarkupSafe-2.1.1-cp37-cp37m-win_amd64.whl", hash = "sha256:97a68e6ada378df82bc9f16b800ab77cbf4b2fada0081794318520138c088e4a"}, + {file = "MarkupSafe-2.1.1-cp38-cp38-macosx_10_9_universal2.whl", hash = "sha256:e8c843bbcda3a2f1e3c2ab25913c80a3c5376cd00c6e8c4a86a89a28c8dc5452"}, + {file = "MarkupSafe-2.1.1-cp38-cp38-macosx_10_9_x86_64.whl", hash = "sha256:0212a68688482dc52b2d45013df70d169f542b7394fc744c02a57374a4207003"}, + {file = "MarkupSafe-2.1.1-cp38-cp38-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:8e576a51ad59e4bfaac456023a78f6b5e6e7651dcd383bcc3e18d06f9b55d6d1"}, + {file = "MarkupSafe-2.1.1-cp38-cp38-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:4b9fe39a2ccc108a4accc2676e77da025ce383c108593d65cc909add5c3bd601"}, + {file = "MarkupSafe-2.1.1-cp38-cp38-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:96e37a3dc86e80bf81758c152fe66dbf60ed5eca3d26305edf01892257049925"}, + {file = "MarkupSafe-2.1.1-cp38-cp38-musllinux_1_1_aarch64.whl", hash = "sha256:6d0072fea50feec76a4c418096652f2c3238eaa014b2f94aeb1d56a66b41403f"}, + {file = "MarkupSafe-2.1.1-cp38-cp38-musllinux_1_1_i686.whl", hash = "sha256:089cf3dbf0cd6c100f02945abeb18484bd1ee57a079aefd52cffd17fba910b88"}, + {file = "MarkupSafe-2.1.1-cp38-cp38-musllinux_1_1_x86_64.whl", hash = "sha256:6a074d34ee7a5ce3effbc526b7083ec9731bb3cbf921bbe1d3005d4d2bdb3a63"}, + {file = "MarkupSafe-2.1.1-cp38-cp38-win32.whl", hash = "sha256:421be9fbf0ffe9ffd7a378aafebbf6f4602d564d34be190fc19a193232fd12b1"}, + {file = "MarkupSafe-2.1.1-cp38-cp38-win_amd64.whl", hash = "sha256:fc7b548b17d238737688817ab67deebb30e8073c95749d55538ed473130ec0c7"}, + {file = "MarkupSafe-2.1.1-cp39-cp39-macosx_10_9_universal2.whl", hash = "sha256:e04e26803c9c3851c931eac40c695602c6295b8d432cbe78609649ad9bd2da8a"}, + {file = "MarkupSafe-2.1.1-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:b87db4360013327109564f0e591bd2a3b318547bcef31b468a92ee504d07ae4f"}, + {file = "MarkupSafe-2.1.1-cp39-cp39-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:99a2a507ed3ac881b975a2976d59f38c19386d128e7a9a18b7df6fff1fd4c1d6"}, + {file = "MarkupSafe-2.1.1-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:56442863ed2b06d19c37f94d999035e15ee982988920e12a5b4ba29b62ad1f77"}, + {file = "MarkupSafe-2.1.1-cp39-cp39-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:3ce11ee3f23f79dbd06fb3d63e2f6af7b12db1d46932fe7bd8afa259a5996603"}, + {file = "MarkupSafe-2.1.1-cp39-cp39-musllinux_1_1_aarch64.whl", hash = "sha256:33b74d289bd2f5e527beadcaa3f401e0df0a89927c1559c8566c066fa4248ab7"}, + {file = "MarkupSafe-2.1.1-cp39-cp39-musllinux_1_1_i686.whl", hash = "sha256:43093fb83d8343aac0b1baa75516da6092f58f41200907ef92448ecab8825135"}, + {file = "MarkupSafe-2.1.1-cp39-cp39-musllinux_1_1_x86_64.whl", hash = "sha256:8e3dcf21f367459434c18e71b2a9532d96547aef8a871872a5bd69a715c15f96"}, + {file = "MarkupSafe-2.1.1-cp39-cp39-win32.whl", hash = "sha256:d4306c36ca495956b6d568d276ac11fdd9c30a36f1b6eb928070dc5360b22e1c"}, + {file = "MarkupSafe-2.1.1-cp39-cp39-win_amd64.whl", hash = "sha256:46d00d6cfecdde84d40e572d63735ef81423ad31184100411e6e3388d405e247"}, + {file = "MarkupSafe-2.1.1.tar.gz", hash = "sha256:7f91197cc9e48f989d12e4e6fbc46495c446636dfc81b9ccf50bb0ec74b91d4b"}, +] +mergedeep = [ + {file = "mergedeep-1.3.4-py3-none-any.whl", hash = "sha256:70775750742b25c0d8f36c55aed03d24c3384d17c951b3175d898bd778ef0307"}, + {file = "mergedeep-1.3.4.tar.gz", hash = "sha256:0096d52e9dad9939c3d975a774666af186eda617e6ca84df4c94dec30004f2a8"}, +] +mkdocs = [] +mkdocs-autorefs = [ + {file = "mkdocs-autorefs-0.4.1.tar.gz", hash = "sha256:70748a7bd025f9ecd6d6feeba8ba63f8e891a1af55f48e366d6d6e78493aba84"}, + {file = "mkdocs_autorefs-0.4.1-py3-none-any.whl", hash = "sha256:a2248a9501b29dc0cc8ba4c09f4f47ff121945f6ce33d760f145d6f89d313f5b"}, +] +mkdocs-material = [] +mkdocs-material-extensions = [ + {file = "mkdocs-material-extensions-1.0.3.tar.gz", hash = "sha256:bfd24dfdef7b41c312ede42648f9eb83476ea168ec163b613f9abd12bbfddba2"}, + {file = "mkdocs_material_extensions-1.0.3-py3-none-any.whl", hash = "sha256:a82b70e533ce060b2a5d9eb2bc2e1be201cf61f901f93704b4acf6e3d5983a44"}, +] +mkdocstrings = [ + {file = "mkdocstrings-0.19.0-py3-none-any.whl", hash = "sha256:3217d510d385c961f69385a670b2677e68e07b5fea4a504d86bf54c006c87c7d"}, + {file = "mkdocstrings-0.19.0.tar.gz", hash = "sha256:efa34a67bad11229d532d89f6836a8a215937548623b64f3698a1df62e01cc3e"}, +] +mkdocstrings-python = [ + {file = "mkdocstrings-python-0.7.1.tar.gz", hash = "sha256:c334b382dca202dfa37071c182418a6df5818356a95d54362a2b24822ca3af71"}, + {file = "mkdocstrings_python-0.7.1-py3-none-any.whl", hash = "sha256:a22060bfa374697678e9af4e62b020d990dad2711c98f7a9fac5c0345bef93c7"}, +] +msgpack = [ + {file = "msgpack-1.0.4-cp310-cp310-macosx_10_9_universal2.whl", hash = "sha256:4ab251d229d10498e9a2f3b1e68ef64cb393394ec477e3370c457f9430ce9250"}, + {file = "msgpack-1.0.4-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:112b0f93202d7c0fef0b7810d465fde23c746a2d482e1e2de2aafd2ce1492c88"}, + {file = "msgpack-1.0.4-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:002b5c72b6cd9b4bafd790f364b8480e859b4712e91f43014fe01e4f957b8467"}, + {file = "msgpack-1.0.4-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:35bc0faa494b0f1d851fd29129b2575b2e26d41d177caacd4206d81502d4c6a6"}, + {file = "msgpack-1.0.4-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:4733359808c56d5d7756628736061c432ded018e7a1dff2d35a02439043321aa"}, + {file = "msgpack-1.0.4-cp310-cp310-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:eb514ad14edf07a1dbe63761fd30f89ae79b42625731e1ccf5e1f1092950eaa6"}, + {file = "msgpack-1.0.4-cp310-cp310-musllinux_1_1_aarch64.whl", hash = "sha256:c23080fdeec4716aede32b4e0ef7e213c7b1093eede9ee010949f2a418ced6ba"}, + {file = "msgpack-1.0.4-cp310-cp310-musllinux_1_1_i686.whl", hash = "sha256:49565b0e3d7896d9ea71d9095df15b7f75a035c49be733051c34762ca95bbf7e"}, + {file = "msgpack-1.0.4-cp310-cp310-musllinux_1_1_x86_64.whl", hash = "sha256:aca0f1644d6b5a73eb3e74d4d64d5d8c6c3d577e753a04c9e9c87d07692c58db"}, + {file = "msgpack-1.0.4-cp310-cp310-win32.whl", hash = "sha256:0dfe3947db5fb9ce52aaea6ca28112a170db9eae75adf9339a1aec434dc954ef"}, + {file = "msgpack-1.0.4-cp310-cp310-win_amd64.whl", hash = "sha256:4dea20515f660aa6b7e964433b1808d098dcfcabbebeaaad240d11f909298075"}, + {file = "msgpack-1.0.4-cp36-cp36m-macosx_10_9_x86_64.whl", hash = "sha256:e83f80a7fec1a62cf4e6c9a660e39c7f878f603737a0cdac8c13131d11d97f52"}, + {file = "msgpack-1.0.4-cp36-cp36m-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:3c11a48cf5e59026ad7cb0dc29e29a01b5a66a3e333dc11c04f7e991fc5510a9"}, + {file = "msgpack-1.0.4-cp36-cp36m-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:1276e8f34e139aeff1c77a3cefb295598b504ac5314d32c8c3d54d24fadb94c9"}, + {file = "msgpack-1.0.4-cp36-cp36m-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:6c9566f2c39ccced0a38d37c26cc3570983b97833c365a6044edef3574a00c08"}, + {file = "msgpack-1.0.4-cp36-cp36m-musllinux_1_1_aarch64.whl", hash = "sha256:fcb8a47f43acc113e24e910399376f7277cf8508b27e5b88499f053de6b115a8"}, + {file = "msgpack-1.0.4-cp36-cp36m-musllinux_1_1_i686.whl", hash = "sha256:76ee788122de3a68a02ed6f3a16bbcd97bc7c2e39bd4d94be2f1821e7c4a64e6"}, + {file = "msgpack-1.0.4-cp36-cp36m-musllinux_1_1_x86_64.whl", hash = "sha256:0a68d3ac0104e2d3510de90a1091720157c319ceeb90d74f7b5295a6bee51bae"}, + {file = "msgpack-1.0.4-cp36-cp36m-win32.whl", hash = "sha256:85f279d88d8e833ec015650fd15ae5eddce0791e1e8a59165318f371158efec6"}, + {file = "msgpack-1.0.4-cp36-cp36m-win_amd64.whl", hash = "sha256:c1683841cd4fa45ac427c18854c3ec3cd9b681694caf5bff04edb9387602d661"}, + {file = "msgpack-1.0.4-cp37-cp37m-macosx_10_9_x86_64.whl", hash = "sha256:a75dfb03f8b06f4ab093dafe3ddcc2d633259e6c3f74bb1b01996f5d8aa5868c"}, + {file = "msgpack-1.0.4-cp37-cp37m-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:9667bdfdf523c40d2511f0e98a6c9d3603be6b371ae9a238b7ef2dc4e7a427b0"}, + {file = "msgpack-1.0.4-cp37-cp37m-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:11184bc7e56fd74c00ead4f9cc9a3091d62ecb96e97653add7a879a14b003227"}, + {file = "msgpack-1.0.4-cp37-cp37m-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:ac5bd7901487c4a1dd51a8c58f2632b15d838d07ceedaa5e4c080f7190925bff"}, + {file = "msgpack-1.0.4-cp37-cp37m-musllinux_1_1_aarch64.whl", hash = "sha256:1e91d641d2bfe91ba4c52039adc5bccf27c335356055825c7f88742c8bb900dd"}, + {file = "msgpack-1.0.4-cp37-cp37m-musllinux_1_1_i686.whl", hash = "sha256:2a2df1b55a78eb5f5b7d2a4bb221cd8363913830145fad05374a80bf0877cb1e"}, + {file = "msgpack-1.0.4-cp37-cp37m-musllinux_1_1_x86_64.whl", hash = "sha256:545e3cf0cf74f3e48b470f68ed19551ae6f9722814ea969305794645da091236"}, + {file = "msgpack-1.0.4-cp37-cp37m-win32.whl", hash = "sha256:2cc5ca2712ac0003bcb625c96368fd08a0f86bbc1a5578802512d87bc592fe44"}, + {file = "msgpack-1.0.4-cp37-cp37m-win_amd64.whl", hash = "sha256:eba96145051ccec0ec86611fe9cf693ce55f2a3ce89c06ed307de0e085730ec1"}, + {file = "msgpack-1.0.4-cp38-cp38-macosx_10_9_universal2.whl", hash = "sha256:7760f85956c415578c17edb39eed99f9181a48375b0d4a94076d84148cf67b2d"}, + {file = "msgpack-1.0.4-cp38-cp38-macosx_10_9_x86_64.whl", hash = "sha256:449e57cc1ff18d3b444eb554e44613cffcccb32805d16726a5494038c3b93dab"}, + {file = "msgpack-1.0.4-cp38-cp38-macosx_11_0_arm64.whl", hash = "sha256:d603de2b8d2ea3f3bcb2efe286849aa7a81531abc52d8454da12f46235092bcb"}, + {file = "msgpack-1.0.4-cp38-cp38-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:48f5d88c99f64c456413d74a975bd605a9b0526293218a3b77220a2c15458ba9"}, + {file = "msgpack-1.0.4-cp38-cp38-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:6916c78f33602ecf0509cc40379271ba0f9ab572b066bd4bdafd7434dee4bc6e"}, + {file = "msgpack-1.0.4-cp38-cp38-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:81fc7ba725464651190b196f3cd848e8553d4d510114a954681fd0b9c479d7e1"}, + {file = "msgpack-1.0.4-cp38-cp38-musllinux_1_1_aarch64.whl", hash = "sha256:d5b5b962221fa2c5d3a7f8133f9abffc114fe218eb4365e40f17732ade576c8e"}, + {file = "msgpack-1.0.4-cp38-cp38-musllinux_1_1_i686.whl", hash = "sha256:77ccd2af37f3db0ea59fb280fa2165bf1b096510ba9fe0cc2bf8fa92a22fdb43"}, + {file = "msgpack-1.0.4-cp38-cp38-musllinux_1_1_x86_64.whl", hash = "sha256:b17be2478b622939e39b816e0aa8242611cc8d3583d1cd8ec31b249f04623243"}, + {file = "msgpack-1.0.4-cp38-cp38-win32.whl", hash = "sha256:2bb8cdf50dd623392fa75525cce44a65a12a00c98e1e37bf0fb08ddce2ff60d2"}, + {file = "msgpack-1.0.4-cp38-cp38-win_amd64.whl", hash = "sha256:26b8feaca40a90cbe031b03d82b2898bf560027160d3eae1423f4a67654ec5d6"}, + {file = "msgpack-1.0.4-cp39-cp39-macosx_10_9_universal2.whl", hash = "sha256:462497af5fd4e0edbb1559c352ad84f6c577ffbbb708566a0abaaa84acd9f3ae"}, + {file = "msgpack-1.0.4-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:2999623886c5c02deefe156e8f869c3b0aaeba14bfc50aa2486a0415178fce55"}, + {file = "msgpack-1.0.4-cp39-cp39-macosx_11_0_arm64.whl", hash = "sha256:f0029245c51fd9473dc1aede1160b0a29f4a912e6b1dd353fa6d317085b219da"}, + {file = "msgpack-1.0.4-cp39-cp39-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:ed6f7b854a823ea44cf94919ba3f727e230da29feb4a99711433f25800cf747f"}, + {file = "msgpack-1.0.4-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:0df96d6eaf45ceca04b3f3b4b111b86b33785683d682c655063ef8057d61fd92"}, + {file = "msgpack-1.0.4-cp39-cp39-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:6a4192b1ab40f8dca3f2877b70e63799d95c62c068c84dc028b40a6cb03ccd0f"}, + {file = "msgpack-1.0.4-cp39-cp39-musllinux_1_1_aarch64.whl", hash = "sha256:0e3590f9fb9f7fbc36df366267870e77269c03172d086fa76bb4eba8b2b46624"}, + {file = "msgpack-1.0.4-cp39-cp39-musllinux_1_1_i686.whl", hash = "sha256:1576bd97527a93c44fa856770197dec00d223b0b9f36ef03f65bac60197cedf8"}, + {file = "msgpack-1.0.4-cp39-cp39-musllinux_1_1_x86_64.whl", hash = "sha256:63e29d6e8c9ca22b21846234913c3466b7e4ee6e422f205a2988083de3b08cae"}, + {file = "msgpack-1.0.4-cp39-cp39-win32.whl", hash = "sha256:fb62ea4b62bfcb0b380d5680f9a4b3f9a2d166d9394e9bbd9666c0ee09a3645c"}, + {file = "msgpack-1.0.4-cp39-cp39-win_amd64.whl", hash = "sha256:4d5834a2a48965a349da1c5a79760d94a1a0172fbb5ab6b5b33cbf8447e109ce"}, + {file = "msgpack-1.0.4.tar.gz", hash = "sha256:f5d869c18f030202eb412f08b28d2afeea553d6613aee89e200d7aca7ef01f5f"}, +] +multidict = [ + {file = "multidict-6.0.2-cp310-cp310-macosx_10_9_universal2.whl", hash = "sha256:0b9e95a740109c6047602f4db4da9949e6c5945cefbad34a1299775ddc9a62e2"}, + {file = "multidict-6.0.2-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:ac0e27844758d7177989ce406acc6a83c16ed4524ebc363c1f748cba184d89d3"}, + {file = "multidict-6.0.2-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:041b81a5f6b38244b34dc18c7b6aba91f9cdaf854d9a39e5ff0b58e2b5773b9c"}, + {file = "multidict-6.0.2-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:5fdda29a3c7e76a064f2477c9aab1ba96fd94e02e386f1e665bca1807fc5386f"}, + {file = "multidict-6.0.2-cp310-cp310-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:3368bf2398b0e0fcbf46d85795adc4c259299fec50c1416d0f77c0a843a3eed9"}, + {file = "multidict-6.0.2-cp310-cp310-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:f4f052ee022928d34fe1f4d2bc743f32609fb79ed9c49a1710a5ad6b2198db20"}, + {file = "multidict-6.0.2-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:225383a6603c086e6cef0f2f05564acb4f4d5f019a4e3e983f572b8530f70c88"}, + {file = "multidict-6.0.2-cp310-cp310-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:50bd442726e288e884f7be9071016c15a8742eb689a593a0cac49ea093eef0a7"}, + {file = "multidict-6.0.2-cp310-cp310-musllinux_1_1_aarch64.whl", hash = "sha256:47e6a7e923e9cada7c139531feac59448f1f47727a79076c0b1ee80274cd8eee"}, + {file = "multidict-6.0.2-cp310-cp310-musllinux_1_1_i686.whl", hash = "sha256:0556a1d4ea2d949efe5fd76a09b4a82e3a4a30700553a6725535098d8d9fb672"}, + {file = "multidict-6.0.2-cp310-cp310-musllinux_1_1_ppc64le.whl", hash = "sha256:626fe10ac87851f4cffecee161fc6f8f9853f0f6f1035b59337a51d29ff3b4f9"}, + {file = "multidict-6.0.2-cp310-cp310-musllinux_1_1_s390x.whl", hash = "sha256:8064b7c6f0af936a741ea1efd18690bacfbae4078c0c385d7c3f611d11f0cf87"}, + {file = "multidict-6.0.2-cp310-cp310-musllinux_1_1_x86_64.whl", hash = "sha256:2d36e929d7f6a16d4eb11b250719c39560dd70545356365b494249e2186bc389"}, + {file = "multidict-6.0.2-cp310-cp310-win32.whl", hash = "sha256:fcb91630817aa8b9bc4a74023e4198480587269c272c58b3279875ed7235c293"}, + {file = "multidict-6.0.2-cp310-cp310-win_amd64.whl", hash = "sha256:8cbf0132f3de7cc6c6ce00147cc78e6439ea736cee6bca4f068bcf892b0fd658"}, + {file = "multidict-6.0.2-cp37-cp37m-macosx_10_9_x86_64.whl", hash = "sha256:05f6949d6169878a03e607a21e3b862eaf8e356590e8bdae4227eedadacf6e51"}, + {file = "multidict-6.0.2-cp37-cp37m-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:e2c2e459f7050aeb7c1b1276763364884595d47000c1cddb51764c0d8976e608"}, + {file = "multidict-6.0.2-cp37-cp37m-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:d0509e469d48940147e1235d994cd849a8f8195e0bca65f8f5439c56e17872a3"}, + {file = "multidict-6.0.2-cp37-cp37m-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:514fe2b8d750d6cdb4712346a2c5084a80220821a3e91f3f71eec11cf8d28fd4"}, + {file = "multidict-6.0.2-cp37-cp37m-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:19adcfc2a7197cdc3987044e3f415168fc5dc1f720c932eb1ef4f71a2067e08b"}, + {file = "multidict-6.0.2-cp37-cp37m-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:b9d153e7f1f9ba0b23ad1568b3b9e17301e23b042c23870f9ee0522dc5cc79e8"}, + {file = "multidict-6.0.2-cp37-cp37m-musllinux_1_1_aarch64.whl", hash = "sha256:aef9cc3d9c7d63d924adac329c33835e0243b5052a6dfcbf7732a921c6e918ba"}, + {file = "multidict-6.0.2-cp37-cp37m-musllinux_1_1_i686.whl", hash = "sha256:4571f1beddff25f3e925eea34268422622963cd8dc395bb8778eb28418248e43"}, + {file = "multidict-6.0.2-cp37-cp37m-musllinux_1_1_ppc64le.whl", hash = "sha256:d48b8ee1d4068561ce8033d2c344cf5232cb29ee1a0206a7b828c79cbc5982b8"}, + {file = "multidict-6.0.2-cp37-cp37m-musllinux_1_1_s390x.whl", hash = "sha256:45183c96ddf61bf96d2684d9fbaf6f3564d86b34cb125761f9a0ef9e36c1d55b"}, + {file = "multidict-6.0.2-cp37-cp37m-musllinux_1_1_x86_64.whl", hash = "sha256:75bdf08716edde767b09e76829db8c1e5ca9d8bb0a8d4bd94ae1eafe3dac5e15"}, + {file = "multidict-6.0.2-cp37-cp37m-win32.whl", hash = "sha256:a45e1135cb07086833ce969555df39149680e5471c04dfd6a915abd2fc3f6dbc"}, + {file = "multidict-6.0.2-cp37-cp37m-win_amd64.whl", hash = "sha256:6f3cdef8a247d1eafa649085812f8a310e728bdf3900ff6c434eafb2d443b23a"}, + {file = "multidict-6.0.2-cp38-cp38-macosx_10_9_universal2.whl", hash = "sha256:0327292e745a880459ef71be14e709aaea2f783f3537588fb4ed09b6c01bca60"}, + {file = "multidict-6.0.2-cp38-cp38-macosx_10_9_x86_64.whl", hash = "sha256:e875b6086e325bab7e680e4316d667fc0e5e174bb5611eb16b3ea121c8951b86"}, + {file = "multidict-6.0.2-cp38-cp38-macosx_11_0_arm64.whl", hash = "sha256:feea820722e69451743a3d56ad74948b68bf456984d63c1a92e8347b7b88452d"}, + {file = "multidict-6.0.2-cp38-cp38-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:9cc57c68cb9139c7cd6fc39f211b02198e69fb90ce4bc4a094cf5fe0d20fd8b0"}, + {file = "multidict-6.0.2-cp38-cp38-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:497988d6b6ec6ed6f87030ec03280b696ca47dbf0648045e4e1d28b80346560d"}, + {file = "multidict-6.0.2-cp38-cp38-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:89171b2c769e03a953d5969b2f272efa931426355b6c0cb508022976a17fd376"}, + {file = "multidict-6.0.2-cp38-cp38-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:684133b1e1fe91eda8fa7447f137c9490a064c6b7f392aa857bba83a28cfb693"}, + {file = "multidict-6.0.2-cp38-cp38-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:fd9fc9c4849a07f3635ccffa895d57abce554b467d611a5009ba4f39b78a8849"}, + {file = "multidict-6.0.2-cp38-cp38-musllinux_1_1_aarch64.whl", hash = "sha256:e07c8e79d6e6fd37b42f3250dba122053fddb319e84b55dd3a8d6446e1a7ee49"}, + {file = "multidict-6.0.2-cp38-cp38-musllinux_1_1_i686.whl", hash = "sha256:4070613ea2227da2bfb2c35a6041e4371b0af6b0be57f424fe2318b42a748516"}, + {file = "multidict-6.0.2-cp38-cp38-musllinux_1_1_ppc64le.whl", hash = "sha256:47fbeedbf94bed6547d3aa632075d804867a352d86688c04e606971595460227"}, + {file = "multidict-6.0.2-cp38-cp38-musllinux_1_1_s390x.whl", hash = "sha256:5774d9218d77befa7b70d836004a768fb9aa4fdb53c97498f4d8d3f67bb9cfa9"}, + {file = "multidict-6.0.2-cp38-cp38-musllinux_1_1_x86_64.whl", hash = "sha256:2957489cba47c2539a8eb7ab32ff49101439ccf78eab724c828c1a54ff3ff98d"}, + {file = "multidict-6.0.2-cp38-cp38-win32.whl", hash = "sha256:e5b20e9599ba74391ca0cfbd7b328fcc20976823ba19bc573983a25b32e92b57"}, + {file = "multidict-6.0.2-cp38-cp38-win_amd64.whl", hash = "sha256:8004dca28e15b86d1b1372515f32eb6f814bdf6f00952699bdeb541691091f96"}, + {file = "multidict-6.0.2-cp39-cp39-macosx_10_9_universal2.whl", hash = "sha256:2e4a0785b84fb59e43c18a015ffc575ba93f7d1dbd272b4cdad9f5134b8a006c"}, + {file = "multidict-6.0.2-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:6701bf8a5d03a43375909ac91b6980aea74b0f5402fbe9428fc3f6edf5d9677e"}, + {file = "multidict-6.0.2-cp39-cp39-macosx_11_0_arm64.whl", hash = "sha256:a007b1638e148c3cfb6bf0bdc4f82776cef0ac487191d093cdc316905e504071"}, + {file = "multidict-6.0.2-cp39-cp39-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:07a017cfa00c9890011628eab2503bee5872f27144936a52eaab449be5eaf032"}, + {file = "multidict-6.0.2-cp39-cp39-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:c207fff63adcdf5a485969131dc70e4b194327666b7e8a87a97fbc4fd80a53b2"}, + {file = "multidict-6.0.2-cp39-cp39-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:373ba9d1d061c76462d74e7de1c0c8e267e9791ee8cfefcf6b0b2495762c370c"}, + {file = "multidict-6.0.2-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:bfba7c6d5d7c9099ba21f84662b037a0ffd4a5e6b26ac07d19e423e6fdf965a9"}, + {file = "multidict-6.0.2-cp39-cp39-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:19d9bad105dfb34eb539c97b132057a4e709919ec4dd883ece5838bcbf262b80"}, + {file = "multidict-6.0.2-cp39-cp39-musllinux_1_1_aarch64.whl", hash = "sha256:de989b195c3d636ba000ee4281cd03bb1234635b124bf4cd89eeee9ca8fcb09d"}, + {file = "multidict-6.0.2-cp39-cp39-musllinux_1_1_i686.whl", hash = "sha256:7c40b7bbece294ae3a87c1bc2abff0ff9beef41d14188cda94ada7bcea99b0fb"}, + {file = "multidict-6.0.2-cp39-cp39-musllinux_1_1_ppc64le.whl", hash = "sha256:d16cce709ebfadc91278a1c005e3c17dd5f71f5098bfae1035149785ea6e9c68"}, + {file = "multidict-6.0.2-cp39-cp39-musllinux_1_1_s390x.whl", hash = "sha256:a2c34a93e1d2aa35fbf1485e5010337c72c6791407d03aa5f4eed920343dd360"}, + {file = "multidict-6.0.2-cp39-cp39-musllinux_1_1_x86_64.whl", hash = "sha256:feba80698173761cddd814fa22e88b0661e98cb810f9f986c54aa34d281e4937"}, + {file = "multidict-6.0.2-cp39-cp39-win32.whl", hash = "sha256:23b616fdc3c74c9fe01d76ce0d1ce872d2d396d8fa8e4899398ad64fb5aa214a"}, + {file = "multidict-6.0.2-cp39-cp39-win_amd64.whl", hash = "sha256:4bae31803d708f6f15fd98be6a6ac0b6958fcf68fda3c77a048a4f9073704aae"}, + {file = "multidict-6.0.2.tar.gz", hash = "sha256:5ff3bd75f38e4c43f1f470f2df7a4d430b821c4ce22be384e1459cb57d6bb013"}, +] +mypy = [] +mypy-extensions = [ + {file = "mypy_extensions-0.4.3-py2.py3-none-any.whl", hash = "sha256:090fedd75945a69ae91ce1303b5824f428daf5a028d2f6ab8a299250a846f15d"}, + {file = "mypy_extensions-0.4.3.tar.gz", hash = "sha256:2d82818f5bb3e369420cb3c4060a7970edba416647068eb4c5343488a6c604a8"}, +] +nanoid = [] +nodeenv = [ + {file = "nodeenv-1.7.0-py2.py3-none-any.whl", hash = "sha256:27083a7b96a25f2f5e1d8cb4b6317ee8aeda3bdd121394e5ac54e498028a042e"}, + {file = "nodeenv-1.7.0.tar.gz", hash = "sha256:e0e7f7dfb85fc5394c6fe1e8fa98131a2473e04311a45afb6508f7cf1836fa2b"}, +] +packaging = [ + {file = "packaging-21.3-py3-none-any.whl", hash = "sha256:ef103e05f519cdc783ae24ea4e2e0f508a9c99b2d4969652eed6a2e1ea5bd522"}, + {file = "packaging-21.3.tar.gz", hash = "sha256:dd47c42927d89ab911e606518907cc2d3a1f38bbd026385970643f9c5b8ecfeb"}, +] +pathspec = [] +platformdirs = [ + {file = "platformdirs-2.5.2-py3-none-any.whl", hash = "sha256:027d8e83a2d7de06bbac4e5ef7e023c02b863d7ea5d079477e722bb41ab25788"}, + {file = "platformdirs-2.5.2.tar.gz", hash = "sha256:58c8abb07dcb441e6ee4b11d8df0ac856038f944ab98b7be6b27b2a3c7feef19"}, +] +pluggy = [ + {file = "pluggy-1.0.0-py2.py3-none-any.whl", hash = "sha256:74134bbf457f031a36d68416e1509f34bd5ccc019f0bcc952c7b909d06b37bd3"}, + {file = "pluggy-1.0.0.tar.gz", hash = "sha256:4224373bacce55f955a878bf9cfa763c1e360858e330072059e10bad68531159"}, +] +pre-commit = [] +py = [ + {file = "py-1.11.0-py2.py3-none-any.whl", hash = "sha256:607c53218732647dff4acdfcd50cb62615cedf612e72d1724fb1a0cc6405b378"}, + {file = "py-1.11.0.tar.gz", hash = "sha256:51c75c4126074b472f746a24399ad32f6053d1b34b68d2fa41e558e6f4a98719"}, +] +pygments = [] +pymdown-extensions = [] +pyparsing = [ + {file = "pyparsing-3.0.9-py3-none-any.whl", hash = "sha256:5026bae9a10eeaefb61dab2f09052b9f4307d44aee4eda64b309723d8d206bbc"}, + {file = "pyparsing-3.0.9.tar.gz", hash = "sha256:2b020ecf7d21b687f219b71ecad3631f644a47f01403fa1d1036b0c6416d70fb"}, +] +pytest = [] +pytest-aiohttp = [ + {file = "pytest-aiohttp-1.0.4.tar.gz", hash = "sha256:39ff3a0d15484c01d1436cbedad575c6eafbf0f57cdf76fb94994c97b5b8c5a4"}, + {file = "pytest_aiohttp-1.0.4-py3-none-any.whl", hash = "sha256:1d2dc3a304c2be1fd496c0c2fb6b31ab60cd9fc33984f761f951f8ea1eb4ca95"}, +] +pytest-asyncio = [] +pytest-cov = [ + {file = "pytest-cov-2.12.1.tar.gz", hash = "sha256:261ceeb8c227b726249b376b8526b600f38667ee314f910353fa318caa01f4d7"}, + {file = "pytest_cov-2.12.1-py2.py3-none-any.whl", hash = "sha256:261bb9e47e65bd099c89c3edf92972865210c36813f80ede5277dceb77a4a62a"}, +] +python-dateutil = [ + {file = "python-dateutil-2.8.2.tar.gz", hash = "sha256:0123cacc1627ae19ddf3c27a5de5bd67ee4586fbdd6440d9748f8abb483d3e86"}, + {file = "python_dateutil-2.8.2-py2.py3-none-any.whl", hash = "sha256:961d03dc3453ebbc59dbdea9e4e11c5651520a876d0f4db161e8674aae935da9"}, +] +pyyaml = [ + {file = "PyYAML-6.0-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:d4db7c7aef085872ef65a8fd7d6d09a14ae91f691dec3e87ee5ee0539d516f53"}, + {file = "PyYAML-6.0-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:9df7ed3b3d2e0ecfe09e14741b857df43adb5a3ddadc919a2d94fbdf78fea53c"}, + {file = "PyYAML-6.0-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:77f396e6ef4c73fdc33a9157446466f1cff553d979bd00ecb64385760c6babdc"}, + {file = "PyYAML-6.0-cp310-cp310-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:a80a78046a72361de73f8f395f1f1e49f956c6be882eed58505a15f3e430962b"}, + {file = "PyYAML-6.0-cp310-cp310-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:f84fbc98b019fef2ee9a1cb3ce93e3187a6df0b2538a651bfb890254ba9f90b5"}, + {file = "PyYAML-6.0-cp310-cp310-win32.whl", hash = "sha256:2cd5df3de48857ed0544b34e2d40e9fac445930039f3cfe4bcc592a1f836d513"}, + {file = "PyYAML-6.0-cp310-cp310-win_amd64.whl", hash = "sha256:daf496c58a8c52083df09b80c860005194014c3698698d1a57cbcfa182142a3a"}, + {file = "PyYAML-6.0-cp36-cp36m-macosx_10_9_x86_64.whl", hash = "sha256:897b80890765f037df3403d22bab41627ca8811ae55e9a722fd0392850ec4d86"}, + {file = "PyYAML-6.0-cp36-cp36m-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:50602afada6d6cbfad699b0c7bb50d5ccffa7e46a3d738092afddc1f9758427f"}, + {file = "PyYAML-6.0-cp36-cp36m-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:48c346915c114f5fdb3ead70312bd042a953a8ce5c7106d5bfb1a5254e47da92"}, + {file = "PyYAML-6.0-cp36-cp36m-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:98c4d36e99714e55cfbaaee6dd5badbc9a1ec339ebfc3b1f52e293aee6bb71a4"}, + {file = "PyYAML-6.0-cp36-cp36m-win32.whl", hash = "sha256:0283c35a6a9fbf047493e3a0ce8d79ef5030852c51e9d911a27badfde0605293"}, + {file = "PyYAML-6.0-cp36-cp36m-win_amd64.whl", hash = "sha256:07751360502caac1c067a8132d150cf3d61339af5691fe9e87803040dbc5db57"}, + {file = "PyYAML-6.0-cp37-cp37m-macosx_10_9_x86_64.whl", hash = "sha256:819b3830a1543db06c4d4b865e70ded25be52a2e0631ccd2f6a47a2822f2fd7c"}, + {file = "PyYAML-6.0-cp37-cp37m-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:473f9edb243cb1935ab5a084eb238d842fb8f404ed2193a915d1784b5a6b5fc0"}, + {file = "PyYAML-6.0-cp37-cp37m-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:0ce82d761c532fe4ec3f87fc45688bdd3a4c1dc5e0b4a19814b9009a29baefd4"}, + {file = "PyYAML-6.0-cp37-cp37m-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:231710d57adfd809ef5d34183b8ed1eeae3f76459c18fb4a0b373ad56bedcdd9"}, + {file = "PyYAML-6.0-cp37-cp37m-win32.whl", hash = "sha256:c5687b8d43cf58545ade1fe3e055f70eac7a5a1a0bf42824308d868289a95737"}, + {file = "PyYAML-6.0-cp37-cp37m-win_amd64.whl", hash = "sha256:d15a181d1ecd0d4270dc32edb46f7cb7733c7c508857278d3d378d14d606db2d"}, + {file = "PyYAML-6.0-cp38-cp38-macosx_10_9_x86_64.whl", hash = "sha256:0b4624f379dab24d3725ffde76559cff63d9ec94e1736b556dacdfebe5ab6d4b"}, + {file = "PyYAML-6.0-cp38-cp38-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:213c60cd50106436cc818accf5baa1aba61c0189ff610f64f4a3e8c6726218ba"}, + {file = "PyYAML-6.0-cp38-cp38-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:9fa600030013c4de8165339db93d182b9431076eb98eb40ee068700c9c813e34"}, + {file = "PyYAML-6.0-cp38-cp38-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:277a0ef2981ca40581a47093e9e2d13b3f1fbbeffae064c1d21bfceba2030287"}, + {file = "PyYAML-6.0-cp38-cp38-win32.whl", hash = "sha256:d4eccecf9adf6fbcc6861a38015c2a64f38b9d94838ac1810a9023a0609e1b78"}, + {file = "PyYAML-6.0-cp38-cp38-win_amd64.whl", hash = "sha256:1e4747bc279b4f613a09eb64bba2ba602d8a6664c6ce6396a4d0cd413a50ce07"}, + {file = "PyYAML-6.0-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:055d937d65826939cb044fc8c9b08889e8c743fdc6a32b33e2390f66013e449b"}, + {file = "PyYAML-6.0-cp39-cp39-macosx_11_0_arm64.whl", hash = "sha256:e61ceaab6f49fb8bdfaa0f92c4b57bcfbea54c09277b1b4f7ac376bfb7a7c174"}, + {file = "PyYAML-6.0-cp39-cp39-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:d67d839ede4ed1b28a4e8909735fc992a923cdb84e618544973d7dfc71540803"}, + {file = "PyYAML-6.0-cp39-cp39-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:cba8c411ef271aa037d7357a2bc8f9ee8b58b9965831d9e51baf703280dc73d3"}, + {file = "PyYAML-6.0-cp39-cp39-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:40527857252b61eacd1d9af500c3337ba8deb8fc298940291486c465c8b46ec0"}, + {file = "PyYAML-6.0-cp39-cp39-win32.whl", hash = "sha256:b5b9eccad747aabaaffbc6064800670f0c297e52c12754eb1d976c57e4f74dcb"}, + {file = "PyYAML-6.0-cp39-cp39-win_amd64.whl", hash = "sha256:b3d267842bf12586ba6c734f89d1f5b871df0273157918b0ccefa29deb05c21c"}, + {file = "PyYAML-6.0.tar.gz", hash = "sha256:68fb519c14306fec9720a2a5b45bc9f0c8d1b9c72adf45c37baedfcd949c35a2"}, +] +pyyaml-env-tag = [ + {file = "pyyaml_env_tag-0.1-py3-none-any.whl", hash = "sha256:af31106dec8a4d68c60207c1886031cbf839b68aa7abccdb19868200532c2069"}, + {file = "pyyaml_env_tag-0.1.tar.gz", hash = "sha256:70092675bda14fdec33b31ba77e7543de9ddc88f2e5b99160396572d11525bdb"}, +] +requests = [] +rich = [] +six = [ + {file = "six-1.16.0-py2.py3-none-any.whl", hash = "sha256:8abb2f1d86890a2dfb989f9a77cfcfd3e47c2a354b01111771326f8aa26e0254"}, + {file = "six-1.16.0.tar.gz", hash = "sha256:1e61c37477a1626458e36f7b1d82aa5c9b094fa4802892072e49de9c60c4c926"}, +] +syrupy = [] +time-machine = [] +toml = [ + {file = "toml-0.10.2-py2.py3-none-any.whl", hash = "sha256:806143ae5bfb6a3c6e736a764057db0e6a0e05e338b5630894a5f779cabb4f9b"}, + {file = "toml-0.10.2.tar.gz", hash = "sha256:b3bda1d108d5dd99f4a20d24d9c348e91c4db7ab1b749200bded2f839ccbe68f"}, +] +tomli = [ + {file = "tomli-2.0.1-py3-none-any.whl", hash = "sha256:939de3e7a6161af0c887ef91b7d41a53e7c5a1ca976325f429cb46ea9bc30ecc"}, + {file = "tomli-2.0.1.tar.gz", hash = "sha256:de526c12914f0c550d15924c62d72abc48d6fe7364aa87328337a31007fe8a4f"}, +] +typed-ast = [ + {file = "typed_ast-1.5.4-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:669dd0c4167f6f2cd9f57041e03c3c2ebf9063d0757dc89f79ba1daa2bfca9d4"}, + {file = "typed_ast-1.5.4-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:211260621ab1cd7324e0798d6be953d00b74e0428382991adfddb352252f1d62"}, + {file = "typed_ast-1.5.4-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:267e3f78697a6c00c689c03db4876dd1efdfea2f251a5ad6555e82a26847b4ac"}, + {file = "typed_ast-1.5.4-cp310-cp310-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:c542eeda69212fa10a7ada75e668876fdec5f856cd3d06829e6aa64ad17c8dfe"}, + {file = "typed_ast-1.5.4-cp310-cp310-win_amd64.whl", hash = "sha256:a9916d2bb8865f973824fb47436fa45e1ebf2efd920f2b9f99342cb7fab93f72"}, + {file = "typed_ast-1.5.4-cp36-cp36m-macosx_10_9_x86_64.whl", hash = "sha256:79b1e0869db7c830ba6a981d58711c88b6677506e648496b1f64ac7d15633aec"}, + {file = "typed_ast-1.5.4-cp36-cp36m-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:a94d55d142c9265f4ea46fab70977a1944ecae359ae867397757d836ea5a3f47"}, + {file = "typed_ast-1.5.4-cp36-cp36m-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:183afdf0ec5b1b211724dfef3d2cad2d767cbefac291f24d69b00546c1837fb6"}, + {file = "typed_ast-1.5.4-cp36-cp36m-win_amd64.whl", hash = "sha256:639c5f0b21776605dd6c9dbe592d5228f021404dafd377e2b7ac046b0349b1a1"}, + {file = "typed_ast-1.5.4-cp37-cp37m-macosx_10_9_x86_64.whl", hash = "sha256:cf4afcfac006ece570e32d6fa90ab74a17245b83dfd6655a6f68568098345ff6"}, + {file = "typed_ast-1.5.4-cp37-cp37m-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:ed855bbe3eb3715fca349c80174cfcfd699c2f9de574d40527b8429acae23a66"}, + {file = "typed_ast-1.5.4-cp37-cp37m-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:6778e1b2f81dfc7bc58e4b259363b83d2e509a65198e85d5700dfae4c6c8ff1c"}, + {file = "typed_ast-1.5.4-cp37-cp37m-win_amd64.whl", hash = "sha256:0261195c2062caf107831e92a76764c81227dae162c4f75192c0d489faf751a2"}, + {file = "typed_ast-1.5.4-cp38-cp38-macosx_10_9_x86_64.whl", hash = "sha256:2efae9db7a8c05ad5547d522e7dbe62c83d838d3906a3716d1478b6c1d61388d"}, + {file = "typed_ast-1.5.4-cp38-cp38-macosx_11_0_arm64.whl", hash = "sha256:7d5d014b7daa8b0bf2eaef684295acae12b036d79f54178b92a2b6a56f92278f"}, + {file = "typed_ast-1.5.4-cp38-cp38-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:370788a63915e82fd6f212865a596a0fefcbb7d408bbbb13dea723d971ed8bdc"}, + {file = "typed_ast-1.5.4-cp38-cp38-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:4e964b4ff86550a7a7d56345c7864b18f403f5bd7380edf44a3c1fb4ee7ac6c6"}, + {file = "typed_ast-1.5.4-cp38-cp38-win_amd64.whl", hash = "sha256:683407d92dc953c8a7347119596f0b0e6c55eb98ebebd9b23437501b28dcbb8e"}, + {file = "typed_ast-1.5.4-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:4879da6c9b73443f97e731b617184a596ac1235fe91f98d279a7af36c796da35"}, + {file = "typed_ast-1.5.4-cp39-cp39-macosx_11_0_arm64.whl", hash = "sha256:3e123d878ba170397916557d31c8f589951e353cc95fb7f24f6bb69adc1a8a97"}, + {file = "typed_ast-1.5.4-cp39-cp39-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:ebd9d7f80ccf7a82ac5f88c521115cc55d84e35bf8b446fcd7836eb6b98929a3"}, + {file = "typed_ast-1.5.4-cp39-cp39-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:98f80dee3c03455e92796b58b98ff6ca0b2a6f652120c263efdba4d6c5e58f72"}, + {file = "typed_ast-1.5.4-cp39-cp39-win_amd64.whl", hash = "sha256:0fdbcf2fef0ca421a3f5912555804296f0b0960f0418c440f5d6d3abb549f3e1"}, + {file = "typed_ast-1.5.4.tar.gz", hash = "sha256:39e21ceb7388e4bb37f4c679d72707ed46c2fbf2a5609b8b8ebc4b067d977df2"}, +] +typing-extensions = [] +urllib3 = [] +virtualenv = [] +watchdog = [ + {file = "watchdog-2.1.9-cp310-cp310-macosx_10_9_universal2.whl", hash = "sha256:a735a990a1095f75ca4f36ea2ef2752c99e6ee997c46b0de507ba40a09bf7330"}, + {file = "watchdog-2.1.9-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:6b17d302850c8d412784d9246cfe8d7e3af6bcd45f958abb2d08a6f8bedf695d"}, + {file = "watchdog-2.1.9-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:ee3e38a6cc050a8830089f79cbec8a3878ec2fe5160cdb2dc8ccb6def8552658"}, + {file = "watchdog-2.1.9-cp36-cp36m-macosx_10_9_x86_64.whl", hash = "sha256:64a27aed691408a6abd83394b38503e8176f69031ca25d64131d8d640a307591"}, + {file = "watchdog-2.1.9-cp37-cp37m-macosx_10_9_x86_64.whl", hash = "sha256:195fc70c6e41237362ba720e9aaf394f8178bfc7fa68207f112d108edef1af33"}, + {file = "watchdog-2.1.9-cp38-cp38-macosx_10_9_universal2.whl", hash = "sha256:bfc4d351e6348d6ec51df007432e6fe80adb53fd41183716017026af03427846"}, + {file = "watchdog-2.1.9-cp38-cp38-macosx_10_9_x86_64.whl", hash = "sha256:8250546a98388cbc00c3ee3cc5cf96799b5a595270dfcfa855491a64b86ef8c3"}, + {file = "watchdog-2.1.9-cp38-cp38-macosx_11_0_arm64.whl", hash = "sha256:117ffc6ec261639a0209a3252546b12800670d4bf5f84fbd355957a0595fe654"}, + {file = "watchdog-2.1.9-cp39-cp39-macosx_10_9_universal2.whl", hash = "sha256:97f9752208f5154e9e7b76acc8c4f5a58801b338de2af14e7e181ee3b28a5d39"}, + {file = "watchdog-2.1.9-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:247dcf1df956daa24828bfea5a138d0e7a7c98b1a47cf1fa5b0c3c16241fcbb7"}, + {file = "watchdog-2.1.9-cp39-cp39-macosx_11_0_arm64.whl", hash = "sha256:226b3c6c468ce72051a4c15a4cc2ef317c32590d82ba0b330403cafd98a62cfd"}, + {file = "watchdog-2.1.9-pp37-pypy37_pp73-macosx_10_9_x86_64.whl", hash = "sha256:d9820fe47c20c13e3c9dd544d3706a2a26c02b2b43c993b62fcd8011bcc0adb3"}, + {file = "watchdog-2.1.9-pp38-pypy38_pp73-macosx_10_9_x86_64.whl", hash = "sha256:70af927aa1613ded6a68089a9262a009fbdf819f46d09c1a908d4b36e1ba2b2d"}, + {file = "watchdog-2.1.9-pp39-pypy39_pp73-macosx_10_9_x86_64.whl", hash = "sha256:ed80a1628cee19f5cfc6bb74e173f1b4189eb532e705e2a13e3250312a62e0c9"}, + {file = "watchdog-2.1.9-py3-none-manylinux2014_aarch64.whl", hash = "sha256:9f05a5f7c12452f6a27203f76779ae3f46fa30f1dd833037ea8cbc2887c60213"}, + {file = "watchdog-2.1.9-py3-none-manylinux2014_armv7l.whl", hash = "sha256:255bb5758f7e89b1a13c05a5bceccec2219f8995a3a4c4d6968fe1de6a3b2892"}, + {file = "watchdog-2.1.9-py3-none-manylinux2014_i686.whl", hash = "sha256:d3dda00aca282b26194bdd0adec21e4c21e916956d972369359ba63ade616153"}, + {file = "watchdog-2.1.9-py3-none-manylinux2014_ppc64.whl", hash = "sha256:186f6c55abc5e03872ae14c2f294a153ec7292f807af99f57611acc8caa75306"}, + {file = "watchdog-2.1.9-py3-none-manylinux2014_ppc64le.whl", hash = "sha256:083171652584e1b8829581f965b9b7723ca5f9a2cd7e20271edf264cfd7c1412"}, + {file = "watchdog-2.1.9-py3-none-manylinux2014_s390x.whl", hash = "sha256:b530ae007a5f5d50b7fbba96634c7ee21abec70dc3e7f0233339c81943848dc1"}, + {file = "watchdog-2.1.9-py3-none-manylinux2014_x86_64.whl", hash = "sha256:4f4e1c4aa54fb86316a62a87b3378c025e228178d55481d30d857c6c438897d6"}, + {file = "watchdog-2.1.9-py3-none-win32.whl", hash = "sha256:5952135968519e2447a01875a6f5fc8c03190b24d14ee52b0f4b1682259520b1"}, + {file = "watchdog-2.1.9-py3-none-win_amd64.whl", hash = "sha256:7a833211f49143c3d336729b0020ffd1274078e94b0ae42e22f596999f50279c"}, + {file = "watchdog-2.1.9-py3-none-win_ia64.whl", hash = "sha256:ad576a565260d8f99d97f2e64b0f97a48228317095908568a9d5c786c829d428"}, + {file = "watchdog-2.1.9.tar.gz", hash = "sha256:43ce20ebb36a51f21fa376f76d1d4692452b2527ccd601950d69ed36b9e21609"}, +] +yarl = [] +zipp = [] diff --git a/testbed/Textualize__textual/pyproject.toml b/testbed/Textualize__textual/pyproject.toml new file mode 100644 index 0000000000000000000000000000000000000000..460ba3d9af8a3ffc2ed2856bfcdff917c372b739 --- /dev/null +++ b/testbed/Textualize__textual/pyproject.toml @@ -0,0 +1,71 @@ +[tool.poetry] +name = "textual" +version = "0.2.0b5" +homepage = "https://github.com/Textualize/textual" +description = "Modern Text User Interface framework" +authors = ["Will McGugan "] +license = "MIT" +readme = "README.md" +classifiers = [ + "Development Status :: 1 - Planning", + "Environment :: Console", + "Intended Audience :: Developers", + "Operating System :: MacOS", + "Operating System :: POSIX :: Linux", + "Programming Language :: Python :: 3.7", + "Programming Language :: Python :: 3.8", + "Programming Language :: Python :: 3.9", + "Programming Language :: Python :: 3.10", + "Typing :: Typed", +] +include = [ + "src/textual/py.typed" +] + +[tool.poetry.scripts] +textual = "textual.cli.cli:run" + +[tool.poetry.dependencies] +python = "^3.7" +rich = "^12.6.0" +#rich = {path="../rich", develop=true} +importlib-metadata = "^4.11.3" +typing-extensions = { version = "^4.0.0", python = "<3.10" } + +# Dependencies below are required for devtools only +aiohttp = { version = "^3.8.1", optional = true } +click = {version = "8.1.2", optional = true} +msgpack = { version = "^1.0.3", optional = true } +nanoid = "^2.0.0" + +[tool.poetry.extras] +dev = ["aiohttp", "click", "msgpack"] + +[tool.poetry.dev-dependencies] +pytest = "^7.1.3" +black = "^22.3.0" +mypy = "^0.982" +pytest-cov = "^2.12.1" +mkdocs = "^1.3.0" +mkdocstrings = {extras = ["python"], version = "^0.19.0"} +mkdocs-material = "^8.2.15" +pre-commit = "^2.13.0" +pytest-aiohttp = "^1.0.4" +time-machine = "^2.6.0" +Jinja2 = "<3.1.0" +syrupy = "^3.0.0" + +[tool.black] +includes = "src" + +[tool.pytest.ini_options] +asyncio_mode = "auto" +testpaths = ["tests"] +addopts = "--strict-markers" +markers = [ + "integration_test: marks tests as slow integration tests (deselect with '-m \"not integration_test\"')", +] + +[build-system] +requires = ["poetry-core>=1.0.0"] +build-backend = "poetry.core.masonry.api" diff --git a/testbed/Textualize__textual/reference/README.md b/testbed/Textualize__textual/reference/README.md new file mode 100644 index 0000000000000000000000000000000000000000..62f72ad39e86c6d886ec8e3f5c1d2b7d63603605 --- /dev/null +++ b/testbed/Textualize__textual/reference/README.md @@ -0,0 +1 @@ +Contains private docs, mainly for the developers reference diff --git a/testbed/Textualize__textual/reference/_color_system.md b/testbed/Textualize__textual/reference/_color_system.md new file mode 100644 index 0000000000000000000000000000000000000000..7915c39f95f6997006192ea8484356d8027ccedf --- /dev/null +++ b/testbed/Textualize__textual/reference/_color_system.md @@ -0,0 +1,73 @@ +_Note: This is kind of a living document, which might not form part of the user-facing documentation._ + +# Textual Color System + +Textual's color system is a palette of colors for building TUIs, and a set of guidelines for how they should be used. Based loosely on Google's Material color system, the Textual color system ensures that elements in the TUI look aesthetically pleasing while maximizing legibility + +## The colors + +There are 10 base colors specified in the Textual Color System. Although it is unlikely that all will need to be specified, since some may be derived from others, and some defaults may not need to be changed. + +A dark mode is automatically derived from the base colors. See Dark Mode below. + +### Shades + +Each color has 6 additional shades (3 darker and 3 lighter), giving a total of 7 shades per color. These are calculated automatically from the base colors. + +### Primary and Secondary + +The _primary_ and _secondary_ colors are used as a background for large areas of the interface, such as headers and sidebars. The secondary color is optional, and if not supplied will be set to be the same as primary. If supplied, the secondary color should be compliment the primary, and together can be considered the _branding colors_ as they have the greatest influence over the look of the TUI. + +### Background and Surface + +The _surface_ colors is the base color which goes behind text. The _background_ color is typically the negative space where there is no content. + +These two colors tend to be very similar, with just enough difference in lightness to tell them apart. They should be chosen for good contrast with the text. + +In light mode the default background is #efefef (a bright grey) and the surface is #f5f5f5 (off white). In dark mode the default background is 100% black, and the default surface is #121212 (very dark grey). + +Note that, although both background and surface support the full range of shades, it may not be possible to darken or lighten them further. i.e. you can't get any lighter than 100% white or darken than 100% black. + +### Panel + +The _panel_ color is typically used as a background to emphasize text on the default surface, or as a UI element that is above the regular UI, such as a menu. + +The default panel color is derived from the surface color by blending it towards either white or black text (depending on mode). + +Unlike background and surface, the panel color is automatically selected so that it can always be lightened or darkened by the full range. + +### Accent + +The _accent_ color should be a contrasting color use in UI elements that should stand out, such as selections, status bars, and underlines. + +### Warning, Error, and Success + +The _warning_, _error_, and _success_ colors have semantic meaning. While they could be any color, by convention warning should be amber / orange, error should be red, and success should be green. + +### System + +The system color is used for system controls such as scrollbars. The default is for the system color to be the same as accent, but it is recommended that a different color is chosen to differentiate app controls from those rendered by the Textual system. + +## Text + +For every color and shade there is an automatically calculated text color, which is either white or black, chosen to produce the greatest contrast. + +The default text color as a slight alpha component, so that it not pure black or pure white, but a slight tint of the background showing through. Additionally, there are two text shades with increasingly greater alpha for reduced intensity text. + +## Dark Mode + +A dark mode is automatically generated from the theme. The dark variations of the primary and secondary colors are generated by blending with the background color. This ensures that the branding remains intact, while still providing dark backgrounds. + +The dark variations of the background and surface color defaults are selected. The other colors remain the same as light mode. The overall effect is that the majority of the interface is dark, with small portions highlighted by color. + +## Naming + +The color system produces a number of constants which are exposed in the CSS via variables. + +The name of the color will return one of the standard set of colors, for example `primary` or `panel`. + +For one of the shade variations, you can append `-darken-1`, `-darken-2`, `-darken-3` for increasingly darker colors, and `-lighten-1`, `lighten-2`, `lighten-3` for increasingly light colors. + +For the contrasting text color, prefix the name with `text-`, for instance `text-primary` or `text-panel`. Note that if the text is to be on top of a darkened or lightened color, it must also be included in the name. i.e. if the background is `primary-darken-2`, then the corresponding text color should be `text-primary-darken-2`. + +The additional two levels of faded text may be requested by appending `-fade-1` or `-fade-2` for decreasing levels of text alpha. diff --git a/testbed/Textualize__textual/reference/_devtools.md b/testbed/Textualize__textual/reference/_devtools.md new file mode 100644 index 0000000000000000000000000000000000000000..fa66208fe4fb6b1fb99f7ef23f043be55c0bc1f1 --- /dev/null +++ b/testbed/Textualize__textual/reference/_devtools.md @@ -0,0 +1,14 @@ +# Devtools + +## Installation + +Using the Textual Devtools requires installation of the `dev` extra dependency. + +https://python-poetry.org/docs/pyproject/#extras + +## Running + +TODO: Note how we run the devtools themselves and how we run our Textual apps +such that they can connect. Don't forget Windows instructions :) +We might also add a link to the documentation from the exception that gets +raised when the "dev" extra dependencies aren't installed. diff --git a/testbed/Textualize__textual/reference/box.monopic b/testbed/Textualize__textual/reference/box.monopic new file mode 100644 index 0000000000000000000000000000000000000000..064eb03e4ba1158bfaec55d202625a1a4714cf34 Binary files /dev/null and b/testbed/Textualize__textual/reference/box.monopic differ diff --git a/testbed/Textualize__textual/sandbox/darren/basic.css b/testbed/Textualize__textual/sandbox/darren/basic.css new file mode 100644 index 0000000000000000000000000000000000000000..ce284de80997b2fd9c471c718c0ca2f4e7d2f50e --- /dev/null +++ b/testbed/Textualize__textual/sandbox/darren/basic.css @@ -0,0 +1,252 @@ +/* CSS file for basic.py */ + + + + * { + transition: color 300ms linear, background 300ms linear; +} + + +*:hover { + /* tint: 30% red; + /* outline: heavy red; */ +} + +App > Screen { + + background: $surface; + color: $text; + layers: base sidebar; + + color: $text; + background: $background; + layout: vertical; + + overflow: hidden; + +} + +#tree-container { + overflow-y: auto; + height: 20; + margin: 1 2; + background: $panel; + padding: 1 2; +} + +DirectoryTree { + padding: 0 1; + height: auto; + +} + + + + +DataTable { + /*border:heavy red;*/ + /* tint: 10% green; */ + /* opacity: 50%; */ + padding: 1; + margin: 1 2; + height: 24; +} + +#sidebar { + color: $text; + background: $panel; + dock: left; + width: 30; + margin-bottom: 1; + offset-x: -100%; + transition: offset 500ms in_out_cubic 2s; + layer: sidebar; +} + +#sidebar.-active { + offset-x: 0; +} + +#sidebar .title { + height: 1; + background: $primary-background-darken-1; + color: $text-muted; + border-right: wide $background; + content-align: center middle; +} + +#sidebar .user { + height: 8; + background: $panel-darken-1; + color: $text-muted; + border-right: wide $background; + content-align: center middle; +} + +#sidebar .content { + background: $panel-darken-2; + color: $text; + border-right: wide $background; + content-align: center middle; +} + + + + +Tweet { + height:12; + width: 100%; + + + background: $panel; + color: $text; + layout: vertical; + /* border: outer $primary; */ + padding: 1; + border: wide $panel; + overflow: auto; + /* scrollbar-gutter: stable; */ + align-horizontal: center; + box-sizing: border-box; +} + + +.scrollable { + overflow-x: auto; + overflow-y: scroll; + margin: 1 2; + height: 24; + align-horizontal: center; + layout: vertical; +} + +.code { + height: auto; + +} + + +TweetHeader { + height:1; + background: $accent; + color: $text +} + +TweetBody { + width: 100%; + background: $panel; + color: $text; + height: auto; + padding: 0 1 0 0; +} + +Tweet.scroll-horizontal TweetBody { + width: 350; +} + +.button { + background: $accent; + color: $text; + width:20; + height: 3; + /* border-top: hidden $accent-darken-3; */ + border: tall $accent-darken-2; + /* border-left: tall $accent-darken-1; */ + + + /* padding: 1 0 0 0 ; */ + + transition: background 400ms in_out_cubic, color 400ms in_out_cubic; + +} + +.button:hover { + background: $accent-lighten-1; + color: $text-disabled; + width: 20; + height: 3; + border: tall $accent-darken-1; + /* border-left: tall $accent-darken-3; */ + + + + +} + +#footer { + color: $text; + background: $accent; + height: 1; + + content-align: center middle; + dock:bottom; +} + + +#sidebar .content { + layout: vertical +} + +OptionItem { + height: 3; + background: $panel; + border-right: wide $background; + border-left: blank; + content-align: center middle; +} + +OptionItem:hover { + height: 3; + color: $text; + background: $primary-darken-1; + /* border-top: hkey $accent2-darken-3; + border-bottom: hkey $accent2-darken-3; */ + text-style: bold; + border-left: outer $secondary-darken-2; +} + +Error { + width: 100%; + height:3; + background: $error; + color: $text; + border-top: tall $error-darken-2; + border-bottom: tall $error-darken-2; + + padding: 0; + text-style: bold; + align-horizontal: center; +} + +Warning { + width: 100%; + height:3; + background: $warning; + color: $text-muted; + border-top: tall $warning-darken-2; + border-bottom: tall $warning-darken-2; + + text-style: bold; + align-horizontal: center; +} + +Success { + width: 100%; + + height:auto; + box-sizing: border-box; + background: $success; + color: $text-muted; + + border-top: hkey $success-darken-2; + border-bottom: hkey $success-darken-2; + + text-style: bold ; + + align-horizontal: center; +} + + +.horizontal { + layout: horizontal +} diff --git a/testbed/Textualize__textual/sandbox/darren/basic.py b/testbed/Textualize__textual/sandbox/darren/basic.py new file mode 100644 index 0000000000000000000000000000000000000000..4c70cdd699d15a069692c14ea4cbfc3a0eec2315 --- /dev/null +++ b/testbed/Textualize__textual/sandbox/darren/basic.py @@ -0,0 +1,235 @@ +from rich.console import RenderableType + +from rich.syntax import Syntax +from rich.text import Text + +from textual.app import App, ComposeResult +from textual.reactive import Reactive +from textual.widget import Widget +from textual.widgets import Static, DataTable, DirectoryTree, Header, Footer +from textual.containers import Container + +CODE = ''' +from __future__ import annotations + +from typing import Iterable, TypeVar + +T = TypeVar("T") + + +def loop_first(values: Iterable[T]) -> Iterable[tuple[bool, T]]: + """Iterate and generate a tuple with a flag for first value.""" + iter_values = iter(values) + try: + value = next(iter_values) + except StopIteration: + return + yield True, value + for value in iter_values: + yield False, value + + +def loop_last(values: Iterable[T]) -> Iterable[tuple[bool, T]]: + """Iterate and generate a tuple with a flag for last value.""" + iter_values = iter(values) + try: + previous_value = next(iter_values) + except StopIteration: + return + for value in iter_values: + yield False, previous_value + previous_value = value + yield True, previous_value + + +def loop_first_last(values: Iterable[T]) -> Iterable[tuple[bool, bool, T]]: + """Iterate and generate a tuple with a flag for first and last value.""" + iter_values = iter(values) + try: + previous_value = next(iter_values) + except StopIteration: + return + first = True + for value in iter_values: + yield first, False, previous_value + first = False + previous_value = value + yield first, True, previous_value +''' + + +lorem_short = """Lorem ipsum dolor sit amet, consectetur adipiscing elit. In velit liber a a a, volutpat nec hendrerit at, faucibus in odio. Aliquam hendrerit nibh sed quam volutpat maximus. Nullam suscipit convallis lorem quis sodales. In tristique lobortis ante et dictum. Ut at finibus ipsum.""" +lorem = ( + lorem_short + + """ In urna dolor, placerat et mi facilisis, congue sollicitudin massa. Phasellus felis turpis, cursus eu lectus et, porttitor malesuada augue. Sed feugiat volutpat velit, sollicitudin fringilla velit bibendum faucibus. Lorem ipsum dolor sit amet, consectetur adipiscing elit. In velit libero, volutpat nec hendrerit at, faucibus in odio. Aliquam hendrerit nibh sed quam volutpat maximus. Nullam suscipit convallis lorem quis sodales. In tristique lobortis ante et dictum. Ut at finibus ipsum. In urna dolor, placerat et mi facilisis, congue sollicitudin massa. Phasellus felis turpis, cursus eu lectus et, porttitor malesuada augue. Sed feugiat volutpat velit, sollicitudin fringilla velit bibendum faucibus. """ +) + +lorem_short_text = Text.from_markup(lorem_short) +lorem_long_text = Text.from_markup(lorem * 2) + + +class TweetHeader(Widget): + def render(self) -> RenderableType: + return Text("Lorem Impsum", justify="center") + + +class TweetBody(Widget): + short_lorem = Reactive(False) + + def render(self) -> Text: + return lorem_short_text if self.short_lorem else lorem_long_text + + +class Tweet(Widget): + pass + + +class OptionItem(Widget): + def render(self) -> Text: + return Text("Option") + + +class Error(Widget): + def render(self) -> Text: + return Text("This is an error message", justify="center") + + +class Warning(Widget): + def render(self) -> Text: + return Text("This is a warning message", justify="center") + + +class Success(Widget): + def render(self) -> Text: + return Text("This is a success message", justify="center") + + +class BasicApp(App, css_path="basic.css"): + """A basic app demonstrating CSS""" + + def on_load(self): + """Bind keys here.""" + self.bind("s", "toggle_class('#sidebar', '-active')", description="Sidebar") + self.bind("d", "toggle_dark", description="Dark mode") + self.bind("q", "quit", description="Quit") + self.bind("f", "query_test", description="Query test") + + def compose(self): + yield Header() + + table = DataTable() + self.scroll_to_target = Tweet(TweetBody()) + + yield Container( + Tweet(TweetBody()), + Widget( + Static( + Syntax(CODE, "python", line_numbers=True, indent_guides=True), + classes="code", + ), + classes="scrollable", + ), + table, + Widget(DirectoryTree("~/code/textual"), id="tree-container"), + Error(), + Tweet(TweetBody(), classes="scrollbar-size-custom"), + Warning(), + Tweet(TweetBody(), classes="scroll-horizontal"), + Success(), + Tweet(TweetBody(), classes="scroll-horizontal"), + Tweet(TweetBody(), classes="scroll-horizontal"), + Tweet(TweetBody(), classes="scroll-horizontal"), + Tweet(TweetBody(), classes="scroll-horizontal"), + Tweet(TweetBody(), classes="scroll-horizontal"), + ) + yield Widget( + Widget(classes="title"), + Widget(classes="user"), + OptionItem(), + OptionItem(), + OptionItem(), + Widget(classes="content"), + id="sidebar", + ) + yield Footer() + + table.add_column("Foo", width=20) + table.add_column("Bar", width=20) + table.add_column("Baz", width=20) + table.add_column("Foo", width=20) + table.add_column("Bar", width=20) + table.add_column("Baz", width=20) + table.zebra_stripes = True + for n in range(100): + table.add_row(*[f"Cell ([b]{n}[/b], {col})" for col in range(6)]) + + def on_mount(self): + self.sub_title = "Widget demo" + + async def on_key(self, event) -> None: + await self.dispatch_key(event) + + def action_toggle_dark(self): + self.dark = not self.dark + + def action_query_test(self): + query = self.query("Tweet") + self.log(query) + self.log(query.nodes) + self.log(query) + self.log(query.nodes) + + query.set_styles("outline: outer red;") + + query = query.exclude(".scroll-horizontal") + self.log(query) + self.log(query.nodes) + + # query = query.filter(".rubbish") + # self.log(query) + # self.log(query.first()) + + async def key_q(self): + await self.shutdown() + + def key_x(self): + self.panic(self.tree) + + def key_escape(self): + self.app.bell() + + def key_t(self): + # Pressing "t" toggles the content of the TweetBody widget, from a long "Lorem ipsum..." to a shorter one. + tweet_body = self.query("TweetBody").first() + tweet_body.short_lorem = not tweet_body.short_lorem + + def key_v(self): + self.get_child(id="content").scroll_to_widget(self.scroll_to_target) + + def key_space(self): + self.bell() + + +app = BasicApp() + +if __name__ == "__main__": + app.run() + + # from textual.geometry import Region + # from textual.color import Color + + # print(Region.intersection.cache_info()) + # print(Region.overlaps.cache_info()) + # print(Region.union.cache_info()) + # print(Region.split_vertical.cache_info()) + # print(Region.__contains__.cache_info()) + # from textual.css.scalar import Scalar + + # print(Scalar.resolve_dimension.cache_info()) + + # from rich.style import Style + # from rich.cells import cached_cell_len + + # print(Style._add.cache_info()) + + # print(cached_cell_len.cache_info()) diff --git a/testbed/Textualize__textual/sandbox/darren/buttons.css b/testbed/Textualize__textual/sandbox/darren/buttons.css new file mode 100644 index 0000000000000000000000000000000000000000..695e85016cb57b84d3c65cd1400dc4f9caa5f912 --- /dev/null +++ b/testbed/Textualize__textual/sandbox/darren/buttons.css @@ -0,0 +1,6 @@ +Button { + padding-left: 1; + padding-right: 1; + margin: 3; + text-opacity: 30%; +} diff --git a/testbed/Textualize__textual/sandbox/darren/buttons.py b/testbed/Textualize__textual/sandbox/darren/buttons.py new file mode 100644 index 0000000000000000000000000000000000000000..65d9e3ffcd19215505d701c971695d585c258dcf --- /dev/null +++ b/testbed/Textualize__textual/sandbox/darren/buttons.py @@ -0,0 +1,34 @@ +from textual import events +from textual.app import App, ComposeResult +from textual.containers import Vertical +from textual.widgets import Button + + +class ButtonsApp(App[str]): + def compose(self) -> ComposeResult: + yield Vertical( + Button("default", id="foo"), + Button.success("success", id="bar"), + Button.warning("warning", id="baz"), + Button.error("error", id="baz"), + ) + + def on_button_pressed(self, event: Button.Pressed) -> None: + self.app.bell() + + async def on_key(self, event: events.Key) -> None: + await self.dispatch_key(event) + + def key_d(self): + self.dark = not self.dark + + +app = ButtonsApp( + log_path="textual.log", + css_path="buttons.css", + watch_css=True, +) + +if __name__ == "__main__": + result = app.run() + print(repr(result)) diff --git a/testbed/Textualize__textual/sandbox/darren/file_search.py b/testbed/Textualize__textual/sandbox/darren/file_search.py new file mode 100644 index 0000000000000000000000000000000000000000..da25f983af5c31ab1e55ea8cff48c81dbdb81d2a --- /dev/null +++ b/testbed/Textualize__textual/sandbox/darren/file_search.py @@ -0,0 +1,68 @@ +from __future__ import annotations + +from pathlib import Path +from typing import Iterable + +from rich.console import RenderableType +from rich.table import Table +from rich.text import Text + +from textual.app import App +from textual.geometry import Size +from textual.reactive import Reactive +from textual.widget import Widget +from textual.widgets._input import Input + + +def get_files() -> list[Path]: + files = list(Path.cwd().iterdir()) + return files + + +class FileTable(Widget): + filter = Reactive("", layout=True) + + def __init__(self, *args, files: Iterable[Path] | None = None, **kwargs): + super().__init__(*args, **kwargs) + self.files = files if files is not None else [] + + @property + def filtered_files(self) -> list[Path]: + return [ + file + for file in self.files + if self.filter == "" or (self.filter and self.filter in file.name) + ] + + def get_content_height(self, container: Size, viewport: Size, width: int) -> int: + return len(self.filtered_files) + + def render(self) -> RenderableType: + grid = Table.grid() + grid.add_column() + for file in self.filtered_files: + file_text = Text(f" {file.name}") + if self.filter: + file_text.highlight_regex(self.filter, "black on yellow") + grid.add_row(file_text) + return grid + + +class FileSearchApp(App): + dark = True + + def on_mount(self) -> None: + self.file_table = FileTable(id="file_table", files=list(Path.cwd().iterdir())) + self.search_bar = Input(placeholder="Search for files...") + # self.search_bar.focus() + self.mount(search_bar=self.search_bar) + self.mount(file_table_wrapper=Widget(self.file_table)) + + def on_input_changed(self, event: Input.Changed) -> None: + self.file_table.filter = event.value + + +app = FileSearchApp(css_path="file_search.scss", watch_css=True) + +if __name__ == "__main__": + result = app.run() diff --git a/testbed/Textualize__textual/sandbox/darren/file_search.scss b/testbed/Textualize__textual/sandbox/darren/file_search.scss new file mode 100644 index 0000000000000000000000000000000000000000..b1d95cea60a90efb1717f94afb3dea6eb2e8f080 --- /dev/null +++ b/testbed/Textualize__textual/sandbox/darren/file_search.scss @@ -0,0 +1,15 @@ +Screen { + +} + +#file_table_wrapper { + scrollbar-color: $accent-darken-1; +} + +#file_table { + height: auto; +} + +#search_bar { + height: 1; +} diff --git a/testbed/Textualize__textual/sandbox/darren/just_a_box.css b/testbed/Textualize__textual/sandbox/darren/just_a_box.css new file mode 100644 index 0000000000000000000000000000000000000000..45797dac1bb1a9ef6c5a53ad87d60fee87c43df7 --- /dev/null +++ b/testbed/Textualize__textual/sandbox/darren/just_a_box.css @@ -0,0 +1,12 @@ +Screen { + align: center middle; + background: darkslategrey; + overflow: auto auto; +} + +#box1 { + background: darkmagenta; + width: auto; + opacity: 0.5; + padding: 4 8; +} diff --git a/testbed/Textualize__textual/sandbox/darren/just_a_box.py b/testbed/Textualize__textual/sandbox/darren/just_a_box.py new file mode 100644 index 0000000000000000000000000000000000000000..51157227cec488b511b00d837a668a564f1d5d31 --- /dev/null +++ b/testbed/Textualize__textual/sandbox/darren/just_a_box.py @@ -0,0 +1,35 @@ +from __future__ import annotations + +from textual.app import App, ComposeResult +from textual.binding import Binding +from textual.widgets import Static, Footer, Header + + +class JustABox(App): + BINDINGS = [ + Binding(key="t", action="text_fade_out", description="text-opacity fade out"), + Binding(key="o,f,w", action="widget_fade_out", description="opacity fade out"), + ] + + def compose(self) -> ComposeResult: + yield Header() + yield Static("Hello, world!", id="box1") + yield Footer() + + def action_text_fade_out(self) -> None: + box = self.query_one("#box1") + self.animator.animate(box.styles, "text_opacity", value=0.0, duration=1) + + def action_widget_fade_out(self) -> None: + box = self.query_one("#box1") + self.animator.animate(box.styles, "opacity", value=0.0, duration=1) + + def key_d(self): + print(self.screen.styles.get_rules()) + print(self.screen.styles.css) + + +app = JustABox(watch_css=True, css_path="../darren/just_a_box.css") + +if __name__ == "__main__": + app.run() diff --git a/testbed/Textualize__textual/sandbox/darren/tabs.py b/testbed/Textualize__textual/sandbox/darren/tabs.py new file mode 100644 index 0000000000000000000000000000000000000000..06485038aefedb5d6e70bc5c113347415182a85e --- /dev/null +++ b/testbed/Textualize__textual/sandbox/darren/tabs.py @@ -0,0 +1,147 @@ +from dataclasses import dataclass + +from rich.console import RenderableType +from rich.padding import Padding +from rich.rule import Rule +from rich.style import Style + +from textual import events +from textual.app import App +from textual.widget import Widget +from textual.widgets.tabs import Tabs, Tab + + +class Hr(Widget): + def render(self) -> RenderableType: + return Rule() + + +class Info(Widget): + def __init__(self, text: str) -> None: + super().__init__() + self.text = text + + def render(self) -> RenderableType: + return Padding(f"{self.text}", pad=(0, 1)) + + +@dataclass +class WidgetDescription: + description: str + widget: Widget + + +class BasicApp(App): + """Sandbox application used for testing/development by Textual developers""" + + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + self.keys_to_tabs = { + "1": Tab("January", name="one"), + "2": Tab("ใซๆœˆ", name="two"), + "3": Tab("March", name="three"), + "4": Tab("April", name="four"), + "5": Tab("May", name="five"), + "6": Tab("And a really long tab!", name="six"), + } + tabs = list(self.keys_to_tabs.values()) + self.examples = [ + WidgetDescription( + "Customise the spacing between tabs, e.g. tab_padding=1", + Tabs( + tabs, + tab_padding=1, + ), + ), + WidgetDescription( + "Change the opacity of inactive tab text, e.g. inactive_text_opacity=.2", + Tabs( + tabs, + active_tab="two", + active_bar_style="#1493FF", + inactive_text_opacity=0.2, + tab_padding=2, + ), + ), + WidgetDescription( + "Change the color of the inactive portions of the underline, e.g. inactive_bar_style='blue'", + Tabs( + tabs, + active_tab="four", + inactive_bar_style="blue", + ), + ), + WidgetDescription( + "Change the color of the active portion of the underline, e.g. active_bar_style='red'", + Tabs( + tabs, + active_tab="five", + active_bar_style="red", + inactive_text_opacity=1, + ), + ), + WidgetDescription( + "Change the styling of active and inactive labels (active_tab_style, inactive_tab_style)", + Tabs( + tabs, + active_tab="one", + active_bar_style="#DA812D", + active_tab_style="bold #FFCB4D on #021720", + inactive_tab_style="italic #887AEF on #021720", + inactive_bar_style="#695CC8", + inactive_text_opacity=0.6, + ), + ), + WidgetDescription( + "Change the animation duration and function (animation_duration=1, animation_function='out_quad')", + Tabs( + tabs, + active_tab="one", + active_bar_style="#887AEF", + inactive_text_opacity=0.2, + animation_duration=1, + animation_function="out_quad", + ), + ), + WidgetDescription( + "Choose which tab to start on by name, e.g. active_tab='three'", + Tabs( + tabs, + active_tab="three", + active_bar_style="#FFCB4D", + tab_padding=3, + ), + ), + ] + + def on_load(self): + """Bind keys here.""" + self.bind("tab", "toggle_class('#sidebar', '-active')") + self.bind("a", "toggle_class('#header', '-visible')") + self.bind("c", "toggle_class('#content', '-content-visible')") + self.bind("d", "toggle_class('#footer', 'dim')") + + def on_key(self, event: events.Key) -> None: + for example in self.examples: + tab = self.keys_to_tabs.get(event.key) + if tab: + example.widget._active_tab_name = tab.name + + def on_mount(self): + """Build layout here.""" + self.mount( + info=Info( + "\n" + "โ€ข The examples below show customisation options for the [bold #1493FF]Tabs[/] widget.\n" + "โ€ข Press keys 1-6 on your keyboard to switch tabs, or click on a tab.", + ) + ) + for example in self.examples: + info = Info(example.description) + self.mount(Hr()) + self.mount(info) + self.mount(example.widget) + + +app = BasicApp(css_path="tabs.scss", watch_css=True, log_path="textual.log") +app.run() diff --git a/testbed/Textualize__textual/sandbox/darren/tabs.scss b/testbed/Textualize__textual/sandbox/darren/tabs.scss new file mode 100644 index 0000000000000000000000000000000000000000..1b5c28439999b30f427bbbb336cb9b67fcc4f69c --- /dev/null +++ b/testbed/Textualize__textual/sandbox/darren/tabs.scss @@ -0,0 +1,9 @@ +$background: #021720; + +App > View { + background: $background; +} + +#info { + height: 4; +} diff --git a/testbed/Textualize__textual/sandbox/darren/text_align.py b/testbed/Textualize__textual/sandbox/darren/text_align.py new file mode 100644 index 0000000000000000000000000000000000000000..ccc55696a191b23a99abc7cad328a18e94ce7623 --- /dev/null +++ b/testbed/Textualize__textual/sandbox/darren/text_align.py @@ -0,0 +1,33 @@ +from __future__ import annotations + +from textual.app import App, ComposeResult +from textual.widgets import Static + +TEXT = ( + "I must not fear. Fear is the mind-killer. Fear is the little-death that " + "brings total obliteration. I will face my fear. I will permit it to pass over " + "me and through me. And when it has gone past, I will turn the inner eye to " + "see its path. Where the fear has gone there will be nothing. Only I will " + "remain. " +) + + +class TextAlign(App): + def compose(self) -> ComposeResult: + left = Static("[b]Left aligned[/]\n" + TEXT, id="one") + yield left + + right = Static("[b]Center aligned[/]\n" + TEXT, id="two") + yield right + + center = Static("[b]Right aligned[/]\n" + TEXT, id="three") + yield center + + full = Static("[b]Fully justified[/]\n" + TEXT, id="four") + yield full + + +app = TextAlign(css_path="text_align.scss", watch_css=True) + +if __name__ == "__main__": + app.run() diff --git a/testbed/Textualize__textual/sandbox/darren/text_align.scss b/testbed/Textualize__textual/sandbox/darren/text_align.scss new file mode 100644 index 0000000000000000000000000000000000000000..c594254d6b16790e3cc65951a93cf3b395b000c2 --- /dev/null +++ b/testbed/Textualize__textual/sandbox/darren/text_align.scss @@ -0,0 +1,24 @@ +#one { + text-align: left; + background: lightblue; + +} + +#two { + text-align: center; + background: indianred; +} + +#three { + text-align: right; + background: palegreen; +} + +#four { + text-align: justify; + background: palevioletred; +} + +Static { + padding: 1; +} diff --git a/testbed/Textualize__textual/sandbox/will/add_remove.py b/testbed/Textualize__textual/sandbox/will/add_remove.py new file mode 100644 index 0000000000000000000000000000000000000000..f3777b5558cf940dd59b1ed5249380dc507b0aa4 --- /dev/null +++ b/testbed/Textualize__textual/sandbox/will/add_remove.py @@ -0,0 +1,71 @@ +import random + +from textual.containers import Horizontal, Vertical +from textual.app import App, ComposeResult +from textual.widgets import Button, Static + + +class Thing(Static): + def on_show(self) -> None: + self.scroll_visible() + + +class AddRemoveApp(App): + DEFAULT_CSS = """ + #buttons { + dock: top; + height: auto; + } + #buttons Button { + width: 1fr; + } + #items { + height: 100%; + overflow-y: scroll; + } + Thing { + height: 5; + background: $panel; + border: tall $primary; + margin: 1 1; + content-align: center middle; + } + """ + + def on_mount(self) -> None: + self.count = 0 + + def compose(self) -> ComposeResult: + yield Vertical( + Horizontal( + Button("Add", variant="success", id="add"), + Button("Remove", variant="error", id="remove"), + Button("Remove random", variant="warning", id="remove_random"), + id="buttons", + ), + Vertical(id="items"), + ) + + def on_button_pressed(self, event: Button.Pressed) -> None: + if event.button.id == "add": + self.count += 1 + self.query("#items").first().mount( + Thing(f"Thing {self.count}", id=f"thing{self.count}") + ) + elif event.button.id == "remove": + things = self.query("#items Thing") + if things: + things.last().remove() + + elif event.button.id == "remove_random": + things = self.query("#items Thing") + if things: + random.choice(things).remove() + + self.app.bell() + + +app = AddRemoveApp() + +if __name__ == "__main__": + app.run() diff --git a/testbed/Textualize__textual/sandbox/will/align.css b/testbed/Textualize__textual/sandbox/will/align.css new file mode 100644 index 0000000000000000000000000000000000000000..ec40f834619974dae4b518c6b52ce28c7c4797b2 --- /dev/null +++ b/testbed/Textualize__textual/sandbox/will/align.css @@ -0,0 +1,14 @@ +Screen { + align: center middle; +} + +Label { + + width: 20; + height: 5; + background: blue; + color: white; + border: tall white; + margin: 1; + content-align: center middle; +} diff --git a/testbed/Textualize__textual/sandbox/will/align.py b/testbed/Textualize__textual/sandbox/will/align.py new file mode 100644 index 0000000000000000000000000000000000000000..864f6eb95dea2e4fbabe2d1c65084cdf6d52d953 --- /dev/null +++ b/testbed/Textualize__textual/sandbox/will/align.py @@ -0,0 +1,19 @@ +from textual.app import App, ComposeResult +from textual.widgets import Static + + +class Label(Static): + pass + + +class AlignApp(App): + CSS_PATH = "align.css" + + def compose(self) -> ComposeResult: + yield Label("Hello") + yield Label("World!") + + +if __name__ == "__main__": + app = AlignApp() + app.run() diff --git a/testbed/Textualize__textual/sandbox/will/basic.css b/testbed/Textualize__textual/sandbox/will/basic.css new file mode 100644 index 0000000000000000000000000000000000000000..e113d23fc7c598c27bc22f31fc5bbeb212c17173 --- /dev/null +++ b/testbed/Textualize__textual/sandbox/will/basic.css @@ -0,0 +1,265 @@ +/* CSS file for basic.py */ + + + + * { + transition: color 300ms linear, background 300ms linear; +} + +Tweet.tall { + height: 24; +} + +*:hover { + /* tint: 30% red; + /* outline: heavy red; */ +} + +App > Screen { + + color: $text; + layers: base sidebar; + layout: vertical; + overflow: hidden; + +} + +#tree-container { + background: $panel; + overflow-y: auto; + height: 20; + margin: 1 2; + + padding: 1 2; +} + +DirectoryTree { + padding: 0 1; + height: auto; + +} + + +#table-container { + background: $panel; + height: auto; + margin: 1 2; +} + +DataTable { + /*border:heavy red;*/ + /* tint: 10% green; */ + /* text-opacity: 50%; */ + + + margin: 1 2; + height: 24; +} + +#sidebar { + background: $panel; + color: $text; + dock: left; + width: 30; + margin-bottom: 1; + offset-x: -100%; + + transition: offset 500ms in_out_cubic; + layer: sidebar; +} + +#sidebar.-active { + offset-x: 0; +} + +#sidebar .title { + height: 1; + background: $primary-background-darken-1; + color: $text; + border-right: wide $background; + content-align: center middle; +} + +#sidebar .user { + height: 8; + background: $panel-darken-1; + color: $text; + border-right: wide $background; + content-align: center middle; +} + +#sidebar .content { + background: $panel-darken-2; + color: $text; + border-right: wide $background; + content-align: center middle; +} + + + + +Tweet { + height:12; + width: 100%; + margin: 0 2; + + margin:0 2; + background: $panel; + color: $text; + layout: vertical; + /* border: outer $primary; */ + padding: 1; + border: wide $panel; + + /* scrollbar-gutter: stable; */ + + box-sizing: border-box; + +} + + +.scrollable { + overflow-x: auto; + overflow-y: scroll; + padding: 0 2; + margin: 1 2; + height: 24; + + layout: vertical; +} + +.code { + height: auto; +} + + +TweetHeader { + height:1; + background: $accent; + color: $text; +} + +TweetBody { + width: 100%; + background: $panel; + color: $text; + height: auto; + padding: 0 1 0 0; +} + +Tweet.scroll-horizontal { + + overflow-x: auto; +} + +Tweet.scroll-horizontal TweetBody { + width: 350; + +} + +.button { + background: $accent; + color: $text; + width:20; + height: 3; + /* border-top: hidden $accent-darken-3; */ + border: tall $accent-darken-2; + /* border-left: tall $accent-darken-1; */ + + + /* padding: 1 0 0 0 ; */ + + transition: background 400ms in_out_cubic, color 400ms in_out_cubic; + +} + +.button:hover { + background: $accent-lighten-1; + color: $text; + width: 20; + height: 3; + border: tall $accent-darken-1; + /* border-left: tall $accent-darken-3; */ + + + + +} + +#footer { + color: $text; + background: $accent; + height: 1; + + content-align: center middle; + dock:bottom; +} + + +#sidebar .content { + layout: vertical; +} + +OptionItem { + height: 3; + background: $panel; + border-right: wide $background; + border-left: blank; + content-align: center middle; +} + +OptionItem:hover { + height: 3; + color: $text; + background: $primary-darken-1; + /* border-top: hkey $accent2-darken-3; + border-bottom: hkey $accent2-darken-3; */ + text-style: bold; + border-left: outer $secondary-darken-2; +} + +Error { + width: 100%; + height:3; + background: $error; + color: $text; + border-top: tall $error-darken-2; + border-bottom: tall $error-darken-2; + + padding: 0; + text-style: bold; + content-align: center middle; +} + +Warning { + width: 100%; + height:3; + background: $warning; + color: $text; + border-top: tall $warning-darken-2; + border-bottom: tall $warning-darken-2; + + text-style: bold; + content-align: center middle; +} + +Success { + width: 100%; + + height:auto; + box-sizing: border-box; + background: $success; + color: $text; + + border-top: hkey $success-darken-2; + border-bottom: hkey $success-darken-2; + + text-style: bold ; + + content-align: center middle; +} + + +.horizontal { + layout: horizontal +} diff --git a/testbed/Textualize__textual/sandbox/will/basic.py b/testbed/Textualize__textual/sandbox/will/basic.py new file mode 100644 index 0000000000000000000000000000000000000000..d50509b9d2c72b2d4d71d6f604e0f2d1228705cd --- /dev/null +++ b/testbed/Textualize__textual/sandbox/will/basic.py @@ -0,0 +1,243 @@ +from rich.console import RenderableType + +from rich.syntax import Syntax +from rich.text import Text + +from textual.app import App, ComposeResult +from textual.reactive import Reactive +from textual.widget import Widget +from textual.widgets import Static, DataTable, DirectoryTree, Header, Footer +from textual.containers import Container, Vertical + +CODE = ''' +from __future__ import annotations + +from typing import Iterable, TypeVar + +T = TypeVar("T") + + +def loop_first(values: Iterable[T]) -> Iterable[tuple[bool, T]]: + """Iterate and generate a tuple with a flag for first value.""" + iter_values = iter(values) + try: + value = next(iter_values) + except StopIteration: + return + yield True, value + for value in iter_values: + yield False, value + + +def loop_last(values: Iterable[T]) -> Iterable[tuple[bool, T]]: + """Iterate and generate a tuple with a flag for last value.""" + iter_values = iter(values) + try: + previous_value = next(iter_values) + except StopIteration: + return + for value in iter_values: + yield False, previous_value + previous_value = value + yield True, previous_value + + +def loop_first_last(values: Iterable[T]) -> Iterable[tuple[bool, bool, T]]: + """Iterate and generate a tuple with a flag for first and last value.""" + iter_values = iter(values) + try: + previous_value = next(iter_values) + except StopIteration: + return + first = True + for value in iter_values: + yield first, False, previous_value + first = False + previous_value = value + yield first, True, previous_value +''' + + +lorem_short = """Lorem ipsum dolor sit amet, consectetur adipiscing elit. In velit liber a a a, volutpat nec hendrerit at, faucibus in odio. Aliquam hendrerit nibh sed quam volutpat maximus. Nullam suscipit convallis lorem quis sodales. In tristique lobortis ante et dictum. Ut at finibus ipsum.""" +lorem = ( + lorem_short + + """ In urna dolor, placerat et mi facilisis, congue sollicitudin massa. Phasellus felis turpis, cursus eu lectus et, porttitor malesuada augue. Sed feugiat volutpat velit, sollicitudin fringilla velit bibendum faucibus. Lorem ipsum dolor sit amet, consectetur adipiscing elit. In velit libero, volutpat nec hendrerit at, faucibus in odio. Aliquam hendrerit nibh sed quam volutpat maximus. Nullam suscipit convallis lorem quis sodales. In tristique lobortis ante et dictum. Ut at finibus ipsum. In urna dolor, placerat et mi facilisis, congue sollicitudin massa. Phasellus felis turpis, cursus eu lectus et, porttitor malesuada augue. Sed feugiat volutpat velit, sollicitudin fringilla velit bibendum faucibus. """ +) + +lorem_short_text = Text.from_markup(lorem_short) +lorem_long_text = Text.from_markup(lorem * 2) + + +class TweetHeader(Static): + def render(self) -> RenderableType: + return Text("Lorem Impsum", justify="center") + + +class TweetBody(Static): + short_lorem = Reactive(False) + + def render(self) -> Text: + return lorem_short_text if self.short_lorem else lorem_long_text + + +class Tweet(Vertical): + pass + + +class OptionItem(Static): + def render(self) -> Text: + return Text("Option") + + +class Error(Static): + def render(self) -> Text: + return Text("This is an error message", justify="center") + + +class Warning(Static): + def render(self) -> Text: + return Text("This is a warning message", justify="center") + + +class Success(Static): + def render(self) -> Text: + return Text("This is a success message", justify="center") + + +class BasicApp(App): + """A basic app demonstrating CSS""" + + CSS_PATH = "basic.css" + + def on_load(self): + """Bind keys here.""" + self.bind("s", "toggle_class('#sidebar', '-active')", description="Sidebar") + self.bind("d", "toggle_dark", description="Dark mode") + self.bind("q", "quit", description="Quit") + self.bind("f", "query_test", description="Query test") + + def compose(self): + yield Header() + + table = DataTable() + self.scroll_to_target = Tweet(TweetBody()) + + yield Vertical( + Tweet(TweetBody()), + Tweet( + Static( + Syntax( + CODE, + "python", + theme="ansi_dark", + line_numbers=True, + indent_guides=True, + ), + classes="code", + ), + classes="tall", + ), + Container(table, id="table-container"), + Container(DirectoryTree("~/"), id="tree-container"), + Error(), + Tweet(TweetBody(), classes="scrollbar-size-custom"), + Warning(), + Tweet(TweetBody(), classes="scroll-horizontal"), + Success(), + Tweet(TweetBody(), classes="scroll-horizontal"), + Tweet(TweetBody(), classes="scroll-horizontal"), + Tweet(TweetBody(), classes="scroll-horizontal"), + Tweet(TweetBody(), classes="scroll-horizontal"), + Tweet(TweetBody(), classes="scroll-horizontal"), + ) + yield Widget( + Static("Title", classes="title"), + Static("Content", classes="user"), + OptionItem(), + OptionItem(), + OptionItem(), + Static(classes="content"), + id="sidebar", + ) + yield Footer() + + table.add_column("Foo", width=20) + table.add_column("Bar", width=20) + table.add_column("Baz", width=20) + table.add_column("Foo", width=20) + table.add_column("Bar", width=20) + table.add_column("Baz", width=20) + table.zebra_stripes = True + for n in range(100): + table.add_row(*[f"Cell ([b]{n}[/b], {col})" for col in range(6)]) + + def on_mount(self): + self.sub_title = "Widget demo" + + async def on_key(self, event) -> None: + await self.dispatch_key(event) + + def action_toggle_dark(self): + self.dark = not self.dark + + def action_query_test(self): + query = self.query("Tweet") + self.log(query) + self.log(query.nodes) + self.log(query) + self.log(query.nodes) + + query.set_styles("outline: outer red;") + + query = query.exclude(".scroll-horizontal") + self.log(query) + self.log(query.nodes) + + # query = query.filter(".rubbish") + # self.log(query) + # self.log(query.first()) + + async def key_q(self): + await self.shutdown() + + def key_x(self): + self.panic(self.tree) + + def key_escape(self): + self.app.bell() + + def key_t(self): + # Pressing "t" toggles the content of the TweetBody widget, from a long "Lorem ipsum..." to a shorter one. + tweet_body = self.query("TweetBody").first() + tweet_body.short_lorem = not tweet_body.short_lorem + + def key_v(self): + self.get_child(id="content").scroll_to_widget(self.scroll_to_target) + + def key_space(self): + self.bell() + + +app = BasicApp() + +if __name__ == "__main__": + app.run() + + # from textual.geometry import Region + # from textual.color import Color + + # print(Region.intersection.cache_info()) + # print(Region.overlaps.cache_info()) + # print(Region.union.cache_info()) + # print(Region.split_vertical.cache_info()) + # print(Region.__contains__.cache_info()) + # from textual.css.scalar import Scalar + + # print(Scalar.resolve_dimension.cache_info()) + + # from rich.style import Style + # from rich.cells import cached_cell_len + + # print(Style._add.cache_info()) + + # print(cached_cell_len.cache_info()) diff --git a/testbed/Textualize__textual/sandbox/will/bindings.py b/testbed/Textualize__textual/sandbox/will/bindings.py new file mode 100644 index 0000000000000000000000000000000000000000..3cf717a0f70a22c9ffc535cb053839a84865e72d --- /dev/null +++ b/testbed/Textualize__textual/sandbox/will/bindings.py @@ -0,0 +1,54 @@ +from textual.app import App, ComposeResult +from textual.widgets import Footer, Static + + +class Focusable(Static, can_focus=True): + DEFAULT_CSS = """ + Focusable { + background: blue 20%; + height: 1fr; + padding: 1; + } + Focusable:hover { + outline: solid white; + } + Focusable:focus { + background: red 20%; + } + + """ + + +class Focusable1(Focusable): + + BINDINGS = [ + ("a", "app.bell", "Ding"), + ] + + def render(self) -> str: + return repr(self) + + +class Focusable2(Focusable): + CSS = "" + BINDINGS = [ + ("b", "app.bell", "Beep"), + ("f1", "app.quit", "QUIT"), + ] + + def render(self) -> str: + return repr(self) + + +class BindingApp(App): + BINDINGS = [("f1", "app.bell", "Bell")] + + def compose(self) -> ComposeResult: + yield Focusable1() + yield Focusable2() + yield Footer() + + +app = BindingApp() +if __name__ == "__main__": + app.run() diff --git a/testbed/Textualize__textual/sandbox/will/box.css b/testbed/Textualize__textual/sandbox/will/box.css new file mode 100644 index 0000000000000000000000000000000000000000..fcc4c3d4a4a76d90a4b628d8e60ed8de5d081407 --- /dev/null +++ b/testbed/Textualize__textual/sandbox/will/box.css @@ -0,0 +1,28 @@ +Screen { + background: white; + color:black; +} + +#box1 { + width: 10; + height: 5; + background: red 40%; + box-sizing: content-box; +} + + +#box2 { + width: 10; + height: 5; + padding: 1; + background:blue 40%; + box-sizing: content-box; +} + +#box3 { + width: 10; + height: 5; + background:green 40%; + border: heavy; + box-sizing: content-box; +} diff --git a/testbed/Textualize__textual/sandbox/will/box.py b/testbed/Textualize__textual/sandbox/will/box.py new file mode 100644 index 0000000000000000000000000000000000000000..ab99d4ee6a55b0067fc2fab0c7c48c291da9e3ff --- /dev/null +++ b/testbed/Textualize__textual/sandbox/will/box.py @@ -0,0 +1,13 @@ +from textual.app import App +from textual.widgets import Static + +class BoxApp(App): + + def compose(self): + yield Static("0123456789", id="box1") + yield Static("0123456789", id="box2") + yield Static("0123456789", id="box3") + + +app = BoxApp(css_path="box.css") +app.run() diff --git a/testbed/Textualize__textual/sandbox/will/buttons.css b/testbed/Textualize__textual/sandbox/will/buttons.css new file mode 100644 index 0000000000000000000000000000000000000000..ca01af2b5f7ea1a783fa93da42168c58e2ad87e7 --- /dev/null +++ b/testbed/Textualize__textual/sandbox/will/buttons.css @@ -0,0 +1,24 @@ + +Button { + margin: 1; + width: 100%; +} + +Vertical { + height: auto; +} + +Horizontal { + height: auto; +} + +Horizontal Button { + width: 20; + + margin: 1 2 ; +} + +#scroll { + height: 10; + +} diff --git a/testbed/Textualize__textual/sandbox/will/calculator.css b/testbed/Textualize__textual/sandbox/will/calculator.css new file mode 100644 index 0000000000000000000000000000000000000000..ce9458a104186b3e52db090e2adfc545b949af6d --- /dev/null +++ b/testbed/Textualize__textual/sandbox/will/calculator.css @@ -0,0 +1,32 @@ +Screen { + overflow: auto; +} + +#calculator { + layout: grid; + grid-size: 4; + grid-gutter: 1 2; + grid-columns: 1fr; + grid-rows: 2fr 1fr 1fr 1fr 1fr 1fr; + margin: 1 2; + min-height:25; + min-width: 26; +} + +Button { + width: 100%; + height: 100%; +} + +#numbers { + column-span: 4; + content-align: right middle; + padding: 0 1; + height: 100%; + background: $primary-lighten-2; + color: $text; +} + +#number-0 { + column-span: 2; +} diff --git a/testbed/Textualize__textual/sandbox/will/calculator.py b/testbed/Textualize__textual/sandbox/will/calculator.py new file mode 100644 index 0000000000000000000000000000000000000000..972202b1791438c89296c0acaa93cf8dbca13020 --- /dev/null +++ b/testbed/Textualize__textual/sandbox/will/calculator.py @@ -0,0 +1,144 @@ +from decimal import Decimal + +from textual.app import App, ComposeResult +from textual import events +from textual.containers import Container +from textual.reactive import Reactive +from textual.widgets import Button, Static + + +class CalculatorApp(App): + """A working 'desktop' calculator.""" + + numbers = Reactive.var("0") + show_ac = Reactive.var(True) + left = Reactive.var(Decimal("0")) + right = Reactive.var(Decimal("0")) + value = Reactive.var("") + operator = Reactive.var("plus") + + KEY_MAP = { + "+": "plus", + "-": "minus", + ".": "point", + "*": "multiply", + "/": "divide", + "_": "plus-minus", + "%": "percent", + "=": "equals", + } + + def watch_numbers(self, value: str) -> None: + """Called when numbers is updated.""" + # Update the Numbers widget + self.query_one("#numbers", Static).update(value) + + def compute_show_ac(self) -> bool: + """Compute switch to show AC or C button""" + return self.value in ("", "0") and self.numbers == "0" + + def watch_show_ac(self, show_ac: bool) -> None: + """Called when show_ac changes.""" + self.query_one("#c").display = not show_ac + self.query_one("#ac").display = show_ac + + def compose(self) -> ComposeResult: + """Add our buttons.""" + yield Container( + Static(id="numbers"), + Button("AC", id="ac", variant="primary"), + Button("C", id="c", variant="primary"), + Button("+/-", id="plus-minus", variant="primary"), + Button("%", id="percent", variant="primary"), + Button("รท", id="divide", variant="warning"), + Button("7", id="number-7"), + Button("8", id="number-8"), + Button("9", id="number-9"), + Button("ร—", id="multiply", variant="warning"), + Button("4", id="number-4"), + Button("5", id="number-5"), + Button("6", id="number-6"), + Button("-", id="minus", variant="warning"), + Button("1", id="number-1"), + Button("2", id="number-2"), + Button("3", id="number-3"), + Button("+", id="plus", variant="warning"), + Button("0", id="number-0"), + Button(".", id="point"), + Button("=", id="equals", variant="warning"), + id="calculator", + ) + + def on_key(self, event: events.Key) -> None: + """Called when the user presses a key.""" + + print(f"KEY {event} was pressed!") + + def press(button_id: str) -> None: + self.query_one(f"#{button_id}", Button).press() + self.set_focus(None) + + key = event.key + if key.isdecimal(): + press(f"number-{key}") + elif key == "c": + press("c") + press("ac") + elif key in self.KEY_MAP: + press(self.KEY_MAP[key]) + + def on_button_pressed(self, event: Button.Pressed) -> None: + """Called when a button is pressed.""" + + button_id = event.button.id + assert button_id is not None + + self.bell() # Terminal bell + + def do_math() -> None: + """Does the math: LEFT OPERATOR RIGHT""" + try: + if self.operator == "plus": + self.left += self.right + elif self.operator == "minus": + self.left -= self.right + elif self.operator == "divide": + self.left /= self.right + elif self.operator == "multiply": + self.left *= self.right + self.numbers = str(self.left) + self.value = "" + except Exception: + self.numbers = "Error" + + if button_id.startswith("number-"): + number = button_id.partition("-")[-1] + self.numbers = self.value = self.value.lstrip("0") + number + elif button_id == "plus-minus": + self.numbers = self.value = str(Decimal(self.value or "0") * -1) + elif button_id == "percent": + self.numbers = self.value = str(Decimal(self.value or "0") / Decimal(100)) + elif button_id == "point": + if "." not in self.value: + self.numbers = self.value = (self.value or "0") + "." + elif button_id == "ac": + self.value = "" + self.left = self.right = Decimal(0) + self.operator = "plus" + self.numbers = "0" + elif button_id == "c": + self.value = "" + self.numbers = "0" + elif button_id in ("plus", "minus", "divide", "multiply"): + self.right = Decimal(self.value or "0") + do_math() + self.operator = button_id + elif button_id == "equals": + if self.value: + self.right = Decimal(self.value) + do_math() + + +app = CalculatorApp(css_path="calculator.css") +if __name__ == "__main__": + app.run() diff --git a/testbed/Textualize__textual/sandbox/will/center.py b/testbed/Textualize__textual/sandbox/will/center.py new file mode 100644 index 0000000000000000000000000000000000000000..dddaf086c1fbd38afe9e4750a881c9b70e1f6f9c --- /dev/null +++ b/testbed/Textualize__textual/sandbox/will/center.py @@ -0,0 +1,28 @@ +from textual.app import App +from textual.widgets import Static + + +class CenterApp(App): + DEFAULT_CSS = """ + + CenterApp Screen { + layout: center; + overflow: auto auto; + } + + CenterApp Static { + border: wide $primary; + background: $panel; + width: 50; + height: 20; + margin: 1 2; + content-align: center middle; + } + + """ + + def compose(self): + yield Static("Hello World!") + + +app = CenterApp() diff --git a/testbed/Textualize__textual/sandbox/will/center2.py b/testbed/Textualize__textual/sandbox/will/center2.py new file mode 100644 index 0000000000000000000000000000000000000000..7abbefe2912e1f0b546b93f1af52b6890fbc6439 --- /dev/null +++ b/testbed/Textualize__textual/sandbox/will/center2.py @@ -0,0 +1,55 @@ +from textual.app import App +from textual.containers import Vertical, Center +from textual.widgets import Static + + +class CenterApp(App): + DEFAULT_CSS = """ + + #sidebar { + dock: left; + width: 32; + height: 100%; + border-right: vkey $primary; + } + + #bottombar { + dock: bottom; + height: 12; + width: 100%; + border-top: hkey $primary; + } + + #hello { + border: wide $primary; + width: 40; + height: 16; + margin: 2 4; + } + + #sidebar.hidden { + width: 0; + } + + Static { + background: $panel; + color: $text; + content-align: center middle; + } + + """ + + def on_mount(self) -> None: + self.bind("t", "toggle_class('#sidebar', 'hidden')") + + def compose(self): + yield Static("Sidebar", id="sidebar") + yield Vertical( + Static("Bottom bar", id="bottombar"), + Center( + Static("Hello World!", id="hello"), + ), + ) + + +app = CenterApp() diff --git a/testbed/Textualize__textual/sandbox/will/design.css b/testbed/Textualize__textual/sandbox/will/design.css new file mode 100644 index 0000000000000000000000000000000000000000..3230444324624d41f03e892e945dd1ced033169e --- /dev/null +++ b/testbed/Textualize__textual/sandbox/will/design.css @@ -0,0 +1,23 @@ +Screen { + background: $surface; +} + +Container { + height: auto; + background: $boost; + +} + +Panel { + height: auto; + background: $boost; + margin: 1 2; + +} + +Content { + background: $boost; + padding: 1 2; + margin: 1 2; + color: auto 95%; +} diff --git a/testbed/Textualize__textual/sandbox/will/design.py b/testbed/Textualize__textual/sandbox/will/design.py new file mode 100644 index 0000000000000000000000000000000000000000..56452147f86efd976c89e3f36915eeb34bffa124 --- /dev/null +++ b/testbed/Textualize__textual/sandbox/will/design.py @@ -0,0 +1,35 @@ +from textual.app import App +from textual.containers import Container +from textual.widgets import Header, Footer, Static + + +class Content(Static): + pass + + +class Panel(Container): + pass + + +class Panel2(Container): + pass + + +class DesignApp(App): + BINDINGS = [("d", "toggle_dark", "Toggle dark mode")] + + def compose(self): + yield Header() + yield Footer() + yield Container( + Content("content"), + Panel( + Content("more content"), + Content("more content"), + ), + ) + + +app = DesignApp(css_path="design.css") +if __name__ == "__main__": + app.run() diff --git a/testbed/Textualize__textual/sandbox/will/dock.py b/testbed/Textualize__textual/sandbox/will/dock.py new file mode 100644 index 0000000000000000000000000000000000000000..7f358aa0a72208319e9f6e14cb41d04dfc17a2fb --- /dev/null +++ b/testbed/Textualize__textual/sandbox/will/dock.py @@ -0,0 +1,52 @@ +from textual.app import App, ComposeResult +from textual.widgets import Static + + +class DockApp(App): + def compose(self) -> ComposeResult: + + self.screen.styles.layers = "base sidebar" + + header = Static("Header", id="header") + header.styles.dock = "top" + header.styles.height = "3" + + header.styles.background = "blue" + header.styles.color = "white" + header.styles.margin = 0 + header.styles.align_horizontal = "center" + + # header.styles.layer = "base" + + header.styles.box_sizing = "border-box" + + yield header + + footer = Static("Footer") + footer.styles.dock = "bottom" + footer.styles.height = 1 + footer.styles.background = "green" + footer.styles.color = "white" + + yield footer + + sidebar = Static("Sidebar", id="sidebar") + sidebar.styles.dock = "right" + sidebar.styles.width = 20 + sidebar.styles.height = "100%" + sidebar.styles.background = "magenta" + # sidebar.styles.layer = "sidebar" + + yield sidebar + + for n, color in zip(range(5), ["red", "green", "blue", "yellow", "magenta"]): + thing = Static(f"Thing {n}", id=f"#thing{n}") + thing.styles.border = ("heavy", "rgba(0,0,0,0.2)") + thing.styles.background = f"{color} 20%" + thing.styles.height = 15 + yield thing + + +app = DockApp() +if __name__ == "__main__": + app.run() diff --git a/testbed/Textualize__textual/sandbox/will/dock_layer.py b/testbed/Textualize__textual/sandbox/will/dock_layer.py new file mode 100644 index 0000000000000000000000000000000000000000..4d414ff388316f56b8359bcec40215bc94491819 --- /dev/null +++ b/testbed/Textualize__textual/sandbox/will/dock_layer.py @@ -0,0 +1,36 @@ +from textual.app import App, ComposeResult +from textual.widgets import Static + + +class OrderApp(App): + + CSS = """ + Screen { + layout: center; + } + Static { + border: heavy white; + } + #one { + background: red; + width:20; + height: 30; + dock:left; + } + #two { + background: blue; + width:30; + height: 20; + dock:left; + } + + """ + + def compose(self) -> ComposeResult: + yield Static("One", id="one") + yield Static("Two", id="two") + + +app = OrderApp() +if __name__ == "__main__": + app.run() diff --git a/testbed/Textualize__textual/sandbox/will/fill.css b/testbed/Textualize__textual/sandbox/will/fill.css new file mode 100644 index 0000000000000000000000000000000000000000..c48424199225fa5d1864864a995502f4c2fd5529 --- /dev/null +++ b/testbed/Textualize__textual/sandbox/will/fill.css @@ -0,0 +1,8 @@ +App Static { + border: heavy white; + background: blue; + color: white; + height: 100%; + + box-sizing: border-box; +} diff --git a/testbed/Textualize__textual/sandbox/will/fill.py b/testbed/Textualize__textual/sandbox/will/fill.py new file mode 100644 index 0000000000000000000000000000000000000000..8a5ea89915fa319aaa5c8edbb41c34b1dbef5264 --- /dev/null +++ b/testbed/Textualize__textual/sandbox/will/fill.py @@ -0,0 +1,10 @@ +from textual.app import App, ComposeResult +from textual.widgets import Static + + +class FillApp(App): + def compose(self) -> ComposeResult: + yield Static("Hello") + + +app = FillApp(css_path="fill.css") diff --git a/testbed/Textualize__textual/sandbox/will/footer.py b/testbed/Textualize__textual/sandbox/will/footer.py new file mode 100644 index 0000000000000000000000000000000000000000..b2faa6a498371cf38c0825cd5c4697876c9b49eb --- /dev/null +++ b/testbed/Textualize__textual/sandbox/will/footer.py @@ -0,0 +1,17 @@ +from textual.app import App +from textual.widgets import Header, Footer + + +class FooterApp(App): + def on_mount(self): + self.sub_title = "Header and footer example" + self.bind("b", "app.bell", description="Play the Bell") + self.bind("d", "dark", description="Toggle dark") + self.bind("f1", "app.bell", description="Hello World") + + def action_dark(self): + self.dark = not self.dark + + def compose(self): + yield Header() + yield Footer() diff --git a/testbed/Textualize__textual/sandbox/will/input.py b/testbed/Textualize__textual/sandbox/will/input.py new file mode 100644 index 0000000000000000000000000000000000000000..c74972ac9eb63d34e46fc01c5708b2c463d16905 --- /dev/null +++ b/testbed/Textualize__textual/sandbox/will/input.py @@ -0,0 +1,19 @@ +from textual.app import App +from textual.widgets import Input + + +class InputApp(App): + + CSS = """ + Input { + width: 20; + } + """ + + def compose(self): + yield Input("ไฝ 123456789็•Œ", placeholder="Type something") + + +if __name__ == "__main__": + app = InputApp() + app.run() diff --git a/testbed/Textualize__textual/sandbox/will/just_a_box.css b/testbed/Textualize__textual/sandbox/will/just_a_box.css new file mode 100644 index 0000000000000000000000000000000000000000..617fbaf5988a86ac0814211a4ca52c4d98f285b0 --- /dev/null +++ b/testbed/Textualize__textual/sandbox/will/just_a_box.css @@ -0,0 +1,24 @@ +Screen { + background: lightcoral; +} + +#left_pane { + background: red; + width: 30; + height: auto; +} + +#middle_pane { + background: green; + width: 140; +} + +#right_pane { + background: blue; + width: 30; +} + +.box { + height: 5; + width: 15; +} diff --git a/testbed/Textualize__textual/sandbox/will/just_a_box.py b/testbed/Textualize__textual/sandbox/will/just_a_box.py new file mode 100644 index 0000000000000000000000000000000000000000..df19e259aa9570e506b5d16c9e2d0f65dd47d029 --- /dev/null +++ b/testbed/Textualize__textual/sandbox/will/just_a_box.py @@ -0,0 +1,43 @@ +from __future__ import annotations + +from rich.console import RenderableType +from rich.panel import Panel + +from textual import events +from textual.app import App, ComposeResult +from textual.containers import Container, Horizontal, Vertical +from textual.widget import Widget + + +class Box(Widget, can_focus=True): + DEFAULT_CSS = "#box {background: blue;}" + + def render(self) -> RenderableType: + return Panel("Box") + + +class JustABox(App): + def compose(self) -> ComposeResult: + # yield Container(Box(classes="box")) + yield Horizontal( + Vertical( + Box(id="box1", classes="box"), + Box(id="box2", classes="box"), + id="left_pane", + ), + id="horizontal", + ) + + def key_p(self): + for k, v in self.app.stylesheet.source.items(): + print(k) + print(self.query_one("#horizontal").styles.layout) + + async def on_key(self, event: events.Key) -> None: + await self.dispatch_key(event) + + +app = JustABox(css_path="just_a_box.css", watch_css=True) + +if __name__ == "__main__": + app.run() diff --git a/testbed/Textualize__textual/sandbox/will/layer_order.py b/testbed/Textualize__textual/sandbox/will/layer_order.py new file mode 100644 index 0000000000000000000000000000000000000000..d5a5a8fdef2b3fd66bba8efc964ad7706d67a860 --- /dev/null +++ b/testbed/Textualize__textual/sandbox/will/layer_order.py @@ -0,0 +1,39 @@ +from textual.app import App, ComposeResult +from textual.widgets import Static + + +class OrderApp(App): + + CSS = """ + Screen { + layout: center; + } + Static { + border: heavy white; + } + #one { + background: red; + width:20; + height: 30; + } + #two { + background: blue; + width:30; + height: 20; + } + #three { + background: green; + width:40; + height:10 + } + """ + + def compose(self) -> ComposeResult: + yield Static("One", id="one") + yield Static("Two", id="two") + yield Static("Three", id="three") + + +app = OrderApp() +if __name__ == "__main__": + app.run() diff --git a/testbed/Textualize__textual/sandbox/will/offset.css b/testbed/Textualize__textual/sandbox/will/offset.css new file mode 100644 index 0000000000000000000000000000000000000000..349f23a5e89659d1a9f537cfcb37c27ec336c820 --- /dev/null +++ b/testbed/Textualize__textual/sandbox/will/offset.css @@ -0,0 +1,21 @@ +Screen { + align: center middle; +} + +#parent { + width: 32; + height: 8; + background: $panel; +} + +#tag { + color: $text; + background: $success; + padding: 2 4; + width: auto; + offset: -8 -4; +} + +#child { + background: red; +} diff --git a/testbed/Textualize__textual/sandbox/will/offset.py b/testbed/Textualize__textual/sandbox/will/offset.py new file mode 100644 index 0000000000000000000000000000000000000000..3fbd7a57c4779ce66e5d0d8af8ae50220a663b92 --- /dev/null +++ b/testbed/Textualize__textual/sandbox/will/offset.py @@ -0,0 +1,14 @@ +from textual.app import App, ComposeResult +from textual.containers import Vertical +from textual.widgets import Static + + +class OffsetExample(App): + def compose(self) -> ComposeResult: + yield Vertical(Static("Child", id="child"), id="parent") + yield Static("Tag", id="tag") + + +app = OffsetExample(css_path="offset.css") +if __name__ == "__main__": + app.run() diff --git a/testbed/Textualize__textual/sandbox/will/order.py b/testbed/Textualize__textual/sandbox/will/order.py new file mode 100644 index 0000000000000000000000000000000000000000..639baa126d0cbdd2aa33da6015d5b501be04708c --- /dev/null +++ b/testbed/Textualize__textual/sandbox/will/order.py @@ -0,0 +1,27 @@ +import asyncio +from textual.app import App +from textual import events +from textual.widget import Widget + + +class OrderWidget(Widget, can_focus=True): + def on_key(self, event) -> None: + self.log("PRESS", event.key) + + +class OrderApp(App): + def compose(self): + yield OrderWidget() + + async def on_mount(self): + async def send_keys(): + self.query_one(OrderWidget).focus() + chars = ["tab", "enter", "h", "e", "l", "l", "o"] + for char in chars: + self.log("SENDING", char) + await self.post_message(events.Key(self, key=char)) + + self.set_timer(1, lambda: asyncio.create_task(send_keys())) + + +app = OrderApp() diff --git a/testbed/Textualize__textual/sandbox/will/screens.py b/testbed/Textualize__textual/sandbox/will/screens.py new file mode 100644 index 0000000000000000000000000000000000000000..3a9f34dc22e59aa28bf6f7fdeac942fa4cc4e6b6 --- /dev/null +++ b/testbed/Textualize__textual/sandbox/will/screens.py @@ -0,0 +1,66 @@ +from textual.app import App, Screen, ComposeResult +from textual.widgets import Static, Footer, Pretty + + +class ModalScreen(Screen): + def compose(self) -> ComposeResult: + yield Pretty(self.app.screen_stack) + yield Footer() + + def on_screen_resume(self): + self.query_one(Pretty).update(self.app.screen_stack) + + +class NewScreen(Screen): + def compose(self): + yield Pretty(self.app.screen_stack) + yield Footer() + + def on_screen_resume(self): + self.query_one(Pretty).update(self.app.screen_stack) + + +class ScreenApp(App): + DEFAULT_CSS = """ + ScreenApp Screen { + background: #111144; + color: white; + + + } + ScreenApp ModalScreen { + background: #114411; + color: white; + + + } + ScreenApp Pretty { + height: auto; + content-align: center middle; + background: white 20%; + } + """ + + def compose(self) -> ComposeResult: + yield Static("On Screen 1") + yield Footer() + + def on_mount(self) -> None: + + self.install_screen(NewScreen("Screen1"), name="1") + self.install_screen(NewScreen("Screen2"), name="2") + self.install_screen(NewScreen("Screen3"), name="3") + + self.bind("1", "switch_screen('1')", description="Screen 1") + self.bind("2", "switch_screen('2')", description="Screen 2") + self.bind("3", "switch_screen('3')", description="Screen 3") + self.bind("s", "modal_screen", description="add screen") + self.bind("escape", "back", description="Go back") + + def action_modal_screen(self) -> None: + self.push_screen(ModalScreen()) + + +app = ScreenApp() +if __name__ == "__main__": + app.run() diff --git a/testbed/Textualize__textual/sandbox/will/scrolly.py b/testbed/Textualize__textual/sandbox/will/scrolly.py new file mode 100644 index 0000000000000000000000000000000000000000..d97c1ea4f4e0cbe5432a5e1f04690233e99e3aed --- /dev/null +++ b/testbed/Textualize__textual/sandbox/will/scrolly.py @@ -0,0 +1,32 @@ +from rich.text import Text +from textual.app import App, ComposeResult +from textual.widgets import Static + +text = "\n".join("FOO BAR bazz etc sdfsdf " * 20 for n in range(1000)) + + +class Content(Static): + DEFAULT_CSS = """ + Content { + width: auto; + } + """ + + def render(self): + return Text(text, no_wrap=False) + + +class ScrollApp(App): + CSS = """ + Screen { + overflow: auto; + } + """ + + def compose(self) -> ComposeResult: + yield Content() + + +app = ScrollApp() +if __name__ == "__main__": + app.run() diff --git a/testbed/Textualize__textual/sandbox/will/spacing.css b/testbed/Textualize__textual/sandbox/will/spacing.css new file mode 100644 index 0000000000000000000000000000000000000000..5e1aec208a17e463c3dd0ceb550d8a74d264dedb --- /dev/null +++ b/testbed/Textualize__textual/sandbox/will/spacing.css @@ -0,0 +1,13 @@ +Screen { + + overflow: auto; + +} + +Static { + background: blue 20%; + height: 100%; + margin: 2 4; + min-width: 80; + min-height: 40; +} diff --git a/testbed/Textualize__textual/sandbox/will/spacing.py b/testbed/Textualize__textual/sandbox/will/spacing.py new file mode 100644 index 0000000000000000000000000000000000000000..92e195eb14a74a94cc942c272f352e77b35c5d8c --- /dev/null +++ b/testbed/Textualize__textual/sandbox/will/spacing.py @@ -0,0 +1,15 @@ +from textual.app import App +from textual.widgets import Static + + +class Clickable(Static): + def on_click(self): + self.app.bell() + + +class SpacingApp(App): + def compose(self): + yield Static(id="2332") + + +app = SpacingApp(css_path="spacing.css") diff --git a/testbed/Textualize__textual/sandbox/will/table.py b/testbed/Textualize__textual/sandbox/will/table.py new file mode 100644 index 0000000000000000000000000000000000000000..7458d68dd9d52cb097744c6c9c54a45edac50296 --- /dev/null +++ b/testbed/Textualize__textual/sandbox/will/table.py @@ -0,0 +1,85 @@ +from textual.app import App, ComposeResult +from textual.widgets import DataTable + +from rich.syntax import Syntax +from rich.table import Table + +CODE = '''\ +def loop_first_last(values: Iterable[T]) -> Iterable[tuple[bool, bool, T]]: + """Iterate and generate a tuple with a flag for first and last value.""" + iter_values = iter(values) + try: + previous_value = next(iter_values) + except StopIteration: + return + first = True + for value in iter_values: + yield first, False, previous_value + first = False + previous_value = value + yield first, True, previous_value''' + +test_table = Table(title="Star Wars Movies") + +test_table.add_column("Released", style="cyan", no_wrap=True) +test_table.add_column("Title", style="magenta") +test_table.add_column("Box Office", justify="right", style="green") + +test_table.add_row("Dec 20, 2019", "Star Wars: The Rise of Skywalker", "$952,110,690") +test_table.add_row("May 25, 2018", "Solo: A Star Wars Story", "$393,151,347") +test_table.add_row( + "Dec 15, 2017", "Star Wars Ep. V111: The Last Jedi", "$1,332,539,889" +) +test_table.add_row("Dec 16, 2016", "Rogue One: A Star Wars Story", "$1,332,439,889") + + +class TableApp(App): + def compose(self) -> ComposeResult: + table = self.table = DataTable(id="data") + yield table + + table.add_column("Foo") + table.add_column("Bar") + table.add_column("Baz") + table.add_column("Foo") + table.add_column("Bar") + table.add_column("Baz") + + for n in range(200): + height = 1 + row = [f"row [b]{n}[/b] col [i]{c}[/i]" for c in range(6)] + if n == 10: + row[1] = Syntax( + CODE, + "python", + theme="ansi_dark", + line_numbers=True, + indent_guides=True, + ) + height = 13 + + if n == 30: + row[1] = test_table + height = 13 + table.add_row(*row, height=height) + + table.focus() + + def on_mount(self): + self.bind("d", "toggle_dark") + self.bind("z", "toggle_zebra") + self.bind("x", "exit") + + def action_toggle_dark(self) -> None: + self.app.dark = not self.app.dark + + def action_toggle_zebra(self) -> None: + self.table.zebra_stripes = not self.table.zebra_stripes + + def action_exit(self) -> None: + pass + + +app = TableApp() +if __name__ == "__main__": + print(app.run()) diff --git a/testbed/Textualize__textual/sandbox/will/table_layout.css b/testbed/Textualize__textual/sandbox/will/table_layout.css new file mode 100644 index 0000000000000000000000000000000000000000..2b79bcbadcd61e45950e29867a47a43c65fba6ae --- /dev/null +++ b/testbed/Textualize__textual/sandbox/will/table_layout.css @@ -0,0 +1,23 @@ +Screen { + layout: grid; + grid-columns: 2fr 1fr 1fr; + grid-rows: 1fr 1fr; + grid-gutter: 1 2; +} + +Static { +border: solid white; +background: blue 20%; +height: 100%; +width: 100%; +} + +#foo { + row-span: 2; +} + +#last { + column-span: 3; + margin: 1; + +} diff --git a/testbed/Textualize__textual/sandbox/will/table_layout.py b/testbed/Textualize__textual/sandbox/will/table_layout.py new file mode 100644 index 0000000000000000000000000000000000000000..709217c3851c65d9f372d9f73a89a8f151c6f843 --- /dev/null +++ b/testbed/Textualize__textual/sandbox/will/table_layout.py @@ -0,0 +1,19 @@ +from textual.app import App + +from textual.widgets import Static + + +class TableLayoutApp(App): + def compose(self): + yield Static("foo", id="foo") + yield Static("bar") + yield Static("baz") + + yield Static("foo") + yield Static("bar") + yield Static("baz", id="last") + + +app = TableLayoutApp(css_path="table_layout.css") +if __name__ == "__main__": + app.run() diff --git a/testbed/Textualize__textual/sandbox/will/tree.py b/testbed/Textualize__textual/sandbox/will/tree.py new file mode 100644 index 0000000000000000000000000000000000000000..8f5a9c46be11d034789e81f225f1e2a1c72d7f26 --- /dev/null +++ b/testbed/Textualize__textual/sandbox/will/tree.py @@ -0,0 +1,16 @@ +from textual.app import App + +from textual.containers import Container +from textual.widgets import DirectoryTree + + +class TreeApp(App): + def compose(self): + tree = DirectoryTree("~/projects") + yield Container(tree) + tree.focus() + + +app = TreeApp() +if __name__ == "__main__": + app.run() diff --git a/testbed/Textualize__textual/src/textual/cli/cli.py b/testbed/Textualize__textual/src/textual/cli/cli.py new file mode 100644 index 0000000000000000000000000000000000000000..13e1674115c1c9ae4880b48913de109b57e6a53a --- /dev/null +++ b/testbed/Textualize__textual/src/textual/cli/cli.py @@ -0,0 +1,113 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING + +import click +from importlib_metadata import version +from textual.devtools.server import _run_devtools +from textual._import_app import import_app, AppFail + +if TYPE_CHECKING: + from textual.app import App + + +@click.group() +@click.version_option(version("textual")) +def run(): + pass + + +@run.command(help="Run the Textual Devtools console.") +@click.option("-v", "verbose", help="Enable verbose logs.", is_flag=True) +@click.option("-x", "--exclude", "exclude", help="Exclude log group(s)", multiple=True) +def console(verbose: bool, exclude: list[str]) -> None: + from rich.console import Console + + console = Console() + console.clear() + console.show_cursor(False) + try: + _run_devtools(verbose=verbose, exclude=exclude) + finally: + console.show_cursor(True) + + +@run.command( + "run", + context_settings={ + "ignore_unknown_options": True, + }, +) +@click.argument("import_name", metavar="FILE or FILE:APP") +@click.option("--dev", "dev", help="Enable development mode", is_flag=True) +@click.option("--press", "press", help="Comma separated keys to simulate press") +def run_app(import_name: str, dev: bool, press: str) -> None: + """Run a Textual app. + + The code to run may be given as a path (ending with .py) or as a Python + import, which will load the code and run an app called "app". You may optionally + add a colon plus the class or class instance you want to run. + + Here are some examples: + + textual run foo.py + + textual run foo.py:MyApp + + textual run module.foo + + textual run module.foo:MyApp + + If you are running a file and want to pass command line arguments, wrap the filename and arguments + in quotes: + + textual run "foo.py arg --option" + + """ + + import os + import sys + + from textual.features import parse_features + + features = set(parse_features(os.environ.get("TEXTUAL", ""))) + if dev: + features.add("debug") + features.add("devtools") + + os.environ["TEXTUAL"] = ",".join(sorted(features)) + try: + app = import_app(import_name) + except AppFail as error: + from rich.console import Console + + console = Console(stderr=True) + console.print(str(error)) + sys.exit(1) + + press_keys = press.split(",") if press else None + result = app.run(press=press_keys) + + if result is not None: + from rich.console import Console + from rich.pretty import Pretty + + console = Console() + console.print("[b]The app returned:") + console.print(Pretty(result)) + + +@run.command("borders") +def borders(): + """Explore the border styles available in Textual.""" + from textual.cli.previews import borders + + borders.app.run() + + +@run.command("easing") +def easing(): + """Explore the animation easing functions available in Textual.""" + from textual.cli.previews import easing + + easing.app.run() diff --git a/testbed/Textualize__textual/src/textual/css/_error_tools.py b/testbed/Textualize__textual/src/textual/css/_error_tools.py new file mode 100644 index 0000000000000000000000000000000000000000..b22d9caa018aea60c67b700f5e21d7b356427576 --- /dev/null +++ b/testbed/Textualize__textual/src/textual/css/_error_tools.py @@ -0,0 +1,30 @@ +from __future__ import annotations + +from typing import Iterable + + +def friendly_list( + words: Iterable[str], joiner: str = "or", omit_empty: bool = True +) -> str: + """Generate a list of words as readable prose. + + >>> friendly_list(["foo", "bar", "baz"]) + "'foo', 'bar', or 'baz'" + + Args: + words (Iterable[str]): A list of words. + joiner (str, optional): The last joiner word. Defaults to "or". + + Returns: + str: List as prose. + """ + words = [ + repr(word) for word in sorted(words, key=str.lower) if word or not omit_empty + ] + if len(words) == 1: + return words[0] + elif len(words) == 2: + word1, word2 = words + return f"{word1} {joiner} {word2}" + else: + return f'{", ".join(words[:-1])}, {joiner} {words[-1]}' diff --git a/testbed/Textualize__textual/src/textual/css/_help_renderables.py b/testbed/Textualize__textual/src/textual/css/_help_renderables.py new file mode 100644 index 0000000000000000000000000000000000000000..ca2307f221f350d174d7a94f713885c800dc601e --- /dev/null +++ b/testbed/Textualize__textual/src/textual/css/_help_renderables.py @@ -0,0 +1,92 @@ +from __future__ import annotations + +from typing import Iterable + +import rich.repr +from rich.console import Console, ConsoleOptions, RenderResult +from rich.highlighter import ReprHighlighter +from rich.markup import render +from rich.text import Text +from rich.tree import Tree + +_highlighter = ReprHighlighter() + + +def _markup_and_highlight(text: str) -> Text: + """Highlight and render markup in a string of text, returning + a styled Text object. + + Args: + text (str): The text to highlight and markup. + + Returns: + Text: The Text, with highlighting and markup applied. + """ + return _highlighter(render(text)) + + +class Example: + """Renderable for an example, which can appear below bullet points in + the help text. + + Attributes: + markup (str): The markup to display for this example + """ + + def __init__(self, markup: str) -> None: + self.markup = markup + + def __rich_console__( + self, console: Console, options: ConsoleOptions + ) -> RenderResult: + yield _markup_and_highlight(f" [dim]e.g. [/][i]{self.markup}[/]") + + +@rich.repr.auto +class Bullet: + """Renderable for a single 'bullet point' containing information and optionally some examples + pertaining to that information. + + Attributes: + markup (str): The markup to display + examples (Iterable[Example] | None): An optional list of examples + to display below this bullet. + """ + + def __init__(self, markup: str, examples: Iterable[Example] | None = None) -> None: + self.markup = markup + self.examples = [] if examples is None else examples + + def __rich_console__( + self, console: Console, options: ConsoleOptions + ) -> RenderResult: + yield _markup_and_highlight(self.markup) + yield from self.examples + + +@rich.repr.auto +class HelpText: + """Renderable for help text - the user is shown this when they + encounter a style-related error (e.g. setting a style property to an invalid + value). + + Attributes: + summary (str): A succinct summary of the issue. + bullets (Iterable[Bullet] | None): Bullet points which provide additional + context around the issue. These are rendered below the summary. Defaults to None. + """ + + def __init__(self, summary: str, *, bullets: Iterable[Bullet] = None) -> None: + self.summary = summary + self.bullets = bullets or [] + + def __str__(self) -> str: + return self.summary + + def __rich_console__( + self, console: Console, options: ConsoleOptions + ) -> RenderResult: + tree = Tree(_markup_and_highlight(f"[b blue]{self.summary}"), guide_style="dim") + for bullet in self.bullets: + tree.add(bullet) + yield tree diff --git a/testbed/Textualize__textual/src/textual/css/_help_text.py b/testbed/Textualize__textual/src/textual/css/_help_text.py new file mode 100644 index 0000000000000000000000000000000000000000..e148426edb72c30d339d94e9969c31d76800752b --- /dev/null +++ b/testbed/Textualize__textual/src/textual/css/_help_text.py @@ -0,0 +1,765 @@ +from __future__ import annotations + +import sys +from dataclasses import dataclass +from typing import Iterable + +from textual.color import ColorParseError +from textual.css._help_renderables import Example, Bullet, HelpText +from textual.css.constants import ( + VALID_BORDER, + VALID_LAYOUT, + VALID_ALIGN_HORIZONTAL, + VALID_ALIGN_VERTICAL, + VALID_STYLE_FLAGS, + VALID_TEXT_ALIGN, +) + +if sys.version_info >= (3, 8): + from typing import Literal, Iterable, Sequence +else: + from typing_extensions import Literal + +from textual.css._error_tools import friendly_list +from textual.css.scalar import SYMBOL_UNIT + +StylingContext = Literal["inline", "css"] +"""The type of styling the user was using when the error was encountered. +Used to give help text specific to the context i.e. we give CSS help if the +user hit an issue with their CSS, and Python help text when the user has an +issue with inline styles.""" + + +@dataclass +class ContextSpecificBullets: + """ + Args: + inline (Iterable[Bullet]): Information only relevant to users who are using inline styling. + css (Iterable[Bullet]): Information only relevant to users who are using CSS. + """ + + inline: Sequence[Bullet] + css: Sequence[Bullet] + + def get_by_context(self, context: StylingContext) -> list[Bullet]: + """Get the information associated with the given context + + Args: + context (StylingContext | None): The context to retrieve info for. + """ + if context == "inline": + return list(self.inline) + else: + return list(self.css) + + +def _python_name(property_name: str) -> str: + """Convert a CSS property name to the corresponding Python attribute name + + Args: + property_name (str): The CSS property name + + Returns: + str: The Python attribute name as found on the Styles object + """ + return property_name.replace("-", "_") + + +def _css_name(property_name: str) -> str: + """Convert a Python style attribute name to the corresponding CSS property name + + Args: + property_name (str): The Python property name + + Returns: + str: The CSS property name + """ + return property_name.replace("_", "-") + + +def _contextualize_property_name( + property_name: str, + context: StylingContext, +) -> str: + """Convert a property name to CSS or inline by replacing + '-' with '_' or vice-versa + + Args: + property_name (str): The name of the property + context (StylingContext): The context the property is being used in. + + Returns: + str: The property name converted to the given context. + """ + return _css_name(property_name) if context == "css" else _python_name(property_name) + + +def _spacing_examples(property_name: str) -> ContextSpecificBullets: + """Returns examples for spacing properties""" + return ContextSpecificBullets( + inline=[ + Bullet( + f"Set [i]{property_name}[/] to a tuple to assign spacing to each edge", + examples=[ + Example( + f"widget.styles.{property_name} = (1, 2) [dim]# Vertical, horizontal" + ), + Example( + f"widget.styles.{property_name} = (1, 2, 3, 4) [dim]# Top, right, bottom, left" + ), + ], + ), + Bullet( + "Or to an integer to assign a single value to all edges", + examples=[Example(f"widget.styles.{property_name} = 2")], + ), + ], + css=[ + Bullet( + "Supply 1, 2 or 4 integers separated by a space", + examples=[ + Example(f"{property_name}: 1;"), + Example(f"{property_name}: 1 2; [dim]# Vertical, horizontal"), + Example( + f"{property_name}: 1 2 3 4; [dim]# Top, right, bottom, left" + ), + ], + ), + ], + ) + + +def property_invalid_value_help_text( + property_name: str, context: StylingContext, *, suggested_property_name: str = None +) -> HelpText: + """Help text to show when the user supplies an invalid value for CSS property + property. + + Args: + property_name (str): The name of the property + context (StylingContext | None): The context the spacing property is being used in. + Keyword Args: + suggested_property_name (str | None): A suggested name for the property (e.g. "width" for "wdth"). Defaults to None. + + Returns: + HelpText: Renderable for displaying the help text for this property + """ + property_name = _contextualize_property_name(property_name, context) + summary = f"Invalid CSS property {property_name!r}" + if suggested_property_name: + suggested_property_name = _contextualize_property_name( + suggested_property_name, context + ) + summary += f'. Did you mean "{suggested_property_name}"?' + return HelpText(summary) + + +def spacing_wrong_number_of_values_help_text( + property_name: str, + num_values_supplied: int, + context: StylingContext, +) -> HelpText: + """Help text to show when the user supplies the wrong number of values + for a spacing property (e.g. padding or margin). + + Args: + property_name (str): The name of the property + num_values_supplied (int): The number of values the user supplied (a number other than 1, 2 or 4). + context (StylingContext | None): The context the spacing property is being used in. + + Returns: + HelpText: Renderable for displaying the help text for this property + """ + property_name = _contextualize_property_name(property_name, context) + return HelpText( + summary=f"Invalid number of values for the [i]{property_name}[/] property", + bullets=[ + Bullet( + f"You supplied {num_values_supplied} values for the [i]{property_name}[/] property" + ), + Bullet( + "Spacing properties like [i]margin[/] and [i]padding[/] require either 1, 2 or 4 integer values" + ), + *_spacing_examples(property_name).get_by_context(context), + ], + ) + + +def spacing_invalid_value_help_text( + property_name: str, + context: StylingContext, +) -> HelpText: + """Help text to show when the user supplies an invalid value for a spacing + property. + + Args: + property_name (str): The name of the property + context (StylingContext | None): The context the spacing property is being used in. + + Returns: + HelpText: Renderable for displaying the help text for this property + """ + property_name = _contextualize_property_name(property_name, context) + return HelpText( + summary=f"Invalid value for the [i]{property_name}[/] property", + bullets=_spacing_examples(property_name).get_by_context(context), + ) + + +def scalar_help_text( + property_name: str, + context: StylingContext, +) -> HelpText: + """Help text to show when the user supplies an invalid value for + a scalar property. + + Args: + property_name (str): The name of the property + num_values_supplied (int): The number of values the user supplied (a number other than 1, 2 or 4). + context (StylingContext | None): The context the scalar property is being used in. + + Returns: + HelpText: Renderable for displaying the help text for this property + """ + property_name = _contextualize_property_name(property_name, context) + return HelpText( + summary=f"Invalid value for the [i]{property_name}[/] property", + bullets=[ + Bullet( + f"Scalar properties like [i]{property_name}[/] require numerical values and an optional unit" + ), + Bullet(f"Valid units are {friendly_list(SYMBOL_UNIT)}"), + *ContextSpecificBullets( + inline=[ + Bullet( + "Assign a string, int or Scalar object itself", + examples=[ + Example(f'widget.styles.{property_name} = "50%"'), + Example(f"widget.styles.{property_name} = 10"), + Example(f"widget.styles.{property_name} = Scalar(...)"), + ], + ), + ], + css=[ + Bullet( + "Write the number followed by the unit", + examples=[ + Example(f"{property_name}: 50%;"), + Example(f"{property_name}: 5;"), + ], + ), + ], + ).get_by_context(context), + ], + ) + + +def string_enum_help_text( + property_name: str, + valid_values: Iterable[str], + context: StylingContext, +) -> HelpText: + """Help text to show when the user supplies an invalid value for a string + enum property. + + Args: + property_name (str): The name of the property + valid_values (list[str]): A list of the values that are considered valid. + context (StylingContext | None): The context the property is being used in. + + Returns: + HelpText: Renderable for displaying the help text for this property + """ + property_name = _contextualize_property_name(property_name, context) + return HelpText( + summary=f"Invalid value for the [i]{property_name}[/] property", + bullets=[ + Bullet( + f"The [i]{property_name}[/] property can only be set to {friendly_list(valid_values)}" + ), + *ContextSpecificBullets( + inline=[ + Bullet( + "Assign any of the valid strings to the property", + examples=[ + Example(f'widget.styles.{property_name} = "{valid_value}"') + for valid_value in sorted(valid_values) + ], + ) + ], + css=[ + Bullet( + "Assign any of the valid strings to the property", + examples=[ + Example(f"{property_name}: {valid_value};") + for valid_value in sorted(valid_values) + ], + ) + ], + ).get_by_context(context), + ], + ) + + +def color_property_help_text( + property_name: str, + context: StylingContext, + *, + error: Exception = None, +) -> HelpText: + """Help text to show when the user supplies an invalid value for a color + property. For example, an unparseable color string. + + Args: + property_name (str): The name of the property + context (StylingContext | None): The context the property is being used in. + error (ColorParseError | None): The error that caused this help text to be displayed. Defaults to None. + + Returns: + HelpText: Renderable for displaying the help text for this property + """ + property_name = _contextualize_property_name(property_name, context) + summary = f"Invalid value for the [i]{property_name}[/] property" + suggested_color = ( + error.suggested_color if error and isinstance(error, ColorParseError) else None + ) + if suggested_color: + summary += f'. Did you mean "{suggested_color}"?' + return HelpText( + summary=summary, + bullets=[ + Bullet( + f"The [i]{property_name}[/] property can only be set to a valid color" + ), + Bullet(f"Colors can be specified using hex, RGB, or ANSI color names"), + *ContextSpecificBullets( + inline=[ + Bullet( + "Assign colors using strings or Color objects", + examples=[ + Example(f'widget.styles.{property_name} = "#ff00aa"'), + Example( + f'widget.styles.{property_name} = "rgb(12,231,45)"' + ), + Example(f'widget.styles.{property_name} = "red"'), + Example( + f"widget.styles.{property_name} = Color(1, 5, 29, a=0.5)" + ), + ], + ) + ], + css=[ + Bullet( + "Colors can be set as follows", + examples=[ + Example(f"{property_name}: [#ff00aa]#ff00aa[/];"), + Example(f"{property_name}: rgb(12,231,45);"), + Example(f"{property_name}: [rgb(255,0,0)]red[/];"), + ], + ) + ], + ).get_by_context(context), + ], + ) + + +def border_property_help_text(property_name: str, context: StylingContext) -> HelpText: + """Help text to show when the user supplies an invalid value for a border + property (such as border, border-right, outline) + + Args: + property_name (str): The name of the property + context (StylingContext | None): The context the property is being used in. + + Returns: + HelpText: Renderable for displaying the help text for this property + """ + property_name = _contextualize_property_name(property_name, context) + return HelpText( + summary=f"Invalid value for [i]{property_name}[/] property", + bullets=[ + *ContextSpecificBullets( + inline=[ + Bullet( + f"Set [i]{property_name}[/] using a tuple of the form (, )", + examples=[ + Example( + f'widget.styles.{property_name} = ("solid", "red")' + ), + Example( + f'widget.styles.{property_name} = ("round", "#f0f0f0")' + ), + Example( + f'widget.styles.{property_name} = [("dashed", "#f0f0f0"), ("solid", "blue")] [dim]# Vertical, horizontal' + ), + ], + ), + Bullet( + f"Valid values for are:\n{friendly_list(VALID_BORDER)}" + ), + Bullet( + f"Colors can be specified using hex, RGB, or ANSI color names" + ), + ], + css=[ + Bullet( + f"Set [i]{property_name}[/] using a value of the form [i] [/]", + examples=[ + Example(f"{property_name}: solid red;"), + Example(f"{property_name}: dashed #00ee22;"), + ], + ), + Bullet( + f"Valid values for are:\n{friendly_list(VALID_BORDER)}" + ), + Bullet( + f"Colors can be specified using hex, RGB, or ANSI color names" + ), + ], + ).get_by_context(context), + ], + ) + + +def layout_property_help_text(property_name: str, context: StylingContext) -> HelpText: + """Help text to show when the user supplies an invalid value + for a layout property. + + Args: + property_name (str): The name of the property + context (StylingContext | None): The context the property is being used in. + + Returns: + HelpText: Renderable for displaying the help text for this property + """ + property_name = _contextualize_property_name(property_name, context) + return HelpText( + summary=f"Invalid value for [i]{property_name}[/] property", + bullets=[ + Bullet( + f"The [i]{property_name}[/] property expects a value of {friendly_list(VALID_LAYOUT)}" + ), + ], + ) + + +def dock_property_help_text(property_name: str, context: StylingContext) -> HelpText: + """Help text to show when the user supplies an invalid value for dock. + + Args: + property_name (str): The name of the property + context (StylingContext | None): The context the property is being used in. + + Returns: + HelpText: Renderable for displaying the help text for this property + """ + property_name = _contextualize_property_name(property_name, context) + return HelpText( + summary=f"Invalid value for [i]{property_name}[/] property", + bullets=[ + Bullet("The value must be one of 'top', 'right', 'bottom' or 'left'"), + *ContextSpecificBullets( + inline=[ + Bullet( + "The 'dock' rule aligns a widget relative to the screen.", + examples=[Example(f'header.styles.dock = "top"')], + ) + ], + css=[ + Bullet( + "The 'dock' rule aligns a widget relative to the screen.", + examples=[Example(f"dock: top")], + ) + ], + ).get_by_context(context), + ], + ) + + +def fractional_property_help_text( + property_name: str, context: StylingContext +) -> HelpText: + """Help text to show when the user supplies an invalid value for a fractional property. + + Args: + property_name (str): The name of the property + context (StylingContext | None): The context the property is being used in. + + Returns: + HelpText: Renderable for displaying the help text for this property + """ + property_name = _contextualize_property_name(property_name, context) + return HelpText( + summary=f"Invalid value for [i]{property_name}[/] property", + bullets=[ + *ContextSpecificBullets( + inline=[ + Bullet( + f"Set [i]{property_name}[/] to a string or float value", + examples=[ + Example(f'widget.styles.{property_name} = "50%"'), + Example(f"widget.styles.{property_name} = 0.25"), + ], + ) + ], + css=[ + Bullet( + f"Set [i]{property_name}[/] to a string or float", + examples=[ + Example(f"{property_name}: 50%;"), + Example(f"{property_name}: 0.25;"), + ], + ) + ], + ).get_by_context(context) + ], + ) + + +def offset_property_help_text(context: StylingContext) -> HelpText: + """Help text to show when the user supplies an invalid value for the offset property. + + Args: + context (StylingContext | None): The context the property is being used in. + + Returns: + HelpText: Renderable for displaying the help text for this property + """ + return HelpText( + summary="Invalid value for [i]offset[/] property", + bullets=[ + *ContextSpecificBullets( + inline=[ + Bullet( + markup="The [i]offset[/] property expects a tuple of 2 values [i](, )[/]", + examples=[ + Example("widget.styles.offset = (2, '50%')"), + ], + ), + ], + css=[ + Bullet( + markup="The [i]offset[/] property expects a value of the form [i] [/]", + examples=[ + Example( + "offset: 2 3; [dim]# Horizontal offset of 2, vertical offset of 3" + ), + Example( + "offset: 2 50%; [dim]# Horizontal offset of 2, vertical offset of 50%" + ), + ], + ), + ], + ).get_by_context(context), + Bullet(" and can be a number or scalar value"), + ], + ) + + +def scrollbar_size_property_help_text(context: StylingContext) -> HelpText: + """Help text to show when the user supplies an invalid value for the scrollbar-size property. + + Args: + context (StylingContext | None): The context the property is being used in. + + Returns: + HelpText: Renderable for displaying the help text for this property + """ + return HelpText( + summary="Invalid value for [i]scrollbar-size[/] property", + bullets=[ + *ContextSpecificBullets( + inline=[ + Bullet( + markup="The [i]scrollbar_size[/] property expects a tuple of 2 values [i](, )[/]", + examples=[ + Example("widget.styles.scrollbar_size = (2, 1)"), + ], + ), + ], + css=[ + Bullet( + markup="The [i]scrollbar-size[/] property expects a value of the form [i] [/]", + examples=[ + Example( + "scrollbar-size: 2 3; [dim]# Horizontal size of 2, vertical size of 3" + ), + ], + ), + ], + ).get_by_context(context), + Bullet( + " and must be positive integers, greater than zero" + ), + ], + ) + + +def scrollbar_size_single_axis_help_text(property_name: str) -> HelpText: + """Help text to show when the user supplies an invalid value for a scrollbar-size-* property. + + Args: + property_name (str): The name of the property + + Returns: + HelpText: Renderable for displaying the help text for this property + """ + return HelpText( + summary=f"Invalid value for [i]{property_name}[/]", + bullets=[ + Bullet( + markup=f"The [i]{property_name}[/] property can only be set to a positive integer, greater than zero", + examples=[ + Example(f"{property_name}: 2;"), + ], + ), + ], + ) + + +def integer_help_text(property_name: str) -> HelpText: + """Help text to show when the user supplies an invalid integer value. + + Args: + property_name (str): The name of the property + + Returns: + HelpText: Renderable for displaying the help text for this property + """ + return HelpText( + summary=f"Invalid value for [i]{property_name}[/]", + bullets=[ + Bullet( + markup=f"An integer value is expected here", + examples=[ + Example(f"{property_name}: 2;"), + ], + ), + ], + ) + + +def align_help_text() -> HelpText: + """Help text to show when the user supplies an invalid value for a `align`. + + Returns: + HelpText: Renderable for displaying the help text for this property + """ + return HelpText( + summary="Invalid value for [i]align[/] property", + bullets=[ + Bullet( + markup="The [i]align[/] property expects exactly 2 values", + examples=[ + Example("align: "), + Example( + "align: center middle; [dim]# Center vertically & horizontally within parent" + ), + Example( + "align: left middle; [dim]# Align on the middle left of the parent" + ), + ], + ), + Bullet( + f"Valid values for are {friendly_list(VALID_ALIGN_HORIZONTAL)}" + ), + Bullet( + f"Valid values for are {friendly_list(VALID_ALIGN_VERTICAL)}", + ), + ], + ) + + +def text_align_help_text() -> HelpText: + """Help text to show when the user supplies an invalid value for the text-align property + + Returns: + HelpText: Renderable for displaying the help text for this property. + """ + return HelpText( + summary="Invalid value for the [i]text-align[/] property.", + bullets=[ + Bullet( + f"The [i]text-align[/] property must be one of {friendly_list(VALID_TEXT_ALIGN)}", + examples=[ + Example("text-align: center;"), + Example("text-align: right;"), + ], + ) + ], + ) + + +def offset_single_axis_help_text(property_name: str) -> HelpText: + """Help text to show when the user supplies an invalid value for an offset-* property. + + Args: + property_name (str): The name of the property + + Returns: + HelpText: Renderable for displaying the help text for this property + """ + return HelpText( + summary=f"Invalid value for [i]{property_name}[/]", + bullets=[ + Bullet( + markup=f"The [i]{property_name}[/] property can be set to a number or scalar value", + examples=[ + Example(f"{property_name}: 10;"), + Example(f"{property_name}: 50%;"), + ], + ), + Bullet(f"Valid scalar units are {friendly_list(SYMBOL_UNIT)}"), + ], + ) + + +def style_flags_property_help_text( + property_name: str, value: str, context: StylingContext +) -> HelpText: + """Help text to show when the user supplies an invalid value for a style flags property. + + Args: + property_name (str): The name of the property + context (StylingContext | None): The context the property is being used in. + + Returns: + HelpText: Renderable for displaying the help text for this property + """ + property_name = _contextualize_property_name(property_name, context) + return HelpText( + summary=f"Invalid value '{value}' in [i]{property_name}[/] property", + bullets=[ + Bullet( + f"Style flag values such as [i]{property_name}[/] expect space-separated values" + ), + Bullet(f"Permitted values are {friendly_list(VALID_STYLE_FLAGS)}"), + *ContextSpecificBullets( + inline=[ + Bullet( + markup="Supply a string or Style object", + examples=[ + Example( + f'widget.styles.{property_name} = "bold italic underline"' + ) + ], + ), + ], + css=[ + Bullet( + markup="Supply style flags separated by spaces", + examples=[Example(f"{property_name}: bold italic underline;")], + ) + ], + ).get_by_context(context), + ], + ) + + +def table_rows_or_columns_help_text( + property_name: str, value: str, context: StylingContext +): + property_name = _contextualize_property_name(property_name, context) + return HelpText( + summary=f"Invalid value '{value}' in [i]{property_name}[/] property" + ) diff --git a/testbed/Textualize__textual/src/textual/css/_styles_builder.py b/testbed/Textualize__textual/src/textual/css/_styles_builder.py new file mode 100644 index 0000000000000000000000000000000000000000..15e7ebd8ec57891266819e0da49abb2dd05b71c2 --- /dev/null +++ b/testbed/Textualize__textual/src/textual/css/_styles_builder.py @@ -0,0 +1,974 @@ +from __future__ import annotations + +from functools import lru_cache +from typing import Iterable, NoReturn, Sequence, cast + +import rich.repr + +from .._border import BorderValue, normalize_border_value +from .._duration import _duration_as_seconds +from .._easing import EASING +from ..color import Color, ColorParseError +from ..geometry import Spacing, SpacingDimensions, clamp +from ..suggestions import get_suggestion +from ._error_tools import friendly_list +from ._help_renderables import HelpText +from ._help_text import ( + align_help_text, + border_property_help_text, + color_property_help_text, + dock_property_help_text, + fractional_property_help_text, + integer_help_text, + layout_property_help_text, + offset_property_help_text, + offset_single_axis_help_text, + property_invalid_value_help_text, + scalar_help_text, + scrollbar_size_property_help_text, + scrollbar_size_single_axis_help_text, + spacing_invalid_value_help_text, + spacing_wrong_number_of_values_help_text, + string_enum_help_text, + style_flags_property_help_text, + table_rows_or_columns_help_text, + text_align_help_text, +) +from .constants import ( + VALID_ALIGN_HORIZONTAL, + VALID_ALIGN_VERTICAL, + VALID_BORDER, + VALID_BOX_SIZING, + VALID_DISPLAY, + VALID_EDGE, + VALID_OVERFLOW, + VALID_SCROLLBAR_GUTTER, + VALID_STYLE_FLAGS, + VALID_TEXT_ALIGN, + VALID_VISIBILITY, +) +from .errors import DeclarationError, StyleValueError +from .model import Declaration +from .scalar import ( + Scalar, + ScalarError, + ScalarOffset, + ScalarParseError, + Unit, + percentage_string_to_float, +) +from .styles import Styles +from .tokenize import Token +from .transition import Transition +from .types import BoxSizing, Display, Edge, EdgeType, Overflow, Visibility + + +def _join_tokens(tokens: Iterable[Token], joiner: str = "") -> str: + """Convert tokens into a string by joining their values + + Args: + tokens (Iterable[Token]): Tokens to join + joiner (str): String to join on, defaults to "" + + Returns: + str: The tokens, joined together to form a string. + """ + return joiner.join(token.value for token in tokens) + + +class StylesBuilder: + """ + The StylesBuilder object takes tokens parsed from the CSS and converts + to the appropriate internal types. + """ + + def __init__(self) -> None: + self.styles = Styles() + + def __rich_repr__(self) -> rich.repr.Result: + yield "styles", self.styles + + def __repr__(self) -> str: + return "StylesBuilder()" + + def error(self, name: str, token: Token, message: str | HelpText) -> NoReturn: + raise DeclarationError(name, token, message) + + def add_declaration(self, declaration: Declaration) -> None: + if not declaration.tokens: + return + rule_name = declaration.name.replace("-", "_") + process_method = getattr(self, f"process_{rule_name}", None) + + if process_method is None: + suggested_property_name = self._get_suggested_property_name_for_rule( + declaration.name + ) + self.error( + declaration.name, + declaration.token, + property_invalid_value_help_text( + declaration.name, + "css", + suggested_property_name=suggested_property_name, + ), + ) + return + + tokens = declaration.tokens + + important = tokens[-1].name == "important" + if important: + tokens = tokens[:-1] + self.styles.important.add(rule_name) + try: + process_method(declaration.name, tokens) + except DeclarationError: + raise + except Exception as error: + self.error(declaration.name, declaration.token, str(error)) + + @lru_cache(maxsize=None) + def _get_processable_rule_names(self) -> Sequence[str]: + """ + Returns the list of CSS properties we can manage - + i.e. the ones for which we have a `process_[property name]` method + + Returns: + Sequence[str]: All the "Python-ised" CSS property names this class can handle. + + Example: ("width", "background", "offset_x", ...) + """ + return [attr[8:] for attr in dir(self) if attr.startswith("process_")] + + def _process_enum_multiple( + self, name: str, tokens: list[Token], valid_values: set[str], count: int + ) -> tuple[str, ...]: + """Generic code to process a declaration with two enumerations, like overflow: auto auto""" + if len(tokens) > count or not tokens: + self.error(name, tokens[0], f"expected 1 to {count} tokens here") + results: list[str] = [] + append = results.append + for token in tokens: + token_name, value, _, _, location, _ = token + if token_name != "token": + self.error( + name, + token, + f"invalid token {value!r}; expected {friendly_list(valid_values)}", + ) + append(value) + + short_results = results[:] + + while len(results) < count: + results.extend(short_results) + results = results[:count] + + return tuple(results) + + def _process_enum( + self, name: str, tokens: list[Token], valid_values: set[str] + ) -> str: + """Process a declaration that expects an enum. + + Args: + name (str): Name of declaration. + tokens (list[Token]): Tokens from parser. + valid_values (list[str]): A set of valid values. + + Returns: + bool: True if the value is valid or False if it is invalid (also generates an error) + """ + + if len(tokens) != 1: + string_enum_help_text(name, valid_values=list(valid_values), context="css"), + + token = tokens[0] + token_name, value, _, _, location, _ = token + if token_name != "token": + self.error( + name, + token, + string_enum_help_text( + name, valid_values=list(valid_values), context="css" + ), + ) + if value not in valid_values: + self.error( + name, + token, + string_enum_help_text( + name, valid_values=list(valid_values), context="css" + ), + ) + return value + + def process_display(self, name: str, tokens: list[Token]) -> None: + for token in tokens: + name, value, _, _, location, _ = token + + if name == "token": + value = value.lower() + if value in VALID_DISPLAY: + self.styles._rules["display"] = cast(Display, value) + else: + self.error( + name, + token, + string_enum_help_text( + "display", valid_values=list(VALID_DISPLAY), context="css" + ), + ) + else: + self.error( + name, + token, + string_enum_help_text( + "display", valid_values=list(VALID_DISPLAY), context="css" + ), + ) + + def _process_scalar(self, name: str, tokens: list[Token]) -> None: + def scalar_error(): + self.error( + name, tokens[0], scalar_help_text(property_name=name, context="css") + ) + + if not tokens: + return + if len(tokens) == 1: + try: + self.styles._rules[name.replace("-", "_")] = Scalar.parse( + tokens[0].value + ) + except ScalarParseError: + scalar_error() + else: + scalar_error() + + def process_box_sizing(self, name: str, tokens: list[Token]) -> None: + for token in tokens: + name, value, _, _, location, _ = token + + if name == "token": + value = value.lower() + if value in VALID_BOX_SIZING: + self.styles._rules["box_sizing"] = cast(BoxSizing, value) + else: + self.error( + name, + token, + string_enum_help_text( + "box-sizing", + valid_values=list(VALID_BOX_SIZING), + context="css", + ), + ) + else: + self.error( + name, + token, + string_enum_help_text( + "box-sizing", valid_values=list(VALID_BOX_SIZING), context="css" + ), + ) + + def process_width(self, name: str, tokens: list[Token]) -> None: + self._process_scalar(name, tokens) + + def process_height(self, name: str, tokens: list[Token]) -> None: + self._process_scalar(name, tokens) + + def process_min_width(self, name: str, tokens: list[Token]) -> None: + self._process_scalar(name, tokens) + + def process_min_height(self, name: str, tokens: list[Token]) -> None: + self._process_scalar(name, tokens) + + def process_max_width(self, name: str, tokens: list[Token]) -> None: + self._process_scalar(name, tokens) + + def process_max_height(self, name: str, tokens: list[Token]) -> None: + self._process_scalar(name, tokens) + + def process_overflow(self, name: str, tokens: list[Token]) -> None: + rules = self.styles._rules + overflow_x, overflow_y = self._process_enum_multiple( + name, tokens, VALID_OVERFLOW, 2 + ) + rules["overflow_x"] = cast(Overflow, overflow_x) + rules["overflow_y"] = cast(Overflow, overflow_y) + + def process_overflow_x(self, name: str, tokens: list[Token]) -> None: + self.styles._rules["overflow_x"] = cast( + Overflow, self._process_enum(name, tokens, VALID_OVERFLOW) + ) + + def process_overflow_y(self, name: str, tokens: list[Token]) -> None: + self.styles._rules["overflow_y"] = cast( + Overflow, self._process_enum(name, tokens, VALID_OVERFLOW) + ) + + def process_visibility(self, name: str, tokens: list[Token]) -> None: + for token in tokens: + name, value, _, _, location, _ = token + if name == "token": + value = value.lower() + if value in VALID_VISIBILITY: + self.styles._rules["visibility"] = cast(Visibility, value) + else: + self.error( + name, + token, + string_enum_help_text( + "visibility", + valid_values=list(VALID_VISIBILITY), + context="css", + ), + ) + else: + string_enum_help_text( + "visibility", valid_values=list(VALID_VISIBILITY), context="css" + ) + + def _process_fractional(self, name: str, tokens: list[Token]) -> None: + if not tokens: + return + token = tokens[0] + error = False + if len(tokens) != 1: + error = True + else: + token_name = token.name + value = token.value + rule_name = name.replace("-", "_") + if token_name == "scalar" and value.endswith("%"): + try: + text_opacity = percentage_string_to_float(value) + self.styles.set_rule(rule_name, text_opacity) + except ValueError: + error = True + elif token_name == "number": + try: + text_opacity = clamp(float(value), 0, 1) + self.styles.set_rule(rule_name, text_opacity) + except ValueError: + error = True + else: + error = True + + if error: + self.error(name, token, fractional_property_help_text(name, context="css")) + + process_opacity = _process_fractional + process_text_opacity = _process_fractional + + def _process_space(self, name: str, tokens: list[Token]) -> None: + space: list[int] = [] + append = space.append + for token in tokens: + token_name, value, _, _, _, _ = token + if token_name == "number": + try: + append(int(value)) + except ValueError: + self.error( + name, + token, + spacing_invalid_value_help_text(name, context="css"), + ) + else: + self.error( + name, token, spacing_invalid_value_help_text(name, context="css") + ) + if len(space) not in (1, 2, 4): + self.error( + name, + tokens[0], + spacing_wrong_number_of_values_help_text( + name, num_values_supplied=len(space), context="css" + ), + ) + self.styles._rules[name] = Spacing.unpack(cast(SpacingDimensions, tuple(space))) + + def _process_space_partial(self, name: str, tokens: list[Token]) -> None: + """Process granular margin / padding declarations.""" + if len(tokens) != 1: + self.error( + name, tokens[0], spacing_invalid_value_help_text(name, context="css") + ) + + _EDGE_SPACING_MAP = {"top": 0, "right": 1, "bottom": 2, "left": 3} + token = tokens[0] + token_name, value, _, _, _, _ = token + if token_name == "number": + space = int(value) + else: + self.error( + name, token, spacing_invalid_value_help_text(name, context="css") + ) + style_name, _, edge = name.replace("-", "_").partition("_") + + current_spacing = cast( + "tuple[int, int, int, int]", + self.styles._rules.get(style_name, (0, 0, 0, 0)), + ) + + spacing_list = list(current_spacing) + spacing_list[_EDGE_SPACING_MAP[edge]] = space + + self.styles._rules[style_name] = Spacing(*spacing_list) + + process_padding = _process_space + process_margin = _process_space + + process_margin_top = _process_space_partial + process_margin_right = _process_space_partial + process_margin_bottom = _process_space_partial + process_margin_left = _process_space_partial + + process_padding_top = _process_space_partial + process_padding_right = _process_space_partial + process_padding_bottom = _process_space_partial + process_padding_left = _process_space_partial + + def _parse_border(self, name: str, tokens: list[Token]) -> BorderValue: + + border_type: EdgeType = "solid" + border_color = Color(0, 255, 0) + + def border_value_error(): + self.error(name, token, border_property_help_text(name, context="css")) + + for token in tokens: + token_name, value, _, _, _, _ = token + if token_name == "token": + if value in VALID_BORDER: + border_type = value + else: + try: + border_color = Color.parse(value) + except ColorParseError: + border_value_error() + + elif token_name == "color": + try: + border_color = Color.parse(value) + except ColorParseError: + border_value_error() + + else: + border_value_error() + + return normalize_border_value((border_type, border_color)) + + def _process_border_edge(self, edge: str, name: str, tokens: list[Token]) -> None: + border = self._parse_border(name, tokens) + self.styles._rules[f"border_{edge}"] = border + + def process_border(self, name: str, tokens: list[Token]) -> None: + border = self._parse_border(name, tokens) + rules = self.styles._rules + rules["border_top"] = rules["border_right"] = border + rules["border_bottom"] = rules["border_left"] = border + + def process_border_top(self, name: str, tokens: list[Token]) -> None: + self._process_border_edge("top", name, tokens) + + def process_border_right(self, name: str, tokens: list[Token]) -> None: + self._process_border_edge("right", name, tokens) + + def process_border_bottom(self, name: str, tokens: list[Token]) -> None: + self._process_border_edge("bottom", name, tokens) + + def process_border_left(self, name: str, tokens: list[Token]) -> None: + self._process_border_edge("left", name, tokens) + + def _process_outline(self, edge: str, name: str, tokens: list[Token]) -> None: + border = self._parse_border(name, tokens) + self.styles._rules[f"outline_{edge}"] = border + + def process_outline(self, name: str, tokens: list[Token]) -> None: + border = self._parse_border(name, tokens) + rules = self.styles._rules + rules["outline_top"] = rules["outline_right"] = border + rules["outline_bottom"] = rules["outline_left"] = border + + def process_outline_top(self, name: str, tokens: list[Token]) -> None: + self._process_outline("top", name, tokens) + + def process_parse_border_right(self, name: str, tokens: list[Token]) -> None: + self._process_outline("right", name, tokens) + + def process_outline_bottom(self, name: str, tokens: list[Token]) -> None: + self._process_outline("bottom", name, tokens) + + def process_outline_left(self, name: str, tokens: list[Token]) -> None: + self._process_outline("left", name, tokens) + + def process_offset(self, name: str, tokens: list[Token]) -> None: + def offset_error(name: str, token: Token) -> None: + self.error(name, token, offset_property_help_text(context="css")) + + if not tokens: + return + if len(tokens) != 2: + offset_error(name, tokens[0]) + else: + token1, token2 = tokens + + if token1.name not in ("scalar", "number"): + offset_error(name, token1) + if token2.name not in ("scalar", "number"): + offset_error(name, token2) + + scalar_x = Scalar.parse(token1.value, Unit.WIDTH) + scalar_y = Scalar.parse(token2.value, Unit.HEIGHT) + self.styles._rules["offset"] = ScalarOffset(scalar_x, scalar_y) + + def process_offset_x(self, name: str, tokens: list[Token]) -> None: + if not tokens: + return + if len(tokens) != 1: + self.error(name, tokens[0], offset_single_axis_help_text(name)) + else: + token = tokens[0] + if token.name not in ("scalar", "number"): + self.error(name, token, offset_single_axis_help_text(name)) + x = Scalar.parse(token.value, Unit.WIDTH) + y = self.styles.offset.y + self.styles._rules["offset"] = ScalarOffset(x, y) + + def process_offset_y(self, name: str, tokens: list[Token]) -> None: + if not tokens: + return + if len(tokens) != 1: + self.error(name, tokens[0], offset_single_axis_help_text(name)) + else: + token = tokens[0] + if token.name not in ("scalar", "number"): + self.error(name, token, offset_single_axis_help_text(name)) + y = Scalar.parse(token.value, Unit.HEIGHT) + x = self.styles.offset.x + self.styles._rules["offset"] = ScalarOffset(x, y) + + def process_layout(self, name: str, tokens: list[Token]) -> None: + from ..layouts.factory import MissingLayout, get_layout + + if tokens: + if len(tokens) != 1: + self.error( + name, tokens[0], layout_property_help_text(name, context="css") + ) + else: + value = tokens[0].value + layout_name = value + try: + self.styles._rules["layout"] = get_layout(layout_name) + except MissingLayout: + self.error( + name, + tokens[0], + layout_property_help_text(name, context="css"), + ) + + def process_color(self, name: str, tokens: list[Token]) -> None: + """Processes a simple color declaration.""" + name = name.replace("-", "_") + + color: Color | None = None + alpha: float | None = None + + for token in tokens: + if ( + "background" not in name + and token.name == "token" + and token.value == "auto" + ): + self.styles._rules[f"auto_{name}"] = True + elif token.name == "scalar": + alpha_scalar = Scalar.parse(token.value) + if alpha_scalar.unit != Unit.PERCENT: + self.error(name, token, "alpha must be given as a percentage.") + alpha = alpha_scalar.value / 100.0 + + elif token.name in ("color", "token"): + try: + color = Color.parse(token.value) + except Exception as error: + self.error( + name, + token, + color_property_help_text(name, context="css", error=error), + ) + else: + self.error(name, token, color_property_help_text(name, context="css")) + + if color is not None or alpha is not None: + if alpha is not None: + color = (color or Color(255, 255, 255)).with_alpha(alpha) + self.styles._rules[name] = color + + process_tint = process_color + process_background = process_color + process_scrollbar_color = process_color + process_scrollbar_color_hover = process_color + process_scrollbar_color_active = process_color + process_scrollbar_corner_color = process_color + process_scrollbar_background = process_color + process_scrollbar_background_hover = process_color + process_scrollbar_background_active = process_color + + process_link_color = process_color + process_link_background = process_color + process_hover_color = process_color + process_hover_background = process_color + + def process_text_style(self, name: str, tokens: list[Token]) -> None: + for token in tokens: + value = token.value + if value not in VALID_STYLE_FLAGS: + self.error( + name, + token, + style_flags_property_help_text(name, value, context="css"), + ) + + style_definition = " ".join(token.value for token in tokens) + self.styles._rules[name.replace("-", "_")] = style_definition + + process_link_style = process_text_style + process_hover_style = process_text_style + + def process_text_align(self, name: str, tokens: list[Token]) -> None: + """Process a text-align declaration""" + if not tokens: + return + + if len(tokens) > 1 or tokens[0].value not in VALID_TEXT_ALIGN: + self.error( + name, + tokens[0], + text_align_help_text(), + ) + + self.styles._rules["text_align"] = tokens[0].value + + def process_dock(self, name: str, tokens: list[Token]) -> None: + if not tokens: + return + + if len(tokens) > 1 or tokens[0].value not in VALID_EDGE: + self.error( + name, + tokens[0], + dock_property_help_text(name, context="css"), + ) + + dock = tokens[0].value + self.styles._rules["dock"] = dock + + def process_layer(self, name: str, tokens: list[Token]) -> None: + if len(tokens) > 1: + self.error(name, tokens[1], f"unexpected tokens in dock-edge declaration") + self.styles._rules["layer"] = tokens[0].value + + def process_layers(self, name: str, tokens: list[Token]) -> None: + layers: list[str] = [] + for token in tokens: + if token.name != "token": + self.error(name, token, "{token.name} not expected here") + layers.append(token.value) + self.styles._rules["layers"] = tuple(layers) + + def process_transition(self, name: str, tokens: list[Token]) -> None: + transitions: dict[str, Transition] = {} + + def make_groups() -> Iterable[list[Token]]: + """Batch tokens into comma-separated groups.""" + group: list[Token] = [] + for token in tokens: + if token.name == "comma": + if group: + yield group + group = [] + else: + group.append(token) + if group: + yield group + + valid_duration_token_names = ("duration", "number") + for tokens in make_groups(): + css_property = "" + duration = 1.0 + easing = "linear" + delay = 0.0 + + try: + iter_tokens = iter(tokens) + token = next(iter_tokens) + if token.name != "token": + self.error(name, token, "expected property") + + css_property = token.value + token = next(iter_tokens) + if token.name not in valid_duration_token_names: + self.error(name, token, "expected duration or number") + try: + duration = _duration_as_seconds(token.value) + except ScalarError as error: + self.error(name, token, str(error)) + + token = next(iter_tokens) + if token.name != "token": + self.error(name, token, "easing function expected") + + if token.value not in EASING: + self.error( + name, + token, + f"expected easing function; found {token.value!r}", + ) + easing = token.value + + token = next(iter_tokens) + if token.name not in valid_duration_token_names: + self.error(name, token, "expected duration or number") + try: + delay = _duration_as_seconds(token.value) + except ScalarError as error: + self.error(name, token, str(error)) + except StopIteration: + pass + transitions[css_property] = Transition(duration, easing, delay) + + self.styles._rules["transitions"] = transitions + + def process_align(self, name: str, tokens: list[Token]) -> None: + def align_error(name, token): + self.error(name, token, align_help_text()) + + if len(tokens) != 2: + self.error(name, tokens[0], align_help_text()) + + token_horizontal = tokens[0] + token_vertical = tokens[1] + + if token_horizontal.name != "token": + align_error(name, token_horizontal) + elif token_horizontal.value not in VALID_ALIGN_HORIZONTAL: + align_error(name, token_horizontal) + + if token_vertical.name != "token": + align_error(name, token_vertical) + elif token_vertical.value not in VALID_ALIGN_VERTICAL: + align_error(name, token_horizontal) + + name = name.replace("-", "_") + self.styles._rules[f"{name}_horizontal"] = token_horizontal.value + self.styles._rules[f"{name}_vertical"] = token_vertical.value + + def process_align_horizontal(self, name: str, tokens: list[Token]) -> None: + try: + value = self._process_enum(name, tokens, VALID_ALIGN_HORIZONTAL) + except StyleValueError: + self.error( + name, + tokens[0], + string_enum_help_text(name, VALID_ALIGN_HORIZONTAL, context="css"), + ) + else: + self.styles._rules[name.replace("-", "_")] = value + + def process_align_vertical(self, name: str, tokens: list[Token]) -> None: + try: + value = self._process_enum(name, tokens, VALID_ALIGN_VERTICAL) + except StyleValueError: + self.error( + name, + tokens[0], + string_enum_help_text(name, VALID_ALIGN_VERTICAL, context="css"), + ) + else: + self.styles._rules[name.replace("-", "_")] = value + + process_content_align = process_align + process_content_align_horizontal = process_align_horizontal + process_content_align_vertical = process_align_vertical + + def process_scrollbar_gutter(self, name: str, tokens: list[Token]) -> None: + try: + value = self._process_enum(name, tokens, VALID_SCROLLBAR_GUTTER) + except StyleValueError: + self.error( + name, + tokens[0], + string_enum_help_text(name, VALID_SCROLLBAR_GUTTER, context="css"), + ) + else: + self.styles._rules[name.replace("-", "_")] = value + + def process_scrollbar_size(self, name: str, tokens: list[Token]) -> None: + def scrollbar_size_error(name: str, token: Token) -> None: + self.error(name, token, scrollbar_size_property_help_text(context="css")) + + if not tokens: + return + if len(tokens) != 2: + scrollbar_size_error(name, tokens[0]) + else: + token1, token2 = tokens + + if token1.name != "number" or not token1.value.isdigit(): + scrollbar_size_error(name, token1) + if token2.name != "number" or not token2.value.isdigit(): + scrollbar_size_error(name, token2) + + horizontal = int(token1.value) + if horizontal == 0: + scrollbar_size_error(name, token1) + vertical = int(token2.value) + if vertical == 0: + scrollbar_size_error(name, token2) + self.styles._rules["scrollbar_size_horizontal"] = horizontal + self.styles._rules["scrollbar_size_vertical"] = vertical + + def process_scrollbar_size_vertical(self, name: str, tokens: list[Token]) -> None: + if not tokens: + return + if len(tokens) != 1: + self.error(name, tokens[0], scrollbar_size_single_axis_help_text(name)) + else: + token = tokens[0] + if token.name != "number" or not token.value.isdigit(): + self.error(name, token, scrollbar_size_single_axis_help_text(name)) + value = int(token.value) + if value == 0: + self.error(name, token, scrollbar_size_single_axis_help_text(name)) + self.styles._rules["scrollbar_size_vertical"] = value + + def process_scrollbar_size_horizontal(self, name: str, tokens: list[Token]) -> None: + if not tokens: + return + if len(tokens) != 1: + self.error(name, tokens[0], scrollbar_size_single_axis_help_text(name)) + else: + token = tokens[0] + if token.name != "number" or not token.value.isdigit(): + self.error(name, token, scrollbar_size_single_axis_help_text(name)) + value = int(token.value) + if value == 0: + self.error(name, token, scrollbar_size_single_axis_help_text(name)) + self.styles._rules["scrollbar_size_horizontal"] = value + + def _process_grid_rows_or_columns(self, name: str, tokens: list[Token]) -> None: + scalars: list[Scalar] = [] + for token in tokens: + if token.name == "number": + scalars.append(Scalar.from_number(float(token.value))) + elif token.name == "scalar": + scalars.append( + Scalar.parse( + token.value, + percent_unit=Unit.WIDTH if name == "rows" else Unit.HEIGHT, + ) + ) + else: + self.error( + name, + token, + table_rows_or_columns_help_text(name, token.value, context="css"), + ) + self.styles._rules[name.replace("-", "_")] = scalars + + process_grid_rows = _process_grid_rows_or_columns + process_grid_columns = _process_grid_rows_or_columns + + def _process_integer(self, name: str, tokens: list[Token]) -> None: + if not tokens: + return + if len(tokens) != 1: + self.error(name, tokens[0], integer_help_text(name)) + else: + token = tokens[0] + if token.name != "number" or not token.value.isdigit(): + self.error(name, token, integer_help_text(name)) + value = int(token.value) + if value == 0: + self.error(name, token, integer_help_text(name)) + self.styles._rules[name.replace("-", "_")] = value + + process_grid_gutter_horizontal = _process_integer + process_grid_gutter_vertical = _process_integer + process_column_span = _process_integer + process_row_span = _process_integer + process_grid_size_columns = _process_integer + process_grid_size_rows = _process_integer + + def process_grid_gutter(self, name: str, tokens: list[Token]) -> None: + if not tokens: + return + if len(tokens) == 1: + token = tokens[0] + if token.name != "number": + self.error(name, token, integer_help_text(name)) + value = max(0, int(token.value)) + self.styles._rules["grid_gutter_horizontal"] = value + self.styles._rules["grid_gutter_vertical"] = value + + elif len(tokens) == 2: + token = tokens[0] + if token.name != "number": + self.error(name, token, integer_help_text(name)) + value = max(0, int(token.value)) + self.styles._rules["grid_gutter_horizontal"] = value + token = tokens[1] + if token.name != "number": + self.error(name, token, integer_help_text(name)) + value = max(0, int(token.value)) + self.styles._rules["grid_gutter_vertical"] = value + + else: + self.error(name, tokens[0], "expected two integers here") + + def process_grid_size(self, name: str, tokens: list[Token]) -> None: + if not tokens: + return + if len(tokens) == 1: + token = tokens[0] + if token.name != "number": + self.error(name, token, integer_help_text(name)) + value = max(0, int(token.value)) + self.styles._rules["grid_size_columns"] = value + self.styles._rules["grid_size_rows"] = 0 + + elif len(tokens) == 2: + token = tokens[0] + if token.name != "number": + self.error(name, token, integer_help_text(name)) + value = max(0, int(token.value)) + self.styles._rules["grid_size_columns"] = value + token = tokens[1] + if token.name != "number": + self.error(name, token, integer_help_text(name)) + value = max(0, int(token.value)) + self.styles._rules["grid_size_rows"] = value + + else: + self.error(name, tokens[0], "expected two integers here") + + def _get_suggested_property_name_for_rule(self, rule_name: str) -> str | None: + """ + Returns a valid CSS property "Python" name, or None if no close matches could be found. + + Args: + rule_name (str): An invalid "Python-ised" CSS property (i.e. "offst_x" rather than "offst-x") + + Returns: + str | None: The closest valid "Python-ised" CSS property. + Returns `None` if no close matches could be found. + + Example: returns "background" for rule_name "bkgrund", "offset_x" for "ofset_x" + """ + return get_suggestion(rule_name, self._get_processable_rule_names()) diff --git a/testbed/Textualize__textual/src/textual/css/constants.py b/testbed/Textualize__textual/src/textual/css/constants.py new file mode 100644 index 0000000000000000000000000000000000000000..38a718a6a24420e57a498802a57bb26cbde92166 --- /dev/null +++ b/testbed/Textualize__textual/src/textual/css/constants.py @@ -0,0 +1,60 @@ +from __future__ import annotations +import sys +import typing + +if sys.version_info >= (3, 8): + from typing import Final +else: + from typing_extensions import Final # pragma: no cover + +from ..geometry import Spacing + +if typing.TYPE_CHECKING: + from .types import EdgeType + +VALID_VISIBILITY: Final = {"visible", "hidden"} +VALID_DISPLAY: Final = {"block", "none"} +VALID_BORDER: Final[set[EdgeType]] = { + "none", + "hidden", + "ascii", + "round", + "blank", + "solid", + "double", + "dashed", + "heavy", + "inner", + "outer", + "hkey", + "vkey", + "tall", + "wide", +} +VALID_EDGE: Final = {"top", "right", "bottom", "left"} +VALID_LAYOUT: Final = {"vertical", "horizontal", "center", "grid"} + +VALID_BOX_SIZING: Final = {"border-box", "content-box"} +VALID_OVERFLOW: Final = {"scroll", "hidden", "auto"} +VALID_ALIGN_HORIZONTAL: Final = {"left", "center", "right"} +VALID_ALIGN_VERTICAL: Final = {"top", "middle", "bottom"} +VALID_TEXT_ALIGN: Final = {"start", "end", "left", "right", "center", "justify"} +VALID_SCROLLBAR_GUTTER: Final = {"auto", "stable"} +VALID_STYLE_FLAGS: Final = { + "none", + "not", + "bold", + "blink", + "italic", + "underline", + "overline", + "strike", + "b", + "i", + "u", + "uu", + "o", + "reverse", +} + +NULL_SPACING: Final = Spacing.all(0) diff --git a/testbed/Textualize__textual/src/textual/css/errors.py b/testbed/Textualize__textual/src/textual/css/errors.py new file mode 100644 index 0000000000000000000000000000000000000000..c0a5ca95d9e932e63f9534990934f02f699a669c --- /dev/null +++ b/testbed/Textualize__textual/src/textual/css/errors.py @@ -0,0 +1,50 @@ +from __future__ import annotations + +from rich.console import ConsoleOptions, Console, RenderResult +from rich.traceback import Traceback + +from ._help_renderables import HelpText +from .tokenize import Token +from .tokenizer import TokenError + + +class DeclarationError(Exception): + def __init__(self, name: str, token: Token, message: str | HelpText) -> None: + self.name = name + self.token = token + self.message = message + super().__init__(str(message)) + + +class StyleTypeError(TypeError): + pass + + +class UnresolvedVariableError(TokenError): + pass + + +class StyleValueError(ValueError): + """Raised when the value of a style property is not valid + + Attributes: + help_text (HelpText | None): Optional HelpText to be rendered when this + error is raised. + """ + + def __init__(self, *args, help_text: HelpText | None = None): + super().__init__(*args) + self.help_text = help_text + + def __rich_console__( + self, console: Console, options: ConsoleOptions + ) -> RenderResult: + yield Traceback.from_exception(type(self), self, self.__traceback__) + if self.help_text is not None: + yield "" + yield self.help_text + yield "" + + +class StylesheetError(Exception): + pass diff --git a/testbed/Textualize__textual/src/textual/css/match.py b/testbed/Textualize__textual/src/textual/css/match.py new file mode 100644 index 0000000000000000000000000000000000000000..4b647c461132e30fd626573179d23b8a608ac397 --- /dev/null +++ b/testbed/Textualize__textual/src/textual/css/match.py @@ -0,0 +1,74 @@ +from __future__ import annotations + +from typing import Iterable, TYPE_CHECKING +from .model import CombinatorType, Selector, SelectorSet + + +if TYPE_CHECKING: + from ..dom import DOMNode + + +def match(selector_sets: Iterable[SelectorSet], node: DOMNode) -> bool: + """Check if a given selector matches any of the given selector sets. + + Args: + selector_sets (Iterable[SelectorSet]): Iterable of selector sets. + node (DOMNode): DOM node. + + Returns: + bool: True if the node matches the selector, otherwise False. + """ + return any( + _check_selectors(selector_set.selectors, node.css_path_nodes) + for selector_set in selector_sets + ) + + +def _check_selectors(selectors: list[Selector], css_path_nodes: list[DOMNode]) -> bool: + """Match a list of selectors against a node. + + Args: + selectors (list[Selector]): A list of selectors. + node (DOMNode): A DOM node. + + Returns: + bool: True if the node matches the selector. + """ + + DESCENDENT = CombinatorType.DESCENDENT + + node = css_path_nodes[-1] + path_count = len(css_path_nodes) + selector_count = len(selectors) + + stack: list[tuple[int, int]] = [(0, 0)] + + push = stack.append + pop = stack.pop + selector_index = 0 + + while stack: + selector_index, node_index = stack[-1] + if selector_index == selector_count or node_index == path_count: + pop() + else: + path_node = css_path_nodes[node_index] + selector = selectors[selector_index] + if selector.combinator == DESCENDENT: + # Find a matching descendent + if selector.check(path_node): + if path_node is node and selector_index == selector_count - 1: + return True + stack[-1] = (selector_index + 1, node_index + selector.advance) + push((selector_index, node_index + 1)) + else: + stack[-1] = (selector_index, node_index + 1) + else: + # Match the next node + if selector.check(path_node): + if path_node is node and selector_index == selector_count - 1: + return True + stack[-1] = (selector_index + 1, node_index + selector.advance) + else: + pop() + return False diff --git a/testbed/Textualize__textual/src/textual/css/model.py b/testbed/Textualize__textual/src/textual/css/model.py new file mode 100644 index 0000000000000000000000000000000000000000..c5efebc15353aa668868869e9a5797575dd1c18e --- /dev/null +++ b/testbed/Textualize__textual/src/textual/css/model.py @@ -0,0 +1,235 @@ +from __future__ import annotations + + +import rich.repr + +from dataclasses import dataclass, field +from enum import Enum +from typing import Iterable, TYPE_CHECKING + +from .styles import Styles +from .tokenize import Token +from .types import Specificity3 + +if TYPE_CHECKING: + from ..dom import DOMNode + + +class SelectorType(Enum): + UNIVERSAL = 1 + TYPE = 2 + CLASS = 3 + ID = 4 + + +class CombinatorType(Enum): + SAME = 1 + DESCENDENT = 2 + CHILD = 3 + + +@dataclass +class Selector: + """Represents a CSS selector. + + Some examples of selectors: + + * + Header.title + App > Content + """ + + name: str + combinator: CombinatorType = CombinatorType.DESCENDENT + type: SelectorType = SelectorType.TYPE + pseudo_classes: list[str] = field(default_factory=list) + specificity: Specificity3 = field(default_factory=lambda: (0, 0, 0)) + _name_lower: str = field(default="", repr=False) + advance: int = 1 + + @property + def css(self) -> str: + """Rebuilds the selector as it would appear in CSS.""" + pseudo_suffix = "".join(f":{name}" for name in self.pseudo_classes) + if self.type == SelectorType.UNIVERSAL: + return "*" + elif self.type == SelectorType.TYPE: + return f"{self.name}{pseudo_suffix}" + elif self.type == SelectorType.CLASS: + return f".{self.name}{pseudo_suffix}" + else: + return f"#{self.name}{pseudo_suffix}" + + def __post_init__(self) -> None: + self._name_lower = self.name.lower() + self._checks = { + SelectorType.UNIVERSAL: self._check_universal, + SelectorType.TYPE: self._check_type, + SelectorType.CLASS: self._check_class, + SelectorType.ID: self._check_id, + } + + def _add_pseudo_class(self, pseudo_class: str) -> None: + """Adds a pseudo class and updates specificity. + + Args: + pseudo_class (str): Name of pseudo class. + """ + self.pseudo_classes.append(pseudo_class) + specificity1, specificity2, specificity3 = self.specificity + self.specificity = (specificity1, specificity2 + 1, specificity3) + + def check(self, node: DOMNode) -> bool: + """Check if a given node matches the selector. + + Args: + node (DOMNode): A DOM node. + + Returns: + bool: True if the selector matches, otherwise False. + """ + return self._checks[self.type](node) + + def _check_universal(self, node: DOMNode) -> bool: + return node.has_pseudo_class(*self.pseudo_classes) + + def _check_type(self, node: DOMNode) -> bool: + if self._name_lower not in node._css_type_names: + return False + if self.pseudo_classes and not node.has_pseudo_class(*self.pseudo_classes): + return False + return True + + def _check_class(self, node: DOMNode) -> bool: + if not node.has_class(self._name_lower): + return False + if self.pseudo_classes and not node.has_pseudo_class(*self.pseudo_classes): + return False + return True + + def _check_id(self, node: DOMNode) -> bool: + if not node.id == self._name_lower: + return False + if self.pseudo_classes and not node.has_pseudo_class(*self.pseudo_classes): + return False + return True + + +@dataclass +class Declaration: + token: Token + name: str + tokens: list[Token] = field(default_factory=list) + + +@rich.repr.auto(angular=True) +@dataclass +class SelectorSet: + selectors: list[Selector] = field(default_factory=list) + specificity: Specificity3 = (0, 0, 0) + + def __post_init__(self) -> None: + SAME = CombinatorType.SAME + for selector, next_selector in zip(self.selectors, self.selectors[1:]): + selector.advance = int(next_selector.combinator != SAME) + + @property + def css(self) -> str: + return RuleSet._selector_to_css(self.selectors) + + def __rich_repr__(self) -> rich.repr.Result: + selectors = RuleSet._selector_to_css(self.selectors) + yield selectors + yield None, self.specificity + + @classmethod + def from_selectors(cls, selectors: list[list[Selector]]) -> Iterable[SelectorSet]: + for selector_list in selectors: + id_total = class_total = type_total = 0 + for selector in selector_list: + _id, _class, _type = selector.specificity + id_total += _id + class_total += _class + type_total += _type + yield SelectorSet(selector_list, (id_total, class_total, type_total)) + + +@dataclass +class RuleSet: + selector_set: list[SelectorSet] = field(default_factory=list) + styles: Styles = field(default_factory=Styles) + errors: list[tuple[Token, str]] = field(default_factory=list) + + is_default_rules: bool = False + tie_breaker: int = 0 + selector_names: set[str] = field(default_factory=set) + + def __hash__(self): + return id(self) + + @classmethod + def _selector_to_css(cls, selectors: list[Selector]) -> str: + tokens: list[str] = [] + for selector in selectors: + if selector.combinator == CombinatorType.DESCENDENT: + tokens.append(" ") + elif selector.combinator == CombinatorType.CHILD: + tokens.append(" > ") + tokens.append(selector.css) + return "".join(tokens).strip() + + @property + def selectors(self): + return ", ".join( + self._selector_to_css(selector_set.selectors) + for selector_set in self.selector_set + ) + + @property + def css(self) -> str: + """Generate the CSS this RuleSet + + Returns: + str: A string containing CSS code. + """ + declarations = "\n".join(f" {line}" for line in self.styles.css_lines) + css = f"{self.selectors} {{\n{declarations}\n}}" + return css + + def _post_parse(self) -> None: + """Called after the RuleSet is parsed.""" + # Build a set of the class names that have been updated + + class_type = SelectorType.CLASS + id_type = SelectorType.ID + type_type = SelectorType.TYPE + universal_type = SelectorType.UNIVERSAL + + update_selectors = self.selector_names.update + + for selector_set in self.selector_set: + update_selectors( + "*" + for selector in selector_set.selectors + if selector.type == universal_type + ) + update_selectors( + selector.name + for selector in selector_set.selectors + if selector.type == type_type + ) + update_selectors( + f".{selector.name}" + for selector in selector_set.selectors + if selector.type == class_type + ) + update_selectors( + f"#{selector.name}" + for selector in selector_set.selectors + if selector.type == id_type + ) + update_selectors( + f":{pseudo_class}" + for selector in selector_set.selectors + for pseudo_class in selector.pseudo_classes + ) diff --git a/testbed/Textualize__textual/src/textual/css/parse.py b/testbed/Textualize__textual/src/textual/css/parse.py new file mode 100644 index 0000000000000000000000000000000000000000..c9ba19fd2fb2222922553cadacbd9c375140d48a --- /dev/null +++ b/testbed/Textualize__textual/src/textual/css/parse.py @@ -0,0 +1,387 @@ +from __future__ import annotations + +from functools import lru_cache +from pathlib import PurePath +from typing import Iterator, Iterable, NoReturn, Sequence + +from rich import print + +from .errors import UnresolvedVariableError +from .types import Specificity3 +from ._styles_builder import StylesBuilder, DeclarationError +from .model import ( + Declaration, + RuleSet, + Selector, + CombinatorType, + SelectorSet, + SelectorType, +) +from .styles import Styles +from ..suggestions import get_suggestion +from .tokenize import tokenize, tokenize_declarations, Token, tokenize_values +from .tokenizer import EOFError, ReferencedBy + +SELECTOR_MAP: dict[str, tuple[SelectorType, Specificity3]] = { + "selector": (SelectorType.TYPE, (0, 0, 1)), + "selector_start": (SelectorType.TYPE, (0, 0, 1)), + "selector_class": (SelectorType.CLASS, (0, 1, 0)), + "selector_start_class": (SelectorType.CLASS, (0, 1, 0)), + "selector_id": (SelectorType.ID, (1, 0, 0)), + "selector_start_id": (SelectorType.ID, (1, 0, 0)), + "selector_universal": (SelectorType.UNIVERSAL, (0, 0, 0)), + "selector_start_universal": (SelectorType.UNIVERSAL, (0, 0, 0)), +} + + +@lru_cache(maxsize=1024) +def parse_selectors(css_selectors: str) -> tuple[SelectorSet, ...]: + tokens = iter(tokenize(css_selectors, "")) + + get_selector = SELECTOR_MAP.get + combinator: CombinatorType | None = CombinatorType.DESCENDENT + selectors: list[Selector] = [] + rule_selectors: list[list[Selector]] = [] + + while True: + try: + token = next(tokens) + except EOFError: + break + token_name = token.name + if token_name == "pseudo_class": + selectors[-1]._add_pseudo_class(token.value.lstrip(":")) + elif token_name == "whitespace": + if combinator is None or combinator == CombinatorType.SAME: + combinator = CombinatorType.DESCENDENT + elif token_name == "new_selector": + rule_selectors.append(selectors[:]) + selectors.clear() + combinator = None + elif token_name == "declaration_set_start": + break + elif token_name == "combinator_child": + combinator = CombinatorType.CHILD + else: + _selector, specificity = get_selector( + token_name, (SelectorType.TYPE, (0, 0, 0)) + ) + selectors.append( + Selector( + name=token.value.lstrip(".#"), + combinator=combinator or CombinatorType.DESCENDENT, + type=_selector, + specificity=specificity, + ) + ) + combinator = CombinatorType.SAME + if selectors: + rule_selectors.append(selectors[:]) + + selector_set = tuple(SelectorSet.from_selectors(rule_selectors)) + return selector_set + + +def parse_rule_set( + tokens: Iterator[Token], + token: Token, + is_default_rules: bool = False, + tie_breaker: int = 0, +) -> Iterable[RuleSet]: + get_selector = SELECTOR_MAP.get + combinator: CombinatorType | None = CombinatorType.DESCENDENT + selectors: list[Selector] = [] + rule_selectors: list[list[Selector]] = [] + styles_builder = StylesBuilder() + + while True: + if token.name == "pseudo_class": + selectors[-1]._add_pseudo_class(token.value.lstrip(":")) + elif token.name == "whitespace": + if combinator is None or combinator == CombinatorType.SAME: + combinator = CombinatorType.DESCENDENT + elif token.name == "new_selector": + rule_selectors.append(selectors[:]) + selectors.clear() + combinator = None + elif token.name == "declaration_set_start": + break + elif token.name == "combinator_child": + combinator = CombinatorType.CHILD + else: + _selector, specificity = get_selector( + token.name, (SelectorType.TYPE, (0, 0, 0)) + ) + selectors.append( + Selector( + name=token.value.lstrip(".#"), + combinator=combinator or CombinatorType.DESCENDENT, + type=_selector, + specificity=specificity, + ) + ) + combinator = CombinatorType.SAME + + token = next(tokens) + + if selectors: + rule_selectors.append(selectors[:]) + + declaration = Declaration(token, "") + + errors: list[tuple[Token, str]] = [] + + while True: + token = next(tokens) + token_name = token.name + if token_name in ("whitespace", "declaration_end"): + continue + if token_name == "declaration_name": + if declaration.tokens: + try: + styles_builder.add_declaration(declaration) + except DeclarationError as error: + errors.append((error.token, error.message)) + declaration = Declaration(token, "") + declaration.name = token.value.rstrip(":") + elif token_name == "declaration_set_end": + break + else: + declaration.tokens.append(token) + + if declaration.tokens: + try: + styles_builder.add_declaration(declaration) + except DeclarationError as error: + errors.append((error.token, error.message)) + + rule_set = RuleSet( + list(SelectorSet.from_selectors(rule_selectors)), + styles_builder.styles, + errors, + is_default_rules=is_default_rules, + tie_breaker=tie_breaker, + ) + rule_set._post_parse() + yield rule_set + + +def parse_declarations(css: str, path: str) -> Styles: + """Parse declarations and return a Styles object. + + Args: + css (str): String containing CSS. + path (str): Path to the CSS, or something else to identify the location. + + Returns: + Styles: A styles object. + """ + + tokens = iter(tokenize_declarations(css, path)) + styles_builder = StylesBuilder() + + declaration: Declaration | None = None + errors: list[tuple[Token, str]] = [] + + while True: + token = next(tokens, None) + if token is None: + break + token_name = token.name + if token_name in ("whitespace", "declaration_end", "eof"): + continue + if token_name == "declaration_name": + if declaration and declaration.tokens: + try: + styles_builder.add_declaration(declaration) + except DeclarationError as error: + errors.append((error.token, error.message)) + raise + declaration = Declaration(token, "") + declaration.name = token.value.rstrip(":") + elif token_name == "declaration_set_end": + break + else: + if declaration: + declaration.tokens.append(token) + + if declaration and declaration.tokens: + try: + styles_builder.add_declaration(declaration) + except DeclarationError as error: + errors.append((error.token, error.message)) + raise + + return styles_builder.styles + + +def _unresolved(variable_name: str, variables: Iterable[str], token: Token) -> NoReturn: + """Raise a TokenError regarding an unresolved variable. + + Args: + variable_name (str): A variable name. + variables (Iterable[str]): Possible choices used to generate suggestion. + token (Token): The Token. + + Raises: + UnresolvedVariableError: Always raises a TokenError. + + """ + message = f"reference to undefined variable '${variable_name}'" + suggested_variable = get_suggestion(variable_name, list(variables)) + if suggested_variable: + message += f"; did you mean '${suggested_variable}'?" + + raise UnresolvedVariableError( + token.path, + token.code, + token.start, + message, + end=token.end, + ) + + +def substitute_references( + tokens: Iterable[Token], css_variables: dict[str, list[Token]] | None = None +) -> Iterable[Token]: + """Replace variable references with values by substituting variable reference + tokens with the tokens representing their values. + + Args: + tokens (Iterable[Token]): Iterator of Tokens which may contain tokens + with the name "variable_ref". + + Returns: + Iterable[Token]: Yields Tokens such that any variable references (tokens where + token.name == "variable_ref") have been replaced with the tokens representing + the value. In other words, an Iterable of Tokens similar to the original input, + but with variables resolved. Substituted tokens will have their referenced_by + attribute populated with information about where the tokens are being substituted to. + """ + variables: dict[str, list[Token]] = css_variables.copy() if css_variables else {} + + iter_tokens = iter(tokens) + + while tokens: + token = next(iter_tokens, None) + if token is None: + break + if token.name == "variable_name": + variable_name = token.value[1:-1] # Trim the $ and the :, i.e. "$x:" -> "x" + yield token + + while True: + token = next(iter_tokens, None) + # TODO: Mypy error looks legit + if token.name == "whitespace": + yield token + else: + break + + # Store the tokens for any variable definitions, and substitute + # any variable references we encounter with them. + while True: + if not token: + break + elif token.name == "whitespace": + variables.setdefault(variable_name, []).append(token) + yield token + elif token.name == "variable_value_end": + yield token + break + # For variables referring to other variables + elif token.name == "variable_ref": + ref_name = token.value[1:] + if ref_name in variables: + variable_tokens = variables.setdefault(variable_name, []) + reference_tokens = variables[ref_name] + variable_tokens.extend(reference_tokens) + ref_location = token.location + ref_length = len(token.value) + for _token in reference_tokens: + yield _token.with_reference( + ReferencedBy( + ref_name, ref_location, ref_length, token.code + ) + ) + else: + _unresolved(ref_name, variables.keys(), token) + else: + variables.setdefault(variable_name, []).append(token) + yield token + token = next(iter_tokens, None) + elif token.name == "variable_ref": + variable_name = token.value[1:] # Trim the $, so $x -> x + if variable_name in variables: + variable_tokens = variables[variable_name] + ref_location = token.location + ref_length = len(token.value) + ref_code = token.code + for _token in variable_tokens: + yield _token.with_reference( + ReferencedBy(variable_name, ref_location, ref_length, ref_code) + ) + else: + _unresolved(variable_name, variables.keys(), token) + else: + yield token + + +def parse( + css: str, + path: str | PurePath, + variables: dict[str, str] | None = None, + variable_tokens: dict[str, list[Token]] | None = None, + is_default_rules: bool = False, + tie_breaker: int = 0, +) -> Iterable[RuleSet]: + """Parse CSS by tokenizing it, performing variable substitution, + and generating rule sets from it. + + Args: + css (str): The input CSS + path (str): Path to the CSS + variables (dict[str, str]): Substitution variables to substitute tokens for. + is_default_rules (bool): True if the rules we're extracting are + default (i.e. in Widget.DEFAULT_CSS) rules. False if they're from user defined CSS. + """ + + reference_tokens = tokenize_values(variables) if variables is not None else {} + if variable_tokens: + reference_tokens.update(variable_tokens) + + tokens = iter(substitute_references(tokenize(css, path), variable_tokens)) + while True: + token = next(tokens, None) + if token is None: + break + if token.name.startswith("selector_start"): + yield from parse_rule_set( + tokens, + token, + is_default_rules=is_default_rules, + tie_breaker=tie_breaker, + ) + + +if __name__ == "__main__": + print(parse_selectors("Foo > Bar.baz { foo: bar")) + + css = """#something { + text: on red; + transition: offset 5.51s in_out_cubic; + offset-x: 100%; +} +""" + + from textual.css.stylesheet import Stylesheet, StylesheetParseError + from rich.console import Console + + console = Console() + stylesheet = Stylesheet() + try: + stylesheet.add_source(css) + except StylesheetParseError as e: + console.print(e.errors) + print(stylesheet) + print(stylesheet.css) diff --git a/testbed/Textualize__textual/src/textual/css/query.py b/testbed/Textualize__textual/src/textual/css/query.py new file mode 100644 index 0000000000000000000000000000000000000000..93addb6fb1d741642e3352b47d16843e4f295684 --- /dev/null +++ b/testbed/Textualize__textual/src/textual/css/query.py @@ -0,0 +1,334 @@ +""" +A DOMQuery is a set of DOM nodes associated with a given CSS selector. + +This set of nodes may be further filtered with the filter method. Additional methods apply +actions to the nodes in the query. + +If this sounds like JQuery, a (once) popular JS library, it is no coincidence. + +DOMQuery objects are typically created by Widget.query method. + +Queries are *lazy*. Results will be calculated at the point you iterate over the query, or call +a method which evaluates the query, such as first() and last(). + +""" + + +from __future__ import annotations + +from typing import cast, Generic, TYPE_CHECKING, Iterator, TypeVar, overload + +import rich.repr + +from .errors import DeclarationError +from .match import match +from .model import SelectorSet +from .parse import parse_declarations, parse_selectors + +if TYPE_CHECKING: + from ..dom import DOMNode + from ..widget import Widget + + +class QueryError(Exception): + """Base class for a query related error.""" + + +class NoMatches(QueryError): + """No nodes matched the query.""" + + +class WrongType(QueryError): + """Query result was not of the correct type.""" + + +QueryType = TypeVar("QueryType", bound="Widget") + + +@rich.repr.auto(angular=True) +class DOMQuery(Generic[QueryType]): + __slots__ = [ + "_node", + "_nodes", + "_filters", + "_excludes", + ] + + def __init__( + self, + node: DOMNode, + *, + filter: str | None = None, + exclude: str | None = None, + parent: DOMQuery | None = None, + ) -> None: + + self._node = node + self._nodes: list[QueryType] | None = None + self._filters: list[tuple[SelectorSet, ...]] = ( + parent._filters.copy() if parent else [] + ) + self._excludes: list[tuple[SelectorSet, ...]] = ( + parent._excludes.copy() if parent else [] + ) + if filter is not None: + self._filters.append(parse_selectors(filter)) + if exclude is not None: + self._excludes.append(parse_selectors(exclude)) + + @property + def node(self) -> DOMNode: + return self._node + + @property + def nodes(self) -> list[QueryType]: + """Lazily evaluate nodes.""" + from ..widget import Widget + + if self._nodes is None: + nodes = [ + node + for node in self._node.walk_children(Widget) + if all(match(selector_set, node) for selector_set in self._filters) + ] + nodes = [ + node + for node in nodes + if not any(match(selector_set, node) for selector_set in self._excludes) + ] + self._nodes = cast("list[QueryType]", nodes) + return self._nodes + + def __len__(self) -> int: + return len(self.nodes) + + def __bool__(self) -> bool: + """True if non-empty, otherwise False.""" + return bool(self.nodes) + + def __iter__(self) -> Iterator[QueryType]: + return iter(self.nodes) + + def __reversed__(self) -> Iterator[QueryType]: + return reversed(self.nodes) + + @overload + def __getitem__(self, index: int) -> QueryType: + ... + + @overload + def __getitem__(self, index: slice) -> list[QueryType]: + ... + + def __getitem__(self, index: int | slice) -> QueryType | list[QueryType]: + return self.nodes[index] + + def __rich_repr__(self) -> rich.repr.Result: + yield self.node + if self._filters: + yield "filter", " AND ".join( + ",".join(selector.css for selector in selectors) + for selectors in self._filters + ) + if self._excludes: + yield "exclude", " OR ".join( + ",".join(selector.css for selector in selectors) + for selectors in self._excludes + ) + + def filter(self, selector: str) -> DOMQuery[QueryType]: + """Filter this set by the given CSS selector. + + Args: + selector (str): A CSS selector. + + Returns: + DOMQuery: New DOM Query. + """ + + return DOMQuery(self.node, filter=selector, parent=self) + + def exclude(self, selector: str) -> DOMQuery[QueryType]: + """Exclude nodes that match a given selector. + + Args: + selector (str): A CSS selector. + + Returns: + DOMQuery: New DOM query. + """ + return DOMQuery(self.node, exclude=selector, parent=self) + + ExpectType = TypeVar("ExpectType") + + @overload + def first(self) -> Widget: + ... + + @overload + def first(self, expect_type: type[ExpectType]) -> ExpectType: + ... + + def first( + self, expect_type: type[ExpectType] | None = None + ) -> QueryType | ExpectType: + """Get the *first* matching node. + + Args: + expect_type (type[ExpectType] | None, optional): Require matched node is of this type, + or None for any type. Defaults to None. + + Raises: + WrongType: If the wrong type was found. + NoMatches: If there are no matching nodes in the query. + + Returns: + Widget | ExpectType: The matching Widget. + """ + if self.nodes: + first = self.nodes[0] + if expect_type is not None: + if not isinstance(first, expect_type): + raise WrongType( + f"Query value is wrong type; expected {expect_type}, got {type(first)}" + ) + return first + else: + raise NoMatches(f"No nodes match {self!r}") + + @overload + def last(self) -> Widget: + ... + + @overload + def last(self, expect_type: type[ExpectType]) -> ExpectType: + ... + + def last( + self, expect_type: type[ExpectType] | None = None + ) -> QueryType | ExpectType: + """Get the *last* matching node. + + Args: + expect_type (type[ExpectType] | None, optional): Require matched node is of this type, + or None for any type. Defaults to None. + + Raises: + WrongType: If the wrong type was found. + NoMatches: If there are no matching nodes in the query. + + Returns: + Widget | ExpectType: The matching Widget. + """ + if self.nodes: + last = self.nodes[-1] + if expect_type is not None: + if not isinstance(last, expect_type): + raise WrongType( + f"Query value is wrong type; expected {expect_type}, got {type(last)}" + ) + return last + else: + raise NoMatches(f"No nodes match {self!r}") + + @overload + def results(self) -> Iterator[Widget]: + ... + + @overload + def results(self, filter_type: type[ExpectType]) -> Iterator[ExpectType]: + ... + + def results( + self, filter_type: type[ExpectType] | None = None + ) -> Iterator[Widget | ExpectType]: + """Get query results, optionally filtered by a given type. + + Args: + filter_type (type[ExpectType] | None): A Widget class to filter results, + or None for no filter. Defaults to None. + + Yields: + Iterator[Widget | ExpectType]: An iterator of Widget instances. + """ + if filter_type is None: + yield from self + else: + for node in self: + if isinstance(node, filter_type): + yield node + + def set_class(self, add: bool, *class_names: str) -> DOMQuery[QueryType]: + """Set the given class name(s) according to a condition. + + Args: + add (bool): Add the classes if True, otherwise remove them. + + Returns: + DOMQuery: Self. + """ + for node in self: + node.set_class(add, *class_names) + return self + + def add_class(self, *class_names: str) -> DOMQuery[QueryType]: + """Add the given class name(s) to nodes.""" + for node in self: + node.add_class(*class_names) + return self + + def remove_class(self, *class_names: str) -> DOMQuery[QueryType]: + """Remove the given class names from the nodes.""" + for node in self: + node.remove_class(*class_names) + return self + + def toggle_class(self, *class_names: str) -> DOMQuery[QueryType]: + """Toggle the given class names from matched nodes.""" + for node in self: + node.toggle_class(*class_names) + return self + + def remove(self) -> DOMQuery[QueryType]: + """Remove matched nodes from the DOM""" + for node in self: + node.remove() + return self + + def set_styles( + self, css: str | None = None, **update_styles + ) -> DOMQuery[QueryType]: + """Set styles on matched nodes. + + Args: + css (str, optional): CSS declarations to parser, or None. Defaults to None. + """ + _rich_traceback_omit = True + + for node in self: + node.set_styles(**update_styles) + if css is not None: + try: + new_styles = parse_declarations(css, path="set_styles") + except DeclarationError as error: + raise DeclarationError(error.name, error.token, error.message) from None + for node in self: + node._inline_styles.merge(new_styles) + node.refresh(layout=True) + return self + + def refresh( + self, *, repaint: bool = True, layout: bool = False + ) -> DOMQuery[QueryType]: + """Refresh matched nodes. + + Args: + repaint (bool): Repaint node(s). defaults to True. + layout (bool): Layout node(s). Defaults to False. + + Returns: + DOMQuery: Query for chaining. + """ + for node in self: + node.refresh(repaint=repaint, layout=layout) + return self diff --git a/testbed/Textualize__textual/src/textual/css/scalar.py b/testbed/Textualize__textual/src/textual/css/scalar.py new file mode 100644 index 0000000000000000000000000000000000000000..bb4368514ad6665932b041dcd61539310b87fe51 --- /dev/null +++ b/testbed/Textualize__textual/src/textual/css/scalar.py @@ -0,0 +1,392 @@ +from __future__ import annotations + +from enum import Enum, unique +from fractions import Fraction +from functools import lru_cache +import re +from typing import Iterable, NamedTuple + +import rich.repr + +from ..geometry import Offset, Size, clamp + + +class ScalarError(Exception): + pass + + +class ScalarResolveError(ScalarError): + pass + + +class ScalarParseError(ScalarError): + pass + + +@unique +class Unit(Enum): + """Enumeration of the various units inherited from CSS.""" + + CELLS = 1 + FRACTION = 2 + PERCENT = 3 + WIDTH = 4 + HEIGHT = 5 + VIEW_WIDTH = 6 + VIEW_HEIGHT = 7 + AUTO = 8 + + +UNIT_EXCLUDES_BORDER = {Unit.CELLS, Unit.FRACTION, Unit.VIEW_WIDTH, Unit.VIEW_HEIGHT} + +UNIT_SYMBOL = { + Unit.CELLS: "", + Unit.FRACTION: "fr", + Unit.PERCENT: "%", + Unit.WIDTH: "w", + Unit.HEIGHT: "h", + Unit.VIEW_WIDTH: "vw", + Unit.VIEW_HEIGHT: "vh", +} + +SYMBOL_UNIT = {v: k for k, v in UNIT_SYMBOL.items()} + +_MATCH_SCALAR = re.compile(r"^(-?\d+\.?\d*)(fr|%|w|h|vw|vh)?$").match + + +def _resolve_cells( + value: float, size: Size, viewport: Size, fraction_unit: Fraction +) -> Fraction: + """Resolves explicit cell size, i.e. width: 10 + + Args: + value (float): Scalar value. + size (Size): Size of widget. + viewport (Size): Size of viewport. + fraction_unit (Fraction): Size of fraction, i.e. size of 1fr as a Fraction. + + Returns: + Fraction: Resolved unit. + """ + return Fraction(value) + + +def _resolve_fraction( + value: float, size: Size, viewport: Size, fraction_unit: Fraction +) -> Fraction: + """Resolves a fraction unit i.e. width: 2fr + + Args: + value (float): Scalar value. + size (Size): Size of widget. + viewport (Size): Size of viewport. + fraction_unit (Fraction): Size of fraction, i.e. size of 1fr as a Fraction. + + Returns: + Fraction: Resolved unit. + """ + return fraction_unit * Fraction(value) + + +def _resolve_width( + value: float, size: Size, viewport: Size, fraction_unit: Fraction +) -> Fraction: + """Resolves width unit i.e. width: 50w. + + Args: + value (float): Scalar value. + size (Size): Size of widget. + viewport (Size): Size of viewport. + fraction_unit (Fraction): Size of fraction, i.e. size of 1fr as a Fraction. + + Returns: + Fraction: Resolved unit. + """ + return Fraction(value) * Fraction(size.width, 100) + + +def _resolve_height( + value: float, size: Size, viewport: Size, fraction_unit: Fraction +) -> Fraction: + """Resolves height unit, i.e. height: 12h. + + Args: + value (float): Scalar value. + size (Size): Size of widget. + viewport (Size): Size of viewport. + fraction_unit (Fraction): Size of fraction, i.e. size of 1fr as a Fraction. + + Returns: + Fraction: Resolved unit. + """ + return Fraction(value) * Fraction(size.height, 100) + + +def _resolve_view_width( + value: float, size: Size, viewport: Size, fraction_unit: Fraction +) -> Fraction: + """Resolves view width unit, i.e. width: 25vw. + + Args: + value (float): Scalar value. + size (Size): Size of widget. + viewport (Size): Size of viewport. + fraction_unit (Fraction): Size of fraction, i.e. size of 1fr as a Fraction. + + Returns: + Fraction: Resolved unit. + """ + return Fraction(value) * Fraction(viewport.width, 100) + + +def _resolve_view_height( + value: float, size: Size, viewport: Size, fraction_unit: Fraction +) -> Fraction: + """Resolves view height unit, i.e. height: 25vh. + + Args: + value (float): Scalar value. + size (Size): Size of widget. + viewport (Size): Size of viewport. + fraction_unit (Fraction): Size of fraction, i.e. size of 1fr as a Fraction. + + Returns: + Fraction: Resolved unit. + """ + return Fraction(value) * Fraction(viewport.height, 100) + + +RESOLVE_MAP = { + Unit.CELLS: _resolve_cells, + Unit.FRACTION: _resolve_fraction, + Unit.WIDTH: _resolve_width, + Unit.HEIGHT: _resolve_height, + Unit.VIEW_WIDTH: _resolve_view_width, + Unit.VIEW_HEIGHT: _resolve_view_height, +} + + +def get_symbols(units: Iterable[Unit]) -> list[str]: + """Get symbols for an iterable of units. + + Args: + units (Iterable[Unit]): A number of units. + + Returns: + list[str]: List of symbols. + """ + return [UNIT_SYMBOL[unit] for unit in units] + + +class Scalar(NamedTuple): + """A numeric value and a unit.""" + + value: float + unit: Unit + percent_unit: Unit + + def __str__(self) -> str: + value, unit, _ = self + if unit == Unit.AUTO: + return "auto" + return f"{int(value) if value.is_integer() else value}{self.symbol}" + + @property + def is_cells(self) -> bool: + """Check if the Scalar is explicit cells.""" + return self.unit == Unit.CELLS + + @property + def is_percent(self) -> bool: + """Check if the Scalar is a percentage unit.""" + return self.unit == Unit.PERCENT + + @property + def is_fraction(self) -> bool: + """Check if the unit is a fraction.""" + return self.unit == Unit.FRACTION + + @property + def excludes_border(self) -> bool: + return self.unit in UNIT_EXCLUDES_BORDER + + @property + def cells(self) -> int | None: + """Check if the unit is explicit cells.""" + value, unit, _ = self + return int(value) if unit == Unit.CELLS else None + + @property + def fraction(self) -> int | None: + """Get the fraction value, or None if not a value.""" + value, unit, _ = self + return int(value) if unit == Unit.FRACTION else None + + @property + def symbol(self) -> str: + """Get the symbol of this unit.""" + return UNIT_SYMBOL[self.unit] + + @property + def is_auto(self) -> bool: + """Check if this is an auto unit.""" + return self.unit == Unit.AUTO + + @classmethod + def from_number(cls, value: float) -> Scalar: + """Create a scalar with cells unit. + + Args: + value (float): A number of cells. + + Returns: + Scalar: New Scalar. + """ + return cls(float(value), Unit.CELLS, Unit.WIDTH) + + @classmethod + def parse(cls, token: str, percent_unit: Unit = Unit.WIDTH) -> Scalar: + """Parse a string in to a Scalar + + Args: + token (str): A string containing a scalar, e.g. "3.14fr" + + Raises: + ScalarParseError: If the value is not a valid scalar + + Returns: + Scalar: New scalar + """ + if token.lower() == "auto": + scalar = cls(1.0, Unit.AUTO, Unit.AUTO) + else: + match = _MATCH_SCALAR(token) + if match is None: + raise ScalarParseError(f"{token!r} is not a valid scalar") + value, unit_name = match.groups() + scalar = cls(float(value), SYMBOL_UNIT[unit_name or ""], percent_unit) + return scalar + + @lru_cache(maxsize=4096) + def resolve_dimension( + self, size: Size, viewport: Size, fraction_unit: Fraction | None = None + ) -> Fraction: + """Resolve scalar with units in to a dimensions. + + Args: + size (tuple[int, int]): Size of the container. + viewport (tuple[int, int]): Size of the viewport (typically terminal size) + + Raises: + ScalarResolveError: If the unit is unknown. + + Returns: + int: A size (in cells) + """ + value, unit, percent_unit = self + + if unit == Unit.PERCENT: + unit = percent_unit + try: + dimension = RESOLVE_MAP[unit]( + value, size, viewport, fraction_unit or Fraction(1) + ) + except KeyError: + raise ScalarResolveError(f"expected dimensions; found {str(self)!r}") + return dimension + + def copy_with( + self, + value: float | None = None, + unit: Unit | None = None, + percent_unit: Unit | None = None, + ) -> Scalar: + """Get a copy of this Scalar, with values optionally modified + + Args: + value (float | None): The new value, or None to keep the same value + unit (Unit | None): The new unit, or None to keep the same unit + percent_unit (Unit | None): The new percent_unit, or None to keep the same percent_unit + """ + return Scalar( + value if value is not None else self.value, + unit if unit is not None else self.unit, + percent_unit if percent_unit is not None else self.percent_unit, + ) + + +@rich.repr.auto(angular=True) +class ScalarOffset(NamedTuple): + """An Offset with two scalars, used to animate between to Scalars.""" + + x: Scalar + y: Scalar + + @classmethod + def null(cls) -> ScalarOffset: + """Get a null scalar offset (0, 0).""" + return NULL_SCALAR + + @classmethod + def from_offset(cls, offset: tuple[int, int]) -> ScalarOffset: + """Create a Scalar offset from a tuple of integers. + + Args: + offset (tuple[int, int]): Offset in cells. + + Returns: + ScalarOffset: New offset. + """ + x, y = offset + return cls( + Scalar(x, Unit.CELLS, Unit.WIDTH), + Scalar(y, Unit.CELLS, Unit.HEIGHT), + ) + + def __bool__(self) -> bool: + x, y = self + return bool(x.value or y.value) + + def __rich_repr__(self) -> rich.repr.Result: + yield None, str(self.x) + yield None, str(self.y) + + def resolve(self, size: Size, viewport: Size) -> Offset: + """Resolve the offset in to cells. + + Args: + size (Size): Size of container. + viewport (Size): Size of viewport. + + Returns: + Offset: Offset in cells. + """ + x, y = self + return Offset( + round(x.resolve_dimension(size, viewport)), + round(y.resolve_dimension(size, viewport)), + ) + + +NULL_SCALAR = ScalarOffset(Scalar.from_number(0), Scalar.from_number(0)) + + +def percentage_string_to_float(string: str) -> float: + """Convert a string percentage e.g. '20%' to a float e.g. 20.0. + + Args: + string (str): The percentage string to convert. + """ + string = string.strip() + if string.endswith("%"): + float_percentage = clamp(float(string[:-1]) / 100.0, 0.0, 1.0) + else: + float_percentage = float(string) + return float_percentage + + +if __name__ == "__main__": + print(Scalar.parse("3.14fr")) + s = Scalar.parse("23") + print(repr(s)) + print(repr(s.cells)) diff --git a/testbed/Textualize__textual/src/textual/css/scalar_animation.py b/testbed/Textualize__textual/src/textual/css/scalar_animation.py new file mode 100644 index 0000000000000000000000000000000000000000..c584ef692ca637009e263d224f3302e23d658e26 --- /dev/null +++ b/testbed/Textualize__textual/src/textual/css/scalar_animation.py @@ -0,0 +1,74 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING + +from .scalar import ScalarOffset +from .._animator import Animation +from .._animator import EasingFunction +from .._types import CallbackType +from ..geometry import Offset + +if TYPE_CHECKING: + from ..widget import Widget + from .styles import Styles + + +class ScalarAnimation(Animation): + def __init__( + self, + widget: Widget, + styles: Styles, + start_time: float, + attribute: str, + value: ScalarOffset, + duration: float | None, + speed: float | None, + easing: EasingFunction, + on_complete: CallbackType | None = None, + ): + assert ( + speed is not None or duration is not None + ), "One of speed or duration required" + self.widget = widget + self.styles = styles + self.start_time = start_time + self.attribute = attribute + self.final_value = value + self.easing = easing + self.on_complete = on_complete + + size = widget.outer_size + viewport = widget.app.size + + self.start: Offset = getattr(styles, attribute).resolve(size, viewport) + self.destination: Offset = value.resolve(size, viewport) + + if speed is not None: + distance = self.start.get_distance_to(self.destination) + self.duration = distance / speed + else: + assert duration is not None, "Duration expected to be non-None" + self.duration = duration + + def __call__(self, time: float) -> bool: + factor = min(1.0, (time - self.start_time) / self.duration) + eased_factor = self.easing(factor) + + if eased_factor >= 1: + setattr(self.styles, self.attribute, self.final_value) + return True + + offset = self.start + (self.destination - self.start) * eased_factor + current = self.styles._rules[self.attribute] + if current != offset: + setattr(self.styles, f"{self.attribute}", offset) + + return False + + def __eq__(self, other: object) -> bool: + if isinstance(other, ScalarAnimation): + return ( + self.final_value == other.final_value + and self.duration == other.duration + ) + return False diff --git a/testbed/Textualize__textual/src/textual/css/styles.py b/testbed/Textualize__textual/src/textual/css/styles.py new file mode 100644 index 0000000000000000000000000000000000000000..493913445fa318decf2e8b336a5bc6e7496a29b5 --- /dev/null +++ b/testbed/Textualize__textual/src/textual/css/styles.py @@ -0,0 +1,1058 @@ +from __future__ import annotations + +import sys +from abc import ABC, abstractmethod +from dataclasses import dataclass, field +from functools import lru_cache +from operator import attrgetter +from typing import TYPE_CHECKING, Any, Iterable, NamedTuple, cast + +import rich.repr +from rich.style import Style + +from .._types import CallbackType +from .._animator import BoundAnimator, DEFAULT_EASING, Animatable, EasingFunction +from ..color import Color +from ..geometry import Offset, Spacing +from ._style_properties import ( + AlignProperty, + BooleanProperty, + BorderProperty, + BoxProperty, + ColorProperty, + DockProperty, + FractionalProperty, + IntegerProperty, + LayoutProperty, + NameListProperty, + NameProperty, + OffsetProperty, + ScalarListProperty, + ScalarProperty, + SpacingProperty, + StringEnumProperty, + StyleFlagsProperty, + TransitionsProperty, +) +from .constants import ( + VALID_ALIGN_HORIZONTAL, + VALID_ALIGN_VERTICAL, + VALID_BOX_SIZING, + VALID_DISPLAY, + VALID_OVERFLOW, + VALID_SCROLLBAR_GUTTER, + VALID_VISIBILITY, + VALID_TEXT_ALIGN, +) +from .scalar import Scalar, ScalarOffset, Unit +from .scalar_animation import ScalarAnimation +from .transition import Transition +from .types import ( + AlignHorizontal, + AlignVertical, + BoxSizing, + Display, + Edge, + Overflow, + ScrollbarGutter, + Specificity3, + Specificity6, + Visibility, + TextAlign, +) + +if sys.version_info >= (3, 8): + from typing import TypedDict +else: + from typing_extensions import TypedDict + +if TYPE_CHECKING: + from .._animator import Animation + from .._layout import Layout + from ..dom import DOMNode + + +class RulesMap(TypedDict, total=False): + """A typed dict for CSS rules. + + Any key may be absent, indicating that rule has not been set. + + Does not define composite rules, that is a rule that is made of a combination of other rules. + """ + + display: Display + visibility: Visibility + layout: "Layout" + + auto_color: bool + color: Color + background: Color + text_style: Style + + opacity: float + text_opacity: float + + padding: Spacing + margin: Spacing + offset: ScalarOffset + + border_top: tuple[str, Color] + border_right: tuple[str, Color] + border_bottom: tuple[str, Color] + border_left: tuple[str, Color] + + outline_top: tuple[str, Color] + outline_right: tuple[str, Color] + outline_bottom: tuple[str, Color] + outline_left: tuple[str, Color] + + box_sizing: BoxSizing + width: Scalar + height: Scalar + min_width: Scalar + min_height: Scalar + max_width: Scalar + max_height: Scalar + + dock: str + + overflow_x: Overflow + overflow_y: Overflow + + layers: tuple[str, ...] + layer: str + + transitions: dict[str, Transition] + + tint: Color + + scrollbar_color: Color + scrollbar_color_hover: Color + scrollbar_color_active: Color + + scrollbar_corner_color: Color + + scrollbar_background: Color + scrollbar_background_hover: Color + scrollbar_background_active: Color + + scrollbar_gutter: ScrollbarGutter + + scrollbar_size_vertical: int + scrollbar_size_horizontal: int + + align_horizontal: AlignHorizontal + align_vertical: AlignVertical + + content_align_horizontal: AlignHorizontal + content_align_vertical: AlignVertical + + grid_size_rows: int + grid_size_columns: int + grid_gutter_horizontal: int + grid_gutter_vertical: int + grid_rows: tuple[Scalar, ...] + grid_columns: tuple[Scalar, ...] + + row_span: int + column_span: int + + text_align: TextAlign + + link_color: Color + auto_link_color: bool + link_background: Color + link_style: Style + + hover_color: Color + auto_hover_color: bool + hover_background: Color + hover_style: Style + + +RULE_NAMES = list(RulesMap.__annotations__.keys()) +RULE_NAMES_SET = frozenset(RULE_NAMES) +_rule_getter = attrgetter(*RULE_NAMES) + + +class DockGroup(NamedTuple): + name: str + edge: Edge + z: int + + +class StylesBase(ABC): + """A common base class for Styles and RenderStyles""" + + ANIMATABLE = { + "offset", + "padding", + "margin", + "width", + "height", + "min_width", + "min_height", + "max_width", + "max_height", + "auto_color", + "color", + "background", + "opacity", + "text_opacity", + "tint", + "scrollbar_color", + "scrollbar_color_hover", + "scrollbar_color_active", + "scrollbar_background", + "scrollbar_background_hover", + "scrollbar_background_active", + "link_color", + "link_background", + "hover_color", + "hover_background", + } + + node: DOMNode | None = None + + display = StringEnumProperty(VALID_DISPLAY, "block", layout=True) + visibility = StringEnumProperty(VALID_VISIBILITY, "visible") + layout = LayoutProperty() + + auto_color = BooleanProperty(default=False) + color = ColorProperty(Color(255, 255, 255)) + background = ColorProperty(Color(0, 0, 0, 0), background=True) + text_style = StyleFlagsProperty() + + opacity = FractionalProperty() + text_opacity = FractionalProperty() + + padding = SpacingProperty() + margin = SpacingProperty() + offset = OffsetProperty() + + border = BorderProperty(layout=True) + border_top = BoxProperty(Color(0, 255, 0)) + border_right = BoxProperty(Color(0, 255, 0)) + border_bottom = BoxProperty(Color(0, 255, 0)) + border_left = BoxProperty(Color(0, 255, 0)) + + outline = BorderProperty(layout=False) + outline_top = BoxProperty(Color(0, 255, 0)) + outline_right = BoxProperty(Color(0, 255, 0)) + outline_bottom = BoxProperty(Color(0, 255, 0)) + outline_left = BoxProperty(Color(0, 255, 0)) + + box_sizing = StringEnumProperty(VALID_BOX_SIZING, "border-box", layout=True) + width = ScalarProperty(percent_unit=Unit.WIDTH) + height = ScalarProperty(percent_unit=Unit.HEIGHT) + min_width = ScalarProperty(percent_unit=Unit.WIDTH, allow_auto=False) + min_height = ScalarProperty(percent_unit=Unit.HEIGHT, allow_auto=False) + max_width = ScalarProperty(percent_unit=Unit.WIDTH, allow_auto=False) + max_height = ScalarProperty(percent_unit=Unit.HEIGHT, allow_auto=False) + + dock = DockProperty() + + overflow_x = StringEnumProperty(VALID_OVERFLOW, "hidden") + overflow_y = StringEnumProperty(VALID_OVERFLOW, "hidden") + + layer = NameProperty() + layers = NameListProperty() + transitions = TransitionsProperty() + + tint = ColorProperty("transparent") + scrollbar_color = ColorProperty("ansi_bright_magenta") + scrollbar_color_hover = ColorProperty("ansi_yellow") + scrollbar_color_active = ColorProperty("ansi_bright_yellow") + + scrollbar_corner_color = ColorProperty("#666666") + + scrollbar_background = ColorProperty("#555555") + scrollbar_background_hover = ColorProperty("#444444") + scrollbar_background_active = ColorProperty("black") + + scrollbar_gutter = StringEnumProperty(VALID_SCROLLBAR_GUTTER, "auto") + + scrollbar_size_vertical = IntegerProperty(default=1, layout=True) + scrollbar_size_horizontal = IntegerProperty(default=1, layout=True) + + align_horizontal = StringEnumProperty(VALID_ALIGN_HORIZONTAL, "left") + align_vertical = StringEnumProperty(VALID_ALIGN_VERTICAL, "top") + align = AlignProperty() + + content_align_horizontal = StringEnumProperty(VALID_ALIGN_HORIZONTAL, "left") + content_align_vertical = StringEnumProperty(VALID_ALIGN_VERTICAL, "top") + content_align = AlignProperty() + + grid_rows = ScalarListProperty() + grid_columns = ScalarListProperty() + + grid_size_columns = IntegerProperty(default=1, layout=True) + grid_size_rows = IntegerProperty(default=0, layout=True) + grid_gutter_horizontal = IntegerProperty(default=0, layout=True) + grid_gutter_vertical = IntegerProperty(default=0, layout=True) + + row_span = IntegerProperty(default=1, layout=True) + column_span = IntegerProperty(default=1, layout=True) + + text_align = StringEnumProperty(VALID_TEXT_ALIGN, "start") + + link_color = ColorProperty("transparent") + auto_link_color = BooleanProperty(False) + link_background = ColorProperty("transparent") + link_style = StyleFlagsProperty() + + hover_color = ColorProperty("transparent") + auto_hover_color = BooleanProperty(False) + hover_background = ColorProperty("transparent") + hover_style = StyleFlagsProperty() + + def __eq__(self, styles: object) -> bool: + """Check that Styles contains the same rules.""" + if not isinstance(styles, StylesBase): + return NotImplemented + return self.get_rules() == styles.get_rules() + + @property + def gutter(self) -> Spacing: + """Get space around widget. + + Returns: + Spacing: Space around widget content. + """ + spacing = self.padding + self.border.spacing + return spacing + + @property + def auto_dimensions(self) -> bool: + """Check if width or height are set to 'auto'.""" + has_rule = self.has_rule + return (has_rule("width") and self.width.is_auto) or ( + has_rule("height") and self.height.is_auto + ) + + @abstractmethod + def has_rule(self, rule: str) -> bool: + """Check if a rule is set on this Styles object. + + Args: + rule (str): Rule name. + + Returns: + bool: ``True`` if the rules is present, otherwise ``False``. + """ + + @abstractmethod + def clear_rule(self, rule: str) -> bool: + """Removes the rule from the Styles object, as if it had never been set. + + Args: + rule (str): Rule name. + + Returns: + bool: ``True`` if a rule was cleared, or ``False`` if the rule is already not set. + """ + + @abstractmethod + def get_rules(self) -> RulesMap: + """Get the rules in a mapping. + + Returns: + RulesMap: A TypedDict of the rules. + """ + + @abstractmethod + def set_rule(self, rule: str, value: object | None) -> bool: + """Set a rule. + + Args: + rule (str): Rule name. + value (object | None): New rule value. + + Returns: + bool: ``True`` if the rule changed, otherwise ``False``. + """ + + @abstractmethod + def get_rule(self, rule: str, default: object = None) -> object: + """Get an individual rule. + + Args: + rule (str): Name of rule. + default (object, optional): Default if rule does not exists. Defaults to None. + + Returns: + object: Rule value or default. + """ + + @abstractmethod + def refresh(self, *, layout: bool = False, children: bool = False) -> None: + """Mark the styles as requiring a refresh. + + Args: + layout (bool, optional): Also require a layout. Defaults to False. + children (bool, opional): Also refresh children. Defaults to False. + """ + + @abstractmethod + def reset(self) -> None: + """Reset the rules to initial state.""" + + @abstractmethod + def merge(self, other: StylesBase) -> None: + """Merge values from another Styles. + + Args: + other (Styles): A Styles object. + """ + + @abstractmethod + def merge_rules(self, rules: RulesMap) -> None: + """Merge rules in to Styles. + + Args: + rules (RulesMap): A mapping of rules. + """ + + def get_render_rules(self) -> RulesMap: + """Get rules map with defaults.""" + # Get a dictionary of rules, going through the properties + rules = dict(zip(RULE_NAMES, _rule_getter(self))) + return cast(RulesMap, rules) + + @classmethod + def is_animatable(cls, rule: str) -> bool: + """Check if a given rule may be animated. + + Args: + rule (str): Name of the rule. + + Returns: + bool: ``True`` if the rule may be animated, otherwise ``False``. + """ + return rule in cls.ANIMATABLE + + @classmethod + @lru_cache(maxsize=1024) + def parse(cls, css: str, path: str, *, node: DOMNode = None) -> Styles: + """Parse CSS and return a Styles object. + + Args: + css (str): Textual CSS. + path (str): Path or string indicating source of CSS. + node (DOMNode, optional): Node to associate with the Styles. Defaults to None. + + Returns: + Styles: A Styles instance containing result of parsing CSS. + """ + from .parse import parse_declarations + + styles = parse_declarations(css, path) + styles.node = node + return styles + + def _get_transition(self, key: str) -> Transition | None: + """Get a transition. + + Args: + key (str): Transition key. + + Returns: + Transition | None: Transition object or None it no transition exists. + """ + if key in self.ANIMATABLE: + return self.transitions.get(key, None) + else: + return None + + def _align_width(self, width: int, parent_width: int) -> int: + """Align the width dimension. + + Args: + width (int): Width of the content. + parent_width (int): Width of the parent container. + + Returns: + int: An offset to add to the X coordinate. + """ + offset_x = 0 + align_horizontal = self.align_horizontal + if align_horizontal != "left": + if align_horizontal == "center": + offset_x = (parent_width - width) // 2 + else: + offset_x = parent_width - width + return offset_x + + def _align_height(self, height: int, parent_height: int) -> int: + """Align the height dimensions + + Args: + height (int): Height of the content. + parent_height (int): Height of the parent container. + + Returns: + int: An offset to add to the Y coordinate. + """ + offset_y = 0 + align_vertical = self.align_vertical + if align_vertical != "top": + if align_vertical == "middle": + offset_y = (parent_height - height) // 2 + else: + offset_y = parent_height - height + return offset_y + + def _align_size(self, child: tuple[int, int], parent: tuple[int, int]) -> Offset: + """Align a size according to alignment rules. + + Args: + child (tuple[int, int]): The size of the child (width, height) + parent (tuple[int, int]): The size of the parent (width, height) + + Returns: + Offset: Offset required to align the child. + """ + width, height = child + parent_width, parent_height = parent + return Offset( + self._align_width(width, parent_width), + self._align_height(height, parent_height), + ) + + +@rich.repr.auto +@dataclass +class Styles(StylesBase): + node: DOMNode | None = None + _rules: RulesMap = field(default_factory=dict) + + important: set[str] = field(default_factory=set) + + def copy(self) -> Styles: + """Get a copy of this Styles object.""" + return Styles(node=self.node, _rules=self.get_rules(), important=self.important) + + def has_rule(self, rule: str) -> bool: + assert rule in RULE_NAMES_SET, f"no such rule {rule!r}" + return rule in self._rules + + def clear_rule(self, rule: str) -> bool: + """Removes the rule from the Styles object, as if it had never been set. + + Args: + rule (str): Rule name. + + Returns: + bool: ``True`` if a rule was cleared, or ``False`` if it was already not set. + """ + return self._rules.pop(rule, None) is not None + + def get_rules(self) -> RulesMap: + return self._rules.copy() + + def set_rule(self, rule: str, value: object | None) -> bool: + """Set a rule. + + Args: + rule (str): Rule name. + value (object | None): New rule value. + + Returns: + bool: ``True`` if the rule changed, otherwise ``False``. + """ + if value is None: + return self._rules.pop(rule, None) is not None + else: + current = self._rules.get(rule) + self._rules[rule] = value + return current != value + + def get_rule(self, rule: str, default: object = None) -> object: + return self._rules.get(rule, default) + + def refresh(self, *, layout: bool = False, children: bool = False) -> None: + if self.node is not None: + self.node.refresh(layout=layout) + if children: + for child in self.node.walk_children(with_self=False): + child.refresh(layout=layout) + + def reset(self) -> None: + """Reset the rules to initial state.""" + self._rules.clear() + + def merge(self, other: Styles) -> None: + """Merge values from another Styles. + + Args: + other (Styles): A Styles object. + """ + + self._rules.update(other._rules) + + def merge_rules(self, rules: RulesMap) -> None: + self._rules.update(rules) + + def extract_rules( + self, + specificity: Specificity3, + is_default_rules: bool = False, + tie_breaker: int = 0, + ) -> list[tuple[str, Specificity6, Any]]: + """Extract rules from Styles object, and apply !important css specificity as + well as higher specificity of user CSS vs widget CSS. + + Args: + specificity (Specificity3): A node specificity. + is_default_rules (bool): True if the rules we're extracting are + default (i.e. in Widget.DEFAULT_CSS) rules. False if they're from user defined CSS. + + Returns: + list[tuple[str, Specificity5, Any]]]: A list containing a tuple of , . + """ + is_important = self.important.__contains__ + + rules = [ + ( + rule_name, + ( + 0 if is_default_rules else 1, + 1 if is_important(rule_name) else 0, + *specificity, + tie_breaker, + ), + rule_value, + ) + for rule_name, rule_value in self._rules.items() + ] + return rules + + def __rich_repr__(self) -> rich.repr.Result: + has_rule = self.has_rule + for name in RULE_NAMES: + if has_rule(name): + yield name, getattr(self, name) + if self.important: + yield "important", self.important + + def __textual_animation__( + self, + attribute: str, + value: Any, + start_time: float, + duration: float | None, + speed: float | None, + easing: EasingFunction, + on_complete: CallbackType | None = None, + ) -> ScalarAnimation | None: + # from ..widget import Widget + # node = self.node + # assert isinstance(self.node, Widget) + if isinstance(value, ScalarOffset): + return ScalarAnimation( + self.node, + self, + start_time, + attribute, + value, + duration=duration, + speed=speed, + easing=easing, + on_complete=on_complete, + ) + return None + + def _get_border_css_lines( + self, rules: RulesMap, name: str + ) -> Iterable[tuple[str, str]]: + """Get pairs of strings containing , for border css declarations. + + Args: + rules (RulesMap): A rules map. + name (str): Name of rules (border or outline) + + Returns: + Iterable[tuple[str, str]]: An iterable of CSS declarations. + + """ + + has_rule = rules.__contains__ + get_rule = rules.__getitem__ + + has_top = has_rule(f"{name}_top") + has_right = has_rule(f"{name}_right") + has_bottom = has_rule(f"{name}_bottom") + has_left = has_rule(f"{name}_left") + if not any((has_top, has_right, has_bottom, has_left)): + # No border related rules + return + + if all((has_top, has_right, has_bottom, has_left)): + # All rules are set + # See if we can set them with a single border: declaration + top = get_rule(f"{name}_top") + right = get_rule(f"{name}_right") + bottom = get_rule(f"{name}_bottom") + left = get_rule(f"{name}_left") + + if top == right and right == bottom and bottom == left: + border_type, border_color = rules[f"{name}_top"] + yield name, f"{border_type} {border_color.hex}" + return + + # Check for edges + if has_top: + border_type, border_color = rules[f"{name}_top"] + yield f"{name}-top", f"{border_type} {border_color.hex}" + + if has_right: + border_type, border_color = rules[f"{name}_right"] + yield f"{name}-right", f"{border_type} {border_color.hex}" + + if has_bottom: + border_type, border_color = rules[f"{name}_bottom"] + yield f"{name}-bottom", f"{border_type} {border_color.hex}" + + if has_left: + border_type, border_color = rules[f"{name}_left"] + yield f"{name}-left", f"{border_type} {border_color.hex}" + + @property + def css_lines(self) -> list[str]: + lines: list[str] = [] + append = lines.append + + def append_declaration(name: str, value: str) -> None: + if name in self.important: + append(f"{name}: {value} !important;") + else: + append(f"{name}: {value};") + + rules = self.get_rules() + get_rule = rules.get + has_rule = rules.__contains__ + + if has_rule("display"): + append_declaration("display", rules["display"]) + if has_rule("visibility"): + append_declaration("visibility", rules["visibility"]) + if has_rule("padding"): + append_declaration("padding", rules["padding"].css) + if has_rule("margin"): + append_declaration("margin", rules["margin"].css) + + for name, rule in self._get_border_css_lines(rules, "border"): + append_declaration(name, rule) + + for name, rule in self._get_border_css_lines(rules, "outline"): + append_declaration(name, rule) + + if has_rule("offset"): + x, y = self.offset + append_declaration("offset", f"{x} {y}") + if has_rule("dock"): + append_declaration("dock", rules["dock"]) + if has_rule("layers"): + append_declaration("layers", " ".join(self.layers)) + if has_rule("layer"): + append_declaration("layer", self.layer) + if has_rule("layout"): + assert self.layout is not None + append_declaration("layout", self.layout.name) + + if has_rule("color"): + append_declaration("color", self.color.hex) + if has_rule("background"): + append_declaration("background", self.background.hex) + if has_rule("text_style"): + append_declaration("text-style", str(get_rule("text_style"))) + if has_rule("tint"): + append_declaration("tint", self.tint.css) + + if has_rule("overflow_x"): + append_declaration("overflow-x", self.overflow_x) + if has_rule("overflow_y"): + append_declaration("overflow-y", self.overflow_y) + + if has_rule("scrollbar_color"): + append_declaration("scrollbar-color", self.scrollbar_color.css) + if has_rule("scrollbar_color_hover"): + append_declaration("scrollbar-color-hover", self.scrollbar_color_hover.css) + if has_rule("scrollbar_color_active"): + append_declaration( + "scrollbar-color-active", self.scrollbar_color_active.css + ) + + if has_rule("scrollbar_corner_color"): + append_declaration( + "scrollbar-corner-color", self.scrollbar_corner_color.css + ) + + if has_rule("scrollbar_background"): + append_declaration("scrollbar-background", self.scrollbar_background.css) + if has_rule("scrollbar_background_hover"): + append_declaration( + "scrollbar-background-hover", self.scrollbar_background_hover.css + ) + if has_rule("scrollbar_background_active"): + append_declaration( + "scrollbar-background-active", self.scrollbar_background_active.css + ) + + if has_rule("scrollbar_gutter"): + append_declaration("scrollbar-gutter", self.scrollbar_gutter) + if has_rule("scrollbar_size"): + append_declaration( + "scrollbar-size", + f"{self.scrollbar_size_horizontal} {self.scrollbar_size_vertical}", + ) + else: + if has_rule("scrollbar_size_horizontal"): + append_declaration( + "scrollbar-size-horizontal", str(self.scrollbar_size_horizontal) + ) + if has_rule("scrollbar_size_vertical"): + append_declaration( + "scrollbar-size-vertical", str(self.scrollbar_size_vertical) + ) + + if has_rule("box_sizing"): + append_declaration("box-sizing", self.box_sizing) + if has_rule("width"): + append_declaration("width", str(self.width)) + if has_rule("height"): + append_declaration("height", str(self.height)) + if has_rule("min_width"): + append_declaration("min-width", str(self.min_width)) + if has_rule("min_height"): + append_declaration("min-height", str(self.min_height)) + if has_rule("max_width"): + append_declaration("max-width", str(self.min_width)) + if has_rule("max_height"): + append_declaration("max-height", str(self.min_height)) + if has_rule("transitions"): + append_declaration( + "transition", + ", ".join( + f"{name} {transition}" + for name, transition in self.transitions.items() + ), + ) + + if has_rule("align_horizontal") and has_rule("align_vertical"): + append_declaration( + "align", f"{self.align_horizontal} {self.align_vertical}" + ) + elif has_rule("align_horizontal"): + append_declaration("align-horizontal", self.align_horizontal) + elif has_rule("align_vertical"): + append_declaration("align-vertical", self.align_vertical) + + if has_rule("content_align_horizontal") and has_rule("content_align_vertical"): + append_declaration( + "content-align", + f"{self.content_align_horizontal} {self.content_align_vertical}", + ) + elif has_rule("content_align_horizontal"): + append_declaration( + "content-align-horizontal", self.content_align_horizontal + ) + elif has_rule("content_align_vertical"): + append_declaration("content-align-vertical", self.content_align_vertical) + + if has_rule("text_align"): + append_declaration("text-align", self.text_align) + + if has_rule("opacity"): + append_declaration("opacity", str(self.opacity)) + if has_rule("text_opacity"): + append_declaration("text-opacity", str(self.text_opacity)) + + if has_rule("grid_columns"): + append_declaration( + "grid-columns", + " ".join(str(scalar) for scalar in self.grid_columns or ()), + ) + if has_rule("grid_rows"): + append_declaration( + "grid-rows", + " ".join(str(scalar) for scalar in self.grid_rows or ()), + ) + if has_rule("grid_size_columns"): + append_declaration("grid-size-columns", str(self.grid_size_columns)) + if has_rule("grid_size_rows"): + append_declaration("grid-size-rows", str(self.grid_size_rows)) + + if has_rule("grid_gutter_horizontal"): + append_declaration( + "grid-gutter-horizontal", str(self.grid_gutter_horizontal) + ) + if has_rule("grid_gutter_vertical"): + append_declaration("grid-gutter-vertical", str(self.grid_gutter_vertical)) + + if has_rule("row_span"): + append_declaration("row-span", str(self.row_span)) + if has_rule("column_span"): + append_declaration("column-span", str(self.column_span)) + + if has_rule("link_color"): + append_declaration("link-color", self.link_color.css) + if has_rule("link_background"): + append_declaration("link-background", self.link_background.css) + if has_rule("link_style"): + append_declaration("link-style", str(self.link_style)) + + if has_rule("hover_color"): + append_declaration("hover-color", self.hover_color.css) + if has_rule("hover_background"): + append_declaration("hover-background", self.hover_background.css) + if has_rule("hover_style"): + append_declaration("hover-style", str(self.hover_style)) + + lines.sort() + return lines + + @property + def css(self) -> str: + return "\n".join(self.css_lines) + + +@rich.repr.auto +class RenderStyles(StylesBase): + """Presents a combined view of two Styles object: a base Styles and inline Styles.""" + + def __init__(self, node: DOMNode, base: Styles, inline_styles: Styles) -> None: + self.node = node + self._base_styles = base + self._inline_styles = inline_styles + self._animate: BoundAnimator | None = None + + @property + def base(self) -> Styles: + """Quick access to base (css) style.""" + return self._base_styles + + @property + def inline(self) -> Styles: + """Quick access to the inline styles.""" + return self._inline_styles + + @property + def rich_style(self) -> Style: + """Get a Rich style for this Styles object.""" + assert self.node is not None + return self.node.rich_style + + def animate( + self, + attribute: str, + value: float | Animatable, + *, + final_value: object = ..., + duration: float | None = None, + speed: float | None = None, + delay: float = 0.0, + easing: EasingFunction | str = DEFAULT_EASING, + on_complete: CallbackType | None = None, + ) -> None: + """Animate an attribute. + + Args: + attribute (str): Name of the attribute to animate. + value (float | Animatable): The value to animate to. + final_value (object, optional): The final value of the animation. Defaults to `value` if not set. + duration (float | None, optional): The duration of the animate. Defaults to None. + speed (float | None, optional): The speed of the animation. Defaults to None. + delay (float, optional): A delay (in seconds) before the animation starts. Defaults to 0.0. + easing (EasingFunction | str, optional): An easing method. Defaults to "in_out_cubic". + on_complete (CallbackType | None, optional): A callable to invoke when the animation is finished. Defaults to None. + + """ + if self._animate is None: + self._animate = self.node.app.animator.bind(self) + assert self._animate is not None + self._animate( + attribute, + value, + final_value=final_value, + duration=duration, + speed=speed, + delay=delay, + easing=easing, + on_complete=on_complete, + ) + + def __rich_repr__(self) -> rich.repr.Result: + for rule_name in RULE_NAMES: + if self.has_rule(rule_name): + yield rule_name, getattr(self, rule_name) + + def refresh(self, *, layout: bool = False, children: bool = False) -> None: + self._inline_styles.refresh(layout=layout, children=children) + + def merge(self, other: Styles) -> None: + """Merge values from another Styles. + + Args: + other (Styles): A Styles object. + """ + self._inline_styles.merge(other) + + def merge_rules(self, rules: RulesMap) -> None: + self._inline_styles.merge_rules(rules) + + def reset(self) -> None: + """Reset the rules to initial state.""" + self._inline_styles.reset() + + def has_rule(self, rule: str) -> bool: + """Check if a rule has been set.""" + return self._inline_styles.has_rule(rule) or self._base_styles.has_rule(rule) + + def set_rule(self, rule: str, value: object | None) -> bool: + return self._inline_styles.set_rule(rule, value) + + def get_rule(self, rule: str, default: object = None) -> object: + if self._inline_styles.has_rule(rule): + return self._inline_styles.get_rule(rule, default) + return self._base_styles.get_rule(rule, default) + + def clear_rule(self, rule_name: str) -> bool: + """Clear a rule (from inline).""" + return self._inline_styles.clear_rule(rule_name) + + def get_rules(self) -> RulesMap: + """Get rules as a dictionary""" + rules = {**self._base_styles._rules, **self._inline_styles._rules} + return cast(RulesMap, rules) + + @property + def css(self) -> str: + """Get the CSS for the combined styles.""" + styles = Styles() + styles.merge(self._base_styles) + styles.merge(self._inline_styles) + combined_css = styles.css + return combined_css + + +if __name__ == "__main__": + styles = Styles() + + styles.display = "none" + styles.visibility = "hidden" + styles.border = ("solid", "rgb(10,20,30)") + styles.outline_right = ("solid", "red") + styles.text_style = "italic" + styles.dock = "bar" + styles.layers = "foo bar" + + from rich import print + + print(styles.text_style) + print(styles.text) + + print(styles) + print(styles.css) + + print(styles.extract_rules((0, 1, 0))) diff --git a/testbed/Textualize__textual/src/textual/css/stylesheet.py b/testbed/Textualize__textual/src/textual/css/stylesheet.py new file mode 100644 index 0000000000000000000000000000000000000000..d3b8efd49c9076d83feac7161140834d53b73b6e --- /dev/null +++ b/testbed/Textualize__textual/src/textual/css/stylesheet.py @@ -0,0 +1,509 @@ +from __future__ import annotations + +import os +from collections import defaultdict +from operator import itemgetter +from pathlib import Path, PurePath +from typing import Iterable, NamedTuple, cast + +import rich.repr +from rich.console import Console, ConsoleOptions, RenderableType, RenderResult +from rich.markup import render +from rich.padding import Padding +from rich.panel import Panel +from rich.style import Style +from rich.syntax import Syntax +from rich.text import Text + +from .. import messages +from .._profile import timer +from ..dom import DOMNode +from ..widget import Widget +from .errors import StylesheetError +from .match import _check_selectors +from .model import RuleSet +from .parse import parse +from .styles import RulesMap, Styles +from .tokenize import Token, tokenize_values +from .tokenizer import TokenError +from .types import Specificity3, Specificity6 + + +class StylesheetParseError(StylesheetError): + def __init__(self, errors: StylesheetErrors) -> None: + self.errors = errors + + def __rich__(self) -> RenderableType: + return self.errors + + +class StylesheetErrors: + def __init__(self, rules: list[RuleSet]) -> None: + self.rules = rules + self.variables: dict[str, str] = {} + + @classmethod + def _get_snippet(cls, code: str, line_no: int) -> RenderableType: + syntax = Syntax( + code, + lexer="scss", + theme="ansi_light", + line_numbers=True, + indent_guides=True, + line_range=(max(0, line_no - 2), line_no + 2), + highlight_lines={line_no}, + ) + return syntax + + def __rich_console__( + self, console: Console, options: ConsoleOptions + ) -> RenderResult: + error_count = 0 + for rule in self.rules: + for token, message in rule.errors: + error_count += 1 + + if token.path: + path = Path(token.path) + filename = path.name + else: + path = None + filename = "" + + if token.referenced_by: + line_idx, col_idx = token.referenced_by.location + line_no, col_no = line_idx + 1, col_idx + 1 + path_string = ( + f"{path.absolute() if path else filename}:{line_no}:{col_no}" + ) + else: + line_idx, col_idx = token.location + line_no, col_no = line_idx + 1, col_idx + 1 + path_string = ( + f"{path.absolute() if path else filename}:{line_no}:{col_no}" + ) + + link_style = Style( + link=f"file://{path.absolute()}", + color="red", + bold=True, + italic=True, + ) + + path_text = Text(path_string, style=link_style) + title = Text.assemble(Text("Error at ", style="bold red"), path_text) + yield "" + yield Panel( + self._get_snippet( + token.referenced_by.code if token.referenced_by else token.code, + line_no, + ), + title=title, + title_align="left", + border_style="red", + ) + yield Padding(message, pad=(0, 0, 1, 3)) + + yield "" + yield render( + f" [b][red]CSS parsing failed:[/] {error_count} error{'s' if error_count != 1 else ''}[/] found in stylesheet" + ) + + +class CssSource(NamedTuple): + """Contains the CSS content and whether or not the CSS comes from user defined stylesheets + vs widget-level stylesheets. + + Args: + content (str): The CSS as a string. + is_defaults (bool): True if the CSS is default (i.e. that defined at the widget level). + False if it's user CSS (which will override the defaults). + """ + + content: str + is_defaults: bool + tie_breaker: int = 0 + + +@rich.repr.auto(angular=True) +class Stylesheet: + def __init__(self, *, variables: dict[str, str] | None = None) -> None: + self._rules: list[RuleSet] = [] + self._rules_map: dict[str, list[RuleSet]] | None = None + self._variables = variables or {} + self.__variable_tokens: dict[str, list[Token]] | None = None + self.source: dict[str, CssSource] = {} + self._require_parse = False + + def __rich_repr__(self) -> rich.repr.Result: + yield list(self.source.keys()) + + @property + def _variable_tokens(self) -> dict[str, list[Token]]: + if self.__variable_tokens is None: + self.__variable_tokens = tokenize_values(self._variables) + return self.__variable_tokens + + @property + def rules(self) -> list[RuleSet]: + """List of rule sets. + + Returns: + list[RuleSet]: List of rules sets for this stylesheet. + """ + if self._require_parse: + self.parse() + self._require_parse = False + assert self._rules is not None + return self._rules + + @property + def rules_map(self) -> dict[str, list[RuleSet]]: + """Structure that maps a selector on to a list of rules. + + Returns: + dict[str, list[RuleSet]]: Mapping of selector to rule sets. + """ + if self._rules_map is None: + rules_map: dict[str, list[RuleSet]] = defaultdict(list) + for rule in self.rules: + for name in rule.selector_names: + rules_map[name].append(rule) + self._rules_map = dict(rules_map) + return self._rules_map + + @property + def css(self) -> str: + return "\n\n".join(rule_set.css for rule_set in self.rules) + + def copy(self) -> Stylesheet: + """Create a copy of this stylesheet. + + Returns: + Stylesheet: New stylesheet. + """ + stylesheet = Stylesheet(variables=self._variables.copy()) + stylesheet.source = self.source.copy() + return stylesheet + + def set_variables(self, variables: dict[str, str]) -> None: + """Set CSS variables. + + Args: + variables (dict[str, str]): A mapping of name to variable. + """ + self._variables = variables + self._variables_tokens = None + + def _parse_rules( + self, + css: str, + path: str | PurePath, + is_default_rules: bool = False, + tie_breaker: int = 0, + ) -> list[RuleSet]: + """Parse CSS and return rules. + + Args: + is_default_rules: + css (str): String containing Textual CSS. + path (str | PurePath): Path to CSS or unique identifier + is_default_rules (bool): True if the rules we're extracting are + default (i.e. in Widget.DEFAULT_CSS) rules. False if they're from user defined CSS. + + Raises: + StylesheetError: If the CSS is invalid. + + Returns: + list[RuleSet]: List of RuleSets. + """ + try: + rules = list( + parse( + css, + path, + variable_tokens=self._variable_tokens, + is_default_rules=is_default_rules, + tie_breaker=tie_breaker, + ) + ) + except TokenError: + raise + except Exception as error: + raise StylesheetError(f"failed to parse css; {error}") + + return rules + + def read(self, filename: str | PurePath) -> None: + """Read Textual CSS file. + + Args: + filename (str | PurePath): filename of CSS. + + Raises: + StylesheetError: If the CSS could not be read. + StylesheetParseError: If the CSS is invalid. + """ + filename = os.path.expanduser(filename) + try: + with open(filename, "rt") as css_file: + css = css_file.read() + path = os.path.abspath(filename) + except Exception as error: + raise StylesheetError(f"unable to read {filename!r}; {error}") + self.source[str(path)] = CssSource(css, False, 0) + self._require_parse = True + + def add_source( + self, + css: str, + path: str | PurePath | None = None, + is_default_css: bool = False, + tie_breaker: int = 0, + ) -> None: + """Parse CSS from a string. + + Args: + css (str): String with CSS source. + path (str | PurePath, optional): The path of the source if a file, or some other identifier. + Defaults to None. + is_default_css (bool): True if the CSS is defined in the Widget, False if the CSS is defined + in a user stylesheet. + + Raises: + StylesheetError: If the CSS could not be read. + StylesheetParseError: If the CSS is invalid. + """ + + if path is None: + path = str(hash(css)) + elif isinstance(path, PurePath): + path = str(css) + if path in self.source and self.source[path].content == css: + # Path already in source, and CSS is identical + content, is_defaults, source_tie_breaker = self.source[path] + if source_tie_breaker > tie_breaker: + self.source[path] = CssSource(content, is_defaults, tie_breaker) + return + self.source[path] = CssSource(css, is_default_css, tie_breaker) + self._require_parse = True + + def parse(self) -> None: + """Parse the source in the stylesheet. + + Raises: + StylesheetParseError: If there are any CSS related errors. + """ + rules: list[RuleSet] = [] + add_rules = rules.extend + for path, (css, is_default_rules, tie_breaker) in self.source.items(): + css_rules = self._parse_rules( + css, path, is_default_rules=is_default_rules, tie_breaker=tie_breaker + ) + if any(rule.errors for rule in css_rules): + error_renderable = StylesheetErrors(css_rules) + raise StylesheetParseError(error_renderable) + add_rules(css_rules) + self._rules = rules + self._require_parse = False + self._rules_map = None + + def reparse(self) -> None: + """Re-parse source, applying new variables. + + Raises: + StylesheetError: If the CSS could not be read. + StylesheetParseError: If the CSS is invalid. + + """ + # Do this in a fresh Stylesheet so if there are errors we don't break self. + stylesheet = Stylesheet(variables=self._variables) + for path, (css, is_defaults, tie_breaker) in self.source.items(): + stylesheet.add_source( + css, path, is_default_css=is_defaults, tie_breaker=tie_breaker + ) + stylesheet.parse() + self._rules = stylesheet.rules + self._rules_map = None + self.source = stylesheet.source + + @classmethod + def _check_rule( + cls, rule: RuleSet, css_path_nodes: list[DOMNode] + ) -> Iterable[Specificity3]: + for selector_set in rule.selector_set: + if _check_selectors(selector_set.selectors, css_path_nodes): + yield selector_set.specificity + + def apply( + self, + node: DOMNode, + *, + limit_rules: set[RuleSet] | None = None, + animate: bool = False, + ) -> None: + """Apply the stylesheet to a DOM node. + + Args: + node (DOMNode): The ``DOMNode`` to apply the stylesheet to. + Applies the styles defined in this ``Stylesheet`` to the node. + If the same rule is defined multiple times for the node (e.g. multiple + classes modifying the same CSS property), then only the most specific + rule will be applied. + animate (bool, optional): Animate changed rules. Defaults to ``False``. + """ + # Dictionary of rule attribute names e.g. "text_background" to list of tuples. + # The tuples contain the rule specificity, and the value for that rule. + # We can use this to determine, for a given rule, whether we should apply it + # or not by examining the specificity. If we have two rules for the + # same attribute, then we can choose the most specific rule and use that. + rule_attributes: defaultdict[str, list[tuple[Specificity6, object]]] + rule_attributes = defaultdict(list) + + _check_rule = self._check_rule + css_path_nodes = node.css_path_nodes + + rules: Iterable[RuleSet] + if limit_rules: + rules = [rule for rule in reversed(self.rules) if rule in limit_rules] + else: + rules = reversed(self.rules) + # Collect the rules defined in the stylesheet + node._has_hover_style = False + for rule in rules: + is_default_rules = rule.is_default_rules + tie_breaker = rule.tie_breaker + if ":hover" in rule.selector_names: + node._has_hover_style = True + for base_specificity in _check_rule(rule, css_path_nodes): + for key, rule_specificity, value in rule.styles.extract_rules( + base_specificity, is_default_rules, tie_breaker + ): + rule_attributes[key].append((rule_specificity, value)) + + if not rule_attributes: + return + # For each rule declared for this node, keep only the most specific one + get_first_item = itemgetter(0) + node_rules: RulesMap = cast( + RulesMap, + { + name: max(specificity_rules, key=get_first_item)[1] + for name, specificity_rules in rule_attributes.items() + }, + ) + self.replace_rules(node, node_rules, animate=animate) + + node._component_styles.clear() + for component in node.COMPONENT_CLASSES: + virtual_node = DOMNode(classes=component) + virtual_node._attach(node) + self.apply(virtual_node, animate=False) + node._component_styles[component] = virtual_node.styles + + @classmethod + def replace_rules( + cls, node: DOMNode, rules: RulesMap, animate: bool = False + ) -> None: + """Replace style rules on a node, animating as required. + + Args: + node (DOMNode): A DOM node. + rules (RulesMap): Mapping of rules. + animate (bool, optional): Enable animation. Defaults to False. + """ + + # Alias styles and base styles + styles = node.styles + base_styles = styles.base + + # Styles currently used on new rules + modified_rule_keys = base_styles.get_rules().keys() | rules.keys() + # Current render rules (missing rules are filled with default) + current_render_rules = styles.get_render_rules() + + # Calculate replacement rules (defaults + new rules) + new_styles = Styles(node, rules) + + if new_styles == base_styles: + # Nothing to change, return early + return + + # New render rules + new_render_rules = new_styles.get_render_rules() + + # Some aliases + is_animatable = styles.is_animatable + get_current_render_rule = current_render_rules.get + get_new_render_rule = new_render_rules.get + + if animate: + for key in modified_rule_keys: + # Get old and new render rules + old_render_value = get_current_render_rule(key) + new_render_value = get_new_render_rule(key) + # Get new rule value (may be None) + new_value = rules.get(key) + + # Check if this can / should be animated + if is_animatable(key) and new_render_value != old_render_value: + transition = new_styles._get_transition(key) + if transition is not None: + duration, easing, delay = transition + node.app.animator.animate( + node.styles.base, + key, + new_render_value, + final_value=new_value, + duration=duration, + delay=delay, + easing=easing, + ) + continue + # Default is to set value (if new_value is None, rule will be removed) + setattr(base_styles, key, new_value) + else: + # Not animated, so we apply the rules directly + get_rule = rules.get + + for key in modified_rule_keys: + setattr(base_styles, key, get_rule(key)) + + node.post_message_no_wait(messages.StylesUpdated(sender=node)) + + def update(self, root: DOMNode, animate: bool = False) -> None: + """Update styles on node and its children. + + Args: + root (DOMNode): Root note to update. + animate (bool, optional): Enable CSS animation. Defaults to False. + """ + + self.update_nodes(root.walk_children(), animate=animate) + + def update_nodes(self, nodes: Iterable[DOMNode], animate: bool = False) -> None: + """Update styles for nodes. + + Args: + nodes (DOMNode): Nodes to update. + animate (bool, optional): Enable CSS animation. Defaults to False. + """ + + rules_map = self.rules_map + apply = self.apply + + for node in nodes: + rules = { + rule + for name in node._selector_names + if name in rules_map + for rule in rules_map[name] + } + apply(node, limit_rules=rules, animate=animate) + if isinstance(node, Widget) and node.is_scrollable: + if node.show_vertical_scrollbar: + apply(node.vertical_scrollbar) + if node.show_horizontal_scrollbar: + apply(node.horizontal_scrollbar) + if node.show_horizontal_scrollbar and node.show_vertical_scrollbar: + apply(node.scrollbar_corner) diff --git a/testbed/Textualize__textual/src/textual/css/tokenize.py b/testbed/Textualize__textual/src/textual/css/tokenize.py new file mode 100644 index 0000000000000000000000000000000000000000..dbec369dffaff01850efc7871444f19d878007ad --- /dev/null +++ b/testbed/Textualize__textual/src/textual/css/tokenize.py @@ -0,0 +1,214 @@ +from __future__ import annotations + +import re +from pathlib import PurePath +from typing import Iterable + +from textual.css.tokenizer import Expect, Tokenizer, Token + +PERCENT = r"-?\d+\.?\d*%" +DECIMAL = r"-?\d+\.?\d*" +COMMA = r"\s*,\s*" +OPEN_BRACE = r"\(\s*" +CLOSE_BRACE = r"\s*\)" + +HEX_COLOR = r"\#[0-9a-fA-F]{8}|\#[0-9a-fA-F]{6}|\#[0-9a-fA-F]{4}|\#[0-9a-fA-F]{3}" +RGB_COLOR = rf"rgb{OPEN_BRACE}{DECIMAL}{COMMA}{DECIMAL}{COMMA}{DECIMAL}{CLOSE_BRACE}|rgba{OPEN_BRACE}{DECIMAL}{COMMA}{DECIMAL}{COMMA}{DECIMAL}{COMMA}{DECIMAL}{CLOSE_BRACE}" +HSL_COLOR = rf"hsl{OPEN_BRACE}{DECIMAL}{COMMA}{PERCENT}{COMMA}{PERCENT}{CLOSE_BRACE}|hsla{OPEN_BRACE}{DECIMAL}{COMMA}{PERCENT}{COMMA}{PERCENT}{COMMA}{DECIMAL}{CLOSE_BRACE}" + +COMMENT_START = r"\/\*" +SCALAR = rf"{DECIMAL}(?:fr|%|w|h|vw|vh)" +DURATION = r"\d+\.?\d*(?:ms|s)" +NUMBER = r"\-?\d+\.?\d*" +COLOR = rf"{HEX_COLOR}|{RGB_COLOR}|{HSL_COLOR}" +KEY_VALUE = r"[a-zA-Z_-][a-zA-Z0-9_-]*=[0-9a-zA-Z_\-\/]+" +TOKEN = "[a-zA-Z][a-zA-Z0-9_-]*" +STRING = r"\".*?\"" +VARIABLE_REF = r"\$[a-zA-Z0-9_\-]+" + +IDENTIFIER = r"[a-zA-Z_\-][a-zA-Z0-9_\-]*" + +# Values permitted in variable and rule declarations. +DECLARATION_VALUES = { + "scalar": SCALAR, + "duration": DURATION, + "number": NUMBER, + "color": COLOR, + "key_value": KEY_VALUE, + "token": TOKEN, + "string": STRING, + "variable_ref": VARIABLE_REF, +} + +# The tokenizers "expectation" while at the root/highest level of scope +# in the CSS file. At this level we might expect to see selectors, comments, +# variable definitions etc. +expect_root_scope = Expect( + whitespace=r"\s+", + comment_start=COMMENT_START, + selector_start_id=r"\#" + IDENTIFIER, + selector_start_class=r"\." + IDENTIFIER, + selector_start_universal=r"\*", + selector_start=r"[a-zA-Z_\-]+", + variable_name=rf"{VARIABLE_REF}:", +).expect_eof(True) + +# After a variable declaration e.g. "$warning-text: TOKENS;" +# for tokenizing variable value ------^~~~~~~^ +expect_variable_name_continue = Expect( + variable_value_end=r"\n|;", + whitespace=r"\s+", + comment_start=COMMENT_START, + **DECLARATION_VALUES, +).expect_eof(True) + +expect_comment_end = Expect( + comment_end=re.escape("*/"), +) + +# After we come across a selector in CSS e.g. ".my-class", we may +# find other selectors, pseudo-classes... e.g. ".my-class :hover" +expect_selector_continue = Expect( + whitespace=r"\s+", + comment_start=COMMENT_START, + pseudo_class=r"\:[a-zA-Z_-]+", + selector_id=r"\#[a-zA-Z_\-][a-zA-Z0-9_\-]*", + selector_class=r"\.[a-zA-Z_\-][a-zA-Z0-9_\-]*", + selector_universal=r"\*", + selector=r"[a-zA-Z_\-]+", + combinator_child=">", + new_selector=r",", + declaration_set_start=r"\{", +) + +# A rule declaration e.g. "text: red;" +# ^---^ +expect_declaration = Expect( + whitespace=r"\s+", + comment_start=COMMENT_START, + declaration_name=r"[a-zA-Z_\-]+\:", + declaration_set_end=r"\}", +) + +expect_declaration_solo = Expect( + whitespace=r"\s+", + comment_start=COMMENT_START, + declaration_name=r"[a-zA-Z_\-]+\:", + declaration_set_end=r"\}", +).expect_eof(True) + +# The value(s)/content from a rule declaration e.g. "text: red;" +# ^---^ +expect_declaration_content = Expect( + declaration_end=r";", + whitespace=r"\s+", + comment_start=COMMENT_START, + **DECLARATION_VALUES, + important=r"\!important", + comma=",", + declaration_set_end=r"\}", +) + +expect_declaration_content_solo = Expect( + declaration_end=r";", + whitespace=r"\s+", + comment_start=COMMENT_START, + **DECLARATION_VALUES, + important=r"\!important", + comma=",", + declaration_set_end=r"\}", +).expect_eof(True) + + +class TokenizerState: + """State machine for the tokenizer. + + Attributes: + EXPECT: The initial expectation of the tokenizer. Since we start tokenizing + at the root scope, we might expect to see either a variable or selector, for example. + STATE_MAP: Maps token names to Expects, defines the sets of valid tokens + that we'd expect to see next, given the current token. For example, if + we've just processed a variable declaration name, we next expect to see + the value of that variable. + """ + + EXPECT = expect_root_scope + STATE_MAP = { + "variable_name": expect_variable_name_continue, + "variable_value_end": expect_root_scope, + "selector_start": expect_selector_continue, + "selector_start_id": expect_selector_continue, + "selector_start_class": expect_selector_continue, + "selector_start_universal": expect_selector_continue, + "selector_id": expect_selector_continue, + "selector_class": expect_selector_continue, + "selector_universal": expect_selector_continue, + "declaration_set_start": expect_declaration, + "declaration_name": expect_declaration_content, + "declaration_end": expect_declaration, + "declaration_set_end": expect_root_scope, + } + + def __call__(self, code: str, path: str | PurePath) -> Iterable[Token]: + tokenizer = Tokenizer(code, path=path) + expect = self.EXPECT + get_token = tokenizer.get_token + get_state = self.STATE_MAP.get + while True: + token = get_token(expect) + name = token.name + if name == "comment_start": + tokenizer.skip_to(expect_comment_end) + continue + elif name == "eof": + break + expect = get_state(name, expect) + yield token + + +class DeclarationTokenizerState(TokenizerState): + EXPECT = expect_declaration_solo + STATE_MAP = { + "declaration_name": expect_declaration_content, + "declaration_end": expect_declaration_solo, + } + + +class ValueTokenizerState(TokenizerState): + EXPECT = expect_declaration_content_solo + + +tokenize = TokenizerState() +tokenize_declarations = DeclarationTokenizerState() +tokenize_value = ValueTokenizerState() + + +def tokenize_values(values: dict[str, str]) -> dict[str, list[Token]]: + """Tokens the values in a dict of strings. + + Args: + values (dict[str, str]): A mapping of CSS variable name on to a value, to be + added to the CSS context. + + Returns: + dict[str, list[Token]]: A mapping of name on to a list of tokens, + """ + value_tokens = { + name: list(tokenize_value(value, "__name__")) for name, value in values.items() + } + return value_tokens + + +if __name__ == "__main__": + from rich import print + + css = """#something { + + color: rgb(10,12,23) + } + """ + # transition: offset 500 in_out_cubic; + tokens = tokenize(css, __name__) + print(list(tokens)) + + print(tokenize_values({"primary": "rgb(10,20,30)", "secondary": "#ff00ff"})) diff --git a/testbed/Textualize__textual/src/textual/css/tokenizer.py b/testbed/Textualize__textual/src/textual/css/tokenizer.py new file mode 100644 index 0000000000000000000000000000000000000000..15dc90508d57f1c347c7fdd94ce4f1deb97145e7 --- /dev/null +++ b/testbed/Textualize__textual/src/textual/css/tokenizer.py @@ -0,0 +1,257 @@ +from __future__ import annotations + +import re +from pathlib import PurePath +from typing import NamedTuple + +from rich.console import Group, RenderableType +from rich.highlighter import ReprHighlighter +from rich.padding import Padding +from rich.panel import Panel +import rich.repr +from rich.syntax import Syntax +from rich.text import Text + +from ._error_tools import friendly_list +from .._loop import loop_last + + +class TokenError(Exception): + """Error raised when the CSS cannot be tokenized (syntax error).""" + + def __init__( + self, + path: str, + code: str, + start: tuple[int, int], + message: str, + end: tuple[int, int] | None = None, + ) -> None: + """ + Args: + path (str): Path to source or "" if source is parsed from a literal. + code (str): The code being parsed. + start (tuple[int, int]): Line number of the error. + message (str): A message associated with the error. + end (tuple[int, int] | None): End location of token, or None if not known. Defaults to None. + """ + + self.path = path + self.code = code + self.start = start + self.end = end or start + super().__init__(message) + + def _get_snippet(self) -> Panel: + """Get a short snippet of code around a given line number. + + Returns: + Panel: A renderable. + """ + line_no = self.start[0] + # TODO: Highlight column number + syntax = Syntax( + self.code, + lexer="scss", + theme="ansi_light", + line_numbers=True, + indent_guides=True, + line_range=(max(0, line_no - 2), line_no + 2), + highlight_lines={line_no}, + ) + syntax.stylize_range("reverse bold", self.start, self.end) + return Panel(syntax, border_style="red") + + def __rich__(self) -> RenderableType: + highlighter = ReprHighlighter() + errors: list[RenderableType] = [] + + message = str(self) + errors.append(Text(" Error in stylesheet:", style="bold red")) + + line_no, col_no = self.start + + errors.append(highlighter(f" {self.path or ''}:{line_no}:{col_no}")) + errors.append(self._get_snippet()) + + final_message = "\n".join( + f"โ€ข {message_part.strip()}" for message_part in message.split(";") + ) + errors.append( + Padding( + highlighter( + Text(final_message, "red"), + ), + pad=(0, 1), + ) + ) + + return Group(*errors) + + +class EOFError(TokenError): + pass + + +class Expect: + def __init__(self, **tokens: str) -> None: + self.names = list(tokens.keys()) + self.regexes = list(tokens.values()) + self._regex = re.compile( + "(" + + "|".join(f"(?P<{name}>{regex})" for name, regex in tokens.items()) + + ")" + ) + self.match = self._regex.match + self.search = self._regex.search + self._expect_eof = False + + def expect_eof(self, eof: bool) -> Expect: + self._expect_eof = eof + return self + + def __rich_repr__(self) -> rich.repr.Result: + yield from zip(self.names, self.regexes) + + +class ReferencedBy(NamedTuple): + name: str + location: tuple[int, int] + length: int + code: str + + +@rich.repr.auto +class Token(NamedTuple): + name: str + value: str + path: str + code: str + location: tuple[int, int] + referenced_by: ReferencedBy | None = None + + @property + def start(self) -> tuple[int, int]: + """Start line and column (1 indexed).""" + line, offset = self.location + return (line + 1, offset) + + @property + def end(self) -> tuple[int, int]: + """End line and column (1 indexed).""" + line, offset = self.location + return (line + 1, offset + len(self.value)) + + def with_reference(self, by: ReferencedBy | None) -> "Token": + """Return a copy of the Token, with reference information attached. + This is used for variable substitution, where a variable reference + can refer to tokens which were defined elsewhere. With the additional + ReferencedBy data attached, we can track where the token we are referring + to is used. + """ + return Token( + name=self.name, + value=self.value, + path=self.path, + code=self.code, + location=self.location, + referenced_by=by, + ) + + def __str__(self) -> str: + return self.value + + def __rich_repr__(self) -> rich.repr.Result: + yield "name", self.name + yield "value", self.value + yield "path", self.path + yield "code", self.code if len(self.code) < 40 else self.code[:40] + "..." + yield "location", self.location + yield "referenced_by", self.referenced_by, None + + +class Tokenizer: + def __init__(self, text: str, path: str | PurePath = "") -> None: + self.path = str(path) + self.code = text + self.lines = text.splitlines(keepends=True) + self.line_no = 0 + self.col_no = 0 + + def get_token(self, expect: Expect) -> Token: + line_no = self.line_no + col_no = self.col_no + if line_no >= len(self.lines): + if expect._expect_eof: + return Token( + "eof", + "", + self.path, + self.code, + (line_no + 1, col_no + 1), + None, + ) + else: + raise EOFError( + self.path, + self.code, + (line_no + 1, col_no + 1), + "Unexpected end of file", + ) + line = self.lines[line_no] + match = expect.match(line, col_no) + if match is None: + expected = friendly_list(" ".join(name.split("_")) for name in expect.names) + message = f"Expected one of {expected}.; Did you forget a semicolon at the end of a line?" + raise TokenError( + self.path, + self.code, + (line_no, col_no), + message, + ) + iter_groups = iter(match.groups()) + + next(iter_groups) + + for name, value in zip(expect.names, iter_groups): + if value is not None: + break + else: + # For MyPy's benefit + raise AssertionError("can't reach here") + + token = Token( + name, + value, + self.path, + self.code, + (line_no, col_no), + referenced_by=None, + ) + col_no += len(value) + if col_no >= len(line): + line_no += 1 + col_no = 0 + self.line_no = line_no + self.col_no = col_no + return token + + def skip_to(self, expect: Expect) -> Token: + line_no = self.line_no + col_no = self.col_no + + while True: + if line_no >= len(self.lines): + raise EOFError( + self.path, self.code, line_no, col_no, "Unexpected end of file" + ) + line = self.lines[line_no] + match = expect.search(line, col_no) + + if match is None: + line_no += 1 + col_no = 0 + else: + self.line_no = line_no + self.col_no = match.span(0)[0] + return self.get_token(expect) diff --git a/testbed/Textualize__textual/src/textual/css/transition.py b/testbed/Textualize__textual/src/textual/css/transition.py new file mode 100644 index 0000000000000000000000000000000000000000..9d9facf1023168f2617a61f3be0abe0d19c8a228 --- /dev/null +++ b/testbed/Textualize__textual/src/textual/css/transition.py @@ -0,0 +1,16 @@ +from typing import NamedTuple + + +class Transition(NamedTuple): + duration: float = 1.0 + easing: str = "linear" + delay: float = 0.0 + + def __str__(self) -> str: + duration, easing, delay = self + if delay: + return f"{duration:.1f}s {easing} {delay:.1f}" + elif easing != "linear": + return f"{duration:.1f}s {easing}" + else: + return f"{duration:.1f}s" diff --git a/testbed/Textualize__textual/src/textual/css/types.py b/testbed/Textualize__textual/src/textual/css/types.py new file mode 100644 index 0000000000000000000000000000000000000000..6fb0929a409f7cc27f2ff1462e3c02a3672f8412 --- /dev/null +++ b/testbed/Textualize__textual/src/textual/css/types.py @@ -0,0 +1,47 @@ +from __future__ import annotations + +import sys +from typing import Tuple + +from ..color import Color + +if sys.version_info >= (3, 8): + from typing import Literal +else: + from typing_extensions import Literal + + +Edge = Literal["top", "right", "bottom", "left"] +DockEdge = Literal["top", "right", "bottom", "left", ""] +EdgeType = Literal[ + "", + "ascii", + "none", + "hidden", + "blank", + "round", + "solid", + "double", + "dashed", + "heavy", + "inner", + "outer", + "hkey", + "vkey", + "tall", + "wide", +] +Visibility = Literal["visible", "hidden", "initial", "inherit"] +Display = Literal["block", "none"] +AlignHorizontal = Literal["left", "center", "right"] +AlignVertical = Literal["top", "middle", "bottom"] +ScrollbarGutter = Literal["auto", "stable"] +BoxSizing = Literal["border-box", "content-box"] +Overflow = Literal["scroll", "hidden", "auto"] +EdgeStyle = Tuple[EdgeType, Color] +TextAlign = Literal["left", "start", "center", "right", "end", "justify"] + +Specificity3 = Tuple[int, int, int] +Specificity4 = Tuple[int, int, int, int] +Specificity5 = Tuple[int, int, int, int, int] +Specificity6 = Tuple[int, int, int, int, int, int] diff --git a/testbed/Textualize__textual/src/textual/draw.py b/testbed/Textualize__textual/src/textual/draw.py new file mode 100644 index 0000000000000000000000000000000000000000..17d2edbf23c4ecb71b661d5dc61c52cc35564775 --- /dev/null +++ b/testbed/Textualize__textual/src/textual/draw.py @@ -0,0 +1,10 @@ +from enum import Enum + + +class DrawStyle(Enum): + NONE = "none" + ASCII = "ascii" + SQUARE = "square" + HEAVY = "heavy" + ROUNDED = "rounded" + DOUBLE = "double" diff --git a/testbed/Textualize__textual/src/textual/drivers/win32.py b/testbed/Textualize__textual/src/textual/drivers/win32.py new file mode 100644 index 0000000000000000000000000000000000000000..1e931e4c82562d2ac964d25b110e09c20fbbcf0f --- /dev/null +++ b/testbed/Textualize__textual/src/textual/drivers/win32.py @@ -0,0 +1,287 @@ +import ctypes +import msvcrt +import sys +import threading +from asyncio import AbstractEventLoop, run_coroutine_threadsafe +from ctypes import Structure, Union, byref, wintypes +from ctypes.wintypes import BOOL, CHAR, DWORD, HANDLE, SHORT, UINT, WCHAR, WORD +from typing import IO, Callable, List, Optional + +from .._types import EventTarget +from .._xterm_parser import XTermParser +from ..events import Event, Resize +from ..geometry import Size + +KERNEL32 = ctypes.WinDLL("kernel32", use_last_error=True) + +# Console input modes +ENABLE_ECHO_INPUT = 0x0004 +ENABLE_EXTENDED_FLAGS = 0x0080 +ENABLE_INSERT_MODE = 0x0020 +ENABLE_LINE_INPUT = 0x0002 +ENABLE_MOUSE_INPUT = 0x0010 +ENABLE_PROCESSED_INPUT = 0x0001 +ENABLE_QUICK_EDIT_MODE = 0x0040 +ENABLE_WINDOW_INPUT = 0x0008 +ENABLE_VIRTUAL_TERMINAL_INPUT = 0x0200 + +# Console output modes +ENABLE_PROCESSED_OUTPUT = 0x0001 +ENABLE_WRAP_AT_EOL_OUTPUT = 0x0002 +ENABLE_VIRTUAL_TERMINAL_PROCESSING = 0x0004 +DISABLE_NEWLINE_AUTO_RETURN = 0x0008 +ENABLE_LVB_GRID_WORLDWIDE = 0x0010 + +STD_INPUT_HANDLE = -10 +STD_OUTPUT_HANDLE = -11 + +WAIT_TIMEOUT = 0x00000102 + +GetStdHandle = KERNEL32.GetStdHandle +GetStdHandle.argtypes = [wintypes.DWORD] +GetStdHandle.restype = wintypes.HANDLE + + +class COORD(Structure): + """https://docs.microsoft.com/en-us/windows/console/coord-str""" + + _fields_ = [ + ("X", SHORT), + ("Y", SHORT), + ] + + +class uChar(Union): + """https://docs.microsoft.com/en-us/windows/console/key-event-record-str""" + + _fields_ = [ + ("AsciiChar", CHAR), + ("UnicodeChar", WCHAR), + ] + + +class KEY_EVENT_RECORD(Structure): + """https://docs.microsoft.com/en-us/windows/console/key-event-record-str""" + + _fields_ = [ + ("bKeyDown", BOOL), + ("wRepeatCount", WORD), + ("wVirtualKeyCode", WORD), + ("wVirtualScanCode", WORD), + ("uChar", uChar), + ("dwControlKeyState", DWORD), + ] + + +class MOUSE_EVENT_RECORD(Structure): + """https://docs.microsoft.com/en-us/windows/console/mouse-event-record-str""" + + _fields_ = [ + ("dwMousePosition", COORD), + ("dwButtonState", DWORD), + ("dwControlKeyState", DWORD), + ("dwEventFlags", DWORD), + ] + + +class WINDOW_BUFFER_SIZE_RECORD(Structure): + """https://docs.microsoft.com/en-us/windows/console/window-buffer-size-record-str""" + + _fields_ = [("dwSize", COORD)] + + +class MENU_EVENT_RECORD(Structure): + """https://docs.microsoft.com/en-us/windows/console/menu-event-record-str""" + + _fields_ = [("dwCommandId", UINT)] + + +class FOCUS_EVENT_RECORD(Structure): + """https://docs.microsoft.com/en-us/windows/console/focus-event-record-str""" + + _fields_ = [("bSetFocus", BOOL)] + + +class InputEvent(Union): + """https://docs.microsoft.com/en-us/windows/console/input-record-str""" + + _fields_ = [ + ("KeyEvent", KEY_EVENT_RECORD), + ("MouseEvent", MOUSE_EVENT_RECORD), + ("WindowBufferSizeEvent", WINDOW_BUFFER_SIZE_RECORD), + ("MenuEvent", MENU_EVENT_RECORD), + ("FocusEvent", FOCUS_EVENT_RECORD), + ] + + +class INPUT_RECORD(Structure): + """https://docs.microsoft.com/en-us/windows/console/input-record-str""" + + _fields_ = [("EventType", wintypes.WORD), ("Event", InputEvent)] + + +def _set_console_mode(file: IO, mode: int) -> bool: + """Set the console mode for a given file (stdout or stdin). + + Args: + file (IO): A file like object. + mode (int): New mode. + + Returns: + bool: True on success, otherwise False. + """ + windows_filehandle = msvcrt.get_osfhandle(file.fileno()) + success = KERNEL32.SetConsoleMode(windows_filehandle, mode) + return success + + +def _get_console_mode(file: IO) -> int: + """Get the console mode for a given file (stdout or stdin) + + Args: + file (IO): A file-like object. + + Returns: + int: The current console mode. + """ + windows_filehandle = msvcrt.get_osfhandle(file.fileno()) + mode = wintypes.DWORD() + KERNEL32.GetConsoleMode(windows_filehandle, ctypes.byref(mode)) + return mode.value + + +def enable_application_mode() -> Callable[[], None]: + """Enable application mode. + + Returns: + Callable[[], None]: A callable that will restore terminal to previous state. + """ + + terminal_in = sys.stdin + terminal_out = sys.stdout + + current_console_mode_in = _get_console_mode(terminal_in) + current_console_mode_out = _get_console_mode(terminal_out) + + def restore() -> None: + """Restore console mode to previous settings""" + _set_console_mode(terminal_in, current_console_mode_in) + _set_console_mode(terminal_out, current_console_mode_out) + + _set_console_mode( + terminal_out, current_console_mode_out | ENABLE_VIRTUAL_TERMINAL_PROCESSING + ) + _set_console_mode(terminal_in, ENABLE_VIRTUAL_TERMINAL_INPUT) + return restore + + +def _wait_for_handles(handles: List[HANDLE], timeout: int = -1) -> Optional[HANDLE]: + """ + Waits for multiple handles. (Similar to 'select') Returns the handle which is ready. + Returns `None` on timeout. + http://msdn.microsoft.com/en-us/library/windows/desktop/ms687025(v=vs.85).aspx + Note that handles should be a list of `HANDLE` objects, not integers. See + this comment in the patch by @quark-zju for the reason why: + ''' Make sure HANDLE on Windows has a correct size + Previously, the type of various HANDLEs are native Python integer + types. The ctypes library will treat them as 4-byte integer when used + in function arguments. On 64-bit Windows, HANDLE is 8-byte and usually + a small integer. Depending on whether the extra 4 bytes are zero-ed out + or not, things can happen to work, or break. ''' + This function returns either `None` or one of the given `HANDLE` objects. + (The return value can be tested with the `is` operator.) + """ + arrtype = HANDLE * len(handles) + handle_array = arrtype(*handles) + + ret: int = KERNEL32.WaitForMultipleObjects( + len(handle_array), handle_array, BOOL(False), DWORD(timeout) + ) + + if ret == WAIT_TIMEOUT: + return None + else: + return handles[ret] + + +class EventMonitor(threading.Thread): + """A thread to send key / window events to Textual loop.""" + + def __init__( + self, + loop: AbstractEventLoop, + app, + target: EventTarget, + exit_event: threading.Event, + process_event: Callable[[Event], None], + ) -> None: + self.loop = loop + self.app = app + self.target = target + self.exit_event = exit_event + self.process_event = process_event + super().__init__() + + def run(self) -> None: + exit_requested = self.exit_event.is_set + parser = XTermParser(self.target, lambda: False) + + try: + read_count = wintypes.DWORD(0) + hIn = GetStdHandle(STD_INPUT_HANDLE) + + MAX_EVENTS = 1024 + KEY_EVENT = 0x0001 + WINDOW_BUFFER_SIZE_EVENT = 0x0004 + + arrtype = INPUT_RECORD * MAX_EVENTS + input_records = arrtype() + ReadConsoleInputW = KERNEL32.ReadConsoleInputW + keys: List[str] = [] + append_key = keys.append + + while not exit_requested(): + # Wait for new events + if _wait_for_handles([hIn], 200) is None: + # No new events + continue + + # Get new events + ReadConsoleInputW( + hIn, byref(input_records), MAX_EVENTS, byref(read_count) + ) + read_input_records = input_records[: read_count.value] + + del keys[:] + new_size: Optional[tuple[int, int]] = None + + for input_record in read_input_records: + event_type = input_record.EventType + + if event_type == KEY_EVENT: + # Key event, store unicode char in keys list + key_event = input_record.Event.KeyEvent + key = key_event.uChar.UnicodeChar + if key_event.bKeyDown or key == "\x1b": + append_key(key) + elif event_type == WINDOW_BUFFER_SIZE_EVENT: + # Window size changed, store size + size = input_record.Event.WindowBufferSizeEvent.dwSize + new_size = (size.X, size.Y) + + if keys: + # Process keys + for event in parser.feed("".join(keys)): + self.process_event(event) + if new_size is not None: + # Process changed size + self.on_size_change(*new_size) + + except Exception as error: + self.app.log.error("EVENT MONITOR ERROR", error) + + def on_size_change(self, width: int, height: int) -> None: + """Called when terminal size changes.""" + size = Size(width, height) + event = Resize(self.target, size, size) + run_coroutine_threadsafe(self.target.post_message(event), loop=self.loop) diff --git a/testbed/Textualize__textual/src/textual/layouts/__init__.py b/testbed/Textualize__textual/src/textual/layouts/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/testbed/Textualize__textual/src/textual/layouts/factory.py b/testbed/Textualize__textual/src/textual/layouts/factory.py new file mode 100644 index 0000000000000000000000000000000000000000..a5f89d843a1e3bbec5509d43c7581697f8c2343f --- /dev/null +++ b/testbed/Textualize__textual/src/textual/layouts/factory.py @@ -0,0 +1,35 @@ +from __future__ import annotations + +from .._layout import Layout +from .horizontal import HorizontalLayout +from .grid import GridLayout +from .vertical import VerticalLayout + +LAYOUT_MAP: dict[str, type[Layout]] = { + "horizontal": HorizontalLayout, + "grid": GridLayout, + "vertical": VerticalLayout, +} + + +class MissingLayout(Exception): + pass + + +def get_layout(name: str) -> Layout: + """Get a named layout object. + + Args: + name (str): Name of the layout. + + Raises: + MissingLayout: If the named layout doesn't exist. + + Returns: + Layout: A layout object. + """ + + layout_class = LAYOUT_MAP.get(name) + if layout_class is None: + raise MissingLayout(f"no layout called {name!r}, valid layouts") + return layout_class() diff --git a/testbed/Textualize__textual/src/textual/layouts/horizontal.py b/testbed/Textualize__textual/src/textual/layouts/horizontal.py new file mode 100644 index 0000000000000000000000000000000000000000..9261f24763475e98a2630840fd7651907b645c07 --- /dev/null +++ b/testbed/Textualize__textual/src/textual/layouts/horizontal.py @@ -0,0 +1,66 @@ +from __future__ import annotations + +from fractions import Fraction +from typing import cast + +from textual.geometry import Size, Region +from textual._layout import ArrangeResult, Layout, WidgetPlacement + +from textual.widget import Widget + + +class HorizontalLayout(Layout): + """Used to layout Widgets horizontally on screen, from left to right. Since Widgets naturally + fill the space of their parent container, all widgets used in a horizontal layout should have a specified. + """ + + name = "horizontal" + + def arrange( + self, parent: Widget, children: list[Widget], size: Size + ) -> ArrangeResult: + + placements: list[WidgetPlacement] = [] + add_placement = placements.append + + x = max_height = Fraction(0) + parent_size = parent.outer_size + + styles = [child.styles for child in children if child.styles.width is not None] + total_fraction = sum( + [int(style.width.value) for style in styles if style.width.is_fraction] + ) + fraction_unit = Fraction(size.width, total_fraction or 1) + + box_models = [ + widget._get_box_model(size, parent_size, fraction_unit) + for widget in cast("list[Widget]", children) + ] + + margins = [ + max((box1.margin.right, box2.margin.left)) + for box1, box2 in zip(box_models, box_models[1:]) + ] + if box_models: + margins.append(box_models[-1].margin.right) + + x = Fraction(box_models[0].margin.left if box_models else 0) + + displayed_children = [child for child in children if child.display] + + _Region = Region + _WidgetPlacement = WidgetPlacement + for widget, box_model, margin in zip(children, box_models, margins): + content_width, content_height, box_margin = box_model + offset_y = box_margin.top + next_x = x + content_width + region = _Region( + int(x), offset_y, int(next_x - int(x)), int(content_height) + ) + max_height = max( + max_height, content_height + offset_y + box_model.margin.bottom + ) + add_placement(_WidgetPlacement(region, box_model.margin, widget, 0)) + x = next_x + margin + + return placements, set(displayed_children) diff --git a/testbed/Textualize__textual/src/textual/layouts/vertical.py b/testbed/Textualize__textual/src/textual/layouts/vertical.py new file mode 100644 index 0000000000000000000000000000000000000000..d7afced192207e20a550cd3b2e43506e4ccfd30b --- /dev/null +++ b/testbed/Textualize__textual/src/textual/layouts/vertical.py @@ -0,0 +1,58 @@ +from __future__ import annotations + +from fractions import Fraction +from typing import cast, TYPE_CHECKING + +from ..geometry import Region, Size +from .._layout import ArrangeResult, Layout, WidgetPlacement + +if TYPE_CHECKING: + from ..widget import Widget + + +class VerticalLayout(Layout): + """Used to layout Widgets vertically on screen, from top to bottom.""" + + name = "vertical" + + def arrange( + self, parent: Widget, children: list[Widget], size: Size + ) -> ArrangeResult: + + placements: list[WidgetPlacement] = [] + add_placement = placements.append + + parent_size = parent.outer_size + + styles = [child.styles for child in children if child.styles.height is not None] + total_fraction = sum( + [int(style.height.value) for style in styles if style.height.is_fraction] + ) + fraction_unit = Fraction(size.height, total_fraction or 1) + + box_models = [ + widget._get_box_model(size, parent_size, fraction_unit) + for widget in children + ] + + margins = [ + max((box1.margin.bottom, box2.margin.top)) + for box1, box2 in zip(box_models, box_models[1:]) + ] + if box_models: + margins.append(box_models[-1].margin.bottom) + + y = Fraction(box_models[0].margin.top if box_models else 0) + + _Region = Region + _WidgetPlacement = WidgetPlacement + for widget, box_model, margin in zip(children, box_models, margins): + content_width, content_height, box_margin = box_model + next_y = y + content_height + region = _Region( + box_margin.left, int(y), int(content_width), int(next_y) - int(y) + ) + add_placement(_WidgetPlacement(region, box_model.margin, widget, 0)) + y = next_y + margin + + return placements, set(children) diff --git a/testbed/Textualize__textual/src/textual/message.py b/testbed/Textualize__textual/src/textual/message.py new file mode 100644 index 0000000000000000000000000000000000000000..c808aed800a5d487d5c9975f5f66fbffd61fa6b2 --- /dev/null +++ b/testbed/Textualize__textual/src/textual/message.py @@ -0,0 +1,122 @@ +from __future__ import annotations + +from typing import ClassVar, TYPE_CHECKING + +import rich.repr + +from . import _clock +from .case import camel_to_snake +from ._types import MessageTarget as MessageTarget + +if TYPE_CHECKING: + from .widget import Widget + + +@rich.repr.auto +class Message: + """Base class for a message. + + Args: + sender (MessageTarget): The sender of the message / event. + + """ + + __slots__ = [ + "sender", + "name", + "time", + "_forwarded", + "_no_default_action", + "_stop_propagation", + "_handler_name", + ] + + sender: MessageTarget + bubble: ClassVar[bool] = True # Message will bubble to parent + verbose: ClassVar[bool] = False # Message is verbose + no_dispatch: ClassVar[bool] = False # Message may not be handled by client code + namespace: ClassVar[str] = "" # Namespace to disambiguate messages + + def __init__(self, sender: MessageTarget) -> None: + self.sender = sender + self.name = camel_to_snake(self.__class__.__name__) + self.time = _clock.get_time_no_wait() + self._forwarded = False + self._no_default_action = False + self._stop_propagation = False + self._handler_name = ( + f"on_{self.namespace}_{self.name}" if self.namespace else f"on_{self.name}" + ) + super().__init__() + + def __rich_repr__(self) -> rich.repr.Result: + yield self.sender + + def __init_subclass__( + cls, + bubble: bool | None = True, + verbose: bool = False, + no_dispatch: bool | None = False, + namespace: str | None = None, + ) -> None: + super().__init_subclass__() + if bubble is not None: + cls.bubble = bubble + cls.verbose = verbose + if no_dispatch is not None: + cls.no_dispatch = no_dispatch + if namespace is not None: + cls.namespace = namespace + + @property + def is_forwarded(self) -> bool: + return self._forwarded + + @property + def handler_name(self) -> str: + """The name of the handler associated with this message.""" + # Property to make it read only + return self._handler_name + + def _set_forwarded(self) -> None: + """Mark this event as being forwarded.""" + self._forwarded = True + + def can_replace(self, message: "Message") -> bool: + """Check if another message may supersede this one. + + Args: + message (Message): Another message. + + Returns: + bool: True if this message may replace the given message + """ + return False + + def prevent_default(self, prevent: bool = True) -> Message: + """Suppress the default action(s). This will prevent handlers in any base classes + from being called. + + Args: + prevent (bool, optional): True if the default action should be suppressed, + or False if the default actions should be performed. Defaults to True. + """ + self._no_default_action = prevent + return self + + def stop(self, stop: bool = True) -> Message: + """Stop propagation of the message to parent. + + Args: + stop (bool, optional): The stop flag. Defaults to True. + """ + self._stop_propagation = stop + return self + + async def _bubble_to(self, widget: Widget) -> None: + """Bubble to a widget (typically the parent). + + Args: + widget (Widget): Target of bubble. + """ + await widget.post_message(self) diff --git a/testbed/Textualize__textual/src/textual/renderables/blank.py b/testbed/Textualize__textual/src/textual/renderables/blank.py new file mode 100644 index 0000000000000000000000000000000000000000..b83dbbc349da65a86adadb76b72b80a928717bf6 --- /dev/null +++ b/testbed/Textualize__textual/src/textual/renderables/blank.py @@ -0,0 +1,33 @@ +from __future__ import annotations + +from rich.console import ConsoleOptions, Console, RenderResult +from rich.segment import Segment +from rich.style import Style + +from ..color import Color + + +class Blank: + """Draw solid background color.""" + + def __init__(self, color: Color | str = "transparent") -> None: + background = Color.parse(color) + self._style = Style.from_color(bgcolor=background.rich_color) + + def __rich_console__( + self, console: Console, options: ConsoleOptions + ) -> RenderResult: + width = options.max_width + height = options.height or options.max_height + + segment = Segment(" " * width, self._style) + line = Segment.line() + for _ in range(height): + yield segment + yield line + + +if __name__ == "__main__": + from rich import print + + print(Blank("red")) diff --git a/testbed/Textualize__textual/src/textual/renderables/underline_bar.py b/testbed/Textualize__textual/src/textual/renderables/underline_bar.py new file mode 100644 index 0000000000000000000000000000000000000000..c0d508df67ecf2e60de4f81aef7db3ffbfb54417 --- /dev/null +++ b/testbed/Textualize__textual/src/textual/renderables/underline_bar.py @@ -0,0 +1,139 @@ +from __future__ import annotations + +from rich.console import ConsoleOptions, Console, RenderResult +from rich.style import StyleType +from rich.text import Text + + +class UnderlineBar: + """Thin horizontal bar with a portion highlighted. + + Args: + highlight_range (tuple[float, float]): The range to highlight. Defaults to ``(0, 0)`` (no highlight) + highlight_style (StyleType): The style of the highlighted range of the bar. + background_style (StyleType): The style of the non-highlighted range(s) of the bar. + width (int, optional): The width of the bar, or ``None`` to fill available width. + """ + + def __init__( + self, + highlight_range: tuple[float, float] = (0, 0), + highlight_style: StyleType = "magenta", + background_style: StyleType = "grey37", + clickable_ranges: dict[str, tuple[int, int]] | None = None, + width: int | None = None, + ) -> None: + self.highlight_range = highlight_range + self.highlight_style = highlight_style + self.background_style = background_style + self.clickable_ranges = clickable_ranges or {} + self.width = width + + def __rich_console__( + self, console: Console, options: ConsoleOptions + ) -> RenderResult: + highlight_style = console.get_style(self.highlight_style) + background_style = console.get_style(self.background_style) + + half_bar_right = "โ•ธ" + half_bar_left = "โ•บ" + bar = "โ”" + + width = self.width or options.max_width + start, end = self.highlight_range + + start = max(start, 0) + end = min(end, width) + + output_bar = Text("", end="") + + if start == end == 0 or end < 0 or start > end: + output_bar.append(Text(bar * width, style=background_style, end="")) + yield output_bar + return + + # Round start and end to nearest half + start = round(start * 2) / 2 + end = round(end * 2) / 2 + + # Check if we start/end on a number that rounds to a .5 + half_start = start - int(start) > 0 + half_end = end - int(end) > 0 + + # Initial non-highlighted portion of bar + output_bar.append( + Text(bar * (int(start - 0.5)), style=background_style, end="") + ) + if not half_start and start > 0: + output_bar.append(Text(half_bar_right, style=background_style, end="")) + + # The highlighted portion + bar_width = int(end) - int(start) + if half_start: + output_bar.append( + Text( + half_bar_left + bar * (bar_width - 1), style=highlight_style, end="" + ) + ) + else: + output_bar.append(Text(bar * bar_width, style=highlight_style, end="")) + if half_end: + output_bar.append(Text(half_bar_right, style=highlight_style, end="")) + + # The non-highlighted tail + if not half_end and end - width != 0: + output_bar.append(Text(half_bar_left, style=background_style, end="")) + output_bar.append( + Text(bar * (int(width) - int(end) - 1), style=background_style, end="") + ) + + # Fire actions when certain ranges are clicked (e.g. for tabs) + for range_name, (start, end) in self.clickable_ranges.items(): + output_bar.apply_meta( + {"@click": f"range_clicked('{range_name}')"}, start, end + ) + + yield output_bar + + +if __name__ == "__main__": + import random + from time import sleep + from rich.color import ANSI_COLOR_NAMES + + console = Console() + + def frange(start, end, step): + current = start + while current < end: + yield current + current += step + + while current >= 0: + yield current + current -= step + + step = 0.1 + start_range = frange(0.5, 10.5, step) + end_range = frange(10, 20, step) + ranges = zip(start_range, end_range) + + console.print(UnderlineBar(width=20), f" (.0, .0)") + + for range in ranges: + color = random.choice(list(ANSI_COLOR_NAMES.keys())) + console.print( + UnderlineBar(range, highlight_style=color, width=20), + f" {range}", + ) + + from rich.live import Live + + bar = UnderlineBar(highlight_range=(0, 4.5), width=80) + with Live(bar, refresh_per_second=60) as live: + while True: + bar.highlight_range = ( + bar.highlight_range[0] + 0.1, + bar.highlight_range[1] + 0.1, + ) + sleep(0.005) diff --git a/testbed/Textualize__textual/src/textual/screen.py b/testbed/Textualize__textual/src/textual/screen.py new file mode 100644 index 0000000000000000000000000000000000000000..e3c1787cb1e37cd8db4fd31456e0578fe4d48ad1 --- /dev/null +++ b/testbed/Textualize__textual/src/textual/screen.py @@ -0,0 +1,351 @@ +from __future__ import annotations + +import sys +from typing import Iterable + +import rich.repr +from rich.console import RenderableType +from rich.style import Style + +from . import errors, events, messages +from ._callback import invoke +from ._compositor import Compositor, MapGeometry +from .timer import Timer +from ._types import CallbackType +from .geometry import Offset, Region, Size +from .reactive import Reactive +from .renderables.blank import Blank +from .widget import Widget + +if sys.version_info >= (3, 8): + from typing import Final +else: + from typing_extensions import Final + +# Screen updates will be batched so that they don't happen more often than 60 times per second: +UPDATE_PERIOD: Final = 1 / 60 + + +@rich.repr.auto +class Screen(Widget): + """A widget for the root of the app.""" + + DEFAULT_CSS = """ + Screen { + layout: vertical; + overflow-y: auto; + background: $surface; + } + """ + + dark: Reactive[bool] = Reactive(False) + + def __init__( + self, + name: str | None = None, + id: str | None = None, + classes: str | None = None, + ) -> None: + super().__init__(name=name, id=id, classes=classes) + self._compositor = Compositor() + self._dirty_widgets: set[Widget] = set() + self._update_timer: Timer | None = None + self._callbacks: list[CallbackType] = [] + + @property + def is_transparent(self) -> bool: + return False + + @property + def is_current(self) -> bool: + """Check if this screen is current (i.e. visible to user).""" + return self.app.screen is self + + @property + def update_timer(self) -> Timer: + """Timer used to perform updates.""" + if self._update_timer is None: + self._update_timer = self.set_interval( + UPDATE_PERIOD, self._on_timer_update, name="screen_update", pause=True + ) + return self._update_timer + + @property + def widgets(self) -> list[Widget]: + """Get all widgets.""" + return list(self._compositor.map.keys()) + + @property + def visible_widgets(self) -> list[Widget]: + """Get a list of visible widgets.""" + return list(self._compositor.visible_widgets) + + def watch_dark(self, dark: bool) -> None: + pass + + def render(self) -> RenderableType: + background = self.styles.background + if background.is_transparent: + return self.app.render() + return Blank(background) + + def get_offset(self, widget: Widget) -> Offset: + """Get the absolute offset of a given Widget. + + Args: + widget (Widget): A widget + + Returns: + Offset: The widget's offset relative to the top left of the terminal. + """ + return self._compositor.get_offset(widget) + + def get_widget_at(self, x: int, y: int) -> tuple[Widget, Region]: + """Get the widget at a given coordinate. + + Args: + x (int): X Coordinate. + y (int): Y Coordinate. + + Returns: + tuple[Widget, Region]: Widget and screen region. + """ + return self._compositor.get_widget_at(x, y) + + def get_widgets_at(self, x: int, y: int) -> Iterable[tuple[Widget, Region]]: + """Get all widgets under a given coordinate. + + Args: + x (int): X coordinate. + y (int): Y coordinate. + + Returns: + Iterable[tuple[Widget, Region]]: Sequence of (WIDGET, REGION) tuples. + """ + return self._compositor.get_widgets_at(x, y) + + def get_style_at(self, x: int, y: int) -> Style: + """Get the style under a given coordinate. + + Args: + x (int): X Coordinate. + y (int): Y Coordinate. + + Returns: + Style: Rich Style object + """ + return self._compositor.get_style_at(x, y) + + def find_widget(self, widget: Widget) -> MapGeometry: + """Get the screen region of a Widget. + + Args: + widget (Widget): A Widget within the composition. + + Returns: + Region: Region relative to screen. + """ + return self._compositor.find_widget(widget) + + async def _on_idle(self, event: events.Idle) -> None: + # Check for any widgets marked as 'dirty' (needs a repaint) + event.prevent_default() + + if self.is_current: + if self._layout_required: + self._refresh_layout() + self._layout_required = False + self._dirty_widgets.clear() + if self._repaint_required: + self._dirty_widgets.clear() + self._dirty_widgets.add(self) + self._repaint_required = False + + if self._dirty_widgets: + self.update_timer.resume() + + # The Screen is idle - a good opportunity to invoke the scheduled callbacks + await self._invoke_and_clear_callbacks() + + def _on_timer_update(self) -> None: + """Called by the _update_timer.""" + # Render widgets together + if self._dirty_widgets: + self._compositor.update_widgets(self._dirty_widgets) + self.app._display(self, self._compositor.render()) + self._dirty_widgets.clear() + + self.update_timer.pause() + if self._callbacks: + self.post_message_no_wait(events.InvokeCallbacks(self)) + + async def _on_invoke_callbacks(self, event: events.InvokeCallbacks) -> None: + """Handle PostScreenUpdate events, which are sent after the screen is updated""" + await self._invoke_and_clear_callbacks() + + async def _invoke_and_clear_callbacks(self) -> None: + """If there are scheduled callbacks to run, call them and clear + the callback queue.""" + if self._callbacks: + callbacks = self._callbacks[:] + self._callbacks.clear() + for callback in callbacks: + await invoke(callback) + + def _invoke_later(self, callback: CallbackType) -> None: + """Enqueue a callback to be invoked after the screen is repainted. + + Args: + callback (CallbackType): A callback. + """ + + self._callbacks.append(callback) + self.check_idle() + + def _refresh_layout(self, size: Size | None = None, full: bool = False) -> None: + """Refresh the layout (can change size and positions of widgets).""" + size = self.outer_size if size is None else size + if not size: + return + + self._compositor.update_widgets(self._dirty_widgets) + self.update_timer.pause() + try: + hidden, shown, resized = self._compositor.reflow(self, size) + Hide = events.Hide + Show = events.Show + for widget in hidden: + widget.post_message_no_wait(Hide(self)) + for widget in shown: + widget.post_message_no_wait(Show(self)) + + # We want to send a resize event to widgets that were just added or change since last layout + send_resize = shown | resized + ResizeEvent = events.Resize + + layers = self._compositor.layers + for widget, ( + region, + _order, + _clip, + virtual_size, + container_size, + _, + ) in layers: + widget._size_updated(region.size, virtual_size, container_size) + if widget in send_resize: + widget.post_message_no_wait( + ResizeEvent(self, region.size, virtual_size, container_size) + ) + + except Exception as error: + self.app._handle_exception(error) + return + display_update = self._compositor.render(full=full) + if display_update is not None: + self.app._display(self, display_update) + + async def _on_update(self, message: messages.Update) -> None: + message.stop() + message.prevent_default() + widget = message.widget + assert isinstance(widget, Widget) + self._dirty_widgets.add(widget) + self.check_idle() + + async def _on_layout(self, message: messages.Layout) -> None: + message.stop() + message.prevent_default() + self._layout_required = True + self.check_idle() + + def _screen_resized(self, size: Size): + """Called by App when the screen is resized.""" + self._refresh_layout(size, full=True) + + def _on_screen_resume(self) -> None: + """Called by the App""" + + size = self.app.size + self._refresh_layout(size, full=True) + + async def _on_resize(self, event: events.Resize) -> None: + event.stop() + + async def _handle_mouse_move(self, event: events.MouseMove) -> None: + try: + if self.app.mouse_captured: + widget = self.app.mouse_captured + region = self.find_widget(widget).region + else: + widget, region = self.get_widget_at(event.x, event.y) + except errors.NoWidget: + await self.app._set_mouse_over(None) + else: + await self.app._set_mouse_over(widget) + mouse_event = events.MouseMove( + self, + event.x - region.x, + event.y - region.y, + event.delta_x, + event.delta_y, + event.button, + event.shift, + event.meta, + event.ctrl, + screen_x=event.screen_x, + screen_y=event.screen_y, + style=event.style, + ) + widget.hover_style = event.style + mouse_event._set_forwarded() + await widget._forward_event(mouse_event) + + async def _forward_event(self, event: events.Event) -> None: + if event.is_forwarded: + return + event._set_forwarded() + if isinstance(event, (events.Enter, events.Leave)): + await self.post_message(event) + + elif isinstance(event, events.MouseMove): + event.style = self.get_style_at(event.screen_x, event.screen_y) + await self._handle_mouse_move(event) + + elif isinstance(event, events.MouseEvent): + try: + if self.app.mouse_captured: + widget = self.app.mouse_captured + region = self.find_widget(widget).region + else: + widget, region = self.get_widget_at(event.x, event.y) + except errors.NoWidget: + self.app.set_focus(None) + else: + if isinstance(event, events.MouseUp) and widget.can_focus: + if self.app.focused is not widget: + self.app.set_focus(widget) + event.stop() + return + event.style = self.get_style_at(event.screen_x, event.screen_y) + if widget is self: + event._set_forwarded() + await self.post_message(event) + else: + await widget._forward_event( + event._apply_offset(-region.x, -region.y) + ) + + elif isinstance(event, (events.MouseScrollDown, events.MouseScrollUp)): + try: + widget, _region = self.get_widget_at(event.x, event.y) + except errors.NoWidget: + return + scroll_widget = widget + if scroll_widget is not None: + if scroll_widget is self: + await self.post_message(event) + else: + await scroll_widget._forward_event(event) + else: + await self.post_message(event) diff --git a/testbed/Textualize__textual/src/textual/widgets/__init__.py b/testbed/Textualize__textual/src/textual/widgets/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..634b6678554ca4aeafe3bbe3b6beb17c647c6cc2 --- /dev/null +++ b/testbed/Textualize__textual/src/textual/widgets/__init__.py @@ -0,0 +1,46 @@ +from __future__ import annotations +from importlib import import_module +import typing + +from ..case import camel_to_snake + +if typing.TYPE_CHECKING: + from ..widget import Widget + + +# โš ๏ธFor any new built-in Widget we create, not only we have to add them to the following list, but also to the +# `__init__.pyi` file in this same folder - otherwise text editors and type checkers won't be able to "see" them. +__all__ = [ + "Button", + "DataTable", + "DirectoryTree", + "Footer", + "Header", + "Placeholder", + "Pretty", + "Static", + "Input", + "TextLog", + "TreeControl", + "Welcome", +] + + +_WIDGETS_LAZY_LOADING_CACHE: dict[str, type[Widget]] = {} + +# Let's decrease startup time by lazy loading our Widgets: +def __getattr__(widget_class: str) -> type[Widget]: + try: + return _WIDGETS_LAZY_LOADING_CACHE[widget_class] + except KeyError: + pass + + if widget_class not in __all__: + raise ImportError(f"Package 'textual.widgets' has no class '{widget_class}'") + + widget_module_path = f"._{camel_to_snake(widget_class)}" + module = import_module(widget_module_path, package="textual.widgets") + class_ = getattr(module, widget_class) + + _WIDGETS_LAZY_LOADING_CACHE[widget_class] = class_ + return class_ diff --git a/testbed/Textualize__textual/src/textual/widgets/__init__.pyi b/testbed/Textualize__textual/src/textual/widgets/__init__.pyi new file mode 100644 index 0000000000000000000000000000000000000000..922bfb479d5d02cd0d655d6cff3cf8885b8c8144 --- /dev/null +++ b/testbed/Textualize__textual/src/textual/widgets/__init__.pyi @@ -0,0 +1,13 @@ +# This stub file must re-export every classes exposed in the __init__.py's `__all__` list: +from ._button import Button as Button +from ._data_table import DataTable as DataTable +from ._directory_tree import DirectoryTree as DirectoryTree +from ._footer import Footer as Footer +from ._header import Header as Header +from ._placeholder import Placeholder as Placeholder +from ._pretty import Pretty as Pretty +from ._static import Static as Static +from ._input import Input as Input +from ._text_log import TextLog as TextLog +from ._tree_control import TreeControl as TreeControl +from ._welcome import Welcome as Welcome diff --git a/testbed/Textualize__textual/src/textual/widgets/_button.py b/testbed/Textualize__textual/src/textual/widgets/_button.py new file mode 100644 index 0000000000000000000000000000000000000000..7bc4d3a8cb43e089249d944c5891b04dbd859b3e --- /dev/null +++ b/testbed/Textualize__textual/src/textual/widgets/_button.py @@ -0,0 +1,353 @@ +from __future__ import annotations + +import sys +from functools import partial +from typing import cast + +if sys.version_info >= (3, 8): + from typing import Literal +else: + from typing_extensions import Literal # pragma: no cover + +import rich.repr +from rich.console import RenderableType +from rich.text import Text, TextType + +from .. import events +from ..css._error_tools import friendly_list +from ..message import Message +from ..reactive import Reactive +from ..widgets import Static + +ButtonVariant = Literal["default", "primary", "success", "warning", "error"] +_VALID_BUTTON_VARIANTS = {"default", "primary", "success", "warning", "error"} + + +class InvalidButtonVariant(Exception): + pass + + +class Button(Static, can_focus=True): + """A simple clickable button.""" + + DEFAULT_CSS = """ + Button { + width: auto; + min-width: 16; + height: 3; + background: $panel; + color: $text; + border: none; + border-top: tall $panel-lighten-2; + border-bottom: tall $panel-darken-3; + content-align: center middle; + text-style: bold; + } + + Button.-disabled { + opacity: 0.4; + text-opacity: 0.7; + } + + Button:focus { + text-style: bold reverse; + } + + Button:hover { + border-top: tall $panel-lighten-1; + background: $panel-darken-2; + color: $text; + } + + Button.-active { + background: $panel; + border-bottom: tall $panel-lighten-2; + border-top: tall $panel-darken-2; + tint: $background 30%; + } + + /* Primary variant */ + Button.-primary { + background: $primary; + color: $text; + border-top: tall $primary-lighten-3; + border-bottom: tall $primary-darken-3; + + } + + Button.-primary:hover { + background: $primary-darken-2; + color: $text; + border-top: tall $primary-lighten-2; + } + + Button.-primary.-active { + background: $primary; + border-bottom: tall $primary-lighten-3; + border-top: tall $primary-darken-3; + } + + + /* Success variant */ + Button.-success { + background: $success; + color: $text; + border-top: tall $success-lighten-2; + border-bottom: tall $success-darken-3; + } + + Button.-success:hover { + background: $success-darken-2; + color: $text; + } + + Button.-success.-active { + background: $success; + border-bottom: tall $success-lighten-2; + border-top: tall $success-darken-2; + } + + + /* Warning variant */ + Button.-warning { + background: $warning; + color: $text; + border-top: tall $warning-lighten-2; + border-bottom: tall $warning-darken-3; + } + + Button.-warning:hover { + background: $warning-darken-2; + color: $text; + + } + + Button.-warning.-active { + background: $warning; + border-bottom: tall $warning-lighten-2; + border-top: tall $warning-darken-2; + } + + + /* Error variant */ + Button.-error { + background: $error; + color: $text; + border-top: tall $error-lighten-2; + border-bottom: tall $error-darken-3; + + } + + Button.-error:hover { + background: $error-darken-1; + color: $text; + + } + + Button.-error.-active { + background: $error; + border-bottom: tall $error-lighten-2; + border-top: tall $error-darken-2; + } + + """ + + ACTIVE_EFFECT_DURATION = 0.3 + """When buttons are clicked they get the `-active` class for this duration (in seconds)""" + + class Pressed(Message, bubble=True): + @property + def button(self) -> Button: + return cast(Button, self.sender) + + def __init__( + self, + label: TextType | None = None, + disabled: bool = False, + variant: ButtonVariant = "default", + *, + name: str | None = None, + id: str | None = None, + classes: str | None = None, + ): + """Create a Button widget. + + Args: + label (str): The text that appears within the button. + disabled (bool): Whether the button is disabled or not. + variant (ButtonVariant): The variant of the button. + name: The name of the button. + id: The ID of the button in the DOM. + classes: The CSS classes of the button. + """ + super().__init__(name=name, id=id, classes=classes) + + if label is None: + label = self.css_identifier_styled + + self.label = self.validate_label(label) + + self.disabled = disabled + if disabled: + self.add_class("-disabled") + + self.variant = variant + + label: Reactive[RenderableType] = Reactive("") + variant = Reactive.init("default") + disabled = Reactive(False) + + def __rich_repr__(self) -> rich.repr.Result: + yield from super().__rich_repr__() + yield "variant", self.variant, "default" + yield "disabled", self.disabled, False + + def watch_mouse_over(self, value: bool) -> None: + """Update from CSS if mouse over state changes.""" + if self._has_hover_style and not self.disabled: + self.app.update_styles(self) + + def validate_variant(self, variant: str) -> str: + if variant not in _VALID_BUTTON_VARIANTS: + raise InvalidButtonVariant( + f"Valid button variants are {friendly_list(_VALID_BUTTON_VARIANTS)}" + ) + return variant + + def watch_variant(self, old_variant: str, variant: str): + self.remove_class(f"_{old_variant}") + self.add_class(f"-{variant}") + + def watch_disabled(self, disabled: bool) -> None: + self.set_class(disabled, "-disabled") + self.can_focus = not disabled + + def validate_label(self, label: RenderableType) -> RenderableType: + """Parse markup for self.label""" + if isinstance(label, str): + return Text.from_markup(label) + return label + + def render(self) -> RenderableType: + label = self.label.copy() + label = Text.assemble(" ", label, " ") + label.stylize(self.text_style) + return label + + async def _on_click(self, event: events.Click) -> None: + event.stop() + self.press() + + def press(self) -> None: + """Respond to a button press.""" + if self.disabled or not self.display: + return + # Manage the "active" effect: + self._start_active_affect() + # ...and let other components know that we've just been clicked: + self.emit_no_wait(Button.Pressed(self)) + + def _start_active_affect(self) -> None: + """Start a small animation to show the button was clicked.""" + self.add_class("-active") + self.set_timer( + self.ACTIVE_EFFECT_DURATION, partial(self.remove_class, "-active") + ) + + async def _on_key(self, event: events.Key) -> None: + if event.key == "enter" and not self.disabled: + self._start_active_affect() + await self.emit(Button.Pressed(self)) + + @classmethod + def success( + cls, + label: TextType | None = None, + disabled: bool = False, + *, + name: str | None = None, + id: str | None = None, + classes: str | None = None, + ) -> Button: + """Utility constructor for creating a success Button variant. + + Args: + label (str): The text that appears within the button. + disabled (bool): Whether the button is disabled or not. + name: The name of the button. + id: The ID of the button in the DOM. + classes: The CSS classes of the button. + + Returns: + Button: A Button widget of the 'success' variant. + """ + return Button( + label=label, + disabled=disabled, + variant="success", + name=name, + id=id, + classes=classes, + ) + + @classmethod + def warning( + cls, + label: TextType | None = None, + disabled: bool = False, + *, + name: str | None = None, + id: str | None = None, + classes: str | None = None, + ) -> Button: + """Utility constructor for creating a warning Button variant. + + Args: + label (str): The text that appears within the button. + disabled (bool): Whether the button is disabled or not. + name: The name of the button. + id: The ID of the button in the DOM. + classes: The CSS classes of the button. + + Returns: + Button: A Button widget of the 'warning' variant. + """ + return Button( + label=label, + disabled=disabled, + variant="warning", + name=name, + id=id, + classes=classes, + ) + + @classmethod + def error( + cls, + label: TextType | None = None, + disabled: bool = False, + *, + name: str | None = None, + id: str | None = None, + classes: str | None = None, + ) -> Button: + """Utility constructor for creating an error Button variant. + + Args: + label (str): The text that appears within the button. + disabled (bool): Whether the button is disabled or not. + name: The name of the button. + id: The ID of the button in the DOM. + classes: The CSS classes of the button. + + Returns: + Button: A Button widget of the 'error' variant. + """ + return Button( + label=label, + disabled=disabled, + variant="error", + name=name, + id=id, + classes=classes, + ) diff --git a/testbed/Textualize__textual/src/textual/widgets/_data_table.py b/testbed/Textualize__textual/src/textual/widgets/_data_table.py new file mode 100644 index 0000000000000000000000000000000000000000..8cc67cc21af2985be2c84277f252e586cd9ce9f2 --- /dev/null +++ b/testbed/Textualize__textual/src/textual/widgets/_data_table.py @@ -0,0 +1,647 @@ +from __future__ import annotations + +import sys +from dataclasses import dataclass, field +from itertools import chain, zip_longest +from typing import ClassVar, Generic, Iterable, NamedTuple, TypeVar, cast + +from rich.console import RenderableType +from rich.padding import Padding +from rich.protocol import is_renderable +from rich.segment import Segment +from rich.style import Style +from rich.text import Text, TextType + +from .. import events, messages +from .._cache import LRUCache +from .._profile import timer +from .._segment_tools import line_crop +from .._types import Lines +from ..geometry import Region, Size, Spacing, clamp +from ..reactive import Reactive +from ..render import measure +from ..scroll_view import ScrollView + +if sys.version_info >= (3, 8): + from typing import Literal +else: + from typing_extensions import Literal + +CursorType = Literal["cell", "row", "column"] +CELL: CursorType = "cell" +CellType = TypeVar("CellType") + + +def default_cell_formatter(obj: object) -> RenderableType | None: + """Format a cell in to a renderable. + + Args: + obj (object): Data for a cell. + + Returns: + RenderableType | None: A renderable or None if the object could not be rendered. + """ + if isinstance(obj, str): + return Text.from_markup(obj) + if not is_renderable(obj): + return None + return cast(RenderableType, obj) + + +@dataclass +class Column: + """Table column.""" + + label: Text + width: int = 0 + visible: bool = False + index: int = 0 + + content_width: int = 0 + auto_width: bool = False + + @property + def render_width(self) -> int: + """Width in cells, required to render a column.""" + # +2 is to account for space padding either side of the cell + if self.auto_width: + return self.content_width + 2 + else: + return self.width + 2 + + +@dataclass +class Row: + """Table row.""" + + index: int + height: int + y: int + cell_renderables: list[RenderableType] = field(default_factory=list) + + +@dataclass +class Cell: + """Table cell.""" + + value: object + + +class Coord(NamedTuple): + """An object to represent the coordinate of a cell within the data table.""" + + row: int + column: int + + def left(self) -> Coord: + """Get coordinate to the left.""" + row, column = self + return Coord(row, column - 1) + + def right(self) -> Coord: + """Get coordinate to the right.""" + row, column = self + return Coord(row, column + 1) + + def up(self) -> Coord: + """Get coordinate above.""" + row, column = self + return Coord(row - 1, column) + + def down(self) -> Coord: + """Get coordinate below.""" + row, column = self + return Coord(row + 1, column) + + +class DataTable(ScrollView, Generic[CellType], can_focus=True): + + DEFAULT_CSS = """ + App.-dark DataTable { + background:; + } + DataTable { + background: $surface ; + color: $text; + } + DataTable > .datatable--header { + text-style: bold; + background: $primary; + color: $text; + } + DataTable > .datatable--fixed { + text-style: bold; + background: $primary; + color: $text; + } + + DataTable > .datatable--odd-row { + + } + + DataTable > .datatable--even-row { + background: $primary 10%; + } + + DataTable > .datatable--cursor { + background: $secondary; + color: $text; + } + + .-dark-mode DataTable > .datatable--even-row { + background: $primary 15%; + } + + DataTable > .datatable--highlight { + background: $secondary 20%; + } + """ + + COMPONENT_CLASSES: ClassVar[set[str]] = { + "datatable--header", + "datatable--fixed", + "datatable--odd-row", + "datatable--even-row", + "datatable--highlight", + "datatable--cursor", + } + + def __init__( + self, + *, + name: str | None = None, + id: str | None = None, + classes: str | None = None, + ) -> None: + super().__init__(name=name, id=id, classes=classes) + self.columns: list[Column] = [] + self.rows: dict[int, Row] = {} + self.data: dict[int, list[CellType]] = {} + self.row_count = 0 + self._y_offsets: list[tuple[int, int]] = [] + self._row_render_cache: LRUCache[ + tuple[int, int, Style, int, int], tuple[Lines, Lines] + ] + self._row_render_cache = LRUCache(1000) + self._cell_render_cache: LRUCache[tuple[int, int, Style, bool, bool], Lines] + self._cell_render_cache = LRUCache(10000) + self._line_cache: LRUCache[ + tuple[int, int, int, int, int, int, Style], list[Segment] + ] + self._line_cache = LRUCache(1000) + + self._line_no = 0 + self._require_update_dimensions: bool = False + self._new_rows: set[int] = set() + + show_header = Reactive(True) + fixed_rows = Reactive(0) + fixed_columns = Reactive(0) + zebra_stripes = Reactive(False) + header_height = Reactive(1) + show_cursor = Reactive(True) + cursor_type = Reactive(CELL) + + cursor_cell: Reactive[Coord] = Reactive(Coord(0, 0), repaint=False) + hover_cell: Reactive[Coord] = Reactive(Coord(0, 0), repaint=False) + + @property + def hover_row(self) -> int: + return self.hover_cell.row + + @property + def hover_column(self) -> int: + return self.hover_cell.column + + @property + def cursor_row(self) -> int: + return self.cursor_cell.row + + @property + def cursor_column(self) -> int: + return self.cursor_cell.column + + def _clear_caches(self) -> None: + self._row_render_cache.clear() + self._cell_render_cache.clear() + self._line_cache.clear() + self._styles_cache.clear() + + def get_row_height(self, row_index: int) -> int: + if row_index == -1: + return self.header_height + return self.rows[row_index].height + + async def on_styles_updated(self, message: messages.StylesUpdated) -> None: + self._clear_caches() + self.refresh() + + def watch_show_header(self, show_header: bool) -> None: + self._clear_caches() + + def watch_fixed_rows(self, fixed_rows: int) -> None: + self._clear_caches() + + def watch_zebra_stripes(self, zebra_stripes: bool) -> None: + self._clear_caches() + + def watch_hover_cell(self, old: Coord, value: Coord) -> None: + self.refresh_cell(*old) + self.refresh_cell(*value) + + def watch_cursor_cell(self, old: Coord, value: Coord) -> None: + self.refresh_cell(*old) + self.refresh_cell(*value) + + def validate_cursor_cell(self, value: Coord) -> Coord: + row, column = value + row = clamp(row, 0, self.row_count - 1) + column = clamp(column, self.fixed_columns, len(self.columns) - 1) + return Coord(row, column) + + def _update_dimensions(self, new_rows: Iterable[int]) -> None: + """Called to recalculate the virtual (scrollable) size.""" + for row_index in new_rows: + for column, renderable in zip( + self.columns, self._get_row_renderables(row_index) + ): + content_width = measure(self.app.console, renderable, 1) + column.content_width = max(column.content_width, content_width) + + total_width = sum(column.render_width for column in self.columns) + header_height = self.header_height if self.show_header else 0 + self.virtual_size = Size( + total_width, + len(self._y_offsets) + header_height, + ) + + def _get_cell_region(self, row_index: int, column_index: int) -> Region: + if row_index not in self.rows: + return Region(0, 0, 0, 0) + row = self.rows[row_index] + x = sum(column.render_width for column in self.columns[:column_index]) + width = self.columns[column_index].render_width + height = row.height + y = row.y + if self.show_header: + y += self.header_height + cell_region = Region(x, y, width, height) + return cell_region + + def add_columns(self, *labels: TextType) -> None: + """Add a number of columns. + + Args: + *labels: Column headers. + + """ + for label in labels: + self.add_column(label, width=None) + + def add_column(self, label: TextType, *, width: int | None = None) -> None: + """Add a column to the table. + + Args: + label (TextType): A str or Text object containing the label (shown top of column). + width (int, optional): Width of the column in cells or None to fit content. Defaults to None. + """ + text_label = Text.from_markup(label) if isinstance(label, str) else label + + content_width = measure(self.app.console, text_label, 1) + if width is None: + column = Column( + text_label, + content_width, + index=len(self.columns), + content_width=content_width, + auto_width=True, + ) + else: + column = Column( + text_label, width, content_width=content_width, index=len(self.columns) + ) + + self.columns.append(column) + self._require_update_dimensions = True + self.check_idle() + + def add_row(self, *cells: CellType, height: int = 1) -> None: + """Add a row. + + Args: + *cells: Positional arguments should contain cell data. + height (int, optional): The height of a row (in lines). Defaults to 1. + """ + row_index = self.row_count + + self.data[row_index] = list(cells) + self.rows[row_index] = Row(row_index, height, self._line_no) + + for line_no in range(height): + self._y_offsets.append((row_index, line_no)) + + self.row_count += 1 + self._line_no += height + + self._new_rows.add(row_index) + self._require_update_dimensions = True + self.check_idle() + + def add_rows(self, rows: Iterable[Iterable[CellType]]) -> None: + """Add a number of rows. + + Args: + rows (Iterable[Iterable[CellType]]): Iterable of rows. A row is an iterable of cells. + """ + for row in rows: + self.add_row(*row) + + def on_idle(self) -> None: + if self._require_update_dimensions: + self._require_update_dimensions = False + new_rows = self._new_rows.copy() + self._new_rows.clear() + self._update_dimensions(new_rows) + + def refresh_cell(self, row_index: int, column_index: int) -> None: + """Refresh a cell. + + Args: + row_index (int): Row index. + column_index (int): Column index. + """ + if row_index < 0 or column_index < 0: + return + region = self._get_cell_region(row_index, column_index) + if not self.window_region.overlaps(region): + return + region = region.translate(-self.scroll_offset) + self.refresh(region) + + def _get_row_renderables(self, row_index: int) -> list[RenderableType]: + """Get renderables for the given row. + + Args: + row_index (int): Index of the row. + + Returns: + list[RenderableType]: List of renderables + """ + + if row_index == -1: + row = [column.label for column in self.columns] + return row + + data = self.data.get(row_index) + empty = Text() + if data is None: + return [empty for _ in self.columns] + else: + return [ + Text() if datum is None else default_cell_formatter(datum) or empty + for datum, _ in zip_longest(data, range(len(self.columns))) + ] + + def _render_cell( + self, + row_index: int, + column_index: int, + style: Style, + width: int, + cursor: bool = False, + hover: bool = False, + ) -> Lines: + """Render the given cell. + + Args: + row_index (int): Index of the row. + column_index (int): Index of the column. + style (Style): Style to apply. + width (int): Width of the cell. + + Returns: + Lines: A list of segments per line. + """ + if hover: + style += self.get_component_styles("datatable--highlight").rich_style + if cursor: + style += self.get_component_styles("datatable--cursor").rich_style + cell_key = (row_index, column_index, style, cursor, hover) + if cell_key not in self._cell_render_cache: + style += Style.from_meta({"row": row_index, "column": column_index}) + height = ( + self.header_height if row_index == -1 else self.rows[row_index].height + ) + cell = self._get_row_renderables(row_index)[column_index] + lines = self.app.console.render_lines( + Padding(cell, (0, 1)), + self.app.console.options.update_dimensions(width, height), + style=style, + ) + self._cell_render_cache[cell_key] = lines + return self._cell_render_cache[cell_key] + + def _render_row( + self, + row_index: int, + line_no: int, + base_style: Style, + cursor_column: int = -1, + hover_column: int = -1, + ) -> tuple[Lines, Lines]: + """Render a row in to lines for each cell. + + Args: + row_index (int): Index of the row. + line_no (int): Line number (on screen, 0 is top) + base_style (Style): Base style of row. + + Returns: + tuple[Lines, Lines]: Lines for fixed cells, and Lines for scrollable cells. + """ + + cache_key = (row_index, line_no, base_style, cursor_column, hover_column) + + if cache_key in self._row_render_cache: + return self._row_render_cache[cache_key] + + render_cell = self._render_cell + + if self.fixed_columns: + fixed_style = self.get_component_styles("datatable--fixed").rich_style + fixed_style += Style.from_meta({"fixed": True}) + fixed_row = [ + render_cell(row_index, column.index, fixed_style, column.render_width)[ + line_no + ] + for column in self.columns[: self.fixed_columns] + ] + else: + fixed_row = [] + + if row_index == -1: + row_style = self.get_component_styles("datatable--header").rich_style + else: + if self.zebra_stripes: + component_row_style = ( + "datatable--odd-row" if row_index % 2 else "datatable--even-row" + ) + row_style = self.get_component_styles(component_row_style).rich_style + else: + row_style = base_style + + scrollable_row = [ + render_cell( + row_index, + column.index, + row_style, + column.render_width, + cursor=cursor_column == column.index, + hover=hover_column == column.index, + )[line_no] + for column in self.columns + ] + + row_pair = (fixed_row, scrollable_row) + self._row_render_cache[cache_key] = row_pair + return row_pair + + def _get_offsets(self, y: int) -> tuple[int, int]: + """Get row number and line offset for a given line. + + Args: + y (int): Y coordinate relative to screen top. + + Returns: + tuple[int, int]: Line number and line offset within cell. + """ + if self.show_header: + if y < self.header_height: + return (-1, y) + y -= self.header_height + if y > len(self._y_offsets): + raise LookupError("Y coord {y!r} is greater than total height") + return self._y_offsets[y] + + def _render_line( + self, y: int, x1: int, x2: int, base_style: Style + ) -> list[Segment]: + """Render a line in to a list of segments. + + Args: + y (int): Y coordinate of line + x1 (int): X start crop. + x2 (int): X end crop (exclusive). + base_style (Style): Style to apply to line. + + Returns: + list[Segment]: List of segments for rendering. + """ + + width = self.size.width + + try: + row_index, line_no = self._get_offsets(y) + except LookupError: + return [Segment(" " * width, base_style)] + cursor_column = ( + self.cursor_column + if (self.show_cursor and self.cursor_row == row_index) + else -1 + ) + hover_column = self.hover_column if (self.hover_row == row_index) else -1 + + cache_key = (y, x1, x2, width, cursor_column, hover_column, base_style) + if cache_key in self._line_cache: + return self._line_cache[cache_key] + + fixed, scrollable = self._render_row( + row_index, + line_no, + base_style, + cursor_column=cursor_column, + hover_column=hover_column, + ) + fixed_width = sum( + column.render_width for column in self.columns[: self.fixed_columns] + ) + + fixed_line: list[Segment] = list(chain.from_iterable(fixed)) if fixed else [] + scrollable_line: list[Segment] = list(chain.from_iterable(scrollable)) + + segments = fixed_line + line_crop(scrollable_line, x1 + fixed_width, x2, width) + segments = Segment.adjust_line_length(segments, width, style=base_style) + simplified_segments = list(Segment.simplify(segments)) + + self._line_cache[cache_key] = simplified_segments + return segments + + def render_line(self, y: int) -> list[Segment]: + width, height = self.size + scroll_x, scroll_y = self.scroll_offset + fixed_top_row_count = sum( + self.get_row_height(row_index) for row_index in range(self.fixed_rows) + ) + if self.show_header: + fixed_top_row_count += self.get_row_height(-1) + + style = self.rich_style + + if y >= fixed_top_row_count: + y += scroll_y + + return self._render_line(y, scroll_x, scroll_x + width, style) + + def on_mouse_move(self, event: events.MouseMove): + meta = event.style.meta + if meta: + try: + self.hover_cell = Coord(meta["row"], meta["column"]) + except KeyError: + pass + + def _get_cell_border(self) -> Spacing: + top = self.header_height if self.show_header else 0 + top += sum( + self.rows[row_index].height + for row_index in range(self.fixed_rows) + if row_index in self.rows + ) + left = sum(column.render_width for column in self.columns[: self.fixed_columns]) + return Spacing(top, 0, 0, left) + + def _scroll_cursor_in_to_view(self, animate: bool = False) -> None: + region = self._get_cell_region(self.cursor_row, self.cursor_column) + spacing = self._get_cell_border() + self.scrollbar_gutter + self.scroll_to_region(region, animate=animate, spacing=spacing) + + def on_click(self, event: events.Click) -> None: + meta = self.get_style_at(event.x, event.y).meta + if meta: + self.cursor_cell = Coord(meta["row"], meta["column"]) + self._scroll_cursor_in_to_view() + event.stop() + + def key_down(self, event: events.Key): + self.cursor_cell = self.cursor_cell.down() + event.stop() + event.prevent_default() + self._scroll_cursor_in_to_view() + + def key_up(self, event: events.Key): + self.cursor_cell = self.cursor_cell.up() + event.stop() + event.prevent_default() + self._scroll_cursor_in_to_view() + + def key_right(self, event: events.Key): + self.cursor_cell = self.cursor_cell.right() + event.stop() + event.prevent_default() + self._scroll_cursor_in_to_view(animate=True) + + def key_left(self, event: events.Key): + self.cursor_cell = self.cursor_cell.left() + event.stop() + event.prevent_default() + self._scroll_cursor_in_to_view(animate=True) diff --git a/testbed/Textualize__textual/src/textual/widgets/_directory_tree.py b/testbed/Textualize__textual/src/textual/widgets/_directory_tree.py new file mode 100644 index 0000000000000000000000000000000000000000..ffae6442f7e675d78c6aee8637d4ace46a489d43 --- /dev/null +++ b/testbed/Textualize__textual/src/textual/widgets/_directory_tree.py @@ -0,0 +1,131 @@ +from __future__ import annotations + +from dataclasses import dataclass +from functools import lru_cache +from os import scandir +import os.path + +from rich.console import RenderableType +import rich.repr + +from rich.text import Text + +from .. import events +from ..message import Message +from .._types import MessageTarget +from ._tree_control import TreeControl, TreeNode + + +@dataclass +class DirEntry: + path: str + is_dir: bool + + +class DirectoryTree(TreeControl[DirEntry]): + @rich.repr.auto + class FileClick(Message, bubble=True): + def __init__(self, sender: MessageTarget, path: str) -> None: + self.path = path + super().__init__(sender) + + def __init__( + self, + path: str, + *, + name: str | None = None, + id: str | None = None, + classes: str | None = None, + ) -> None: + self.path = os.path.expanduser(path.rstrip("/")) + label = os.path.basename(self.path) + data = DirEntry(self.path, True) + super().__init__(label, data, name=name, id=id, classes=classes) + self.root.tree.guide_style = "black" + + def render_node(self, node: TreeNode[DirEntry]) -> RenderableType: + return self.render_tree_label( + node, + node.data.is_dir, + node.expanded, + node.is_cursor, + node.id == self.hover_node, + self.has_focus, + ) + + @lru_cache(maxsize=1024 * 32) + def render_tree_label( + self, + node: TreeNode[DirEntry], + is_dir: bool, + expanded: bool, + is_cursor: bool, + is_hover: bool, + has_focus: bool, + ) -> RenderableType: + meta = { + "@click": f"click_label({node.id})", + "tree_node": node.id, + "cursor": node.is_cursor, + } + label = Text(node.label) if isinstance(node.label, str) else node.label + if is_hover: + label.stylize("underline") + if is_dir: + label.stylize("bold") + icon = "๐Ÿ“‚" if expanded else "๐Ÿ“" + else: + icon = "๐Ÿ“„" + label.highlight_regex(r"\..*$", "italic") + + if label.plain.startswith("."): + label.stylize("dim") + + if is_cursor and has_focus: + cursor_style = self.get_component_styles("tree--cursor").rich_style + label.stylize(cursor_style) + + icon_label = Text(f"{icon} ", no_wrap=True, overflow="ellipsis") + label + icon_label.apply_meta(meta) + return icon_label + + def on_styles_updated(self) -> None: + self.render_tree_label.cache_clear() + + def on_mount(self) -> None: + self.call_later(self.load_directory, self.root) + + async def load_directory(self, node: TreeNode[DirEntry]): + path = node.data.path + directory = sorted( + list(scandir(path)), key=lambda entry: (not entry.is_dir(), entry.name) + ) + for entry in directory: + node.add(entry.name, DirEntry(entry.path, entry.is_dir())) + node.loaded = True + node.expand() + self.refresh(layout=True) + + async def on_tree_control_node_selected( + self, message: TreeControl.NodeSelected[DirEntry] + ) -> None: + dir_entry = message.node.data + if not dir_entry.is_dir: + await self.emit(self.FileClick(self, dir_entry.path)) + else: + if not message.node.loaded: + await self.load_directory(message.node) + message.node.expand() + else: + message.node.toggle() + + +if __name__ == "__main__": + from textual import events + from textual.app import App + + class TreeApp(App): + async def on_mount(self, event: events.Mount) -> None: + await self.screen.dock(DirectoryTree("/Users/willmcgugan/projects")) + + TreeApp(log_path="textual.log").run() diff --git a/testbed/Textualize__textual/src/textual/widgets/_placeholder.py b/testbed/Textualize__textual/src/textual/widgets/_placeholder.py new file mode 100644 index 0000000000000000000000000000000000000000..7ce714a2419e3576cd2e39408ca9b5f82229ff88 --- /dev/null +++ b/testbed/Textualize__textual/src/textual/widgets/_placeholder.py @@ -0,0 +1,63 @@ +from __future__ import annotations + +from rich import box +from rich.align import Align +from rich.console import RenderableType +from rich.panel import Panel +from rich.pretty import Pretty +import rich.repr +from rich.style import Style + +from .. import events +from ..reactive import Reactive +from ..widget import Widget + + +@rich.repr.auto(angular=False) +class Placeholder(Widget, can_focus=True): + + has_focus: Reactive[bool] = Reactive(False) + mouse_over: Reactive[bool] = Reactive(False) + + def __init__( + # parent class constructor signature: + self, + *children: Widget, + name: str | None = None, + id: str | None = None, + classes: str | None = None, + # ...and now for our own class specific params: + title: str | None = None, + ) -> None: + super().__init__(*children, name=name, id=id, classes=classes) + self.title = title + + def __rich_repr__(self) -> rich.repr.Result: + yield from super().__rich_repr__() + yield "has_focus", self.has_focus, False + yield "mouse_over", self.mouse_over, False + + def render(self) -> RenderableType: + # Apply colours only inside render_styled + # Pass the full RICH style object into `render` - not the `Styles` + return Panel( + Align.center( + Pretty(self, no_wrap=True, overflow="ellipsis"), + vertical="middle", + ), + title=self.title or self.__class__.__name__, + border_style="green" if self.mouse_over else "blue", + box=box.HEAVY if self.has_focus else box.ROUNDED, + ) + + async def on_focus(self, event: events.Focus) -> None: + self.has_focus = True + + async def on_blur(self, event: events.Blur) -> None: + self.has_focus = False + + async def on_enter(self, event: events.Enter) -> None: + self.mouse_over = True + + async def on_leave(self, event: events.Leave) -> None: + self.mouse_over = False diff --git a/testbed/Textualize__textual/src/textual/widgets/_pretty.py b/testbed/Textualize__textual/src/textual/widgets/_pretty.py new file mode 100644 index 0000000000000000000000000000000000000000..ff43350f5e29ae2183773509e9268f9f6e925b37 --- /dev/null +++ b/testbed/Textualize__textual/src/textual/widgets/_pretty.py @@ -0,0 +1,36 @@ +from __future__ import annotations + +from typing import Any +from rich.pretty import Pretty as PrettyRenderable + +from ..widget import Widget + + +class Pretty(Widget): + DEFAULT_CSS = """ + Static { + height: auto; + } + """ + + def __init__( + self, + object: Any, + *, + name: str | None = None, + id: str | None = None, + classes: str | None = None, + ) -> None: + super().__init__( + name=name, + id=id, + classes=classes, + ) + self._renderable = PrettyRenderable(object) + + def render(self) -> PrettyRenderable: + return self._renderable + + def update(self, object: Any) -> None: + self._renderable = PrettyRenderable(object) + self.refresh(layout=True) diff --git a/testbed/Textualize__textual/src/textual/widgets/_static.py b/testbed/Textualize__textual/src/textual/widgets/_static.py new file mode 100644 index 0000000000000000000000000000000000000000..0d5004baec81e3adc7d22bb30857aa4fcd3c4d80 --- /dev/null +++ b/testbed/Textualize__textual/src/textual/widgets/_static.py @@ -0,0 +1,98 @@ +from __future__ import annotations + +from rich.console import RenderableType +from rich.protocol import is_renderable +from rich.text import Text + +from ..errors import RenderError +from ..widget import Widget + + +def _check_renderable(renderable: object): + """Check if a renderable conforms to the Rich Console protocol + (https://rich.readthedocs.io/en/latest/protocol.html) + + Args: + renderable (object): A potentially renderable object. + + Raises: + RenderError: If the object can not be rendered. + """ + if not is_renderable(renderable): + raise RenderError( + f"unable to render {renderable!r}; a string, Text, or other Rich renderable is required" + ) + + +class Static(Widget): + """A widget to display simple static content, or use as a base class for more complex widgets. + + Args: + renderable (RenderableType, optional): A Rich renderable, or string containing console markup. + Defaults to "". + expand (bool, optional): Expand content if required to fill container. Defaults to False. + shrink (bool, optional): Shrink content if required to fill container. Defaults to False. + markup (bool, optional): True if markup should be parsed and rendered. Defaults to True. + name (str | None, optional): Name of widget. Defaults to None. + id (str | None, optional): ID of Widget. Defaults to None. + classes (str | None, optional): Space separated list of class names. Defaults to None. + """ + + DEFAULT_CSS = """ + Static { + height: auto; + } + """ + + _renderable: RenderableType + + def __init__( + self, + renderable: RenderableType = "", + *, + expand: bool = False, + shrink: bool = False, + markup: bool = True, + name: str | None = None, + id: str | None = None, + classes: str | None = None, + ) -> None: + + super().__init__(name=name, id=id, classes=classes) + self.expand = expand + self.shrink = shrink + self.markup = markup + self.renderable = renderable + _check_renderable(renderable) + + @property + def renderable(self) -> RenderableType: + return self._renderable or "" + + @renderable.setter + def renderable(self, renderable: RenderableType) -> None: + if isinstance(renderable, str): + if self.markup: + self._renderable = Text.from_markup(renderable) + else: + self._renderable = Text(renderable) + else: + self._renderable = renderable + + def render(self) -> RenderableType: + """Get a rich renderable for the widget's content. + + Returns: + RenderableType: A rich renderable. + """ + return self._renderable + + def update(self, renderable: RenderableType = "") -> None: + """Update the widget's content area with new text or Rich renderable. + + Args: + renderable (RenderableType, optional): A new rich renderable. Defaults to empty renderable; + """ + _check_renderable(renderable) + self.renderable = renderable + self.refresh(layout=True) diff --git a/testbed/Textualize__textual/src/textual/widgets/_text_log.py b/testbed/Textualize__textual/src/textual/widgets/_text_log.py new file mode 100644 index 0000000000000000000000000000000000000000..d471bb5b227ac9ab3dd0a82a75fcbbf108fdf8ac --- /dev/null +++ b/testbed/Textualize__textual/src/textual/widgets/_text_log.py @@ -0,0 +1,134 @@ +from __future__ import annotations + +from typing import cast + +from rich.console import RenderableType +from rich.highlighter import ReprHighlighter +from rich.pretty import Pretty +from rich.protocol import is_renderable +from rich.segment import Segment +from rich.text import Text + +from ..reactive import var +from ..geometry import Size, Region +from ..scroll_view import ScrollView +from .._cache import LRUCache +from .._segment_tools import line_crop +from .._types import Lines + + +class TextLog(ScrollView, can_focus=True): + DEFAULT_CSS = """ + TextLog{ + background: $surface; + color: $text; + overflow-y: scroll; + } + """ + + max_lines: var[int | None] = var(None) + min_width: var[int] = var(78) + wrap: var[bool] = var(False) + highlight: var[bool] = var(False) + + def __init__( + self, + *, + max_lines: int | None = None, + min_width: int = 78, + wrap: bool = False, + highlight: bool = False, + name: str | None = None, + id: str | None = None, + classes: str | None = None, + ) -> None: + self.max_lines = max_lines + self.lines: list[list[Segment]] = [] + self._line_cache: LRUCache[tuple[int, int, int, int], list[Segment]] + self._line_cache = LRUCache(1024) + self.max_width: int = 0 + self.min_width = min_width + self.wrap = wrap + self.highlight = highlight + self.highlighter = ReprHighlighter() + super().__init__(name=name, id=id, classes=classes) + + def _on_styles_updated(self) -> None: + self._line_cache.clear() + + def write(self, content: RenderableType | object) -> None: + """Write text or a rich renderable. + + Args: + content (RenderableType): Rich renderable (or text). + """ + + renderable: RenderableType + if not is_renderable(content): + renderable = Pretty(content) + else: + if isinstance(content, str): + if self.highlight: + renderable = self.highlighter(content) + else: + renderable = Text(content) + else: + renderable = cast(RenderableType, content) + + console = self.app.console + width = max(self.min_width, self.size.width or self.min_width) + + render_options = console.options.update_width(width) + if not self.wrap: + render_options = render_options.update(overflow="ignore", no_wrap=True) + segments = self.app.console.render(renderable, render_options) + lines = list(Segment.split_lines(segments)) + self.max_width = max( + self.max_width, + max(sum(segment.cell_length for segment in _line) for _line in lines), + ) + self.lines.extend(lines) + + if self.max_lines is not None: + self.lines = self.lines[-self.max_lines :] + self.virtual_size = Size(self.max_width, len(self.lines)) + self.scroll_end(animate=False, speed=100) + + def clear(self) -> None: + """Clear the text log.""" + del self.lines[:] + self.max_width = 0 + self.virtual_size = Size(self.max_width, len(self.lines)) + + def render_line(self, y: int) -> list[Segment]: + scroll_x, scroll_y = self.scroll_offset + return self._render_line(scroll_y + y, scroll_x, self.size.width) + + def render_lines(self, crop: Region) -> Lines: + """Render the widget in to lines. + + Args: + crop (Region): Region within visible area to. + + Returns: + Lines: A list of list of segments + """ + lines = self._styles_cache.render_widget(self, crop) + return lines + + def _render_line(self, y: int, scroll_x: int, width: int) -> list[Segment]: + + if y >= len(self.lines): + return [Segment(" " * width, self.rich_style)] + + key = (y, scroll_x, width, self.max_width) + if key in self._line_cache: + return self._line_cache[key] + + line = self.lines[y] + line = Segment.adjust_line_length( + line, max(self.max_width, width), self.rich_style + ) + line = line_crop(line, scroll_x, scroll_x + width, self.max_width) + self._line_cache[key] = line + return line diff --git a/testbed/Textualize__textual/src/textual/widgets/_tree_control.py b/testbed/Textualize__textual/src/textual/widgets/_tree_control.py new file mode 100644 index 0000000000000000000000000000000000000000..c471e0686d95078ccfc0168b157d8c8d24be244b --- /dev/null +++ b/testbed/Textualize__textual/src/textual/widgets/_tree_control.py @@ -0,0 +1,427 @@ +from __future__ import annotations + + +from typing import ClassVar, Generic, Iterator, NewType, TypeVar + +import rich.repr +from rich.console import RenderableType +from rich.style import Style, NULL_STYLE +from rich.text import Text, TextType +from rich.tree import Tree + +from ..geometry import Region, Size +from .. import events +from ..reactive import Reactive +from .._types import MessageTarget +from ..widgets import Static +from ..message import Message +from .. import messages + + +NodeID = NewType("NodeID", int) + + +NodeDataType = TypeVar("NodeDataType") +EventNodeDataType = TypeVar("EventNodeDataType") + + +@rich.repr.auto +class TreeNode(Generic[NodeDataType]): + def __init__( + self, + parent: TreeNode[NodeDataType] | None, + node_id: NodeID, + control: TreeControl, + tree: Tree, + label: TextType, + data: NodeDataType, + ) -> None: + self.parent = parent + self.id = node_id + self._control = control + self._tree = tree + self.label = label + self.data = data + self.loaded = False + self._expanded = False + self._empty = False + self._tree.expanded = False + self.children: list[TreeNode] = [] + + def __rich_repr__(self) -> rich.repr.Result: + yield "id", self.id + yield "label", self.label + yield "data", self.data + + @property + def control(self) -> TreeControl: + return self._control + + @property + def empty(self) -> bool: + return self._empty + + @property + def expanded(self) -> bool: + return self._expanded + + @property + def is_cursor(self) -> bool: + return self.control.cursor == self.id and self.control.show_cursor + + @property + def tree(self) -> Tree: + return self._tree + + @property + def next_node(self) -> TreeNode[NodeDataType] | None: + """The next node in the tree, or None if at the end.""" + + if self.expanded and self.children: + return self.children[0] + else: + + sibling = self.next_sibling + if sibling is not None: + return sibling + + node = self + while True: + if node.parent is None: + return None + sibling = node.parent.next_sibling + if sibling is not None: + return sibling + else: + node = node.parent + + @property + def previous_node(self) -> TreeNode[NodeDataType] | None: + """The previous node in the tree, or None if at the end.""" + + sibling = self.previous_sibling + if sibling is not None: + + def last_sibling(node) -> TreeNode[NodeDataType]: + if node.expanded and node.children: + return last_sibling(node.children[-1]) + else: + return ( + node.children[-1] if (node.children and node.expanded) else node + ) + + return last_sibling(sibling) + + if self.parent is None: + return None + return self.parent + + @property + def next_sibling(self) -> TreeNode[NodeDataType] | None: + """The next sibling, or None if last sibling.""" + if self.parent is None: + return None + iter_siblings = iter(self.parent.children) + try: + for node in iter_siblings: + if node is self: + return next(iter_siblings) + except StopIteration: + pass + return None + + @property + def previous_sibling(self) -> TreeNode[NodeDataType] | None: + """Previous sibling or None if first sibling.""" + if self.parent is None: + return None + iter_siblings = iter(self.parent.children) + sibling: TreeNode[NodeDataType] | None = None + + for node in iter_siblings: + if node is self: + return sibling + sibling = node + return None + + def expand(self, expanded: bool = True) -> None: + self._expanded = expanded + self._tree.expanded = expanded + self._control.refresh(layout=True) + + def toggle(self) -> None: + self.expand(not self._expanded) + + def add(self, label: TextType, data: NodeDataType) -> None: + self._control.add(self.id, label, data=data) + self._control.refresh(layout=True) + self._empty = False + + def __rich__(self) -> RenderableType: + return self._control.render_node(self) + + +class TreeControl(Generic[NodeDataType], Static, can_focus=True): + DEFAULT_CSS = """ + TreeControl { + color: $text; + height: auto; + width: 100%; + link-style: not underline; + } + + TreeControl > .tree--guides { + color: $success; + } + + TreeControl > .tree--guides-highlight { + color: $success; + text-style: uu; + } + + TreeControl > .tree--guides-cursor { + color: $secondary; + text-style: bold; + } + + TreeControl > .tree--labels { + color: $text; + } + + TreeControl > .tree--cursor { + background: $secondary; + color: $text; + } + + """ + + COMPONENT_CLASSES: ClassVar[set[str]] = { + "tree--guides", + "tree--guides-highlight", + "tree--guides-cursor", + "tree--labels", + "tree--cursor", + } + + class NodeSelected(Generic[EventNodeDataType], Message, bubble=False): + def __init__( + self, sender: MessageTarget, node: TreeNode[EventNodeDataType] + ) -> None: + self.node = node + super().__init__(sender) + + def __init__( + self, + label: TextType, + data: NodeDataType, + *, + name: str | None = None, + id: str | None = None, + classes: str | None = None, + ) -> None: + super().__init__(name=name, id=id, classes=classes) + self.data = data + + self.node_id = NodeID(0) + self.nodes: dict[NodeID, TreeNode[NodeDataType]] = {} + self._tree = Tree(label) + + self.root: TreeNode[NodeDataType] = TreeNode( + None, self.node_id, self, self._tree, label, data + ) + + self._tree.label = self.root + self.nodes[NodeID(self.node_id)] = self.root + + self.auto_links = False + + hover_node: Reactive[NodeID | None] = Reactive(None) + cursor: Reactive[NodeID] = Reactive(NodeID(0)) + cursor_line: Reactive[int] = Reactive(0) + show_cursor: Reactive[bool] = Reactive(False) + + def watch_cursor_line(self, value: int) -> None: + line_region = Region(0, value, self.size.width, 1) + self.emit_no_wait(messages.ScrollToRegion(self, line_region)) + + def get_content_height(self, container: Size, viewport: Size, width: int) -> int: + def get_size(tree: Tree) -> int: + return 1 + sum( + get_size(child) if child.expanded else 1 for child in tree.children + ) + + size = get_size(self._tree) + return size + + def add( + self, + node_id: NodeID, + label: TextType, + data: NodeDataType, + ) -> None: + + parent = self.nodes[node_id] + self.node_id = NodeID(self.node_id + 1) + child_tree = parent._tree.add(label) + child_tree.guide_style = self._guide_style + child_node: TreeNode[NodeDataType] = TreeNode( + parent, self.node_id, self, child_tree, label, data + ) + parent.children.append(child_node) + child_tree.label = child_node + self.nodes[self.node_id] = child_node + + self.refresh(layout=True) + + def find_cursor(self) -> int | None: + """Find the line location for the cursor node.""" + + node_id = self.cursor + line = 0 + + stack: list[Iterator[TreeNode[NodeDataType]]] + stack = [iter([self.root])] + + pop = stack.pop + push = stack.append + while stack: + iter_children = pop() + try: + node = next(iter_children) + except StopIteration: + continue + else: + if node.id == node_id: + return line + line += 1 + push(iter_children) + if node.children and node.expanded: + push(iter(node.children)) + return None + + def render(self) -> RenderableType: + guide_style = self._guide_style + + def update_guide_style(tree: Tree) -> None: + tree.guide_style = guide_style + for child in tree.children: + if child.expanded: + update_guide_style(child) + + update_guide_style(self._tree) + if self.hover_node is not None: + hover = self.nodes.get(self.hover_node) + if hover is not None: + hover._tree.guide_style = self._highlight_guide_style + if self.cursor is not None and self.show_cursor: + cursor = self.nodes.get(self.cursor) + if cursor is not None: + cursor._tree.guide_style = self._cursor_guide_style + return self._tree + + def render_node(self, node: TreeNode[NodeDataType]) -> RenderableType: + label_style = self.get_component_styles("tree--labels").rich_style + label = ( + Text(node.label, no_wrap=True, style=label_style, overflow="ellipsis") + if isinstance(node.label, str) + else node.label + ) + if node.id == self.hover_node: + label.stylize("underline") + label.apply_meta({"@click": f"click_label({node.id})", "tree_node": node.id}) + return label + + def action_click_label(self, node_id: NodeID) -> None: + node = self.nodes[node_id] + self.cursor = node.id + self.cursor_line = self.find_cursor() or 0 + self.show_cursor = True + self.post_message_no_wait(self.NodeSelected(self, node)) + + def on_mount(self) -> None: + self._tree.guide_style = self._guide_style + + @property + def _guide_style(self) -> Style: + return self.get_component_rich_style("tree--guides") + + @property + def _highlight_guide_style(self) -> Style: + return self.get_component_rich_style("tree--guides-highlight") + + @property + def _cursor_guide_style(self) -> Style: + return self.get_component_rich_style("tree--guides-cursor") + + def on_mouse_move(self, event: events.MouseMove) -> None: + self.hover_node = event.style.meta.get("tree_node") + + def key_down(self, event: events.Key) -> None: + event.stop() + self.cursor_down() + + def key_up(self, event: events.Key) -> None: + event.stop() + self.cursor_up() + + def key_pagedown(self) -> None: + assert self.parent is not None + height = self.container_viewport.height + + cursor = self.cursor + cursor_line = self.cursor_line + for _ in range(height): + cursor_node = self.nodes[cursor] + next_node = cursor_node.next_node + if next_node is not None: + cursor_line += 1 + cursor = next_node.id + self.cursor = cursor + self.cursor_line = cursor_line + + def key_pageup(self) -> None: + assert self.parent is not None + height = self.container_viewport.height + cursor = self.cursor + cursor_line = self.cursor_line + for _ in range(height): + cursor_node = self.nodes[cursor] + previous_node = cursor_node.previous_node + if previous_node is not None: + cursor_line -= 1 + cursor = previous_node.id + self.cursor = cursor + self.cursor_line = cursor_line + + def key_home(self) -> None: + self.cursor_line = 0 + self.cursor = NodeID(0) + + def key_end(self) -> None: + self.cursor = self.nodes[NodeID(0)].children[-1].id + self.cursor_line = self.find_cursor() or 0 + + def key_enter(self, event: events.Key) -> None: + cursor_node = self.nodes[self.cursor] + event.stop() + self.post_message_no_wait(self.NodeSelected(self, cursor_node)) + + def cursor_down(self) -> None: + if not self.show_cursor: + self.show_cursor = True + return + cursor_node = self.nodes[self.cursor] + next_node = cursor_node.next_node + if next_node is not None: + self.cursor_line += 1 + self.cursor = next_node.id + + def cursor_up(self) -> None: + if not self.show_cursor: + self.show_cursor = True + return + cursor_node = self.nodes[self.cursor] + previous_node = cursor_node.previous_node + if previous_node is not None: + self.cursor_line -= 1 + self.cursor = previous_node.id diff --git a/testbed/Textualize__textual/src/textual/widgets/tabs.py b/testbed/Textualize__textual/src/textual/widgets/tabs.py new file mode 100644 index 0000000000000000000000000000000000000000..48381586a17fc9531687988fb298829f13a3f09c --- /dev/null +++ b/testbed/Textualize__textual/src/textual/widgets/tabs.py @@ -0,0 +1,342 @@ +from __future__ import annotations + +import string +from dataclasses import dataclass +from typing import Iterable + +from rich.cells import cell_len +from rich.console import Console, ConsoleOptions, RenderableType, RenderResult +from rich.segment import Segment +from rich.style import StyleType, Style +from rich.text import Text + +from textual import events +from textual._layout_resolve import layout_resolve, Edge +from textual.keys import Keys +from textual.reactive import Reactive +from textual.renderables.text_opacity import TextOpacity +from textual.renderables.underline_bar import UnderlineBar +from textual.widget import Widget + +__all__ = ["Tab", "Tabs"] + + +@dataclass +class Tab: + """Data container representing a single tab. + + Attributes: + label (str): The user-facing label that will appear inside the tab. + name (str, optional): A unique string key that will identify the tab. If None, it will default to the label. + If the name is not unique within a single list of tabs, only the final Tab will be displayed. + """ + + label: str + name: str | None = None + + def __post_init__(self): + if self.name is None: + self.name = self.label + + def __str__(self): + return self.label + + +class TabsRenderable: + """Renderable for the Tabs widget.""" + + def __init__( + self, + tabs: Iterable[Tab], + *, + active_tab_name: str, + active_tab_style: StyleType, + active_bar_style: StyleType, + inactive_tab_style: StyleType, + inactive_bar_style: StyleType, + inactive_text_opacity: float, + tab_padding: int | None, + bar_offset: float, + width: int | None = None, + ): + self.tabs = {tab.name: tab for tab in tabs} + + try: + self.active_tab_name = active_tab_name or next(iter(self.tabs)) + except StopIteration: + self.active_tab_name = None + + self.active_tab_style = active_tab_style + self.active_bar_style = active_bar_style + + self.inactive_tab_style = inactive_tab_style + self.inactive_bar_style = inactive_bar_style + + self.bar_offset = bar_offset + self.width = width + self.tab_padding = tab_padding + self.inactive_text_opacity = inactive_text_opacity + + self._label_range_cache: dict[str, tuple[int, int]] = {} + self._selection_range_cache: dict[str, tuple[int, int]] = {} + + def __rich_console__( + self, console: Console, options: ConsoleOptions + ) -> RenderResult: + if self.tabs: + yield from self.get_tab_labels(console, options) + yield Segment.line() + yield from self.get_underline_bar(console) + + def get_tab_labels(self, console: Console, options: ConsoleOptions) -> RenderResult: + """Yields the spaced-out labels that appear above the line for the Tabs widget""" + width = self.width or options.max_width + tab_values = self.tabs.values() + + space = Edge(size=self.tab_padding or None, min_size=1, fraction=1) + edges = [] + for tab in tab_values: + tab = Edge(size=cell_len(tab.label), min_size=1, fraction=None) + edges.extend([space, tab, space]) + + spacing = layout_resolve(width, edges=edges) + + active_tab_style = console.get_style(self.active_tab_style) + inactive_tab_style = console.get_style(self.inactive_tab_style) + + label_cell_cursor = 0 + for tab_index, tab in enumerate(tab_values): + tab_edge_index = tab_index * 3 + 1 + + len_label_text = spacing[tab_edge_index] + lpad = spacing[tab_edge_index - 1] + rpad = spacing[tab_edge_index + 1] + + label_left_padding = Text(" " * lpad, end="") + label_right_padding = Text(" " * rpad, end="") + + padded_label = f"{label_left_padding}{tab.label}{label_right_padding}" + if tab.name == self.active_tab_name: + yield Text(padded_label, end="", style=active_tab_style) + else: + tab_content = Text( + padded_label, + end="", + style=inactive_tab_style + + Style.from_meta({"@click": f"range_clicked('{tab.name}')"}), + ) + dimmed_tab_content = TextOpacity( + tab_content, opacity=self.inactive_text_opacity + ) + segments = console.render(dimmed_tab_content) + yield from segments + + # Cache the position of the label text within this tab + label_cell_cursor += lpad + self._label_range_cache[tab.name] = ( + label_cell_cursor, + label_cell_cursor + len_label_text, + ) + label_cell_cursor += len_label_text + rpad + + # Cache the position of the whole tab, i.e. the range that can be clicked + self._selection_range_cache[tab.name] = ( + label_cell_cursor - lpad, + label_cell_cursor + len_label_text + rpad, + ) + + def get_underline_bar(self, console: Console) -> RenderResult: + """Yields the bar that appears below the tab labels in the Tabs widget""" + if self.tabs: + ranges = self._label_range_cache + tab_index = int(self.bar_offset) + next_tab_index = (tab_index + 1) % len(ranges) + range_values = list(ranges.values()) + tab1_start, tab1_end = range_values[tab_index] + tab2_start, tab2_end = range_values[next_tab_index] + + bar_start = tab1_start + (tab2_start - tab1_start) * ( + self.bar_offset - tab_index + ) + bar_end = tab1_end + (tab2_end - tab1_end) * (self.bar_offset - tab_index) + else: + bar_start = 0 + bar_end = 0 + underline = UnderlineBar( + highlight_range=(bar_start, bar_end), + highlight_style=self.active_bar_style, + background_style=self.inactive_bar_style, + clickable_ranges=self._selection_range_cache, + ) + yield from console.render(underline) + + +class Tabs(Widget): + """Widget which displays a set of horizontal tabs. + + Args: + tabs (list[Tab]): A list of Tab objects defining the tabs which should be rendered. + active_tab (str, optional): The name of the tab that should be active on first render. + active_tab_style (StyleType): Style to apply to the label of the active tab. + active_bar_style (StyleType): Style to apply to the underline of the active tab. + inactive_tab_style (StyleType): Style to apply to the label of inactive tabs. + inactive_bar_style (StyleType): Style to apply to the underline of inactive tabs. + inactive_text_opacity (float): Opacity of the text labels of inactive tabs. + animation_duration (float): The duration of the tab change animation, in seconds. + animation_function (str): The easing function to use for the tab change animation. + tab_padding (int, optional): The padding at the side of each tab. If None, tabs will + automatically be padded such that they fit the available horizontal space. + search_by_first_character (bool): If True, entering a character on your keyboard + will activate the next tab (in left-to-right order) with a label starting with + that character. + """ + + _active_tab_name: Reactive[str | None] = Reactive("") + _bar_offset: Reactive[float] = Reactive(0.0) + + def __init__( + self, + tabs: list[Tab], + active_tab: str | None = None, + active_tab_style: StyleType = "#f0f0f0 on #021720", + active_bar_style: StyleType = "#1BB152", + inactive_tab_style: StyleType = "#f0f0f0 on #021720", + inactive_bar_style: StyleType = "#455058", + inactive_text_opacity: float = 0.5, + animation_duration: float = 0.3, + animation_function: str = "out_cubic", + tab_padding: int | None = None, + search_by_first_character: bool = True, + ) -> None: + super().__init__() + self.tabs = tabs + + self._bar_offset = float(self.find_tab_by_name(active_tab) or 0) + self._active_tab_name = active_tab or next(iter(self.tabs), None) + + self.active_tab_style = active_tab_style + self.active_bar_style = active_bar_style + + self.inactive_bar_style = inactive_bar_style + self.inactive_tab_style = inactive_tab_style + self.inactive_text_opacity = inactive_text_opacity + + self.animation_function = animation_function + self.animation_duration = animation_duration + + self.tab_padding = tab_padding + + self.search_by_first_character = search_by_first_character + + def on_key(self, event: events.Key) -> None: + """Handles key press events when this widget is in focus. + Pressing "escape" removes focus from this widget. Use the left and + right arrow keys to cycle through tabs. Use number keys to jump to tabs + based in their number ("1" jumps to the leftmost tab). Type a character + to cycle through tabs with labels beginning with that character. + + Args: + event (events.Key): The Key event being handled + """ + if not self.tabs: + event.prevent_default() + return + + if event.key == Keys.Escape: + self.app.set_focus(None) + elif event.key == Keys.Right: + self.activate_next_tab() + elif event.key == Keys.Left: + self.activate_previous_tab() + elif event.key in string.digits: + self.activate_tab_by_number(int(event.key)) + elif self.search_by_first_character: + self.activate_tab_by_first_char(event.key) + + event.prevent_default() + + def activate_next_tab(self) -> None: + """Activate the tab to the right of the currently active tab""" + current_tab_index = self.find_tab_by_name(self._active_tab_name) + next_tab_index = (current_tab_index + 1) % len(self.tabs) + next_tab_name = self.tabs[next_tab_index].name + self._active_tab_name = next_tab_name + + def activate_previous_tab(self) -> None: + """Activate the tab to the left of the currently active tab""" + current_tab_index = self.find_tab_by_name(self._active_tab_name) + previous_tab_index = current_tab_index - 1 + previous_tab_name = self.tabs[previous_tab_index].name + self._active_tab_name = previous_tab_name + + def activate_tab_by_first_char(self, char: str) -> None: + """Activate the next tab that begins with the character + + Args: + char (str): The character to search for + """ + + def find_next_matching_tab( + char: str, start: int | None, end: int | None + ) -> Tab | None: + for tab in self.tabs[start:end]: + if tab.label.lower().startswith(char.lower()): + return tab + + current_tab_index = self.find_tab_by_name(self._active_tab_name) + next_tab_index = (current_tab_index + 1) % len(self.tabs) + + next_matching_tab = find_next_matching_tab(char, next_tab_index, None) + if not next_matching_tab: + next_matching_tab = find_next_matching_tab(char, None, current_tab_index) + + if next_matching_tab: + self._active_tab_name = next_matching_tab.name + + def activate_tab_by_number(self, tab_number: int) -> None: + """Activate a tab using the tab number. + + Args: + tab_number (int): The number of the tab. + The leftmost tab is number 1, the next is 2, and so on. 0 represents the 10th tab. + """ + if tab_number > len(self.tabs): + return + if tab_number == 0 and len(self.tabs) >= 10: + tab_number = 10 + self._active_tab_name = self.tabs[tab_number - 1].name + + def action_range_clicked(self, target_tab_name: str) -> None: + """Handles 'range_clicked' actions which are fired when tabs are clicked""" + self._active_tab_name = target_tab_name + + def watch__active_tab_name(self, tab_name: str) -> None: + """Animates the underline bar position when the active tab changes""" + target_tab_index = self.find_tab_by_name(tab_name) + self.animate( + "_bar_offset", + float(target_tab_index), + easing=self.animation_function, + duration=self.animation_duration, + ) + + def find_tab_by_name(self, tab_name: str) -> int: + """Return the index of the first tab with a certain name + + Args: + tab_name (str): The name to search for. + """ + return next((i for i, tab in enumerate(self.tabs) if tab.name == tab_name), 0) + + def render(self) -> RenderableType: + return TabsRenderable( + self.tabs, + tab_padding=self.tab_padding, + active_tab_name=self._active_tab_name, + active_tab_style=self.active_tab_style, + active_bar_style=self.active_bar_style, + inactive_tab_style=self.inactive_tab_style, + inactive_bar_style=self.inactive_bar_style, + bar_offset=self._bar_offset, + inactive_text_opacity=self.inactive_text_opacity, + ) diff --git a/testbed/Textualize__textual/tests/__init__.py b/testbed/Textualize__textual/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/testbed/Textualize__textual/tests/cli/test_cli.py b/testbed/Textualize__textual/tests/cli/test_cli.py new file mode 100644 index 0000000000000000000000000000000000000000..3909ba67c75fc228567055e9b0a087d5d95825b3 --- /dev/null +++ b/testbed/Textualize__textual/tests/cli/test_cli.py @@ -0,0 +1,10 @@ +from click.testing import CliRunner +from importlib_metadata import version + +from textual.cli.cli import run + + +def test_cli_version(): + runner = CliRunner() + result = runner.invoke(run, ["--version"]) + assert version("textual") in result.output diff --git a/testbed/Textualize__textual/tests/css/test_scalar.py b/testbed/Textualize__textual/tests/css/test_scalar.py new file mode 100644 index 0000000000000000000000000000000000000000..c7add3d8265a666cc20a23d387f99a2ad0ab9050 --- /dev/null +++ b/testbed/Textualize__textual/tests/css/test_scalar.py @@ -0,0 +1,19 @@ +from textual.css.scalar import Scalar, Unit + + +def test_copy_with_value(): + old = Scalar(1, Unit.HEIGHT, Unit.CELLS) + new = old.copy_with(value=2) + assert new == Scalar(2, Unit.HEIGHT, Unit.CELLS) + + +def test_copy_with_unit(): + old = Scalar(1, Unit.HEIGHT, Unit.CELLS) + new = old.copy_with(unit=Unit.WIDTH) + assert new == Scalar(1, Unit.WIDTH, Unit.CELLS) + + +def test_copy_with_percent_unit(): + old = Scalar(1, Unit.HEIGHT, Unit.CELLS) + new = old.copy_with(percent_unit=Unit.FRACTION) + assert new == Scalar(1, Unit.HEIGHT, Unit.FRACTION) diff --git a/testbed/Textualize__textual/tests/css/test_styles.py b/testbed/Textualize__textual/tests/css/test_styles.py new file mode 100644 index 0000000000000000000000000000000000000000..a7c574ecc906098afec40b4a999b6d36deeb3e50 --- /dev/null +++ b/testbed/Textualize__textual/tests/css/test_styles.py @@ -0,0 +1,293 @@ +import sys +from decimal import Decimal + +if sys.version_info >= (3, 10): + from typing import Literal +else: # pragma: no cover + from typing_extensions import Literal + +import pytest + +from rich.style import Style + +from textual.app import ComposeResult +from textual.color import Color +from textual.css.errors import StyleValueError +from textual.css.scalar import Scalar, Unit +from textual.css.styles import Styles, RenderStyles +from textual.dom import DOMNode +from textual.widget import Widget + +from tests.utilities.test_app import AppTest + + +def test_styles_reset(): + styles = Styles() + styles.text_style = "not bold" + assert styles.text_style == Style(bold=False) + styles.reset() + assert styles.text_style is Style.null() + + +def test_has_rule(): + styles = Styles() + assert not styles.has_rule("text_style") + styles.text_style = "bold" + assert styles.has_rule("text_style") + styles.text_style = None + assert not styles.has_rule("text_style") + + +def test_clear_rule(): + styles = Styles() + styles.text_style = "bold" + assert styles.has_rule("text_style") + styles.clear_rule("text_style") + assert not styles.has_rule("text_style") + + +def test_get_rules(): + styles = Styles() + # Empty rules at start + assert styles.get_rules() == {} + styles.text_style = "bold" + assert styles.get_rules() == {"text_style": Style.parse("bold")} + styles.display = "none" + assert styles.get_rules() == { + "text_style": Style.parse("bold"), + "display": "none", + } + + +def test_set_rule(): + styles = Styles() + assert styles.get_rules() == {} + styles.set_rule("text_style", Style.parse("bold")) + assert styles.get_rules() == {"text_style": Style.parse("bold")} + + +def test_reset(): + styles = Styles() + assert styles.get_rules() == {} + styles.set_rule("text_style", Style.parse("bold")) + assert styles.get_rules() == {"text_style": Style.parse("bold")} + styles.reset() + assert styles.get_rules() == {} + + +def test_merge(): + styles = Styles() + styles.set_rule("text_style", Style.parse("bold")) + styles2 = Styles() + styles2.set_rule("display", "none") + styles.merge(styles2) + assert styles.get_rules() == { + "text_style": Style.parse("bold"), + "display": "none", + } + + +def test_merge_rules(): + styles = Styles() + styles.set_rule("text_style", Style.parse("bold")) + styles.merge_rules({"display": "none"}) + assert styles.get_rules() == { + "text_style": Style.parse("bold"), + "display": "none", + } + + +def test_render_styles_border(): + base = Styles() + inline = Styles() + styles_view = RenderStyles(None, base, inline) + + base.border_top = ("heavy", "red") + # Base has border-top: heavy red + assert styles_view.border_top == ("heavy", Color.parse("red")) + + inline.border_left = ("rounded", "green") + # Base has border-top heavy red, inline has border-left: rounded green + assert styles_view.border_top == ("heavy", Color.parse("red")) + assert styles_view.border_left == ("rounded", Color.parse("green")) + assert styles_view.border == ( + ("heavy", Color.parse("red")), + ("", Color(0, 255, 0)), + ("", Color(0, 255, 0)), + ("rounded", Color.parse("green")), + ) + + +def test_get_opacity_default(): + styles = RenderStyles(DOMNode(), Styles(), Styles()) + assert styles.text_opacity == 1.0 + + +def test_styles_css_property(): + css = "opacity: 50%; text-opacity: 20%; background: green; color: red; tint: dodgerblue 20%;" + styles = Styles().parse(css, path="") + assert styles.css == ( + "background: #008000;\n" + "color: #FF0000;\n" + "opacity: 0.5;\n" + "text-opacity: 0.2;\n" + "tint: rgba(30,144,255,0.2);" + ) + + +@pytest.mark.parametrize( + "set_value, expected", + [ + [0.2, 0.2], + [-0.4, 0.0], + [5.8, 1.0], + ["25%", 0.25], + ["-10%", 0.0], + ["120%", 1.0], + ], +) +def test_opacity_set_then_get(set_value, expected): + styles = RenderStyles(DOMNode(), Styles(), Styles()) + styles.text_opacity = set_value + assert styles.text_opacity == expected + + +def test_opacity_set_invalid_type_error(): + styles = RenderStyles(DOMNode(), Styles(), Styles()) + with pytest.raises(StyleValueError): + styles.text_opacity = "invalid value" + + +@pytest.mark.parametrize( + "size_dimension_input,size_dimension_expected_output", + [ + # fmt: off + [None, None], + [1, Scalar(1, Unit.CELLS, Unit.WIDTH)], + [1.0, Scalar(1.0, Unit.CELLS, Unit.WIDTH)], + [1.2, Scalar(1.2, Unit.CELLS, Unit.WIDTH)], + [1.2e3, Scalar(1200.0, Unit.CELLS, Unit.WIDTH)], + ["20", Scalar(20, Unit.CELLS, Unit.WIDTH)], + ["1.4", Scalar(1.4, Unit.CELLS, Unit.WIDTH)], + [Scalar(100, Unit.CELLS, Unit.WIDTH), Scalar(100, Unit.CELLS, Unit.WIDTH)], + [Scalar(10.3, Unit.CELLS, Unit.WIDTH), Scalar(10.3, Unit.CELLS, Unit.WIDTH)], + [Scalar(10.4, Unit.CELLS, Unit.HEIGHT), Scalar(10.4, Unit.CELLS, Unit.HEIGHT)], + [Scalar(10.5, Unit.PERCENT, Unit.WIDTH), Scalar(10.5, Unit.WIDTH, Unit.WIDTH)], + [Scalar(10.6, Unit.PERCENT, Unit.PERCENT), Scalar(10.6, Unit.WIDTH, Unit.WIDTH)], + [Scalar(10.7, Unit.HEIGHT, Unit.PERCENT), Scalar(10.7, Unit.HEIGHT, Unit.PERCENT)], + # percentage values are normalised to floats and get the WIDTH "percent_unit": + [Scalar(11, Unit.PERCENT, Unit.HEIGHT), Scalar(11.0, Unit.WIDTH, Unit.WIDTH)], + # fmt: on + ], +) +def test_widget_style_size_can_accept_various_data_types_and_normalize_them( + size_dimension_input, size_dimension_expected_output +): + widget = Widget() + + widget.styles.width = size_dimension_input + assert widget.styles.width == size_dimension_expected_output + + +@pytest.mark.parametrize( + "size_dimension_input", + [ + "a", + "1.4e3", + 3.14j, + Decimal("3.14"), + list(), + tuple(), + dict(), + ], +) +def test_widget_style_size_fails_if_data_type_is_not_supported(size_dimension_input): + widget = Widget() + + with pytest.raises(StyleValueError): + widget.styles.width = size_dimension_input + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "overflow_y,scrollbar_gutter,scrollbar_size,text_length,expected_text_widget_width,expects_vertical_scrollbar", + ( + # ------------------------------------------------ + # ----- Let's start with `overflow-y: auto`: + # short text: full width, no scrollbar + ["auto", "auto", 1, "short_text", 80, False], + # long text: reduced width, scrollbar + ["auto", "auto", 1, "long_text", 78, True], + # short text, `scrollbar-gutter: stable`: reduced width, no scrollbar + ["auto", "stable", 1, "short_text", 78, False], + # long text, `scrollbar-gutter: stable`: reduced width, scrollbar + ["auto", "stable", 1, "long_text", 78, True], + # ------------------------------------------------ + # ----- And now let's see the behaviour with `overflow-y: scroll`: + # short text: reduced width, scrollbar + ["scroll", "auto", 1, "short_text", 78, True], + # long text: reduced width, scrollbar + ["scroll", "auto", 1, "long_text", 78, True], + # short text, `scrollbar-gutter: stable`: reduced width, scrollbar + ["scroll", "stable", 1, "short_text", 78, True], + # long text, `scrollbar-gutter: stable`: reduced width, scrollbar + ["scroll", "stable", 1, "long_text", 78, True], + # ------------------------------------------------ + # ----- Finally, let's check the behaviour with `overflow-y: hidden`: + # short text: full width, no scrollbar + ["hidden", "auto", 1, "short_text", 80, False], + # long text: full width, no scrollbar + ["hidden", "auto", 1, "long_text", 80, False], + # short text, `scrollbar-gutter: stable`: reduced width, no scrollbar + ["hidden", "stable", 1, "short_text", 78, False], + # long text, `scrollbar-gutter: stable`: reduced width, no scrollbar + ["hidden", "stable", 1, "long_text", 78, False], + # ------------------------------------------------ + # ----- Bonus round with a custom scrollbar size, now that we can set this: + ["auto", "auto", 3, "short_text", 80, False], + ["auto", "auto", 3, "long_text", 77, True], + ["scroll", "auto", 3, "short_text", 77, True], + ["scroll", "stable", 3, "short_text", 77, True], + ["hidden", "auto", 3, "long_text", 80, False], + ["hidden", "stable", 3, "short_text", 77, False], + ), +) +async def test_scrollbar_gutter( + overflow_y: str, + scrollbar_gutter: str, + scrollbar_size: int, + text_length: Literal["short_text", "long_text"], + expected_text_widget_width: int, + expects_vertical_scrollbar: bool, +): + from rich.text import Text + from textual.geometry import Size + + class TextWidget(Widget): + def render(self) -> Text: + text_multiplier = 10 if text_length == "long_text" else 2 + return Text( + "Lorem ipsum dolor sit amet, consectetur adipiscing elit. In velit liber a a a." + * text_multiplier + ) + + container = Widget() + container.styles.height = 3 + container.styles.overflow_y = overflow_y + container.styles.scrollbar_gutter = scrollbar_gutter + if scrollbar_size > 1: + container.styles.scrollbar_size_vertical = scrollbar_size + + text_widget = TextWidget() + text_widget.styles.height = "auto" + container._add_child(text_widget) + + class MyTestApp(AppTest): + def compose(self) -> ComposeResult: + yield container + + app = MyTestApp(test_name="scrollbar_gutter", size=Size(80, 10)) + await app.boot_and_shutdown() + + assert text_widget.outer_size.width == expected_text_widget_width + assert container.scrollbars_enabled[0] is expects_vertical_scrollbar diff --git a/testbed/Textualize__textual/tests/css/test_stylesheet.py b/testbed/Textualize__textual/tests/css/test_stylesheet.py new file mode 100644 index 0000000000000000000000000000000000000000..be54fe936a31558221e3428386ff15d68333acaf --- /dev/null +++ b/testbed/Textualize__textual/tests/css/test_stylesheet.py @@ -0,0 +1,250 @@ +from contextlib import nullcontext as does_not_raise +from typing import Any + +import pytest + +from textual.color import Color +from textual.css._help_renderables import HelpText +from textual.css.stylesheet import Stylesheet, StylesheetParseError, CssSource +from textual.css.tokenizer import TokenError +from textual.dom import DOMNode +from textual.geometry import Spacing +from textual.widget import Widget + + +def _make_user_stylesheet(css: str) -> Stylesheet: + stylesheet = Stylesheet() + stylesheet.source["test.css"] = CssSource(css, is_defaults=False) + stylesheet.parse() + return stylesheet + + +def test_stylesheet_apply_highest_specificity_wins(): + """#ids have higher specificity than .classes""" + css = "#id {color: red;} .class {color: blue;}" + stylesheet = _make_user_stylesheet(css) + node = DOMNode(classes="class", id="id") + stylesheet.apply(node) + + assert node.styles.color == Color(255, 0, 0) + + +def test_stylesheet_apply_doesnt_override_defaults(): + css = "#id {color: red;}" + stylesheet = _make_user_stylesheet(css) + node = DOMNode(id="id") + stylesheet.apply(node) + + assert node.styles.margin == Spacing.all(0) + assert node.styles.box_sizing == "border-box" + + +def test_stylesheet_apply_highest_specificity_wins_multiple_classes(): + """When we use two selectors containing only classes, then the selector + `.b.c` has greater specificity than the selector `.a`""" + css = ".b.c {background: blue;} .a {background: red; color: lime;}" + stylesheet = _make_user_stylesheet(css) + node = DOMNode(classes="a b c") + stylesheet.apply(node) + + assert node.styles.background == Color(0, 0, 255) + assert node.styles.color == Color(0, 255, 0) + + +def test_stylesheet_many_classes_dont_overrule_id(): + """#id is further to the left in the specificity tuple than class, and + a selector containing multiple classes cannot take priority over even a + single class.""" + css = "#id {color: red;} .a.b.c.d {color: blue;}" + stylesheet = _make_user_stylesheet(css) + node = DOMNode(classes="a b c d", id="id") + stylesheet.apply(node) + + assert node.styles.color == Color(255, 0, 0) + + +def test_stylesheet_last_rule_wins_when_same_rule_twice_in_one_ruleset(): + css = "#id {color: red; color: blue;}" + stylesheet = _make_user_stylesheet(css) + node = DOMNode(id="id") + stylesheet.apply(node) + + assert node.styles.color == Color(0, 0, 255) + + +def test_stylesheet_rulesets_merged_for_duplicate_selectors(): + css = "#id {color: red; background: lime;} #id {color:blue;}" + stylesheet = _make_user_stylesheet(css) + node = DOMNode(id="id") + stylesheet.apply(node) + + assert node.styles.color == Color(0, 0, 255) + assert node.styles.background == Color(0, 255, 0) + + +def test_stylesheet_apply_takes_final_rule_in_specificity_clash(): + """.a and .b both contain background and have same specificity, so .b wins + since it was declared last - the background should be blue.""" + css = ".a {background: red; color: lime;} .b {background: blue;}" + stylesheet = _make_user_stylesheet(css) + node = DOMNode(classes="a b", id="c") + stylesheet.apply(node) + + assert node.styles.color == Color(0, 255, 0) # color: lime + assert node.styles.background == Color(0, 0, 255) # background: blue + + +def test_stylesheet_apply_empty_rulesets(): + """Ensure that we don't crash when working with empty rulesets""" + css = ".a {} .b {}" + stylesheet = _make_user_stylesheet(css) + node = DOMNode(classes="a b") + stylesheet.apply(node) + + +def test_stylesheet_apply_user_css_over_widget_css(): + user_css = ".a {color: red; tint: yellow;}" + + class MyWidget(Widget): + DEFAULT_CSS = ".a {color: blue !important; background: lime;}" + + node = MyWidget() + node.add_class("a") + + stylesheet = _make_user_stylesheet(user_css) + stylesheet.add_source( + MyWidget.DEFAULT_CSS, "widget.py:MyWidget", is_default_css=True + ) + stylesheet.apply(node) + + # The node is red because user CSS overrides Widget.DEFAULT_CSS + assert node.styles.color == Color(255, 0, 0) + # The background colour defined in the Widget still applies, since user CSS doesn't override it + assert node.styles.background == Color(0, 255, 0) + # As expected, the tint colour is yellow, since there's no competition between user or widget CSS + assert node.styles.tint == Color(255, 255, 0) + + +@pytest.mark.parametrize( + "css_value,expectation,expected_color", + [ + # Valid values: + ["transparent", does_not_raise(), Color(0, 0, 0, 0)], + ["ansi_red", does_not_raise(), Color(128, 0, 0)], + ["ansi_bright_magenta", does_not_raise(), Color(255, 0, 255)], + ["red", does_not_raise(), Color(255, 0, 0)], + ["lime", does_not_raise(), Color(0, 255, 0)], + ["coral", does_not_raise(), Color(255, 127, 80)], + ["aqua", does_not_raise(), Color(0, 255, 255)], + ["deepskyblue", does_not_raise(), Color(0, 191, 255)], + ["rebeccapurple", does_not_raise(), Color(102, 51, 153)], + ["#ffcc00", does_not_raise(), Color(255, 204, 0)], + ["#ffcc0033", does_not_raise(), Color(255, 204, 0, 0.2)], + ["rgb(200,90,30)", does_not_raise(), Color(200, 90, 30)], + ["rgba(200,90,30,0.3)", does_not_raise(), Color(200, 90, 30, 0.3)], + # Some invalid ones: + ["coffee", pytest.raises(StylesheetParseError), None], # invalid color name + ["ansi_dark_cyan", pytest.raises(StylesheetParseError), None], + ["red 4", pytest.raises(StylesheetParseError), None], # space in it + ["1", pytest.raises(StylesheetParseError), None], # invalid value + ["()", pytest.raises(TokenError), None], # invalid tokens + ], +) +def test_color_property_parsing(css_value, expectation, expected_color): + stylesheet = Stylesheet() + css = """ + * { + background: ${COLOR}; + } + """.replace( + "${COLOR}", css_value + ) + + with expectation: + stylesheet.add_source(css) + stylesheet.parse() + + if expected_color: + css_rule = stylesheet.rules[0] + assert css_rule.styles.background == expected_color + + +@pytest.mark.parametrize( + "css_property_name,expected_property_name_suggestion", + [ + ["backgroundu", "background"], + ["bckgroundu", "background"], + ["ofset-x", "offset-x"], + ["ofst_y", "offset-y"], + ["colr", "color"], + ["colour", "color"], + ["wdth", "width"], + ["wth", "width"], + ["wh", None], + ["xkcd", None], + ], +) +def test_did_you_mean_for_css_property_names( + css_property_name: str, expected_property_name_suggestion +): + stylesheet = Stylesheet() + css = """ + * { + border: blue; + ${PROPERTY}: red; + } + """.replace( + "${PROPERTY}", css_property_name + ) + + stylesheet.add_source(css) + with pytest.raises(StylesheetParseError) as err: + stylesheet.parse() + + _, help_text = err.value.errors.rules[0].errors[0] # type: Any, HelpText + displayed_css_property_name = css_property_name.replace("_", "-") + expected_summary = f"Invalid CSS property {displayed_css_property_name!r}" + if expected_property_name_suggestion: + expected_summary += f'. Did you mean "{expected_property_name_suggestion}"?' + assert help_text.summary == expected_summary + + +@pytest.mark.parametrize( + "css_property_name,css_property_value,expected_color_suggestion", + [ + ["color", "blu", "blue"], + ["background", "chartruse", "chartreuse"], + ["tint", "ansi_whi", "ansi_white"], + ["scrollbar-color", "transprnt", "transparent"], + ["color", "xkcd", None], + ], +) +def test_did_you_mean_for_color_names( + css_property_name: str, css_property_value: str, expected_color_suggestion +): + stylesheet = Stylesheet() + css = """ + * { + border: blue; + ${PROPERTY}: ${VALUE}; + } + """.replace( + "${PROPERTY}", css_property_name + ).replace( + "${VALUE}", css_property_value + ) + + stylesheet.add_source(css) + with pytest.raises(StylesheetParseError) as err: + stylesheet.parse() + + _, help_text = err.value.errors.rules[0].errors[0] # type: Any, HelpText + displayed_css_property_name = css_property_name.replace("_", "-") + expected_error_summary = ( + f"Invalid value for the [i]{displayed_css_property_name}[/] property" + ) + + if expected_color_suggestion is not None: + expected_error_summary += f'. Did you mean "{expected_color_suggestion}"?' + + assert help_text.summary == expected_error_summary diff --git a/testbed/Textualize__textual/tests/devtools/__init__.py b/testbed/Textualize__textual/tests/devtools/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..c668d5fd7db04eaa0665d4cf47a7f27761ac2c65 --- /dev/null +++ b/testbed/Textualize__textual/tests/devtools/__init__.py @@ -0,0 +1,16 @@ +import os +import sys + +import pytest + +_MACOS_CI = sys.platform == "darwin" and os.getenv("CI", "0") != "0" +_WINDOWS = sys.platform == "win32" + +# TODO - this needs to be revisited - perhaps when aiohttp 4.0 is released? +# We get occasional test failures relating to devtools. These *appear* to be limited to MacOS, +# and the error messages suggest the event loop is being shutdown before async fixture +# teardown code has finished running. These are very rare, but are much more of an issue on +# CI since they can delay builds that have passed locally. +pytestmark = pytest.mark.skipif( + _MACOS_CI or _WINDOWS, reason="Issue #411" +) diff --git a/testbed/Textualize__textual/tests/devtools/conftest.py b/testbed/Textualize__textual/tests/devtools/conftest.py new file mode 100644 index 0000000000000000000000000000000000000000..b819512e28f78777944cee9aad1727fb21fecd5b --- /dev/null +++ b/testbed/Textualize__textual/tests/devtools/conftest.py @@ -0,0 +1,29 @@ +from io import StringIO + +import pytest + +from textual.devtools.server import _make_devtools_aiohttp_app +from textual.devtools.client import DevtoolsClient +from textual.devtools.service import DevtoolsService + + +@pytest.fixture +async def server(aiohttp_server, unused_tcp_port): + app = _make_devtools_aiohttp_app( + size_change_poll_delay_secs=0.001, + ) + server = await aiohttp_server(app, port=unused_tcp_port) + service: DevtoolsService = app["service"] + yield server + await service.shutdown() + await server.close() + + +@pytest.fixture +async def devtools(aiohttp_client, server): + client = await aiohttp_client(server) + devtools = DevtoolsClient(host=client.host, port=client.port) + await devtools.connect() + yield devtools + await devtools.disconnect() + await client.close() diff --git a/testbed/Textualize__textual/tests/devtools/test_devtools.py b/testbed/Textualize__textual/tests/devtools/test_devtools.py new file mode 100644 index 0000000000000000000000000000000000000000..b8c65bfd1d2c215db0b00c6e8510de8349836078 --- /dev/null +++ b/testbed/Textualize__textual/tests/devtools/test_devtools.py @@ -0,0 +1,96 @@ +from datetime import datetime + +import pytest +import time_machine +from rich.align import Align +from rich.console import Console +from rich.segment import Segment + +import msgpack +from tests.utilities.render import wait_for_predicate +from textual.devtools.renderables import DevConsoleLog, DevConsoleNotice + +TIMESTAMP = 1649166819 +WIDTH = 40 +# The string "Hello, world!" is encoded in the payload below +_EXAMPLE_LOG = { + "type": "client_log", + "payload": { + "segments": b"\x80\x04\x955\x00\x00\x00\x00\x00\x00\x00]\x94\x8c\x0crich.segment\x94\x8c\x07Segment\x94\x93\x94\x8c\rHello, world!\x94NN\x87\x94\x81\x94a.", + "line_number": 123, + "path": "abc/hello.py", + "timestamp": TIMESTAMP, + }, +} +EXAMPLE_LOG = msgpack.packb(_EXAMPLE_LOG) + + +@pytest.fixture(scope="module") +def console(): + return Console(width=WIDTH) + + +@time_machine.travel(TIMESTAMP) +def test_log_message_render(console): + message = DevConsoleLog( + [Segment("content")], + path="abc/hello.py", + line_number=123, + unix_timestamp=TIMESTAMP, + group=0, + verbosity=0, + severity=0, + ) + table = next(iter(message.__rich_console__(console, console.options))) + + assert len(table.rows) == 1 + + columns = list(table.columns) + left_cells = list(columns[0].cells) + left = left_cells[0] + right_cells = list(columns[1].cells) + right: Align = right_cells[0] + + # Since we can't guarantee the timezone the tests will run in... + local_time = datetime.fromtimestamp(TIMESTAMP) + string_timestamp = local_time.time() + + assert left.plain == f"[{string_timestamp}] UNDEFINED" + assert right.align == "right" + assert "hello.py:123" in right.renderable + + +def test_internal_message_render(console): + message = DevConsoleNotice("hello") + rule = next(iter(message.__rich_console__(console, console.options))) + assert rule.title == "hello" + assert rule.characters == "โ”€" + + +async def test_devtools_valid_client_log(devtools): + await devtools.websocket.send_bytes(EXAMPLE_LOG) + assert devtools.is_connected + + +async def test_devtools_string_not_json_message(devtools): + await devtools.websocket.send_str("ABCDEFG") + assert devtools.is_connected + + +async def test_devtools_invalid_json_message(devtools): + await devtools.websocket.send_json({"invalid": "json"}) + assert devtools.is_connected + + +async def test_devtools_spillover_message(devtools): + await devtools.websocket.send_json( + {"type": "client_spillover", "payload": {"spillover": 123}} + ) + assert devtools.is_connected + + +async def test_devtools_console_size_change(server, devtools): + # Update the width of the console on the server-side + server.app["service"].console.width = 124 + # Wait for the client side to update the console on their end + await wait_for_predicate(lambda: devtools.console.width == 124) diff --git a/testbed/Textualize__textual/tests/devtools/test_devtools_client.py b/testbed/Textualize__textual/tests/devtools/test_devtools_client.py new file mode 100644 index 0000000000000000000000000000000000000000..6f4eae22cb8847119d287e7c2988185aae2af8a7 --- /dev/null +++ b/testbed/Textualize__textual/tests/devtools/test_devtools_client.py @@ -0,0 +1,107 @@ +import json +import types +from asyncio import Queue +from datetime import datetime + +import time_machine +from aiohttp.web_ws import WebSocketResponse +from rich.console import ConsoleDimensions +from rich.panel import Panel +import msgpack + +from tests.utilities.render import wait_for_predicate +from textual.devtools.client import DevtoolsClient +from textual.devtools.redirect_output import DevtoolsLog + +CALLER_LINENO = 123 +CALLER_PATH = "a/b/c.py" +CALLER = types.SimpleNamespace(filename=CALLER_PATH, lineno=CALLER_LINENO) +TIMESTAMP = 1649166819 + + +def test_devtools_client_initialize_defaults(): + devtools = DevtoolsClient() + assert devtools.url == "ws://127.0.0.1:8081" + + +async def test_devtools_client_is_connected(devtools): + assert devtools.is_connected + + +@time_machine.travel(datetime.utcfromtimestamp(TIMESTAMP)) +async def test_devtools_log_places_encodes_and_queues_message(devtools): + + await devtools._stop_log_queue_processing() + devtools.log(DevtoolsLog("Hello, world!", CALLER)) + queued_log = await devtools.log_queue.get() + queued_log_data = msgpack.unpackb(queued_log) + print(repr(queued_log_data)) + + +@time_machine.travel(datetime.utcfromtimestamp(TIMESTAMP)) +async def test_devtools_log_places_encodes_and_queues_many_logs_as_string(devtools): + await devtools._stop_log_queue_processing() + devtools.log(DevtoolsLog(("hello", "world"), CALLER)) + queued_log = await devtools.log_queue.get() + queued_log_data = msgpack.unpackb(queued_log) + print(repr(queued_log_data)) + assert queued_log_data == { + "type": "client_log", + "payload": { + "group": 0, + "verbosity": 0, + "timestamp": 1649166819, + "path": "a/b/c.py", + "line_number": 123, + "segments": b"\x80\x04\x95@\x00\x00\x00\x00\x00\x00\x00]\x94(\x8c\x0crich.segment\x94\x8c\x07Segment\x94\x93\x94\x8c\x0bhello world\x94NN\x87\x94\x81\x94h\x03\x8c\x01\n\x94NN\x87\x94\x81\x94e.", + }, + } + + +async def test_devtools_log_spillover(devtools): + # Give the devtools an intentionally small max queue size + await devtools._stop_log_queue_processing() + devtools.log_queue = Queue(maxsize=2) + + # Force spillover of 2 + devtools.log(DevtoolsLog((Panel("hello, world"),), CALLER)) + devtools.log(DevtoolsLog("second message", CALLER)) + devtools.log(DevtoolsLog("third message", CALLER)) # Discarded by rate-limiting + devtools.log(DevtoolsLog("fourth message", CALLER)) # Discarded by rate-limiting + + assert devtools.spillover == 2 + + # Consume log queue + while not devtools.log_queue.empty(): + await devtools.log_queue.get() + + # Add another message now that we're under spillover threshold + devtools.log(DevtoolsLog("another message", CALLER)) + await devtools.log_queue.get() + + # Ensure we're informing the server of spillover rate-limiting + spillover_message = await devtools.log_queue.get() + assert json.loads(spillover_message) == { + "type": "client_spillover", + "payload": {"spillover": 2}, + } + + +async def test_devtools_client_update_console_dimensions(devtools, server): + """Sending new server info through websocket from server to client should (eventually) + result in the dimensions of the devtools client console being updated to match. + """ + server_to_client: WebSocketResponse = next( + iter(server.app["service"].clients) + ).websocket + server_info = { + "type": "server_info", + "payload": { + "width": 123, + "height": 456, + }, + } + await server_to_client.send_json(server_info) + await wait_for_predicate( + lambda: devtools.console.size == ConsoleDimensions(123, 456) + ) diff --git a/testbed/Textualize__textual/tests/renderables/__init__.py b/testbed/Textualize__textual/tests/renderables/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/testbed/Textualize__textual/tests/renderables/test_sparkline.py b/testbed/Textualize__textual/tests/renderables/test_sparkline.py new file mode 100644 index 0000000000000000000000000000000000000000..74f1f2f6bccb50d471f626dceef7e88976218089 --- /dev/null +++ b/testbed/Textualize__textual/tests/renderables/test_sparkline.py @@ -0,0 +1,41 @@ +from tests.utilities.render import render +from textual.renderables.sparkline import Sparkline + +GREEN = "\x1b[38;2;0;255;0m" +RED = "\x1b[38;2;255;0;0m" +BLENDED = "\x1b[38;2;127;127;0m" # Color between red and green +STOP = "\x1b[0m" + + +def test_sparkline_no_data(): + assert render(Sparkline([], width=4)) == f"{GREEN}โ–โ–โ–โ–{STOP}" + + +def test_sparkline_single_datapoint(): + assert render(Sparkline([2.5], width=4)) == f"{RED}โ–ˆโ–ˆโ–ˆโ–ˆ{STOP}" + + +def test_sparkline_two_values_min_max(): + assert render(Sparkline([2, 4], width=2)) == f"{GREEN}โ–{STOP}{RED}โ–ˆ{STOP}" + + +def test_sparkline_expand_data_to_width(): + assert render(Sparkline([2, 4], + width=4)) == f"{GREEN}โ–{STOP}{GREEN}โ–{STOP}{RED}โ–ˆ{STOP}{RED}โ–ˆ{STOP}" + + +def test_sparkline_expand_data_to_width_non_divisible(): + assert render(Sparkline([2, 4], width=3)) == f"{GREEN}โ–{STOP}{GREEN}โ–{STOP}{RED}โ–ˆ{STOP}" + + +def test_sparkline_shrink_data_to_width(): + assert render(Sparkline([2, 2, 4, 4, 6, 6], width=3)) == f"{GREEN}โ–{STOP}{BLENDED}โ–„{STOP}{RED}โ–ˆ{STOP}" + + +def test_sparkline_shrink_data_to_width_non_divisible(): + assert render( + Sparkline([1, 2, 3, 4, 5], width=3, summary_function=min)) == f"{GREEN}โ–{STOP}{BLENDED}โ–„{STOP}{RED}โ–ˆ{STOP}" + + +def test_sparkline_color_blend(): + assert render(Sparkline([1, 2, 3], width=3)) == f"{GREEN}โ–{STOP}{BLENDED}โ–„{STOP}{RED}โ–ˆ{STOP}" diff --git a/testbed/Textualize__textual/tests/renderables/test_tint.py b/testbed/Textualize__textual/tests/renderables/test_tint.py new file mode 100644 index 0000000000000000000000000000000000000000..52e54aa60c0e133729865c4152e309e19e81a060 --- /dev/null +++ b/testbed/Textualize__textual/tests/renderables/test_tint.py @@ -0,0 +1,17 @@ +import io + +from rich.console import Console +from rich.text import Text + +from textual.color import Color +from textual.renderables.tint import Tint + + +def test_tint(): + console = Console(file=io.StringIO(), force_terminal=True, color_system="truecolor") + renderable = Text.from_markup("[#aabbcc on #112233]foo") + console.print(Tint(renderable, Color(0, 100, 0, 0.5))) + output = console.file.getvalue() + print(repr(output)) + expected = "\x1b[38;2;85;143;102;48;2;8;67;25mfoo\x1b[0m\n" + assert output == expected diff --git a/testbed/Textualize__textual/tests/renderables/test_underline_bar.py b/testbed/Textualize__textual/tests/renderables/test_underline_bar.py new file mode 100644 index 0000000000000000000000000000000000000000..549b331e3b4adff8cab4c5895c56949d048c898f --- /dev/null +++ b/testbed/Textualize__textual/tests/renderables/test_underline_bar.py @@ -0,0 +1,143 @@ +from unittest.mock import create_autospec + +from rich.console import Console +from rich.console import ConsoleOptions +from rich.text import Text + +from tests.utilities.render import render +from textual.renderables.underline_bar import UnderlineBar + +MAGENTA = "\x1b[35m" +GREY = "\x1b[38;5;59m" +STOP = "\x1b[0m" +GREEN = "\x1b[32m" +RED = "\x1b[31m" + + +def test_no_highlight(): + bar = UnderlineBar(width=6) + assert render(bar) == f"{GREY}โ”โ”โ”โ”โ”โ”{STOP}" + + +def test_highlight_from_zero(): + bar = UnderlineBar(highlight_range=(0, 2.5), width=6) + assert render(bar) == ( + f"{MAGENTA}โ”โ”{STOP}{MAGENTA}โ•ธ{STOP}{GREY}โ”โ”โ”{STOP}" + ) + + +def test_highlight_from_zero_point_five(): + bar = UnderlineBar(highlight_range=(0.5, 2), width=6) + assert render(bar) == ( + f"{MAGENTA}โ•บโ”{STOP}{GREY}โ•บ{STOP}{GREY}โ”โ”โ”{STOP}" + ) + + +def test_highlight_middle(): + bar = UnderlineBar(highlight_range=(2, 4), width=6) + assert render(bar) == ( + f"{GREY}โ”{STOP}" + f"{GREY}โ•ธ{STOP}" + f"{MAGENTA}โ”โ”{STOP}" + f"{GREY}โ•บ{STOP}" + f"{GREY}โ”{STOP}" + ) + + +def test_highlight_half_start(): + bar = UnderlineBar(highlight_range=(2.5, 4), width=6) + assert render(bar) == ( + f"{GREY}โ”โ”{STOP}" + f"{MAGENTA}โ•บโ”{STOP}" + f"{GREY}โ•บ{STOP}" + f"{GREY}โ”{STOP}" + ) + + +def test_highlight_half_end(): + bar = UnderlineBar(highlight_range=(2, 4.5), width=6) + assert render(bar) == ( + f"{GREY}โ”{STOP}" + f"{GREY}โ•ธ{STOP}" + f"{MAGENTA}โ”โ”{STOP}" + f"{MAGENTA}โ•ธ{STOP}" + f"{GREY}โ”{STOP}" + ) + + +def test_highlight_half_start_and_half_end(): + bar = UnderlineBar(highlight_range=(2.5, 4.5), width=6) + assert render(bar) == ( + f"{GREY}โ”โ”{STOP}" + f"{MAGENTA}โ•บโ”{STOP}" + f"{MAGENTA}โ•ธ{STOP}" + f"{GREY}โ”{STOP}" + ) + + +def test_highlight_to_near_end(): + bar = UnderlineBar(highlight_range=(3, 5.5), width=6) + assert render(bar) == ( + f"{GREY}โ”โ”{STOP}" + f"{GREY}โ•ธ{STOP}" + f"{MAGENTA}โ”โ”{STOP}" + f"{MAGENTA}โ•ธ{STOP}" + ) + + +def test_highlight_to_end(): + bar = UnderlineBar(highlight_range=(3, 6), width=6) + assert render(bar) == ( + f"{GREY}โ”โ”{STOP}{GREY}โ•ธ{STOP}{MAGENTA}โ”โ”โ”{STOP}" + ) + + +def test_highlight_out_of_bounds_start(): + bar = UnderlineBar(highlight_range=(-2, 3), width=6) + assert render(bar) == ( + f"{MAGENTA}โ”โ”โ”{STOP}{GREY}โ•บ{STOP}{GREY}โ”โ”{STOP}" + ) + + +def test_highlight_out_of_bounds_end(): + bar = UnderlineBar(highlight_range=(3, 9), width=6) + assert render(bar) == ( + f"{GREY}โ”โ”{STOP}{GREY}โ•ธ{STOP}{MAGENTA}โ”โ”โ”{STOP}" + ) + + +def test_highlight_full_range_out_of_bounds_end(): + bar = UnderlineBar(highlight_range=(9, 10), width=6) + assert render(bar) == f"{GREY}โ”โ”โ”โ”โ”โ”{STOP}" + + +def test_highlight_full_range_out_of_bounds_start(): + bar = UnderlineBar(highlight_range=(-5, -2), width=6) + assert render(bar) == f"{GREY}โ”โ”โ”โ”โ”โ”{STOP}" + + +def test_custom_styles(): + bar = UnderlineBar(highlight_range=(2, 4), highlight_style="red", background_style="green", width=6) + assert render(bar) == ( + f"{GREEN}โ”{STOP}" + f"{GREEN}โ•ธ{STOP}" + f"{RED}โ”โ”{STOP}" + f"{GREEN}โ•บ{STOP}" + f"{GREEN}โ”{STOP}" + ) + + +def test_clickable_ranges(): + bar = UnderlineBar(highlight_range=(0, 1), width=6, clickable_ranges={"foo": (0, 2), "bar": (4, 5)}) + + console = create_autospec(Console) + options = create_autospec(ConsoleOptions) + text: Text = list(bar.__rich_console__(console, options))[0] + + start, end, style = text.spans[-2] + assert (start, end) == (0, 2) + assert style.meta == {'@click': "range_clicked('foo')"} + + start, end, style = text.spans[-1] + assert (start, end) == (4, 5) + assert style.meta == {'@click': "range_clicked('bar')"} diff --git a/testbed/Textualize__textual/tests/snapshot_tests/__init__.py b/testbed/Textualize__textual/tests/snapshot_tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/testbed/Textualize__textual/tests/snapshot_tests/__snapshots__/test_snapshots.ambr b/testbed/Textualize__textual/tests/snapshot_tests/__snapshots__/test_snapshots.ambr new file mode 100644 index 0000000000000000000000000000000000000000..0ef6e8f655bf49f732711ff42807fa9c3a51a6b7 --- /dev/null +++ b/testbed/Textualize__textual/tests/snapshot_tests/__snapshots__/test_snapshots.ambr @@ -0,0 +1,1094 @@ +# name: test_dock_layout_sidebar + ''' + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Textual + + + + + + + + + + Sidebar1Docking a widget removes it from the layout and  + fixes its position, aligned to either the top,  + right, bottom, or left edges of a container. + + Docked widgets will not scroll out of view,  + making them ideal for sticky headers, footers,  + and sidebars. + โ–‡โ–‡ + Docking a widget removes it from the layout and  + fixes its position, aligned to either the top,  + right, bottom, or left edges of a container. + + Docked widgets will not scroll out of view,  + making them ideal for sticky headers, footers,  + and sidebars. + + Docking a widget removes it from the layout and  + fixes its position, aligned to either the top,  + right, bottom, or left edges of a container. + + Docked widgets will not scroll out of view,  + making them ideal for sticky headers, footers,  + and sidebars. + + + + + + ''' +# --- +# name: test_grid_layout_basic + ''' + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Textual + + + + + + + + + + โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” + โ”‚Oneโ”‚โ”‚Twoโ”‚โ”‚Threeโ”‚ + โ”‚โ”‚โ”‚โ”‚โ”‚โ”‚ + โ”‚โ”‚โ”‚โ”‚โ”‚โ”‚ + โ”‚โ”‚โ”‚โ”‚โ”‚โ”‚ + โ”‚โ”‚โ”‚โ”‚โ”‚โ”‚ + โ”‚โ”‚โ”‚โ”‚โ”‚โ”‚ + โ”‚โ”‚โ”‚โ”‚โ”‚โ”‚ + โ”‚โ”‚โ”‚โ”‚โ”‚โ”‚ + โ”‚โ”‚โ”‚โ”‚โ”‚โ”‚ + โ”‚โ”‚โ”‚โ”‚โ”‚โ”‚ + โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ + โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” + โ”‚Fourโ”‚โ”‚Fiveโ”‚โ”‚Sixโ”‚ + โ”‚โ”‚โ”‚โ”‚โ”‚โ”‚ + โ”‚โ”‚โ”‚โ”‚โ”‚โ”‚ + โ”‚โ”‚โ”‚โ”‚โ”‚โ”‚ + โ”‚โ”‚โ”‚โ”‚โ”‚โ”‚ + โ”‚โ”‚โ”‚โ”‚โ”‚โ”‚ + โ”‚โ”‚โ”‚โ”‚โ”‚โ”‚ + โ”‚โ”‚โ”‚โ”‚โ”‚โ”‚ + โ”‚โ”‚โ”‚โ”‚โ”‚โ”‚ + โ”‚โ”‚โ”‚โ”‚โ”‚โ”‚ + โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ + + + + + ''' +# --- +# name: test_grid_layout_basic_overflow + ''' + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Textual + + + + + + + + + + โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” + โ”‚Oneโ”‚โ”‚Twoโ”‚โ”‚Threeโ”‚ + โ”‚โ”‚โ”‚โ”‚โ”‚โ”‚ + โ”‚โ”‚โ”‚โ”‚โ”‚โ”‚ + โ”‚โ”‚โ”‚โ”‚โ”‚โ”‚ + โ”‚โ”‚โ”‚โ”‚โ”‚โ”‚ + โ”‚โ”‚โ”‚โ”‚โ”‚โ”‚ + โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ + โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” + โ”‚Fourโ”‚โ”‚Fiveโ”‚โ”‚Sixโ”‚ + โ”‚โ”‚โ”‚โ”‚โ”‚โ”‚ + โ”‚โ”‚โ”‚โ”‚โ”‚โ”‚ + โ”‚โ”‚โ”‚โ”‚โ”‚โ”‚ + โ”‚โ”‚โ”‚โ”‚โ”‚โ”‚ + โ”‚โ”‚โ”‚โ”‚โ”‚โ”‚ + โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ + โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” + โ”‚Sevenโ”‚ + โ”‚โ”‚ + โ”‚โ”‚ + โ”‚โ”‚ + โ”‚โ”‚ + โ”‚โ”‚ + โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ + + + + + ''' +# --- +# name: test_grid_layout_gutter + ''' + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Textual + + + + + + + + + + OneTwoThree + + + + + + + + + + + + FourFiveSix + + + + + + + + + + + + + + + + ''' +# --- +# name: test_horizontal_layout + ''' + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Textual + + + + + + + + + + โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” + โ”‚Oneโ”‚โ”‚Twoโ”‚โ”‚Threeโ”‚ + โ”‚โ”‚โ”‚โ”‚โ”‚โ”‚ + โ”‚โ”‚โ”‚โ”‚โ”‚โ”‚ + โ”‚โ”‚โ”‚โ”‚โ”‚โ”‚ + โ”‚โ”‚โ”‚โ”‚โ”‚โ”‚ + โ”‚โ”‚โ”‚โ”‚โ”‚โ”‚ + โ”‚โ”‚โ”‚โ”‚โ”‚โ”‚ + โ”‚โ”‚โ”‚โ”‚โ”‚โ”‚ + โ”‚โ”‚โ”‚โ”‚โ”‚โ”‚ + โ”‚โ”‚โ”‚โ”‚โ”‚โ”‚ + โ”‚โ”‚โ”‚โ”‚โ”‚โ”‚ + โ”‚โ”‚โ”‚โ”‚โ”‚โ”‚ + โ”‚โ”‚โ”‚โ”‚โ”‚โ”‚ + โ”‚โ”‚โ”‚โ”‚โ”‚โ”‚ + โ”‚โ”‚โ”‚โ”‚โ”‚โ”‚ + โ”‚โ”‚โ”‚โ”‚โ”‚โ”‚ + โ”‚โ”‚โ”‚โ”‚โ”‚โ”‚ + โ”‚โ”‚โ”‚โ”‚โ”‚โ”‚ + โ”‚โ”‚โ”‚โ”‚โ”‚โ”‚ + โ”‚โ”‚โ”‚โ”‚โ”‚โ”‚ + โ”‚โ”‚โ”‚โ”‚โ”‚โ”‚ + โ”‚โ”‚โ”‚โ”‚โ”‚โ”‚ + โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ + + + + + ''' +# --- +# name: test_layers + ''' + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Textual + + + + + + + + + + + + + + + + + + + + + box1 (layer = above) + + + + + + box2 (layer = below) + + + + + + + + + + + ''' +# --- +# name: test_vertical_layout + ''' + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Textual + + + + + + + + + + โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” + โ”‚Oneโ”‚ + โ”‚โ”‚ + โ”‚โ”‚ + โ”‚โ”‚ + โ”‚โ”‚ + โ”‚โ”‚ + โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ + โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” + โ”‚Twoโ”‚ + โ”‚โ”‚ + โ”‚โ”‚ + โ”‚โ”‚ + โ”‚โ”‚ + โ”‚โ”‚ + โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ + โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” + โ”‚Threeโ”‚ + โ”‚โ”‚ + โ”‚โ”‚ + โ”‚โ”‚ + โ”‚โ”‚ + โ”‚โ”‚ + โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ + + + + + ''' +# --- diff --git a/testbed/Textualize__textual/tests/snapshot_tests/snapshot_report_template.jinja2 b/testbed/Textualize__textual/tests/snapshot_tests/snapshot_report_template.jinja2 new file mode 100644 index 0000000000000000000000000000000000000000..d1f7b2530960d8577f21a6fdbe879961d3a17991 --- /dev/null +++ b/testbed/Textualize__textual/tests/snapshot_tests/snapshot_report_template.jinja2 @@ -0,0 +1,197 @@ + + + + + + Textual Snapshot Test Report + + + + + +
+
+
+

+ Textual Snapshot Tests +

+ Showing diffs for {{ fails }} mismatched snapshot(s) +
+
+
+ + {{ diffs | length }} snapshots changed + + ยท + + {{ passes }} snapshots matched + +
+
+
+
+
+
+
+ + {% for diff in diffs %} +
+
+
+
+ + {{ diff.test_name }} + + {{ diff.path }}:{{ diff.line_number }} + + +
+ + +
+
+
+
+
+ {{ diff.actual }} +
+ Output from test (More info) +
+
+
+
+ +
+
+ {{ diff.snapshot }} +
+
+ Historical snapshot +
+
+
+
+
+ + + {# Modal with debug info: #} + +
+
+ {% endfor %} + +
+
+
+
+

If you're happy with the test output, run pytest with the --snapshot-update flag to update the snapshot. +

+
+
+
+
+ +
+
+
+

Report generated at UTC {{ now }}.

+
+
+
+ +
+ + + + + + + + diff --git a/testbed/Textualize__textual/tests/snapshot_tests/test_snapshots.py b/testbed/Textualize__textual/tests/snapshot_tests/test_snapshots.py new file mode 100644 index 0000000000000000000000000000000000000000..34cb261b9e44045054333772eae304a1f507e526 --- /dev/null +++ b/testbed/Textualize__textual/tests/snapshot_tests/test_snapshots.py @@ -0,0 +1,26 @@ +def test_grid_layout_basic(snap_compare): + assert snap_compare("docs/examples/guide/layout/grid_layout1.py") + + +def test_grid_layout_basic_overflow(snap_compare): + assert snap_compare("docs/examples/guide/layout/grid_layout2.py") + + +def test_grid_layout_gutter(snap_compare): + assert snap_compare("docs/examples/guide/layout/grid_layout7_gutter.py") + + +def test_layers(snap_compare): + assert snap_compare("docs/examples/guide/layout/layers.py") + + +def test_horizontal_layout(snap_compare): + assert snap_compare("docs/examples/guide/layout/horizontal_layout.py") + + +def test_vertical_layout(snap_compare): + assert snap_compare("docs/examples/guide/layout/vertical_layout.py") + + +def test_dock_layout_sidebar(snap_compare): + assert snap_compare("docs/examples/guide/layout/dock_layout2_sidebar.py") diff --git a/testbed/Textualize__textual/tests/test_animator.py b/testbed/Textualize__textual/tests/test_animator.py new file mode 100644 index 0000000000000000000000000000000000000000..a92f38c9606ab95cdd74be14dca498488bc0ee16 --- /dev/null +++ b/testbed/Textualize__textual/tests/test_animator.py @@ -0,0 +1,269 @@ +from __future__ import annotations + +from dataclasses import dataclass +from unittest.mock import Mock + +import pytest + +from textual._animator import Animator, SimpleAnimation +from textual._easing import EASING, DEFAULT_EASING + + +class Animatable: + """An animatable object.""" + + def __init__(self, value): + self.value = value + + def blend(self, destination: Animatable, factor: float) -> Animatable: + return Animatable(self.value + (destination.value - self.value) * factor) + + +@dataclass +class AnimateTest: + """An object with animatable properties.""" + + foo: float | None = 0.0 # Plain float that may be set to None on final_value + bar: Animatable = Animatable(0) # A mock object supporting the animatable protocol + + +def test_simple_animation(): + """Test an animation from one float to another.""" + + # Thing that may be animated + animate_test = AnimateTest() + + # Fake wall-clock time + time = 100.0 + + # Object that does the animation + animation = SimpleAnimation( + animate_test, + "foo", + time, + 3.0, + start_value=20.0, + end_value=50.0, + final_value=None, + easing=lambda x: x, + ) + + assert animate_test.foo == 0.0 + + assert animation(time) is False + assert animate_test.foo == 20.0 + + assert animation(time + 1.0) is False + assert animate_test.foo == 30.0 + + assert animation(time + 2.0) is False + assert animate_test.foo == 40.0 + + assert animation(time + 2.9) is False # Not quite final value + assert animate_test.foo == pytest.approx(49.0) + + assert animation(time + 3.0) is True # True to indicate animation is complete + assert animate_test.foo is None # This is final_value + + assert animation(time + 3.0) is True + assert animate_test.foo is None + + +def test_simple_animation_duration_zero(): + """Test animation handles duration of 0.""" + + # Thing that may be animated + animatable = AnimateTest() + + # Fake wall-clock time + time = 100.0 + + # Object that does the animation + animation = SimpleAnimation( + animatable, + "foo", + time, + 0.0, + start_value=20.0, + end_value=50.0, + final_value=50.0, + easing=lambda x: x, + ) + + assert animation(time) is True # Duration is 0, so this is last value + assert animatable.foo == 50.0 + + assert animation(time + 1.0) is True + assert animatable.foo == 50.0 + + +def test_simple_animation_reverse(): + """Test an animation from one float to another, where the end value is less than the start.""" + + # Thing that may be animated + animate_Test = AnimateTest() + + # Fake wall-clock time + time = 100.0 + + # Object that does the animation + animation = SimpleAnimation( + animate_Test, + "foo", + time, + 3.0, + start_value=50.0, + end_value=20.0, + final_value=20.0, + easing=lambda x: x, + ) + + assert animation(time) is False + assert animate_Test.foo == 50.0 + + assert animation(time + 1.0) is False + assert animate_Test.foo == 40.0 + + assert animation(time + 2.0) is False + assert animate_Test.foo == 30.0 + + assert animation(time + 3.0) is True + assert animate_Test.foo == 20.0 + + +def test_animatable(): + """Test SimpleAnimation works with the Animatable protocol""" + + animate_test = AnimateTest() + + # Fake wall-clock time + time = 100.0 + + # Object that does the animation + animation = SimpleAnimation( + animate_test, + "bar", + time, + 3.0, + start_value=Animatable(20.0), + end_value=Animatable(50.0), + final_value=Animatable(50.0), + easing=lambda x: x, + ) + + assert animation(time) is False + assert animate_test.bar.value == 20.0 + + assert animation(time + 1.0) is False + assert animate_test.bar.value == 30.0 + + assert animation(time + 2.0) is False + assert animate_test.bar.value == 40.0 + + assert animation(time + 2.9) is False + assert animate_test.bar.value == pytest.approx(49.0) + + assert animation(time + 3.0) is True # True to indicate animation is complete + assert animate_test.bar.value == 50.0 + + +class MockAnimator(Animator): + """A mock animator.""" + + def __init__(self, *args) -> None: + super().__init__(*args) + self._time = 0.0 + self._on_animation_frame_called = False + + def on_animation_frame(self): + self._on_animation_frame_called = True + + def _get_time(self): + return self._time + + +async def test_animator(): + target = Mock() + animator = MockAnimator(target) + animate_test = AnimateTest() + + # Animate attribute "foo" on animate_test to 100.0 in 10 seconds + animator.animate(animate_test, "foo", 100.0, duration=10.0) + + expected = SimpleAnimation( + animate_test, + "foo", + 0.0, + duration=10.0, + start_value=0.0, + end_value=100.0, + final_value=100.0, + easing=EASING[DEFAULT_EASING], + ) + assert animator._animations[(id(animate_test), "foo")] == expected + assert not animator._on_animation_frame_called + + await animator() + assert animate_test.foo == 0 + + animator._time = 5 + await animator() + assert animate_test.foo == 50 + + # New animation in the middle of an existing one + animator.animate(animate_test, "foo", 200, duration=1) + assert animate_test.foo == 50 + + animator._time = 6 + await animator() + assert animate_test.foo == 200 + + +def test_bound_animator(): + target = Mock() + animator = MockAnimator(target) + animate_test = AnimateTest() + + # Bind an animator so it animates attributes on the given object + bound_animator = animator.bind(animate_test) + + # Animate attribute "foo" on animate_test to 100.0 in 10 seconds + bound_animator("foo", 100.0, duration=10) + + expected = SimpleAnimation( + animate_test, + "foo", + 0, + duration=10, + start_value=0, + end_value=100, + final_value=100, + easing=EASING[DEFAULT_EASING], + ) + assert animator._animations[(id(animate_test), "foo")] == expected + + +async def test_animator_on_complete_callback_not_fired_before_duration_ends(): + callback = Mock() + animate_test = AnimateTest() + animator = MockAnimator(Mock()) + + animator.animate(animate_test, "foo", 200, duration=10, on_complete=callback) + + animator._time = 9 + await animator() + + assert not callback.called + + +async def test_animator_on_complete_callback_fired_at_duration(): + callback = Mock() + animate_test = AnimateTest() + animator = MockAnimator(Mock()) + + animator.animate(animate_test, "foo", 200, duration=10, on_complete=callback) + + animator._time = 10 + await animator() + + callback.assert_called_once_with() diff --git a/testbed/Textualize__textual/tests/test_arrange.py b/testbed/Textualize__textual/tests/test_arrange.py new file mode 100644 index 0000000000000000000000000000000000000000..580d68e02e45ba93dd8dbcc48a03c25d3e9d799b --- /dev/null +++ b/testbed/Textualize__textual/tests/test_arrange.py @@ -0,0 +1,93 @@ +from textual._arrange import arrange, TOP_Z +from textual._layout import WidgetPlacement +from textual.geometry import Region, Size, Spacing +from textual.widget import Widget + + +def test_arrange_empty(): + container = Widget(id="container") + + placements, widgets, spacing = arrange(container, [], Size(80, 24), Size(80, 24)) + assert placements == [] + assert widgets == set() + assert spacing == Spacing(0, 0, 0, 0) + + +def test_arrange_dock_top(): + container = Widget(id="container") + child = Widget(id="child") + header = Widget(id="header") + header.styles.dock = "top" + header.styles.height = "1" + + placements, widgets, spacing = arrange( + container, [child, header], Size(80, 24), Size(80, 24) + ) + assert placements == [ + WidgetPlacement( + Region(0, 0, 80, 1), Spacing(), header, order=TOP_Z, fixed=True + ), + WidgetPlacement(Region(0, 1, 80, 23), Spacing(), child, order=0, fixed=False), + ] + assert widgets == {child, header} + assert spacing == Spacing(1, 0, 0, 0) + + +def test_arrange_dock_left(): + container = Widget(id="container") + child = Widget(id="child") + header = Widget(id="header") + header.styles.dock = "left" + header.styles.width = "10" + + placements, widgets, spacing = arrange( + container, [child, header], Size(80, 24), Size(80, 24) + ) + assert placements == [ + WidgetPlacement( + Region(0, 0, 10, 24), Spacing(), header, order=TOP_Z, fixed=True + ), + WidgetPlacement(Region(10, 0, 70, 24), Spacing(), child, order=0, fixed=False), + ] + assert widgets == {child, header} + assert spacing == Spacing(0, 0, 0, 10) + + +def test_arrange_dock_right(): + container = Widget(id="container") + child = Widget(id="child") + header = Widget(id="header") + header.styles.dock = "right" + header.styles.width = "10" + + placements, widgets, spacing = arrange( + container, [child, header], Size(80, 24), Size(80, 24) + ) + assert placements == [ + WidgetPlacement( + Region(70, 0, 10, 24), Spacing(), header, order=TOP_Z, fixed=True + ), + WidgetPlacement(Region(0, 0, 70, 24), Spacing(), child, order=0, fixed=False), + ] + assert widgets == {child, header} + assert spacing == Spacing(0, 10, 0, 0) + + +def test_arrange_dock_bottom(): + container = Widget(id="container") + child = Widget(id="child") + header = Widget(id="header") + header.styles.dock = "bottom" + header.styles.height = "1" + + placements, widgets, spacing = arrange( + container, [child, header], Size(80, 24), Size(80, 24) + ) + assert placements == [ + WidgetPlacement( + Region(0, 23, 80, 1), Spacing(), header, order=TOP_Z, fixed=True + ), + WidgetPlacement(Region(0, 0, 80, 23), Spacing(), child, order=0, fixed=False), + ] + assert widgets == {child, header} + assert spacing == Spacing(0, 0, 1, 0) diff --git a/testbed/Textualize__textual/tests/test_auto_refresh.py b/testbed/Textualize__textual/tests/test_auto_refresh.py new file mode 100644 index 0000000000000000000000000000000000000000..d5122a7a4de5e57dcb2e80be5e527aa1928db119 --- /dev/null +++ b/testbed/Textualize__textual/tests/test_auto_refresh.py @@ -0,0 +1,28 @@ +from time import time + +from textual.app import App + + +class RefreshApp(App[float]): + def __init__(self): + self.count = 0 + super().__init__() + + def on_mount(self): + self.start = time() + self.auto_refresh = 0.1 + + def _automatic_refresh(self): + self.count += 1 + if self.count == 3: + self.exit(time() - self.start) + super()._automatic_refresh() + + +def test_auto_refresh(): + app = RefreshApp() + + elapsed = app.run(quit_after=1, headless=True) + assert elapsed is not None + # CI can run slower, so we need to give this a bit of margin + assert 0.2 <= elapsed < 0.8 diff --git a/testbed/Textualize__textual/tests/test_binding.py b/testbed/Textualize__textual/tests/test_binding.py new file mode 100644 index 0000000000000000000000000000000000000000..d2d61ac18b959ef4e7f7b4128d6b8aa3091ff93e --- /dev/null +++ b/testbed/Textualize__textual/tests/test_binding.py @@ -0,0 +1,31 @@ +import pytest + +from textual.binding import Bindings, Binding + +BINDING1 = Binding("a,b", action="action1", description="description1") +BINDING2 = Binding("c", action="action2", description="description2") + + +@pytest.fixture +def bindings(): + yield Bindings([BINDING1, BINDING2]) + + +def test_bindings_get_key(bindings): + assert bindings.get_key("b") == Binding("b", action="action1", description="description1") + assert bindings.get_key("c") == BINDING2 + + +def test_bindings_merge_simple(bindings): + left = Bindings([BINDING1]) + right = Bindings([BINDING2]) + assert Bindings.merge([left, right]).keys == bindings.keys + + +def test_bindings_merge_overlap(): + left = Bindings([BINDING1]) + another_binding = Binding("a", action="another_action", description="another_description") + assert Bindings.merge([left, Bindings([another_binding])]).keys == { + "a": another_binding, + "b": Binding("b", action="action1", description="description1"), + } diff --git a/testbed/Textualize__textual/tests/test_border.py b/testbed/Textualize__textual/tests/test_border.py new file mode 100644 index 0000000000000000000000000000000000000000..4e2d563900ebc15c6a53ca27fb7fe8d4a407377c --- /dev/null +++ b/testbed/Textualize__textual/tests/test_border.py @@ -0,0 +1,25 @@ +from rich.segment import Segment +from rich.style import Style + +from textual._border import get_box, render_row + + +def test_border_render_row(): + + style = Style.parse("red") + row = (Segment("โ”", style), Segment("โ”", style), Segment("โ”“", style)) + + assert render_row(row, 5, False, False) == [Segment(row[1].text * 5, row[1].style)] + assert render_row(row, 5, True, False) == [ + row[0], + Segment(row[1].text * 4, row[1].style), + ] + assert render_row(row, 5, False, True) == [ + Segment(row[1].text * 4, row[1].style), + row[2], + ] + assert render_row(row, 5, True, True) == [ + row[0], + Segment(row[1].text * 3, row[1].style), + row[2], + ] diff --git a/testbed/Textualize__textual/tests/test_box_model.py b/testbed/Textualize__textual/tests/test_box_model.py new file mode 100644 index 0000000000000000000000000000000000000000..1c82620ff0869dde9c60d7b910d17359985fc428 --- /dev/null +++ b/testbed/Textualize__textual/tests/test_box_model.py @@ -0,0 +1,199 @@ +from __future__ import annotations + +from fractions import Fraction + +from textual.box_model import BoxModel, get_box_model +from textual.css.styles import Styles +from textual.geometry import Size, Spacing + + +def test_content_box(): + styles = Styles() + styles.width = 10 + styles.height = 8 + styles.padding = 1 + styles.border = ("solid", "red") + + one = Fraction(1) + + # border-box is default + assert styles.box_sizing == "border-box" + + def get_auto_width(container: Size, parent: Size) -> int: + assert False, "must not be called" + + def get_auto_height(container: Size, parent: Size) -> int: + assert False, "must not be called" + + box_model = get_box_model( + styles, Size(60, 20), Size(80, 24), one, get_auto_width, get_auto_height + ) + # Size should be inclusive of padding / border + assert box_model == BoxModel(Fraction(10), Fraction(8), Spacing(0, 0, 0, 0)) + + # Switch to content-box + styles.box_sizing = "content-box" + + box_model = get_box_model( + styles, Size(60, 20), Size(80, 24), one, get_auto_width, get_auto_height + ) + # width and height have added padding / border to accommodate content + assert box_model == BoxModel(Fraction(14), Fraction(12), Spacing(0, 0, 0, 0)) + + +def test_width(): + """Test width settings.""" + styles = Styles() + one = Fraction(1) + + def get_auto_width(container: Size, parent: Size) -> int: + return 10 + + def get_auto_height(container: Size, parent: Size, width: int) -> int: + return 10 + + box_model = get_box_model( + styles, Size(60, 20), Size(80, 24), one, get_auto_width, get_auto_height + ) + assert box_model == BoxModel(Fraction(60), Fraction(20), Spacing(0, 0, 0, 0)) + + # Add a margin and check that it is reported + styles.margin = (1, 2, 3, 4) + + box_model = get_box_model( + styles, Size(60, 20), Size(80, 24), one, get_auto_width, get_auto_height + ) + assert box_model == BoxModel(Fraction(54), Fraction(16), Spacing(1, 2, 3, 4)) + + # Set width to auto-detect + styles.width = "auto" + + box_model = get_box_model( + styles, Size(60, 20), Size(80, 24), one, get_auto_width, get_auto_height + ) + # Setting width to auto should call get_auto_width + assert box_model == BoxModel(Fraction(10), Fraction(16), Spacing(1, 2, 3, 4)) + + # Set width to 100 vw which should make it the width of the parent + styles.width = "100vw" + + box_model = get_box_model( + styles, Size(60, 20), Size(80, 24), one, get_auto_width, get_auto_height + ) + assert box_model == BoxModel(Fraction(80), Fraction(16), Spacing(1, 2, 3, 4)) + + # Set the width to 100% should make it fill the container size + styles.width = "100%" + + box_model = get_box_model( + styles, Size(60, 20), Size(80, 24), one, get_auto_width, get_auto_height + ) + assert box_model == BoxModel(Fraction(54), Fraction(16), Spacing(1, 2, 3, 4)) + + styles.width = "100vw" + styles.max_width = "50%" + + box_model = get_box_model( + styles, Size(60, 20), Size(80, 24), one, get_auto_width, get_auto_height + ) + assert box_model == BoxModel(Fraction(30), Fraction(16), Spacing(1, 2, 3, 4)) + + +def test_height(): + """Test width settings.""" + styles = Styles() + one = Fraction(1) + + def get_auto_width(container: Size, parent: Size) -> int: + return 10 + + def get_auto_height(container: Size, parent: Size, width: int) -> int: + return 10 + + box_model = get_box_model( + styles, Size(60, 20), Size(80, 24), one, get_auto_width, get_auto_height + ) + assert box_model == BoxModel(Fraction(60), Fraction(20), Spacing(0, 0, 0, 0)) + + # Add a margin and check that it is reported + styles.margin = (1, 2, 3, 4) + + box_model = get_box_model( + styles, Size(60, 20), Size(80, 24), one, get_auto_width, get_auto_height + ) + assert box_model == BoxModel(Fraction(54), Fraction(16), Spacing(1, 2, 3, 4)) + + # Set width to 100 vw which should make it the width of the parent + styles.height = "100vh" + + box_model = get_box_model( + styles, Size(60, 20), Size(80, 24), one, get_auto_width, get_auto_height + ) + assert box_model == BoxModel(Fraction(54), Fraction(24), Spacing(1, 2, 3, 4)) + + # Set the width to 100% should make it fill the container size + styles.height = "100%" + + box_model = get_box_model( + styles, Size(60, 20), Size(80, 24), one, get_auto_width, get_auto_height + ) + assert box_model == BoxModel(Fraction(54), Fraction(16), Spacing(1, 2, 3, 4)) + + styles.height = "auto" + styles.margin = 2 + + box_model = get_box_model( + styles, Size(60, 20), Size(80, 24), one, get_auto_width, get_auto_height + ) + assert box_model == BoxModel(Fraction(56), Fraction(10), Spacing(2, 2, 2, 2)) + + styles.margin = 1, 2, 3, 4 + styles.height = "100vh" + styles.max_height = "50%" + + box_model = get_box_model( + styles, Size(60, 20), Size(80, 24), one, get_auto_width, get_auto_height + ) + assert box_model == BoxModel(Fraction(54), Fraction(10), Spacing(1, 2, 3, 4)) + + +def test_max(): + """Check that max_width and max_height are respected.""" + styles = Styles() + styles.width = 100 + styles.height = 80 + styles.max_width = 40 + styles.max_height = 30 + one = Fraction(1) + + def get_auto_width(container: Size, parent: Size) -> int: + assert False, "must not be called" + + def get_auto_height(container: Size, parent: Size) -> int: + assert False, "must not be called" + + box_model = get_box_model( + styles, Size(40, 30), Size(80, 24), one, get_auto_width, get_auto_height + ) + assert box_model == BoxModel(Fraction(40), Fraction(30), Spacing(0, 0, 0, 0)) + + +def test_min(): + """Check that min_width and min_height are respected.""" + styles = Styles() + styles.width = 10 + styles.height = 5 + styles.min_width = 40 + styles.min_height = 30 + one = Fraction(1) + + def get_auto_width(container: Size, parent: Size) -> int: + assert False, "must not be called" + + def get_auto_height(container: Size, parent: Size) -> int: + assert False, "must not be called" + + box_model = get_box_model( + styles, Size(40, 30), Size(80, 24), one, get_auto_width, get_auto_height + ) + assert box_model == BoxModel(Fraction(40), Fraction(30), Spacing(0, 0, 0, 0)) diff --git a/testbed/Textualize__textual/tests/test_cache.py b/testbed/Textualize__textual/tests/test_cache.py new file mode 100644 index 0000000000000000000000000000000000000000..e81b7e06a6dc786d6f7f262b88bf1b68257b9d56 --- /dev/null +++ b/testbed/Textualize__textual/tests/test_cache.py @@ -0,0 +1,129 @@ +from __future__ import annotations +from __future__ import unicode_literals + +import pytest + +from textual._cache import LRUCache + + +def test_lru_cache(): + cache = LRUCache(3) + + # insert some values + cache["foo"] = 1 + cache["bar"] = 2 + cache["baz"] = 3 + assert "foo" in cache + assert "bar" in cache + assert "baz" in cache + + # Cache size is 3, so the following should kick oldest one out + cache["egg"] = 4 + assert "foo" not in cache + assert "egg" in cache + + # cache is now full + # look up two keys + cache["bar"] + cache["baz"] + + # Insert a new value + cache["eggegg"] = 5 + assert len(cache) == 3 + # Check it kicked out the 'oldest' key + assert "egg" not in cache + assert "eggegg" in cache + + +def test_lru_cache_get(): + cache = LRUCache(3) + + # insert some values + cache["foo"] = 1 + cache["bar"] = 2 + cache["baz"] = 3 + assert "foo" in cache + + # Cache size is 3, so the following should kick oldest one out + cache["egg"] = 4 + # assert len(cache) == 3 + assert cache.get("foo") is None + assert "egg" in cache + + # cache is now full + # look up two keys + cache.get("bar") + cache.get("baz") + + # Insert a new value + cache["eggegg"] = 5 + # Check it kicked out the 'oldest' key + assert "egg" not in cache + assert "eggegg" in cache + + +def test_lru_cache_mapping(): + """Test cache values can be set and read back.""" + cache = LRUCache(3) + cache["foo"] = 1 + cache.set("bar", 2) + cache.set("baz", 3) + assert cache["foo"] == 1 + assert cache["bar"] == 2 + assert cache.get("baz") == 3 + + +def test_lru_cache_clear(): + cache = LRUCache(3) + assert len(cache) == 0 + cache["foo"] = 1 + assert "foo" in cache + assert len(cache) == 1 + cache.clear() + assert "foo" not in cache + assert len(cache) == 0 + + +def test_lru_cache_bool(): + cache = LRUCache(3) + assert not cache + cache["foo"] = "bar" + assert cache + + +@pytest.mark.parametrize( + "keys,expected", + [ + ((), ()), + (("foo",), ("foo",)), + (("foo", "bar"), ("foo", "bar")), + (("foo", "bar", "baz"), ("foo", "bar", "baz")), + (("foo", "bar", "baz", "egg"), ("bar", "baz", "egg")), + (("foo", "bar", "baz", "egg", "bob"), ("baz", "egg", "bob")), + ], +) +def test_lru_cache_evicts(keys: list[str], expected: list[str]): + """Test adding adding additional values evicts oldest key""" + cache = LRUCache(3) + for value, key in enumerate(keys): + cache[key] = value + assert tuple(cache.keys()) == expected + + +@pytest.mark.parametrize( + "keys,expected_len", + [ + ((), 0), + (("foo",), 1), + (("foo", "bar"), 2), + (("foo", "bar", "baz"), 3), + (("foo", "bar", "baz", "egg"), 3), + (("foo", "bar", "baz", "egg", "bob"), 3), + ], +) +def test_lru_cache_len(keys: list[str], expected_len: int): + """Test adding adding additional values evicts oldest key""" + cache = LRUCache(3) + for value, key in enumerate(keys): + cache[key] = value + assert len(cache) == expected_len diff --git a/testbed/Textualize__textual/tests/test_case.py b/testbed/Textualize__textual/tests/test_case.py new file mode 100644 index 0000000000000000000000000000000000000000..dbc7b94b2b22071f0b5fb6ebb229878cd409ec2e --- /dev/null +++ b/testbed/Textualize__textual/tests/test_case.py @@ -0,0 +1,5 @@ +from textual.case import camel_to_snake + + +def test_camel_to_snake(): + assert camel_to_snake("FooBar") == "foo_bar" diff --git a/testbed/Textualize__textual/tests/test_color.py b/testbed/Textualize__textual/tests/test_color.py new file mode 100644 index 0000000000000000000000000000000000000000..10340d3dc9f40690a0b437ce83507302d6210b53 --- /dev/null +++ b/testbed/Textualize__textual/tests/test_color.py @@ -0,0 +1,218 @@ +import pytest +from rich.color import Color as RichColor +from rich.text import Text + +from textual.color import Color, Lab, lab_to_rgb, rgb_to_lab + + +def test_rich_color(): + """Check conversion to Rich color.""" + assert Color(10, 20, 30, 1.0).rich_color == RichColor.from_rgb(10, 20, 30) + assert Color.from_rich_color(RichColor.from_rgb(10, 20, 30)) == Color( + 10, 20, 30, 1.0 + ) + + +def test_rich_color_rich_output(): + assert isinstance(Color(10, 20, 30).__rich__(), Text) + + +def test_normalized(): + assert Color(255, 128, 64).normalized == pytest.approx((1.0, 128 / 255, 64 / 255)) + + +def test_clamped(): + assert Color(300, 100, -20, 1.5).clamped == Color(255, 100, 0, 1.0) + + +def test_css(): + """Check conversion to CSS style""" + assert Color(10, 20, 30, 1.0).css == "rgb(10,20,30)" + assert Color(10, 20, 30, 0.5).css == "rgba(10,20,30,0.5)" + + +def test_monochrome(): + assert Color(10, 20, 30).monochrome == Color(19, 19, 19) + assert Color(10, 20, 30, 0.5).monochrome == Color(19, 19, 19, 0.5) + assert Color(255, 255, 255).monochrome == Color(255, 255, 255) + assert Color(0, 0, 0).monochrome == Color(0, 0, 0) + + +def test_rgb(): + assert Color(10, 20, 30, 0.55).rgb == (10, 20, 30) + + +def test_hls(): + + red = Color(200, 20, 32) + print(red.hsl) + assert red.hsl == pytest.approx( + (0.9888888888888889, 0.818181818181818, 0.43137254901960786) + ) + assert Color.from_hsl( + 0.9888888888888889, 0.818181818181818, 0.43137254901960786 + ).normalized == pytest.approx(red.normalized, rel=1e-5) + + +def test_color_brightness(): + assert Color(255, 255, 255).brightness == 1 + assert Color(0, 0, 0).brightness == 0 + assert Color(127, 127, 127).brightness == pytest.approx(0.49803921568627446) + assert Color(255, 127, 64).brightness == pytest.approx(0.6199607843137255) + + +def test_color_hex(): + assert Color(255, 0, 127).hex == "#FF007F" + assert Color(255, 0, 127, 0.5).hex == "#FF007F7F" + + +def test_color_css(): + assert Color(255, 0, 127).css == "rgb(255,0,127)" + assert Color(255, 0, 127, 0.5).css == "rgba(255,0,127,0.5)" + + +def test_color_with_alpha(): + assert Color(255, 50, 100).with_alpha(0.25) == Color(255, 50, 100, 0.25) + + +def test_color_blend(): + assert Color(0, 0, 0).blend(Color(255, 255, 255), 0) == Color(0, 0, 0) + assert Color(0, 0, 0).blend(Color(255, 255, 255), 1.0) == Color(255, 255, 255) + assert Color(0, 0, 0).blend(Color(255, 255, 255), 0.5) == Color(127, 127, 127) + + +@pytest.mark.parametrize( + "text,expected", + [ + ("#000000", Color(0, 0, 0, 1.0)), + ("#ffffff", Color(255, 255, 255, 1.0)), + ("#FFFFFF", Color(255, 255, 255, 1.0)), + ("#fab", Color(255, 170, 187, 1.0)), # #ffaabb + ("#fab0", Color(255, 170, 187, 0.0)), # #ffaabb00 + ("#020304ff", Color(2, 3, 4, 1.0)), + ("#02030400", Color(2, 3, 4, 0.0)), + ("#0203040f", Color(2, 3, 4, 0.058823529411764705)), + ("rgb(0,0,0)", Color(0, 0, 0, 1.0)), + ("rgb(255,255,255)", Color(255, 255, 255, 1.0)), + ("rgba(255,255,255,1)", Color(255, 255, 255, 1.0)), + ("rgb(2,3,4)", Color(2, 3, 4, 1.0)), + ("rgba(2,3,4,1.0)", Color(2, 3, 4, 1.0)), + ("rgba(2,3,4,0.058823529411764705)", Color(2, 3, 4, 0.058823529411764705)), + ("hsl(45,25%,25%)", Color(80, 72, 48)), + ("hsla(45,25%,25%,0.35)", Color(80, 72, 48, 0.35)), + ], +) +def test_color_parse(text, expected): + assert Color.parse(text) == expected + + +@pytest.mark.parametrize( + "input,output", + [ + ("rgb( 300, 300 , 300 )", Color(255, 255, 255)), + ("rgba( 2 , 3 , 4, 1.0 )", Color(2, 3, 4, 1.0)), + ("hsl( 45, 25% , 25% )", Color(80, 72, 48)), + ("hsla( 45, 25% , 25%, 0.35 )", Color(80, 72, 48, 0.35)), + ], +) +def test_color_parse_input_has_spaces(input, output): + assert Color.parse(input) == output + + +@pytest.mark.parametrize( + "input,output", + [ + ("rgb(300, 300, 300)", Color(255, 255, 255)), + ("rgba(300, 300, 300, 300)", Color(255, 255, 255, 1.0)), + ("hsl(400, 200%, 250%)", Color(255, 255, 255, 1.0)), + ("hsla(400, 200%, 250%, 1.9)", Color(255, 255, 255, 1.0)), + ], +) +def test_color_parse_clamp(input, output): + assert Color.parse(input) == output + + +def test_color_parse_hsl_negative_degrees(): + assert Color.parse("hsl(-90, 50%, 50%)") == Color.parse("hsl(270, 50%, 50%)") + + +def test_color_parse_hsla_negative_degrees(): + assert Color.parse("hsla(-45, 50%, 50%, 0.2)") == Color.parse( + "hsla(315, 50%, 50%, 0.2)" + ) + + +def test_color_parse_color(): + # as a convenience, if Color.parse is passed a color object, it will return it + color = Color(20, 30, 40, 0.5) + assert Color.parse(color) is color + + +def test_color_add(): + assert Color(50, 100, 200) + Color(10, 20, 30, 0.9) == Color(14, 28, 47) + + +# Computed with http://www.easyrgb.com/en/convert.php, +# (r, g, b) values in sRGB to (L*, a*, b*) values in CIE-L*ab. +RGB_LAB_DATA = [ + (10, 23, 73, 10.245, 15.913, -32.672), + (200, 34, 123, 45.438, 67.750, -8.008), + (0, 0, 0, 0, 0, 0), + (255, 255, 255, 100, 0, 0), +] + + +def test_color_darken(): + assert Color(200, 210, 220).darken(1) == Color(0, 0, 0) + assert Color(200, 210, 220).darken(-1) == Color(255, 255, 255) + assert Color(200, 210, 220).darken(0.1) == Color(172, 182, 192) + assert Color(200, 210, 220).darken(0.5) == Color(71, 80, 88) + + +def test_color_lighten(): + assert Color(200, 210, 220).lighten(1) == Color(255, 255, 255) + assert Color(200, 210, 220).lighten(-1) == Color(0, 0, 0) + assert Color(200, 210, 220).lighten(0.1) == Color(228, 238, 248) + + +@pytest.mark.parametrize( + "r, g, b, L_, a_, b_", + RGB_LAB_DATA, +) +def test_rgb_to_lab(r, g, b, L_, a_, b_): + """Test conversion from the RGB color space to CIE-L*ab.""" + rgb = Color(r, g, b) + lab = rgb_to_lab(rgb) + assert lab.L == pytest.approx(L_, abs=0.1) + assert lab.a == pytest.approx(a_, abs=0.1) + assert lab.b == pytest.approx(b_, abs=0.1) + + +@pytest.mark.parametrize( + "r, g, b, L_, a_, b_", + RGB_LAB_DATA, +) +def test_lab_to_rgb(r, g, b, L_, a_, b_): + """Test conversion from the CIE-L*ab color space to RGB.""" + + lab = Lab(L_, a_, b_) + rgb = lab_to_rgb(lab) + assert rgb.r == pytest.approx(r, abs=1) + assert rgb.g == pytest.approx(g, abs=1) + assert rgb.b == pytest.approx(b, abs=1) + + +def test_rgb_lab_rgb_roundtrip(): + """Test RGB -> CIE-L*ab -> RGB color conversion roundtripping.""" + + for r in range(0, 256, 32): + for g in range(0, 256, 32): + for b in range(0, 256, 32): + c_ = lab_to_rgb(rgb_to_lab(Color(r, g, b))) + assert c_.r == pytest.approx(r, abs=1) + assert c_.g == pytest.approx(g, abs=1) + assert c_.b == pytest.approx(b, abs=1) + + +def test_inverse(): + assert Color(55, 0, 255, 0.1).inverse == Color(200, 255, 0, 0.1) diff --git a/testbed/Textualize__textual/tests/test_compositor_regions_to_spans.py b/testbed/Textualize__textual/tests/test_compositor_regions_to_spans.py new file mode 100644 index 0000000000000000000000000000000000000000..31de88ad52dd1ff83fa08d46d9b965f0add5ad5f --- /dev/null +++ b/testbed/Textualize__textual/tests/test_compositor_regions_to_spans.py @@ -0,0 +1,54 @@ +from textual._compositor import Compositor +from textual.geometry import Region + + +def test_regions_to_ranges_no_regions(): + assert list(Compositor._regions_to_spans([])) == [] + + +def test_regions_to_ranges_single_region(): + regions = [Region(0, 0, 3, 2)] + assert list(Compositor._regions_to_spans(regions)) == [ + (0, 0, 3), + (1, 0, 3), + ] + + +def test_regions_to_ranges_partially_overlapping_regions(): + regions = [Region(0, 0, 2, 2), Region(1, 1, 2, 2)] + assert list(Compositor._regions_to_spans(regions)) == [ + (0, 0, 2), + (1, 0, 3), + (2, 1, 3), + ] + + +def test_regions_to_ranges_fully_overlapping_regions(): + regions = [Region(1, 1, 3, 3), Region(2, 2, 1, 1), Region(0, 2, 3, 1)] + assert list(Compositor._regions_to_spans(regions)) == [ + (1, 1, 4), + (2, 0, 4), + (3, 1, 4), + ] + + +def test_regions_to_ranges_disjoint_regions_different_lines(): + regions = [Region(0, 0, 2, 1), Region(2, 2, 2, 1)] + assert list(Compositor._regions_to_spans(regions)) == [(0, 0, 2), (2, 2, 4)] + + +def test_regions_to_ranges_disjoint_regions_same_line(): + regions = [Region(0, 0, 1, 2), Region(2, 0, 1, 1)] + assert list(Compositor._regions_to_spans(regions)) == [ + (0, 0, 1), + (0, 2, 3), + (1, 0, 1), + ] + + +def test_regions_to_ranges_directly_adjacent_ranges_merged(): + regions = [Region(0, 0, 1, 2), Region(1, 0, 1, 2)] + assert list(Compositor._regions_to_spans(regions)) == [ + (0, 0, 2), + (1, 0, 2), + ] diff --git a/testbed/Textualize__textual/tests/test_dom.py b/testbed/Textualize__textual/tests/test_dom.py new file mode 100644 index 0000000000000000000000000000000000000000..e4254f6e556efd7a5df99d00f2caa0d72643c021 --- /dev/null +++ b/testbed/Textualize__textual/tests/test_dom.py @@ -0,0 +1,77 @@ +import pytest + +from textual.css.errors import StyleValueError +from textual.css.query import NoMatches +from textual.dom import DOMNode, BadIdentifier + + +def test_display_default(): + node = DOMNode() + assert node.display is True + + +@pytest.mark.parametrize( + "setter_value,style_value", + [[True, "block"], [False, "none"], ["block", "block"], ["none", "none"]], +) +def test_display_set_bool(setter_value, style_value): + node = DOMNode() + node.display = setter_value + assert node.styles.display == style_value + + +def test_display_set_invalid_value(): + node = DOMNode() + with pytest.raises(StyleValueError): + node.display = "blah" + + +@pytest.fixture +def parent(): + parent = DOMNode(id="parent") + child1 = DOMNode(id="child1") + child2 = DOMNode(id="child2") + grandchild1 = DOMNode(id="grandchild1") + child1._add_child(grandchild1) + + parent._add_child(child1) + parent._add_child(child2) + + yield parent + + +def test_get_child_gets_first_child(parent): + child = parent.get_child(id="child1") + assert child.id == "child1" + assert child.get_child(id="grandchild1").id == "grandchild1" + assert parent.get_child(id="child2").id == "child2" + + +def test_get_child_no_matching_child(parent): + with pytest.raises(NoMatches): + parent.get_child(id="doesnt-exist") + + +def test_get_child_only_immediate_descendents(parent): + with pytest.raises(NoMatches): + parent.get_child(id="grandchild1") + + +def test_validate(): + with pytest.raises(BadIdentifier): + DOMNode(id="23") + with pytest.raises(BadIdentifier): + DOMNode(id=".3") + with pytest.raises(BadIdentifier): + DOMNode(classes="+2323") + with pytest.raises(BadIdentifier): + DOMNode(classes="foo 22") + + node = DOMNode() + node.add_class("foo") + with pytest.raises(BadIdentifier): + node.add_class("1") + with pytest.raises(BadIdentifier): + node.remove_class("1") + with pytest.raises(BadIdentifier): + node.toggle_class("1") diff --git a/testbed/Textualize__textual/tests/test_easing.py b/testbed/Textualize__textual/tests/test_easing.py new file mode 100644 index 0000000000000000000000000000000000000000..abdfe0a7005fdcef575602d0211f0f23d1031e4a --- /dev/null +++ b/testbed/Textualize__textual/tests/test_easing.py @@ -0,0 +1,741 @@ +""" +Test the easing functions by sampling the range [0, 1] uniformly in 21 points. +Then, a TypeScript script was used to sample all the original functions, +the data was collected, and is here tested against the Python implementation. +""" + +import pytest + +from textual._easing import EASING + + +POINTS = [ + 0.0, + 0.05, + 0.1, + 0.15, + 0.2, + 0.25, + 0.3, + 0.35, + 0.4, + 0.45, + 0.5, + 0.55, + 0.6, + 0.65, + 0.7, + 0.75, + 0.8, + 0.85, + 0.9, + 0.95, + 1.0, +] + +DATA = { + "none": [1] * len(POINTS), + "round": [0] * POINTS.index(0.5) + [1] * (len(POINTS) - POINTS.index(0.5)), + "linear": POINTS[::], + "in_sine": [ + 0, + 0.003082666266872036, + 0.01231165940486223, + 0.027630079602323443, + 0.04894348370484647, + 0.07612046748871326, + 0.1089934758116321, + 0.1473598356459077, + 0.19098300562505255, + 0.23959403439996907, + 0.2928932188134524, + 0.35055195166981645, + 0.41221474770752686, + 0.4775014352840511, + 0.5460095002604531, + 0.6173165676349102, + 0.6909830056250525, + 0.7665546361440945, + 0.843565534959769, + 0.921540904272155, + 0.9999999999999999, + ], + "out_sine": [ + 0, + 0.07845909572784494, + 0.15643446504023087, + 0.2334453638559054, + 0.3090169943749474, + 0.3826834323650898, + 0.45399049973954675, + 0.5224985647159488, + 0.5877852522924731, + 0.6494480483301837, + 0.7071067811865475, + 0.760405965600031, + 0.8090169943749475, + 0.8526401643540922, + 0.8910065241883678, + 0.9238795325112867, + 0.9510565162951535, + 0.9723699203976766, + 0.9876883405951378, + 0.996917333733128, + 1, + ], + "in_out_sine": [ + 0, + 0.006155829702431115, + 0.024471741852423234, + 0.05449673790581605, + 0.09549150281252627, + 0.1464466094067262, + 0.20610737385376343, + 0.27300475013022657, + 0.3454915028125263, + 0.4217827674798845, + 0.49999999999999994, + 0.5782172325201155, + 0.6545084971874737, + 0.7269952498697734, + 0.7938926261462365, + 0.8535533905932737, + 0.9045084971874737, + 0.9455032620941839, + 0.9755282581475768, + 0.9938441702975689, + 1, + ], + "in_quad": [ + 0, + 0.0025000000000000005, + 0.010000000000000002, + 0.0225, + 0.04000000000000001, + 0.0625, + 0.09, + 0.12249999999999998, + 0.16000000000000003, + 0.2025, + 0.25, + 0.30250000000000005, + 0.36, + 0.42250000000000004, + 0.48999999999999994, + 0.5625, + 0.6400000000000001, + 0.7224999999999999, + 0.81, + 0.9025, + 1, + ], + "out_quad": [ + 0, + 0.09750000000000003, + 0.18999999999999995, + 0.2775000000000001, + 0.3599999999999999, + 0.4375, + 0.51, + 0.5774999999999999, + 0.64, + 0.6975, + 0.75, + 0.7975000000000001, + 0.84, + 0.8775000000000001, + 0.9099999999999999, + 0.9375, + 0.96, + 0.9775, + 0.99, + 0.9974999999999999, + 1, + ], + "in_out_quad": [ + 0, + 0.005000000000000001, + 0.020000000000000004, + 0.045, + 0.08000000000000002, + 0.125, + 0.18, + 0.24499999999999997, + 0.32000000000000006, + 0.405, + 0.5, + 0.5950000000000001, + 0.6799999999999999, + 0.755, + 0.82, + 0.875, + 0.92, + 0.955, + 0.98, + 0.995, + 1, + ], + "in_cubic": [ + 0, + 0.00012500000000000003, + 0.0010000000000000002, + 0.003375, + 0.008000000000000002, + 0.015625, + 0.027, + 0.04287499999999999, + 0.06400000000000002, + 0.09112500000000001, + 0.125, + 0.16637500000000005, + 0.216, + 0.27462500000000006, + 0.3429999999999999, + 0.421875, + 0.5120000000000001, + 0.6141249999999999, + 0.7290000000000001, + 0.8573749999999999, + 1, + ], + "out_cubic": [ + 0, + 0.1426250000000001, + 0.2709999999999999, + 0.3858750000000001, + 0.4879999999999999, + 0.578125, + 0.657, + 0.7253749999999999, + 0.784, + 0.833625, + 0.875, + 0.908875, + 0.9359999999999999, + 0.957125, + 0.973, + 0.984375, + 0.992, + 0.996625, + 0.999, + 0.999875, + 1, + ], + "in_out_cubic": [ + 0, + 0.0005000000000000001, + 0.004000000000000001, + 0.0135, + 0.03200000000000001, + 0.0625, + 0.108, + 0.17149999999999996, + 0.25600000000000006, + 0.36450000000000005, + 0.5, + 0.6355000000000002, + 0.744, + 0.8285, + 0.8919999999999999, + 0.9375, + 0.968, + 0.9865, + 0.996, + 0.9994999999999999, + 1, + ], + "in_quart": [ + 0, + 0.000006250000000000002, + 0.00010000000000000003, + 0.00050625, + 0.0016000000000000005, + 0.00390625, + 0.0081, + 0.015006249999999995, + 0.025600000000000008, + 0.04100625000000001, + 0.0625, + 0.09150625000000004, + 0.1296, + 0.17850625000000006, + 0.24009999999999992, + 0.31640625, + 0.40960000000000013, + 0.5220062499999999, + 0.6561000000000001, + 0.8145062499999999, + 1, + ], + "out_quart": [ + 0, + 0.18549375, + 0.3438999999999999, + 0.4779937500000001, + 0.5903999999999998, + 0.68359375, + 0.7599, + 0.8214937499999999, + 0.8704000000000001, + 0.90849375, + 0.9375, + 0.95899375, + 0.9743999999999999, + 0.98499375, + 0.9919, + 0.99609375, + 0.9984, + 0.99949375, + 0.9999, + 0.99999375, + 1, + ], + "in_out_quart": [ + 0, + 0.000050000000000000016, + 0.0008000000000000003, + 0.00405, + 0.012800000000000004, + 0.03125, + 0.0648, + 0.12004999999999996, + 0.20480000000000007, + 0.32805000000000006, + 0.5, + 0.6719500000000002, + 0.7951999999999999, + 0.87995, + 0.9351999999999999, + 0.96875, + 0.9872, + 0.99595, + 0.9992, + 0.99995, + 1, + ], + "in_quint": [ + 0, + 3.1250000000000013e-7, + 0.000010000000000000004, + 0.0000759375, + 0.00032000000000000013, + 0.0009765625, + 0.00243, + 0.005252187499999998, + 0.010240000000000004, + 0.018452812500000006, + 0.03125, + 0.050328437500000024, + 0.07776, + 0.11602906250000004, + 0.16806999999999994, + 0.2373046875, + 0.32768000000000014, + 0.4437053124999999, + 0.5904900000000002, + 0.7737809374999999, + 1, + ], + "out_quint": [ + 0, + 0.2262190625, + 0.4095099999999998, + 0.5562946875000001, + 0.6723199999999998, + 0.7626953125, + 0.8319300000000001, + 0.8839709375, + 0.92224, + 0.9496715625, + 0.96875, + 0.9815471875, + 0.98976, + 0.9947478125, + 0.99757, + 0.9990234375, + 0.99968, + 0.9999240625, + 0.99999, + 0.9999996875, + 1, + ], + "in_out_quint": [ + 0, + 0.000005000000000000002, + 0.00016000000000000007, + 0.001215, + 0.005120000000000002, + 0.015625, + 0.03888, + 0.08403499999999997, + 0.16384000000000007, + 0.2952450000000001, + 0.5, + 0.7047550000000002, + 0.8361599999999999, + 0.915965, + 0.96112, + 0.984375, + 0.99488, + 0.998785, + 0.99984, + 0.999995, + 1, + ], + "in_expo": [ + 0, + 0.0013810679320049757, + 0.001953125, + 0.0027621358640099515, + 0.00390625, + 0.005524271728019903, + 0.0078125, + 0.011048543456039806, + 0.015625, + 0.02209708691207961, + 0.03125, + 0.04419417382415922, + 0.0625, + 0.08838834764831845, + 0.125, + 0.1767766952966369, + 0.25, + 0.3535533905932738, + 0.5, + 0.7071067811865476, + 1, + ], + "out_expo": [ + 0, + 0.2928932188134524, + 0.5, + 0.6464466094067263, + 0.75, + 0.8232233047033631, + 0.875, + 0.9116116523516815, + 0.9375, + 0.9558058261758408, + 0.96875, + 0.9779029130879204, + 0.984375, + 0.9889514565439602, + 0.9921875, + 0.99447572827198, + 0.99609375, + 0.99723786413599, + 0.998046875, + 0.998618932067995, + 1, + ], + "in_out_expo": [ + 0, + 0.0009765625, + 0.001953125, + 0.00390625, + 0.0078125, + 0.015625, + 0.03125, + 0.0625, + 0.125, + 0.25, + 0.5, + 0.75, + 0.875, + 0.9375, + 0.96875, + 0.984375, + 0.9921875, + 0.99609375, + 0.998046875, + 0.9990234375, + 1, + ], + "in_circ": [ + 0, + 0.0012507822280910519, + 0.005012562893380035, + 0.011314003335740508, + 0.020204102886728803, + 0.031754163448145745, + 0.04606079858305434, + 0.06325030024024025, + 0.08348486100883201, + 0.10697144502541245, + 0.1339745962155614, + 0.16483534557549673, + 0.19999999999999996, + 0.24006579232146685, + 0.285857157145715, + 0.3385621722338523, + 0.40000000000000013, + 0.473217312357363, + 0.5641101056459328, + 0.6877501000800801, + 1, + ], + "out_circ": [ + 0, + 0.31224989991991997, + 0.4358898943540673, + 0.526782687642637, + 0.5999999999999999, + 0.6614378277661477, + 0.714142842854285, + 0.7599342076785331, + 0.8, + 0.8351646544245033, + 0.8660254037844386, + 0.8930285549745877, + 0.916515138991168, + 0.9367496997597597, + 0.9539392014169457, + 0.9682458365518543, + 0.9797958971132712, + 0.9886859966642595, + 0.99498743710662, + 0.998749217771909, + 1, + ], + "in_out_circ": [ + 0, + 0.0025062814466900174, + 0.010102051443364402, + 0.02303039929152717, + 0.041742430504416006, + 0.0669872981077807, + 0.09999999999999998, + 0.1429285785728575, + 0.20000000000000007, + 0.2820550528229664, + 0.5, + 0.7179449471770338, + 0.7999999999999999, + 0.8570714214271424, + 0.8999999999999999, + 0.9330127018922193, + 0.958257569495584, + 0.9769696007084728, + 0.9898979485566356, + 0.9974937185533099, + 1, + ], + "in_back": [ + 0, + -0.003916252500000001, + -0.014314220000000004, + -0.029167717499999996, + -0.046450560000000016, + -0.06413656250000001, + -0.08019953999999999, + -0.09261330750000002, + -0.09935168000000005, + -0.09838847249999999, + -0.08769750000000004, + -0.06525257750000002, + -0.029027519999999973, + 0.023003857500000002, + 0.09286773999999975, + 0.18259031249999969, + 0.29419775999999986, + 0.4297162674999999, + 0.5911720200000001, + 0.7805912024999997, + 0.9999999999999998, + ], + "out_back": [ + 2.220446049250313e-16, + 0.21940879750000053, + 0.40882797999999987, + 0.5702837325000001, + 0.7058022400000001, + 0.8174096875000002, + 0.9071322600000001, + 0.9769961425, + 1.02902752, + 1.0652525775, + 1.0876975, + 1.0983884725, + 1.09935168, + 1.0926133075, + 1.08019954, + 1.0641365625, + 1.04645056, + 1.0291677175, + 1.01431422, + 1.0039162525, + 1, + ], + "in_out_back": [ + -0, + -0.011177092750000001, + -0.037518552000000004, + -0.06823964924999999, + -0.092555656, + -0.09968184375, + -0.07883348399999998, + -0.019225848250000063, + 0.0899257920000001, + 0.25940616525, + 0.5, + 0.7405938347500003, + 0.9100742079999999, + 1.01922584825, + 1.078833484, + 1.09968184375, + 1.092555656, + 1.06823964925, + 1.0375185519999999, + 1.0111770927500001, + 1, + ], + "in_elastic": [ + 0, + 0.0006905339660024924, + 0.001953125, + 0.0013810679320049725, + -0.0019531250000000126, + -0.005524271728019903, + -0.0039062499999999918, + 0.00552427172801992, + 0.015625, + 0.011048543456039785, + -0.015625000000000045, + -0.04419417382415922, + -0.031249999999999948, + 0.04419417382415934, + 0.125, + 0.08838834764831832, + -0.1250000000000001, + -0.3535533905932738, + -0.24999999999999986, + 0.353553390593274, + 1, + ], + "out_elastic": [ + 0, + 0.6464466094067263, + 1.25, + 1.3535533905932737, + 1.125, + 0.9116116523516816, + 0.875, + 0.9558058261758408, + 1.03125, + 1.0441941738241591, + 1.015625, + 0.9889514565439602, + 0.984375, + 0.99447572827198, + 1.00390625, + 1.00552427172802, + 1.001953125, + 0.998618932067995, + 0.998046875, + 0.9993094660339975, + 1, + ], + "in_out_elastic": [ + 0, + 0.0009765625, + 0.000339156597005722, + -0.0036706742999449557, + -0.0039062499999999935, + 0.011969444423734044, + 0.023938888847468056, + -0.03125000000000003, + -0.11746157759823853, + 0.04341204441673268, + 0.5, + 0.9565879555832674, + 1.1174615775982386, + 1.03125, + 0.9760611111525319, + 0.988030555576266, + 1.00390625, + 1.003670674299945, + 0.9996608434029943, + 0.9990234375, + 1, + ], + "in_bounce": [ + 0, + 0.015468750000000031, + 0.01187500000000008, + 0.05484375000000008, + 0.06000000000000005, + 0.02734375, + 0.06937499999999996, + 0.1673437499999999, + 0.22750000000000004, + 0.24984375000000003, + 0.234375, + 0.18109375000000005, + 0.09000000000000019, + 0.07359375000000024, + 0.31937499999999985, + 0.52734375, + 0.6975000000000001, + 0.82984375, + 0.9243750000000001, + 0.98109375, + 1, + ], + "out_bounce": [ + 0, + 0.018906250000000003, + 0.07562500000000001, + 0.17015624999999998, + 0.30250000000000005, + 0.47265625, + 0.6806249999999999, + 0.9264062499999998, + 0.9099999999999998, + 0.81890625, + 0.765625, + 0.75015625, + 0.7725, + 0.8326562500000001, + 0.930625, + 0.97265625, + 0.94, + 0.9451562499999999, + 0.9881249999999999, + 0.98453125, + 1, + ], + "in_out_bounce": [ + 0, + 0.00593750000000004, + 0.030000000000000027, + 0.03468749999999998, + 0.11375000000000002, + 0.1171875, + 0.045000000000000095, + 0.15968749999999993, + 0.34875000000000006, + 0.46218750000000003, + 0.5, + 0.5378125, + 0.6512499999999999, + 0.8403125, + 0.9550000000000001, + 0.8828125, + 0.88625, + 0.9653125, + 0.97, + 0.9940624999999998, + 1, + ], +} + + +def test_coverage(): + assert set(DATA.keys()) == set(EASING.keys()) + + +def test_easings(): + for name, values in DATA.items(): + func = EASING[name] + for point, value in zip(POINTS, values): + assert value == pytest.approx(func(point)) diff --git a/testbed/Textualize__textual/tests/test_features.py b/testbed/Textualize__textual/tests/test_features.py new file mode 100644 index 0000000000000000000000000000000000000000..d99b6c244de25863c8a49911a642974255411bef --- /dev/null +++ b/testbed/Textualize__textual/tests/test_features.py @@ -0,0 +1,29 @@ +from __future__ import annotations + +from textual.app import App + + +def test_textual_env_var(monkeypatch): + monkeypatch.setenv("TEXTUAL", "") + app = App() + assert app.features == set() + assert app.devtools_enabled is False + assert app.debug is False + + monkeypatch.setenv("TEXTUAL", "devtools") + app = App() + assert app.features == {"devtools"} + assert app.devtools_enabled is True + assert app.debug is False + + monkeypatch.setenv("TEXTUAL", "devtools,debug") + app = App() + assert app.features == {"devtools", "debug"} + assert app.devtools_enabled is True + assert app.debug is True + + monkeypatch.setenv("TEXTUAL", "devtools, debug") + app = App() + assert app.features == {"devtools", "debug"} + assert app.devtools_enabled is True + assert app.debug is True diff --git a/testbed/Textualize__textual/tests/test_focus.py b/testbed/Textualize__textual/tests/test_focus.py new file mode 100644 index 0000000000000000000000000000000000000000..78542aed93035a82a85795c75f02634d316de124 --- /dev/null +++ b/testbed/Textualize__textual/tests/test_focus.py @@ -0,0 +1,53 @@ +from textual.app import App +from textual.screen import Screen +from textual.widget import Widget + + +class Focusable(Widget, can_focus=True): + pass + + +class NonFocusable(Widget, can_focus=False, can_focus_children=False): + pass + + +async def test_focus_chain(): + + app = App() + app._set_active() + app.push_screen(Screen()) + + # Check empty focus chain + assert not app.focus_chain + + app.screen._add_children( + Focusable(id="foo"), + NonFocusable(id="bar"), + Focusable(Focusable(id="Paul"), id="container1"), + NonFocusable(Focusable(id="Jessica"), id="container2"), + Focusable(id="baz"), + ) + + focused = [widget.id for widget in app.focus_chain] + assert focused == ["foo", "Paul", "baz"] + + +async def test_focus_next_and_previous(): + + app = App() + app._set_active() + app.push_screen(Screen()) + app.screen._add_children( + Focusable(id="foo"), + NonFocusable(id="bar"), + Focusable(Focusable(id="Paul"), id="container1"), + NonFocusable(Focusable(id="Jessica"), id="container2"), + Focusable(id="baz"), + ) + + assert app.focus_next().id == "foo" + assert app.focus_next().id == "Paul" + assert app.focus_next().id == "baz" + + assert app.focus_previous().id == "Paul" + assert app.focus_previous().id == "foo" diff --git a/testbed/Textualize__textual/tests/test_geometry.py b/testbed/Textualize__textual/tests/test_geometry.py new file mode 100644 index 0000000000000000000000000000000000000000..766dc703f4a3a15e200162cc435fe5eac43b8878 --- /dev/null +++ b/testbed/Textualize__textual/tests/test_geometry.py @@ -0,0 +1,437 @@ +import pytest + +from textual.geometry import clamp, Offset, Size, Region, Spacing + + +def test_dimensions_region(): + assert Size(30, 40).region == Region(0, 0, 30, 40) + + +def test_dimensions_contains(): + assert Size(10, 10).contains(5, 5) + assert Size(10, 10).contains(9, 9) + assert Size(10, 10).contains(0, 0) + assert not Size(10, 10).contains(10, 9) + assert not Size(10, 10).contains(9, 10) + assert not Size(10, 10).contains(-1, 0) + assert not Size(10, 10).contains(0, -1) + + +def test_dimensions_contains_point(): + assert Size(10, 10).contains_point(Offset(5, 5)) + assert Size(10, 10).contains_point(Offset(9, 9)) + assert Size(10, 10).contains_point(Offset(0, 0)) + assert not Size(10, 10).contains_point(Offset(10, 9)) + assert not Size(10, 10).contains_point(Offset(9, 10)) + assert not Size(10, 10).contains_point(Offset(-1, 0)) + assert not Size(10, 10).contains_point(Offset(0, -1)) + + +def test_dimensions_contains_special(): + with pytest.raises(TypeError): + (1, 2, 3) in Size(10, 10) + + assert (5, 5) in Size(10, 10) + assert (9, 9) in Size(10, 10) + assert (0, 0) in Size(10, 10) + assert (10, 9) not in Size(10, 10) + assert (9, 10) not in Size(10, 10) + assert (-1, 0) not in Size(10, 10) + assert (0, -1) not in Size(10, 10) + + +def test_dimensions_bool(): + assert Size(1, 1) + assert Size(3, 4) + assert not Size(0, 1) + assert not Size(1, 0) + + +def test_dimensions_area(): + assert Size(0, 0).area == 0 + assert Size(1, 0).area == 0 + assert Size(1, 1).area == 1 + assert Size(4, 5).area == 20 + + +def test_clamp(): + assert clamp(5, 0, 10) == 5 + assert clamp(-1, 0, 10) == 0 + assert clamp(11, 0, 10) == 10 + assert clamp(0, 0, 10) == 0 + assert clamp(10, 0, 10) == 10 + assert clamp(5, 10, 0) == 5 + + +def test_offset_bool(): + assert Offset(1, 0) + assert Offset(0, 1) + assert Offset(0, -1) + assert not Offset(0, 0) + + +def test_offset_is_origin(): + assert Offset(0, 0).is_origin + assert not Offset(1, 0).is_origin + + +def test_offset_add(): + assert Offset(1, 1) + Offset(2, 2) == Offset(3, 3) + assert Offset(1, 2) + Offset(3, 4) == Offset(4, 6) + with pytest.raises(TypeError): + Offset(1, 1) + "foo" + + +def test_offset_sub(): + assert Offset(1, 1) - Offset(2, 2) == Offset(-1, -1) + assert Offset(3, 4) - Offset(2, 1) == Offset(1, 3) + with pytest.raises(TypeError): + Offset(1, 1) - "foo" + + +def test_offset_neg(): + assert Offset(0, 0) == Offset(0, 0) + assert -Offset(2, -3) == Offset(-2, 3) + + +def test_offset_mul(): + assert Offset(2, 1) * 2 == Offset(4, 2) + assert Offset(2, 1) * -2 == Offset(-4, -2) + assert Offset(2, 1) * 0 == Offset(0, 0) + with pytest.raises(TypeError): + Offset(10, 20) * "foo" + + +def test_offset_blend(): + assert Offset(1, 2).blend(Offset(3, 4), 0) == Offset(1, 2) + assert Offset(1, 2).blend(Offset(3, 4), 1) == Offset(3, 4) + assert Offset(1, 2).blend(Offset(3, 4), 0.5) == Offset(2, 3) + + +def test_offset_get_distance_to(): + assert Offset(20, 30).get_distance_to(Offset(20, 30)) == 0 + assert Offset(0, 0).get_distance_to(Offset(1, 0)) == 1.0 + assert Offset(2, 1).get_distance_to(Offset(5, 5)) == 5.0 + + +def test_region_null(): + assert Region() == Region(0, 0, 0, 0) + assert not Region() + + +def test_region_from_union(): + with pytest.raises(ValueError): + Region.from_union([]) + regions = [ + Region(10, 20, 30, 40), + Region(15, 25, 5, 5), + Region(30, 25, 20, 10), + ] + assert Region.from_union(regions) == Region(10, 20, 40, 40) + + +def test_region_from_offset(): + assert Region.from_offset(Offset(3, 4), (5, 6)) == Region(3, 4, 5, 6) + + +@pytest.mark.parametrize( + "window,region,scroll", + [ + (Region(0, 0, 200, 100), Region(0, 0, 200, 100), Offset(0, 0)), + (Region(0, 0, 200, 100), Region(0, -100, 10, 10), Offset(0, -100)), + (Region(10, 15, 20, 10), Region(0, 0, 50, 50), Offset(-10, -15)), + ], +) +def test_get_scroll_to_visible(window, region, scroll): + assert Region.get_scroll_to_visible(window, region) == scroll + assert region.overlaps(window + scroll) + + +def test_region_area(): + assert Region(3, 4, 0, 0).area == 0 + assert Region(3, 4, 5, 6).area == 30 + + +def test_region_size(): + assert isinstance(Region(3, 4, 5, 6).size, Size) + assert Region(3, 4, 5, 6).size == Size(5, 6) + + +def test_region_origin(): + assert Region(1, 2, 3, 4).offset == Offset(1, 2) + + +def test_region_bottom_left(): + assert Region(1, 2, 3, 4).bottom_left == Offset(1, 6) + + +def test_region_top_right(): + assert Region(1, 2, 3, 4).top_right == Offset(4, 2) + + +def test_region_bottom_right(): + assert Region(1, 2, 3, 4).bottom_right == Offset(4, 6) + + +def test_region_add(): + assert Region(1, 2, 3, 4) + (10, 20) == Region(11, 22, 3, 4) + with pytest.raises(TypeError): + Region(1, 2, 3, 4) + "foo" + + +def test_region_sub(): + assert Region(11, 22, 3, 4) - (10, 20) == Region(1, 2, 3, 4) + with pytest.raises(TypeError): + Region(1, 2, 3, 4) - "foo" + + +def test_region_at_offset(): + assert Region(10, 10, 30, 40).at_offset((0, 0)) == Region(0, 0, 30, 40) + assert Region(10, 10, 30, 40).at_offset((-15, 30)) == Region(-15, 30, 30, 40) + + +def test_crop_size(): + assert Region(10, 20, 100, 200).crop_size((50, 40)) == Region(10, 20, 50, 40) + assert Region(10, 20, 100, 200).crop_size((500, 40)) == Region(10, 20, 100, 40) + + +def test_clip_size(): + assert Region(10, 10, 100, 80).clip_size((50, 100)) == Region(10, 10, 50, 80) + + +def test_region_overlaps(): + assert Region(10, 10, 30, 20).overlaps(Region(0, 0, 20, 20)) + assert not Region(10, 10, 5, 5).overlaps(Region(15, 15, 20, 20)) + + assert not Region(10, 10, 5, 5).overlaps(Region(0, 0, 50, 10)) + assert Region(10, 10, 5, 5).overlaps(Region(0, 0, 50, 11)) + assert not Region(10, 10, 5, 5).overlaps(Region(0, 15, 50, 10)) + assert Region(10, 10, 5, 5).overlaps(Region(0, 14, 50, 10)) + + +def test_region_contains(): + assert Region(10, 10, 20, 30).contains(10, 10) + assert Region(10, 10, 20, 30).contains(29, 39) + assert not Region(10, 10, 20, 30).contains(30, 40) + + +def test_region_contains_point(): + assert Region(10, 10, 20, 30).contains_point((10, 10)) + assert Region(10, 10, 20, 30).contains_point((29, 39)) + assert not Region(10, 10, 20, 30).contains_point((30, 40)) + with pytest.raises(TypeError): + Region(10, 10, 20, 30).contains_point((1, 2, 3)) + + +def test_region_contains_region(): + assert Region(10, 10, 20, 30).contains_region(Region(10, 10, 5, 5)) + assert not Region(10, 10, 20, 30).contains_region(Region(10, 9, 5, 5)) + assert not Region(10, 10, 20, 30).contains_region(Region(9, 10, 5, 5)) + assert Region(10, 10, 20, 30).contains_region(Region(10, 10, 20, 30)) + assert not Region(10, 10, 20, 30).contains_region(Region(10, 10, 21, 30)) + assert not Region(10, 10, 20, 30).contains_region(Region(10, 10, 20, 31)) + + +def test_region_translate(): + assert Region(1, 2, 3, 4).translate((10, 20)) == Region(11, 22, 3, 4) + assert Region(1, 2, 3, 4).translate((0, 20)) == Region(1, 22, 3, 4) + + +def test_region_contains_special(): + assert (10, 10) in Region(10, 10, 20, 30) + assert (9, 10) not in Region(10, 10, 20, 30) + assert Region(10, 10, 5, 5) in Region(10, 10, 20, 30) + assert Region(5, 5, 5, 5) not in Region(10, 10, 20, 30) + assert "foo" not in Region(0, 0, 10, 10) + + +def test_clip(): + assert Region(10, 10, 20, 30).clip(20, 25) == Region(10, 10, 10, 15) + + +def test_region_shrink(): + margin = Spacing(top=1, right=2, bottom=3, left=4) + region = Region(x=10, y=10, width=50, height=50) + assert region.shrink(margin) == Region(x=14, y=11, width=44, height=46) + + +def test_region_grow(): + margin = Spacing(top=1, right=2, bottom=3, left=4) + region = Region(x=10, y=10, width=50, height=50) + assert region.grow(margin) == Region(x=6, y=9, width=56, height=54) + + +def test_region_intersection(): + assert Region(0, 0, 100, 50).intersection(Region(10, 10, 10, 10)) == Region( + 10, 10, 10, 10 + ) + assert Region(10, 10, 30, 20).intersection(Region(20, 15, 60, 40)) == Region( + 20, 15, 20, 15 + ) + + assert not Region(10, 10, 20, 30).intersection(Region(50, 50, 100, 200)) + + +def test_region_union(): + assert Region(5, 5, 10, 10).union(Region(20, 30, 10, 5)) == Region(5, 5, 25, 30) + + +def test_size_add(): + assert Size(5, 10) + Size(2, 3) == Size(7, 13) + with pytest.raises(TypeError): + Size(1, 2) + "foo" + + +def test_size_sub(): + assert Size(5, 10) - Size(2, 3) == Size(3, 7) + with pytest.raises(TypeError): + Size(1, 2) - "foo" + + +def test_region_x_extents(): + assert Region(5, 10, 20, 30).column_span == (5, 25) + + +def test_region_y_extents(): + assert Region(5, 10, 20, 30).line_span == (10, 40) + + +def test_region_x_max(): + assert Region(5, 10, 20, 30).right == 25 + + +def test_region_y_max(): + assert Region(5, 10, 20, 30).bottom == 40 + + +def test_region_columns_range(): + assert Region(5, 10, 20, 30).column_range == range(5, 25) + + +def test_region_lines_range(): + assert Region(5, 10, 20, 30).line_range == range(10, 40) + + +def test_region_reset_offset(): + assert Region(5, 10, 20, 30).reset_offset == Region(0, 0, 20, 30) + + +def test_region_expand(): + assert Region(50, 10, 10, 5).expand((2, 3)) == Region(48, 7, 14, 11) + + +def test_spacing_bool(): + assert Spacing(1, 0, 0, 0) + assert Spacing(0, 1, 0, 0) + assert Spacing(0, 1, 0, 0) + assert Spacing(0, 0, 1, 0) + assert Spacing(0, 0, 0, 1) + assert not Spacing(0, 0, 0, 0) + + +def test_spacing_width(): + assert Spacing(2, 3, 4, 5).width == 8 + + +def test_spacing_height(): + assert Spacing(2, 3, 4, 5).height == 6 + + +def test_spacing_top_left(): + assert Spacing(2, 3, 4, 5).top_left == (5, 2) + + +def test_spacing_bottom_right(): + assert Spacing(2, 3, 4, 5).bottom_right == (3, 4) + + +def test_spacing_totals(): + assert Spacing(2, 3, 4, 5).totals == (8, 6) + + +def test_spacing_css(): + assert Spacing(1, 1, 1, 1).css == "1" + assert Spacing(1, 2, 1, 2).css == "1 2" + assert Spacing(1, 2, 3, 4).css == "1 2 3 4" + + +def test_spacing_unpack(): + assert Spacing.unpack(1) == Spacing(1, 1, 1, 1) + assert Spacing.unpack((1,)) == Spacing(1, 1, 1, 1) + assert Spacing.unpack((1, 2)) == Spacing(1, 2, 1, 2) + assert Spacing.unpack((1, 2, 3, 4)) == Spacing(1, 2, 3, 4) + + with pytest.raises(ValueError): + assert Spacing.unpack(()) == Spacing(1, 2, 1, 2) + + with pytest.raises(ValueError): + assert Spacing.unpack((1, 2, 3)) == Spacing(1, 2, 1, 2) + + with pytest.raises(ValueError): + assert Spacing.unpack((1, 2, 3, 4, 5)) == Spacing(1, 2, 1, 2) + + +def test_spacing_add(): + assert Spacing(1, 2, 3, 4) + Spacing(5, 6, 7, 8) == Spacing(6, 8, 10, 12) + + with pytest.raises(TypeError): + Spacing(1, 2, 3, 4) + "foo" + + +def test_spacing_sub(): + assert Spacing(1, 2, 3, 4) - Spacing(5, 6, 7, 8) == Spacing(-4, -4, -4, -4) + + with pytest.raises(TypeError): + Spacing(1, 2, 3, 4) - "foo" + + +def test_spacing_convenience_constructors(): + assert Spacing.vertical(2) == Spacing(2, 0, 2, 0) + assert Spacing.horizontal(2) == Spacing(0, 2, 0, 2) + assert Spacing.all(2) == Spacing(2, 2, 2, 2) + + +def test_split(): + assert Region(10, 5, 22, 15).split(10, 5) == ( + Region(10, 5, 10, 5), + Region(20, 5, 12, 5), + Region(10, 10, 10, 10), + Region(20, 10, 12, 10), + ) + + +def test_split_negative(): + assert Region(10, 5, 22, 15).split(-1, -1) == ( + Region(10, 5, 21, 14), + Region(31, 5, 1, 14), + Region(10, 19, 21, 1), + Region(31, 19, 1, 1), + ) + + +def test_split_vertical(): + assert Region(10, 5, 22, 15).split_vertical(10) == ( + Region(10, 5, 10, 15), + Region(20, 5, 12, 15), + ) + + +def test_split_vertical_negative(): + assert Region(10, 5, 22, 15).split_vertical(-1) == ( + Region(10, 5, 21, 15), + Region(31, 5, 1, 15), + ) + + +def test_split_horizontal(): + assert Region(10, 5, 22, 15).split_horizontal(5) == ( + Region(10, 5, 22, 5), + Region(10, 10, 22, 10), + ) + + +def test_split_horizontal_negative(): + assert Region(10, 5, 22, 15).split_horizontal(-1) == ( + Region(10, 5, 22, 14), + Region(10, 19, 22, 1), + ) diff --git a/testbed/Textualize__textual/tests/test_integration_layout.py b/testbed/Textualize__textual/tests/test_integration_layout.py new file mode 100644 index 0000000000000000000000000000000000000000..cbfaaced94813e216d9b802f498605caf07931fe --- /dev/null +++ b/testbed/Textualize__textual/tests/test_integration_layout.py @@ -0,0 +1,325 @@ +from __future__ import annotations +from typing import cast, List, Sequence + +import pytest +from rich.console import RenderableType +from rich.text import Text + +from tests.utilities.test_app import AppTest +from textual.app import ComposeResult +from textual.css.types import EdgeType +from textual.geometry import Size +from textual.widget import Widget +from textual.widgets import Placeholder + +pytestmark = pytest.mark.integration_test + +# Let's allow ourselves some abbreviated names for those tests, +# in order to make the test cases a bit easier to read :-) +SCREEN_W = 100 # width of our Screens +SCREEN_H = 8 # height of our Screens +SCREEN_SIZE = Size(SCREEN_W, SCREEN_H) +PLACEHOLDERS_DEFAULT_H = 3 # the default height for our Placeholder widgets + +# As per Widget's CSS property, by default Widgets have a horizontal scrollbar of size 1 +# and a vertical scrollbar of size 2: +SCROLL_H_SIZE = 1 +SCROLL_V_SIZE = 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + ( + "placeholders_count", + "root_container_style", + "placeholders_style", + "expected_root_widget_virtual_size", + "expected_placeholders_size", + "expected_placeholders_offset_x", + ), + ( + *[ + [ + 1, + f"border: {invisible_border_edge};", # #root has no visible border + "", # no specific placeholder style + # #root's virtual size=screen size + (SCREEN_W, SCREEN_H), + # placeholders width=same than screen :: height=default height + (SCREEN_W, PLACEHOLDERS_DEFAULT_H), + # placeholders should be at offset 0 + 0, + ] + for invisible_border_edge in ("", "none", "hidden") + ], + [ + 1, + "border: solid white;", # #root has a visible border + "", # no specific placeholder style + # #root's virtual size is smaller because of its borders + (SCREEN_W - 2, SCREEN_H - 2), + # placeholders width=same than screen, minus 2 borders :: height=default height minus 2 borders + (SCREEN_W - 2, PLACEHOLDERS_DEFAULT_H), + # placeholders should be at offset 1 because of #root's border + 1, + ], + [ + 4, + "border: solid white;", # #root has a visible border + "", # no specific placeholder style + # #root's virtual height should be as high as its stacked content + (SCREEN_W - 2 - 1, PLACEHOLDERS_DEFAULT_H * 4), + # placeholders width=same than screen, minus 2 borders, minus scrollbar :: height=default height minus 2 borders + (SCREEN_W - 2 - SCROLL_V_SIZE, PLACEHOLDERS_DEFAULT_H), + # placeholders should be at offset 1 because of #root's border + 1, + ], + [ + 1, + "border: solid white;", # #root has a visible border + "align: center top;", # placeholders are centered horizontally + # #root's virtual size=screen size + (SCREEN_W, SCREEN_H), + # placeholders width=same than screen, minus 2 borders :: height=default height + (SCREEN_W - 2, PLACEHOLDERS_DEFAULT_H), + # placeholders should be at offset 1 because of #root's border + 1, + ], + [ + 4, + "border: solid white;", # #root has a visible border + "align: center top;", # placeholders are centered horizontally + # #root's virtual height should be as high as its stacked content + ( + SCREEN_W - 2 - SCROLL_V_SIZE, + PLACEHOLDERS_DEFAULT_H * 4, + ), + # placeholders width=same than screen, minus 2 borders, minus scrollbar :: height=default height + (SCREEN_W - 2 - SCROLL_V_SIZE, PLACEHOLDERS_DEFAULT_H), + # placeholders should be at offset 1 because of #root's border + 1, + ], + ), +) +async def test_composition_of_vertical_container_with_children( + placeholders_count: int, + root_container_style: str, + placeholders_style: str, + expected_placeholders_size: tuple[int, int], + expected_root_widget_virtual_size: tuple[int, int], + expected_placeholders_offset_x: int, +): + class VerticalContainer(Widget): + DEFAULT_CSS = ( + """ + VerticalContainer { + layout: vertical; + overflow: hidden auto; + ${root_container_style} + } + + VerticalContainer Placeholder { + height: ${placeholders_height}; + ${placeholders_style} + } + """.replace( + "${root_container_style}", root_container_style + ) + .replace("${placeholders_height}", str(PLACEHOLDERS_DEFAULT_H)) + .replace("${placeholders_style}", placeholders_style) + ) + + class MyTestApp(AppTest): + def compose(self) -> ComposeResult: + placeholders = [ + Placeholder(id=f"placeholder_{i}", name=f"Placeholder #{i}") + for i in range(placeholders_count) + ] + + yield VerticalContainer(*placeholders, id="root") + + app = MyTestApp(size=SCREEN_SIZE, test_name="compositor") + + expected_screen_size = SCREEN_SIZE + + async with app.in_running_state(): + # root widget checks: + root_widget = cast(Widget, app.get_child("root")) + assert root_widget.outer_size == expected_screen_size + root_widget_region = app.screen.find_widget(root_widget).region + assert root_widget_region == ( + 0, + 0, + expected_screen_size.width, + expected_screen_size.height, + ) + + app_placeholders = cast(List[Widget], app.query("Placeholder")) + assert len(app_placeholders) == placeholders_count + + # placeholder widgets checks: + for placeholder in app_placeholders: + assert placeholder.outer_size == expected_placeholders_size + assert placeholder.styles.offset.x.value == 0.0 + assert app.screen.get_offset(placeholder).x == expected_placeholders_offset_x + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "edge_type,expected_box_inner_size,expected_box_size,expected_top_left_edge_color,expects_visible_char_at_top_left_edge", + ( + # These first 3 types of border edge types are synonyms, and display no borders: + ["", Size(SCREEN_W, 1), Size(SCREEN_W, 1), "black", False], + ["none", Size(SCREEN_W, 1), Size(SCREEN_W, 1), "black", False], + ["hidden", Size(SCREEN_W, 1), Size(SCREEN_W, 1), "black", False], + # Let's transition to "blank": we still see no visible border, but the size is increased + # as the gutter space is reserved the same way it would be with a border: + ["blank", Size(SCREEN_W - 2, 1), Size(SCREEN_W, 3), "#ffffff", False], + # And now for the "normally visible" border edge types: + # --> we see a visible border, and the size is increased: + *[ + [edge_style, Size(SCREEN_W - 2, 1), Size(SCREEN_W, 3), "#ffffff", True] + for edge_style in [ + "round", + "solid", + "double", + "dashed", + "heavy", + "inner", + "outer", + "hkey", + "vkey", + ] + ], + ), +) +async def test_border_edge_types_impact_on_widget_size( + edge_type: EdgeType, + expected_box_inner_size: Size, + expected_box_size: Size, + expected_top_left_edge_color: str, + expects_visible_char_at_top_left_edge: bool, +): + class BorderTarget(Widget): + def render(self) -> RenderableType: + return Text("border target", style="black on yellow", justify="center") + + border_target = BorderTarget() + border_target.styles.height = "auto" + border_target.styles.border = (edge_type, "white") + + class MyTestApp(AppTest): + def compose(self) -> ComposeResult: + yield border_target + + app = MyTestApp(size=SCREEN_SIZE, test_name="border_edge_types") + + await app.boot_and_shutdown() + + box_inner_size = Size( + border_target.content_region.width, + border_target.content_region.height, + ) + assert box_inner_size == expected_box_inner_size + + assert border_target.outer_size == expected_box_size + + top_left_edge_style = app.screen.get_style_at(0, 0) + top_left_edge_color = top_left_edge_style.color.name + assert top_left_edge_color.upper() == expected_top_left_edge_color.upper() + + top_left_edge_char = app.get_char_at(0, 0) + top_left_edge_char_is_a_visible_one = top_left_edge_char != " " + assert top_left_edge_char_is_a_visible_one == expects_visible_char_at_top_left_edge + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "large_widget_size,container_style,expected_large_widget_visible_region_size", + ( + # In these tests we're going to insert a "large widget" + # into a container with size (20,20). + # ---------------- let's start! + # no overflow/scrollbar instructions: no scrollbars + [Size(30, 30), "color: red", Size(20, 20)], + # explicit hiding of the overflow: no scrollbars either + [Size(30, 30), "overflow: hidden", Size(20, 20)], + # scrollbar for both directions + [ + Size(30, 30), + "overflow: auto", + Size( + 20 - SCROLL_V_SIZE, + 20 - SCROLL_H_SIZE, + ), + ], + # horizontal scrollbar + [Size(30, 30), "overflow-x: auto", Size(20, 20 - SCROLL_H_SIZE)], + # vertical scrollbar + [Size(30, 30), "overflow-y: auto", Size(20 - SCROLL_V_SIZE, 20)], + # scrollbar for both directions, custom scrollbar size + [Size(30, 30), ("overflow: auto", "scrollbar-size: 3 5"), Size(20 - 5, 20 - 3)], + # scrollbar for both directions, custom vertical scrollbar size + [ + Size(30, 30), + ("overflow: auto", "scrollbar-size-vertical: 3"), + Size(20 - 3, 20 - SCROLL_H_SIZE), + ], + # scrollbar for both directions, custom horizontal scrollbar size + [ + Size(30, 30), + ("overflow: auto", "scrollbar-size-horizontal: 3"), + Size(20 - SCROLL_V_SIZE, 20 - 3), + ], + # scrollbar needed only horizontally, custom scrollbar size + [ + Size(30, 20), + ("overflow: auto", "scrollbar-size: 3 3"), + Size(20, 20 - 3), + ], + ), +) +async def test_scrollbar_size_impact_on_the_layout( + large_widget_size: Size, + container_style: str | Sequence[str], + expected_large_widget_visible_region_size: Size, +): + class LargeWidget(Widget): + def on_mount(self): + self.styles.width = large_widget_size[0] + self.styles.height = large_widget_size[1] + + container_style_rules = ( + [container_style] if isinstance(container_style, str) else container_style + ) + + class LargeWidgetContainer(Widget): + # TODO: Once textual#581 ("Default versus User CSS") is solved the following CSS should just use the + # "LargeWidgetContainer" selector, without having to use a more specific one to be able to override Widget's CSS: + DEFAULT_CSS = """ + #large-widget-container { + width: 20; + height: 20; + ${container_style}; + } + """.replace( + "${container_style}", + ";\n".join(container_style_rules), + ) + + large_widget = LargeWidget() + large_widget.expand = False + container = LargeWidgetContainer(large_widget, id="large-widget-container") + + class MyTestApp(AppTest): + def compose(self) -> ComposeResult: + yield container + + app = MyTestApp(size=Size(40, 40), test_name="scrollbar_size_impact_on_the_layout") + + await app.boot_and_shutdown() + + compositor = app.screen._compositor + widgets_map = compositor.map + large_widget_visible_region_size = widgets_map[large_widget].visible_region.size + assert large_widget_visible_region_size == expected_large_widget_visible_region_size diff --git a/testbed/Textualize__textual/tests/test_integration_scrolling.py b/testbed/Textualize__textual/tests/test_integration_scrolling.py new file mode 100644 index 0000000000000000000000000000000000000000..8c4175c62feed5a651775aed0b6c04c2f896d01f --- /dev/null +++ b/testbed/Textualize__textual/tests/test_integration_scrolling.py @@ -0,0 +1,115 @@ +from __future__ import annotations +from typing import Sequence, cast + +import pytest + +from tests.utilities.test_app import AppTest +from textual.app import ComposeResult +from textual.geometry import Size +from textual.widget import Widget +from textual.widgets import Placeholder + +pytestmark = pytest.mark.integration_test + +SCREEN_SIZE = Size(100, 30) + + +@pytest.mark.skip("Needs a rethink") +@pytest.mark.asyncio +@pytest.mark.parametrize( + ( + "screen_size", + "placeholders_count", + "scroll_to_placeholder_id", + "scroll_to_animate", + "waiting_duration", + "last_screen_expected_placeholder_ids", + ), + ( + [SCREEN_SIZE, 10, None, None, 0.01, (0, 1, 2, 3, 4)], + [SCREEN_SIZE, 10, "placeholder_3", False, 0.01, (0, 1, 2, 3, 4)], + [SCREEN_SIZE, 10, "placeholder_5", False, 0.01, (1, 2, 3, 4, 5)], + [SCREEN_SIZE, 10, "placeholder_7", False, 0.01, (3, 4, 5, 6, 7)], + [SCREEN_SIZE, 10, "placeholder_9", False, 0.01, (5, 6, 7, 8, 9)], + # N.B. Scroll duration is hard-coded to 0.2 in the `scroll_to_widget` method atm + # Waiting for this duration should allow us to see the scroll finished: + [SCREEN_SIZE, 10, "placeholder_9", True, 0.21, (5, 6, 7, 8, 9)], + # After having waited for approximately half of the scrolling duration, we should + # see the middle Placeholders as we're scrolling towards the last of them. + [SCREEN_SIZE, 10, "placeholder_9", True, 0.1, (4, 5, 6, 7, 8)], + ), +) +async def test_scroll_to_widget( + screen_size: Size, + placeholders_count: int, + scroll_to_animate: bool | None, + scroll_to_placeholder_id: str | None, + waiting_duration: float | None, + last_screen_expected_placeholder_ids: Sequence[int], +): + class VerticalContainer(Widget): + DEFAULT_CSS = """ + VerticalContainer { + layout: vertical; + overflow: hidden auto; + } + VerticalContainer Placeholder { + margin: 1 0; + height: 5; + } + """ + + class MyTestApp(AppTest): + DEFAULT_CSS = """ + Placeholder { + height: 5; /* minimal height to see the name of a Placeholder */ + } + """ + + def compose(self) -> ComposeResult: + placeholders = [ + Placeholder(id=f"placeholder_{i}", name=f"Placeholder #{i}") + for i in range(placeholders_count) + ] + + yield VerticalContainer(*placeholders, id="root") + + app = MyTestApp(size=screen_size, test_name="scroll_to_widget") + + async with app.in_running_state(waiting_duration_after_yield=waiting_duration or 0): + if scroll_to_placeholder_id: + target_widget_container = cast(Widget, app.query("#root").first()) + target_widget = cast( + Widget, app.query(f"#{scroll_to_placeholder_id}").first() + ) + target_widget_container.scroll_to_widget( + target_widget, animate=scroll_to_animate + ) + + last_display_capture = app.last_display_capture + + placeholders_visibility_by_id = { + id_: f"placeholder_{id_}" in last_display_capture + for id_ in range(placeholders_count) + } + print(placeholders_visibility_by_id) + # Let's start by checking placeholders that should be visible: + for placeholder_id in last_screen_expected_placeholder_ids: + assert placeholders_visibility_by_id[placeholder_id] is True, ( + f"Placeholder '{placeholder_id}' should be visible but isn't" + f" :: placeholders_visibility_by_id={placeholders_visibility_by_id}" + ) + + # Ok, now for placeholders that should *not* be visible: + # We're simply going to check that all the placeholders that are not in + # `last_screen_expected_placeholder_ids` are not on the screen: + last_screen_expected_out_of_viewport_placeholder_ids = sorted( + tuple( + set(range(placeholders_count)) - set(last_screen_expected_placeholder_ids) + ) + ) + for placeholder_id in last_screen_expected_out_of_viewport_placeholder_ids: + assert placeholders_visibility_by_id[placeholder_id] is False, ( + f"Placeholder '{placeholder_id}' should not be visible but is" + f" :: placeholders_visibility_by_id={placeholders_visibility_by_id}" + ) diff --git a/testbed/Textualize__textual/tests/test_layout_resolve.py b/testbed/Textualize__textual/tests/test_layout_resolve.py new file mode 100644 index 0000000000000000000000000000000000000000..77ba2643ef77b3ac9d1545a179b548301e307b4a --- /dev/null +++ b/testbed/Textualize__textual/tests/test_layout_resolve.py @@ -0,0 +1,100 @@ +from __future__ import annotations + +from typing import NamedTuple + +import pytest +from textual._layout_resolve import layout_resolve + + +class Edge(NamedTuple): + size: int | None = None + fraction: int = 1 + min_size: int = 1 + + +def test_empty(): + assert layout_resolve(10, []) == [] + + +def test_total_zero(): + assert layout_resolve(0, [Edge(10)]) == [10] + + +def test_single(): + # One edge fixed size + assert layout_resolve(100, [Edge(10)]) == [10] + # One edge fraction of 1 + assert layout_resolve(100, [Edge(None, 1)]) == [100] + # One edge fraction 3 + assert layout_resolve(100, [Edge(None, 2)]) == [100] + # One edge, fraction1, min size 20 + assert layout_resolve(100, [Edge(None, 1, 20)]) == [100] + # One edge fraction 1, min size 120 + assert layout_resolve(100, [Edge(None, 1, 120)]) == [120] + + +def test_two(): + # Two edges fixed size + assert layout_resolve(100, [Edge(10), Edge(20)]) == [10, 20] + # Two edges, fixed size of one exceeds total + assert layout_resolve(100, [Edge(120), Edge(None, 1)]) == [120, 1] + # Two edges, fraction 1 each + assert layout_resolve(100, [Edge(None, 1), Edge(None, 1)]) == [50, 50] + # Two edges, one with fraction 2, one with fraction 1 + # Note first value is rounded down, second is rounded up + assert layout_resolve(100, [Edge(None, 2), Edge(None, 1)]) == [66, 34] + # Two edges, both with fraction 2 + assert layout_resolve(100, [Edge(None, 2), Edge(None, 2)]) == [50, 50] + # Two edges, one with fraction 3, one with fraction 1 + assert layout_resolve(100, [Edge(None, 3), Edge(None, 1)]) == [75, 25] + # Two edges, one with fraction 3, one with fraction 1, second with min size of 30 + assert layout_resolve(100, [Edge(None, 3), Edge(None, 1, 30)]) == [70, 30] + # Two edges, one with fraction 1 and min size 30, one with fraction 3 + assert layout_resolve(100, [Edge(None, 1, 30), Edge(None, 3)]) == [30, 70] + + +@pytest.mark.parametrize( + "size, edges, result", + [ + (10, [Edge(8), Edge(None, 0, 2), Edge(4)], [8, 2, 4]), + (10, [Edge(None, 1), Edge(None, 1), Edge(None, 1)], [3, 3, 4]), + (10, [Edge(5), Edge(None, 1), Edge(None, 1)], [5, 2, 3]), + (10, [Edge(None, 2), Edge(None, 1), Edge(None, 1)], [5, 2, 3]), + (10, [Edge(None, 2), Edge(3), Edge(None, 1)], [4, 3, 3]), + ( + 10, + [Edge(None, 2), Edge(None, 1), Edge(None, 1), Edge(None, 1)], + [4, 2, 2, 2], + ), + ( + 10, + [Edge(None, 4), Edge(None, 1), Edge(None, 1), Edge(None, 1)], + [5, 2, 1, 2], + ), + (2, [Edge(None, 1), Edge(None, 1), Edge(None, 1)], [1, 1, 1]), + ( + 2, + [ + Edge(None, 1, min_size=5), + Edge(None, 1, min_size=4), + Edge(None, 1, min_size=3), + ], + [5, 4, 3], + ), + ( + 18, + [ + Edge(None, 1, min_size=1), + Edge(3), + Edge(None, 1, min_size=1), + Edge(4), + Edge(None, 1, min_size=1), + Edge(5), + Edge(None, 1, min_size=1), + ], + [1, 3, 2, 4, 1, 5, 2], + ), + ], +) +def test_multiple(size, edges, result): + assert layout_resolve(size, edges) == result diff --git a/testbed/Textualize__textual/tests/test_loop.py b/testbed/Textualize__textual/tests/test_loop.py new file mode 100644 index 0000000000000000000000000000000000000000..c235f23a5dcf6effd44e957b2be104fcbb07c318 --- /dev/null +++ b/testbed/Textualize__textual/tests/test_loop.py @@ -0,0 +1,28 @@ +from textual._loop import loop_first, loop_last, loop_first_last + + +def test_loop_first(): + assert list(loop_first([])) == [] + iterable = loop_first(["apples", "oranges", "pears", "lemons"]) + assert next(iterable) == (True, "apples") + assert next(iterable) == (False, "oranges") + assert next(iterable) == (False, "pears") + assert next(iterable) == (False, "lemons") + + +def test_loop_last(): + assert list(loop_last([])) == [] + iterable = loop_last(["apples", "oranges", "pears", "lemons"]) + assert next(iterable) == (False, "apples") + assert next(iterable) == (False, "oranges") + assert next(iterable) == (False, "pears") + assert next(iterable) == (True, "lemons") + + +def test_loop_first_last(): + assert list(loop_first_last([])) == [] + iterable = loop_first_last(["apples", "oranges", "pears", "lemons"]) + assert next(iterable) == (True, False, "apples") + assert next(iterable) == (False, False, "oranges") + assert next(iterable) == (False, False, "pears") + assert next(iterable) == (False, True, "lemons") diff --git a/testbed/Textualize__textual/tests/test_parser.py b/testbed/Textualize__textual/tests/test_parser.py new file mode 100644 index 0000000000000000000000000000000000000000..f48da58b103a507046cdfbaf909e1bff05ea0a20 --- /dev/null +++ b/testbed/Textualize__textual/tests/test_parser.py @@ -0,0 +1,53 @@ +from textual._parser import Parser + + +def test_read1(): + class TestParser(Parser[str]): + """A simple parser that reads a byte at a time from a stream.""" + + def parse(self, on_token): + while True: + data = yield self.read1() + if not data: + break + on_token(data) + + test_parser = TestParser() + test_data = "Where there is a Will there is a way!" + + for size in range(1, len(test_data) + 1): + # Feed the parser in pieces, first 1 character at a time, then 2, etc + data = [] + for offset in range(0, len(test_data), size): + for chunk in test_parser.feed(test_data[offset : offset + size]): + data.append(chunk) + # Check we have received all the data in characters, no matter the fee dsize + assert len(data) == len(test_data) + assert "".join(data) == test_data + + +def test_read(): + class TestParser(Parser[str]): + """A parser that reads chunks of a given size from the stream.""" + + def __init__(self, size): + self.size = size + super().__init__() + + def parse(self, on_token): + while True: + data = yield self.read1() + if not data: + break + on_token(data) + + test_data = "Where there is a Will there is a way!" + + for read_size in range(1, len(test_data) + 1): + for size in range(1, len(test_data) + 1): + test_parser = TestParser(read_size) + data = [] + for offset in range(0, len(test_data), size): + for chunk in test_parser.feed(test_data[offset : offset + size]): + data.append(chunk) + assert "".join(data) == test_data diff --git a/testbed/Textualize__textual/tests/test_partition.py b/testbed/Textualize__textual/tests/test_partition.py new file mode 100644 index 0000000000000000000000000000000000000000..de5147058e2044d1fd6e585611d58ca2786c9d41 --- /dev/null +++ b/testbed/Textualize__textual/tests/test_partition.py @@ -0,0 +1,27 @@ +from textual._partition import partition + + +def test_partition(): + def is_odd(value: int) -> bool: + return bool(value % 2) + + def is_greater_than_five(value: int) -> bool: + return value > 5 + + assert partition(is_odd, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) == ( + [2, 4, 6, 8, 10], + [1, 3, 5, 7, 9], + ) + + assert partition(is_odd, [1, 2]) == ([2], [1]) + assert partition(is_odd, [1]) == ([], [1]) + assert partition(is_odd, []) == ([], []) + + assert partition(is_greater_than_five, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) == ( + [1, 2, 3, 4, 5], + [6, 7, 8, 9, 10], + ) + + assert partition(is_greater_than_five, [6, 7, 8, 9, 10]) == ([], [6, 7, 8, 9, 10]) + + assert partition(is_greater_than_five, [1, 2, 3]) == ([1, 2, 3], []) diff --git a/testbed/Textualize__textual/tests/test_query.py b/testbed/Textualize__textual/tests/test_query.py new file mode 100644 index 0000000000000000000000000000000000000000..be610804658a4715d9233f07c7a8e70c6427f32a --- /dev/null +++ b/testbed/Textualize__textual/tests/test_query.py @@ -0,0 +1,80 @@ +from textual.widget import Widget + + +def test_query(): + class View(Widget): + pass + + class App(Widget): + pass + + app = App() + main_view = View(id="main") + help_view = View(id="help") + app._add_child(main_view) + app._add_child(help_view) + + widget1 = Widget(id="widget1") + widget2 = Widget(id="widget2") + sidebar = Widget(id="sidebar") + sidebar.add_class("float") + + helpbar = Widget(id="helpbar") + helpbar.add_class("float") + + main_view._add_child(widget1) + main_view._add_child(widget2) + main_view._add_child(sidebar) + + sub_view = View(id="sub") + sub_view.add_class("-subview") + main_view._add_child(sub_view) + + tooltip = Widget(id="tooltip") + tooltip.add_class("float", "transient") + sub_view._add_child(tooltip) + + help = Widget(id="markdown") + help_view._add_child(help) + help_view._add_child(helpbar) + + # repeat tests to account for caching + for repeat in range(3): + assert list(app.query("Frob")) == [] + assert list(app.query(".frob")) == [] + assert list(app.query("#frob")) == [] + + assert list(app.query("App")) == [app] + assert list(app.query("#main")) == [main_view] + assert list(app.query("View#main")) == [main_view] + assert list(app.query("#widget1")) == [widget1] + assert list(app.query("#widget2")) == [widget2] + + assert list(app.query("Widget.float")) == [sidebar, tooltip, helpbar] + assert list(app.query("Widget.float").results(Widget)) == [ + sidebar, + tooltip, + helpbar, + ] + assert list(app.query("Widget.float").results(View)) == [] + + assert list(app.query("Widget.float.transient")) == [tooltip] + + assert list(app.query("App > View")) == [main_view, help_view] + assert list(app.query("App > View#help")) == [help_view] + assert list(app.query("App > View#main .float ")) == [sidebar, tooltip] + assert list(app.query("View > View")) == [sub_view] + + assert list(app.query("#help *")) == [help, helpbar] + assert list(app.query("#main *")) == [ + widget1, + widget2, + sidebar, + sub_view, + tooltip, + ] + + assert list(app.query("App,View")) == [app, main_view, sub_view, help_view] + assert list(app.query("#widget1, #widget2")) == [widget1, widget2] + assert list(app.query("#widget1 , #widget2")) == [widget1, widget2] + assert list(app.query("#widget1, #widget2, App")) == [app, widget1, widget2] diff --git a/testbed/Textualize__textual/tests/test_resolve.py b/testbed/Textualize__textual/tests/test_resolve.py new file mode 100644 index 0000000000000000000000000000000000000000..4fac5ded2472990fc16d035a66dcad092ff056f6 --- /dev/null +++ b/testbed/Textualize__textual/tests/test_resolve.py @@ -0,0 +1,58 @@ +import pytest + +from textual.geometry import Size +from textual.css.scalar import Scalar +from textual._resolve import resolve + + +def test_resolve_empty(): + assert resolve([], 10, 1, Size(20, 10), Size(80, 24)) == [] + + +@pytest.mark.parametrize( + "scalars,total,gutter,result", + [ + (["10"], 100, 0, [(0, 10)]), + ( + ["10", "20"], + 100, + 0, + [(0, 10), (10, 20)], + ), + ( + ["10", "20"], + 100, + 1, + [(0, 10), (11, 20)], + ), + ( + ["10", "1fr"], + 100, + 1, + [(0, 10), (11, 89)], + ), + ( + ["1fr", "1fr"], + 100, + 0, + [(0, 50), (50, 50)], + ), + ( + ["3", "1fr", "1fr", "1"], + 100, + 1, + [(0, 3), (4, 46), (51, 47), (99, 1)], + ), + ], +) +def test_resolve(scalars, total, gutter, result): + assert ( + resolve( + [Scalar.parse(scalar) for scalar in scalars], + total, + gutter, + Size(40, 20), + Size(80, 24), + ) + == result + ) diff --git a/testbed/Textualize__textual/tests/test_screens.py b/testbed/Textualize__textual/tests/test_screens.py new file mode 100644 index 0000000000000000000000000000000000000000..9a9365aa2ff1fecde84e8119ae4e3b1b9d1b95b3 --- /dev/null +++ b/testbed/Textualize__textual/tests/test_screens.py @@ -0,0 +1,93 @@ +import sys + +import pytest + +from textual.app import App, ScreenStackError +from textual.screen import Screen + + +skip_py310 = pytest.mark.skipif( + sys.version_info.minor == 10 and sys.version_info.major == 3, + reason="segfault on py3.10", +) + + +@skip_py310 +@pytest.mark.asyncio +async def test_screens(): + + app = App() + app._set_active() + + with pytest.raises(ScreenStackError): + app.screen + + assert not app._installed_screens + + screen1 = Screen(name="screen1") + screen2 = Screen(name="screen2") + screen3 = Screen(name="screen3") + + # installs screens + app.install_screen(screen1, "screen1") + app.install_screen(screen2, "screen2") + + # Check they are installed + assert app.is_screen_installed("screen1") + assert app.is_screen_installed("screen2") + + assert app.get_screen("screen1") is screen1 + with pytest.raises(KeyError): + app.get_screen("foo") + + # Check screen3 is not installed + assert not app.is_screen_installed("screen3") + + # Installs screen3 + app.install_screen(screen3, "screen3") + # Confirm installed + assert app.is_screen_installed("screen3") + + # Check screen stack is empty + assert app.screen_stack == [] + # Push a screen + app.push_screen("screen1") + # Check it is on the stack + assert app.screen_stack == [screen1] + # Check it is current + assert app.screen is screen1 + + # Switch to another screen + app.switch_screen("screen2") + # Check it has changed the stack and that it is current + assert app.screen_stack == [screen2] + assert app.screen is screen2 + + # Push another screen + app.push_screen("screen3") + assert app.screen_stack == [screen2, screen3] + assert app.screen is screen3 + + # Pop a screen + assert app.pop_screen() is screen3 + assert app.screen is screen2 + assert app.screen_stack == [screen2] + + # Uninstall screens + app.uninstall_screen(screen1) + assert not app.is_screen_installed(screen1) + app.uninstall_screen("screen3") + assert not app.is_screen_installed(screen1) + + # Check we can't uninstall a screen on the stack + with pytest.raises(ScreenStackError): + app.uninstall_screen(screen2) + + # Check we can't pop last screen + with pytest.raises(ScreenStackError): + app.pop_screen() + + screen1.remove() + screen2.remove() + screen3.remove() + await app.shutdown() diff --git a/testbed/Textualize__textual/tests/test_segment_tools.py b/testbed/Textualize__textual/tests/test_segment_tools.py new file mode 100644 index 0000000000000000000000000000000000000000..770f33e23992cdff2ac139ae71238a3b4b144d11 --- /dev/null +++ b/testbed/Textualize__textual/tests/test_segment_tools.py @@ -0,0 +1,113 @@ +from rich.segment import Segment +from rich.style import Style + + +from textual._segment_tools import line_crop, line_trim, line_pad + + +def test_line_crop(): + bold = Style(bold=True) + italic = Style(italic=True) + segments = [ + Segment("Hello", bold), + Segment(" World!", italic), + ] + total = sum(segment.cell_length for segment in segments) + + assert line_crop(segments, 1, 2, total) == [Segment("e", bold)] + assert line_crop(segments, 4, 20, total) == [ + Segment("o", bold), + Segment(" World!", italic), + ] + + +def test_line_crop_emoji(): + bold = Style(bold=True) + italic = Style(italic=True) + segments = [ + Segment("Hello", bold), + Segment("๐Ÿ’ฉ๐Ÿ’ฉ๐Ÿ’ฉ", italic), + ] + total = sum(segment.cell_length for segment in segments) + assert line_crop(segments, 8, 11, total) == [Segment(" ๐Ÿ’ฉ", italic)] + assert line_crop(segments, 9, 11, total) == [Segment("๐Ÿ’ฉ", italic)] + + +def test_line_crop_edge(): + segments = [Segment("foo"), Segment("bar"), Segment("baz")] + total = sum(segment.cell_length for segment in segments) + + assert line_crop(segments, 2, 9, total) == [ + Segment("o"), + Segment("bar"), + Segment("baz"), + ] + assert line_crop(segments, 3, 9, total) == [Segment("bar"), Segment("baz")] + assert line_crop(segments, 4, 9, total) == [Segment("ar"), Segment("baz")] + assert line_crop(segments, 4, 8, total) == [Segment("ar"), Segment("ba")] + + +def test_line_crop_edge_2(): + segments = [ + Segment("โ•ญโ”€"), + Segment( + "โ”€โ”€โ”€โ”€โ”€โ”€ Placeholder โ”€โ”€โ”€โ”€โ”€โ”€โ”€", + ), + Segment( + "โ”€โ•ฎ", + ), + ] + total = sum(segment.cell_length for segment in segments) + result = line_crop(segments, 30, 60, total) + expected = [] + print(repr(result)) + assert result == expected + + +def test_line_trim(): + segments = [Segment("foo")] + + assert line_trim(segments, False, False) == segments + assert line_trim(segments, True, False) == [Segment("oo")] + assert line_trim(segments, False, True) == [Segment("fo")] + assert line_trim(segments, True, True) == [Segment("o")] + + fob_segments = [Segment("f"), Segment("o"), Segment("b")] + + assert line_trim(fob_segments, True, False) == [ + Segment("o"), + Segment("b"), + ] + + assert line_trim(fob_segments, False, True) == [ + Segment("f"), + Segment("o"), + ] + + assert line_trim(fob_segments, True, True) == [ + Segment("o"), + ] + + assert line_trim([], True, True) == [] + + +def test_line_pad(): + segments = [Segment("foo"), Segment("bar")] + style = Style.parse("red") + assert line_pad(segments, 2, 3, style) == [ + Segment(" ", style), + *segments, + Segment(" ", style), + ] + + assert line_pad(segments, 0, 3, style) == [ + *segments, + Segment(" ", style), + ] + + assert line_pad(segments, 2, 0, style) == [ + Segment(" ", style), + *segments, + ] + + assert line_pad(segments, 0, 0, style) == segments diff --git a/testbed/Textualize__textual/tests/test_styles_cache.py b/testbed/Textualize__textual/tests/test_styles_cache.py new file mode 100644 index 0000000000000000000000000000000000000000..d30c1cebfb14cf291998e58fa7d80e5c088be65d --- /dev/null +++ b/testbed/Textualize__textual/tests/test_styles_cache.py @@ -0,0 +1,272 @@ +from __future__ import annotations + +from rich.segment import Segment +from rich.style import Style + +from textual.color import Color +from textual.geometry import Region, Size +from textual.css.styles import Styles +from textual._styles_cache import StylesCache +from textual._types import Lines + + +def _extract_content(lines: Lines): + """Extract the text content from lines.""" + content = ["".join(segment.text for segment in line) for line in lines] + return content + + +def test_set_dirty(): + cache = StylesCache() + cache.set_dirty(Region(3, 4, 10, 2)) + assert not cache.is_dirty(3) + assert cache.is_dirty(4) + assert cache.is_dirty(5) + assert not cache.is_dirty(6) + + +def test_no_styles(): + """Test that empty style returns the content un-altered""" + content = [ + [Segment("foo")], + [Segment("bar")], + [Segment("baz")], + ] + styles = Styles() + cache = StylesCache() + lines = cache.render( + styles, + Size(3, 3), + Color.parse("blue"), + Color.parse("green"), + content.__getitem__, + content_size=Size(3, 3), + ) + style = Style.from_color(bgcolor=Color.parse("green").rich_color) + expected = [ + [Segment("foo", style)], + [Segment("bar", style)], + [Segment("baz", style)], + ] + assert lines == expected + + +def test_border(): + content = [ + [Segment("foo")], + [Segment("bar")], + [Segment("baz")], + ] + styles = Styles() + styles.border = ("heavy", "white") + cache = StylesCache() + lines = cache.render( + styles, + Size(5, 5), + Color.parse("blue"), + Color.parse("green"), + content.__getitem__, + content_size=Size(3, 3), + ) + + text_content = _extract_content(lines) + + expected_text = [ + "โ”โ”โ”โ”โ”“", + "โ”ƒfooโ”ƒ", + "โ”ƒbarโ”ƒ", + "โ”ƒbazโ”ƒ", + "โ”—โ”โ”โ”โ”›", + ] + + assert text_content == expected_text + + +def test_padding(): + content = [ + [Segment("foo")], + [Segment("bar")], + [Segment("baz")], + ] + styles = Styles() + styles.padding = 1 + cache = StylesCache() + lines = cache.render( + styles, + Size(5, 5), + Color.parse("blue"), + Color.parse("green"), + content.__getitem__, + content_size=Size(3, 3), + ) + + text_content = _extract_content(lines) + + expected_text = [ + " ", + " foo ", + " bar ", + " baz ", + " ", + ] + + assert text_content == expected_text + + +def test_padding_border(): + content = [ + [Segment("foo")], + [Segment("bar")], + [Segment("baz")], + ] + styles = Styles() + styles.padding = 1 + styles.border = ("heavy", "white") + cache = StylesCache() + lines = cache.render( + styles, + Size(7, 7), + Color.parse("blue"), + Color.parse("green"), + content.__getitem__, + content_size=Size(3, 3), + ) + + text_content = _extract_content(lines) + + expected_text = [ + "โ”โ”โ”โ”โ”โ”โ”“", + "โ”ƒ โ”ƒ", + "โ”ƒ foo โ”ƒ", + "โ”ƒ bar โ”ƒ", + "โ”ƒ baz โ”ƒ", + "โ”ƒ โ”ƒ", + "โ”—โ”โ”โ”โ”โ”โ”›", + ] + + assert text_content == expected_text + + +def test_outline(): + content = [ + [Segment("foo")], + [Segment("bar")], + [Segment("baz")], + ] + styles = Styles() + styles.outline = ("heavy", "white") + cache = StylesCache() + lines = cache.render( + styles, + Size(3, 3), + Color.parse("blue"), + Color.parse("green"), + content.__getitem__, + content_size=Size(3, 3), + ) + + text_content = _extract_content(lines) + expected_text = [ + "โ”โ”โ”“", + "โ”ƒaโ”ƒ", + "โ”—โ”โ”›", + ] + assert text_content == expected_text + + +def test_crop(): + content = [ + [Segment("foo")], + [Segment("bar")], + [Segment("baz")], + ] + styles = Styles() + styles.padding = 1 + styles.border = ("heavy", "white") + cache = StylesCache() + lines = cache.render( + styles, + Size(7, 7), + Color.parse("blue"), + Color.parse("green"), + content.__getitem__, + content_size=Size(3, 3), + crop=Region(2, 2, 3, 3), + ) + text_content = _extract_content(lines) + expected_text = [ + "foo", + "bar", + "baz", + ] + assert text_content == expected_text + + +def test_dirty_cache(): + """Check that we only render content once or if it has been marked as dirty.""" + + content = [ + [Segment("foo")], + [Segment("bar")], + [Segment("baz")], + ] + rendered_lines: list[int] = [] + + def get_content_line(y: int) -> list[Segment]: + rendered_lines.append(y) + return content[y] + + styles = Styles() + styles.padding = 1 + styles.border = ("heavy", "white") + cache = StylesCache() + lines = cache.render( + styles, + Size(7, 7), + Color.parse("blue"), + Color.parse("green"), + get_content_line, + ) + assert rendered_lines == [0, 1, 2] + del rendered_lines[:] + + text_content = _extract_content(lines) + expected_text = [ + "โ”โ”โ”โ”โ”โ”โ”“", + "โ”ƒ โ”ƒ", + "โ”ƒ foo โ”ƒ", + "โ”ƒ bar โ”ƒ", + "โ”ƒ baz โ”ƒ", + "โ”ƒ โ”ƒ", + "โ”—โ”โ”โ”โ”โ”โ”›", + ] + assert text_content == expected_text + + # Re-render styles, check that content was not requested + lines = cache.render( + styles, + Size(7, 7), + Color.parse("blue"), + Color.parse("green"), + get_content_line, + content_size=Size(3, 3), + ) + assert rendered_lines == [] + del rendered_lines[:] + text_content = _extract_content(lines) + assert text_content == expected_text + + # Mark 2 lines as dirty + cache.set_dirty(Region(0, 2, 7, 2)) + + lines = cache.render( + styles, + Size(7, 7), + Color.parse("blue"), + Color.parse("green"), + get_content_line, + content_size=Size(3, 3), + ) + assert rendered_lines == [0, 1] + text_content = _extract_content(lines) + assert text_content == expected_text diff --git a/testbed/Textualize__textual/tests/test_suggestions.py b/testbed/Textualize__textual/tests/test_suggestions.py new file mode 100644 index 0000000000000000000000000000000000000000..8faedcbafe454a6fa648f8ebbbe93be83d7a0c95 --- /dev/null +++ b/testbed/Textualize__textual/tests/test_suggestions.py @@ -0,0 +1,35 @@ +import pytest + +from textual.suggestions import get_suggestion, get_suggestions + + +@pytest.mark.parametrize( + "word, possible_words, expected_result", + ( + ["background", ("background",), "background"], + ["backgroundu", ("background",), "background"], + ["bkgrund", ("background",), "background"], + ["llow", ("background",), None], + ["llow", ("background", "yellow"), "yellow"], + ["yllow", ("background", "yellow", "ellow"), "yellow"], + ), +) +def test_get_suggestion(word, possible_words, expected_result): + assert get_suggestion(word, possible_words) == expected_result + + +@pytest.mark.parametrize( + "word, possible_words, count, expected_result", + ( + ["background", ("background",), 1, ["background"]], + ["backgroundu", ("background",), 1, ["background"]], + ["bkgrund", ("background",), 1, ["background"]], + ["llow", ("background",), 1, []], + ["llow", ("background", "yellow"), 1, ["yellow"]], + ["yllow", ("background", "yellow", "ellow"), 1, ["yellow"]], + ["yllow", ("background", "yellow", "ellow"), 2, ["yellow", "ellow"]], + ["yllow", ("background", "yellow", "red"), 2, ["yellow"]], + ), +) +def test_get_suggestions(word, possible_words, count, expected_result): + assert get_suggestions(word, possible_words, count) == expected_result diff --git a/testbed/Textualize__textual/tests/test_text_backend.py b/testbed/Textualize__textual/tests/test_text_backend.py new file mode 100644 index 0000000000000000000000000000000000000000..bf92967201abf34be62f7439664a379960721fd3 --- /dev/null +++ b/testbed/Textualize__textual/tests/test_text_backend.py @@ -0,0 +1,159 @@ +from textual._text_backend import TextEditorBackend + +CONTENT = "Hello, world!" + + +def test_set_content(): + editor = TextEditorBackend() + editor.set_content(CONTENT) + assert editor.content == CONTENT + + +def test_delete_back_cursor_at_start_is_noop(): + editor = TextEditorBackend(CONTENT) + assert not editor.delete_back() + assert editor == TextEditorBackend(CONTENT, 0) + + +def test_delete_back_cursor_at_end(): + editor = TextEditorBackend(CONTENT) + assert editor.cursor_text_end() + assert editor.delete_back() + assert editor == TextEditorBackend("Hello, world", 12) + + +def test_delete_back_cursor_in_middle(): + editor = TextEditorBackend(CONTENT, 5) + assert editor.delete_back() + assert editor == TextEditorBackend("Hell, world!", 4) + + +def test_delete_forward_cursor_at_start(): + editor = TextEditorBackend(CONTENT) + assert editor.delete_forward() + assert editor.content == "ello, world!" + + +def test_delete_forward_cursor_at_end_is_noop(): + editor = TextEditorBackend(CONTENT) + assert editor.cursor_text_end() + assert not editor.delete_forward() + assert editor == TextEditorBackend(CONTENT, len(CONTENT)) + + +def test_delete_forward_cursor_in_middle(): + editor = TextEditorBackend(CONTENT, 5) + editor.cursor_index = 5 + assert editor.delete_forward() + assert editor == TextEditorBackend("Hello world!", 5) + + +def test_cursor_left_cursor_at_start_is_noop(): + editor = TextEditorBackend(CONTENT) + assert not editor.cursor_left() + assert editor == TextEditorBackend(CONTENT) + + +def test_cursor_left_cursor_in_middle(): + editor = TextEditorBackend(CONTENT, 6) + assert editor.cursor_left() + assert editor == TextEditorBackend(CONTENT, 5) + + +def test_cursor_left_cursor_at_end(): + editor = TextEditorBackend(CONTENT, len(CONTENT)) + assert editor.cursor_left() + assert editor == TextEditorBackend(CONTENT, len(CONTENT) - 1) + + +def test_cursor_right_cursor_at_start(): + editor = TextEditorBackend(CONTENT) + assert editor.cursor_right() + assert editor == TextEditorBackend(CONTENT, 1) + + +def test_cursor_right_cursor_in_middle(): + editor = TextEditorBackend(CONTENT, 5) + assert editor.cursor_right() + assert editor == TextEditorBackend(CONTENT, 6) + + +def test_cursor_right_cursor_at_end_is_noop(): + editor = TextEditorBackend(CONTENT, len(CONTENT)) + editor.cursor_right() + assert editor == TextEditorBackend(CONTENT, len(CONTENT)) + + +def test_query_cursor_left_cursor_at_start_returns_false(): + editor = TextEditorBackend(CONTENT) + assert not editor.query_cursor_left() + + +def test_query_cursor_left_cursor_at_end_returns_true(): + editor = TextEditorBackend(CONTENT, len(CONTENT)) + assert editor.query_cursor_left() + + +def test_query_cursor_left_cursor_in_middle_returns_true(): + editor = TextEditorBackend(CONTENT, 6) + assert editor.query_cursor_left() + + +def test_query_cursor_right_cursor_at_start_returns_true(): + editor = TextEditorBackend(CONTENT) + assert editor.query_cursor_right() + + +def test_query_cursor_right_cursor_in_middle_returns_true(): + editor = TextEditorBackend(CONTENT, 6) + assert editor.query_cursor_right() + + +def test_query_cursor_right_cursor_at_end_returns_false(): + editor = TextEditorBackend(CONTENT, len(CONTENT)) + assert not editor.query_cursor_right() + +def test_cursor_text_start_cursor_already_at_start(): + editor = TextEditorBackend(CONTENT) + assert not editor.cursor_text_start() + assert editor.cursor_index == 0 + +def test_cursor_text_start_cursor_in_middle(): + editor = TextEditorBackend(CONTENT, 6) + assert editor.cursor_text_start() + assert editor.cursor_index == 0 + +def test_cursor_text_end_cursor_already_at_end(): + editor = TextEditorBackend(CONTENT, len(CONTENT)) + assert not editor.cursor_text_end() + assert editor.cursor_index == len(CONTENT) + +def test_cursor_text_end_cursor_in_middle(): + editor = TextEditorBackend(CONTENT, len(CONTENT)) + assert not editor.cursor_text_end() + assert editor.cursor_index == len(CONTENT) + + +def test_insert_at_cursor_cursor_at_start(): + editor = TextEditorBackend(CONTENT) + assert editor.insert("ABC") + assert editor.content == "ABC" + CONTENT + assert editor.cursor_index == len("ABC") + +def test_insert_at_cursor_cursor_in_middle(): + start_cursor_index = 6 + editor = TextEditorBackend(CONTENT, start_cursor_index) + assert editor.insert("ABC") + assert editor.content == "Hello,ABC world!" + assert editor.cursor_index == start_cursor_index + len("ABC") + + +def test_insert_at_cursor_cursor_at_end(): + editor = TextEditorBackend(CONTENT, len(CONTENT)) + assert editor.insert("ABC") + assert editor.content == CONTENT + "ABC" + assert editor.cursor_index == len(editor.content) + +def test_get_range(): + editor = TextEditorBackend(CONTENT) + assert editor.get_range(0, 5) == "Hello" diff --git a/testbed/Textualize__textual/tests/test_widget.py b/testbed/Textualize__textual/tests/test_widget.py new file mode 100644 index 0000000000000000000000000000000000000000..bd06d4c223e777d4a1fadb716292e60942831830 --- /dev/null +++ b/testbed/Textualize__textual/tests/test_widget.py @@ -0,0 +1,67 @@ +import pytest +from rich.style import Style + +from textual.app import App +from textual.css.errors import StyleValueError +from textual.geometry import Size +from textual.widget import Widget + + +@pytest.mark.parametrize( + "set_val, get_val, style_str", + [ + [True, True, "visible"], + [False, False, "hidden"], + ["hidden", False, "hidden"], + ["visible", True, "visible"], + ], +) +def test_widget_set_visible_true(set_val, get_val, style_str): + widget = Widget() + widget.visible = set_val + + assert widget.visible is get_val + assert widget.styles.visibility == style_str + + +def test_widget_set_visible_invalid_string(): + widget = Widget() + + with pytest.raises(StyleValueError): + widget.visible = "nope! no widget for me!" + + assert widget.visible + + +def test_widget_content_width(): + class TextWidget(Widget): + def __init__(self, text: str, id: str) -> None: + self.text = text + super().__init__(id=id) + self.expand = False + self.shrink = True + + def render(self) -> str: + return self.text + + widget1 = TextWidget("foo", id="widget1") + widget2 = TextWidget("foo\nbar", id="widget2") + widget3 = TextWidget("foo\nbar\nbaz", id="widget3") + + app = App() + app._set_active() + + width = widget1.get_content_width(Size(20, 20), Size(80, 24)) + height = widget1.get_content_height(Size(20, 20), Size(80, 24), width) + assert width == 3 + assert height == 1 + + width = widget2.get_content_width(Size(20, 20), Size(80, 24)) + height = widget2.get_content_height(Size(20, 20), Size(80, 24), width) + assert width == 3 + assert height == 2 + + width = widget3.get_content_width(Size(20, 20), Size(80, 24)) + height = widget3.get_content_height(Size(20, 20), Size(80, 24), width) + assert width == 3 + assert height == 3 diff --git a/testbed/Textualize__textual/tests/test_xterm_parser.py b/testbed/Textualize__textual/tests/test_xterm_parser.py new file mode 100644 index 0000000000000000000000000000000000000000..993903a052d5b42c1465b31464de46a713b36cdf --- /dev/null +++ b/testbed/Textualize__textual/tests/test_xterm_parser.py @@ -0,0 +1,307 @@ +import itertools +from unittest import mock + +import pytest + +from textual._xterm_parser import XTermParser +from textual.events import ( + Paste, + Key, + MouseDown, + MouseUp, + MouseMove, + MouseScrollDown, + MouseScrollUp, +) +from textual.messages import TerminalSupportsSynchronizedOutput + + +def chunks(data, size): + if size == 0: + yield data + return + + chunk_start = 0 + chunk_end = size + while True: + yield data[chunk_start:chunk_end] + chunk_start = chunk_end + chunk_end += size + if chunk_end >= len(data): + yield data[chunk_start:chunk_end] + break + + +@pytest.fixture +def parser(): + return XTermParser(sender=mock.sentinel, more_data=lambda: False) + + +@pytest.mark.parametrize("chunk_size", [2, 3, 4, 5, 6]) +def test_varying_parser_chunk_sizes_no_missing_data(parser, chunk_size): + end = "\x1b[8~" + text = "ABCDEFGH" + + data = end + text + events = [] + for chunk in chunks(data, chunk_size): + events.append(parser.feed(chunk)) + + events = list(itertools.chain.from_iterable(list(event) for event in events)) + + assert events[0].key == "end" + assert [event.key for event in events[1:]] == list(text) + + +def test_bracketed_paste(parser): + """When bracketed paste mode is enabled in the terminal emulator and + the user pastes in some text, it will surround the pasted input + with the escape codes "\x1b[200~" and "\x1b[201~". The text between + these codes corresponds to a single `Paste` event in Textual. + """ + pasted_text = "PASTED" + events = list(parser.feed(f"\x1b[200~{pasted_text}\x1b[201~")) + + assert len(events) == 1 + assert isinstance(events[0], Paste) + assert events[0].text == pasted_text + assert events[0].sender == mock.sentinel + + +def test_bracketed_paste_content_contains_escape_codes(parser): + """When performing a bracketed paste, if the pasted content contains + supported ANSI escape sequences, it should not interfere with the paste, + and no escape sequences within the bracketed paste should be converted + into Textual events. + """ + pasted_text = "PAS\x0fTED" + events = list(parser.feed(f"\x1b[200~{pasted_text}\x1b[201~")) + assert len(events) == 1 + assert events[0].text == pasted_text + + +def test_bracketed_paste_amongst_other_codes(parser): + pasted_text = "PASTED" + events = list(parser.feed(f"\x1b[8~\x1b[200~{pasted_text}\x1b[201~\x1b[8~")) + assert len(events) == 3 # Key.End -> Paste -> Key.End + assert events[0].key == "end" + assert events[1].text == pasted_text + assert events[2].key == "end" + + +def test_cant_match_escape_sequence_too_long(parser): + """The sequence did not match, and we hit the maximum sequence search + length threshold, so each character should be issued as a key-press instead. + """ + sequence = "\x1b[123456789123456789123" + events = list(parser.feed(sequence)) + + # Every character in the sequence is converted to a key press + assert len(events) == len(sequence) + assert all(isinstance(event, Key) for event in events) + + # When we backtrack '\x1b' is translated to '^' + assert events[0].key == "circumflex_accent" + + # The rest of the characters correspond to the expected key presses + events = events[1:] + for index, character in enumerate(sequence[1:]): + assert events[index].char == character + + +@pytest.mark.parametrize( + "chunk_size", + [ + pytest.param( + 2, marks=pytest.mark.xfail(reason="Fails when ESC at end of chunk") + ), + 3, + pytest.param( + 4, marks=pytest.mark.xfail(reason="Fails when ESC at end of chunk") + ), + 5, + 6, + ], +) +def test_unknown_sequence_followed_by_known_sequence(parser, chunk_size): + """When we feed the parser an unknown sequence followed by a known + sequence. The characters in the unknown sequence are delivered as keys, + and the known escape sequence that follows is delivered as expected. + """ + unknown_sequence = "\x1b[?" + known_sequence = "\x1b[8~" # key = 'end' + + sequence = unknown_sequence + known_sequence + + events = [] + parser.more_data = lambda: True + for chunk in chunks(sequence, chunk_size): + events.append(parser.feed(chunk)) + + events = list(itertools.chain.from_iterable(list(event) for event in events)) + + assert [event.key for event in events] == [ + "circumflex_accent", + "left_square_bracket", + "question_mark", + "end", + ] + + +def test_simple_key_presses_all_delivered_correct_order(parser): + sequence = "123abc" + events = parser.feed(sequence) + assert "".join(event.key for event in events) == sequence + + +def test_simple_keypress_non_character_key(parser): + sequence = "\x09" + events = list(parser.feed(sequence)) + assert len(events) == 1 + assert events[0].key == "tab" + + +def test_key_presses_and_escape_sequence_mixed(parser): + sequence = "abc\x1b[13~123" + events = list(parser.feed(sequence)) + + assert len(events) == 7 + assert "".join(event.key for event in events) == "abcf3123" + + +def test_single_escape(parser): + """A single \x1b should be interpreted as a single press of the Escape key""" + events = parser.feed("\x1b") + assert [event.key for event in events] == ["escape"] + + +def test_double_escape(parser): + """Windows Terminal writes double ESC when the user presses the Escape key once.""" + events = parser.feed("\x1b\x1b") + assert [event.key for event in events] == ["escape"] + + +@pytest.mark.parametrize( + "sequence, event_type, shift, meta", + [ + # Mouse down, with and without modifiers + ("\x1b[<0;50;25M", MouseDown, False, False), + ("\x1b[<4;50;25M", MouseDown, True, False), + ("\x1b[<8;50;25M", MouseDown, False, True), + # Mouse up, with and without modifiers + ("\x1b[<0;50;25m", MouseUp, False, False), + ("\x1b[<4;50;25m", MouseUp, True, False), + ("\x1b[<8;50;25m", MouseUp, False, True), + ], +) +def test_mouse_click(parser, sequence, event_type, shift, meta): + """ANSI codes for mouse should be converted to Textual events""" + events = list(parser.feed(sequence)) + + assert len(events) == 1 + + event = events[0] + + assert isinstance(event, event_type) + assert event.x == 49 + assert event.y == 24 + assert event.screen_x == 49 + assert event.screen_y == 24 + assert event.meta is meta + assert event.shift is shift + + +@pytest.mark.parametrize( + "sequence, shift, meta, button", + [ + ("\x1b[<32;15;38M", False, False, 1), # Click and drag + ("\x1b[<35;15;38M", False, False, 0), # Basic cursor movement + ("\x1b[<39;15;38M", True, False, 0), # Shift held down + ("\x1b[<43;15;38M", False, True, 0), # Meta held down + ], +) +def test_mouse_move(parser, sequence, shift, meta, button): + events = list(parser.feed(sequence)) + + assert len(events) == 1 + + event = events[0] + + assert isinstance(event, MouseMove) + assert event.x == 14 + assert event.y == 37 + assert event.shift is shift + assert event.meta is meta + assert event.button == button + + +@pytest.mark.parametrize( + "sequence", + [ + "\x1b[<64;18;25M", + "\x1b[<68;18;25M", + "\x1b[<72;18;25M", + ], +) +def test_mouse_scroll_up(parser, sequence): + """Scrolling the mouse with and without modifiers held down. + We don't currently capture modifier keys in scroll events. + """ + events = list(parser.feed(sequence)) + + assert len(events) == 1 + + event = events[0] + + assert isinstance(event, MouseScrollUp) + assert event.x == 17 + assert event.y == 24 + + +@pytest.mark.parametrize( + "sequence", + [ + "\x1b[<65;18;25M", + "\x1b[<69;18;25M", + "\x1b[<73;18;25M", + ], +) +def test_mouse_scroll_down(parser, sequence): + events = list(parser.feed(sequence)) + + assert len(events) == 1 + + event = events[0] + + assert isinstance(event, MouseScrollDown) + assert event.x == 17 + assert event.y == 24 + + +def test_mouse_event_detected_but_info_not_parsed(parser): + # I don't know if this can actually happen in reality, but + # there's a branch in the code that allows for the possibility. + events = list(parser.feed("\x1b[<65;18;20;25M")) + assert len(events) == 0 + + +def test_escape_sequence_resulting_in_multiple_keypresses(parser): + """Some sequences are interpreted as more than 1 keypress""" + events = list(parser.feed("\x1b[2;4~")) + assert len(events) == 2 + assert events[0].key == "escape" + assert events[1].key == "shift+insert" + + +def test_terminal_mode_reporting_synchronized_output_supported(parser): + sequence = "\x1b[?2026;1$y" + events = list(parser.feed(sequence)) + assert len(events) == 1 + assert isinstance(events[0], TerminalSupportsSynchronizedOutput) + assert events[0].sender == mock.sentinel + + +def test_terminal_mode_reporting_synchronized_output_not_supported(parser): + sequence = "\x1b[?2026;0$y" + events = list(parser.feed(sequence)) + assert events == [] diff --git a/testbed/Textualize__textual/tests/utilities/render.py b/testbed/Textualize__textual/tests/utilities/render.py new file mode 100644 index 0000000000000000000000000000000000000000..f1511e53c249113f66db53b75f39c98deec80b29 --- /dev/null +++ b/testbed/Textualize__textual/tests/utilities/render.py @@ -0,0 +1,56 @@ +import asyncio +import io +import re +from typing import Callable + +import pytest +from rich.console import Console, RenderableType + +re_link_ids = re.compile(r"id=[\d\.\-]*?;.*?\x1b") + + +def replace_link_ids(render: str) -> str: + """Link IDs have a random ID and system path which is a problem for + reproducible tests. + + """ + return re_link_ids.sub("id=0;foo\x1b", render) + + +def render(renderable: RenderableType, no_wrap: bool = False) -> str: + console = Console( + width=100, file=io.StringIO(), color_system="truecolor", legacy_windows=False + ) + with console.capture() as capture: + console.print(renderable, no_wrap=no_wrap, end="") + output = replace_link_ids(capture.get()) + return output + + +async def wait_for_predicate( + predicate: Callable[[], bool], + timeout_secs: float = 2, + poll_delay_secs: float = 0.001, +) -> None: + """Wait for the given predicate to become True by evaluating it every `poll_delay_secs` + seconds. Fail the pytest test if the predicate does not become True after `timeout_secs` + seconds. + + Args: + predicate (Callable[[], bool]): The predicate function which will be called repeatedly. + timeout_secs (float): If the predicate doesn't evaluate to True after this number of + seconds, the test will fail. + poll_delay_secs (float): The number of seconds to wait between each call to the + predicate function. + """ + time_taken = 0 + while True: + result = predicate() + if result: + return + await asyncio.sleep(poll_delay_secs) + time_taken += poll_delay_secs + if time_taken > timeout_secs: + pytest.fail( + f"Predicate {predicate} did not return True after {timeout_secs} seconds." + ) diff --git a/testbed/Textualize__textual/tools/gen_easings_tests.ts b/testbed/Textualize__textual/tools/gen_easings_tests.ts new file mode 100644 index 0000000000000000000000000000000000000000..ceb5de02aa2643064045bb70f5105ab26a1537bf --- /dev/null +++ b/testbed/Textualize__textual/tools/gen_easings_tests.ts @@ -0,0 +1,233 @@ +/* + * Easing functions from http://easings.net; + * This script generates the data points used to test the _easing.py functions. + */ + +function easeInSine(x: number): number { + return 1 - cos((x * PI) / 2); +} + +function easeOutSine(x: number): number { + return sin((x * PI) / 2); +} + +function easeInOutSine(x: number): number { + return -(cos(PI * x) - 1) / 2; +} + + +function easeInQuad(x: number): number { + return x * x; +} + +function easeOutQuad(x: number): number { + return 1 - (1 - x) * (1 - x); +} + +function easeInOutQuad(x: number): number { + return x < 0.5 ? 2 * x * x : 1 - pow(-2 * x + 2, 2) / 2; +} + + +function easeInCubic(x: number): number { + return x * x * x; +} + +function easeOutCubic(x: number): number { + return 1 - pow(1 - x, 3); +} + +function easeInOutCubic(x: number): number { + return x < 0.5 ? 4 * x * x * x : 1 - pow(-2 * x + 2, 3) / 2; +} + + +function easeInQuart(x: number): number { + return x * x * x * x; +} + +function easeOutQuart(x: number): number { + return 1 - pow(1 - x, 4); +} + +function easeInOutQuart(x: number): number { + return x < 0.5 ? 8 * x * x * x * x : 1 - pow(-2 * x + 2, 4) / 2; +} + + +function easeInQuint(x: number): number { + return x * x * x * x * x; +} + +function easeOutQuint(x: number): number { + return 1 - pow(1 - x, 5); +} + +function easeInOutQuint(x: number): number { + return x < 0.5 ? 16 * x * x * x * x * x : 1 - pow(-2 * x + 2, 5) / 2; +} + + +function easeInExpo(x: number): number { + return x === 0 ? 0 : pow(2, 10 * x - 10); +} + +function easeOutExpo(x: number): number { + return x === 1 ? 1 : 1 - pow(2, -10 * x); +} + +function easeInOutExpo(x: number): number { + return x === 0 + ? 0 + : x === 1 + ? 1 + : x < 0.5 ? pow(2, 20 * x - 10) / 2 + : (2 - pow(2, -20 * x + 10)) / 2; +} + + +function easeInCirc(x: number): number { + return 1 - sqrt(1 - pow(x, 2)); +} + +function easeOutCirc(x: number): number { + return sqrt(1 - pow(x - 1, 2)); +} + +function easeInOutCirc(x: number): number { + return x < 0.5 + ? (1 - sqrt(1 - pow(2 * x, 2))) / 2 + : (sqrt(1 - pow(-2 * x + 2, 2)) + 1) / 2; +} + + +function easeInBack(x: number): number { + const c1 = 1.70158; + const c3 = c1 + 1; + + return c3 * x * x * x - c1 * x * x; +} + +function easeOutBack(x: number): number { + const c1 = 1.70158; + const c3 = c1 + 1; + + return 1 + c3 * pow(x - 1, 3) + c1 * pow(x - 1, 2); +} + +function easeInOutBack(x: number): number { + const c1 = 1.70158; + const c2 = c1 * 1.525; + + return x < 0.5 + ? (pow(2 * x, 2) * ((c2 + 1) * 2 * x - c2)) / 2 + : (pow(2 * x - 2, 2) * ((c2 + 1) * (x * 2 - 2) + c2) + 2) / 2; +} + + +function easeInElastic(x: number): number { + const c4 = (2 * Math.PI) / 3; + + return x === 0 + ? 0 + : x === 1 + ? 1 + : -pow(2, 10 * x - 10) * sin((x * 10 - 10.75) * c4); +} + +function easeOutElastic(x: number): number { + const c4 = (2 * Math.PI) / 3; + + return x === 0 + ? 0 + : x === 1 + ? 1 + : pow(2, -10 * x) * sin((x * 10 - 0.75) * c4) + 1; +} + +function easeInOutElastic(x: number): number { + const c5 = (2 * Math.PI) / 4.5; + + return x === 0 + ? 0 + : x === 1 + ? 1 + : x < 0.5 + ? -(pow(2, 20 * x - 10) * sin((20 * x - 11.125) * c5)) / 2 + : (pow(2, -20 * x + 10) * sin((20 * x - 11.125) * c5)) / 2 + 1; + +} + + +function easeInBounce(x: number): number { + return 1 - easeOutBounce(1 - x); +} + +function easeOutBounce(x: number): number { + const n1 = 7.5625; + const d1 = 2.75; + + if (x < 1 / d1) { + return n1 * x * x; + } else if (x < 2 / d1) { + return n1 * (x -= 1.5 / d1) * x + 0.75; + } else if (x < 2.5 / d1) { + return n1 * (x -= 2.25 / d1) * x + 0.9375; + } else { + return n1 * (x -= 2.625 / d1) * x + 0.984375; + } +} + +function easeInOutBounce(x: number): number { + return x < 0.5 + ? (1 - easeOutBounce(1 - 2 * x)) / 2 + : (1 + easeOutBounce(2 * x - 1)) / 2; +} + + +const funcs = [ + easeInSine, easeOutSine, easeInOutSine, easeInQuad, easeOutQuad, easeInOutQuad, + easeInCubic, easeOutCubic, easeInOutCubic, easeInQuart, easeOutQuart, easeInOutQuart, + easeInQuint, easeOutQuint, easeInOutQuint, easeInExpo, easeOutExpo, easeInOutExpo, + easeInCirc, easeOutCirc, easeInOutCirc, easeInBack, easeOutBack, easeInOutBack, + easeInElastic, easeOutElastic, easeInOutElastic, easeInBounce, easeOutBounce, easeInOutBounce +]; + +const points = [ + 0.0, + 0.05, + 0.1, + 0.15, + 0.2, + 0.25, + 0.3, + 0.35, + 0.4, + 0.45, + 0.5, + 0.55, + 0.6, + 0.65, + 0.7, + 0.75, + 0.8, + 0.85, + 0.9, + 0.95, + 1.0 +]; + +let PI = Math.PI; +let cos = Math.cos; +let sin = Math.sin; +let pow = Math.pow; +let sqrt = Math.sqrt; + +for (func of funcs) { + console.log(func.name); + let values = []; + for (point of points) { + values.push(func(point)); + } + console.log(values); +} diff --git a/testbed/TileDB-Inc__TileDB-Py/.dockerignore b/testbed/TileDB-Inc__TileDB-Py/.dockerignore new file mode 100644 index 0000000000000000000000000000000000000000..59a12e5fd711750510d32d44598bd59b24aef647 --- /dev/null +++ b/testbed/TileDB-Inc__TileDB-Py/.dockerignore @@ -0,0 +1,4 @@ +build +vv +venv +cibuildwheel_env diff --git a/testbed/TileDB-Inc__TileDB-Py/.github/workflows/build-wheels.yml b/testbed/TileDB-Inc__TileDB-Py/.github/workflows/build-wheels.yml new file mode 100644 index 0000000000000000000000000000000000000000..f67cf374a107e2b1646534f652f2d98ad42a40b2 --- /dev/null +++ b/testbed/TileDB-Inc__TileDB-Py/.github/workflows/build-wheels.yml @@ -0,0 +1,163 @@ +name: Build and test wheels + +on: + workflow_dispatch: + inputs: + version: + description: Version to use are release version + required: true + type: string + test_pypi: + description: Upload packages to test.pypi.org + required: false + type: boolean + default: false + push: + tags: + - "*" + +env: + SETUPTOOLS_SCM_PRETEND_VERSION_FOR_TILEDB: ${{ inputs.version }} + S3_BUCKET: ${{ vars.S3_BUCKET }} + TILEDB_NAMESPACE: ${{ vars.TILEDB_NAMESPACE }} + TILEDB_TOKEN: ${{ secrets.TILEDB_TOKEN }} + +jobs: + build_wheels: + name: Wheel ${{ matrix.buildplat[0] }}-${{ matrix.buildplat[1] }}-${{ matrix.python }} + runs-on: ${{ matrix.buildplat[0] }} + strategy: + matrix: + buildplat: + - [ubuntu-22.04, manylinux_x86_64] + - [macos-13, macosx_x86_64] + - [macos-14, macosx_arm64] + - [windows-2022, win_amd64] + python: ["cp39", "cp310", "cp311", "cp312", "cp313"] + + steps: + - uses: actions/checkout@v4 + + - name: "Brew setup on macOS" # x-ref c8e49ba8f8b9ce + if: ${{ startsWith(matrix.os, 'macos-') == true }} + run: | + set -e pipefail + brew update + brew install automake pkg-config ninja llvm + + - name: Build wheels + uses: pypa/cibuildwheel@v2.21.3 + env: + CIBW_BUILD_VERBOSITY: 3 + CIBW_ENVIRONMENT_PASS_LINUX: SETUPTOOLS_SCM_PRETEND_VERSION_FOR_TILEDB S3_BUCKET TILEDB_TOKEN TILEDB_NAMESPACE + CIBW_ENVIRONMENT_MACOS: > + CC=clang + CXX=clang++ + MACOSX_DEPLOYMENT_TARGET: "11.0" + CIBW_ARCHS: all + CIBW_PRERELEASE_PYTHONS: True + CIBW_BUILD: ${{ matrix.python }}-${{ matrix.buildplat[1] }} + # __init__.py interferes with the tests and is included as local file instead of + # used from wheels. To be honest, tests should not be in the source folder at all. + CIBW_BEFORE_TEST: rm {project}/tiledb/__init__.py + with: + output-dir: wheelhouse + + - uses: actions/upload-artifact@v4 + with: + name: cibw-wheels-${{ matrix.buildplat[0] }}-${{ matrix.buildplat[1] }}-${{ matrix.python }} + path: "./wheelhouse/*.whl" + + build_sdist: + name: Build source distribution + runs-on: ubuntu-latest + outputs: + sdist_name: ${{ steps.get_sdist_name.outputs.sdist_name }} + steps: + - uses: actions/checkout@v4 + + - name: Build sdist + run: pipx run build --sdist + + - name: Get sdist package name + id: get_sdist_name + run: | + echo "sdist_name=$(ls dist/ | head -n 1)" >> "$GITHUB_OUTPUT" + + - uses: actions/upload-artifact@v4 + with: + name: sdist + path: dist/*.tar.gz + + test_sdist: + name: Test source distribution package + needs: [build_sdist] + strategy: + matrix: + os: + - macos-13 + - macos-14 + - windows-2022 + - ubuntu-22.04 + python: ["3.9", "3.10", "3.11", "3.12", "3.13"] + runs-on: ${{ matrix.os }} + steps: + - name: Set up Python ${{ matrix.python }} + uses: actions/setup-python@v5 + with: + python-version: ${{ matrix.python }} + + - name: Download sdist artifact + uses: actions/download-artifact@v4 + with: + name: sdist + path: dist + + - name: Install sdist artifact + run: pip install --verbose dist/${{ needs.build_sdist.outputs.sdist_name }} + + - uses: actions/checkout@v4 + + - name: Install test dependencies + run: pip install pytest hypothesis psutil pyarrow + + - name: Run tests + shell: bash + run: | + PROJECT_CWD=$PWD + rm tiledb/__init__.py + cd .. + pytest -vv --showlocals $PROJECT_CWD + + - name: "Re-run tests without pandas" + run: | + pip uninstall -y pandas + pytest -vv --showlocals $PROJECT_CWD + + upload_pypi: + needs: [build_wheels, test_sdist] + runs-on: ubuntu-latest + environment: pypi + permissions: + id-token: write + outputs: + package_version: ${{ steps.get_package_version.outputs.package_version }} + steps: + - uses: actions/download-artifact@v4 + with: + path: dist + merge-multiple: true + + - id: get_package_version + run: | + echo "package_version=$(ls dist/ | head -n 1 | cut -d - -f 2)" >> "$GITHUB_OUTPUT" + + - name: Upload to test-pypi + if: inputs.test_pypi + uses: pypa/gh-action-pypi-publish@release/v1 + with: + repository-url: https://test.pypi.org/legacy/ + + - name: Upload to pypi + if: startsWith(github.ref, 'refs/tags/') + uses: pypa/gh-action-pypi-publish@release/v1 diff --git a/testbed/TileDB-Inc__TileDB-Py/.github/workflows/ci-tiledb-from-source.yml b/testbed/TileDB-Inc__TileDB-Py/.github/workflows/ci-tiledb-from-source.yml new file mode 100644 index 0000000000000000000000000000000000000000..6d222f3ac56d814b38f0266185fb3eb9271ef048 --- /dev/null +++ b/testbed/TileDB-Inc__TileDB-Py/.github/workflows/ci-tiledb-from-source.yml @@ -0,0 +1,94 @@ +name: TileDB Python CI Using TileDB Core Source Build + +on: + workflow_dispatch: + inputs: + libtiledb_ref: + default: dev + type: string + libtiledb_version: + type: string + +jobs: + + build_libtiledb: + runs-on: ubuntu-latest + steps: + - name: Checkout TileDB Core ${{ inputs.libtiledb_ref || 'dev' }} + uses: actions/checkout@v4 + with: + repository: TileDB-Inc/TileDB + ref: ${{ inputs.libtiledb_ref || 'dev' }} + + - name: Configure TileDB + run: | + cmake -S . -B build \ + -DCMAKE_BUILD_TYPE=Release \ + -DBUILD_SHARED_LIBS=ON \ + -DCMAKE_INSTALL_PREFIX=./dist \ + -DTILEDB_INSTALL_LIBDIR=lib \ + -DTILEDB_S3=ON \ + -DTILEDB_AZURE=ON \ + -DTILEDB_GCS=ON \ + -DTILEDB_HDFS=ON \ + -DTILEDB_SERIALIZATION=ON \ + -DTILEDB_WEBP=ON \ + -DTILEDB_TESTS=OFF \ + -DVCPKG_TARGET_TRIPLET=x64-linux-release + + - name: Build TileDB + env: + TILEDB_PACKAGE_VERSION: ${{ inputs.libtiledb_version || '0.1' }} + run: cmake --build build --config Release --target package + + - name: Upload TileDB Core Artifact + uses: actions/upload-artifact@v4 + with: + name: libtiledb + path: | + build/tiledb-*.tar.gz* + build/tiledb-*.zip* + + build_tiledb_py: + needs: + - build_libtiledb + runs-on: ubuntu-latest + steps: + - name: Set up Python + uses: actions/setup-python@v5 + with: + python-version: "3.11" + + - name: Checkout TileDB-Py + uses: actions/checkout@v4 + + - name: Download TileDB Core Artifact + uses: actions/download-artifact@v4 + with: + name: libtiledb + path: ${{ github.workspace }}/libtiledb + + - name: Unpack Release Archive + run: tar xvf ${{ github.workspace }}/libtiledb/*.tar.gz --directory ${{ github.workspace }}/libtiledb + + - name: Build TileDB-Py Wheel + env: + TILEDB_PATH: ${{ github.workspace }}/libtiledb + run: | + python -m pip wheel -w dist --verbose . + WHEEL=$(ls dist/tiledb-*.whl) + python -m pip install ${WHEEL}[test] + + - name: Upload TileDB Core Artifact + uses: actions/upload-artifact@v4 + with: + name: tiledb-py + path: | + dist/tiledb-*.whl + + - name: Run tests + run: | + PROJECT_CWD=$PWD + rm tiledb/__init__.py + cd /tmp + pytest -vv --showlocals $PROJECT_CWD diff --git a/testbed/TileDB-Inc__TileDB-Py/.github/workflows/ci.yml b/testbed/TileDB-Inc__TileDB-Py/.github/workflows/ci.yml new file mode 100644 index 0000000000000000000000000000000000000000..71fc1ceb77727e72e6dbc4881fe6bd9c213f5f9c --- /dev/null +++ b/testbed/TileDB-Inc__TileDB-Py/.github/workflows/ci.yml @@ -0,0 +1,115 @@ +name: TileDB Python CI + +on: [push, pull_request, workflow_dispatch] + +concurrency: + group: ${{ github.head_ref || github.run_id }} + cancel-in-progress: true + +env: + S3_BUCKET: ${{ vars.S3_BUCKET }} + TILEDB_NAMESPACE: ${{ vars.TILEDB_NAMESPACE }} + TILEDB_TOKEN: ${{ secrets.TILEDB_TOKEN }} + +jobs: + build: + runs-on: ${{ matrix.os }} + defaults: + run: + shell: bash + strategy: + matrix: + os: + - ubuntu-latest + - macos-13 + # libfaketime tests fail on macos arm. Disable tests for now. + # - macos-14 + - windows-latest + python-version: [ "3.9", "3.10", "3.11", "3.12", "3.13" ] + fail-fast: false + env: + MACOSX_DEPLOYMENT_TARGET: "11" + steps: + - name: Checkout TileDB-Py `dev` + uses: actions/checkout@v4 + + - name: Setup MSVC toolset (VS 2022) + uses: TheMrMilchmann/setup-msvc-dev@v3 + if: startsWith(matrix.os, 'windows') + with: + arch: x64 + + - name: Install Ninja (VS 2022) + uses: seanmiddleditch/gha-setup-ninja@v4 + if: startsWith(matrix.os, 'windows') + + - name: Set up Python ${{ matrix.python-version }} + uses: actions/setup-python@v4 + with: + python-version: ${{ matrix.python-version }} + + - name: Print Python version + run: | + which python + which pip + python --version + + - name: Print env + run: printenv + + - name: Print pip debug info + run: pip debug --verbose + + # Remove after upstream PR fully-deployed: + # - https://github.com/actions/runner-images/pull/7125 + - name: "Install homebrew dependencies" + run: brew install pkg-config + if: startsWith(matrix.os, 'macos') + + - name: "Install libfaketime (linux and macOS)" + if: ${{ ! startsWith(matrix.os, 'windows') }} + run: | + git clone https://github.com/wolfcw/libfaketime/ + cd libfaketime + sudo make install + cd .. + + - name: "Build and Install TileDB-Py" + # We use pipx here to produce wheel/sdist to upload as artifact in case of error + run: | + pipx run --python ${{ matrix.python-version }} build + WHEEL_NAME=$(ls dist/*.whl) + pip install --verbose ${WHEEL_NAME}[test] + + - name: "Run tests" + run: | + PROJECT_CWD=$PWD + rm tiledb/__init__.py + cd /tmp + pytest -vv --showlocals $PROJECT_CWD + + - name: "Re-run tests without pandas" + run: | + pip uninstall -y pandas + pytest -vv --showlocals $PROJECT_CWD + + - name: "Print log files (failed build only)" + run: | + set -xeo pipefail + # Display log files if the build failed + echo 'Dumping log files for failed build' + echo '----------------------------------' + for f in $(find build -name *.log); + do echo '------' + echo $f + echo '======' + cat $f + done; + if: failure() + + - name: "Upload files for debug" + if: always() + uses: actions/upload-artifact@v4 + with: + name: cibw-wheels-${{ matrix.os }}-${{ matrix.python-version }} + path: "." diff --git a/testbed/TileDB-Inc__TileDB-Py/.github/workflows/daily-test-build-numpy.yml b/testbed/TileDB-Inc__TileDB-Py/.github/workflows/daily-test-build-numpy.yml new file mode 100644 index 0000000000000000000000000000000000000000..a6ecb592a5760d4b6ec7474f736398407f845c2b --- /dev/null +++ b/testbed/TileDB-Inc__TileDB-Py/.github/workflows/daily-test-build-numpy.yml @@ -0,0 +1,121 @@ +name: TileDB Python CI - With Earliest Supported Version of NumPy + +on: + workflow_dispatch: + inputs: + libtiledb_version: + description: TileDB Core Version + required: true + type: string + workflow_call: + inputs: + libtiledb_version: + required: true + type: string + +jobs: + test: + runs-on: ${{ matrix.os }} + defaults: + run: + shell: bash + strategy: + matrix: + os: [ubuntu-latest, macos-13, macos-14, windows-latest] + python-version: ["3.9", "3.10", "3.11", "3.12", "3.13"] + include: + # https://github.com/scipy/oldest-supported-numpy/blob/main/setup.cfg + - python-version: "3.13" + numpy-version: "2.1.0" + - python-version: "3.12" + numpy-version: "1.26.4" + - python-version: "3.12" + numpy-version: "2.0.1" + - python-version: "3.11" + numpy-version: "1.25.2" + - python-version: "3.11" + numpy-version: "2.0.1" + - python-version: "3.10" + numpy-version: "1.25.2" + - python-version: "3.10" + numpy-version: "2.0.1" + - python-version: "3.9" + numpy-version: "1.25.2" + fail-fast: false + env: + TILEDB_VERSION: ${{ inputs.libtiledb_version }} + MACOSX_DEPLOYMENT_TARGET: "11" + VCPKG_BINARY_SOURCES: 'clear;x-gha,readwrite' + steps: + - name: Checkout TileDB-Py `dev` + uses: actions/checkout@v4 + + - name: Setup MSVC toolset (VS 2022) + uses: TheMrMilchmann/setup-msvc-dev@v3 + if: startsWith(matrix.os, 'windows') + with: + arch: x64 + + - name: Install Ninja (VS 2022) + uses: seanmiddleditch/gha-setup-ninja@v4 + if: startsWith(matrix.os, 'windows') + + - name: Enable vcpkg binary caching + uses: actions/github-script@v6 + with: + script: | + core.exportVariable('ACTIONS_CACHE_URL', process.env.ACTIONS_CACHE_URL || ''); + core.exportVariable('ACTIONS_RUNTIME_TOKEN', process.env.ACTIONS_RUNTIME_TOKEN || ''); + + - name: "Set CMAKE_GENERATOR" + run: export CMAKE_GENERATOR="Ninja" + if: startsWith(matrix.os, 'windows') + + - name: Set up Python ${{ matrix.python-version }} + uses: actions/setup-python@v5 + with: + python-version: ${{ matrix.python-version }} + + - name: Print Python version + run: | + which python + which pip + python --version + + - name: Print env + run: printenv + + - name: Checkout TileDB-Py `dev` + uses: actions/checkout@v3 + + - name: Build TileDB-Py + run: pip install --verbose .[test] + + - name: Install Numpy + run: | + pip install numpy==${{ matrix.numpy-version }} + + - name: Print installed Python dependencies + run: pip list + + - name: Run tests + run: | + PROJECT_CWD=$PWD + rm tiledb/__init__.py + cd /tmp + pytest -vv --showlocals $PROJECT_CWD + + create_issue_on_fail: + permissions: + issues: write + runs-on: ubuntu-latest + needs: test + if: failure() || cancelled() + steps: + - uses: actions/checkout@v3 + - name: Create Issue if Build Fails + uses: TileDB-Inc/github-actions/open-issue@main + with: + name: nightly build with earliest supported numpy + label: bug,nightly-failure + assignee: kounelisagis,nguyenv,ihnorton \ No newline at end of file diff --git a/testbed/TileDB-Inc__TileDB-Py/.github/workflows/daily-test-build.yml b/testbed/TileDB-Inc__TileDB-Py/.github/workflows/daily-test-build.yml new file mode 100644 index 0000000000000000000000000000000000000000..9018352d6d29227e0d5d129f9fc0ea72bcb4907f --- /dev/null +++ b/testbed/TileDB-Inc__TileDB-Py/.github/workflows/daily-test-build.yml @@ -0,0 +1,94 @@ +name: Daily Test Build TileDB-Py Against Core + +on: + workflow_call: + inputs: + libtiledb_version: + required: true + type: string + +jobs: + test: + runs-on: ${{ matrix.os }} + defaults: + run: + shell: bash + strategy: + matrix: + os: [ubuntu-latest, macos-13, macos-14, windows-latest] + fail-fast: false + + env: + TILEDB_VERSION: ${{ inputs.libtiledb_version }} + MACOSX_DEPLOYMENT_TARGET: "11" + VCPKG_BINARY_SOURCES: 'clear;x-gha,readwrite' + + steps: + - name: Setup MSVC toolset (VS 2022) + uses: TheMrMilchmann/setup-msvc-dev@v3 + if: matrix.os == 'windows-latest' + with: + arch: x64 + + - name: Enable vcpkg binary caching + uses: actions/github-script@v6 + with: + script: | + core.exportVariable('ACTIONS_CACHE_URL', process.env.ACTIONS_CACHE_URL || ''); + core.exportVariable('ACTIONS_RUNTIME_TOKEN', process.env.ACTIONS_RUNTIME_TOKEN || ''); + + - name: Install Ninja (VS 2022) + uses: seanmiddleditch/gha-setup-ninja@v4 + if: matrix.os == 'windows-latest' + + - name: "Set CMAKE_GENERATOR" + run: echo "CMAKE_GENERATOR=Ninja" >> $GITHUB_ENV + if: matrix.os == 'windows-latest' + + - name: Set up Python + uses: actions/setup-python@v5 + with: + python-version: "3.11" + + - name: Print Python version + run: | + which python + which pip + python --version + + - name: Print env + run: printenv + + # Remove after upstream PR fully-deployed: + # - https://github.com/actions/runner-images/pull/7125 + - name: "Install homebrew dependencies" + run: brew install pkg-config + if: matrix.os == 'macos-13' || matrix.os == 'macos-14' + + - name: Checkout TileDB-Py `dev` + uses: actions/checkout@v4 + + - name: Build and install TileDB-Py and dependencies + run: python -m pip install --verbose .[test] + + - name: Run tests + run: | + PROJECT_CWD=$PWD + rm tiledb/__init__.py + cd /tmp + pytest -vv --showlocals $PROJECT_CWD + + create_issue_on_fail: + permissions: + issues: write + runs-on: ubuntu-latest + needs: test + if: failure() || cancelled() + steps: + - uses: actions/checkout@v3 + - name: Create Issue if Build Fails + uses: TileDB-Inc/github-actions/open-issue@main + with: + name: nightly build + label: bug,nightly-failure + assignee: kounelisagis,nguyenv,ihnorton diff --git a/testbed/TileDB-Inc__TileDB-Py/.github/workflows/daily-tests.yml b/testbed/TileDB-Inc__TileDB-Py/.github/workflows/daily-tests.yml new file mode 100644 index 0000000000000000000000000000000000000000..1e89769be4cddf40ad19eb7fb6fab655c4c68a27 --- /dev/null +++ b/testbed/TileDB-Inc__TileDB-Py/.github/workflows/daily-tests.yml @@ -0,0 +1,23 @@ +name: Daily Tests TileDB-Py + +on: + schedule: + # runs every day at 5:00 UTC (1:00AM EST / Midnight CST) + - cron: "0 5 * * *" + workflow_dispatch: + +jobs: + ci1: + uses: ./.github/workflows/daily-test-build.yml + with: + libtiledb_version: '2.26.0' + + ci2: + uses: ./.github/workflows/daily-test-build.yml + with: + libtiledb_version: '2.25.0' + + ci3: + uses: ./.github/workflows/daily-test-build-numpy.yml + with: + libtiledb_version: '2.25.0' diff --git a/testbed/TileDB-Inc__TileDB-Py/.github/workflows/format.yml b/testbed/TileDB-Inc__TileDB-Py/.github/workflows/format.yml new file mode 100644 index 0000000000000000000000000000000000000000..30b1d79bc2e4f91f2bae2f8f893282dc185a1364 --- /dev/null +++ b/testbed/TileDB-Inc__TileDB-Py/.github/workflows/format.yml @@ -0,0 +1,19 @@ +name: TileDB Python Linting + +on: [push, pull_request, workflow_dispatch] + +jobs: + lint: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v3 + - uses: actions/setup-python@v4 + + - name: Run pre-commit hooks on all files + run: python -m pip -v install pre-commit && pre-commit run -a -v + + - name: Check formatting (linux only)' + run: | + source $GITHUB_WORKSPACE/ci/scripts/check_formatting_linux.sh + shell: bash + if: ${{ runner.os == 'Linux' }} diff --git a/testbed/TileDB-Inc__TileDB-Py/.gitignore b/testbed/TileDB-Inc__TileDB-Py/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..9daa9a8fc3b1967cc8468a7fc315e34ede163fcc --- /dev/null +++ b/testbed/TileDB-Inc__TileDB-Py/.gitignore @@ -0,0 +1,115 @@ +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] +*$py.class + +# C extensions +*.so +*.dylib + +# Cython extensions +*.cpp + +# Distribution / packaging +.Python +env/ +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +wheels/ +*.egg-info/ +.installed.cfg +*.egg +tiledb/_generated_version.py + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*.cover +.hypothesis/ + +# Translations +*.mo +*.pot + +# Django stuff: +*.log +local_settings.py + +# Flask stuff: +instance/ +.webassets-cache + +# Scrapy stuff: +.scrapy + +# Sphinx documentation +doc/source/_build +doc/source/_sidebar.rst.inc + +# PyBuilder +target/ + +# Jupyter Notebook +.ipynb_checkpoints + +# pyenv +.python-version + +# celery beat schedule file +celerybeat-schedule + +# SageMath parsed files +*.sage.py + +# dotenv +.env + +# virtualenv +.venv +venv/ +ENV/ + +# Spyder project settings +.spyderproject +.spyproject + +# Rope project settings +.ropeproject + +# mkdocs documentation +/site + +# mypy +.mypy_cache/ + +# IntelliJ +.idea + +# Visual Studio Code +.vscode/ + +*.DS_Store diff --git a/testbed/TileDB-Inc__TileDB-Py/.pre-commit-config.yaml b/testbed/TileDB-Inc__TileDB-Py/.pre-commit-config.yaml new file mode 100644 index 0000000000000000000000000000000000000000..f3fd8e17ca3753d2bb63a478c4acd924b21f2c43 --- /dev/null +++ b/testbed/TileDB-Inc__TileDB-Py/.pre-commit-config.yaml @@ -0,0 +1,9 @@ +repos: + - repo: https://github.com/ambv/black + rev: 22.12.0 + hooks: + - id: black + - repo: https://github.com/charliermarsh/ruff-pre-commit + rev: v0.4.4 + hooks: + - id: ruff diff --git a/testbed/TileDB-Inc__TileDB-Py/.readthedocs.yml b/testbed/TileDB-Inc__TileDB-Py/.readthedocs.yml new file mode 100644 index 0000000000000000000000000000000000000000..43d03881b99764c14c2ea22327155459f1521607 --- /dev/null +++ b/testbed/TileDB-Inc__TileDB-Py/.readthedocs.yml @@ -0,0 +1,22 @@ +# Don't build any extra formats +formats: [] + +# Use RTD config version 2 +# https://docs.readthedocs.io/en/stable/config-file/v2.html +version: 2 + +# Set build OS to avoid build failures with old compiler +build: + os: "ubuntu-22.04" + tools: + python: "3.12" + +sphinx: + configuration: doc/source/conf.py + +python: + install: + - method: pip + path: . + extra_requirements: + - doc diff --git a/testbed/TileDB-Inc__TileDB-Py/CMakeLists.txt b/testbed/TileDB-Inc__TileDB-Py/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..dfd75c62dc910486b8efba6bc19486c1020d8445 --- /dev/null +++ b/testbed/TileDB-Inc__TileDB-Py/CMakeLists.txt @@ -0,0 +1,60 @@ +cmake_minimum_required(VERSION 3.15...3.26) + +project(${SKBUILD_PROJECT_NAME}) + +set(PYBIND11_NEWPYTHON ON) + +find_package( + Python + COMPONENTS Interpreter Development.Module NumPy + REQUIRED +) + +find_package(pybind11 CONFIG REQUIRED) + +if (TILEDB_PATH) + file(REAL_PATH "${TILEDB_PATH}" USER_TILEDB_PATH EXPAND_TILDE) + file(GLOB_RECURSE USER_TILEDB_CONFIG_PATH "${TILEDB_PATH}/**/TileDBConfig.cmake") + cmake_path(GET USER_TILEDB_CONFIG_PATH PARENT_PATH USER_TILEDB_DIR) + set(TileDB_DIR ${USER_TILEDB_DIR}) +endif() + +# In the future we should use vcpkg +if (TILEDB_PATH) + find_package(TileDB + HINTS ${USER_TILEDB_DIR} ${TILEDB_PATH} + QUIET NO_DEFAULT_PATH REQUIRED) +else() + find_package(TileDB QUIET) +endif() + +if (NOT TileDB_FOUND) + include(cmake/DownloadTileDB.cmake) + if (TILEDB_VERSION) + message(STATUS "Downloading TileDB version \"${TILEDB_VERSION}\" ...") + if (TILEDB_HASH) + fetch_prebuilt_tiledb( + VERSION ${TILEDB_VERSION} + RELLIST_HASH SHA256=${TILEDB_HASH} + ) + else() + fetch_prebuilt_tiledb( + VERSION ${TILEDB_VERSION} + ) + endif() + else() + message(STATUS "Downloading TileDB default version ...") + # Download latest release + fetch_prebuilt_tiledb( + VERSION 2.26.2 + RELLIST_HASH SHA256=86c19d7c5246cb18e370a4272cead63ea84bd651789842e618de4d57d4510522 + ) + endif() + find_package(TileDB REQUIRED) + set(TILEDB_DOWNLOADED TRUE) +else() + message(STATUS "Found external TileDB core library") +endif() + +message(STATUS "Using libtiledb path: " "${TileDB_DIR}") +add_subdirectory(tiledb) diff --git a/testbed/TileDB-Inc__TileDB-Py/CONTRIBUTING.md b/testbed/TileDB-Inc__TileDB-Py/CONTRIBUTING.md new file mode 100644 index 0000000000000000000000000000000000000000..ac7254bf5d48802d0ca006ad7cb2122fafd1c8c6 --- /dev/null +++ b/testbed/TileDB-Inc__TileDB-Py/CONTRIBUTING.md @@ -0,0 +1,48 @@ +# Contributing to TileDB-Py + +Thanks for your interest in TileDB-Py. The notes below give some pointers for filing issues and bug reports, or contributing to the code. + +## Contribution Checklist +- Reporting a bug? Please include the following information + - operating system and version (windows, linux, macos, etc.) + - the output of `tiledb.version()` and `tiledb.libtiledb.version()` + - if possible, a minimal working example demonstrating the bug or issue (along with any data to re-create, when feasible) +- Please paste code blocks with triple backquotes (```) so that github will format it nicely. See [GitHub's guide on Markdown](https://guides.github.com/features/mastering-markdown) for more formatting tricks. + +## Contributing Code +*By contributing code to TileDB-Py, you are agreeing to release it under the [MIT License](https://github.com/TileDB-Inc/TileDB/tree/dev/LICENSE).* + +### Contribution Workflow + +- Quick steps to build locally: + - install prerequisites via pip or conda: `pybind11` `cython` `numpy` `pandas` `pyarrow` + - recommended: install TileDB embedded (libtiledb) + + NOTE: if libtiledb path is not specified with `--tiledb`, it will be built automatically by `setup.py`. However, this build + is internal to the source tree and somewhat difficult to modify. When working on both projects simultaneously, it is + strongly suggested to build libtiledb separately. Changes to libtiledb must be `make install-tiledb` to `dist` in + order to be used with `--tiledb`. + + - from latest release build: https://github.com/TileDB-Inc/TileDB/releases + - `tar xf tiledb--.tar.gz -C /path/to/extract` + - use `--tiledb=/path/to/extract` (note: this path should _contain_ the `lib` directory) + - from [conda-forge](): `mamba install tiledb` + - `--tiledb=$CONDA_PREFIX` + - from source: https://docs.tiledb.com/main/how-to/installation/building-from-source/c-cpp + - use `--tiledb=/path/to/tiledb/dist` option when running ``setup.py`` in the step below + - if building libtiledb from source, to enable serialization pass ``--enable-serialization`` + to the ``bootstrap`` script before compiling + - serialization is optional. if libtiledb is not build with serialization, then it will not be + enabled in TileDB-Py + + - build TileDB-Py + ``` + git clone https://github.com/TileDB-Inc/TileDB-Py + cd TileDB-Py + python setup.py develop --tiledb= + ``` + +- Make changes locally, then rebuild with `python setup.py develop [--tiledb=<>]` +- Make sure to run `pytest` to verify changes against tests (add new tests where applicable). + - Execute the tests as `pytest tiledb` from the top-level directory or `pytest` in the `tiledb/` directory. +- Please submit [pull requests](https://help.github.com/en/desktop/contributing-to-projects/creating-a-pull-request) against the default [`dev` branch of TileDB-Py](https://github.com/TileDB-Inc/TileDB-Py/tree/dev) diff --git a/testbed/TileDB-Inc__TileDB-Py/HISTORY.md b/testbed/TileDB-Inc__TileDB-Py/HISTORY.md new file mode 100644 index 0000000000000000000000000000000000000000..c8f42bf90c833a102354988d083e3590bbc8f499 --- /dev/null +++ b/testbed/TileDB-Inc__TileDB-Py/HISTORY.md @@ -0,0 +1,1545 @@ +# Release 0.32.5 + +* TileDB-Py 0.32.5 includes TileDB Embedded [2.26.2](https://github.com/TileDB-Inc/TileDB/releases/tag/2.26.2) + +## Improvements + +* Fix GroupMetadata backwards compatibility by @kounelisagis in https://github.com/TileDB-Inc/TileDB-Py/pull/2102 +* Fix typo in API doc for create_bucket by @nickvigilante in https://github.com/TileDB-Inc/TileDB-Py/pull/2101 +* Update enumerations exception message by @shaunrd0 in https://github.com/TileDB-Inc/TileDB-Py/pull/2096 +* Handle removal of 'StorageManager' from stats dumps in 2.27 - Part 2 by @kounelisagis https://github.com/TileDB-Inc/TileDB-Py/pull/2098 + +## Build system changes + +* Revert "Do not run CI in PR twice (#2082)" by @kounelisagis in https://github.com/TileDB-Inc/TileDB-Py/pull/2100 + +# Release 0.32.4 + +TileDB-Py 0.32.4 was inadvertently released against TileDB [2.26.1](https://github.com/TileDB-Inc/TileDB/releases/tag/2.26.1). This will be corrected in 0.32.5, but the version delta does not justify yanking 0.32.4 + +## Improvements + +* Add `TILEDB_DATETIME_DAY` type support for Arrow by @kounelisagis in https://github.com/TileDB-Inc/TileDB-Py/pull/2002 +* Extend the `GroupMetadata` functionality to support NumPy arrays by @kounelisagis in https://github.com/TileDB-Inc/TileDB-Py/pull/2085 +* Add extra argument to Group::add_member by @kounelisagis in https://github.com/TileDB-Inc/TileDB-Py/pull/2093 +* Handle removal of 'StorageManager' from stats dumps in 2.27 by @kounelisagis in https://github.com/TileDB-Inc/TileDB-Py/pull/2088 +* Make default value for `vfs.s3.region` in test conditional by @kounelisagis in https://github.com/TileDB-Inc/TileDB-Py/pull/2086 +* Make error message for non-existing `Enumeration` in test conditional by @kounelisagis in https://github.com/TileDB-Inc/TileDB-Py/pull/2087 +* Fix randomly failing test `DenseArrayTest::test_open_with_timestamp[False]` by @kounelisagis in https://github.com/TileDB-Inc/TileDB-Py/pull/2090 +* Fix skipif condition for test_cloud by @kounelisagis in https://github.com/TileDB-Inc/TileDB-Py/pull/2084 +* Raise error when sparse=True is passed to `tiledb.from_numpy` by @kounelisagis in https://github.com/TileDB-Inc/TileDB-Py/pull/2080 +* Documentation and CI updates by @kounelisagis in https://github.com/TileDB-Inc/TileDB-Py/pull/2078 +* Move `DenseArrayImpl` to pure Python by @kounelisagis and @nguyenv in https://github.com/TileDB-Inc/TileDB-Py/pull/2071 +* Move `PackedBuffer` and `pack_metadata_val` to pure Python, and wrap `tiledb_datatype_size` with pybind by @kounelisagis in https://github.com/TileDB-Inc/TileDB-Py/pull/2072 +* Move `SparseArrayImpl` to pure Python by @kounelisagis in https://github.com/TileDB-Inc/TileDB-Py/pull/2065 + +## Build system changes + +* Add CI to test against the TileDB core library built from source with a custom version by @dudoslav and @kounelisagis in https://github.com/TileDB-Inc/TileDB-Py/pull/2091 +* Do not run CI in PR twice by @dudoslav in https://github.com/TileDB-Inc/TileDB-Py/pull/2082 +* Disable release for Python 3.8 by @dudoslav in https://github.com/TileDB-Inc/TileDB-Py/pull/2081 +* Re-enable automatic upload to pypi by @dudoslav and @kounelisagis in https://github.com/TileDB-Inc/TileDB-Py/pull/2034 +* Drop Python 3.8 support by @kounelisagis in https://github.com/TileDB-Inc/TileDB-Py/pull/2079 + +# Release 0.32.3 + +* TileDB-Py 0.32.3 includes TileDB Embedded [2.26.2](https://github.com/TileDB-Inc/TileDB/releases/tag/2.26.2) + +## Build system changes + +* Override tag version in manylinux container by @dudoslav in https://github.com/TileDB-Inc/TileDB-Py/pull/2077 + +# Release 0.32.2 + +## Improvements + +* Fix object_type return value by @kounelisagis in https://github.com/TileDB-Inc/TileDB-Py/pull/2073 + +# Release 0.32.1 + +* TileDB-Py 0.32.1 includes TileDB Embedded [2.26.1](https://github.com/TileDB-Inc/TileDB/releases/tag/2.26.1) + +## Improvements + +* Move vacuum to pure Python by @kounelisagis in https://github.com/TileDB-Inc/TileDB-Py/pull/2067 +* Make dump calls conditional by @kounelisagis in https://github.com/TileDB-Inc/TileDB-Py/pull/2062 + +## Build system changes + +* Bump libtiledb version to 2.26.0 for daily tests by @kounelisagis in https://github.com/TileDB-Inc/TileDB-Py/pull/2063 + +# Release 0.32.0 + +* TileDB-Py 0.32.0 includes TileDB Embedded [2.26.0](https://github.com/TileDB-Inc/TileDB/releases/tag/2.26.0) + +## Improvements + +* Replace dump() calls with operator<< by @kounelisagis in https://github.com/TileDB-Inc/TileDB-Py/pull/1975 +* Convert config values to strings in VFS init by @gspowley and @kounelisagis in https://github.com/TileDB-Inc/TileDB-Py/pull/2060 +* Move DomainIndexer, Stats, and Array helper functions from Cython to pybind by @kounelisagis in https://github.com/TileDB-Inc/TileDB-Py/pull/2057 +* Refactor Aggregation from Cython to Pure Python by @kounelisagis in https://github.com/TileDB-Inc/TileDB-Py/pull/2056 +* Move tiledb_object_* API calls from Cython to pybind by @kounelisagis in https://github.com/TileDB-Inc/TileDB-Py/pull/2049 +* Don't check dtype if column_types is not set - from_pandas by @kounelisagis in https://github.com/TileDB-Inc/TileDB-Py/pull/2055 +* Fix serialization test and add command line option by @kounelisagis in https://github.com/TileDB-Inc/TileDB-Py/pull/2052 +* Remove deprecations by @kounelisagis in https://github.com/TileDB-Inc/TileDB-Py/pull/2050 +* Make from_pandas respect column_types for index dimensions by @kounelisagis in https://github.com/TileDB-Inc/TileDB-Py/pull/2046 +* Remove Dask test skips and add Dask as a test dependency by @kounelisagis in https://github.com/TileDB-Inc/TileDB-Py/pull/2047 +* Fix exception when calling label_index on a Query object by @sric0880 and @kounelisagis in https://github.com/TileDB-Inc/TileDB-Py/pull/2044 +* Improve Query Condition error messages to align with TileDB-SOMA-Py by @kounelisagis in https://github.com/TileDB-Inc/TileDB-Py/pull/2041 +* Fix numpy.ma.fix_invalid issue in NumPy 2.1.0 by replacing with numpy.ma.masked_invalid by @kounelisagis in https://github.com/TileDB-Inc/TileDB-Py/pull/2042 +* Add scope_ctx to doc build by @spencerseale in https://github.com/TileDB-Inc/TileDB-Py/pull/2038 +* Passing Empty List to multirange_index and df should return Empty Results by @nguyenv and @kounelisagis in https://github.com/TileDB-Inc/TileDB-Py/pull/1412 +* Get rid all BNF lines in QueryCondition docstring by @kounelisagis in https://github.com/TileDB-Inc/TileDB-Py/pull/2028 +* Add tiledb_current_domain_t as type by @kounelisagis in https://github.com/TileDB-Inc/TileDB-Py/pull/2033 +* Add Enumeration in api ref docs by @kounelisagis in https://github.com/TileDB-Inc/TileDB-Py/pull/2026 +* Hide sensitive params shown in Config::__repr__ by @kounelisagis in https://github.com/TileDB-Inc/TileDB-Py/pull/2029 +* Wrap current domain API by @kounelisagis in https://github.com/TileDB-Inc/TileDB-Py/pull/2015 + +## Build system changes + +* Bump libtiledb and numpy versions for daily tests / make CurrentDomain and NDRectangle code conditional by @kounelisagis in https://github.com/TileDB-Inc/TileDB-Py/pull/2036 +* Fix compilation warnings by @kounelisagis in https://github.com/TileDB-Inc/TileDB-Py/pull/1940 +* Add packaging as dependency by @dudoslav in https://github.com/TileDB-Inc/TileDB-Py/pull/2032 +* Expose setup.py flag to enable deprecations by @kounelisagis in https://github.com/TileDB-Inc/TileDB-Py/pull/2025 +* Update Cython minimum version to 3 by @kounelisagis in https://github.com/TileDB-Inc/TileDB-Py/pull/2027 + +# Release 0.31.1 + +## Improvements + +* Fix malformed doc str for tiledb.array_schema.ArraySchema by @kounelisagis in https://github.com/TileDB-Inc/TileDB-Py/pull/2007 +* Fix deprecation and test by @kounelisagis in https://github.com/TileDB-Inc/TileDB-Py/pull/2021 + +## Build system changes + +* Add pandas dependency to test group by @dudoslav and @kounelisagis in https://github.com/TileDB-Inc/TileDB-Py/pull/2022 +* Define TILEDB_REMOVE_DEPRECATIONS macro for cc and remove deprecated code by @kounelisagis and @dudoslav in https://github.com/TileDB-Inc/TileDB-Py/pull/2023 + +# Release 0.31.0 + +* TileDB-Py 0.31.0 includes TileDB Embedded [2.25.0](https://github.com/TileDB-Inc/TileDB/releases/tag/2.25.0) + +## Improvements + +* Remove deprecated Array.delete_fragments code path by @teo-tsirpanis and @kounelisagis in https://github.com/TileDB-Inc/TileDB-Py/pull/2009 +* Fix a typo in an error message by @johnkerl in https://github.com/TileDB-Inc/TileDB-Py/pull/2004 +* Support ctx argument in array_exists by @kounelisagis in https://github.com/TileDB-Inc/TileDB-Py/pull/2003 +* Move fragment list consolidation API to pybind by @kounelisagis in https://github.com/TileDB-Inc/TileDB-Py/pull/1999 + +## Build system changes + +* Add version pins for pandas 3.0 by @kounelisagis https://github.com/TileDB-Inc/TileDB-Py/pull/2016 +* Scikit-build-core build system rework by @dudoslav and @ihnorton in https://github.com/TileDB-Inc/TileDB-Py/pull/1988 +* Patches for the build system by @dudoslav, @ihnorton and @kounelisagis in https://github.com/TileDB-Inc/TileDB-Py/pull/2010, https://github.com/TileDB-Inc/TileDB-Py/pull/2011, https://github.com/TileDB-Inc/TileDB-Py/pull/2013, https://github.com/TileDB-Inc/TileDB-Py/pull/2014, https://github.com/TileDB-Inc/TileDB-Py/pull/2018, https://github.com/TileDB-Inc/TileDB-Py/pull/2019, https://github.com/TileDB-Inc/TileDB-Py/pull/2020 + +# Release 0.30.2 + +## Packaging Notes + +While we currently plan to maintain support for CentOS 7-compatible systems (GLIBC 2.17) through TileDB 2.31, ecosystem and infrastructure updates following the CentOS 7 end-of-life on 30/Jun/2024 may necessitate dropping support earlier. Please contact us if you still use a CentOS 7 (GLIBC 2.17)-like Linux distribution. + +## Improvements + +* Fix OverflowError: Python int too large to convert to C long by @kounelisagis in https://github.com/TileDB-Inc/TileDB-Py/pull/2000 +* Wrap as_built function by @kounelisagis in https://github.com/TileDB-Inc/TileDB-Py/pull/1994 +* Fix array.query() incorrectly handling nullables by @kounelisagis in https://github.com/TileDB-Inc/TileDB-Py/pull/1998 +* Add offending column when from_pandas -> _get_column_infos fails by @kounelisagis in https://github.com/TileDB-Inc/TileDB-Py/pull/1997 + +# Release 0.30.1 + +* TileDB-Py 0.30.1 includes TileDB Embedded [2.24.1](https://github.com/TileDB-Inc/TileDB/releases/tag/2.24.1) + +## Improvements + +* Document Azure, GCS and local support for VFS.ls_recursive by @kounelisagis in https://github.com/TileDB-Inc/TileDB-Py/pull/1980 +* Skip Dask failing test on Windows by @kounelisagis in https://github.com/TileDB-Inc/TileDB-Py/pull/1995 + +# Release 0.30.0 + +* TileDB-Py 0.30.0 includes TileDB Embedded [2.24.0](https://github.com/TileDB-Inc/TileDB/releases/tag/2.24.0) + +## Improvements + +* Add test for blob attribute by @kounelisagis in https://github.com/TileDB-Inc/TileDB-Py/pull/1985 +* Deprecate support for [] indexing with floats by @kounelisagis in https://github.com/TileDB-Inc/TileDB-Py/pull/1982 +* Fix Query constructor to return error for dense arrays with return_incomplete=True by @kounelisagis in https://github.com/TileDB-Inc/TileDB-Py/pull/1976 +* Expose WebP enums by @kounelisagis in https://github.com/TileDB-Inc/TileDB-Py/pull/1974 +* Add Array.query in docs and improve docs in general by @kounelisagis in https://github.com/TileDB-Inc/TileDB-Py/pull/1965 +* Add support for creating WKB/WKT attributes by @jp-dark in https://github.com/TileDB-Inc/TileDB-Py/pull/1912 +* Add wrapping for ls recursive by @kounelisagis in https://github.com/TileDB-Inc/TileDB-Py/pull/1968 +* Fix compatibility for delete_fragments by @kounelisagis in https://github.com/TileDB-Inc/TileDB-Py/pull/1966 + +## Build system changes + +* Fix pinning wrong numpy version by @kounelisagis in https://github.com/TileDB-Inc/TileDB-Py/pull/1989 +* Remove pin to MSVC toolset version in CI by @teo-tsirpanis in https://github.com/TileDB-Inc/TileDB-Py/pull/1991 +* Fix ModuleNotFoundError: No module named 'numpy' on build by @kounelisagis and @ihnorton in https://github.com/TileDB-Inc/TileDB-Py/pull/1979 +* Add support for numpy2 by @kounelisagis in https://github.com/TileDB-Inc/TileDB-Py/pull/1969 +* Fix syntax error in nightly build workflow by @ihnorton in https://github.com/TileDB-Inc/TileDB-Py/pull/1970 +* Set an upper bound for numpy to dodge 2.0 by @sgillies in https://github.com/TileDB-Inc/TileDB-Py/pull/1963 + +# Release 0.29.1 + +## Build system changes + +* Add numpy upper bound to dodge 2.0 by @kounelisagis in https://github.com/TileDB-Inc/TileDB-Py/pull/1993 + +# Release 0.29.0 + +* TileDB-Py 0.29.0 includes TileDB Embedded [2.23.0](https://github.com/TileDB-Inc/TileDB/releases/tag/2.23.0) + +## Improvements + +* Add wrapping for ls_recursive by @kounelisagis in https://github.com/TileDB-Inc/TileDB-Py/pull/1933 +* Migrate away from deprecated TileDB C++ APIs by @kounelisagis in https://github.com/TileDB-Inc/TileDB-Py/pull/1958 +* Pybind11 Config should honor prefix for iter by @Shelnutt2 in https://github.com/TileDB-Inc/TileDB-Py/pull/1962 +* Fix test skipping by @kounelisagis in https://github.com/TileDB-Inc/TileDB-Py/pull/1957 +* Make timestamp overrides optional in tests and add faketime test by @kounelisagis in https://github.com/TileDB-Inc/TileDB-Py/pull/1953 +* Wrap tiledb_array_consolidate_fragments from pybind11 by @kounelisagis in https://github.com/TileDB-Inc/TileDB-Py/pull/1948 + +## Build system changes + +* Enable python 3.12 by @dudoslav in https://github.com/TileDB-Inc/TileDB-Py/pull/1959 +* Add .vscode to .gitignore by @kounelisagis in https://github.com/TileDB-Inc/TileDB-Py/pull/1952 + +# Release 0.28.0 + +## TileDB Embedded updates + +* TileDB-Py 0.28.0 includes TileDB Embedded [2.22.0](https://github.com/TileDB-Inc/TileDB/releases/tag/2.22.0) + +## Improvements + +* Update type signature for VFS::readinto by @kounelisagis in https://github.com/TileDB-Inc/TileDB-Py/pull/1937 +* Show enumerated value-types in enum-printer by @kounelisagis in https://github.com/TileDB-Inc/TileDB-Py/pull/1936 +* Add wrapping for new consolidation plan API by @kounelisagis in https://github.com/TileDB-Inc/TileDB-Py/pull/1935 +* Add test for Group constructor invalid uri object type by @kounelisagis in https://github.com/TileDB-Inc/TileDB-Py/pull/1941 +* Update doc for tiledb.consolidate by @ihnorton in https://github.com/TileDB-Inc/TileDB-Py/pull/1946 +* Improve documentation of from_numpy function by @kounelisagis in https://github.com/TileDB-Inc/TileDB-Py/pull/1942 + +## Build system changes + +* Exclude .pytest_cache and .hypothesis files by @kounelisagis in https://github.com/TileDB-Inc/TileDB-Py/pull/1932 +* Remove modular building option by @kounelisagis in https://github.com/TileDB-Inc/TileDB-Py/pull/1938 +* Fix wrong version number for Python API docs by @kounelisagis in https://github.com/TileDB-Inc/TileDB-Py/pull/1947 +* Remove conditional code for TileDB < 2.16 by @kounelisagis in https://github.com/TileDB-Inc/TileDB-Py/pull/1949 +* Update nightly test target to 2.21 by @ihnorton in https://github.com/TileDB-Inc/TileDB-Py/pull/1950 + +# Release 0.27.1 + +## TileDB Embedded updates + +* TileDB-Py 0.27.1 includes TileDB Embedded [2.21.1](https://github.com/TileDB-Inc/TileDB/releases/tag/2.21.1) + +## Improvements + +* Add tests to ensure empty result on query condition for invalid enum. [1882](https://github.com/TileDB-Inc/TileDB-Py/pull/1882) + +# Release 0.27.0 + +* TileDB-Py 0.27.0 includes TileDB Embedded [2.21.0](https://github.com/TileDB-Inc/TileDB/releases/tag/2.21.0) + +# Release 0.26.4 + +## Bug Fixes + +* Fix VFS `read`, `seek` with numpy integer sizes. [#1927](https://github.com/TileDB-Inc/TileDB-Py/pull/1927) +* Remove erroneous `_ctx` check for GroupMetadata [#1925](https://github.com/TileDB-Inc/TileDB-Py/pull/1925) + +# Release 0.26.3 + +## Improvements + +* Fix vfs readinto when buff is not bytes. [#1915](https://github.com/TileDB-Inc/TileDB-Py/pull/1915) +* Update daily test builds to use single source of truth for libtiledb target versions. [1910](https://github.com/TileDB-Inc/TileDB-Py/pull/1910) +* Remove Python 3.7 CI jobs. [1916](https://github.com/TileDB-Inc/TileDB-Py/pull/1916) + +# Release 0.26.2 + +## Improvements + +* Added API support for TileDB aggregates. [#1889](https://github.com/TileDB-Inc/TileDB-Py/pull/1889) +* For compatibility with fsspec and rasterio, `isdir()`, `isfile()`, and `size()` aliases have been added to the `VFS` class. [#1902](https://github.com/TileDB-Inc/TileDB-Py/pull/1902). + +# Release 0.26.1 + +* TileDB-Py 0.26.1 includes TileDB Embedded [2.20.1](https://github.com/TileDB-Inc/TileDB/releases/tag/2.20.1) + +# Release 0.26.0 + +* TileDB-Py 0.26.0 includes TileDB Embedded [2.20.0](https://github.com/TileDB-Inc/TileDB/releases/tag/2.20.0) + +## Bug Fixes + +* Add safe `Group.__repr__` [#1890](https://github.com/TileDB-Inc/TileDB-Py/pull/1890) +* Use safe repr if ArraySchema was not properly constructed [#1896](https://github.com/TileDB-Inc/TileDB-Py/pull/1896) + +## Improvements + +* Warn when `os.fork()` is used in the presence of a Tiledb context [#1876](https://github.com/TileDB-Inc/TileDB-Py/pull/1876/files). +* Enable GCS in osx-arm64 wheel builds [#1899](https://github.com/TileDB-Inc/TileDB-Py/pull/1899) + +# Release 0.25.0 + +* TileDB-Py 0.25.0 includes TileDB Embedded [2.19.0](https://github.com/TileDB-Inc/TileDB/releases/tag/2.19.0) + +## Improvements + +* Fix fill value for complex attributes [1872](https://github.com/TileDB-Inc/TileDB-Py/pull/1872) +* Update current-release nightly target [1873](https://github.com/TileDB-Inc/TileDB-Py/pull/1873) +* Add full check of attribute properties in __eq__ method [1874](https://github.com/TileDB-Inc/TileDB-Py/pull/1874) +* Add all array properties to ArraySchema.__eq__ [1875](https://github.com/TileDB-Inc/TileDB-Py/pull/1875) +* Error out if query condition given empty set [1877](https://github.com/TileDB-Inc/TileDB-Py/pull/1877) + +# Release 0.24.0 + +* TileDB-Py 0.24.0 includes TileDB Embedded [2.18.2](https://github.com/TileDB-Inc/TileDB/releases/tag/2.18.2) + +## Improvements + +* Release the GIL while consolidation. [#1865](https://github.com/TileDB-Inc/TileDB-Py/pull/1864) +* Add Group Metadata Consolidation and Vacuuming. [#1833](https://github.com/TileDB-Inc/TileDB-Py/pull/1833) +* Fix domain equality check. [#1866](https://github.com/TileDB-Inc/TileDB-Py/pull/1866) +* Fix reading DeltaFilter and DoubleDeltaFilter options for FilterList. [#1862](https://github.com/TileDB-Inc/TileDB-Py/pull/1862) +* Do not flush VFS handles on closing. [#1863](https://github.com/TileDB-Inc/TileDB-Py/pull/1863) +* Add context manager before enter `.array_exists`. [#1868](https://github.com/TileDB-Inc/TileDB-Py/pull/1868) (thanks, new contributor `p4perf4ce`!) + +# Release 0.23.4 + +* TileDB-Py 0.23.4 includes TileDB Embedded [2.17.4](https://github.com/TileDB-Inc/TileDB/releases/tag/2.17.4) + +## Improvements + +* Add `COMPRESSION_REINTERPRET_DATATYPE` to allowed `FilterOption` [#1855](https://github.com/TileDB-Inc/TileDB-Py/pull/1855) +* Add `filter_name` to `Filter` class [#1856](https://github.com/TileDB-Inc/TileDB-Py/pull/1856) + +## Bug Fixes + +* Do not use `dtype.kind` in enumeration extend type checking [#1853](https://github.com/TileDB-Inc/TileDB-Py/pull/1853) +* Empty enumerations should be casted to the dtype of the enumeration [#1854](https://github.com/TileDB-Inc/TileDB-Py/pull/1854) +* Correct writing nullable string attributes and all nulled data [#1848](https://github.com/TileDB-Inc/TileDB-Py/pull/1848) +* Pandas 2+ fix: use `pa.schema.with_metadata`, replacing passing metadata to `pa.schema` constructor [#1858](https://github.com/TileDB-Inc/TileDB-Py/pull/1858) + +# Release 0.23.3 + +## Bug Fixes + +* Correct `Enumeration.extend` to handle integers, include Booleans, of different sizes [#1850](https://github.com/TileDB-Inc/TileDB-Py/pull/1850) + +# Release 0.23.2 + +* TileDB-Py 0.23.2 includes TileDB Embedded [2.17.3](https://github.com/TileDB-Inc/TileDB/releases/tag/2.17.3) + +## Improvements + +* Add support for enumeration extension API. [#1847](https://github.com/TileDB-Inc/TileDB-Py/pull/1847) +* Support new set membership query condition. [#1837](https://github.com/TileDB-Inc/TileDB-Py/pull/1837) +* Create `ArraySchemaEvolution` for new operation. [#1839](https://github.com/TileDB-Inc/TileDB-Py/pull/1839) +* Add sparse dimension label example. [#1843](https://github.com/TileDB-Inc/TileDB-Py/pull/1843) + +# Release 0.23.1 + +* TileDB-Py 0.23.1 includes TileDB Embedded [2.17.1](https://github.com/TileDB-Inc/TileDB/releases/tag/2.17.1) + +# Release 0.23.0 + +* TileDB-Py 0.23.0 includes TileDB Embedded [2.17.0](https://github.com/TileDB-Inc/TileDB/releases/tag/2.17.0) + +## Improvements + +* Support for "enumerated datatypes" (aka categoricals or factors). [#1790](https://github.com/TileDB-Inc/TileDB-Py/pull/1790) +* Introduce `Array.read_subarray` and `Array.write_subarray` APIs. [#1824](https://github.com/TileDB-Inc/TileDB-Py/pull/1824) +* Avoid importing Pandas until we actually use it. [#1825](https://github.com/TileDB-Inc/TileDB-Py/pull/1825) +* Make VFS accept path-like objects to refer to files. [#1818](https://github.com/TileDB-Inc/TileDB-Py/pull/1818) + +## Bug Fixes + +* Use object equality check in buffer conversion, fixes state serialization bug in distributed use-case. [#1822](https://github.com/TileDB-Inc/TileDB-Py/pull/1822) + +# Release 0.22.3 + +* TileDB-Py 0.22.3 includes TileDB Embedded [2.16.3](https://github.com/TileDB-Inc/TileDB/releases/tag/2.16.3) + +## Improvements + +* Wrap Delta filter. [#1710](https://github.com/TileDB-Inc/TileDB-Py/pull/1710) + +# Release 0.22.2 + +* TileDB-Py 0.22.2 includes TileDB Embedded [2.16.2](https://github.com/TileDB-Inc/TileDB/releases/tag/2.16.2) + +# Release 0.22.1 + +* TileDB-Py 0.22.1 includes TileDB Embedded [2.16.1](https://github.com/TileDB-Inc/TileDB/releases/tag/2.16.1) + +# Release 0.22.0 + +* TileDB-Py 0.22.0 includes TileDB Embedded [2.16.0](https://github.com/TileDB-Inc/TileDB/releases/tag/2.16.0) + +## Improvements + +* Added support for variable-length dimension label reads [#1802](https://github.com/TileDB-Inc/TileDB-Py/pull/1802) + +## Bug Fixes + +* Fix online help typo, and clarify. [#1803](https://github.com/TileDB-Inc/TileDB-Py/pull/1803) +* Fix bad memory access for dimension label tile. [#1804](https://github.com/TileDB-Inc/TileDB-Py/pull/1804) + +# Release 0.21.6 + +## Bug Fixes + +* Fix group.close to work on 2.16. [#1793](https://github.com/TileDB-Inc/TileDB-Py/pull/1793) +* Fix sc-30787, VFS S3 write failure. [#1794](https://github.com/TileDB-Inc/TileDB-Py/pull/1794) + +# Release 0.21.5 + +## TileDB Embedded updates + +* TileDB-Py 0.21.5 includes TileDB Embedded [2.15.4](https://github.com/TileDB-Inc/TileDB/releases/tag/2.15.4) + +## Bug Fixes + +* Handle empty string passed to Query condition [#1774](https://github.com/TileDB-Inc/TileDB-Py/pull/1774) + +# Release 0.21.4 + +## TileDB Embedded updates + +* TileDB-Py 0.21.4 includes TileDB Embedded [2.15.3](https://github.com/TileDB-Inc/TileDB/releases/tag/2.15.3) + +# Release 0.21.3 + +## TileDB Embedded updates + +* TileDB-Py 0.21.3 includes TileDB Embedded [2.15.2](https://github.com/TileDB-Inc/TileDB/releases/tag/2.15.2) + +## Improvements + +* Add support for Group.delete; fixes sc-28030. [#1754](https://github.com/TileDB-Inc/TileDB-Py/pull/1754) + +## Bug Fixes + +* Fix sc-27374: default order mapping fallback. [#1736](https://github.com/TileDB-Inc/TileDB-Py/pull/1736) +* Fix for array_exists hiding errors; fixes SC-27849. [#1754](https://github.com/TileDB-Inc/TileDB-Py/pull/1754) + +# Release 0.21.2 + +## TileDB Embedded updates + +* TileDB-Py 0.21.2 includes TileDB Embedded [2.15.1](https://github.com/TileDB-Inc/TileDB/releases/tag/2.15.1) + +## Improvements + +* Addition of `Group(config=...)` and `Group.set_config` [#1715](https://github.com/TileDB-Inc/TileDB-Py/pull/1715) + +# Release 0.21.1 + +*0.21.0 tag was invalid and thus deleted before PyPI release.* + +## TileDB Embedded updates +* TileDB-Py 0.21.0 includes TileDB Embedded [2.15.0](https://github.com/TileDB-Inc/TileDB/releases/tag/2.15.0) + +## Improvements +* Move `ArraySchema` from Cython to pure Python [#1340](https://github.com/TileDB-Inc/TileDB-Py/pull/1340) + +## Bug Fixes +* Correct `Attr.fill` for UTF-8 [#1594](https://github.com/TileDB-Inc/TileDB-Py/pull/1594) + +# Release 0.20.0 + +## TileDB Embedded updates +* TileDB-Py 0.20.0 includes TileDB Embedded [TileDB 2.14.0](https://github.com/TileDB-Inc/TileDB/releases/tag/2.14.0) + +## Bug Fixes + +* Introduce safe repr for classes for `Filter`, `FilterList`, `Dim`, `Domain`, and `Attr`. [#1545](https://github.com/TileDB-Inc/TileDB-Py/pull/1545), [#1555](https://github.com/TileDB-Inc/TileDB-Py/pull/1555) + +# Release 0.19.1 + +## TileDB Embedded updates: +* TileDB-Py 0.19.1 includes TileDB Embedded [TileDB 2.13.1](https://github.com/TileDB-Inc/TileDB/releases/tag/2.13.1) + +## Improvements +* Move `Dim` and `Domain` from Cython to pure Python [#1327](https://github.com/TileDB-Inc/TileDB-Py/pull/1327) + +## Bug Fixes +* Ensure NumPy array matches array schema dimensions for dense writes [#1514](https://github.com/TileDB-Inc/TileDB-Py/pull/1514) + +# Release 0.19.0 + +## Packaging Notes +* Added support for Python 3.11 + +## TileDB Embedded updates: +* TileDB-Py 0.19.0 includes TileDB Embedded [TileDB 2.13.0](https://github.com/TileDB-Inc/TileDB/releases/tag/2.13.0) + +## Deprecations +* `FragmentInfoList.non_empty_domain` deprecated for `FragmentInfoList.nonempty_domain` +* `FragmentInfoList.to_vacuum_num` deprecated for `len(FragmentInfoList.to_vacuum)` +* `FragmentInfoList.to_vacuum_uri` deprecated for `FragmentInfoList.to_vacuum` +* `FragmentInfoList.dense` deprecated for `not FragmentInfoList.dense` +* `FragmentInfo.non_empty_domain` deprecated for `FragmentInfo.nonempty_domain` +* `FragmentInfo.to_vacuum_num` deprecated for `len(FragmentInfo.to_vacuum)` +* `FragmentInfo.to_vacuum_uri` deprecated for `FragmentInfo.to_vacuum` +* `FragmentInfo.dense` deprecated for `not FragmentInfo.dense` +* `FragmentsInfo` deprecated for `FragmentInfoList` +* `tiledb.delete_fragments` deprecated for `Array.delete_fragments` +* `Array.timestamp` deprecated for `Array.timestamp_range` +* `Array.coords_dtype` deprecated with no replacement; combined coords have been removed from libtiledb +* `Array.timestamp` deprecated for `Array.timestamp_range` +* `Array.query(attr_cond=...)` deprecated for `Array.query(cond=...)` +* `Array.query(cond=tiledb.QueryCondition('expression'))` deprecated for `Array.query(cond='expression')` + +## API Changes +* Add support for `WebpFilter` [#1395](https://github.com/TileDB-Inc/TileDB-Py/pull/1395) +* Support Boolean types for query conditions [#1432](https://github.com/TileDB-Inc/TileDB-Py/pull/1432) +* Support for partial consolidation using a list of fragment URIs [#1431](https://github.com/TileDB-Inc/TileDB-Py/pull/1431) +* Addition of `ArraySchemaEvolution.timestamp` [#1480](https://github.com/TileDB-Inc/TileDB-Py/pull/1480) +* Addition of `ArraySchema.has_dim` [#1430](https://github.com/TileDB-Inc/TileDB-Py/pull/1430) +* Addition of `Array.delete_array` [#1428](https://github.com/TileDB-Inc/TileDB-Py/pull/1428) + +## Bug Fixes +* Fix issue where queries in delete mode error out on arrays with string dimensions [#1473](https://github.com/TileDB-Inc/TileDB-Py/pull/1473) +* Fix representation of nullable integers in dataframe when using PyArrow path [#1439](https://github.com/TileDB-Inc/TileDB-Py/pull/1439) +* Check for uninitialized query state after submit and error out if uninitialized [#1483](https://github.com/TileDB-Inc/TileDB-Py/pull/1483) + +# Release 0.18.3 + +## Packaging Notes +* Linux wheels now built on `manylinux2014`; previously built on `manylinux2010` +* Windows wheels NOT AVAILABLE for this release + +## TileDB Embedded updates: +* TileDB-Py 0.18.3 includes TileDB Embedded [TileDB 2.12.3](https://github.com/TileDB-Inc/TileDB/releases/tag/2.12.3) + +## Improvements +* Move `from_numpy` out of Cython into pure Python [#1436](https://github.com/TileDB-Inc/TileDB-Py/pull/1436) + +## Bug Fixes +* Fix `.df` and `.multi_index` always returning attributes applied in query conditions [#1433](https://github.com/TileDB-Inc/TileDB-Py/pull/1433) + +# Release 0.18.2 + +## TileDB Embedded updates: +* TileDB-Py 0.18.2 includes TileDB Embedded [TileDB 2.12.2](https://github.com/TileDB-Inc/TileDB/releases/tag/2.12.2) + +# Release 0.18.1 + +## TileDB Embedded updates: +* TileDB-Py 0.18.1 includes TileDB Embedded [TileDB 2.12.1](https://github.com/TileDB-Inc/TileDB/releases/tag/2.12.1) + +## Improvements +* Reintroduce moving `Attr` from Cython to pure Python [#1411](https://github.com/TileDB-Inc/TileDB-Py/pull/1411) + +## Bug Fixes +* Properly handle whitespaces in a query condition [#1398](https://github.com/TileDB-Inc/TileDB-Py/pull/1398) + +# Release 0.18.0 + +## TileDB Embedded updates: +* TileDB-Py 0.18.0 includes TileDB Embedded [TileDB 2.12.0](https://github.com/TileDB-Inc/TileDB/releases/tag/2.12.0) + +## API Changes +* Changes to query conditions [#1341](https://github.com/TileDB-Inc/TileDB-Py/pull/1341) + * Support query conditions on sparse dimensions + * Deprecate `attr_cond` in favor of `cond` + * Deprecate passing `tiledb.QueryCondition` to `cond` in favor of passing string directly +* Add support for `XORFilter` [#1294](https://github.com/TileDB-Inc/TileDB-Py/pull/1294) +* Addition of `Array.delete_fragments`; deprecate `tiledb.delete_fragments` [#1329](https://github.com/TileDB-Inc/TileDB-Py/pull/1329) +* Array and Group metadata now store bytes as `TILEDB_BLOB` [#1384](https://github.com/TileDB-Inc/TileDB-Py/pull/1384) +* Addition of `{Array,Group}.metadata.dump()` [#1384](https://github.com/TileDB-Inc/TileDB-Py/pull/1384) +* Addition of `Group.is_relative` to check if the URI component of a group member is relative [#1386](https://github.com/TileDB-Inc/TileDB-Py/pull/1386) +* Addition of query deletes to delete data that satisifies a given query condition [#1309](https://github.com/TileDB-Inc/TileDB-Py/pull/1309) +* Addition of `FileIO.readinto` [#1389](https://github.com/TileDB-Inc/TileDB-Py/pull/1389) + +## Improvements +* Addition of Utility Function `get_last_ctx_err_str()` for C API [#1351](https://github.com/TileDB-Inc/TileDB-Py/pull/1351) +* Move `Context` and `Config` from Cython to pure Python [#1379](https://github.com/TileDB-Inc/TileDB-Py/pull/1379) + +# TileDB-Py 0.17.6 Release Notes + +## Bug Fixes +* Correct writing empty/null strings to array. `tiledb.main.array_to_buffer` needs to resize data buffer at the end of `convert_unicode`; otherwise, last cell will be store with trailing nulls chars [#1339](https://github.com/TileDB-Inc/TileDB-Py/pull/1339) +* Revert [#1326](https://github.com/TileDB-Inc/TileDB-Py/pull/1326) due to issues with `Context` lifetime with in multiprocess settings [#1372](https://github.com/TileDB-Inc/TileDB-Py/pull/1372) + +# TileDB-Py 0.17.5 Release Notes + +## Improvements +* Move `Attr` from Cython to pure Python [#1326](https://github.com/TileDB-Inc/TileDB-Py/pull/1326) +* Move `Domain` and `Dim` from Cython to pure Python [#1327](https://github.com/TileDB-Inc/TileDB-Py/pull/1327) + +## API Changes +* Permit true-ASCII attributes in non-from-pandas dataframes [#1337](https://github.com/TileDB-Inc/TileDB-Py/pull/1337) +* Addition of `Array.upgrade_version` to upgrade array to latest version [#1334](https://github.com/TileDB-Inc/TileDB-Py/pull/1334) +* Attributes in query conditions no longer need to be passed to `Array.query`'s `attr` arg [#1333](https://github.com/TileDB-Inc/TileDB-Py/pull/1333) +* `ArraySchemaEvolution` checks context's last error for error message [#1335](https://github.com/TileDB-Inc/TileDB-Py/pull/1335) + +# TileDB-Py 0.17.4 Release Notes + +## TileDB Embedded updates: +* TileDB-Py 0.17.4 includes TileDB Embedded [TileDB 2.11.3](https://github.com/TileDB-Inc/TileDB/releases/tag/2.11.3) + +## API Changes +* Addition of `FloatScaleFilter` [#1195](https://github.com/TileDB-Inc/TileDB-Py/pull/1195) +* Addition of `d` mode for arrays to delete data that satisfies a given query condition [#1309](https://github.com/TileDB-Inc/TileDB-Py/pull/1309) + +## Misc Updates +* Wheels are minimally supported for macOS 10.15 Catalina [#1275](https://github.com/TileDB-Inc/TileDB-Py/pull/1275) + +# TileDB-Py 0.17.3 Release Notes + +## TileDB Embedded updates: +* TileDB-Py 0.17.3 includes TileDB Embedded [TileDB 2.11.2](https://github.com/TileDB-Inc/TileDB/releases/tag/2.11.2) + +## API Changes +* Add ability to pass shape tuple to empty_like [#1316](https://github.com/TileDB-Inc/TileDB-Py/pull/1316) +* Support retrieving MBRs of var-sized dimensions [#1311](https://github.com/TileDB-Inc/TileDB-Py/pull/1311) + +## Misc Updates +* Wheels will no longer be supported for macOS 10.15 Catalina; the minimum supported macOS version is now 11 Big Sur [#1300](https://github.com/TileDB-Inc/TileDB-Py/pull/1300) +* Wheels will no longer supported for Python 3.6 [#1300](https://github.com/TileDB-Inc/TileDB-Py/pull/1300) + + +# TileDB-Py 0.17.2 Release Notes + +## TileDB Embedded updates: +* TileDB-Py 0.17.2 includes TileDB Embedded [TileDB 2.11.1](https://github.com/TileDB-Inc/TileDB/releases/tag/2.11.1) + +## Bug Fixes +* Fix issue where querying an array with a Boolean type when `arrow=True`, but is unselected in `.query(attr=...)`, results in an error `pyarrow.lib.ArrowInvalid: Invalid column index to set field.` [#1291](https://github.com/TileDB-Inc/TileDB-Py/pull/1291) +* Use Arrow type fixed-width binary ("w:") for non-variable TILEDB_CHAR [#1286](https://github.com/TileDB-Inc/TileDB-Py/pull/1286) + +# TileDB-Py 0.17.1 Release Notes + +## API Changes +* Support `datetime64` for `QueryCondition` [#1279](https://github.com/TileDB-Inc/TileDB-Py/pull/1279) + +# TileDB-Py 0.17.0 Release Notes + +## TileDB Embedded updates: +* TileDB-Py 0.17.0 includes TileDB Embedded [TileDB 2.11.0](https://github.com/TileDB-Inc/TileDB/releases/tag/2.11.0) + +# TileDB-Py 0.16.5 Release Notes + +## TileDB Embedded updates: +* TileDB-Py 0.16.5 includes TileDB Embedded [TileDB 2.10.4](https://github.com/TileDB-Inc/TileDB/releases/tag/2.10.4) + +# TileDB-Py 0.16.4 Release Notes + +## TileDB Embedded updates: +* TileDB-Py 0.16.4 includes TileDB Embedded [TileDB 2.10.3](https://github.com/TileDB-Inc/TileDB/releases/tag/2.10.3) + +## Improvements +* `setup.py` revert back to retrieving core version by using `ctypes` by parsing `tiledb_version.h`; the tiledb shared object lib now returns back a full path [#1226](https://github.com/TileDB-Inc/TileDB-Py/pull/1226) +* Update minimum required cmake version to =>3.23; required for building `libtiledb` [#1260](https://github.com/TileDB-Inc/TileDB-Py/pull/1260) + +## API Changes +* Addition of `in` operator for `QueryCondition` [#1214](https://github.com/TileDB-Inc/TileDB-Py/pull/1214) +* Revert the regular indexer `[:]` to return entire array rather than nonempty domain in order to maintain NumPy semantics [#1261](https://github.com/TileDB-Inc/TileDB-Py/pull/1261) + +## Bug Fixes +* Deprecate `Filestore.import_uri` in lieu of `Filestore.copy_from` [#1226](https://github.com/TileDB-Inc/TileDB-Py/pull/1226) + +# TileDB-Py 0.16.3 Release Notes + +## Packaging Notes +* This removes `import tkinter` from `test_libtiledb.py` which was preventing the conda package from building properly + +# TileDB-Py 0.16.2 Release Notes + +## TileDB Embedded updates: +* TileDB-Py 0.16.2 includes TileDB Embedded [TileDB 2.10.2](https://github.com/TileDB-Inc/TileDB/releases/tag/2.10.2) + +## Improvements +* `setup.py` retrieves core version by using `ctypes` to call `tiledb_version` rather than parsing `tiledb_version.h` [#1191](https://github.com/TileDB-Inc/TileDB-Py/pull/1191) + +## Bug Fixes +* Set nonempty domain to `(None, None)` for empty string [#1182](https://github.com/TileDB-Inc/TileDB-Py/pull/1182) + +## API Changes +* Support `QueryCondition` for dense arrays [#1198](https://github.com/TileDB-Inc/TileDB-Py/pull/1198) +* Querying dense array with `[:]` returns shape that matches nonempty domain, consistent with `.df[:]` and `.multi_index[:]` [#1199](https://github.com/TileDB-Inc/TileDB-Py/pull/1199) +* Addition of `from_numpy` support for `mode={ingest,schema_only,append}` [#1185](https://github.com/TileDB-Inc/TileDB-Py/pull/1185) + +# TileDB-Py 0.16.1 Release Notes + +## TileDB Embedded updates: +* TileDB-Py 0.16.1 includes TileDB Embedded [TileDB 2.10.1](https://github.com/TileDB-Inc/TileDB/releases/tag/2.10.1) + +# TileDB-Py 0.16.0 Release Notes + +## TileDB Embedded updates: +* TileDB-Py 0.16.0 includes TileDB Embedded [TileDB 2.10.0](https://github.com/TileDB-Inc/TileDB/releases/tag/2.10.0) + +## API Changes +* Addition of `Filestore` API [#1070](https://github.com/TileDB-Inc/TileDB-Py/pull/1070) +* Use `bool` instead of `uint8` for Boolean dtype in `dataframe_.py` [#1154](https://github.com/TileDB-Inc/TileDB-Py/pull/1154) +* Support `QueryCondition` OR operator [#1146](https://github.com/TileDB-Inc/TileDB-Py/pull/1146) + +# TileDB-Py 0.15.6 Release Notes + +## TileDB Embedded updates: +* TileDB-Py 0.15.6 includes TileDB Embedded [TileDB 2.9.5](https://github.com/TileDB-Inc/TileDB/releases/tag/2.9.5) + +# TileDB-Py 0.15.5 Release Notes + +## TileDB Embedded updates: +* TileDB-Py 0.15.5 includes TileDB Embedded [TileDB 2.9.4](https://github.com/TileDB-Inc/TileDB/releases/tag/2.9.4) + +## API Changes +* Support `TILEDB_BLOB` dtype [#1159](https://github.com/TileDB-Inc/TileDB-Py/pull/1159) + +## Bug Fixes +* Fix error where passing a `Context` to `Group` would segfault intermittenly [#1165](https://github.com/TileDB-Inc/TileDB-Py/pull/1165) +* Correct Boolean values when `use_arrow=True` [#1167](https://github.com/TileDB-Inc/TileDB-Py/pull/1167) + +# TileDB-Py 0.15.4 Release Notes + +## Packaging Notes +* Due to a packaging error, the wheels for 0.15.4 should not be used. + +# TileDB-Py 0.15.3 Release Notes + +## TileDB Embedded updates: +* TileDB-Py 0.15.3 includes TileDB Embedded [TileDB 2.9.3](https://github.com/TileDB-Inc/TileDB/releases/tag/2.9.3) + +# TileDB-Py 0.15.2 Release Notes + +## TileDB Embedded updates: +* TileDB-Py 0.15.2 includes TileDB Embedded [TileDB 2.9.2](https://github.com/TileDB-Inc/TileDB/releases/tag/2.9.2) + +## Improvements +* Refactor `MultiRangeIndexer` & `DataFrameIndexer`: addition of ABC `_BaseIndexer` with virtual method `_run_query` and generator `_BaseIndexer.__iter__`; remove `_iter_state`; and fix bugs related to incomplete queries [#1134](https://github.com/TileDB-Inc/TileDB-Py/pull/1134) + +## Bug Fixes +* Fix race condition in `{Dense,Sparse}Array.__new__` [#1096](https://github.com/TileDB-Inc/TileDB-Py/pull/1096) +* Correcting `stats_dump` issues: Python stats now also in JSON form if `json=True`, resolve name mangling of `json` argument and `json` module, and pulling "timer" and "counter" stats from `stats_json_core` for `libtiledb`>=2.3 [#1140](https://github.com/TileDB-Inc/TileDB-Py/pull/1140) + +## API Changes +* Addition of `tiledb.DictionaryFilter` [#1074](https://github.com/TileDB-Inc/TileDB-Py/pull/1074) +* Add support for `Datatype::TILEDB_BOOL` [#1110](https://github.com/TileDB-Inc/TileDB-Py/pull/1110) +* Addition of `Group.__contains__` to check if member with given name is in Group [#1125](https://github.com/TileDB-Inc/TileDB-Py/pull/1125) +* Support with-statement for `Group`s [#1124](https://github.com/TileDB-Inc/TileDB-Py/pull/1124) +* Addition of `keys`, `values`, and `items` to `Group.meta` [#1123](https://github.com/TileDB-Inc/TileDB-Py/pull/1123) +* `Group.member` also returns name if given [#1141](https://github.com/TileDB-Inc/TileDB-Py/pull/1141) + +# TileDB-Py 0.15.1 Release Notes + +## TileDB Embedded updates: +* TileDB-Py 0.15.1 includes TileDB Embedded [TileDB 2.9.1](https://github.com/TileDB-Inc/TileDB/releases/tag/2.9.1) + +# TileDB-Py 0.15.0 Release Notes + +## TileDB Embedded updates: +* TileDB-Py 0.15.0 includes TileDB Embedded [TileDB 2.9.0](https://github.com/TileDB-Inc/TileDB/releases/tag/2.9.0) + +## Misc Updates +* Wheels will no longer be supported for macOS 10.14 Mojave; the minimum supported macOS version is now 10.15 Catalina [#1080](https://github.com/TileDB-Inc/TileDB-Py/pull/1080) + +# TileDB-Py 0.14.5 Release Notes + +## TileDB Embedded updates: +* TileDB-Py 0.14.5 includes TileDB Embedded [TileDB 2.8.3](https://github.com/TileDB-Inc/TileDB/releases/tag/2.8.3) + +# TileDB-Py 0.14.4 Release Notes + +## Misc Updates +* Update `MACOSX_DEPLOYMENT_TARGET` from 10.14 to 10.15 [#1080](https://github.com/TileDB-Inc/TileDB-Py/pull/1080) + +## Bug Fixes +* Correct handling of Arrow cell count with all empty result [#1082](https://github.com/TileDB-Inc/TileDB-Py/pull/1082) + +# TileDB-Py 0.14.3 Release Notes + +## Improvements +* Refactor display of TileDB objects in Jupyter notebooks to be more readable [#1049](https://github.com/TileDB-Inc/TileDB-Py/pull/1049) +* Improve documentation for `Filter`, `FilterList`, `VFS`, `FileIO`, `Group`, and `QueryCondition` [#1043](https://github.com/TileDB-Inc/TileDB-Py/pull/1043), [#1058](https://github.com/TileDB-Inc/TileDB-Py/pull/1058) + +## Bug Fixes +* `Dim.shape` correctly errors out if type is not integer or datetime [#1055](https://github.com/TileDB-Inc/TileDB-Py/pull/1055) +* Correctly check dtypes in `from_pandas` for supported versions of NumPy <1.20 [#1054](https://github.com/TileDB-Inc/TileDB-Py/pull/1054) +* Fix Arrow Table lifetime issues when using`.query(return_arrow=True)` [#1056](https://github.com/TileDB-Inc/TileDB-Py/pull/1056) + +# TileDB-Py 0.14.2 Release Notes + +## TileDB Embedded updates: +* TileDB-Py 0.14.2 includes TileDB Embedded [TileDB 2.8.2](https://github.com/TileDB-Inc/TileDB/releases/tag/2.8.2) + +## Improvements +* Add `Group` and `Object` to docs [#1040](https://github.com/TileDB-Inc/TileDB-Py/pull/1040) + +## Bug Fixes +* Correct `Group.__repr__` to call correct `_dump` function [#1040](https://github.com/TileDB-Inc/TileDB-Py/pull/1040) +* Check type of `ctx` in `from_pandas` and `from_csv` [#1042](https://github.com/TileDB-Inc/TileDB-Py/pull/1042) +* Only allow use of `.df` indexer for `.query(return_arrow=True)`; error out with meaningful error message otherwise [#1045](https://github.com/TileDB-Inc/TileDB-Py/pull/1045) + +# TileDB-Py 0.14.1 Release Notes + +## TileDB Embedded updates: +* TileDB-Py 0.14.1 includes TileDB Embedded [TileDB 2.8.1](https://github.com/TileDB-Inc/TileDB/releases/tag/2.8.1) + +# TileDB-Py 0.14.0 Release Notes + +## TileDB Embedded updates: +* TileDB-Py 0.14.0 includes TileDB Embedded [TileDB 2.8.0](https://github.com/TileDB-Inc/TileDB/releases/tag/2.8.0) + +## API Changes +* Addition of `Group` and `Object` classes to support improved groups [#1022](https://github.com/TileDB-Inc/TileDB-Py/pull/1022) + +# TileDB-Py 0.13.3 Release Notes + +## TileDB Embedded updates: +* The Python 3.10 / manylinux2014 wheels for TileDB-Py 0.13.3 include TileDB Embedded [TileDB 2.7.2](https://github.com/TileDB-Inc/TileDB/releases/tag/2.7.2) built with GCS support + +## Improvements +* Move `VFS`, `FileIO`, and `FileHandle` classes from Cython to Pybind11 [#934](https://github.com/TileDB-Inc/TileDB-Py/pull/934) + +# TileDB-Py 0.13.2 Release Notes + +## TileDB Embedded updates: +* TileDB-Py 0.13.2 includes TileDB Embedded [TileDB 2.7.2](https://github.com/TileDB-Inc/TileDB/releases/tag/2.7.2) + +## Improvements +* Move `FilterList` and `Filter` classes from Cython to Pybind11 [#921](https://github.com/TileDB-Inc/TileDB-Py/pull/921) + +## Bug Fixes +* Fix default validity for write to nullable attribute [#994](https://github.com/TileDB-Inc/TileDB-Py/pull/994) +* Reduce query time for dense var-length arrays by including extra offset element in initial buffer allocation [#1005](https://github.com/TileDB-Inc/TileDB-Py/pull/1005) +* Fix round-trippable repr for dimension tile [#998](https://github.com/TileDB-Inc/TileDB-Py/pull/998) + +## API Changes +* Addition of `ArraySchema.version` to get version of array schema [#949](https://github.com/TileDB-Inc/TileDB-Py/pull/949) +* Deprecate `coords_filters` from `ArraySchema` [#993](https://github.com/TileDB-Inc/TileDB-Py/pull/993) +* Allow setting `ascii` in `column_type` for `from_pandas`/`from_csv` [#999](https://github.com/TileDB-Inc/TileDB-Py/pull/999) + +# TileDB-Py 0.13.1 Release Notes + +## TileDB Embedded updates: +* TileDB-Py 0.13.1 includes TileDB Embedded [TileDB 2.7.1](https://github.com/TileDB-Inc/TileDB/releases/tag/2.7.1) + +# TileDB-Py 0.13.0 Release Notes + +## TileDB Embedded updates: +* TileDB-Py 0.13.0 includes TileDB Embedded [TileDB 2.7.0](https://github.com/TileDB-Inc/TileDB/releases/tag/2.7.0) + +## API Changes +* Deprecate partial vacuuming [#930](https://github.com/TileDB-Inc/TileDB-Py/pull/930) +* Default `from_csv` to use `filter=ZstdFilter()` if not specified for `Attr` or `Dim` [#937](https://github.com/TileDB-Inc/TileDB-Py/pull/937) + +# TileDB-Py 0.12.4 Release Notes + +## TileDB Embedded updates: +* TileDB-Py 0.12.4 includes TileDB Embedded [TileDB 2.6.4](https://github.com/TileDB-Inc/TileDB/releases/tag/2.6.4) + +# TileDB-Py 0.12.3 Release Notes + +## TileDB Embedded updates: +* TileDB-Py 0.12.3 includes TileDB Embedded [TileDB 2.6.3](https://github.com/TileDB-Inc/TileDB/releases/tag/2.6.3) + +## Bug Fixes +* Properly initalize query in order to retrieve estimate results [#920](https://github.com/TileDB-Inc/TileDB-Py/pull/920) +* Enable building with serialization disabled [#924](https://github.com/TileDB-Inc/TileDB-Py/pull/924) +* Do not print out `FragmentInfo_frags` for `repr` [#925](https://github.com/TileDB-Inc/TileDB-Py/pull/925) +* Error out with `IndexError` when attempting to use a step in the regular indexer [#911](https://github.com/TileDB-Inc/TileDB-Py/pull/911) + +# TileDB-Py 0.12.2 Release Notes + +## TileDB Embedded updates: +* TileDB-Py 0.12.2 includes TileDB Embedded [TileDB 2.6.2](https://github.com/TileDB-Inc/TileDB/releases/tag/2.6.2) + +## API Changes +* Addition of `ArraySchema.validity_filters` [#898](https://github.com/TileDB-Inc/TileDB-Py/pull/898) + +# TileDB-Py 0.12.1 Release Notes + +## TileDB Embedded updates: +* TileDB-Py 0.12.1 includes TileDB Embedded [TileDB 2.6.1](https://github.com/TileDB-Inc/TileDB/releases/tag/2.6.1) +## Bug fixes +* Cast 'dim`'s dtype in `Domain` to `str` prior to applying `html.escape` [#883](https://github.com/TileDB-Inc/TileDB-Py/pull/883) +* Support attributes with spaces in `QueryCondition` by casting with attr(); values may be casted with val() [#886](https://github.com/TileDB-Inc/TileDB-Py/pull/886) + +# TileDB-Py 0.12.0 Release Notes + +## TileDB Embedded updates: +* TileDB-Py 0.12.0 includes TileDB Embedded [TileDB 2.6.0](https://github.com/TileDB-Inc/TileDB/releases/tag/2.6.0) + +## API Changes +* Allow writing to dimension-only array (zero attributes) by using assignment to `None`, for example: `A[coords] = None` (given `A: tiledb.Array`) [#854](https://github.com/TileDB-Inc/TileDB-Py/pull/854) +* Remove repeating header names for `attr` when displaying `ArraySchema` in Jupyter Notebooks [#856](https://github.com/TileDB-Inc/TileDB-Py/pull/856) +* `tiledb.VFS.open` returns `FileIO` object; no longer returns `FileHandle` [#802](https://github.com/TileDB-Inc/TileDB-Py/pull/802) +* Addition of `tiledb.copy_fragments_to_existing_array` [#864](https://github.com/TileDB-Inc/TileDB-Py/pull/864) + +## Bug fixes +* HTML escape strings for `Dim` and `Attr`'s `name` and `dtype` [#856](https://github.com/TileDB-Inc/TileDB-Py/pull/856) +* Fix attribute view for multi-indexer [#866](https://github.com/TileDB-Inc/TileDB-Py/pull/866) + +## Improvements +* Metadata-related API calls are now 'nogil' [#867](https://github.com/TileDB-Inc/TileDB-Py/pull/867) + +# TileDB-Py 0.11.5 Release Notes + +* Added missing dependency on [`packaging`](https://pypi.org/project/packaging/) in requirements.txt [#852](https://github.com/TileDB-Inc/TileDB-Py/pull/852) + +# TileDB-Py 0.11.4 Release Notes + +## TileDB Embedded updates: +* TileDB-Py 0.11.4 includes TileDB Embedded [TileDB 2.5.3](https://github.com/TileDB-Inc/TileDB/releases/tag/2.5.3) + +## API Changes +* Add rich display for TileDB objects in Jupyter notebooks [#824](https://github.com/TileDB-Inc/TileDB-Py/pull/824) +* Support `TILEDB_STRING_ASCII` for array metadata [#828](https://github.com/TileDB-Inc/TileDB-Py/pull/828) + +# TileDB-Py 0.11.3 Release Notes + +## Impovements +* Support for Python 3.10 [#808](https://github.com/TileDB-Inc/TileDB-Py/pull/808) + +## API Changes +* Addition of `tiledb.version()` to return version as a tuple [#801](https://github.com/TileDB-Inc/TileDB-Py/pull/801) +* `Query.get_stats` and `Ctx.get_stats` changed function signature; automatically `print_out` stats and add option to output as `json` [#809](https://github.com/TileDB-Inc/TileDB-Py/pull/809) + +## Bug fixes +* `tiledb.delete_fragments` removes unused schemas [#813](https://github.com/TileDB-Inc/TileDB-Py/pull/813) + +# TileDB-Py 0.11.2 Release Notes + +## TileDB Embedded updates: +* TileDB-Py 0.11.2 includes TileDB Embedded [TileDB 2.5.2](https://github.com/TileDB-Inc/TileDB/releases/tag/2.5.2) + +## Bug fixes +* Support dict parameter for 'config' argument to VFS constructor [#805](https://github.com/TileDB-Inc/TileDB-Py/pull/805) + +# TileDB-Py 0.11.1 Release Notes + +## TileDB Embedded updates: +* TileDB-Py 0.11.1 includes TileDB Embedded [TileDB 2.5.1](https://github.com/TileDB-Inc/TileDB/releases/tag/2.5.1) + +## Bug fixes +* Support dict parameter for 'config' argument to VFS constructor [#805](https://github.com/TileDB-Inc/TileDB-Py/pull/805) +* Correct libtiledb version checking for Fragment Info API getters' MBRs and array schema name [#784](https://github.com/TileDB-Inc/TileDB-Py/pull/784) + +# TileDB-Py 0.11.0 Release Notes + +## TileDB Embedded updates: +* TileDB-Py 0.11.0 includes TileDB Embedded [TileDB 2.5.0](https://github.com/TileDB-Inc/TileDB/releases/tag/2.5.0) + +## API Changes +* Addition of MBRs to `FragmentInfo` API [#760](https://github.com/TileDB-Inc/TileDB-Py/pull/760) +* Addition of `array_schema_name` to `FragmentInfo` API [#777](https://github.com/TileDB-Inc/TileDB-Py/pull/777) +* Addition of `tiledb.create_array_from_fragments` to copy fragments within a given timestamp range to a new array [#777](https://github.com/TileDB-Inc/TileDB-Py/pull/777) + +# TileDB-Py 0.10.5 Release Notes + +## API Changes +* Addition of `tiledb.delete_fragments` to remove fragments within a given timestamp range [#774](https://github.com/TileDB-Inc/TileDB-Py/pull/774) + +# TileDB-Py 0.10.4 Release Notes + +## TileDB Embedded updates: +* TileDB-Py 0.10.4 includes TileDB Embedded [TileDB 2.4.3](https://github.com/TileDB-Inc/TileDB/releases/tag/2.4.3) + +## Bug fixes +* Error out when applying `QueryCondition` to dense arrays; this feature will be implemented in TileDB Embedded 2.5 [#753](https://github.com/TileDB-Inc/TileDB-Py/pull/753) +* Ensure that indexer, multi-indexer, and .df return the same results when applying `QueryCondition` [#753](https://github.com/TileDB-Inc/TileDB-Py/pull/753) +* Fix error when using .df with PyArrow 6 due to incorrect metadata field in exported schema [#764](https://github.com/TileDB-Inc/TileDB-Py/pull/764) +* Fix [#755](https://github.com/TileDB-Inc/TileDB-Py/issues/755): `from_pandas` to correctly round-trip unnamed Index [#761](https://github.com/TileDB-Inc/TileDB-Py/pull/761) +* Fix .df indexer bug with empty result set [#744](https://github.com/TileDB-Inc/TileDB-Py/pull/744) + +## API Changes +* Close the `PyFragmentInfo` object in the `FragmentInfoList` constructor to reflect changes in the `FragmentInfo` API in TileDB Embedded 2.5 [#752](https://github.com/TileDB-Inc/TileDB-Py/pull/752) +* Make `ctx` argument optional for `ArraySchemaEvolution` [#743](https://github.com/TileDB-Inc/TileDB-Py/pull/743) +* Remove `coords_filters` from `ArraySchema` for dense arrays [#762](https://github.com/TileDB-Inc/TileDB-Py/pull/762) + +# TileDB-Py 0.10.3 Release Notes + +## TileDB Embedded updates: +* TileDB-Py 0.10.3 includes TileDB Embedded [TileDB 2.4.2](https://github.com/TileDB-Inc/TileDB/releases/tag/2.4.2) + - Note that 2.4.1 was skipped due to accidental tagging of the 2.4.1 git tag during CI testing + +## API Changes +* Addition of `overwrite` parameter to `Array.create` [#713](https://github.com/TileDB-Inc/TileDB-Py/pull/713) +* Addition of `"ascii"` dtype for `Dim`s [#720](https://github.com/TileDB-Inc/TileDB-Py/pull/720) + +## Bug fixes +* Pass `Ctx` to `ArraySchema.load` in `from_pandas` [#709](https://github.com/TileDB-Inc/TileDB-Py/pull/709) +* Give clear error message when attempting to apply `QueryCondition` on dimensions [#722](https://github.com/TileDB-Inc/TileDB-Py/pull/722) +* Do not add string range when querying empty array [#721](https://github.com/TileDB-Inc/TileDB-Py/pull/721) + +## Improvements +* String dimension default fix in core [#2436](https://github.com/TileDB-Inc/TileDB/pull/2436) reverts a previous change in which the nonempty domain was passed the to multi-range indexer if unspecified [#712](https://github.com/TileDB-Inc/TileDB-Py/pull/712) + +# TileDB-Py 0.10.2 Release Notes + +## API Changes +* Deprecate sparse writes to dense arrays [#681](https://github.com/TileDB-Inc/TileDB-Py/pull/681) +* Addition of `Attr.isascii` [#681](https://github.com/TileDB-Inc/TileDB-Py/pull/681) +* Addition of `Ctx.get_stats` and `Query.get_stats` [#698](https://github.com/TileDB-Inc/TileDB-Py/pull/698) + +## Improvements +* Added support for `timestamp` argument in `tiledb.from_numpy` [#699](https://github.com/TileDB-Inc/TileDB-Py/pull/699) + +# TileDB-Py 0.10.1 Release Notes + +## API Changes +* Do not require `domain=(None, None)` for string dimensions [#662](https://github.com/TileDB-Inc/TileDB-Py/pull/662) + +## Improvements +* Print a warning about ContextVar bug when running under ipykernel < 6.0. [#665](https://github.com/TileDB-Inc/TileDB-Py/pull/665) + Please see https://github.com/TileDB-Inc/TileDB-Py/issues/667 for more information. +* `tiledb.Dim` representation now displays `var=True` for dimensions with `bytes` datatype, consistent with `tiledb.Attr` [#669](https://github.com/TileDB-Inc/TileDB-Py/pull/669) + +## Bug fixes +* Fix concurrent use of `Array.multi_index` and `.df` by using new instance for each invocation [#672](https://github.com/TileDB-Inc/TileDB-Py/pull/672) +* For attributes, if `var=False` but the bytestring is fixed-width or if `var=True` but the bytestring is variable length, error out [#663](https://github.com/TileDB-Inc/TileDB-Py/pull/663) + +# TileDB-Py 0.10.0 Release Notes + +## TileDB Embedded updates: +* TileDB-Py 0.10.0 includes TileDB Embedded [TileDB 2.4.0](https://github.com/TileDB-Inc/TileDB/releases/tag/2.4.0) with a number of + new features and improvements, including: + - new platform support: Apple M1 + - support for ArraySchema evolution (adding and removing attributes) + - support for Azure SAS (shared access signature) tokens + +## API Changes +* When using `Array.multi_index`, an empty result is returned if the nonempty domain is empty [#656](https://github.com/TileDB-Inc/TileDB-Py/pull/656) +* Addition of `Array.set_query` to read array using a serialized query [#651](https://github.com/TileDB-Inc/TileDB-Py/pull/651) + +## Improvements +* Support numeric column names in `from_pandas` by casting to str dtype [#652](https://github.com/TileDB-Inc/TileDB-Py/pull/652) +* New `tiledb.ArraySchemaEvolution` API to add and drop attributes from an existing array [#657](https://github.com/TileDB-Inc/TileDB-Py/pull/657) + +## Bug Fixes +* Correct listing of consolidated fragments to vacuum in the Fragment Info API by deprecating `FragmentInfoList.to_vacuum_uri`, `FragmentInfoList.to_vacuum_num`, `FragmentInfo.to_vacuum_uri`, and `FragmentInfo.to_vacuum_num` and replacing with `FragmentInfoList.to_vacuum` [#650](https://github.com/TileDB-Inc/TileDB-Py/pull/650) +* Correct issue where appending `None` to `FilterList` causes segfault by checking the `filter` argument [#653](https://github.com/TileDB-Inc/TileDB-Py/pull/653) + +# TileDB-Py 0.9.5 Release Notes + +## TileDB Embedded updates: +* TileDB-Py 0.9.5 includes TileDB Embedded [TileDB 2.3.3](https://github.com/TileDB-Inc/TileDB/releases/tag/2.3.3) + +## Improvements +* Consolidate `_nonempty_domain_var` into `nonempty_domain` [#632](https://github.com/TileDB-Inc/TileDB-Py/pull/632) +* Support more valid Python syntax for `QueryCondition` statements [#636](https://github.com/TileDB-Inc/TileDB-Py/pull/636) +* Addition of `ascii` dtype to `Attr` allows `QueryCondition` to support var-length strings [#637](https://github.com/TileDB-Inc/TileDB-Py/pull/637) + +# TileDB-Py 0.9.4 Release Notes + +## Improvements +* Support pickling for arrays in write-mode [#626](https://github.com/TileDB-Inc/TileDB-Py/pull/626) + +## Bug Fixes +* Fixed multi-range indexer to default to explicitly pass in the non-empty domain if dimensions are unspecified [#630](https://github.com/TileDB-Inc/TileDB-Py/pull/630) + +# TileDB-Py 0.9.3 Release Notes + +## Packaging Notes +* Due to a packaging issue released with 0.9.3 (NumPy ABI compatibility with NumPy < 1.20 for Python 3.8), this section is intentionally left blank. + +# TileDB-Py 0.9.2 Release Notes + +## Packaging Notes +* Fixed release builder ordering issue which led to CRLF line endings in 0.9.1 source distribution. + +## API Changes +* Deprecate `Array.timestamp` and replace with `Array.timestamp_range` [#616](https://github.com/TileDB-Inc/TileDB-Py/pull/616) + +## Improvements +* Set `ArraySchema.tile_order=None` for Hilbert-ordered arrays [#609](https://github.com/TileDB-Inc/TileDB-Py/pull/609) +* Use CIBW to build release wheels on Linux [#613](https://github.com/TileDB-Inc/TileDB-Py/pull/613) +* Addition of Pickling functionality for `SparseArray` [#618](https://github.com/TileDB-Inc/TileDB-Py/pull/618) + +# TileDB-Py 0.9.1 Release Notes + +## TileDB Embedded updates: +* TileDB-Py 0.9.1 includes TileDB Embedded [TileDB 2.3.1](https://github.com/TileDB-Inc/TileDB/releases/tag/2.3.1) + +## Improvements +* Support passing a timestamp range for consolidation and vacuuming [#603](https://github.com/TileDB-Inc/TileDB-Py/pull/603) + +## Bug Fixes +* FragmentInfo API's to_vacuum_uri() function corrected to iterate through `to_vacuum_num` rather than `fragment_num`[#603](https://github.com/TileDB-Inc/TileDB-Py/pull/603) +* Return "NA" For ArraySchema.tile_order if "Hilbert" [#605](https://github.com/TileDB-Inc/TileDB-Py/pull/605) + +# TileDB-Py 0.9.0 Release Notes + +## TileDB Embedded updates: +* TileDB-Py 0.9.0 includes TileDB Embedded [TileDB 2.3](https://github.com/TileDB-Inc/TileDB/releases/tag/2.3) with a significant + number of new features and improvements. + +## Packaging Notes +* Windows wheels are now built with TileDB Cloud REST support enabled [#541](https://github.com/TileDB-Inc/TileDB-Py/pull/541) + +## Improvements +* Addition of `QueryCondition` API to filter query on attributes [#576](https://github.com/TileDB-Inc/TileDB-Py/pull/576) + +## Bug Fixes +* Fixed `from_pandas` append error for sparse arrayse: no need to specify 'row_start_idx' [#593](https://github.com/TileDB-Inc/TileDB-Py/pull/593) +* Fixed 'index_dims' kwarg handling for `from_pandas` [#590](https://github.com/TileDB-Inc/TileDB-Py/pull/590) + +## API Changes +* `from_dataframe` function has been removed; deprecated in TileDB-Py 0.6 and replaced by `from_pandas`. + +--- + +# TileDB-Py 0.8.11 Release Notes + +## Bug fixes +* Fixed incorrect NumPy ABI target in Linux wheels [#590](https://github.com/TileDB-Inc/TileDB-Py/pull/590) +* QueryCondition API will cast condition values to the datatype of the corresponding attribute [#589](https://github.com/TileDB-Inc/TileDB-Py/pull/589) +* QueryCondition API errors out when there are mismatched attributes to `query`'s `attr_cond` and `attrs` arguments [#589](https://github.com/TileDB-Inc/TileDB-Py/pull/589) +* QueryCondition API can now parse negative numbers [#589](https://github.com/TileDB-Inc/TileDB-Py/pull/589) + + +# TileDB-Py 0.8.10 Release Notes + +## Improvements +* Disabled libtiledb Werror compilation argument for from-source builds via setup.py [#574](https://github.com/TileDB-Inc/TileDB-Py/pull/574) +* Relaxed NumPy version requirements for from-source builds via setup.py [#575](https://github.com/TileDB-Inc/TileDB-Py/pull/575) + +## Bug fixes +* Fixed FragmentInfoList where context was not being passed to ArraySchema [#573](https://github.com/TileDB-Inc/TileDB-Py/pull/573) + * Fixed FragmentInfoList where context was not being passed to ArraySchema [#578](https://github.com/TileDB-Inc/TileDB-Py/pull/578) +* Fixed read bug due to large estimated result size [#579](https://github.com/TileDB-Inc/TileDB-Py/pull/579) +* Fixed bug reading nullable attributes due to missing buffer resize [#581](https://github.com/TileDB-Inc/TileDB-Py/pull/581) +* Fixed Python output for `tiledb.stats_dump` [#586](https://github.com/TileDB-Inc/TileDB-Py/pull/586) + +# TileDB-Py 0.8.9 Release Notes + +## TileDB Embedded updates: +* TileDB-Py 0.8.9 includes TileDB Embedded [TileDB 2.2.9](https://github.com/TileDB-Inc/TileDB/releases/tag/2.2.9) + +## Improvements +* Support for iterating over incomplete query results [#548](https://github.com/TileDB-Inc/TileDB-Py/pull/548) + - This feature provides the capability to consume partial query results with a fixed maximum buffer size + rather than the the default behavior of resizing buffers and resubmitting to completion. + Usage example: `examples/incomplete_iteration.py` + (along with test in: `test_libtiledb.py:test_incomplete_return`) +* Rename FragmentsInfo to FragmentInfoList [#551](https://github.com/TileDB-Inc/TileDB-Py/pull/551) +* Dataframe creation uses Zstd default compression level (-1) [#552](https://github.com/TileDB-Inc/TileDB-Py/pull/552) +* Rename Fragment Info API's `non_empty_domain` attribute to `nonempty_domain` [#553](https://github.com/TileDB-Inc/TileDB-Py/pull/553) +* Added configuration option `py.alloc_max_bytes` to control maximum initial buffer allocation [#557](https://github.com/TileDB-Inc/TileDB-Py/pull/557) + +## Bug fixes +* Fixed incorrected error raised in .df[] indexer when pyarrow not installed [#554](https://github.com/TileDB-Inc/TileDB-Py/pull/554) +* Fixed `from_pandas(attr_filters=None, dim_filters=None)` (previously used internal defaults) [#564](https://github.com/TileDB-Inc/TileDB-Py/pull/554) +* Fixed `from_pandas` write bug due to incorrect classification of str/bytes columns [#562](https://github.com/TileDB-Inc/TileDB-Py/pull/562) +* Fix segfault due to mismatched validity num and data buffer sizes [#567](https://github.com/TileDB-Inc/TileDB-Py/pull/567) + +# TileDB-Py 0.8.8 Release Notes + +## TileDB Embedded updates: +* TileDB-Py 0.8.8 includes TileDB Embedded [TileDB 2.2.8](https://github.com/TileDB-Inc/TileDB/releases/tag/2.2.8) + +# TileDB-Py 0.8.7 Release Notes + +## Improvements +* ArraySchema support for `cell_order="hilbert"` [#535](https://github.com/TileDB-Inc/TileDB-Py/pull/535) + +## Bug fixes +* Fixed regression in `from_pandas` with string-valued index dimensions [#526](https://github.com/TileDB-Inc/TileDB-Py/pull/526) +* Fixed GC lifetime bug in string buffer conversion [#525](https://github.com/TileDB-Inc/TileDB-Py/pull/526) +* Fixed `FilterList`'s `repr()` method [#528](https://github.com/TileDB-Inc/TileDB-Py/pull/528) + +# TileDB-Py 0.8.6 Release Notes + +## TileDB Embedded updates: +* TileDB-Py 0.8.6 includes TileDB Embedded [TileDB 2.2.7](https://github.com/TileDB-Inc/TileDB/releases/tag/2.2.7) + +## Improvements +* Addition of `VFS()` functions `copy_file()` and `copy_dir()` [#507](https://github.com/TileDB-Inc/TileDB-Py/pull/507) +* Add support in `from_pandas` for storing Pandas extension types as variable-length attributes [#515](https://github.com/TileDB-Inc/TileDB-Py/pull/515) +* Add support for sparse writes to dense arrays [#521](https://github.com/TileDB-Inc/TileDB-Py/pull/521) + +## Bug fixes +* Multi-length attributes, regardless of fixed or var-length, do not work query properly with PyArrow enabled due to lack of Arrow List support. When using `.df[]` with PyArrow enabled, we are returning a clear message to the user to use `query(use_pyarrow=False)` [#513](https://github.com/TileDB-Inc/TileDB-Py/pull/513) + +# TileDB-Py 0.8.5 Release Notes + +## TileDB Embedded updates: +* TileDB-Py 0.8.5 includes TileDB Embedded [TileDB 2.2.6](https://github.com/TileDB-Inc/TileDB/releases/tag/2.2.6) + +## Documentation Updates +* Added example reading/writing RGB (multi-component) array [#487](https://github.com/TileDB-Inc/TileDB-Py/pull/487) + +## Improvements +* Restore `tiledb.stats_dump` default to `verbose=True` [#491](https://github.com/TileDB-Inc/TileDB-Py/pull/491) +* Remove `non_empty_domain_var()` Fragment Info PyBind11 Function and only use `get_non_empty_domain()` for both fixed and var-length domains [#505](https://github.com/TileDB-Inc/TileDB-Py/pull/505) + +# TileDB-Py 0.8.4 Release Notes + +## Improvements +* Addition of high-level function `array_fragments()` that returns a `FragmentsInfo` object [#488](https://github.com/TileDB-Inc/TileDB-Py/pull/488) +* Added support for `from_pandas`/`df[]` round-trip of Pandas nullable integer and bool types [#480](https://github.com/TileDB-Inc/TileDB-Py/pull/480) +* Fragment info API example usage now provided at `examples/fragment_info.py` [#479](https://github.com/TileDB-Inc/TileDB-Py/pull/479) +* Fragment info API parameters have been rearranged to match the rest of the TileDB Python API such that the `uri` is provided first and `context`, an optional parameter that defaults to `tiledb.default_ctx()`, is provided second [#479](https://github.com/TileDB-Inc/TileDB-Py/pull/479) + +## Bug fixes +* Fix bug in `Attr` to ensure that all Unicode strings are automatically set to `var=True` [#495]https://github.com/TileDB-Inc/TileDB-Py/pull/495 +* Fix bug in Array.multi_index slicing bug for sparse array with dimension range including 0 [#482](https://github.com/TileDB-Inc/TileDB-Py/pull/482) + +# TileDB-Py 0.8.3 Release Notes + +## TileDB Embedded updates: +* TileDB-Py 0.8.3 includes TileDB Embedded [TileDB 2.2.4](https://github.com/TileDB-Inc/TileDB/releases/tag/2.2.4) + +## Improvements +* Added `nullable` keyword argument to `Attr` constructor [#474](https://github.com/TileDB-Inc/TileDB-Py/pull/474) + +## Bug fixes +* Fix bug in Array.multi_index with slice range including 0 (incorrectly used the nonempty domain as endpoint) [#473](https://github.com/TileDB-Inc/TileDB-Py/pull/473) + +# TileDB-Py 0.8.2 Release Notes + +## Packaging Notes +* This is a version bump to fix numpy compatibility pinning in the wheel build system. + +# TileDB-Py 0.8.1 Release Notes + +## TileDB Embedded updates: +* TileDB-Py 0.8.1 includes TileDB Embedded [TileDB 2.2.3](https://github.com/TileDB-Inc/TileDB/releases/tag/2.2.3) + +## Packaging Notes +* TileDB-Py 0.8 does not support Python 2. + +# TileDB-Py 0.8.0 Release Notes + +## TileDB Embedded updates: +* TileDB-Py 0.8.0 includes TileDB Embedded 2.2.2 featuring a number of significant + improvements in core storage engine functionality. See release notes for + [TileDB 2.2.1](https://github.com/TileDB-Inc/TileDB/releases/tag/2.2.1) and + [TileDB 2.2.2](https://github.com/TileDB-Inc/TileDB/releases/tag/2.2.2). + +## Packaging Notes +* TileDB-Py 0.8 does not support Python 2. + +## Improvements +* Add initial `tiledb.from_parquet` functionality (beta) [[a90d5d9b1b](https://github.com/TileDB-Inc/TileDB-Py/commit/a90d5d9b1b6a39b48090592297fe98a7f33338fb)] +* Preload metadata in .df query path to reduce read latency for remote arrays [[79ab12fcf0](https://github.com/TileDB-Inc/TileDB-Py/commit/79ab12fcf0ede0cbac822392a30ee7640595e93c)] + +## Bug fixes +* Update py::dtype usage for compatibility with pybind11 2.6.2 [[9d3d3d3c43](https://github.com/TileDB-Inc/TileDB-Py/commit/9d3d3d3c430fbc058d04773f03ddc63bd47f79e3)] + +# TileDB-Py 0.7.7 Release Notes + +## Bug fixes +* Cherry-pick commit 9d3d3d3c43 to ix runtime bug in conda packages built against pybind11 2.6.2 [9d3d3d3c430f](https://github.com/TileDB-Inc/TileDB-Py/commit/9d3d3d3c430fbc058d04773f03ddc63bd47f79e3) + +# TileDB-Py 0.7.6 Release Notes + +## Packaging Notes +* TileDB-Py 0.7.x will be the last version of TileDB-Py supporting Python 2. + +## Bug fixes +* Fix read compatibility for empty strings written with 2.1 or 2.2 [#462](https://github.com/TileDB-Inc/TileDB-Py/pull/462) +* Fix #457: make sure to fit automatic tile extent to dim range for date type [#464](https://github.com/TileDB-Inc/TileDB-Py/pull/464) + +# TileDB-Py 0.7.5 Release Notes + +## Packaging Notes +* TileDB-Py 0.7.x will be the last version of TileDB-Py supporting Python 2. + +## TileDB Embedded updates: +* TileDB-Py 0.7.5 includes [TileDB Embedded 2.1.6](https://github.com/TileDB-Inc/TileDB/releases/tag/2.1.6) + +## Improvements +* FragmentInfo API by default returns information from all fragments and dimensions [#444](https://github.com/TileDB-Inc/TileDB-Py/pull/444) +* Add integer multi-indexing for NumPy datetime64 dimensions [#447](https://github.com/TileDB-Inc/TileDB-Py/pull/447) +* Add `from_csv/pandas` support for `timestamp` keyword argument to specify write timestamp [#450](https://github.com/TileDB-Inc/TileDB-Py/pull/450) +* Add verbosity option to `stats_dump()` [#452](https://github.com/TileDB-Inc/TileDB-Py/pull/452) +* Add `unique_dim_values()` to return unique dimension values for a given `SparseArray` [#454](https://github.com/TileDB-Inc/TileDB-Py/pull/454) +* Add support to `query()` for returning subsets of specified dimensions [#458](https://github.com/TileDB-Inc/TileDB-Py/pull/458) +* Optimize string array writes [#459](https://github.com/TileDB-Inc/TileDB-Py/pull/459) + +## Bug fixes +* Fix `Dim.shape` for dense array with datetime dimension [#448](https://github.com/TileDB-Inc/TileDB-Py/pull/448) + +# TileDB-Py 0.7.4 Release Notes + +## Improvements +* Support selecting subset of dimensions in Array.query via new keyword argument `dims: List[String]`. The `coords=True` kwarg is still supported for compatibility, and continues to return all dimensions [#433](https://github.com/TileDB-Inc/TileDB-Py/pull/433) +* Support Dim(filters=FilterList) keyword argument to set filters on a per-Dim basis [#434](https://github.com/TileDB-Inc/TileDB-Py/pull/434) +* Support tiledb.from_csv setting attribute and dimension filters by dictionary of {name: filter} [#434](https://github.com/TileDB-Inc/TileDB-Py/pull/434) +* Add ArraySchema.check wrapping `tiledb_array_schema_check` [#435](https://github.com/TileDB-Inc/TileDB-Py/pull/435) +* Add support for attribute fill values `tiledb.Attr(fill=...)` and `Attr.fill` getter [#437](https://github.com/TileDB-Inc/TileDB-Py/pull/437) + +## API Changes +* tiledb.from_csv keyword arg `attrs_filters` renamed to `attr_filters` [#434](https://github.com/TileDB-Inc/TileDB-Py/pull/434) + +## Bug fixes +* Fix bug in `multi_index` slicing of dense arrays [#438](https://github.com/TileDB-Inc/TileDB-Py/pull/438) + +# TileDB-Py 0.7.3 Release Notes + +## Improvements +* The default result layout for indexing/querying sparse arrays is now TILEDB_UNORDERED [#428](https://github.com/TileDB-Inc/TileDB-Py/pull/428), [#431](https://github.com/TileDB-Inc/TileDB-Py/pull/431) +* Added documentation for all TileDB-Py configuration parameters [#430](https://github.com/TileDB-Inc/TileDB-Py/pull/430) +* Fixed documentation rendering for `Array.query` [#430](https://github.com/TileDB-Inc/TileDB-Py/pull/430) + +## Bug fixes +* Fix sparse dimension type selection when array type is not specified to from_pandas [#429](https://github.com/TileDB-Inc/TileDB-Py/pull/429) +* Don't pass allows_duplicates=True to dense array constructor (tiledb.from_csv) [#428](https://github.com/TileDB-Inc/TileDB-Py/pull/428) + +# TileDB-Py 0.7.2 Release Notes + +## TileDB Embedded updates: +* TileDB-Py 0.7.2 includes [TileDB Embedded 2.1.3](https://github.com/TileDB-Inc/TileDB/releases/tag/2.1.3) + Including a fix for issue [#409](https://github.com/TileDB-Inc/TileDB-Py/issues/409). + +## Changes +* The default array type for `from_pandas` and `from_csv` is now dense, if unspecified, except when passing a dataframe with string indexes to `from_pandas` [#424](https://github.com/TileDB-Inc/TileDB-Py/pull/408) + +## Improvements +* Automatically determine column to dimension mapping for `tiledb.from_csv` append mode [#408](https://github.com/TileDB-Inc/TileDB-Py/pull/408) + +## Bug fixes +* Fixed `tiledb.from_csv/dataframe` error when ingesting single-row/index datasets [#422]() +* Fixed intermittent `csv_sparse_col_to_dims` failure due to duplicate result ordering [#423](https://github.com/TileDB-Inc/TileDB-Py/pull/423) + +# TileDB-Py 0.7.1 Release Notes + +## Improvements +* Added support for `df[]` indexing via `tiledb.Array.query` [#411](https://github.com/TileDB-Inc/TileDB-Py/pull/411) +* Modified `stats_dump` to return internal stats as string, allowing for output in Jupyter notebooks [#403](https://github.com/TileDB-Inc/TileDB-Py/pull/403) +* Added `__repr__` to `Array` and `Ctx` [#413](https://github.com/TileDB-Inc/TileDB-Py/pull/413) +* `tiledb.open` now supports `timestamp` keyword argument [#419](https://github.com/TileDB-Inc/TileDB-Py/pull/419) +* `tiledb.Domain` now supports passing a list of `Dim`s without unpacking [#419](https://github.com/TileDB-Inc/TileDB-Py/pull/419) + +## Bug fixes +* Fixed PyPI wheels load error on newer macOS due to overlinkage against system libraries in build process (curl -> libintl) [#418](https://github.com/TileDB-Inc/TileDB-Py/pull/418) +* Fixed PyPI wheels load error on Windows due to building against TBB [#419](https://github.com/TileDB-Inc/TileDB-Py/pull/419) +* Fixed indexing of attribute named 'coords' [#414](https://github.com/TileDB-Inc/TileDB-Py/pull/414) +* `open_dataframe` now uses the underlying Array's `nonempty_domain` to avoid errors opening unlimited domain arrays [#409](https://github.com/TileDB-Inc/TileDB-Py/pull/409) + +# TileDB-Py 0.7.0 Release Notes + +## TileDB Embedded updates: +* TileDB-Py 0.7.0 includes [TileDB Embedded 2.1.2](https://github.com/TileDB-Inc/TileDB/releases/tag/2.1.2) + featuring a number of significant improvements, with major highlights including: + - no longer uses Intel TBB for parallelization by default. Along with many benefits to TileDB Embedded, this + significantly reduces complications and bugs with python multiprocessing fork mode. + - Support coalescing subarray ranges to give major performance boosts. + +## Packaging Notes +* TileDB-Py 0.7 packages on PyPI support macOS 10.13+ and manylinux10-compatible Linux distributions only. + For now, wheels could be produced supporting older systems but without Google Cloud Support; if needed, + please contact us to discuss. + +## Improvements +* Added ".df[]" indexer tiledb.Array: directly returns a Pandas dataframe from a query (uses `multi_index` indexing behavior) [#390](https://github.com/TileDB-Inc/TileDB-Py/pull/389) +* Added parallel CSV ingestion example using Python multiprocessing with `tiledb.from_csv` [#397](https://github.com/TileDB-Inc/TileDB-Py/pull/397) +* Added wrapping and support for TileDB checksumming filters: `ChecksumMD5Filter` and `ChecksumSHA256Filter` [#389](https://github.com/TileDB-Inc/TileDB-Py/pull/389) +* Removed TBB install from default setup.py, corresponding to TileDB Embedded changes [#389](https://github.com/TileDB-Inc/TileDB-Py/pull/389) +* Add support for 'capacity' kwarg to `from_csv`/`from_pandas` [#391](https://github.com/TileDB-Inc/TileDB-Py/pull/391) +* Add support for 'tile' kwarg to `from_csv`/`from_pandas` to customize Dim tile extent [#391](https://github.com/TileDB-Inc/TileDB-Py/pull/391) +* Added '--release-symbols' option for building in release optimization with debug symbols [#402](https://github.com/TileDB-Inc/TileDB-Py/pull/402) +* Changed `allows_duplicates` default to `True` for `from_csv/from_pandas` [#394](https://github.com/TileDB-Inc/TileDB-Py/pull/394) + +## Bug fixes +* Fixed bug indexing anonymous attributes of sparse arrays using `A[]` (did not affect dense or multi_index) [#404](https://github.com/TileDB-Inc/TileDB-Py/pull/404) +* Fixed rendering of column name in mixed dtype exception [#382](https://github.com/TileDB-Inc/TileDB-Py/pull/382) +* Fixed forwarding of 'ctx' kwarg to from_csv/from_pandas [#383](https://github.com/TileDB-Inc/TileDB-Py/pull/383) +* Fixed type of return values for empty results when indexing a sparse array [#384](https://github.com/TileDB-Inc/TileDB-Py/pull/384) + +## Misc Updates +* Added round-trip tests for all filter `repr` objects [#389](https://github.com/TileDB-Inc/TileDB-Py/pull/389) + +# TileDB-Py 0.6.6 Release Notes + +**Note that we will be removing wheel support for macOS 10.9-10.12 in TileDB-Py 0.7 (planned for release in August 2020).** This change is due to upstream (AWS SDK) minimum version requirements. The minimum supported version for macOS wheels on PyPI will be macOS 10.13. + +**Note that we will be removing support for [manylinux1](https://github.com/pypa/manylinux/tree/manylinux1) wheels in TileDB-Py 0.7 (planned for release in August 2020).** manylinux1 is based on CentOS5, which has been unsupported for several years. We now provide wheels built with [manylinux2010](https://www.python.org/dev/peps/pep-0571/), which is based on CentOS6 / glibc 2.12. + +## Improvements +* Bump release target to [TileDB 2.0.7](https://github.com/TileDB-Inc/TileDB/releases/tag/2.0.7) + +# TileDB-Py 0.6.5 Release Notes + +We have added manylinux2010 wheels, corresponding to CentOS6 / glibc 2.12. + +We are deprecating support for manylinux1 (CentOS5 / glibc 2.0.7), which is not supported by +the Google Cloud Storage SDK. We are planning to remove manylinux1 wheel support in the +TileDB-Py 0.7 release. + + +## Improvements +* Enabled Google Cloud Storage support in macOS and linux (manylinux2010) wheels on PyPI ([#364](https://github.com/TileDB-Inc/TileDB-Py/pull/364)) + +# TileDB-Py 0.6.4 Release Notes + +## API notes +* Deprecated `initialize_ctx` in favor of `default_ctx(config: tiledb.Config)` [#351](https://github.com/TileDB-Inc/TileDB-Py/pull/351) + +## Improvements +* Bump release target to [TileDB 2.0.6](https://github.com/TileDB-Inc/TileDB/releases/tag/2.0.6) +* Improved error reporting for input data type mismatches [#359](https://github.com/TileDB-Inc/TileDB-Py/pull/359) +* Added `tiledb.VFS.dir_size` [#343](https://github.com/TileDB-Inc/TileDB-Py/pull/343) +* Added read and buffer conversion statistics for python to `tiledb.stats_dump` [#354](https://github.com/TileDB-Inc/TileDB-Py/pull/354) +* Implemented string deduplication to reduce conversion time for string arrays [#357](https://github.com/TileDB-Inc/TileDB-Py/pull/357) + +## Bug fixes +* Fixed argument order for `Array.consolidate` with a Config override parameter [#344](https://github.com/TileDB-Inc/TileDB-Py/pull/344) + +# TileDB-Py 0.6.3 Release Notes + +## Improvements +* Bump release target to [TileDB 2.0.5](https://github.com/TileDB-Inc/TileDB/releases/tag/2.0.5) + +## Bug fixes +* Fix unnecessary implicit ordering requirement for multi-attribute assignment. [#328](https://github.com/TileDB-Inc/TileDB-Py/pull/328) + +# TileDB-Py 0.6.2 Release Notes + +## Bug fixes +* Fix `nonempty_domain` with heterogeneous non-string dimensions ([#320](https://github.com/TileDB-Inc/TileDB-Py/pull/320)) + +## Improvements +* Add doctest for `tiledb.vacuum` ([#319](https://github.com/TileDB-Inc/TileDB-Py/pull/320)) + +# TileDB-Py 0.6.1 Release Notes + +## Bug fixes +* Fix assignment order for `nonempty_domain` with string dimensions ([#308](https://github.com/TileDB-Inc/TileDB-Py/pull/308)) (test in [#311](https://github.com/TileDB-Inc/TileDB-Py/commit/35e5ff64ccfe7bf8f30a5900bfbe67c46cd1f97d)) +* Fix bug in string attribute handling for var-length attributes ([#307](https://github.com/TileDB-Inc/TileDB-Py/issues/307)) +* Fix regression reading anonymous attributes from TileDB 1.7 arrays ([#311](https://github.com/TileDB-Inc/TileDB-Py/pull/311)) +* Fix incorrect `multi_index` error when string attribute results are empty ([#311](https://github.com/TileDB-Inc/TileDB-Py/pull/311)) + +# TileDB-Py 0.6.0 Release Notes + +## Improvements +* Target TileDB version 2.0 + - Added support for heterogeneous and string-typed dimensions [#304](https://github.com/TileDB-Inc/TileDB-Py/pull/304) + - Added support for `tiledb_array_vacuum` for cleaning up consolidated fragments +* Added Windows wheels for Python 3.7 and 3.8 on PyPI + +# TileDB-Py 0.5.9 Release Notes + +* Bump release target to [TileDB 1.7.7](https://github.com/TileDB-Inc/TileDB/releases/tag/1.7.7) + +# TileDB-Py 0.5.8 Release Notes + +* Rebuild/release due to wheel build error on linux for 0.5.7. + +# TileDB-Py 0.5.7 Release Notes + +* Bump release target to [TileDB 1.7.6](https://github.com/TileDB-Inc/TileDB/releases/tag/1.7.6) + +# TileDB-Py 0.5.6 Release Notes + +* Bump release target to [TileDB 1.7.5](https://github.com/TileDB-Inc/TileDB/releases/tag/1.7.5) + +# TileDB-Py 0.5.5 Release Notes + +* Bump release target to [TileDB 1.7.4](https://github.com/TileDB-Inc/TileDB/releases/tag/1.7.4) + +## Improvements +- Return coordinates by default for dense `multi_index` queries [#259]( +https://github.com/TileDB-Inc/TileDB-Py/pull/259) + +# TileDB-Py 0.5.4 Release Notes + +* Bump release target to [TileDB 1.7.3](https://github.com/TileDB-Inc/TileDB/releases/tag/1.7.3) + +## Improvements +- macOS wheels are now available on PyPI [#258](https://github.com/TileDB-Inc/TileDB-Py/pull/258) +- Delay default ctx initialization, allows per-process global config options to be controlled by user [#256](https://github.com/TileDB-Inc/TileDB-Py/pull/256) + +# TileDB-Py 0.5.3 Release Notes + +PyPI packages: https://pypi.org/project/tiledb/0.5.3/ + +## Improvements +- Reduce i/o overhead of `tiledb.open` and array constructors. [#239](https://github.com/TileDB-Inc/TileDB-Py/pull/239), [#240](https://github.com/TileDB-Inc/TileDB-Py/pull/240) +- Internal support for retrying incomplete queries in all array indexing modes. [#238](https://github.com/TileDB-Inc/TileDB-Py/pull/238), [#252](https://github.com/TileDB-Inc/TileDB-Py/pull/252) +- Eliminate reference cycles to improve Ctx cleanup. [#249](https://github.com/TileDB-Inc/TileDB-Py/pull/249) +- Support for retrieving compressor level from filter. [#234](https://github.com/TileDB-Inc/TileDB-Py/pull/234) + +## Bug fixes +- Fix variable-length indexing error. [#236](https://github.com/TileDB-Inc/TileDB-Py/pull/236) +- Fix race condition initializing `tiledb.cloud` mixin from thread pool. [#246](https://github.com/TileDB-Inc/TileDB-Py/pull/246) + +# TileDB-Py 0.5.2 Release Notes + +## Bug fixes +- Fix bug in multi_index result buffer calculation [#232](https://github.com/TileDB-Inc/TileDB-Py/pull/232) + +# TileDB-Py 0.5.1 Release Notes + +## Bug fixes +- [Fix current buffer size calculation](https://github.com/TileDB-Inc/TileDB-Py/commit/3af75b5911b2195ceb66a41d582d9ffa9aa227b6) +- [Fix incorrect query_free in multi-range dense path](https://github.com/TileDB-Inc/TileDB-Py/commit/dbec665da3ebd0e0b5a341d22e47b25ede05cd7d) + +## Other +- [Support '--tiledb=source' option for setup.py to ensure build from source](https://github.com/TileDB-Inc/TileDB-Py/commit/67e7c5c490caf97c5351352cb720116a1c5e1a0d) + +# TileDB-Py 0.5.0 Release Notes + +## New features +- add support for multi-range queries [#219](https://github.com/TileDB-Inc/TileDB-Py/pull/219) +- add support for TileDB array metadata [#213](https://github.com/TileDB-Inc/TileDB-Py/pull/213) +- add support for TILEDB_DATETIME_* attributes, domains, and slicing [#211](https://github.com/TileDB-Inc/TileDB-Py/pull/211) +- add support for retrieving list of fragments written by the most recent write to an array [#207](https://github.com/TileDB-Inc/TileDB-Py/pull/207) + +## Bug fixes +- fix read error with multi-attribute sparse arrays [#214](https://github.com/TileDB-Inc/TileDB-Py/pull/214) + +# TileDB-Py 0.4.4 Release Notes + +* Bump release target to [TileDB 1.6.3](https://github.com/TileDB-Inc/TileDB/releases/tag/1.6.3) + +## New features +- add `dim_type` keyword argument to `from_numpy` in order to override inferred Dimension dtype [#194](https://github.com/TileDB-Inc/TileDB-Py/pull/194) +- add `Array.domain_index`: slice over any range within the domain bounds, including negative slices [#202](https://github.com/TileDB-Inc/TileDB-Py/pull/202) + +# TileDB-Py 0.4.3 Release Notes + +* Bump release target to [TileDB 1.6.0](https://github.com/TileDB-Inc/TileDB/releases/tag/1.6.0) + + +## New features +- allow `tiledb.open` and `Array.create` to take an optional Ctx to override schema [#162](https://github.com/TileDB-Inc/TileDB-Py/pull/162) +- add `tiledb.array_exists` [#167](https://github.com/TileDB-Inc/TileDB-Py/pull/167) + +## Bug fixes +- wrap query_submits into try / finally blocks correctly propagate KeyboardInterrupt errors while cleaning up resources [#155](https://github.com/TileDB-Inc/TileDB-Py/pull/155) +- fixed OOB access in exception handling path [#159](https://github.com/TileDB-Inc/TileDB-Py/pull/159) +- raise an error when trying to consolidate an open readonly array [#172](https://github.com/TileDB-Inc/TileDB-Py/pull/172) + +# TileDB-Py 0.4.2 Release Notes + +TileDB-Py 0.4.2 contains several improvements as well as bug-fixes associated with the TileDB 1.5.1 release. + +## New features + +- support for NumPy complex types ([#142](https://github.com/TileDB-Inc/TileDB-Py/pull/142)) + +## Bug fixes +- fixed query buffer memory leak ([#151](https://github.com/TileDB-Inc/TileDB-Py/pull/151)) +- fixed segfault during consolidation ([TileDB #1213](https://github.com/TileDB-Inc/TileDB/pull/1213)) + - *note: to receive this fix, conda and source builds should be updated to TileDB 1.5.1. TileDB-Py 0.4.2 binaries on PyPI bundle the updated TileDB 1.5.1 library.* +- fixed indexing with array dtype different from the platform default ([#146](https://github.com/TileDB-Inc/TileDB-Py/pull/146)) +- fixed `VFS.is_bucket` when VFS is initialized with a Ctx object ([#148](https://github.com/TileDB-Inc/TileDB-Py/pull/148)) +- fixed `schema_like` to correctly forward a Ctx keyword arg ([#148](https://github.com/TileDB-Inc/TileDB-Py/pull/148)) + +# TileDB-Py 0.4.1 Release Notes + +## New Features: + +* several high-level API additions (tiledb.open, .save, .empty_like, .schema_like), and serialization improvements including pickling support for DenseArray objects (#129) +* manylinux1 wheels for Python 2.7, 3.5, 3.6, and 3.7 are available on PyPI: https://pypi.org/project/tiledb + +# TileDB-Py 0.4.0 Release Notes + +This release builds TileDB-Py against TileDB 1.5 + +## New Features: + +* support for variable-length arrays (#120) + +## Breaking changes: + +* the Ctx argument is now a keyword argument, simplifying API use in the common case (#122) + + for example: `tiledb.DenseArray(ctx, uri, ...)` becomes: tiledb.DenseArray(uri, ...) + or optionally `tiledb.DenseArray(uri, ..., ctx=ctx)` diff --git a/testbed/TileDB-Inc__TileDB-Py/LICENSE b/testbed/TileDB-Inc__TileDB-Py/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..611697815192926242a262a33fa274c0286048d5 --- /dev/null +++ b/testbed/TileDB-Inc__TileDB-Py/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2017-2018 TileDB Inc. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/testbed/TileDB-Inc__TileDB-Py/README.md b/testbed/TileDB-Inc__TileDB-Py/README.md new file mode 100644 index 0000000000000000000000000000000000000000..cdb9bed4cd7e68ef3448f59543304536e3fe40f6 --- /dev/null +++ b/testbed/TileDB-Inc__TileDB-Py/README.md @@ -0,0 +1,40 @@ +TileDB logo + + +[![Build Status](https://dev.azure.com/TileDB-Inc/CI/_apis/build/status/TileDB-Inc.TileDB-Py?branchName=dev)](https://dev.azure.com/TileDB-Inc/CI/_build/latest?definitionId=1&branchName=dev) +![](https://raw.githubusercontent.com/TileDB-Inc/TileDB/dev/doc/anaconda.svg?sanitize=true)[![Anaconda download count badge](https://anaconda.org/conda-forge/TileDB-Py/badges/downloads.svg)](https://anaconda.org/conda-forge/TileDB-Py) + + +# TileDB-Py + +*TileDB-Py* is a [Python](https://python.org) interface to the [TileDB Storage Engine](https://github.com/TileDB-Inc/TileDB). + +# Quick Links + +* [Installation](https://docs.tiledb.com/developer/installation/quick-install) +* [Build Instructions](https://docs.tiledb.com/main/how-to/installation/building-from-source/python) +* [TileDB Documentation](https://docs.tiledb.com/main/) +* [Python API reference](https://tiledb-inc-tiledb-py.readthedocs-hosted.com/en/stable) + +# Quick Installation + +TileDB-Py is available from either [PyPI](https://pypi.org/project/tiledb/) with ``pip``: + +``` +pip install tiledb +``` + +or from [conda-forge](https://anaconda.org/conda-forge/tiledb-py) with +[conda](https://conda.io/docs/) or [mamba](https://github.com/mamba-org/mamba#installation): + +``` +conda install -c conda-forge tiledb-py +``` + +Dataframes functionality (`tiledb.from_pandas`, `Array.df[]`) requires [Pandas](https://pandas.pydata.org/) 1.0 or higher, and [PyArrow](https://arrow.apache.org/docs/python/) 1.0 or higher. + +# Contributing + +We welcome contributions, please see [`CONTRIBUTING.md`](https://github.com/TileDB-Inc/TileDB-Py/blob/dev/CONTRIBUTING.md) for suggestions and +development-build instructions. For larger features, please open an issue to discuss goals and +approach in order to ensure a smooth PR integration and review process. diff --git a/testbed/TileDB-Inc__TileDB-Py/ci/README.md b/testbed/TileDB-Inc__TileDB-Py/ci/README.md new file mode 100644 index 0000000000000000000000000000000000000000..1307a20f0f752255bf6d3bc2586f45c49a0563e4 --- /dev/null +++ b/testbed/TileDB-Inc__TileDB-Py/ci/README.md @@ -0,0 +1,44 @@ +# CI documentation + +TileDB-Py currently uses two CI services: + - GitHub actions for routine CI + - Azure Pipelines for release packaging + +## GitHub Actions + + + +### Nightly Builds + +- + +## Azure Pipelines + +AZP is configured in [azure-pipelines.yml](), which points to two pipeline files in `misc`: + - [misc/azure-ci.yml](): Legacy CI, to ensure that the release build continue to work. + - [misc/azure-release.yml](): release build system, which creates Python wheels for PyPI distribution. + + +### Release builds + +AZP release builds + +### Service Connection + +In order to create issues after nightly build failure, the AZP nightly pipeline uses a service connection +with authorization to post to GitHub. + - Configuration page: [https://dev.azure.com/TileDB-Inc/CI/_settings/adminservices](https://dev.azure.com/TileDB-Inc/CI/_settings/adminservices) + - Connection name: `TileDB-Py-Test` + - Setup, from services configuration page above: + - Create a new Personal Access token + - At present, the repo dispatch token must be linked to an individual user account. + - Visit: https://github.com/settings/tokens/new + - Create token with `public_repo` scope and 1 year expiration (maximum) + - Visit configuration page linked above + - Select `New Service Connection` + - Select `Generic` + - Server URL: `https://api.github.com/` + - Password/token: + - Disable access to all repositories (will require pipeline-specific authorization on first pipeline execution) + - Save the new connection. Note that the connection name must match the name specified for + `connectedServieName` in `misc/azure-release.yml`. Note that you diff --git a/testbed/TileDB-Inc__TileDB-Py/ci/scripts/check_formatting_linux.sh b/testbed/TileDB-Inc__TileDB-Py/ci/scripts/check_formatting_linux.sh new file mode 100644 index 0000000000000000000000000000000000000000..07b61f61f1296356ecbb9e7dacefaccef0c7d0bd --- /dev/null +++ b/testbed/TileDB-Inc__TileDB-Py/ci/scripts/check_formatting_linux.sh @@ -0,0 +1,38 @@ +#!/bin/bash + +# +# The MIT License (MIT) +# +# Copyright (c) 2021 TileDB, Inc. +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in all +# copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +# SOFTWARE. +# + +# Check test formatting - linux ONLY + +set -e pipefail + +# Install clang-format +ls -la +sudo ./ci/scripts/install-clangformat.sh + +src=$GITHUB_WORKSPACE +cd $src + +$src/ci/scripts/run-clang-format.sh $src clang-format-16 0 diff --git a/testbed/TileDB-Inc__TileDB-Py/ci/scripts/install-clangformat.sh b/testbed/TileDB-Inc__TileDB-Py/ci/scripts/install-clangformat.sh new file mode 100644 index 0000000000000000000000000000000000000000..3bb230b8a5ff029f8e4c2f967c747b23ee26e671 --- /dev/null +++ b/testbed/TileDB-Inc__TileDB-Py/ci/scripts/install-clangformat.sh @@ -0,0 +1,63 @@ +#!/bin/bash + +# +# The MIT License (MIT) +# +# Copyright (c) 2019-2021 TileDB, Inc. +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in all +# copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +# SOFTWARE. +# + +die() { + echo "$@" 1>&2 ; popd 2>/dev/null; exit 1 +} + +install_apt_pkg() { + wget -O - https://apt.llvm.org/llvm-snapshot.gpg.key | sudo apt-key add - + add-apt-repository 'deb http://apt.llvm.org/focal/ llvm-toolchain-focal-16 main' && + apt-get update -qq && apt-get install -qq -y clang-format-16 +} + +install_brew_pkg() { + brew upgrade && brew install clang-format +} + +install_clang_format() { + if [[ $OSTYPE == linux* ]]; then + if [ -n "$(command -v apt-get)" ]; then + install_apt_pkg || die "could not install apt clang format package" + else + die "unsupported Linux package management system" + fi + elif [[ $OSTYPE == darwin* ]]; then + if [ -n "$(command -v brew)" ]; then + install_brew_pkg || die "could not install brew clang format package" + else + die "homebrew is not installed!" + fi + else + die "unsupported OS" + fi +} + +run() { + install_clang_format +} + +run diff --git a/testbed/TileDB-Inc__TileDB-Py/ci/scripts/run-clang-format.sh b/testbed/TileDB-Inc__TileDB-Py/ci/scripts/run-clang-format.sh new file mode 100644 index 0000000000000000000000000000000000000000..1249ddaa0e26ef49f625a6331f27250d280f4d0f --- /dev/null +++ b/testbed/TileDB-Inc__TileDB-Py/ci/scripts/run-clang-format.sh @@ -0,0 +1,63 @@ +#!/bin/bash +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Runs clang format in the given directory +# Arguments: +# $1 - Path to the source tree +# $2 - Path to the clang format binary +# $3 - Apply fixes (will raise an error if false and not there where changes) +# $ARGN - Files to run clang format on +# + +SOURCE_DIR=$1 +shift +CLANG_FORMAT=$1 +shift +APPLY_FIXES=$1 +shift + +echo "Running clang-format version:" `$CLANG_FORMAT --version` + +# clang format will only find its configuration if we are in +# the source tree or in a path relative to the source tree +pushd $SOURCE_DIR + +src=$SOURCE_DIR +SOURCE_PATHS=($src/tiledb) +FIND_FILES=(-name "*.cc" -or -name "*.c" -or -name "*.h") + +if [ "$APPLY_FIXES" == "1" ]; then + find "${SOURCE_PATHS[@]}" \( "${FIND_FILES[@]}" \) -print0 | xargs -0 -P8 $CLANG_FORMAT -i + +else + NUM_CORRECTIONS=`find "${SOURCE_PATHS[@]}" \( "${FIND_FILES[@]}" \) -print0 | xargs -0 -P8 $CLANG_FORMAT -output-replacements-xml | grep offset | wc -l` + + if [ "$NUM_CORRECTIONS" -gt "0" ]; then + echo "clang-format suggested changes" + + # If running on CI, print out the change-set + if [ "$CI" = true ]; then + echo "-------- see list of files to update below --------" + find "${SOURCE_PATHS[@]}" "${FIND_FILES[@]}" -print0 | xargs -P8 -0 $CLANG_FORMAT -i + git diff --name-only + + echo "-------- see diff below --------" + git diff + fi + + # Fail the job + exit 1 + fi +fi +popd diff --git a/testbed/TileDB-Inc__TileDB-Py/cmake/DownloadTileDB.cmake b/testbed/TileDB-Inc__TileDB-Py/cmake/DownloadTileDB.cmake new file mode 100644 index 0000000000000000000000000000000000000000..8db5015bdb591b0973d34c0aee87f054b4396b43 --- /dev/null +++ b/testbed/TileDB-Inc__TileDB-Py/cmake/DownloadTileDB.cmake @@ -0,0 +1,125 @@ +# +# FindTileDB_EP.cmake +# +# +# The MIT License +# +# Copyright (c) 2023 TileDB, Inc. +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +# THE SOFTWARE. + +include(FetchContent) + +function(fetch_tiledb_release_list VERSION) + # Local constants + set(UPSTREAM_URL "https://github.com/TileDB-Inc/TileDB/releases/download") + list(LENGTH ARGV COUNT) + if (${COUNT} GREATER 1) + list(GET ARGV 1 EXPECTED_HASH) + endif() + + if(NOT VERSION) + set(VERSION latest) + endif() + + if(EXPECTED_HASH) + file(DOWNLOAD + ${UPSTREAM_URL}/${VERSION}/releases.csv + ${CMAKE_CURRENT_BINARY_DIR}/releases.csv + SHOW_PROGRESS + EXPECTED_HASH ${EXPECTED_HASH} + ) + else() + message(WARNING "Downloading release list without SHA checksum!") + file(DOWNLOAD + ${UPSTREAM_URL}/${VERSION}/releases.csv + ${CMAKE_CURRENT_BINARY_DIR}/releases.csv + SHOW_PROGRESS + ) + endif() + + file(STRINGS + ${CMAKE_CURRENT_BINARY_DIR}/releases.csv + RELLIST + ) + + # Remove csv table headers + list(POP_FRONT RELLIST) + + foreach(LINE ${RELLIST}) + string(REPLACE "," ";" LINE ${LINE}) + list(LENGTH LINE LENGTH) + + list(GET LINE 0 PLATFORM) + list(GET LINE 1 URL) + list(GET LINE 2 SHA) + + set(RELEASE_VAR TILEDB_${PLATFORM}) + set(URL_${RELEASE_VAR} ${URL} PARENT_SCOPE) + set(HASH_${RELEASE_VAR} ${SHA} PARENT_SCOPE) + endforeach() +endfunction() + +function(detect_artifact_name OUT_VAR) + if (WIN32) # Windows + SET(${OUT_VAR} TILEDB_WINDOWS-X86_64 PARENT_SCOPE) + elseif(APPLE) # OSX + if (CMAKE_OSX_ARCHITECTURES) + set(ACTUAL_TARGET ${CMAKE_OSX_ARCHITECTURES}) + else() + set(ACTUAL_TARGET ${CMAKE_SYSTEM_PROCESSOR}) + endif() + + if (ACTUAL_TARGET MATCHES "(x86_64)|(AMD64|amd64)|(^i.86$)") + SET(${OUT_VAR} TILEDB_MACOS-X86_64 PARENT_SCOPE) + elseif (ACTUAL_TARGET STREQUAL arm64 OR ACTUAL_TARGET MATCHES "^aarch64" OR CMAKE_SYSTEM_PROCESSOR MATCHES "^arm") + SET(${OUT_VAR} TILEDB_MACOS-ARM64 PARENT_SCOPE) + endif() + else() # Linux + SET(${OUT_VAR} TILEDB_LINUX-X86_64 PARENT_SCOPE) + endif() +endfunction() + +function(fetch_prebuilt_tiledb) + # Arguments + set(oneValueArgs VERSION ARTIFACT_NAME RELLIST_HASH) + set(multiValueArgs) + cmake_parse_arguments( + FETCH_PREBUILT_TILEDB + "${options}" + "${oneValueArgs}" + "${multiValueArgs}" + ${ARGN} + ) + + fetch_tiledb_release_list(${FETCH_PREBUILT_TILEDB_VERSION} ${FETCH_PREBUILT_TILEDB_RELLIST_HASH}) + + if(NOT FETCH_PREBUILT_TILEDB_ARTIFACT_NAME) + detect_artifact_name(FETCH_PREBUILT_TILEDB_ARTIFACT_NAME) + endif() + + string(STRIP ${HASH_${FETCH_PREBUILT_TILEDB_ARTIFACT_NAME}} HASH_${FETCH_PREBUILT_TILEDB_ARTIFACT_NAME}) + FetchContent_Declare( + tiledb + URL ${URL_${FETCH_PREBUILT_TILEDB_ARTIFACT_NAME}} + URL_HASH SHA256=${HASH_${FETCH_PREBUILT_TILEDB_ARTIFACT_NAME}} + ) + FetchContent_MakeAvailable(tiledb) + set(TileDB_DIR ${tiledb_SOURCE_DIR}/lib/cmake/TileDB PARENT_SCOPE) +endfunction() \ No newline at end of file diff --git a/testbed/TileDB-Inc__TileDB-Py/doc/local-build.sh b/testbed/TileDB-Inc__TileDB-Py/doc/local-build.sh new file mode 100644 index 0000000000000000000000000000000000000000..e82cef3aea5cb05da93e5111ba1814f07a49ef32 --- /dev/null +++ b/testbed/TileDB-Inc__TileDB-Py/doc/local-build.sh @@ -0,0 +1,75 @@ +#!/bin/bash + +# +# Builds the ReadTheDocs documentation locally. +# Usage. Execute in this directory: +# $ ./local-build.sh +# This creates a Python virtual env 'venv' in the current directory. +# + +# Choose the default directories +source_dir="source" +build_dir="source/_build" +venv_dir="venv" +ext_dir="../" + +die() { + echo "$@" 1>&2 ; popd 2>/dev/null; exit 1 +} + +arg() { + echo "$1" | sed "s/^${2-[^=]*=}//" | sed "s/:/;/g" +} + +# Display bootstrap usage +usage() { +echo ' +Usage: '"$0"' [] +Options: [defaults in brackets after descriptions] +Configuration: + --help print this message + --tiledb=PATH (required) path to TileDB repo root +' + exit 10 +} + +# Parse arguments +tiledb="" +while test $# != 0; do + case "$1" in + --tiledb=*) dir=`arg "$1"` + tiledb="$dir";; + --help) usage ;; + *) die "Unknown option: $1" ;; + esac + shift +done + +if [ ! -d "${tiledb}" ]; then + die "invalid tiledb installation directory (use --tiledb)" +fi + +build_ext() { + pushd "${ext_dir}" + TILEDB_PATH=${tiledb} pip install .[doc] || die "could not install tiledb-py" + popd +} + +build_site() { + if [[ $OSTYPE == darwin* ]]; then + export DYLD_LIBRARY_PATH="${tiledb}/lib" + else + export LD_LIBRARY_PATH="${tiledb}/lib" + fi + export TILEDB_PY_NO_VERSION_CHECK="yes" + sphinx-build -E -T -b html -d ${build_dir}/doctrees -D language=en ${source_dir} ${build_dir}/html || \ + die "could not build sphinx site" +} + +run() { + build_ext + build_site + echo "Build complete. Open '${build_dir}/html/index.html' in your browser." +} + +run diff --git a/testbed/TileDB-Inc__TileDB-Py/doc/source/_static/custom.css b/testbed/TileDB-Inc__TileDB-Py/doc/source/_static/custom.css new file mode 100644 index 0000000000000000000000000000000000000000..df83da73e39c010c946d2b05e781db25f801fc5d --- /dev/null +++ b/testbed/TileDB-Inc__TileDB-Py/doc/source/_static/custom.css @@ -0,0 +1,20 @@ +.wy-side-nav-search { + background-color: #fafafa; + color: #404040; +} + +.wy-side-nav-search > a { + color: #2980B9; +} + +.wy-side-nav-search > div.version { + color: rgba(64, 64, 64, 0.3); +} + +.red { + color: red; +} + +.green { + color: green; +} \ No newline at end of file diff --git a/testbed/TileDB-Inc__TileDB-Py/doc/source/_static/favicon.ico b/testbed/TileDB-Inc__TileDB-Py/doc/source/_static/favicon.ico new file mode 100644 index 0000000000000000000000000000000000000000..c5f7b85ac8737c0cf5ab5cecbbc297f0313f4515 Binary files /dev/null and b/testbed/TileDB-Inc__TileDB-Py/doc/source/_static/favicon.ico differ diff --git a/testbed/TileDB-Inc__TileDB-Py/doc/source/conf.py b/testbed/TileDB-Inc__TileDB-Py/doc/source/conf.py new file mode 100644 index 0000000000000000000000000000000000000000..a13dc2032b358ce90c0ca4924c9353a5cf5b935b --- /dev/null +++ b/testbed/TileDB-Inc__TileDB-Py/doc/source/conf.py @@ -0,0 +1,168 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +# + +# -- Imports configuration ------------------------------------------------- + +import os +import sys +from os.path import abspath, dirname, join +import sphinx_rtd_theme +from importlib.metadata import version as get_version + +sys.path.insert(0, abspath(join(dirname(__file__)))) + +# -- ReadTheDocs configuration --------------------------------------------- + +# Special handling on ReadTheDocs builds. +# Some of this code is from https://github.com/robotpy/robotpy-docs/blob/master/conf.py +readthedocs = os.environ.get("READTHEDOCS", None) == "True" +rtd_version = os.environ.get("READTHEDOCS_VERSION", "latest") +rtd_version = rtd_version if rtd_version in ["stable", "latest"] else "stable" + +# -- Project information ----------------------------------------------------- + +project = "TileDB-Py" +copyright = "2024, TileDB, Inc." +author = "TileDB, Inc." + +# The full version, including alpha/beta/rc tags +release: str = get_version("tiledb") +# The short X.Y version +version: str = ".".join(release.split(".")[:2]) + + +# -- General configuration --------------------------------------------------- + +# If your documentation needs a minimal Sphinx version, state it here. +# +# needs_sphinx = '1.0' + +# Add any Sphinx extension module names here, as strings. They can be +# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom +# ones. +extensions = ["sphinx.ext.autodoc", "sphinx.ext.doctest", "sphinx.ext.intersphinx"] + +# Mapping for linking between RTD subprojects. +if readthedocs: + intersphinx_mapping = { + "tiledb": ( + "https://tiledb-inc-tiledb.readthedocs-hosted.com/en/%s/" % rtd_version, + None, + ), + "tiledb-py": ( + "https://tiledb-inc-tiledb.readthedocs-hosted.com/projects/python-api/en/%s/" + % rtd_version, + None, + ), + "python": ("https://docs.python.org/", None), + } + +# Add any paths that contain templates here, relative to this directory. +templates_path = ["_templates"] + +# The suffix(es) of source filenames. +# You can specify multiple suffix as a list of string: +# +# source_suffix = ['.rst', '.md'] +source_suffix = ".rst" + +# The master toctree document. +master_doc = "index" + +# The language for content autogenerated by Sphinx. Refer to documentation +# for a list of supported languages. +# +# This is also used if you do content translation via gettext catalogs. +# Usually you set "language" from the command line for these cases. +language = "en" + +# List of patterns, relative to source directory, that match files and +# directories to ignore when looking for source files. +# This pattern also affects html_static_path and html_extra_path . +exclude_patterns = ["_build", "Thumbs.db", ".DS_Store"] + +# The name of the Pygments (syntax highlighting) style to use. +pygments_style = "friendly" + + +# -- Options for HTML output ------------------------------------------------- + +html_static_path = ["_static"] +html_title = "TileDB Python API Reference โ€” TileDB-Py %s documentation" % version +html_logo = "_static/tiledb-logo_color_no_margin_@4x.png" +html_favicon = "_static/favicon.ico" + +html_theme = "sphinx_rtd_theme" +html_theme_path = [sphinx_rtd_theme.get_html_theme_path()] + +# -- Options for HTMLHelp output --------------------------------------------- + +# Output file base name for HTML help builder. +htmlhelp_basename = "TileDB-Pydoc" + + +# -- Options for LaTeX output ------------------------------------------------ + +latex_elements = { + # The paper size ('letterpaper' or 'a4paper'). + # + # 'papersize': 'letterpaper', + # The font size ('10pt', '11pt' or '12pt'). + # + # 'pointsize': '10pt', + # Additional stuff for the LaTeX preamble. + # + # 'preamble': '', + # Latex figure (float) alignment + # + # 'figure_align': 'htbp', +} + +# Grouping the document tree into LaTeX files. List of tuples +# (source start file, target name, title, +# author, documentclass [howto, manual, or own class]). +latex_documents = [ + (master_doc, "TileDB-Py.tex", "TileDB-Py Documentation", "TileDB, Inc.", "manual") +] + + +# -- Options for manual page output ------------------------------------------ + +# One entry per manual page. List of tuples +# (source start file, name, description, authors, manual section). +man_pages = [(master_doc, "tiledb-py", "TileDB-Py Documentation", [author], 1)] + + +# -- Options for Texinfo output ---------------------------------------------- + +# Grouping the document tree into Texinfo files. List of tuples +# (source start file, target name, title, author, +# dir menu entry, description, category) +texinfo_documents = [ + ( + master_doc, + "TileDB-Py", + "TileDB-Py Documentation", + author, + "TileDB-Py", + "One line description of project.", + "Miscellaneous", + ) +] + +# -- Custom Document processing ---------------------------------------------- + +# Generate the sidebar automatically so that it is identical across all subprojects. +# This (and gensidebar.py) from https://github.com/robotpy/robotpy-docs +import gensidebar + +gensidebar.generate_sidebar( + {"on_rtd": readthedocs, "rtd_version": rtd_version}, "tiledb-py" +) + +# -- Custom setup ----------------------------------------------------------- + + +def setup(app): + app.add_css_file("custom.css") diff --git a/testbed/TileDB-Inc__TileDB-Py/doc/source/gensidebar.py b/testbed/TileDB-Inc__TileDB-Py/doc/source/gensidebar.py new file mode 100644 index 0000000000000000000000000000000000000000..408828c6407911327f980d8ead69e1449e0d134b --- /dev/null +++ b/testbed/TileDB-Inc__TileDB-Py/doc/source/gensidebar.py @@ -0,0 +1,85 @@ +# +# This file generates the sidebar/toctree for all TileDB projects and should +# be copied to each project when it is updated. +# +# This file is originally from the RobotPy documentation project +# https://github.com/robotpy/robotpy-docs, licensed under Apache v2. +# + +import os + + +def write_if_changed(fname, contents): + + try: + with open(fname, "r") as fp: + old_contents = fp.read() + except: + old_contents = "" + + if old_contents != contents: + with open(fname, "w") as fp: + fp.write(contents) + + +def generate_sidebar(conf, conf_api): + + version = conf["rtd_version"] + + lines = [ + "", + ".. DO NOT MODIFY! THIS PAGE IS AUTOGENERATED!", + " To edit the sidebar, modify gensidebar.py and re-build the docs.", + "", + ] + + url_base = "https://tiledb-inc-tiledb.readthedocs-hosted.com" + lang = "en" + + def toctree(name): + lines.extend( + [".. toctree::", " :caption: %s" % name, " :maxdepth: 1", ""] + ) + + def endl(): + lines.append("") + + def write(desc, link): + if conf_api == "tiledb": + args = desc, link + else: + args = desc, "%s/%s/%s/%s.html" % (url_base, lang, version, link) + + lines.append(" %s <%s>" % args) + + def write_api(project, desc, rst_page): + # From non-root project to root project link + if project == "tiledb" and conf_api != "tiledb": + args = desc, url_base, lang, version, rst_page + lines.append(" %s API <%s/%s/%s/%s.html>" % args) + # From anything to non-root project link + elif project != conf_api: + args = desc, url_base, project, lang, version, rst_page + lines.append(" %s API <%s/projects/%s/%s/%s/%s.html>" % args) + # Local project link + else: + args = desc, rst_page + lines.append(" %s API <%s>" % args) + + def write_api_url(desc, url): + lines.append(" %s API <%s>" % (desc, url)) + + # + # Specify the sidebar contents here + # + + toctree("API Reference") + write_api("tiledb", "C", "c-api") + write_api("tiledb", "C++", "c++-api") + write_api("tiledb-py", "Python", "python-api") + write_api_url("R", "https://tiledb-inc.github.io/TileDB-R/reference/index.html") + write_api_url("Java", "https://www.javadoc.io/doc/io.tiledb/tiledb-java") + write_api_url("Go", "https://godoc.org/github.com/TileDB-Inc/TileDB-Go") + endl() + + write_if_changed("_sidebar.rst.inc", "\n".join(lines)) diff --git a/testbed/TileDB-Inc__TileDB-Py/doc/source/index.rst b/testbed/TileDB-Inc__TileDB-Py/doc/source/index.rst new file mode 100644 index 0000000000000000000000000000000000000000..09ea7829ee8f09dfe09b74ea5eafb75386794314 --- /dev/null +++ b/testbed/TileDB-Inc__TileDB-Py/doc/source/index.rst @@ -0,0 +1,6 @@ +TileDB Python Project +===================== + +This project encompasses the Python language bindings for the TileDB library. + +.. include:: _sidebar.rst.inc diff --git a/testbed/TileDB-Inc__TileDB-Py/doc/source/python-api.rst b/testbed/TileDB-Inc__TileDB-Py/doc/source/python-api.rst new file mode 100644 index 0000000000000000000000000000000000000000..6656a0db8cbdc5da9d6533cd8a12359f15b062e2 --- /dev/null +++ b/testbed/TileDB-Inc__TileDB-Py/doc/source/python-api.rst @@ -0,0 +1,246 @@ +TileDB Python API Reference +=========================== + +Modules +------- + +Typical usage of the Python interface to TileDB will use the top-level module ``tiledb``, e.g. + +.. code-block:: python + + import tiledb + +There is also a submodule ``libtiledb`` which contains the necessary bindings to the underlying TileDB native library. Most of the time you will not need to interact with ``tiledb.libtiledb`` unless you need native-library specific information, e.g. the version number: + +.. code-block:: python + + import tiledb + tiledb.libtiledb.version() # Native TileDB library version number + +Getting Started +--------------- + +Arrays may be opened with the ``tiledb.open`` function: + +.. autofunction:: tiledb.open + +Data import helpers +------------------- + +.. autofunction:: tiledb.from_numpy +.. autofunction:: tiledb.from_csv +.. autofunction:: tiledb.from_pandas + +Context +------- + +.. autoclass:: tiledb.Ctx + :members: + +.. autofunction:: tiledb.default_ctx +.. autofunction:: tiledb.scope_ctx + +Config +------ + +.. autoclass:: tiledb.Config + :members: + +Current Domain +-------------- + +.. autoclass:: tiledb.CurrentDomain + :members: + +NDRectangle +----------- + +.. autoclass:: tiledb.NDRectangle + :members: + +Array Schema +------------ + +.. autoclass:: tiledb.ArraySchema + :members: + +.. autofunction:: tiledb.empty_like + +Attribute +--------- + +.. autoclass:: tiledb.Attr + :members: + +Filters +------- + +.. autoclass:: tiledb.FilterList + :members: + + .. automethod:: __getitem__(idx) + .. automethod:: __len__ + +.. autoclass:: tiledb.CompressionFilter + :members: +.. autoclass:: tiledb.GzipFilter + :members: +.. autoclass:: tiledb.ZstdFilter + :members: +.. autoclass:: tiledb.LZ4Filter + :members: +.. autoclass:: tiledb.Bzip2Filter + :members: +.. autoclass:: tiledb.RleFilter + :members: +.. autoclass:: tiledb.DoubleDeltaFilter + :members: +.. autoclass:: tiledb.BitShuffleFilter + :members: +.. autoclass:: tiledb.ByteShuffleFilter + :members: +.. autoclass:: tiledb.BitWidthReductionFilter + :members: +.. autoclass:: tiledb.PositiveDeltaFilter + :members: + +Dimension +--------- + +.. autoclass:: tiledb.Dim + :members: + +Domain +------ + +.. autoclass:: tiledb.Domain + :members: + +Array +----- + +.. autoclass:: tiledb.libtiledb.Array + :members: + +.. autofunction:: tiledb.consolidate +.. autofunction:: tiledb.vacuum + +Dense Array +----------- + +.. autoclass:: tiledb.DenseArray + :members: query + :special-members: __getitem__, __setitem__ + +Sparse Array +------------ + +.. autoclass:: tiledb.SparseArray + :members: query + :special-members: __getitem__, __setitem__ + +Query +--------------- + +.. autoclass:: tiledb.libtiledb.Query + :members: + +Query Condition +--------------- + +.. autoclass:: tiledb.QueryCondition + :members: + +Group +----- + +.. autoclass:: tiledb.Group + :members: + + .. automethod:: __getitem__(member) + .. automethod:: __delitem__(uri) + .. automethod:: __contains__(member) + .. automethod:: __len__ + +.. autoclass:: tiledb.Group.GroupMetadata + :members: + + .. automethod:: __setitem__(key, value) + .. automethod:: __getitem__(key) + .. automethod:: __delitem__(key) + .. automethod:: __contains__(key) + .. automethod:: __len__ + .. automethod:: __keys__ + .. automethod:: __values__ + .. automethod:: __items__ + +Object +------ + +.. autoclass:: tiledb.Object + + .. autoattribute:: uri + .. autoattribute:: type + +Object Management +----------------- + +.. autofunction:: tiledb.array_exists +.. autofunction:: tiledb.group_create +.. autofunction:: tiledb.object_type +.. autofunction:: tiledb.remove +.. autofunction:: tiledb.move +.. autofunction:: tiledb.ls +.. autofunction:: tiledb.walk + +Fragment Info +------------- + +.. autoclass:: tiledb.FragmentInfoList + :members: +.. autoclass:: tiledb.FragmentInfo + :members: + +Enumeration +------------ + +.. autoclass:: tiledb.Enumeration + :members: + +Exceptions +---------- + +.. autoexception:: tiledb.TileDBError + :members: + +VFS +--- + +.. autoclass:: tiledb.VFS + :members: + +.. autoclass:: tiledb.FileIO + :members: + + .. automethod:: __len__ + +Filestore +--------- + +.. autoclass:: tiledb.Filestore + :members: + + .. automethod:: __len__ + +Version +------- + +.. autofunction:: tiledb.libtiledb.version + +Statistics +---------- + +.. autofunction:: tiledb.stats_enable +.. autofunction:: tiledb.stats_disable +.. autofunction:: tiledb.stats_reset +.. autofunction:: tiledb.stats_dump diff --git a/testbed/TileDB-Inc__TileDB-Py/examples/config.py b/testbed/TileDB-Inc__TileDB-Py/examples/config.py new file mode 100644 index 0000000000000000000000000000000000000000..1e69997528d5b23efe44dbcf165176015849f48a --- /dev/null +++ b/testbed/TileDB-Inc__TileDB-Py/examples/config.py @@ -0,0 +1,95 @@ +# config.py +# +# LICENSE +# +# The MIT License +# +# Copyright (c) 2020 TileDB, Inc. +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +# THE SOFTWARE. +# +# DESCRIPTION +# +# Please see the TileDB documentation for more information: +# https://docs.tiledb.com/main/how-to/configuration +# +# This program shows how to set/get the TileDB configuration parameters. +# + +import tiledb + + +def set_get_config_ctx_vfs(): + # Create config object + config = tiledb.Config() + + # Set/get config to/from ctx + ctx = tiledb.Ctx(config) + print(ctx.config()) + + # Set/get config to/from VFS + vfs = tiledb.VFS(config) + print(vfs.config()) + + +def set_get_config(): + config = tiledb.Config() + + # Set value + config["vfs.s3.connect_timeout_ms"] = 5000 + + # Get value + tile_cache_size = config["sm.memory_budget"] + print("Memory budget: %s" % str(tile_cache_size)) + + +def print_default(): + config = tiledb.Config() + print("\nDefault settings:") + for p in config.items(): + print('"%s" : "%s"' % (p[0], p[1])) + + +def iter_config_with_prefix(): + config = tiledb.Config() + # Print only the S3 settings. + print("\nVFS S3 settings:") + for p in config.items("vfs.s3."): + print('"%s" : "%s"' % (p[0], p[1])) + + +def save_load_config(): + # Save to file + config = tiledb.Config() + config["sm.memory_budget"] = 1234 + config.save("tiledb_config.txt") + + # Load from file + config_load = tiledb.Config.load("tiledb_config.txt") + print( + "\nTile cache size after loading from file: %s" + % str(config_load["sm.memory_budget"]) + ) + + +set_get_config_ctx_vfs() +set_get_config() +print_default() +iter_config_with_prefix() +save_load_config() diff --git a/testbed/TileDB-Inc__TileDB-Py/examples/errors.py b/testbed/TileDB-Inc__TileDB-Py/examples/errors.py new file mode 100644 index 0000000000000000000000000000000000000000..3cdcc8333eb91c529a5ce8928449bc02d8f7b298 --- /dev/null +++ b/testbed/TileDB-Inc__TileDB-Py/examples/errors.py @@ -0,0 +1,48 @@ +# errors.py +# +# LICENSE +# +# The MIT License +# +# Copyright (c) 2020 TileDB, Inc. +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +# THE SOFTWARE. +# +# DESCRIPTION +# +# Please see the TileDB documentation for more information: +# https://docs.tiledb.com/main/how-to/catching-errors +# +# This example shows how to catch errors in TileDB. +# + +import tiledb + +# Catch an error +try: + tiledb.group_create("my_group") + tiledb.group_create("my_group") +except tiledb.TileDBError as e: + print(f"TileDB exception: {e}") + +# clean up +if tiledb.VFS().is_dir("my_group"): + tiledb.remove("my_group") + +# Setting a different error handler for the context is not yet supported. diff --git a/testbed/TileDB-Inc__TileDB-Py/examples/fragment_info.py b/testbed/TileDB-Inc__TileDB-Py/examples/fragment_info.py new file mode 100644 index 0000000000000000000000000000000000000000..a756956f4a5df96a04b3cd1edc53dc4b8fbbdbcc --- /dev/null +++ b/testbed/TileDB-Inc__TileDB-Py/examples/fragment_info.py @@ -0,0 +1,102 @@ +# fragment_info.py +# +# LICENSE +# +# The MIT License +# +# Copyright (c) 2020 TileDB, Inc. +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +# THE SOFTWARE. +# + + +import numpy as np + +import tiledb + +array_name = "fragment_info" + + +def create_array(): + # The array will be 4x4 with dimensions "rows" and "cols", with domain [1,4] and space tiles 2x2. + dom = tiledb.Domain( + tiledb.Dim(name="rows", domain=(1, 4), tile=2, dtype=np.int32), + tiledb.Dim(name="cols", domain=(1, 4), tile=2, dtype=np.int32), + ) + + # The array will be dense with a single attribute "a" so each (i,j) cell can store an integer. + schema = tiledb.ArraySchema( + domain=dom, sparse=False, attrs=[tiledb.Attr(name="a", dtype=np.int32)] + ) + + # Create the (empty) array on disk. + tiledb.Array.create(array_name, schema) + + +def write_array_1(): + with tiledb.open(array_name, mode="w") as A: + A[1:3, 1:5] = np.array(([[1, 2, 3, 4], [5, 6, 7, 8]])) + + +def write_array_2(): + with tiledb.open(array_name, mode="w") as A: + A[2:4, 2:4] = np.array(([[101, 102], [103, 104]])) + + +def write_array_3(): + with tiledb.open(array_name, mode="w") as A: + A[3:4, 4:5] = np.array(([202])) + + +# Create and write array only if it does not exist +if tiledb.object_type(array_name) != "array": + create_array() + write_array_1() + write_array_2() + write_array_3() + +# tiledb.array_fragments() requires TileDB-Py version > 0.8.5 +fragments_info = tiledb.array_fragments(array_name) + +print("====== FRAGMENTS INFO ======") +print("array uri: {}".format(fragments_info.array_uri)) +print("number of fragments: {}".format(len(fragments_info))) + +to_vac = fragments_info.to_vacuum +print("number of consolidated fragments to vacuum: {}".format(len(to_vac))) +print("uris of consolidated fragments to vacuum: {}".format(to_vac)) + +print(fragments_info.nonempty_domain) +print(fragments_info.sparse) + +for fragment in fragments_info: + print() + print("===== FRAGMENT NUMBER {} =====".format(fragment.num)) + print("fragment uri: {}".format(fragment.uri)) + print("is sparse: {}".format(fragment.sparse)) + print("cell num: {}".format(fragment.cell_num)) + print("has consolidated metadata: {}".format(fragment.has_consolidated_metadata)) + print("nonempty domain: {}".format(fragment.nonempty_domain)) + print("timestamp range: {}".format(fragment.timestamp_range)) + print( + "number of unconsolidated metadata: {}".format( + fragment.unconsolidated_metadata_num + ) + ) + print("version: {}".format(fragment.version)) diff --git a/testbed/TileDB-Inc__TileDB-Py/examples/fragments_consolidation.py b/testbed/TileDB-Inc__TileDB-Py/examples/fragments_consolidation.py new file mode 100644 index 0000000000000000000000000000000000000000..1599e140246b278972b0b1d87db4575d4edea3b5 --- /dev/null +++ b/testbed/TileDB-Inc__TileDB-Py/examples/fragments_consolidation.py @@ -0,0 +1,111 @@ +# fragments_consolidation.py +# +# LICENSE +# +# The MIT License +# +# Copyright (c) 2020 TileDB, Inc. +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +# THE SOFTWARE. +# +# DESCRIPTION +# +# Please see the TileDB documentation for more information: +# https://docs.tiledb.com/main/how-to/arrays/writing-arrays/consolidation-and-vacuuming +# +# When run, this program will create a simple 2D dense array, write some data +# with three queries (creating three fragments), optionally consolidate +# and read the entire array data back. +# + +import sys + +import numpy as np + +import tiledb + +array_name = "fragments_consolidation" + + +def create_array(): + # The array will be 4x4 with dimensions "rows" and "cols", with domain [1,4] and space tiles 2x2. + dom = tiledb.Domain( + tiledb.Dim(name="rows", domain=(1, 4), tile=2, dtype=np.int32), + tiledb.Dim(name="cols", domain=(1, 4), tile=2, dtype=np.int32), + ) + + # The array will be dense with a single attribute "a" so each (i,j) cell can store an integer. + schema = tiledb.ArraySchema( + domain=dom, sparse=False, attrs=[tiledb.Attr(name="a", dtype=np.int32)] + ) + + # Create the (empty) array on disk. + tiledb.Array.create(array_name, schema) + + +def write_array_1(): + with tiledb.open(array_name, mode="w") as A: + A[1:3, 1:5] = np.array(([[1, 2, 3, 4], [5, 6, 7, 8]])) + + +def write_array_2(): + with tiledb.open(array_name, mode="w") as A: + A[2:4, 2:4] = np.array(([[101, 102], [103, 104]])) + + +def write_array_3(): + with tiledb.open(array_name, mode="w") as A: + # Note: sparse (unordered) writes to dense arrays are not yet supported in Python. + # Instead we can make two single-cell writes (results in total of 4 fragments). + A[1:2, 1:2] = np.array(([201])) + A[3:4, 4:5] = np.array(([202])) + + +def read_array(): + with tiledb.open(array_name, mode="r") as A: + # Read the entire array. To get coord values as well, we use the .query() syntax. + data = A.query(coords=True)[:, :] + a_vals = data["a"] + rows = data["rows"] + cols = data["cols"] + for i in range(rows.shape[0]): + for j in range(cols.shape[0]): + print( + "Cell {} has data {}".format( + str((rows[i, j], cols[i, j])), str(a_vals[i, j]) + ) + ) + + +# Create and write array only if it does not exist +if tiledb.object_type(array_name) != "array": + create_array() + write_array_1() + write_array_2() + write_array_3() + +# Optionally consolidate +if len(sys.argv) > 1 and sys.argv[1] == "consolidate": + config = tiledb.Config() + config["sm.consolidation.steps"] = 1 + config["sm.consolidation.step_max_frags"] = 3 + config["sm.consolidation.step_min_frags"] = 1 + tiledb.consolidate(config=config, uri=array_name) + +read_array() diff --git a/testbed/TileDB-Inc__TileDB-Py/examples/in_memory_vfs.py b/testbed/TileDB-Inc__TileDB-Py/examples/in_memory_vfs.py new file mode 100644 index 0000000000000000000000000000000000000000..610aa1c5afa194a59ac2f6240bbb9dcca39809eb --- /dev/null +++ b/testbed/TileDB-Inc__TileDB-Py/examples/in_memory_vfs.py @@ -0,0 +1,50 @@ +# in_memory_vfs.py +# +# LICENSE +# +# The MIT License +# +# Copyright (c) 2024 TileDB, Inc. +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +# THE SOFTWARE. +# +# DESCRIPTION +# +# When run, this program will create a random numpy array, create a TileDB +# DenseArray from it in memory, and read the entire array back from memory. +# It then compares the original numpy array with the TileDB array to check +# that data was written and read correctly (prints True) or not (prints False). +# + +import numpy as np + +import tiledb + +# Create TileDB VFS +vfs = tiledb.VFS() + +file = "mem://myarray" +data = np.random.rand(10, 10) + +if not vfs.is_file(file): + with tiledb.from_numpy(file, data): + pass + +with tiledb.open(file) as A: + print(np.all(A[:] == data)) diff --git a/testbed/TileDB-Inc__TileDB-Py/examples/incomplete_iteration.py b/testbed/TileDB-Inc__TileDB-Py/examples/incomplete_iteration.py new file mode 100644 index 0000000000000000000000000000000000000000..4166cff7d9c1351ea977952b544c24c5a6531ab1 --- /dev/null +++ b/testbed/TileDB-Inc__TileDB-Py/examples/incomplete_iteration.py @@ -0,0 +1,117 @@ +# incomplete_iteration.py +# +# LICENSE +# +# The MIT License +# +# Copyright (c) 2020 TileDB, Inc. +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +# THE SOFTWARE. +# +# DESCRIPTION +# +# Please see the TileDB documentation for more information: +# https://docs.tiledb.com/main/how-to/arrays/reading-arrays/incomplete-queries +# +# When run, this program will create a 1D dense array, write some data +# to it, and read slices back by iteration over incomplete queries. +# + + +import numpy as np + +import tiledb + + +def check_dataframe_deps(): + pd_error = """Pandas version >= 1.0 and < 3.0 required for dataframe functionality. + Please `pip install pandas>=1.0,<3.0` to proceed.""" + + try: + import pandas as pd + except ImportError: + raise Exception(pd_error) + + from packaging.version import Version + + if Version(pd.__version__) < Version("1.0") or Version(pd.__version__) >= Version( + "3.0.0.dev0" + ): + raise Exception(pd_error) + + +# Name of the array to create. +array_name = "incomplete_iteration" + + +def create_array(): + # The array will be 100 cells with dimensions "x". + dom = tiledb.Domain(tiledb.Dim(name="x", domain=(0, 99), tile=100, dtype=np.int64)) + + # The array will be dense with a single string typed attribute "a" + schema = tiledb.ArraySchema( + domain=dom, sparse=True, attrs=[tiledb.Attr(name="a", dtype=str)] + ) + + # Create the (empty) array on disk. + tiledb.SparseArray.create(array_name, schema) + + +def write_array(): + # Open the array and write to it. + with tiledb.open(array_name, mode="w") as A: + extent = A.schema.domain.dim("x").domain + ncells = extent[1] - extent[0] + 1 + + # Data is the Latin alphabet with varying repeat lengths + data = [chr(i % 26 + 97) * (i % 52) for i in range(ncells)] + + # Coords are the dimension range + coords = np.arange(extent[0], extent[1] + 1) + + A[coords] = data + + +def read_array_iterated(): + # in order to force iteration, restrict the buffer sizes + # this setting gives 5 iterations for the example data + init_buffer_bytes = 800 + cfg = tiledb.Config( + { + "py.init_buffer_bytes": init_buffer_bytes, + "py.exact_init_buffer_bytes": "true", + } + ) + + with tiledb.open(array_name, config=cfg) as A: + # iterate over results as a dataframe + iterable = A.query(return_incomplete=True).df[:] + + for i, result in enumerate(iterable): + print(f"--- result {i} is a '{type(result)}' with size {len(result)}") + print(result) + print("---") + + print(f"Query completed after {i} iterations") + + +check_dataframe_deps() +create_array() +write_array() +read_array_iterated() diff --git a/testbed/TileDB-Inc__TileDB-Py/examples/multi_attribute.py b/testbed/TileDB-Inc__TileDB-Py/examples/multi_attribute.py new file mode 100644 index 0000000000000000000000000000000000000000..09cf8d3ee959a271e9f57ff331296c853b42d205 --- /dev/null +++ b/testbed/TileDB-Inc__TileDB-Py/examples/multi_attribute.py @@ -0,0 +1,159 @@ +# multi_attribute.py +# +# LICENSE +# +# The MIT License +# +# Copyright (c) 2020 TileDB, Inc. +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +# THE SOFTWARE. +# +# DESCRIPTION +# +# Please see the TileDB documentation for more information: +# https://docs.tiledb.com/main/how-to/arrays/reading-arrays/multi-range-subarrays +# +# When run, this program will create a simple 2D dense array with two +# attributes, write some data to it, and read a slice of the data back on +# (i) both attributes, and (ii) subselecting on only one of the attributes. +# + + +import numpy as np + +import tiledb + +# Name of the array to create. +array_name = "multi_attribute" + + +def create_array(): + # Check if the array already exists. + if tiledb.object_type(array_name) == "array": + return + + # The array will be 4x4 with dimensions "rows" and "cols", with domain [1,4]. + dom = tiledb.Domain( + tiledb.Dim(name="rows", domain=(1, 4), tile=4, dtype=np.int32), + tiledb.Dim(name="cols", domain=(1, 4), tile=4, dtype=np.int32), + ) + + # Add two attributes "a1" and "a2", so each (i,j) cell can store + # a character on "a1" and a vector of two floats on "a2". + schema = tiledb.ArraySchema( + domain=dom, + sparse=False, + attrs=[ + tiledb.Attr(name="a1", dtype=np.uint8), + tiledb.Attr( + name="a2", + dtype=np.dtype([("", np.float32), ("", np.float32), ("", np.float32)]), + ), + ], + ) + + # Create the (empty) array on disk. + tiledb.DenseArray.create(array_name, schema) + + +def write_array(): + # Open the array and write to it. + with tiledb.DenseArray(array_name, mode="w") as A: + data_a1 = np.array( + ( + list( + map( + ord, + [ + "a", + "b", + "c", + "d", + "e", + "f", + "g", + "h", + "i", + "j", + "k", + "l", + "m", + "n", + "o", + "p", + ], + ) + ) + ) + ) + data_a2 = np.array( + ( + [ + (1.1, 1.2, 1.3), + (2.1, 2.2, 2.3), + (3.1, 3.2, 3.3), + (4.1, 4.2, 4.3), + (5.1, 5.2, 5.3), + (6.1, 6.2, 6.3), + (7.1, 7.2, 7.3), + (8.1, 8.2, 8.3), + (9.1, 9.2, 9.3), + (10.1, 10.2, 10.3), + (11.1, 11.2, 11.3), + (12.1, 12.2, 12.3), + (13.1, 13.2, 13.3), + (14.1, 14.2, 14.3), + (15.1, 15.2, 15.3), + (16.1, 16.2, 16.3), + ] + ), + dtype=[("", np.float32), ("", np.float32), ("", np.float32)], + ) + A[:, :] = {"a1": data_a1, "a2": data_a2} + + +def read_array(): + # Open the array and read from it. + with tiledb.DenseArray(array_name, mode="r") as A: + # Slice only rows 1, 2 and cols 2, 3, 4. + data = A[1:3, 2:5] + print("Reading both attributes a1 and a2:") + a1, a2 = data["a1"].flat, data["a2"].flat + for i, v in enumerate(a1): + print( + "a1: '%s', a2: (%.1f,%.1f,%.1f)" + % (chr(v), a2[i][0], a2[i][1], a2[i][2]) + ) + + +def read_array_subselect(): + # Open the array and read from it. + with tiledb.DenseArray(array_name, mode="r") as A: + # Slice only rows 1, 2 and cols 2, 3, 4, attribute 'a1' only. + # We use the '.query()' syntax which allows attribute subselection. + data = A.query(attrs=["a1"])[1:3, 2:5] + print("Subselecting on attribute a1:") + for a in data["a1"].flat: + print("a1: '%s'" % chr(a)) + + +create_array() +write_array() +read_array() +read_array_subselect() diff --git a/testbed/TileDB-Inc__TileDB-Py/examples/multirange_indexing.py b/testbed/TileDB-Inc__TileDB-Py/examples/multirange_indexing.py new file mode 100644 index 0000000000000000000000000000000000000000..0fdbe8c82f5058cb48b0a6a2e16551b66695991b --- /dev/null +++ b/testbed/TileDB-Inc__TileDB-Py/examples/multirange_indexing.py @@ -0,0 +1,85 @@ +# multirange_indexing.py +# +# LICENSE +# +# The MIT License +# +# Copyright (c) 2020 TileDB, Inc. +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +# THE SOFTWARE. +# +# DESCRIPTION +# +# Please see the TileDB documentation for more information: +# https://docs.tiledb.com/main/how-to/arrays/reading-arrays/multi-range-subarrays +# +# When run, this program will create a simple 2D dense array with two +# attributes, write some data to it, and read a slice of the data back on +# (i) both attributes, and (ii) subselecting on only one of the attributes. +# + + +import numpy as np + +import tiledb + +# Name of the array to create. +array_name = "multi_range" + + +def create_array(): + # Check if the array already exists. + if tiledb.object_type(array_name) == "array": + return + + dom = tiledb.Domain( + tiledb.Dim(name="x", domain=(1, 20), tile=4, dtype=np.int64), + tiledb.Dim(name="y", domain=(1, 20), tile=4, dtype=np.int64), + ) + + # Add a single "a" float attribute + schema = tiledb.ArraySchema( + domain=dom, sparse=False, attrs=[tiledb.Attr(name="a", dtype=np.float64)] + ) + + # Create the (empty) array on disk. + tiledb.DenseArray.create(array_name, schema) + + +def write_array(): + # Open the array and write to it. + with tiledb.DenseArray(array_name, mode="w") as A: + data_a = np.arange(400).reshape(20, 20) + A[:, :] = {"a": data_a} + + +def read_array(): + # Open the array and read from it. + with tiledb.DenseArray(array_name, mode="r") as A: + # Slice only rows: (1,3) inclusive, and 5 + # cols: 2, 5, 7 + data = A.multi_index[[(1, 3), 5], [2, 5, 7]] + print("Reading attribute 'a', [ [1:3, 5], [2,5,7] ]") + a = data["a"] + print(a) + + +create_array() +write_array() +read_array() diff --git a/testbed/TileDB-Inc__TileDB-Py/examples/object.py b/testbed/TileDB-Inc__TileDB-Py/examples/object.py new file mode 100644 index 0000000000000000000000000000000000000000..ceac11acccc560e3d778ddd14af68a517813ddfc --- /dev/null +++ b/testbed/TileDB-Inc__TileDB-Py/examples/object.py @@ -0,0 +1,118 @@ +# object.py +# +# LICENSE +# +# The MIT License +# +# Copyright (c) 2020 TileDB, Inc. +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +# THE SOFTWARE. +# +# DESCRIPTION +# +# Please see the TileDB documentation for more information: +# https://docs.tiledb.com/main/how-to/object-management +# +# This program creates a hierarchy as shown below. Specifically, it creates +# groups `dense_arrays` and `sparse_arrays` in a group `my_group`, and +# then some dense/sparse arrays and key-value store in those groups. +# +# my_group/ +# - dense_arrays/ +# - array_A +# - array_B +# - sparse_arrays/ +# - array_C +# - array_D +# +# The program then shows how to list this hierarchy, as well as +# move/remove TileDB objects. + +import os + +import numpy as np + +import tiledb + + +def create_array(array_name, sparse): + if tiledb.object_type(array_name) == "array": + return + + dom = tiledb.Domain( + tiledb.Dim(name="rows", domain=(1, 4), tile=4, dtype=np.int32), + tiledb.Dim(name="cols", domain=(1, 4), tile=4, dtype=np.int32), + ) + schema = tiledb.ArraySchema( + domain=dom, sparse=sparse, attrs=[tiledb.Attr(name="a", dtype=np.int32)] + ) + if sparse: + tiledb.SparseArray.create(array_name, schema) + else: + tiledb.DenseArray.create(array_name, schema) + + +def path(p): + return os.path.join(os.getcwd(), p) + + +def create_hierarchy(): + # Create groups + tiledb.group_create(path("my_group")) + tiledb.group_create(path("my_group/dense_arrays")) + tiledb.group_create(path("my_group/sparse_arrays")) + + # Create arrays + create_array(path("my_group/dense_arrays/array_A"), False) + create_array(path("my_group/dense_arrays/array_B"), False) + create_array(path("my_group/sparse_arrays/array_C"), True) + create_array(path("my_group/sparse_arrays/array_D"), True) + + +def list_obj(path): + + # List children + print("\nListing hierarchy:") + tiledb.ls(path, lambda obj_path, obj_type: print(obj_path, obj_type)) + + # Walk in a path with a pre- and post-order traversal + print("\nPreorder traversal:") + tiledb.walk( + path, lambda obj_path, obj_type: print(obj_path, obj_type) + ) # Default order is preorder + + print("\nPostorder traversal:") + tiledb.walk( + path, lambda obj_path, obj_type: print(obj_path, obj_type), order="postorder" + ) + + +def move_remove_obj(): + tiledb.move(path("my_group"), path("my_group_2")) + tiledb.remove(path("my_group_2/dense_arrays")) + tiledb.remove(path("my_group_2/sparse_arrays/array_C")) + + +create_hierarchy() +list_obj("my_group") +move_remove_obj() # Renames 'my_group' to 'my_group_2' +list_obj("my_group_2") + +# clean up +tiledb.remove("my_group_2") diff --git a/testbed/TileDB-Inc__TileDB-Py/examples/parallel_csv_ingestion.py b/testbed/TileDB-Inc__TileDB-Py/examples/parallel_csv_ingestion.py new file mode 100644 index 0000000000000000000000000000000000000000..2038df709373dd1d03b1bcf0e0d73502ed343a8d --- /dev/null +++ b/testbed/TileDB-Inc__TileDB-Py/examples/parallel_csv_ingestion.py @@ -0,0 +1,344 @@ +# parallel_csv_ingestion.py +# +# LICENSE +# +# The MIT License +# +# Copyright (c) 2020 TileDB, Inc. +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +# THE SOFTWARE. +# +# DESCRIPTION +# +# This example demonstrates ingestion of CSV files in parallel +# with tiledb.from_csv and Python multiprocessing. +# + +import glob +import multiprocessing +import os +import tempfile +import time +from concurrent.futures import ProcessPoolExecutor + +import numpy as np + +import tiledb + +# helper functions to generate data +from tiledb.tests.common import rand_datetime64_array, rand_utf8 + +# are we running as a test +in_test = "PYTEST_CURRENT_TEST" in os.environ + + +def check_dataframe_deps(): + pd_error = """Pandas version >= 1.0 and < 3.0 required for dataframe functionality. + Please `pip install pandas>=1.0,<3.0` to proceed.""" + + try: + import pandas as pd + except ImportError: + raise Exception(pd_error) + + from packaging.version import Version + + if Version(pd.__version__) < Version("1.0") or Version(pd.__version__) >= Version( + "3.0.0.dev0" + ): + raise Exception(pd_error) + + +def generate_csvs(csv_folder, count=9, min_length=1, max_length=109): + def make_dataframe(col_size): + data = { + "idx_datetime": rand_datetime64_array(col_size, include_extremes=False), + "column_int64": np.random.randint(0, 150000, size=col_size, dtype=np.int64), + "column_uint32": np.random.randint( + 0, 150000, size=col_size, dtype=np.uint32 + ), + "column_float64": np.random.rand(col_size), + "column_utf8": np.array( + [rand_utf8(np.random.randint(1, 100)) for _ in range(col_size)] + ), + } + df = pd.DataFrame.from_dict(data) + + df.set_index("idx_datetime", inplace=True) + return df + + # create list of CSV row-counts to generate + # (each file will have nrows from this list) + csv_lengths = np.random.randint(min_length, max_length, size=count) + + for i, target_length in enumerate(csv_lengths): + output_path = os.path.join(csv_folder, "gen_csv_{}.csv".format(i)) + + df = make_dataframe(target_length) + df.to_csv(output_path) + + +def log_process_errors(*args, **kwargs): + try: + tiledb.from_csv(*args, **kwargs) + except Exception as exc: + # print log to file. randomize just in case + err_id = np.random.randint(np.iinfo(np.int64).max - 1) + err_filename = f"ingest-err-PID_{os.getpid()}_{err_id}.log" + print("err_filename: ", err_filename) + err = f""" ------------------------ + Caught exception: + ------------------------ + {exc} + ------------------------ + with args: + ------------------------ + {args} + ------------------------ + with kwargs: + ------------------------ + {kwargs} + ------------------------ + this message saved to file: {err_filename} + """ + print(err) + + with open(err_filename, "w") as f: + f.writelines(err) + + raise exc + + +def from_csv_mp( + csv_path, + array_path, + list_step_size=5, + chunksize=100, + max_workers=4, + initial_file_count=5, + index_col=None, + parse_dates=True, + attr_types=None, + sparse=True, + allows_duplicates=True, + debug=False, + **kwargs, +): + """ + Multi-process ingestion wrapper around tiledb.from_csv + + Currently uses ProcessPoolExecutor. + """ + + # Setting start method to 'spawn' is required to + # avoid problems with process global state when spawning via fork. + # NOTE: *must be inside __main__* or a function. + if multiprocessing.get_start_method(True) != "spawn": + multiprocessing.set_start_method("spawn", True) + + # Get a list of of CSVs from the target path + csvs = glob.glob(csv_path + "/*.csv") + + if len(csvs) < 1: + raise ValueError("Cannot ingest empty CSV list!") + + # first step: create the array. we read the first N csvs to create schema + # and as check for inconsistency before starting the full run. + tiledb.from_csv( + array_path, + csvs[:initial_file_count], + chunksize=chunksize, # must set chunksize here even though schema_only + index_col=index_col, + parse_dates=parse_dates, + dtype=attr_types, + column_types=attr_types, + engine="c", + debug=debug, + allows_duplicates=True, + sparse=sparse, + mode="schema_only", + **kwargs, + ) + + print("Finished array schema creation") + + # controls number of CSV files passed to each worker process: + # depending on the makeup of the files, we may want to read a number of + # files consecutively (up to chunksize) in order to write more optimal + # fragments. + if list_step_size > len(csvs): + raise ValueError( + "Please choose a step size smaller than the number of CSV files" + ) + + tasks = [] + # high level ingestion timing + start = time.time() + + # ingest the data in parallel + + # note: use ThreadPoolExecutor for debugging + # use ProcessPoolExecutor in general + # with ThreadPoolExecutor(max_workers=max_workers) as executor: + with ProcessPoolExecutor(max_workers=max_workers) as executor: + for first in range(0, len(csvs), list_step_size): + last = min(len(csvs), first + list_step_size) + print(" Submitting task for CSV list range: ", (first, last)) + task = executor.submit( + log_process_errors, + *(array_path, csvs[first:last]), + **dict( + chunksize=chunksize, + index_col=index_col, + parse_dates=parse_dates, + dtype=attr_types, + column_types=attr_types, + engine="c", + debug=debug, + allows_duplicates=allows_duplicates, + ), + **kwargs, + mode="append", + ) + tasks.append(task) + + print("Task results: ", [t.result() for t in tasks]) + + print("Ingestion complete. Duration: ", time.time() - start) + + +############################################################################## +# Usage example +############################################################################## +def example(): + # set up test paths and data + csv_path = tempfile.mkdtemp() + generate_csvs(csv_path, count=11) + print("Finished generating CSVs in path: ", csv_path) + + array_path = tempfile.mkdtemp() + print("Writing output array to: ", array_path) + + # Create Schema + attr_types = { + "column_int64": np.int64, + "column_uint32": np.uint32, + "column_float64": np.float64, + "column_utf8": str, + } + + from_csv_mp( + csv_path, + array_path, + chunksize=27, + list_step_size=5, + max_workers=4, + index_col=["idx_datetime"], + attr_types=attr_types, + ) + + print("Ingestion complete.") + print(" Note: temp paths have undefined lifetime after exit.") + + # apparently no good way to check for "is interactive" in python + if not in_test: + input(" Press any key to continue: ") + + return csv_path, array_path + + +if __name__ == "__main__" and not in_test: + example() + + +############################################################################## +# TEST SECTION +# uses this example as a test of various input combinations +############################################################################## +def df_from_csvs(path, **kwargs): + idx_column = kwargs.pop("tiledb_idx_column", None) + + csv_paths = glob.glob(path + "/*.csv") + csv_df_list = [pd.read_csv(p, **kwargs) for p in csv_paths] + + df = pd.concat(csv_df_list) + + if idx_column is not None: + df.sort_values(idx_column, inplace=True) + df.set_index(idx_column, inplace=True) + df.index = df.index.astype("datetime64[ns]") + + return df + + +def test_parallel_csv_ingestion(): + csv_path, array_path = example() + import pandas._testing as tm + + attr_types = { + "column_int64": np.int64, + "column_uint32": np.uint32, + "column_float64": np.float64, + # Avoid this runtime warning: "DeprecationWarning: `np.str` is a deprecated alias for the builtin `str`." + "column_utf8": str, + } + + # read dataframe from CSV list, set index, and sort + df_direct = df_from_csvs( + csv_path, dtype=attr_types, tiledb_idx_column="idx_datetime" + ) + + # validate the array generated in example() + df_tiledb = tiledb.open_dataframe(array_path) + tm.assert_frame_equal(df_direct, df_tiledb.sort_values("idx_datetime")) + + # ingest over several parameters + for nproc in [1, 5]: # note: already did 4 above + for csv_list_step in [5, 11]: + for chunksize in [10, 100]: + array_tmp = tempfile.mkdtemp() + + print( + "Running ingestion with nproc: '{}', step: '{}', chunksize: '{}'".format( + nproc, csv_list_step, chunksize + ) + ) + print("Writing output array to: ", array_tmp) + + from_csv_mp( + csv_path, + array_tmp, + chunksize=chunksize, + list_step_size=csv_list_step, + max_workers=nproc, + index_col=["idx_datetime"], + attr_types=attr_types, + ) + + df_tiledb = tiledb.open_dataframe(array_tmp) + tm.assert_frame_equal(df_direct, df_tiledb.sort_values("idx_datetime")) + + print("Writing output array to: ", array_path) + + +if __name__ == "__main__": + check_dataframe_deps() + import pandas as pd + + test_parallel_csv_ingestion() diff --git a/testbed/TileDB-Inc__TileDB-Py/examples/query_condition_datetime.py b/testbed/TileDB-Inc__TileDB-Py/examples/query_condition_datetime.py new file mode 100644 index 0000000000000000000000000000000000000000..abbfff66c3efc52b73a5c731c50f585e6a2fe951 --- /dev/null +++ b/testbed/TileDB-Inc__TileDB-Py/examples/query_condition_datetime.py @@ -0,0 +1,70 @@ +# query_condition_datetime.py +# +# LICENSE +# +# The MIT License +# +# Copyright (c) 2021 TileDB, Inc. +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +# THE SOFTWARE. +# + +# This example creates an array with one datetime-typed attribute, +# writes sample data to the array, and then prints out a filtered +# dataframe using the TileDB QueryCondition feature to select on +# either equality or ranges of the generated attribute values. + +import numpy as np +import pandas as pd + +import tiledb + +uri = "query_condition_datetime" + +data = pd.DataFrame( + np.sort(np.random.randint(438923600, 243892360000, 20, dtype=np.int64)).astype( + "M8[ns]" + ), + columns=["dates"], +) +data.sort_values(by="dates") + +tiledb.from_pandas( + uri, + data, + column_types={"dates": "datetime64[ns]"}, +) + +with tiledb.open(uri) as A: + # filter by exact match with the fifth cell + search_date = data["dates"][5].to_numpy().astype(np.int64) + result = A.query(cond=f"dates == {search_date}").df[:] + + print() + print("Attribute dates matching index 5:") + print(result) + + # filter values between cell index 3 and 8 + d1 = data["dates"].iloc[3].to_numpy().astype(np.int64) + d2 = data["dates"].iloc[8].to_numpy().astype(np.int64) + result2 = A.query(cond=f"dates > {d1} and dates < {d2}").df[:] + + print() + print("Attribute dates where 'dates[3] < val < dates[8]'") + print(result2) diff --git a/testbed/TileDB-Inc__TileDB-Py/examples/query_condition_dense.py b/testbed/TileDB-Inc__TileDB-Py/examples/query_condition_dense.py new file mode 100644 index 0000000000000000000000000000000000000000..270f7cbeccaceafec569a04f934d5d8e34348b8d --- /dev/null +++ b/testbed/TileDB-Inc__TileDB-Py/examples/query_condition_dense.py @@ -0,0 +1,105 @@ +# query_condition_dense.py +# +# LICENSE +# +# The MIT License +# +# Copyright (c) 2021 TileDB, Inc. +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +# THE SOFTWARE. +# + +# This example creates an array with one string-typed attribute, +# writes sample data to the array, and then prints out a filtered +# dataframe using the TileDB QueryCondition feature. + +from pprint import pprint + +import numpy as np + +import tiledb + +uri = "query_condition_dense" + + +def create_array(path): + # create a dense array + dom = tiledb.Domain( + tiledb.Dim(name="coords", domain=(1, 10), tile=1, dtype=np.uint32) + ) + attrs = [ + tiledb.Attr(name="attr1", dtype=np.uint64), + tiledb.Attr(name="attr2", dtype=np.float64), + ] + schema = tiledb.ArraySchema(domain=dom, attrs=attrs, sparse=False) + tiledb.Array.create(path, schema, overwrite=True) + + # fill array with randomized values + with tiledb.open(path, "w") as arr: + rand = np.random.default_rng() + arr[:] = { + "attr1": rand.integers(low=0, high=10, size=10), + "attr2": rand.random(size=10), + } + + +def read_array(path): + with tiledb.open(uri) as arr: + print("--- without query condition:") + print() + pprint(arr[:]) + print() + + with tiledb.open(uri) as arr: + qc = "(2 < attr1 < 6) and (attr2 < 0.5 or attr2 > 0.85)" + print(f"--- with query condition {qc}:") + + print(f"--- the fill value for attr1 is {arr.attr('attr1').fill}") + print(f"--- the fill value for attr2 is {arr.attr('attr2').fill}") + + print() + res = arr.query(cond=qc)[:] + pprint(res) + + +if __name__ == "__main__": + """Example output for `python query_condition_dense.py`: + + --- without query condition: + + OrderedDict([('attr1', array([4, 0, 9, 7, 6, 0, 0, 5, 7, 5], dtype=uint64)), + ('attr2', + array([0.74476144, 0.47211544, 0.99054245, 0.36640416, 0.91699594, + 0.06216043, 0.58581863, 0.00505695, 0.7486192 , 0.87649422]))]) + + --- with query condition (2 < attr1 < 6) and (attr2 < 0.5 or attr2 > 0.85): + --- the fill value for attr1 is [18446744073709551615] + --- the fill value for attr2 is [nan] + + OrderedDict([('attr1', + array([18446744073709551615, 18446744073709551615, 18446744073709551615, + 18446744073709551615, 18446744073709551615, 18446744073709551615, + 18446744073709551615, 5, 18446744073709551615, + 5], dtype=uint64)), + ('attr2', + array([ nan, nan, nan, nan, nan, + nan, nan, 0.00505695, nan, 0.87649422]))]) + """ + create_array(uri) + read_array(uri) diff --git a/testbed/TileDB-Inc__TileDB-Py/examples/query_condition_sparse.py b/testbed/TileDB-Inc__TileDB-Py/examples/query_condition_sparse.py new file mode 100644 index 0000000000000000000000000000000000000000..bfcfbf6fad2eda34dca7cf95093452e45ca1d9e9 --- /dev/null +++ b/testbed/TileDB-Inc__TileDB-Py/examples/query_condition_sparse.py @@ -0,0 +1,96 @@ +# query_condition_sparse.py +# +# LICENSE +# +# The MIT License +# +# Copyright (c) 2021 TileDB, Inc. +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +# THE SOFTWARE. +# + +# This example creates an array with one string-typed attribute, +# writes sample data to the array, and then prints out a filtered +# dataframe using the TileDB QueryCondition feature. + +from pprint import pprint + +import numpy as np + +import tiledb + +uri = "query_condition_sparse" + + +def create_array(path): + # create a sparse array + dom = tiledb.Domain( + tiledb.Dim(name="coords", domain=(1, 10), tile=1, dtype=np.uint32) + ) + attrs = [ + tiledb.Attr(name="attr1", dtype=np.uint64), + tiledb.Attr(name="attr2", dtype=np.float64), + ] + schema = tiledb.ArraySchema(domain=dom, attrs=attrs, sparse=True) + tiledb.Array.create(path, schema, overwrite=True) + + # fill array with randomized values + with tiledb.open(path, "w") as arr: + rand = np.random.default_rng() + arr[np.arange(1, 11)] = { + "attr1": rand.integers(low=0, high=10, size=10), + "attr2": rand.random(size=10), + } + + +def read_array(path): + with tiledb.open(uri) as arr: + print("--- without query condition:") + print() + pprint(arr[:]) + print() + + with tiledb.open(uri) as arr: + qc = "(2 < attr1 < 6) and (attr2 < 0.5 or attr2 > 0.85)" + print(f"--- with query condition {qc}:") + print() + res = arr.query(cond=qc)[:] + pprint(res) + + +if __name__ == "__main__": + """Example output for `python query_condition_sparse.py`: + + --- without query condition: + + OrderedDict([('attr1', array([2, 4, 4, 3, 4, 7, 5, 2, 2, 8], dtype=uint64)), + ('attr2', + array([0.62445071, 0.32415481, 0.39117764, 0.66609931, 0.48122102, + 0.93561984, 0.70998524, 0.10322076, 0.28343041, 0.33623958])), + ('coords', + array([ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10], dtype=uint32))]) + + --- with query condition (2 < attr1 < 6) and (attr2 < 0.5 or attr2 > 0.85): + + OrderedDict([('attr1', array([4, 4, 4], dtype=uint64)), + ('attr2', array([0.32415481, 0.39117764, 0.48122102])), + ('coords', array([2, 3, 5], dtype=uint32))]) + """ + create_array(uri) + read_array(uri) diff --git a/testbed/TileDB-Inc__TileDB-Py/examples/query_condition_string.py b/testbed/TileDB-Inc__TileDB-Py/examples/query_condition_string.py new file mode 100644 index 0000000000000000000000000000000000000000..1dfc8286d76efcf9034e26e3992c3c129849f8b6 --- /dev/null +++ b/testbed/TileDB-Inc__TileDB-Py/examples/query_condition_string.py @@ -0,0 +1,67 @@ +# query_condition_string.py +# +# LICENSE +# +# The MIT License +# +# Copyright (c) 2021 TileDB, Inc. +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +# THE SOFTWARE. +# + +# This example creates an array with one string-typed attribute, +# writes sample data to the array, and then prints out a filtered +# dataframe using the TileDB QueryCondition feature. + +import string + +import numpy as np + +import tiledb + + +def create_array(path): + dom = tiledb.Domain(tiledb.Dim(name="d", domain=(1, 10), tile=1, dtype=np.uint32)) + attrs = [tiledb.Attr(name="ascii_attr", dtype="ascii", var=True)] + + schema = tiledb.ArraySchema(domain=dom, attrs=attrs, sparse=True) + + tiledb.SparseArray.create(path, schema, overwrite=True) + + # create array of strings from a to a..j + attr_data = np.array([string.ascii_lowercase[0:n] for n in range(1, 11)], dtype="O") + + with tiledb.open(path, "w") as arr: + arr[np.arange(1, 11)] = {"ascii_attr": attr_data} + + +def read_array(path, cond): + with tiledb.open(path) as arr: + print("QueryCondition is: ", cond) + res = arr.query(cond=cond)[:] + return res + + +uri = "query_condition_string" + +create_array(uri) +filtered_df1 = read_array(uri, "ascii_attr == 'abcd'") +print(" result: ", filtered_df1) +filtered_df2 = read_array(uri, "ascii_attr > 'abc'") +print(" result: ", filtered_df2) diff --git a/testbed/TileDB-Inc__TileDB-Py/examples/quickstart_dense.py b/testbed/TileDB-Inc__TileDB-Py/examples/quickstart_dense.py new file mode 100644 index 0000000000000000000000000000000000000000..a9a57d43a039a1f57e036dec5236c14cc9c21d2b --- /dev/null +++ b/testbed/TileDB-Inc__TileDB-Py/examples/quickstart_dense.py @@ -0,0 +1,82 @@ +# quickstart_dense.py +# +# LICENSE +# +# The MIT License +# +# Copyright (c) 2020 TileDB, Inc. +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +# THE SOFTWARE. +# +# DESCRIPTION +# +# Please refer to the TileDB and TileDB-Py documentation for more information: +# https://docs.tiledb.com/main/how-to +# https://tiledb-inc-tiledb.readthedocs-hosted.com/projects/tiledb-py/en/stable/python-api.html +# +# When run, this program will create a simple 2D dense array, write some data +# to it, and read a slice of the data back. +# + + +import numpy as np + +import tiledb + +# Name of the array to create. +array_name = "quickstart_dense" + + +def create_array(): + + # The array will be 4x4 with dimensions "rows" and "cols", with domain [1,4]. + dom = tiledb.Domain( + tiledb.Dim(name="rows", domain=(1, 4), tile=4, dtype=np.int32), + tiledb.Dim(name="cols", domain=(1, 4), tile=4, dtype=np.int32), + ) + + # The array will be dense with a single attribute "a" so each (i,j) cell can store an integer. + schema = tiledb.ArraySchema( + domain=dom, sparse=False, attrs=[tiledb.Attr(name="a", dtype=np.int32)] + ) + + # Create the (empty) array on disk. + tiledb.DenseArray.create(array_name, schema) + + +def write_array(): + # Open the array and write to it. + with tiledb.DenseArray(array_name, mode="w") as A: + data = np.array(([1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16])) + A[:] = data + + +def read_array(): + # Open the array and read from it. + with tiledb.DenseArray(array_name, mode="r") as A: + # Slice only rows 1, 2 and cols 2, 3, 4. + data = A[1:3, 2:5] + print(data["a"]) + + +if tiledb.object_type(array_name) != "array": + create_array() + write_array() + +read_array() diff --git a/testbed/TileDB-Inc__TileDB-Py/examples/quickstart_dimension_labels.py b/testbed/TileDB-Inc__TileDB-Py/examples/quickstart_dimension_labels.py new file mode 100644 index 0000000000000000000000000000000000000000..7427689ec0e2475b99d87a93c7fed7834e70b044 --- /dev/null +++ b/testbed/TileDB-Inc__TileDB-Py/examples/quickstart_dimension_labels.py @@ -0,0 +1,109 @@ +# quickstart_dimension_labels.py +# +# LICENSE +# +# The MIT License +# +# Copyright (c) 2023 TileDB, Inc. +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +# THE SOFTWARE. +# +# DESCRIPTION +# +# Please refer to the TileDB and TileDB-Py documentation for more information: +# https://docs.tiledb.com/main/how-to +# https://tiledb-inc-tiledb.readthedocs-hosted.com/projects/tiledb-py/en/stable/python-api.html +# +# When run, this program will create a simple 2D dense array with dimension labels, write +# some data to it, and read a slice of the data back. +# + + +import numpy as np + +import tiledb + + +def create_array(uri: str): + """Create array schema with dimension labels""" + dim1 = tiledb.Dim("d1", domain=(1, 5)) + dim2 = tiledb.Dim("d2", domain=(1, 5)) + dom = tiledb.Domain(dim1, dim2) + att = tiledb.Attr("a1", dtype=np.int64) + dim_labels = { + 0: {"l1": dim1.create_label_schema("decreasing", np.int64)}, + 1: { + "l2": dim2.create_label_schema("increasing", np.int64), + "l3": dim2.create_label_schema("increasing", np.float64), + }, + } + schema = tiledb.ArraySchema(domain=dom, attrs=(att,), dim_labels=dim_labels) + tiledb.Array.create(uri, schema) + + +def write_array(uri: str): + """Write attribute and label data to the array""" + a1_data = np.reshape(np.arange(1, 26), (5, 5)) + l1_data = np.arange(5, 0, -1) + l2_data = np.arange(-2, 3) + l3_data = np.linspace(-1.0, 1.0, 5) + with tiledb.open(uri, "w") as array: + array[:] = {"a1": a1_data, "l1": l1_data, "l2": l2_data, "l3": l3_data} + + +def read_array(uri: str): + """Read the array from the dimension label""" + + with tiledb.open(uri, "r") as array: + data1 = array.label_index(["l2"])[1, -1:1] + print("Reading array on [[1, -1:1]] with label 'l2' on dim2") + for name, value in data1.items(): + print(f" '{name}'={value}") + + data2 = array.label_index(["l1", "l2"])[4:5, -2:2] + print("Reading array on [[4:5, -2:2]] with label 'l1' on dim1 and 'l2' on dim2") + for name, value in data2.items(): + print(f" '{name}'={value}") + + data3 = array.label_index(["l3"])[1, 0.0:2.0] + print("Reading array on [[1, 0.0:2.0]] with label 'l3' on dim2") + for name, value in data3.items(): + print(f" '{name}'={value}") + + +if __name__ == "__main__": + # Name of the array to create. + ARRAY_NAME = "quickstart_labels" + + LIBVERSION = tiledb.libtiledb.version() + + if LIBVERSION[0] == 2 and LIBVERSION[1] < 15: + print( + f"Dimension labels requires libtiledb version >= 2.15.0. Current version is" + f" {LIBVERSION[0]}.{LIBVERSION[1]}.{LIBVERSION[2]}" + ) + + else: + # Only create and write to the array if it doesn't already exist. + if tiledb.object_type(ARRAY_NAME) != "array": + create_array(ARRAY_NAME) + write_array(ARRAY_NAME) + + # Read from the array and print output. + read_array(ARRAY_NAME) diff --git a/testbed/TileDB-Inc__TileDB-Py/examples/quickstart_dimension_labels_sparse.py b/testbed/TileDB-Inc__TileDB-Py/examples/quickstart_dimension_labels_sparse.py new file mode 100644 index 0000000000000000000000000000000000000000..9dd03fec98cbc6acbe300d2338a01816655eeeab --- /dev/null +++ b/testbed/TileDB-Inc__TileDB-Py/examples/quickstart_dimension_labels_sparse.py @@ -0,0 +1,121 @@ +# quickstart_dimension_labels_sparse.py +# +# LICENSE +# +# The MIT License +# +# Copyright (c) 2023 TileDB, Inc. +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +# THE SOFTWARE. +# +# DESCRIPTION +# +# Please refer to the TileDB and TileDB-Py documentation for more information: +# https://docs.tiledb.com/main/how-to +# https://tiledb-inc-tiledb.readthedocs-hosted.com/projects/tiledb-py/en/stable/python-api.html +# +# When run, this program will create a simple 2D sparse array with dimension labels, write +# some data to it, and read a slice of the data back. + + +import numpy as np + +import tiledb + + +def create_array(uri: str): + """Create array schema with dimension labels""" + dim1 = tiledb.Dim("index1", domain=(0, 5)) + dim2 = tiledb.Dim("index2", domain=(0, 5)) + dom = tiledb.Domain(dim1, dim2) + att = tiledb.Attr("values", dtype=np.int64) + dim_labels = { + 0: {"x1": dim1.create_label_schema("increasing", np.float64, tile=6)}, + 1: {"x2": dim2.create_label_schema("increasing", np.float64, tile=6)}, + } + schema = tiledb.ArraySchema( + domain=dom, attrs=(att,), dim_labels=dim_labels, sparse=True + ) + tiledb.Array.create(uri, schema) + + +def write_array(uri: str): + """Write attribute and label data to the array""" + # Use dimension label URIs to write directly to dimension label arrays. + schema = tiledb.ArraySchema.load(uri) + with tiledb.open(schema.dim_label("x1").uri, "w") as x1_array: + x1_array[:] = np.linspace(-1.0, 1.0, 6) + with tiledb.open(schema.dim_label("x2").uri, "w") as x2_array: + x2_array[:] = np.linspace(-1.0, 1.0, 6) + + # Write a tridiagonal matrix. + coords1 = np.append(np.arange(1, 6), np.arange(5)) + coords2 = np.append(np.arange(5), np.arange(1, 6)) + data = np.append(np.arange(1, 6), -np.arange(1, 6)) + with tiledb.open(uri, "w") as array: + array[coords1, coords2] = data + + +def read_array(uri: str): + """Read the array from the dimension label""" + + with tiledb.open(uri, "r") as array: + # Create a subarray and set label ranges. + subarray = tiledb.Subarray(array) + subarray.add_label_range("x1", (0.0, 1.0)) + subarray.add_label_range("x2", (0.0, 1.0)) + + # Get data from the main array. + data = array.read_subarray(subarray) + + # Read the labels. + x1_label = array.schema.dim_label("x1") + x2_label = array.schema.dim_label("x2") + with tiledb.open(x1_label.uri) as x1_array: + x1_coords = x1_array.multi_index[data["index1"]] + data["x1"] = x1_coords[x1_label.label_attr_name] + with tiledb.open(array.schema.dim_label("x2").uri) as x2_array: + x2_coords = x2_array.multi_index[data["index2"]] + data["x2"] = x2_coords[x2_label.label_attr_name] + + print("Reading data where 0.0 <= x1 <= 2.0 and -2.0 <= x2 <= 0.0") + for name, value in data.items(): + print(f" '{name}'={value}") + + +if __name__ == "__main__": + # Name of the array to create. + ARRAY_NAME = "quickstart_labels_sparse" + + LIBVERSION = tiledb.libtiledb.version() + + if LIBVERSION[0] == 2 and LIBVERSION[1] < 15: + print( + f"Dimension labels requires libtiledb version >= 2.15.0. Current version is" + f" {LIBVERSION[0]}.{LIBVERSION[1]}.{LIBVERSION[2]}" + ) + + else: + # Only create and write to the array if it doesn't already exist. + if tiledb.object_type(ARRAY_NAME) != "array": + create_array(ARRAY_NAME) + write_array(ARRAY_NAME) + + # Read from the array and print output. + read_array(ARRAY_NAME) diff --git a/testbed/TileDB-Inc__TileDB-Py/examples/quickstart_sparse.py b/testbed/TileDB-Inc__TileDB-Py/examples/quickstart_sparse.py new file mode 100644 index 0000000000000000000000000000000000000000..6b4906c1844e86f8add056c7e7a80e8a1543bac5 --- /dev/null +++ b/testbed/TileDB-Inc__TileDB-Py/examples/quickstart_sparse.py @@ -0,0 +1,85 @@ +# quickstart_sparse.py +# +# LICENSE +# +# The MIT License +# +# Copyright (c) 2020 TileDB, Inc. +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +# THE SOFTWARE. +# +# DESCRIPTION +# +# Please refer to the TileDB and TileDB-Py documentation for more information: +# https://docs.tiledb.com/main/how-to +# https://tiledb-inc-tiledb.readthedocs-hosted.com/projects/tiledb-py/en/stable/python-api.html +# +# When run, this program will create a simple 2D sparse array, write some data +# to it, and read a slice of the data back. +# + + +import numpy as np + +import tiledb + +# Name of the array to create. +array_name = "quickstart_sparse" + + +def create_array(): + # The array will be 4x4 with dimensions "rows" and "cols", with domain [1,4]. + dom = tiledb.Domain( + tiledb.Dim(name="rows", domain=(1, 4), tile=4, dtype=np.int32), + tiledb.Dim(name="cols", domain=(1, 4), tile=4, dtype=np.int32), + ) + + # The array will be sparse with a single attribute "a" so each (i,j) cell can store an integer. + schema = tiledb.ArraySchema( + domain=dom, sparse=True, attrs=[tiledb.Attr(name="a", dtype=np.int32)] + ) + + # Create the (empty) array on disk. + tiledb.SparseArray.create(array_name, schema) + + +def write_array(): + # Open the array and write to it. + with tiledb.SparseArray(array_name, mode="w") as A: + # Write some simple data to cells (1, 1), (2, 4) and (2, 3). + IJ = [1, 2, 2], [1, 4, 3] + data = np.array(([1, 2, 3])) + A[IJ] = data + + +def read_array(): + # Open the array and read from it. + with tiledb.SparseArray(array_name, mode="r") as A: + # Slice only rows 1, 2 and cols 2, 3, 4. + data = A[1:3, 2:5] + a_vals = data["a"] + for i, coord in enumerate(zip(data["rows"], data["cols"])): + print("Cell (%d, %d) has data %d" % (coord[0], coord[1], a_vals[i])) + + +if tiledb.object_type(array_name) != "array": + create_array() + write_array() + +read_array() diff --git a/testbed/TileDB-Inc__TileDB-Py/examples/reading_dense_layouts.py b/testbed/TileDB-Inc__TileDB-Py/examples/reading_dense_layouts.py new file mode 100644 index 0000000000000000000000000000000000000000..a96c80724bf97ceee9c412d67ab229735d67e2f9 --- /dev/null +++ b/testbed/TileDB-Inc__TileDB-Py/examples/reading_dense_layouts.py @@ -0,0 +1,120 @@ +# reading_dense_layouts.py +# +# LICENSE +# +# The MIT License +# +# Copyright (c) 2020 TileDB, Inc. +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +# THE SOFTWARE. +# +# DESCRIPTION +# +# Please see the TileDB documentation for more information: +# https://docs.tiledb.com/main/how-to/arrays/reading-arrays/basic-reading +# +# When run, this program will create a simple 2D dense array, write some data +# to it, and read a slice of the data back in the layout of the user's choice +# (passed as an argument to the program: "row", "col", or "global"). +# + +import sys + +import numpy as np + +import tiledb + +# Name of the array to create. +array_name = "reading_dense_layouts" + + +def create_array(): + # The array will be 4x4 with dimensions "rows" and "cols", with domain [1,4]. + dom = tiledb.Domain( + tiledb.Dim(name="rows", domain=(1, 4), tile=2, dtype=np.int32), + tiledb.Dim(name="cols", domain=(1, 4), tile=2, dtype=np.int32), + ) + + # The array will be dense with a single attribute "a" so each (i,j) cell can store an integer. + schema = tiledb.ArraySchema( + domain=dom, sparse=False, attrs=[tiledb.Attr(name="a", dtype=np.int32)] + ) + + # Create the (empty) array on disk. + tiledb.DenseArray.create(array_name, schema) + + +def write_array(): + # Open the array and write to it. + with tiledb.DenseArray(array_name, mode="w") as A: + # NOTE: global writes are not currently supported in the Python API. + # The following code will produce the same array as the corresponding + # C++ example in the docs (which wrote in global order) + data = np.array(([1, 2, 5, 6], [3, 4, 7, 8], [9, 10, 13, 14], [11, 12, 15, 16])) + A[:] = data + + +def read_array(order): + # Open the array and read from it. + with tiledb.DenseArray(array_name, mode="r") as A: + # Get non-empty domain + print("Non-empty domain: {}".format(A.nonempty_domain())) + + # Slice only rows 1, 2 and cols 2, 3, 4. + # NOTE: The `query` syntax is required to get the coordinates for + # dense arrays and specify an order other than the default row-major + data = A.query(attrs=["a"], order=order, coords=True)[1:3, 2:5] + a_vals = data["a"] + coords = np.asarray(list(zip(data["rows"], data["cols"]))) + + if order != "G" and a_vals.flags["F_CONTIGUOUS"]: + print("NOTE: The following result array has col-major layout internally") + + if order != "G": + for i in range(coords.shape[0]): + for j in range(coords.shape[1]): + print( + "Cell {} has data {}".format( + str(coords[i, j]), str(a_vals[i, j]) + ) + ) + else: + # When reading in global order, TileDB always returns a vector (1D array) + for i in range(coords.shape[0]): + print("Cell {} has data {}".format(str(coords[i]), str(a_vals[i]))) + + +# Check if the array already exists. +if tiledb.object_type(array_name) != "array": + create_array() + write_array() + +layout = "" +if len(sys.argv) > 1: + layout = sys.argv[1] + +order = "C" +if layout == "col": + order = "F" +elif layout == "global": + order = "G" +else: + order = "C" + +read_array(order) diff --git a/testbed/TileDB-Inc__TileDB-Py/examples/reading_sparse_layouts.py b/testbed/TileDB-Inc__TileDB-Py/examples/reading_sparse_layouts.py new file mode 100644 index 0000000000000000000000000000000000000000..cdc7309a62de261423036f4cf3e0f9c09ae0ac66 --- /dev/null +++ b/testbed/TileDB-Inc__TileDB-Py/examples/reading_sparse_layouts.py @@ -0,0 +1,106 @@ +# reading_sparse_layouts.py +# +# LICENSE +# +# The MIT License +# +# Copyright (c) 2020 TileDB, Inc. +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +# THE SOFTWARE. +# +# DESCRIPTION +# +# Please see the TileDB documentation for more information: +# https://docs.tiledb.com/main/how-to/arrays/reading-arrays/basic-reading +# +# When run, this program will create a simple 2D sparse array, write some data +# to it, and read a slice of the data back in the layout of the user's choice +# (passed as an argument to the program: "row", "col", or "global"). +# + + +import sys + +import numpy as np + +import tiledb + +# Name of the array to create. +array_name = "reading_sparse_layouts" + + +def create_array(): + # The array will be 4x4 with dimensions "rows" and "cols", with domain [1,4]. + dom = tiledb.Domain( + tiledb.Dim(name="rows", domain=(1, 4), tile=2, dtype=np.int32), + tiledb.Dim(name="cols", domain=(1, 4), tile=2, dtype=np.int32), + ) + + # The array will be sparse with a single attribute "a" so each (i,j) cell can store an integer. + schema = tiledb.ArraySchema( + domain=dom, sparse=True, attrs=[tiledb.Attr(name="a", dtype=np.int32)] + ) + + # Create the (empty) array on disk. + tiledb.SparseArray.create(array_name, schema) + + +def write_array(): + # Open the array and write to it. + with tiledb.SparseArray(array_name, mode="w") as A: + # To write, the coordinates must be split into two vectors, one per dimension + IJ = [1, 1, 2, 1, 2, 2], [1, 2, 2, 4, 3, 4] + data = np.array(([1, 2, 3, 4, 5, 6])) + A[IJ] = data + + +def read_array(order): + # Open the array and read from it. + with tiledb.SparseArray(array_name, mode="r") as A: + # Get non-empty domain + print("Non-empty domain: {}".format(A.nonempty_domain())) + + # Slice only rows 1, 2 and cols 2, 3, 4. + # NOTE: The `query` syntax is required to specify an order + # other than the default row-major + data = A.query(attrs=["a"], order=order, coords=True)[1:3, 2:5] + a_vals = data["a"] + + for i, coord in enumerate(zip(data["rows"], data["cols"])): + print("Cell {} has data {}".format(str(coord), str(a_vals[i]))) + + +# Check if the array already exists. +if tiledb.object_type(array_name) != "array": + create_array() + write_array() + +layout = "" +if len(sys.argv) > 1: + layout = sys.argv[1] + +order = "C" +if layout == "col": + order = "F" +elif layout == "global": + order = "G" +else: + order = "C" + +read_array(order) diff --git a/testbed/TileDB-Inc__TileDB-Py/examples/string_dimension_labels.py b/testbed/TileDB-Inc__TileDB-Py/examples/string_dimension_labels.py new file mode 100644 index 0000000000000000000000000000000000000000..443896626e2fdf41e8d10916eb424a93fae79846 --- /dev/null +++ b/testbed/TileDB-Inc__TileDB-Py/examples/string_dimension_labels.py @@ -0,0 +1,92 @@ +# string_dimension_label.py +# +# LICENSE +# +# The MIT License +# +# Copyright (c) 2023 TileDB, Inc. +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +# THE SOFTWARE. +# +# DESCRIPTION +# +# Please refer to the TileDB and TileDB-Py documentation for more information: +# https://docs.tiledb.com/main/how-to +# https://tiledb-inc-tiledb.readthedocs-hosted.com/projects/tiledb-py/en/stable/python-api.html +# +# When run, this program will create a simple 2D dense array with a string dimension +# dimension on the column dimension, and read a slice back with the dimension label. +# + +import numpy as np + +import tiledb + + +def create_array(uri: str): + """Create array schema with a dimension label on the columns""" + dim1 = tiledb.Dim("row", domain=(1, 5)) + dim2 = tiledb.Dim("column", domain=(1, 5)) + dom = tiledb.Domain(dim1, dim2) + att = tiledb.Attr("a1", dtype=np.int64) + dim_labels = {1: {"name": dim2.create_label_schema("increasing", "ascii")}} + schema = tiledb.ArraySchema(domain=dom, attrs=(att,), dim_labels=dim_labels) + tiledb.Array.create(uri, schema) + + +def write_array(uri: str): + """Write attribute and label data to the array""" + a1_data = np.reshape(np.arange(1, 26), (5, 5)) + label_data = np.array(["alpha", "beta", "gamma", "kappa", "omega"]) + with tiledb.open(uri, "w") as array: + array[:, :] = {"a1": a1_data, "name": label_data} + + +def read_array(uri: str): + """Read the array from the dimension label""" + + with tiledb.open(uri, "r") as array: + data = array.label_index(["name"])[1, "beta":"kappa"] + print( + "Reading array on [[1, 'beta':'kappa']] with label 'name' on dimension 'col'" + ) + for name, value in data.items(): + print(f" '{name}'={value}") + + +if __name__ == "__main__": + # Name of the array to create. + ARRAY_NAME = "string_dimension_labels" + + LIBVERSION = tiledb.libtiledb.version() + + if LIBVERSION[0] == 2 and LIBVERSION[1] < 15: + print( + f"Dimension labels requires libtiledb version >= 2.15.0. Current version is" + f" {LIBVERSION[0]}.{LIBVERSION[1]}.{LIBVERSION[2]}" + ) + + else: + # Only create and write to the array if it doesn't already exist. + if tiledb.object_type(ARRAY_NAME) != "array": + create_array(ARRAY_NAME) + write_array(ARRAY_NAME) + + # Read from the array and print output. + read_array(ARRAY_NAME) diff --git a/testbed/TileDB-Inc__TileDB-Py/examples/string_float_int_dimensions.py b/testbed/TileDB-Inc__TileDB-Py/examples/string_float_int_dimensions.py new file mode 100644 index 0000000000000000000000000000000000000000..d1fb03b95debfd762f5012348860133263ea3a2e --- /dev/null +++ b/testbed/TileDB-Inc__TileDB-Py/examples/string_float_int_dimensions.py @@ -0,0 +1,82 @@ +# quickstart_dense.py +# +# LICENSE +# +# The MIT License +# +# Copyright (c) 2020 TileDB, Inc. +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +# THE SOFTWARE. +# +# DESCRIPTION +# +# Please see the TileDB documentation for more information: +# https://docs.tiledb.com/main/how-to/arrays/creating-arrays/creating-dimensions +# +# When run, this program will create a simple 2D dense array, write some data +# to it, and read a slice of the data back. +# + + +import numpy as np + +import tiledb + +path = "sparse_mixed_demo" + +dom = tiledb.Domain( + *[ + tiledb.Dim(name="str_dim", domain=(None, None), dtype=np.bytes_), + tiledb.Dim(name="int64_dim", domain=(0, 100), tile=10, dtype=np.int64), + tiledb.Dim( + name="float64_dim", + domain=(-100.0, 100.0), + tile=10, + dtype=np.float64, + ), + ], +) + +att = tiledb.Attr(name="a", dtype=np.int64) +schema = tiledb.ArraySchema(domain=dom, attrs=(att,), sparse=True, capacity=10000) +tiledb.SparseArray.create(path, schema) + +data = [1, 2, 3, 4] +c_str = [b"aa", b"bbb", b"c", b"dddd"] +c_int64 = [0, 10, 20, 30] +c_float64 = [-95.0, -61.5, 1.3, 42.7] + +with tiledb.open(path, "w") as A: + A[c_str, c_int64, c_float64] = data + +with tiledb.open(path) as A: + print("\n\nRead full array:\n") + print(A[:]) + + print("\n\nRead string slice A['c':'dddd']:\n") + print(A["c":"dddd"]) + + print("\n\nRead A[:, 10]: \n") + print(A["aa":"bbb"]) + + print("\n\nRead A.multi_index['aa':'c', 0:10]\n") + print(A.multi_index["aa":"c", 0:10]) + + print("\n\nRead A.multi_index['aa':'bbb', :, -95.0:-61.5]\n") + print(A.multi_index["aa":"bbb", :, -95.0:-61.5]) diff --git a/testbed/TileDB-Inc__TileDB-Py/examples/time_traveling.py b/testbed/TileDB-Inc__TileDB-Py/examples/time_traveling.py new file mode 100644 index 0000000000000000000000000000000000000000..64a0e410bce6ccf8ce4c9fe4c307334a12356a34 --- /dev/null +++ b/testbed/TileDB-Inc__TileDB-Py/examples/time_traveling.py @@ -0,0 +1,77 @@ +# time_traveling.py +# +# LICENSE +# +# The MIT License +# +# Copyright (c) 2020 TileDB, Inc. +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +# THE SOFTWARE. +# +# DESCRIPTION +# +# When run, this program will create a simple sparse array, write some data +# to it at specified timestamps, and read the entire array data back. +# + +import numpy as np + +import tiledb + +# Name of the array to create. +array_name = "time_traveling" + + +def create_array(): + dom = tiledb.Domain(tiledb.Dim(domain=(0, 0), tile=1, dtype=np.int64)) + att = tiledb.Attr(name="num", dtype=np.int64) + schema = tiledb.ArraySchema(sparse=True, domain=dom, attrs=(att,)) + tiledb.SparseArray.create(array_name, schema) + + +def write_array(): + # Open the array and write to it. + for timestamp in range(1, 4): + with tiledb.open(array_name, timestamp=timestamp, mode="w") as T: + T[0] = timestamp + + +def read_array(): + # Open the array and read from it. + with tiledb.open(array_name, mode="r") as T: + print(T[:]["num"]) + + with tiledb.open(array_name, mode="r", timestamp=(1, 2)) as T: + print(T[:]["num"]) + + with tiledb.open(array_name, mode="r", timestamp=(2, 3)) as T: + print(T[:]["num"]) + + with tiledb.open(array_name, mode="r", timestamp=1) as T: + print(T[:]["num"]) + + with tiledb.open(array_name, mode="r", timestamp=(1, None)) as T: + print(T[:]["num"]) + + +if tiledb.object_type(array_name) != "array": + create_array() + write_array() + +read_array() diff --git a/testbed/TileDB-Inc__TileDB-Py/examples/using_tiledb_stats.py b/testbed/TileDB-Inc__TileDB-Py/examples/using_tiledb_stats.py new file mode 100644 index 0000000000000000000000000000000000000000..fe960c52fd0db527fb3f7d77e598137c6fe1aa2f --- /dev/null +++ b/testbed/TileDB-Inc__TileDB-Py/examples/using_tiledb_stats.py @@ -0,0 +1,83 @@ +# using_tiledb_stats.py +# +# LICENSE +# +# The MIT License +# +# Copyright (c) 2020 TileDB, Inc. +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +# THE SOFTWARE. +# +# DESCRIPTION +# +# Please see the TileDB documentation for more information: +# https://docs.tiledb.com/main/how-to/performance/using-performance-statistics +# +# When run, this program will create a 0.5GB dense array, and enable the +# TileDB statistics surrounding reads from the array. +# + +import numpy as np + +import tiledb + +# Name of array. +array_name = "stats_array" + + +def create_array(row_tile_extent, col_tile_extent): + dom = tiledb.Domain( + tiledb.Dim( + name="rows", domain=(1, 12000), tile=row_tile_extent, dtype=np.int32 + ), + tiledb.Dim( + name="cols", domain=(1, 12000), tile=col_tile_extent, dtype=np.int32 + ), + ) + + schema = tiledb.ArraySchema( + domain=dom, sparse=False, attrs=[tiledb.Attr(name="a", dtype=np.int32)] + ) + + # Create the (empty) array on disk. + tiledb.Array.create(array_name, schema) + + +def write_array(): + # Open the array and write to it. + with tiledb.open(array_name, mode="w") as A: + data = np.arange(12000 * 12000).reshape(12000, 12000) + A[:] = data + + +def read_array(): + # Open the array and read from it. + with tiledb.open(array_name, mode="r") as A: + # Read a slice of 3,000 rows. + # Enable the stats for the read query, and print the report. + tiledb.stats_enable() + print(A[1:3001, 1:12001]) + tiledb.stats_dump() + tiledb.stats_disable() + + +# Create array with each row as a tile. +create_array(1, 12000) +write_array() +read_array() diff --git a/testbed/TileDB-Inc__TileDB-Py/examples/variable_length.py b/testbed/TileDB-Inc__TileDB-Py/examples/variable_length.py new file mode 100644 index 0000000000000000000000000000000000000000..f80f4a42df05234060b63dc9c19e2390d4d72217 --- /dev/null +++ b/testbed/TileDB-Inc__TileDB-Py/examples/variable_length.py @@ -0,0 +1,139 @@ +# variable_length.py +# +# LICENSE +# +# The MIT License +# +# Copyright (c) 2020 TileDB, Inc. +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +# THE SOFTWARE. +# +# DESCRIPTION +# +# Please see the TileDB documentation for more information: +# https://docs.tiledb.com/main/how-to/arrays/writing-arrays/var-length-attributes +# +# This program shows how to set/get the TileDB configuration parameters. +# + + +import numpy as np + +#%% +import tiledb +from tiledb.tests.common import assert_subarrays_equal + +array_name = "variable_length_array" + +#%% + + +def create_array(): + dom = tiledb.Domain( + tiledb.Dim(name="rows", domain=(1, 4), tile=4, dtype=np.int64), + tiledb.Dim(name="cols", domain=(1, 4), tile=4, dtype=np.int64), + ) + + attrs = [ + tiledb.Attr(name="a1", var=True, dtype="U"), + tiledb.Attr(name="a2", var=True, dtype=np.int64), + ] + + schema = tiledb.ArraySchema(domain=dom, sparse=False, attrs=attrs) + + tiledb.Array.create(array_name, schema) + + return schema + + +def generate_data(): + # generate test input data + a1_data = np.array( + [ + "a", + "bb", + "ccc", + "dd", + "eee", + "f", + "g", + "hhh", + "i", + "jjj", + "kk", + "l", + "m", + "n", + "oo", + "p", + ], + dtype=object, + ) + + a1_data = a1_data.reshape(4, 4) + + a2_data = np.array( + list( + map( + lambda v: np.repeat(v[0], v[1]).astype(np.int64), + [ + (1, 1), + (2, 2), + (3, 1), + (4, 1), + (5, 1), + (6, 2), + (7, 2), + (8, 3), + (9, 2), + (10, 1), + (11, 1), + (12, 2), + (13, 1), + (14, 3), + (15, 1), + (16, 1), + ], + ) + ), + dtype=object, + ) + a2_data = a2_data.reshape(4, 4) + + data_dict = {"a1": a1_data, "a2": a2_data} + + return data_dict + + +def write_array(data_dict): + # open array for writing, and write data + with tiledb.open(array_name, "w") as array: + array[:] = data_dict + + +def test_output_subarrays(test_dict): + with tiledb.open(array_name) as A: + rt_dict = A[:] + assert_subarrays_equal(test_dict["a2"], rt_dict["a2"]) + + +create_array() +data = generate_data() +write_array(data) +test_output_subarrays(data) diff --git a/testbed/TileDB-Inc__TileDB-Py/examples/vfs.py b/testbed/TileDB-Inc__TileDB-Py/examples/vfs.py new file mode 100644 index 0000000000000000000000000000000000000000..0af8027a4d61dc40fe546c56feff048fc612f075 --- /dev/null +++ b/testbed/TileDB-Inc__TileDB-Py/examples/vfs.py @@ -0,0 +1,112 @@ +# vfs.py +# +# LICENSE +# +# The MIT License +# +# Copyright (c) 2020 TileDB, Inc. +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +# THE SOFTWARE. +# +# DESCRIPTION +# +# Please see the TileDB documentation for more information: +# https://docs.tiledb.com/main/how-to/virtual-filesystem +# +# This program explores the various TileDB VFS tools. +# + +import os +import struct + +import tiledb + + +def path(p): + return os.path.join(os.getcwd(), p) + + +def dirs_files(): + # Create TileDB VFS + vfs = tiledb.VFS() + + # Create directory + if not vfs.is_dir("dir_A"): + vfs.create_dir(path("dir_A")) + print("Created 'dir_A'") + else: + print("'dir_A' already exists") + + # Creating an (empty) file + if not vfs.is_file("dir_A/file_A"): + vfs.touch(path("dir_A/file_A")) + print("Created empty file 'dir_A/file_A'") + else: + print("'dir_A/file_A' already exists") + + # Getting the file size + print("Size of file 'dir_A/file_A': {}".format(vfs.file_size(path("dir_A/file_A")))) + + # Moving files (moving directories is similar) + print("Moving file 'dir_A/file_A' to 'dir_A/file_B'") + vfs.move_file(path("dir_A/file_A"), path("dir_A/file_B")) + + # Deleting files and directories + print("Deleting 'dir_A/file_B' and 'dir_A'") + vfs.remove_file(path("dir_A/file_B")) + vfs.remove_dir(path("dir_A")) + + +def write(): + # Create TileDB VFS + vfs = tiledb.VFS() + + # Write binary data + with vfs.open("tiledb_vfs.bin", "wb") as f: + f.write(struct.pack("f", 153.0)) + f.write("abcd".encode("utf-8")) + + # Write binary data again - this will overwrite the previous file + with vfs.open("tiledb_vfs.bin", "wb") as f: + f.write(struct.pack("f", 153.1)) + f.write("abcdef".encode("utf-8")) + + # Append binary data to existing file (this will NOT work on S3) + with vfs.open("tiledb_vfs.bin", "ab") as f: + f.write("ghijkl".encode("utf-8")) + + +def read(): + # Create TileDB VFS + vfs = tiledb.VFS() + + # Read binary data + with vfs.open("tiledb_vfs.bin", "rb") as f: + # Read the first 4 bytes (bytes [0:4]) + f1 = struct.unpack("f", f.read(4))[0] + + # Read the next 8 bytes (bytes [4:12]) + s1 = bytes.decode(f.read(8), "utf-8") + + print(f"Binary read:\n{f1}\n{s1}") + + +dirs_files() +write() +read() diff --git a/testbed/TileDB-Inc__TileDB-Py/examples/writing_dense_multiple.py b/testbed/TileDB-Inc__TileDB-Py/examples/writing_dense_multiple.py new file mode 100644 index 0000000000000000000000000000000000000000..7dc252454e9fd2154762aa337f9ffac76469b105 --- /dev/null +++ b/testbed/TileDB-Inc__TileDB-Py/examples/writing_dense_multiple.py @@ -0,0 +1,85 @@ +# writing_dense_multiple.py +# +# LICENSE +# +# The MIT License +# +# Copyright (c) 2020 TileDB, Inc. +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +# THE SOFTWARE. +# +# DESCRIPTION +# +# Please see the TileDB documentation for more information: +# https://docs.tiledb.com/main/how-to/arrays/writing-arrays/writing-in-dense-subarrays +# +# When run, this program will create a simple 2D dense array, write some data +# to it with two write queries, and read the entire array data back. +# + + +import numpy as np + +import tiledb + +# Name of the array to create. +array_name = "writing_dense_multiple" + + +def create_array(): + # The array will be 4x4 with dimensions "rows" and "cols", with domain [1,4]. + dom = tiledb.Domain( + tiledb.Dim(name="rows", domain=(1, 4), tile=2, dtype=np.int32), + tiledb.Dim(name="cols", domain=(1, 4), tile=2, dtype=np.int32), + ) + + # The array will be dense with a single attribute "a" so each (i,j) cell can store an integer. + schema = tiledb.ArraySchema( + domain=dom, sparse=False, attrs=[tiledb.Attr(name="a", dtype=np.int32)] + ) + + # Create the (empty) array on disk. + tiledb.DenseArray.create(array_name, schema) + + +def write_array(): + # Open the array and write to it. + with tiledb.DenseArray(array_name, mode="w") as A: + # First write + data = np.array(([1, 2], [3, 4])) + A[1:3, 1:3] = data + + # Second write + data = np.array(([5, 6, 7, 8], [9, 10, 11, 12])) + A[2:4, 1:5] = data + + +def read_array(): + # Open the array and read from it. + with tiledb.DenseArray(array_name, mode="r") as A: + # Slice the entire array + data = A[:] + print(data["a"]) + + +if tiledb.object_type(array_name) != "array": + create_array() + write_array() + +read_array() diff --git a/testbed/TileDB-Inc__TileDB-Py/examples/writing_dense_padding.py b/testbed/TileDB-Inc__TileDB-Py/examples/writing_dense_padding.py new file mode 100644 index 0000000000000000000000000000000000000000..7761aea7b581948fe3fe861c82b2f4d9cf6d627a --- /dev/null +++ b/testbed/TileDB-Inc__TileDB-Py/examples/writing_dense_padding.py @@ -0,0 +1,81 @@ +# writing_dense_padding.py +# +# LICENSE +# +# The MIT License +# +# Copyright (c) 2020 TileDB, Inc. +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +# THE SOFTWARE. +# +# DESCRIPTION +# +# Please see the TileDB documentation for more information: +# https://docs.tiledb.com/main/how-to/arrays/writing-arrays/writing-in-dense-subarrays +# +# When run, this program will create a simple 2D dense array, write some data +# to it in a way that some space is empty, and read the entire array data back. +# + + +import numpy as np + +import tiledb + +# Name of the array to create. +array_name = "writing_dense_padding" + + +def create_array(): + # The array will be 4x4 with dimensions "rows" and "cols", with domain [1,4]. + dom = tiledb.Domain( + tiledb.Dim(name="rows", domain=(1, 4), tile=2, dtype=np.int32), + tiledb.Dim(name="cols", domain=(1, 4), tile=2, dtype=np.int32), + ) + + # The array will be dense with a single attribute "a" so each (i,j) cell can store an integer. + schema = tiledb.ArraySchema( + domain=dom, sparse=False, attrs=[tiledb.Attr(name="a", dtype=np.int32)] + ) + + # Create the (empty) array on disk. + tiledb.DenseArray.create(array_name, schema) + + +def write_array(): + # Open the array and write to it. + with tiledb.DenseArray(array_name, mode="w") as A: + # Write to [2,3], [1,2] + data = np.array(([1, 2], [3, 4])) + A[2:4, 1:3] = data + + +def read_array(): + # Open the array and read from it. + with tiledb.DenseArray(array_name, mode="r") as A: + # Slice the entire array + data = A[:] + print(data["a"]) + + +if tiledb.object_type(array_name) != "array": + create_array() + write_array() + +read_array() diff --git a/testbed/TileDB-Inc__TileDB-Py/examples/writing_dense_rgb.py b/testbed/TileDB-Inc__TileDB-Py/examples/writing_dense_rgb.py new file mode 100644 index 0000000000000000000000000000000000000000..dc212b0488b7a28ea7a09d8b190c89a0a6c12e5f --- /dev/null +++ b/testbed/TileDB-Inc__TileDB-Py/examples/writing_dense_rgb.py @@ -0,0 +1,79 @@ +# writing_dense_rgb.py +# +# LICENSE +# +# The MIT License +# +# Copyright (c) 2021 TileDB, Inc. +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +# THE SOFTWARE. +# +# DESCRIPTION +# +# Please see the TileDB documentation for more information: +# https://docs.tiledb.com/main/how-to/arrays/writing-arrays/writing-in-dense-subarrays +# +# When run, this program will create a 2D+1 multi-component (eg RGB) dense array, write some +# data to it, and read the entire array data. + +import numpy as np + +import tiledb + +img_shape = (100, 224, 224) +img_uri = "writing_dense_rgb" + +image_data = np.random.randint(low=0, high=100, size=(*img_shape, 3), dtype=np.int32) + + +def create_array(): + domain = tiledb.Domain( + tiledb.Dim( + name="image_id", domain=(0, img_shape[0] - 1), tile=4, dtype=np.int32 + ), + tiledb.Dim( + name="x", domain=(0, img_shape[1] - 1), tile=img_shape[1], dtype=np.int32 + ), + tiledb.Dim( + name="y", domain=(0, img_shape[2] - 1), tile=img_shape[2], dtype=np.int32 + ), + ) + + # create multi-component attribute with three int32 components + attr = tiledb.Attr(dtype=np.dtype("i4, i4, i4")) + + schema = tiledb.ArraySchema(domain=domain, sparse=False, attrs=[attr]) + + tiledb.Array.create(img_uri, schema, overwrite=True) + + image_data_rgb = image_data.view(np.dtype("i4, i4, i4")).reshape(img_shape) + + with tiledb.open(img_uri, "w") as A: + # write data to 1st image_id slot + A[:] = image_data_rgb + + +def read_array(): + with tiledb.open(img_uri) as A: + print(A[:].shape) + + +if __name__ == "__main__": + create_array() + read_array() diff --git a/testbed/TileDB-Inc__TileDB-Py/examples/writing_sparse_multiple.py b/testbed/TileDB-Inc__TileDB-Py/examples/writing_sparse_multiple.py new file mode 100644 index 0000000000000000000000000000000000000000..417a2be753013ad8b16327eee436a7047b8c5023 --- /dev/null +++ b/testbed/TileDB-Inc__TileDB-Py/examples/writing_sparse_multiple.py @@ -0,0 +1,89 @@ +# writing_sparse_multiple.py +# +# LICENSE +# +# The MIT License +# +# Copyright (c) 2020 TileDB, Inc. +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +# THE SOFTWARE. +# +# DESCRIPTION +# +# Please see the TileDB documentation for more information: +# https://docs.tiledb.com/main/how-to/arrays/writing-arrays/writing-sparse-cells +# +# When run, this program will create a simple 2D sparse array, write some data +# to it twice, and read all the data back. +# + + +import numpy as np + +import tiledb + +# Name of the array to create. +array_name = "writing_sparse_multiple" + + +def create_array(): + # The array will be 4x4 with dimensions "rows" and "cols", with domain [1,4]. + dom = tiledb.Domain( + tiledb.Dim(name="rows", domain=(1, 4), tile=4, dtype=np.int32), + tiledb.Dim(name="cols", domain=(1, 4), tile=4, dtype=np.int32), + ) + + # The array will be sparse with a single attribute "a" so each (i,j) cell can store an integer. + schema = tiledb.ArraySchema( + domain=dom, sparse=True, attrs=[tiledb.Attr(name="a", dtype=np.int32)] + ) + + # Create the (empty) array on disk. + tiledb.SparseArray.create(array_name, schema) + + +def write_array(): + # Open the array and write to it. + with tiledb.SparseArray(array_name, mode="w") as A: + # First write + IJ = [1, 2, 2], [1, 4, 3] + data = np.array(([1, 2, 3])) + A[IJ] = data + + # Second write + IJ = [4, 2], [1, 4] + data = np.array(([4, 20])) + A[IJ] = data + + +def read_array(): + # Open the array and read from it. + with tiledb.SparseArray(array_name, mode="r") as A: + # Slice entire array + data = A[1:5, 1:5] + a_vals = data["a"] + for i, coord in enumerate(zip(data["rows"], data["cols"])): + print("Cell (%d, %d) has data %d" % (coord[0], coord[1], a_vals[i])) + + +if tiledb.object_type(array_name) != "array": + create_array() + write_array() + +read_array() diff --git a/testbed/TileDB-Inc__TileDB-Py/external/LICENSE-string_view.txt b/testbed/TileDB-Inc__TileDB-Py/external/LICENSE-string_view.txt new file mode 100644 index 0000000000000000000000000000000000000000..36b7cd93cdfbac762f5be4c6ce276df2ea6305c2 --- /dev/null +++ b/testbed/TileDB-Inc__TileDB-Py/external/LICENSE-string_view.txt @@ -0,0 +1,23 @@ +Boost Software License - Version 1.0 - August 17th, 2003 + +Permission is hereby granted, free of charge, to any person or organization +obtaining a copy of the software and accompanying documentation covered by +this license (the "Software") to use, reproduce, display, distribute, +execute, and transmit the Software, and to prepare derivative works of the +Software, and to permit third-parties to whom the Software is furnished to +do so, all subject to the following: + +The copyright notices in the Software and this entire statement, including +the above license grant, this restriction and the following disclaimer, +must be included in all copies of the Software, in whole or in part, and +all derivative works of the Software, unless such copies or derivative +works are solely in the form of machine-executable object code generated by +a source language processor. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT +SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE +FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, +ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. diff --git a/testbed/TileDB-Inc__TileDB-Py/external/LICENSE-tsl_robin_map.txt b/testbed/TileDB-Inc__TileDB-Py/external/LICENSE-tsl_robin_map.txt new file mode 100644 index 0000000000000000000000000000000000000000..c26c5a2079be560fc045394353777f8150568aba --- /dev/null +++ b/testbed/TileDB-Inc__TileDB-Py/external/LICENSE-tsl_robin_map.txt @@ -0,0 +1,23 @@ +/** + * MIT License + * + * Copyright (c) 2017 Thibaut Goetghebuer-Planchon + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ diff --git a/testbed/TileDB-Inc__TileDB-Py/external/tsl/robin_growth_policy.h b/testbed/TileDB-Inc__TileDB-Py/external/tsl/robin_growth_policy.h new file mode 100644 index 0000000000000000000000000000000000000000..ed17c840c48f95619337315ce6389d128de34ce5 --- /dev/null +++ b/testbed/TileDB-Inc__TileDB-Py/external/tsl/robin_growth_policy.h @@ -0,0 +1,348 @@ +/** + * MIT License + * + * Copyright (c) 2017 Thibaut Goetghebuer-Planchon + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +#ifndef TSL_ROBIN_GROWTH_POLICY_H +#define TSL_ROBIN_GROWTH_POLICY_H + + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +#ifdef TSL_DEBUG +# define tsl_rh_assert(expr) assert(expr) +#else +# define tsl_rh_assert(expr) (static_cast(0)) +#endif + + +/** + * If exceptions are enabled, throw the exception passed in parameter, otherwise call std::terminate. + */ +#if (defined(__cpp_exceptions) || defined(__EXCEPTIONS) || (defined (_MSC_VER) && defined (_CPPUNWIND))) && !defined(TSL_NO_EXCEPTIONS) +# define TSL_RH_THROW_OR_TERMINATE(ex, msg) throw ex(msg) +#else +# define TSL_RH_NO_EXCEPTIONS +# ifdef NDEBUG +# define TSL_RH_THROW_OR_TERMINATE(ex, msg) std::terminate() +# else +# include +# define TSL_RH_THROW_OR_TERMINATE(ex, msg) do { std::cerr << msg << std::endl; std::terminate(); } while(0) +# endif +#endif + + +#if defined(__GNUC__) || defined(__clang__) +# define TSL_RH_LIKELY(exp) (__builtin_expect(!!(exp), true)) +#else +# define TSL_RH_LIKELY(exp) (exp) +#endif + + +namespace tsl { +namespace rh { + +/** + * Grow the hash table by a factor of GrowthFactor keeping the bucket count to a power of two. It allows + * the table to use a mask operation instead of a modulo operation to map a hash to a bucket. + * + * GrowthFactor must be a power of two >= 2. + */ +template +class power_of_two_growth_policy { +public: + /** + * Called on the hash table creation and on rehash. The number of buckets for the table is passed in parameter. + * This number is a minimum, the policy may update this value with a higher value if needed (but not lower). + * + * If 0 is given, min_bucket_count_in_out must still be 0 after the policy creation and + * bucket_for_hash must always return 0 in this case. + */ + explicit power_of_two_growth_policy(std::size_t& min_bucket_count_in_out) { + if(min_bucket_count_in_out > max_bucket_count()) { + TSL_RH_THROW_OR_TERMINATE(std::length_error, "The hash table exceeds its maximum size."); + } + + if(min_bucket_count_in_out > 0) { + min_bucket_count_in_out = round_up_to_power_of_two(min_bucket_count_in_out); + m_mask = min_bucket_count_in_out - 1; + } + else { + m_mask = 0; + } + } + + /** + * Return the bucket [0, bucket_count()) to which the hash belongs. + * If bucket_count() is 0, it must always return 0. + */ + std::size_t bucket_for_hash(std::size_t hash) const noexcept { + return hash & m_mask; + } + + /** + * Return the number of buckets that should be used on next growth. + */ + std::size_t next_bucket_count() const { + if((m_mask + 1) > max_bucket_count() / GrowthFactor) { + TSL_RH_THROW_OR_TERMINATE(std::length_error, "The hash table exceeds its maximum size."); + } + + return (m_mask + 1) * GrowthFactor; + } + + /** + * Return the maximum number of buckets supported by the policy. + */ + std::size_t max_bucket_count() const { + // Largest power of two. + return (std::numeric_limits::max() / 2) + 1; + } + + /** + * Reset the growth policy as if it was created with a bucket count of 0. + * After a clear, the policy must always return 0 when bucket_for_hash is called. + */ + void clear() noexcept { + m_mask = 0; + } + +private: + static std::size_t round_up_to_power_of_two(std::size_t value) { + if(is_power_of_two(value)) { + return value; + } + + if(value == 0) { + return 1; + } + + --value; + for(std::size_t i = 1; i < sizeof(std::size_t) * CHAR_BIT; i *= 2) { + value |= value >> i; + } + + return value + 1; + } + + static constexpr bool is_power_of_two(std::size_t value) { + return value != 0 && (value & (value - 1)) == 0; + } + +protected: + static_assert(is_power_of_two(GrowthFactor) && GrowthFactor >= 2, "GrowthFactor must be a power of two >= 2."); + + std::size_t m_mask; +}; + + +/** + * Grow the hash table by GrowthFactor::num / GrowthFactor::den and use a modulo to map a hash + * to a bucket. Slower but it can be useful if you want a slower growth. + */ +template> +class mod_growth_policy { +public: + explicit mod_growth_policy(std::size_t& min_bucket_count_in_out) { + if(min_bucket_count_in_out > max_bucket_count()) { + TSL_RH_THROW_OR_TERMINATE(std::length_error, "The hash table exceeds its maximum size."); + } + + if(min_bucket_count_in_out > 0) { + m_mod = min_bucket_count_in_out; + } + else { + m_mod = 1; + } + } + + std::size_t bucket_for_hash(std::size_t hash) const noexcept { + return hash % m_mod; + } + + std::size_t next_bucket_count() const { + if(m_mod == max_bucket_count()) { + TSL_RH_THROW_OR_TERMINATE(std::length_error, "The hash table exceeds its maximum size."); + } + + const double next_bucket_count = std::ceil(double(m_mod) * REHASH_SIZE_MULTIPLICATION_FACTOR); + if(!std::isnormal(next_bucket_count)) { + TSL_RH_THROW_OR_TERMINATE(std::length_error, "The hash table exceeds its maximum size."); + } + + if(next_bucket_count > double(max_bucket_count())) { + return max_bucket_count(); + } + else { + return std::size_t(next_bucket_count); + } + } + + std::size_t max_bucket_count() const { + return MAX_BUCKET_COUNT; + } + + void clear() noexcept { + m_mod = 1; + } + +private: + static constexpr double REHASH_SIZE_MULTIPLICATION_FACTOR = 1.0 * GrowthFactor::num / GrowthFactor::den; + static const std::size_t MAX_BUCKET_COUNT = + std::size_t(double( + std::numeric_limits::max() / REHASH_SIZE_MULTIPLICATION_FACTOR + )); + + static_assert(REHASH_SIZE_MULTIPLICATION_FACTOR >= 1.1, "Growth factor should be >= 1.1."); + + std::size_t m_mod; +}; + + + +namespace detail { + +#if SIZE_MAX >= ULLONG_MAX +#define TSL_RH_NB_PRIMES 51 +#elif SIZE_MAX >= ULONG_MAX +#define TSL_RH_NB_PRIMES 40 +#else +#define TSL_RH_NB_PRIMES 23 +#endif + +static constexpr const std::array PRIMES = {{ + 1u, 5u, 17u, 29u, 37u, 53u, 67u, 79u, 97u, 131u, 193u, 257u, 389u, 521u, 769u, 1031u, + 1543u, 2053u, 3079u, 6151u, 12289u, 24593u, 49157u, +#if SIZE_MAX >= ULONG_MAX + 98317ul, 196613ul, 393241ul, 786433ul, 1572869ul, 3145739ul, 6291469ul, 12582917ul, + 25165843ul, 50331653ul, 100663319ul, 201326611ul, 402653189ul, 805306457ul, 1610612741ul, + 3221225473ul, 4294967291ul, +#endif +#if SIZE_MAX >= ULLONG_MAX + 6442450939ull, 12884901893ull, 25769803751ull, 51539607551ull, 103079215111ull, 206158430209ull, + 412316860441ull, 824633720831ull, 1649267441651ull, 3298534883309ull, 6597069766657ull, +#endif +}}; + +template +static constexpr std::size_t mod(std::size_t hash) { return hash % PRIMES[IPrime]; } + +// MOD_PRIME[iprime](hash) returns hash % PRIMES[iprime]. This table allows for faster modulo as the +// compiler can optimize the modulo code better with a constant known at the compilation. +static constexpr const std::array MOD_PRIME = {{ + &mod<0>, &mod<1>, &mod<2>, &mod<3>, &mod<4>, &mod<5>, &mod<6>, &mod<7>, &mod<8>, &mod<9>, &mod<10>, + &mod<11>, &mod<12>, &mod<13>, &mod<14>, &mod<15>, &mod<16>, &mod<17>, &mod<18>, &mod<19>, &mod<20>, + &mod<21>, &mod<22>, +#if SIZE_MAX >= ULONG_MAX + &mod<23>, &mod<24>, &mod<25>, &mod<26>, &mod<27>, &mod<28>, &mod<29>, &mod<30>, &mod<31>, &mod<32>, + &mod<33>, &mod<34>, &mod<35>, &mod<36>, &mod<37> , &mod<38>, &mod<39>, +#endif +#if SIZE_MAX >= ULLONG_MAX + &mod<40>, &mod<41>, &mod<42>, &mod<43>, &mod<44>, &mod<45>, &mod<46>, &mod<47>, &mod<48>, &mod<49>, + &mod<50>, +#endif +}}; + +} + +/** + * Grow the hash table by using prime numbers as bucket count. Slower than tsl::rh::power_of_two_growth_policy in + * general but will probably distribute the values around better in the buckets with a poor hash function. + * + * To allow the compiler to optimize the modulo operation, a lookup table is used with constant primes numbers. + * + * With a switch the code would look like: + * \code + * switch(iprime) { // iprime is the current prime of the hash table + * case 0: hash % 5ul; + * break; + * case 1: hash % 17ul; + * break; + * case 2: hash % 29ul; + * break; + * ... + * } + * \endcode + * + * Due to the constant variable in the modulo the compiler is able to optimize the operation + * by a series of multiplications, substractions and shifts. + * + * The 'hash % 5' could become something like 'hash - (hash * 0xCCCCCCCD) >> 34) * 5' in a 64 bits environment. + */ +class prime_growth_policy { +public: + explicit prime_growth_policy(std::size_t& min_bucket_count_in_out) { + auto it_prime = std::lower_bound(detail::PRIMES.begin(), + detail::PRIMES.end(), min_bucket_count_in_out); + if(it_prime == detail::PRIMES.end()) { + TSL_RH_THROW_OR_TERMINATE(std::length_error, "The hash table exceeds its maximum size."); + } + + m_iprime = static_cast(std::distance(detail::PRIMES.begin(), it_prime)); + if(min_bucket_count_in_out > 0) { + min_bucket_count_in_out = *it_prime; + } + else { + min_bucket_count_in_out = 0; + } + } + + std::size_t bucket_for_hash(std::size_t hash) const noexcept { + return detail::MOD_PRIME[m_iprime](hash); + } + + std::size_t next_bucket_count() const { + if(m_iprime + 1 >= detail::PRIMES.size()) { + TSL_RH_THROW_OR_TERMINATE(std::length_error, "The hash table exceeds its maximum size."); + } + + return detail::PRIMES[m_iprime + 1]; + } + + std::size_t max_bucket_count() const { + return detail::PRIMES.back(); + } + + void clear() noexcept { + m_iprime = 0; + } + +private: + unsigned int m_iprime; + + static_assert(std::numeric_limits::max() >= detail::PRIMES.size(), + "The type of m_iprime is not big enough."); +}; + +} +} + +#endif diff --git a/testbed/TileDB-Inc__TileDB-Py/external/tsl/robin_hash.h b/testbed/TileDB-Inc__TileDB-Py/external/tsl/robin_hash.h new file mode 100644 index 0000000000000000000000000000000000000000..e8bc5e68fbcf2e38fd9d67d027bfe567b5b1e62e --- /dev/null +++ b/testbed/TileDB-Inc__TileDB-Py/external/tsl/robin_hash.h @@ -0,0 +1,1451 @@ +/** + * MIT License + * + * Copyright (c) 2017 Thibaut Goetghebuer-Planchon + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +#ifndef TSL_ROBIN_HASH_H +#define TSL_ROBIN_HASH_H + + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "robin_growth_policy.h" + + +namespace tsl { + +namespace detail_robin_hash { + +template +struct make_void { + using type = void; +}; + +template +struct has_is_transparent: std::false_type { +}; + +template +struct has_is_transparent::type>: std::true_type { +}; + +template +struct is_power_of_two_policy: std::false_type { +}; + +template +struct is_power_of_two_policy>: std::true_type { +}; + +// Only available in C++17, we need to be compatible with C++11 +template +const T& clamp( const T& v, const T& lo, const T& hi) { + return std::min(hi, std::max(lo, v)); +} + +template +static T numeric_cast(U value, const char* error_message = "numeric_cast() failed.") { + T ret = static_cast(value); + if(static_cast(ret) != value) { + TSL_RH_THROW_OR_TERMINATE(std::runtime_error, error_message); + } + + const bool is_same_signedness = (std::is_unsigned::value && std::is_unsigned::value) || + (std::is_signed::value && std::is_signed::value); + if(!is_same_signedness && (ret < T{}) != (value < U{})) { + TSL_RH_THROW_OR_TERMINATE(std::runtime_error, error_message); + } + + return ret; +} + + +using truncated_hash_type = std::uint_least32_t; + +/** + * Helper class that stores a truncated hash if StoreHash is true and nothing otherwise. + */ +template +class bucket_entry_hash { +public: + bool bucket_hash_equal(std::size_t /*hash*/) const noexcept { + return true; + } + + truncated_hash_type truncated_hash() const noexcept { + return 0; + } + +protected: + void set_hash(truncated_hash_type /*hash*/) noexcept { + } +}; + +template<> +class bucket_entry_hash { +public: + bool bucket_hash_equal(std::size_t hash) const noexcept { + return m_hash == truncated_hash_type(hash); + } + + truncated_hash_type truncated_hash() const noexcept { + return m_hash; + } + +protected: + void set_hash(truncated_hash_type hash) noexcept { + m_hash = truncated_hash_type(hash); + } + +private: + truncated_hash_type m_hash; +}; + + +/** + * Each bucket entry has: + * - A value of type `ValueType`. + * - An integer to store how far the value of the bucket, if any, is from its ideal bucket + * (ex: if the current bucket 5 has the value 'foo' and `hash('foo') % nb_buckets` == 3, + * `dist_from_ideal_bucket()` will return 2 as the current value of the bucket is two + * buckets away from its ideal bucket) + * If there is no value in the bucket (i.e. `empty()` is true) `dist_from_ideal_bucket()` will be < 0. + * - A marker which tells us if the bucket is the last bucket of the bucket array (useful for the + * iterator of the hash table). + * - If `StoreHash` is true, 32 bits of the hash of the value, if any, are also stored in the bucket. + * If the size of the hash is more than 32 bits, it is truncated. We don't store the full hash + * as storing the hash is a potential opportunity to use the unused space due to the alignment + * of the bucket_entry structure. We can thus potentially store the hash without any extra space + * (which would not be possible with 64 bits of the hash). + */ +template +class bucket_entry: public bucket_entry_hash { + using bucket_hash = bucket_entry_hash; + +public: + using value_type = ValueType; + using distance_type = std::int_least16_t; + + + bucket_entry() noexcept: bucket_hash(), m_dist_from_ideal_bucket(EMPTY_MARKER_DIST_FROM_IDEAL_BUCKET), + m_last_bucket(false) + { + tsl_rh_assert(empty()); + } + + bucket_entry(bool last_bucket) noexcept: bucket_hash(), m_dist_from_ideal_bucket(EMPTY_MARKER_DIST_FROM_IDEAL_BUCKET), + m_last_bucket(last_bucket) + { + tsl_rh_assert(empty()); + } + + bucket_entry(const bucket_entry& other) noexcept(std::is_nothrow_copy_constructible::value): + bucket_hash(other), + m_dist_from_ideal_bucket(EMPTY_MARKER_DIST_FROM_IDEAL_BUCKET), + m_last_bucket(other.m_last_bucket) + { + if(!other.empty()) { + ::new (static_cast(std::addressof(m_value))) value_type(other.value()); + m_dist_from_ideal_bucket = other.m_dist_from_ideal_bucket; + } + } + + /** + * Never really used, but still necessary as we must call resize on an empty `std::vector`. + * and we need to support move-only types. See robin_hash constructor for details. + */ + bucket_entry(bucket_entry&& other) noexcept(std::is_nothrow_move_constructible::value): + bucket_hash(std::move(other)), + m_dist_from_ideal_bucket(EMPTY_MARKER_DIST_FROM_IDEAL_BUCKET), + m_last_bucket(other.m_last_bucket) + { + if(!other.empty()) { + ::new (static_cast(std::addressof(m_value))) value_type(std::move(other.value())); + m_dist_from_ideal_bucket = other.m_dist_from_ideal_bucket; + } + } + + bucket_entry& operator=(const bucket_entry& other) + noexcept(std::is_nothrow_copy_constructible::value) + { + if(this != &other) { + clear(); + + bucket_hash::operator=(other); + if(!other.empty()) { + ::new (static_cast(std::addressof(m_value))) value_type(other.value()); + } + + m_dist_from_ideal_bucket = other.m_dist_from_ideal_bucket; + m_last_bucket = other.m_last_bucket; + } + + return *this; + } + + bucket_entry& operator=(bucket_entry&& ) = delete; + + ~bucket_entry() noexcept { + clear(); + } + + void clear() noexcept { + if(!empty()) { + destroy_value(); + m_dist_from_ideal_bucket = EMPTY_MARKER_DIST_FROM_IDEAL_BUCKET; + } + } + + bool empty() const noexcept { + return m_dist_from_ideal_bucket == EMPTY_MARKER_DIST_FROM_IDEAL_BUCKET; + } + + value_type& value() noexcept { + tsl_rh_assert(!empty()); + return *reinterpret_cast(std::addressof(m_value)); + } + + const value_type& value() const noexcept { + tsl_rh_assert(!empty()); + return *reinterpret_cast(std::addressof(m_value)); + } + + distance_type dist_from_ideal_bucket() const noexcept { + return m_dist_from_ideal_bucket; + } + + bool last_bucket() const noexcept { + return m_last_bucket; + } + + void set_as_last_bucket() noexcept { + m_last_bucket = true; + } + + template + void set_value_of_empty_bucket(distance_type dist_from_ideal_bucket, + truncated_hash_type hash, Args&&... value_type_args) + { + tsl_rh_assert(dist_from_ideal_bucket >= 0); + tsl_rh_assert(empty()); + + ::new (static_cast(std::addressof(m_value))) value_type(std::forward(value_type_args)...); + this->set_hash(hash); + m_dist_from_ideal_bucket = dist_from_ideal_bucket; + + tsl_rh_assert(!empty()); + } + + void swap_with_value_in_bucket(distance_type& dist_from_ideal_bucket, + truncated_hash_type& hash, value_type& value) + { + tsl_rh_assert(!empty()); + + using std::swap; + swap(value, this->value()); + swap(dist_from_ideal_bucket, m_dist_from_ideal_bucket); + + // Avoid warning of unused variable if StoreHash is false + (void) hash; + if(StoreHash) { + const truncated_hash_type tmp_hash = this->truncated_hash(); + this->set_hash(hash); + hash = tmp_hash; + } + } + + static truncated_hash_type truncate_hash(std::size_t hash) noexcept { + return truncated_hash_type(hash); + } + +private: + void destroy_value() noexcept { + tsl_rh_assert(!empty()); + value().~value_type(); + } + +public: + static const distance_type DIST_FROM_IDEAL_BUCKET_LIMIT = 4096; + static_assert(DIST_FROM_IDEAL_BUCKET_LIMIT <= std::numeric_limits::max() - 1, + "DIST_FROM_IDEAL_BUCKET_LIMIT must be <= std::numeric_limits::max() - 1."); + +private: + using storage = typename std::aligned_storage::type; + + static const distance_type EMPTY_MARKER_DIST_FROM_IDEAL_BUCKET = -1; + + distance_type m_dist_from_ideal_bucket; + bool m_last_bucket; + storage m_value; +}; + + + +/** + * Internal common class used by `robin_map` and `robin_set`. + * + * ValueType is what will be stored by `robin_hash` (usually `std::pair` for map and `Key` for set). + * + * `KeySelect` should be a `FunctionObject` which takes a `ValueType` in parameter and returns a + * reference to the key. + * + * `ValueSelect` should be a `FunctionObject` which takes a `ValueType` in parameter and returns a + * reference to the value. `ValueSelect` should be void if there is no value (in a set for example). + * + * The strong exception guarantee only holds if the expression + * `std::is_nothrow_swappable::value && std::is_nothrow_move_constructible::value` is true. + * + * Behaviour is undefined if the destructor of `ValueType` throws. + */ +template +class robin_hash: private Hash, private KeyEqual, private GrowthPolicy { +private: + template + using has_mapped_type = typename std::integral_constant::value>; + + static_assert(noexcept(std::declval().bucket_for_hash(std::size_t(0))), "GrowthPolicy::bucket_for_hash must be noexcept."); + static_assert(noexcept(std::declval().clear()), "GrowthPolicy::clear must be noexcept."); + +public: + template + class robin_iterator; + + using key_type = typename KeySelect::key_type; + using value_type = ValueType; + using size_type = std::size_t; + using difference_type = std::ptrdiff_t; + using hasher = Hash; + using key_equal = KeyEqual; + using allocator_type = Allocator; + using reference = value_type&; + using const_reference = const value_type&; + using pointer = value_type*; + using const_pointer = const value_type*; + using iterator = robin_iterator; + using const_iterator = robin_iterator; + + +private: + /** + * Either store the hash because we are asked by the `StoreHash` template parameter + * or store the hash because it doesn't cost us anything in size and can be used to speed up rehash. + */ + static constexpr bool STORE_HASH = StoreHash || + ( + (sizeof(tsl::detail_robin_hash::bucket_entry) == + sizeof(tsl::detail_robin_hash::bucket_entry)) + && + (sizeof(std::size_t) == sizeof(truncated_hash_type) || + is_power_of_two_policy::value) + && + // Don't store the hash for primitive types with default hash. + (!std::is_arithmetic::value || + !std::is_same>::value) + ); + + /** + * Only use the stored hash on lookup if we are explicitly asked. We are not sure how slow + * the KeyEqual operation is. An extra comparison may slow things down with a fast KeyEqual. + */ + static constexpr bool USE_STORED_HASH_ON_LOOKUP = StoreHash; + + /** + * We can only use the hash on rehash if the size of the hash type is the same as the stored one or + * if we use a power of two modulo. In the case of the power of two modulo, we just mask + * the least significant bytes, we just have to check that the truncated_hash_type didn't truncated + * more bytes. + */ + static bool USE_STORED_HASH_ON_REHASH(size_type bucket_count) { + (void) bucket_count; + if(STORE_HASH && sizeof(std::size_t) == sizeof(truncated_hash_type)) { + return true; + } + else if(STORE_HASH && is_power_of_two_policy::value) { + tsl_rh_assert(bucket_count > 0); + return (bucket_count - 1) <= std::numeric_limits::max(); + } + else { + return false; + } + } + + using bucket_entry = tsl::detail_robin_hash::bucket_entry; + using distance_type = typename bucket_entry::distance_type; + + using buckets_allocator = typename std::allocator_traits::template rebind_alloc; + using buckets_container_type = std::vector; + + +public: + /** + * The 'operator*()' and 'operator->()' methods return a const reference and const pointer respectively to the + * stored value type. + * + * In case of a map, to get a mutable reference to the value associated to a key (the '.second' in the + * stored pair), you have to call 'value()'. + * + * The main reason for this is that if we returned a `std::pair&` instead + * of a `const std::pair&`, the user may modify the key which will put the map in a undefined state. + */ + template + class robin_iterator { + friend class robin_hash; + + private: + using bucket_entry_ptr = typename std::conditional::type; + + + robin_iterator(bucket_entry_ptr bucket) noexcept: m_bucket(bucket) { + } + + public: + using iterator_category = std::forward_iterator_tag; + using value_type = const typename robin_hash::value_type; + using difference_type = std::ptrdiff_t; + using reference = value_type&; + using pointer = value_type*; + + + robin_iterator() noexcept { + } + + // Copy constructor from iterator to const_iterator. + template::type* = nullptr> + robin_iterator(const robin_iterator& other) noexcept: m_bucket(other.m_bucket) { + } + + robin_iterator(const robin_iterator& other) = default; + robin_iterator(robin_iterator&& other) = default; + robin_iterator& operator=(const robin_iterator& other) = default; + robin_iterator& operator=(robin_iterator&& other) = default; + + const typename robin_hash::key_type& key() const { + return KeySelect()(m_bucket->value()); + } + + template::value && IsConst>::type* = nullptr> + const typename U::value_type& value() const { + return U()(m_bucket->value()); + } + + template::value && !IsConst>::type* = nullptr> + typename U::value_type& value() const { + return U()(m_bucket->value()); + } + + reference operator*() const { + return m_bucket->value(); + } + + pointer operator->() const { + return std::addressof(m_bucket->value()); + } + + robin_iterator& operator++() { + while(true) { + if(m_bucket->last_bucket()) { + ++m_bucket; + return *this; + } + + ++m_bucket; + if(!m_bucket->empty()) { + return *this; + } + } + } + + robin_iterator operator++(int) { + robin_iterator tmp(*this); + ++*this; + + return tmp; + } + + friend bool operator==(const robin_iterator& lhs, const robin_iterator& rhs) { + return lhs.m_bucket == rhs.m_bucket; + } + + friend bool operator!=(const robin_iterator& lhs, const robin_iterator& rhs) { + return !(lhs == rhs); + } + + private: + bucket_entry_ptr m_bucket; + }; + + +public: +#if defined(__cplusplus) && __cplusplus >= 201402L + robin_hash(size_type bucket_count, + const Hash& hash, + const KeyEqual& equal, + const Allocator& alloc, + float min_load_factor = DEFAULT_MIN_LOAD_FACTOR, + float max_load_factor = DEFAULT_MAX_LOAD_FACTOR): + Hash(hash), + KeyEqual(equal), + GrowthPolicy(bucket_count), + m_buckets_data( + [&]() { + if(bucket_count > max_bucket_count()) { + TSL_RH_THROW_OR_TERMINATE(std::length_error, + "The map exceeds its maximum bucket count."); + } + + return bucket_count; + }(), alloc + ), + m_buckets(m_buckets_data.empty()?static_empty_bucket_ptr():m_buckets_data.data()), + m_bucket_count(bucket_count), + m_nb_elements(0), + m_grow_on_next_insert(false), + m_try_shrink_on_next_insert(false) + { + if(m_bucket_count > 0) { + tsl_rh_assert(!m_buckets_data.empty()); + m_buckets_data.back().set_as_last_bucket(); + } + + this->min_load_factor(min_load_factor); + this->max_load_factor(max_load_factor); + } +#else + /** + * C++11 doesn't support the creation of a std::vector with a custom allocator and 'count' default-inserted elements. + * The needed contructor `explicit vector(size_type count, const Allocator& alloc = Allocator());` is only + * available in C++14 and later. We thus must resize after using the `vector(const Allocator& alloc)` constructor. + * + * We can't use `vector(size_type count, const T& value, const Allocator& alloc)` as it requires the + * value T to be copyable. + */ + robin_hash(size_type bucket_count, + const Hash& hash, + const KeyEqual& equal, + const Allocator& alloc, + float min_load_factor = DEFAULT_MIN_LOAD_FACTOR, + float max_load_factor = DEFAULT_MAX_LOAD_FACTOR): + Hash(hash), + KeyEqual(equal), + GrowthPolicy(bucket_count), + m_buckets_data(alloc), + m_buckets(static_empty_bucket_ptr()), + m_bucket_count(bucket_count), + m_nb_elements(0), + m_grow_on_next_insert(false), + m_try_shrink_on_next_insert(false) + { + if(bucket_count > max_bucket_count()) { + TSL_RH_THROW_OR_TERMINATE(std::length_error, "The map exceeds its maximum bucket count."); + } + + if(m_bucket_count > 0) { + m_buckets_data.resize(m_bucket_count); + m_buckets = m_buckets_data.data(); + + tsl_rh_assert(!m_buckets_data.empty()); + m_buckets_data.back().set_as_last_bucket(); + } + + this->min_load_factor(min_load_factor); + this->max_load_factor(max_load_factor); + } +#endif + + robin_hash(const robin_hash& other): Hash(other), + KeyEqual(other), + GrowthPolicy(other), + m_buckets_data(other.m_buckets_data), + m_buckets(m_buckets_data.empty()?static_empty_bucket_ptr():m_buckets_data.data()), + m_bucket_count(other.m_bucket_count), + m_nb_elements(other.m_nb_elements), + m_load_threshold(other.m_load_threshold), + m_min_load_factor(other.m_min_load_factor), + m_max_load_factor(other.m_max_load_factor), + m_grow_on_next_insert(other.m_grow_on_next_insert), + m_try_shrink_on_next_insert(other.m_try_shrink_on_next_insert) + { + } + + robin_hash(robin_hash&& other) noexcept(std::is_nothrow_move_constructible::value && + std::is_nothrow_move_constructible::value && + std::is_nothrow_move_constructible::value && + std::is_nothrow_move_constructible::value) + : Hash(std::move(static_cast(other))), + KeyEqual(std::move(static_cast(other))), + GrowthPolicy(std::move(static_cast(other))), + m_buckets_data(std::move(other.m_buckets_data)), + m_buckets(m_buckets_data.empty()?static_empty_bucket_ptr():m_buckets_data.data()), + m_bucket_count(other.m_bucket_count), + m_nb_elements(other.m_nb_elements), + m_load_threshold(other.m_load_threshold), + m_min_load_factor(other.m_min_load_factor), + m_max_load_factor(other.m_max_load_factor), + m_grow_on_next_insert(other.m_grow_on_next_insert), + m_try_shrink_on_next_insert(other.m_try_shrink_on_next_insert) + { + other.clear_and_shrink(); + } + + robin_hash& operator=(const robin_hash& other) { + if(&other != this) { + Hash::operator=(other); + KeyEqual::operator=(other); + GrowthPolicy::operator=(other); + + m_buckets_data = other.m_buckets_data; + m_buckets = m_buckets_data.empty()?static_empty_bucket_ptr(): + m_buckets_data.data(); + m_bucket_count = other.m_bucket_count; + m_nb_elements = other.m_nb_elements; + + m_load_threshold = other.m_load_threshold; + m_min_load_factor = other.m_min_load_factor; + m_max_load_factor = other.m_max_load_factor; + + m_grow_on_next_insert = other.m_grow_on_next_insert; + m_try_shrink_on_next_insert = other.m_try_shrink_on_next_insert; + } + + return *this; + } + + robin_hash& operator=(robin_hash&& other) { + other.swap(*this); + other.clear(); + + return *this; + } + + allocator_type get_allocator() const { + return m_buckets_data.get_allocator(); + } + + + /* + * Iterators + */ + iterator begin() noexcept { + std::size_t i = 0; + while(i < m_bucket_count && m_buckets[i].empty()) { + i++; + } + + return iterator(m_buckets + i); + } + + const_iterator begin() const noexcept { + return cbegin(); + } + + const_iterator cbegin() const noexcept { + std::size_t i = 0; + while(i < m_bucket_count && m_buckets[i].empty()) { + i++; + } + + return const_iterator(m_buckets + i); + } + + iterator end() noexcept { + return iterator(m_buckets + m_bucket_count); + } + + const_iterator end() const noexcept { + return cend(); + } + + const_iterator cend() const noexcept { + return const_iterator(m_buckets + m_bucket_count); + } + + + /* + * Capacity + */ + bool empty() const noexcept { + return m_nb_elements == 0; + } + + size_type size() const noexcept { + return m_nb_elements; + } + + size_type max_size() const noexcept { + return m_buckets_data.max_size(); + } + + /* + * Modifiers + */ + void clear() noexcept { + if(m_min_load_factor > 0.0f) { + clear_and_shrink(); + } + else { + for(auto& bucket: m_buckets_data) { + bucket.clear(); + } + + m_nb_elements = 0; + m_grow_on_next_insert = false; + } + } + + + + template + std::pair insert(P&& value) { + return insert_impl(KeySelect()(value), std::forward

(value)); + } + + template + iterator insert_hint(const_iterator hint, P&& value) { + if(hint != cend() && compare_keys(KeySelect()(*hint), KeySelect()(value))) { + return mutable_iterator(hint); + } + + return insert(std::forward

(value)).first; + } + + template + void insert(InputIt first, InputIt last) { + if(std::is_base_of::iterator_category>::value) + { + const auto nb_elements_insert = std::distance(first, last); + const size_type nb_free_buckets = m_load_threshold - size(); + tsl_rh_assert(m_load_threshold >= size()); + + if(nb_elements_insert > 0 && nb_free_buckets < size_type(nb_elements_insert)) { + reserve(size() + size_type(nb_elements_insert)); + } + } + + for(; first != last; ++first) { + insert(*first); + } + } + + + + template + std::pair insert_or_assign(K&& key, M&& obj) { + auto it = try_emplace(std::forward(key), std::forward(obj)); + if(!it.second) { + it.first.value() = std::forward(obj); + } + + return it; + } + + template + iterator insert_or_assign(const_iterator hint, K&& key, M&& obj) { + if(hint != cend() && compare_keys(KeySelect()(*hint), key)) { + auto it = mutable_iterator(hint); + it.value() = std::forward(obj); + + return it; + } + + return insert_or_assign(std::forward(key), std::forward(obj)).first; + } + + + template + std::pair emplace(Args&&... args) { + return insert(value_type(std::forward(args)...)); + } + + template + iterator emplace_hint(const_iterator hint, Args&&... args) { + return insert_hint(hint, value_type(std::forward(args)...)); + } + + + + template + std::pair try_emplace(K&& key, Args&&... args) { + return insert_impl(key, std::piecewise_construct, + std::forward_as_tuple(std::forward(key)), + std::forward_as_tuple(std::forward(args)...)); + } + + template + iterator try_emplace_hint(const_iterator hint, K&& key, Args&&... args) { + if(hint != cend() && compare_keys(KeySelect()(*hint), key)) { + return mutable_iterator(hint); + } + + return try_emplace(std::forward(key), std::forward(args)...).first; + } + + /** + * Here to avoid `template size_type erase(const K& key)` being used when + * we use an `iterator` instead of a `const_iterator`. + */ + iterator erase(iterator pos) { + erase_from_bucket(pos); + + /** + * Erase bucket used a backward shift after clearing the bucket. + * Check if there is a new value in the bucket, if not get the next non-empty. + */ + if(pos.m_bucket->empty()) { + ++pos; + } + + m_try_shrink_on_next_insert = true; + + return pos; + } + + iterator erase(const_iterator pos) { + return erase(mutable_iterator(pos)); + } + + iterator erase(const_iterator first, const_iterator last) { + if(first == last) { + return mutable_iterator(first); + } + + auto first_mutable = mutable_iterator(first); + auto last_mutable = mutable_iterator(last); + for(auto it = first_mutable.m_bucket; it != last_mutable.m_bucket; ++it) { + if(!it->empty()) { + it->clear(); + m_nb_elements--; + } + } + + if(last_mutable == end()) { + m_try_shrink_on_next_insert = true; + return end(); + } + + + /* + * Backward shift on the values which come after the deleted values. + * We try to move the values closer to their ideal bucket. + */ + std::size_t icloser_bucket = static_cast(first_mutable.m_bucket - m_buckets); + std::size_t ito_move_closer_value = static_cast(last_mutable.m_bucket - m_buckets); + tsl_rh_assert(ito_move_closer_value > icloser_bucket); + + const std::size_t ireturn_bucket = ito_move_closer_value - + std::min(ito_move_closer_value - icloser_bucket, + std::size_t(m_buckets[ito_move_closer_value].dist_from_ideal_bucket())); + + while(ito_move_closer_value < m_bucket_count && m_buckets[ito_move_closer_value].dist_from_ideal_bucket() > 0) { + icloser_bucket = ito_move_closer_value - + std::min(ito_move_closer_value - icloser_bucket, + std::size_t(m_buckets[ito_move_closer_value].dist_from_ideal_bucket())); + + + tsl_rh_assert(m_buckets[icloser_bucket].empty()); + const distance_type new_distance = distance_type(m_buckets[ito_move_closer_value].dist_from_ideal_bucket() - + (ito_move_closer_value - icloser_bucket)); + m_buckets[icloser_bucket].set_value_of_empty_bucket(new_distance, + m_buckets[ito_move_closer_value].truncated_hash(), + std::move(m_buckets[ito_move_closer_value].value())); + m_buckets[ito_move_closer_value].clear(); + + + ++icloser_bucket; + ++ito_move_closer_value; + } + + m_try_shrink_on_next_insert = true; + + return iterator(m_buckets + ireturn_bucket); + } + + + template + size_type erase(const K& key) { + return erase(key, hash_key(key)); + } + + template + size_type erase(const K& key, std::size_t hash) { + auto it = find(key, hash); + if(it != end()) { + erase_from_bucket(it); + m_try_shrink_on_next_insert = true; + + return 1; + } + else { + return 0; + } + } + + + + + + void swap(robin_hash& other) { + using std::swap; + + swap(static_cast(*this), static_cast(other)); + swap(static_cast(*this), static_cast(other)); + swap(static_cast(*this), static_cast(other)); + swap(m_buckets_data, other.m_buckets_data); + swap(m_buckets, other.m_buckets); + swap(m_bucket_count, other.m_bucket_count); + swap(m_nb_elements, other.m_nb_elements); + swap(m_load_threshold, other.m_load_threshold); + swap(m_min_load_factor, other.m_min_load_factor); + swap(m_max_load_factor, other.m_max_load_factor); + swap(m_grow_on_next_insert, other.m_grow_on_next_insert); + swap(m_try_shrink_on_next_insert, other.m_try_shrink_on_next_insert); + } + + + /* + * Lookup + */ + template::value>::type* = nullptr> + typename U::value_type& at(const K& key) { + return at(key, hash_key(key)); + } + + template::value>::type* = nullptr> + typename U::value_type& at(const K& key, std::size_t hash) { + return const_cast(static_cast(this)->at(key, hash)); + } + + + template::value>::type* = nullptr> + const typename U::value_type& at(const K& key) const { + return at(key, hash_key(key)); + } + + template::value>::type* = nullptr> + const typename U::value_type& at(const K& key, std::size_t hash) const { + auto it = find(key, hash); + if(it != cend()) { + return it.value(); + } + else { + TSL_RH_THROW_OR_TERMINATE(std::out_of_range, "Couldn't find key."); + } + } + + template::value>::type* = nullptr> + typename U::value_type& operator[](K&& key) { + return try_emplace(std::forward(key)).first.value(); + } + + + template + size_type count(const K& key) const { + return count(key, hash_key(key)); + } + + template + size_type count(const K& key, std::size_t hash) const { + if(find(key, hash) != cend()) { + return 1; + } + else { + return 0; + } + } + + + template + iterator find(const K& key) { + return find_impl(key, hash_key(key)); + } + + template + iterator find(const K& key, std::size_t hash) { + return find_impl(key, hash); + } + + + template + const_iterator find(const K& key) const { + return find_impl(key, hash_key(key)); + } + + template + const_iterator find(const K& key, std::size_t hash) const { + return find_impl(key, hash); + } + + + template + bool contains(const K& key) const { + return contains(key, hash_key(key)); + } + + template + bool contains(const K& key, std::size_t hash) const { + return count(key, hash) != 0; + } + + + template + std::pair equal_range(const K& key) { + return equal_range(key, hash_key(key)); + } + + template + std::pair equal_range(const K& key, std::size_t hash) { + iterator it = find(key, hash); + return std::make_pair(it, (it == end())?it:std::next(it)); + } + + + template + std::pair equal_range(const K& key) const { + return equal_range(key, hash_key(key)); + } + + template + std::pair equal_range(const K& key, std::size_t hash) const { + const_iterator it = find(key, hash); + return std::make_pair(it, (it == cend())?it:std::next(it)); + } + + /* + * Bucket interface + */ + size_type bucket_count() const { + return m_bucket_count; + } + + size_type max_bucket_count() const { + return std::min(GrowthPolicy::max_bucket_count(), m_buckets_data.max_size()); + } + + /* + * Hash policy + */ + float load_factor() const { + if(bucket_count() == 0) { + return 0; + } + + return float(m_nb_elements)/float(bucket_count()); + } + + float min_load_factor() const { + return m_min_load_factor; + } + + float max_load_factor() const { + return m_max_load_factor; + } + + void min_load_factor(float ml) { + m_min_load_factor = clamp(ml, float(MINIMUM_MIN_LOAD_FACTOR), + float(MAXIMUM_MIN_LOAD_FACTOR)); + } + + void max_load_factor(float ml) { + m_max_load_factor = clamp(ml, float(MINIMUM_MAX_LOAD_FACTOR), + float(MAXIMUM_MAX_LOAD_FACTOR)); + m_load_threshold = size_type(float(bucket_count())*m_max_load_factor); + } + + void rehash(size_type count) { + count = std::max(count, size_type(std::ceil(float(size())/max_load_factor()))); + rehash_impl(count); + } + + void reserve(size_type count) { + rehash(size_type(std::ceil(float(count)/max_load_factor()))); + } + + /* + * Observers + */ + hasher hash_function() const { + return static_cast(*this); + } + + key_equal key_eq() const { + return static_cast(*this); + } + + + /* + * Other + */ + iterator mutable_iterator(const_iterator pos) { + return iterator(const_cast(pos.m_bucket)); + } + +private: + template + std::size_t hash_key(const K& key) const { + return Hash::operator()(key); + } + + template + bool compare_keys(const K1& key1, const K2& key2) const { + return KeyEqual::operator()(key1, key2); + } + + std::size_t bucket_for_hash(std::size_t hash) const { + const std::size_t bucket = GrowthPolicy::bucket_for_hash(hash); + tsl_rh_assert(bucket < m_bucket_count || (bucket == 0 && m_bucket_count == 0)); + + return bucket; + } + + template::value>::type* = nullptr> + std::size_t next_bucket(std::size_t index) const noexcept { + tsl_rh_assert(index < bucket_count()); + + return (index + 1) & this->m_mask; + } + + template::value>::type* = nullptr> + std::size_t next_bucket(std::size_t index) const noexcept { + tsl_rh_assert(index < bucket_count()); + + index++; + return (index != bucket_count())?index:0; + } + + + + template + iterator find_impl(const K& key, std::size_t hash) { + return mutable_iterator(static_cast(this)->find(key, hash)); + } + + template + const_iterator find_impl(const K& key, std::size_t hash) const { + std::size_t ibucket = bucket_for_hash(hash); + distance_type dist_from_ideal_bucket = 0; + + while(dist_from_ideal_bucket <= m_buckets[ibucket].dist_from_ideal_bucket()) { + if(TSL_RH_LIKELY((!USE_STORED_HASH_ON_LOOKUP || m_buckets[ibucket].bucket_hash_equal(hash)) && + compare_keys(KeySelect()(m_buckets[ibucket].value()), key))) + { + return const_iterator(m_buckets + ibucket); + } + + ibucket = next_bucket(ibucket); + dist_from_ideal_bucket++; + } + + return cend(); + } + + void erase_from_bucket(iterator pos) { + pos.m_bucket->clear(); + m_nb_elements--; + + /** + * Backward shift, swap the empty bucket, previous_ibucket, with the values on its right, ibucket, + * until we cross another empty bucket or if the other bucket has a distance_from_ideal_bucket == 0. + * + * We try to move the values closer to their ideal bucket. + */ + std::size_t previous_ibucket = static_cast(pos.m_bucket - m_buckets); + std::size_t ibucket = next_bucket(previous_ibucket); + + while(m_buckets[ibucket].dist_from_ideal_bucket() > 0) { + tsl_rh_assert(m_buckets[previous_ibucket].empty()); + + const distance_type new_distance = distance_type(m_buckets[ibucket].dist_from_ideal_bucket() - 1); + m_buckets[previous_ibucket].set_value_of_empty_bucket(new_distance, m_buckets[ibucket].truncated_hash(), + std::move(m_buckets[ibucket].value())); + m_buckets[ibucket].clear(); + + previous_ibucket = ibucket; + ibucket = next_bucket(ibucket); + } + } + + template + std::pair insert_impl(const K& key, Args&&... value_type_args) { + const std::size_t hash = hash_key(key); + + std::size_t ibucket = bucket_for_hash(hash); + distance_type dist_from_ideal_bucket = 0; + + while(dist_from_ideal_bucket <= m_buckets[ibucket].dist_from_ideal_bucket()) { + if((!USE_STORED_HASH_ON_LOOKUP || m_buckets[ibucket].bucket_hash_equal(hash)) && + compare_keys(KeySelect()(m_buckets[ibucket].value()), key)) + { + return std::make_pair(iterator(m_buckets + ibucket), false); + } + + ibucket = next_bucket(ibucket); + dist_from_ideal_bucket++; + } + + if(rehash_on_extreme_load()) { + ibucket = bucket_for_hash(hash); + dist_from_ideal_bucket = 0; + + while(dist_from_ideal_bucket <= m_buckets[ibucket].dist_from_ideal_bucket()) { + ibucket = next_bucket(ibucket); + dist_from_ideal_bucket++; + } + } + + + if(m_buckets[ibucket].empty()) { + m_buckets[ibucket].set_value_of_empty_bucket(dist_from_ideal_bucket, bucket_entry::truncate_hash(hash), + std::forward(value_type_args)...); + } + else { + insert_value(ibucket, dist_from_ideal_bucket, bucket_entry::truncate_hash(hash), + std::forward(value_type_args)...); + } + + + m_nb_elements++; + /* + * The value will be inserted in ibucket in any case, either because it was + * empty or by stealing the bucket (robin hood). + */ + return std::make_pair(iterator(m_buckets + ibucket), true); + } + + + template + void insert_value(std::size_t ibucket, distance_type dist_from_ideal_bucket, + truncated_hash_type hash, Args&&... value_type_args) + { + value_type value(std::forward(value_type_args)...); + insert_value_impl(ibucket, dist_from_ideal_bucket, hash, value); + } + + void insert_value(std::size_t ibucket, distance_type dist_from_ideal_bucket, + truncated_hash_type hash, value_type&& value) + { + insert_value_impl(ibucket, dist_from_ideal_bucket, hash, value); + } + + /* + * We don't use `value_type&& value` as last argument due to a bug in MSVC when `value_type` is a pointer, + * The compiler is not able to see the difference between `std::string*` and `std::string*&&` resulting in + * a compilation error. + * + * The `value` will be in a moved state at the end of the function. + */ + void insert_value_impl(std::size_t ibucket, distance_type dist_from_ideal_bucket, + truncated_hash_type hash, value_type& value) + { + m_buckets[ibucket].swap_with_value_in_bucket(dist_from_ideal_bucket, hash, value); + ibucket = next_bucket(ibucket); + dist_from_ideal_bucket++; + + while(!m_buckets[ibucket].empty()) { + if(dist_from_ideal_bucket > m_buckets[ibucket].dist_from_ideal_bucket()) { + if(dist_from_ideal_bucket >= bucket_entry::DIST_FROM_IDEAL_BUCKET_LIMIT) { + /** + * The number of probes is really high, rehash the map on the next insert. + * Difficult to do now as rehash may throw an exception. + */ + m_grow_on_next_insert = true; + } + + m_buckets[ibucket].swap_with_value_in_bucket(dist_from_ideal_bucket, hash, value); + } + + ibucket = next_bucket(ibucket); + dist_from_ideal_bucket++; + } + + m_buckets[ibucket].set_value_of_empty_bucket(dist_from_ideal_bucket, hash, std::move(value)); + } + + + void rehash_impl(size_type count) { + robin_hash new_table(count, static_cast(*this), static_cast(*this), + get_allocator(), m_min_load_factor, m_max_load_factor); + + const bool use_stored_hash = USE_STORED_HASH_ON_REHASH(new_table.bucket_count()); + for(auto& bucket: m_buckets_data) { + if(bucket.empty()) { + continue; + } + + const std::size_t hash = use_stored_hash?bucket.truncated_hash(): + new_table.hash_key(KeySelect()(bucket.value())); + + new_table.insert_value_on_rehash(new_table.bucket_for_hash(hash), 0, + bucket_entry::truncate_hash(hash), std::move(bucket.value())); + } + + new_table.m_nb_elements = m_nb_elements; + new_table.swap(*this); + } + + void clear_and_shrink() noexcept { + GrowthPolicy::clear(); + m_buckets_data.clear(); + m_buckets = static_empty_bucket_ptr(); + m_bucket_count = 0; + m_nb_elements = 0; + m_load_threshold = 0; + m_grow_on_next_insert = false; + m_try_shrink_on_next_insert = false; + } + + void insert_value_on_rehash(std::size_t ibucket, distance_type dist_from_ideal_bucket, + truncated_hash_type hash, value_type&& value) + { + while(true) { + if(dist_from_ideal_bucket > m_buckets[ibucket].dist_from_ideal_bucket()) { + if(m_buckets[ibucket].empty()) { + m_buckets[ibucket].set_value_of_empty_bucket(dist_from_ideal_bucket, hash, std::move(value)); + return; + } + else { + m_buckets[ibucket].swap_with_value_in_bucket(dist_from_ideal_bucket, hash, value); + } + } + + dist_from_ideal_bucket++; + ibucket = next_bucket(ibucket); + } + } + + + + /** + * Grow the table if m_grow_on_next_insert is true or we reached the max_load_factor. + * Shrink the table if m_try_shrink_on_next_insert is true (an erase occurred) and + * we're below the min_load_factor. + * + * Return true if the table has been rehashed. + */ + bool rehash_on_extreme_load() { + if(m_grow_on_next_insert || size() >= m_load_threshold) { + rehash_impl(GrowthPolicy::next_bucket_count()); + m_grow_on_next_insert = false; + + return true; + } + + if(m_try_shrink_on_next_insert) { + m_try_shrink_on_next_insert = false; + if(m_min_load_factor != 0.0f && load_factor() < m_min_load_factor) { + reserve(size() + 1); + + return true; + } + } + + return false; + } + + +public: + static const size_type DEFAULT_INIT_BUCKETS_SIZE = 0; + + static constexpr float DEFAULT_MAX_LOAD_FACTOR = 0.5f; + static constexpr float MINIMUM_MAX_LOAD_FACTOR = 0.2f; + static constexpr float MAXIMUM_MAX_LOAD_FACTOR = 0.95f; + + static constexpr float DEFAULT_MIN_LOAD_FACTOR = 0.0f; + static constexpr float MINIMUM_MIN_LOAD_FACTOR = 0.0f; + static constexpr float MAXIMUM_MIN_LOAD_FACTOR = 0.15f; + + static_assert(MINIMUM_MAX_LOAD_FACTOR < MAXIMUM_MAX_LOAD_FACTOR, + "MINIMUM_MAX_LOAD_FACTOR should be < MAXIMUM_MAX_LOAD_FACTOR"); + static_assert(MINIMUM_MIN_LOAD_FACTOR < MAXIMUM_MIN_LOAD_FACTOR, + "MINIMUM_MIN_LOAD_FACTOR should be < MAXIMUM_MIN_LOAD_FACTOR"); + static_assert(MAXIMUM_MIN_LOAD_FACTOR < MINIMUM_MAX_LOAD_FACTOR, + "MAXIMUM_MIN_LOAD_FACTOR should be < MINIMUM_MAX_LOAD_FACTOR"); + +private: + /** + * Return an always valid pointer to an static empty bucket_entry with last_bucket() == true. + */ + bucket_entry* static_empty_bucket_ptr() noexcept { + static bucket_entry empty_bucket(true); + return &empty_bucket; + } + +private: + buckets_container_type m_buckets_data; + + /** + * Points to m_buckets_data.data() if !m_buckets_data.empty() otherwise points to static_empty_bucket_ptr. + * This variable is useful to avoid the cost of checking if m_buckets_data is empty when trying + * to find an element. + * + * TODO Remove m_buckets_data and only use a pointer instead of a pointer+vector to save some space in the robin_hash object. + * Manage the Allocator manually. + */ + bucket_entry* m_buckets; + + /** + * Used a lot in find, avoid the call to m_buckets_data.size() which is a bit slower. + */ + size_type m_bucket_count; + + size_type m_nb_elements; + + size_type m_load_threshold; + + float m_min_load_factor; + float m_max_load_factor; + + bool m_grow_on_next_insert; + + /** + * We can't shrink down the map on erase operations as the erase methods need to return the next iterator. + * Shrinking the map would invalidate all the iterators and we could not return the next iterator in a meaningful way, + * On erase, we thus just indicate on erase that we should try to shrink the hash table on the next insert + * if we go below the min_load_factor. + */ + bool m_try_shrink_on_next_insert; +}; + +} + +} + +#endif diff --git a/testbed/TileDB-Inc__TileDB-Py/external/tsl/robin_map.h b/testbed/TileDB-Inc__TileDB-Py/external/tsl/robin_map.h new file mode 100644 index 0000000000000000000000000000000000000000..86761f5308e19fe136f562aeef5834e44525e585 --- /dev/null +++ b/testbed/TileDB-Inc__TileDB-Py/external/tsl/robin_map.h @@ -0,0 +1,715 @@ +/** + * MIT License + * + * Copyright (c) 2017 Thibaut Goetghebuer-Planchon + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +#ifndef TSL_ROBIN_MAP_H +#define TSL_ROBIN_MAP_H + + +#include +#include +#include +#include +#include +#include +#include "robin_hash.h" + + +namespace tsl { + + +/** + * Implementation of a hash map using open-addressing and the robin hood hashing algorithm with backward shift deletion. + * + * For operations modifying the hash map (insert, erase, rehash, ...), the strong exception guarantee + * is only guaranteed when the expression `std::is_nothrow_swappable>::value && + * std::is_nothrow_move_constructible>::value` is true, otherwise if an exception + * is thrown during the swap or the move, the hash map may end up in a undefined state. Per the standard + * a `Key` or `T` with a noexcept copy constructor and no move constructor also satisfies the + * `std::is_nothrow_move_constructible>::value` criterion (and will thus guarantee the + * strong exception for the map). + * + * When `StoreHash` is true, 32 bits of the hash are stored alongside the values. It can improve + * the performance during lookups if the `KeyEqual` function takes time (if it engenders a cache-miss for example) + * as we then compare the stored hashes before comparing the keys. When `tsl::rh::power_of_two_growth_policy` is used + * as `GrowthPolicy`, it may also speed-up the rehash process as we can avoid to recalculate the hash. + * When it is detected that storing the hash will not incur any memory penalty due to alignment (i.e. + * `sizeof(tsl::detail_robin_hash::bucket_entry) == + * sizeof(tsl::detail_robin_hash::bucket_entry)`) and `tsl::rh::power_of_two_growth_policy` is + * used, the hash will be stored even if `StoreHash` is false so that we can speed-up the rehash (but it will + * not be used on lookups unless `StoreHash` is true). + * + * `GrowthPolicy` defines how the map grows and consequently how a hash value is mapped to a bucket. + * By default the map uses `tsl::rh::power_of_two_growth_policy`. This policy keeps the number of buckets + * to a power of two and uses a mask to map the hash to a bucket instead of the slow modulo. + * Other growth policies are available and you may define your own growth policy, + * check `tsl::rh::power_of_two_growth_policy` for the interface. + * + * `std::pair` must be swappable. + * + * `Key` and `T` must be copy and/or move constructible. + * + * If the destructor of `Key` or `T` throws an exception, the behaviour of the class is undefined. + * + * Iterators invalidation: + * - clear, operator=, reserve, rehash: always invalidate the iterators. + * - insert, emplace, emplace_hint, operator[]: if there is an effective insert, invalidate the iterators. + * - erase: always invalidate the iterators. + */ +template, + class KeyEqual = std::equal_to, + class Allocator = std::allocator>, + bool StoreHash = false, + class GrowthPolicy = tsl::rh::power_of_two_growth_policy<2>> +class robin_map { +private: + template + using has_is_transparent = tsl::detail_robin_hash::has_is_transparent; + + class KeySelect { + public: + using key_type = Key; + + const key_type& operator()(const std::pair& key_value) const noexcept { + return key_value.first; + } + + key_type& operator()(std::pair& key_value) noexcept { + return key_value.first; + } + }; + + class ValueSelect { + public: + using value_type = T; + + const value_type& operator()(const std::pair& key_value) const noexcept { + return key_value.second; + } + + value_type& operator()(std::pair& key_value) noexcept { + return key_value.second; + } + }; + + using ht = detail_robin_hash::robin_hash, KeySelect, ValueSelect, + Hash, KeyEqual, Allocator, StoreHash, GrowthPolicy>; + +public: + using key_type = typename ht::key_type; + using mapped_type = T; + using value_type = typename ht::value_type; + using size_type = typename ht::size_type; + using difference_type = typename ht::difference_type; + using hasher = typename ht::hasher; + using key_equal = typename ht::key_equal; + using allocator_type = typename ht::allocator_type; + using reference = typename ht::reference; + using const_reference = typename ht::const_reference; + using pointer = typename ht::pointer; + using const_pointer = typename ht::const_pointer; + using iterator = typename ht::iterator; + using const_iterator = typename ht::const_iterator; + + +public: + /* + * Constructors + */ + robin_map(): robin_map(ht::DEFAULT_INIT_BUCKETS_SIZE) { + } + + explicit robin_map(size_type bucket_count, + const Hash& hash = Hash(), + const KeyEqual& equal = KeyEqual(), + const Allocator& alloc = Allocator()): + m_ht(bucket_count, hash, equal, alloc) + { + } + + robin_map(size_type bucket_count, + const Allocator& alloc): robin_map(bucket_count, Hash(), KeyEqual(), alloc) + { + } + + robin_map(size_type bucket_count, + const Hash& hash, + const Allocator& alloc): robin_map(bucket_count, hash, KeyEqual(), alloc) + { + } + + explicit robin_map(const Allocator& alloc): robin_map(ht::DEFAULT_INIT_BUCKETS_SIZE, alloc) { + } + + template + robin_map(InputIt first, InputIt last, + size_type bucket_count = ht::DEFAULT_INIT_BUCKETS_SIZE, + const Hash& hash = Hash(), + const KeyEqual& equal = KeyEqual(), + const Allocator& alloc = Allocator()): robin_map(bucket_count, hash, equal, alloc) + { + insert(first, last); + } + + template + robin_map(InputIt first, InputIt last, + size_type bucket_count, + const Allocator& alloc): robin_map(first, last, bucket_count, Hash(), KeyEqual(), alloc) + { + } + + template + robin_map(InputIt first, InputIt last, + size_type bucket_count, + const Hash& hash, + const Allocator& alloc): robin_map(first, last, bucket_count, hash, KeyEqual(), alloc) + { + } + + robin_map(std::initializer_list init, + size_type bucket_count = ht::DEFAULT_INIT_BUCKETS_SIZE, + const Hash& hash = Hash(), + const KeyEqual& equal = KeyEqual(), + const Allocator& alloc = Allocator()): + robin_map(init.begin(), init.end(), bucket_count, hash, equal, alloc) + { + } + + robin_map(std::initializer_list init, + size_type bucket_count, + const Allocator& alloc): + robin_map(init.begin(), init.end(), bucket_count, Hash(), KeyEqual(), alloc) + { + } + + robin_map(std::initializer_list init, + size_type bucket_count, + const Hash& hash, + const Allocator& alloc): + robin_map(init.begin(), init.end(), bucket_count, hash, KeyEqual(), alloc) + { + } + + robin_map& operator=(std::initializer_list ilist) { + m_ht.clear(); + + m_ht.reserve(ilist.size()); + m_ht.insert(ilist.begin(), ilist.end()); + + return *this; + } + + allocator_type get_allocator() const { return m_ht.get_allocator(); } + + + /* + * Iterators + */ + iterator begin() noexcept { return m_ht.begin(); } + const_iterator begin() const noexcept { return m_ht.begin(); } + const_iterator cbegin() const noexcept { return m_ht.cbegin(); } + + iterator end() noexcept { return m_ht.end(); } + const_iterator end() const noexcept { return m_ht.end(); } + const_iterator cend() const noexcept { return m_ht.cend(); } + + + /* + * Capacity + */ + bool empty() const noexcept { return m_ht.empty(); } + size_type size() const noexcept { return m_ht.size(); } + size_type max_size() const noexcept { return m_ht.max_size(); } + + /* + * Modifiers + */ + void clear() noexcept { m_ht.clear(); } + + + + std::pair insert(const value_type& value) { + return m_ht.insert(value); + } + + template::value>::type* = nullptr> + std::pair insert(P&& value) { + return m_ht.emplace(std::forward

(value)); + } + + std::pair insert(value_type&& value) { + return m_ht.insert(std::move(value)); + } + + + iterator insert(const_iterator hint, const value_type& value) { + return m_ht.insert_hint(hint, value); + } + + template::value>::type* = nullptr> + iterator insert(const_iterator hint, P&& value) { + return m_ht.emplace_hint(hint, std::forward

(value)); + } + + iterator insert(const_iterator hint, value_type&& value) { + return m_ht.insert_hint(hint, std::move(value)); + } + + + template + void insert(InputIt first, InputIt last) { + m_ht.insert(first, last); + } + + void insert(std::initializer_list ilist) { + m_ht.insert(ilist.begin(), ilist.end()); + } + + + + + template + std::pair insert_or_assign(const key_type& k, M&& obj) { + return m_ht.insert_or_assign(k, std::forward(obj)); + } + + template + std::pair insert_or_assign(key_type&& k, M&& obj) { + return m_ht.insert_or_assign(std::move(k), std::forward(obj)); + } + + template + iterator insert_or_assign(const_iterator hint, const key_type& k, M&& obj) { + return m_ht.insert_or_assign(hint, k, std::forward(obj)); + } + + template + iterator insert_or_assign(const_iterator hint, key_type&& k, M&& obj) { + return m_ht.insert_or_assign(hint, std::move(k), std::forward(obj)); + } + + + + /** + * Due to the way elements are stored, emplace will need to move or copy the key-value once. + * The method is equivalent to insert(value_type(std::forward(args)...)); + * + * Mainly here for compatibility with the std::unordered_map interface. + */ + template + std::pair emplace(Args&&... args) { + return m_ht.emplace(std::forward(args)...); + } + + + + /** + * Due to the way elements are stored, emplace_hint will need to move or copy the key-value once. + * The method is equivalent to insert(hint, value_type(std::forward(args)...)); + * + * Mainly here for compatibility with the std::unordered_map interface. + */ + template + iterator emplace_hint(const_iterator hint, Args&&... args) { + return m_ht.emplace_hint(hint, std::forward(args)...); + } + + + + + template + std::pair try_emplace(const key_type& k, Args&&... args) { + return m_ht.try_emplace(k, std::forward(args)...); + } + + template + std::pair try_emplace(key_type&& k, Args&&... args) { + return m_ht.try_emplace(std::move(k), std::forward(args)...); + } + + template + iterator try_emplace(const_iterator hint, const key_type& k, Args&&... args) { + return m_ht.try_emplace_hint(hint, k, std::forward(args)...); + } + + template + iterator try_emplace(const_iterator hint, key_type&& k, Args&&... args) { + return m_ht.try_emplace_hint(hint, std::move(k), std::forward(args)...); + } + + + + + iterator erase(iterator pos) { return m_ht.erase(pos); } + iterator erase(const_iterator pos) { return m_ht.erase(pos); } + iterator erase(const_iterator first, const_iterator last) { return m_ht.erase(first, last); } + size_type erase(const key_type& key) { return m_ht.erase(key); } + + /** + * Use the hash value 'precalculated_hash' instead of hashing the key. The hash value should be the same + * as hash_function()(key). Useful to speed-up the lookup to the value if you already have the hash. + */ + size_type erase(const key_type& key, std::size_t precalculated_hash) { + return m_ht.erase(key, precalculated_hash); + } + + /** + * This overload only participates in the overload resolution if the typedef KeyEqual::is_transparent exists. + * If so, K must be hashable and comparable to Key. + */ + template::value>::type* = nullptr> + size_type erase(const K& key) { return m_ht.erase(key); } + + /** + * @copydoc erase(const K& key) + * + * Use the hash value 'precalculated_hash' instead of hashing the key. The hash value should be the same + * as hash_function()(key). Useful to speed-up the lookup to the value if you already have the hash. + */ + template::value>::type* = nullptr> + size_type erase(const K& key, std::size_t precalculated_hash) { + return m_ht.erase(key, precalculated_hash); + } + + + + void swap(robin_map& other) { other.m_ht.swap(m_ht); } + + + + /* + * Lookup + */ + T& at(const Key& key) { return m_ht.at(key); } + + /** + * Use the hash value 'precalculated_hash' instead of hashing the key. The hash value should be the same + * as hash_function()(key). Useful to speed-up the lookup if you already have the hash. + */ + T& at(const Key& key, std::size_t precalculated_hash) { return m_ht.at(key, precalculated_hash); } + + + const T& at(const Key& key) const { return m_ht.at(key); } + + /** + * @copydoc at(const Key& key, std::size_t precalculated_hash) + */ + const T& at(const Key& key, std::size_t precalculated_hash) const { return m_ht.at(key, precalculated_hash); } + + + /** + * This overload only participates in the overload resolution if the typedef KeyEqual::is_transparent exists. + * If so, K must be hashable and comparable to Key. + */ + template::value>::type* = nullptr> + T& at(const K& key) { return m_ht.at(key); } + + /** + * @copydoc at(const K& key) + * + * Use the hash value 'precalculated_hash' instead of hashing the key. The hash value should be the same + * as hash_function()(key). Useful to speed-up the lookup if you already have the hash. + */ + template::value>::type* = nullptr> + T& at(const K& key, std::size_t precalculated_hash) { return m_ht.at(key, precalculated_hash); } + + + /** + * @copydoc at(const K& key) + */ + template::value>::type* = nullptr> + const T& at(const K& key) const { return m_ht.at(key); } + + /** + * @copydoc at(const K& key, std::size_t precalculated_hash) + */ + template::value>::type* = nullptr> + const T& at(const K& key, std::size_t precalculated_hash) const { return m_ht.at(key, precalculated_hash); } + + + + + T& operator[](const Key& key) { return m_ht[key]; } + T& operator[](Key&& key) { return m_ht[std::move(key)]; } + + + + + size_type count(const Key& key) const { return m_ht.count(key); } + + /** + * Use the hash value 'precalculated_hash' instead of hashing the key. The hash value should be the same + * as hash_function()(key). Useful to speed-up the lookup if you already have the hash. + */ + size_type count(const Key& key, std::size_t precalculated_hash) const { + return m_ht.count(key, precalculated_hash); + } + + /** + * This overload only participates in the overload resolution if the typedef KeyEqual::is_transparent exists. + * If so, K must be hashable and comparable to Key. + */ + template::value>::type* = nullptr> + size_type count(const K& key) const { return m_ht.count(key); } + + /** + * @copydoc count(const K& key) const + * + * Use the hash value 'precalculated_hash' instead of hashing the key. The hash value should be the same + * as hash_function()(key). Useful to speed-up the lookup if you already have the hash. + */ + template::value>::type* = nullptr> + size_type count(const K& key, std::size_t precalculated_hash) const { return m_ht.count(key, precalculated_hash); } + + + + + iterator find(const Key& key) { return m_ht.find(key); } + + /** + * Use the hash value 'precalculated_hash' instead of hashing the key. The hash value should be the same + * as hash_function()(key). Useful to speed-up the lookup if you already have the hash. + */ + iterator find(const Key& key, std::size_t precalculated_hash) { return m_ht.find(key, precalculated_hash); } + + const_iterator find(const Key& key) const { return m_ht.find(key); } + + /** + * @copydoc find(const Key& key, std::size_t precalculated_hash) + */ + const_iterator find(const Key& key, std::size_t precalculated_hash) const { + return m_ht.find(key, precalculated_hash); + } + + /** + * This overload only participates in the overload resolution if the typedef KeyEqual::is_transparent exists. + * If so, K must be hashable and comparable to Key. + */ + template::value>::type* = nullptr> + iterator find(const K& key) { return m_ht.find(key); } + + /** + * @copydoc find(const K& key) + * + * Use the hash value 'precalculated_hash' instead of hashing the key. The hash value should be the same + * as hash_function()(key). Useful to speed-up the lookup if you already have the hash. + */ + template::value>::type* = nullptr> + iterator find(const K& key, std::size_t precalculated_hash) { return m_ht.find(key, precalculated_hash); } + + /** + * @copydoc find(const K& key) + */ + template::value>::type* = nullptr> + const_iterator find(const K& key) const { return m_ht.find(key); } + + /** + * @copydoc find(const K& key) + * + * Use the hash value 'precalculated_hash' instead of hashing the key. The hash value should be the same + * as hash_function()(key). Useful to speed-up the lookup if you already have the hash. + */ + template::value>::type* = nullptr> + const_iterator find(const K& key, std::size_t precalculated_hash) const { + return m_ht.find(key, precalculated_hash); + } + + + + + bool contains(const Key& key) const { return m_ht.contains(key); } + + /** + * Use the hash value 'precalculated_hash' instead of hashing the key. The hash value should be the same + * as hash_function()(key). Useful to speed-up the lookup if you already have the hash. + */ + bool contains(const Key& key, std::size_t precalculated_hash) const { + return m_ht.contains(key, precalculated_hash); + } + + /** + * This overload only participates in the overload resolution if the typedef KeyEqual::is_transparent exists. + * If so, K must be hashable and comparable to Key. + */ + template::value>::type* = nullptr> + bool contains(const K& key) const { return m_ht.contains(key); } + + /** + * @copydoc contains(const K& key) const + * + * Use the hash value 'precalculated_hash' instead of hashing the key. The hash value should be the same + * as hash_function()(key). Useful to speed-up the lookup if you already have the hash. + */ + template::value>::type* = nullptr> + bool contains(const K& key, std::size_t precalculated_hash) const { + return m_ht.contains(key, precalculated_hash); + } + + + + + std::pair equal_range(const Key& key) { return m_ht.equal_range(key); } + + /** + * Use the hash value 'precalculated_hash' instead of hashing the key. The hash value should be the same + * as hash_function()(key). Useful to speed-up the lookup if you already have the hash. + */ + std::pair equal_range(const Key& key, std::size_t precalculated_hash) { + return m_ht.equal_range(key, precalculated_hash); + } + + std::pair equal_range(const Key& key) const { return m_ht.equal_range(key); } + + /** + * @copydoc equal_range(const Key& key, std::size_t precalculated_hash) + */ + std::pair equal_range(const Key& key, std::size_t precalculated_hash) const { + return m_ht.equal_range(key, precalculated_hash); + } + + /** + * This overload only participates in the overload resolution if the typedef KeyEqual::is_transparent exists. + * If so, K must be hashable and comparable to Key. + */ + template::value>::type* = nullptr> + std::pair equal_range(const K& key) { return m_ht.equal_range(key); } + + + /** + * @copydoc equal_range(const K& key) + * + * Use the hash value 'precalculated_hash' instead of hashing the key. The hash value should be the same + * as hash_function()(key). Useful to speed-up the lookup if you already have the hash. + */ + template::value>::type* = nullptr> + std::pair equal_range(const K& key, std::size_t precalculated_hash) { + return m_ht.equal_range(key, precalculated_hash); + } + + /** + * @copydoc equal_range(const K& key) + */ + template::value>::type* = nullptr> + std::pair equal_range(const K& key) const { return m_ht.equal_range(key); } + + /** + * @copydoc equal_range(const K& key, std::size_t precalculated_hash) + */ + template::value>::type* = nullptr> + std::pair equal_range(const K& key, std::size_t precalculated_hash) const { + return m_ht.equal_range(key, precalculated_hash); + } + + + + + /* + * Bucket interface + */ + size_type bucket_count() const { return m_ht.bucket_count(); } + size_type max_bucket_count() const { return m_ht.max_bucket_count(); } + + + /* + * Hash policy + */ + float load_factor() const { return m_ht.load_factor(); } + + float min_load_factor() const { return m_ht.min_load_factor(); } + float max_load_factor() const { return m_ht.max_load_factor(); } + + /** + * Set the `min_load_factor` to `ml`. When the `load_factor` of the map goes + * below `min_load_factor` after some erase operations, the map will be + * shrunk when an insertion occurs. The erase method itself never shrinks + * the map. + * + * The default value of `min_load_factor` is 0.0f, the map never shrinks by default. + */ + void min_load_factor(float ml) { m_ht.min_load_factor(ml); } + void max_load_factor(float ml) { m_ht.max_load_factor(ml); } + + void rehash(size_type count) { m_ht.rehash(count); } + void reserve(size_type count) { m_ht.reserve(count); } + + + /* + * Observers + */ + hasher hash_function() const { return m_ht.hash_function(); } + key_equal key_eq() const { return m_ht.key_eq(); } + + /* + * Other + */ + + /** + * Convert a const_iterator to an iterator. + */ + iterator mutable_iterator(const_iterator pos) { + return m_ht.mutable_iterator(pos); + } + + friend bool operator==(const robin_map& lhs, const robin_map& rhs) { + if(lhs.size() != rhs.size()) { + return false; + } + + for(const auto& element_lhs: lhs) { + const auto it_element_rhs = rhs.find(element_lhs.first); + if(it_element_rhs == rhs.cend() || element_lhs.second != it_element_rhs->second) { + return false; + } + } + + return true; + } + + friend bool operator!=(const robin_map& lhs, const robin_map& rhs) { + return !operator==(lhs, rhs); + } + + friend void swap(robin_map& lhs, robin_map& rhs) { + lhs.swap(rhs); + } + +private: + ht m_ht; +}; + + +/** + * Same as `tsl::robin_map`. + */ +template, + class KeyEqual = std::equal_to, + class Allocator = std::allocator>, + bool StoreHash = false> +using robin_pg_map = robin_map; + +} // end namespace tsl + +#endif diff --git a/testbed/TileDB-Inc__TileDB-Py/external/tsl/robin_set.h b/testbed/TileDB-Inc__TileDB-Py/external/tsl/robin_set.h new file mode 100644 index 0000000000000000000000000000000000000000..8f1b9082f8ca6874ed20ec6f913de132af82f82e --- /dev/null +++ b/testbed/TileDB-Inc__TileDB-Py/external/tsl/robin_set.h @@ -0,0 +1,582 @@ +/** + * MIT License + * + * Copyright (c) 2017 Thibaut Goetghebuer-Planchon + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +#ifndef TSL_ROBIN_SET_H +#define TSL_ROBIN_SET_H + + +#include +#include +#include +#include +#include +#include +#include "robin_hash.h" + + +namespace tsl { + + +/** + * Implementation of a hash set using open-addressing and the robin hood hashing algorithm with backward shift deletion. + * + * For operations modifying the hash set (insert, erase, rehash, ...), the strong exception guarantee + * is only guaranteed when the expression `std::is_nothrow_swappable::value && + * std::is_nothrow_move_constructible::value` is true, otherwise if an exception + * is thrown during the swap or the move, the hash set may end up in a undefined state. Per the standard + * a `Key` with a noexcept copy constructor and no move constructor also satisfies the + * `std::is_nothrow_move_constructible::value` criterion (and will thus guarantee the + * strong exception for the set). + * + * When `StoreHash` is true, 32 bits of the hash are stored alongside the values. It can improve + * the performance during lookups if the `KeyEqual` function takes time (or engenders a cache-miss for example) + * as we then compare the stored hashes before comparing the keys. When `tsl::rh::power_of_two_growth_policy` is used + * as `GrowthPolicy`, it may also speed-up the rehash process as we can avoid to recalculate the hash. + * When it is detected that storing the hash will not incur any memory penalty due to alignment (i.e. + * `sizeof(tsl::detail_robin_hash::bucket_entry) == + * sizeof(tsl::detail_robin_hash::bucket_entry)`) and `tsl::rh::power_of_two_growth_policy` is + * used, the hash will be stored even if `StoreHash` is false so that we can speed-up the rehash (but it will + * not be used on lookups unless `StoreHash` is true). + * + * `GrowthPolicy` defines how the set grows and consequently how a hash value is mapped to a bucket. + * By default the set uses `tsl::rh::power_of_two_growth_policy`. This policy keeps the number of buckets + * to a power of two and uses a mask to set the hash to a bucket instead of the slow modulo. + * Other growth policies are available and you may define your own growth policy, + * check `tsl::rh::power_of_two_growth_policy` for the interface. + * + * `Key` must be swappable. + * + * `Key` must be copy and/or move constructible. + * + * If the destructor of `Key` throws an exception, the behaviour of the class is undefined. + * + * Iterators invalidation: + * - clear, operator=, reserve, rehash: always invalidate the iterators. + * - insert, emplace, emplace_hint, operator[]: if there is an effective insert, invalidate the iterators. + * - erase: always invalidate the iterators. + */ +template, + class KeyEqual = std::equal_to, + class Allocator = std::allocator, + bool StoreHash = false, + class GrowthPolicy = tsl::rh::power_of_two_growth_policy<2>> +class robin_set { +private: + template + using has_is_transparent = tsl::detail_robin_hash::has_is_transparent; + + class KeySelect { + public: + using key_type = Key; + + const key_type& operator()(const Key& key) const noexcept { + return key; + } + + key_type& operator()(Key& key) noexcept { + return key; + } + }; + + using ht = detail_robin_hash::robin_hash; + +public: + using key_type = typename ht::key_type; + using value_type = typename ht::value_type; + using size_type = typename ht::size_type; + using difference_type = typename ht::difference_type; + using hasher = typename ht::hasher; + using key_equal = typename ht::key_equal; + using allocator_type = typename ht::allocator_type; + using reference = typename ht::reference; + using const_reference = typename ht::const_reference; + using pointer = typename ht::pointer; + using const_pointer = typename ht::const_pointer; + using iterator = typename ht::iterator; + using const_iterator = typename ht::const_iterator; + + + /* + * Constructors + */ + robin_set(): robin_set(ht::DEFAULT_INIT_BUCKETS_SIZE) { + } + + explicit robin_set(size_type bucket_count, + const Hash& hash = Hash(), + const KeyEqual& equal = KeyEqual(), + const Allocator& alloc = Allocator()): + m_ht(bucket_count, hash, equal, alloc) + { + } + + robin_set(size_type bucket_count, + const Allocator& alloc): robin_set(bucket_count, Hash(), KeyEqual(), alloc) + { + } + + robin_set(size_type bucket_count, + const Hash& hash, + const Allocator& alloc): robin_set(bucket_count, hash, KeyEqual(), alloc) + { + } + + explicit robin_set(const Allocator& alloc): robin_set(ht::DEFAULT_INIT_BUCKETS_SIZE, alloc) { + } + + template + robin_set(InputIt first, InputIt last, + size_type bucket_count = ht::DEFAULT_INIT_BUCKETS_SIZE, + const Hash& hash = Hash(), + const KeyEqual& equal = KeyEqual(), + const Allocator& alloc = Allocator()): robin_set(bucket_count, hash, equal, alloc) + { + insert(first, last); + } + + template + robin_set(InputIt first, InputIt last, + size_type bucket_count, + const Allocator& alloc): robin_set(first, last, bucket_count, Hash(), KeyEqual(), alloc) + { + } + + template + robin_set(InputIt first, InputIt last, + size_type bucket_count, + const Hash& hash, + const Allocator& alloc): robin_set(first, last, bucket_count, hash, KeyEqual(), alloc) + { + } + + robin_set(std::initializer_list init, + size_type bucket_count = ht::DEFAULT_INIT_BUCKETS_SIZE, + const Hash& hash = Hash(), + const KeyEqual& equal = KeyEqual(), + const Allocator& alloc = Allocator()): + robin_set(init.begin(), init.end(), bucket_count, hash, equal, alloc) + { + } + + robin_set(std::initializer_list init, + size_type bucket_count, + const Allocator& alloc): + robin_set(init.begin(), init.end(), bucket_count, Hash(), KeyEqual(), alloc) + { + } + + robin_set(std::initializer_list init, + size_type bucket_count, + const Hash& hash, + const Allocator& alloc): + robin_set(init.begin(), init.end(), bucket_count, hash, KeyEqual(), alloc) + { + } + + + robin_set& operator=(std::initializer_list ilist) { + m_ht.clear(); + + m_ht.reserve(ilist.size()); + m_ht.insert(ilist.begin(), ilist.end()); + + return *this; + } + + allocator_type get_allocator() const { return m_ht.get_allocator(); } + + + /* + * Iterators + */ + iterator begin() noexcept { return m_ht.begin(); } + const_iterator begin() const noexcept { return m_ht.begin(); } + const_iterator cbegin() const noexcept { return m_ht.cbegin(); } + + iterator end() noexcept { return m_ht.end(); } + const_iterator end() const noexcept { return m_ht.end(); } + const_iterator cend() const noexcept { return m_ht.cend(); } + + + /* + * Capacity + */ + bool empty() const noexcept { return m_ht.empty(); } + size_type size() const noexcept { return m_ht.size(); } + size_type max_size() const noexcept { return m_ht.max_size(); } + + /* + * Modifiers + */ + void clear() noexcept { m_ht.clear(); } + + + + + std::pair insert(const value_type& value) { + return m_ht.insert(value); + } + + std::pair insert(value_type&& value) { + return m_ht.insert(std::move(value)); + } + + iterator insert(const_iterator hint, const value_type& value) { + return m_ht.insert_hint(hint, value); + } + + iterator insert(const_iterator hint, value_type&& value) { + return m_ht.insert_hint(hint, std::move(value)); + } + + template + void insert(InputIt first, InputIt last) { + m_ht.insert(first, last); + } + + void insert(std::initializer_list ilist) { + m_ht.insert(ilist.begin(), ilist.end()); + } + + + + + /** + * Due to the way elements are stored, emplace will need to move or copy the key-value once. + * The method is equivalent to insert(value_type(std::forward(args)...)); + * + * Mainly here for compatibility with the std::unordered_map interface. + */ + template + std::pair emplace(Args&&... args) { + return m_ht.emplace(std::forward(args)...); + } + + + + /** + * Due to the way elements are stored, emplace_hint will need to move or copy the key-value once. + * The method is equivalent to insert(hint, value_type(std::forward(args)...)); + * + * Mainly here for compatibility with the std::unordered_map interface. + */ + template + iterator emplace_hint(const_iterator hint, Args&&... args) { + return m_ht.emplace_hint(hint, std::forward(args)...); + } + + + + iterator erase(iterator pos) { return m_ht.erase(pos); } + iterator erase(const_iterator pos) { return m_ht.erase(pos); } + iterator erase(const_iterator first, const_iterator last) { return m_ht.erase(first, last); } + size_type erase(const key_type& key) { return m_ht.erase(key); } + + /** + * Use the hash value 'precalculated_hash' instead of hashing the key. The hash value should be the same + * as hash_function()(key). Useful to speed-up the lookup to the value if you already have the hash. + */ + size_type erase(const key_type& key, std::size_t precalculated_hash) { + return m_ht.erase(key, precalculated_hash); + } + + /** + * This overload only participates in the overload resolution if the typedef KeyEqual::is_transparent exists. + * If so, K must be hashable and comparable to Key. + */ + template::value>::type* = nullptr> + size_type erase(const K& key) { return m_ht.erase(key); } + + /** + * @copydoc erase(const K& key) + * + * Use the hash value 'precalculated_hash' instead of hashing the key. The hash value should be the same + * as hash_function()(key). Useful to speed-up the lookup to the value if you already have the hash. + */ + template::value>::type* = nullptr> + size_type erase(const K& key, std::size_t precalculated_hash) { + return m_ht.erase(key, precalculated_hash); + } + + + + void swap(robin_set& other) { other.m_ht.swap(m_ht); } + + + + /* + * Lookup + */ + size_type count(const Key& key) const { return m_ht.count(key); } + + /** + * Use the hash value 'precalculated_hash' instead of hashing the key. The hash value should be the same + * as hash_function()(key). Useful to speed-up the lookup if you already have the hash. + */ + size_type count(const Key& key, std::size_t precalculated_hash) const { return m_ht.count(key, precalculated_hash); } + + /** + * This overload only participates in the overload resolution if the typedef KeyEqual::is_transparent exists. + * If so, K must be hashable and comparable to Key. + */ + template::value>::type* = nullptr> + size_type count(const K& key) const { return m_ht.count(key); } + + /** + * @copydoc count(const K& key) const + * + * Use the hash value 'precalculated_hash' instead of hashing the key. The hash value should be the same + * as hash_function()(key). Useful to speed-up the lookup if you already have the hash. + */ + template::value>::type* = nullptr> + size_type count(const K& key, std::size_t precalculated_hash) const { return m_ht.count(key, precalculated_hash); } + + + + + iterator find(const Key& key) { return m_ht.find(key); } + + /** + * Use the hash value 'precalculated_hash' instead of hashing the key. The hash value should be the same + * as hash_function()(key). Useful to speed-up the lookup if you already have the hash. + */ + iterator find(const Key& key, std::size_t precalculated_hash) { return m_ht.find(key, precalculated_hash); } + + const_iterator find(const Key& key) const { return m_ht.find(key); } + + /** + * @copydoc find(const Key& key, std::size_t precalculated_hash) + */ + const_iterator find(const Key& key, std::size_t precalculated_hash) const { return m_ht.find(key, precalculated_hash); } + + /** + * This overload only participates in the overload resolution if the typedef KeyEqual::is_transparent exists. + * If so, K must be hashable and comparable to Key. + */ + template::value>::type* = nullptr> + iterator find(const K& key) { return m_ht.find(key); } + + /** + * @copydoc find(const K& key) + * + * Use the hash value 'precalculated_hash' instead of hashing the key. The hash value should be the same + * as hash_function()(key). Useful to speed-up the lookup if you already have the hash. + */ + template::value>::type* = nullptr> + iterator find(const K& key, std::size_t precalculated_hash) { return m_ht.find(key, precalculated_hash); } + + /** + * @copydoc find(const K& key) + */ + template::value>::type* = nullptr> + const_iterator find(const K& key) const { return m_ht.find(key); } + + /** + * @copydoc find(const K& key) + * + * Use the hash value 'precalculated_hash' instead of hashing the key. The hash value should be the same + * as hash_function()(key). Useful to speed-up the lookup if you already have the hash. + */ + template::value>::type* = nullptr> + const_iterator find(const K& key, std::size_t precalculated_hash) const { return m_ht.find(key, precalculated_hash); } + + + + + bool contains(const Key& key) const { return m_ht.contains(key); } + + /** + * Use the hash value 'precalculated_hash' instead of hashing the key. The hash value should be the same + * as hash_function()(key). Useful to speed-up the lookup if you already have the hash. + */ + bool contains(const Key& key, std::size_t precalculated_hash) const { + return m_ht.contains(key, precalculated_hash); + } + + /** + * This overload only participates in the overload resolution if the typedef KeyEqual::is_transparent exists. + * If so, K must be hashable and comparable to Key. + */ + template::value>::type* = nullptr> + bool contains(const K& key) const { return m_ht.contains(key); } + + /** + * @copydoc contains(const K& key) const + * + * Use the hash value 'precalculated_hash' instead of hashing the key. The hash value should be the same + * as hash_function()(key). Useful to speed-up the lookup if you already have the hash. + */ + template::value>::type* = nullptr> + bool contains(const K& key, std::size_t precalculated_hash) const { + return m_ht.contains(key, precalculated_hash); + } + + + + + std::pair equal_range(const Key& key) { return m_ht.equal_range(key); } + + /** + * Use the hash value 'precalculated_hash' instead of hashing the key. The hash value should be the same + * as hash_function()(key). Useful to speed-up the lookup if you already have the hash. + */ + std::pair equal_range(const Key& key, std::size_t precalculated_hash) { + return m_ht.equal_range(key, precalculated_hash); + } + + std::pair equal_range(const Key& key) const { return m_ht.equal_range(key); } + + /** + * @copydoc equal_range(const Key& key, std::size_t precalculated_hash) + */ + std::pair equal_range(const Key& key, std::size_t precalculated_hash) const { + return m_ht.equal_range(key, precalculated_hash); + } + + /** + * This overload only participates in the overload resolution if the typedef KeyEqual::is_transparent exists. + * If so, K must be hashable and comparable to Key. + */ + template::value>::type* = nullptr> + std::pair equal_range(const K& key) { return m_ht.equal_range(key); } + + /** + * @copydoc equal_range(const K& key) + * + * Use the hash value 'precalculated_hash' instead of hashing the key. The hash value should be the same + * as hash_function()(key). Useful to speed-up the lookup if you already have the hash. + */ + template::value>::type* = nullptr> + std::pair equal_range(const K& key, std::size_t precalculated_hash) { + return m_ht.equal_range(key, precalculated_hash); + } + + /** + * @copydoc equal_range(const K& key) + */ + template::value>::type* = nullptr> + std::pair equal_range(const K& key) const { return m_ht.equal_range(key); } + + /** + * @copydoc equal_range(const K& key, std::size_t precalculated_hash) + */ + template::value>::type* = nullptr> + std::pair equal_range(const K& key, std::size_t precalculated_hash) const { + return m_ht.equal_range(key, precalculated_hash); + } + + + + + /* + * Bucket interface + */ + size_type bucket_count() const { return m_ht.bucket_count(); } + size_type max_bucket_count() const { return m_ht.max_bucket_count(); } + + + /* + * Hash policy + */ + float load_factor() const { return m_ht.load_factor(); } + + float min_load_factor() const { return m_ht.min_load_factor(); } + float max_load_factor() const { return m_ht.max_load_factor(); } + + /** + * Set the `min_load_factor` to `ml`. When the `load_factor` of the set goes + * below `min_load_factor` after some erase operations, the set will be + * shrunk when an insertion occurs. The erase method itself never shrinks + * the set. + * + * The default value of `min_load_factor` is 0.0f, the set never shrinks by default. + */ + void min_load_factor(float ml) { m_ht.min_load_factor(ml); } + void max_load_factor(float ml) { m_ht.max_load_factor(ml); } + + void rehash(size_type count) { m_ht.rehash(count); } + void reserve(size_type count) { m_ht.reserve(count); } + + + /* + * Observers + */ + hasher hash_function() const { return m_ht.hash_function(); } + key_equal key_eq() const { return m_ht.key_eq(); } + + + /* + * Other + */ + + /** + * Convert a const_iterator to an iterator. + */ + iterator mutable_iterator(const_iterator pos) { + return m_ht.mutable_iterator(pos); + } + + friend bool operator==(const robin_set& lhs, const robin_set& rhs) { + if(lhs.size() != rhs.size()) { + return false; + } + + for(const auto& element_lhs: lhs) { + const auto it_element_rhs = rhs.find(element_lhs); + if(it_element_rhs == rhs.cend()) { + return false; + } + } + + return true; + } + + friend bool operator!=(const robin_set& lhs, const robin_set& rhs) { + return !operator==(lhs, rhs); + } + + friend void swap(robin_set& lhs, robin_set& rhs) { + lhs.swap(rhs); + } + +private: + ht m_ht; +}; + + +/** + * Same as `tsl::robin_set`. + */ +template, + class KeyEqual = std::equal_to, + class Allocator = std::allocator, + bool StoreHash = false> +using robin_pg_set = robin_set; + +} // end namespace tsl + +#endif + diff --git a/testbed/TileDB-Inc__TileDB-Py/misc/pypi_linux/Dockerfile.aarch64.manylinux2014 b/testbed/TileDB-Inc__TileDB-Py/misc/pypi_linux/Dockerfile.aarch64.manylinux2014 new file mode 100644 index 0000000000000000000000000000000000000000..febf9e34bec9b188dc6fa83d1b1f28c844975545 --- /dev/null +++ b/testbed/TileDB-Inc__TileDB-Py/misc/pypi_linux/Dockerfile.aarch64.manylinux2014 @@ -0,0 +1,61 @@ +FROM quay.io/pypa/manylinux2014_aarch64 + +############################################### +# version args +ARG LIBTILEDB_VERSION=2.5.2 +ENV LIBTILEDB_VERSION=$LIBTILEDB_VERSION + +ARG LIBTILEDB_REPO=https://github.com/TileDB-Inc/TileDB +ENV LIBTILEDB_REPO=$LIBTILEDB_REPO + +ARG TILEDBPY_VERSION=0.11.2 +ENV TILEDBPY_VERSION=$TILEDBPY_VERSION + +ARG CMAKE_VERSION=3.21 +ENV CMAKE_VERSION=$CMAKE_VERSION + +############################################### +# python settings +# NOTE: MUST USE the 'mu' variant here to be compatible +# with "most" linux distros (see manylinux README) +ENV PYTHON_BASE /opt/python/cp38-cp38/bin/ + +RUN useradd tiledb +ENV HOME /home/tiledb + +# dependencies: +# - cmake (need recent) and auditwheel from pip +RUN $PYTHON_BASE/pip install cmake==${CMAKE_VERSION} auditwheel cibuildwheel + +ENV CMAKE $PYTHON_BASE/cmake + +############################################### +# build libtiledb (core) +# notes: +# 1) we are using auditwheel from https://github.com/pypa/auditwheel +# this verifies and tags wheel products with the manylinux1 label, +# and allows us to build libtiledb once, install it to a normal +# system path, and then use it to build wheels for all of the python +# versions. + +# NOTE: NO GCS SUPPORT + +RUN cd /home/tiledb/ && \ + git clone ${LIBTILEDB_REPO} -b ${LIBTILEDB_VERSION} --depth=1 && \ + mkdir build && \ + cd build && \ + $CMAKE -DTILEDB_S3=ON -DTILEDB_AZURE=ON \ + -DTILEDB_SERIALIZATION=ON \ + -DTILEDB_CPP_API=ON -DTILEDB_HDFS=ON -DTILEDB_TESTS=OFF \ + -DTILEDB_GCS=ON \ + -DTILEDB_FORCE_ALL_DEPS:BOOL=ON \ + -DTILEDB_LOG_OUTPUT_ON_FAILURE:BOOL=ON \ + -DSANITIZER=OFF -DTILEDB_WERROR=OFF \ + -DCMAKE_CXX_STANDARD=17 \ + ../TileDB && \ + make -j$(nproc) && \ + make install-tiledb + +############################################### +# add source directory. note: run from base of tree +ADD . /home/tiledb/TileDB-Py diff --git a/testbed/TileDB-Inc__TileDB-Py/misc/pypi_linux/Dockerfile2014 b/testbed/TileDB-Inc__TileDB-Py/misc/pypi_linux/Dockerfile2014 new file mode 100644 index 0000000000000000000000000000000000000000..fde748d3a5bf16d6253bda577f8b237ff4f34648 --- /dev/null +++ b/testbed/TileDB-Inc__TileDB-Py/misc/pypi_linux/Dockerfile2014 @@ -0,0 +1,67 @@ +FROM quay.io/pypa/manylinux2014_x86_64:2022-11-28-5d13db4 + +############################################### +# version args +ARG LIBTILEDB_VERSION=2.2.9 +ENV LIBTILEDB_VERSION=$LIBTILEDB_VERSION + +ARG LIBTILEDB_SHA=dc3bb54adc9bb0d99cb3f56ede2ab5b14e62ab76 +ENV LIBTILEDB_SHA=$LIBTILEDB_SHA + +ARG TILEDBPY_VERSION=0.8.10 +ENV TILEDBPY_VERSION=$TILEDBPY_VERSION + +ARG LIBTILEDB_REPO=https://github.com/TileDB-Inc/TileDB +ENV LIBTILEDB_REPO=$LIBTILEDB_REPO + +############################################### +# python settings +# NOTE: MUST USE the 'mu' variant here to be compatible +# with "most" linux distros (see manylinux README) +ENV PYTHON_BASE /opt/python/cp38-cp38/bin/ + +RUN useradd tiledb +ENV HOME /home/tiledb + +# dependencies: +# - cmake (need recent) and auditwheel from pip +RUN $PYTHON_BASE/pip install cmake<3.22 auditwheel + +ENV CMAKE $PYTHON_BASE/cmake + +############################################### +# 1) Nothing builds under GCC 4.8 due to default constructor unused-parameter warnings +# 2) adding -lrt as a work-around for now because python2.7 doesn't link it, but it +# ends up as an unlinked dependency. +# 3) Capnproto (TileDB Serialization) requeries -DKJ_USE_EPOLL=0 -D__BIONIC__=1 per +# https://github.com/capnproto/capnproto/issues/350#issuecomment-270930594 + +ENV CXXFLAGS -Wno-unused-parameter -lrt -DKJ_USE_EPOLL=0 -D__BIONIC__=1 +ENV CFLAGS -Wno-unused-parameter -lrt -DKJ_USE_EPOLL=0 -D__BIONIC__=1 + +# build libtiledb (core) +# notes: +# 1) we are using auditwheel from https://github.com/pypa/auditwheel +# this verifies and tags wheel products with the manylinux1 label, +# and allows us to build libtiledb once, install it to a normal +# system path, and then use it to build wheels for all of the python +# versions. +RUN cd /home/tiledb/ && \ + git clone ${LIBTILEDB_REPO} && \ + git -C TileDB checkout $LIBTILEDB_SHA && \ + mkdir build && \ + cd build && \ + $CMAKE -DTILEDB_S3=ON -DTILEDB_AZURE=ON -DTILEDB_GCS=ON \ + -DTILEDB_CPP_API=ON -DTILEDB_HDFS=ON -DTILEDB_TESTS=OFF \ + -DTILEDB_FORCE_ALL_DEPS:BOOL=ON \ + -DTILEDB_LOG_OUTPUT_ON_FAILURE:BOOL=ON \ + -DSANITIZER="OFF;-DCOMPILER_SUPPORTS_AVX2:BOOL=FALSE" \ + ../TileDB && \ + make -j8 && \ + make install-tiledb + +ADD misc/pypi_linux/build.sh /usr/bin/build.sh +RUN chmod +x /usr/bin/build.sh + +# add source directory as optional TILEDB_PY_REPO +ADD . /opt/TileDB-Py diff --git a/testbed/TileDB-Inc__TileDB-Py/misc/pypi_linux/build.aarch64.sh b/testbed/TileDB-Inc__TileDB-Py/misc/pypi_linux/build.aarch64.sh new file mode 100644 index 0000000000000000000000000000000000000000..fe9af1c30be03f0cd946c95243c41d4278bc59ad --- /dev/null +++ b/testbed/TileDB-Inc__TileDB-Py/misc/pypi_linux/build.aarch64.sh @@ -0,0 +1,30 @@ +#!/bin/sh + +# Usage: +# 1) update version information +# 2) run from root directory of TileDB-Py checkout +# 3) test and upload wheels to PyPI + +set -xeu + +export LIBTILEDB_VERSION=2.5.3 +export TILEDBPY_VERSION=0.11.5 + +export CIBW_MANYLINUX_AARCH64_IMAGE=wheel-host-aarch64.manylinux2014-$LIBTILEDB_VERSION +export CIBW_SKIP='cp36-* cp310-* pp-* *_i686 pp* *-musllinux*' +export CIBW_PLATFORM='linux' +export CIBW_ENVIRONMENT='TILEDB_PATH=/usr/local/' +export CIBW_BUILD_VERBOSITY=1 +export CIBW_BEFORE_TEST="pip install -r misc/requirements_wheel.txt" +export CIBW_TEST_COMMAND="python -c 'import tiledb'" +export TILEDB_WHEEL_BUILD=1 + +docker build --build-arg=LIBTILEDB_VERSION=$LIBTILEDB_VERSION --build-arg TILEDBPY_VERSION=$TILEDBPY_VERSION -t $CIBW_MANYLINUX_AARCH64_IMAGE -f misc/pypi_linux/Dockerfile.aarch64.manylinux2014 . + +rm -rf /tmp/cibuildwheel_venv +python3 -m venv /tmp/cibuildwheel_venv +. /tmp/cibuildwheel_venv/bin/activate + +pip install cibuildwheel + +cibuildwheel --platform=linux --output-dir=wheelhouse . diff --git a/testbed/TileDB-Inc__TileDB-Py/misc/pypi_linux/build.sh b/testbed/TileDB-Inc__TileDB-Py/misc/pypi_linux/build.sh new file mode 100644 index 0000000000000000000000000000000000000000..79d3db9e9e09fe78350c1557690cce0b396df8d8 --- /dev/null +++ b/testbed/TileDB-Inc__TileDB-Py/misc/pypi_linux/build.sh @@ -0,0 +1,83 @@ +#!/bin/sh + +# USAGE +#------ +# 0) cd TileDB-Py (NOTE: root directory!) +# 1) docker build -f misc/pypi_linux/Dockerfile . -t wheel_builder +# 2) docker run -v `pwd`/misc/pypi_linux/wheels:/wheels -ti wheel_builder build.sh +# +# testing (e.g. using the official python docker images) +# - $ docker run -v `pwd`/misc/pypi_linux/wheels:/wheels --rm -ti python bash +# -- pip3 install /wheels/*cp37*.whl +# -- python3.7 -c "import tiledb; print(tiledb.libtiledb.version()) and assert tiledb.VFS().supports('s3')" +set -ex + +export TILEDB_PY_REPO="/opt/TileDB-Py" + +# build python37 wheel +cd /home/tiledb +git clone $TILEDB_PY_REPO TileDB-Py37 +git -C TileDB-Py37 checkout $TILEDBPY_VERSION + +cd /home/tiledb/TileDB-Py37 +/opt/python/cp37-cp37m/bin/python3.7 -m pip install -r misc/requirements_wheel.txt +/opt/python/cp37-cp37m/bin/python3.7 setup.py build_ext bdist_wheel --tiledb=/usr/local +auditwheel repair dist/*.whl +/opt/python/cp37-cp37m/bin/python3.7 -m pip install wheelhouse/*.whl +cd tiledb/tests +#/opt/python/cp37-cp37m/bin/python3.7 -m unittest + +# build python38 wheel +cd /home/tiledb +git clone $TILEDB_PY_REPO TileDB-Py38 +git -C TileDB-Py38 checkout $TILEDBPY_VERSION + +cd /home/tiledb/TileDB-Py38 +/opt/python/cp38-cp38m/bin/python3.8 -m pip install -r misc/requirements_wheel.txt +/opt/python/cp38-cp38/bin/python3.8 setup.py build_ext bdist_wheel --tiledb=/usr/local +auditwheel repair dist/*.whl +/opt/python/cp38-cp38/bin/python3.8 -m pip install wheelhouse/*.whl +cd tiledb/tests + +# build python39 wheel +cd /home/tiledb +git clone $TILEDB_PY_REPO TileDB-Py39 +git -C TileDB-Py39 checkout $TILEDBPY_VERSION + +cd /home/tiledb/TileDB-Py39 +/opt/python/cp39-cp39m/bin/python3.9 -m pip install -r misc/requirements_wheel.txt +/opt/python/cp39-cp39/bin/python3.9 setup.py build_ext bdist_wheel --tiledb=/usr/local +auditwheel repair dist/*.whl +/opt/python/cp39-cp39/bin/python3.9 -m pip install wheelhouse/*.whl +cd tiledb/tests + +# build python310 wheel +cd /home/tiledb +git clone $TILEDB_PY_REPO TileDB-Py310 +git -C TileDB-Py310 checkout $TILEDBPY_VERSION + +cd /home/tiledb/TileDB-Py310 +/opt/python/cp310-cp310m/bin/python3.10 -m pip install -r misc/requirements_wheel.txt +/opt/python/cp310-cp310/bin/python3.10 setup.py build_ext bdist_wheel --tiledb=/usr/local +auditwheel repair dist/*.whl +/opt/python/cp310-cp310/bin/python3.10 -m pip install wheelhouse/*.whl +cd tiledb/tests + +# build python311 wheel +cd /home/tiledb +git clone $TILEDB_PY_REPO TileDB-Py311 +git -C TileDB-Py311 checkout $TILEDBPY_VERSION + +cd /home/tiledb/TileDB-Py311 +/opt/python/cp311-cp311m/bin/python3.11 -m pip install -r misc/requirements_wheel.txt +/opt/python/cp311-cp311/bin/python3.11 setup.py build_ext bdist_wheel --tiledb=/usr/local +auditwheel repair dist/*.whl +/opt/python/cp311-cp311/bin/python3.11 -m pip install wheelhouse/*.whl +cd tiledb/tests + +# copy build products out +cp /home/tiledb/TileDB-Py37/wheelhouse/* /wheels +cp /home/tiledb/TileDB-Py38/wheelhouse/* /wheels +cp /home/tiledb/TileDB-Py39/wheelhouse/* /wheels +cp /home/tiledb/TileDB-Py310/wheelhouse/* /wheels +cp /home/tiledb/TileDB-Py311/wheelhouse/* /wheels diff --git a/testbed/TileDB-Inc__TileDB-Py/pyproject.toml b/testbed/TileDB-Inc__TileDB-Py/pyproject.toml new file mode 100644 index 0000000000000000000000000000000000000000..8ee52a5001b6489e67b455b91193afc09becb576 --- /dev/null +++ b/testbed/TileDB-Inc__TileDB-Py/pyproject.toml @@ -0,0 +1,120 @@ +[build-system] +requires = [ + "scikit-build-core", + "pybind11", + "Cython>=3", + "numpy>=2.0.1" +] +build-backend = "scikit_build_core.build" + +[project] +requires-python = ">=3.9" +name = "tiledb" +description = "Pythonic interface to the TileDB array storage manager" +readme = "README.md" +license = {text = "MIT"} +authors = [ + {name = "TileDB, Inc.", email = "help@tiledb.io"} +] +maintainers = [ + {name = "TileDB, Inc.", email = "help@tiledb.io"} +] +classifiers=[ + "Development Status :: 4 - Beta", + "Intended Audience :: Developers", + "Intended Audience :: Information Technology", + "Intended Audience :: Science/Research", + "License :: OSI Approved :: MIT License", + "Programming Language :: Python", + "Topic :: Software Development :: Libraries :: Python Modules", + "Operating System :: Unix", + "Operating System :: POSIX :: Linux", + "Operating System :: MacOS :: MacOS X", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3.9", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Programming Language :: Python :: 3.12", + "Programming Language :: Python :: 3.13", +] +dependencies = [ + "numpy>=1.25", + "packaging", +] +dynamic = ["version"] + +[project.optional-dependencies] +doc = [ + "jinja2==3.0.0", + "sphinx-rtd-theme==2.0.0", + "Sphinx", + "breathe", +] +test = [ + "pytest", + "hypothesis", + "psutil", + "pyarrow", + "pandas", + "dask[distributed]", +] + +[project.urls] +homepage = "https://github.com/TileDB-Inc/TileDB-Py" + +[tool.setuptools_scm] +version_file = "tiledb/_generated_version.py" + +[tool.scikit-build] +wheel.expand-macos-universal-tags = true +metadata.version.provider = "scikit_build_core.metadata.setuptools_scm" +wheel.packages = ["tiledb", "examples", "external"] +wheel.license-files = ["LICENSE", "external/LICENSE-*.txt"] +sdist.include = ["tiledb/_generated_version.py"] + +[tool.scikit-build.cmake.define] +TILEDB_PATH = {env="TILEDB_PATH"} +TILEDB_VERSION = {env="TILEDB_VERSION"} +TILEDB_HASH = {env="TILEDB_HASH"} +TILEDB_REMOVE_DEPRECATIONS = "ON" +TILEDB_SERIALIZATION = "OFF" + +[tool.pytest.ini_options] +python_classes = "*Test*" +python_files = "test_*.py" +testpaths = ["tiledb/tests"] +addopts = [ + "--import-mode=importlib", + "--ignore=tiledb/tests/perf", + "--ignore=tiledb/tests/__pycache__", +] +filterwarnings = [ + "error", + "default::pytest.PytestWarning", + "default::DeprecationWarning:distributed", + # Pyarrow emits a warning regarding use of deprecated Pandas function + # Remove this once we bump Pyarrow version + "ignore:Passing a BlockManager to DataFrame is deprecated:DeprecationWarning" +] + +[tool.ruff] +ignore = ["E501", "E722"] +extend-select = ["I001"] +extend-exclude = ["doc"] +fix = true + +[tool.ruff.lint] +select = ["NPY201"] + +[tool.ruff.per-file-ignores] +"tiledb/__init__.py" = ["F401"] + +[tool.cibuildwheel] +test-requires = [ + "pytest", + "hypothesis", + "psutil", + "pyarrow", + "pandas", +] +test-command = "pytest {project}" diff --git a/testbed/TileDB-Inc__TileDB-Py/setup.py b/testbed/TileDB-Inc__TileDB-Py/setup.py new file mode 100644 index 0000000000000000000000000000000000000000..37ee5cb4c6b34d4e8fb4a8186d1e06257f06eab6 --- /dev/null +++ b/testbed/TileDB-Inc__TileDB-Py/setup.py @@ -0,0 +1,52 @@ +import argparse +import os +import subprocess + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("command", choices=["install", "develop"]) + parser.add_argument("--tiledb", type=str, required=False) + parser.add_argument("--debug", action="store_true") + parser.add_argument("--enable-deprecations", action="store_true", required=False) + parser.add_argument("--enable-serialization", action="store_true", required=False) + parser.add_argument("-v", action="store_true") + args = parser.parse_args() + + os.getcwd() + + cmd = [ + "pip", + "install", + ] + + if args.command == "develop": + cmd.append("-e") + + cmd.append(os.getcwd()) + + if args.tiledb: + cmd.append(f"-Cskbuild.cmake.define.TILEDB_PATH={args.tiledb}") + + if args.debug: + cmd.append(f"-Cskbuild.cmake.build-type=Debug") + + if args.enable_deprecations: + cmd.append(f"-Cskbuild.cmake.define.TILEDB_REMOVE_DEPRECATIONS=OFF") + + if args.enable_serialization: + cmd.append(f"-Cskbuild.cmake.define.TILEDB_SERIALIZATION=ON") + + if args.v: + cmd.append("-v") + + print( + "Note: 'setup.py' is deprecated in the Python ecosystem. Limited backward compatibility is currently provided for 'install' and 'develop' commands as passthrough to 'pip'." + ) + print(" running: ", f"`{' '.join(cmd)}`") + + subprocess.run(cmd) + + +if __name__ == "__main__": + main() diff --git a/testbed/TileDB-Inc__TileDB-Py/tiledb/CMakeLists.txt b/testbed/TileDB-Inc__TileDB-Py/tiledb/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..3f9dc05ae68dc4a1de766696b73fb0618c66ba64 --- /dev/null +++ b/testbed/TileDB-Inc__TileDB-Py/tiledb/CMakeLists.txt @@ -0,0 +1,90 @@ +# Cython + +add_custom_command( + OUTPUT libtiledb.cc + COMMAND Python::Interpreter -m cython + "${CMAKE_CURRENT_SOURCE_DIR}/libtiledb.pyx" --output-file libtiledb.cc + DEPENDS libtiledb.pyx + VERBATIM +) + +python_add_library( + libtiledb + MODULE + libtiledb.cc + WITH_SOABI +) + +target_link_libraries( + libtiledb + PUBLIC + Python::NumPy + TileDB::tiledb_shared +) + +target_compile_features( + libtiledb + PUBLIC + cxx_std_20 +) + +# Pybind11 + +pybind11_add_module( + main + main.cc + core.cc + npbuffer.cc + fragment.cc + schema_evolution.cc + util.cc + serialization.cc + tests/test_metadata.cc + tests/test_webp.cc + tests/test_serialization.cc +) + +target_link_libraries( + main + PUBLIC + TileDB::tiledb_shared +) + +target_compile_features( + main + PUBLIC + cxx_std_20 +) + +if (TILEDB_SERIALIZATION) + target_compile_definitions( + main + PRIVATE + TILEDB_SERIALIZATION + ) +endif() + +install(TARGETS main libtiledb DESTINATION tiledb) + +if(TILEDB_DOWNLOADED) + message(STATUS "Adding \"libtiledb\" into install group") + + install(IMPORTED_RUNTIME_ARTIFACTS TileDB::tiledb_shared DESTINATION tiledb) + + if (APPLE) + set_target_properties(main PROPERTIES INSTALL_RPATH "@loader_path") + set_target_properties(libtiledb PROPERTIES INSTALL_RPATH "@loader_path") + elseif(UNIX) + set_target_properties(main PROPERTIES INSTALL_RPATH "\$ORIGIN") + set_target_properties(libtiledb PROPERTIES INSTALL_RPATH "\$ORIGIN") + endif() +else() + # If using external TileDB core library force it to be linked at runtime using RPATH + get_property(TILEDB_LOCATION TARGET TileDB::tiledb_shared PROPERTY LOCATION) + get_filename_component(TILEDB_LOCATION ${TILEDB_LOCATION} DIRECTORY) + message(STATUS "Setting RPATH for targets \"main\" and \"libtiledb\" to ${TILEDB_LOCATION}") + set_target_properties(main PROPERTIES INSTALL_RPATH ${TILEDB_LOCATION}) + set_target_properties(libtiledb PROPERTIES INSTALL_RPATH ${TILEDB_LOCATION}) +endif() + +add_subdirectory(cc) \ No newline at end of file diff --git a/testbed/TileDB-Inc__TileDB-Py/tiledb/__init__.py b/testbed/TileDB-Inc__TileDB-Py/tiledb/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..c51250bb27b11c417f3d84e934c54fc116ee7a0c --- /dev/null +++ b/testbed/TileDB-Inc__TileDB-Py/tiledb/__init__.py @@ -0,0 +1,145 @@ +import ctypes +import os +import sys + +# un-comment this section to fix Cython backtrace line-numbers in +# IPython/Jupyter. see https://bugs.python.org/issue32797#msg323167 +# --- +# try: +# from importlib.machinery import ExtensionFileLoader +# else: +# del ExtensionFileLoader.get_source +# --- + +if os.name == "posix": + if sys.platform == "darwin": + lib_name = "libtiledb.dylib" + else: + lib_name = "libtiledb.so" +else: + lib_name = "tiledb" + +from tiledb.libtiledb import version as libtiledb_version + +if libtiledb_version()[0] == 2 and libtiledb_version()[1] >= 25: + from .current_domain import CurrentDomain + from .ndrectangle import NDRectangle + +del libtiledb_version # no longer needed + +from .array_schema import ArraySchema +from .attribute import Attr +from .cc import TileDBError +from .consolidation_plan import ConsolidationPlan +from .ctx import Config, Ctx, default_ctx, scope_ctx +from .dataframe_ import from_csv, from_pandas, open_dataframe +from .dense_array import DenseArrayImpl +from .dimension import Dim +from .dimension_label import DimLabel +from .dimension_label_schema import DimLabelSchema +from .domain import Domain +from .enumeration import Enumeration +from .filestore import Filestore +from .filter import ( + BitShuffleFilter, + BitWidthReductionFilter, + ByteShuffleFilter, + Bzip2Filter, + ChecksumMD5Filter, + ChecksumSHA256Filter, + CompressionFilter, + DeltaFilter, + DictionaryFilter, + DoubleDeltaFilter, + Filter, + FilterList, + FloatScaleFilter, + GzipFilter, + LZ4Filter, + NoOpFilter, + PositiveDeltaFilter, + RleFilter, + WebpFilter, + XORFilter, + ZstdFilter, +) +from .fragment import ( + FragmentInfo, + FragmentInfoList, + copy_fragments_to_existing_array, + create_array_from_fragments, +) +from .group import Group +from .highlevel import ( + array_exists, + array_fragments, + as_built, + consolidate, + empty_like, + from_numpy, + ls, + move, + object_type, + open, + remove, + save, + schema_like, + vacuum, + walk, +) +from .libtiledb import ( + Array, + Ctx, +) +from .multirange_indexing import EmptyRange +from .object import Object +from .parquet_ import from_parquet +from .query import Query +from .query_condition import QueryCondition +from .schema_evolution import ArraySchemaEvolution +from .sparse_array import SparseArrayImpl +from .stats import ( + stats_disable, + stats_dump, + stats_enable, + stats_reset, +) +from .subarray import Subarray +from .version_helper import version +from .vfs import VFS, FileIO + +__version__ = version.version +group_create = Group.create + +# Note: we use a modified namespace packaging to allow continuity of existing TileDB-Py imports. +# Therefore, 'tiledb/__init__.py' must *only* exist in this package. +# Furthermore, in sub-packages, the `find_packages` helper will not work at the +# root directory due to lack of 'tiledb/__init__.py'. Sub-package 'setup.py' scripts +# must declare constituents accordingly, such as by running 'find_packages' on a sub-directory +# and applying prefixes accordingly. +# 1) https://packaging.python.org/guides/packaging-namespace-packages/#native-namespace-packages +# 2) https://stackoverflow.com/a/53486554 +# +# Note: 'pip -e' in particular will not work without this declaration: +__path__ = __import__("pkgutil").extend_path(__path__, __name__) + +# If tiledb.cloud is installed, add CloudArray methods to TileDB arrays +try: + from tiledb.cloud.cloudarray import CloudArray +except ImportError: + + class DenseArray(DenseArrayImpl): + pass + + class SparseArray(SparseArrayImpl): + pass + +else: + + class DenseArray(DenseArrayImpl, CloudArray): + pass + + class SparseArray(SparseArrayImpl, CloudArray): + pass + + del CloudArray diff --git a/testbed/TileDB-Inc__TileDB-Py/tiledb/aggregation.py b/testbed/TileDB-Inc__TileDB-Py/tiledb/aggregation.py new file mode 100644 index 0000000000000000000000000000000000000000..0decc0a795f37a9c5f83f601d39d33f5826f46f2 --- /dev/null +++ b/testbed/TileDB-Inc__TileDB-Py/tiledb/aggregation.py @@ -0,0 +1,91 @@ +import tiledb.cc as lt + + +class Aggregation: + """ + Proxy object returned by Query.agg to calculate aggregations. + """ + + def __init__(self, query=None, attr_to_aggs={}): + if query is None: + raise ValueError("must pass in a query object") + + self.query = query + self.attr_to_aggs = attr_to_aggs + + def __getitem__(self, selection): + from .main import PyAgg + from .subarray import Subarray + + array = self.query.array + order = self.query.order + + layout = ( + lt.LayoutType.UNORDERED if array.schema.sparse else lt.LayoutType.ROW_MAJOR + ) + if order is None or order == "C": + layout = lt.LayoutType.ROW_MAJOR + elif order == "F": + layout = lt.LayoutType.COL_MAJOR + elif order == "G": + layout = lt.LayoutType.GLOBAL_ORDER + elif order == "U": + layout = lt.LayoutType.UNORDERED + else: + raise ValueError( + "order must be 'C' (TILEDB_ROW_MAJOR), " + "'F' (TILEDB_COL_MAJOR), " + "'G' (TILEDB_GLOBAL_ORDER), " + "or 'U' (TILEDB_UNORDERED)" + ) + + q = PyAgg(array._ctx_(), array, layout, self.attr_to_aggs) + + from .libtiledb import ( + index_as_tuple, + index_domain_subarray, + replace_ellipsis, + replace_scalars_slice, + ) + + selection = index_as_tuple(selection) + dom = array.schema.domain + idx = replace_ellipsis(dom.ndim, selection) + idx, drop_axes = replace_scalars_slice(dom, idx) + dim_ranges = index_domain_subarray(array, dom, idx) + + subarray = Subarray(array, array._ctx_()) + subarray.add_ranges([list([x]) for x in dim_ranges]) + q.set_subarray(subarray) + + cond = self.query.cond + if cond is not None and cond != "": + from .query_condition import QueryCondition + + if isinstance(cond, str): + q.set_cond(QueryCondition(cond)) + else: + raise TypeError("`cond` expects type str.") + + result = q.get_aggregate() + + # If there was only one attribute, just show the aggregate results + if len(result) == 1: + result = result[list(result.keys())[0]] + + # If there was only one aggregate, just show the value + if len(result) == 1: + result = result[list(result.keys())[0]] + + return result + + @property + def multi_index(self): + """Apply Array.multi_index with query parameters.""" + from .multirange_indexing import MultiRangeAggregation + + return MultiRangeAggregation(self.query.array, query=self) + + @property + def df(self): + raise NotImplementedError(".df indexer not supported for Aggregations") diff --git a/testbed/TileDB-Inc__TileDB-Py/tiledb/array.py b/testbed/TileDB-Inc__TileDB-Py/tiledb/array.py new file mode 100644 index 0000000000000000000000000000000000000000..5c271c5e4806dfe184bff5758285a105e98a8420 --- /dev/null +++ b/testbed/TileDB-Inc__TileDB-Py/tiledb/array.py @@ -0,0 +1,245 @@ +import numpy as np + +import tiledb + +# Integer types supported by Python / System +_inttypes = (int, np.integer) + + +def _tiledb_datetime_extent(begin, end): + """ + Returns the integer extent of a datetime range. + + :param begin: beginning of datetime range + :type begin: numpy.datetime64 + :param end: end of datetime range + :type end: numpy.datetime64 + :return: Extent of range, returned as an integer number of time units + :rtype: int + """ + extent = end - begin + 1 + date_unit = np.datetime_data(extent.dtype)[0] + one = np.timedelta64(1, date_unit) + # Dividing a timedelta by 1 will convert the timedelta to an integer + return int(extent / one) + + +def index_as_tuple(idx): + """Forces scalar index objects to a tuple representation""" + if isinstance(idx, tuple): + return idx + return (idx,) + + +def replace_ellipsis(ndim: int, idx: tuple): + """ + Replace indexing ellipsis object with slice objects to match the number + of dimensions. + """ + # count number of ellipsis + n_ellip = sum(1 for i in idx if i is Ellipsis) + if n_ellip > 1: + raise IndexError("an index can only have a single ellipsis ('...')") + elif n_ellip == 1: + n = len(idx) + if (n - 1) >= ndim: + # does nothing, strip it out + idx = tuple(i for i in idx if i is not Ellipsis) + else: + # locate where the ellipse is, count the number of items to left and right + # fill in whole dim slices up to th ndim of the array + left = idx.index(Ellipsis) + right = n - (left + 1) + new_idx = idx[:left] + ((slice(None),) * (ndim - (n - 1))) + if right: + new_idx += idx[-right:] + idx = new_idx + idx_ndim = len(idx) + if idx_ndim < ndim: + idx += (slice(None),) * (ndim - idx_ndim) + if len(idx) > ndim: + raise IndexError("too many indices for array") + return idx + + +def replace_scalars_slice(dom, idx: tuple): + """Replace scalar indices with slice objects""" + new_idx, drop_axes = [], [] + for i in range(dom.ndim): + dim = dom.dim(i) + dim_idx = idx[i] + if np.isscalar(dim_idx): + drop_axes.append(i) + if isinstance(dim_idx, _inttypes): + start = int(dim_idx) + if start < 0: + start += int(dim.domain[1]) + 1 + stop = start + 1 + else: + start = dim_idx + stop = dim_idx + new_idx.append(slice(start, stop, None)) + else: + new_idx.append(dim_idx) + return tuple(new_idx), tuple(drop_axes) + + +def check_for_floats(selection): + """ + Check if a selection object contains floating point values + + :param selection: selection object + :return: True if selection contains floating point values + :rtype: bool + """ + if isinstance(selection, float): + return True + if isinstance(selection, slice): + if isinstance(selection.start, float) or isinstance(selection.stop, float): + return True + elif isinstance(selection, tuple): + for s in selection: + if check_for_floats(s): + return True + return False + + +def index_domain_subarray(array, dom, idx: tuple): + """ + Return a numpy array representation of the tiledb subarray buffer + for a given domain and tuple of index slices + """ + ndim = dom.ndim + if len(idx) != ndim: + raise IndexError( + "number of indices does not match domain rank: " + "(got {!r}, expected: {!r})".format(len(idx), ndim) + ) + + subarray = list() + for r in range(ndim): + # extract lower and upper bounds for domain dimension extent + dim = dom.dim(r) + dim_dtype = dim.dtype + + if array.mode == "r" and ( + np.issubdtype(dim_dtype, np.str_) or np.issubdtype(dim_dtype, np.bytes_) + ): + # NED can only be retrieved in read mode + ned = array.nonempty_domain() + (dim_lb, dim_ub) = ned[r] if ned else (None, None) + else: + (dim_lb, dim_ub) = dim.domain + + dim_slice = idx[r] + if not isinstance(dim_slice, slice): + raise IndexError("invalid index type: {!r}".format(type(dim_slice))) + + start, stop, step = dim_slice.start, dim_slice.stop, dim_slice.step + + if np.issubdtype(dim_dtype, np.str_) or np.issubdtype(dim_dtype, np.bytes_): + if start is None or stop is None: + if start is None: + start = dim_lb + if stop is None: + stop = dim_ub + elif not isinstance(start, (str, bytes)) or not isinstance( + stop, (str, bytes) + ): + raise tiledb.TileDBError( + f"Non-string range '({start},{stop})' provided for string dimension '{dim.name}'" + ) + subarray.append((start, stop)) + continue + + if step and array.schema.sparse: + raise IndexError("steps are not supported for sparse arrays") + + # Datetimes will be treated specially + is_datetime = dim_dtype.kind == "M" + + # Promote to a common type + if start is not None and stop is not None: + if type(start) != type(stop): + promoted_dtype = np.promote_types(type(start), type(stop)) + start = np.array(start, dtype=promoted_dtype, ndmin=1)[0] + stop = np.array(stop, dtype=promoted_dtype, ndmin=1)[0] + + if start is not None: + if is_datetime and not isinstance(start, np.datetime64): + raise IndexError( + "cannot index datetime dimension with non-datetime interval" + ) + # don't round / promote fp slices + if np.issubdtype(dim_dtype, np.integer): + if isinstance(start, (np.float32, np.float64)): + raise IndexError( + "cannot index integral domain dimension with floating point slice" + ) + elif not isinstance(start, _inttypes): + raise IndexError( + "cannot index integral domain dimension with non-integral slice (dtype: {})".format( + type(start) + ) + ) + # apply negative indexing (wrap-around semantics) + if not is_datetime and start < 0: + start += int(dim_ub) + 1 + if start < dim_lb: + # numpy allows start value < the array dimension shape, + # clamp to lower bound of dimension domain + # start = dim_lb + raise IndexError("index out of bounds ") + else: + start = dim_lb + if stop is not None: + if is_datetime and not isinstance(stop, np.datetime64): + raise IndexError( + "cannot index datetime dimension with non-datetime interval" + ) + # don't round / promote fp slices + if np.issubdtype(dim_dtype, np.integer): + if isinstance(start, (np.float32, np.float64)): + raise IndexError( + "cannot index integral domain dimension with floating point slice" + ) + elif not isinstance(start, _inttypes): + raise IndexError( + "cannot index integral domain dimension with non-integral slice (dtype: {})".format( + type(start) + ) + ) + if not is_datetime and stop < 0: + stop = np.int64(stop) + dim_ub + if stop > dim_ub: + # numpy allows stop value > than the array dimension shape, + # clamp to upper bound of dimension domain + if is_datetime: + stop = dim_ub + else: + stop = int(dim_ub) + 1 + else: + if np.issubdtype(dim_dtype, np.floating) or is_datetime: + stop = dim_ub + else: + stop = int(dim_ub) + 1 + + if np.issubdtype(type(stop), np.floating): + # inclusive bounds for floating point / datetime ranges + start = dim_dtype.type(start) + stop = dim_dtype.type(stop) + subarray.append((start, stop)) + elif is_datetime: + # need to ensure that datetime ranges are in the units of dim_dtype + # so that add_range and output shapes work correctly + start = start.astype(dim_dtype) + stop = stop.astype(dim_dtype) + subarray.append((start, stop)) + elif np.issubdtype(type(stop), np.integer): + # normal python indexing semantics + subarray.append((start, int(stop) - 1)) + else: + raise IndexError( + "domain indexing is defined for integral and floating point values" + ) + return subarray diff --git a/testbed/TileDB-Inc__TileDB-Py/tiledb/array_schema.py b/testbed/TileDB-Inc__TileDB-Py/tiledb/array_schema.py new file mode 100644 index 0000000000000000000000000000000000000000..09cf727f505b5b760ccdcf4059d058ab1b42a3a3 --- /dev/null +++ b/testbed/TileDB-Inc__TileDB-Py/tiledb/array_schema.py @@ -0,0 +1,510 @@ +import io +import numbers +import warnings +from typing import Sequence, Tuple, Union + +import numpy as np + +import tiledb.cc as lt +from tiledb.libtiledb import version as libtiledb_version + +from .attribute import Attr +from .ctx import Ctx, CtxMixin, default_ctx +from .dimension_label import DimLabel +from .domain import Domain +from .filter import Filter, FilterList + +if libtiledb_version()[0] == 2 and libtiledb_version()[1] >= 25: + from .current_domain import CurrentDomain + +_tiledb_order_to_string = { + lt.LayoutType.ROW_MAJOR: "row-major", + lt.LayoutType.COL_MAJOR: "col-major", + lt.LayoutType.GLOBAL_ORDER: "global", + lt.LayoutType.UNORDERED: "unordered", + lt.LayoutType.HILBERT: "hilbert", +} + +_string_to_tiledb_order = {v: k for k, v in _tiledb_order_to_string.items()} +_string_to_tiledb_order.update( + { + "C": lt.LayoutType.ROW_MAJOR, + "R": lt.LayoutType.COL_MAJOR, + "H": lt.LayoutType.HILBERT, + "U": lt.LayoutType.UNORDERED, + None: lt.LayoutType.ROW_MAJOR, # default (fixed in SC-27374) + } +) + + +class ArraySchema(CtxMixin, lt.ArraySchema): + """ + Schema class for TileDB dense / sparse array representations + + :param domain: Domain of schema + :param attrs: tuple of attributes + :param cell_order: TileDB label for cell layout + :param tile_order: TileDB label for tile layout + :param int capacity: tile cell capacity + :param offsets_filters: (default None) offsets filter list + :param validity_filters: (default None) validity filter list + :param bool allows_duplicates: True if duplicates are allowed + :param bool sparse: True if schema is sparse, else False \ + (set by SparseArray and DenseArray derived classes) + :param dim_labels: dict(dim_index, dict(dim_name, tiledb.DimSchema)) + :param enums: list of enumeration names + :param tiledb.Ctx ctx: A TileDB Context + :raises: :py:exc:`tiledb.TileDBError` + + """ + + def __init__( + self, + domain: Domain = None, + attrs: Sequence[Attr] = (), + cell_order: str = "row-major", + tile_order: str = "row-major", + capacity: int = 0, + coords_filters: Union[FilterList, Sequence[Filter]] = None, + offsets_filters: Union[FilterList, Sequence[Filter]] = None, + validity_filters: Union[FilterList, Sequence[Filter]] = None, + allows_duplicates: bool = False, + sparse: bool = False, + dim_labels={}, + enums=None, + ctx: Ctx = None, + ): + super().__init__(ctx, lt.ArrayType.SPARSE if sparse else lt.ArrayType.DENSE) + + if enums is not None: + for enum_name in enums: + self._add_enumeration(self._ctx, enum_name) + + if attrs is not None: + for att in attrs: + if not isinstance(att, Attr): + raise TypeError( + "Cannot create schema with non-Attr value for 'attrs' argument" + ) + self._add_attr(att) + + try: + self._cell_order = _string_to_tiledb_order.get(cell_order) + except (TypeError, ValueError): + raise ValueError(f"unknown tiledb layout: {cell_order}") + + try: + self._tile_order = _string_to_tiledb_order.get(tile_order) + except (TypeError, ValueError): + raise ValueError(f"unknown tiledb layout: {tile_order}") + + if capacity > 0: + self._capacity = capacity + + if coords_filters is not None: + warnings.warn( + "coords_filters is deprecated; set the FilterList for each dimension", + DeprecationWarning, + ) + + self._coords_filters = FilterList() + + dims_with_coords_filters = [] + for dim in domain: + dim._filters = FilterList(coords_filters) + dims_with_coords_filters.append(dim) + domain = Domain(dims_with_coords_filters) + + if domain is not None: + self._domain = domain + + if offsets_filters is not None: + self._offsets_filters = FilterList(offsets_filters) + + if validity_filters is not None: + self._validity_filters = FilterList(validity_filters) + + self._allows_dups = allows_duplicates + + for dim_index, labels_on_dim in dim_labels.items(): + for label_name, label_schema in labels_on_dim.items(): + self._add_dim_label(self._ctx, label_name, dim_index, label_schema) + + self._check() + + @classmethod + def load(cls, uri, ctx: Ctx = None, key: str = None): + if not ctx: + ctx = default_ctx() + + args = [ctx, uri] + if key is not None: + args.extend((lt.EncryptionType.AES_256_GCM, key)) + + return cls.from_pybind11(ctx, lt.ArraySchema(*args)) + + @classmethod + def from_file(cls, uri: str = None, ctx: Ctx = None): + """Create an ArraySchema for a Filestore Array from a given file. + If a uri is not given, then create a default schema.""" + schema = lt.Filestore._schema_create(ctx or default_ctx(), uri) + return cls.from_pybind11(ctx, schema) + + def __eq__(self, other): + """Instance is equal to another ArraySchema""" + if not isinstance(other, ArraySchema): + return False + if not ( + self.sparse == other.sparse + and self.cell_order == other.cell_order + and self.tile_order == other.tile_order + and self.capacity == other.capacity + and self.coords_filters == other.coords_filters + and self.offsets_filters == other.offsets_filters + and self.validity_filters == other.validity_filters + and self.nattr == other.nattr + and self.domain == other.domain + ): + return False + if self.sparse and self.allows_duplicates != other.allows_duplicates: + return False + for i in range(self.nattr): + if self.attr(i) != other.attr(i): + return False + return True + + def __len__(self): + """Returns the number of Attributes in the ArraySchema""" + return self._nattr + + def __iter__(self): + """Returns a generator object that iterates over the ArraySchema's Attribute objects""" + return (self.attr(i) for i in range(self.nattr)) + + @property + def ctx(self) -> Ctx: + """The array schema's context + + :rtype: tiledb.Ctx + """ + return self._ctx + + def check(self) -> bool: + """Checks the correctness of the array schema + + :rtype: None + :raises: :py:exc:`tiledb.TileDBError` if invalid + """ + return self._check() + + @property + def sparse(self) -> bool: + """True if the array is a sparse array representation + + :rtype: bool + :raises: :py:exc:`tiledb.TileDBError` + + """ + return self._array_type == lt.ArrayType.SPARSE + + @property + def allows_duplicates(self) -> bool: + """Returns True if the (sparse) array allows duplicates.""" + + if not self.sparse: + raise lt.TileDBError( + "ArraySchema.allows_duplicates does not apply to dense arrays" + ) + + return self._allows_dups + + @property + def capacity(self) -> int: + """The array capacity + + :rtype: int + :raises: :py:exc:`tiledb.TileDBError` + + """ + return self._capacity + + @property + def cell_order(self) -> str: + """The cell order layout of the array. + + :rtype: str + """ + return _tiledb_order_to_string[self._cell_order] + + @property + def tile_order(self) -> str: + """The tile order layout of the array. + + :rtype: str + :raises: :py:exc:`tiledb.TileDBError` + + """ + layout_string = _tiledb_order_to_string[self._tile_order] + return layout_string if self.cell_order != "hilbert" else None + + @property + def offsets_filters(self) -> FilterList: + """The FilterList for the array's variable-length attribute offsets + + :rtype: tiledb.FilterList + :raises: :py:exc:`tiledb.TileDBError` + """ + return FilterList.from_pybind11(self._ctx, self._offsets_filters) + + @property + def coords_filters(self) -> FilterList: + """The FilterList for the array's coordinates + + :rtype: tiledb.FilterList + :raises: :py:exc:`tiledb.TileDBError` + """ + return FilterList.from_pybind11(self._ctx, self._coords_filters) + + @coords_filters.setter + def coords_filters(self, value): + warnings.warn( + "coords_filters is deprecated; set the FilterList for each dimension", + DeprecationWarning, + ) + + @property + def validity_filters(self) -> FilterList: + """The FilterList for the array's validity + + :rtype: tiledb.FilterList + :raises: :py:exc:`tiledb.TileDBError` + """ + return FilterList.from_pybind11(self._ctx, self._validity_filters) + + @property + def domain(self) -> Domain: + """The Domain associated with the array. + + :rtype: tiledb.Domain + :raises: :py:exc:`tiledb.TileDBError` + + """ + return Domain.from_pybind11(self._ctx, self._domain) + + @property + def nattr(self) -> int: + """The number of array attributes. + + :rtype: int + :raises: :py:exc:`tiledb.TileDBError` + + """ + return self._nattr + + @property + def ndim(self) -> int: + """The number of array domain dimensions. + + :rtype: int + """ + return self.domain.ndim + + @property + def shape(self) -> Tuple[np.dtype, np.dtype]: + """The array's shape + + :rtype: tuple(numpy scalar, numpy scalar) + :raises TypeError: floating point (inexact) domain + """ + return self.domain.shape + + @property + def version(self) -> int: + """The array's schema (storage) version. + + :rtype: int + :raises: :py:exc:`tiledb.TileDBError` + """ + return self._version + + def _needs_var_buffer(self, name: str) -> bool: + """ + Returns true if the given attribute or dimension is var-sized + :param name: + :rtype: bool + """ + if self.has_attr(name): + return self.attr(name).isvar + elif self.domain.has_dim(name): + return self.domain.dim(name).isvar + else: + raise ValueError( + f"Requested name '{name}' is not an attribute or dimension" + ) + + def attr(self, key: Union[str, int]) -> Attr: + """Returns an Attr instance given an int index or string label + + :param key: attribute index (positional or associative) + :type key: int or str + :rtype: tiledb.Attr + :return: The ArraySchema attribute at index or with the given name (label) + :raises TypeError: invalid key type + + """ + if isinstance(key, str): + return Attr.from_pybind11(self._ctx, self._attr(key)) + elif isinstance(key, numbers.Integral): + return Attr.from_pybind11(self._ctx, self._attr(int(key))) + raise TypeError( + "attr indices must be a string name, " + "or an integer index, not {0!r}".format(type(key)) + ) + + def dim_label(self, name: str) -> DimLabel: + """Returns a TileDB DimensionLabel given the label name + + :param name: name of the dimensin label + :return: The dimension label associated with the given name + """ + return DimLabel.from_pybind11(self._ctx, self._dim_label(self._ctx, name)) + + def has_attr(self, name: str) -> bool: + """Returns true if the given name is an Attribute of the ArraySchema + + :param name: attribute name + :rtype: boolean + """ + return self._has_attribute(name) + + def has_dim_label(self, name: str) -> bool: + """Returns true if the given name is a DimensionLabel of the ArraySchema + + Note: If using an version of libtiledb that does not support dimension labels + this will return false. + + :param name: dimension label name + :rtype: boolean + """ + return self._has_dim_label(self._ctx, name) + + if libtiledb_version()[0] == 2 and libtiledb_version()[1] >= 25: + + @property + def current_domain(self) -> CurrentDomain: + """Get the current domain + + :rtype: tiledb.CurrentDomain + """ + curr_dom = CurrentDomain.from_pybind11( + self._ctx, self._current_domain(self._ctx) + ) + curr_dom._set_domain(self.domain) + return curr_dom + + def set_current_domain(self, current_domain): + """Set the current domain + + :param current_domain: The current domain to set + :type current_domain: tiledb.CurrentDomain + """ + self._set_current_domain(self._ctx, current_domain) + + def attr_or_dim_dtype(self, name: str) -> bool: + if self.has_attr(name): + dtype = self.attr(name).dtype + elif self.domain.has_dim(name): + dtype = self.domain.dim(name).dtype + else: + raise lt.TileDBError(f"Unknown attribute or dimension ('{name}')") + + if dtype.itemsize == 0: + # special handling for flexible numpy dtypes: change itemsize from 0 to 1 + dtype = np.dtype((dtype, 1)) + return dtype + + def dump(self): + """Dumps a string representation of the array object to standard output (stdout)""" + print(self._dump(), "\n") + + def __repr__(self): + # use safe repr if pybind11 constructor failed or the array schema did + # not construct properly + try: + self._check() + except lt.TileDBError: + return object.__repr__(self) + + if self._ctx is None: + return object.__repr__(self) + + # TODO support/use __qualname__ + output = io.StringIO() + output.write("ArraySchema(\n") + output.write(" domain=Domain(*[\n") + for i in range(self.domain.ndim): + output.write(f" {repr(self.domain.dim(i))},\n") + output.write(" ]),\n") + output.write(" attrs=[\n") + for i in range(self.nattr): + output.write(f" {repr(self.attr(i))},\n") + output.write(" ],\n") + output.write( + f" cell_order='{self.cell_order}',\n" + f" tile_order={repr(self.tile_order)},\n" + ) + if self.sparse: + output.write(f" capacity={self.capacity},\n") + output.write(f" sparse={self.sparse},\n") + if self.sparse: + output.write(f" allows_duplicates={self.allows_duplicates},\n") + + output.write(")\n") + + return output.getvalue() + + def _repr_html_(self): + output = io.StringIO() + + output.write("") + + output.write("") + output.write(f"") + + output.write("") + output.write("") + output.write("") + output.write("") + + output.write("") + output.write(f"") + + output.write("") + output.write(f"") + + if self.sparse: + output.write("") + output.write(f"") + + output.write("") + output.write(f"") + + if self.sparse: + output.write("") + output.write(f"") + + output.write("
Domain
{self.domain._repr_html_()}
Attributes
") + output.write("") + output.write("") + output.write("") + output.write("") + output.write("") + output.write("") + output.write("") + output.write("") + for i in range(self.nattr): + output.write(f"{self.attr(i)._repr_html_row_only_()}") + output.write("
NameData TypeIs Var-LenIs NullableFilters
") + output.write("
Cell Order
{self.cell_order}
Tile Order
{self.tile_order}
Capacity
{self.capacity}
Sparse
{self.sparse}
Allows DuplicatesK/th>
{self.allows_duplicates}
") + + return output.getvalue() diff --git a/testbed/TileDB-Inc__TileDB-Py/tiledb/attribute.py b/testbed/TileDB-Inc__TileDB-Py/tiledb/attribute.py new file mode 100644 index 0000000000000000000000000000000000000000..0e723fe0c0acdfe642e1e472d5cec02c0d47a182 --- /dev/null +++ b/testbed/TileDB-Inc__TileDB-Py/tiledb/attribute.py @@ -0,0 +1,329 @@ +import io +import warnings +from typing import Any, Optional, Sequence, Union + +import numpy as np + +import tiledb.cc as lt + +from .ctx import Ctx, CtxMixin +from .datatypes import DataType +from .filter import Filter, FilterList + + +class Attr(CtxMixin, lt.Attribute): + """ + Represents a TileDB attribute. + """ + + def __init__( + self, + name: str = "", + dtype: np.dtype = np.float64, + fill: Any = None, + var: bool = None, + nullable: bool = False, + filters: Union[FilterList, Sequence[Filter]] = None, + enum_label: str = None, + ctx: Optional[Ctx] = None, + ): + """Class representing a TileDB array attribute. + + :param name: Attribute name, empty if anonymous + :param dtype: Attribute value datatype + :param fill: Fill value for unset cells + :param var: Attribute is variable-length (automatic for byte/string types) + :param nullable: Attribute is nullable + :param filters: List of filters to apply + :param ctx: A TileDB Context + :raises TypeError: invalid dtype + :raises tiledb.TileDBError: + """ + dt = DataType.from_numpy( + np.dtype(dtype) if dtype not in ("ascii", "blob", "wkb", "wkt") else dtype + ) + + # ensure that all strings are var-length + if (var is None and dtype == "ascii") or np.issubdtype(dt.np_dtype, np.str_): + var = True + elif np.issubdtype(dt.np_dtype, np.bytes_): + if dt.np_dtype.itemsize > 0 and var: + warnings.warn( + f"Attr given `var=True` but `dtype` `{dtype}` is fixed; " + "setting `dtype=S0`. Hint: set `var=True` with `dtype=S0`, " + f"or `var=False`with `dtype={dtype}`", + DeprecationWarning, + ) + elif dt.np_dtype.itemsize == 0 and dtype != "ascii": + if var is False: + warnings.warn( + "Attr given `var=False` but `dtype` `S0` is var-length; " + "setting `var=True` and `dtype=S0`. Hint: set `var=False` " + "with `dtype=S0`, or `var=False` with a fixed-width " + "string `dtype=S` where is n>1", + DeprecationWarning, + ) + var = True + + super().__init__(ctx, name, dt.tiledb_type) + + if var: + self._ncell = lt.TILEDB_VAR_NUM() + elif dt.ncells != lt.TILEDB_VAR_NUM(): + self._ncell = dt.ncells + else: + raise TypeError("dtype is not compatible with var-length attribute") + + if filters is not None: + if isinstance(filters, FilterList): + self._filters = filters + else: + self._filters = FilterList(filters) + + if fill is not None: + if self._tiledb_dtype == lt.DataType.STRING_UTF8: + self._fill = np.array([fill.encode("utf-8")], dtype="S") + elif self.dtype == np.dtype("complex64") or self.dtype == np.dtype( + "complex128" + ): + if hasattr(fill, "dtype") and fill.dtype in { + np.dtype("f4, f4"), + np.dtype("f8, f8"), + }: + _fill = fill["f0"] + fill["f1"] * 1j + elif hasattr(fill, "__len__") and len(fill) == 2: + _fill = fill[0] + fill[1] * 1j + else: + _fill = fill + self._fill = np.array(_fill, dtype=self.dtype) + else: + self._fill = np.array([fill], dtype=self.dtype) + + if nullable is not None: + self._nullable = nullable + + if enum_label is not None: + self._set_enumeration_name(self._ctx, enum_label) + + def __eq__(self, other): + if not isinstance(other, Attr): + return False + if self.isnullable != other.isnullable or self.dtype != other.dtype: + return False + if not self.isnullable: + # Check the fill values are equal. + def equal_or_nan(x, y): + return x == y or (np.isnan(x) and np.isnan(y)) + + if self.ncells == 1: + if not equal_or_nan(self.fill, other.fill): + return False + elif np.issubdtype(self.dtype, np.bytes_) or np.issubdtype( + self.dtype, np.str_ + ): + if self.fill != other.fill: + return False + elif self.dtype in {np.dtype("complex64"), np.dtype("complex128")}: + if not ( + equal_or_nan(np.real(self.fill), np.real(other.fill)) + and equal_or_nan(np.imag(self.fill), np.imag(other.fill)) + ): + return False + else: + if not all( + equal_or_nan(x, y) + or ( + isinstance(x, str) + and x.lower() == "nat" + and isinstance(y, str) + and y.lower() == "nat" + ) + for x, y in zip(self.fill[0], other.fill[0]) + ): + return False + return ( + self._internal_name == other._internal_name + and self.isvar == other.isvar + and self.filters == other.filters + ) + + def dump(self): + """Dumps a string representation of the Attr object to standard output (stdout)""" + print(self._dump(), "\n") + + @property + def dtype(self) -> np.dtype: + """Return numpy dtype object representing the Attr type + + :rtype: numpy.dtype + + """ + return DataType.from_tiledb(self._tiledb_dtype, self._ncell).np_dtype + + @property + def name(self) -> str: + """Attribute string name, empty string if the attribute is anonymous + + :rtype: str + :raises: :py:exc:`tiledb.TileDBError` + + """ + internal_name = self._name + # handle __attr names from arrays written with libtiledb < 2 + if internal_name == "__attr": + return "" + return internal_name + + @property + def _internal_name(self): + return self._name + + @property + def isanon(self) -> bool: + """True if attribute is an anonymous attribute + + :rtype: bool + + """ + return self._name == "" or self._name.startswith("__attr") + + @property + def filters(self) -> FilterList: + """FilterList of the TileDB attribute + + :rtype: tiledb.FilterList + :raises: :py:exc:`tiledb.TileDBError` + + """ + return FilterList.from_pybind11(self._ctx, self._filters) + + @property + def fill(self) -> Any: + """Fill value for unset cells of this attribute + + :rtype: depends on dtype + :raises: :py:exc:`tiledb.TileDBERror` + """ + dtype = self.dtype + if np.issubdtype(dtype, np.bytes_): + return self._fill.tobytes() + if np.issubdtype(dtype, np.str_): + return self._fill.tobytes().decode("utf-8") + if np.issubdtype(dtype, np.datetime64): + return self._fill[0].astype(np.timedelta64) + return self._fill + + @property + def isnullable(self) -> bool: + """True if the attribute is nullable + + :rtype: bool + :raises: :py:exc:`tiledb.TileDBError` + + """ + return self._nullable + + @property + def isvar(self) -> bool: + """True if the attribute is variable length + + :rtype: bool + :raises: :py:exc:`tiledb.TileDBError` + + """ + return self._var + + @property + def ncells(self) -> int: + """The number of cells (scalar values) for a given attribute value + + :rtype: int + :raises: :py:exc:`tiledb.TileDBError` + + """ + assert self._ncell != 0 + return int(self._ncell) + + @property + def isascii(self) -> bool: + """True if the attribute is TileDB dtype TILEDB_STRING_ASCII + + :rtype: bool + :raises: :py:exc:`tiledb.TileDBError` + + """ + return self._tiledb_dtype == lt.DataType.STRING_ASCII + + @property + def enum_label(self): + return self._get_enumeration_name(self._ctx) + + def __repr__(self): + # use safe repr if pybind11 constructor failed + if self._ctx is None: + return object.__repr__(self) + + filters_str = "" + if self.filters: + filters_str = ", filters=FilterList([" + for f in self.filters: + filters_str += repr(f) + ", " + filters_str += "])" + + if self._tiledb_dtype == lt.DataType.STRING_ASCII: + attr_dtype = "ascii" + elif self._tiledb_dtype == lt.DataType.BLOB: + attr_dtype = "blob" + elif ( + hasattr(lt.DataType, "GEOM_WKB") + and self._tiledb_dtype == lt.DataType.GEOM_WKB + ): + attr_dtype = "wkb" + elif ( + hasattr(lt.DataType, "GEOM_WKT") + and self._tiledb_dtype == lt.DataType.GEOM_WKT + ): + attr_dtype = "wkt" + else: + attr_dtype = self.dtype + + if self.enum_label is None: + enum_label = None + else: + enum_label = f"'{self.enum_label!s}'" + + # filters_str must be last with no spaces + return ( + f"""Attr(name={repr(self.name)}, dtype='{attr_dtype!s}', """ + f"""var={self.isvar!s}, nullable={self.isnullable!s}, """ + f"""enum_label={enum_label}{filters_str})""" + ) + + def _repr_html_(self): + output = io.StringIO() + + output.write("") + output.write("") + output.write("") + output.write("") + output.write("") + output.write("") + output.write("") + output.write("") + output.write(f"{self._repr_html_row_only_()}") + output.write("
NameData TypeIs Var-LenIs NullableFilters
") + + return output.getvalue() + + def _repr_html_row_only_(self): + output = io.StringIO() + + output.write("") + output.write(f"{self.name}") + output.write(f"{'ascii' if self.isascii else self.dtype}") + output.write(f"{self.isvar}") + output.write(f"{self.isnullable}") + output.write(f"{self.filters._repr_html_()}") + output.write("") + + return output.getvalue() diff --git a/testbed/TileDB-Inc__TileDB-Py/tiledb/cc/CMakeLists.txt b/testbed/TileDB-Inc__TileDB-Py/tiledb/cc/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..ced8acaf944685f9bcfff62d2714e597accd8d72 --- /dev/null +++ b/testbed/TileDB-Inc__TileDB-Py/tiledb/cc/CMakeLists.txt @@ -0,0 +1,67 @@ +pybind11_add_module( + cc + array.cc + attribute.cc + common.cc + common.h + consolidation_plan.cc + context.cc + current_domain.cc + dimension_label.cc + domain.cc + enum.cc + enumeration.cc + filestore.cc + filter.cc + group.cc + object.cc + query.cc + schema.cc + subarray.cc + tiledbcpp.cc + vfs.cc +) + +target_link_libraries( + cc + PUBLIC + TileDB::tiledb_shared +) + +target_compile_features( + cc + PUBLIC + cxx_std_20 +) + +if (TILEDB_REMOVE_DEPRECATIONS) + target_compile_definitions( + cc + PRIVATE + TILEDB_REMOVE_DEPRECATIONS + ) +endif() + +if (TILEDB_SERIALIZATION) + target_compile_definitions( + cc + PRIVATE + TILEDB_SERIALIZATION + ) +endif() + +install(TARGETS cc DESTINATION tiledb) + +if(TILEDB_DOWNLOADED) + if (APPLE) + set_target_properties(cc PROPERTIES INSTALL_RPATH "@loader_path") + elseif(UNIX) + set_target_properties(cc PROPERTIES INSTALL_RPATH "\$ORIGIN") + endif() +else() + # If using external TileDB core library force it to be linked at runtime using RPATH + get_property(TILEDB_LOCATION TARGET TileDB::tiledb_shared PROPERTY LOCATION) + get_filename_component(TILEDB_LOCATION ${TILEDB_LOCATION} DIRECTORY) + message(STATUS "Setting RPATH for target \"cc\" to ${TILEDB_LOCATION}") + set_target_properties(cc PROPERTIES INSTALL_RPATH ${TILEDB_LOCATION}) +endif() diff --git a/testbed/TileDB-Inc__TileDB-Py/tiledb/cc/array.cc b/testbed/TileDB-Inc__TileDB-Py/tiledb/cc/array.cc new file mode 100644 index 0000000000000000000000000000000000000000..89d51cb0e324d85a5c3824f9b58f226133f1fd5e --- /dev/null +++ b/testbed/TileDB-Inc__TileDB-Py/tiledb/cc/array.cc @@ -0,0 +1,192 @@ +#include // for enums +#include // C++ + +#include "common.h" + +#include +#include +#include +#include + +namespace libtiledbcpp { + +using namespace tiledb; +namespace py = pybind11; + +void init_array(py::module &m) { + py::class_(m, "Array") + //.def(py::init()) + .def( + py::init(), + py::keep_alive<1, 2>() /* Array keeps Context alive */) + + // Temporary initializer while Array is converted from Cython to PyBind. + .def(py::init([](const Context &ctx, py::object array) { + tiledb_array_t *c_array = (py::capsule)array.attr("__capsule__")(); + return std::make_unique(ctx, c_array, false); + }), + py::keep_alive<1, 2>(), py::keep_alive<1, 3>()) + + // TODO capsule Array(const Context& ctx, tiledb_array_t* carray, + // tiledb_config_t* config) + .def("is_open", &Array::is_open) + .def("uri", &Array::uri) + .def("schema", &Array::schema) + //.def("ptr", [](Array& arr){ return py::capsule(arr.ptr()); } ) + .def("open", (void(Array::*)(tiledb_query_type_t)) & Array::open) + .def("reopen", &Array::reopen) + .def("set_open_timestamp_start", &Array::set_open_timestamp_start) + .def("set_open_timestamp_end", &Array::set_open_timestamp_end) + .def_property_readonly("open_timestamp_start", + &Array::open_timestamp_start) + .def_property_readonly("open_timestamp_end", &Array::open_timestamp_end) + .def("set_config", &Array::set_config) + .def("config", &Array::config) + .def("close", &Array::close) + .def("consolidate", + [](Array &self, const Context &ctx, Config *config) { + if (self.query_type() == TILEDB_READ) { + throw TileDBError("cannot consolidate array opened in readonly " + "mode (mode='r')"); + } + Array::consolidate(ctx, self.uri(), config); + }) + .def("consolidate", + [](Array &self, const Context &ctx, + const std::vector &fragment_uris, Config *config) { + if (self.query_type() == TILEDB_READ) { + throw TileDBError("cannot consolidate array opened in readonly " + "mode (mode='r')"); + } + std::vector c_strings; + c_strings.reserve(fragment_uris.size()); + for (const auto &str : fragment_uris) { + c_strings.push_back(str.c_str()); + } + + Array::consolidate(ctx, self.uri(), c_strings.data(), + fragment_uris.size(), config); + }) + .def("consolidate", + [](Array &self, const Context &ctx, + const std::tuple ×tamp, Config *config) { + if (self.query_type() == TILEDB_READ) { + throw TileDBError("cannot consolidate array opened in readonly " + "mode (mode='r')"); + } + int start, end; + std::tie(start, end) = timestamp; + + config->set("sm.consolidation.timestamp_start", + std::to_string(start)); + config->set("sm.consolidation.timestamp_end", std::to_string(end)); + + Array::consolidate(ctx, self.uri(), config); + }) + .def("vacuum", &Array::vacuum) + .def("create", + py::overload_cast( + &Array::create)) + .def("load_schema", + py::overload_cast( + &Array::load_schema)) + .def("encryption_type", &Array::encryption_type) + + // TODO non_empty_domain + // TODO non_empty_domain_var + + .def("query_type", &Array::query_type) + .def("consolidate_fragments", + [](Array &self, const Context &ctx, + const std::vector &fragment_uris, Config *config) { + std::vector c_strings; + c_strings.reserve(fragment_uris.size()); + for (const auto &str : fragment_uris) { + c_strings.push_back(str.c_str()); + } + ctx.handle_error(tiledb_array_consolidate_fragments( + ctx.ptr().get(), self.uri().c_str(), c_strings.data(), + fragment_uris.size(), config->ptr().get())); + }) + .def("consolidate_metadata", + py::overload_cast(&Array::consolidate_metadata)) + .def("put_metadata", + [](Array &self, std::string &key, tiledb_datatype_t tdb_type, + const py::buffer &b) { + py::buffer_info info = b.request(); + + // size_t size = std::reduce(info.shape.begin(), + // info.shape.end()); + size_t size = 1; + for (auto s : info.shape) { + size *= s; + } + // size_t nbytes = size * info.itemsize; + + self.put_metadata(key, tdb_type, size, info.ptr); + /* + std::cout << "ndim: " << info.ndim << std::endl; + + + std::cout << "sz: " << size << std::endl; + std::cout << "imsz: " << info.itemsize << std::endl; + + std::cout << "--|" << std::endl; + for (auto& s : info.shape) { + std::cout << s << std::endl; + } + */ + }) + .def("get_metadata", + [](Array &self, std::string &key) -> py::buffer { + tiledb_datatype_t tdb_type; + uint32_t value_num = 0; + const void *data_ptr = nullptr; + + self.get_metadata(key, &tdb_type, &value_num, &data_ptr); + + if (data_ptr == nullptr && value_num != 1) { + throw py::key_error(); + } + + assert(data_ptr != nullptr); + return py::memoryview::from_memory( + data_ptr, value_num * tiledb_datatype_size(tdb_type)); + }) + .def("get_metadata_from_index", + [](Array &self, uint64_t index) -> py::tuple { + tiledb_datatype_t tdb_type; + uint32_t value_num = 0; + const void *data_ptr = nullptr; + std::string key; + + self.get_metadata_from_index(index, &key, &tdb_type, &value_num, + &data_ptr); + + if (data_ptr == nullptr && value_num != 1) { + throw py::key_error(); + } + // TODO handle empty value case + + assert(data_ptr != nullptr); + auto buf = py::memoryview::from_memory( + data_ptr, value_num * tiledb_datatype_size(tdb_type)); + + return py::make_tuple(tdb_type, buf); + }) + .def("delete_metadata", &Array::delete_metadata) + .def("has_metadata", + [](Array &self, std::string &key) -> py::tuple { + tiledb_datatype_t has_type; + bool has_it = self.has_metadata(key, &has_type); + return py::make_tuple(has_it, has_type); + }) + .def("metadata_num", &Array::metadata_num) + .def("delete_array", + py::overload_cast( + &Array::delete_array)); +} + +} // namespace libtiledbcpp diff --git a/testbed/TileDB-Inc__TileDB-Py/tiledb/cc/attribute.cc b/testbed/TileDB-Inc__TileDB-Py/tiledb/cc/attribute.cc new file mode 100644 index 0000000000000000000000000000000000000000..b06d5c4fc15f27fa36ef450afef760874756c8de --- /dev/null +++ b/testbed/TileDB-Inc__TileDB-Py/tiledb/cc/attribute.cc @@ -0,0 +1,121 @@ +#include +#include + +#include +#include +#include +#include + +#include "common.h" + +namespace libtiledbcpp { + +using namespace tiledb; +using namespace tiledbpy::common; +namespace py = pybind11; + +void set_fill_value(Attribute &attr, py::array value) { + attr.set_fill_value(value.data(), value.nbytes()); +} + +py::array get_fill_value(Attribute &attr) { + // Get the fill value from the C++ API as a void* value. + const void *value; + uint64_t size; + attr.get_fill_value(&value, &size); + + // If this is a string type, we want to return each value as a single cell. + if (is_tdb_str(attr.type())) { + auto value_type = py::dtype("|S1"); + return py::array(value_type, size, value); + } + + // If this is a record type (void), return a single cell. + // If this is a blob-like type, we want to return each value as a single byte + // cell. + auto tdb_type = attr.type(); + if (tdb_type == TILEDB_BLOB +#if TILEDB_VERSION_MAJOR >= 2 && TILEDB_VERSION_MINOR >= 21 + || tdb_type == TILEDB_GEOM_WKB || tdb_type == TILEDB_GEOM_WKT +#endif + ) { + auto value_type = py::dtype("S"); + return py::array(value_type, size, value); + } + + // Get the number of values in a cell and the Python datatype. + auto value_num = attr.cell_val_num(); + auto value_type = tdb_to_np_dtype(attr.type(), value_num); + + if (py::getattr(value_type, "kind").is(py::str("V"))) { + return py::array(value_type, 1, value); + } + + // If this is a complex type both cell values fit in a single complex element. + if (value_type.is(py::dtype("complex64")) || + value_type.is(py::dtype("complex128"))) { + return py::array(value_type, 1, value); + } + + return py::array(value_type, value_num, value); +} + +void set_enumeration_name(Attribute &attr, const Context &ctx, + const std::string &enumeration_name) { + AttributeExperimental::set_enumeration_name(ctx, attr, enumeration_name); +} + +std::optional get_enumeration_name(Attribute &attr, + const Context &ctx) { + return AttributeExperimental::get_enumeration_name(ctx, attr); +} + +void init_attribute(py::module &m) { + py::class_(m, "Attribute") + .def(py::init()) + + .def(py::init()) + + .def( + py::init()) + + .def(py::init()) + + .def( + "__capsule__", + [](Attribute &attr) { return py::capsule(attr.ptr().get(), "attr"); }) + + .def_property_readonly("_name", &Attribute::name) + + .def_property_readonly("_tiledb_dtype", &Attribute::type) + + .def_property("_nullable", &Attribute::nullable, &Attribute::set_nullable) + + .def_property("_ncell", &Attribute::cell_val_num, + &Attribute::set_cell_val_num) + + .def_property_readonly("_var", &Attribute::variable_sized) + + .def_property("_filters", &Attribute::filter_list, + &Attribute::set_filter_list) + + .def_property_readonly("_cell_size", &Attribute::cell_size) + + .def_property("_fill", get_fill_value, set_fill_value) + + .def("_get_enumeration_name", get_enumeration_name) + + .def("_set_enumeration_name", set_enumeration_name) + + .def("_dump", [](Attribute &attr) { +#if TILEDB_VERSION_MAJOR >= 2 && TILEDB_VERSION_MINOR >= 26 + std::stringstream ss; + ss << attr; + return ss.str(); +#else + attr.dump(); +#endif + }); +} + +} // namespace libtiledbcpp diff --git a/testbed/TileDB-Inc__TileDB-Py/tiledb/cc/common.cc b/testbed/TileDB-Inc__TileDB-Py/tiledb/cc/common.cc new file mode 100644 index 0000000000000000000000000000000000000000..7015cebcec64a445d1b52c5e1ae73ad684133507 --- /dev/null +++ b/testbed/TileDB-Inc__TileDB-Py/tiledb/cc/common.cc @@ -0,0 +1,230 @@ +#include "common.h" + +#include + +std::unordered_map _tdb_to_np_name_dtype = { + {TILEDB_INT32, "int32"}, + {TILEDB_INT64, "int64"}, + {TILEDB_FLOAT32, "float32"}, + {TILEDB_FLOAT64, "float64"}, + {TILEDB_INT8, "int8"}, + {TILEDB_UINT8, "uint8"}, + {TILEDB_INT16, "int16"}, + {TILEDB_UINT16, "uint16"}, + {TILEDB_UINT32, "uint32"}, + {TILEDB_UINT64, "uint64"}, + {TILEDB_STRING_ASCII, "S"}, + {TILEDB_STRING_UTF8, "U1"}, + {TILEDB_CHAR, "S1"}, + {TILEDB_DATETIME_YEAR, "M8[Y]"}, + {TILEDB_DATETIME_MONTH, "M8[M]"}, + {TILEDB_DATETIME_WEEK, "M8[W]"}, + {TILEDB_DATETIME_DAY, "M8[D]"}, + {TILEDB_DATETIME_HR, "M8[h]"}, + {TILEDB_DATETIME_MIN, "M8[m]"}, + {TILEDB_DATETIME_SEC, "M8[s]"}, + {TILEDB_DATETIME_MS, "M8[ms]"}, + {TILEDB_DATETIME_US, "M8[us]"}, + {TILEDB_DATETIME_NS, "M8[ns]"}, + {TILEDB_DATETIME_PS, "M8[ps]"}, + {TILEDB_DATETIME_FS, "M8[fs]"}, + {TILEDB_DATETIME_AS, "M8[as]"}, + /* duration types map to timedelta */ + {TILEDB_TIME_HR, "m8[h]"}, + {TILEDB_TIME_MIN, "m8[m]"}, + {TILEDB_TIME_SEC, "m8[s]"}, + {TILEDB_TIME_MS, "m8[ms]"}, + {TILEDB_TIME_US, "m8[us]"}, + {TILEDB_TIME_NS, "m8[ns]"}, + {TILEDB_TIME_PS, "m8[ps]"}, + {TILEDB_TIME_FS, "m8[fs]"}, + {TILEDB_TIME_AS, "m8[as]"}, + {TILEDB_BLOB, "byte"}, + {TILEDB_BOOL, "bool"}, +#if TILEDB_VERSION_MAJOR >= 2 && TILEDB_VERSION_MINOR >= 21 + {TILEDB_GEOM_WKB, "byte"}, + {TILEDB_GEOM_WKT, "S"}, +#endif +}; + +std::unordered_map _np_name_to_tdb_dtype = { + {"int32", TILEDB_INT32}, + {"int64", TILEDB_INT64}, + {"float32", TILEDB_FLOAT32}, + {"float64", TILEDB_FLOAT64}, + {"int8", TILEDB_INT8}, + {"uint8", TILEDB_UINT8}, + {"int16", TILEDB_INT16}, + {"uint16", TILEDB_UINT16}, + {"uint32", TILEDB_UINT32}, + {"uint64", TILEDB_UINT64}, + {"datetime64[Y]", TILEDB_DATETIME_YEAR}, + {"datetime64[M]", TILEDB_DATETIME_MONTH}, + {"datetime64[W]", TILEDB_DATETIME_WEEK}, + {"datetime64[D]", TILEDB_DATETIME_DAY}, + {"datetime64[h]", TILEDB_DATETIME_HR}, + {"datetime64[m]", TILEDB_DATETIME_MIN}, + {"datetime64[s]", TILEDB_DATETIME_SEC}, + {"datetime64[ms]", TILEDB_DATETIME_MS}, + {"datetime64[us]", TILEDB_DATETIME_US}, + {"datetime64[ns]", TILEDB_DATETIME_NS}, + {"datetime64[ps]", TILEDB_DATETIME_PS}, + {"datetime64[fs]", TILEDB_DATETIME_FS}, + {"datetime64[as]", TILEDB_DATETIME_AS}, + /* duration types map to timedelta */ + {"timedelta64[h]", TILEDB_TIME_HR}, + {"timedelta64[m]", TILEDB_TIME_MIN}, + {"timedelta64[s]", TILEDB_TIME_SEC}, + {"timedelta64[ms]", TILEDB_TIME_MS}, + {"timedelta64[us]", TILEDB_TIME_US}, + {"timedelta64[ns]", TILEDB_TIME_NS}, + {"timedelta64[ps]", TILEDB_TIME_PS}, + {"timedelta64[fs]", TILEDB_TIME_FS}, + {"timedelta64[as]", TILEDB_TIME_AS}, + {"bool", TILEDB_BOOL}, +}; + +namespace tiledbpy::common { + +size_t buffer_nbytes(py::buffer_info &info) { + return info.itemsize * std::accumulate(info.shape.begin(), info.shape.end(), + 1, std::multiplies<>()); +} + +bool expect_buffer_nbytes(py::buffer_info &info, tiledb_datatype_t datatype, + size_t nelem) { + size_t nbytes = buffer_nbytes(info); + size_t nbytes_expected = tiledb_datatype_size(datatype) * nelem; + return nbytes == nbytes_expected; +} + +} // namespace tiledbpy::common + +py::dtype tdb_to_np_dtype(tiledb_datatype_t type, uint32_t cell_val_num) { + if (type == TILEDB_CHAR || type == TILEDB_STRING_UTF8 || + type == TILEDB_STRING_ASCII) { + std::string base_str = (type == TILEDB_STRING_UTF8) ? "|U" : "|S"; + if (cell_val_num < TILEDB_VAR_NUM) + base_str += std::to_string(cell_val_num); + return py::dtype(base_str); + } + + if (cell_val_num == 1) { + if (type == TILEDB_STRING_UTF16 || type == TILEDB_STRING_UTF32) + TPY_ERROR_LOC("Unimplemented UTF16 or UTF32 string conversion!"); + if (type == TILEDB_STRING_UCS2 || type == TILEDB_STRING_UCS4) + TPY_ERROR_LOC("Unimplemented UCS2 or UCS4 string conversion!"); + + if (_tdb_to_np_name_dtype.count(type) == 1) + return py::dtype(_tdb_to_np_name_dtype[type]); + } + + if (cell_val_num == 2) { + if (type == TILEDB_FLOAT32) + return py::dtype("complex64"); + if (type == TILEDB_FLOAT64) + return py::dtype("complex128"); + } + + if (cell_val_num == TILEDB_VAR_NUM) + return tdb_to_np_dtype(type, 1); + + if (cell_val_num > 1) { + py::dtype base_dtype = tdb_to_np_dtype(type, 1); + py::tuple rec_elem = py::make_tuple("", base_dtype); + py::list rec_list; + for (size_t i = 0; i < cell_val_num; i++) + rec_list.append(rec_elem); + // note: we call the 'dtype' constructor b/c py::dtype does not accept + // list + auto np = py::module::import("numpy"); + auto np_dtype = np.attr("dtype"); + return np_dtype(rec_list); + } + + TPY_ERROR_LOC("tiledb datatype not understood ('" + + tiledb::impl::type_to_str(type) + + "', cell_val_num: " + std::to_string(cell_val_num) + ")"); +} + +tiledb_datatype_t np_to_tdb_dtype(py::dtype type) { + auto name = py::str(py::getattr(type, "name")); + if (_np_name_to_tdb_dtype.count(name) == 1) + return _np_name_to_tdb_dtype[name]; + + auto kind = py::str(py::getattr(type, "kind")); + if (kind.is(py::str("S"))) + return TILEDB_STRING_ASCII; + if (kind.is(py::str("U"))) + return TILEDB_STRING_UTF8; + + TPY_ERROR_LOC("could not handle numpy dtype: " + + py::getattr(type, "name").cast()); +} + +bool is_tdb_num(tiledb_datatype_t type) { + switch (type) { + case TILEDB_INT8: + case TILEDB_INT16: + case TILEDB_UINT8: + case TILEDB_INT32: + case TILEDB_INT64: + case TILEDB_UINT16: + case TILEDB_UINT32: + case TILEDB_UINT64: + case TILEDB_FLOAT32: + case TILEDB_FLOAT64: + return true; + default: + return false; + } +} + +bool is_tdb_str(tiledb_datatype_t type) { + switch (type) { + case TILEDB_STRING_ASCII: + case TILEDB_STRING_UTF8: + case TILEDB_CHAR: + return true; + default: + return false; + } +} + +py::size_t get_ncells(py::dtype type) { + auto np = py::module::import("numpy"); + auto np_issubdtype = np.attr("issubdtype"); + auto np_complexfloating = np.attr("complexfloating"); + auto np_character = np.attr("character"); + + py::bool_ ischaracter = np_issubdtype(type, np_character); + if (ischaracter) { + py::dtype base_dtype = + np.attr("dtype")(py::make_tuple(type.attr("kind"), 1)); + if (type.itemsize() == 0) + return TILEDB_VAR_NUM; + return type.itemsize() / base_dtype.itemsize(); + } + + py::bool_ iscomplexfloating = np_issubdtype(type, np_complexfloating); + if (iscomplexfloating) + return 2; + + return 1; +} + +py::array_t +uint8_bool_to_uint8_bitmap(py::array_t validity_array) { + // TODO profile, probably replace; avoid inplace reassignment + auto np = py::module::import("numpy"); + auto packbits = np.attr("packbits"); + auto tmp = packbits(validity_array, "bitorder"_a = "little"); + return tmp; +} + +uint64_t count_zeros(py::array_t a) { + uint64_t count = 0; + for (py::ssize_t idx = 0; idx < a.size(); idx++) + count += (a.data()[idx] == 0) ? 1 : 0; + return count; +} diff --git a/testbed/TileDB-Inc__TileDB-Py/tiledb/cc/common.h b/testbed/TileDB-Inc__TileDB-Py/tiledb/cc/common.h new file mode 100644 index 0000000000000000000000000000000000000000..4c5725ccd66513e0b93d73b3c392c9821fa3aa5e --- /dev/null +++ b/testbed/TileDB-Inc__TileDB-Py/tiledb/cc/common.h @@ -0,0 +1,43 @@ +#include // for enums +#include // C++ + +#include +#include +#include +#include + +using namespace tiledb; +namespace py = pybind11; +using namespace pybind11::literals; + +#define TPY_ERROR_LOC(m) \ + throw TileDBPyError(std::string(m) + " (" + __FILE__ + ":" + \ + std::to_string(__LINE__) + ")"); + +class TileDBPyError : std::runtime_error { +public: + explicit TileDBPyError(const char *m) : std::runtime_error(m) {} + explicit TileDBPyError(std::string m) : std::runtime_error(m.c_str()) {} + +public: + virtual const char *what() const noexcept override { + return std::runtime_error::what(); + } +}; + +namespace tiledbpy::common { + +size_t buffer_nbytes(py::buffer_info &info); + +bool expect_buffer_nbytes(py::buffer_info &info, tiledb_datatype_t datatype, + size_t nbytes); + +} // namespace tiledbpy::common + +py::dtype tdb_to_np_dtype(tiledb_datatype_t type, uint32_t cell_val_num); +tiledb_datatype_t np_to_tdb_dtype(py::dtype type); + +bool is_tdb_num(tiledb_datatype_t type); +bool is_tdb_str(tiledb_datatype_t type); + +py::size_t get_ncells(py::dtype type); \ No newline at end of file diff --git a/testbed/TileDB-Inc__TileDB-Py/tiledb/cc/consolidation_plan.cc b/testbed/TileDB-Inc__TileDB-Py/tiledb/cc/consolidation_plan.cc new file mode 100644 index 0000000000000000000000000000000000000000..c1dd4c36bb0e27cf3245f82bb2f081bd64b2e80e --- /dev/null +++ b/testbed/TileDB-Inc__TileDB-Py/tiledb/cc/consolidation_plan.cc @@ -0,0 +1,28 @@ +#include +#include + +#include +#include +#include +#include + +#include "common.h" + +namespace libtiledbcpp { + +using namespace tiledb; +using namespace tiledbpy::common; +namespace py = pybind11; + +void init_consolidation_plan(py::module &m) { + py::class_(m, "ConsolidationPlan") + + .def(py::init(), py::keep_alive<1, 2>(), + py::keep_alive<1, 3>()) + + .def_property_readonly("_num_nodes", &ConsolidationPlan::num_nodes) + .def("_num_fragments", &ConsolidationPlan::num_fragments) + .def("_fragment_uri", &ConsolidationPlan::fragment_uri) + .def("_dump", &ConsolidationPlan::dump); +} +} // namespace libtiledbcpp diff --git a/testbed/TileDB-Inc__TileDB-Py/tiledb/cc/context.cc b/testbed/TileDB-Inc__TileDB-Py/tiledb/cc/context.cc new file mode 100644 index 0000000000000000000000000000000000000000..0b02cfa6aa67fb768bedf243621567f9a087a2aa --- /dev/null +++ b/testbed/TileDB-Inc__TileDB-Py/tiledb/cc/context.cc @@ -0,0 +1,80 @@ +#include // C++ + +#include +#include +#include +#include + +namespace libtiledbcpp { + +using namespace tiledb; +namespace py = pybind11; + +void init_context(py::module &m) { + py::class_(m, "Context") + .def(py::init()) + .def(py::init()) + .def(py::init()) + .def(py::init()) + + .def("__capsule__", + [](Context &ctx) { return py::capsule(ctx.ptr().get(), "ctx"); }) + + .def("config", &Context::config) + .def("set_tag", &Context::set_tag) + .def("get_stats", &Context::stats) + .def("is_supported_fs", &Context::is_supported_fs); +} + +void init_config(py::module &m) { + py::class_(m, "Config") + .def(py::init()) + .def(py::init()) + .def(py::init>()) + .def(py::init()) + + .def("__capsule__", + [](Config &config) { + return py::capsule(config.ptr().get(), "config"); + }) + + .def("set", &Config::set) + .def("get", &Config::get) + .def("update", + [](Config &cfg, py::dict &odict) { + for (auto item : odict) { + cfg.set(item.first.cast(), item.second.cast()); + } + }) + + .def("save_to_file", &Config::save_to_file) + .def("__eq__", &Config::operator==) + .def("__ne__", &Config::operator!=) + //.def("_ptr", &Config::ptr) // TBD should this be capsule? + .def("__setitem__", [](Config &cfg, std::string ¶m, + std::string &val) { cfg[param] = val; }) + .def("__getitem__", + [](const Config &cfg, std::string ¶m) { + try { + return cfg.get(param); + } catch (TileDBError &e) { + throw py::key_error(); + } + }) + .def("__delitem__", + [](Config &cfg, const std::string ¶m) { + try { + cfg.unset(param); + } catch (TileDBError &e) { + throw py::key_error(); + } + }) + .def( + "_iter", + [](Config &cfg, std::string prefix) { + return py::make_iterator(cfg.begin(prefix), cfg.end()); + }, + py::keep_alive<0, 1>(), py::arg("prefix") = "") + .def("unset", &Config::unset); +} +}; // namespace libtiledbcpp diff --git a/testbed/TileDB-Inc__TileDB-Py/tiledb/cc/current_domain.cc b/testbed/TileDB-Inc__TileDB-Py/tiledb/cc/current_domain.cc new file mode 100644 index 0000000000000000000000000000000000000000..f45b1c33f417b269ff3b44a3a15800c7c25a8fdb --- /dev/null +++ b/testbed/TileDB-Inc__TileDB-Py/tiledb/cc/current_domain.cc @@ -0,0 +1,224 @@ +#include +#include + +#include +#include +#include +#include +#include + +#include "common.h" + +namespace libtiledbcpp { + +using namespace tiledb; +using namespace tiledbpy::common; +namespace py = pybind11; + +void init_current_domain(py::module &m) { +#if TILEDB_VERSION_MAJOR >= 2 && TILEDB_VERSION_MINOR >= 25 + py::class_(m, "NDRectangle") + .def(py::init()) + + .def(py::init()) + + .def("_set_range", + py::overload_cast( + &NDRectangle::set_range), + py::arg("dim_name"), py::arg("start"), py::arg("end")) + .def("_set_range", + py::overload_cast( + &NDRectangle::set_range), + py::arg("dim_name"), py::arg("start"), py::arg("end")) + .def("_set_range", + py::overload_cast( + &NDRectangle::set_range), + py::arg("dim_name"), py::arg("start"), py::arg("end")) + .def("_set_range", + py::overload_cast( + &NDRectangle::set_range), + py::arg("dim_name"), py::arg("start"), py::arg("end")) + .def("_set_range", + py::overload_cast( + &NDRectangle::set_range), + py::arg("dim_name"), py::arg("start"), py::arg("end")) + .def("_set_range", + py::overload_cast( + &NDRectangle::set_range), + py::arg("dim_name"), py::arg("start"), py::arg("end")) + .def("_set_range", + py::overload_cast( + &NDRectangle::set_range), + py::arg("dim_name"), py::arg("start"), py::arg("end")) + .def("_set_range", + py::overload_cast( + &NDRectangle::set_range), + py::arg("dim_name"), py::arg("start"), py::arg("end")) + .def("_set_range", + py::overload_cast( + &NDRectangle::set_range), + py::arg("dim_name"), py::arg("start"), py::arg("end")) + .def("_set_range", + py::overload_cast( + &NDRectangle::set_range), + py::arg("dim_name"), py::arg("start"), py::arg("end")) + .def( + "_set_range", + [](NDRectangle &ndrect, const std::string &dim_name, + const std::string &start, const std::string &end) { + return ndrect.set_range(dim_name, start, end); + }, + py::arg("dim_name"), py::arg("start"), py::arg("end")) + .def("_set_range", + py::overload_cast( + &NDRectangle::set_range), + py::arg("dim_idx"), py::arg("start"), py::arg("end")) + .def("_set_range", + py::overload_cast( + &NDRectangle::set_range), + py::arg("dim_idx"), py::arg("start"), py::arg("end")) + .def("_set_range", + py::overload_cast( + &NDRectangle::set_range), + py::arg("dim_idx"), py::arg("start"), py::arg("end")) + .def("_set_range", + py::overload_cast( + &NDRectangle::set_range), + py::arg("dim_idx"), py::arg("start"), py::arg("end")) + .def("_set_range", + py::overload_cast( + &NDRectangle::set_range), + py::arg("dim_idx"), py::arg("start"), py::arg("end")) + .def("_set_range", + py::overload_cast( + &NDRectangle::set_range), + py::arg("dim_idx"), py::arg("start"), py::arg("end")) + .def("_set_range", + py::overload_cast( + &NDRectangle::set_range), + py::arg("dim_idx"), py::arg("start"), py::arg("end")) + .def("_set_range", + py::overload_cast( + &NDRectangle::set_range), + py::arg("dim_idx"), py::arg("start"), py::arg("end")) + .def("_set_range", + py::overload_cast( + &NDRectangle::set_range), + py::arg("dim_idx"), py::arg("start"), py::arg("end")) + .def("_set_range", + py::overload_cast( + &NDRectangle::set_range), + py::arg("dim_idx"), py::arg("start"), py::arg("end")) + .def( + "_set_range", + [](NDRectangle &ndrect, uint32_t dim_idx, const std::string &start, + const std::string &end) { + return ndrect.set_range(dim_idx, start, end); + }, + py::arg("dim_name"), py::arg("start"), py::arg("end")) + + .def("_range", + [](NDRectangle &ndrect, const std::string &dim_name, + const py::dtype &n_type) -> py::tuple { + if (n_type.is(py::dtype::of())) { + auto range = ndrect.range(dim_name); + return py::make_tuple(range[0], range[1]); + } else if (n_type.is(py::dtype::of())) { + auto range = ndrect.range(dim_name); + return py::make_tuple(range[0], range[1]); + } else if (n_type.is(py::dtype::of())) { + auto range = ndrect.range(dim_name); + return py::make_tuple(range[0], range[1]); + } else if (n_type.is(py::dtype::of())) { + auto range = ndrect.range(dim_name); + return py::make_tuple(range[0], range[1]); + } else if (n_type.is(py::dtype::of())) { + auto range = ndrect.range(dim_name); + return py::make_tuple(range[0], range[1]); + } else if (n_type.is(py::dtype::of())) { + auto range = ndrect.range(dim_name); + return py::make_tuple(range[0], range[1]); + } else if (n_type.is(py::dtype::of())) { + auto range = ndrect.range(dim_name); + return py::make_tuple(range[0], range[1]); + } else if (n_type.is(py::dtype::of())) { + auto range = ndrect.range(dim_name); + return py::make_tuple(range[0], range[1]); + } else if (n_type.is(py::dtype::of())) { + auto range = ndrect.range(dim_name); + return py::make_tuple(range[0], range[1]); + } else if (n_type.is(py::dtype::of())) { + auto range = ndrect.range(dim_name); + return py::make_tuple(range[0], range[1]); + } else if (py::getattr(n_type, "kind").is(py::str("S")) || + py::getattr(n_type, "kind").is(py::str("U"))) { + auto range = ndrect.range(dim_name); + return py::make_tuple(range[0], range[1]); + } else { + TPY_ERROR_LOC("Unsupported type for NDRectangle's range"); + } + }) + .def("_range", + [](NDRectangle &ndrect, unsigned dim_idx, + const py::dtype &n_type) -> py::tuple { + if (n_type.is(py::dtype::of())) { + auto range = ndrect.range(dim_idx); + return py::make_tuple(range[0], range[1]); + } else if (n_type.is(py::dtype::of())) { + auto range = ndrect.range(dim_idx); + return py::make_tuple(range[0], range[1]); + } else if (n_type.is(py::dtype::of())) { + auto range = ndrect.range(dim_idx); + return py::make_tuple(range[0], range[1]); + } else if (n_type.is(py::dtype::of())) { + auto range = ndrect.range(dim_idx); + return py::make_tuple(range[0], range[1]); + } else if (n_type.is(py::dtype::of())) { + auto range = ndrect.range(dim_idx); + return py::make_tuple(range[0], range[1]); + } else if (n_type.is(py::dtype::of())) { + auto range = ndrect.range(dim_idx); + return py::make_tuple(range[0], range[1]); + } else if (n_type.is(py::dtype::of())) { + auto range = ndrect.range(dim_idx); + return py::make_tuple(range[0], range[1]); + } else if (n_type.is(py::dtype::of())) { + auto range = ndrect.range(dim_idx); + return py::make_tuple(range[0], range[1]); + } else if (n_type.is(py::dtype::of())) { + auto range = ndrect.range(dim_idx); + return py::make_tuple(range[0], range[1]); + } else if (n_type.is(py::dtype::of())) { + auto range = ndrect.range(dim_idx); + return py::make_tuple(range[0], range[1]); + } else if (py::getattr(n_type, "kind").is(py::str("S")) || + py::getattr(n_type, "kind").is(py::str("U"))) { + auto range = ndrect.range(dim_idx); + return py::make_tuple(range[0], range[1]); + } else { + TPY_ERROR_LOC("Unsupported type for NDRectangle's range"); + } + }); + + py::class_(m, "CurrentDomain") + .def(py::init()) + + .def(py::init()) + + .def("__capsule__", + [](CurrentDomain &curr_dom) { + return py::capsule(curr_dom.ptr().get(), "curr_dom"); + }) + + .def_property_readonly("_type", &CurrentDomain::type) + + .def("_set_ndrectangle", &CurrentDomain::set_ndrectangle, + py::arg("ndrect")) + + .def("_ndrectangle", &CurrentDomain::ndrectangle) + + .def("_is_empty", &CurrentDomain::is_empty); +#endif +} + +} // namespace libtiledbcpp diff --git a/testbed/TileDB-Inc__TileDB-Py/tiledb/cc/dimension_label.cc b/testbed/TileDB-Inc__TileDB-Py/tiledb/cc/dimension_label.cc new file mode 100644 index 0000000000000000000000000000000000000000..4628517ede56453e9e4571f36a1648be94e53424 --- /dev/null +++ b/testbed/TileDB-Inc__TileDB-Py/tiledb/cc/dimension_label.cc @@ -0,0 +1,46 @@ +#include +#include + +#include +#include +#include +#include + +#include "common.h" + +namespace libtiledbcpp { + +using namespace tiledb; +using namespace tiledbpy::common; +namespace py = pybind11; + +void init_dimension_label(py::module &m) { + py::class_(m, "DimensionLabel") + .def(py::init()) + + .def(py::init()) + + .def("__capsule__", + [](DimensionLabel &dim_label) { + return py::capsule(dim_label.ptr().get(), "dim_label"); + }) + + .def_property_readonly("_label_attr_name", + &DimensionLabel::label_attr_name) + + .def_property_readonly("_dim_index", &DimensionLabel::dimension_index) + + .def_property_readonly("_tiledb_label_order", + &DimensionLabel::label_order) + + .def_property_readonly("_tiledb_label_dtype", &DimensionLabel::label_type) + + .def_property_readonly("_label_ncell", + &DimensionLabel::label_cell_val_num) + + .def_property_readonly("_name", &DimensionLabel::name) + + .def_property_readonly("_uri", &DimensionLabel::uri); +} + +}; // namespace libtiledbcpp diff --git a/testbed/TileDB-Inc__TileDB-Py/tiledb/cc/domain.cc b/testbed/TileDB-Inc__TileDB-Py/tiledb/cc/domain.cc new file mode 100644 index 0000000000000000000000000000000000000000..4623dbde2df822e61e1c278643ce5b9eccc34cd6 --- /dev/null +++ b/testbed/TileDB-Inc__TileDB-Py/tiledb/cc/domain.cc @@ -0,0 +1,215 @@ +#include + +#include +#include +#include +#include + +#include "common.h" + +namespace libtiledbcpp { + +using namespace tiledb; +using namespace tiledbpy::common; +namespace py = pybind11; + +void init_domain(py::module &m) { + py::class_(m, "Dimension") + .def(py::init()) + + .def(py::init([](const Context &ctx, const std::string &name, + tiledb_datatype_t datatype, py::object domain, + py::object tile_extent) { + void *dim_dom = nullptr; + void *dim_tile = nullptr; + + if (!domain.is_none()) { + py::buffer domain_buffer = py::buffer(domain); + py::buffer_info domain_info = domain_buffer.request(); + dim_dom = domain_info.ptr; + } + + if (!tile_extent.is_none()) { + py::buffer tile_buffer = py::buffer(tile_extent); + py::buffer_info tile_extent_info = tile_buffer.request(); + dim_tile = tile_extent_info.ptr; + } + + return std::make_unique( + Dimension::create(ctx, name, datatype, dim_dom, dim_tile)); + }), + py::keep_alive<1, 2>()) + + .def(py::init(), py::keep_alive<1, 2>()) + + .def_property_readonly("_name", &Dimension::name) + + .def_property_readonly( + "_domain", + [](Dimension &dim) { + switch (dim.type()) { + case TILEDB_UINT64: { + auto dom = dim.domain(); + return py::make_tuple(dom.first, dom.second); + } + case TILEDB_DATETIME_YEAR: + case TILEDB_DATETIME_MONTH: + case TILEDB_DATETIME_WEEK: + case TILEDB_DATETIME_DAY: + case TILEDB_DATETIME_HR: + case TILEDB_DATETIME_MIN: + case TILEDB_DATETIME_SEC: + case TILEDB_DATETIME_MS: + case TILEDB_DATETIME_US: + case TILEDB_DATETIME_NS: + case TILEDB_DATETIME_PS: + case TILEDB_DATETIME_FS: + case TILEDB_DATETIME_AS: + case TILEDB_INT64: { + auto dom = dim.domain(); + return py::make_tuple(dom.first, dom.second); + } + case TILEDB_UINT32: { + auto dom = dim.domain(); + return py::make_tuple(dom.first, dom.second); + } + case TILEDB_INT32: { + auto dom = dim.domain(); + return py::make_tuple(dom.first, dom.second); + } + case TILEDB_UINT16: { + auto dom = dim.domain(); + return py::make_tuple(dom.first, dom.second); + } + case TILEDB_INT16: { + auto dom = dim.domain(); + return py::make_tuple(dom.first, dom.second); + } + case TILEDB_UINT8: { + auto dom = dim.domain(); + return py::make_tuple(dom.first, dom.second); + } + case TILEDB_INT8: { + auto dom = dim.domain(); + return py::make_tuple(dom.first, dom.second); + } + case TILEDB_FLOAT64: { + auto dom = dim.domain(); + return py::make_tuple(dom.first, dom.second); + } + case TILEDB_FLOAT32: { + auto dom = dim.domain(); + return py::make_tuple(dom.first, dom.second); + } + case TILEDB_STRING_ASCII: { + return py::make_tuple("", ""); + } + default: + TPY_ERROR_LOC("Unsupported dtype for Dimension's domain"); + } + }) + + .def_property_readonly( + "_tile", + [](Dimension &dim) -> py::object { + switch (dim.type()) { + case TILEDB_UINT64: { + return py::cast(dim.tile_extent()); + } + case TILEDB_DATETIME_YEAR: + case TILEDB_DATETIME_MONTH: + case TILEDB_DATETIME_WEEK: + case TILEDB_DATETIME_DAY: + case TILEDB_DATETIME_HR: + case TILEDB_DATETIME_MIN: + case TILEDB_DATETIME_SEC: + case TILEDB_DATETIME_MS: + case TILEDB_DATETIME_US: + case TILEDB_DATETIME_NS: + case TILEDB_DATETIME_PS: + case TILEDB_DATETIME_FS: + case TILEDB_DATETIME_AS: + case TILEDB_INT64: { + return py::cast(dim.tile_extent()); + } + case TILEDB_UINT32: { + return py::cast(dim.tile_extent()); + } + case TILEDB_INT32: { + return py::cast(dim.tile_extent()); + } + case TILEDB_UINT16: { + return py::cast(dim.tile_extent()); + } + case TILEDB_INT16: { + return py::cast(dim.tile_extent()); + } + case TILEDB_UINT8: { + return py::cast(dim.tile_extent()); + } + case TILEDB_INT8: { + return py::cast(dim.tile_extent()); + } + case TILEDB_FLOAT64: { + return py::cast(dim.tile_extent()); + } + case TILEDB_FLOAT32: { + return py::cast(dim.tile_extent()); + } + case TILEDB_STRING_ASCII: { + return py::none(); + } + default: + TPY_ERROR_LOC("Unsupported dtype for Dimension's tile extent"); + } + }) + + .def_property("_filters", &Dimension::filter_list, + &Dimension::set_filter_list) + + .def_property("_ncell", &Dimension::cell_val_num, + &Dimension::set_cell_val_num) + + .def_property_readonly("_tiledb_dtype", &Dimension::type) + + .def("_domain_to_str", &Dimension::domain_to_str); + + py::class_(m, "Domain") + .def(py::init()) + + .def(py::init()) + + .def(py::init()) + + .def("__capsule__", + [](Domain &dom) { return py::capsule(dom.ptr().get(), "dom"); }) + + .def_property_readonly("_ncell", + [](Domain &dom) { return dom.cell_num(); }) + + .def_property_readonly("_tiledb_dtype", &Domain::type) + + .def_property_readonly("_ndim", &Domain::ndim) + + .def_property_readonly("_dims", &Domain::dimensions) + + .def("_dim", py::overload_cast(&Domain::dimension, py::const_)) + .def("_dim", py::overload_cast(&Domain::dimension, + py::const_)) + + .def("_has_dim", &Domain::has_dimension) + + .def("_add_dim", &Domain::add_dimension, py::keep_alive<1, 2>()) + + .def("_dump", [](Domain &dom) { +#if TILEDB_VERSION_MAJOR >= 2 && TILEDB_VERSION_MINOR >= 26 + std::stringstream ss; + ss << dom; + return ss.str(); +#else + dom.dump(); +#endif + }); +} + +} // namespace libtiledbcpp diff --git a/testbed/TileDB-Inc__TileDB-Py/tiledb/cc/enum.cc b/testbed/TileDB-Inc__TileDB-Py/tiledb/cc/enum.cc new file mode 100644 index 0000000000000000000000000000000000000000..0aea25ce44f9c3fed0a652f27c89a069c53a055c --- /dev/null +++ b/testbed/TileDB-Inc__TileDB-Py/tiledb/cc/enum.cc @@ -0,0 +1,197 @@ +#include + +#include +#include +#include +#include + +namespace libtiledbcpp { + +using namespace tiledb; +namespace py = pybind11; + +void init_enums(py::module &m) { + // consts from tiledb.h + m.def("TILEDB_VAR_NUM", []() { return TILEDB_VAR_NUM; }); + m.def("TILEDB_MAX_PATH", []() { return TILEDB_MAX_PATH; }); + m.def("TILEDB_OFFSET_SIZE", []() { return TILEDB_OFFSET_SIZE; }); + m.def("TILEDB_TIMESTAMP_NOW_MS", []() { return TILEDB_TIMESTAMP_NOW_MS; }); + + py::enum_(m, "DataType", py::module_local()) + .value("INT32", TILEDB_INT32) + .value("INT64", TILEDB_INT64) + .value("FLOAT32", TILEDB_FLOAT32) + .value("FLOAT64", TILEDB_FLOAT64) + .value("CHAR", TILEDB_CHAR) + .value("INT8", TILEDB_INT8) + .value("UINT8", TILEDB_UINT8) + .value("INT16", TILEDB_INT16) + .value("UINT16", TILEDB_UINT16) + .value("UINT32", TILEDB_UINT32) + .value("UINT64", TILEDB_UINT64) + .value("BOOL", TILEDB_BOOL) + .value("STRING_ASCII", TILEDB_STRING_ASCII) + .value("STRING_UTF8", TILEDB_STRING_UTF8) + .value("STRING_UTF16", TILEDB_STRING_UTF16) + .value("STRING_UTF32", TILEDB_STRING_UTF32) + .value("STRING_UCS2", TILEDB_STRING_UCS2) + .value("STRING_UCS4", TILEDB_STRING_UCS4) + .value("ANY", TILEDB_ANY) + .value("DATETIME_YEAR", TILEDB_DATETIME_YEAR) + .value("DATETIME_MONTH", TILEDB_DATETIME_MONTH) + .value("DATETIME_WEEK", TILEDB_DATETIME_WEEK) + .value("DATETIME_DAY", TILEDB_DATETIME_DAY) + .value("DATETIME_HR", TILEDB_DATETIME_HR) + .value("DATETIME_MIN", TILEDB_DATETIME_MIN) + .value("DATETIME_SEC", TILEDB_DATETIME_SEC) + .value("DATETIME_MS", TILEDB_DATETIME_MS) + .value("DATETIME_US", TILEDB_DATETIME_US) + .value("DATETIME_NS", TILEDB_DATETIME_NS) + .value("DATETIME_PS", TILEDB_DATETIME_PS) + .value("DATETIME_FS", TILEDB_DATETIME_FS) + .value("DATETIME_AS", TILEDB_DATETIME_AS) + .value("TIME_HR", TILEDB_TIME_HR) + .value("TIME_MIN", TILEDB_TIME_MIN) + .value("TIME_SEC", TILEDB_TIME_SEC) + .value("TIME_MS", TILEDB_TIME_MS) + .value("TIME_US", TILEDB_TIME_US) + .value("TIME_NS", TILEDB_TIME_NS) + .value("TIME_PS", TILEDB_TIME_PS) + .value("TIME_FS", TILEDB_TIME_FS) + .value("TIME_AS", TILEDB_TIME_AS) + .value("BLOB", TILEDB_BLOB) +#if TILEDB_VERSION_MAJOR >= 2 && TILEDB_VERSION_MINOR >= 21 + .value("GEOM_WKB", TILEDB_GEOM_WKB) + .value("GEOM_WKT", TILEDB_GEOM_WKT) +#endif + ; // line continuation for ifdef + + py::enum_(m, "ArrayType") + .value("DENSE", TILEDB_DENSE) + .value("SPARSE", TILEDB_SPARSE); + + py::enum_(m, "LayoutType") + .value("ROW_MAJOR", TILEDB_ROW_MAJOR) + .value("COL_MAJOR", TILEDB_COL_MAJOR) + .value("GLOBAL_ORDER", TILEDB_GLOBAL_ORDER) + .value("UNORDERED", TILEDB_UNORDERED) + .value("HILBERT", TILEDB_HILBERT); + + py::enum_(m, "DataOrder") + .value("UNORDERED_DATA", TILEDB_UNORDERED_DATA) + .value("INCREASING_DATA", TILEDB_INCREASING_DATA) + .value("DECREASING_DATA", TILEDB_DECREASING_DATA); + + py::enum_(m, "FilterType") + .value("NONE", TILEDB_FILTER_NONE) + .value("GZIP", TILEDB_FILTER_GZIP) + .value("ZSTD", TILEDB_FILTER_ZSTD) + .value("LZ4", TILEDB_FILTER_LZ4) + .value("RLE", TILEDB_FILTER_RLE) + .value("BZIP2", TILEDB_FILTER_BZIP2) + .value("DELTA", TILEDB_FILTER_DELTA) + .value("DOUBLE_DELTA", TILEDB_FILTER_DOUBLE_DELTA) + .value("BIT_WIDTH_REDUCTION", TILEDB_FILTER_BIT_WIDTH_REDUCTION) + .value("BITSHUFFLE", TILEDB_FILTER_BITSHUFFLE) + .value("BYTESHUFFLE", TILEDB_FILTER_BYTESHUFFLE) + .value("POSITIVE_DELTA", TILEDB_FILTER_POSITIVE_DELTA) + .value("CHECKSUM_MD5", TILEDB_FILTER_CHECKSUM_MD5) + .value("CHECKSUM_SHA256", TILEDB_FILTER_CHECKSUM_SHA256) + .value("SCALE_FLOAT", TILEDB_FILTER_SCALE_FLOAT) + .value("DICTIONARY", TILEDB_FILTER_DICTIONARY) + .value("XOR", TILEDB_FILTER_XOR) + .value("WEBP", TILEDB_FILTER_WEBP); + + py::enum_(m, "FilterOption") + .value("COMPRESSION_LEVEL", TILEDB_COMPRESSION_LEVEL) + .value("BIT_WIDTH_MAX_WINDOW", TILEDB_BIT_WIDTH_MAX_WINDOW) + .value("POSITIVE_DELTA_MAX_WINDOW", TILEDB_POSITIVE_DELTA_MAX_WINDOW) + .value("SCALE_FLOAT_BYTEWIDTH", TILEDB_SCALE_FLOAT_BYTEWIDTH) + .value("SCALE_FLOAT_FACTOR", TILEDB_SCALE_FLOAT_FACTOR) + .value("SCALE_FLOAT_OFFSET", TILEDB_SCALE_FLOAT_OFFSET) + .value("WEBP_INPUT_FORMAT", TILEDB_WEBP_INPUT_FORMAT) + .value("WEBP_QUALITY", TILEDB_WEBP_QUALITY) + .value("WEBP_LOSSLESS", TILEDB_WEBP_LOSSLESS) + .value("COMPRESSION_REINTERPRET_DATATYPE", + TILEDB_COMPRESSION_REINTERPRET_DATATYPE); + + py::enum_(m, "WebpInputFormat") + .value("WEBP_NONE", TILEDB_WEBP_NONE) + .value("WEBP_RGB", TILEDB_WEBP_RGB) + .value("WEBP_RGBA", TILEDB_WEBP_RGBA) + .value("WEBP_BGR", TILEDB_WEBP_BGR) + .value("WEBP_BGRA", TILEDB_WEBP_BGRA); + + py::enum_(m, "EncryptionType") + .value("NO_ENCRYPTION", TILEDB_NO_ENCRYPTION) + .value("AES_256_GCM", TILEDB_AES_256_GCM); + + py::enum_(m, "WalkOrder") + .value("PREORDER", TILEDB_PREORDER) + .value("POSTORDER", TILEDB_POSTORDER); + + py::enum_(m, "QueryStatus") + .value("FAILED", Query::Status::FAILED) + .value("COMPLETE", Query::Status::COMPLETE) + .value("INPROGRESS", Query::Status::INPROGRESS) + .value("INCOMPLETE", Query::Status::INCOMPLETE) + .value("UNINITIALIZED", Query::Status::UNINITIALIZED) + .export_values(); + + py::enum_(m, "QueryType") + .value("READ", TILEDB_READ) + .value("WRITE", TILEDB_WRITE) + .value("DELETE", TILEDB_DELETE) + .value("MODIFY_EXCLUSIVE", TILEDB_MODIFY_EXCLUSIVE); + + py::enum_(m, "QueryConditionOp", + py::module_local()) + .value("LT", TILEDB_LT) + .value("LE", TILEDB_LE) + .value("GT", TILEDB_GT) + .value("GE", TILEDB_GE) + .value("EQ", TILEDB_EQ) + .value("NE", TILEDB_NE); + + py::enum_(m, "VFSMode") + .value("READ", TILEDB_VFS_READ) + .value("WRITE", TILEDB_VFS_WRITE) + .value("APPEND", TILEDB_VFS_APPEND); + + py::enum_(m, "FileSystem") + .value("S3", TILEDB_S3) + .value("AZURE", TILEDB_AZURE) + .value("GCS", TILEDB_GCS) + .value("HDFS", TILEDB_HDFS); + + py::enum_(m, "ObjectType") + .value("ARRAY", Object::Type::Array) + .value("GROUP", Object::Type::Group) + .value("INVALID", Object::Type::Invalid) + .export_values(); + + py::enum_(m, "MIMEType") + .value("AUTODETECT", TILEDB_MIME_AUTODETECT) + .value("TIFF", TILEDB_MIME_TIFF) + .value("PDF", TILEDB_MIME_PDF); + +#if TILEDB_VERSION_MAJOR >= 2 && TILEDB_VERSION_MINOR >= 25 + py::enum_(m, "CurrentDomainType") + .value("NDRECTANGLE", TILEDB_NDRECTANGLE); +#endif + // test helpers to check enum name against typed value + m.def("_enum_string", &tiledb::impl::type_to_str); + m.def("_enum_string", + py::overload_cast(&tiledb::ArraySchema::to_str)); + m.def("_enum_string", + py::overload_cast(&tiledb::ArraySchema::to_str)); + m.def("_enum_string", + py::overload_cast(&tiledb::Filter::to_str)); + m.def("_enum_string", [](Query::Status status) { + std::stringstream ss; + ss << status; + return ss.str(); + }); +} + +}; // namespace libtiledbcpp diff --git a/testbed/TileDB-Inc__TileDB-Py/tiledb/cc/enumeration.cc b/testbed/TileDB-Inc__TileDB-Py/tiledb/cc/enumeration.cc new file mode 100644 index 0000000000000000000000000000000000000000..131de3a533c4223535a6e8585cedec42a65f985b --- /dev/null +++ b/testbed/TileDB-Inc__TileDB-Py/tiledb/cc/enumeration.cc @@ -0,0 +1,98 @@ +#include +#include + +#include +#include +#include +#include + +#include "common.h" + +namespace libtiledbcpp { + +using namespace tiledb; +using namespace tiledbpy::common; +namespace py = pybind11; + +void init_enumeration(py::module &m) { + py::class_(m, "Enumeration") + .def(py::init()) + + .def(py::init([](const Context &ctx, const std::string &name, + py::dtype type, bool ordered) { + tiledb_datatype_t data_type; + try { + data_type = np_to_tdb_dtype(type); + } catch (const TileDBPyError &e) { + throw py::type_error(e.what()); + } + py::size_t cell_val_num = get_ncells(type); + + return Enumeration::create_empty(ctx, name, data_type, cell_val_num, + ordered); + })) + + .def(py::init([](const Context &ctx, const std::string &name, + std::vector &values, bool ordered, + tiledb_datatype_t type) { + return Enumeration::create(ctx, name, values, ordered, type); + })) + + .def(py::init([](const Context &ctx, const std::string &name, + bool ordered, py::array data, py::array offsets) { + tiledb_datatype_t data_type; + try { + data_type = np_to_tdb_dtype(data.dtype()); + } catch (const TileDBPyError &e) { + throw py::type_error(e.what()); + } + + py::buffer_info data_buffer = data.request(); + if (data_buffer.ndim != 1) + throw py::type_error("Only 1D Numpy arrays can be stored as " + "enumeration values"); + + py::size_t cell_val_num = + offsets.size() == 0 ? get_ncells(data.dtype()) : TILEDB_VAR_NUM; + + return Enumeration::create( + ctx, name, data_type, cell_val_num, ordered, data.data(), + data.nbytes(), offsets.size() == 0 ? nullptr : offsets.data(), + offsets.nbytes()); + })) + + .def(py::init(), py::keep_alive<1, 2>()) + + .def("__capsule__", + [](Enumeration &enmr) { + return py::capsule(enmr.ptr().get(), "enmr"); + }) + + .def_property_readonly("name", &Enumeration::name) + + .def_property_readonly("type", &Enumeration::type) + + .def_property_readonly("cell_val_num", &Enumeration::cell_val_num) + + .def_property_readonly("ordered", &Enumeration::ordered) + + .def("values", + [](Enumeration &enmr) { + auto data = enmr.as_vector(); + auto dtype = tdb_to_np_dtype(enmr.type(), enmr.cell_val_num()); + return py::array(dtype, data.size() / dtype.itemsize(), + data.data()); + }) + .def("str_values", + [](Enumeration &enmr) { return enmr.as_vector(); }) + + .def( + "extend", + static_cast &)>( + &Enumeration::extend)) + .def("extend", [](Enumeration &enmr, py::array data) { + return enmr.extend(data.data(), data.nbytes(), nullptr, 0); + }); +} + +} // namespace libtiledbcpp diff --git a/testbed/TileDB-Inc__TileDB-Py/tiledb/cc/filestore.cc b/testbed/TileDB-Inc__TileDB-Py/tiledb/cc/filestore.cc new file mode 100644 index 0000000000000000000000000000000000000000..72fd5bee61dbffa34dc4a3f8722c4aae5e4749cf --- /dev/null +++ b/testbed/TileDB-Inc__TileDB-Py/tiledb/cc/filestore.cc @@ -0,0 +1,100 @@ +#include +#include + +#include +#include +#include +#include + +#include "common.h" + +namespace libtiledbcpp { + +using namespace tiledb; +using namespace tiledbpy::common; +namespace py = pybind11; + +class Filestore { +public: + // TODO this works, but isn't actually in use at the moment. + // we are still using tiledb.libtiledb.ArraySchema. when we switch to using + // tiledb.cc.ArraySchema, use this function instead. + static ArraySchema schema_create(const Context &ctx, const char *uri) { + tiledb_array_schema_t *schema; + tiledb_filestore_schema_create(ctx.ptr().get(), uri, &schema); + return ArraySchema(ctx, py::capsule(schema)); + } + + static void uri_import(const Context &ctx, const char *filestore_array_uri, + const char *file_uri, tiledb_mime_type_t mime_type) { + ctx.handle_error(tiledb_filestore_uri_import( + ctx.ptr().get(), filestore_array_uri, file_uri, mime_type)); + } + + static void uri_export(const Context &ctx, const char *filestore_array_uri, + const char *file_uri) { + ctx.handle_error(tiledb_filestore_uri_export(ctx.ptr().get(), file_uri, + filestore_array_uri)); + } + + static void buffer_import(const Context &ctx, const char *filestore_array_uri, + py::buffer buf, tiledb_mime_type_t mime_type) { + + py::buffer_info buffer = buf.request(); + ctx.handle_error( + tiledb_filestore_buffer_import(ctx.ptr().get(), filestore_array_uri, + buffer.ptr, py::len(buf), mime_type)); + } + + static py::bytes buffer_export(const Context &ctx, + const char *filestore_array_uri, size_t offset, + size_t size) { + py::array data = py::array(py::dtype::of(), size); + py::buffer_info buffer = data.request(); + + ctx.handle_error(tiledb_filestore_buffer_export( + ctx.ptr().get(), filestore_array_uri, offset, buffer.ptr, size)); + + auto np = py::module::import("numpy"); + auto to_bytes = np.attr("ndarray").attr("tobytes"); + + return to_bytes(data); + } + + static size_t size(const Context &ctx, const char *filestore_array_uri) { + size_t size; + ctx.handle_error( + tiledb_filestore_size(ctx.ptr().get(), filestore_array_uri, &size)); + return size; + } + + static const char *mime_type_to_str(tiledb_mime_type_t mime_type) { + const char *str; + tiledb_mime_type_to_str(mime_type, &str); + return str; + } + + static tiledb_mime_type_t mime_type_from_str(const char *str) { + tiledb_mime_type_t mime_type; + tiledb_mime_type_from_str(str, &mime_type); + return mime_type; + } +}; + +void init_filestore(py::module &m) { + py::class_(m, "Filestore") + .def_static("_schema_create", &Filestore::schema_create, + py::keep_alive<1, 2>()) + .def_static("_uri_import", &Filestore::uri_import, py::keep_alive<1, 2>()) + .def_static("_uri_export", &Filestore::uri_export, py::keep_alive<1, 2>()) + .def_static("_buffer_import", &Filestore::buffer_import, + py::keep_alive<1, 2>()) + .def_static("_buffer_export", &Filestore::buffer_export, + py::keep_alive<1, 2>()) + .def_static("_size", &Filestore::size, py::keep_alive<1, 2>()) + .def_static("_mime_type_to_str", &Filestore::mime_type_to_str) + .def_static("_mime_type_from_str", &Filestore::mime_type_from_str); + ; +}; + +}; // namespace libtiledbcpp diff --git a/testbed/TileDB-Inc__TileDB-Py/tiledb/cc/filter.cc b/testbed/TileDB-Inc__TileDB-Py/tiledb/cc/filter.cc new file mode 100644 index 0000000000000000000000000000000000000000..7ff907022d7767c76060f26cf4cdea1f647e7c3a --- /dev/null +++ b/testbed/TileDB-Inc__TileDB-Py/tiledb/cc/filter.cc @@ -0,0 +1,135 @@ +#include +// #include // for filter_dump, not yet available + +#include +#include +#include +#include + +#include "common.h" + +namespace libtiledbcpp { + +using namespace tiledb; +using namespace tiledbpy::common; +namespace py = pybind11; + +void init_filter(py::module &m) { + py::class_(m, "Filter") + .def(py::init()) + + .def_property_readonly("_type", &Filter::filter_type) + + .def("_set_option", + [](Filter &filter, Context ctx, tiledb_filter_option_t option, + py::object value) { + switch (option) { + case TILEDB_COMPRESSION_LEVEL: + filter.set_option(option, value.cast()); + break; + case TILEDB_BIT_WIDTH_MAX_WINDOW: + case TILEDB_POSITIVE_DELTA_MAX_WINDOW: + filter.set_option(option, value.cast()); + break; + case TILEDB_SCALE_FLOAT_BYTEWIDTH: + filter.set_option(option, value.cast()); + break; + case TILEDB_SCALE_FLOAT_FACTOR: + case TILEDB_SCALE_FLOAT_OFFSET: + filter.set_option(option, value.cast()); + break; + case TILEDB_WEBP_INPUT_FORMAT: + filter.set_option(option, value.cast()); + break; + case TILEDB_WEBP_QUALITY: + filter.set_option(option, value.cast()); + break; + case TILEDB_WEBP_LOSSLESS: + filter.set_option(option, value.cast()); + break; + case TILEDB_COMPRESSION_REINTERPRET_DATATYPE: + filter.set_option(option, value.cast()); + break; + default: + TPY_ERROR_LOC("Unrecognized filter option to _set_option"); + } + }) + + .def("_get_option", + [](Filter &filter, Context ctx, + tiledb_filter_option_t option) -> py::object { + switch (option) { + case TILEDB_COMPRESSION_LEVEL: { + int32_t value; + filter.get_option(option, &value); + return py::cast(value); + } + case TILEDB_BIT_WIDTH_MAX_WINDOW: + case TILEDB_POSITIVE_DELTA_MAX_WINDOW: { + uint32_t value; + filter.get_option(option, &value); + return py::cast(value); + } + case TILEDB_SCALE_FLOAT_BYTEWIDTH: { + uint64_t value; + filter.get_option(option, &value); + return py::cast(value); + } + case TILEDB_SCALE_FLOAT_FACTOR: + case TILEDB_SCALE_FLOAT_OFFSET: { + double value; + filter.get_option(option, &value); + return py::cast(value); + } + case TILEDB_WEBP_INPUT_FORMAT: { + uint8_t value; + filter.get_option(option, &value); + return py::cast(value); + } + case TILEDB_WEBP_QUALITY: { + float value; + filter.get_option(option, &value); + return py::cast(value); + } + case TILEDB_WEBP_LOSSLESS: { + uint8_t value; + filter.get_option(option, &value); + return py::cast(value); + } + case TILEDB_COMPRESSION_REINTERPRET_DATATYPE: { + auto value = filter.get_option(option); + return py::cast(static_cast(value)); + } + default: + TPY_ERROR_LOC("Unrecognized filter option to _get_option"); + } + }) +#if TILEDB_VERSION_MAJOR >= 2 && TILEDB_VERSION_MINOR >= 26 + .def("_dump", + [](Filter &filter) { + std::stringstream ss; + ss << filter; + return ss.str(); + }) +#endif + ; + + py::class_(m, "FilterList") + .def(py::init()) + .def(py::init()) + .def(py::init()) + + .def("__capsule__", + [](FilterList &filterlist) { + return py::capsule(filterlist.ptr().get(), "fl"); + }) + + .def_property("_chunksize", &FilterList::max_chunk_size, + &FilterList::set_max_chunk_size) + + .def("_nfilters", &FilterList::nfilters) + .def("_filter", &FilterList::filter) + .def("_add_filter", &FilterList::add_filter); +} // namespace libtiledbcpp + +} // namespace libtiledbcpp diff --git a/testbed/TileDB-Inc__TileDB-Py/tiledb/cc/group.cc b/testbed/TileDB-Inc__TileDB-Py/tiledb/cc/group.cc new file mode 100644 index 0000000000000000000000000000000000000000..dcdf918e6b95922b895199801d216c02fbeaf597 --- /dev/null +++ b/testbed/TileDB-Inc__TileDB-Py/tiledb/cc/group.cc @@ -0,0 +1,225 @@ +#include +#include + +#include +#include +#include +#include + +#include "common.h" + +namespace libtiledbcpp { + +using namespace tiledb; +using namespace tiledbpy::common; +namespace py = pybind11; + +void put_metadata_numpy(Group &group, const std::string &key, py::array value) { + tiledb_datatype_t value_type; + try { + value_type = np_to_tdb_dtype(value.dtype()); + } catch (const TileDBPyError &e) { + throw py::type_error(e.what()); + } + + if (value.ndim() != 1) + throw py::type_error("Only 1D Numpy arrays can be stored as metadata"); + + py::size_t ncells = get_ncells(value.dtype()); + // we can't store multi-cell arrays as metadata + // e.g. an array of strings containing strings of more than one character + if (ncells != 1 && value.size() > 1) + throw py::type_error("Unsupported dtype '" + + std::string(py::str(value.dtype())) + + "' for metadata"); + + auto value_num = is_tdb_str(value_type) ? value.nbytes() : value.size(); + group.put_metadata(key, value_type, value_num, + value_num > 0 ? value.data() : nullptr); +} + +void put_metadata(Group &group, const std::string &key, + tiledb_datatype_t value_type, uint32_t value_num, + py::buffer &value) { + + py::buffer_info info = value.request(); + group.put_metadata(key, value_type, value_num, info.ptr); +} + +bool has_metadata(Group &group, const std::string &key) { + tiledb_datatype_t _unused_value_type; + return group.has_metadata(key, &_unused_value_type); +} + +std::string get_key_from_index(Group &group, uint64_t index) { + std::string key; + tiledb_datatype_t tdb_type; + uint32_t value_num; + const void *value; + + group.get_metadata_from_index(index, &key, &tdb_type, &value_num, &value); + + return key; +} + +py::object unpack_metadata_val(tiledb_datatype_t value_type, uint32_t value_num, + const char *value_ptr) { + if (value_num == 0) + throw TileDBError("internal error: unexpected value_num==0"); + + if (value_type == TILEDB_STRING_UTF8) { + return value_ptr == nullptr ? py::str() : py::str(value_ptr, value_num); + } + + if (value_type == TILEDB_BLOB || value_type == TILEDB_CHAR || + value_type == TILEDB_STRING_ASCII) { + return value_ptr == nullptr ? py::bytes() : py::bytes(value_ptr, value_num); + } + + if (value_ptr == nullptr) + return py::tuple(); + + py::tuple unpacked(value_num); + for (uint32_t i = 0; i < value_num; i++) { + switch (value_type) { + case TILEDB_INT64: + unpacked[i] = *((int64_t *)value_ptr); + break; + case TILEDB_FLOAT64: + unpacked[i] = *((double *)value_ptr); + break; + case TILEDB_FLOAT32: + unpacked[i] = *((float *)value_ptr); + break; + case TILEDB_INT32: + unpacked[i] = *((int32_t *)value_ptr); + break; + case TILEDB_UINT32: + unpacked[i] = *((uint32_t *)value_ptr); + break; + case TILEDB_UINT64: + unpacked[i] = *((uint64_t *)value_ptr); + break; + case TILEDB_INT8: + unpacked[i] = *((int8_t *)value_ptr); + break; + case TILEDB_UINT8: + unpacked[i] = *((uint8_t *)value_ptr); + break; + case TILEDB_INT16: + unpacked[i] = *((int16_t *)value_ptr); + break; + case TILEDB_UINT16: + unpacked[i] = *((uint16_t *)value_ptr); + break; + default: + throw TileDBError("TileDB datatype not supported"); + } + value_ptr += tiledb_datatype_size(value_type); + } + + if (value_num > 1) + return unpacked; + + // for single values, return the value directly + return unpacked[0]; +} + +py::array unpack_metadata_ndarray(tiledb_datatype_t value_type, + uint32_t value_num, const char *value_ptr) { + py::dtype dtype = tdb_to_np_dtype(value_type, 1); + + if (value_ptr == nullptr) { + auto np = py::module::import("numpy"); + return np.attr("empty")(py::make_tuple(0), dtype); + } + + // special case for TILEDB_STRING_UTF8: TileDB assumes size=1 + if (value_type != TILEDB_STRING_UTF8) { + value_num *= tiledb_datatype_size(value_type); + } + + auto buf = py::memoryview::from_memory(value_ptr, value_num); + + auto np = py::module::import("numpy"); + return np.attr("frombuffer")(buf, dtype); +} + +py::tuple get_metadata(Group &group, const py::str &key, bool is_ndarray) { + tiledb_datatype_t tdb_type; + uint32_t value_num; + const char *value_ptr; + + group.get_metadata(key, &tdb_type, &value_num, (const void **)&value_ptr); + if (is_ndarray) { + auto arr = unpack_metadata_ndarray(tdb_type, value_num, value_ptr); + return py::make_tuple(arr, tdb_type); + } else { + auto arr = unpack_metadata_val(tdb_type, value_num, value_ptr); + return py::make_tuple(arr, tdb_type); + } +} + +bool has_member(Group &group, std::string obj) { + try { + group.member(obj); + } catch (const TileDBError &e) { + return false; + } + return true; +} + +void init_group(py::module &m) { + py::class_(m, "Group") + .def( + py::init(), + py::keep_alive<1, 2>()) + .def(py::init(), + py::keep_alive<1, 2>()) + + .def("_open", &Group::open) + .def("_set_config", &Group::set_config) + .def("_config", &Group::config) + .def("_close", [](Group &self) { self.close(true); }) + .def_property_readonly("_isopen", &Group::is_open) + .def_property_readonly("_uri", &Group::uri) + .def_property_readonly("_query_type", &Group::query_type) + + .def("_put_metadata", put_metadata_numpy) + .def("_put_metadata", put_metadata) + + .def("_delete_metadata", &Group::delete_metadata) + .def("_has_metadata", has_metadata) + .def("_metadata_num", &Group::metadata_num) + .def("_get_metadata", get_metadata) + .def("_get_key_from_index", get_key_from_index) + + .def("_add", &Group::add_member, py::arg("uri"), + py::arg("relative") = false, py::arg("name") = std::nullopt +#if TILEDB_VERSION_MAJOR >= 2 && TILEDB_VERSION_MINOR >= 27 + , + py::arg("type") = std::nullopt +#endif + ) + .def("_remove", &Group::remove_member) + .def("_delete_group", &Group::delete_group) + .def("_member_count", &Group::member_count) + .def("_member", + static_cast(&Group::member)) + .def("_member", + static_cast(&Group::member)) + .def("_has_member", has_member) + .def("_is_relative", &Group::is_relative) + .def("_dump", &Group::dump) + + /* static methods */ + .def_static("_create", &Group::create) + .def_static("_consolidate_metadata", &Group::consolidate_metadata, + py::arg("ctx"), py::arg("uri"), + py::arg("config") = (Config *)nullptr) + .def_static("_vacuum_metadata", &Group::vacuum_metadata, py::arg("ctx"), + py::arg("uri"), py::arg("config") = (Config *)nullptr); +} + +} // namespace libtiledbcpp diff --git a/testbed/TileDB-Inc__TileDB-Py/tiledb/cc/object.cc b/testbed/TileDB-Inc__TileDB-Py/tiledb/cc/object.cc new file mode 100644 index 0000000000000000000000000000000000000000..e0111a1f882e4d02bca06bbafd223020bec5b0ea --- /dev/null +++ b/testbed/TileDB-Inc__TileDB-Py/tiledb/cc/object.cc @@ -0,0 +1,33 @@ +#include + +#include +#include +#include +#include + +#include "common.h" + +namespace libtiledbcpp { + +using namespace tiledb; +using namespace tiledbpy::common; +namespace py = pybind11; + +void init_object(py::module &m) { + py::class_(m, "Object") + .def(py::init &>()) + .def(py::init &>()) + + .def_property_readonly("_type", &Object::type) + .def_property_readonly("_uri", &Object::uri) + .def_property_readonly("_name", &Object::name) + .def("__repr__", &Object::to_str) + + .def_static("_object", &Object::object) + .def_static("_remove", &Object::remove) + .def_static("_move", &Object::move); +} + +} // namespace libtiledbcpp diff --git a/testbed/TileDB-Inc__TileDB-Py/tiledb/cc/query.cc b/testbed/TileDB-Inc__TileDB-Py/tiledb/cc/query.cc new file mode 100644 index 0000000000000000000000000000000000000000..145277c33fc8eb05392af02f4d9e58793fbede33 --- /dev/null +++ b/testbed/TileDB-Inc__TileDB-Py/tiledb/cc/query.cc @@ -0,0 +1,112 @@ +#include // C++ +#include + +#include "common.h" + +#include +#include +#include +#include + +// #pragma clang diagnostic ignored "-Wdeprecated-declarations" +// #pragma gcc diagnostic ignored "-Wdeprecated-declarations" + +namespace libtiledbcpp { + +using namespace tiledb; +using namespace std; +namespace py = pybind11; + +void init_query(py::module &m) { + py::class_(m, "Query") + + //.def(py::init()) + + .def(py::init(), + py::keep_alive<1, 2>() /* Keep context alive. */, + py::keep_alive<1, 3>() /* Keep array alive. */) + + .def(py::init(), + py::keep_alive<1, 2>() /* Keep context alive. */, + py::keep_alive<1, 3>() /* Keep array alive. */) + + // TODO .def("ptr", [&]() -> py::capsule) + + .def_property("layout", &Query::query_layout, &Query::set_layout) + + .def_property_readonly("query_type", &Query::query_type) + + .def_property_readonly("_subarray", + [](Query &query) { + // TODO: Before merge make sure the lifetime of + // the resulting subarray is not tied to this + // query. + Subarray subarray(query.ctx(), query.array()); + query.update_subarray_from_query(&subarray); + return subarray; + }) + + // TODO .def("array") -> Array& + + .def("has_results", &Query::has_results) + + .def("is_complete", + [](const Query &query) { + return query.query_status() == Query::Status::COMPLETE; + }) + + .def("finalize", &Query::finalize) + + .def("fragment_num", &Query::fragment_num) + + .def("fragment_uri", &Query::fragment_uri) + + .def("query_status", &Query::query_status) + + .def("set_condition", &Query::set_condition) + + //.def("set_data_buffer", + // (Query& (Query::*)(const std::string&, void*, + // uint64_t))&Query::set_data_buffer); + + .def("set_data_buffer", + [](Query &q, std::string name, py::array a) { + // TODO check_type(a.dtype) + // size_t item_size = a.itemsize(); + q.set_data_buffer(name, const_cast(a.data()), a.size()); + }) + + .def("set_offsets_buffer", + [](Query &q, std::string name, py::array a) { + // TODO check_type(a.dtype) + // size_t item_size = a.itemsize(); + q.set_offsets_buffer(name, (uint64_t *)(a.data()), a.size()); + }) + + .def("set_subarray", + [](Query &query, const Subarray &subarray) { + return query.set_subarray(subarray); + }) + + .def("set_validity_buffer", + [](Query &q, std::string name, py::array a) { + // TODO check_type(a.dtype) + // size_t item_size = a.itemsize(); + q.set_validity_buffer(name, (uint8_t *)(a.data()), a.size()); + }) + + .def("submit", &Query::submit, py::call_guard()) + + /** hackery from another branch... */ + //.def("set_fragment_uri", &Query::set_fragment_uri) + //.def("unset_buffer", &Query::unset_buffer) + //.def("set_continuation", [](Query& q) { + // q.ctx().handle_error( + // tiledb_query_set_continuation(q.ctx().ptr().get(), q.ptr().get()) + // ); + //}) + ; +} + +} // namespace libtiledbcpp diff --git a/testbed/TileDB-Inc__TileDB-Py/tiledb/cc/schema.cc b/testbed/TileDB-Inc__TileDB-Py/tiledb/cc/schema.cc new file mode 100644 index 0000000000000000000000000000000000000000..0069c8c83a1a15e3f8cd8864493859fa58b9350f --- /dev/null +++ b/testbed/TileDB-Inc__TileDB-Py/tiledb/cc/schema.cc @@ -0,0 +1,297 @@ +#include // C++ +#include // (needed for dimension labels) + +#include +#include +#include +#include + +namespace libtiledbcpp { + +using namespace tiledb; +namespace py = pybind11; + +class DimensionLabelSchema { +public: + DimensionLabelSchema(tiledb_datatype_t dim_type, py::object dim_tile_extent, + tiledb_data_order_t label_order, + tiledb_datatype_t label_type) + : dim_type_{dim_type}, dim_tile_extent_{dim_tile_extent}, + label_order_{label_order}, label_type_{label_type}, + label_filters_{std::nullopt} {} + + DimensionLabelSchema(tiledb_datatype_t dim_type, py::object dim_tile_extent, + tiledb_data_order_t label_order, + tiledb_datatype_t label_type, + const FilterList &label_filters) + : dim_type_{dim_type}, dim_tile_extent_{dim_tile_extent}, + label_order_{label_order}, label_type_{label_type}, + label_filters_{label_filters} {} + + tiledb_datatype_t dim_type() const { return dim_type_; } + + const void *dim_tile_extent() const { + + if (dim_tile_extent_.is_none()) { + return nullptr; + } + py::buffer tile_buffer = py::buffer(dim_tile_extent_); + py::buffer_info tile_extent_info = tile_buffer.request(); + return tile_extent_info.ptr; + } + + bool has_dim_tile_extent() const { return !dim_tile_extent_.is_none(); } + + bool has_label_filters() const { return label_filters_.has_value(); } + + tiledb_datatype_t label_type() const { return label_type_; } + + tiledb_data_order_t label_order() const { return label_order_; } + + const std::optional &label_filters() const { + return label_filters_; + } + +private: + tiledb_datatype_t dim_type_; + py::object dim_tile_extent_; + tiledb_data_order_t label_order_; + tiledb_datatype_t label_type_; + std::optional label_filters_; +}; + +void init_schema(py::module &m) { + py::class_(m, "DimensionLabelSchema") + .def(py::init(), + py::keep_alive<1, 3>()) + + .def(py::init(), + py::keep_alive<1, 3>()) + + .def_property_readonly("_dim_dtype", &DimensionLabelSchema::dim_type) + + .def_property_readonly("_has_label_filters", + &DimensionLabelSchema::has_label_filters) + + .def_property_readonly("_label_dtype", &DimensionLabelSchema::label_type) + + .def_property_readonly("_label_filters", + [](DimensionLabelSchema &dim_label_schema) { + return dim_label_schema.label_filters().value(); + }) + + .def_property_readonly("_label_order", &DimensionLabelSchema::label_order) + + .def_property_readonly( + "_dim_tile_extent", + [](DimensionLabelSchema &dim_label_schema) -> py::object { + const void *tile_extent = dim_label_schema.dim_tile_extent(); + if (tile_extent == nullptr) { + return py::none(); + } + auto dim_type = dim_label_schema.dim_type(); + + switch (dim_type) { + case TILEDB_UINT64: { + using T = uint64_t; + return py::cast(*static_cast(tile_extent)); + } + case TILEDB_DATETIME_YEAR: + case TILEDB_DATETIME_MONTH: + case TILEDB_DATETIME_WEEK: + case TILEDB_DATETIME_DAY: + case TILEDB_DATETIME_HR: + case TILEDB_DATETIME_MIN: + case TILEDB_DATETIME_SEC: + case TILEDB_DATETIME_MS: + case TILEDB_DATETIME_US: + case TILEDB_DATETIME_NS: + case TILEDB_DATETIME_PS: + case TILEDB_DATETIME_FS: + case TILEDB_DATETIME_AS: + case TILEDB_INT64: { + using T = int64_t; + return py::cast(*static_cast(tile_extent)); + } + case TILEDB_UINT32: { + using T = uint32_t; + return py::cast(*static_cast(tile_extent)); + } + case TILEDB_INT32: { + using T = int32_t; + return py::cast(*static_cast(tile_extent)); + } + case TILEDB_UINT16: { + using T = uint16_t; + return py::cast(*static_cast(tile_extent)); + } + case TILEDB_INT16: { + using T = int16_t; + return py::cast(*static_cast(tile_extent)); + } + case TILEDB_UINT8: { + using T = uint8_t; + return py::cast(*static_cast(tile_extent)); + } + case TILEDB_INT8: { + using T = int8_t; + return py::cast(*static_cast(tile_extent)); + } + case TILEDB_FLOAT64: { + using T = double; + return py::cast(*static_cast(tile_extent)); + } + case TILEDB_FLOAT32: { + using T = float; + return py::cast(*static_cast(tile_extent)); + } + case TILEDB_STRING_ASCII: { + // This should have already been caught in the check for a mullptr + // above. + throw TileDBError("Setting a tile extent on a string dimension " + "is not supported for dimension labels"); + } + default: + throw TileDBError("Unsupported dtype for dimension tile extent"); + } + }); + + py::class_(m, "ArraySchema") + .def(py::init()) + + .def(py::init(), py::keep_alive<1, 2>()) + + .def(py::init()) + + .def(py::init()) + + .def("__capsule__", + [](ArraySchema &schema) { + return py::capsule(schema.ptr().get(), "schema"); + }) + + .def("_dump", + [](ArraySchema &schema) { +#if TILEDB_VERSION_MAJOR >= 2 && TILEDB_VERSION_MINOR >= 26 + std::stringstream ss; + ss << schema; + return ss.str(); +#else + schema.dump(); +#endif + }) + + .def("_ctx", &ArraySchema::context) + + .def_property("_domain", &ArraySchema::domain, &ArraySchema::set_domain) + + .def_property_readonly("_array_type", &ArraySchema::array_type) + + // .def_property_readonly("timestamp_range", + // &ArraySchema::timestamp_range) + + .def_property("_capacity", &ArraySchema::capacity, + &ArraySchema::set_capacity) + + .def_property_readonly("_version", &ArraySchema::version) + + .def_property("_cell_order", &ArraySchema::cell_order, + &ArraySchema::set_cell_order) + + .def_property("_tile_order", &ArraySchema::tile_order, + &ArraySchema::set_tile_order) + + .def_property("_allows_dups", &ArraySchema::allows_dups, + &ArraySchema::set_allows_dups) + + .def_property("_coords_filters", &ArraySchema::coords_filter_list, + &ArraySchema::set_coords_filter_list) + + .def_property("_offsets_filters", &ArraySchema::offsets_filter_list, + &ArraySchema::set_offsets_filter_list) + + .def_property("_validity_filters", &ArraySchema::validity_filter_list, + &ArraySchema::set_validity_filter_list) + + .def("_attr", py::overload_cast( + &ArraySchema::attribute, py::const_)) + .def("_attr", + py::overload_cast(&ArraySchema::attribute, py::const_)) + + .def("_dim_label", + [](const ArraySchema &schema, const Context &context, + const std::string &name) { + return ArraySchemaExperimental::dimension_label(context, schema, + name); + }) + + .def_property_readonly("_nattr", &ArraySchema::attribute_num) + + .def_property_readonly( + "_ndim", [](ArraySchema schema) { return schema.domain().ndim(); }) + + .def("_add_attr", &ArraySchema::add_attribute) + + .def("_add_dim_label", + [](ArraySchema &schema, const Context &ctx, const std::string &name, + uint32_t dim_index, + const DimensionLabelSchema &dim_label_schema) { + // Check dimension datatype. + auto dim_type = schema.domain().dimension(dim_index).type(); + if (dim_label_schema.dim_type() != dim_type) { + throw TileDBError("Cannot add dimension label '" + name + + "'; The dimension datatype does not match the " + "datatype of the dimension in the array."); + } + + // Add dimension label. + ArraySchemaExperimental::add_dimension_label( + ctx, schema, dim_index, name, dim_label_schema.label_order(), + dim_label_schema.label_type(), + dim_label_schema.label_filters()); + + // If dimension tile extent is set, add dimension tile extent. + if (dim_label_schema.has_dim_tile_extent()) { + ctx.handle_error( + tiledb_array_schema_set_dimension_label_tile_extent( + ctx.ptr().get(), schema.ptr().get(), name.c_str(), + dim_type, dim_label_schema.dim_tile_extent())); + } + }) + + .def("_check", &ArraySchema::check) + + .def("_has_attribute", &ArraySchema::has_attribute) + + .def("_has_dim_label", + [](const ArraySchema &schema, const Context &ctx, + const std::string &name) { + return ArraySchemaExperimental::has_dimension_label(ctx, schema, + name); + }) + + .def("_add_enumeration", + [](const ArraySchema &schema, const Context &ctx, + const Enumeration &enmr) { + ArraySchemaExperimental::add_enumeration(ctx, schema, enmr); + }) + +#if TILEDB_VERSION_MAJOR >= 2 && TILEDB_VERSION_MINOR >= 25 + .def("_current_domain", + [](const ArraySchema &schema, const Context &ctx) { + return ArraySchemaExperimental::current_domain(ctx, schema); + }) + + .def("_set_current_domain", + [](ArraySchema &schema, const Context &ctx, + const CurrentDomain ¤t_domain) { + ArraySchemaExperimental::set_current_domain(ctx, schema, + current_domain); + }) +#endif + ; +} + +} // namespace libtiledbcpp diff --git a/testbed/TileDB-Inc__TileDB-Py/tiledb/cc/subarray.cc b/testbed/TileDB-Inc__TileDB-Py/tiledb/cc/subarray.cc new file mode 100644 index 0000000000000000000000000000000000000000..673993cdba268df6cad987cae1a97d12cab8f841 --- /dev/null +++ b/testbed/TileDB-Inc__TileDB-Py/tiledb/cc/subarray.cc @@ -0,0 +1,658 @@ +#include // for enums +#include // C++ +#include // for `tiledb_subarray_has_label_range` +#include // C++ + +#include "common.h" + +#include +#include +#include +#include + +namespace libtiledbcpp { + +using namespace tiledb; +namespace py = pybind11; + +template struct SubarrayDimensionManipulator { + + static void copy(Subarray &subarray, Subarray &original, uint32_t dim_idx) { + for (uint64_t range_idx{0}; range_idx < original.range_num(dim_idx); + ++range_idx) { + std::array range = original.range(dim_idx, range_idx); + subarray.add_range(dim_idx, range[0], range[1], range[2]); + } + } + + static py::ssize_t length(Subarray &subarray, uint32_t dim_idx) { + uint64_t length = 0; + for (uint64_t range_idx{0}; range_idx < subarray.range_num(dim_idx); + ++range_idx) { + std::array range = subarray.range(dim_idx, range_idx); + if (range[2] != 0 && range[1] != 1) { + throw TileDBPyError("Support for getting the lenght of ranges with a " + "stride is not yet implemented."); + } + + auto range_length = static_cast(range[1] - range[0]); + if (length > std::numeric_limits::max() - range_length - 1) { + throw TileDBPyError("Overflow error computing subarray shape"); + } + length += range_length + 1; + } + if (length > PY_SSIZE_T_MAX) { + throw TileDBPyError("Overflow error computing subarray shape"); + } + return Py_SAFE_DOWNCAST(length, Py_ssize_t, uint64_t); + } +}; + +template <> struct SubarrayDimensionManipulator { + + static void copy(Subarray &subarray, Subarray &original, uint32_t dim_idx) { + for (uint64_t range_idx{0}; range_idx < original.range_num(dim_idx); + ++range_idx) { + std::array range = original.range(dim_idx, range_idx); + subarray.add_range(dim_idx, range[0], range[1]); + } + } + + static uint64_t length(Subarray &, uint32_t) { + throw TileDBPyError( + "Getting length of ranges is not supported on string dimensions."); + } +}; + +void add_dim_range(Subarray &subarray, uint32_t dim_idx, py::tuple r) { + if (py::len(r) == 0) + return; + else if (py::len(r) != 2) + TPY_ERROR_LOC("Unexpected range len != 2"); + + auto r0 = r[0]; + auto r1 = r[1]; + + auto tiledb_type = + subarray.array().schema().domain().dimension(dim_idx).type(); + + try { + switch (tiledb_type) { + case TILEDB_INT32: { + using T = int32_t; + subarray.add_range(dim_idx, r0.cast(), r1.cast()); + break; + } + case TILEDB_INT64: { + using T = int64_t; + subarray.add_range(dim_idx, r0.cast(), r1.cast()); + break; + } + case TILEDB_INT8: { + using T = int8_t; + subarray.add_range(dim_idx, r0.cast(), r1.cast()); + break; + } + case TILEDB_UINT8: { + using T = uint8_t; + subarray.add_range(dim_idx, r0.cast(), r1.cast()); + break; + } + case TILEDB_INT16: { + using T = int16_t; + subarray.add_range(dim_idx, r0.cast(), r1.cast()); + break; + } + case TILEDB_UINT16: { + using T = uint16_t; + subarray.add_range(dim_idx, r0.cast(), r1.cast()); + break; + } + case TILEDB_UINT32: { + using T = uint32_t; + subarray.add_range(dim_idx, r0.cast(), r1.cast()); + break; + } + case TILEDB_UINT64: { + using T = uint64_t; + subarray.add_range(dim_idx, r0.cast(), r1.cast()); + break; + } + case TILEDB_FLOAT32: { + using T = float; + subarray.add_range(dim_idx, r0.cast(), r1.cast()); + break; + } + case TILEDB_FLOAT64: { + using T = double; + subarray.add_range(dim_idx, r0.cast(), r1.cast()); + break; + } + case TILEDB_STRING_ASCII: + case TILEDB_STRING_UTF8: + case TILEDB_CHAR: { + if (!py::isinstance(r0) != !py::isinstance(r1)) { + TPY_ERROR_LOC( + "internal error: ranges must both be strings or (None, None)"); + } else if (!py::isinstance(r0) && + !py::isinstance(r1) && + !py::isinstance(r0) && !py::isinstance(r1) && + !py::isinstance(r0) && + !py::isinstance(r1)) { + TPY_ERROR_LOC( + "internal error: expected string type for var-length dim!"); + } + + if (!py::isinstance(r0) && !py::isinstance(r0)) + subarray.add_range(dim_idx, r0.cast(), + r1.cast()); + + break; + } + case TILEDB_DATETIME_YEAR: + case TILEDB_DATETIME_MONTH: + case TILEDB_DATETIME_WEEK: + case TILEDB_DATETIME_DAY: + case TILEDB_DATETIME_HR: + case TILEDB_DATETIME_MIN: + case TILEDB_DATETIME_SEC: + case TILEDB_DATETIME_MS: + case TILEDB_DATETIME_US: + case TILEDB_DATETIME_NS: + case TILEDB_DATETIME_PS: + case TILEDB_DATETIME_FS: + case TILEDB_DATETIME_AS: { + case TILEDB_TIME_HR: + case TILEDB_TIME_MIN: + case TILEDB_TIME_SEC: + case TILEDB_TIME_MS: + case TILEDB_TIME_US: + case TILEDB_TIME_NS: + case TILEDB_TIME_PS: + case TILEDB_TIME_FS: + case TILEDB_TIME_AS: + py::dtype dtype = tdb_to_np_dtype(tiledb_type, 1); + auto dt0 = py::isinstance(r0) ? r0 : r0.attr("astype")(dtype); + auto dt1 = py::isinstance(r1) ? r1 : r1.attr("astype")(dtype); + + // TODO, this is suboptimal, should define pybind converter + if (py::isinstance(dt0) && py::isinstance(dt1)) { + subarray.add_range(dim_idx, py::cast(dt0), + py::cast(dt1)); + } else { + auto darray = py::array(py::make_tuple(dt0, dt1)); + subarray.add_range(dim_idx, *(int64_t *)darray.data(0), + *(int64_t *)darray.data(1)); + } + + break; + } + default: + TPY_ERROR_LOC("Unknown dim type conversion!"); + } + } catch (py::cast_error &e) { + (void)e; + std::string msg = "Failed to cast dim range '" + (std::string)py::repr(r) + + "' to dim type " + tiledb::impl::type_to_str(tiledb_type); + TPY_ERROR_LOC(msg); + } +} + +void copy_ranges_on_dim(Subarray &subarray, Subarray original, + uint32_t dim_idx) { + + auto tiledb_type = + subarray.array().schema().domain().dimension(dim_idx).type(); + + switch (tiledb_type) { + case TILEDB_INT32: { + using T = int32_t; + SubarrayDimensionManipulator::copy(subarray, original, dim_idx); + break; + } + case TILEDB_INT64: { + using T = int64_t; + SubarrayDimensionManipulator::copy(subarray, original, dim_idx); + break; + } + case TILEDB_INT8: { + using T = int8_t; + SubarrayDimensionManipulator::copy(subarray, original, dim_idx); + break; + } + case TILEDB_UINT8: { + using T = uint8_t; + SubarrayDimensionManipulator::copy(subarray, original, dim_idx); + break; + } + case TILEDB_INT16: { + using T = int16_t; + SubarrayDimensionManipulator::copy(subarray, original, dim_idx); + break; + } + case TILEDB_UINT16: { + using T = uint16_t; + SubarrayDimensionManipulator::copy(subarray, original, dim_idx); + break; + } + case TILEDB_UINT32: { + using T = uint32_t; + SubarrayDimensionManipulator::copy(subarray, original, dim_idx); + break; + } + case TILEDB_UINT64: { + using T = uint64_t; + SubarrayDimensionManipulator::copy(subarray, original, dim_idx); + break; + } + case TILEDB_FLOAT32: { + using T = float; + SubarrayDimensionManipulator::copy(subarray, original, dim_idx); + break; + } + case TILEDB_FLOAT64: { + using T = double; + SubarrayDimensionManipulator::copy(subarray, original, dim_idx); + break; + } + case TILEDB_STRING_ASCII: + case TILEDB_STRING_UTF8: + case TILEDB_CHAR: { + using T = std::string; + SubarrayDimensionManipulator::copy(subarray, original, dim_idx); + break; + } + case TILEDB_DATETIME_YEAR: + case TILEDB_DATETIME_MONTH: + case TILEDB_DATETIME_WEEK: + case TILEDB_DATETIME_DAY: + case TILEDB_DATETIME_HR: + case TILEDB_DATETIME_MIN: + case TILEDB_DATETIME_SEC: + case TILEDB_DATETIME_MS: + case TILEDB_DATETIME_US: + case TILEDB_DATETIME_NS: + case TILEDB_DATETIME_PS: + case TILEDB_DATETIME_FS: + case TILEDB_DATETIME_AS: { + case TILEDB_TIME_HR: + case TILEDB_TIME_MIN: + case TILEDB_TIME_SEC: + case TILEDB_TIME_MS: + case TILEDB_TIME_US: + case TILEDB_TIME_NS: + case TILEDB_TIME_PS: + case TILEDB_TIME_FS: + case TILEDB_TIME_AS: + using T = int64_t; + SubarrayDimensionManipulator::copy(subarray, original, dim_idx); + break; + } + default: + TPY_ERROR_LOC("Unknown dim type conversion!"); + } +} + +py::ssize_t length_ranges(Subarray &subarray, uint32_t dim_idx) { + + auto tiledb_type = + subarray.array().schema().domain().dimension(dim_idx).type(); + + switch (tiledb_type) { + case TILEDB_INT32: { + using T = int32_t; + return SubarrayDimensionManipulator::length(subarray, dim_idx); + } + case TILEDB_INT64: { + using T = int64_t; + return SubarrayDimensionManipulator::length(subarray, dim_idx); + } + case TILEDB_INT8: { + using T = int8_t; + return SubarrayDimensionManipulator::length(subarray, dim_idx); + } + case TILEDB_UINT8: { + using T = uint8_t; + return SubarrayDimensionManipulator::length(subarray, dim_idx); + } + case TILEDB_INT16: { + using T = int16_t; + return SubarrayDimensionManipulator::length(subarray, dim_idx); + } + case TILEDB_UINT16: { + using T = uint16_t; + return SubarrayDimensionManipulator::length(subarray, dim_idx); + } + case TILEDB_UINT32: { + using T = uint32_t; + return SubarrayDimensionManipulator::length(subarray, dim_idx); + } + case TILEDB_UINT64: { + using T = uint64_t; + return SubarrayDimensionManipulator::length(subarray, dim_idx); + } + case TILEDB_DATETIME_YEAR: + case TILEDB_DATETIME_MONTH: + case TILEDB_DATETIME_WEEK: + case TILEDB_DATETIME_DAY: + case TILEDB_DATETIME_HR: + case TILEDB_DATETIME_MIN: + case TILEDB_DATETIME_SEC: + case TILEDB_DATETIME_MS: + case TILEDB_DATETIME_US: + case TILEDB_DATETIME_NS: + case TILEDB_DATETIME_PS: + case TILEDB_DATETIME_FS: + case TILEDB_DATETIME_AS: { + case TILEDB_TIME_HR: + case TILEDB_TIME_MIN: + case TILEDB_TIME_SEC: + case TILEDB_TIME_MS: + case TILEDB_TIME_US: + case TILEDB_TIME_NS: + case TILEDB_TIME_PS: + case TILEDB_TIME_FS: + case TILEDB_TIME_AS: + using T = int64_t; + return SubarrayDimensionManipulator::length(subarray, dim_idx); + } + default: + TPY_ERROR_LOC("Dimension length not supported on a dimension with the " + "given datatype."); + } +} + +void add_dim_point_ranges(const Context &ctx, Subarray &subarray, + uint32_t dim_idx, pybind11::handle dim_range) { + + // Cast range object to appropriately typed py::array. + auto tiledb_type = + subarray.array().schema().domain().dimension(dim_idx).type(); + py::dtype dtype = tdb_to_np_dtype(tiledb_type, 1); + py::array ranges = dim_range.attr("astype")(dtype); + + // Set point ranges using C-API. + tiledb_ctx_t *c_ctx = ctx.ptr().get(); + tiledb_subarray_t *c_subarray = subarray.ptr().get(); + ctx.handle_error(tiledb_subarray_add_point_ranges( + c_ctx, c_subarray, dim_idx, (void *)ranges.data(), ranges.size())); +} + +void add_label_range(const Context &ctx, Subarray &subarray, + const std::string &label_name, py::tuple r) { + if (py::len(r) == 0) + return; + else if (py::len(r) != 2) + TPY_ERROR_LOC("Unexpected range len != 2"); + + auto r0 = r[0]; + auto r1 = r[1]; + + auto tiledb_type = ArraySchemaExperimental::dimension_label( + ctx, subarray.array().schema(), label_name) + .label_type(); + + try { + switch (tiledb_type) { + case TILEDB_INT32: { + using T = int32_t; + SubarrayExperimental::add_label_range(ctx, subarray, label_name, + r0.cast(), r1.cast()); + break; + } + case TILEDB_INT64: { + using T = int64_t; + SubarrayExperimental::add_label_range(ctx, subarray, label_name, + r0.cast(), r1.cast()); + break; + } + case TILEDB_INT8: { + using T = int8_t; + SubarrayExperimental::add_label_range(ctx, subarray, label_name, + r0.cast(), r1.cast()); + break; + } + case TILEDB_UINT8: { + using T = uint8_t; + SubarrayExperimental::add_label_range(ctx, subarray, label_name, + r0.cast(), r1.cast()); + break; + } + case TILEDB_INT16: { + using T = int16_t; + SubarrayExperimental::add_label_range(ctx, subarray, label_name, + r0.cast(), r1.cast()); + break; + } + case TILEDB_UINT16: { + using T = uint16_t; + SubarrayExperimental::add_label_range(ctx, subarray, label_name, + r0.cast(), r1.cast()); + break; + } + case TILEDB_UINT32: { + using T = uint32_t; + SubarrayExperimental::add_label_range(ctx, subarray, label_name, + r0.cast(), r1.cast()); + break; + } + case TILEDB_UINT64: { + using T = uint64_t; + SubarrayExperimental::add_label_range(ctx, subarray, label_name, + r0.cast(), r1.cast()); + break; + } + case TILEDB_FLOAT32: { + using T = float; + SubarrayExperimental::add_label_range(ctx, subarray, label_name, + r0.cast(), r1.cast()); + break; + } + case TILEDB_FLOAT64: { + using T = double; + SubarrayExperimental::add_label_range(ctx, subarray, label_name, + r0.cast(), r1.cast()); + break; + } + case TILEDB_STRING_ASCII: + case TILEDB_STRING_UTF8: + case TILEDB_CHAR: { + if (!py::isinstance(r0) != !py::isinstance(r1)) { + TPY_ERROR_LOC( + "internal error: ranges must both be strings or (None, None)"); + } else if (!py::isinstance(r0) && + !py::isinstance(r1) && + !py::isinstance(r0) && !py::isinstance(r1) && + !py::isinstance(r0) && + !py::isinstance(r1)) { + TPY_ERROR_LOC( + "internal error: expected string type for var-length label!"); + } + + if (!py::isinstance(r0) && !py::isinstance(r0)) { + std::string r0_string = r0.cast(); + std::string r1_string = r1.cast(); + SubarrayExperimental::add_label_range(ctx, subarray, label_name, + r0_string, r1_string); + } + break; + } + case TILEDB_DATETIME_YEAR: + case TILEDB_DATETIME_MONTH: + case TILEDB_DATETIME_WEEK: + case TILEDB_DATETIME_DAY: + case TILEDB_DATETIME_HR: + case TILEDB_DATETIME_MIN: + case TILEDB_DATETIME_SEC: + case TILEDB_DATETIME_MS: + case TILEDB_DATETIME_US: + case TILEDB_DATETIME_NS: + case TILEDB_DATETIME_PS: + case TILEDB_DATETIME_FS: + case TILEDB_DATETIME_AS: { + case TILEDB_TIME_HR: + case TILEDB_TIME_MIN: + case TILEDB_TIME_SEC: + case TILEDB_TIME_MS: + case TILEDB_TIME_US: + case TILEDB_TIME_NS: + case TILEDB_TIME_PS: + case TILEDB_TIME_FS: + case TILEDB_TIME_AS: + py::dtype dtype = tdb_to_np_dtype(tiledb_type, 1); + auto dt0 = py::isinstance(r0) ? r0 : r0.attr("astype")(dtype); + auto dt1 = py::isinstance(r1) ? r1 : r1.attr("astype")(dtype); + + if (py::isinstance(dt0) && py::isinstance(dt1)) { + SubarrayExperimental::add_label_range(ctx, subarray, label_name, + py::cast(dt0), + py::cast(dt1)); + } else { + auto darray = py::array(py::make_tuple(dt0, dt1)); + SubarrayExperimental::add_label_range(ctx, subarray, label_name, + *(int64_t *)darray.data(0), + *(int64_t *)darray.data(1)); + } + + break; + } + default: + TPY_ERROR_LOC("Unknown dimension label type conversion!"); + } + } catch (py::cast_error &e) { + (void)e; + std::string msg = "Failed to cast label range '" + + (std::string)py::repr(r) + "' to label type " + + tiledb::impl::type_to_str(tiledb_type); + TPY_ERROR_LOC(msg); + } +} + +bool has_label_range(const Context &ctx, Subarray &subarray, uint32_t dim_idx) { + int32_t has_label; + auto rc = tiledb_subarray_has_label_ranges( + ctx.ptr().get(), subarray.ptr().get(), dim_idx, &has_label); + if (rc == TILEDB_ERR) { + throw TileDBError("Failed to check dimension for label ranges"); + } + return has_label == 1; +} + +void init_subarray(py::module &m) { + py::class_(m, "Subarray") + .def(py::init()) + + .def(py::init(), + py::keep_alive<1, 2>() /* Keep context alive. */, + py::keep_alive<1, 3>() /* Keep array alive. */) + + .def("__capsule__", + [](Subarray &subarray) { + return py::capsule(subarray.ptr().get(), "subarray"); + }) + + .def("_add_dim_range", + [](Subarray &subarray, uint32_t dim_idx, py::tuple range) { + add_dim_range(subarray, dim_idx, range); + }) + + .def("_add_label_range", + [](Subarray &subarray, const Context &ctx, + const std::string &label_name, py::tuple range) { + add_label_range(ctx, subarray, label_name, range); + }) + + .def("_add_ranges_bulk", + [](Subarray &subarray, const Context &ctx, py::iterable ranges) { + uint32_t dim_idx = 0; + for (auto dim_range : ranges) { + if (py::isinstance(dim_range)) { + add_dim_point_ranges(ctx, subarray, dim_idx, dim_range); + } else { + py::tuple dim_range_iter = dim_range.cast(); + for (auto r : dim_range_iter) { + py::tuple range_tuple = r.cast(); + add_dim_range(subarray, dim_idx, range_tuple); + } + } + dim_idx++; + } + }) + + .def("_add_dim_point_ranges", + [](Subarray &subarray, const Context &ctx, uint32_t dim_idx, + pybind11::handle dim_range) { + add_dim_point_ranges(ctx, subarray, dim_idx, dim_range); + }) + + .def("_add_ranges", + [](Subarray &subarray, const Context &ctx, py::iterable ranges) { + uint32_t dim_idx = 0; + for (auto dim_range : ranges) { + py::tuple dim_range_iter = dim_range.cast(); + for (auto r : dim_range_iter) { + py::tuple r_tuple = r.cast(); + add_dim_range(subarray, dim_idx, r_tuple); + } + dim_idx++; + } + }) + + .def("_add_label_ranges", + [](Subarray &subarray, const Context &ctx, py::iterable ranges) { + py::dict label_ranges = ranges.cast(); + for (std::pair pair : label_ranges) { + py::str label_name = pair.first.cast(); + py::tuple label_range_iter = pair.second.cast(); + for (auto r : label_range_iter) { + py::tuple r_tuple = r.cast(); + add_label_range(ctx, subarray, label_name, r_tuple); + } + } + }) + + .def("_has_label_range", + [](Subarray &subarray, const Context &ctx, uint32_t dim_idx) { + return has_label_range(ctx, subarray, dim_idx); + }) + + .def("copy_ranges", + [](Subarray &subarray, Subarray &original, py::iterable dims) { + for (auto dim_idx : dims) { + copy_ranges_on_dim(subarray, original, dim_idx.cast()); + } + }) + + .def("_range_num", py::overload_cast( + &Subarray::range_num, py::const_)) + + .def("_range_num", + py::overload_cast(&Subarray::range_num, py::const_)) + + .def("_label_range_num", + [](Subarray &subarray, const Context &ctx, + const std::string &label_name) { + return SubarrayExperimental::label_range_num(ctx, subarray, + label_name); + }) + + .def("_shape", + [](Subarray &subarray, const Context &ctx) { + auto ndim = subarray.array().schema().domain().ndim(); + // Create numpy array and get pointer to data. + py::array_t shape(ndim); + py::buffer_info shape_result = shape.request(); + py::ssize_t *shape_ptr = + static_cast(shape_result.ptr); + // Set size for each dimension. + for (uint32_t dim_idx{0}; dim_idx < ndim; ++dim_idx) { + shape_ptr[dim_idx] = length_ranges(subarray, dim_idx); + } + return shape; + }) + + // End definitions. + ; +} + +} // namespace libtiledbcpp diff --git a/testbed/TileDB-Inc__TileDB-Py/tiledb/cc/tiledbcpp.cc b/testbed/TileDB-Inc__TileDB-Py/tiledb/cc/tiledbcpp.cc new file mode 100644 index 0000000000000000000000000000000000000000..cce6e433f63be4f7b160193972bdb0fa1adcc0fd --- /dev/null +++ b/testbed/TileDB-Inc__TileDB-Py/tiledb/cc/tiledbcpp.cc @@ -0,0 +1,83 @@ +#include // C++ + +#include "common.h" +#include +#include +#include +#include + +namespace libtiledbcpp { + +using namespace tiledb; +namespace py = pybind11; + +template +using overload_cast_ = pybind11::detail::overload_cast_impl; + +void init_array(py::module &); +void init_attribute(py::module &); +void init_context(py::module &); +void init_config(py::module &); +void init_consolidation_plan(py::module &m); +void init_current_domain(py::module &m); +void init_enums(py::module &); +void init_enumeration(py::module &); +void init_dimension_label(py::module &m); +void init_domain(py::module &m); +void init_file_handle(py::module &); +void init_filestore(py::module &m); +void init_filter(py::module &); +void init_group(py::module &); +void init_object(py::module &m); +void init_query(py::module &m); +void init_schema(py::module &); +void init_subarray(py::module &); +void init_vfs(py::module &m); + +PYBIND11_MODULE(cc, m) { + + init_array(m); + init_attribute(m); + init_context(m); + init_config(m); + init_consolidation_plan(m); + init_current_domain(m); + init_dimension_label(m); + init_domain(m); + init_enums(m); + init_enumeration(m); + init_file_handle(m); + init_filestore(m); + init_filter(m); + init_group(m); + init_object(m); + init_query(m); + init_schema(m); + init_subarray(m); + init_vfs(m); + + py::register_exception(m, "TileDBError"); + + /* + We need to make sure C++ TileDBError is translated to a correctly-typed py + error. Note that using py::exception(..., "TileDBError") creates a new + exception in the *readquery* module, so we must import to reference. + */ + py::register_exception_translator([](std::exception_ptr p) { + auto tiledb_py_error = + (py::object)py::module::import("tiledb").attr("TileDBError"); + + try { + if (p) + std::rethrow_exception(p); + } catch (const TileDBPyError &e) { + PyErr_SetString(tiledb_py_error.ptr(), e.what()); + } catch (const tiledb::TileDBError &e) { + PyErr_SetString(tiledb_py_error.ptr(), e.what()); + } catch (py::builtin_exception &e) { + throw; + }; + }); +} + +}; // namespace libtiledbcpp diff --git a/testbed/TileDB-Inc__TileDB-Py/tiledb/cc/vfs.cc b/testbed/TileDB-Inc__TileDB-Py/tiledb/cc/vfs.cc new file mode 100644 index 0000000000000000000000000000000000000000..debf87df1d4dd565c81854556246a365d0133151 --- /dev/null +++ b/testbed/TileDB-Inc__TileDB-Py/tiledb/cc/vfs.cc @@ -0,0 +1,139 @@ +#include +#include + +#include +#include +#include +#include +#include + +#include "common.h" + +namespace libtiledbcpp { + +using namespace tiledb; +using namespace tiledbpy::common; +namespace py = pybind11; + +void init_vfs(py::module &m) { + py::class_(m, "VFS") + .def(py::init(), py::keep_alive<1, 2>()) + .def(py::init(), py::keep_alive<1, 2>()) + + .def_property_readonly("_ctx", &VFS::context) + .def_property_readonly("_config", &VFS::config) + + .def("_create_bucket", &VFS::create_bucket) + .def("_remove_bucket", &VFS::remove_bucket) + .def("_is_bucket", &VFS::is_bucket) + .def("_empty_bucket", &VFS::empty_bucket) + .def("_is_empty_bucket", &VFS::is_empty_bucket) + + .def("_create_dir", &VFS::create_dir) + .def("_is_dir", &VFS::is_dir) + .def("_remove_dir", &VFS::remove_dir) + .def("_dir_size", &VFS::dir_size) + .def("_move_dir", &VFS::move_dir) + .def("_copy_dir", &VFS::copy_dir) + + .def("_is_file", &VFS::is_file) + .def("_remove_file", &VFS::remove_file) + .def("_file_size", &VFS::file_size) + .def("_move_file", &VFS::move_file) + .def("_copy_file", &VFS::copy_file) + + .def("_ls", &VFS::ls) + .def( + "_ls_recursive", + // 1. the user provides a callback, the user callback is passed to the + // C++ function. Return an empty vector. + // 2. no callback is passed and a default callback is used. The + // default callback just appends each path gathered. Return the paths. + [](VFS &vfs, std::string uri, py::object callback) { + tiledb::Context ctx; + if (callback.is_none()) { + std::vector paths; + tiledb::VFSExperimental::ls_recursive( + ctx, vfs, uri, + [&](const std::string_view path, + uint64_t object_size) -> bool { + paths.push_back(std::string(path)); + return true; + }); + return paths; + } else { + tiledb::VFSExperimental::ls_recursive( + ctx, vfs, uri, + [&](const std::string_view path, + uint64_t object_size) -> bool { + return callback(path, object_size).cast(); + }); + return std::vector(); + } + }) + .def("_touch", &VFS::touch); +} + +class FileHandle { +private: + Context _ctx; + tiledb_vfs_fh_t *_fh; + +public: + FileHandle(const Context &ctx, const VFS &vfs, std::string uri, + tiledb_vfs_mode_t mode) + : _ctx(ctx) { + _ctx.handle_error(tiledb_vfs_open(_ctx.ptr().get(), vfs.ptr().get(), + uri.c_str(), mode, &this->_fh)); + } + + void close() { + _ctx.handle_error(tiledb_vfs_close(_ctx.ptr().get(), this->_fh)); + } + + py::bytes read(uint64_t offset, uint64_t nbytes) { + py::array data = py::array(py::dtype::of(), nbytes); + py::buffer_info buffer = data.request(); + + _ctx.handle_error(tiledb_vfs_read(_ctx.ptr().get(), this->_fh, offset, + buffer.ptr, nbytes)); + + auto np = py::module::import("numpy"); + auto to_bytes = np.attr("ndarray").attr("tobytes"); + + return to_bytes(data); + } + + void write(py::buffer data) { + py::buffer_info buffer = data.request(); + _ctx.handle_error(tiledb_vfs_write(_ctx.ptr().get(), this->_fh, buffer.ptr, + buffer.shape[0])); + } + + void flush() { + _ctx.handle_error(tiledb_vfs_sync(_ctx.ptr().get(), this->_fh)); + } + + bool closed() { + int32_t is_closed; + _ctx.handle_error( + tiledb_vfs_fh_is_closed(_ctx.ptr().get(), this->_fh, &is_closed)); + return is_closed; + } +}; + +void init_file_handle(py::module &m) { + py::class_(m, "FileHandle") + .def(py::init(), + py::keep_alive<1, 2>()) + + .def_property_readonly("_closed", &FileHandle::closed) + + .def("_close", &FileHandle::close) + .def("_read", &FileHandle::read) + .def("_write", &FileHandle::write) + .def("_flush", &FileHandle::flush); +} + +} // namespace libtiledbcpp diff --git a/testbed/TileDB-Inc__TileDB-Py/tiledb/common.pxi b/testbed/TileDB-Inc__TileDB-Py/tiledb/common.pxi new file mode 100644 index 0000000000000000000000000000000000000000..85137e43259c8d763bd1f0618f338839f558b214 --- /dev/null +++ b/testbed/TileDB-Inc__TileDB-Py/tiledb/common.pxi @@ -0,0 +1,62 @@ +from cpython.bytes cimport ( + PyBytes_AS_STRING, + PyBytes_FromString, + PyBytes_FromStringAndSize, + PyBytes_GET_SIZE, + PyBytes_Size, +) +from cpython.float cimport PyFloat_FromDouble +from cpython.long cimport PyLong_FromLong +from cpython.ref cimport Py_DECREF, Py_INCREF, PyTypeObject +from libc cimport limits +from libc.stddef cimport ptrdiff_t +from libc.stdint cimport ( + int8_t, + int16_t, + int32_t, + int64_t, + uint8_t, + uint16_t, + uint32_t, + uint64_t, + uintptr_t, +) +from libc.stdio cimport FILE, stdout +from libc.stdlib cimport calloc, free, malloc +from libc.string cimport memcpy +from libcpp.vector cimport vector + + +cdef extern from "Python.h": + object PyUnicode_FromStringAndSize(const char *u, Py_ssize_t size) + object PyUnicode_FromString(const char *u) + +# Numpy imports +""" +cdef extern from "numpyFlags.h": + # Include 'numpyFlags.h' into the generated C code to disable warning. + # This must be included before numpy is cimported + pass +""" + +import numpy as np + +cimport numpy as np + + +cdef extern from "numpy/arrayobject.h": + # Steals a reference to dtype, need to incref the dtype + object PyArray_NewFromDescr(PyTypeObject* subtype, + np.dtype descr, + int nd, + np.npy_intp* dims, + np.npy_intp* strides, + void* data, + int flags, + object obj) + # Steals a reference to dtype, need to incref the dtype + object PyArray_Scalar(void* ptr, np.dtype descr, object itemsize) + void PyArray_ENABLEFLAGS(np.ndarray arr, int flags) + void* PyDataMem_NEW(size_t nbytes) + void* PyDataMem_RENEW(void* data, size_t nbytes) + void PyDataMem_FREE(void* data) diff --git a/testbed/TileDB-Inc__TileDB-Py/tiledb/consolidation_plan.py b/testbed/TileDB-Inc__TileDB-Py/tiledb/consolidation_plan.py new file mode 100644 index 0000000000000000000000000000000000000000..a6343ae36e1412081eb0a91899469ca6d0ad03df --- /dev/null +++ b/testbed/TileDB-Inc__TileDB-Py/tiledb/consolidation_plan.py @@ -0,0 +1,113 @@ +import pprint + +import tiledb.cc as lt + +from .ctx import Ctx, CtxMixin, default_ctx +from .libtiledb import Array + + +class ConsolidationPlan(CtxMixin, lt.ConsolidationPlan): + """Represents TileDB ConsolidationPlan class""" + + def __init__(self, ctx: Ctx, array: lt.Array, fragment_size: int): + """Class representing the consolidation plan for an array. The plan divides the fragments of the array into different nodes that need to be consolidated together. + + :param ctx: A TileDB Context + :param array: The array + :param fragment_size: The desired fragment size + """ + if ctx is None: + ctx = default_ctx() + + if not isinstance(array, Array): + raise ValueError("`array` argument must be of type Array") + + if not isinstance(fragment_size, int): + raise ValueError("`fragment_size` argument must be of type int") + + super().__init__(ctx, lt.Array(ctx, array), fragment_size) + + def __len__(self): + """Returns the number of nodes in the consolidation plan""" + return self.num_nodes + + def __repr__(self): + attrs = { + "num_nodes": self.num_nodes, + "fragments": { + f"node_{node_idx}": { + "num_fragments": self.num_fragments(node_idx), + "fragment_uris": [ + self.fragment_uri(node_idx, fragment_idx) + for fragment_idx in range(self.num_fragments(node_idx)) + ], + } + for node_idx in range(self.num_nodes) + }, + } + + return pprint.PrettyPrinter().pformat(attrs) + + def _repr_html_(self): + from io import StringIO + + output = StringIO() + output.write("
\n") + + output.write("

Consolidation Plan

\n") + output.write("\n") + output.write( + "\n" + ) + for node_idx in range(self.num_nodes): + output.write( + f"\n" + ) + output.write("
NodeNum FragmentsFragment URIs
{node_idx}{self.num_fragments(node_idx)}{', '.join(self.fragment_uri(node_idx, fragment_idx) for fragment_idx in range(self.num_fragments(node_idx)))}
\n") + + output.write("
\n") + return output.getvalue() + + def __getitem__(self, idx): + if idx < 0 or idx >= self.num_nodes: + raise IndexError("Index out of bounds") + + return { + "num_fragments": self.num_fragments(idx), + "fragment_uris": [ + self.fragment_uri(idx, fragment_idx) + for fragment_idx in range(self.num_fragments(idx)) + ], + } + + @property + def num_nodes(self) -> int: + """ + :rtype: int + :return: The number of nodes in the consolidation plan + """ + return self._num_nodes + + def num_fragments(self, node_idx: int) -> int: + """ + :param node_idx: Node index to retrieve the data for + :rtype: int + :return: The number of fragments for a node in the consolidation plan + """ + return self._num_fragments(node_idx) + + def fragment_uri(self, node_idx: int, fragment_idx: int) -> str: + """ + :param node_idx: Node index to retrieve the data for + :param fragment_idx: Fragment index to retrieve the data for + :rtype: str + :return: The fragment URI for a node/fragment in the consolidation plan + """ + return self._fragment_uri(node_idx, fragment_idx) + + def dump(self) -> str: + """ + :rtype: str + :return: The JSON string for the plan + """ + return self._dump() diff --git a/testbed/TileDB-Inc__TileDB-Py/tiledb/core.cc b/testbed/TileDB-Inc__TileDB-Py/tiledb/core.cc new file mode 100644 index 0000000000000000000000000000000000000000..22ddf5d0030528eb1973fe452602adb409046113 --- /dev/null +++ b/testbed/TileDB-Inc__TileDB-Py/tiledb/core.cc @@ -0,0 +1,1844 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "npbuffer.h" +#include "util.h" +#include +#include +#include +#include + +#include // C +#include // C++ +#include // C +#include // C++ + +// clang-format off +// do not re-order these headers +#include "py_arrowio" +#include "py_arrow_io_impl.h" +// clang-format on + +#if defined(TILEDB_SERIALIZATION) +#include // C +#endif + +#include "../external/tsl/robin_map.h" + +#if !defined(NDEBUG) +// #include "debug.cc" +#endif + +#include "query_condition.cc" + +namespace tiledbpy { + +using namespace tiledb; +namespace py = pybind11; +using namespace pybind11::literals; + +using TimerType = std::chrono::duration; +struct StatsInfo { + std::map counters; +}; + +bool config_has_key(tiledb::Config config, std::string key) { + return config.contains(key); +} + +struct PAPair { + int64_t get_array() { + if (!exported_) { + TPY_ERROR_LOC("Cannot export uninitialized array!"); + } + return (int64_t)&array_; + }; + int64_t get_schema() { + if (!exported_) { + TPY_ERROR_LOC("Cannot export uninitialized schema!"); + } + return (int64_t)&schema_; + } + + ArrowSchema schema_; + ArrowArray array_; + bool exported_ = false; +}; + +// global stats counters +static std::unique_ptr g_stats; + +// forward declaration +py::dtype tiledb_dtype(tiledb_datatype_t type, uint32_t cell_val_num); + +struct BufferInfo { + BufferInfo(std::string name, size_t data_nbytes, tiledb_datatype_t data_type, + uint32_t cell_val_num, size_t offsets_num, size_t validity_num, + bool isvar = false, bool isnullable = false) + + : name(name), type(data_type), cell_val_num(cell_val_num), isvar(isvar), + isnullable(isnullable) { + try { + dtype = tiledb_dtype(data_type, cell_val_num); + elem_nbytes = tiledb_datatype_size(type); + data = py::array(py::dtype("uint8"), data_nbytes); + offsets = py::array_t(offsets_num); + validity = py::array_t(validity_num); + } catch (py::error_already_set &e) { + TPY_ERROR_LOC(e.what()) + } + // TODO use memset here for zero'd buffers in debug mode + } + + string name; + tiledb_datatype_t type; + py::dtype dtype; + size_t elem_nbytes = 1; + uint64_t data_vals_read = 0; + uint32_t cell_val_num; + uint64_t offsets_read = 0; + uint64_t validity_vals_read = 0; + bool isvar; + bool isnullable; + + py::array data; + py::array_t offsets; + py::array_t validity; +}; + +struct BufferHolder { + py::object data; + py::object offsets; + py::object validity; + + BufferHolder(py::object d, py::object o, py::object v) + : data(d), offsets(o), validity(v) {} + + static void free_buffer_holder(BufferHolder *self) { delete self; } +}; + +py::dtype tiledb_dtype(tiledb_datatype_t type, uint32_t cell_val_num) { + if (cell_val_num == 1) { + auto np = py::module::import("numpy"); + auto datetime64 = np.attr("datetime64"); + switch (type) { + case TILEDB_INT32: + return py::dtype("int32"); + case TILEDB_INT64: + return py::dtype("int64"); + case TILEDB_FLOAT32: + return py::dtype("float32"); + case TILEDB_FLOAT64: + return py::dtype("float64"); + case TILEDB_INT8: + return py::dtype("int8"); + case TILEDB_UINT8: + return py::dtype("uint8"); + case TILEDB_INT16: + return py::dtype("int16"); + case TILEDB_UINT16: + return py::dtype("uint16"); + case TILEDB_UINT32: + return py::dtype("uint32"); + case TILEDB_UINT64: + return py::dtype("uint64"); + case TILEDB_STRING_ASCII: + return py::dtype("S1"); + case TILEDB_STRING_UTF8: + return py::dtype("U1"); + case TILEDB_STRING_UTF16: + case TILEDB_STRING_UTF32: + TPY_ERROR_LOC("Unimplemented UTF16 or UTF32 string conversion!"); + case TILEDB_STRING_UCS2: + case TILEDB_STRING_UCS4: + TPY_ERROR_LOC("Unimplemented UCS2 or UCS4 string conversion!"); + case TILEDB_CHAR: + return py::dtype("S1"); + case TILEDB_DATETIME_YEAR: + return py::dtype("M8[Y]"); + case TILEDB_DATETIME_MONTH: + return py::dtype("M8[M]"); + case TILEDB_DATETIME_WEEK: + return py::dtype("M8[W]"); + case TILEDB_DATETIME_DAY: + return py::dtype("M8[D]"); + case TILEDB_DATETIME_HR: + return py::dtype("M8[h]"); + case TILEDB_DATETIME_MIN: + return py::dtype("M8[m]"); + case TILEDB_DATETIME_SEC: + return py::dtype("M8[s]"); + case TILEDB_DATETIME_MS: + return py::dtype("M8[ms]"); + case TILEDB_DATETIME_US: + return py::dtype("M8[us]"); + case TILEDB_DATETIME_NS: + return py::dtype("M8[ns]"); + case TILEDB_DATETIME_PS: + return py::dtype("M8[ps]"); + case TILEDB_DATETIME_FS: + return py::dtype("M8[fs]"); + case TILEDB_DATETIME_AS: + return py::dtype("M8[as]"); + + /* duration types map to timedelta */ + case TILEDB_TIME_HR: + return py::dtype("m8[h]"); + case TILEDB_TIME_MIN: + return py::dtype("m8[m]"); + case TILEDB_TIME_SEC: + return py::dtype("m8[s]"); + case TILEDB_TIME_MS: + return py::dtype("m8[ms]"); + case TILEDB_TIME_US: + return py::dtype("m8[us]"); + case TILEDB_TIME_NS: + return py::dtype("m8[ns]"); + case TILEDB_TIME_PS: + return py::dtype("m8[ps]"); + case TILEDB_TIME_FS: + return py::dtype("m8[fs]"); + case TILEDB_TIME_AS: + return py::dtype("m8[as]"); + case TILEDB_BLOB: + return py::dtype("byte"); + case TILEDB_BOOL: + return py::dtype("bool"); +#if TILEDB_VERSION_MAJOR >= 2 && TILEDB_VERSION_MINOR >= 21 + case TILEDB_GEOM_WKB: + return py::dtype("byte"); + case TILEDB_GEOM_WKT: + return py::dtype("S"); +#endif + + case TILEDB_ANY: + break; + } + } else if (cell_val_num == 2 && type == TILEDB_FLOAT32) { + return py::dtype("complex64"); + } else if (cell_val_num == 2 && type == TILEDB_FLOAT64) { + return py::dtype("complex128"); + } else if (type == TILEDB_CHAR || type == TILEDB_STRING_UTF8 || + type == TILEDB_STRING_ASCII) { + std::string base_str; + switch (type) { + case TILEDB_CHAR: + case TILEDB_STRING_ASCII: + base_str = "|S"; + break; + case TILEDB_STRING_UTF8: + base_str = "|U"; + break; + default: + TPY_ERROR_LOC("internal error: unhandled string type"); + } + if (cell_val_num < TILEDB_VAR_NUM) { + base_str = base_str + std::to_string(cell_val_num); + } + return py::dtype(base_str); + } else if (cell_val_num == TILEDB_VAR_NUM) { + return tiledb_dtype(type, 1); + } else if (cell_val_num > 1) { + py::dtype base_dtype = tiledb_dtype(type, 1); + py::tuple rec_elem = py::make_tuple("", base_dtype); + py::list rec_list; + for (size_t i = 0; i < cell_val_num; i++) + rec_list.append(rec_elem); + auto np = py::module::import("numpy"); + // note: we call the 'dtype' constructor b/c py::dtype does not accept list + auto np_dtype = np.attr("dtype"); + return np_dtype(rec_list); + } + + TPY_ERROR_LOC("tiledb datatype not understood ('" + + tiledb::impl::type_to_str(type) + + "', cell_val_num: " + std::to_string(cell_val_num) + ")"); +} + +py::array_t +uint8_bool_to_uint8_bitmap(py::array_t validity_array) { + // TODO profile, probably replace; avoid inplace reassignment + auto np = py::module::import("numpy"); + auto packbits = np.attr("packbits"); + auto tmp = packbits(validity_array, "bitorder"_a = "little"); + return tmp; +} + +uint64_t count_zeros(py::array_t a) { + uint64_t count = 0; + for (Py_ssize_t idx = 0; idx < a.size(); idx++) + count += (a.data()[idx] == 0) ? 1 : 0; + return count; +} + +class PyAgg { + using ByteBuffer = py::array_t; + using AggToBufferMap = std::map; + using AttrToAggsMap = std::map; + +private: + Context ctx_; + std::shared_ptr array_; + std::shared_ptr query_; + AttrToAggsMap result_buffers_; + AttrToAggsMap validity_buffers_; + + py::dict original_input_; + std::vector attrs_; + +public: + PyAgg() = delete; + + PyAgg(const Context &ctx, py::object py_array, py::object py_layout, + py::dict attr_to_aggs_input) + : ctx_(ctx), original_input_(attr_to_aggs_input) { + tiledb_array_t *c_array_ = (py::capsule)py_array.attr("__capsule__")(); + + // We never own this pointer; pass own=false + array_ = std::make_shared(ctx_, c_array_, false); + query_ = std::make_shared(ctx_, *array_, TILEDB_READ); + + bool issparse = array_->schema().array_type() == TILEDB_SPARSE; + tiledb_layout_t layout = (tiledb_layout_t)py_layout.cast(); + if (!issparse && layout == TILEDB_UNORDERED) { + TPY_ERROR_LOC("TILEDB_UNORDERED read is not supported for dense arrays") + } + query_->set_layout(layout); + + // Iterate through the requested attributes + for (auto attr_to_aggs : attr_to_aggs_input) { + auto attr_name = attr_to_aggs.first.cast(); + auto aggs = attr_to_aggs.second.cast>(); + + tiledb::Attribute attr = array_->schema().attribute(attr_name); + attrs_.push_back(attr_name); + + // For non-nullable attributes, applying max and min to the empty set is + // undefined. To check for this, we need to also run the count aggregate + // to make sure count != 0 + bool requested_max = + std::find(aggs.begin(), aggs.end(), "max") != aggs.end(); + bool requested_min = + std::find(aggs.begin(), aggs.end(), "min") != aggs.end(); + if (!attr.nullable() && (requested_max || requested_min)) { + // If the user already also requested count, then we don't need to + // request it again + if (std::find(aggs.begin(), aggs.end(), "count") == aggs.end()) { + aggs.push_back("count"); + } + } + + // Iterate through the aggreate operations to apply on the given attribute + for (auto agg_name : aggs) { + _apply_agg_operator_to_attr(agg_name, attr_name); + + // Set the result data buffers + auto *res_buf = &result_buffers_[attr_name][agg_name]; + if ("count" == agg_name || "null_count" == agg_name || + "mean" == agg_name) { + // count and null_count use uint64 and mean uses float64 + *res_buf = py::array(py::dtype("uint8"), 8); + } else { + // max, min, and sum use the dtype of the attribute + py::dtype dt(tiledb_dtype(attr.type(), attr.cell_size())); + *res_buf = py::array(py::dtype("uint8"), dt.itemsize()); + } + query_->set_data_buffer(attr_name + agg_name, (void *)res_buf->data(), + 1); + + if (attr.nullable()) { + // For nullable attributes, if the input set for the aggregation + // contains all NULL values, we will not get an aggregate value back + // as this operation is undefined. We need to check the validity + // buffer beforehand to see if we had a valid result + if (!("count" == agg_name || "null_count" == agg_name)) { + auto *val_buf = &validity_buffers_[attr.name()][agg_name]; + *val_buf = py::array(py::dtype("uint8"), 1); + query_->set_validity_buffer(attr_name + agg_name, + (uint8_t *)val_buf->data(), 1); + } + } + } + } + } + + void _apply_agg_operator_to_attr(const std::string &op_label, + const std::string &attr_name) { + using AggregateFunc = + std::function; + + std::unordered_map label_to_agg_func = { + {"sum", QueryExperimental::create_unary_aggregate}, + {"min", QueryExperimental::create_unary_aggregate}, + {"max", QueryExperimental::create_unary_aggregate}, + {"mean", QueryExperimental::create_unary_aggregate}, + {"null_count", + QueryExperimental::create_unary_aggregate}, + }; + + QueryChannel default_channel = + QueryExperimental::get_default_channel(*query_); + + if (label_to_agg_func.find(op_label) != label_to_agg_func.end()) { + AggregateFunc create_unary_aggregate = label_to_agg_func.at(op_label); + ChannelOperation op = create_unary_aggregate(*query_, attr_name); + default_channel.apply_aggregate(attr_name + op_label, op); + } else if ("count" == op_label) { + default_channel.apply_aggregate(attr_name + op_label, CountOperation()); + } else { + TPY_ERROR_LOC("Invalid channel operation " + op_label + + " passed to apply_aggregate."); + } + } + + py::dict get_aggregate() { + query_->submit(); + + // Cast the results to the correct dtype and output this as a Python dict + py::dict output; + for (auto attr_to_agg : original_input_) { + // Be clear in our variable names for strings as py::dict uses py::str + // keys whereas std::map uses std::string keys + std::string attr_cpp_name = attr_to_agg.first.cast(); + + py::str attr_py_name(attr_cpp_name); + output[attr_py_name] = py::dict(); + + tiledb::Attribute attr = array_->schema().attribute(attr_cpp_name); + + for (auto agg_py_name : original_input_[attr_py_name]) { + std::string agg_cpp_name = agg_py_name.cast(); + + if (_is_invalid(attr, agg_cpp_name)) { + output[attr_py_name][agg_py_name] = + _is_integer_dtype(attr) ? py::none() : py::cast(NAN); + } else { + output[attr_py_name][agg_py_name] = _set_result(attr, agg_cpp_name); + } + } + } + return output; + } + + bool _is_invalid(tiledb::Attribute attr, std::string agg_name) { + if (attr.nullable()) { + if ("count" == agg_name || "null_count" == agg_name) + return false; + + // For nullable attributes, check if the validity buffer returned false + const void *val_buf = validity_buffers_[attr.name()][agg_name].data(); + return *((uint8_t *)(val_buf)) == 0; + } else { + // For non-nullable attributes, max and min are undefined for the empty + // set, so we must check the count == 0 + if ("max" == agg_name || "min" == agg_name) { + const void *count_buf = result_buffers_[attr.name()]["count"].data(); + return *((uint64_t *)(count_buf)) == 0; + } + return false; + } + } + + bool _is_integer_dtype(tiledb::Attribute attr) { + switch (attr.type()) { + case TILEDB_INT8: + case TILEDB_INT16: + case TILEDB_UINT8: + case TILEDB_INT32: + case TILEDB_INT64: + case TILEDB_UINT16: + case TILEDB_UINT32: + case TILEDB_UINT64: + return true; + default: + return false; + } + } + + py::object _set_result(tiledb::Attribute attr, std::string agg_name) { + const void *agg_buf = result_buffers_[attr.name()][agg_name].data(); + + if ("mean" == agg_name) + return py::cast(*((double *)agg_buf)); + + if ("count" == agg_name || "null_count" == agg_name) + return py::cast(*((uint64_t *)agg_buf)); + + switch (attr.type()) { + case TILEDB_FLOAT32: + return py::cast("sum" == agg_name ? *((double *)agg_buf) + : *((float *)agg_buf)); + case TILEDB_FLOAT64: + return py::cast(*((double *)agg_buf)); + case TILEDB_INT8: + return py::cast(*((int8_t *)agg_buf)); + case TILEDB_UINT8: + return py::cast(*((uint8_t *)agg_buf)); + case TILEDB_INT16: + return py::cast(*((int16_t *)agg_buf)); + case TILEDB_UINT16: + return py::cast(*((uint16_t *)agg_buf)); + case TILEDB_UINT32: + return py::cast(*((uint32_t *)agg_buf)); + case TILEDB_INT32: + return py::cast(*((int32_t *)agg_buf)); + case TILEDB_INT64: + return py::cast(*((int64_t *)agg_buf)); + case TILEDB_UINT64: + return py::cast(*((uint64_t *)agg_buf)); + default: + TPY_ERROR_LOC( + "[_cast_agg_result] Invalid tiledb dtype for aggregation result") + } + } + + void set_subarray(py::object py_subarray) { + query_->set_subarray(*py_subarray.cast()); + } + + void set_cond(py::object cond) { + py::object init_pyqc = cond.attr("init_query_condition"); + + try { + init_pyqc(array_->uri(), attrs_, ctx_); + } catch (tiledb::TileDBError &e) { + TPY_ERROR_LOC(e.what()); + } catch (py::error_already_set &e) { + TPY_ERROR_LOC(e.what()); + } + auto pyqc = (cond.attr("c_obj")).cast(); + auto qc = pyqc.ptr().get(); + query_->set_condition(*qc); + } +}; + +class PyQuery { +private: + Context ctx_; + std::shared_ptr domain_; + std::shared_ptr array_schema_; + std::shared_ptr array_; + std::shared_ptr query_; + std::vector attrs_; + std::vector dims_; + std::map buffers_; + std::vector buffers_order_; + + bool deduplicate_ = true; + bool use_arrow_ = false; + // initialize the query buffers with exactly `init_buffer_bytes` + // rather than the estimated result size. for incomplete testing. + bool exact_init_bytes_ = false; + uint64_t init_buffer_bytes_ = DEFAULT_INIT_BUFFER_BYTES; + uint64_t alloc_max_bytes_ = DEFAULT_ALLOC_MAX_BYTES; + tiledb_layout_t layout_ = TILEDB_ROW_MAJOR; + + // label buffer list + unordered_map label_input_buffer_data_; + +public: + tiledb_ctx_t *c_ctx_; + tiledb_array_t *c_array_; + bool preload_metadata_ = false; + bool return_incomplete_ = false; + size_t retries_ = 0; + +public: + PyQuery() = delete; + + PyQuery(const Context &ctx, py::object array, py::iterable attrs, + py::iterable dims, py::object py_layout, py::object use_arrow) + : ctx_(ctx) { + init_config(); + // initialize arrow argument from user, if provided + // call after init_config + if (!use_arrow.is(py::none())) { + use_arrow_ = py::cast(use_arrow); + } + + tiledb_array_t *c_array_ = (py::capsule)array.attr("__capsule__")(); + + // we never own this pointer, pass own=false + array_ = std::make_shared(ctx_, c_array_, false); + + array_schema_ = std::make_shared(array_->schema()); + + domain_ = std::make_shared(array_schema_->domain()); + + bool issparse = array_->schema().array_type() == TILEDB_SPARSE; + + std::string mode = py::str(array.attr("mode")); + auto query_mode = TILEDB_READ; + if (mode == "r") { + query_mode = TILEDB_READ; + } else if (mode == "d") { + query_mode = TILEDB_DELETE; + } else { + throw std::invalid_argument("Invalid query mode: " + mode); + } + + // initialize the dims that we are asked to read + for (auto d : dims) { + dims_.push_back(d.cast()); + } + + // initialize the attrs that we are asked to read + for (auto a : attrs) { + attrs_.push_back(a.cast()); + } + + if (query_mode == TILEDB_READ) { + py::object pre_buffers = array.attr("_buffers"); + if (!pre_buffers.is(py::none())) { + py::dict pre_buffers_dict = pre_buffers.cast(); + + // iterate over (key, value) pairs + for (std::pair b : pre_buffers_dict) { + py::str name = b.first.cast(); + + // unpack value tuple of (data, offsets) + auto bfrs = b.second.cast>(); + auto data_array = bfrs.first.cast(); + auto offsets_array = bfrs.second.cast(); + + import_buffer(name, data_array, offsets_array); + } + } + } + + query_ = std::make_shared(ctx_, *array_, query_mode); + // [](Query* p){} /* note: no deleter*/); + + if (query_mode == TILEDB_READ) { + layout_ = (tiledb_layout_t)py_layout.cast(); + if (!issparse && layout_ == TILEDB_UNORDERED) { + TPY_ERROR_LOC("TILEDB_UNORDERED read is not supported for dense arrays") + } + query_->set_layout(layout_); + } + + if (use_arrow_) { + // enable arrow mode in the Query + auto tmp_config = ctx_.config(); + tmp_config.set("sm.var_offsets.bitsize", "64"); + tmp_config.set("sm.var_offsets.mode", "elements"); + tmp_config.set("sm.var_offsets.extra_element", "true"); + ctx_.handle_error(tiledb_query_set_config( + ctx_.ptr().get(), query_->ptr().get(), tmp_config.ptr().get())); + } + } + + void set_subarray(py::object py_subarray) { + query_->set_subarray(*py_subarray.cast()); + } + +#if defined(TILEDB_SERIALIZATION) + void set_serialized_query(py::buffer serialized_query) { + int rc; + tiledb_query_t *c_query; + tiledb_buffer_t *c_buffer; + tiledb_ctx_t *c_ctx = ctx_.ptr().get(); + + rc = tiledb_buffer_alloc(c_ctx, &c_buffer); + if (rc == TILEDB_ERR) + TPY_ERROR_LOC("Could not allocate c_buffer."); + + py::buffer_info buffer_info = serialized_query.request(); + rc = tiledb_buffer_set_data(c_ctx, c_buffer, buffer_info.ptr, + buffer_info.shape[0]); + if (rc == TILEDB_ERR) + TPY_ERROR_LOC("Could not set c_buffer."); + + c_query = query_.get()->ptr().get(); + rc = tiledb_deserialize_query(c_ctx, c_buffer, TILEDB_CAPNP, 0, c_query); + if (rc == TILEDB_ERR) + TPY_ERROR_LOC("Could not deserialize query."); + } +#endif + + void set_cond(py::object cond) { + py::object init_pyqc = cond.attr("init_query_condition"); + + try { + init_pyqc(array_->uri(), attrs_, ctx_); + } catch (tiledb::TileDBError &e) { + TPY_ERROR_LOC(e.what()); + } catch (py::error_already_set &e) { + TPY_ERROR_LOC(e.what()); + } + auto pyqc = (cond.attr("c_obj")).cast(); + auto qc = pyqc.ptr().get(); + query_->set_condition(*qc); + } + + bool is_dimension(std::string name) { return domain_->has_dimension(name); } + + bool is_attribute(std::string name) { + return array_schema_->has_attribute(name); + } + + bool is_dimension_label(std::string name) { + return ArraySchemaExperimental::has_dimension_label(ctx_, *array_schema_, + name); + } + + bool is_var(std::string name) { + if (is_dimension(name)) { + auto dim = domain_->dimension(name); + return dim.cell_val_num() == TILEDB_VAR_NUM; + } else if (is_attribute(name)) { + auto attr = array_schema_->attribute(name); + return attr.cell_val_num() == TILEDB_VAR_NUM; + } else if (is_dimension_label(name)) { + auto dim_label = + ArraySchemaExperimental::dimension_label(ctx_, *array_schema_, name); + return dim_label.label_cell_val_num() == TILEDB_VAR_NUM; + } else { + TPY_ERROR_LOC("Unknown buffer type for is_var check (expected attribute " + "or dimension)") + } + } + + bool is_nullable(std::string name) { + if (is_dimension(name) || is_dimension_label(name)) { + return false; + } + + auto attr = array_schema_->attribute(name); + return attr.nullable(); + } + + std::pair buffer_type(std::string name) { + tiledb_datatype_t type; + uint32_t cell_val_num; + if (is_dimension(name)) { + type = domain_->dimension(name).type(); + cell_val_num = domain_->dimension(name).cell_val_num(); + } else if (is_attribute(name)) { + type = array_schema_->attribute(name).type(); + cell_val_num = array_schema_->attribute(name).cell_val_num(); + } else if (is_dimension_label(name)) { + auto dim_label = + ArraySchemaExperimental::dimension_label(ctx_, *array_schema_, name); + type = dim_label.label_type(); + cell_val_num = dim_label.label_cell_val_num(); + } else { + TPY_ERROR_LOC("Unknown buffer '" + name + "'"); + } + return {type, cell_val_num}; + } + + uint32_t buffer_ncells(std::string name) { + if (is_dimension(name)) { + return domain_->dimension(name).cell_val_num(); + } else if (is_attribute(name)) { + return array_schema_->attribute(name).cell_val_num(); + } + TPY_ERROR_LOC("Unknown buffer '" + name + "' for buffer_ncells"); + } + + py::dtype buffer_dtype(std::string name) { + try { + auto t = buffer_type(name); + return tiledb_dtype(t.first, t.second); + } catch (TileDBError &e) { + (void)e; + return py::none(); + } + } + + bool is_sparse() { return array_->schema().array_type() == TILEDB_SPARSE; } + + void import_buffer(std::string name, py::array data, py::array offsets) { + tiledb_datatype_t type; + uint32_t cell_val_num; + std::tie(type, cell_val_num) = buffer_type(name); + auto dtype = tiledb_dtype(type, cell_val_num); + + buffers_order_.push_back(name); + // set nbytes and noffsets=0 here to avoid allocation; buffers set below + auto buffer_info = BufferInfo(name, 0, type, cell_val_num, 0, + 0, // TODO + is_var(name), is_nullable(name)); + buffer_info.data = data; + buffer_info.offsets = offsets; + buffers_.insert({name, buffer_info}); + } + + void alloc_buffer(std::string name) { + tiledb_datatype_t type; + uint32_t cell_val_num; + uint64_t cell_nbytes; + bool var; + bool nullable; + uint64_t buf_nbytes = 0; + uint64_t offsets_num = 0; + uint64_t validity_num = 0; + bool dense = array_schema_->array_type() == TILEDB_DENSE; + if (is_dimension_label(name)) { + auto dim_label = + ArraySchemaExperimental::dimension_label(ctx_, *array_schema_, name); + type = dim_label.label_type(); + cell_val_num = dim_label.label_cell_val_num(); + var = cell_val_num == TILEDB_VAR_NUM; + nullable = false; + + cell_nbytes = tiledb_datatype_size(type); + uint64_t ncells = label_input_buffer_data_[name]; + + if (!var) { + cell_nbytes *= cell_val_num; + } else { + offsets_num = ncells; + } + buf_nbytes = ncells * cell_nbytes; + } else { + std::tie(type, cell_val_num) = buffer_type(name); + cell_nbytes = tiledb_datatype_size(type); + if (cell_val_num != TILEDB_VAR_NUM) { + cell_nbytes *= cell_val_num; + } + var = is_var(name); + nullable = is_nullable(name); + + if (retries_ < 1 && dense) { + // we must not call after submitting + if (nullable && var) { + auto sizes = query_->est_result_size_var_nullable(name); + offsets_num = sizes[0]; + buf_nbytes = sizes[1]; + validity_num = sizes[2] / sizeof(uint8_t); + } else if (nullable && !var) { + auto sizes = query_->est_result_size_nullable(name); + buf_nbytes = sizes[0]; + validity_num = sizes[1] / sizeof(uint8_t); + } else if (!nullable && var) { + auto size_pair = query_->est_result_size_var(name); + buf_nbytes = size_pair[0]; + offsets_num = size_pair[1]; + } else { // !nullable && !var + buf_nbytes = query_->est_result_size(name); + } + + // Add extra offset to estimate in order to avoid incomplete resubmit + // libtiledb 2.7.* does not include extra element in estimate. + // Remove this section after resolution of SC-16301. + offsets_num += (var && use_arrow_) ? 1 : 0; + } + } + + // - for sparse arrays: don't try to allocate more than alloc_max_bytes_ + // - for dense arrays: the estimate should be exact, so don't cap + if (is_sparse() && buf_nbytes > alloc_max_bytes_) { + buf_nbytes = alloc_max_bytes_; + } + // use max to avoid overflowing to zero in the multiplication, in case the + // estimate is too large + if (max(validity_num, validity_num * sizeof(uint8_t)) > alloc_max_bytes_) { + validity_num = alloc_max_bytes_ / sizeof(uint8_t); + } + if (max(offsets_num, offsets_num * sizeof(uint64_t)) > alloc_max_bytes_) { + offsets_num = alloc_max_bytes_ / sizeof(uint64_t); + } + + // use init_buffer_bytes configuration option if the + // estimate is smaller + if ((var || is_sparse()) && + (buf_nbytes < init_buffer_bytes_ || exact_init_bytes_)) { + buf_nbytes = init_buffer_bytes_; + offsets_num = init_buffer_bytes_ / sizeof(uint64_t); + validity_num = init_buffer_bytes_ / cell_nbytes; + } + + buffers_order_.push_back(name); + buffers_.insert( + {name, BufferInfo(name, buf_nbytes, type, cell_val_num, offsets_num, + validity_num, var, nullable)}); + } + + void add_label_buffer(std::string &label_name, uint64_t ncells) { + label_input_buffer_data_[label_name] = ncells; + } + + py::object get_buffers() { + py::dict rmap; + for (auto &bp : buffers_) { + py::list result; + const auto name = bp.first; + const BufferInfo b = bp.second; + result.append(b.data); + result.append(b.offsets); + rmap[py::str{name}] = result; + } + return std::move(rmap); + } + + void set_buffers() { + for (auto bp : buffers_) { + auto name = bp.first; + const BufferInfo b = bp.second; + + size_t offsets_read = b.offsets_read; + size_t data_vals_read = b.data_vals_read; + size_t validity_vals_read = b.validity_vals_read; + + void *data_ptr = + (void *)((char *)b.data.data() + (data_vals_read * b.elem_nbytes)); + uint64_t data_nelem = + (b.data.size() - (data_vals_read * b.elem_nbytes)) / b.elem_nbytes; + + // Experimental version of API call is needed to support type-checking + // on dimension label buffers. + QueryExperimental::set_data_buffer(*query_, b.name, data_ptr, data_nelem); + + if (b.isvar) { + size_t offsets_size = b.offsets.size() - offsets_read; + uint64_t *offsets_ptr = (uint64_t *)b.offsets.data() + offsets_read; + + query_->set_offsets_buffer(b.name, (uint64_t *)(offsets_ptr), + offsets_size); + } + if (b.isnullable) { + uint64_t validity_size = b.validity.size() - validity_vals_read; + uint8_t *validity_ptr = + (uint8_t *)b.validity.data() + validity_vals_read; + + query_->set_validity_buffer(b.name, validity_ptr, validity_size); + } + } + } + + void update_read_elem_num() { + auto result_elements = + QueryExperimental::result_buffer_elements_nullable_labels(*query_); + + for (const auto &read_info : result_elements) { + auto name = read_info.first; + uint64_t offset_elem_num = 0, data_vals_num = 0, validity_elem_num = 0; + std::tie(offset_elem_num, data_vals_num, validity_elem_num) = + read_info.second; + + BufferInfo &buf = buffers_.at(name); + + // TODO if we ever support per-attribute read offset bitsize + // then need to handle here. Currently this is hard-coded to + // 64-bit to match query config. + auto offset_ptr = buf.offsets.mutable_data(); + + if (buf.isvar) { + if (offset_elem_num > 0) { + // account for 'sm.var_offsets.extra_element' + offset_elem_num -= (use_arrow_) ? 1 : 0; + } + + if (buf.offsets_read > 0) { + if (offset_ptr[buf.offsets_read] == 0) { + auto last_size = (buf.data_vals_read * buf.elem_nbytes); + + for (uint64_t i = 0; i < offset_elem_num; i++) { + offset_ptr[buf.offsets_read + i] += last_size; + } + } + } + } + + buf.data_vals_read += data_vals_num; + buf.offsets_read += offset_elem_num; + buf.validity_vals_read += validity_elem_num; + + if ((Py_ssize_t)(buf.data_vals_read * buf.elem_nbytes) > + (Py_ssize_t)buf.data.size()) { + throw TileDBError( + "After read query, data buffer out of bounds: " + name + " (" + + std::to_string(buf.data_vals_read * buf.elem_nbytes) + " > " + + std::to_string(buf.data.size()) + ")"); + } + if ((Py_ssize_t)buf.offsets_read > buf.offsets.size()) { + throw TileDBError("After read query, offsets buffer out of bounds: " + + name + " (" + std::to_string(buf.offsets_read) + + " > " + std::to_string(buf.offsets.size()) + ")"); + } + if ((Py_ssize_t)buf.validity_vals_read > buf.validity.size()) { + throw TileDBError("After read query, validity buffer out of bounds: " + + name + " (" + std::to_string(buf.validity_vals_read) + + " > " + std::to_string(buf.validity.size()) + ")"); + } + } + } + + void reset_read_elem_num() { + for (auto &bp : buffers_) { + auto &buf = bp.second; + + buf.offsets_read = 0; + buf.data_vals_read = 0; + buf.validity_vals_read = 0; + } + } + + uint64_t get_max_retries() { + // should make this a templated getter for any key w/ default + std::string tmp_str; + size_t max_retries; + try { + tmp_str = ctx_.config().get("py.max_incomplete_retries"); + max_retries = std::stoull(tmp_str); + } catch (const std::invalid_argument &e) { + (void)e; + throw TileDBError( + "Failed to convert 'py.max_incomplete_retries' to uint64_t ('" + + tmp_str + "')"); + } catch (tiledb::TileDBError &e) { + (void)e; + max_retries = 100; + } + return max_retries; + } + + void resubmit_read() { + tiledb_query_status_details_t status_details; + tiledb_query_get_status_details(ctx_.ptr().get(), query_.get()->ptr().get(), + &status_details); + + if (status_details.incomplete_reason == TILEDB_REASON_USER_BUFFER_SIZE) { + auto start_incomplete_buffer_update = + std::chrono::high_resolution_clock::now(); + for (auto &bp : buffers_) { + auto &buf = bp.second; + + // Check if values buffer should be resized + if ((buf.data_vals_read == 0) || + (int64_t)(buf.data_vals_read * buf.elem_nbytes) > + (buf.data.nbytes() + 1) / 2) { + size_t new_size = buf.data.size() * 2; + buf.data.resize({new_size}, false); + } + + // Check if offset buffer should be resized + if ((buf.isvar && buf.offsets_read == 0) || + ((int64_t)(buf.offsets_read * sizeof(uint64_t)) > + (buf.offsets.nbytes() + 1) / 2)) { + size_t new_offsets_size = buf.offsets.size() * 2; + buf.offsets.resize({new_offsets_size}, false); + } + + // Check if validity buffer should be resized + if ((buf.isnullable && buf.validity_vals_read == 0) || + ((int64_t)(buf.validity_vals_read * sizeof(uint8_t)) > + (buf.validity.nbytes() + 1) / 2)) { + size_t new_validity_size = buf.validity.size() * 2; + buf.validity.resize({new_validity_size}, false); + } + } + + // note: this block confuses lldb. continues from here unless bp set after + // block. + set_buffers(); + + if (g_stats) { + auto now = std::chrono::high_resolution_clock::now(); + g_stats.get() + ->counters["py.read_query_incomplete_buffer_resize_time"] += + now - start_incomplete_buffer_update; + } + } + + { + py::gil_scoped_release release; + query_->submit(); + } + + if (query_->query_status() == Query::Status::UNINITIALIZED) { + TPY_ERROR_LOC("Unexpected state: Query::Submit returned uninitialized"); + } + + update_read_elem_num(); + + return; + } + + void resize_output_buffers() { + // resize the output buffers to match the final read total + // the higher level code uses the size of the buffers to + // determine how much to unpack, but we may have over-allocated + + // account for the extra element at the end of offsets in arrow mode + size_t arrow_offset_size = use_arrow_ ? 1 : 0; + + for (auto &bp : buffers_) { + auto name = bp.first; + auto &buf = bp.second; + + Py_ssize_t final_data_nbytes = buf.data_vals_read * buf.elem_nbytes; + Py_ssize_t final_offsets_count = buf.offsets_read + arrow_offset_size; + Py_ssize_t final_validity_count = buf.validity_vals_read; + + assert(final_data_nbytes <= buf.data.size()); + assert(final_offsets_count <= + (Py_ssize_t)(buf.offsets.size() + arrow_offset_size)); + + buf.data.resize({final_data_nbytes}); + buf.offsets.resize({final_offsets_count}); + buf.validity.resize({final_validity_count}); + + if (use_arrow_) { + if (retries_ > 0) { + // we need to write the final size to the final offset slot + // because core doesn't track size between incomplete submits + buf.offsets.mutable_data()[buf.offsets_read] = final_data_nbytes; + } + + // reset bytes-read so that set_buffers uses the full buffer size + buf.data_vals_read = 0; + buf.offsets_read = 0; + buf.validity_vals_read = 0; + } + } + if (use_arrow_) { + // this is a very light hack: + // call set_buffers here to reset the buffers to the *full* + // buffer in case there were incomplete queries. without this call, + // the active tiledb::Query only knows about the buffer ptr/size + // for the *last* submit loop, so we don't get full result set. + // ArrowAdapter gets the buffer sizes from tiledb::Query. + set_buffers(); + } + } + + void allocate_buffers() { + // allocate buffers for dims + // - we want to return dims first, if any requested + for (size_t dim_idx = 0; dim_idx < domain_->ndim(); dim_idx++) { + auto dim = domain_->dimension(dim_idx); + if ((std::find(dims_.begin(), dims_.end(), dim.name()) == dims_.end()) && + // we need to also check if this is an attr for backward-compatibility + (std::find(attrs_.begin(), attrs_.end(), dim.name()) == + attrs_.end())) { + continue; + } + alloc_buffer(dim.name()); + } + + // allocate buffers for label dimensions + for (const auto &label_data : label_input_buffer_data_) { + alloc_buffer(label_data.first); + } + + // allocate buffers for attributes + // - schema.attributes() is unordered, but we need to return ordered + // results + for (size_t attr_idx = 0; attr_idx < array_schema_->attribute_num(); + attr_idx++) { + auto attr = array_schema_->attribute(attr_idx); + if (std::find(attrs_.begin(), attrs_.end(), attr.name()) == + attrs_.end()) { + continue; + } + alloc_buffer(attr.name()); + } + } + + void submit_read() { + if (retries_ > 0 && + query_->query_status() == tiledb::Query::Status::INCOMPLETE) { + buffers_.clear(); + assert(buffers_.size() == 0); + + buffers_order_.clear(); + // reset_read_elem_num(); + } else if (buffers_.size() != 0) { + // we have externally imported buffers + return; + } + + // start time + auto start = std::chrono::high_resolution_clock::now(); + + // Initiate a metadata API request to make libtiledb fetch the + // metadata ahead of time. In some queries we know we will always + // access metadata, so initiating this call saves time when loading + // from remote arrays because metadata i/o is lazy in core. + /* + // This section is disabled pending final disposition of SC-11720 + // This call is not currently safe as of TileDB 2.5, and has caused + // reproducible deadlocks with the subesequent calls to + // Array::est_result_sizes from the main thread. + // + std::future metadata_num_preload; + if (preload_metadata_) { + metadata_num_preload = std::async( + std::launch::async, [this]() { return array_->metadata_num(); }); + } + */ + + allocate_buffers(); + + // set the buffers on the Query + set_buffers(); + + size_t max_retries = get_max_retries(); + + auto start_submit = std::chrono::high_resolution_clock::now(); + { + py::gil_scoped_release release; + query_->submit(); + } + + if (query_->query_status() == Query::Status::UNINITIALIZED) { + TPY_ERROR_LOC("Unexpected state: Query::Submit returned uninitialized"); + } + + if (g_stats) { + auto now = std::chrono::high_resolution_clock::now(); + g_stats.get()->counters["py.core_read_query_initial_submit_time"] += + now - start_submit; + } + + // update the BufferInfo read-counts to match the query results read + update_read_elem_num(); + + // fetch the result of the metadata get task + // this will block if not yet completed + /* + // disabled, see comment above + if (preload_metadata_) { + metadata_num_preload.get(); + } + */ + + auto incomplete_start = std::chrono::high_resolution_clock::now(); + + // TODO: would be nice to have a callback here for custom realloc strategy + while (!return_incomplete_ && + query_->query_status() == Query::Status::INCOMPLETE) { + if (++retries_ > max_retries) + TPY_ERROR_LOC( + "Exceeded maximum retries ('py.max_incomplete_retries': '" + + std::to_string(max_retries) + "')"); + + resubmit_read(); + } + + if (g_stats && retries_ > 0) { + auto now = std::chrono::high_resolution_clock::now(); + g_stats.get()->counters["py.core_read_query_incomplete_retry_time"] += + now - incomplete_start; + } + + // update TileDB-Py stat counter + if (g_stats) { + auto now = std::chrono::high_resolution_clock::now(); + g_stats.get()->counters["py.core_read_query_total_time"] += now - start; + } + + if (g_stats) { + g_stats.get()->counters["py.query_retries_count"] += TimerType(retries_); + } + + resize_output_buffers(); + + if (return_incomplete_) { + // increment in case we submit again + retries_++; + } + } + + py::array unpack_buffer(std::string name, py::array buf, + py::array_t off) { + auto start = std::chrono::high_resolution_clock::now(); + + if (off.size() < 1) + TPY_ERROR_LOC(std::string("Unexpected empty offsets array ('") + name + + "')"); + + auto dtype = buffer_dtype(name); + bool is_unicode = dtype.is(py::dtype("U")); + bool is_str = dtype.is(py::dtype("S")); + if (is_unicode || is_str) { + dtype = py::dtype("O"); + } + + // Hashmap for string deduplication + // fastest so far: + typedef tsl::robin_map MapType; + MapType map; + std::vector object_v; + if (is_unicode) { + map.reserve(size_t(off.size() / 10) + 1); + } + + auto result_array = py::array(py::dtype("O"), off.size()); + auto result_p = (py::object *)result_array.mutable_data(); + uint64_t last = 0; + uint64_t cur = 0; + size_t size = 0; + uint64_t create = 0; + + auto off_data = off.data(); + last = off_data[0]; // initial should always be 0 + for (auto i = 1; i < off.size() + 1; i++) { + if (i == off.size()) + cur = buf.nbytes(); + else { + cur = off_data[i]; + } + + size = cur - last; + + py::object o; + auto data_ptr = (char *)buf.data() + last; + if (is_unicode) + if (size == 0 || (data_ptr[0] == '\0' && size == 1)) { + o = py::str(""); + } else { + if (!deduplicate_) { + o = py::str(data_ptr, size); + } else { + auto v = std::string_view{data_ptr, size}; + auto h = std::hash()(v); + auto needle = map.find(h); + if (needle == map.end()) { + o = py::str(data_ptr, size); + map.insert(needle, {h, create}); + object_v.push_back(o); + create++; + } else { + auto idx = needle->second; + o = object_v[idx]; + } + } + } + else if (is_str) + if (size == 0 || (data_ptr[0] == '\0' && size == 1)) { + o = py::bytes(""); + } else { + o = py::bytes(data_ptr, size); + } + else { + o = py::array(py::dtype("uint8"), size, data_ptr); + o.attr("dtype") = dtype; + } + + result_p[i - 1] = o; + last = cur; + } + + if (g_stats) { + auto now = std::chrono::high_resolution_clock::now(); + g_stats.get()->counters["py.buffer_conversion_time"] += now - start; + } + + return result_array; + } + + void submit_write() {} + + void submit() { + if (array_->query_type() == TILEDB_READ) { + submit_read(); + } else if (array_->query_type() == TILEDB_WRITE) { + submit_write(); + } else if (array_->query_type() == TILEDB_DELETE) { + query_->submit(); + if (query_->query_status() == Query::Status::UNINITIALIZED) { + TPY_ERROR_LOC("Unexpected state: Query::Submit returned uninitialized"); + } + } else { + TPY_ERROR_LOC("Unknown query type!") + } + } + + py::dict results() { + py::dict results; + for (auto &buffer_name : buffers_order_) { + auto bp = buffers_.at(buffer_name); + results[py::str(buffer_name)] = + py::make_tuple(bp.data, bp.offsets, bp.validity); + } + return results; + } + + std::unique_ptr buffer_to_pa(std::string name) { + if (query_->query_status() != tiledb::Query::Status::COMPLETE) + TPY_ERROR_LOC("Cannot convert buffers unless Query is complete"); + + tiledb::arrow::ArrowAdapter adapter(&ctx_, query_.get()); + + std::unique_ptr pa_pair(new PAPair()); + + adapter.export_buffer(name.c_str(), &(pa_pair->array_), &(pa_pair->schema_), + nullptr, nullptr); + pa_pair->exported_ = true; + + return pa_pair; + } + + py::object buffers_to_pa_table() { + using namespace pybind11::literals; + + auto pa = py::module::import("pyarrow"); + auto pa_array_import = pa.attr("Array").attr("_import_from_c"); + + tiledb::arrow::ArrowAdapter adapter(&ctx_, query_.get()); + + py::list names; + py::list results; + for (auto &buffer_name : buffers_order_) { + BufferInfo &buffer_info = buffers_.at(buffer_name); + + auto buffer_holder = new BufferHolder( + buffer_info.data, buffer_info.validity, buffer_info.offsets); + + ArrowArray c_pa_array; + ArrowSchema c_pa_schema; + adapter.export_buffer(buffer_name.c_str(), + static_cast(&c_pa_array), + static_cast(&c_pa_schema), + (tiledb::arrow::ArrowAdapter::release_cb) + BufferHolder::free_buffer_holder, + buffer_holder); + + if (is_nullable(buffer_name)) { + // count zeros before converting to bitmap + c_pa_array.null_count = count_zeros(buffer_info.validity); + // convert to bitmap + buffer_info.validity = uint8_bool_to_uint8_bitmap(buffer_info.validity); + c_pa_array.buffers[0] = buffer_info.validity.data(); + c_pa_array.n_buffers = is_var(buffer_name) ? 3 : 2; + c_pa_schema.flags |= ARROW_FLAG_NULLABLE; + } else if (!is_var(buffer_name)) { + // reset the number of buffers for non-nullable data + c_pa_array.n_buffers = 2; + } + + // work around for SC-11522: metadata field must be set to nullptr + c_pa_schema.metadata = nullptr; + py::object pa_array = pa_array_import(py::int_((ptrdiff_t)&c_pa_array), + py::int_((ptrdiff_t)&c_pa_schema)); + + results.append(pa_array); + names.append(buffer_name); + } + + auto pa_table = + pa.attr("Table").attr("from_arrays")(results, "names"_a = names); + return pa_table; + } + + py::object is_incomplete() { + if (!query_) { + throw TileDBPyError("Internal error: PyQuery not initialized!"); + } + return py::cast(query_->query_status() == + tiledb::Query::Status::INCOMPLETE); + } + + py::object estimated_result_sizes() { + // vector of names to estimate + std::vector estim_names; + + for (size_t dim_idx = 0; dim_idx < domain_->ndim(); dim_idx++) { + auto dim = domain_->dimension(dim_idx); + if ((std::find(dims_.begin(), dims_.end(), dim.name()) == dims_.end()) && + // we need to also check if this is an attr for backward-compatibility + (std::find(attrs_.begin(), attrs_.end(), dim.name()) == + attrs_.end())) { + continue; + } + estim_names.push_back(dim.name()); + } + + // iterate by idx: schema.attributes() is unordered, but we need to + // return ordered results + for (size_t attr_idx = 0; attr_idx < array_schema_->attribute_num(); + attr_idx++) { + auto attr = array_schema_->attribute(attr_idx); + if (std::find(attrs_.begin(), attrs_.end(), attr.name()) == + attrs_.end()) { + continue; + } + estim_names.push_back(attr.name()); + } + + py::dict results; + + for (auto const &name : estim_names) { + size_t est_offsets = 0, est_data_bytes = 0; + + if (is_var(name)) { + query_->est_result_size_var(name); + auto est_sizes = query_->est_result_size_var(name); + est_offsets = std::get<0>(est_sizes); + est_data_bytes = std::get<1>(est_sizes); + } else { + est_data_bytes = query_->est_result_size(name); + } + results[py::str(name)] = py::make_tuple(est_offsets, est_data_bytes); + } + + return std::move(results); + } + + py::array _test_array() { + py::array_t a; + a.resize({10}); + + a.resize({20}); + return std::move(a); + } + + uint64_t _test_init_buffer_bytes() { + // test helper to get the configured init_buffer_bytes + return init_buffer_bytes_; + } + uint64_t _test_alloc_max_bytes() { + // test helper to get the configured init_buffer_bytes + return alloc_max_bytes_; + } + + std::string get_stats() { return query_->stats(); } + +private: + void init_config() { + // get config parameters + std::string tmp_str; + if (config_has_key(ctx_.config(), "py.init_buffer_bytes")) { + tmp_str = ctx_.config().get("py.init_buffer_bytes"); + try { + init_buffer_bytes_ = std::stoull(tmp_str); + } catch (const std::invalid_argument &e) { + (void)e; + throw std::invalid_argument( + "Failed to convert 'py.init_buffer_bytes' to uint64_t ('" + + tmp_str + "')"); + } + } + + if (config_has_key(ctx_.config(), "py.alloc_max_bytes")) { + tmp_str = ctx_.config().get("py.alloc_max_bytes"); + try { + alloc_max_bytes_ = std::stoull(tmp_str); + } catch (const std::invalid_argument &e) { + (void)e; + throw std::invalid_argument( + "Failed to convert 'py.alloc_max_bytes' to uint64_t ('" + tmp_str + + "')"); + } + if (alloc_max_bytes_ < pow(1024, 2)) { + throw std::invalid_argument("Invalid parameter: 'py.alloc_max_bytes' " + "must be >= 1 MB (1024 ** 2 bytes)"); + }; + } + + if (config_has_key(ctx_.config(), "py.deduplicate")) { + tmp_str = ctx_.config().get("py.deduplicate"); + if (tmp_str == "true") { + deduplicate_ = true; + } else if (tmp_str == "false") { + deduplicate_ = false; + } else { + throw std::invalid_argument( + "Failed to convert configuration 'py.deduplicate' to bool ('" + + tmp_str + "')"); + } + } + + if (config_has_key(ctx_.config(), "py.exact_init_buffer_bytes")) { + tmp_str = ctx_.config().get("py.exact_init_buffer_bytes"); + if (tmp_str == "true") { + exact_init_bytes_ = true; + } else if (tmp_str == "false") { + exact_init_bytes_ = false; + } else { + throw std::invalid_argument("Failed to convert configuration " + "'py.exact_init_buffer_bytes' to bool ('" + + tmp_str + "')"); + } + } + + if (config_has_key(ctx_.config(), "py.use_arrow")) { + tmp_str = ctx_.config().get("py.use_arrow"); + if (tmp_str == "True") { + use_arrow_ = true; + } else if (tmp_str == "False") { + use_arrow_ = false; + } else { + throw std::invalid_argument( + "Failed to convert configuration 'py.use_arrow' to bool ('" + + tmp_str + "')"); + } + } + } + +}; // namespace tiledbpy + +void init_stats() { + g_stats.reset(new StatsInfo()); + + auto stats_counters = g_stats.get()->counters; + stats_counters["py.core_read_query_initial_submit_time"] = TimerType(); + stats_counters["py.core_read_query_total_time"] = TimerType(); + stats_counters["py.core_read_query_incomplete_retry_time"] = TimerType(); + stats_counters["py.buffer_conversion_time"] = TimerType(); + stats_counters["py.read_query_incomplete_buffer_resize_time"] = TimerType(); + stats_counters["py.query_retries_count"] = TimerType(); +} + +void disable_stats() { g_stats.reset(nullptr); } + +bool stats_enabled() { return (bool)g_stats; } + +void increment_stat(std::string key, double value) { + auto &stats_counters = g_stats.get()->counters; + + if (stats_counters.count(key) == 0) + stats_counters[key] = TimerType(); + + auto &timer = stats_counters[key]; + auto incr = std::chrono::duration(value); + timer += incr; +} + +bool use_stats() { return (bool)g_stats; } + +py::object get_stats() { + if (!g_stats) { + TPY_ERROR_LOC("Stats counters are not uninitialized!") + } + + auto &stats_counters = g_stats.get()->counters; + + py::dict res; + for (auto iter = stats_counters.begin(); iter != stats_counters.end(); + ++iter) { + auto val = std::chrono::duration(iter->second); + res[py::str(iter->first)] = py::float_(val.count()); + } + return std::move(res); +} + +py::object python_internal_stats(bool dict = false) { + if (!g_stats) { + TPY_ERROR_LOC("Stats counters are not uninitialized!") + } + + auto counters = g_stats.get()->counters; + auto rq_time = counters["py.core_read_query_initial_submit_time"].count(); + + if (dict) { + py::dict stats; + + // core.cc is only tracking read time right now; don't output if we + // have no query submission time + if (rq_time == 0) { + return std::move(stats); + } + + for (auto &stat : counters) { + stats[py::str(stat.first)] = stat.second.count(); + } + + return std::move(stats); + } else { + std::ostringstream os; + + // core.cc is only tracking read time right now; don't output if we + // have no query submission time + if (rq_time == 0) { + return py::str(os.str()); + } + + os << std::endl; + os << "==== Python Stats ====" << std::endl << std::endl; + + for (auto &stat : counters) { + os << " " << stat.first << " : " << stat.second.count() << std::endl; + } + + return py::str(os.str()); + } +} + +py::str as_built_dump() { + tiledb_string_t *s; + int rc = tiledb_as_built_dump(&s); + if (rc != TILEDB_OK) { + TPY_ERROR_LOC("Could not dump as built."); + } + const char *data_ptr; + py::size_t length; + + tiledb_string_view(s, &data_ptr, &length); + py::str res(data_ptr, length); + tiledb_string_free(&s); + + return res; +} + +auto walk_callback = [](const char *path_ptr, tiledb_object_t obj, + void *pyfunc) { + std::string my_path(path_ptr); + std::string my_objtype; + if (obj == TILEDB_GROUP) { + my_objtype = "group"; + } else if (obj == TILEDB_ARRAY) { + my_objtype = "array"; + } else { + return 0; + } + try { + py::function func = py::cast((PyObject *)pyfunc); + func(my_path, my_objtype); + } catch (py::stop_iteration) { + return 0; + } + return 1; +}; + +void init_core(py::module &m) { + init_query_condition(m); + + auto pq = + py::class_(m, "PyQuery") + .def(py::init()) + .def("add_label_buffer", &PyQuery::add_label_buffer) + .def("buffer_dtype", &PyQuery::buffer_dtype) + .def("results", &PyQuery::results) + .def("set_subarray", &PyQuery::set_subarray) + .def("set_cond", &PyQuery::set_cond) +#if defined(TILEDB_SERIALIZATION) + .def("set_serialized_query", &PyQuery::set_serialized_query) +#endif + .def("submit", &PyQuery::submit) + .def("unpack_buffer", &PyQuery::unpack_buffer) + .def("estimated_result_sizes", &PyQuery::estimated_result_sizes) + .def("get_stats", &PyQuery::get_stats) + .def("_allocate_buffers", &PyQuery::allocate_buffers) + .def("_get_buffers", &PyQuery::get_buffers) + .def("_buffer_to_pa", &PyQuery::buffer_to_pa) + .def("_buffers_to_pa_table", &PyQuery::buffers_to_pa_table) + .def("_test_array", &PyQuery::_test_array) + .def("_test_err", + [](py::object self, std::string s) { throw TileDBPyError(s); }) + .def_readwrite("_preload_metadata", &PyQuery::preload_metadata_) + .def_readwrite("_return_incomplete", &PyQuery::return_incomplete_) + // properties + .def_property_readonly("is_incomplete", &PyQuery::is_incomplete) + .def_property_readonly("_test_init_buffer_bytes", + &PyQuery::_test_init_buffer_bytes) + .def_property_readonly("_test_alloc_max_bytes", + &PyQuery::_test_alloc_max_bytes) + .def_readonly("retries", &PyQuery::retries_); + + py::class_(m, "PyAgg") + .def(py::init(), + "ctx"_a, "py_array"_a, "py_layout"_a, "attr_to_aggs_input"_a) + .def("set_subarray", &PyAgg::set_subarray) + .def("set_cond", &PyAgg::set_cond) + .def("get_aggregate", &PyAgg::get_aggregate); + + py::class_(m, "PAPair") + .def(py::init()) + .def("get_array", &PAPair::get_array) + .def("get_schema", &PAPair::get_schema); + + m.def("array_to_buffer", &convert_np); + + m.def("init_stats", []() { + Stats::enable(); + init_stats(); + }); + m.def("disable_stats", []() { + Stats::disable(); + disable_stats(); + }); + m.def("stats_enabled", &stats_enabled); + m.def("reset_stats", []() { + Stats::reset(); + init_stats(); + }); + m.def("stats_raw_dump_str", []() { + std::string out; + Stats::raw_dump(&out); + return out; + }); + m.def("stats_dump_str", []() { + std::string out; + Stats::dump(&out); + return out; + }); + m.def("python_internal_stats", &python_internal_stats, + py::arg("dict") = false); + m.def("increment_stat", &increment_stat); + m.def("get_stats", &get_stats); + m.def("use_stats", &use_stats); + m.def("datatype_size", &tiledb_datatype_size); + m.def("as_built_dump", &as_built_dump); + m.def("object_type", + [](const std::string &uri, const Context &ctx) -> py::object { + tiledb_object_t res; + ctx.handle_error( + tiledb_object_type(ctx.ptr().get(), uri.c_str(), &res)); + if (res == TILEDB_ARRAY) { + return py::str("array"); + } else if (res == TILEDB_GROUP) { + return py::str("group"); + } + return py::none(); + }); + m.def("ls", + [](const std::string &path, py::function func, const Context &ctx) { + ctx.handle_error(tiledb_object_ls(ctx.ptr().get(), path.c_str(), + walk_callback, (void *)func.ptr())); + }); + m.def("walk", [](const std::string path, py::function func, + const std::string order, const Context &ctx) { + tiledb_walk_order_t walk_order; + if (order == "postorder") { + walk_order = TILEDB_POSTORDER; + } else if (order == "preorder") { + walk_order = TILEDB_PREORDER; + } else { + throw TileDBError("unknown walk order " + order); + } + ctx.handle_error(tiledb_object_walk(ctx.ptr().get(), path.c_str(), + walk_order, walk_callback, + (void *)func.ptr())); + }); + m.def("remove", &Object::remove); + m.def("move", &Object::move); + + /* + We need to make sure C++ TileDBError is translated to a correctly-typed py + error. Note that using py::exception(..., "TileDBError") creates a new + exception in the *readquery* module, so we must import to reference. +*/ + static auto tiledb_py_error = + (py::object)py::module::import("tiledb").attr("TileDBError"); + + py::register_exception_translator([](std::exception_ptr p) { + try { + if (p) + std::rethrow_exception(p); + } catch (const TileDBPyError &e) { + PyErr_SetString(tiledb_py_error.ptr(), e.what()); + } catch (const tiledb::TileDBError &e) { + PyErr_SetString(tiledb_py_error.ptr(), e.what()); + } catch (py::builtin_exception &e) { + // just forward the error + throw; + //} catch (std::runtime_error &e) { + // std::cout << "unexpected runtime_error: " << e.what() << std::endl; + } + }); +}; +}; // namespace tiledbpy diff --git a/testbed/TileDB-Inc__TileDB-Py/tiledb/ctx.py b/testbed/TileDB-Inc__TileDB-Py/tiledb/ctx.py new file mode 100644 index 0000000000000000000000000000000000000000..b4898f3767e4489624e068c1f7702802ba3a221c --- /dev/null +++ b/testbed/TileDB-Inc__TileDB-Py/tiledb/ctx.py @@ -0,0 +1,607 @@ +import io +import sys +from contextlib import contextmanager +from contextvars import ContextVar +from typing import Union + +import tiledb +import tiledb.cc as lt + +_ctx_var = ContextVar("ctx") + +already_warned = False +_needs_fork_wrapper = sys.platform != "win32" and sys.version_info < (3, 12) + + +class Config(lt.Config): + """TileDB Config class + + The Config object stores configuration parameters for both TileDB Embedded + and TileDB-Py. + + For TileDB Embedded parameters, see: + + https://docs.tiledb.com/main/how-to/configuration#configuration-parameters + + The following configuration options are supported by TileDB-Py: + + - `py.init_buffer_bytes`: + + Initial allocation size in bytes for attribute and dimensions buffers. + If result size exceed the pre-allocated buffer(s), then the query will return + incomplete and TileDB-Py will allocate larger buffers and resubmit. + Specifying a sufficiently large buffer size will often improve performance. + Default 10 MB (1024**2 * 10). + + - `py.use_arrow`: + + Use `pyarrow` from the Apache Arrow project to convert + query results into Pandas dataframe format when requested. + Default `True`. + + - `py.deduplicate`: + + Attempt to deduplicate Python objects during buffer + conversion to Python. Deduplication may reduce memory usage for datasets + with many identical strings, at the cost of some performance reduction + due to hash calculation/lookup for each object. + + Unknown parameters will be ignored! + + :param dict params: Set parameter values from dict like object + :param str path: Set parameter values from persisted Config parameter file + """ + + def __init__(self, params: dict = None, path: str = None): + super().__init__() + if path is not None: + self.load(path) + if params is not None: + self.update(params) + + @staticmethod + def load(uri: str): + """Constructs a Config class instance from config parameters loaded from a local Config file + + :parameter str uri: a local URI config file path + :rtype: tiledb.Config + :return: A TileDB Config instance with persisted parameter values + :raises TypeError: `uri` cannot be converted to a unicode string + :raises: :py:exc:`tiledb.TileDBError` + + """ + return lt.Config(uri) + + def __setitem__(self, key: str, value: str): + """Sets a config parameter value. + + :param str key: Name of parameter to set + :param str value: Value of parameter to set + :raises TypeError: `key` or `value` cannot be encoded into a UTF-8 string + :raises: :py:exc:`tiledb.TileDBError` + + """ + self.set(str(key), str(value)) + + def get(self, key: str, raise_keyerror: bool = True): + try: + return super().get(key) + except Exception: + if raise_keyerror: + raise KeyError(key) + else: + return None + + def __getitem__(self, key: str): + """Gets a config parameter value. + + :param str key: Name of parameter to get + :return: Config parameter value string + :rtype str: + :raises TypeError: `key` cannot be encoded into a UTF-8 string + :raises KeyError: Config parameter not found + :raises: :py:exc:`tiledb.TileDBError` + + """ + return self.get(key, True) + + def __delitem__(self, key: str): + """ + Removes a configured parameter (resetting it to its default). + + :param str key: Name of parameter to reset. + :raises TypeError: `key` cannot be encoded into a UTF-8 string + + """ + self.unset(key) + + def __iter__(self): + """Returns an iterator over the Config parameters (keys)""" + return ConfigKeys(self) + + def __len__(self): + """Returns the number of parameters (keys) held by the Config object""" + return sum(1 for _ in self) + + def __eq__(self, config): + if not isinstance(config, Config): + return False + keys = set(self.keys()) + okeys = set(config.keys()) + if keys != okeys: + return False + for k in keys: + val, oval = self[k], config[k] + if val != oval: + return False + return True + + unserialized_params_ = { + "vfs.azure.storage_account_name", + "vfs.azure.storage_account_key", + "vfs.azure.storage_sas_token", + "vfs.s3.proxy_username", + "vfs.s3.proxy_password", + "vfs.s3.aws_access_key_id", + "vfs.s3.aws_secret_access_key", + "vfs.s3.aws_session_token", + "vfs.s3.aws_role_arn", + "vfs.s3.aws_external_id", + "vfs.s3.aws_load_frequency", + "vfs.s3.aws_session_name", + "vfs.gcs.service_account_key", + "vfs.gcs.workload_identity_configuration", + "vfs.gcs.impersonate_service_account", + "rest.username", + "rest.password", + "rest.token", + } + + def __repr__(self): + colnames = ["Parameter", "Value"] + params = list(self.keys()) + values = list(map(repr, self.values())) + # for unserialized params, we don't want to print their values + values = [ + "*" * 10 if p in self.unserialized_params_ and v != "''" else v + for i, (p, v) in enumerate(zip(params, values)) + ] + colsizes = [ + max(len(colnames[0]), *map(len, (p for p in params))), + max(len(colnames[1]), *map(len, (v for v in values))), + ] + format_str = " | ".join("{{:<{}}}".format(i) for i in colsizes) + output = [] + output.append(format_str.format(colnames[0], colnames[1])) + output.append(format_str.format("-" * colsizes[0], "-" * colsizes[1])) + output.extend(format_str.format(p, v) for p, v in zip(params, values)) + return "\n".join(output) + + def _repr_html_(self): + output = io.StringIO() + + output.write("") + + output.write("") + output.write("") + output.write("") + output.write("") + + params = list(self.keys()) + values = list(map(repr, self.values())) + # for unserialized params, we don't want to print their values + values = [ + "*" * 10 if p in self.unserialized_params_ and v != "''" else v + for i, (p, v) in enumerate(zip(params, values)) + ] + + for p, v in zip(params, values): + output.write("") + output.write(f"") + output.write(f"") + output.write("") + + output.write("
ParameterValue
{p}{v}
") + + return output.getvalue() + + def items(self, prefix: str = ""): + """Returns an iterator object over Config parameters, values + + :param str prefix: return only parameters with a given prefix + :rtype: ConfigItems + :returns: iterator over Config parameter, value tuples + + """ + return ConfigItems(self, prefix=prefix) + + def keys(self, prefix: str = ""): + """Returns an iterator object over Config parameters (keys) + + :param str prefix: return only parameters with a given prefix + :rtype: ConfigKeys + :returns: iterator over Config parameter string keys + + """ + return ConfigKeys(self, prefix=prefix) + + def values(self, prefix: str = ""): + """Returns an iterator object over Config values + + :param str prefix: return only parameters with a given prefix + :rtype: ConfigValues + :returns: iterator over Config string values + + """ + return ConfigValues(self, prefix=prefix) + + def dict(self, prefix: str = ""): + """Returns a dict representation of a Config object + + :param str prefix: return only parameters with a given prefix + :rtype: dict + :return: Config parameter / values as a Python dict + + """ + return dict(ConfigItems(self, prefix=prefix)) + + def clear(self): + """Unsets all Config parameters (returns them to their default values)""" + for k in self.keys(): + del self[k] + + # def get(self, key, *args: Optional[str]): + # """Gets the value of a config parameter, or a default value. + + # :param str key: Config parameter + # :param args: return `arg` if Config does not contain parameter `key` + # :return: Parameter value, `arg` or None. + + # """ + # nargs = len(args) + # if nargs > 1: + # raise TypeError("get expected at most 2 arguments, got {}".format(nargs)) + # try: + # return self[key] + # except KeyError: + # return args[0] if nargs == 1 else None + + def update(self, odict: dict): + """Update a config object with parameter, values from a dict like object + + :param odict: dict-like object containing parameter, values to update Config. + + """ + super().update(dict(odict)) + + def from_file(self, path: str): + """Update a Config object with from a persisted config file + + :param path: A local Config file path + + """ + config = Config.load(path) + self.update(config) + + def save(self, uri: str): + """Persist Config parameter values to a config file + + :parameter str uri: a local URI config file path + :raises TypeError: `uri` cannot be converted to a unicode string + :raises: :py:exc:`tiledb.TileDBError` + + """ + self.save_to_file(uri) + + +class ConfigKeys: + """ + An iterator object over Config parameter strings (keys) + """ + + def __init__(self, config: Config, prefix: str = ""): + self.config_items = ConfigItems(config, prefix=prefix) + + def __iter__(self): + return self + + def __next__(self): + (k, _) = self.config_items.__next__() + return k + + +class ConfigValues: + """ + An iterator object over Config parameter value strings + """ + + def __init__(self, config: Config, prefix: str = ""): + self.config_items = ConfigItems(config, prefix=prefix) + + def __iter__(self): + return self + + def __next__(self): + (_, v) = self.config_items.__next__() + return v + + +class ConfigItems: + """ + An iterator object over Config parameter, values + + :param config: TileDB Config object + :type config: tiledb.Config + :param prefix: (default "") Filter paramter names with given prefix + :type prefix: str + + """ + + def __init__(self, config: Config, prefix: str = ""): + self.config = config + self.iter = config._iter(prefix) + + def __iter__(self): + return self.iter + + def __next__(self): + return self.iter.__next__() + + +class Ctx(lt.Context): + """Class representing a TileDB context. + + A TileDB context wraps a TileDB storage manager. + + :param config: Initialize Ctx with given config parameters + :type config: tiledb.Config or dict + + """ + + def __init__(self, config: Config = None): + _config = lt.Config() + + if config is not None: + if isinstance(config, lt.Config): + _config = config + elif isinstance(config, Config): + _config.update(config.dict()) + elif isinstance(config, dict): + _config.update(config) + else: + raise TypeError( + "Ctx's config argument expects type `tiledb.Config` or `dict`" + ) + + super().__init__(_config) + + self._set_default_tags() + + # The core tiledb library uses threads and it's easy + # to experience deadlocks when forking a process that is using + # tiledb. The project doesn't have a solution for this at the + # moment other than to avoid using fork(), which is the same + # recommendation that Python makes. Python 3.12 warns if you + # fork() when multiple threads are detected and Python 3.14 will + # make it so you never accidentally fork(): multiprocessing will + # default to "spawn" on Linux. + _ensure_os_fork_wrap() + + def __repr__(self): + return "tiledb.Ctx() [see Ctx.config() for configuration]" + + def config(self): + """Returns the Config instance associated with the Ctx.""" + new = Config.__new__(Config) + # bypass calling Config.__init__, call lt.Config.__init__ instead + lt.Config.__init__(new, super().config()) + return new + + def set_tag(self, key: str, value: str): + """Sets a (string, string) "tag" on the Ctx (internal).""" + super().set_tag(key, value) + + def _set_default_tags(self): + """Sets all default tags on the Ctx""" + self.set_tag("x-tiledb-api-language", "python") + self.set_tag( + "x-tiledb-api-language-version", + f"{sys.version_info.major}." + f"{sys.version_info.minor}." + f"{sys.version_info.micro}", + ) + self.set_tag("x-tiledb-api-sys-platform", sys.platform) + + def get_stats(self, print_out: bool = True, json: bool = False): + """Retrieves the stats from a TileDB context. + + :param print_out: Print string to console (default True), or return as string + :param json: Return stats JSON object (default: False) + """ + stats = super().get_stats() + + if json: + import json + + output = json.loads(stats) + else: + output = stats + + if print_out: + print(output) + else: + return output + + +class CtxMixin: + """ + Base mixin class for pure Python classes that extend PyBind11 TileDB classes. + + To use this class, a subclass must: + - Inherit from it first (i.e. `class Foo(CtxMixin, Bar)`, not `class Foo(Bar, CtxMixin)` + - Call super().__init__ by passing `ctx` (tiledb.Ctx or None) as first parameter and + zero or more pure Python positional parameters + """ + + def __init__(self, ctx, *args, _pass_ctx_to_super=True): + if not ctx: + ctx = default_ctx() + + if _pass_ctx_to_super: + super().__init__(ctx, *args) + else: + super().__init__(*args) + + # we set this here because if the super().__init__() constructor above fails, + # we don't want to set self._ctx + self._ctx = ctx + + @classmethod + def from_capsule(cls, ctx, capsule): + """Create an instance of this class from a PyCapsule instance""" + # bypass calling self.__init__, call CtxMixin.__init__ instead + self = cls.__new__(cls) + CtxMixin.__init__(self, ctx, capsule) + return self + + @classmethod + def from_pybind11(cls, ctx, lt_obj): + """Create an instance of this class from a PyBind11 instance""" + # bypass calling self.__init__, call CtxMixin.__init__ instead + self = cls.__new__(cls) + CtxMixin.__init__(self, ctx, lt_obj, _pass_ctx_to_super=False) + return self + + +def check_ipykernel_warn_once(): + """ + This function checks if we have imported ipykernel version < 6 in the + current process, and provides a warning that default_ctx/scope_ctx will + not work correctly due to a bug in IPython contextvar support.""" + global already_warned + if not already_warned: + try: + import warnings + + if "ipykernel" in sys.modules and tuple( + map(int, sys.modules["ipykernel"].__version__.split(".")) + ) < (6, 0): + warnings.warn( + "tiledb.default_ctx and scope_ctx will not function correctly " + "due to bug in IPython contextvar support. You must supply a " + "Ctx object to each function for custom configuration options. " + "Please consider upgrading to ipykernel >= 6!" + "Please see https://github.com/TileDB-Inc/TileDB-Py/issues/667 " + "for more information." + ) + except: + pass + finally: + already_warned = True + + +@contextmanager +def scope_ctx(ctx_or_config: Union["Ctx", "Config", dict] = None) -> "Ctx": + """ + Context manager for setting the default `tiledb.Ctx` context variable when entering + a block of code and restoring it to its previous value when exiting the block. + + :param ctx_or_config: :py:class:`tiledb.Ctx` or :py:class:`tiledb.Config` object + or dictionary with config parameters. + :return: Ctx + """ + check_ipykernel_warn_once() + + if ctx_or_config is not None and not ( + isinstance(ctx_or_config, tiledb.Ctx) + or isinstance(ctx_or_config, tiledb.Config) + or isinstance(ctx_or_config, dict) + ): + raise ValueError( + "scope_ctx takes in `tiledb.Ctx` object, `tiledb.Config` object, or " + "dictionary with config parameters." + ) + + if not isinstance(ctx_or_config, tiledb.Ctx): + ctx = tiledb.Ctx(ctx_or_config) + else: + ctx = ctx_or_config + token = _ctx_var.set(ctx) + try: + yield _ctx_var.get() + finally: + _ctx_var.reset(token) + + +def default_ctx(config: Union["Config", dict] = None) -> "Ctx": + """ + Returns, and optionally initializes, the default `tiledb.Ctx` context variable. + + This Ctx object is used by Python API functions when no `ctx` keyword argument + is provided. Most API functions accept an optional `ctx` kwarg, but that is typically + only necessary in advanced usage with multiple contexts per program. + + For initialization, this function must be called before any other tiledb functions. + The initialization call accepts a :py:class:`tiledb.Config` object to override the + defaults for process-global parameters. + + :param config: :py:class:`tiledb.Config` object or dictionary with config parameters. + :return: Ctx + """ + check_ipykernel_warn_once() + + if config is not None and not ( + isinstance(config, tiledb.Config) or isinstance(config, dict) + ): + raise ValueError( + "default_ctx takes in `tiledb.Config` object or " + "dictionary with config parameters." + ) + + try: + ctx = _ctx_var.get() + if config is not None: + raise tiledb.TileDBError("Global context already initialized!") + + # The core tiledb library uses threads and it's easy + # to experience deadlocks when forking a process that is using + # tiledb. The project doesn't have a solution for this at the + # moment other than to avoid using fork(), which is the same + # recommendation that Python makes. Python 3.12 warns if you + # fork() when multiple threads are detected and Python 3.14 will + # make it so you never accidentally fork(): multiprocessing will + # default to "spawn" on Linux. + _ensure_os_fork_wrap() + except LookupError: + ctx = tiledb.Ctx(config) + _ctx_var.set(ctx) + return ctx + + +def _ensure_os_fork_wrap(): + global _needs_fork_wrapper + if _needs_fork_wrapper: + import os + import warnings + from functools import wraps + + def warning_wrapper(func): + @wraps(func) + def wrapper(): + warnings.warn( + "TileDB is a multithreading library and deadlocks " + "are likely if fork() is called after a TileDB " + "context has been created (such as for array " + "access). To safely use TileDB with " + "multiprocessing or concurrent.futures, choose " + "'spawn' as the start method for child processes. " + "For example: " + "multiprocessing.set_start_method('spawn').", + UserWarning, + ) + return func() + + return wrapper + + os.fork = warning_wrapper(os.fork) + _needs_fork_wrapper = False diff --git a/testbed/TileDB-Inc__TileDB-Py/tiledb/current_domain.py b/testbed/TileDB-Inc__TileDB-Py/tiledb/current_domain.py new file mode 100644 index 0000000000000000000000000000000000000000..f00755f845a9138f78c1fe58674453057b7f71cb --- /dev/null +++ b/testbed/TileDB-Inc__TileDB-Py/tiledb/current_domain.py @@ -0,0 +1,58 @@ +import tiledb.cc as lt + +from .ctx import Ctx, CtxMixin +from .domain import Domain +from .ndrectangle import NDRectangle + + +class CurrentDomain(CtxMixin, lt.CurrentDomain): + """ + Represents a TileDB current domain. + """ + + def __init__(self, ctx: Ctx): + """Class representing the current domain of a TileDB Array. + + :param ctx: A TileDB Context + :raises tiledb.TileDBError: + """ + super().__init__(ctx) + + def _set_domain(self, domain: Domain): + self._domain = domain + + @property + def type(self): + """The type of the current domain. + + :rtype: tiledb.CurrentDomainType + """ + return self._type + + @property + def is_empty(self): + """Checks if the current domain is empty. + + :rtype: bool + """ + return self._is_empty() + + def set_ndrectangle(self, ndrect: NDRectangle): + """Sets an N-dimensional rectangle representation on a current domain. + + :param ndrect: The N-dimensional rectangle to be used. + :raises tiledb.TileDBError: + """ + self._set_ndrectangle(ndrect) + self._domain = ndrect._get_domain() + + @property + def ndrectangle(self): + """Gets the N-dimensional rectangle associated with the current domain object. + + :rtype: NDRectangle + :raises tiledb.TileDBError: + """ + ndrect = NDRectangle.from_pybind11(self._ctx, self._ndrectangle()) + ndrect._set_domain(self._domain) + return ndrect diff --git a/testbed/TileDB-Inc__TileDB-Py/tiledb/data_order.py b/testbed/TileDB-Inc__TileDB-Py/tiledb/data_order.py new file mode 100644 index 0000000000000000000000000000000000000000..9ff84a7486ee42ae924b919f7ff08f1f3dae1859 --- /dev/null +++ b/testbed/TileDB-Inc__TileDB-Py/tiledb/data_order.py @@ -0,0 +1,9 @@ +from enum import Enum + +import tiledb.cc as lt + + +class DataOrder(Enum): + increasing = lt.DataOrder.INCREASING_DATA + decreasing = lt.DataOrder.DECREASING_DATA + unordered = lt.DataOrder.UNORDERED_DATA diff --git a/testbed/TileDB-Inc__TileDB-Py/tiledb/dataframe_.py b/testbed/TileDB-Inc__TileDB-Py/tiledb/dataframe_.py new file mode 100644 index 0000000000000000000000000000000000000000..489bb10f5d4e899c26fb6ec9730efb3f6dea857d --- /dev/null +++ b/testbed/TileDB-Inc__TileDB-Py/tiledb/dataframe_.py @@ -0,0 +1,982 @@ +import copy +import json +import os +import warnings +from dataclasses import dataclass +from typing import Any, List, Optional, Union + +import numpy as np + +import tiledb +from tiledb.libtiledb import version as libtiledb_version + +from .datatypes import DataType + + +def check_dataframe_deps(): + pd_error = """Pandas version >= 1.0 and < 3.0 required for dataframe functionality. + Please `pip install pandas>=1.0,<3.0` to proceed.""" + pa_error = """PyArrow version >= 1.0 is suggested for dataframe functionality. + Please `pip install pyarrow>=1.0`.""" + + try: + import pandas as pd + except ImportError: + raise Exception(pd_error) + + from packaging.version import Version + + if Version(pd.__version__) < Version("1.0") or Version(pd.__version__) >= Version( + "3.0.0.dev0" + ): + raise Exception(pd_error) + + try: + import pyarrow as pa + + if Version(pa.__version__) < Version("1.0"): + warnings.warn(pa_error) + except ImportError: + warnings.warn(pa_error) + + +# Note: 'None' is used to indicate optionality for many of these options +# For example, if the `sparse` argument is unspecified we will default +# to False (dense) unless the input has string or heterogenous indexes. +TILEDB_KWARG_DEFAULTS = { + "ctx": None, + "sparse": None, + "index_dims": None, + "allows_duplicates": True, + "mode": "ingest", + "attr_filters": True, + "dim_filters": True, + "coords_filters": True, + "offsets_filters": True, + "full_domain": False, + "tile": None, + "row_start_idx": None, + "fillna": None, + "column_types": None, + "varlen_types": None, + "capacity": None, + "date_spec": None, + "cell_order": "row-major", + "tile_order": "row-major", + "timestamp": None, + "debug": None, +} + + +def parse_tiledb_kwargs(kwargs): + parsed_args = dict(TILEDB_KWARG_DEFAULTS) + + for key in TILEDB_KWARG_DEFAULTS.keys(): + if key in kwargs: + parsed_args[key] = kwargs.pop(key) + + return parsed_args + + +def _infer_dtype_from_pandas(values, column_name): + from pandas.api import types as pd_types + + inferred_dtype = pd_types.infer_dtype(values) + if inferred_dtype == "bytes": + return np.bytes_ + elif inferred_dtype == "string": + return " tile_max: + dim_max = np.datetime64(dtype_max - tile, date_unit) + elif np.issubdtype(dtype, np.integer): + tile_max = np.iinfo(np.uint64).max - tile + if np.uint64(dtype_max - dtype_min) > tile_max: + dim_max = dtype_max - tile + else: + dim_min, dim_max = None, None + + # TODO: simplify this logic and/or move to DataType.cast_tile_extent + if np.issubdtype(dtype, np.integer) or np.issubdtype(dtype, np.datetime64): + # we can't make a tile larger than the dimension range or lower than 1 + tile = max(1, min(tile, 1 + np.uint64(dim_max - dim_min))) + elif np.issubdtype(dtype, np.floating): + # this difference can be inf + with np.errstate(over="ignore"): + dim_range = dim_max - dim_min + if dim_range < tile: + tile = np.ceil(dim_range) + + return tiledb.Dim( + domain=(dim_min, dim_max), + # libtiledb only supports TILEDB_ASCII dimensions, so we must use + # nb.bytes_ which will force encoding on write + dtype=np.bytes_ if dtype == np.str_ else dtype, + tile=tile, + **kwargs, + ) + + +def _sparse_from_dtypes(dtypes, sparse=None): + if any(dtype in (np.bytes_, np.str_) for dtype in dtypes): + if sparse is False: + raise tiledb.TileDBError( + "Cannot create dense array with string-typed dimensions" + ) + if sparse is None: + return True + + dtype0 = next(iter(dtypes)) + if not all(dtype0 == dtype for dtype in dtypes): + if sparse is False: + raise tiledb.TileDBError( + "Cannot create dense array with heterogeneous dimension data types" + ) + if sparse is None: + return True + + # Fall back to default dense type if unspecified and not inferred from dimension types + return sparse if sparse is not None else False + + +def create_dims( + df, index_dims, column_infos, tile=None, full_domain=False, filters=None +): + check_dataframe_deps() + import pandas as pd + + per_dim_tile = isinstance(tile, dict) + if tile is not None: + tile_values = tile.values() if per_dim_tile else (tile,) + if not all(isinstance(v, (int, float)) for v in tile_values): + raise ValueError( + "Invalid tile kwarg: expected int or dict of column names mapped to ints. " + f"Got '{tile!r}'" + ) + + index = df.index + name_dtype_values = [] + dim_metadata = {} + + for name in index_dims or index.names: + if name in index.names: + values = index.get_level_values(name) + elif name in df.columns: + values = df[name] + else: + raise ValueError(f"Unknown column or index named {name!r}") + + if name in column_infos: + dtype = column_infos[name].dtype + else: + dtype = ColumnInfo.from_values(values).dtype + internal_dtype = dtype + + if name == "__tiledb_rows" and isinstance(index, pd.RangeIndex): + internal_dtype = np.dtype("uint64") + if name is None: + name = "__tiledb_rows" + + dim_metadata[name] = dtype + name_dtype_values.append((name, internal_dtype, values)) + + ndim = len(name_dtype_values) + default_dim_tile = ( + 10000 if ndim == 1 else 1000 if ndim == 2 else 100 if ndim == 3 else 10 + ) + + def get_dim_tile(name): + dim_tile = tile.get(name) if per_dim_tile else tile + return dim_tile if dim_tile is not None else default_dim_tile + + dims = [ + create_dim( + dtype=dtype, + values=values, + full_domain=full_domain, + tile=get_dim_tile(name), + name=name, + filters=_get_attr_dim_filters(name, filters), + ) + for name, dtype, values in name_dtype_values + ] + + return dims, dim_metadata + + +def write_array_metadata(array, attr_metadata=None, index_metadata=None): + """ + :param array: open, writable TileDB array + :param metadata: dict + :return: + """ + if attr_metadata: + attr_md_dict = {n: str(t) for n, t in attr_metadata.items()} + array.meta["__pandas_attribute_repr"] = json.dumps(attr_md_dict) + if index_metadata: + index_md_dict = {n: str(t) for n, t in index_metadata.items()} + array.meta["__pandas_index_dims"] = json.dumps(index_md_dict) + + +def _df_to_np_arrays(df, column_infos, fillna): + ret = {} + nullmaps = {} + for name, column in df.items(): + column_info = column_infos[name] + if fillna is not None and name in fillna: + column = column.fillna(fillna[name]) + + to_numpy_kwargs = {} + + if not column_info.var: + to_numpy_kwargs.update(dtype=column_info.dtype) + + if column_info.nullable: + # use default 0/empty for the dtype + to_numpy_kwargs.update(na_value=column_info.dtype.type()) + nullmaps[name] = (~column.isna()).to_numpy(dtype=np.uint8) + + if column_info.enumeration: + # Enumerations should get the numerical codes instead of converting enumeration values + ret[name] = column.cat.codes.to_numpy(**to_numpy_kwargs) + else: + ret[name] = column.to_numpy(**to_numpy_kwargs) + + return ret, nullmaps + + +def from_pandas(uri, dataframe, **kwargs): + """Create TileDB array at given URI from a Pandas dataframe + + Supports most Pandas series types, including nullable integers and + bools. + + :param uri: URI for new TileDB array + :param dataframe: pandas DataFrame + + :Keyword Arguments: + + * Any `pandas.read_csv `_ supported keyword argument + * **ctx** - A TileDB context + * **sparse** - (default True) Create sparse schema + * **chunksize** - (default None) Maximum number of rows to read at a time. Note that this is also a `pandas.read_csv` argument + which `tiledb.read_csv` checks for in order to correctly read a file batchwise. + * **index_dims** (``List[str]``) -- List of column name(s) to use as dimension(s) in TileDB array schema. This is the recommended way to create dimensions. + * **allows_duplicates** - Generated schema should allow duplicates + * **mode** - Creation mode, one of 'ingest' (default), 'schema_only', 'append' + * **attr_filters** - FilterList to apply to Attributes: FilterList or Dict[str -> FilterList] for any attribute(s). Unspecified attributes will use default. + * **dim_filters** - FilterList to apply to Dimensions: FilterList or Dict[str -> FilterList] for any dimensions(s). Unspecified dimensions will use default. + * **offsets_filters** - FilterList to apply to all offsets + * **full_domain** - Dimensions should be created with full range of the dtype + * **tile** - Dimension tiling: accepts either an int that applies the tiling to all dimensions or a dict("dim_name": int) to specifically assign tiling to a given dimension + * **row_start_idx** - Start index to start new write (for row-indexed ingestions). + * **fillna** - Value to use to fill holes + * **column_types** - Dictionary of {``column_name``: dtype} to apply dtypes to columns + * **varlen_types** - A set of {dtypes}; any column wihin the set is converted to a variable length attribute + * **capacity** - Schema capacity. + * **date_spec** - Dictionary of {``column_name``: format_spec} to apply to date/time columns which are not correctly inferred by pandas 'parse_dates'. Format must be specified using the Python format codes: https://docs.python.org/3/library/datetime.html#strftime-and-strptime-behavior + * **cell_order** - (default 'row-major) Schema cell order: 'row-major', 'col-major', or 'hilbert' + * **tile_order** - (default 'row-major) Schema tile order: 'row-major' or 'col-major' + * **timestamp** - Write TileDB array at specific timestamp. + + :raises: :py:exc:`tiledb.TileDBError` + :return: None + + """ + check_dataframe_deps() + + if "tiledb_args" in kwargs: + tiledb_args = kwargs.pop("tiledb_args") + else: + tiledb_args = parse_tiledb_kwargs(kwargs) + + ctx = tiledb_args.get("ctx") + if ctx is not None and not isinstance(ctx, tiledb.Ctx): + raise ValueError(f"`ctx` expected a TileDB Context object but saw {type(ctx)}") + + with tiledb.scope_ctx(ctx): + _from_pandas(uri, dataframe, tiledb_args) + + +def _from_pandas(uri, dataframe, tiledb_args): + import pandas as pd + + mode = tiledb_args.get("mode", "ingest") + + if mode != "append" and tiledb.array_exists(uri): + raise tiledb.TileDBError(f"Array URI '{uri}' already exists!") + + sparse = tiledb_args["sparse"] + index_dims = tiledb_args.get("index_dims") or () + row_start_idx = tiledb_args.get("row_start_idx") + + write = True + create_array = True + if mode is not None: + if mode == "schema_only": + write = False + elif mode == "append": + create_array = False + schema = tiledb.ArraySchema.load(uri) + if not schema.sparse and row_start_idx is None: + raise tiledb.TileDBError( + "Cannot append to dense array without 'row_start_idx'" + ) + elif mode != "ingest": + raise tiledb.TileDBError(f"Invalid mode specified ('{mode}')") + + # TODO: disentangle the full_domain logic + full_domain = tiledb_args.get("full_domain", False) + if sparse is False and (not index_dims or "index_col" not in tiledb_args): + full_domain = True + if full_domain is None and tiledb_args.get("nrows"): + full_domain = False + + date_spec = tiledb_args.get("date_spec") + if date_spec: + dataframe = dataframe.assign( + **{ + name: pd.to_datetime(dataframe[name], format=format) + for name, format in date_spec.items() + } + ) + + dataframe.columns = dataframe.columns.map(str) + column_infos = _get_column_infos( + dataframe, tiledb_args.get("column_types"), tiledb_args.get("varlen_types") + ) + + with tiledb.scope_ctx(tiledb_args.get("ctx")): + if create_array: + with warnings.catch_warnings(): + warnings.simplefilter("always") + _create_array( + uri, + dataframe, + sparse, + full_domain, + index_dims, + column_infos, + tiledb_args, + ) + + if write: + if tiledb_args.get("debug", True): + print(f"`tiledb.from_pandas` writing '{len(dataframe)}' rows") + + write_dict, nullmaps = _df_to_np_arrays( + dataframe, column_infos, tiledb_args.get("fillna") + ) + _write_array( + uri, + dataframe, + write_dict, + nullmaps, + create_array, + index_dims, + row_start_idx, + timestamp=tiledb_args.get("timestamp"), + ) + + +def _create_array(uri, df, sparse, full_domain, index_dims, column_infos, tiledb_args): + dims, dim_metadata = create_dims( + df, + index_dims, + column_infos, + full_domain=full_domain, + tile=tiledb_args.get("tile"), + filters=tiledb_args.get("dim_filters", True), + ) + sparse = _sparse_from_dtypes(dim_metadata.values(), sparse) + + # ignore any column used as a dim/index + attr_names = [c for c in df.columns if c not in index_dims] + attrs, attr_metadata = _get_attrs( + attr_names, column_infos, tiledb_args.get("attr_filters", True) + ) + enums = _get_enums(attr_names, column_infos) + + # create the ArraySchema + with warnings.catch_warnings(): + warnings.simplefilter("always") + coord_filter = tiledb_args.get("coords_filters", True) + schema = tiledb.ArraySchema( + sparse=sparse, + domain=tiledb.Domain(*dims), + attrs=attrs, + enums=enums, + cell_order=tiledb_args["cell_order"], + tile_order=tiledb_args["tile_order"], + coords_filters=None + if coord_filter is True + else _get_schema_filters(coord_filter), + offsets_filters=_get_schema_filters( + tiledb_args.get("offsets_filters", True) + ), + # 0 will use the libtiledb internal default + capacity=tiledb_args.get("capacity") or 0, + # don't set allows_duplicates=True for dense + allows_duplicates=sparse and tiledb_args.get("allows_duplicates", False), + ) + + tiledb.Array.create(uri, schema) + + # write the metadata so we can reconstruct df + with tiledb.open(uri, "w") as A: + write_array_metadata(A, attr_metadata, dim_metadata) + + +def _write_array( + uri, + df, + write_dict, + nullmaps, + create_array, + index_dims, + row_start_idx=None, + timestamp=None, +): + + with tiledb.open(uri, "w", timestamp=timestamp) as A: + for j in range(A.schema.nattr): + attr = A.schema.attr(j) + if attr.enum_label is not None: + enmr = A.enum(attr.enum_label).values() + df[attr.name] = df[attr.name].cat.set_categories(enmr) + write_dict[attr.name] = df[attr.name].cat.codes + + if A.schema.sparse: + coords = [] + for k in range(A.schema.ndim): + dim_name = A.schema.domain.dim(k).name + if ( + (not create_array or dim_name in index_dims) + and dim_name not in df.index.names + and dim_name != "__tiledb_rows" + ): + # this branch handles the situation where a user did not specify + # index_col and is using mode='append'. We would like to try writing + # with the columns corresponding to existing dimension name. + coords.append(write_dict.pop(dim_name)) + else: + coords.append(df.index.get_level_values(k)) + # TODO ensure correct col/dim ordering + tiledb.libtiledb._setitem_impl_sparse( + A, tuple(coords), write_dict, nullmaps + ) + + else: + if row_start_idx is None: + row_start_idx = 0 + row_end_idx = row_start_idx + len(df) + A._setitem_impl(slice(row_start_idx, row_end_idx), write_dict, nullmaps) + + +def open_dataframe(uri, *, attrs=None, use_arrow=None, idx=slice(None), ctx=None): + """Open TileDB array at given URI as a Pandas dataframe + + If the array was saved using tiledb.from_pandas, then columns + will be interpreted as non-primitive pandas or numpy types when + available. + + :param uri: + :return: dataframe constructed from given TileDB array URI + + **Example:** + + >>> import tiledb + >>> df = tiledb.open_dataframe("iris.tldb") + >>> tiledb.object_type("iris.tldb") + 'array' + """ + check_dataframe_deps() + + # TODO support `distributed=True` option? + with tiledb.open(uri, ctx=ctx) as A: + df = A.query(attrs=attrs, use_arrow=use_arrow, coords=True).df[idx] + + if attrs and list(df.columns) != list(attrs): + df = df[attrs] + + return df + + +def _iterate_csvs_pandas(csv_list, pandas_args): + """Iterate over a list of CSV files. Uses pandas.read_csv with pandas_args and returns + a list of dataframe(s) for each iteration, up to the specified 'chunksize' argument in + 'pandas_args' + """ + import pandas as pd + + assert "chunksize" in pandas_args + chunksize = pandas_args["chunksize"] + + rows_read = 0 + result_list = list() + + file_iter = iter(csv_list) + next_file = next(file_iter, None) + while next_file is not None: + df_iter = pd.read_csv(next_file, **pandas_args) + df_iter.chunksize = chunksize - rows_read + + df = next(df_iter, None) + while df is not None: + result_list.append(df) + rows_read += len(df) + df_iter.chunksize = chunksize - rows_read + + if rows_read == chunksize: + yield result_list + # start over + rows_read = 0 + df_iter.chunksize = chunksize + result_list = list() + + df = next(df_iter, None) + + next_file = next(file_iter, None) + if next_file is None and len(result_list) > 0: + yield result_list + + +def from_csv(uri: str, csv_file: Union[str, List[str]], **kwargs): + """ + Create TileDB array at given URI from a CSV file or list of files + + :param uri: URI for new TileDB array + :param csv_file: input CSV file or list of CSV files. + Note: multi-file ingestion requires a `chunksize` argument. Files will be read in batches of at least `chunksize` rows before writing to the TileDB array. + + :Keyword Arguments: + + * Any `pandas.read_csv `_ supported keyword argument + * **ctx** - A TileDB context + * **sparse** - (default True) Create sparse schema + * **index_dims** (``List[str]``) -- List of column name(s) to use as dimension(s) in TileDB array schema. This is the recommended way to create dimensions. (note: the Pandas ``read_csv`` argument ``index_col`` will be passed through if provided, which results in indexes that will be converted to dimnesions by default; however ``index_dims`` is preferred). + * **allows_duplicates** - Generated schema should allow duplicates + * **mode** - Creation mode, one of 'ingest' (default), 'schema_only', 'append' + * **attr_filters** - FilterList to apply to Attributes: FilterList or Dict[str -> FilterList] for any attribute(s). Unspecified attributes will use default. + * **dim_filters** - FilterList to apply to Dimensions: FilterList or Dict[str -> FilterList] for any dimensions(s). Unspecified dimensions will use default. + * **offsets_filters** - FilterList to apply to all offsets + * **full_domain** - Dimensions should be created with full range of the dtype + * **tile** - Dimension tiling: accepts either an int that applies the tiling to all dimensions or a dict("dim_name": int) to specifically assign tiling to a given dimension + * **row_start_idx** - Start index to start new write (for row-indexed ingestions). + * **fillna** - Value to use to fill holes + * **column_types** - Dictionary of {``column_name``: dtype} to apply dtypes to columns + * **varlen_types** - A set of {dtypes}; any column wihin the set is converted to a variable length attribute + * **capacity** - Schema capacity. + * **date_spec** - Dictionary of {``column_name``: format_spec} to apply to date/time columns which are not correctly inferred by pandas 'parse_dates'. Format must be specified using the Python format codes: https://docs.python.org/3/library/datetime.html#strftime-and-strptime-behavior + * **cell_order** - (default 'row-major) Schema cell order: 'row-major', 'col-major', or 'hilbert' + * **tile_order** - (default 'row-major) Schema tile order: 'row-major' or 'col-major' + * **timestamp** - Write TileDB array at specific timestamp. + + :return: None + + **Example:** + + >>> import tiledb + >>> tiledb.from_csv("iris.tldb", "iris.csv") + >>> tiledb.object_type("iris.tldb") + 'array' + """ + check_dataframe_deps() + import pandas + + if "tiledb_args" in kwargs: + tiledb_args = kwargs.get("tiledb_args") + else: + tiledb_args = parse_tiledb_kwargs(kwargs) + + multi_file = False + pandas_args = copy.deepcopy(kwargs) + + ########################################################################## + # set up common arguments + ########################################################################## + ctx = tiledb_args.get("ctx") + if ctx is not None and not isinstance(ctx, tiledb.Ctx): + raise ValueError(f"`ctx` expected a TileDB Context object but saw {type(ctx)}") + + if isinstance(csv_file, str) and not os.path.isfile(csv_file): + # for non-local files, use TileDB VFS i/o + vfs = tiledb.VFS(ctx=ctx) + csv_file = tiledb.FileIO(vfs, csv_file, mode="rb") + elif isinstance(csv_file, (list, tuple)): + # TODO may be useful to support a filter callback here + multi_file = True + + mode = tiledb_args.get("mode", None) + if mode is not None: + # For schema_only mode we need to pass a max read count into + # pandas.read_csv + # Note that 'nrows' is a pandas arg! + if mode == "schema_only" and "nrows" not in kwargs: + pandas_args["nrows"] = 500 + elif mode not in ["ingest", "append"]: + raise tiledb.TileDBError("Invalid mode specified ('{}')".format(mode)) + + with tiledb.scope_ctx(ctx): + if mode != "append" and tiledb.array_exists(uri): + raise tiledb.TileDBError("Array URI '{}' already exists!".format(uri)) + + # this is a pandas pass-through argument, do not pop! + chunksize = kwargs.get("chunksize", None) + + if multi_file and not (chunksize or mode == "schema_only"): + raise tiledb.TileDBError( + "Multiple input CSV files requires a 'chunksize' argument" + ) + + if multi_file: + input_csv_list = csv_file + else: + input_csv = csv_file + + ########################################################################## + # handle multi_file and chunked arguments + ########################################################################## + # we need to use full-domain for multi or chunked reads, because we + # won't get a chance to see the full range during schema creation + if multi_file or chunksize is not None: + if "nrows" not in kwargs: + tiledb_args["full_domain"] = True + + ########################################################################## + # read path + ########################################################################## + if multi_file: + if mode == "append": + pass + + rows_written = 0 + + # multi-file or chunked always writes to full domain + # TODO: allow specifying dimension range for schema creation + tiledb_args["full_domain"] = True + + for df_list in _iterate_csvs_pandas(input_csv_list, pandas_args): + if df_list is None: + break + df = pandas.concat(df_list) + if "index_col" not in tiledb_args and df.index.name is None: + df.index.name = "__tiledb_rows" + + tiledb_args["row_start_idx"] = rows_written + + from_pandas(uri, df, tiledb_args=tiledb_args, pandas_args=pandas_args) + + tiledb_args["mode"] = "append" + rows_written += len(df) + + if mode == "schema_only": + break + + elif chunksize is not None: + rows_written = 0 + # for chunked reads, we need to iterate over chunks + df_iter = pandas.read_csv(input_csv, **pandas_args) + df = next(df_iter, None) + while df is not None: + if "index_col" not in tiledb_args and df.index.name is None: + df.index.name = "__tiledb_rows" + + # tell from_pandas what row to start the next write + tiledb_args["row_start_idx"] = rows_written + + from_pandas(uri, df, tiledb_args=tiledb_args, pandas_args=pandas_args) + + tiledb_args["mode"] = "append" + rows_written += len(df) + + df = next(df_iter, None) + + else: + df = pandas.read_csv(csv_file, **kwargs) + if "index_col" not in tiledb_args and df.index.name is None: + df.index.name = "__tiledb_rows" + + kwargs.update(tiledb_args) + from_pandas(uri, df, **kwargs) diff --git a/testbed/TileDB-Inc__TileDB-Py/tiledb/datatypes.py b/testbed/TileDB-Inc__TileDB-Py/tiledb/datatypes.py new file mode 100644 index 0000000000000000000000000000000000000000..de47506d3f760d8b5e3259dea0851e1099dfacdd --- /dev/null +++ b/testbed/TileDB-Inc__TileDB-Py/tiledb/datatypes.py @@ -0,0 +1,200 @@ +from __future__ import annotations + +from dataclasses import dataclass +from functools import lru_cache +from typing import Any, Tuple + +import numpy as np + +import tiledb.cc as lt + + +@dataclass(frozen=True) +class DataType: + np_dtype: np.dtype + tiledb_type: lt.DataType + ncells: int + + @classmethod + @lru_cache() + def from_numpy(cls, dtype: np.dtype) -> DataType: + if dtype == "ascii": + return cls(np.dtype("S"), lt.DataType.STRING_ASCII, lt.TILEDB_VAR_NUM()) + + if dtype == "blob": + return cls(np.dtype("S"), lt.DataType.BLOB, 1) + + if hasattr(lt.DataType, "GEOM_WKB") and dtype == "wkb": + return cls(np.dtype("S"), lt.DataType.GEOM_WKB, 1) + + if hasattr(lt.DataType, "GEOM_WKT") and dtype == "wkt": + return cls(np.dtype("S"), lt.DataType.GEOM_WKT, 1) + + dtype = np.dtype(dtype) + if dtype.kind == "V": + # fixed-size record dtypes + if dtype.shape != (): + raise TypeError("nested sub-array numpy dtypes are not supported") + + # check that types are the same + field_dtypes = set(v[0] for v in dtype.fields.values()) + if len(field_dtypes) > 1: + raise TypeError("heterogenous record numpy dtypes are not supported") + + base_dtype = field_dtypes.pop() + ncells = len(dtype.fields) + + elif np.issubdtype(dtype, np.character): + # - flexible datatypes of unknown size have an itemsize of 0 (str, bytes, etc.) + # - character types are always stored as VAR because we don't want to store + # the pad (numpy pads to max length for 'S' and 'U' dtypes) + base_dtype = np.dtype((dtype.kind, 1)) + if dtype.itemsize == 0: + ncells = lt.TILEDB_VAR_NUM() + else: + ncells = dtype.itemsize // base_dtype.itemsize + + else: + base_dtype = dtype + ncells = 2 if np.issubdtype(dtype, np.complexfloating) else 1 + + tiledb_type = _NUMPY_TO_TILEDB.get(base_dtype) + if tiledb_type is None: + raise TypeError(f"{dtype!r} cannot be mapped to a DataType") + + return cls(dtype, tiledb_type, ncells) + + @classmethod + @lru_cache() + def from_tiledb(cls, tiledb_type: lt.DataType, ncells: int = 1) -> DataType: + base_dtype = _TILEDB_TO_NUMPY[tiledb_type] + if tiledb_type in (lt.DataType.CHAR, lt.DataType.STRING_UTF8): + kind = base_dtype.kind + dtype = np.dtype((kind, ncells) if ncells != lt.TILEDB_VAR_NUM() else kind) + elif ncells == 1 or ncells == lt.TILEDB_VAR_NUM(): + dtype = base_dtype + elif ncells == 2 and np.issubdtype(base_dtype, np.floating): + dtype = np.dtype("complex64" if base_dtype.itemsize == 4 else "complex128") + else: + # construct anonymous record dtype + assert ncells > 1 + dtype = np.dtype([("", base_dtype)] * ncells) + + return cls(dtype, tiledb_type, ncells) + + @property # TODO: change to functools.cached_property in Python 3.8+ + def domain(self) -> Tuple[Any, Any]: + dtype = self.np_dtype + + if np.issubdtype(dtype, np.datetime64) or np.issubdtype(dtype, np.timedelta64): + info = np.iinfo(np.int64) + dt_data = np.datetime_data(dtype) + # +1 to exclude NaT + return dtype.type(info.min + 1, dt_data), dtype.type(info.max, dt_data) + + if np.issubdtype(dtype, np.integer): + info = np.iinfo(dtype) + return info.min, info.max + + if np.issubdtype(dtype, np.inexact): + info = np.finfo(dtype) + return info.min, info.max + + if np.issubdtype(dtype, np.bool_): + return False, True + + if np.issubdtype(dtype, np.character): + return None, None + + raise TypeError(f"Cannot determine min/max for {dtype!r}") + + def cast_tile_extent(self, tile_extent: Any) -> np.ndarray: + """Given a tile extent value, cast it to np.array of this datatype's np_dtype.""" + if np.issubdtype(self.np_dtype, np.datetime64): + # Special handling for datetime domains + if isinstance(tile_extent, np.timedelta64): + unit = np.datetime_data(self.np_dtype)[0] + tile_extent /= np.timedelta64(1, unit) + tile_dtype = np.dtype(np.int64) + else: + tile_dtype = self.np_dtype + tile_size_array = np.array(tile_extent, tile_dtype) + if tile_size_array.size != 1: + raise ValueError("tile extent must be a scalar") + return tile_size_array + + def uncast_tile_extent(self, tile_extent: Any) -> np.generic: + """Given a tile extent value from PyBind, cast it to appropriate output.""" + if np.issubdtype(self.np_dtype, np.character): + return tile_extent + if np.issubdtype(self.np_dtype, np.datetime64): + unit = np.datetime_data(self.np_dtype)[0] + return np.timedelta64(tile_extent, unit) + return self.np_dtype.type(tile_extent) + + +# datatype pairs that have a 1-1 mapping between tiledb and numpy +_COMMON_DATATYPES = [ + (np.dtype("bool"), lt.DataType.BOOL), + # signed int + (np.dtype("int8"), lt.DataType.INT8), + (np.dtype("int16"), lt.DataType.INT16), + (np.dtype("int32"), lt.DataType.INT32), + (np.dtype("int64"), lt.DataType.INT64), + # unsigned int + (np.dtype("uint8"), lt.DataType.UINT8), + (np.dtype("uint16"), lt.DataType.UINT16), + (np.dtype("uint32"), lt.DataType.UINT32), + (np.dtype("uint64"), lt.DataType.UINT64), + # float + (np.dtype("float32"), lt.DataType.FLOAT32), + (np.dtype("float64"), lt.DataType.FLOAT64), + # datetime + (np.dtype(" + +#ifndef TILEDBPY_DEBUGCC +#define TILEDBPY_DEBUGCC + +namespace { +extern "C" { + +namespace py = pybind11; +using namespace pybind11::literals; + +// __attribute__((used)) to make the linker keep the symbol +__attribute__((used)) static void pyprint(pybind11::object o) { + pybind11::print(o); +} + +__attribute__((used)) static void pyprint(pybind11::handle h) { + pybind11::print(h); +} + +__attribute__((used)) static std::string pyrepr(py::handle h) { + auto locals = py::dict("_v"_a = h); + return py::cast(py::eval("repr(_v)", py::globals(), locals)); +} + +__attribute__((used)) static std::string pyrepr(py::object o) { + auto locals = py::dict("_v"_a = o); + return py::cast(py::eval("repr(_v)", py::globals(), locals)); +} + +__attribute__((used)) static void pycall1(const char *expr, + pybind11::object o = py::none()) { + // this doesn't work in lldb + // py::scoped_interpreter guard{}; + + /* + * NOTE: the catch statements below do not work in lldb, because exceptions + * are trapped internally. So, an error in eval currently breaks + * use of this function until the process is restarted. + */ + + // usage: given some py::object 'o', exec a string w/ 'local _v'==o, e.g.: + // (lldb) p pycall1("_v.shape", o) + + py::object res = py::none(); + try { + if (!o.is(py::none())) { + auto locals = py::dict("_v"_a = o); + res = py::eval(expr, py::globals(), locals); + } else { + res = py::eval(expr, py::globals()); + } + if (!res.is(py::none())) { + py::print(res); + } + } catch (py::error_already_set &e) { + std::cout << "pycall error_already_set: " << std::endl; + } catch (std::runtime_error &e) { + std::cout << "pycall runtime_error: " << e.what() << std::endl; + } catch (...) { + std::cout << "pycall unknown exception" << std::endl; + } +} + +__attribute__((used)) static void pycall(const char *expr) { + pycall1(expr, py::none()); +} + +__attribute__((used)) static void pyerror() { + // print the last py error, if any +} +} +}; // namespace + +#endif diff --git a/testbed/TileDB-Inc__TileDB-Py/tiledb/dense_array.py b/testbed/TileDB-Inc__TileDB-Py/tiledb/dense_array.py new file mode 100644 index 0000000000000000000000000000000000000000..be9669fc4f615140b404282536806cf4d9d78f72 --- /dev/null +++ b/testbed/TileDB-Inc__TileDB-Py/tiledb/dense_array.py @@ -0,0 +1,777 @@ +import warnings +from collections import OrderedDict + +import numpy as np + +import tiledb +import tiledb.cc as lt + +from .array import ( + check_for_floats, + index_as_tuple, + index_domain_subarray, + replace_ellipsis, + replace_scalars_slice, +) +from .libtiledb import Array, Query +from .subarray import Subarray + + +class DenseArrayImpl(Array): + """Class representing a dense TileDB array. + + Inherits properties and methods of :py:class:`tiledb.Array`. + + """ + + def __init__(self, *args, **kw): + super().__init__(*args, **kw) + if self.schema.sparse: + raise ValueError(f"Array at {self.uri} is not a dense array") + + @property + def ctx(self): + return self._ctx_() + + def __len__(self): + return self.domain.shape[0] + + def __getitem__(self, selection): + """Retrieve data cells for an item or region of the array. + + :param tuple selection: An int index, slice or tuple of integer/slice objects, + specifying the selected subarray region for each dimension of the DenseArray. + :rtype: :py:class:`numpy.ndarray` or :py:class:`collections.OrderedDict` + :returns: If the dense array has a single attribute then a Numpy array of corresponding shape/dtype \ + is returned for that attribute. If the array has multiple attributes, a \ + :py:class:`collections.OrderedDict` is returned with dense Numpy subarrays \ + for each attribute. + :raises IndexError: invalid or unsupported index selection + :raises: :py:exc:`tiledb.TileDBError` + + **Example:** + + >>> import tiledb, numpy as np, tempfile + >>> with tempfile.TemporaryDirectory() as tmp: + ... # Creates array 'array' on disk. + ... A = tiledb.from_numpy(tmp + "/array", np.ones((100, 100))) + ... # Many aspects of Numpy's fancy indexing are supported: + ... A[1:10, ...].shape + ... A[1:10, 20:99].shape + ... A[1, 2].shape + (9, 100) + (9, 79) + () + >>> # Subselect on attributes when reading: + >>> with tempfile.TemporaryDirectory() as tmp: + ... dom = tiledb.Domain(tiledb.Dim(domain=(0, 9), tile=2, dtype=np.uint64)) + ... schema = tiledb.ArraySchema(domain=dom, + ... attrs=(tiledb.Attr(name="a1", dtype=np.int64), + ... tiledb.Attr(name="a2", dtype=np.int64))) + ... tiledb.DenseArray.create(tmp + "/array", schema) + ... with tiledb.DenseArray(tmp + "/array", mode='w') as A: + ... A[0:10] = {"a1": np.zeros((10)), "a2": np.ones((10))} + ... with tiledb.DenseArray(tmp + "/array", mode='r') as A: + ... # Access specific attributes individually. + ... A[0:5]["a1"] + ... A[0:5]["a2"] + array([0, 0, 0, 0, 0]) + array([1, 1, 1, 1, 1]) + + """ + if self.view_attr: + result = self.subarray(selection, attrs=(self.view_attr,)) + return result[self.view_attr] + + result = self.subarray(selection) + for i in range(self.schema.nattr): + attr = self.schema.attr(i) + enum_label = attr.enum_label + if enum_label is not None: + values = self.enum(enum_label).values() + if attr.isnullable: + data = np.array([values[idx] for idx in result[attr.name].data]) + result[attr.name] = np.ma.array(data, mask=result[attr.name].mask) + else: + result[attr.name] = np.array( + [values[idx] for idx in result[attr.name]] + ) + else: + if attr.isnullable: + result[attr.name] = np.ma.array( + result[attr.name].data, mask=result[attr.name].mask + ) + + return result + + def __repr__(self): + if self.isopen: + return f"DenseArray(uri={self.uri!r}, mode={self.mode}, ndim={self.schema.ndim})" + else: + return f"DenseArray(uri={self.uri!r}, mode=closed)" + + def query( + self, + attrs=None, + cond=None, + dims=None, + coords=False, + order="C", + use_arrow=None, + return_arrow=False, + return_incomplete=False, + ): + """Construct a proxy Query object for easy subarray queries of cells + for an item or region of the array across one or more attributes. + + Optionally subselect over attributes, return dense result coordinate values, + and specify a layout a result layout / cell-order. + + :param attrs: the DenseArray attributes to subselect over. + If attrs is None (default) all array attributes will be returned. + Array attributes can be defined by name or by positional index. + :param cond: the str expression to filter attributes or dimensions on. The expression must be parsable by tiledb.QueryCondition(). See help(tiledb.QueryCondition) for more details. + :param dims: the DenseArray dimensions to subselect over. If dims is None (default) + then no dimensions are returned, unless coords=True. + :param coords: if True, return array of coodinate value (default False). + :param order: 'C', 'F', 'U', or 'G' (row-major, col-major, unordered, TileDB global order) + :param mode: "r" to read (default), "d" to delete + :param use_arrow: if True, return dataframes via PyArrow if applicable. + :param return_arrow: if True, return results as a PyArrow Table if applicable. + :param return_incomplete: if True, initialize and return an iterable Query object over the indexed range. + Consuming this iterable returns a result set for each TileDB incomplete query. + See usage example in 'examples/incomplete_iteration.py'. + To retrieve the estimated result sizes for the query ranges, use: + `A.query(..., return_incomplete=True)[...].est_result_size()` + If False (default False), queries will be internally run to completion by resizing buffers and + resubmitting until query is complete. + :return: A proxy Query object that can be used for indexing into the DenseArray + over the defined attributes, in the given result layout (order). + + :raises ValueError: array is not opened for reads (mode = 'r') + :raises: :py:exc:`tiledb.TileDBError` + + **Example:** + + >>> # Subselect on attributes when reading: + >>> with tempfile.TemporaryDirectory() as tmp: + ... dom = tiledb.Domain(tiledb.Dim(domain=(0, 9), tile=2, dtype=np.uint64)) + ... schema = tiledb.ArraySchema(domain=dom, + ... attrs=(tiledb.Attr(name="a1", dtype=np.int64), + ... tiledb.Attr(name="a2", dtype=np.int64))) + ... tiledb.DenseArray.create(tmp + "/array", schema) + ... with tiledb.DenseArray(tmp + "/array", mode='w') as A: + ... A[0:10] = {"a1": np.zeros((10)), "a2": np.ones((10))} + ... with tiledb.DenseArray(tmp + "/array", mode='r') as A: + ... # Access specific attributes individually. + ... np.testing.assert_equal(A.query(attrs=("a1",))[0:5], + ... {"a1": np.zeros(5)}) + + """ + if not self.isopen or self.mode != "r": + raise tiledb.TileDBError("DenseArray must be opened in read mode") + + return Query( + self, + attrs=attrs, + cond=cond, + dims=dims, + coords=coords, + order=order, + use_arrow=use_arrow, + return_arrow=return_arrow, + return_incomplete=return_incomplete, + ) + + def subarray(self, selection, attrs=None, cond=None, coords=False, order=None): + """Retrieve data cells for an item or region of the array. + + Optionally subselect over attributes, return dense result coordinate values, + and specify a layout a result layout / cell-order. + + :param selection: tuple of scalar and/or slice objects + :param cond: the str expression to filter attributes or dimensions on. The expression must be parsable by tiledb.QueryCondition(). See help(tiledb.QueryCondition) for more details. + :param coords: if True, return array of coordinate value (default False). + :param attrs: the DenseArray attributes to subselect over. + If attrs is None (default) all array attributes will be returned. + Array attributes can be defined by name or by positional index. + :param order: 'C', 'F', 'U', or 'G' (row-major, col-major, unordered, TileDB global order) + :returns: If the dense array has a single attribute then a Numpy array of corresponding shape/dtype \ + is returned for that attribute. If the array has multiple attributes, a \ + :py:class:`collections.OrderedDict` is returned with dense Numpy subarrays for each attribute. + :raises IndexError: invalid or unsupported index selection + :raises: :py:exc:`tiledb.TileDBError` + + **Example:** + + >>> with tempfile.TemporaryDirectory() as tmp: + ... dom = tiledb.Domain(tiledb.Dim(domain=(0, 9), tile=2, dtype=np.uint64)) + ... schema = tiledb.ArraySchema(domain=dom, + ... attrs=(tiledb.Attr(name="a1", dtype=np.int64), + ... tiledb.Attr(name="a2", dtype=np.int64))) + ... tiledb.DenseArray.create(tmp + "/array", schema) + ... with tiledb.DenseArray(tmp + "/array", mode='w') as A: + ... A[0:10] = {"a1": np.zeros((10)), "a2": np.ones((10))} + ... with tiledb.DenseArray(tmp + "/array", mode='r') as A: + ... # A[0:5], attribute a1, row-major without coordinates + ... np.testing.assert_equal(A.subarray((slice(0, 5),), attrs=("a1",), coords=False, order='C'), + ... OrderedDict({'a1': np.zeros(5)})) + + """ + if not self.isopen or self.mode != "r": + raise tiledb.TileDBError("DenseArray must be opened in read mode") + + layout = lt.LayoutType.UNORDERED + if order is None or order == "C": + layout = lt.LayoutType.ROW_MAJOR + elif order == "F": + layout = lt.LayoutType.COL_MAJOR + elif order == "G": + layout = lt.LayoutType.GLOBAL_ORDER + elif order == "U": + pass + else: + raise ValueError( + "order must be 'C' (TILEDB_ROW_MAJOR), " + "'F' (TILEDB_COL_MAJOR), " + "'G' (TILEDB_GLOBAL_ORDER), " + "or 'U' (TILEDB_UNORDERED)" + ) + attr_names = list() + if coords == True: + attr_names.extend( + self.schema.domain.dim(i).name for i in range(self.schema.ndim) + ) + elif coords: + attr_names.extend(coords) + + if attrs is None: + attr_names.extend( + self.schema.attr(i)._internal_name for i in range(self.schema.nattr) + ) + else: + attr_names.extend(self.schema.attr(a).name for a in attrs) + + selection = index_as_tuple(selection) + idx = replace_ellipsis(self.schema.domain.ndim, selection) + idx, drop_axes = replace_scalars_slice(self.schema.domain, idx) + dim_ranges = index_domain_subarray(self, self.schema.domain, idx) + subarray = Subarray(self, self._ctx_()) + subarray.add_ranges([list([x]) for x in dim_ranges]) + # Note: we included dims (coords) above to match existing semantics + out = self._read_dense_subarray(subarray, attr_names, cond, layout, coords) + if any(s.step for s in idx): + steps = tuple(slice(None, None, s.step) for s in idx) + for (k, v) in out.items(): + out[k] = v.__getitem__(steps) + if drop_axes: + for (k, v) in out.items(): + out[k] = v.squeeze(axis=drop_axes) + # attribute is anonymous, just return the result + if not coords and self.schema.nattr == 1: + attr = self.schema.attr(0) + if attr.isanon: + return out[attr._internal_name] + return out + + def _read_dense_subarray( + self, subarray, attr_names: list, cond, layout, include_coords + ): + from .main import PyQuery + + q = PyQuery(self._ctx_(), self, tuple(attr_names), tuple(), layout, False) + self.pyquery = q + + if cond is not None and cond != "": + if isinstance(cond, str): + from .query_condition import QueryCondition + + q.set_cond(QueryCondition(cond)) + else: + raise TypeError("`cond` expects type str.") + + q.set_subarray(subarray) + q.submit() + results = OrderedDict() + results = q.results() + + out = OrderedDict() + + output_shape = subarray.shape() + + nattr = len(attr_names) + for i in range(nattr): + name = attr_names[i] + if not self.schema.domain.has_dim(name) and self.schema.attr(name).isvar: + # for var arrays we create an object array + dtype = object + out[name] = q.unpack_buffer( + name, results[name][0], results[name][1] + ).reshape(output_shape) + else: + dtype = q.buffer_dtype(name) + + # sanity check the TileDB buffer size against schema? + # add assert to verify np.require doesn't copy? + arr = results[name][0] + arr.dtype = dtype + if len(arr) == 0: + # special case: the C API returns 0 len for blank arrays + arr = np.zeros(output_shape, dtype=dtype) + elif len(arr) != np.prod(output_shape): + raise Exception( + "Mismatched output array shape! (arr.shape: {}, output.shape: {}".format( + arr.shape, output_shape + ) + ) + + if layout == lt.LayoutType.ROW_MAJOR: + arr.shape = output_shape + arr = np.require(arr, requirements="C") + elif layout == lt.LayoutType.COL_MAJOR: + arr.shape = output_shape + arr = np.require(arr, requirements="F") + else: + arr.shape = np.prod(output_shape) + + out[name] = arr + + if self.schema.has_attr(name) and self.attr(name).isnullable: + out[name] = np.ma.array(out[name], mask=~results[name][2].astype(bool)) + + return out + + def __setitem__(self, selection, val): + """Set / update dense data cells + + :param tuple selection: An int index, slice or tuple of integer/slice objects, + specifiying the selected subarray region for each dimension of the DenseArray. + :param val: a dictionary of array attribute values, values must able to be converted to n-d numpy arrays.\ + if the number of attributes is one, then a n-d numpy array is accepted. + :type val: dict or :py:class:`numpy.ndarray` + :raises IndexError: invalid or unsupported index selection + :raises ValueError: value / coordinate length mismatch + :raises: :py:exc:`tiledb.TileDBError` + + **Example:** + + >>> import tiledb, numpy as np, tempfile + >>> # Write to single-attribute 2D array + >>> with tempfile.TemporaryDirectory() as tmp: + ... # Create an array initially with all zero values + ... with tiledb.from_numpy(tmp + "/array", np.zeros((2, 2))) as A: + ... pass + ... with tiledb.DenseArray(tmp + "/array", mode='w') as A: + ... # Write to the single (anonymous) attribute + ... A[:] = np.array(([1,2], [3,4])) + >>> + >>> # Write to multi-attribute 2D array + >>> with tempfile.TemporaryDirectory() as tmp: + ... dom = tiledb.Domain( + ... tiledb.Dim(domain=(0, 1), tile=2, dtype=np.uint64), + ... tiledb.Dim(domain=(0, 1), tile=2, dtype=np.uint64)) + ... schema = tiledb.ArraySchema(domain=dom, + ... attrs=(tiledb.Attr(name="a1", dtype=np.int64), + ... tiledb.Attr(name="a2", dtype=np.int64))) + ... tiledb.DenseArray.create(tmp + "/array", schema) + ... with tiledb.DenseArray(tmp + "/array", mode='w') as A: + ... # Write to each attribute + ... A[0:2, 0:2] = {"a1": np.array(([-3, -4], [-5, -6])), + ... "a2": np.array(([1, 2], [3, 4]))} + + """ + selection_tuple = ( + (selection,) if not isinstance(selection, tuple) else selection + ) + self._setitem_impl(selection, val, dict()) + + def _setitem_impl(self, selection, val, nullmaps: dict): + """Implementation for setitem with optional support for validity bitmaps.""" + if not self.isopen or self.mode != "w": + raise tiledb.TileDBError("DenseArray is not opened for writing") + + domain = self.domain + idx = replace_ellipsis(domain.ndim, index_as_tuple(selection)) + idx, _drop = replace_scalars_slice(domain, idx) + attributes = list() + values = list() + labels = dict() + + if isinstance(selection, Subarray): + subarray = selection + else: + dim_ranges = index_domain_subarray(self, domain, idx) + subarray = Subarray(self, self._ctx_()) + subarray.add_ranges([list([x]) for x in dim_ranges]) + + subarray_shape = subarray.shape() + if isinstance(val, np.ndarray): + try: + np.broadcast_shapes(subarray_shape, val.shape) + except ValueError: + raise ValueError( + "shape mismatch; data dimensions do not match the domain " + f"given in array schema ({subarray_shape} != {val.shape})" + ) + + if isinstance(val, dict): + # Create dictionary of label names and values + labels = { + name: ( + data + if not type(data) is np.ndarray or data.dtype is np.dtype("O") + else np.ascontiguousarray( + data, dtype=self.schema.dim_label(name).dtype + ) + ) + for name, data in val.items() + if self.schema.has_dim_label(name) + } + + # Create list of attribute names and values + for attr_idx in range(self.schema.nattr): + attr = self.schema.attr(attr_idx) + name = attr.name + attr_val = val[name] + + attributes.append(attr._internal_name) + # object arrays are var-len and handled later + if type(attr_val) is np.ndarray and attr_val.dtype is not np.dtype("O"): + if attr.isnullable and name not in nullmaps: + try: + nullmaps[name] = ~np.ma.masked_invalid(attr_val).mask + attr_val = np.nan_to_num(attr_val) + except Exception as exc: + attr_val = np.asarray(attr_val) + nullmaps[name] = np.array( + [int(v is not None) for v in attr_val], dtype=np.uint8 + ) + attr_val = np.ascontiguousarray(attr_val, dtype=attr.dtype) + + try: + if attr.isvar: + # ensure that the value is array-convertible, for example: pandas.Series + attr_val = np.asarray(attr_val) + if attr.isnullable and name not in nullmaps: + nullmaps[name] = np.array( + [int(v is not None) for v in attr_val], dtype=np.uint8 + ) + else: + if np.issubdtype(attr.dtype, np.bytes_) and not ( + np.issubdtype(attr_val.dtype, np.bytes_) + or attr_val.dtype == np.dtype("O") + ): + raise ValueError( + "Cannot write a string value to non-string " + "typed attribute '{}'!".format(name) + ) + + if attr.isnullable and name not in nullmaps: + try: + nullmaps[name] = ~np.ma.masked_invalid(attr_val).mask + except Exception as exc: + attr_val = np.asarray(attr_val) + nullmaps[name] = np.array( + [int(v is not None) for v in attr_val], + dtype=np.uint8, + ) + + if np.issubdtype(attr.dtype, np.bytes_): + attr_val = np.array( + ["" if v is None else v for v in attr_val] + ) + else: + attr_val = np.nan_to_num(attr_val) + attr_val = np.array( + [0 if v is None else v for v in attr_val] + ) + attr_val = np.ascontiguousarray(attr_val, dtype=attr.dtype) + except Exception as exc: + raise ValueError( + f"NumPy array conversion check failed for attr '{name}'" + ) from exc + + values.append(attr_val) + + elif np.isscalar(val): + for i in range(self.schema.nattr): + attr = self.schema.attr(i) + attributes.append(attr._internal_name) + A = np.empty(subarray_shape, dtype=attr.dtype) + A[:] = val + values.append(A) + elif self.schema.nattr == 1: + attr = self.schema.attr(0) + name = attr.name + attributes.append(attr._internal_name) + # object arrays are var-len and handled later + if type(val) is np.ndarray and val.dtype is not np.dtype("O"): + val = np.ascontiguousarray(val, dtype=attr.dtype) + try: + if attr.isvar: + # ensure that the value is array-convertible, for example: pandas.Series + val = np.asarray(val) + if attr.isnullable and name not in nullmaps: + nullmaps[name] = np.array( + [int(v is None) for v in val], dtype=np.uint8 + ) + else: + if np.issubdtype(attr.dtype, np.bytes_) and not ( + np.issubdtype(val.dtype, np.bytes_) + or val.dtype == np.dtype("O") + ): + raise ValueError( + "Cannot write a string value to non-string " + "typed attribute '{}'!".format(name) + ) + + if attr.isnullable and name not in nullmaps: + nullmaps[name] = ~np.ma.masked_invalid(val).mask + val = np.nan_to_num(val) + val = np.ascontiguousarray(val, dtype=attr.dtype) + except Exception as exc: + raise ValueError( + f"NumPy array conversion check failed for attr '{name}'" + ) from exc + values.append(val) + elif self.view_attr is not None: + # Support single-attribute assignment for multi-attr array + # This is a hack pending + # https://github.com/TileDB-Inc/TileDB/issues/1162 + # (note: implicitly relies on the fact that we treat all arrays + # as zero initialized as long as query returns TILEDB_OK) + # see also: https://github.com/TileDB-Inc/TileDB-Py/issues/128 + if self.schema.nattr == 1: + attributes.append(self.schema.attr(0).name) + values.append(val) + else: + dtype = self.schema.attr(self.view_attr).dtype + with DenseArrayImpl( + self.uri, "r", ctx=tiledb.Ctx(self._ctx_().config()) + ) as readable: + current = readable[selection] + current[self.view_attr] = np.ascontiguousarray(val, dtype=dtype) + # `current` is an OrderedDict + attributes.extend(current.keys()) + values.extend(current.values()) + else: + raise ValueError( + "ambiguous attribute assignment, " + "more than one array attribute " + "(use a dict({'attr': val}) to " + "assign multiple attributes)" + ) + + if nullmaps: + for key, val in nullmaps.items(): + if not self.schema.has_attr(key): + raise tiledb.TileDBError( + "Cannot set validity for non-existent attribute." + ) + if not self.schema.attr(key).isnullable: + raise ValueError( + "Cannot set validity map for non-nullable attribute." + ) + if not isinstance(val, np.ndarray): + raise TypeError( + f"Expected NumPy array for attribute '{key}' " + f"validity bitmap, got {type(val)}" + ) + + from .libtiledb import _write_array_wrapper + + _write_array_wrapper( + self, subarray, [], attributes, values, labels, nullmaps, False + ) + + def __array__(self, dtype=None, **kw): + """Implementation of numpy __array__ protocol (internal). + + :return: Numpy ndarray resulting from indexing the entire array. + + """ + if self.view_attr is None and self.nattr > 1: + raise ValueError( + "cannot call __array__ for TileDB array with more than one attribute" + ) + if self.view_attr: + name = self.view_attr + else: + name = self.schema.attr(0).name + array = self.read_direct(name=name) + if dtype and array.dtype != dtype: + return array.astype(dtype) + return array + + def write_direct(self, array: np.ndarray, **kw): + from .libtiledb import write_direct_dense + + write_direct_dense(self, array, **kw) + + def read_direct(self, name=None): + """Read attribute directly with minimal overhead, returns a numpy ndarray over the entire domain + + :param str attr_name: read directly to an attribute name (default ) + :rtype: numpy.ndarray + :return: numpy.ndarray of `attr_name` values over the entire array domain + :raises: :py:exc:`tiledb.TileDBError` + + """ + if not self.isopen or self.mode != "r": + raise tiledb.TileDBError("DenseArray is not opened for reading") + + if name is None and self.schema.nattr != 1: + raise ValueError( + "read_direct with no provided attribute is ambiguous for multi-attribute arrays" + ) + elif name is None: + attr = self.schema.attr(0) + attr_name = attr._internal_name + else: + attr = self.schema.attr(name) + attr_name = attr._internal_name + order = "C" + cell_layout = lt.LayoutType.ROW_MAJOR + if ( + self.schema.cell_order == "col-major" + and self.schema.tile_order == "col-major" + ): + order = "F" + cell_layout = lt.LayoutType.COL_MAJOR + + schema = self.schema + domain = schema.domain + + idx = tuple(slice(None) for _ in range(domain.ndim)) + range_index = index_domain_subarray(self, domain, idx) + subarray = Subarray(self, self._ctx_()) + subarray.add_ranges([list([x]) for x in range_index]) + out = self._read_dense_subarray( + subarray, + [ + attr_name, + ], + None, + cell_layout, + False, + ) + return out[attr_name] + + def read_subarray(self, subarray): + + from .main import PyQuery + from .query import Query + + # Precompute and label ranges: this step is only needed so the attribute + # buffer sizes are set correctly. + ndim = self.schema.domain.ndim + has_labels = any(subarray.has_label_range(dim_idx) for dim_idx in range(ndim)) + if has_labels: + label_query = Query(self, self._ctx_()) + label_query.set_subarray(subarray) + label_query.submit() + if not label_query.is_complete(): + raise tiledb.TileDBError("Failed to get dimension ranges from labels") + result_subarray = Subarray(self, self._ctx_()) + result_subarray.copy_ranges(label_query.subarray(), range(ndim)) + return self.read_subarray(result_subarray) + + # If the subarray has shape of zero, return empty result without querying. + if subarray.shape() == 0: + if self.view_attr is not None: + return OrderedDict( + ("" if self.view_attr == "__attr" else self.view_attr), + np.array( + [], + self.schema.attr_or_dim_dtype(self.view_attr), + ), + ) + return OrderedDict( + ("" if attr.name == "__attr" else attr.name, np.array([], attr.dtype)) + for attr in self.schema.attrs + ) + + # Create the pyquery and set the subarray. + layout = lt.LayoutType.ROW_MAJOR + pyquery = PyQuery( + self._ctx_(), + self, + tuple( + [self.view_attr] + if self.view_attr is not None + else (attr._internal_name for attr in self.schema) + ), + tuple(), + layout, + False, + ) + pyquery.set_subarray(subarray) + + # Set the array pyquery to this pyquery and submit. + self.pyquery = pyquery + pyquery.submit() + + # Clean-up the results: + result_shape = subarray.shape() + result_dict = OrderedDict() + for name, item in pyquery.results().items(): + if len(item[1]) > 0: + arr = pyquery.unpack_buffer(name, item[0], item[1]) + else: + arr = item[0] + arr.dtype = ( + self.schema.attr_or_dim_dtype(name) + if not self.schema.has_dim_label(name) + else self.schema.dim_label(name).dtype + ) + arr.shape = result_shape + result_dict[name if name != "__attr" else ""] = arr + + return result_dict + + def write_subarray(self, subarray, values): + """Set / update dense data cells + + :param subarray: a subarray object that specifies the region to write + data to. + :param values: a dictionary of array attribute values, values must able to be + converted to n-d numpy arrays. If the number of attributes is one, then a + n-d numpy array is accepted. + :type subarray: :py:class:`tiledb.Subarray` + :type values: dict or :py:class:`numpy.ndarray` + :raises ValueError: value / coordinate length mismatch + :raises: :py:exc:`tiledb.TileDBError` + + **Example:** + + >>> # Write to multi-attribute 2D array + >>> with tempfile.TemporaryDirectory() as tmp: + ... dom = tiledb.Domain( + ... tiledb.Dim(domain=(0, 7), tile=8, dtype=np.uint64), + ... tiledb.Dim(domain=(0, 7), tile=8, dtype=np.uint64)) + ... schema = tiledb.ArraySchema(domain=dom, + ... attrs=(tiledb.Attr(name="a1", dtype=np.int64), + ... tiledb.Attr(name="a2", dtype=np.int64))) + ... tiledb.Array.create(tmp + "/array", schema) + ... with tiledb.open(tmp + "/array", mode='w') as A: + ... subarray = tiledb.Subarray(A) + ... subarray.add_dim_range(0, (0, 1)) + ... subarray.add_dim_range(1, (0, 1)) + ... # Write to each attribute + ... A.write_subarray( + ... subarray, + ... { + ... "a1": np.array(([-3, -4], [-5, -6])), + ... "a2": np.array(([1, 2], [3, 4])), + ... } + ... ) + + """ + # Check for label ranges + for dim_idx in range(self.schema.ndim): + if subarray.has_label_range(dim_idx): + raise tiledb.TileDBError( + f"Label range on dimension {dim_idx}. Support for writing by label " + f"ranges has not been implemented in the Python API." + ) + self._setitem_impl(subarray, values, dict()) diff --git a/testbed/TileDB-Inc__TileDB-Py/tiledb/dimension.py b/testbed/TileDB-Inc__TileDB-Py/tiledb/dimension.py new file mode 100644 index 0000000000000000000000000000000000000000..1e5eb35279dca6e1dd362f0bedf23cd87c34f04f --- /dev/null +++ b/testbed/TileDB-Inc__TileDB-Py/tiledb/dimension.py @@ -0,0 +1,295 @@ +import io +from typing import Any, Optional, Sequence, Tuple, Union + +import numpy as np + +import tiledb.cc as lt + +from .ctx import Ctx, CtxMixin +from .datatypes import DataType +from .filter import Filter, FilterList + + +class Dim(CtxMixin, lt.Dimension): + """ + Represents a TileDB dimension. + """ + + def __init__( + self, + name: str = "__dim_0", + domain: Tuple[Any, Any] = None, + tile: Any = None, + filters: Union[FilterList, Sequence[Filter]] = None, + dtype: np.dtype = np.uint64, + var: bool = None, + ctx: Optional[Ctx] = None, + ): + """Class representing a dimension of a TileDB Array. + + :param name: Dimension name, empty if anonymous + :param domain: TileDB domain + :param tile: Tile extent + :param filters: List of filters to apply + :param dtype: Dimension value datatype + :param var: Dimension is variable-length (automatic for byte/string types) + :param ctx: A TileDB Context + :raises ValueError: invalid domain or tile extent + :raises TypeError: invalid domain, tile extent, or dtype type + :raises tiledb.TileDBError: + """ + dt = DataType.from_numpy(dtype) + dtype = dt.np_dtype + if dtype.kind not in ("i", "u", "f", "M", "S"): + raise TypeError(f"invalid Dim dtype {dtype!r}") + + if var and not np.issubdtype(dtype, np.character): + raise TypeError("'var=True' specified for non-str/bytes dtype") + + if domain is not None and len(domain) != 2: + raise ValueError("invalid domain extent, must be a pair") + + if np.issubdtype(dtype, np.bytes_): + # Handle var-len dom type (currently only TILEDB_STRING_ASCII) + # The dims's dom is implicitly formed as coordinates are written. + tiledb_type = lt.DataType.STRING_ASCII + # XXX: intentionally(?) ignore passed domain and tile + domain = tile = None + else: + tiledb_type = dt.tiledb_type + if domain is None or domain == (None, None): + domain = dt.domain + else: + dtype_min, dtype_max = dt.domain + if not ( + dtype_min <= domain[0] <= dtype_max + and dtype_min <= domain[1] <= dtype_max + ): + raise TypeError( + f"invalid domain extent, domain cannot be safely cast to dtype {dtype!r}" + ) + + domain = np.asarray(domain, dtype) + if np.issubdtype(dtype, np.datetime64): + domain = domain.astype(np.int64) + + if tile is not None: + tile = dt.cast_tile_extent(tile) + + super().__init__(ctx, name, tiledb_type, domain, tile) + + if filters is not None: + if isinstance(filters, FilterList): + self._filters = filters + else: + self._filters = FilterList(filters) + + def __repr__(self) -> str: + # use safe repr if pybind11 constructor failed + if self._ctx is None: + return object.__repr__(self) + + filters_str = "" + if self.filters: + filters_str = ", filters=FilterList([" + for f in self.filters: + filters_str += repr(f) + ", " + filters_str += "])" + + # for consistency, print `var=True` for string-like types + varlen = "" if self.dtype not in (np.str_, np.bytes_) else ", var=True" + return f"Dim(name={self.name!r}, domain={self.domain!s}, tile={self.tile!r}, dtype='{self.dtype!s}'{varlen}{filters_str})" + + def _repr_html_(self) -> str: + output = io.StringIO() + + output.write("") + output.write("") + output.write("") + output.write("") + output.write("") + output.write("") + output.write("") + output.write("") + output.write("") + output.write(self._repr_html_row_only_()) + output.write("
NameDomainTileData TypeIs Var-LenFilters
") + + return output.getvalue() + + def _repr_html_row_only_(self) -> str: + output = io.StringIO() + + output.write("") + output.write(f"{self.name}") + output.write(f"{self.domain}") + output.write(f"{self.tile}") + output.write(f"{self.dtype}") + output.write(f"{self.dtype in (np.str_, np.bytes_)}") + output.write(f"{self.filters._repr_html_()}") + output.write("") + + return output.getvalue() + + def __len__(self) -> int: + return self.size + + def __eq__(self, other) -> bool: + if not isinstance(other, Dim): + return False + return ( + self.name == other.name + and self.domain == other.domain + and self.tile == other.tile + and self.dtype == other.dtype + and self.isvar == other.isvar + and self.filters == other.filters + ) + + def __array__(self, dtype=None, **kw) -> np.array: + if not self._integer_domain(): + raise TypeError( + "conversion to numpy ndarray only valid for integer dimension domains" + ) + lb, ub = self.domain + return np.arange(int(lb), int(ub) + 1, dtype=dtype if dtype else self.dtype) + + def create_label_schema( + self, + order: str = "increasing", + dtype: np.dtype = np.uint64, + tile: Any = None, + filters: Union[FilterList, Sequence[Filter]] = None, + ): + """Creates a dimension label schema for a dimension label on this dimension + + :param order: Order or sort of the label data ('increasing' or 'decreasing'). + :param dtype: Datatype of the label data. + :param tile: Tile extent for the dimension of the dimension label. If + ``None``, it will use the tile extent of this dimension. + :param label_filters: Filter list for the attribute storing the label data. + + :rtype: DimLabelSchema + + """ + from .dimension_label_schema import DimLabelSchema + + return DimLabelSchema( + order, + dtype, + self.dtype, + self.tile if tile is None and self.tile != 0 else tile, + filters, + self._ctx, + ) + + @property + def dtype(self) -> np.dtype: + """Numpy dtype representation of the dimension type. + + :rtype: numpy.dtype + + """ + return DataType.from_tiledb(self._tiledb_dtype).np_dtype + + @property + def name(self) -> str: + """The dimension label string. + + Anonymous dimensions return a default string representation based on the dimension index. + + :rtype: str + + """ + return self._name + + @property + def isvar(self) -> bool: + """True if the dimension is variable length + + :rtype: bool + :raises: :py:exc:`tiledb.TileDBError` + + """ + return self._ncell == lt.TILEDB_VAR_NUM() + + @property + def isanon(self) -> bool: + """True if the dimension is anonymous + + :rtype: bool + + """ + return self.name == "" or self.name.startswith("__dim") + + @property + def filters(self) -> FilterList: + """FilterList of the TileDB dimension + + :rtype: tiledb.FilterList + :raises: :py:exc:`tiledb.TileDBError` + + """ + return FilterList.from_pybind11(self._ctx, self._filters) + + @property + def shape(self) -> Tuple["np.generic", "np.generic"]: + """The shape of the dimension given the dimension's domain. + + **Note**: The shape is only valid for integer and datetime dimension domains. + + :rtype: tuple(numpy scalar, numpy scalar) + :raises TypeError: floating point (inexact) domain + + """ + dtype = self.dtype + if not ( + np.issubdtype(dtype, np.integer) or np.issubdtype(dtype, np.datetime64) + ): + raise TypeError( + "shape only valid for integer and datetime dimension domains" + ) + return ((self._domain[1] - self._domain[0] + 1),) + + @property + def size(self) -> int: + """The size of the dimension domain (number of cells along dimension). + + :rtype: int + :raises TypeError: floating point (inexact) domain + + """ + if not np.issubdtype(self.dtype, np.integer): + raise TypeError("size only valid for integer dimension domains") + return int(self.shape[0]) + + @property + def tile(self) -> np.generic: + """The tile extent of the dimension. + + :rtype: numpy scalar or np.timedelta64 + + """ + dim_dtype = DataType.from_tiledb(self._tiledb_dtype) + return dim_dtype.uncast_tile_extent(self._tile) + + @property + def domain(self) -> Tuple["np.generic", "np.generic"]: + """The dimension (inclusive) domain. + + The dimension's domain is defined by a (lower bound, upper bound) tuple. + + :rtype: tuple(numpy scalar, numpy scalar) + + """ + np_dtype = self.dtype + if np.issubdtype(np_dtype, np.character): + return self._domain + + min_args = [self._domain[0]] + max_args = [self._domain[1]] + if np.issubdtype(np_dtype, np.datetime64): + unit = np.datetime_data(np_dtype)[0] + min_args.append(unit) + max_args.append(unit) + return np_dtype.type(*min_args), np_dtype.type(*max_args) diff --git a/testbed/TileDB-Inc__TileDB-Py/tiledb/dimension_label.py b/testbed/TileDB-Inc__TileDB-Py/tiledb/dimension_label.py new file mode 100644 index 0000000000000000000000000000000000000000..3e762db9f94ac86994583cf104487868839ea7a0 --- /dev/null +++ b/testbed/TileDB-Inc__TileDB-Py/tiledb/dimension_label.py @@ -0,0 +1,119 @@ +import io + +import numpy as np + +import tiledb.cc as lt + +from .ctx import CtxMixin +from .data_order import DataOrder +from .datatypes import DataType + + +class DimLabel(CtxMixin, lt.DimensionLabel): + """ + Represents a TileDB dimension label. + """ + + def __repr__(self) -> str: + dtype = "ascii" if self.isascii else self.dtype + return ( + f"DimLabel(name={self.name}, dtype='{dtype!s}', " + f"var={self.isvar!s}, order={self.order!s})" + ) + + def _repr_html_(self): + output = io.StringIO() + + output.write("") + output.write("") + output.write("") + output.write("") + output.write("") + output.write("") + output.write("") + output.write(f"{self._repr_html_row_only_()}") + output.write("
NameData TypeIs Var-LenData Order
") + + return output.getvalue() + + def _repr_html_row_only_(self): + output = io.StringIO() + + output.write("") + output.write(f"{self.name}") + output.write(f"{'ascii' if self.isascii else self.dtype}") + output.write(f"{self.isvar}") + output.write(f"{self.order}") + output.write("") + + return output.getvalue() + + @property + def dim_index(self) -> int: + """Index of the dimension the labels are for. + + :rtype: int + + """ + return self._dim_index + + @property + def dtype(self) -> np.dtype: + """Numpy dtype representation of the label type. + + :rtype: numpy.dtype + + """ + return DataType.from_tiledb(self._tiledb_label_dtype).np_dtype + + @property + def isvar(self) -> bool: + """True if the labels are variable length. + + :rtype: bool + + """ + return self._label_ncell == lt.TILEDB_VAR_NUM() + + @property + def isascii(self) -> bool: + """True if the labels are variable length. + + :rtype: bool + + """ + return self._tiledb_label_dtype == lt.DataType.STRING_ASCII + + @property + def label_attr_name(self) -> str: + """Name of the attribute storing the label data. + + :rtype: str + """ + return self._label_attr_name + + @property + def name(self) -> str: + """The name of the dimension label. + + :rtype: str + + """ + return self._name + + @property + def order(self) -> str: + """The order of the label data in the dimension label. + + :rtype: str + """ + return DataOrder(self._tiledb_label_order).name + + @property + def uri(self) -> str: + """The URI of the array containing the dimension label data. + + :rtype: str + + """ + return self._uri diff --git a/testbed/TileDB-Inc__TileDB-Py/tiledb/dimension_label_schema.py b/testbed/TileDB-Inc__TileDB-Py/tiledb/dimension_label_schema.py new file mode 100644 index 0000000000000000000000000000000000000000..f107dcb1090d7b0fd7ef82c25194495d8e079ed3 --- /dev/null +++ b/testbed/TileDB-Inc__TileDB-Py/tiledb/dimension_label_schema.py @@ -0,0 +1,119 @@ +from typing import Any, Optional, Sequence, Union + +import numpy as np + +import tiledb.cc as lt + +from .ctx import Ctx, default_ctx +from .data_order import DataOrder +from .datatypes import DataType +from .filter import Filter, FilterList + + +class DimLabelSchema(lt.DimensionLabelSchema): + def __init__( + self, + order: str = "increasing", + label_dtype: np.dtype = np.uint64, + dim_dtype: np.dtype = np.uint64, + dim_tile: Any = None, + label_filters: Union[FilterList, Sequence[Filter]] = None, + ctx: Ctx = None, + ): + """Class defining a dimension label to create as part of an array. + + :param order: Order or sort of the label data ('increasing' or 'decreasing'). + :param label_dtype: Datatype of the label data. + :param dim_dtype: Datatype of the target dimension. + :param dim_tile: Tile extent for the dimension of the dimension label. If + ``None``, it will use the same tile extent as the target dimension. + :param label_filters: Filter list for the attribute storing the label data. + :param ctx: A TileDB Context. + """ + self._ctx = ctx or default_ctx() + + # Get DataType and DataOrder objects + _label_order = DataOrder[order] + _label_dtype = DataType.from_numpy( + np.dtype(label_dtype) + if label_dtype not in ("ascii", "blob") + else label_dtype + ) + np_dtype = _label_dtype.np_dtype + if np.issubdtype(np_dtype, np.bytes_) or np.issubdtype(np_dtype, np.str_): + _label_dtype = DataType( + np_dtype, lt.DataType.STRING_ASCII, lt.TILEDB_VAR_NUM + ) + + _dim_dtype = DataType.from_numpy(dim_dtype) + + # Convert the tile extent (if set) + if dim_tile is not None: + if np.issubdtype(_dim_dtype.np_dtype, np.bytes_): + raise TypeError( + "invalid tile extent, cannot set a tile a string dimension" + ) + _dim_tile = _dim_dtype.cast_tile_extent(dim_tile) + else: + _dim_tile = None + + # Create the PyBind superclass + if label_filters is None: + super().__init__( + _dim_dtype.tiledb_type, + _dim_tile, + _label_order.value, + _label_dtype.tiledb_type, + ) + else: + _label_filters = ( + label_filters + if isinstance(label_filters, FilterList) + else FilterList(label_filters) + ) + super().__init__( + _dim_dtype.tiledb_type, + _dim_tile, + _label_order.value, + _label_dtype.tiledb_type, + _label_filters, + ) + + @property + def dim_dtype(self) -> np.dtype: + """Numpy dtype object representing the dimension type""" + return DataType.from_tiledb(self._dim_dtype).np_dtype + + @property + def dim_tile(self) -> Optional[np.generic]: + """The tile extent of the dimension for the dimension label. + + :rtype: numpy scalar of np.timedelta64 + + """ + tile_extent = self._dim_tile_extent + if tile_extent is None: + return None + dim_dtype = DataType.from_tiledb(self._dim_dtype) + return ( + None if tile_extent is None else dim_dtype.uncast_tile_extent(tile_extent) + ) + + @property + def label_filters(self) -> Optional[FilterList]: + """FilterList of the labels""" + return ( + FilterList.from_pybind11(self._ctx, self._label_filters) + if self._has_label_filters + else None + ) + + @property + def label_dtype(self) -> np.dtype: + """Numpy dtype object representing the label type""" + return DataType.from_tiledb(self._label_dtype).np_dtype + + @property + def label_order(self) -> str: + """Sort order of the labels on the dimension label""" + return DataOrder(self._label_order).name diff --git a/testbed/TileDB-Inc__TileDB-Py/tiledb/domain.py b/testbed/TileDB-Inc__TileDB-Py/tiledb/domain.py new file mode 100644 index 0000000000000000000000000000000000000000..fdb10e45e3d0b61d97911486c3f03a34da3d1902 --- /dev/null +++ b/testbed/TileDB-Inc__TileDB-Py/tiledb/domain.py @@ -0,0 +1,186 @@ +import io +from typing import Optional + +import numpy as np + +import tiledb.cc as lt + +from .ctx import Ctx, CtxMixin +from .datatypes import DataType +from .dimension import Dim + + +class Domain(CtxMixin, lt.Domain): + """ + Represents a TileDB domain. + """ + + def __init__(self, *dims: Dim, ctx: Optional[Ctx] = None): + """Class representing the domain of a TileDB Array. + + :param *dims*: one or more tiledb.Dim objects up to the Domain's ndim + :param ctx: A TileDB Context + :raises TypeError: All dimensions must have the same dtype + :raises tiledb.TileDBError: + """ + super().__init__(ctx) + + # support passing a list of dims without splatting + if len(dims) == 1 and isinstance(dims[0], list): + dims = dims[0] + + if len(dims) == 0: + raise lt.TileDBError("Domain must have ndim >= 1") + + if len(dims) > 1: + if all(dim.name == "__dim_0" for dim in dims): + + def clone_dim_with_name(dim, name): + return Dim( + name=name, + domain=dim.domain, + tile=dim.tile, + filters=dim.filters, + dtype=dim.dtype, + var=dim.isvar, + ctx=dim._ctx, + ) + + # rename anonymous dimensions sequentially + dims = [ + clone_dim_with_name(dims[i], name=f"__dim_{i}") + for i in range(len(dims)) + ] + elif any(dim.name.startswith("__dim_0") for dim in dims[1:]): + raise lt.TileDBError( + "Mixed dimension naming: dimensions must be either all anonymous or all named." + ) + + for d in dims: + if not isinstance(d, Dim): + raise TypeError( + "Cannot create Domain with non-Dim value for 'dims' argument" + ) + self._add_dim(d) + + def __repr__(self): + # use safe repr if pybind11 constructor failed + if self._ctx is None: + return object.__repr__(self) + + dims = ",\n ".join(repr(self.dim(i)) for i in range(self.ndim)) + return "Domain({0!s})".format(dims) + + def _repr_html_(self) -> str: + output = io.StringIO() + + output.write("") + + output.write("") + output.write("") + output.write("") + output.write("") + output.write("") + output.write("") + output.write("") + output.write("") + for i in range(self.ndim): + output.write(self.dim(i)._repr_html_row_only_()) + output.write("
NameDomainTileData TypeIs Var-lengthFilters
") + + return output.getvalue() + + def __len__(self): + """Returns the number of dimensions of the domain""" + return self._ndim + + def __iter__(self): + """Returns a generator object that iterates over the domain's dimension objects""" + return (Dim.from_pybind11(self._ctx, self._dim(i)) for i in range(self.ndim)) + + def __eq__(self, other): + """Returns true if Domain is equal to self. + + :rtype: bool + """ + if not isinstance(other, Domain): + return False + if self.ndim != other.ndim: + return False + return all(self.dim(index) == other.dim(index) for index in range(self.ndim)) + + @property + def ndim(self): + """The number of dimensions of the domain. + + :rtype: int + + """ + return self._ndim + + @property + def dtype(self): + """The numpy dtype of the domain's dimension type. + + :rtype: numpy.dtype + + """ + return DataType.from_tiledb(self._tiledb_dtype).np_dtype + + @property + def shape(self): + """The domain's shape, valid only for integer domains. + + :rtype: tuple + :raises TypeError: floating point (inexact) domain + + """ + return tuple(dim.shape[0] for dim in self) + + @property + def size(self): + """The domain's size (number of cells), valid only for integer domains. + + :rtype: int + :raises TypeError: floating point (inexact) domain + + """ + if not np.issubdtype(self.dtype, self.integer): + raise TypeError("size valid only for integer domains") + return np.product(self.shape) + + def _is_homogeneous(self): + dtype0 = self.dim(0).dtype + return all(self.dim(i).dtype == dtype0 for i in range(1, self.ndim)) + + @property + def homogeneous(self): + """Returns True if the domain's dimension types are homogeneous.""" + return self._is_homogeneous() + + def dim(self, dim_id): + """Returns a Dim object from the domain given the dimension's index or name. + + :param dim_d: dimension index (int) or name (str) + :raises: :py:exc:`tiledb.TileDBError` + + """ + if not isinstance(dim_id, (int, str)): + raise ValueError( + f"Unsupported dim identifier: '{dim_id!r}' (expected int or str)" + ) + return Dim.from_pybind11(self._ctx, self._dim(dim_id)) + + def has_dim(self, name): + """ + Returns true if the Domain has a Dimension with the given name + + :param name: name of Dimension + :rtype: bool + :return: + """ + return self._has_dim(name) + + def dump(self): + """Dumps a string representation of the domain object to standard output (STDOUT)""" + print(self._dump(), "\n") diff --git a/testbed/TileDB-Inc__TileDB-Py/tiledb/domain_indexer.py b/testbed/TileDB-Inc__TileDB-Py/tiledb/domain_indexer.py new file mode 100644 index 0000000000000000000000000000000000000000..8796eb84caa07d3dc3b9394adef396adf4e0d2eb --- /dev/null +++ b/testbed/TileDB-Inc__TileDB-Py/tiledb/domain_indexer.py @@ -0,0 +1,122 @@ +import weakref + +import numpy as np + +import tiledb +import tiledb.cc as lt + + +def _index_as_tuple(idx): + """Forces scalar index objects to a tuple representation""" + if isinstance(idx, tuple): + return idx + return (idx,) + + +class DomainIndexer: + @staticmethod + def with_schema(schema): + indexer = DomainIndexer.__new__(DomainIndexer) + indexer.array = None + indexer.schema = schema + return indexer + + def __init__(self, array, query=None): + self.array_ref = weakref.ref(array) + self.schema = array.schema + self.query = query + + # @property + def schema(self): + return self.array.array_ref().schema + + @property + def array(self): + assert ( + self.array_ref() is not None + ), "Internal error: invariant violation (index[] with dead array_ref)" + return self.array_ref() + + def __getitem__(self, idx): + from .subarray import Subarray # prevent circular import + + # implements domain-based indexing: slice by domain coordinates, not 0-based python indexing + + schema = self.array.schema + dom = schema.domain + ndim = dom.ndim + attr_names = list() + + idx = _index_as_tuple(idx) + + if len(idx) < dom.ndim: + raise IndexError( + "number of indices does not match domain rank: " + "(got {!r}, expected: {!r})".format(len(idx), ndim) + ) + + new_idx = [] + for i in range(dom.ndim): + dim = dom.dim(i) + dim_idx = idx[i] + if np.isscalar(dim_idx): + start = dim_idx + stop = dim_idx + new_idx.append(slice(start, stop, None)) + else: + new_idx.append(dim_idx) + + dim_ranges = list() + + for i, subidx in enumerate(new_idx): + assert isinstance(subidx, slice) + dim_ranges.append((subidx.start, subidx.stop)) + subarray = Subarray(self.array) + subarray.add_ranges([list([x]) for x in dim_ranges]) + + attr_names = list(schema.attr(i).name for i in range(schema.nattr)) + attr_cond = None + + order = None + # TODO make coords optional for array.domain_index. there are no kwargs in slicing[], so + # one way to do this would be to overload __call__ and return a new + # object with a flag set. not ideal. + coords = True + + if self.query is not None: + # if we are called via Query object, then we need to respect Query semantics + order = self.query.order + attr_names = ( + self.query.attrs if self.query.attrs else attr_names + ) # query.attrs might be None -> all + attr_cond = self.query.attr_cond + coords = self.query.coords + + if coords: + attr_names = [ + dom.dim(idx).name for idx in range(self.schema.ndim) + ] + attr_names + + if order is None or order == "C": + layout = lt.LayoutType.ROW_MAJOR + elif order == "F": + layout = lt.LayoutType.COL_MAJOR + elif order == "G": + layout = lt.LayoutType.GLOBAL_ORDER + elif order == "U": + layout = lt.LayoutType.UNORDERED + else: + raise ValueError( + "order must be 'C' (TILEDB_ROW_MAJOR), 'F' (TILEDB_COL_MAJOR), or 'G' (TILEDB_GLOBAL_ORDER)" + ) + + if isinstance(self.array, tiledb.sparse_array.SparseArrayImpl): + return self.array._read_sparse_subarray( + subarray, attr_names, attr_cond, layout + ) + elif isinstance(self.array, tiledb.dense_array.DenseArrayImpl): + return self.array._read_dense_subarray( + subarray, attr_names, attr_cond, layout, coords + ) + else: + raise Exception("No handler for Array type: " + str(type(self.array))) diff --git a/testbed/TileDB-Inc__TileDB-Py/tiledb/enumeration.py b/testbed/TileDB-Inc__TileDB-Py/tiledb/enumeration.py new file mode 100644 index 0000000000000000000000000000000000000000..2bd7e930a57ef0a94e7c9e43b0853f3801561dd0 --- /dev/null +++ b/testbed/TileDB-Inc__TileDB-Py/tiledb/enumeration.py @@ -0,0 +1,163 @@ +from __future__ import annotations + +import io +from typing import Any, Optional, Sequence + +import numpy as np +from numpy.typing import NDArray + +import tiledb.cc as lt + +from .ctx import Ctx, CtxMixin +from .datatypes import DataType + + +class Enumeration(CtxMixin, lt.Enumeration): + """ + Represents a TileDB Enumeration. + """ + + def __init__( + self, + name: str, + ordered: bool, + values: Optional[Sequence[Any]] = None, + dtype: Optional[np.dtype] = None, + ctx: Optional[Ctx] = None, + ): + """Class representing the TileDB Enumeration. + + :param name: The name of the to-be created Enumeration + :type name: str + :param ordered: Whether or not to consider this enumeration ordered + :type ordered: bool + :param values: A Numpy array of values for this enumeration + :type values: np.array + :param dtype: The Numpy data type for this enumeration + :type dtype: np.dtype + :param ctx: A TileDB context + :type ctx: tiledb.Ctx + """ + if values is None or len(values) == 0: + if dtype is None: + raise ValueError("dtype must be provided for empty enumeration") + super().__init__(ctx, name, np.dtype(dtype), ordered) + + values = np.array(values) + if np.dtype(values.dtype).kind in "US": + dtype = ( + lt.DataType.STRING_UTF8 + if values.dtype.kind == "U" + else lt.DataType.STRING_ASCII + ) + super().__init__(ctx, name, values, ordered, dtype) + else: + super().__init__(ctx, name, ordered, values, np.array([])) + + @property + def name(self) -> str: + """The enumeration label string. + + :rtype: str + """ + return super().name + + @property + def dtype(self) -> np.dtype: + """Numpy dtype representation of the enumeration type. + + :rtype: numpy.dtype + """ + return DataType.from_tiledb(super().type).np_dtype + + @property + def cell_val_num(self) -> int: + """The enumeration's cell value number. + + :rtype: int + """ + return super().cell_val_num + + @property + def ordered(self) -> bool: + """True if the enumeration is ordered. + + :rtype: bool + """ + return super().ordered + + def values(self) -> NDArray: + """The values of the enumeration. + + :rtype: NDArray + """ + if self.dtype.kind == "U": + return np.array(super().str_values(), dtype=np.str_) + elif self.dtype.kind == "S": + return np.array(super().str_values(), dtype=np.bytes_) + else: + return np.array(super().values(), dtype=self.dtype) + + def extend(self, values: Sequence[Any]) -> Enumeration: + """Add additional values to the enumeration. + + :param values: The values to add to the enumeration + :rtype: Enumeration + """ + values = np.array(values) + if self.dtype.kind in "US" and values.dtype.kind not in "US": + raise lt.TileDBError("Passed in enumeration must be string type") + + if np.issubdtype(self.dtype, np.integer) and not np.issubdtype( + values.dtype, np.integer + ): + raise lt.TileDBError("Passed in enumeration must be integer type") + + return Enumeration.from_pybind11(self._ctx, super().extend(values)) + + def __eq__(self, other): + if not isinstance(other, Enumeration): + return False + + return all( + [ + self.name == other.name, + self.dtype == other.dtype, + self.cell_val_num == other.cell_val_num, + self.ordered == other.ordered, + np.array_equal(self.values(), other.values()), + ] + ) + + def __repr__(self): + # use safe repr if pybind11 constructor failed + if self._ctx is None: + return object.__repr__(self) + + return f"Enumeration(name='{self.name}', dtype={self.dtype}, dtype_name='{self.dtype.name}', cell_val_num={self.cell_val_num}, ordered={self.ordered}, values={list(self.values())})" + + def _repr_html_(self): + output = io.StringIO() + + output.write("") + output.write("") + output.write("") + output.write("") + output.write("") + output.write("") + output.write(f"{self._repr_html_row_only_()}") + output.write("
NameData TypeOrdered
") + + return output.getvalue() + + def _repr_html_row_only_(self): + output = io.StringIO() + + output.write("") + output.write(f"{self.name}") + output.write(f"{self.dtype}") + output.write(f"{self.cell_val_num}") + output.write(f"{self.ordered}") + output.write("") + + return output.getvalue() diff --git a/testbed/TileDB-Inc__TileDB-Py/tiledb/filestore.py b/testbed/TileDB-Inc__TileDB-Py/tiledb/filestore.py new file mode 100644 index 0000000000000000000000000000000000000000..ffe0de7660a770fcffc35f2cfcd58366301489ee --- /dev/null +++ b/testbed/TileDB-Inc__TileDB-Py/tiledb/filestore.py @@ -0,0 +1,151 @@ +import warnings +from typing import ByteString, Optional + +import tiledb.cc as lt + +from .ctx import Ctx, default_ctx + + +class Filestore: + """ + Functions to set and get data to and from a TileDB Filestore Array. + + A Filestore Array may be created using `ArraySchema.from_file` combined + with `Array.create`. + + :param str uri: The URI to the TileDB Fileshare Array + :param tiledb.Ctx ctx: A TileDB context + """ + + def __init__(self, uri: str, ctx: Optional[Ctx] = None) -> None: + self._ctx = ctx or default_ctx() + self._filestore_uri = uri + + def write(self, buffer: ByteString, mime_type: str = "AUTODETECT") -> None: + """ + Import data from an object that supports the buffer protocol to a Filestore Array. + + :param buffer ByteString: Data of type bytes, bytearray, memoryview, etc. + :param str mime_type: MIME types are "AUTODETECT" (default), "image/tiff", "application/pdf" + + """ + try: + buffer = memoryview(buffer) + except TypeError: + raise TypeError( + "Unexpected buffer type: buffer must support buffer protocol" + ) + + if not isinstance(mime_type, str): + raise TypeError( + f"Unexpected mime_type type '{type(mime_type)}': expected str" + ) + + try: + lt.Filestore._buffer_import( + self._ctx, + self._filestore_uri, + buffer, + lt.Filestore._mime_type_from_str(mime_type), + ) + except Exception as e: + raise (e) + + def read(self, offset: int = 0, size: int = -1) -> bytes: + """ + :param int offset: Byte position to begin reading. Defaults to beginning of filestore. + :param int size: Total number of bytes to read. Defaults to -1 which reads the entire filestore. + :rtype: bytes + :return: Data from the Filestore Array + + """ + if not isinstance(offset, int): + raise TypeError(f"Unexpected offset type '{type(offset)}': expected int") + + if not isinstance(size, int): + raise TypeError(f"Unexpected size type '{type(size)}': expected int") + + if size == -1: + size = len(self) + size = min(size, len(self) - offset) + + return lt.Filestore._buffer_export( + self._ctx, + self._filestore_uri, + offset, + size, + ) + + @staticmethod + def copy_from( + filestore_array_uri: str, + file_uri: str, + mime_type: str = "AUTODETECT", + ctx: Optional[Ctx] = None, + ) -> None: + """ + Copy data from a file to a Filestore Array. + + :param str filestore_array_uri: The URI to the TileDB Fileshare Array + :param str file_uri: URI of file to export + :param str mime_type: MIME types are "AUTODETECT" (default), "image/tiff", "application/pdf" + :param tiledb.Ctx ctx: A TileDB context + + """ + if not isinstance(filestore_array_uri, str): + raise TypeError( + f"Unexpected filestore_array_uri type '{type(filestore_array_uri)}': expected str" + ) + + if not isinstance(file_uri, str): + raise TypeError( + f"Unexpected file_uri type '{type(file_uri)}': expected str" + ) + + if not isinstance(mime_type, str): + raise TypeError( + f"Unexpected mime_type type '{type(mime_type)}': expected str" + ) + + ctx = ctx or default_ctx() + + lt.Filestore._uri_import( + ctx, + filestore_array_uri, + file_uri, + lt.Filestore._mime_type_from_str(mime_type), + ) + + @staticmethod + def copy_to( + filestore_array_uri: str, file_uri: str, ctx: Optional[Ctx] = None + ) -> None: + """ + Copy data from a Filestore Array to a file. + + :param str filestore_array_uri: The URI to the TileDB Fileshare Array + :param str file_uri: The URI to the TileDB Fileshare Array + :param tiledb.Ctx ctx: A TileDB context + + """ + if not isinstance(filestore_array_uri, str): + raise TypeError( + f"Unexpected filestore_array_uri type '{type(filestore_array_uri)}': expected str" + ) + + if not isinstance(file_uri, str): + raise TypeError( + f"Unexpected file_uri type '{type(file_uri)}': expected str" + ) + + ctx = ctx or default_ctx() + + lt.Filestore._uri_export(ctx, filestore_array_uri, file_uri) + + def __len__(self) -> int: + """ + :rtype: int + :return: Bytes in the Filestore Array + + """ + return lt.Filestore._size(self._ctx, self._filestore_uri) diff --git a/testbed/TileDB-Inc__TileDB-Py/tiledb/filter.py b/testbed/TileDB-Inc__TileDB-Py/tiledb/filter.py new file mode 100644 index 0000000000000000000000000000000000000000..6d60c763adba548a7851a58ea279d136698ebdb7 --- /dev/null +++ b/testbed/TileDB-Inc__TileDB-Py/tiledb/filter.py @@ -0,0 +1,989 @@ +import io +from typing import List, Optional, Sequence, Union, overload + +import numpy as np + +import tiledb.cc as lt + +from .ctx import Ctx, CtxMixin +from .datatypes import DataType + + +class Filter(CtxMixin, lt.Filter): + """Base class for all TileDB filters.""" + + options: Sequence[lt.FilterOption] = () + + def __init__(self, type: lt.FilterOption, ctx: Optional[Ctx] = None): + super().__init__(ctx, type) + + def __repr__(self) -> str: + # use safe repr if pybind11 constructor failed + if self._ctx is None: + return object.__repr__(self) + + output = io.StringIO() + output.write(f"{type(self).__name__}(") + if hasattr(self, "_attrs_"): + attr_output = [] + for f in self._attrs_(): + a = getattr(self, f) + attr_output.append(f"{f}={a}") + output.write(",".join(attr_output)) + output.write(")") + return output.getvalue() + + def _repr_html_(self) -> str: + output = io.StringIO() + + opt = list(self._attrs_().keys())[0] if self._attrs_() else "" + val = getattr(self, opt) if self._attrs_() else "" + + output.write("
\n") + output.write("\n") + output.write("\n") + output.write(f"\n") + output.write(f"") + output.write(f"") + output.write("\n") + output.write("
{type(self).__name__}{opt}{val}
\n") + output.write("
\n") + + return output.getvalue() + + def __eq__(self, other: "Filter"): + if other.__class__ is not self.__class__: + return False + for f in self._attrs_(): + left = getattr(self, f) + right = getattr(other, f) + if left != right: + return False + return True + + @property + def filter_name(self): + return self._type.name + + +class CompressionFilter(Filter): + """ + Base class for filters performing compression. + + All compression filters support a compression level option, although + some (such as RLE) ignore it. + + **Example:** + + >>> import tiledb, numpy as np, tempfile + >>> with tempfile.TemporaryDirectory() as tmp: + ... dom = tiledb.Domain(tiledb.Dim(domain=(0, 9), tile=2, dtype=np.uint64)) + ... a1 = tiledb.Attr(name="a1", dtype=np.int64, + ... filters=tiledb.FilterList([tiledb.CompressionFilter(level=10)])) + ... schema = tiledb.ArraySchema(domain=dom, attrs=(a1,)) + ... tiledb.DenseArray.create(tmp + "/array", schema) + + """ + + options = (lt.FilterOption.COMPRESSION_LEVEL,) + + def __init__(self, type: lt.FilterType, level: int = -1, ctx: Optional[Ctx] = None): + if not isinstance(level, int): + raise ValueError("`level` argument must be a int") + + super().__init__(type, ctx) + self._set_option(self._ctx, lt.FilterOption.COMPRESSION_LEVEL, level) + + @property + def level(self): + return self._get_option(self._ctx, lt.FilterOption.COMPRESSION_LEVEL) + + +class NoOpFilter(Filter): + """A filter that does nothing.""" + + def __init__(self, ctx: Optional[Ctx] = None): + super().__init__(lt.FilterType.NONE, ctx) + + def _attrs_(self): + return {} + + +class GzipFilter(CompressionFilter): + """ + Filter that compresses using gzip. + + :param ctx: TileDB Ctx + :type ctx: tiledb.Ctx + :param level: -1 (default) sets the compressor level to the default level as specified in TileDB core. Otherwise, sets the compressor level to the given value. + :type level: int + + **Example:** + + >>> import tiledb, numpy as np, tempfile + >>> with tempfile.TemporaryDirectory() as tmp: + ... dom = tiledb.Domain(tiledb.Dim(domain=(0, 9), tile=2, dtype=np.uint64)) + ... a1 = tiledb.Attr(name="a1", dtype=np.int64, + ... filters=tiledb.FilterList([tiledb.GzipFilter()])) + ... schema = tiledb.ArraySchema(domain=dom, attrs=(a1,)) + ... tiledb.DenseArray.create(tmp + "/array", schema) + + """ + + def __init__(self, level: int = -1, ctx: Optional[Ctx] = None): + if not isinstance(level, int): + raise ValueError("`level` argument must be a int") + + super().__init__(lt.FilterType.GZIP, level, ctx) + + def _attrs_(self): + return {"level": self.level} + + +class ZstdFilter(CompressionFilter): + """ + Filter that compresses using zstd. + + :param ctx: TileDB Ctx + :type ctx: tiledb.Ctx + :param level: -1 (default) sets the compressor level to the default level as specified in TileDB core. Otherwise, sets the compressor level to the given value. + :type level: int + + **Example:** + + >>> import tiledb, numpy as np, tempfile + >>> with tempfile.TemporaryDirectory() as tmp: + ... dom = tiledb.Domain(tiledb.Dim(domain=(0, 9), tile=2, dtype=np.uint64)) + ... a1 = tiledb.Attr(name="a1", dtype=np.int64, + ... filters=tiledb.FilterList([tiledb.ZstdFilter()])) + ... schema = tiledb.ArraySchema(domain=dom, attrs=(a1,)) + ... tiledb.DenseArray.create(tmp + "/array", schema) + + """ + + def __init__(self, level: int = -1, ctx: Optional[Ctx] = None): + if not isinstance(level, int): + raise ValueError("`level` argument must be a int") + + super().__init__(lt.FilterType.ZSTD, level, ctx) + + def _attrs_(self): + return {"level": self.level} + + +class LZ4Filter(CompressionFilter): + """ + Filter that compresses using lz4. + + :param ctx: TileDB Ctx + :type ctx: tiledb.Ctx + :param level: -1 (default) sets the compressor level to the default level as specified in TileDB core. Otherwise, sets the compressor level to the given value. + :type level: int + + **Example:** + + >>> import tiledb, numpy as np, tempfile + >>> with tempfile.TemporaryDirectory() as tmp: + ... dom = tiledb.Domain(tiledb.Dim(domain=(0, 9), tile=2, dtype=np.uint64)) + ... a1 = tiledb.Attr(name="a1", dtype=np.int64, + ... filters=tiledb.FilterList([tiledb.LZ4Filter()])) + ... schema = tiledb.ArraySchema(domain=dom, attrs=(a1,)) + ... tiledb.DenseArray.create(tmp + "/array", schema) + + """ + + def __init__(self, level: int = -1, ctx: Optional[Ctx] = None): + if not isinstance(level, int): + raise ValueError("`level` argument must be a int") + + super().__init__(lt.FilterType.LZ4, level, ctx) + + def _attrs_(self): + return {"level": self.level} + + +class Bzip2Filter(CompressionFilter): + """ + Filter that compresses using bzip2. + + :param level: -1 (default) sets the compressor level to the default level as specified in TileDB core. Otherwise, sets the compressor level to the given value. + :type level: int + + **Example:** + + >>> import tiledb, numpy as np, tempfile + >>> with tempfile.TemporaryDirectory() as tmp: + ... dom = tiledb.Domain(tiledb.Dim(domain=(0, 9), tile=2, dtype=np.uint64)) + ... a1 = tiledb.Attr(name="a1", dtype=np.int64, + ... filters=tiledb.FilterList([tiledb.Bzip2Filter()])) + ... schema = tiledb.ArraySchema(domain=dom, attrs=(a1,)) + ... tiledb.DenseArray.create(tmp + "/array", schema) + + """ + + def __init__(self, level: int = -1, ctx: Optional[Ctx] = None): + if not isinstance(level, int): + raise ValueError("`level` argument must be a int") + + super().__init__(lt.FilterType.BZIP2, level, ctx) + + def _attrs_(self): + return {"level": self.level} + + +class RleFilter(CompressionFilter): + """ + Filter that compresses using run-length encoding (RLE). + + :param level: -1 (default) sets the compressor level to the default level as specified in TileDB core. Otherwise, sets the compressor level to the given value. + :type level: int + + **Example:** + + >>> import tiledb, numpy as np, tempfile + >>> with tempfile.TemporaryDirectory() as tmp: + ... dom = tiledb.Domain(tiledb.Dim(domain=(0, 9), tile=2, dtype=np.uint64)) + ... a1 = tiledb.Attr(name="a1", dtype=np.int64, + ... filters=tiledb.FilterList([tiledb.RleFilter()])) + ... schema = tiledb.ArraySchema(domain=dom, attrs=(a1,)) + ... tiledb.DenseArray.create(tmp + "/array", schema) + + """ + + def __init__(self, level: int = -1, ctx: Optional[Ctx] = None): + if not isinstance(level, int): + raise ValueError("`level` argument must be a int") + + super().__init__(lt.FilterType.RLE, level, ctx) + + def _attrs_(self): + return {} + + +class DeltaFilter(CompressionFilter): + """ + Filter that compresses using run-length encoding (RLE). + + :param level: -1 (default) sets the compressor level to the default level as specified in TileDB core. Otherwise, sets the compressor level to the given value. + :type level: int + :param reinterp_dtype: (optional) sets the compressor to compress the data treating + as the new datatype. + :type reinterp_dtype: numpy, lt.DataType + **Example:** + + >>> import tiledb, numpy as np, tempfile + >>> with tempfile.TemporaryDirectory() as tmp: + ... dom = tiledb.Domain(tiledb.Dim(domain=(0, 9), tile=2, dtype=np.uint64)) + ... a1 = tiledb.Attr(name="a1", dtype=np.int64, + ... filters=tiledb.FilterList([tiledb.DeltaFilter()])) + ... schema = tiledb.ArraySchema(domain=dom, attrs=(a1,)) + ... tiledb.DenseArray.create(tmp + "/array", schema) + + """ + + options = ( + lt.FilterOption.COMPRESSION_LEVEL, + lt.FilterOption.COMPRESSION_REINTERPRET_DATATYPE, + ) + + def __init__( + self, + level: int = -1, + reinterp_dtype: Optional[Union[np.dtype, lt.DataType]] = None, + ctx: Optional[Ctx] = None, + ): + if not isinstance(level, int): + raise ValueError("`level` argument must be a int") + + super().__init__(lt.FilterType.DELTA, level, ctx) + + if reinterp_dtype is not None: + if isinstance(reinterp_dtype, lt.DataType): + dtype = reinterp_dtype + else: + dtype = DataType.from_numpy(reinterp_dtype).tiledb_type + self._set_option( + self._ctx, lt.FilterOption.COMPRESSION_REINTERPRET_DATATYPE, dtype + ) + + def _attrs_(self): + return {"reinterp_dtype": self.reinterp_dtype} + + @property + def reinterp_dtype(self): + tiledb_dtype = self._get_option( + self._ctx, lt.FilterOption.COMPRESSION_REINTERPRET_DATATYPE + ) + if tiledb_dtype == lt.DataType.ANY: + return None + dtype = DataType.from_tiledb(tiledb_dtype) + return dtype.np_dtype + + +class DoubleDeltaFilter(CompressionFilter): + """ + Filter that performs double-delta encoding. + + :param level: -1 (default) sets the compressor level to the default level as specified in TileDB core. Otherwise, sets the compressor level to the given value. + :type level: int + :param reinterp_dtype: (optional) sets the compressor to compress the data treating as the new datatype. + + **Example:** + + >>> import tiledb, numpy as np, tempfile + >>> with tempfile.TemporaryDirectory() as tmp: + ... dom = tiledb.Domain(tiledb.Dim(domain=(0, 9), tile=2, dtype=np.uint64)) + ... a1 = tiledb.Attr(name="a1", dtype=np.int64, + ... filters=tiledb.FilterList([tiledb.DoubleDeltaFilter()])) + ... schema = tiledb.ArraySchema(domain=dom, attrs=(a1,)) + ... tiledb.DenseArray.create(tmp + "/array", schema) + + """ + + options = ( + lt.FilterOption.COMPRESSION_LEVEL, + lt.FilterOption.COMPRESSION_REINTERPRET_DATATYPE, + ) + + def __init__( + self, + level: int = -1, + reinterp_dtype: Optional[Union[np.dtype, lt.DataType]] = None, + ctx: Optional[Ctx] = None, + ): + if not isinstance(level, int): + raise ValueError("`level` argument must be a int") + + super().__init__(lt.FilterType.DOUBLE_DELTA, level, ctx) + + if reinterp_dtype is not None: + if isinstance(reinterp_dtype, lt.DataType): + dtype = reinterp_dtype + else: + dtype = DataType.from_numpy(reinterp_dtype).tiledb_type + self._set_option( + self._ctx, lt.FilterOption.COMPRESSION_REINTERPRET_DATATYPE, dtype + ) + + def _attrs_(self): + return {"reinterp_dtype": self.reinterp_dtype} + + @property + def reinterp_dtype(self): + tiledb_dtype = self._get_option( + self._ctx, lt.FilterOption.COMPRESSION_REINTERPRET_DATATYPE + ) + if tiledb_dtype == lt.DataType.ANY: + return None + dtype = DataType.from_tiledb(tiledb_dtype) + return dtype.np_dtype + + +class DictionaryFilter(CompressionFilter): + """ + Filter that performs dictionary encoding. + + :param level: -1 (default) sets the compressor level to the default level as specified in TileDB core. Otherwise, sets the compressor level to the given value. + :type level: int + + **Example:** + + >>> import tiledb, numpy as np, tempfile + >>> with tempfile.TemporaryDirectory() as tmp: + ... dom = tiledb.Domain(tiledb.Dim(domain=(0, 9), tile=2, dtype=np.uint64)) + ... a1 = tiledb.Attr(name="a1", dtype=np.int64, + ... filters=tiledb.FilterList([tiledb.DictionaryFilter()])) + ... schema = tiledb.ArraySchema(domain=dom, attrs=(a1,)) + ... tiledb.DenseArray.create(tmp + "/array", schema) + + """ + + def __init__(self, level: int = -1, ctx: Optional[Ctx] = None): + if not isinstance(level, int): + raise ValueError("`level` argument must be a int") + + super().__init__(lt.FilterType.DICTIONARY, level, ctx) + + def _attrs_(self): + return {} + + +class BitShuffleFilter(Filter): + """ + Filter that performs a bit shuffle transformation. + + **Example:** + + >>> import tiledb, numpy as np, tempfile + >>> with tempfile.TemporaryDirectory() as tmp: + ... dom = tiledb.Domain(tiledb.Dim(domain=(0, 9), tile=2, dtype=np.uint64)) + ... a1 = tiledb.Attr(name="a1", dtype=np.int64, + ... filters=tiledb.FilterList([tiledb.BitShuffleFilter()])) + ... schema = tiledb.ArraySchema(domain=dom, attrs=(a1,)) + ... tiledb.DenseArray.create(tmp + "/array", schema) + + """ + + def __init__(self, ctx: Optional[Ctx] = None): + super().__init__(lt.FilterType.BITSHUFFLE, ctx) + + def _attrs_(self): + return {} + + +class ByteShuffleFilter(Filter): + """ + Filter that performs a byte shuffle transformation. + + **Example:** + + >>> import tiledb, numpy as np, tempfile + >>> with tempfile.TemporaryDirectory() as tmp: + ... dom = tiledb.Domain(tiledb.Dim(domain=(0, 9), tile=2, dtype=np.uint64)) + ... a1 = tiledb.Attr(name="a1", dtype=np.int64, + ... filters=tiledb.FilterList([tiledb.ByteShuffleFilter()])) + ... schema = tiledb.ArraySchema(domain=dom, attrs=(a1,)) + ... tiledb.DenseArray.create(tmp + "/array", schema) + + """ + + def __init__(self, ctx: Optional[Ctx] = None): + super().__init__(lt.FilterType.BYTESHUFFLE, ctx) + + def _attrs_(self): + return {} + + +class BitWidthReductionFilter(Filter): + """Filter that performs bit-width reduction. + + :param ctx: A TileDB Context + :type ctx: tiledb.Ctx + :param window: -1 (default) sets the max window size for the filter to the default window size as specified in TileDB core. Otherwise, sets the compressor level to the given value. + :type window: int + + **Example:** + + >>> import tiledb, numpy as np, tempfile + >>> with tempfile.TemporaryDirectory() as tmp: + ... dom = tiledb.Domain(tiledb.Dim(domain=(0, 9), tile=2, dtype=np.uint64)) + ... a1 = tiledb.Attr(name="a1", dtype=np.int64, + ... filters=tiledb.FilterList([tiledb.BitWidthReductionFilter()])) + ... schema = tiledb.ArraySchema(domain=dom, attrs=(a1,)) + ... tiledb.DenseArray.create(tmp + "/array", schema) + + """ + + options = (lt.FilterOption.BIT_WIDTH_MAX_WINDOW,) + + def __init__(self, window: int = -1, ctx: Optional[Ctx] = None): + if not isinstance(window, int): + raise ValueError("`window` argument must be a int") + + super().__init__(lt.FilterType.BIT_WIDTH_REDUCTION, ctx) + + if window != -1: + self._set_option(self._ctx, lt.FilterOption.BIT_WIDTH_MAX_WINDOW, window) + + def _attrs_(self): + return {"window": self.window} + + @property + def window(self): + return self._get_option(self._ctx, lt.FilterOption.BIT_WIDTH_MAX_WINDOW) + + +class PositiveDeltaFilter(Filter): + """ + Filter that performs positive-delta encoding. + + :param ctx: A TileDB Context + :type ctx: tiledb.Ctx + :param window: -1 (default) sets the max window size for the filter to the default window size as specified in TileDB core. Otherwise, sets the compressor level to the given value. + :type window: int + + **Example:** + + >>> import tiledb, numpy as np, tempfile + >>> with tempfile.TemporaryDirectory() as tmp: + ... dom = tiledb.Domain(tiledb.Dim(domain=(0, 9), tile=2, dtype=np.uint64)) + ... a1 = tiledb.Attr(name="a1", dtype=np.int64, + ... filters=tiledb.FilterList([tiledb.PositiveDeltaFilter()])) + ... schema = tiledb.ArraySchema(domain=dom, attrs=(a1,)) + ... tiledb.DenseArray.create(tmp + "/array", schema) + + """ + + options = (lt.FilterOption.POSITIVE_DELTA_MAX_WINDOW,) + + def __init__(self, window: int = -1, ctx: Optional[Ctx] = None): + if not isinstance(window, int): + raise ValueError("`window` argument must be a int") + + super().__init__(lt.FilterType.POSITIVE_DELTA, ctx) + if window != -1: + self._set_option( + self._ctx, lt.FilterOption.POSITIVE_DELTA_MAX_WINDOW, window + ) + + def _attrs_(self): + return {"window": self.window} + + @property + def window(self): + return self._get_option(self._ctx, lt.FilterOption.POSITIVE_DELTA_MAX_WINDOW) + + +class ChecksumMD5Filter(Filter): + """ + MD5 checksum filter. + + **Example:** + + >>> import tiledb, numpy as np, tempfile + >>> with tempfile.TemporaryDirectory() as tmp: + ... dom = tiledb.Domain(tiledb.Dim(domain=(0, 9), tile=2, dtype=np.uint64)) + ... a1 = tiledb.Attr(name="a1", dtype=np.int64, + ... filters=tiledb.FilterList([tiledb.ChecksumMD5Filter()])) + ... schema = tiledb.ArraySchema(domain=dom, attrs=(a1,)) + ... tiledb.DenseArray.create(tmp + "/array", schema) + + """ + + def __init__(self, ctx: Optional[Ctx] = None): + super().__init__(lt.FilterType.CHECKSUM_MD5, ctx) + + def _attrs_(self): + return {} + + +class ChecksumSHA256Filter(Filter): + """ + SHA256 checksum filter. + + **Example:** + + >>> import tiledb, numpy as np, tempfile + >>> with tempfile.TemporaryDirectory() as tmp: + ... dom = tiledb.Domain(tiledb.Dim(domain=(0, 9), tile=2, dtype=np.uint64)) + ... a1 = tiledb.Attr(name="a1", dtype=np.int64, + ... filters=tiledb.FilterList([tiledb.ChecksumSHA256Filter()])) + ... schema = tiledb.ArraySchema(domain=dom, attrs=(a1,)) + ... tiledb.DenseArray.create(tmp + "/array", schema) + + """ + + def __init__(self, ctx: Optional[Ctx] = None): + super().__init__(lt.FilterType.CHECKSUM_SHA256, ctx) + + def _attrs_(self): + return {} + + +class FloatScaleFilter(Filter): + """ + Filter that stores floats as integers in a reduced representation via scaling. + The reduced storage space is in lieu of some precision loss. The float scaling + filter takes three parameters: the factor, the offset, and the bytewidth. + On write, the float scaling filter applies the factor (scaling factor) and offset, + and stores the value of round((raw_float - offset) / factor) as an + integer with the specified NumPy dtype. + On read, the float scaling filter will reverse the factor and offset, + and returns the floating point data, with a potential loss of precision. + :param factor: the scaling factor used to translate the data + :type factor: float + :param offset: the offset value used to translate the data + :type offset: float + :param bytewidth: values may be stored as integers of bytewidth 1, 2, 4, or 8 + :type np.integer: + :param ctx: A TileDB Context + :type ctx: tiledb.Ctx + **Example:** + >>> import tiledb, numpy as np, tempfile + >>> with tempfile.TemporaryDirectory() as tmp: + ... dom = tiledb.Domain(tiledb.Dim(domain=(0, 9), tile=2, dtype=np.uint64)) + ... a1 = tiledb.Attr(name="a1", dtype=np.int64, + ... filters=tiledb.FilterList([tiledb.FloatScaleFilter(1, 0)])) + ... schema = tiledb.ArraySchema(domain=dom, attrs=(a1,)) + ... tiledb.DenseArray.create(tmp + "/array", schema) + """ + + options = ( + lt.FilterOption.SCALE_FLOAT_FACTOR, + lt.FilterOption.SCALE_FLOAT_OFFSET, + lt.FilterOption.SCALE_FLOAT_BYTEWIDTH, + ) + + def __init__( + self, + factor: float = None, + offset: float = None, + bytewidth: int = None, + ctx: Optional[Ctx] = None, + ): + self._factor = factor + self._offset = offset + self._bytewidth = bytewidth + super().__init__(lt.FilterType.SCALE_FLOAT, ctx) + + if factor: + self._set_option( + self._ctx, lt.FilterOption.SCALE_FLOAT_FACTOR, float(factor) + ) + + if offset is not None: + # 0 evals to false so we weren't actually setting here + # if offset==0 :upside-down-face: + self._set_option( + self._ctx, lt.FilterOption.SCALE_FLOAT_OFFSET, float(offset) + ) + + if bytewidth: + self._set_option( + self._ctx, lt.FilterOption.SCALE_FLOAT_BYTEWIDTH, bytewidth + ) + + def dump(self): + print(self._dump(), "\n") + + def _attrs_(self): + return { + "factor": self._factor, + "offset": self._offset, + "bytewidth": self._bytewidth, + } + + @property + def factor(self): + return self._get_option(self._ctx, lt.FilterOption.SCALE_FLOAT_FACTOR) + + @property + def offset(self): + return self._get_option(self._ctx, lt.FilterOption.SCALE_FLOAT_OFFSET) + + @property + def bytewidth(self): + return self._get_option(self._ctx, lt.FilterOption.SCALE_FLOAT_BYTEWIDTH) + + +class XORFilter(Filter): + """ + XOR filter. + + **Example:** + + >>> import tiledb, numpy as np, tempfile + >>> with tempfile.TemporaryDirectory() as tmp: + ... dom = tiledb.Domain(tiledb.Dim(domain=(0, 9), tile=2, dtype=np.uint64)) + ... a1 = tiledb.Attr(name="a1", dtype=np.int64, + ... filters=tiledb.FilterList([tiledb.XORFilter()])) + ... schema = tiledb.ArraySchema(domain=dom, attrs=(a1,)) + ... tiledb.DenseArray.create(tmp + "/array", schema) + + """ + + def __init__(self, ctx: Optional[Ctx] = None): + super().__init__(lt.FilterType.XOR, ctx) + + def _attrs_(self): + return {} + + +class WebpFilter(Filter): + """ + The WebP filter provides three options: quality, format, and lossless + + The quality option is used as quality_factor setting for WebP lossy + compression and expects a float value in the range of 0.0f - 100.0f + Quality of 0 corresponds to low quality and small output sizes, whereas 100 + is the highest quality and largest output size. + + The format option is used to define colorspace format of image data and + expects an enum of TILEDB_WEBP_RGB, TILEDB_WEBP_BGR, TILEDB_WEBP_RGBA, or + TILEDB_WEBP_BGRA. + + The lossless option is used to enable(1) or disable(0) lossless compression. + With this option enabled, the quality setting will be ignored. + + On write this filter takes raw colorspace values (RGB, RBGA, etc) and encodes + into WebP format before writing data to the array. + + On read, this filter decodes WebP data and returns raw colorspace values to + the caller. + + This filter expects the array to provide two dimensions for Y, X pixel position. + Dimensions may be defined with any name, but Y, X should be at dimension index 0, 1 respectively. + Dimensions can be any two matching integral types, such as `{uint64_t, uint64_t}` or `{int64_t, int64_t}`. + + The WebP filter supports only the `uint8_t` type for attributes. + + :param quality: quality_factor setting for lossy WebP compression + :type quality: float in range [0.0, 100.0] + :param input_format: The input colorspace format of the image + :type input_format: np.uint8 corresponding to one of TILEDB_WEBP_{RGB, BGR, RGBA, BGRA} + :param lossless: Enable (1) or disable (0) lossless image compression + :type lossless: np.uint8 + :param ctx: A TileDB Context + :type ctx: tiledb.Ctx + + **Example:** + + >>> import tiledb, numpy as np, tempfile + >>> with tempfile.TemporaryDirectory() as tmp: + ... # Using RGB colorspace format + ... pixel_depth = 3 # For RGBA / BGRA pixel_depth is 4 + ... dims = (tiledb.Dim(name='Y', + ... domain=(1, img_height), + ... dtype=np.uint8, + ... tile=img_height / 2,), + ... tiledb.Dim(name='X', + ... domain=(1, img_width * pixel_depth), + ... dtype=np.uint8, + ... tile=(img_width / 2) * pixel_depth,)) + ... dom = tiledb.Domain(*dims) + ... rgb = tiledb.Attr(name="rgb", dtype=np.uint8, + ... filters=tiledb.FilterList([tiledb.WebpFilter(input_format=1, quality=100.0, lossless=1)])) + ... schema = tiledb.ArraySchema(domain=dom, attrs=(rgb,)) + ... tiledb.DenseArray.create(tmp + "/array", schema) + + """ + + options = ( + lt.FilterOption.WEBP_INPUT_FORMAT, + lt.FilterOption.WEBP_QUALITY, + lt.FilterOption.WEBP_LOSSLESS, + ) + + # Expose WebP enums at the top level + WebpInputFormat = lt.WebpInputFormat + + def __init__( + self, + input_format: lt.WebpInputFormat = None, + quality: float = None, + lossless: bool = None, + ctx: Optional[Ctx] = None, + ): + self._input_format = input_format + self._quality = quality + self._lossless = lossless + super().__init__(lt.FilterType.WEBP, ctx) + + if input_format is not None: + self._set_option( + self._ctx, + lt.FilterOption.WEBP_INPUT_FORMAT, + lt.WebpInputFormat(input_format), + ) + + if quality is not None: + self._set_option(self._ctx, lt.FilterOption.WEBP_QUALITY, float(quality)) + + if lossless is not None: + self._set_option(self._ctx, lt.FilterOption.WEBP_LOSSLESS, lossless) + + def _attrs_(self): + return { + "input_format": self._input_format, + "quality": self._quality, + "lossless": self._lossless, + } + + @property + def input_format(self): + return lt.WebpInputFormat( + self._get_option(self._ctx, lt.FilterOption.WEBP_INPUT_FORMAT) + ) + + @property + def quality(self): + return self._get_option(self._ctx, lt.FilterOption.WEBP_QUALITY) + + @property + def lossless(self): + return self._get_option(self._ctx, lt.FilterOption.WEBP_LOSSLESS) + + +# +class FilterList(CtxMixin, lt.FilterList): + """ + An ordered list of Filter objects for filtering TileDB data. + + FilterLists contain zero or more Filters, used for filtering attribute data, the array coordinate data, etc. + + :param ctx: A TileDB context + :type ctx: tiledb.Ctx + :param filters: An iterable of Filter objects to add. + :param chunksize: (default None) chunk size used by the filter list in bytes + :type chunksize: int + + **Example:** + + >>> import tiledb, numpy as np, tempfile + >>> with tempfile.TemporaryDirectory() as tmp: + ... dom = tiledb.Domain(tiledb.Dim(domain=(0, 9), tile=2, dtype=np.uint64)) + ... # Create several filters + ... gzip_filter = tiledb.GzipFilter() + ... bw_filter = tiledb.BitWidthReductionFilter() + ... # Create a filter list that will first perform bit width reduction, then gzip compression. + ... filters = tiledb.FilterList([bw_filter, gzip_filter]) + ... a1 = tiledb.Attr(name="a1", dtype=np.int64, filters=filters) + ... # Create a second attribute filtered only by gzip compression. + ... a2 = tiledb.Attr(name="a2", dtype=np.int64, + ... filters=tiledb.FilterList([gzip_filter])) + ... schema = tiledb.ArraySchema(domain=dom, attrs=(a1, a2)) + ... tiledb.DenseArray.create(tmp + "/array", schema) + + """ + + filter_type_cc_to_python = { + lt.FilterType.GZIP: GzipFilter, + lt.FilterType.ZSTD: ZstdFilter, + lt.FilterType.LZ4: LZ4Filter, + lt.FilterType.BZIP2: Bzip2Filter, + lt.FilterType.RLE: RleFilter, + lt.FilterType.DELTA: DeltaFilter, + lt.FilterType.DOUBLE_DELTA: DoubleDeltaFilter, + lt.FilterType.BIT_WIDTH_REDUCTION: BitWidthReductionFilter, + lt.FilterType.BITSHUFFLE: BitShuffleFilter, + lt.FilterType.BYTESHUFFLE: ByteShuffleFilter, + lt.FilterType.POSITIVE_DELTA: PositiveDeltaFilter, + lt.FilterType.CHECKSUM_MD5: ChecksumMD5Filter, + lt.FilterType.CHECKSUM_SHA256: ChecksumSHA256Filter, + lt.FilterType.DICTIONARY: DictionaryFilter, + lt.FilterType.SCALE_FLOAT: FloatScaleFilter, + lt.FilterType.XOR: XORFilter, + lt.FilterType.WEBP: WebpFilter, + lt.FilterType.NONE: NoOpFilter, + } + + def __init__( + self, + filters: Sequence[Filter] = None, + chunksize: int = None, + ctx: Optional[Ctx] = None, + ): + super().__init__(ctx) + if filters is not None: + for f in filters: + if not isinstance(f, Filter): + raise ValueError( + "filters argument must be an iterable of TileDB filter objects" + ) + self._add_filter(f) + if chunksize is not None: + self._chunksize = chunksize + + @property + def chunksize(self): + return self._chunksize + + @overload + def __getitem__(self, idx: int) -> Filter: + ... + + @overload + def __getitem__(self, idx: slice) -> List[Filter]: + ... + + def __getitem__(self, idx): + """Gets a copy of the filter in the list at the given index + + :param idx: index into the + :type idx: int or slice + :returns: A filter at given index / slice + :raises IndexError: invalid index + :raises: :py:exc:`tiledb.TileDBError` + + """ + if not isinstance(idx, (int, slice)): + raise TypeError( + "FilterList indices must be integers or slices, not {:s}".format( + type(idx).__name__ + ) + ) + + if isinstance(idx, int): + if idx < 0 or idx > (len(self) - 1): + raise IndexError("FilterList index out of range") + idx = slice(idx, idx + 1) + else: + if ( + not isinstance(idx.start, int) + or not isinstance(idx.stop, int) + or not isinstance(idx.step, int) + ): + raise IndexError("FilterList slice indices must be integers or None") + + filters = [] + (start, stop, step) = idx.indices(len(self)) + for i in range(start, stop, step): + filters.append(self._filter(i)) + + if len(filters) == 1: + return filters[0] + + return filters + + def __eq__(self, other: Union["FilterList", Sequence[Filter]]) -> bool: + if other is None: + return False + if len(self) != len(other): + return False + for i, f in enumerate(self): + if f != other[i]: + return False + return True + + def __len__(self) -> int: + """ + :rtype: int + :return: Number of filters in the FilterList + + """ + return self._nfilters() + + def append(self, filter: Filter): + """ + :param Filter filter: the filter to append into the FilterList + :raises ValueError: filter argument incorrect type + + """ + if not isinstance(filter, Filter): + raise ValueError("filter argument must be a TileDB Filter object") + self._add_filter(filter) + + def __repr__(self) -> str: + filters = ",\n ".join(repr(self._filter(i)) for i in range(len(self))) + return "FilterList([{0!s}])".format(filters) + + def _repr_html_(self) -> str: + if len(self) == 0: + return "-" + + output = io.StringIO() + output.write("
\n") + output.write("\n") + output.write("\n") + output.write("\n") + output.write("\n") + output.write("\n") + output.write("\n") + for filter in self: + opt = list(filter._attrs_().keys())[0] if filter._attrs_() else "-" + val = getattr(filter, opt) if filter._attrs_() else "-" + output.write("\n") + output.write(f"\n") + output.write(f"") + output.write(f"") + output.write("\n") + output.write("
NameOptionLevel
{type(filter).__name__}{opt}{val}
\n") + output.write("
\n") + + return output.getvalue() + + def _filter(self, i: int) -> Filter: + fil = super()._filter(i) + filtype = self.filter_type_cc_to_python[fil._type] + ctx = self._ctx + return filtype(*(fil._get_option(ctx, opt) for opt in filtype.options), ctx=ctx) diff --git a/testbed/TileDB-Inc__TileDB-Py/tiledb/fragment.cc b/testbed/TileDB-Inc__TileDB-Py/tiledb/fragment.cc new file mode 100644 index 0000000000000000000000000000000000000000..e463626b50dd82fabe54e2f7f9e6d4f8fecb4034 --- /dev/null +++ b/testbed/TileDB-Inc__TileDB-Py/tiledb/fragment.cc @@ -0,0 +1,306 @@ + +#include +#include +#include +#include + +#include + +#include "util.h" +#include // C++ + +#if !defined(NDEBUG) +// #include "debug.cc" +#endif + +namespace tiledbpy { + +using namespace std; +using namespace tiledb; +namespace py = pybind11; +using namespace pybind11::literals; + +class PyFragmentInfo { + +private: + Context ctx_; + unique_ptr fi_; + + py::object schema_; + + uint32_t num_fragments_; + py::tuple uri_; + py::tuple version_; + py::tuple nonempty_domain_; + py::tuple cell_num_; + py::tuple timestamp_range_; + py::tuple sparse_; + uint32_t unconsolidated_metadata_num_; + py::tuple has_consolidated_metadata_; + py::tuple to_vacuum_; + py::tuple mbrs_; + py::tuple array_schema_name_; + +public: + tiledb_ctx_t *c_ctx_; + +public: + PyFragmentInfo() = delete; + + PyFragmentInfo(const string &uri, py::object schema, py::bool_ include_mbrs, + py::object ctx) { + schema_ = schema; + + tiledb_ctx_t *c_ctx_ = (py::capsule)ctx.attr("__capsule__")(); + + if (c_ctx_ == nullptr) + TPY_ERROR_LOC("Invalid context pointer!"); + + ctx_ = Context(c_ctx_, false); + + fi_ = unique_ptr(new FragmentInfo(ctx_, uri)); + + load(); + + num_fragments_ = fragment_num(); + uri_ = fill_uri(); + version_ = fill_version(); + nonempty_domain_ = fill_non_empty_domain(); + cell_num_ = fill_cell_num(); + timestamp_range_ = fill_timestamp_range(); + sparse_ = fill_sparse(); + unconsolidated_metadata_num_ = unconsolidated_metadata_num(); + has_consolidated_metadata_ = fill_has_consolidated_metadata(); + to_vacuum_ = fill_to_vacuum_uri(); + array_schema_name_ = fill_array_schema_name(); + + if (include_mbrs) + mbrs_ = fill_mbr(); + + close(); + } + + uint32_t get_num_fragments() { return num_fragments_; }; + py::tuple get_uri() { return uri_; }; + py::tuple get_version() { return version_; }; + py::tuple get_nonempty_domain() { return nonempty_domain_; }; + py::tuple get_cell_num() { return cell_num_; }; + py::tuple get_timestamp_range() { return timestamp_range_; }; + py::tuple get_sparse() { return sparse_; }; + uint32_t get_unconsolidated_metadata_num() { + return unconsolidated_metadata_num_; + }; + py::tuple get_has_consolidated_metadata() { + return has_consolidated_metadata_; + }; + py::tuple get_to_vacuum() { return to_vacuum_; }; + py::tuple get_mbrs() { return mbrs_; }; + py::tuple get_array_schema_name() { return array_schema_name_; }; + + void dump() const { return fi_->dump(stdout); } + +private: + template + py::object for_all_fid(T (FragmentInfo::*fn)(uint32_t) const) const { + py::list l; + uint32_t nfrag = fragment_num(); + + for (uint32_t i = 0; i < nfrag; ++i) + l.append((fi_.get()->*fn)(i)); + return py::tuple(l); + } + + void load() const { + try { + fi_->load(); + } catch (TileDBError &e) { + TPY_ERROR_LOC(e.what()); + } + } + + void close() { fi_.reset(); } + + py::tuple fill_uri() const { + return for_all_fid(&FragmentInfo::fragment_uri); + } + + py::tuple fill_non_empty_domain() const { + py::list all_frags; + uint32_t nfrag = fragment_num(); + + for (uint32_t fid = 0; fid < nfrag; ++fid) + all_frags.append(fill_non_empty_domain(fid)); + + return std::move(all_frags); + } + + py::tuple fill_non_empty_domain(uint32_t fid) const { + py::list all_dims; + int ndim = (schema_.attr("domain").attr("ndim")).cast(); + + for (int did = 0; did < ndim; ++did) + all_dims.append(fill_non_empty_domain(fid, did)); + + return std::move(all_dims); + } + + template + py::tuple fill_non_empty_domain(uint32_t fid, T did) const { + py::bool_ isvar = get_dim_isvar(schema_.attr("domain"), did); + + if (isvar) { + pair lims = fi_->non_empty_domain_var(fid, did); + return py::make_tuple(lims.first, lims.second); + } + + py::dtype type = get_dim_type(schema_.attr("domain"), did); + py::dtype array_type = + type.kind() == 'M' ? pybind11::dtype::of() : type; + + py::array limits = py::array(array_type, 2); + py::buffer_info buffer = limits.request(); + fi_->get_non_empty_domain(fid, did, buffer.ptr); + + if (type.kind() == 'M') { + auto np = py::module::import("numpy"); + auto datetime64 = np.attr("datetime64"); + auto datetime_data = np.attr("datetime_data"); + + uint64_t *dates = static_cast(buffer.ptr); + limits = py::make_tuple(datetime64(dates[0], datetime_data(type)), + datetime64(dates[1], datetime_data(type))); + } + + return std::move(limits); + } + + py::bool_ get_dim_isvar(py::object dom, uint32_t did) const { + // passing templated type "did" to Python function dom.attr("dim") + // does not work + return (dom.attr("dim")(did).attr("isvar")).cast(); + } + + py::bool_ get_dim_isvar(py::object dom, string did) const { + // passing templated type "did" to Python function dom.attr("dim") + // does not work + return (dom.attr("dim")(did).attr("isvar")).cast(); + } + + py::dtype get_dim_type(py::object dom, uint32_t did) const { + // passing templated type "did" to Python function dom.attr("dim") + // does not work + return (dom.attr("dim")(did).attr("dtype")).cast(); + } + + py::dtype get_dim_type(py::object dom, string did) const { + // passing templated type "did" to Python function dom.attr("dim") + // does not work + return (dom.attr("dim")(did).attr("dtype")).cast(); + } + + py::tuple fill_timestamp_range() const { + return for_all_fid(&FragmentInfo::timestamp_range); + } + + uint32_t fragment_num() const { return fi_->fragment_num(); } + + py::tuple fill_sparse() const { return for_all_fid(&FragmentInfo::sparse); } + + py::tuple fill_cell_num() const { + return for_all_fid(&FragmentInfo::cell_num); + } + + py::tuple fill_version() const { return for_all_fid(&FragmentInfo::version); } + + py::tuple fill_has_consolidated_metadata() const { + return for_all_fid(&FragmentInfo::has_consolidated_metadata); + } + + uint32_t unconsolidated_metadata_num() const { + return fi_->unconsolidated_metadata_num(); + } + + uint32_t to_vacuum_num() const { return fi_->to_vacuum_num(); } + + py::tuple fill_to_vacuum_uri() const { + py::list l; + uint32_t nfrag = to_vacuum_num(); + + for (uint32_t i = 0; i < nfrag; ++i) + l.append((fi_->to_vacuum_uri(i))); + return py::tuple(l); + } + + py::tuple fill_mbr() const { + py::list all_frags; + uint32_t nfrag = fragment_num(); + + for (uint32_t fid = 0; fid < nfrag; ++fid) + all_frags.append(fill_mbr(fid)); + + return std::move(all_frags); + } + + py::tuple fill_mbr(uint32_t fid) const { + py::list all_mbrs; + uint64_t nmbr = fi_->mbr_num(fid); + + for (uint32_t mid = 0; mid < nmbr; ++mid) + all_mbrs.append(fill_mbr(fid, mid)); + + return std::move(all_mbrs); + } + + py::tuple fill_mbr(uint32_t fid, uint32_t mid) const { + py::list all_dims; + int ndim = (schema_.attr("domain").attr("ndim")).cast(); + + for (int did = 0; did < ndim; ++did) + all_dims.append(fill_mbr(fid, mid, did)); + + return std::move(all_dims); + } + + py::tuple fill_mbr(uint32_t fid, uint32_t mid, uint32_t did) const { + py::bool_ isvar = get_dim_isvar(schema_.attr("domain"), did); + + if (isvar) { + auto limits = fi_->mbr_var(fid, mid, did); + return py::make_tuple(limits.first, limits.second); + } + + py::dtype type = get_dim_type(schema_.attr("domain"), did); + py::dtype array_type = + type.kind() == 'M' ? pybind11::dtype::of() : type; + py::array limits = py::array(array_type, 2); + py::buffer_info buffer = limits.request(); + fi_->get_mbr(fid, mid, did, buffer.ptr); + return std::move(limits); + } + + py::tuple fill_array_schema_name() const { + return for_all_fid(&FragmentInfo::array_schema_name); + } +}; + +void init_fragment(py::module &m) { + py::class_(m, "PyFragmentInfo") + .def(py::init()) + .def("get_num_fragments", &PyFragmentInfo::get_num_fragments) + .def("get_uri", &PyFragmentInfo::get_uri) + .def("get_version", &PyFragmentInfo::get_version) + .def("get_nonempty_domain", &PyFragmentInfo::get_nonempty_domain) + .def("get_cell_num", &PyFragmentInfo::get_cell_num) + .def("get_timestamp_range", &PyFragmentInfo::get_timestamp_range) + .def("get_sparse", &PyFragmentInfo::get_sparse) + .def("get_unconsolidated_metadata_num", + &PyFragmentInfo::get_unconsolidated_metadata_num) + .def("get_has_consolidated_metadata", + &PyFragmentInfo::get_has_consolidated_metadata) + .def("get_to_vacuum", &PyFragmentInfo::get_to_vacuum) + .def("get_mbrs", &PyFragmentInfo::get_mbrs) + .def("get_array_schema_name", &PyFragmentInfo::get_array_schema_name) + .def("dump", &PyFragmentInfo::dump); +} + +}; // namespace tiledbpy diff --git a/testbed/TileDB-Inc__TileDB-Py/tiledb/fragment.py b/testbed/TileDB-Inc__TileDB-Py/tiledb/fragment.py new file mode 100644 index 0000000000000000000000000000000000000000..04be4021adaad8f16ed96e8a3bf0d439c05f2173 --- /dev/null +++ b/testbed/TileDB-Inc__TileDB-Py/tiledb/fragment.py @@ -0,0 +1,516 @@ +import os +import pprint +import warnings + +import tiledb +from tiledb.libtiledb import version as libtiledb_version + +from .main import PyFragmentInfo + +""" +Classes and functions relating to TileDB fragments. +""" + + +class FragmentInfoList: + """ + Class representing an ordered list of FragmentInfo objects. + + :param array_uri: URI for the TileDB array (any supported TileDB URI) + :type array_uri: str + :param include_mbrs: (default False) include minimum bounding rectangles in FragmentInfo result + :type include_mbrs: bool + :param ctx: A TileDB context + :type ctx: tiledb.Ctx + + :ivar uri: URIs of fragments + :ivar version: Fragment version of each fragment + :ivar nonempty_domain: Non-empty domain of each fragment + :ivar cell_num: Number of cells in each fragment + :ivar timestamp_range: Timestamp range of when each fragment was written + :ivar sparse: For each fragment, True if fragment is sparse, else False + :ivar has_consolidated_metadata: For each fragment, True if fragment has consolidated fragment metadata, else False + :ivar unconsolidated_metadata_num: Number of unconsolidated metadata fragments in each fragment + :ivar to_vacuum: URIs of already consolidated fragments to vacuum + :ivar mbrs: (TileDB Embedded 2.5.0+ only) The mimimum bounding rectangle of each fragment; only present when `include_mbrs=True` + :ivar array_schema_name: (TileDB Embedded 2.5.0+ only) The array schema's name + + **Example:** + + >>> import tiledb, numpy as np, tempfile + >>> with tempfile.TemporaryDirectory() as tmp: + ... # The array will be 4x4 with dimensions "rows" and "cols", with domain [1,4] and space tiles 2x2 + ... dom = tiledb.Domain( + ... tiledb.Dim(name="rows", domain=(1, 4), tile=2, dtype=np.int32), + ... tiledb.Dim(name="cols", domain=(1, 4), tile=2, dtype=np.int32), + ... ) + ... # The array will be dense with a single attribute "a" so each (i,j) cell can store an integer. + ... schema = tiledb.ArraySchema( + ... domain=dom, sparse=False, attrs=[tiledb.Attr(name="a", dtype=np.int32)] + ... ) + ... # Set URI of the array + ... uri = tmp + "/array" + ... # Create the (empty) array on disk. + ... tiledb.Array.create(uri, schema) + ... + ... # Write three fragments to the array + ... with tiledb.DenseArray(uri, mode="w") as A: + ... A[1:3, 1:5] = np.array(([[1, 2, 3, 4], [5, 6, 7, 8]])) + ... with tiledb.DenseArray(uri, mode="w") as A: + ... A[2:4, 2:4] = np.array(([101, 102], [103, 104])) + ... with tiledb.DenseArray(uri, mode="w") as A: + ... A[3:4, 4:5] = np.array(([202])) + ... + ... # tiledb.array_fragments() requires TileDB-Py version > 0.8.5 + ... fragments_info = tiledb.array_fragments(uri) + ... + ... "====== FRAGMENTS INFO ======" + ... f"number of fragments: {len(fragments_info)}" + ... f"nonempty domains: {fragments_info.nonempty_domain}" + ... f"sparse fragments: {fragments_info.sparse}" + ... + ... for fragment in fragments_info: + ... f"===== FRAGMENT NUMBER {fragment.num} =====" + ... f"is sparse: {fragment.sparse}" + ... f"cell num: {fragment.cell_num}" + ... f"has consolidated metadata: {fragment.has_consolidated_metadata}" + ... f"nonempty domain: {fragment.nonempty_domain}" + '====== FRAGMENTS INFO ======' + 'number of fragments: 3' + 'nonempty domains: (((1, 2), (1, 4)), ((2, 3), (2, 3)), ((3, 3), (4, 4)))' + 'sparse fragments: (False, False, False)' + '===== FRAGMENT NUMBER 0 =====' + 'is sparse: False' + 'cell num: 8' + 'has consolidated metadata: False' + 'nonempty domain: ((1, 2), (1, 4))' + '===== FRAGMENT NUMBER 1 =====' + 'is sparse: False' + 'cell num: 16' + 'has consolidated metadata: False' + 'nonempty domain: ((2, 3), (2, 3))' + '===== FRAGMENT NUMBER 2 =====' + 'is sparse: False' + 'cell num: 4' + 'has consolidated metadata: False' + 'nonempty domain: ((3, 3), (4, 4))' + + """ + + def __init__(self, array_uri, include_mbrs=False, ctx=None): + if ctx is None: + ctx = tiledb.default_ctx() + + schema = tiledb.ArraySchema.load(array_uri, ctx=ctx) + + self.array_uri = array_uri + + fi = PyFragmentInfo(self.array_uri, schema, include_mbrs, ctx) + + self.__nums = fi.get_num_fragments() + self.uri = fi.get_uri() + self.version = fi.get_version() + self.nonempty_domain = fi.get_nonempty_domain() + self.cell_num = fi.get_cell_num() + self.timestamp_range = fi.get_timestamp_range() + self.sparse = fi.get_sparse() + self.unconsolidated_metadata_num = fi.get_unconsolidated_metadata_num() + self.has_consolidated_metadata = fi.get_has_consolidated_metadata() + self.to_vacuum = fi.get_to_vacuum() + + if include_mbrs: + if libtiledb_version() >= (2, 5, 0): + self.mbrs = fi.get_mbrs() + else: + warnings.warn( + "MBRs for fragments not available; " + "please install libtiledb 2.5.0+", + UserWarning, + ) + + if libtiledb_version() >= (2, 5, 0): + self.array_schema_name = fi.get_array_schema_name() + + def __getattr__(self, name): + if name == "mbrs": + raise AttributeError( + "'FragmentInfoList' object has no attribute 'mbrs'. " + "(Hint: retrieving minimum bounding rectangles is disabled " + "by default to optimize speed and space. " + "Use tiledb.array_fragments(include_mbrs=True) to enable)" + ) + return self.__getattribute__(name) + + def __iter__(self): + return FragmentsInfoIterator(self) + + def __getitem__(self, key): + if isinstance(key, slice): + # Get the start, stop, and step from the slice + return [FragmentInfo(self, idx) for idx in range(*key.indices(len(self)))] + elif isinstance(key, int): + return FragmentInfo(self, key) + else: + raise TypeError("Invalid argument type.") + + def __len__(self): + return self.__nums + + def __repr__(self): + public_attrs = { + key: value + for (key, value) in self.__dict__.items() + if not key.startswith("_") + } + return pprint.PrettyPrinter().pformat(public_attrs) + + def _repr_html_(self) -> str: + from io import StringIO + + output = StringIO() + output.write("
\n") + output.write(f"

Fragments for {self.array_uri}

\n") + for frag in self: + output.write("
\n") + output.write(f"{frag.uri}\n") + output.write(frag._repr_html_()) + output.write("
\n") + output.write("
\n") + return output.getvalue() + + +class FragmentsInfoIterator: + """ + Iterator class for the FragmentsInfo container. + """ + + def __init__(self, fragments): + self._fragments = fragments + self._index = 0 + + def __next__(self): + if self._index < len(self._fragments): + fi = FragmentInfo(self._fragments, self._index) + self._index += 1 + return fi + raise StopIteration + + +class FragmentInfo: + """ + Class representing the metadata for a single fragment. See :py:class:`tiledb.FragmentInfoList` for example of usage. + + :ivar uri: URIs of fragments + :ivar version: Fragment version of each fragment + :ivar nonempty_domain: Non-empty domain of each fragment + :ivar cell_num: Number of cells in each fragment + :ivar timestamp_range: Timestamp range of when each fragment was written + :ivar sparse: For each fragment, True if fragment is sparse, else False + :ivar has_consolidated_metadata: For each fragment, True if fragment has consolidated fragment metadata, else False + :ivar unconsolidated_metadata_num: Number of unconsolidated metadata fragments in each fragment + :ivar to_vacuum: URIs of already consolidated fragments to vacuum + :ivar mbrs: (TileDB Embedded 2.5.0+ only) The mimimum bounding rectangle of each fragment; only present when `include_mbrs=True` + :ivar array_schema_name: (TileDB Embedded 2.5.0+ only) The array schema's name + """ + + def __init__(self, fragments: FragmentInfoList, num): + self.num = num + self.uri = fragments.uri[num] + self.version = fragments.version[num] + self.nonempty_domain = fragments.nonempty_domain[num] + self.cell_num = fragments.cell_num[num] + self.timestamp_range = fragments.timestamp_range[num] + self.sparse = fragments.sparse[num] + self.has_consolidated_metadata = fragments.has_consolidated_metadata[num] + self.unconsolidated_metadata_num = fragments.unconsolidated_metadata_num + + if hasattr(fragments, "mbrs"): + self.mbrs = fragments.mbrs[num] + + if hasattr(fragments, "array_schema_name"): + self.array_schema_name = fragments.array_schema_name[num] + + def __repr__(self): + public_attrs = { + key: value + for (key, value) in self.__dict__.items() + if not key.startswith("_") + } + return pprint.PrettyPrinter().pformat(public_attrs) + + def _repr_html_(self) -> str: + from io import StringIO + + output = StringIO() + output.write("
\n") + output.write("\n") + for key in self.__dict__: + if not key.startswith("_"): + output.write("\n") + output.write(f"\n") + output.write(f"\n") + output.write("\n") + output.write("
{key}{self.__dict__[key]}
\n") + output.write("
\n") + + return output.getvalue() + + def __getattr__(self, name): + if name == "mbrs": + raise AttributeError( + "'FragmentInfo' object has no attribute 'mbrs'. " + "(Hint: retrieving minimum bounding rectangles is disabled " + "by default to optimize speed and space. " + "Use tiledb.array_fragments(include_mbrs=True) to enable)" + ) + return self.__getattribute__(name) + + +def create_array_from_fragments( + src_uri, + dst_uri, + timestamp_range, + config=None, + ctx=None, + verbose=False, + dry_run=False, +): + """ + (POSIX only). Create a new array from an already existing array by selecting + fragments that fall withing a given timestamp_range. The original array is located + at src_uri and the new array is created at dst_uri. + + :param str src_uri: URI for the source TileDB array (any supported TileDB URI) + :param str dst_uri: URI for the newly created TileDB array (any supported TileDB URI) + :param (int, int) timestamp_range: (default None) If not None, vacuum the + array using the given range (inclusive) + :param config: Override the context configuration. Defaults to ctx.config() + :param ctx: (optional) TileDB Ctx + :param verbose: (optional) Print fragments being copied (default: False) + :param dry_run: (optional) Preview fragments to be copied without + running (default: False) + """ + if tiledb.array_exists(dst_uri): + raise tiledb.TileDBError(f"Array URI `{dst_uri}` already exists") + + if not isinstance(timestamp_range, tuple) and len(timestamp_range) != 2: + raise TypeError( + "'timestamp_range' argument expects tuple(start: int, end: int)" + ) + + if not ctx: + ctx = tiledb.default_ctx() + + if config is None: + config = tiledb.Config(ctx.config()) + + vfs = tiledb.VFS(config=config, ctx=ctx) + + fragment_info = tiledb.array_fragments(src_uri) + + if len(fragment_info) < 1: + print("Cannot create new array; no fragments to copy") + return + + if verbose or dry_run: + print(f"Creating directory for array at {dst_uri}\n") + + if not dry_run: + vfs.create_dir(dst_uri) + + src_lock = os.path.join(src_uri, "__lock.tdb") + dst_lock = os.path.join(dst_uri, "__lock.tdb") + + if verbose or dry_run: + print(f"Copying lock file {dst_uri}\n") + + if not dry_run: + vfs.copy_file(f"{src_lock}", f"{dst_lock}") + + list_new_style_schema = [ver >= 10 for ver in fragment_info.version] + is_mixed_versions = len(set(list_new_style_schema)) > 1 + if is_mixed_versions: + raise tiledb.TileDBError( + "Cannot copy fragments - this array contains a mix of old and " + "new style schemas" + ) + is_new_style_schema = list_new_style_schema[0] + + for frag in fragment_info: + if not ( + timestamp_range[0] <= frag.timestamp_range[0] + and frag.timestamp_range[1] <= timestamp_range[1] + ): + continue + + schema_name = frag.array_schema_name + if is_new_style_schema: + schema_name = os.path.join("__schema", schema_name) + src_schema = os.path.join(src_uri, schema_name) + dst_schema = os.path.join(dst_uri, schema_name) + + if verbose or dry_run: + print(f"Copying schema `{src_schema}` to `{dst_schema}`\n") + + if not dry_run: + if is_new_style_schema: + new_style_schema_uri = os.path.join(dst_uri, "__schema") + if not vfs.is_dir(new_style_schema_uri): + vfs.create_dir(new_style_schema_uri) + + if not vfs.is_file(dst_schema): + vfs.copy_file(src_schema, dst_schema) + + base_name = os.path.basename(frag.uri) + if frag.version < 12: + frag_name = base_name + else: + vfs.create_dir(os.path.join(dst_uri, "__fragments")) + frag_name = os.path.join("__fragments", base_name) + + src_frag = os.path.join(src_uri, frag_name) + dst_frag = os.path.join(dst_uri, frag_name) + + if frag.version < 12: + ok_or_wrt_name = f"{base_name}.ok" + else: + vfs.create_dir(os.path.join(dst_uri, "__commits")) + ok_or_wrt_name = os.path.join("__commits", f"{base_name}.wrt") + + src_ok_or_wrt = os.path.join(src_uri, ok_or_wrt_name) + dst_ok_or_wrt = os.path.join(dst_uri, ok_or_wrt_name) + + if verbose or dry_run: + print(f"Copying `{src_frag}` to `{dst_frag}`\n") + print(f"Copying `{src_ok_or_wrt}` to `{dst_ok_or_wrt}`\n") + + if not dry_run: + vfs.copy_dir(src_frag, dst_frag) + vfs.copy_file(src_ok_or_wrt, dst_ok_or_wrt) + + +def copy_fragments_to_existing_array( + src_uri, + dst_uri, + timestamp_range, + config=None, + ctx=None, + verbose=False, + dry_run=False, +): + """ + (POSIX only). Copy fragments from an array at src_uri to another array at + dst_uri by selecting fragments that fall withing a given timestamp_range. + + :param str src_uri: URI for the source TileDB array (any supported TileDB URI) + :param str dst_uri: URI for the destination TileDB array (any supported TileDB URI) + :param (int, int) timestamp_range: (default None) If not None, vacuum the + array using the given range (inclusive) + :param config: Override the context configuration. Defaults to ctx.config() + :param ctx: (optional) TileDB Ctx + :param verbose: (optional) Print fragments being copied (default: False) + :param dry_run: (optional) Preview fragments to be copied without + running (default: False) + """ + if not tiledb.array_exists(dst_uri): + raise tiledb.TileDBError(f"Array URI `{dst_uri}` does not exist") + + if not isinstance(timestamp_range, tuple) and len(timestamp_range) != 2: + raise TypeError( + "'timestamp_range' argument expects tuple(start: int, end: int)" + ) + + if not ctx: + ctx = tiledb.default_ctx() + + if config is None: + config = tiledb.Config(ctx.config()) + + vfs = tiledb.VFS(config=config, ctx=ctx) + + dst_schema_file = os.path.join(dst_uri, "__array_schema.tdb") + src_schema_file = os.path.join(src_uri, "__array_schema.tdb") + dst_schema_dir = os.path.join(dst_uri, "__schema") + src_schema_dir = os.path.join(src_uri, "__schema") + + is_old_style = vfs.is_file(dst_schema_file) and vfs.is_file(src_schema_file) + is_new_style = vfs.is_dir(dst_schema_dir) and vfs.is_dir(src_schema_dir) + + if is_old_style and is_new_style: + raise tiledb.TileDBError( + "Mix of old and new style schemas detected. There can only be " + "one schema version present in both the source and destination " + "arrays and both must be identical" + ) + elif is_new_style: + + def filtered_schema_dir(uri): + return [x for x in vfs.ls(uri) if "__enumerations" not in x] + + if ( + len(filtered_schema_dir(dst_schema_dir)) != 1 + or len(filtered_schema_dir(src_schema_dir)) != 1 + ): + raise tiledb.TileDBError( + "Mutltiple evolved schemas detected. There can only be one " + "schema version present in both the source and destination " + "arrays and both must be identical" + ) + schema_name = os.path.basename(vfs.ls(src_schema_dir)[0]) + src_schema = os.path.join(src_uri, "__schema", schema_name) + dst_schema = os.path.join(dst_uri, "__schema", schema_name) + + if tiledb.ArraySchema.load(src_uri) != tiledb.ArraySchema.load(dst_uri): + raise tiledb.TileDBError( + "The source and destination array must have matching schemas." + ) + + if is_new_style: + if verbose or dry_run: + print(f"Copying schema `{src_schema}` to `{dst_schema}`\n") + + if not dry_run: + vfs.copy_file(src_schema, dst_schema) + + array_fragments = tiledb.array_fragments(src_uri) + + for frag in array_fragments: + if not ( + timestamp_range[0] <= frag.timestamp_range[0] + and frag.timestamp_range[1] <= timestamp_range[1] + ): + continue + + base_name = os.path.basename(frag.uri) + if frag.version < 12: + frag_name = base_name + else: + vfs.create_dir(os.path.join(dst_uri, "__fragments")) + frag_name = os.path.join("__fragments", base_name) + + src_frag = os.path.join(src_uri, frag_name) + dst_frag = os.path.join(dst_uri, frag_name) + + if frag.version < 12: + ok_or_wrt_name = f"{base_name}.ok" + else: + ok_or_wrt_name = os.path.join("__commits", f"{base_name}.wrt") + + src_ok_or_wrt = os.path.join(src_uri, ok_or_wrt_name) + dst_ok_or_wrt = os.path.join(dst_uri, ok_or_wrt_name) + + if src_frag == dst_frag: + if verbose or dry_run: + print( + f"Fragment {src_frag} not copied. Already exists in " + "destination array.\n" + ) + continue + + if verbose or dry_run: + print(f"Copying `{src_frag}` to `{dst_frag}`\n") + print(f"Copying `{src_ok_or_wrt}` to `{dst_ok_or_wrt}`\n") + + if not dry_run: + vfs.copy_dir(src_frag, dst_frag) + vfs.copy_file(src_ok_or_wrt, dst_ok_or_wrt) diff --git a/testbed/TileDB-Inc__TileDB-Py/tiledb/group.py b/testbed/TileDB-Inc__TileDB-Py/tiledb/group.py new file mode 100644 index 0000000000000000000000000000000000000000..ff1366adef9969bb19c920289dda925ca5f4ea09 --- /dev/null +++ b/testbed/TileDB-Inc__TileDB-Py/tiledb/group.py @@ -0,0 +1,525 @@ +from typing import MutableMapping, Optional, Union + +import numpy as np + +import tiledb.cc as lt + +from .ctx import Config, Ctx, CtxMixin, default_ctx +from .datatypes import DataType +from .object import Object + + +class Group(CtxMixin, lt.Group): + """ + Support for organizing multiple arrays in arbitrary directory hierarchies. + + Group members may be any number of nested groups and arrays. Members are stored as tiledb.Objects which indicate the member's URI and type. + + Groups may contain associated metadata similar to array metadata where + keys are strings. Singleton values may be of type int, float, str, or bytes. Multiple values of the same type may be placed in containers of type list, tuple, or 1-D np.ndarray. The values within containers are limited to type int or float. + + See more at: https://docs.tiledb.com/main/background/key-concepts-and-data-format#arrays-and-groups + + :param uri: The URI to the Group + :type uri: str + :param mode: Read mode ('r'), write mode ('w'), or modify exclusive ('m') + :type mode: str + :param config: A TileDB config + :type config: Config or dict + :param ctx: A TileDB context + :type ctx: tiledb.Ctx + + **Example:** + + >>> # Create a group + >>> grp_path = "root_group" + >>> tiledb.Group.create(grp_path) + >>> grp = tiledb.Group(grp_path, "w") + >>> + >>> # Create an array and add as a member to the group + >>> array_path = "array.tdb" + >>> domain = tiledb.Domain(tiledb.Dim(domain=(1, 8), tile=2)) + >>> a1 = tiledb.Attr("val", dtype="f8") + >>> schema = tiledb.ArraySchema(domain=domain, attrs=(a1,)) + >>> tiledb.Array.create(array_path, schema) + >>> grp.add(array_path) + >>> + >>> # Create a group and add as a subgroup + >>> subgrp_path = "sub_group" + >>> tiledb.Group.create(subgrp_path) + >>> grp.add(subgrp_path) + >>> + >>> # Add metadata to the subgroup + >>> grp.meta["ints"] = [1, 2, 3] + >>> grp.meta["str"] = "string_metadata" + >>> grp.close() + >>> + >>> grp.open("r") + >>> # Dump all the members in string format + >>> mbrs_repr = grp + >>> # Or create a list of Objects in the Group + >>> mbrs_iter = list(grp) + >>> # Get the first member's uri and type + >>> member_uri, member_type = grp[0].uri, grp[0].type + >>> grp.close() + >>> + >>> # Remove the subgroup + >>> grp.open("w") + >>> grp.remove(subgrp_path) + >>> grp.close() + >>> + >>> # Delete the subgroup + >>> grp.open("m") + >>> grp.delete(subgrp_path) + >>> grp.close() + """ + + _NP_DATA_PREFIX = "__np_flat_" + _NP_SHAPE_PREFIX = "__np_shape_" + + _mode_to_query_type = { + "r": lt.QueryType.READ, + "w": lt.QueryType.WRITE, + "m": lt.QueryType.MODIFY_EXCLUSIVE, + } + + _query_type_to_mode = {t: m for m, t in _mode_to_query_type.items()} + + __was_deleted__ = False + + class GroupMetadata(MutableMapping): + """ + Holds metadata for the associated Group in a dictionary-like structure. + """ + + GroupMetadataValueType = Union[int, float, str, bytes, np.ndarray] + + def __init__(self, group: "Group"): + self._group = group + + def __setitem__(self, key: str, value: GroupMetadataValueType): + """ + :param str key: Key for the Group metadata entry + :param value: Value for the Group metadata entry + :type value: Union[int, float, str, bytes, np.ndarray] + + """ + if not isinstance(key, str): + raise TypeError(f"Unexpected key type '{type(key)}': expected str") + + # ensure previous key(s) are deleted (e.g. in case of replacing a + # non-numpy value with a numpy value or vice versa) + del self[key] + + put_metadata = self._group._put_metadata + if isinstance(value, np.ndarray): + flat_value = value.ravel() + put_metadata(f"{Group._NP_DATA_PREFIX}{key}", flat_value) + if value.shape != flat_value.shape: + # If the value is not a 1D ndarray, store its associated shape. + # The value's shape will be stored as separate metadata with the correct prefix. + self.__setitem__(f"{Group._NP_SHAPE_PREFIX}{key}", value.shape) + elif isinstance(value, np.generic): + tiledb_type = DataType.from_numpy(value.dtype).tiledb_type + if tiledb_type in (lt.DataType.BLOB, lt.DataType.CHAR): + put_metadata(key, tiledb_type, len(value), value) + elif tiledb_type == lt.DataType.STRING_UTF8: + put_metadata( + key, lt.DataType.STRING_UTF8, len(value), value.encode("UTF-8") + ) + else: + put_metadata(key, tiledb_type, 1, value) + else: + from .metadata import pack_metadata_val + + packed_buf = pack_metadata_val(value) + tiledb_type = packed_buf.tdbtype + value_num = packed_buf.value_num + data_view = packed_buf.data + + put_metadata(key, tiledb_type, value_num, data_view) + + def __getitem__(self, key: str, include_type=False) -> GroupMetadataValueType: + """ + :param str key: Key of the Group metadata entry + :rtype: Union[int, float, str, bytes, np.ndarray] + :return: The value associated with the key + + """ + if not isinstance(key, str): + raise TypeError(f"Unexpected key type '{type(key)}': expected str") + + if self._group._has_metadata(key): + data, tdb_type = self._group._get_metadata(key, False) + dtype = DataType.from_tiledb(tdb_type).np_dtype + # we return all int and float values as numpy scalars + if dtype.kind in ("i", "f") and not isinstance(data, tuple): + data = np.dtype(dtype).type(data) + elif self._group._has_metadata(f"{Group._NP_DATA_PREFIX}{key}"): + data, tdb_type = self._group._get_metadata( + f"{Group._NP_DATA_PREFIX}{key}", True + ) + # reshape numpy array back to original shape, if needed + # this will not be found in any case for TileDB-Py <= 0.32.3. + shape_key = f"{Group._NP_SHAPE_PREFIX}{key}" + if self._group._has_metadata(shape_key): + shape, tdb_type = self._group._get_metadata(shape_key, False) + data = data.reshape(shape) + else: + raise KeyError(f"KeyError: {key}") + + return (data, tdb_type) if include_type else data + + def __delitem__(self, key: str): + """Removes the entry from the Group metadata. + + :param str key: Key of the Group metadata entry + + """ + if not isinstance(key, str): + raise TypeError(f"Unexpected key type '{type(key)}': expected str") + + # key may be stored as is or it may be prefixed (for numpy values) + # we don't know this here so delete all potential internal keys + for k in key, Group._NP_DATA_PREFIX + key, Group._NP_SHAPE_PREFIX + key: + self._group._delete_metadata(k) + + def __contains__(self, key: str) -> bool: + """ + :param str key: Key of the Group metadata entry + :rtype: bool + :return: True if the key is in the Group metadata, otherwise False + + """ + if not isinstance(key, str): + raise TypeError(f"Unexpected key type '{type(key)}': expected str") + + # key may be stored as is or it may be prefixed (for numpy values) + # we don't know this here so check all potential internal keys + return self._group._has_metadata(key) or self._group._has_metadata( + f"{Group._NP_DATA_PREFIX}{key}" + ) + + def __len__(self) -> int: + """ + :rtype: int + :return: Number of entries in the Group metadata + + """ + num = self._group._metadata_num() + # subtract the _NP_SHAPE_PREFIX prefixed keys + for key in self._iter(keys_only=True): + if key.startswith(Group._NP_SHAPE_PREFIX): + num -= 1 + + return num + + def _iter(self, keys_only: bool = True, dump: bool = False): + """ + Iterate over Group metadata keys or (key, value) tuples + :param keys_only: whether to yield just keys or values too + :param dump: whether to yield a formatted string for each metadata entry + """ + if keys_only and dump: + raise ValueError("keys_only and dump cannot both be True") + + metadata_num = self._group._metadata_num() + for i in range(metadata_num): + key = self._group._get_key_from_index(i) + + if keys_only: + yield key + else: + val, val_dtype = self.__getitem__(key, include_type=True) + + if dump: + yield ( + "### Array Metadata ###\n" + f"- Key: {key}\n" + f"- Value: {val}\n" + f"- Type: {val_dtype}\n" + ) + else: + yield key, val + + def __iter__(self): + np_data_prefix_len = len(Group._NP_DATA_PREFIX) + for key in self._iter(keys_only=True): + if key.startswith(Group._NP_DATA_PREFIX): + yield key[np_data_prefix_len:] + elif not key.startswith(Group._NP_SHAPE_PREFIX): + yield key + # else: ignore the shape keys + + def __repr__(self): + return str(dict(self)) + + def setdefault(self, key, default=None): + raise NotImplementedError( + "Group.GroupMetadata.setdefault requires read-write access" + ) + + def pop(self, key, default=None): + raise NotImplementedError( + "Group.GroupMetadata.pop requires read-write access" + ) + + def popitem(self): + raise NotImplementedError( + "Group.GroupMetadata.popitem requires read-write access" + ) + + def clear(self): + raise NotImplementedError( + "Group.GroupMetadata.clear requires read-write access" + ) + + def dump(self): + """Output information about all group metadata to stdout.""" + for metadata in self._iter(keys_only=False, dump=True): + print(metadata) + + def __init__( + self, + uri: str, + mode: str = "r", + config: Config = None, + ctx: Optional[Ctx] = None, + ): + if mode not in Group._mode_to_query_type: + raise ValueError(f"invalid mode {mode}") + query_type = Group._mode_to_query_type[mode] + + if config is None: + super().__init__(ctx, uri, query_type) + else: + super().__init__(ctx, uri, query_type, config) + + self._meta = self.GroupMetadata(self) + + @staticmethod + def create(uri: str, ctx: Optional[Ctx] = None): + """ + Create a new Group. + + :param uri: The URI to the to-be created Group + :type uri: str + :param ctx: A TileDB context + :type ctx: tiledb.Ctx + """ + ctx = ctx or default_ctx() + lt.Group._create(ctx, uri) + + def open(self, mode: str = "r"): + """ + Open a Group in read mode ("r") or write mode ("w"). + + :param mode: Read mode ('r') or write mode ('w') + :type mode: str + """ + if mode not in Group._mode_to_query_type: + raise ValueError(f"invalid mode {mode}") + query_type = Group._mode_to_query_type[mode] + + self._open(query_type) + + def close(self): + """ + Close a Group. + """ + self._close() + + def add(self, uri: str, name: str = None, relative: bool = False): + """ + Adds a member to the Group. + + :param uri: The URI of the member to add + :type uri: str + :param relative: Whether the path of the URI is a relative path (default=relative: False) + :type relative: bool + :param name: An optional name for the Group (default=None) + :type name: str + """ + if name: + self._add(uri, relative, name) + else: + self._add(uri, relative) + + def delete(self, recursive: bool = False): + """ + Delete a Group. The group needs to be opened in 'm' mode. + + :param uri: The URI of the group to delete + """ + self._delete_group(self.uri, recursive) + self.__was_deleted__ = True + + def __getitem__(self, member: Union[int, str]) -> Object: + """ + Retrieve a member from the Group as an Object. + + :param member: The index or name of the member + :type member: Union[int, str] + :return: The member as an Object + :rtype: Object + """ + if not isinstance(member, (int, str)): + raise TypeError( + f"Unexpected member type '{type(member)}': expected int or str" + ) + + obj = self._member(member) + return Object(obj._type, obj._uri, obj._name) + + def __len__(self) -> int: + """ + :rtype: int + :return: Number of members in the Group + + """ + return self._member_count() + + def remove(self, member: str): + """ + Remove a member from the Group. + + :param member: The URI or name of the member + :type member: str + """ + if not isinstance(member, str): + raise TypeError(f"Unexpected member type '{type(member)}': expected str") + + self._remove(member) + + def __delitem__(self, uri: str): + """ + Remove a member from the group. + + :param uri: The URI to the member + :type uri: str + """ + self._remove(uri) + + def __iter__(self): + return iter(self[i] for i in range(len(self))) + + def __contains__(self, member: str) -> bool: + """ + :return: Whether the Group contains a member with the given name + :rtype: bool + """ + return self._has_member(member) + + def __repr__(self): + # use safe repr if pybind11 constructor failed + if self._ctx is None: + return object.__repr__(self) + + return self._dump(True) + + def __enter__(self): + """ + The `__enter__` and `__exit__` methods allow TileDB groups to be opened (and auto-closed) + using with-as syntax. + """ + return self + + def __exit__(self, exc_type, exc_val, exc_tb): + """ + The `__enter__` and `__exit__` methods allow TileDB groups to be opened (and auto-closed) + using with-as syntax. + """ + # Don't close if this was a delete operation: the group will be closed + # automatically. + if not (hasattr(self, "__deleted") or self.__was_deleted__): + self.__was_deleted__ = False + self.close() + + @property + def meta(self) -> GroupMetadata: + """ + :return: The Group's metadata as a key-value structure + :rtype: GroupMetadata + """ + return self._meta + + @property + def isopen(self) -> bool: + """ + :return: Whether or not the Group is open + :rtype: bool + """ + return self._isopen + + @property + def uri(self) -> str: + """ + :return: URI of the Group + :rtype: str + """ + return self._uri + + @property + def mode(self) -> str: + """ + :return: Read mode ('r'), write mode ('w'), or modify exclusive ('m') + :rtype: str + """ + return self._query_type_to_mode[self._query_type] + + def is_relative(self, name: str) -> bool: + """ + :param name: Name of member to retrieve associated relative indicator + :type name: str + :return: Whether the attribute is relative + :rtype: bool + """ + return self._is_relative(name) + + def set_config(self, cfg: Config): + """ + :param cfg: Config to set on the Group + :type cfg: Config + """ + if self.isopen: + raise ValueError( + "`set_config` can only be used on closed groups. " + "Use `group.cl0se()` or Group(.., closed=True)" + ) + self._set_config(cfg) + + @staticmethod + def consolidate_metadata( + uri: str, config: Config = None, ctx: Optional[Ctx] = None + ): + """ + Consolidate the group metadata. + + :param uri: The URI of the TileDB group to be consolidated + :type uri: str + :param config: Optional configuration parameters for the consolidation + :type config: Config + :param ctx: Optional TileDB context + :type ctx: Ctx + """ + if ctx is None: + ctx = default_ctx() + + lt.Group._consolidate_metadata(ctx, uri, config) + + @staticmethod + def vacuum_metadata(uri: str, config: Config = None, ctx: Optional[Ctx] = None): + """ + Vacuum the group metadata. + + :param uri: The URI of the TileDB group to be vacuum + :type uri: str + :param config: Optional configuration parameters for the vacuuming + :type config: Config + :param ctx: Optional TileDB context + :type ctx: Ctx + """ + if ctx is None: + ctx = default_ctx() + + lt.Group._vacuum_metadata(ctx, uri, config) diff --git a/testbed/TileDB-Inc__TileDB-Py/tiledb/highlevel.py b/testbed/TileDB-Inc__TileDB-Py/tiledb/highlevel.py new file mode 100644 index 0000000000000000000000000000000000000000..243d476d13a7e3b7e830056582c88989a167c595 --- /dev/null +++ b/testbed/TileDB-Inc__TileDB-Py/tiledb/highlevel.py @@ -0,0 +1,566 @@ +import json +import warnings +from typing import Callable, Optional + +import numpy as np + +import tiledb +import tiledb.cc as lt + +from .dataframe_ import create_dim + + +def open(uri, mode="r", key=None, attr=None, config=None, timestamp=None, ctx=None): + """ + Open a TileDB array at the given URI + + :param uri: any TileDB supported URI + :param timestamp: array timestamp to open, int or None. + See the TileDB `time traveling `_ + documentation for detailed functionality description. + :param key: encryption key, str or None + :param str mode: (default 'r') Open the array object in read 'r', write 'w', modify exclusive 'm' mode, or delete 'd' mode + :param attr: attribute name to select from a multi-attribute array, str or None + :param config: TileDB config dictionary, dict or None + :return: open TileDB {Sparse,Dense}Array object + """ + return tiledb.Array.load_typed( + uri, + mode=mode, + key=key, + timestamp=timestamp, + attr=attr, + ctx=_get_ctx(ctx, config), + ) + + +def save(uri, array, **kwargs): + """ + Save array-like object at the given URI. + + :param uri: str or None + :param array: array-like object convertible to NumPy + :param kwargs: optional keyword args will be forwarded to tiledb.Array constructor + :return: + """ + # TODO: deprecate this in favor of from_numpy? + return from_numpy(uri, array, **kwargs) + + +def empty_like(uri, arr, config=None, key=None, tile=None, ctx=None, dtype=None): + """ + Create and return an empty, writeable DenseArray with schema based on + a NumPy-array like object. + + :param uri: array URI + :param arr: NumPy ndarray, or shape tuple + :param config: (optional, deprecated) configuration to apply to *new* Ctx + :param key: (optional) encryption key, if applicable + :param tile: (optional) tiling of generated array + :param ctx: (optional) TileDB Ctx + :param dtype: (optional) required if arr is a shape tuple + :return: + """ + ctx = _get_ctx(ctx, config) + if isinstance(arr, tuple): + if dtype is None: + raise ValueError("dtype must be valid data type (e.g. np.int32), not None") + schema = schema_like(shape=arr, tile=tile, ctx=ctx, dtype=dtype) + else: + schema = schema_like(arr, tile=tile, ctx=ctx) + tiledb.DenseArray.create(uri, schema, key=key, ctx=ctx) + return tiledb.DenseArray(uri, mode="w", key=key, ctx=ctx) + + +def from_numpy(uri, array, config=None, ctx=None, **kwargs): + """ + Write a NumPy array into a TileDB DenseArray, + returning a readonly DenseArray instance. + + :param str uri: URI for the TileDB array (any supported TileDB URI) + :param numpy.ndarray array: dense numpy array to persist + :param config: TileDB config dictionary, dict or None + :param tiledb.Ctx ctx: A TileDB Context + :param kwargs: additional arguments to pass to the DenseArray constructor + :rtype: tiledb.DenseArray + :return: An open DenseArray (read mode) with a single anonymous attribute + :raises TypeError: cannot convert ``uri`` to unicode string + :raises: :py:exc:`tiledb.TileDBError` + + :Keyword Arguments: + + * **full_domain** - Dimensions should be created with full range of the dtype (default: False) + * **mode** - Creation mode, one of 'ingest' (default), 'schema_only', 'append' + * **append_dim** - The dimension along which the Numpy array is append (default: 0). + * **start_idx** - The starting index to append to. By default, append to the end of the existing data. + * **timestamp** - Write TileDB array at specific timestamp. + * **dim_dtype** - Dimension data type, default np.uint64 + * **attr_name** - Attribute name, default empty string + * **tile** - Tile extent for each dimension, default None + + Additionally, arguments accepted by ArraySchema constructor can also be passed to customize the underlying array schema. + + **Example:** + + >>> import tiledb, numpy as np, tempfile + >>> with tempfile.TemporaryDirectory() as tmp: + ... # Creates array 'array' on disk. + ... with tiledb.from_numpy(tmp + "/array", np.array([1.0, 2.0, 3.0])) as A: + ... pass + """ + if not isinstance(array, np.ndarray): + raise Exception("from_numpy is only currently supported for numpy.ndarray") + + ctx = _get_ctx(ctx, config) + mode = kwargs.pop("mode", "ingest") + timestamp = kwargs.pop("timestamp", None) + sparse = kwargs.pop("sparse", False) + + if sparse: + raise tiledb.TileDBError("from_numpy only supports dense arrays") + + if mode not in ("ingest", "schema_only", "append"): + raise tiledb.TileDBError(f"Invalid mode specified ('{mode}')") + + if mode in ("ingest", "schema_only"): + try: + with tiledb.Array.load_typed(uri): + raise tiledb.TileDBError(f"Array URI '{uri}' already exists!") + except tiledb.TileDBError: + pass + + if mode == "append": + kwargs["append_dim"] = kwargs.get("append_dim", 0) + if tiledb.ArraySchema.load(uri).sparse: + raise tiledb.TileDBError("Cannot append to sparse array") + + if mode in ("ingest", "schema_only"): + schema = _schema_like_numpy(array, ctx, **kwargs) + tiledb.Array.create(uri, schema) + + if mode in ("ingest", "append"): + kwargs["mode"] = mode + with tiledb.open(uri, mode="w", ctx=ctx, timestamp=timestamp) as arr: + # probably need better typecheck here + if array.dtype == object: + arr[:] = array + else: + arr.write_direct(np.ascontiguousarray(array), **kwargs) + + return tiledb.DenseArray(uri, mode="r", ctx=ctx) + + +def array_exists(uri, isdense=False, issparse=False, ctx=None): + """ + Check if arrays exists and is open-able at the given URI + + :param str uri: URI for the TileDB array (any supported TileDB URI) + :param bool isdense: (optional) Restrict to dense array types + :param bool issparse: (optional) Restrict to sparse array types + :param ctx: (optional) TileDB Ctx + """ + ctx = _get_ctx(ctx) + # note: we can't use *only* object_type here, because it returns 'array' even if + # no files exist in the __schema directory (eg after delete). See SC-27854 + # but we need to use it first here, or else tiledb.open below will error out if + # the array does not exist. + if tiledb.object_type(uri, ctx) != "array": + return False + try: + with tiledb.open(uri, ctx=ctx) as a: + if isdense: + return not a.schema.sparse + if issparse: + return a.schema.sparse + return True + except tiledb.TileDBError as exc: + if ( + exc.args[0] + == "[TileDB::Array] Error: Cannot open array; Array does not exist." + ): + return False + else: + raise + + +def array_fragments(uri, include_mbrs=False, ctx=None): + """ + Creates a `FragmentInfoList` object, which is an ordered list of `FragmentInfo` + objects, representing all fragments in the array at the given URI. + + The returned object contain the following attributes: + - `uri`: URIs of fragments + - `version`: Fragment version of each fragment + - `nonempty_domain`: Non-empty domain of each fragment + - `cell_num`: Number of cells in each fragment + - `timestamp_range`: Timestamp range of when each fragment was written + - `sparse`: For each fragment, True if fragment is sparse, else False + - `has_consolidated_metadata`: For each fragment, True if fragment has consolidated fragment metadata, else False + - `unconsolidated_metadata_num`: Number of unconsolidated metadata fragments in each fragment + - `to_vacuum`: URIs of already consolidated fragments to vacuum + - `mbrs`: The mimimum bounding rectangle of each fragment; only present when `include_mbrs=True` + + :param str uri: URI for the TileDB array (any supported TileDB URI) + :param bool include_mbrs: Include minimum bouding rectangles in result; this is disabled by default for optimize time and space + :param ctx: (optional) TileDB Ctx + :return: FragmentInfoList + """ + return tiledb.FragmentInfoList(uri, include_mbrs, ctx) + + +def consolidate(uri, config=None, ctx=None, fragment_uris=None, timestamp=None): + """Consolidates TileDB array fragments for improved read performance + + :param str uri: URI to the TileDB Array + :param str key: (default None) Key to decrypt array if the array is encrypted + :param tiledb.Config config: The TileDB Config with consolidation parameters set + :param tiledb.Ctx ctx: (default None) The TileDB Context + :param fragment_uris: (default None) Consolidate the array using a list of fragment file names + :param timestamp: (default None) If not None, consolidate the array using the given tuple(int, int) UNIX seconds range (inclusive). This argument will be ignored if `fragment_uris` is passed. + :rtype: str or bytes + :return: path (URI) to the consolidated TileDB Array + :raises TypeError: cannot convert path to unicode string + :raises: :py:exc:`tiledb.TileDBError` + + Rather than passing the timestamp into this function, it may be set with + the config parameters `"sm.vacuum.timestamp_start"`and + `"sm.vacuum.timestamp_end"` which takes in a time in UNIX seconds. If both + are set then this function's `timestamp` argument will be used. + + **Example:** + + >>> import tiledb, tempfile, numpy as np, os + >>> path = tempfile.mkdtemp() + + >>> with tiledb.from_numpy(path, np.zeros(4), timestamp=1) as A: + ... pass + >>> with tiledb.open(path, 'w', timestamp=2) as A: + ... A[:] = np.ones(4, dtype=np.int64) + >>> with tiledb.open(path, 'w', timestamp=3) as A: + ... A[:] = np.ones(4, dtype=np.int64) + >>> with tiledb.open(path, 'w', timestamp=4) as A: + ... A[:] = np.ones(4, dtype=np.int64) + >>> len(tiledb.array_fragments(path)) + 4 + + >>> fragment_names = [ + ... os.path.basename(f) for f in tiledb.array_fragments(path).uri + ... ] + >>> array_uri = tiledb.consolidate( + ... path, fragment_uris=[fragment_names[1], fragment_names[3]] + ... ) + >>> len(tiledb.array_fragments(path)) + 3 + + """ + ctx = _get_ctx(ctx) + if config is None: + config = lt.Config() + + arr = lt.Array(ctx, uri, lt.QueryType.WRITE) + + if fragment_uris is not None: + if timestamp is not None: + warnings.warn( + "The `timestamp` argument will be ignored and only fragments " + "passed to `fragment_uris` will be consolidated", + DeprecationWarning, + ) + return arr.consolidate(ctx, fragment_uris, config) + elif timestamp is not None: + return arr.consolidate(ctx, timestamp, config) + else: + return arr.consolidate(ctx, config) + + +def vacuum(uri, config=None, ctx=None, timestamp=None): + """ + Vacuum underlying array fragments after consolidation. + + :param str uri: URI of array to be vacuumed + :param config: Override the context configuration for vacuuming. + Defaults to None, inheriting the context parameters. + :param (ctx: tiledb.Ctx, optional): Context. Defaults to + `tiledb.default_ctx()`. + :raises TypeError: cannot convert `uri` to unicode string + :raises: :py:exc:`tiledb.TileDBError` + + This operation of this function is controlled by + the `"sm.vacuum.mode"` parameter, which accepts the values ``fragments``, + ``fragment_meta``, and ``array_meta``. Rather than passing the timestamp + into this function, it may be set by using `"sm.vacuum.timestamp_start"`and + `"sm.vacuum.timestamp_end"` which takes in a time in UNIX seconds. If both + are set then this function's `timestamp` argument will be used. + + **Example:** + + >>> import tiledb, numpy as np + >>> import tempfile + >>> path = tempfile.mkdtemp() + >>> with tiledb.from_numpy(path, np.random.rand(4)) as A: + ... pass # make sure to close + >>> with tiledb.open(path, 'w') as A: + ... for i in range(4): + ... A[:] = np.ones(4, dtype=np.int64) * i + >>> paths = tiledb.VFS().ls(path) + >>> # should be 12 (2 base files + 2*5 fragment+ok files) + >>> (); len(paths); () # doctest:+ELLIPSIS + (...) + >>> () ; tiledb.consolidate(path) ; () # doctest:+ELLIPSIS + (...) + >>> tiledb.vacuum(path) + >>> paths = tiledb.VFS().ls(path) + >>> # should now be 4 ( base files + 2 fragment+ok files) + >>> (); len(paths); () # doctest:+ELLIPSIS + (...) + + """ + ctx = _get_ctx(ctx) + if config is None: + config = tiledb.Config() + + if timestamp is not None: + warnings.warn( + "Partial vacuuming via timestamp will be deprecrated in " + "a future release and replaced by passing in fragment URIs.", + DeprecationWarning, + ) + + if not isinstance(timestamp, tuple) and len(timestamp) != 2: + raise TypeError("'timestamp' argument expects tuple(start: int, end: int)") + + if timestamp[0] is not None: + config["sm.vacuum.timestamp_start"] = timestamp[0] + if timestamp[1] is not None: + config["sm.vacuum.timestamp_end"] = timestamp[1] + + lt.Array.vacuum(ctx, uri, config) + + +def schema_like(*args, shape=None, dtype=None, ctx=None, **kwargs): + """ + Return an ArraySchema corresponding to a NumPy-like object or + `shape` and `dtype` kwargs. Users are encouraged to pass 'tile' + and 'capacity' keyword arguments as appropriate for a given + application. + + :param A: NumPy array-like object, or TileDB reference URI, optional + :param tuple shape: array shape, optional + :param dtype: array dtype, optional + :param Ctx ctx: TileDB Ctx + :param kwargs: additional keyword arguments to pass through, optional + :return: tiledb.ArraySchema + """ + ctx = _get_ctx(ctx) + + def is_ndarray_like(arr): + return hasattr(arr, "shape") and hasattr(arr, "dtype") and hasattr(arr, "ndim") + + # support override of default dimension dtype + dim_dtype = kwargs.pop("dim_dtype", np.uint64) + if len(args) == 1: + arr = args[0] + if not is_ndarray_like(arr): + raise ValueError("expected ndarray-like object") + schema = _schema_like_numpy(arr, ctx, dim_dtype, tile=kwargs.pop("tile", None)) + elif shape and dtype: + if np.issubdtype(np.bytes_, dtype): + dtype = np.dtype("S") + elif np.issubdtype(dtype, np.str_): + dtype = np.dtype("U") + + ndim = len(shape) + tiling = _regularize_tiling(kwargs.pop("tile", None), ndim) + + dims = [] + for d in range(ndim): + # support smaller tile extents by kwargs + # domain is based on full shape + tile_extent = tiling[d] if tiling else shape[d] + domain = (0, shape[d] - 1) + dims.append( + tiledb.Dim(domain=domain, tile=tile_extent, dtype=dim_dtype, ctx=ctx) + ) + + att = tiledb.Attr(dtype=dtype, ctx=ctx) + dom = tiledb.Domain(*dims, ctx=ctx) + schema = tiledb.ArraySchema(ctx=ctx, domain=dom, attrs=(att,), **kwargs) + elif kwargs is not None: + raise ValueError + else: + raise ValueError( + "Must provide either ndarray-like object or 'shape' " + "and 'dtype' keyword arguments" + ) + + return schema + + +def as_built(return_json_string=False): + """ + Dumps the TileDB build configuration to a dictionary or string. + + :param bool return_json_string: Return the output as a string instead of a dictionary + :return: dict or str + """ + res = tiledb.main.as_built_dump() + + if return_json_string: + return res + + return json.loads(res) + + +def object_type(uri: str, ctx: tiledb.Ctx = None) -> Optional[str]: + """Returns the TileDB object type at the specified URI as a string. + + :param uri: URI of the TileDB resource + :param ctx: The TileDB Context + :return: object type string ("array" or "group") or None if invalid TileDB object``` + """ + ctx = _get_ctx(ctx) + + return tiledb.main.object_type(uri, ctx) + + +def ls(uri: str, func: Callable, ctx: tiledb.Ctx = None): + """Lists TileDB resources and applies a callback that have a prefix of ``uri`` (one level deep). + + :param uri: URI of TileDB group object + :param func: callback to execute on every listed TileDB resource,\ + resource URI and object type label are passed as arguments to the callback + :param ctx: A TileDB Context + """ + ctx = _get_ctx(ctx) + + tiledb.main.ls(uri, func, ctx) + + +def walk(uri: str, func: Callable, order: str = "preorder", ctx: tiledb.Ctx = None): + """Recursively visits TileDB resources and applies a callback to resources that have a prefix of ``uri`` + + :param uri: URI of TileDB group object + :param func: callback to execute on every listed TileDB resource,\ + resource URI and object type label are passed as arguments to the callback + :param ctx: The TileDB context + :param order: 'preorder' (default) or 'postorder' tree traversal + :raises ValueError: unknown order + :raises: :py:exc:`tiledb.TileDBError` + """ + ctx = _get_ctx(ctx) + + tiledb.main.walk(uri, func, order, ctx) + + +def remove(uri: str, ctx: tiledb.Ctx = None): + """Removes (deletes) the TileDB object at the specified URI + + :param uri: URI of the TileDB resource + :param ctx: The TileDB Context + :raises: :py:exc:`tiledb.TileDBError` + """ + ctx = _get_ctx(ctx) + + tiledb.main.remove(ctx, uri) + + +def move(old_uri: str, new_uri: str, ctx: tiledb.Ctx = None): + """Moves a TileDB resource (group, array, key-value). + + :param old_uri: URI of the TileDB resource to move + :param new_uri: URI of the destination + :param ctx: The TileDB Context + :raises: :py:exc:`TileDBError` + """ + ctx = _get_ctx(ctx) + + tiledb.main.move(ctx, old_uri, new_uri) + + +def _schema_like_numpy( + array, + ctx, + dim_dtype=np.uint64, + attr_name="", + full_domain=False, + tile=None, + **kwargs, +): + """ + Internal helper function for schema_like to create array schema from + NumPy array-like object. + """ + # create an ArraySchema from the numpy array object + tiling = _regularize_tiling(tile, array.ndim) + dims = [ + create_dim( + dtype=dim_dtype, + values=(0, array.shape[d] - 1), + full_domain=full_domain, + tile=tiling[d] if tiling else array.shape[d], + ctx=ctx, + ) + for d in range(array.ndim) + ] + var = False + if array.dtype == object: + # for object arrays, we use the dtype of the first element + # consistency check should be done later, if needed + el0 = array.flat[0] + if isinstance(el0, bytes): + el_dtype = np.dtype("S") + var = True + elif isinstance(el0, str): + el_dtype = np.dtype("U") + var = True + elif isinstance(el0, np.ndarray): + if len(el0.shape) != 1: + raise TypeError( + "Unsupported sub-array type for Attribute: {} " + "(only string arrays and 1D homogeneous NumPy arrays are supported)".format( + type(el0) + ) + ) + el_dtype = el0.dtype + else: + raise TypeError( + "Unsupported sub-array type for Attribute: {} " + "(only strings and homogeneous-typed NumPy arrays are supported)".format( + type(el0) + ) + ) + else: + el_dtype = array.dtype + + att = tiledb.Attr(dtype=el_dtype, name=attr_name, var=var, ctx=ctx) + dom = tiledb.Domain(*dims, ctx=ctx) + return tiledb.ArraySchema(ctx=ctx, domain=dom, attrs=(att,), **kwargs) + + +def _regularize_tiling(tile, ndim): + """ + Internal helper function for schema_like and _schema_like_numpy to regularize tiling. + """ + if not tile: + return None + + if np.isscalar(tile): + return tuple(int(tile) for _ in range(ndim)) + + if isinstance(tile, str) or len(tile) != ndim: + raise ValueError("'tile' must be iterable and match array dimensionality") + + return tuple(tile) + + +def _get_ctx(ctx=None, config=None): + if ctx: + if config: + raise ValueError( + "Received extra Ctx or Config argument: either one may be provided, but not both" + ) + elif config: + ctx = tiledb.Ctx(tiledb.Config(config)) + else: + ctx = tiledb.default_ctx() + return ctx diff --git a/testbed/TileDB-Inc__TileDB-Py/tiledb/indexing.pyx b/testbed/TileDB-Inc__TileDB-Py/tiledb/indexing.pyx new file mode 100644 index 0000000000000000000000000000000000000000..5d1b33a23e47704e3f8a96192f676f6bcb968306 --- /dev/null +++ b/testbed/TileDB-Inc__TileDB-Py/tiledb/indexing.pyx @@ -0,0 +1,271 @@ +from libc.stdio cimport printf + +import numpy as np + + +cdef class QueryAttr(object): + cdef unicode name + cdef np.dtype dtype + + def __init__(self, name, dtype): + self.name = name + self.dtype = dtype + +cdef dict execute_multi_index(Array array, + tiledb_query_t* query_ptr, + tuple attr_names, + return_coord): + + # NOTE: query_ptr *must* only be freed in caller + + cdef: + tiledb_ctx_t* ctx_ptr = PyCapsule_GetPointer( + array.ctx.__capsule__(), "ctx") + tiledb_query_status_t query_status + + cdef: + uint64_t result_bytes = 0 + size_t result_elements + float result_elements_f, result_rem + uint64_t el_count = 0 + bint repeat_query = True + uint64_t repeat_count = 0 + uint64_t buffer_bytes_remaining = 0 + uint64_t* buffer_sizes_ptr = NULL + + cdef: + np.dtype coords_dtype + + cdef: + Py_ssize_t attr_idx + bytes battr_name + unicode attr_name + np.ndarray attr_array + np.dtype attr_dtype + QueryAttr qattr + + cdef list attrs = list() + + # Coordinate attribute buffers must be set first + if return_coord: + dims = tuple(array.schema.domain.dim(dim_idx) for dim_idx in \ + range(array.schema.ndim)) + attrs += [QueryAttr(dim.name, dim.dtype) for dim in dims] + + # Get the attributes + attrs += [QueryAttr(a.name, a.dtype) + for a in [array.schema.attr(name) + for name in attr_names]] + + + # Create and assign attribute result buffers + + cdef Py_ssize_t nattr = len(attrs) + cdef uint64_t ndim = array.ndim + + cdef dict result_dict = dict() + cdef np.ndarray buffer_sizes = np.zeros(nattr, np.uint64) + cdef np.ndarray result_bytes_read = np.zeros(nattr, np.uint64) + + cdef uint64_t init_buffer_size = 1310720 * 8 # 10 MB int64 + if 'py.init_buffer_bytes' in array.ctx.config(): + init_buffer_size = int(array.ctx.config()['py.init_buffer_bytes']) + # switch from exponential to linear (+4GB) allocation + cdef uint64_t linear_alloc_bytes = 4 * (2**30) # 4 GB + + # There are two different conditions which may cause incomplete queries, + # requiring retries and potentially reallocation to complete the read. + # 1) user-allocated buffer is not large enough. In this case, we need to + # allocate more memory and retry. This is accomplished below by resizing + # the array in-place (preserving the existing data), then bumping the + # query buffer pointer. + # 2) internal memory limit is exceeded: the libtiledb parameter + # 'sm.memory_budget' governs internal memory allocation. If libtiledb's + # internal allocation exceeds this budget, the query may need to be + # retried, but we do not necessarily need to bump the user buffer allocation. + while repeat_query: + for attr_idx in range(nattr): + qattr = attrs[attr_idx] + attr_name = qattr.name + attr_dtype = qattr.dtype + + # allocate initial array + if repeat_count == 0: + result_dict[attr_name] = np.zeros(int(init_buffer_size / attr_dtype.itemsize), + dtype=attr_dtype) + + # Get the array here in order to save a lookup + attr_array = result_dict[attr_name] + if repeat_count > 0: + buffer_bytes_remaining = attr_array.nbytes - result_bytes_read[attr_idx] + if buffer_sizes[attr_idx] > (.25 * buffer_bytes_remaining): + # Check number of bytes read during the *last* pass. + # The conditional above handles situation (2) in order to avoid re-allocation + # on every repeat, in case we are reading small chunks at a time due to libtiledb + # memory budget. + # TODO make sure 'refcheck=False' is always safe + if attr_array.nbytes < linear_alloc_bytes: + attr_array.resize(attr_array.size * 2, refcheck=False) + else: + new_size = attr_array.size + linear_alloc_bytes / attr_dtype.itemsize + attr_array.resize(new_size, refcheck=False) + + battr_name = attr_name.encode('UTF-8') + attr_array_ptr = np.PyArray_DATA(attr_array) + + # we need to give the pointer to the current starting point after reallocation + attr_array_ptr = \ + (attr_array_ptr + result_bytes_read[attr_idx]) + + buffer_sizes[attr_idx] = attr_array.nbytes - result_bytes_read[attr_idx] + buffer_sizes_ptr = np.PyArray_DATA(buffer_sizes) + + rc = tiledb_query_set_data_buffer( + ctx_ptr, query_ptr, battr_name, attr_array_ptr, + &(buffer_sizes_ptr[attr_idx])) + + if rc != TILEDB_OK: + # NOTE: query_ptr *must* only be freed in caller + _raise_ctx_err(ctx_ptr, rc) + + with nogil: + rc = tiledb_query_submit(ctx_ptr, query_ptr) + + if rc != TILEDB_OK: + # NOTE: query_ptr *must* only be freed in caller + _raise_ctx_err(ctx_ptr, rc) + + # update bytes-read count + for attr_idx in range(nattr): + result_bytes_read[attr_idx] += buffer_sizes[attr_idx] + + rc = tiledb_query_get_status(ctx_ptr, query_ptr, &query_status) + if rc != TILEDB_OK: + # NOTE: query_ptr *must* only be freed in caller + _raise_ctx_err(ctx_ptr, rc) + + if query_status == TILEDB_INCOMPLETE: + #printf("%s\n", "got incomplete!") + repeat_query = True + repeat_count += 1 + elif query_status == TILEDB_COMPLETED: + repeat_query = False + break + elif query_status == TILEDB_FAILED: + raise TileDBError("Query returned TILEDB_FAILED") + elif query_status == TILEDB_INPROGRESS: + raise TileDBError("Query returned TILEDB_INPROGRESS") + elif query_status == TILEDB_INCOMPLETE: + raise TileDBError("Query returned TILEDB_INCOMPLETE") + else: + raise TileDBError("internal error: unknown query status") + + # resize arrays to final bytes-read + for attr_idx in range(nattr): + qattr = attrs[attr_idx] + attr_name = qattr.name + attr_dtype = qattr.dtype + + attr_item_size = attr_dtype.itemsize + attr_array = result_dict[attr_name] + attr_array.resize(int(result_bytes_read[attr_idx] / attr_item_size), refcheck=False) + + return result_dict + +cpdef multi_index(Array array, tuple attr_names, tuple ranges, + order = None, coords = None): + + cdef tiledb_layout_t layout = TILEDB_UNORDERED + if order is None or order == 'C': + layout = TILEDB_ROW_MAJOR + elif order == 'F': + layout = TILEDB_COL_MAJOR + elif order == 'G': + layout = TILEDB_GLOBAL_ORDER + else: + raise ValueError("order must be 'C' (TILEDB_ROW_MAJOR), "\ + "'F' (TILEDB_COL_MAJOR), "\ + "or 'G' (TILEDB_GLOBAL_ORDER)") + + cdef tiledb_ctx_t* ctx_ptr = PyCapsule_GetPointer( + array.ctx.__capsule__(), "ctx") + cdef tiledb_array_t* array_ptr = array.ptr + cdef tiledb_query_t* query_ptr = NULL + + cdef int rc = TILEDB_OK + rc = tiledb_query_alloc(ctx_ptr, array_ptr, TILEDB_READ, &query_ptr) + if rc != TILEDB_OK: + tiledb_query_free(&query_ptr) + _raise_ctx_err(ctx_ptr, rc) + rc = tiledb_query_set_layout(ctx_ptr, query_ptr, layout) + if rc != TILEDB_OK: + tiledb_query_free(&query_ptr) + _raise_ctx_err(ctx_ptr, rc) + + dim = array.schema.domain.dim(0) + cdef uint32_t c_dim_idx + cdef void* start_ptr = NULL + cdef void* end_ptr = NULL + cdef tuple cur_range + + cdef np.ndarray start + cdef np.ndarray end + + # Add ranges to query + ##################### + # we loop over the range tuple left to right and apply + # (unspecified dimensions are excluded) + cdef Py_ssize_t dim_idx, range_idx + cdef tiledb_subarray_t* subarray_ptr = NULL + cdef bint is_default = True + + rc = tiledb_subarray_alloc(ctx_ptr, array_ptr, &subarray_ptr) + if rc != TILEDB_OK: + tiledb_subarray_free(&subarray_ptr) + tiledb_query_free(&query_ptr) + _raise_ctx_err(ctx_ptr, rc) + + for dim_idx in range(len(ranges)): + c_dim_idx = dim_idx + dim_ranges = ranges[dim_idx] + + # skip empty dimensions + if len(dim_ranges) == 0: + continue + + is_default = False + for range_idx in range(len(dim_ranges)): + if len(dim_ranges[range_idx]) != 2: + tiledb_subarray_free(&subarray_ptr) + tiledb_query_free(&query_ptr) + raise TileDBError("internal error: invalid sub-range: ", dim_ranges[range_idx]) + + start = np.array(dim_ranges[range_idx][0], dtype=dim.dtype) + end = np.array(dim_ranges[range_idx][1], dtype=dim.dtype) + + start_ptr = np.PyArray_DATA(start) + end_ptr = np.PyArray_DATA(end) + + rc = tiledb_subarray_add_range( + ctx_ptr, subarray_ptr, dim_idx, start_ptr, end_ptr, NULL) + + if rc != TILEDB_OK: + tiledb_subarray_free(&subarray_ptr) + tiledb_query_free(&query_ptr) + _raise_ctx_err(ctx_ptr, rc) + + if not is_default: + rc = tiledb_query_set_subarray_t(ctx_ptr, query_ptr, subarray_ptr) + if rc != TILEDB_OK: + tiledb_subarray_free(&subarray_ptr) + tiledb_query_free(&query_ptr) + _raise_ctx_err(ctx_ptr, rc) + + try: + if coords is None: + coords = True + result = execute_multi_index(array, query_ptr, attr_names, coords) + finally: + tiledb_query_free(&query_ptr) + + return result diff --git a/testbed/TileDB-Inc__TileDB-Py/tiledb/libmetadata.pyx b/testbed/TileDB-Inc__TileDB-Py/tiledb/libmetadata.pyx new file mode 100644 index 0000000000000000000000000000000000000000..a0369adf7ba20035b1c58f1963249fa16fe27214 --- /dev/null +++ b/testbed/TileDB-Inc__TileDB-Py/tiledb/libmetadata.pyx @@ -0,0 +1,479 @@ +import weakref +from collections.abc import MutableMapping + +from cython.operator cimport dereference as deref + +from .datatypes import DataType + +_NP_DATA_PREFIX = "__np_flat_" +_NP_SHAPE_PREFIX = "__np_shape_" + + +cdef extern from "Python.h": + int PyBUF_READ + object PyMemoryView_FromMemory(char*, Py_ssize_t, int) + + + +cdef object unpack_metadata_val( + tiledb_datatype_t value_type, uint32_t value_num, const char* value_ptr + ): + assert value_num != 0, "internal error: unexpected value_num==0" + + if value_type == TILEDB_STRING_UTF8: + return value_ptr[:value_num].decode('UTF-8') if value_ptr != NULL else '' + + if value_type in (TILEDB_BLOB, TILEDB_CHAR, TILEDB_STRING_ASCII): + return value_ptr[:value_num] if value_ptr != NULL else b'' + + if value_ptr == NULL: + return () + + unpacked = [None] * value_num + cdef uint64_t itemsize = tiledb_datatype_size(value_type) + for i in range(value_num): + if value_type == TILEDB_INT64: + unpacked[i] = deref( value_ptr) + elif value_type == TILEDB_FLOAT64: + unpacked[i] = deref( value_ptr) + elif value_type == TILEDB_FLOAT32: + unpacked[i] = deref( value_ptr) + elif value_type == TILEDB_INT32: + unpacked[i] = deref( value_ptr) + elif value_type == TILEDB_UINT32: + unpacked[i] = deref( value_ptr) + elif value_type == TILEDB_UINT64: + unpacked[i] = deref( value_ptr) + elif value_type == TILEDB_INT8: + unpacked[i] = deref( value_ptr) + elif value_type == TILEDB_UINT8: + unpacked[i] = deref( value_ptr) + elif value_type == TILEDB_INT16: + unpacked[i] = deref( value_ptr) + elif value_type == TILEDB_UINT16: + unpacked[i] = deref( value_ptr) + else: + raise NotImplementedError(f"TileDB datatype '{value_type}' not supported") + value_ptr += itemsize + + # we don't differentiate between length-1 sequences and scalars + return unpacked[0] if value_num == 1 else tuple(unpacked) + + +cdef np.ndarray unpack_metadata_ndarray( + tiledb_datatype_t value_type, uint32_t value_num, const char* value_ptr + ): + cdef np.dtype dtype = DataType.from_tiledb(value_type).np_dtype + if value_ptr == NULL: + return np.array((), dtype=dtype) + + # special case for TILEDB_STRING_UTF8: TileDB assumes size=1 + if value_type != TILEDB_STRING_UTF8: + value_num *= dtype.itemsize + + return np.frombuffer(PyMemoryView_FromMemory(value_ptr, value_num, PyBUF_READ), + dtype=dtype).copy() + + +cdef object unpack_metadata( + bint is_ndarray, + tiledb_datatype_t value_type, + uint32_t value_num, + const char * value_ptr + ): + if value_ptr == NULL and value_num != 1: + raise KeyError + + if is_ndarray: + return unpack_metadata_ndarray(value_type, value_num, value_ptr) + else: + return unpack_metadata_val(value_type, value_num, value_ptr) + + +cdef put_metadata(Array array, key, value): + cdef: + tiledb_datatype_t tiledb_type + uint32_t value_num + cdef const unsigned char[:] data_view + cdef const void* data_ptr + tiledb_ctx_t* ctx_ptr = NULL + + if isinstance(value, np.ndarray): + if value.ndim != 1: + raise TypeError(f"Only 1D Numpy arrays can be stored as metadata") + + dt = DataType.from_numpy(value.dtype) + if dt.ncells != 1: + raise TypeError(f"Unsupported dtype '{value.dtype}'") + + tiledb_type = dt.tiledb_type + value_num = len(value) + # special case for TILEDB_STRING_UTF8: TileDB assumes size=1 + if tiledb_type == TILEDB_STRING_UTF8: + value_num *= value.itemsize + data_ptr = np.PyArray_DATA(value) + else: + from .metadata import pack_metadata_val + packed_buf = pack_metadata_val(value) + tiledb_type = packed_buf.tdbtype + value_num = packed_buf.value_num + data_view = packed_buf.data + data_ptr = &data_view[0] if value_num > 0 else NULL + + key_utf8 = key.encode('UTF-8') + cdef const char* key_utf8_ptr = key_utf8 + cdef int rc = TILEDB_OK + ctx_ptr = PyCapsule_GetPointer(array.ctx.__capsule__(), "ctx") + with nogil: + rc = tiledb_array_put_metadata( + ctx_ptr, + array.ptr, + key_utf8_ptr, + tiledb_type, + value_num, + data_ptr, + ) + if rc != TILEDB_OK: + _raise_ctx_err(ctx_ptr, rc) + + +cdef object get_metadata(Array array, key, is_ndarray=False): + cdef: + tiledb_datatype_t value_type + uint32_t value_num = 0 + const char* value_ptr = NULL + bytes key_utf8 = key.encode('UTF-8') + const char* key_utf8_ptr = key_utf8 + tiledb_ctx_t* ctx_ptr = NULL + + cdef int32_t rc = TILEDB_OK + ctx_ptr = PyCapsule_GetPointer(array.ctx.__capsule__(), "ctx") + with nogil: + rc = tiledb_array_get_metadata( + ctx_ptr, + array.ptr, + key_utf8_ptr, + &value_type, + &value_num, + &value_ptr, + ) + if rc != TILEDB_OK: + _raise_ctx_err(ctx_ptr, rc) + + return unpack_metadata(is_ndarray, value_type, value_num, value_ptr) + + +def iter_metadata(Array array, keys_only, dump=False): + """ + Iterate over array metadata keys or (key, value) tuples + + :param array: tiledb_array_t + :param keys_only: whether to yield just keys or values too + """ + cdef: + tiledb_ctx_t* ctx_ptr = PyCapsule_GetPointer( + array.ctx.__capsule__(), "ctx") + tiledb_array_t* array_ptr = array.ptr + uint64_t metadata_num + const char* key_ptr = NULL + uint32_t key_len + tiledb_datatype_t value_type + uint32_t value_num + const char* value_ptr = NULL + const char* value_type_str = NULL + + if keys_only and dump: + raise ValueError("keys_only and dump cannot both be True") + + cdef int32_t rc = TILEDB_OK + with nogil: + rc = tiledb_array_get_metadata_num(ctx_ptr, array_ptr, &metadata_num) + if rc != TILEDB_OK: + _raise_ctx_err(ctx_ptr, rc) + + for i in range(metadata_num): + with nogil: + rc = tiledb_array_get_metadata_from_index( + ctx_ptr, + array_ptr, + i, + &key_ptr, + &key_len, + &value_type, + &value_num, + &value_ptr, + ) + if rc != TILEDB_OK: + _raise_ctx_err(ctx_ptr, rc) + + key = key_ptr[:key_len].decode('UTF-8') + + if keys_only: + yield key + else: + value = unpack_metadata(key.startswith(_NP_DATA_PREFIX), + value_type, value_num, value_ptr) + + if dump: + rc = tiledb_datatype_to_str(value_type, &value_type_str) + if rc != TILEDB_OK: + _raise_ctx_err(ctx_ptr, rc) + + yield ( + "### Array Metadata ###\n" + f"- Key: {key}\n" + f"- Value: {value}\n" + f"- Type: {value_type_str.decode('UTF-8')}\n" + ) + else: + yield key, value + + +cdef class Metadata: + def __init__(self, array): + self.array_ref = weakref.ref(array) + + @property + def array(self): + assert self.array_ref() is not None, \ + "Internal error: invariant violation ([] from gc'd Array)" + return self.array_ref() + + def __setitem__(self, key, value): + if not isinstance(key, str): + raise TypeError(f"Unexpected key type '{type(key)}': expected str") + + # ensure previous key(s) are deleted (e.g. in case of replacing a + # non-numpy value with a numpy value or vice versa) + del self[key] + + if isinstance(value, np.ndarray): + flat_value = value.ravel() + put_metadata(self.array, _NP_DATA_PREFIX + key, flat_value) + if value.shape != flat_value.shape: + put_metadata(self.array, _NP_SHAPE_PREFIX + key, value.shape) + else: + put_metadata(self.array, key, value) + + def __getitem__(self, key): + if not isinstance(key, str): + raise TypeError(f"Unexpected key type '{type(key)}': expected str") + + array = self.array + try: + return get_metadata(array, key) + except KeyError as ex: + try: + np_array = get_metadata(array, _NP_DATA_PREFIX + key, is_ndarray=True) + except KeyError: + raise KeyError(key) from None + + try: + shape = get_metadata(array, _NP_SHAPE_PREFIX + key) + except KeyError: + return np_array + else: + return np_array.reshape(shape) + + def __delitem__(self, key): + if not isinstance(key, str): + raise TypeError(f"Unexpected key type '{type(key)}': expected str") + + cdef: + tiledb_ctx_t* ctx_ptr = PyCapsule_GetPointer(( + self.array).ctx.__capsule__(), "ctx") + tiledb_array_t* array_ptr = (self.array).ptr + const char* key_utf8_ptr + int32_t rc + + # key may be stored as is or it may be prefixed (for numpy values) + # we don't know this here so delete all potential internal keys + for k in key, _NP_DATA_PREFIX + key, _NP_SHAPE_PREFIX + key: + key_utf8 = k.encode('UTF-8') + key_utf8_ptr = key_utf8 + with nogil: + rc = tiledb_array_delete_metadata(ctx_ptr, array_ptr, key_utf8_ptr) + if rc != TILEDB_OK: + _raise_ctx_err(ctx_ptr, rc) + + def __contains__(self, key): + if not isinstance(key, str): + raise TypeError(f"Unexpected key type '{type(key)}': expected str") + + cdef: + tiledb_ctx_t* ctx_ptr = PyCapsule_GetPointer(( + self.array).ctx.__capsule__(), "ctx") + tiledb_array_t* array_ptr = (self.array).ptr + bytes key_utf8 = key.encode('UTF-8') + const char* key_utf8_ptr = key_utf8 + tiledb_datatype_t value_type + int32_t has_key + + cdef int32_t rc = TILEDB_OK + with nogil: + rc = tiledb_array_has_metadata_key( + ctx_ptr, + array_ptr, + key_utf8_ptr, + &value_type, + &has_key, + ) + if rc != TILEDB_OK: + _raise_ctx_err(ctx_ptr, rc) + + # if key doesn't exist, check the _NP_DATA_PREFIX prefixed key + if not has_key and not key.startswith(_NP_DATA_PREFIX): + has_key = self.__contains__(_NP_DATA_PREFIX + key) + + return bool(has_key) + + def consolidate(self): + """ + Consolidate array metadata. Array must be closed. + + :return: + """ + # TODO: ensure that the array is not x-locked? + ctx = ( self.array).ctx + config = ctx.config() + cdef: + uint32_t rc = 0 + tiledb_ctx_t* ctx_ptr = PyCapsule_GetPointer( + ctx.__capsule__(), "ctx") + tiledb_config_t* config_ptr = NULL + tiledb_encryption_type_t key_type = TILEDB_NO_ENCRYPTION + const char* key_ptr = NULL + uint32_t key_len = 0 + bytes bkey + bytes buri = unicode_path(self.array.uri) + str key = (self.array).key + tiledb_error_t* err_ptr = NULL + + if config: + config_ptr = PyCapsule_GetPointer( + config.__capsule__(), "config") + + if key is not None: + if isinstance(key, str): + bkey = key.encode('ascii') + else: + bkey = bytes(self.array.key) + key_type = TILEDB_AES_256_GCM + key_ptr = PyBytes_AS_STRING(bkey) + #TODO: unsafe cast here ssize_t -> uint64_t + key_len = PyBytes_GET_SIZE(bkey) + + rc = tiledb_config_alloc(&config_ptr, &err_ptr) + if rc != TILEDB_OK: + _raise_ctx_err(ctx_ptr, rc) + + rc = tiledb_config_set(config_ptr, "sm.encryption_type", "AES_256_GCM", &err_ptr) + if rc != TILEDB_OK: + _raise_ctx_err(ctx_ptr, rc) + + rc = tiledb_config_set(config_ptr, "sm.encryption_key", key_ptr, &err_ptr) + if rc != TILEDB_OK: + _raise_ctx_err(ctx_ptr, rc) + + cdef const char* buri_ptr = buri + + with nogil: + rc = tiledb_array_consolidate( + ctx_ptr, + buri_ptr, + config_ptr) + if rc != TILEDB_OK: + _raise_ctx_err(ctx_ptr, rc) + + get = MutableMapping.get + update = MutableMapping.update + + def setdefault(self, key, default=None): + raise NotImplementedError("Metadata.setdefault requires read-write access to array") + + def pop(self, key, default=None): + raise NotImplementedError("Metadata.pop requires read-write access to array") + + def popitem(self): + raise NotImplementedError("Metadata.popitem requires read-write access to array") + + def clear(self): + raise NotImplementedError("Metadata.clear requires read-write access to array") + + def __len__(self): + cdef: + tiledb_ctx_t* ctx_ptr = PyCapsule_GetPointer(( + self.array).ctx.__capsule__(), "ctx") + tiledb_array_t* array_ptr = (self.array).ptr + uint64_t num + + cdef int32_t rc = TILEDB_OK + with nogil: + rc = tiledb_array_get_metadata_num(ctx_ptr, array_ptr, &num) + if rc != TILEDB_OK: + _raise_ctx_err(ctx_ptr, rc) + + # subtract the _NP_SHAPE_PREFIX prefixed keys + for key in iter_metadata(self.array, keys_only=True): + if key.startswith(_NP_SHAPE_PREFIX): + num -= 1 + + return num + + def __iter__(self): + np_data_prefix_len = len(_NP_DATA_PREFIX) + for key in iter_metadata(self.array, keys_only=True): + if key.startswith(_NP_DATA_PREFIX): + yield key[np_data_prefix_len:] + elif not key.startswith(_NP_SHAPE_PREFIX): + yield key + # else: ignore the shape keys + + def keys(self): + """ + Return metadata keys as list. + + :return: List of keys + """ + # TODO this should be an iterator/view + return list(self) + + def values(self): + """ + Return metadata values as list. + + :return: List of values + """ + # TODO this should be an iterator/view + return [v for k, v in self._iteritems()] + + def items(self): + # TODO this should be an iterator/view + return tuple(self._iteritems()) + + def _iteritems(self): + np_data_prefix_len = len(_NP_DATA_PREFIX) + np_shape_prefix_len = len(_NP_SHAPE_PREFIX) + ndarray_items = [] + np_shape_map = {} + + # 1. yield all non-ndarray (key, value) pairs and keep track of + # the ndarray data and shape to assemble them later + for key, value in iter_metadata(self.array, keys_only=False): + if key.startswith(_NP_DATA_PREFIX): + ndarray_items.append((key[np_data_prefix_len:], value)) + elif key.startswith(_NP_SHAPE_PREFIX): + np_shape_map[key[np_shape_prefix_len:]] = value + else: + yield key, value + + # 2. yield all ndarray (key, value) pairs after reshaping (if necessary) + for key, value in ndarray_items: + shape = np_shape_map.get(key) + if shape is not None: + value = value.reshape(shape) + yield key, value + + def dump(self): + for metadata in iter_metadata(self.array, keys_only=False, dump=True): + print(metadata) \ No newline at end of file diff --git a/testbed/TileDB-Inc__TileDB-Py/tiledb/libtiledb.pxd b/testbed/TileDB-Inc__TileDB-Py/tiledb/libtiledb.pxd new file mode 100644 index 0000000000000000000000000000000000000000..2812220a9edbd88e69f9de3cdd88ddc14d4ce1b6 --- /dev/null +++ b/testbed/TileDB-Inc__TileDB-Py/tiledb/libtiledb.pxd @@ -0,0 +1,1156 @@ +#!python +#cython: language_level=3 + +from libc.stdint cimport uint32_t, uint64_t +from libc.stdio cimport FILE +from .domain_indexer import DomainIndexer +include "common.pxi" + +cdef extern from "Python.h": + char* PyUnicode_AsUTF8(object unicode) + +cdef extern from "tiledb/tiledb.h": + # Constants + enum: TILEDB_OK + enum: TILEDB_ERR + enum: TILEDB_OOM + + enum: TILEDB_VAR_NUM + unsigned int tiledb_var_num() + + enum: TILEDB_MAX_PATH + unsigned int tiledb_max_path() + + enum: TILEDB_OFFSET_SIZE + unsigned int tiledb_offset_size() + + # Version + void tiledb_version(int* major, int* minor, int* rev) + + # Enums + ctypedef enum tiledb_object_t: + TILEDB_INVALID + TILEDB_GROUP + TILEDB_ARRAY + + ctypedef enum tiledb_query_type_t: + TILEDB_MODIFY_EXCLUSIVE + TILEDB_DELETE + TILEDB_READ + TILEDB_WRITE + + ctypedef enum tiledb_query_status_t: + TILEDB_FAILED + TILEDB_COMPLETED + TILEDB_INPROGRESS + TILEDB_INCOMPLETE + + ctypedef enum tiledb_datatype_t: + TILEDB_INT32 + TILEDB_INT64 + TILEDB_FLOAT32 + TILEDB_FLOAT64 + TILEDB_BLOB + TILEDB_GEOM_WKB + TILEDB_GEOM_WKT + TILEDB_CHAR + TILEDB_INT8 + TILEDB_UINT8 + TILEDB_INT16 + TILEDB_UINT16 + TILEDB_UINT32 + TILEDB_UINT64 + TILEDB_STRING_ASCII + TILEDB_STRING_UTF8 + TILEDB_STRING_UTF16 + TILEDB_STRING_UTF32 + TILEDB_STRING_UCS2 + TILEDB_STRING_UCS4 + TILEDB_DATETIME_YEAR + TILEDB_DATETIME_MONTH + TILEDB_DATETIME_WEEK + TILEDB_DATETIME_DAY + TILEDB_DATETIME_HR + TILEDB_DATETIME_MIN + TILEDB_DATETIME_SEC + TILEDB_DATETIME_MS + TILEDB_DATETIME_US + TILEDB_DATETIME_NS + TILEDB_DATETIME_PS + TILEDB_DATETIME_FS + TILEDB_DATETIME_AS + TILEDB_BOOL + + ctypedef enum tiledb_array_type_t: + TILEDB_DENSE + TILEDB_SPARSE + + ctypedef enum tiledb_layout_t: + TILEDB_ROW_MAJOR + TILEDB_COL_MAJOR + TILEDB_GLOBAL_ORDER + TILEDB_UNORDERED + TILEDB_HILBERT + + ctypedef enum tiledb_data_order_t: + TILEDB_UNORDERED_DATA + TILEDB_INCREASING_DATA + TILEDB_DECREASING_DATA + + ctypedef enum tiledb_encryption_type_t: + TILEDB_NO_ENCRYPTION + TILEDB_AES_256_GCM + + ctypedef enum tiledb_filesystem_t: + TILEDB_HDFS + TILEDB_S3 + TILEDB_AZURE + TILEDB_GCS + + ctypedef enum tiledb_vfs_mode_t: + TILEDB_VFS_READ + TILEDB_VFS_WRITE + TILEDB_VFS_APPEND + + # Types + ctypedef struct tiledb_ctx_t: + pass + ctypedef struct tiledb_config_t: + pass + ctypedef struct tiledb_config_iter_t: + pass + ctypedef struct tiledb_enumeration_t: + pass + ctypedef struct tiledb_error_t: + pass + ctypedef struct tiledb_array_t: + pass + ctypedef struct tiledb_attribute_t: + pass + ctypedef struct tiledb_array_schema_t: + pass + ctypedef struct tiledb_dimension_t: + pass + ctypedef struct tiledb_domain_t: + pass + ctypedef struct tiledb_query_t: + pass + ctypedef struct tiledb_subarray_t: + pass + ctypedef struct tiledb_filter_list_t: + pass + ctypedef struct tiledb_vfs_t: + pass + ctypedef struct tiledb_vfs_fh_t: + pass + + # Config + int tiledb_config_alloc( + tiledb_config_t** config, + tiledb_error_t** error) + + void tiledb_config_free( + tiledb_config_t** config) + + int tiledb_config_set( + tiledb_config_t* config, + const char* param, + const char* value, + tiledb_error_t** error) + + int tiledb_config_get( + tiledb_config_t* config, + const char* param, + const char** value, + tiledb_error_t** error) + + int tiledb_config_load_from_file( + tiledb_config_t* config, + const char* filename, + tiledb_error_t** error) nogil + + int tiledb_config_unset( + tiledb_config_t* config, + const char* param, + tiledb_error_t** error) + + int tiledb_config_save_to_file( + tiledb_config_t* config, + const char* filename, + tiledb_error_t** error) nogil + + # Config Iterator + int tiledb_config_iter_alloc( + tiledb_config_t* config, + const char* prefix, + tiledb_config_iter_t** config_iter, + tiledb_error_t** error) + + void tiledb_config_iter_free( + tiledb_config_iter_t** config_iter) + + int tiledb_config_iter_here( + tiledb_config_iter_t* config_iter, + const char** param, + const char** value, + tiledb_error_t** error) + + int tiledb_config_iter_next( + tiledb_config_iter_t* config_iter, + tiledb_error_t** error) + + int tiledb_config_iter_done( + tiledb_config_iter_t* config_iter, + int* done, + tiledb_error_t** error) + + # Context + int tiledb_ctx_alloc( + tiledb_config_t* config, + tiledb_ctx_t** ctx) + + void tiledb_ctx_free( + tiledb_ctx_t** ctx) + + int tiledb_ctx_get_config( + tiledb_ctx_t* ctx, + tiledb_config_t** config) + + int tiledb_ctx_get_last_error( + tiledb_ctx_t* ctx, + tiledb_error_t** error) + + int tiledb_ctx_get_stats( + tiledb_ctx_t* ctx, + char** stats_json); + + int tiledb_ctx_is_supported_fs( + tiledb_ctx_t* ctx, + tiledb_filesystem_t fs, + int* is_supported) + + int tiledb_ctx_set_tag( + tiledb_ctx_t* ctx, + const char* key, + const char* value) + + # Error + int tiledb_error_message( + tiledb_error_t* err, + char** msg) + + void tiledb_error_free( + tiledb_error_t** err) + + # Attribute + int tiledb_attribute_alloc( + tiledb_ctx_t* ctx, + const char* name, + tiledb_datatype_t atype, + tiledb_attribute_t** attr) + + void tiledb_attribute_free( + tiledb_attribute_t** attr) + + int tiledb_attribute_set_filter_list( + tiledb_ctx_t* ctx_ptr, + const tiledb_attribute_t* attr, + tiledb_filter_list_t* filter_list) + + int tiledb_attribute_set_fill_value( + tiledb_ctx_t *ctx, + tiledb_attribute_t *attr, + const void *value, uint64_t size) + + int tiledb_attribute_set_cell_val_num( + tiledb_ctx_t* ctx, + tiledb_attribute_t* attr, + unsigned int cell_val_num) + + int tiledb_attribute_get_name( + tiledb_ctx_t* ctx, + const tiledb_attribute_t* attr, + const char** name) + + int tiledb_attribute_get_type( + tiledb_ctx_t* ctx, + const tiledb_attribute_t* attr, + tiledb_datatype_t* type) + + int tiledb_attribute_get_filter_list( + tiledb_ctx_t* ctx, + const tiledb_attribute_t* attr, + tiledb_filter_list_t** filter_list) + + int tiledb_attribute_get_fill_value( + tiledb_ctx_t *ctx, + tiledb_attribute_t *attr, + const void **value, + uint64_t *size) + + int tiledb_attribute_get_cell_val_num( + tiledb_ctx_t* ctx, + const tiledb_attribute_t* attr, + unsigned int* cell_val_num) + + int tiledb_attribute_set_nullable( + tiledb_ctx_t* ctx, + const tiledb_attribute_t* attr, + uint8_t nullable) + + int tiledb_attribute_get_nullable( + tiledb_ctx_t* ctx, + const tiledb_attribute_t* attr, + uint8_t* nullable) + + int tiledb_attribute_dump( + tiledb_ctx_t* ctx, + const tiledb_attribute_t* attr, + FILE* out) + + # Datatype + uint64_t tiledb_datatype_size( + tiledb_datatype_t type); + + # Domain + int tiledb_domain_alloc( + tiledb_ctx_t* ctx, + tiledb_domain_t** domain) + + void tiledb_domain_free( + tiledb_domain_t** domain) + + int tiledb_domain_get_type( + tiledb_ctx_t* ctx, + const tiledb_domain_t* domain, + tiledb_datatype_t* dtype) + + int tiledb_domain_get_ndim( + tiledb_ctx_t* ctx, + const tiledb_domain_t* domain, + unsigned int* ndim) + + int tiledb_domain_add_dimension( + tiledb_ctx_t* ctx, + tiledb_domain_t* domain, + tiledb_dimension_t* dim) + + int tiledb_domain_get_dimension_from_index( + tiledb_ctx_t* ctx, + const tiledb_domain_t* domain, + unsigned int index, + tiledb_dimension_t** dim) + + int tiledb_domain_get_dimension_from_name( + tiledb_ctx_t* ctx, + const tiledb_domain_t* domain, + const char* name, + tiledb_dimension_t** dim) + + int tiledb_domain_has_dimension( + tiledb_ctx_t * ctx, + const tiledb_domain_t* domain, + const char* name, + int32_t* has_dim) + + int tiledb_domain_dump( + tiledb_ctx_t* ctx, + const tiledb_domain_t* domain, + FILE* out) + + # Dimension + int tiledb_dimension_alloc( + tiledb_ctx_t* ctx, + const char* name, + tiledb_datatype_t type, + const void* dim_domain, + const void* tile_extent, + tiledb_dimension_t** dim) + + void tiledb_dimension_free( + tiledb_dimension_t** dim) + + int tiledb_dimension_get_name( + tiledb_ctx_t* ctx, + const tiledb_dimension_t* dim, + const char** name) + + int tiledb_dimension_get_cell_val_num( + tiledb_ctx_t* ctx, + const tiledb_dimension_t* dim, + uint32_t* cell_val_num) + + int tiledb_dimension_get_type( + tiledb_ctx_t* ctx, + const tiledb_dimension_t* dim, + tiledb_datatype_t* type) + + int tiledb_dimension_get_domain( + tiledb_ctx_t* ctx, + const tiledb_dimension_t* dim, + const void** domain) + + int tiledb_dimension_get_tile_extent( + tiledb_ctx_t* ctx, + const tiledb_dimension_t* dim, + const void** tile_extent) + + int tiledb_dimension_get_filter_list( + tiledb_ctx_t *ctx, + tiledb_dimension_t *dim, + tiledb_filter_list_t **filter_list) + + int tiledb_dimension_set_filter_list( + tiledb_ctx_t *ctx, + tiledb_dimension_t *dim, + tiledb_filter_list_t *filter_list) + + # Array schema + int tiledb_array_schema_alloc( + tiledb_ctx_t* ctx, + tiledb_array_type_t array_type, + tiledb_array_schema_t** array_schema) + + void tiledb_array_schema_free( + tiledb_array_schema_t** array_schema) + + int tiledb_array_schema_add_attribute( + tiledb_ctx_t* ctx, + tiledb_array_schema_t* array_schema, + tiledb_attribute_t* attr) + + int tiledb_array_schema_has_attribute( + tiledb_ctx_t* ctx, + tiledb_array_schema_t* array_schema, + const char* name, + int32_t* has_attr) + + int tiledb_array_schema_set_domain( + tiledb_ctx_t* ctx, + tiledb_array_schema_t* array_schema, + tiledb_domain_t* domain); + + int tiledb_array_schema_set_capacity( + tiledb_ctx_t* ctx, + tiledb_array_schema_t* array_schema, + uint64_t capacity); + + int tiledb_array_schema_set_cell_order( + tiledb_ctx_t* ctx, + tiledb_array_schema_t* array_schema, + tiledb_layout_t cell_order); + + int tiledb_array_schema_set_tile_order( + tiledb_ctx_t* ctx, + tiledb_array_schema_t* array_schema, + tiledb_layout_t tile_order) + + int tiledb_array_schema_set_offsets_filter_list( + tiledb_ctx_t* ctx, + tiledb_array_schema_t* array_schmea, + tiledb_filter_list_t* filter_list) + + int tiledb_array_schema_set_coords_filter_list( + tiledb_ctx_t* ctx, + tiledb_array_schema_t* array_schema, + tiledb_filter_list_t* filter_list) + + int tiledb_array_schema_set_validity_filter_list( + tiledb_ctx_t* ctx, + tiledb_array_schema_t* array_schema, + tiledb_filter_list_t* filter_list) + + int tiledb_array_schema_check( + tiledb_ctx_t* ctx, + tiledb_array_schema_t* array_schema) + + int tiledb_array_schema_load( + tiledb_ctx_t* ctx, + const char* array_uri, + tiledb_array_schema_t** array_schema) nogil + + int tiledb_array_schema_get_array_type( + tiledb_ctx_t* ctx, + const tiledb_array_schema_t* array_schema, + tiledb_array_type_t* array_type) + + int tiledb_array_schema_get_capacity( + tiledb_ctx_t* ctx, + const tiledb_array_schema_t* array_schema, + uint64_t* capacity) + + int tiledb_array_schema_get_cell_order( + tiledb_ctx_t* ctx, + const tiledb_array_schema_t* array_schema, + tiledb_layout_t* cell_order) + + int tiledb_array_schema_get_coords_filter_list( + tiledb_ctx_t* ctx, + const tiledb_array_schema_t* array_schema, + tiledb_filter_list_t** filter_list) + + int tiledb_array_schema_get_offsets_filter_list( + tiledb_ctx_t* ctx, + const tiledb_array_schema_t* array_schema, + tiledb_filter_list_t** filter_list) + + int tiledb_array_schema_get_validity_filter_list( + tiledb_ctx_t* ctx, + tiledb_array_schema_t* array_schema, + tiledb_filter_list_t** filter_list) + + int tiledb_array_schema_get_domain( + tiledb_ctx_t* ctx, + const tiledb_array_schema_t* array_schema, + tiledb_domain_t** domain) + + int tiledb_array_schema_get_tile_order( + tiledb_ctx_t* ctx, + const tiledb_array_schema_t* array_schema, + tiledb_layout_t* tile_order) + + int tiledb_array_schema_get_attribute_num( + tiledb_ctx_t* ctx, + const tiledb_array_schema_t* array_schema, + unsigned int* num_attributes) + + int tiledb_array_schema_get_attribute_from_index( + tiledb_ctx_t* ctx, + const tiledb_array_schema_t* array_schema, + unsigned int index, + tiledb_attribute_t** attr) + + int tiledb_array_schema_get_attribute_from_name( + tiledb_ctx_t* ctx, + const tiledb_array_schema_t* array_schema, + const char* name, + tiledb_attribute_t** attr) + + int tiledb_array_schema_get_array_name( + tiledb_ctx_t* ctx, + const tiledb_array_schema_t* array_schema, + const char** array_name) + + int tiledb_array_schema_get_allows_dups( + tiledb_ctx_t* ctx, + tiledb_array_schema_t* array_schema, + int* allows_dups); + + int tiledb_array_schema_set_allows_dups( + tiledb_ctx_t* ctx, + tiledb_array_schema_t* array_schema, + int allows_dups) + + int tiledb_array_schema_dump( + tiledb_ctx_t* ctx, + const tiledb_array_schema_t* array_schema, + FILE* out) + + int tiledb_array_schema_get_version( + tiledb_ctx_t* ctx, + tiledb_array_schema_t* array_schema, + uint32_t* version) + + int tiledb_array_get_open_timestamp_start( + tiledb_ctx_t* ctx, + tiledb_array_t* array, + uint64_t* timestamp_start) + + int tiledb_array_get_open_timestamp_end( + tiledb_ctx_t* ctx, + tiledb_array_t* array, + uint64_t* timestamp_end) + + int tiledb_array_set_config( + tiledb_ctx_t* ctx, + tiledb_array_t* array, + tiledb_config_t* config) + + int tiledb_array_set_open_timestamp_start( + tiledb_ctx_t* ctx, + tiledb_array_t* array, + uint64_t timestamp_start) + + int tiledb_array_set_open_timestamp_end( + tiledb_ctx_t* ctx, + tiledb_array_t* array, + uint64_t timestamp_end) + + int tiledb_array_put_metadata( + tiledb_ctx_t* ctx, + tiledb_array_t* array, + const char* key, + tiledb_datatype_t value_type, + uint32_t value_num, + const void* value) nogil + + int tiledb_array_delete_metadata( + tiledb_ctx_t* ctx, + tiledb_array_t* array, + const char* key) nogil + + int tiledb_array_has_metadata_key( + tiledb_ctx_t* ctx, + tiledb_array_t* array, + const char* key, + tiledb_datatype_t* value_type, + int32_t* has_key) nogil + + int tiledb_array_get_metadata( + tiledb_ctx_t* ctx, + tiledb_array_t* array, + const char* key, + tiledb_datatype_t* value_type, + uint32_t* value_num, + const void** value) nogil + + int tiledb_array_get_metadata_num( + tiledb_ctx_t* ctx, + tiledb_array_t* array, + uint64_t* num) nogil + + int tiledb_array_get_metadata_from_index( + tiledb_ctx_t* ctx, + tiledb_array_t* array, + uint64_t index, + const char** key, + uint32_t* key_len, + tiledb_datatype_t* value_type, + uint32_t* value_num, + const void** value) nogil + + int tiledb_array_consolidate_metadata( + tiledb_ctx_t* ctx, + const char* array_uri, + tiledb_config_t* config) nogil + + int tiledb_array_delete( + tiledb_ctx_t* ctx, + const char* uri) nogil + + # Query + int tiledb_query_alloc( + tiledb_ctx_t* ctx, + tiledb_array_t* array, + tiledb_query_type_t query_type, + tiledb_query_t** query) + + int tiledb_query_set_subarray_t( + tiledb_ctx_t* ctx, + tiledb_query_t* query, + const tiledb_subarray_t*) + + int32_t tiledb_query_set_data_buffer( + tiledb_ctx_t* ctx, + tiledb_query_t* query, + const char* name, + void* buffer, + uint64_t* buffer_size) + + int tiledb_query_set_validity_buffer( + tiledb_ctx_t* ctx, + tiledb_query_t* query, + const char* name, + uint8_t* buffer, + uint64_t* buffer_size) + + int32_t tiledb_query_set_offsets_buffer( + tiledb_ctx_t* ctx, + tiledb_query_t* query, + const char* name, + uint64_t* buffer, + uint64_t* buffer_size) + + int tiledb_query_set_layout( + tiledb_ctx_t* ctx, + tiledb_query_t* query, + tiledb_layout_t layout) + + void tiledb_query_free( + tiledb_query_t** query) + + int tiledb_query_finalize( + tiledb_ctx_t* ctx, + tiledb_query_t* query) nogil + + int tiledb_query_submit( + tiledb_ctx_t* ctx, + tiledb_query_t* query) nogil + + int tiledb_query_submit_async( + tiledb_ctx_t* ctx, + tiledb_query_t* query, + void* (*callback)(void*) noexcept, + void* callback_data) + + int tiledb_query_get_status( + tiledb_ctx_t* ctx, + tiledb_query_t* query, + tiledb_query_status_t* status) + + int tiledb_query_get_subarray_t( + tiledb_ctx_t* ctx, + const tiledb_query_t* query, + tiledb_subarray_t** subarray) + + int tiledb_query_get_type( + tiledb_ctx_t* ctx, + tiledb_query_t* query, + tiledb_query_type_t* query_type) + + int tiledb_query_has_results( + tiledb_ctx_t* ctx, + tiledb_query_t* query, + int* has_results) + + int tiledb_query_get_fragment_num( + tiledb_ctx_t* ctx, + const tiledb_query_t* query, + uint32_t* num) + + int tiledb_query_get_fragment_uri( + tiledb_ctx_t* ctx, + const tiledb_query_t* query, + uint64_t idx, + const char** uri) + + int tiledb_query_get_fragment_timestamp_range( + tiledb_ctx_t* ctx, + const tiledb_query_t* query, + uint64_t idx, + uint64_t* t1, + uint64_t* t2) + + int tiledb_query_get_est_result_size( + tiledb_ctx_t* ctx, + const tiledb_query_t* query, + const char* attr_name, + uint64_t* size) + + int tiledb_query_get_est_result_size_var( + tiledb_ctx_t* ctx, + const tiledb_query_t* query, + const char* attr_name, + uint64_t* size_off, + uint64_t* size_val) + + int tiledb_query_get_stats( + tiledb_ctx_t* ctx, + tiledb_query_t* query, + char** stats_json) + + # Subarray + int tiledb_subarray_alloc( + tiledb_ctx_t* ctx, + const tiledb_array_t* array, + tiledb_subarray_t** subarray) + + void tiledb_subarray_free(tiledb_subarray_t** subarray) + + int tiledb_subarray_add_range( + tiledb_ctx_t* ctx, + tiledb_subarray_t* subarray, + uint32_t dim_idx, + const void* start, + const void* end, + const void* stride) + + int tiledb_subarray_add_range_var( + tiledb_ctx_t* ctx, + tiledb_subarray_t* subarray, + uint32_t dim_idx, + const void* start, + uint64_t start_size, + const void* end, + uint64_t end_size) + + int tiledb_subarray_set_subarray( + tiledb_ctx_t* ctx, + tiledb_subarray_t* subarray, + const void* subarray_v) + + # Array + int tiledb_array_alloc( + tiledb_ctx_t* ctx, + const char* uri, + tiledb_array_t** array) + + int tiledb_array_open( + tiledb_ctx_t* ctx, + tiledb_array_t* array, + tiledb_query_type_t query_type) nogil + + int tiledb_array_reopen( + tiledb_ctx_t* ctx, + tiledb_array_t* array) nogil + + int tiledb_array_reopen_at( + tiledb_ctx_t* ctx, + tiledb_array_t* array, + uint64_t timestamp) nogil + + int tiledb_array_close( + tiledb_ctx_t* ctx, + tiledb_array_t* array) nogil + + void tiledb_array_free( + tiledb_array_t** array) + + int tiledb_array_create( + tiledb_ctx_t* ctx, + const char* uri, + const tiledb_array_schema_t* array_schema) nogil + + int tiledb_array_is_open( + tiledb_ctx_t* ctx, + tiledb_array_t* array, + int* is_open) + + int tiledb_array_consolidate( + tiledb_ctx_t* ctx, + const char* array_path, + tiledb_config_t* config) nogil + + int tiledb_array_delete_fragments_v2( + tiledb_ctx_t* ctx, + const char* uri, + uint64_t timestamp_start, + uint64_t timestamp_end) + + int tiledb_array_get_schema( + tiledb_ctx_t* ctx, + tiledb_array_t* array, + tiledb_array_schema_t** array_schema) nogil + + int tiledb_array_get_timestamp( + tiledb_ctx_t* ctx, + tiledb_array_t* array, + uint64_t* timestamp) nogil + + int tiledb_array_get_query_type( + tiledb_ctx_t* ctx, + tiledb_array_t* array, + tiledb_query_type_t* query_type) + + int tiledb_array_get_non_empty_domain( + tiledb_ctx_t* ctx, + tiledb_array_t* array, + void* domain, + int* isempty) nogil + + int32_t tiledb_array_get_non_empty_domain_from_index( + tiledb_ctx_t* ctx, + tiledb_array_t* array, + uint32_t idx, + void* domain, + int32_t* is_empty); + + int32_t tiledb_array_get_non_empty_domain_from_name( + tiledb_ctx_t* ctx, + tiledb_array_t* array, + const char* name, + void* domain, + int32_t* is_empty); + + int32_t tiledb_array_get_non_empty_domain_var_size_from_index( + tiledb_ctx_t* ctx, + tiledb_array_t* array, + uint32_t idx, + uint64_t* start_size, + uint64_t* end_size, + int32_t* is_empty) + + int32_t tiledb_array_get_non_empty_domain_var_size_from_name( + tiledb_ctx_t* ctx, + tiledb_array_t* array, + const char* name, + uint64_t* start_size, + uint64_t* end_size, + int32_t* is_empty) + + int32_t tiledb_array_get_non_empty_domain_var_from_index( + tiledb_ctx_t* ctx, + tiledb_array_t* array, + uint32_t idx, + void* start, + void* end, + int32_t* is_empty); + + int32_t tiledb_array_get_non_empty_domain_var_from_name( + tiledb_ctx_t* ctx, + tiledb_array_t* array, + const char* name, + void* start, + void* end, + int32_t* is_empty) + + int32_t tiledb_array_get_enumeration( + tiledb_ctx_t* ctx, + const tiledb_array_t* array, + const char* name, + tiledb_enumeration_t** enumeration) + + int tiledb_array_vacuum( + tiledb_ctx_t* ctx, + const char* array_uri, + tiledb_config_t* config) nogil + + # Resource management + int tiledb_object_type( + tiledb_ctx_t* ctx, + const char* path, + tiledb_object_t* otype) nogil + + int tiledb_object_remove( + tiledb_ctx_t* ctx, + const char* path) nogil + + int tiledb_object_move( + tiledb_ctx_t* ctx, + const char* old_path, + const char* new_path) nogil + + int tiledb_object_ls( + tiledb_ctx_t* ctx, + const char* path, + int (*callback)(const char*, tiledb_object_t, void*) noexcept, + void* data) + + # VFS + int tiledb_vfs_alloc( + tiledb_ctx_t* ctx, + tiledb_config_t* config, + tiledb_vfs_t** vfs) + + void tiledb_vfs_free( + tiledb_vfs_t** vfs) + + int tiledb_vfs_create_bucket( + tiledb_ctx_t* ctx, + tiledb_vfs_t* vfs, + const char* uri) nogil + + int tiledb_vfs_remove_bucket( + tiledb_ctx_t* ctx, + tiledb_vfs_t* vfs, + const char* uri) nogil + + int tiledb_vfs_empty_bucket( + tiledb_ctx_t* ctx, + tiledb_vfs_t* vfs, + const char* uri) nogil + + int tiledb_vfs_is_empty_bucket( + tiledb_ctx_t* ctx, + tiledb_vfs_t* vfs, + const char* uri, + int* is_empty) nogil + + int tiledb_vfs_is_bucket( + tiledb_ctx_t* ctx, + tiledb_vfs_t* vfs, + const char* uri, + int* is_bucket) nogil + + int tiledb_vfs_create_dir( + tiledb_ctx_t* ctx, + tiledb_vfs_t* vfs, + const char* uri) nogil + + int tiledb_vfs_is_dir( + tiledb_ctx_t* ctx, + tiledb_vfs_t* vfs, + const char* uri, + int* is_dir) nogil + + int tiledb_vfs_remove_dir( + tiledb_ctx_t* ctx, + tiledb_vfs_t* vfs, + const char* uri) nogil + + int tiledb_vfs_is_file( + tiledb_ctx_t* ctx, + tiledb_vfs_t* vfs, + const char* uri, + int* is_file) nogil + + int tiledb_vfs_remove_file( + tiledb_ctx_t* ctx, + tiledb_vfs_t* vfs, + const char* uri) nogil + + int tiledb_vfs_file_size( + tiledb_ctx_t* ctx, + tiledb_vfs_t* vfs, + const char* uri, + uint64_t* size) nogil + + int tiledb_vfs_dir_size( + tiledb_ctx_t * ctx, + tiledb_vfs_t * vfs, + const char * uri, + uint64_t * size) nogil + + int tiledb_vfs_ls( + tiledb_ctx_t * ctx, + tiledb_vfs_t * vfs, + const char * path, + void * data) nogil + + int tiledb_vfs_move_file( + tiledb_ctx_t* ctx, + tiledb_vfs_t* vfs, + const char* old_uri, + const char* new_uri) nogil + + int tiledb_vfs_move_dir( + tiledb_ctx_t* ctx, + tiledb_vfs_t* vfs, + const char* old_uri, + const char* new_uri) nogil + + int tiledb_vfs_copy_file( + tiledb_ctx_t* ctx, + tiledb_vfs_t* vfs, + const char* old_uri, + const char* new_uri) nogil + + int tiledb_vfs_copy_dir( + tiledb_ctx_t* ctx, + tiledb_vfs_t* vfs, + const char* old_uri, + const char* new_uri) nogil + + int tiledb_vfs_open( + tiledb_ctx_t* ctx, + tiledb_vfs_t* vfs, + const char* uri, + tiledb_vfs_mode_t mode, + tiledb_vfs_fh_t** fh) nogil + + int tiledb_vfs_close( + tiledb_ctx_t* ctx, + tiledb_vfs_fh_t* fh) nogil + + int tiledb_vfs_read( + tiledb_ctx_t* ctx, + tiledb_vfs_fh_t* fh, + uint64_t offset, + void* buffer, + uint64_t nbytes) nogil + + int tiledb_vfs_write( + tiledb_ctx_t* ctx, + tiledb_vfs_fh_t* fh, + const void* buffer, + uint64_t nbytes) nogil + + int tiledb_vfs_sync( + tiledb_ctx_t* ctx, + tiledb_vfs_fh_t* fh) nogil + + void tiledb_vfs_fh_free( + tiledb_vfs_fh_t** fh) nogil + + int tiledb_vfs_fh_is_closed( + tiledb_ctx_t* ctx, + tiledb_vfs_fh_t* fh, + int* is_closed) nogil + + int tiledb_vfs_touch( + tiledb_ctx_t* ctx, + tiledb_vfs_t* vfs, + const char* uri) nogil + + int tiledb_vfs_get_config( + tiledb_ctx_t* ctx, + tiledb_vfs_t* vfs, + tiledb_config_t** config) + + # URI + int tiledb_uri_to_path( + tiledb_ctx_t* ctx, + const char* uri, + char* path_out, + unsigned* path_length) nogil + + int tiledb_datatype_to_str( + tiledb_datatype_t datatype, + const char** datatype_str + ) + +cdef extern from "tiledb/tiledb_experimental.h": + # Filestore + int tiledb_filestore_schema_create( + tiledb_ctx_t* ctx, + const char* uri, + tiledb_array_schema_t** array_schema) nogil + + int tiledb_array_upgrade_version( + tiledb_ctx_t* ctx, + const char* array_uri, + tiledb_config_t* config) nogil + + int tiledb_array_consolidate_fragments( + tiledb_ctx_t* ctx, + const char* array_uri, + const char** fragment_uris, + const uint64_t num_fragments, + tiledb_config_t* config + ) + +# Free helper functions +cpdef unicode ustring(object s) +cpdef check_error(object ctx, int rc) +cdef _raise_tiledb_error(tiledb_error_t* err_ptr) +cdef _raise_ctx_err(tiledb_ctx_t* ctx_ptr, int rc) + +############################################################################### +# # +# TileDB-Py API declaration # +# # +############################################################################### + +cdef class Array(object): + cdef object __weakref__ + cdef object ctx + cdef tiledb_array_t* ptr + cdef unicode uri + cdef unicode mode + cdef bint _isopen + cdef object view_attr # can be None + cdef object key # can be None + cdef object schema + cdef object _buffers + + cdef object domain_index + cdef object multi_index + cdef object df + cdef Metadata meta + cdef object last_fragment_info + cdef object pyquery + + cdef _ndarray_is_varlen(self, np.ndarray array) + +cdef class Query(object): + cdef Array array + cdef object attrs + cdef object cond + cdef object dims + cdef object order + cdef object coords + cdef object index_col + cdef object use_arrow + cdef object return_arrow + cdef object return_incomplete + cdef object domain_index + cdef object multi_index + cdef object df + +cdef class ReadQuery(object): + cdef object _buffers + cdef object _offsets + +cdef class Metadata(object): + cdef object array_ref + diff --git a/testbed/TileDB-Inc__TileDB-Py/tiledb/libtiledb.pyx b/testbed/TileDB-Inc__TileDB-Py/tiledb/libtiledb.pyx new file mode 100644 index 0000000000000000000000000000000000000000..fb0ce7a962b1ef66fd5f026a50bd623260046375 --- /dev/null +++ b/testbed/TileDB-Inc__TileDB-Py/tiledb/libtiledb.pyx @@ -0,0 +1,2059 @@ +#!python +#cython: embedsignature=True +#cython: auto_pickle=False + +from cpython.pycapsule cimport PyCapsule_GetPointer, PyCapsule_IsValid, PyCapsule_New +from cpython.version cimport PY_MAJOR_VERSION +from .domain_indexer import DomainIndexer + +include "common.pxi" +include "indexing.pyx" +include "libmetadata.pyx" +import io +import warnings +import collections.abc +from collections import OrderedDict +from json import dumps as json_dumps, loads as json_loads + +from ._generated_version import version_tuple as tiledbpy_version +from .cc import TileDBError +from .ctx import Config, Ctx, default_ctx +from .vfs import VFS +from .sparse_array import SparseArrayImpl +from .dense_array import DenseArrayImpl + +############################################################################### +# Numpy initialization code (critical) # +############################################################################### + +# https://docs.scipy.org/doc/numpy/reference/c-api.array.html#c.import_array +np.import_array() + +############################################################################### +# Utility/setup # +############################################################################### + +# Use unified numpy printing +np.set_printoptions(legacy="1.21" if np.lib.NumpyVersion(np.__version__) >= "1.22.0" else False) + + +cdef tiledb_ctx_t* safe_ctx_ptr(object ctx): + if ctx is None: + raise TileDBError("internal error: invalid Ctx object") + return PyCapsule_GetPointer(ctx.__capsule__(), "ctx") + +def version(): + """Return the version of the linked ``libtiledb`` shared library + + :rtype: tuple + :return: Semver version (major, minor, rev) + + """ + cdef: + int major = 0 + int minor = 0 + int rev = 0 + tiledb_version(&major, &minor, &rev) + return major, minor, rev + + +# note: this function is cdef, so it must return a python object in order to +# properly forward python exceptions raised within the function. See: +# https://cython.readthedocs.io/en/latest/src/userguide/language_basics.html#error-return-values +cdef dict get_query_fragment_info(tiledb_ctx_t* ctx_ptr, + tiledb_query_t* query_ptr): + + cdef int rc = TILEDB_OK + cdef uint32_t num_fragments + cdef Py_ssize_t fragment_idx + cdef const char* fragment_uri_ptr + cdef unicode fragment_uri + cdef uint64_t fragment_t1, fragment_t2 + cdef dict result = dict() + + rc = tiledb_query_get_fragment_num(ctx_ptr, query_ptr, &num_fragments) + if rc != TILEDB_OK: + _raise_ctx_err(ctx_ptr, rc) + + if (num_fragments < 1): + return result + + for fragment_idx in range(0, num_fragments): + + rc = tiledb_query_get_fragment_uri(ctx_ptr, query_ptr, fragment_idx, &fragment_uri_ptr) + if rc != TILEDB_OK: + _raise_ctx_err(ctx_ptr, rc) + + rc = tiledb_query_get_fragment_timestamp_range( + ctx_ptr, query_ptr, fragment_idx, &fragment_t1, &fragment_t2) + if rc != TILEDB_OK: + _raise_ctx_err(ctx_ptr, rc) + + fragment_uri = fragment_uri_ptr.decode('UTF-8') + result[fragment_uri] = (fragment_t1, fragment_t2) + + return result + +def _write_array_wrapper( + object tiledb_array, + object subarray, + list coordinates, + list buffer_names, + list values, + dict labels, + dict nullmaps, + bint issparse, + ): + + cdef tiledb_ctx_t* ctx_ptr = safe_ctx_ptr(tiledb_array.ctx) + cdef tiledb_array_t* array_ptr = (tiledb_array).ptr + cdef dict fragment_info = (tiledb_array).last_fragment_info + _write_array(ctx_ptr, array_ptr, tiledb_array, subarray, coordinates, buffer_names, values, labels, nullmaps, fragment_info, issparse) + +cdef _write_array( + tiledb_ctx_t* ctx_ptr, + tiledb_array_t* array_ptr, + object tiledb_array, + object subarray, + list coordinates, + list buffer_names, + list values, + dict labels, + dict nullmaps, + dict fragment_info, + bint issparse, + ): + + # used for buffer conversion (local import to avoid circularity) + from .main import array_to_buffer + + cdef bint isfortran = False + cdef Py_ssize_t nattr = len(buffer_names) + cdef Py_ssize_t nlabel = len(labels) + + # Create arrays to hold buffer sizes + cdef Py_ssize_t nbuffer = nattr + nlabel + if issparse: + nbuffer += tiledb_array.schema.ndim + cdef np.ndarray buffer_sizes = np.zeros((nbuffer,), dtype=np.uint64) + cdef np.ndarray buffer_offsets_sizes = np.zeros((nbuffer,), dtype=np.uint64) + cdef np.ndarray nullmaps_sizes = np.zeros((nbuffer,), dtype=np.uint64) + + # Create lists for data and offset buffers + output_values = list() + output_offsets = list() + + # Set data and offset buffers for attributes + for i in range(nattr): + # if dtype is ASCII, ensure all characters are valid + if tiledb_array.schema.attr(i).isascii: + try: + values[i] = np.asarray(values[i], dtype=np.bytes_) + except Exception as exc: + raise TileDBError(f'dtype of attr {tiledb_array.schema.attr(i).name} is "ascii" but attr_val contains invalid ASCII characters') + + attr = tiledb_array.schema.attr(i) + + if attr.isvar: + try: + if attr.isnullable: + if(np.issubdtype(attr.dtype, np.str_) + or np.issubdtype(attr.dtype, np.bytes_)): + attr_val = np.array(["" if v is None else v for v in values[i]]) + else: + attr_val = np.nan_to_num(values[i]) + else: + attr_val = values[i] + buffer, offsets = array_to_buffer(attr_val, True, False) + except Exception as exc: + raise type(exc)(f"Failed to convert buffer for attribute: '{attr.name}'") from exc + buffer_offsets_sizes[i] = offsets.nbytes + else: + buffer, offsets = values[i], None + + buffer_sizes[i] = buffer.nbytes + output_values.append(buffer) + output_offsets.append(offsets) + + # Check value layouts + if len(values) and nattr > 1: + value = output_values[0] + isfortran = value.ndim > 1 and value.flags.f_contiguous + for value in values: + if value.ndim > 1 and value.flags.f_contiguous and not isfortran: + raise ValueError("mixed C and Fortran array layouts") + + # Set data and offsets buffers for dimensions (sparse arrays only) + ibuffer = nattr + if issparse: + for dim_idx, coords in enumerate(coordinates): + if tiledb_array.schema.domain.dim(dim_idx).isvar: + buffer, offsets = array_to_buffer(coords, True, False) + buffer_sizes[ibuffer] = buffer.nbytes + buffer_offsets_sizes[ibuffer] = offsets.nbytes + else: + buffer, offsets = coords, None + buffer_sizes[ibuffer] = buffer.nbytes + output_values.append(buffer) + output_offsets.append(offsets) + + name = tiledb_array.schema.domain.dim(dim_idx).name + buffer_names.append(name) + + ibuffer = ibuffer + 1 + + for label_name, label_values in labels.items(): + # Append buffer name + buffer_names.append(label_name) + # Get label data buffer and offsets buffer for the labels + dim_label = tiledb_array.schema.dim_label(label_name) + if dim_label.isvar: + buffer, offsets = array_to_buffer(label_values, True, False) + buffer_sizes[ibuffer] = buffer.nbytes + buffer_offsets_sizes[ibuffer] = offsets.nbytes + else: + buffer, offsets = label_values, None + buffer_sizes[ibuffer] = buffer.nbytes + # Append the buffers + output_values.append(buffer) + output_offsets.append(offsets) + + ibuffer = ibuffer + 1 + + + # Allocate the query + cdef int rc = TILEDB_OK + cdef tiledb_query_t* query_ptr = NULL + rc = tiledb_query_alloc(ctx_ptr, array_ptr, TILEDB_WRITE, &query_ptr) + if rc != TILEDB_OK: + _raise_ctx_err(ctx_ptr, rc) + + # Set layout + cdef tiledb_layout_t layout = ( + TILEDB_UNORDERED + if issparse + else (TILEDB_COL_MAJOR if isfortran else TILEDB_ROW_MAJOR) + ) + rc = tiledb_query_set_layout(ctx_ptr, query_ptr, layout) + if rc != TILEDB_OK: + tiledb_query_free(&query_ptr) + _raise_ctx_err(ctx_ptr, rc) + + # Create and set the subarray for the query (dense arrays only) + cdef np.ndarray s_start + cdef np.ndarray s_end + cdef np.dtype dim_dtype = None + cdef void* s_start_ptr = NULL + cdef void* s_end_ptr = NULL + cdef tiledb_subarray_t* subarray_ptr = NULL + if not issparse: + subarray_ptr = PyCapsule_GetPointer( + subarray.__capsule__(), "subarray") + # Set the subarray on the query + rc = tiledb_query_set_subarray_t(ctx_ptr, query_ptr, subarray_ptr) + if rc != TILEDB_OK: + tiledb_query_free(&query_ptr) + _raise_ctx_err(ctx_ptr, rc) + + # Set buffers on the query + cdef bytes bname + cdef void* buffer_ptr = NULL + cdef uint64_t* offsets_buffer_ptr = NULL + cdef uint8_t* nulmap_buffer_ptr = NULL + cdef uint64_t* buffer_sizes_ptr = np.PyArray_DATA(buffer_sizes) + cdef uint64_t* offsets_buffer_sizes_ptr = np.PyArray_DATA(buffer_offsets_sizes) + cdef uint64_t* nullmaps_sizes_ptr = np.PyArray_DATA(nullmaps_sizes) + try: + for i, buffer_name in enumerate(buffer_names): + # Get utf-8 version of the name for C-API calls + bname = buffer_name.encode('UTF-8') + + # Set data buffer + buffer_ptr = np.PyArray_DATA(output_values[i]) + rc = tiledb_query_set_data_buffer( + ctx_ptr, query_ptr, bname, buffer_ptr, &(buffer_sizes_ptr[i])) + if rc != TILEDB_OK: + _raise_ctx_err(ctx_ptr, rc) + + # Set offsets buffer + if output_offsets[i] is not None: + offsets_buffer_ptr = np.PyArray_DATA(output_offsets[i]) + rc = tiledb_query_set_offsets_buffer( + ctx_ptr, + query_ptr, + bname, + offsets_buffer_ptr, + &(offsets_buffer_sizes_ptr[i]) + ) + if rc != TILEDB_OK: + _raise_ctx_err(ctx_ptr, rc) + + # Set validity buffer + if buffer_name in nullmaps: + # NOTE: validity map is owned *by the caller* + nulmap = nullmaps[buffer_name] + nullmaps_sizes[i] = len(nulmap) + nulmap_buffer_ptr = np.PyArray_DATA(nulmap) + rc = tiledb_query_set_validity_buffer( + ctx_ptr, + query_ptr, + bname, + nulmap_buffer_ptr, + &(nullmaps_sizes_ptr[i]) + ) + if rc != TILEDB_OK: + _raise_ctx_err(ctx_ptr, rc) + + with nogil: + rc = tiledb_query_submit(ctx_ptr, query_ptr) + if rc != TILEDB_OK: + _raise_ctx_err(ctx_ptr, rc) + + rc = tiledb_query_finalize(ctx_ptr, query_ptr) + if rc != TILEDB_OK: + _raise_ctx_err(ctx_ptr, rc) + + if fragment_info is not False: + assert(type(fragment_info) is dict) + fragment_info.clear() + fragment_info.update(get_query_fragment_info(ctx_ptr, query_ptr)) + + finally: + tiledb_query_free(&query_ptr) + return + +cdef _raise_tiledb_error(tiledb_error_t* err_ptr): + cdef const char* err_msg_ptr = NULL + ret = tiledb_error_message(err_ptr, &err_msg_ptr) + if ret != TILEDB_OK: + tiledb_error_free(&err_ptr) + if ret == TILEDB_OOM: + raise MemoryError() + raise TileDBError("error retrieving error message") + cdef unicode message_string + try: + message_string = err_msg_ptr.decode('UTF-8', 'strict') + finally: + tiledb_error_free(&err_ptr) + raise TileDBError(message_string) + + +cdef _raise_ctx_err(tiledb_ctx_t* ctx_ptr, int rc): + if rc == TILEDB_OK: + return + if rc == TILEDB_OOM: + raise MemoryError() + cdef tiledb_error_t* err_ptr = NULL + cdef int ret = tiledb_ctx_get_last_error(ctx_ptr, &err_ptr) + if ret != TILEDB_OK: + tiledb_error_free(&err_ptr) + if ret == TILEDB_OOM: + raise MemoryError() + raise TileDBError("error retrieving error object from ctx") + _raise_tiledb_error(err_ptr) + + +cpdef check_error(object ctx, int rc): + cdef tiledb_ctx_t* ctx_ptr = PyCapsule_GetPointer( + ctx.__capsule__(), "ctx") + _raise_ctx_err(ctx_ptr, rc) + + +cpdef unicode ustring(object s): + """Coerce a python object to a unicode string""" + + if type(s) is unicode: + return s + elif PY_MAJOR_VERSION < 3 and isinstance(s, bytes): + return ( s).decode('ascii') + elif isinstance(s, unicode): + return unicode(s) + raise TypeError( + "ustring() must be a string or a bytes-like object" + ", not {0!r}".format(type(s))) + + +cdef bytes unicode_path(object path): + """Returns a UTF-8 encoded byte representation of a given URI path string""" + return ustring(path).encode('UTF-8') + + +############################################################################### +# # +# CLASS DEFINITIONS # +# # +############################################################################### + +from .array import _tiledb_datetime_extent, index_as_tuple, replace_ellipsis, replace_scalars_slice, check_for_floats, index_domain_subarray + +# Wrapper class to allow returning a Python object so that exceptions work correctly +# within preload_array +cdef class ArrayPtr(object): + cdef tiledb_array_t* ptr + +cdef ArrayPtr preload_array(uri, mode, key, timestamp, ctx=None): + """Open array URI without constructing specific type of Array object (internal).""" + if not ctx: + ctx = default_ctx() + # ctx + cdef tiledb_ctx_t* ctx_ptr = safe_ctx_ptr(ctx) + # uri + cdef bytes buri = unicode_path(uri) + cdef const char* uri_ptr = PyBytes_AS_STRING(buri) + # mode + cdef tiledb_query_type_t query_type = TILEDB_READ + # key + cdef bytes bkey + cdef tiledb_encryption_type_t key_type = TILEDB_NO_ENCRYPTION + cdef const char* key_ptr = NULL + cdef unsigned int key_len = 0 + + # convert python mode string to a query type + mode_to_query_type = { + "r": TILEDB_READ, + "w": TILEDB_WRITE, + "m": TILEDB_MODIFY_EXCLUSIVE, + "d": TILEDB_DELETE + } + if mode not in mode_to_query_type: + raise ValueError("TileDB array mode must be 'r', 'w', 'm', or 'd'") + query_type = mode_to_query_type[mode] + + # check the key, and convert the key to bytes + if key is not None: + if isinstance(key, str): + bkey = key.encode('ascii') + else: + bkey = bytes(key) + key_type = TILEDB_AES_256_GCM + key_ptr = PyBytes_AS_STRING(bkey) + #TODO: unsafe cast here ssize_t -> uint64_t + key_len = PyBytes_GET_SIZE(bkey) + + cdef uint64_t ts_start = 0 + cdef uint64_t ts_end = 0 + cdef bint set_start = False, set_end = False + + if timestamp is not None: + if isinstance(timestamp, tuple): + if len(timestamp) != 2: + raise ValueError("'timestamp' argument expects either int or tuple(start: int, end: int)") + if timestamp[0] is not None: + ts_start = timestamp[0] + set_start = True + if timestamp[1] is not None: + ts_end = timestamp[1] + set_end = True + elif isinstance(timestamp, int): + # handle the existing behavior for unary timestamp + # which is equivalent to endpoint of the range + ts_end = timestamp + set_end = True + else: + raise TypeError("Unexpected argument type for 'timestamp' keyword argument") + + # allocate and then open the array + cdef tiledb_array_t* array_ptr = NULL + cdef int rc = TILEDB_OK + rc = tiledb_array_alloc(ctx_ptr, uri_ptr, &array_ptr) + if rc != TILEDB_OK: + _raise_ctx_err(ctx_ptr, rc) + + cdef tiledb_config_t* config_ptr = NULL + cdef tiledb_error_t* err_ptr = NULL + if key is not None: + rc = tiledb_config_alloc(&config_ptr, &err_ptr) + if rc != TILEDB_OK: + _raise_ctx_err(ctx_ptr, rc) + + rc = tiledb_config_set(config_ptr, "sm.encryption_type", "AES_256_GCM", &err_ptr) + if rc != TILEDB_OK: + _raise_ctx_err(ctx_ptr, rc) + + rc = tiledb_config_set(config_ptr, "sm.encryption_key", key_ptr, &err_ptr) + if rc != TILEDB_OK: + _raise_ctx_err(ctx_ptr, rc) + + try: + # note: tiledb_array_set_config copies the config + rc = tiledb_array_set_config(ctx_ptr, array_ptr, config_ptr) + if rc != TILEDB_OK: + _raise_ctx_err(ctx_ptr, rc) + finally: + tiledb_config_free(&config_ptr) + + try: + if set_start: + check_error(ctx, + tiledb_array_set_open_timestamp_start(ctx_ptr, array_ptr, ts_start) + ) + if set_end: + check_error(ctx, + tiledb_array_set_open_timestamp_end(ctx_ptr, array_ptr, ts_end) + ) + except: + tiledb_array_free(&array_ptr) + raise + + with nogil: + rc = tiledb_array_open(ctx_ptr, array_ptr, query_type) + + if rc != TILEDB_OK: + tiledb_array_free(&array_ptr) + _raise_ctx_err(ctx_ptr, rc) + + cdef ArrayPtr retval = ArrayPtr() + retval.ptr = array_ptr + return retval + +cdef class Array(object): + """Base class for TileDB array objects. + + Defines common properties/functionality for the different array types. When + an Array instance is initialized, the array is opened with the specified mode. + + :param str uri: URI of array to open + :param str mode: (default 'r') Open the array object in read 'r', write 'w', or delete 'd' mode + :param str key: (default None) If not None, encryption key to decrypt the array + :param tuple timestamp: (default None) If int, open the array at a given TileDB + timestamp. If tuple, open at the given start and end TileDB timestamps. + :param str attr: (default None) open one attribute of the array; indexing a + dense array will return a Numpy ndarray directly rather than a dictionary. + :param Ctx ctx: TileDB context + """ + def __init__(self, uri, mode='r', key=None, timestamp=None, + attr=None, ctx=None): + if not ctx: + ctx = default_ctx() + # ctx + cdef tiledb_ctx_t* ctx_ptr = safe_ctx_ptr(ctx) + # array + cdef ArrayPtr preload_ptr + + if not self._isopen: + preload_ptr = preload_array(uri, mode, key, timestamp, ctx) + self.ptr = preload_ptr.ptr + + assert self.ptr != NULL, "internal error: unexpected null tiledb_array_t pointer in Array.__init__" + cdef tiledb_array_t* array_ptr = self.ptr + + cdef tiledb_array_schema_t* array_schema_ptr = NULL + try: + rc = TILEDB_OK + with nogil: + rc = tiledb_array_get_schema(ctx_ptr, array_ptr, &array_schema_ptr) + if rc != TILEDB_OK: + _raise_ctx_err(ctx_ptr, rc) + from .array_schema import ArraySchema + schema = ArraySchema.from_capsule(ctx, PyCapsule_New(array_schema_ptr, "schema", NULL)) + except: + tiledb_array_close(ctx_ptr, array_ptr) + tiledb_array_free(&array_ptr) + self.ptr = NULL + raise + + # view on a single attribute + if attr and not any(attr == schema.attr(i).name for i in range(schema.nattr)): + tiledb_array_close(ctx_ptr, array_ptr) + tiledb_array_free(&array_ptr) + self.ptr = NULL + raise KeyError("No attribute matching '{}'".format(attr)) + else: + self.view_attr = unicode(attr) if (attr is not None) else None + + self.ctx = ctx + self.uri = unicode(uri) + self.mode = unicode(mode) + self.schema = schema + self.key = key + self.domain_index = DomainIndexer(self) + self.pyquery = None + + self.last_fragment_info = dict() + self.meta = Metadata(self) + + def __cinit__(self): + self.ptr = NULL + + def __dealloc__(self): + if self.ptr != NULL: + tiledb_array_free(&self.ptr) + + def __capsule__(self): + if self.ptr == NULL: + raise TileDBError("internal error: cannot create capsule for uninitialized Ctx!") + cdef const char* name = "ctx" + cap = PyCapsule_New((self.ptr), name, NULL) + return cap + + def __repr__(self): + if self.isopen: + return "Array(type={0}, uri={1!r}, mode={2}, ndim={3})"\ + .format("Sparse" if self.schema.sparse else "Dense", self.uri, self.mode, self.schema.ndim) + else: + return "Array(uri={0!r}, mode=closed)" + + def _ctx_(self) -> Ctx: + """ + Get Ctx object associated with the array (internal). + This method exists for serialization. + + :return: Ctx object used to open the array. + :rtype: Ctx + """ + return self.ctx + + @classmethod + def create(cls, uri, schema, key=None, overwrite=False, ctx=None): + """Creates a TileDB Array at the given URI + + :param str uri: URI at which to create the new empty array. + :param ArraySchema schema: Schema for the array + :param str key: (default None) Encryption key to use for array + :param bool overwrite: (default False) Overwrite the array if it already exists + :param Ctx ctx: (default None) Optional TileDB Ctx used when creating the array, + by default uses the ArraySchema's associated context + (*not* necessarily ``tiledb.default_ctx``). + + """ + if issubclass(cls, DenseArrayImpl) and schema.sparse: + raise ValueError("Array.create `schema` argument must be a dense schema for DenseArray and subclasses") + if issubclass(cls, SparseArrayImpl) and not schema.sparse: + raise ValueError("Array.create `schema` argument must be a sparse schema for SparseArray and subclasses") + + cdef tiledb_ctx_t* ctx_ptr = safe_ctx_ptr(schema.ctx) + cdef bytes buri = unicode_path(uri) + cdef const char* uri_ptr = PyBytes_AS_STRING(buri) + cdef tiledb_array_schema_t* schema_ptr = PyCapsule_GetPointer( + schema.__capsule__(), "schema") + + cdef bytes bkey + cdef tiledb_encryption_type_t key_type = TILEDB_NO_ENCRYPTION + cdef const char* key_ptr = NULL + cdef unsigned int key_len = 0 + + cdef tiledb_config_t* config_ptr = NULL + cdef tiledb_error_t* err_ptr = NULL + cdef int rc = TILEDB_OK + + if key is not None: + if isinstance(key, str): + bkey = key.encode('ascii') + else: + bkey = bytes(key) + key_type = TILEDB_AES_256_GCM + key_ptr = PyBytes_AS_STRING(bkey) + #TODO: unsafe cast here ssize_t -> uint64_t + key_len = PyBytes_GET_SIZE(bkey) + + rc = tiledb_config_alloc(&config_ptr, &err_ptr) + if rc != TILEDB_OK: + _raise_ctx_err(ctx_ptr, rc) + + rc = tiledb_config_set(config_ptr, "sm.encryption_type", "AES_256_GCM", &err_ptr) + if rc != TILEDB_OK: + _raise_ctx_err(ctx_ptr, rc) + + rc = tiledb_config_set(config_ptr, "sm.encryption_key", key_ptr, &err_ptr) + if rc != TILEDB_OK: + _raise_ctx_err(ctx_ptr, rc) + rc = tiledb_ctx_alloc(config_ptr, &ctx_ptr) + if rc != TILEDB_OK: + _raise_ctx_err(ctx_ptr, rc) + + if overwrite: + from .highlevel import object_type + if object_type(uri) == "array": + if uri.startswith("file://") or "://" not in uri: + if VFS().remove_dir(uri) != TILEDB_OK: + _raise_ctx_err(ctx_ptr, rc) + else: + raise TypeError("Cannot overwrite non-local array.") + else: + warnings.warn("Overwrite set, but array does not exist") + + if ctx is not None: + if not isinstance(ctx, Ctx): + raise TypeError("tiledb.Array.create() expected tiledb.Ctx " + "object to argument ctx") + ctx_ptr = safe_ctx_ptr(ctx) + with nogil: + rc = tiledb_array_create(ctx_ptr, uri_ptr, schema_ptr) + if rc != TILEDB_OK: + _raise_ctx_err(ctx_ptr, rc) + return + + @staticmethod + def load_typed(uri, mode='r', key=None, timestamp=None, attr=None, ctx=None): + """Return a {Dense,Sparse}Array instance from a pre-opened Array (internal)""" + if not ctx: + ctx = default_ctx() + cdef int32_t rc = TILEDB_OK + cdef tiledb_ctx_t* ctx_ptr = safe_ctx_ptr(ctx) + cdef tiledb_array_schema_t* schema_ptr = NULL + cdef tiledb_array_type_t array_type + cdef Array new_array + cdef object new_array_typed + + # *** preload_array owns array_ptr until it returns *** + # and will free array_ptr upon exception + cdef ArrayPtr tmp_array = preload_array(uri, mode, key, timestamp, ctx) + assert tmp_array.ptr != NULL, "Internal error, array loading return nullptr" + cdef tiledb_array_t* array_ptr = tmp_array.ptr + # *** now we own array_ptr -- free in the try..except clause *** + try: + rc = tiledb_array_get_schema(ctx_ptr, array_ptr, &schema_ptr) + if rc != TILEDB_OK: + _raise_ctx_err(ctx_ptr, rc) + + rc = tiledb_array_schema_get_array_type(ctx_ptr, schema_ptr, &array_type) + if rc != TILEDB_OK: + _raise_ctx_err(ctx_ptr, rc) + + tiledb_array_schema_free(&schema_ptr) + + from . import DenseArray, SparseArray + if array_type == TILEDB_DENSE: + new_array_typed = DenseArray.__new__(DenseArray) + else: + new_array_typed = SparseArray.__new__(SparseArray) + + except: + tiledb_array_free(&array_ptr) + raise + + # *** this assignment must happen outside the try block *** + # *** because the array destructor will free array_ptr *** + # note: must use the immediate form `(x).m()` here + # do not assign a temporary Array object + (new_array_typed).ptr = array_ptr + (new_array_typed)._isopen = True + # *** new_array_typed now owns array_ptr *** + + new_array_typed.__init__(uri, mode=mode, key=key, timestamp=timestamp, attr=attr, ctx=ctx) + return new_array_typed + + def __enter__(self): + """ + The `__enter__` and `__exit__` methods allow TileDB arrays to be opened (and auto-closed) + using `with tiledb.open(uri) as A:` syntax. + """ + return self + + def __exit__(self, exc_type, exc_val, exc_tb): + """ + The `__enter__` and `__exit__` methods allow TileDB arrays to be opened (and auto-closed) + using `with tiledb.open(uri) as A:` syntax. + """ + self.close() + + def close(self): + """Closes this array, flushing all buffered data.""" + cdef tiledb_ctx_t* ctx_ptr = safe_ctx_ptr(self.ctx) + cdef tiledb_array_t* array_ptr = self.ptr + cdef int rc = TILEDB_OK + with nogil: + rc = tiledb_array_close(ctx_ptr, array_ptr) + if rc != TILEDB_OK: + _raise_ctx_err(ctx_ptr, rc) + self.schema = None + return + + def reopen(self, timestamp=None): + """ + Reopens this array. + + This is useful when the array is updated after it was opened. + To sync-up with the updates, the user must either close the array and open again, + or just use ``reopen()`` without closing. ``reopen`` will be generally faster than + a close-then-open. + """ + cdef tiledb_ctx_t* ctx_ptr = safe_ctx_ptr(self.ctx) + cdef tiledb_array_t* array_ptr = self.ptr + cdef uint64_t _timestamp = 0 + cdef int rc = TILEDB_OK + if timestamp is not None: + _timestamp = timestamp + rc = tiledb_array_set_open_timestamp_start(ctx_ptr, array_ptr, _timestamp) + if rc != TILEDB_OK: + _raise_ctx_err(ctx_ptr, rc) + + with nogil: + rc = tiledb_array_reopen(ctx_ptr, array_ptr) + if rc != TILEDB_OK: + _raise_ctx_err(ctx_ptr, rc) + return + + @property + def pyquery(self): + return self.pyquery + + @pyquery.setter + def pyquery(self, value): + self.pyquery = value + + @property + def meta(self): + """ + Return array metadata instance + + :rtype: tiledb.Metadata + """ + return self.meta + + @property + def schema(self): + """The :py:class:`ArraySchema` for this array.""" + schema = self.schema + if schema is None: + raise TileDBError("Cannot access schema, array is closed") + return schema + + @property + def mode(self): + """The mode this array was opened with.""" + return self.mode + + @property + def iswritable(self): + """This array is currently opened as writable.""" + return self.mode == 'w' + + @property + def isopen(self): + """True if this array is currently open.""" + cdef int isopen = 0 + cdef tiledb_ctx_t* ctx_ptr = safe_ctx_ptr(self.ctx) + cdef tiledb_array_t* array_ptr = self.ptr + cdef int rc = TILEDB_OK + rc = tiledb_array_is_open(ctx_ptr, array_ptr, &isopen) + if rc != TILEDB_OK: + _raise_ctx_err(ctx_ptr, rc) + return isopen == 1 + + @property + def ndim(self): + """The number of dimensions of this array.""" + return self.schema.ndim + + @property + def domain(self): + """The :py:class:`Domain` of this array.""" + return self.schema.domain + + @property + def dtype(self): + """The NumPy dtype of the specified attribute""" + if self.view_attr is None and self.schema.nattr > 1: + raise NotImplementedError("Multi-attribute does not have single dtype!") + return self.schema.attr(0).dtype + + @property + def shape(self): + """The shape of this array.""" + return self.schema.shape + + @property + def nattr(self): + """The number of attributes of this array.""" + if self.view_attr: + return 1 + else: + return self.schema.nattr + + @property + def view_attr(self): + """The view attribute of this array.""" + return self.view_attr + + @property + def timestamp_range(self): + """Returns the timestamp range the array is opened at + + :rtype: tuple + :returns: tiledb timestamp range at which point the array was opened + + """ + cdef tiledb_ctx_t* ctx_ptr = safe_ctx_ptr(self.ctx) + cdef tiledb_array_t* array_ptr = self.ptr + cdef uint64_t timestamp_start = 0 + cdef uint64_t timestamp_end = 0 + cdef int rc = TILEDB_OK + + rc = tiledb_array_get_open_timestamp_start(ctx_ptr, array_ptr, ×tamp_start) + if rc != TILEDB_OK: + _raise_ctx_err(ctx_ptr, rc) + + rc = tiledb_array_get_open_timestamp_end(ctx_ptr, array_ptr, ×tamp_end) + if rc != TILEDB_OK: + _raise_ctx_err(ctx_ptr, rc) + + return (int(timestamp_start), int(timestamp_end)) + + @property + def uri(self): + """Returns the URI of the array""" + return self.uri + + def subarray(self, selection, attrs=None, coords=False, order=None): + raise NotImplementedError() + + def attr(self, key): + """Returns an :py:class:`Attr` instance given an int index or string label + + :param key: attribute index (positional or associative) + :type key: int or str + :rtype: :py:class:`Attr` + :return: The array attribute at index or with the given name (label) + :raises TypeError: invalid key type""" + return self.schema.attr(key) + + def dim(self, dim_id): + """Returns a :py:class:`Dim` instance given a dim index or name + + :param key: attribute index (positional or associative) + :type key: int or str + :rtype: :py:class:`Attr` + :return: The array attribute at index or with the given name (label) + :raises TypeError: invalid key type""" + return self.schema.domain.dim(dim_id) + + def enum(self, name): + """ + Return the Enumeration from the attribute name. + + :param name: attribute name + :type key: str + :rtype: `Enumeration` + """ + cdef tiledb_ctx_t* ctx_ptr = safe_ctx_ptr(self.ctx) + cdef tiledb_array_t* array_ptr = self.ptr + cdef bytes bname = unicode_path(name) + cdef const char* name_ptr = PyBytes_AS_STRING(bname) + cdef tiledb_enumeration_t* enum_ptr = NULL + rc = tiledb_array_get_enumeration(ctx_ptr, array_ptr, name_ptr, &enum_ptr) + if rc != TILEDB_OK: + _raise_ctx_err(ctx_ptr, rc) + + from .enumeration import Enumeration + return Enumeration.from_capsule(self.ctx, PyCapsule_New(enum_ptr, "enum", NULL)) + + def delete_fragments(self_or_uri, timestamp_start, timestamp_end, ctx=None): + """ + Delete a range of fragments from timestamp_start to timestamp_end. + The array needs to be opened in 'm' mode as shown in the example below. + + :param timestamp_start: the first fragment to delete in the range + :type timestamp_start: int + :param timestamp_end: the last fragment to delete in the range + :type timestamp_end: int + + **Example:** + + >>> import tiledb, tempfile, numpy as np + >>> path = tempfile.mkdtemp() + + >>> with tiledb.from_numpy(path, np.zeros(4), timestamp=1) as A: + ... pass + >>> with tiledb.open(path, 'w', timestamp=2) as A: + ... A[:] = np.ones(4, dtype=np.int64) + + >>> with tiledb.open(path, 'r') as A: + ... A[:] + array([1., 1., 1., 1.]) + + >>> tiledb.Array.delete_fragments(path, 2, 2) + + >>> with tiledb.open(path, 'r') as A: + ... A[:] + array([0., 0., 0., 0.]) + + """ + cdef tiledb_ctx_t* ctx_ptr + cdef tiledb_array_t* array_ptr + cdef tiledb_query_t* query_ptr + cdef bytes buri + cdef int rc = TILEDB_OK + + if isinstance(self_or_uri, str): + uri = self_or_uri + if not ctx: + ctx = default_ctx() + + ctx_ptr = safe_ctx_ptr(ctx) + buri = uri.encode('UTF-8') + + rc = tiledb_array_delete_fragments_v2( + ctx_ptr, + buri, + timestamp_start, + timestamp_end + ) + else: + # TODO: Make this method static and entirely remove the conditional. + raise TypeError( + "The `tiledb.Array.delete_fragments` instance method is deprecated and removed. Use the static method with the same name instead.") + if rc != TILEDB_OK: + _raise_ctx_err(ctx_ptr, rc) + + @staticmethod + def delete_array(uri, ctx=None): + """ + Delete the given array. + + :param str uri: The URI of the array + :param Ctx ctx: TileDB context + + **Example:** + + >>> import tiledb, tempfile, numpy as np + >>> path = tempfile.mkdtemp() + + >>> with tiledb.from_numpy(path, np.zeros(4), timestamp=1) as A: + ... pass + >>> tiledb.array_exists(path) + True + + >>> tiledb.Array.delete_array(path) + + >>> tiledb.array_exists(path) + False + + """ + if not ctx: + ctx = default_ctx() + + cdef tiledb_ctx_t* ctx_ptr = safe_ctx_ptr(ctx) + cdef bytes buri = uri.encode('UTF-8') + + cdef int rc = TILEDB_OK + + rc = tiledb_array_delete(ctx_ptr, buri) + if rc != TILEDB_OK: + _raise_ctx_err(ctx_ptr, rc) + + def nonempty_domain(self): + """Return the minimum bounding domain which encompasses nonempty values. + + :rtype: tuple(tuple(numpy scalar, numpy scalar), ...) + :return: A list of (inclusive) domain extent tuples, that contain all + nonempty cells + + """ + cdef list results = list() + dom = self.schema.domain + + cdef tiledb_ctx_t* ctx_ptr = safe_ctx_ptr(self.ctx) + cdef tiledb_array_t* array_ptr = self.ptr + cdef int rc = TILEDB_OK + cdef uint32_t dim_idx + + cdef uint64_t start_size + cdef uint64_t end_size + cdef int32_t is_empty + cdef np.ndarray start_buf + cdef np.ndarray end_buf + cdef void* start_buf_ptr + cdef void* end_buf_ptr + cdef np.dtype dim_dtype + + for dim_idx in range(dom.ndim): + dim_dtype = dom.dim(dim_idx).dtype + + if np.issubdtype(dim_dtype, np.str_) or np.issubdtype(dim_dtype, np.bytes_): + rc = tiledb_array_get_non_empty_domain_var_size_from_index( + ctx_ptr, array_ptr, dim_idx, &start_size, &end_size, &is_empty) + if rc != TILEDB_OK: + _raise_ctx_err(ctx_ptr, rc) + + if is_empty: + results.append((None, None)) + continue + + buf_dtype = 'S' + start_buf = np.empty(start_size, 'S' + str(start_size)) + end_buf = np.empty(end_size, 'S' + str(end_size)) + start_buf_ptr = np.PyArray_DATA(start_buf) + end_buf_ptr = np.PyArray_DATA(end_buf) + else: + # this one is contiguous + start_buf = np.empty(2, dim_dtype) + start_buf_ptr = np.PyArray_DATA(start_buf) + + if np.issubdtype(dim_dtype, np.str_) or np.issubdtype(dim_dtype, np.bytes_): + rc = tiledb_array_get_non_empty_domain_var_from_index( + ctx_ptr, array_ptr, dim_idx, start_buf_ptr, end_buf_ptr, &is_empty + ) + if rc != TILEDB_OK: + _raise_ctx_err(ctx_ptr, rc) + if is_empty: + return None + + if start_size > 0 and end_size > 0: + results.append((start_buf.item(0), end_buf.item(0))) + else: + results.append((None, None)) + else: + rc = tiledb_array_get_non_empty_domain_from_index( + ctx_ptr, array_ptr, dim_idx, start_buf_ptr, &is_empty + ) + if rc != TILEDB_OK: + _raise_ctx_err(ctx_ptr, rc) + if is_empty: + return None + + res_x, res_y = start_buf.item(0), start_buf.item(1) + + if np.issubdtype(dim_dtype, np.datetime64): + # Convert to np.datetime64 + date_unit = np.datetime_data(dim_dtype)[0] + res_x = np.datetime64(res_x, date_unit) + res_y = np.datetime64(res_y, date_unit) + + results.append((res_x, res_y)) + + return tuple(results) + + def consolidate(self, config=None, key=None, fragment_uris=None, timestamp=None): + """ + Consolidates fragments of an array object for increased read performance. + + Overview: https://docs.tiledb.com/main/concepts/internal-mechanics/consolidation + + :param tiledb.Config config: The TileDB Config with consolidation parameters set + :param key: (default None) encryption key to decrypt an encrypted array + :type key: str or bytes + :param fragment_uris: (default None) Consolidate the array using a list of fragment _names_ (note: the `__ts1_ts2_