discrete-ndtree 0.2.3__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,191 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ Copyright 2024 Kay Richter
180
+
181
+ Licensed under the Apache License, Version 2.0 (the "License");
182
+ you may not use this file except in compliance with the License.
183
+ You may obtain a copy of the License at
184
+
185
+ http://www.apache.org/licenses/LICENSE-2.0
186
+
187
+ Unless required by applicable law or agreed to in writing, software
188
+ distributed under the License is distributed on an "AS IS" BASIS,
189
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
190
+ See the License for the specific language governing permissions and
191
+ limitations under the License.
@@ -0,0 +1,2 @@
1
+ graft discrete_ndtree
2
+ global-exclude *.so *.pyd
@@ -0,0 +1,105 @@
1
+ Metadata-Version: 2.1
2
+ Name: discrete_ndtree
3
+ Version: 0.2.3
4
+ Summary: N-Dimensional Dtree (e.g. Quadtree, Octree) with limited resolution.
5
+ Author: Kay Richter
6
+ License: Apache-2.0
7
+ Project-URL: Repository, https://github.com/KayRichter/nim-dtree
8
+ Project-URL: Issues, https://github.com/KayRichter/nim-dtree/issues
9
+ Keywords: quadtree,octree,nim
10
+ Classifier: License :: OSI Approved :: Apache Software License
11
+ Classifier: Intended Audience :: Developers
12
+ Requires-Python: >=3.7
13
+ Description-Content-Type: text/markdown
14
+ License-File: LICENSE
15
+
16
+ # discrete_ndtree
17
+
18
+ This package provides N-Dimensional trees (e.g. Quadtree, Octree) with a limited smallest node size.
19
+ Opposed to normal ND-Trees, nearby coordinates may access the same cell.
20
+ Example usecases:
21
+ - occupancy maps for 2D and 3D
22
+ - canvas for images without borders
23
+ - timeline of daily temperatures
24
+
25
+
26
+ ## Usage
27
+
28
+ ```python
29
+ from discrete_ndtree import DTree
30
+
31
+
32
+ # create a quadtree with a smallest cell size of 0.5
33
+ quad_tree = DTree(2, 0.5)
34
+
35
+ # reading and writing cells can be done using the subscript operator
36
+ # the default cell content is `None`
37
+ assert quad_tree[0.0, 0.0] is None
38
+ quad_tree[0.0, 0.0] = "value"
39
+ assert quad_tree[0.0, 0.0] == "value"
40
+
41
+ # since the cell size is limited, other nearby coordinates may access the same cell
42
+ assert quad_tree[0.4, 0.4] == "value"
43
+
44
+ # by default the corner of the root of the tree is at the coordinate origin
45
+ # a different point can be set using the `anchor` parameter
46
+ quad_tree = DTree(2, 0.5, anchor=[0.2, 0.2])
47
+ quad_tree[0.0, 0.0] = "value"
48
+ assert quad_tree[0.4, 0.4] is None # coordinate is a different cell now
49
+
50
+ # also the default value for all cells can be changed
51
+ quad_tree = DTree(2, 0.5, default=0)
52
+ assert quad_tree[0.0, 0.0] == 0
53
+
54
+ # it is also possible to get ranges of cells from the tree
55
+ # note that the results includes both ends of the slice
56
+ assert quad_tree[0.1:0.9, 0.1:0.9] == [[0, 0], [0, 0]]
57
+ ```
58
+
59
+
60
+ ## Installation
61
+
62
+ Precompiled wheels are available for Linux (glibc and musl), macOS, and Windows:
63
+
64
+ ```bash
65
+ pip install discrete-ndtree
66
+ ```
67
+
68
+ The wheels ship with dimensions 1-4 precompiled.
69
+ Other dimensions are compiled on demand (see [More dimensions](#more-dimensions)).
70
+
71
+ ## More dimensions
72
+
73
+ Dimensions 1-4 are precompiled; any other dimension is compiled on first use:
74
+
75
+ ```python
76
+ from discrete_ndtree import DTree
77
+
78
+ six_dim_tree = DTree(6, 1.0, anchor=[1.0, -2.0, 3.0, -4.0, 5.0, -6.0], default=False)
79
+ assert six_dim_tree[0.0, 0.0, 0.0, 0.0, 0.0, 0.0] == False
80
+ ```
81
+
82
+ The first construction of a tree with an uncompiled dimension compiles a
83
+ `nim_dtree_dim_<dims>.so` (`.pyd` on Windows) into the `discrete_ndtree` package
84
+ directory, so that directory must be writable.
85
+ This requires a working [Nim compiler](https://nim-lang.org/) (>= 2.2.4) and
86
+ the `nimpy` and `msgpack4nim` packages:
87
+
88
+ ```bash
89
+ nimble install nimpy msgpack4nim
90
+ ```
91
+
92
+ Nim and the nimble package manager can be installed using [choosenim](https://github.com/nim-lang/choosenim)
93
+ To compile dimensions ahead of time, or to bundle several dimensions into one
94
+ binary, use `compile_dimensions`:
95
+
96
+ ```python
97
+ from discrete_ndtree import discrete_ndtree
98
+
99
+ discrete_ndtree.compile_dimensions([6]) # or e.g. [5, 6, 7]
100
+ ```
101
+
102
+ More low level access to the trees is not recommended, but available through
103
+ ```python
104
+ from discrete_ndtree import discrete_ndtree
105
+ ```
@@ -0,0 +1,90 @@
1
+ # discrete_ndtree
2
+
3
+ This package provides N-Dimensional trees (e.g. Quadtree, Octree) with a limited smallest node size.
4
+ Opposed to normal ND-Trees, nearby coordinates may access the same cell.
5
+ Example usecases:
6
+ - occupancy maps for 2D and 3D
7
+ - canvas for images without borders
8
+ - timeline of daily temperatures
9
+
10
+
11
+ ## Usage
12
+
13
+ ```python
14
+ from discrete_ndtree import DTree
15
+
16
+
17
+ # create a quadtree with a smallest cell size of 0.5
18
+ quad_tree = DTree(2, 0.5)
19
+
20
+ # reading and writing cells can be done using the subscript operator
21
+ # the default cell content is `None`
22
+ assert quad_tree[0.0, 0.0] is None
23
+ quad_tree[0.0, 0.0] = "value"
24
+ assert quad_tree[0.0, 0.0] == "value"
25
+
26
+ # since the cell size is limited, other nearby coordinates may access the same cell
27
+ assert quad_tree[0.4, 0.4] == "value"
28
+
29
+ # by default the corner of the root of the tree is at the coordinate origin
30
+ # a different point can be set using the `anchor` parameter
31
+ quad_tree = DTree(2, 0.5, anchor=[0.2, 0.2])
32
+ quad_tree[0.0, 0.0] = "value"
33
+ assert quad_tree[0.4, 0.4] is None # coordinate is a different cell now
34
+
35
+ # also the default value for all cells can be changed
36
+ quad_tree = DTree(2, 0.5, default=0)
37
+ assert quad_tree[0.0, 0.0] == 0
38
+
39
+ # it is also possible to get ranges of cells from the tree
40
+ # note that the results includes both ends of the slice
41
+ assert quad_tree[0.1:0.9, 0.1:0.9] == [[0, 0], [0, 0]]
42
+ ```
43
+
44
+
45
+ ## Installation
46
+
47
+ Precompiled wheels are available for Linux (glibc and musl), macOS, and Windows:
48
+
49
+ ```bash
50
+ pip install discrete-ndtree
51
+ ```
52
+
53
+ The wheels ship with dimensions 1-4 precompiled.
54
+ Other dimensions are compiled on demand (see [More dimensions](#more-dimensions)).
55
+
56
+ ## More dimensions
57
+
58
+ Dimensions 1-4 are precompiled; any other dimension is compiled on first use:
59
+
60
+ ```python
61
+ from discrete_ndtree import DTree
62
+
63
+ six_dim_tree = DTree(6, 1.0, anchor=[1.0, -2.0, 3.0, -4.0, 5.0, -6.0], default=False)
64
+ assert six_dim_tree[0.0, 0.0, 0.0, 0.0, 0.0, 0.0] == False
65
+ ```
66
+
67
+ The first construction of a tree with an uncompiled dimension compiles a
68
+ `nim_dtree_dim_<dims>.so` (`.pyd` on Windows) into the `discrete_ndtree` package
69
+ directory, so that directory must be writable.
70
+ This requires a working [Nim compiler](https://nim-lang.org/) (>= 2.2.4) and
71
+ the `nimpy` and `msgpack4nim` packages:
72
+
73
+ ```bash
74
+ nimble install nimpy msgpack4nim
75
+ ```
76
+
77
+ Nim and the nimble package manager can be installed using [choosenim](https://github.com/nim-lang/choosenim)
78
+ To compile dimensions ahead of time, or to bundle several dimensions into one
79
+ binary, use `compile_dimensions`:
80
+
81
+ ```python
82
+ from discrete_ndtree import discrete_ndtree
83
+
84
+ discrete_ndtree.compile_dimensions([6]) # or e.g. [5, 6, 7]
85
+ ```
86
+
87
+ More low level access to the trees is not recommended, but available through
88
+ ```python
89
+ from discrete_ndtree import discrete_ndtree
90
+ ```
@@ -0,0 +1 @@
1
+ from .discrete_ndtree import DTree
@@ -0,0 +1,229 @@
1
+ from typing import Any, List, Optional, Union
2
+ from pathlib import Path
3
+ import importlib
4
+ import subprocess
5
+ from sys import platform
6
+ import shutil
7
+
8
+
9
+ def compile_dimensions(dimensions: List[int] = [1, 2, 3, 4], print_command: bool = False):
10
+ dims_str = ",".join([str(i) for i in dimensions])
11
+ dims_name = "_".join([str(i) for i in dimensions])
12
+
13
+ current_path = Path(__file__).absolute().parent
14
+ target_filename = f"nim_dtree_dim_{dims_name}"
15
+ source_path = current_path / "nim_dtree_python_bindings.nim"
16
+ new_source_path = current_path / f"{target_filename}.nim"
17
+ shutil.copy2(source_path, new_source_path)
18
+
19
+ params = ["nim", "c", "-d:release", "--app:lib", "--threads:on", f"-d:targetedDimensions={dims_str}"]
20
+ if platform in ["linux", "darwin"]:
21
+ params.append("--out:" + str(current_path / f"{target_filename}.so"))
22
+ else:
23
+ params = params + [
24
+ "--out:" + str(current_path / f"{target_filename}.pyd"),
25
+ "--tlsEmulation:off",
26
+ "--passL:-static"
27
+ ]
28
+ params.append(str(current_path / new_source_path))
29
+
30
+ if print_command:
31
+ print("Compiling bindings using this command: \"", " ".join(params), "\"", sep="")
32
+ result = subprocess.run(params, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE, text=True)
33
+ if result.returncode != 0:
34
+ print(f"Failed to compile {target_filename} (exit code {result.returncode}):")
35
+ print(result.stdout)
36
+ print(result.stderr)
37
+ raise RuntimeError(f"Failed to compile {target_filename}: nim exited with code {result.returncode}")
38
+
39
+ new_source_path.unlink()
40
+
41
+ _update_dimensions_binary_mapping(str(target_filename))
42
+
43
+
44
+ DTreeCoord = List[float]
45
+ DTreeKey = List[int]
46
+
47
+ # raw python bindings can be seen in nim_dtree_python_bindings.nim`
48
+
49
+ class DTreeClimber:
50
+ """
51
+ Low level access to the underlying data structure.
52
+ Usually you get this using the `getNode` method of `DTree`.
53
+ """
54
+ def __init__(self, climber):
55
+ self._climber = climber
56
+
57
+ def level(self) -> int:
58
+ """How many levels until smallest leafs"""
59
+ return self._climber.getLevel()
60
+
61
+ def size(self) -> float:
62
+ """Size of currently covered per dimension by the node"""
63
+ return self._climber.size()
64
+
65
+ def hasData(self) -> bool:
66
+ """Check if the current node has stored any data"""
67
+ return self._climber.hasData()
68
+
69
+ def getData(self):
70
+ """Get the currently stored data.
71
+ Returns the default value if no data is stored and
72
+ a default value was given in the QuadTree constructor"""
73
+ return self._climber.getData()
74
+
75
+ def setData(self, value):
76
+ """Write data to the current node"""
77
+ return self._climber.setData(value)
78
+
79
+ def hasChildren(self) -> bool:
80
+ """Check if hte current node has children"""
81
+ return self._climber.hasChildren()
82
+
83
+ def climb(self, childIndex, creative: bool = True):
84
+ """Climber climbs from current node to the next as given in parameter.
85
+ If this node has no children and `creative` is true,
86
+ children are created beforehand."""
87
+ if creative:
88
+ self._climber.creativeClimb(childIndex)
89
+ else:
90
+ self._climber.climb(childIndex)
91
+
92
+ def climbClone(self, childIndex, creative: bool = True):
93
+ """Creates a new climber, which is located at the child node as given in parameter.
94
+ If this node has no children and `creative` is true,
95
+ children are created beforehand."""
96
+ if creative:
97
+ return DTreeClimber(self._climber.creativeClimbClone(childIndex))
98
+ else:
99
+ return DTreeClimber(self._climber.climbClone(childIndex))
100
+
101
+
102
+ class DTree:
103
+ """
104
+ Wrapper for a more pythonic interface of the underlying datastructure.
105
+ """
106
+ def __init__(self, dimensions: int, min_cell_size: float, anchor: Optional[List[float]] = None, default: Optional[Any] = None):
107
+ """Construct a DTree."""
108
+ if dimensions not in _dimensions_binary_mapping:
109
+ compile_dimensions([dimensions])
110
+ module = _dimensions_binary_mapping[dimensions]
111
+ if anchor is None:
112
+ instance = module.__dict__[f"newDTree{dimensions}D"](min_cell_size, default)
113
+ else:
114
+ assert dimensions == len(anchor), f"Dimensions of parameters do not match. {dimensions} dimensions were requested, but anchor has only {len(anchor)} dimensions."
115
+ instance = module.__dict__[f"newDTree{dimensions}AD"](min_cell_size, anchor, default)
116
+
117
+ self._tree = instance
118
+ self.dimensions = dimensions
119
+
120
+ def anchor(self) -> DTreeCoord:
121
+ """This is the currently smallest coordinate covered"""
122
+ return self._tree.anchor()
123
+
124
+ def minNodeSize(self) -> float:
125
+ """Size of the smalles node (at level 0)"""
126
+ return self._tree.minNodeSize()
127
+
128
+ def depth(self) -> int:
129
+ """How many levels until smallest leafs"""
130
+ return self._tree.depth()
131
+
132
+ def size(self) -> float:
133
+ """Size of currently covered per dimension by the tree"""
134
+ return self._tree.size()
135
+
136
+ def __getitem__(self, key):
137
+ """
138
+ Get the data stored at the leaf node specified in parameters.
139
+ """
140
+
141
+ level = 0
142
+ if len(key) - self._tree.dimensions() == 1:
143
+ level = key[-1]
144
+ key = key[:-1]
145
+
146
+ if any([type(elem) is slice for elem in key]):
147
+ mins = []
148
+ maxs = []
149
+ for elem in key:
150
+ if type(elem) is slice:
151
+ mins.append(elem.start)
152
+ maxs.append(elem.stop)
153
+ else:
154
+ mins.append(elem)
155
+ maxs.append(elem)
156
+
157
+ return self._tree.getRange(mins, maxs)
158
+
159
+ else:
160
+ return self._tree.getNodeByCoord(key, level).getData()
161
+
162
+ def __setitem__(self, key, data):
163
+ """
164
+ Set the data stored at the leaf node specified in parameters.
165
+ """
166
+
167
+ level = 0
168
+ if len(key) - self._tree.dimensions() == 1:
169
+ level = key[-1]
170
+ key = key[:-1]
171
+
172
+ return self._tree.createNodeByCoord(key, level).setData(data)
173
+
174
+ def getNode(self, key: Union[DTreeKey, DTreeCoord], level: int = 0) -> DTreeClimber:
175
+ """
176
+ Get access to node at specified level.
177
+ Does not create nodes if they do not exist and instead returns the closest existing node
178
+ """
179
+
180
+ if key[0] is float:
181
+ return self._tree.getNodeByCoord(key, level)
182
+ else:
183
+ return self._tree.getNodeByKey(key, level)
184
+
185
+ def createNode(self, key: Union[DTreeKey, DTreeCoord], level: int = 0) -> DTreeClimber:
186
+ """
187
+ Get access to node at specified level.
188
+ Creates nodes if they do not exist.
189
+ """
190
+
191
+ if key[0] is float:
192
+ return self._tree.createNodeByCoord(key, level)
193
+ else:
194
+ return self._tree.createNodeByKey(key, level)
195
+
196
+ def serialize(self) -> bytes:
197
+ return self._tree.serialize()
198
+
199
+ def deserialize(self, bytes):
200
+ return self._tree.deserialize(bytes)
201
+
202
+ def __getstate__(self):
203
+ return (self.dimensions, self.serialize())
204
+
205
+ def __setstate__(self, state):
206
+ self.dimensions, tree_serialization = state
207
+ module = _dimensions_binary_mapping[self.dimensions]
208
+ self._tree = module.__dict__[f"newDTree{self.dimensions}"](1.0)
209
+ self.deserialize(tree_serialization)
210
+
211
+
212
+ def _update_dimensions_binary_mapping(module_name: str):
213
+ global _dimensions_binary_mapping
214
+ discrete_ndtree_dim = importlib.import_module("." + module_name, __package__)
215
+ for dims in discrete_ndtree_dim.get_all_dimensions():
216
+ if dims in _dimensions_binary_mapping:
217
+ continue
218
+ else:
219
+ _dimensions_binary_mapping[dims] = discrete_ndtree_dim
220
+
221
+
222
+ _dimensions_binary_mapping = {}
223
+
224
+ if platform in ["linux", "darwin"]:
225
+ for module in Path(__file__).absolute().parent.glob("nim_dtree_*.so"):
226
+ _update_dimensions_binary_mapping(module.stem)
227
+ else:
228
+ for module in Path(__file__).absolute().parent.glob("nim_dtree_*.pyd"):
229
+ _update_dimensions_binary_mapping(module.stem)
@@ -0,0 +1,56 @@
1
+ import std/[math, sequtils]
2
+
3
+ type Vector*[D: static[int], T] = array[D, T]
4
+
5
+ converter toVector*[D: static[int], T](v: array[D, T]): Vector[D, T] =
6
+ Vector[D, T](v)
7
+
8
+ func `+`*[D: static[int], T](left, right: Vector[D, T]): Vector[D, T] =
9
+ for i, (l, r) in zip(left, right):
10
+ result[i] = l + r
11
+
12
+ func `+`*[D: static[int], T](left: Vector[D, T], right: T): Vector[D, T] =
13
+ for i in 0 ..< D:
14
+ result[i] = left[i] + right
15
+
16
+ func `+`*[D: static[int], T](left: T, right: Vector[D, T]): Vector[D, T] =
17
+ right + left
18
+
19
+ func `-`*[D: static[int], T](left, right: Vector[D, T]): Vector[D, T] =
20
+ for i, (l, r) in zip(left, right):
21
+ result[i] = l - r
22
+
23
+ func `*`*[D: static[int], T](left, right: Vector[D, T]): Vector[D, T] =
24
+ for i, (l, r) in zip(left, right):
25
+ result[i] = l * r
26
+
27
+ func `*`*[D: static[int], T](left: Vector[D, T], v: T): Vector[D, T] =
28
+ for i in 0 ..< D:
29
+ result[i] = left[i] * v
30
+
31
+ func `*`*[D: static[int], T](left: T, right: Vector[D, T]): Vector[D, T] =
32
+ right * left
33
+
34
+ ## Calculates euclidean norm
35
+ func norm*[D: static[int], T](vector: Vector[D, T]): T =
36
+ (vector * vector).sum().sqrt()
37
+
38
+ func dot*[D: static[int], T](left, right: Vector[D, T]): T =
39
+ let mul = (left * right)
40
+ for v in mul:
41
+ result = result + v
42
+
43
+ func angle*[D: static[int], T](left, right: Vector[D, T]): T =
44
+ arccos(dot(left, right) / (left.norm() * right.norm()))
45
+
46
+ func anyLower*[D: static[int], T](isThis, lowerThanThis: openArray[T]): bool =
47
+ for i in 0 ..< D:
48
+ if isThis[i] < lowerThanThis[i]:
49
+ return true
50
+ return false
51
+
52
+ func anyLowerEqual*[D: static[int], T](isThis, lowerThanThis: openArray[T]): bool =
53
+ for i in 0 ..< D:
54
+ if isThis[i] <= lowerThanThis[i]:
55
+ return true
56
+ return false