Debian Codegraph @

docs/source/tutorial.rst

raw
1 .. _tutorial:
2
3 Tutorial
4 ------------------------------------------------------------------------------
5
6 This tutorial demonstrates how to take advantage of :ref:`Rtree <home>` for
7 querying data that have a spatial component that can be modeled as bounding
8 boxes.
9
10
11 Creating an index
12 ..............................................................................
13
14 The following section describes the basic instantiation and usage of
15 :ref:`Rtree <home>`.
16
17 Import
18 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
19
20 After :ref:`installing <installation>` :ref:`Rtree <home>`, you should be able to
21 open up a Python prompt and issue the following:
22
23 .. code-block:: pycon
24
25 >>> from rtree import index
26
27 :py:mod:`rtree` is organized as a Python package with a couple of modules
28 and two major classes - :py:class:`rtree.index.Index` and
29 :py:class:`rtree.index.Property`. Users manipulate these classes to interact
30 with the index.
31
32 Construct an instance
33 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
34
35 After importing the index module, construct an index with the default
36 construction:
37
38 .. code-block:: pycon
39
40 >>> idx = index.Index()
41
42 .. note::
43
44 While the default construction is useful in many cases, if you want to
45 manipulate how the index is constructed you will need pass in a
46 :py:class:`rtree.index.Property` instance when creating the index.
47
48 Create a bounding box
49 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
50
51 After instantiating the index, create a bounding box that we can
52 insert into the index:
53
54 .. code-block:: pycon
55
56 >>> left, bottom, right, top = (0.0, 0.0, 1.0, 1.0)
57
58 .. note::
59
60 The coordinate ordering for all functions are sensitive the the index's
61 :py:attr:`~rtree.index.Index.interleaved` data member. If
62 :py:attr:`~rtree.index.Index.interleaved` is False, the coordinates must
63 be in the form [xmin, xmax, ymin, ymax, ..., ..., kmin, kmax]. If
64 :py:attr:`~rtree.index.Index.interleaved` is True, the coordinates must be
65 in the form [xmin, ymin, ..., kmin, xmax, ymax, ..., kmax].
66
67 Insert records into the index
68 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
69
70 Insert an entry into the index:
71
72 .. code-block:: pycon
73
74 >>> idx.insert(0, (left, bottom, right, top))
75
76 .. note::
77
78 Entries that are inserted into the index are not unique in either the
79 sense of the `id` or of the bounding box that is inserted with index
80 entries. If you need to maintain uniqueness, you need to manage that before
81 inserting entries into the Rtree.
82
83 .. note::
84
85 Inserting a point, i.e. where left == right && top == bottom, will
86 essentially insert a single point entry into the index instead of copying
87 extra coordinates and inserting them. There is no shortcut to explicitly
88 insert a single point, however.
89
90 Query the index
91 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
92
93 There are three primary methods for querying the index.
94 :py:meth:`rtree.index.Index.intersection` will return you index entries that
95 *cross* or are *contained* within the given query window.
96 :py:meth:`rtree.index.Index.intersection`
97
98 Intersection
99 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
100
101 Given a query window, return ids that are contained within the window:
102
103 .. code-block:: pycon
104
105 >>> list(idx.intersection((1.0, 1.0, 2.0, 2.0)))
106 [0]
107
108 Given a query window that is beyond the bounds of data we have in the
109 index:
110
111 .. code-block:: pycon
112
113 >>> list(idx.intersection((1.0000001, 1.0000001, 2.0, 2.0)))
114 []
115
116 Nearest Neighbors
117 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
118
119 The following finds the 1 nearest item to the given bounds. If multiple items
120 are of equal distance to the bounds, both are returned:
121
122 .. code-block:: pycon
123
124 >>> idx.insert(1, (left, bottom, right, top))
125 >>> list(idx.nearest((1.0000001, 1.0000001, 2.0, 2.0), 1))
126 [0, 1]
127
128
129 .. _clustered:
130
131 Using Rtree as a cheapo spatial database
132 ..............................................................................
133
134 Rtree also supports inserting any object you can pickle into the index (called
135 a clustered index in `libspatialindex`_ parlance). The following inserts the
136 picklable object ``42`` into the index with the given id ``2``:
137
138 .. code-block:: pycon
139
140 >>> idx.insert(id=2, coordinates=(left, bottom, right, top), obj=42)
141
142 You can then return a list of objects by giving the ``objects=True`` flag
143 to intersection:
144
145 .. code-block:: pycon
146
147 >>> [n.object for n in idx.intersection((left, bottom, right, top), objects=True)]
148 [None, None, 42]
149
150 .. warning::
151 `libspatialindex`_'s clustered indexes were not designed to be a database.
152 You get none of the data integrity protections that a database would
153 purport to offer, but this behavior of :ref:`Rtree <home>` can be useful
154 nonetheless. Consider yourself warned. Now go do cool things with it.
155
156 Serializing your index to a file
157 ..............................................................................
158
159 One of :ref:`Rtree <home>`'s most useful properties is the ability to
160 serialize Rtree indexes to disk. These include the clustered indexes
161 described :ref:`here <clustered>`:
162
163 .. code-block:: pycon
164
165 >>> import os
166 >>> from tempfile import TemporaryDirectory
167 >>> prev_dir = os.getcwd()
168 >>> temp_dir = TemporaryDirectory()
169 >>> os.chdir(temp_dir.name)
170 >>> file_idx = index.Rtree("myidx")
171 >>> file_idx.insert(1, (left, bottom, right, top))
172 >>> file_idx.insert(2, (left - 1.0, bottom - 1.0, right + 1.0, top + 1.0))
173 >>> [n for n in file_idx.intersection((left, bottom, right, top))]
174 [1, 2]
175 >>> sorted(os.listdir())
176 ['myidx.dat', 'myidx.idx']
177 >>> os.chdir(prev_dir)
178 >>> temp_dir.cleanup()
179
180 .. note::
181
182 By default, if an index file with the given name ``myidx`` in the example
183 above already exists on the file system, it will be opened in append mode
184 and not be re-created. You can control this behavior with the
185 :py:attr:`rtree.index.Property.overwrite` property of the index property
186 that can be given to the :py:class:`rtree.index.Index` constructor.
187
188 .. seealso::
189
190 :ref:`performance` describes some parameters you can tune to make
191 file-based indexes run a bit faster. The choices you make for the
192 parameters is entirely dependent on your usage.
193
194 Modifying file names
195 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
196
197 Rtree uses the extensions `dat` and `idx` by default for the two index files
198 that are created when serializing index data to disk. These file extensions
199 are controllable using the :py:attr:`rtree.index.Property.dat_extension` and
200 :py:attr:`rtree.index.Property.idx_extension` index properties.
201
202 .. code-block:: pycon
203
204 >>> p = index.Property()
205 >>> p.dat_extension = "data"
206 >>> p.idx_extension = "index"
207 >>> file_idx = index.Index("rtree", properties=p) # doctest: +SKIP
208
209 3D indexes
210 ..............................................................................
211
212 As of Rtree version 0.5.0, you can create 3D (actually kD) indexes. The
213 following is a 3D index that is to be stored on disk. Persisted indexes are
214 stored on disk using two files -- an index file (.idx) and a data (.dat) file.
215 You can modify the extensions these files use by altering the properties of
216 the index at instantiation time. The following creates a 3D index that is
217 stored on disk as the files ``3d_index.data`` and ``3d_index.index``:
218
219 .. code-block:: pycon
220
221 >>> from rtree import index
222 >>> temp_dir = TemporaryDirectory()
223 >>> os.chdir(temp_dir.name)
224 >>> p = index.Property()
225 >>> p.dimension = 3
226 >>> p.dat_extension = "data"
227 >>> p.idx_extension = "index"
228 >>> idx3d = index.Index("3d_index", properties=p)
229 >>> idx3d.insert(1, (0, 60, 23.0, 0, 60, 42.0))
230 >>> list(idx3d.intersection((-1, 60, 22, 1, 62, 43)))
231 [1]
232 >>> os.chdir(prev_dir)
233 >>> temp_dir.cleanup()
234
235 ZODB and Custom Storages
236 ..............................................................................
237
238 https://mail.zope.org/pipermail/zodb-dev/2010-June/013491.html contains a custom
239 storage backend for `ZODB`_ and you can find example python code `here`_. Note
240 that the code was written in 2011, hasn't been updated and was only an alpha
241 version.
242
243 .. _`here`: https://github.com/Toblerity/zope.index.rtree
244 .. _`ZODB`: https://zodb.org
245 .. _`libspatialindex`: https://libspatialindex.org