├── .github └── workflows │ └── main.yml ├── .gitignore ├── .gitmodules ├── COPYING ├── COPYING.LESSER ├── README.md ├── docs └── imgs │ └── raster2dggs-example.png ├── poetry.lock ├── pyproject.toml └── raster2dggs ├── __init__.py ├── cli.py ├── common.py ├── constants.py ├── geohash.py ├── h3.py ├── maidenhead.py ├── rHP.py └── s2.py /.github/workflows/main.yml: -------------------------------------------------------------------------------- 1 | name: manaakiwhenua-standards 2 | 3 | on: [push] 4 | 5 | jobs: 6 | build: 7 | 8 | runs-on: ubuntu-latest 9 | 10 | steps: 11 | - name : 'Checkout' 12 | uses : 'actions/checkout@v2' 13 | - name : 'manaakiwhenua-standards' 14 | uses : manaakiwhenua/manaakiwhenua-standards@v0.2.2 -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | tests 2 | __pycache__ 3 | dist 4 | .conda* 5 | .vscode/ 6 | -------------------------------------------------------------------------------- /.gitmodules: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/manaakiwhenua/raster2dggs/6f189ae9dd3f4b60182ce5f65e4b1936c37d35cf/.gitmodules -------------------------------------------------------------------------------- /COPYING: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /COPYING.LESSER: -------------------------------------------------------------------------------- 1 | GNU LESSER GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | 9 | This version of the GNU Lesser General Public License incorporates 10 | the terms and conditions of version 3 of the GNU General Public 11 | License, supplemented by the additional permissions listed below. 12 | 13 | 0. Additional Definitions. 14 | 15 | As used herein, "this License" refers to version 3 of the GNU Lesser 16 | General Public License, and the "GNU GPL" refers to version 3 of the GNU 17 | General Public License. 18 | 19 | "The Library" refers to a covered work governed by this License, 20 | other than an Application or a Combined Work as defined below. 21 | 22 | An "Application" is any work that makes use of an interface provided 23 | by the Library, but which is not otherwise based on the Library. 24 | Defining a subclass of a class defined by the Library is deemed a mode 25 | of using an interface provided by the Library. 26 | 27 | A "Combined Work" is a work produced by combining or linking an 28 | Application with the Library. The particular version of the Library 29 | with which the Combined Work was made is also called the "Linked 30 | Version". 31 | 32 | The "Minimal Corresponding Source" for a Combined Work means the 33 | Corresponding Source for the Combined Work, excluding any source code 34 | for portions of the Combined Work that, considered in isolation, are 35 | based on the Application, and not on the Linked Version. 36 | 37 | The "Corresponding Application Code" for a Combined Work means the 38 | object code and/or source code for the Application, including any data 39 | and utility programs needed for reproducing the Combined Work from the 40 | Application, but excluding the System Libraries of the Combined Work. 41 | 42 | 1. Exception to Section 3 of the GNU GPL. 43 | 44 | You may convey a covered work under sections 3 and 4 of this License 45 | without being bound by section 3 of the GNU GPL. 46 | 47 | 2. Conveying Modified Versions. 48 | 49 | If you modify a copy of the Library, and, in your modifications, a 50 | facility refers to a function or data to be supplied by an Application 51 | that uses the facility (other than as an argument passed when the 52 | facility is invoked), then you may convey a copy of the modified 53 | version: 54 | 55 | a) under this License, provided that you make a good faith effort to 56 | ensure that, in the event an Application does not supply the 57 | function or data, the facility still operates, and performs 58 | whatever part of its purpose remains meaningful, or 59 | 60 | b) under the GNU GPL, with none of the additional permissions of 61 | this License applicable to that copy. 62 | 63 | 3. Object Code Incorporating Material from Library Header Files. 64 | 65 | The object code form of an Application may incorporate material from 66 | a header file that is part of the Library. You may convey such object 67 | code under terms of your choice, provided that, if the incorporated 68 | material is not limited to numerical parameters, data structure 69 | layouts and accessors, or small macros, inline functions and templates 70 | (ten or fewer lines in length), you do both of the following: 71 | 72 | a) Give prominent notice with each copy of the object code that the 73 | Library is used in it and that the Library and its use are 74 | covered by this License. 75 | 76 | b) Accompany the object code with a copy of the GNU GPL and this license 77 | document. 78 | 79 | 4. Combined Works. 80 | 81 | You may convey a Combined Work under terms of your choice that, 82 | taken together, effectively do not restrict modification of the 83 | portions of the Library contained in the Combined Work and reverse 84 | engineering for debugging such modifications, if you also do each of 85 | the following: 86 | 87 | a) Give prominent notice with each copy of the Combined Work that 88 | the Library is used in it and that the Library and its use are 89 | covered by this License. 90 | 91 | b) Accompany the Combined Work with a copy of the GNU GPL and this license 92 | document. 93 | 94 | c) For a Combined Work that displays copyright notices during 95 | execution, include the copyright notice for the Library among 96 | these notices, as well as a reference directing the user to the 97 | copies of the GNU GPL and this license document. 98 | 99 | d) Do one of the following: 100 | 101 | 0) Convey the Minimal Corresponding Source under the terms of this 102 | License, and the Corresponding Application Code in a form 103 | suitable for, and under terms that permit, the user to 104 | recombine or relink the Application with a modified version of 105 | the Linked Version to produce a modified Combined Work, in the 106 | manner specified by section 6 of the GNU GPL for conveying 107 | Corresponding Source. 108 | 109 | 1) Use a suitable shared library mechanism for linking with the 110 | Library. A suitable mechanism is one that (a) uses at run time 111 | a copy of the Library already present on the user's computer 112 | system, and (b) will operate properly with a modified version 113 | of the Library that is interface-compatible with the Linked 114 | Version. 115 | 116 | e) Provide Installation Information, but only if you would otherwise 117 | be required to provide such information under section 6 of the 118 | GNU GPL, and only to the extent that such information is 119 | necessary to install and execute a modified version of the 120 | Combined Work produced by recombining or relinking the 121 | Application with a modified version of the Linked Version. (If 122 | you use option 4d0, the Installation Information must accompany 123 | the Minimal Corresponding Source and Corresponding Application 124 | Code. If you use option 4d1, you must provide the Installation 125 | Information in the manner specified by section 6 of the GNU GPL 126 | for conveying Corresponding Source.) 127 | 128 | 5. Combined Libraries. 129 | 130 | You may place library facilities that are a work based on the 131 | Library side by side in a single library together with other library 132 | facilities that are not Applications and are not covered by this 133 | License, and convey such a combined library under terms of your 134 | choice, if you do both of the following: 135 | 136 | a) Accompany the combined library with a copy of the same work based 137 | on the Library, uncombined with any other library facilities, 138 | conveyed under the terms of this License. 139 | 140 | b) Give prominent notice with the combined library that part of it 141 | is a work based on the Library, and explaining where to find the 142 | accompanying uncombined form of the same work. 143 | 144 | 6. Revised Versions of the GNU Lesser General Public License. 145 | 146 | The Free Software Foundation may publish revised and/or new versions 147 | of the GNU Lesser General Public License from time to time. Such new 148 | versions will be similar in spirit to the present version, but may 149 | differ in detail to address new problems or concerns. 150 | 151 | Each version is given a distinguishing version number. If the 152 | Library as you received it specifies that a certain numbered version 153 | of the GNU Lesser General Public License "or any later version" 154 | applies to it, you have the option of following the terms and 155 | conditions either of that published version or of any later version 156 | published by the Free Software Foundation. If the Library as you 157 | received it does not specify a version number of the GNU Lesser 158 | General Public License, you may choose any version of the GNU Lesser 159 | General Public License ever published by the Free Software Foundation. 160 | 161 | If the Library as you received it specifies that a proxy can decide 162 | whether future versions of the GNU Lesser General Public License shall 163 | apply, that proxy's public statement of acceptance of any version is 164 | permanent authorization for you to choose that version for the 165 | Library. 166 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # raster2dggs 2 | 3 | [![pypi](https://img.shields.io/pypi/v/raster2dggs?label=raster2ddgs)](https://pypi.org/project/raster2dggs/) 4 | 5 | Python-based CLI tool to index raster files to DGGS in parallel, writing out to Parquet. 6 | 7 | Currently this supports the following DGGSs: 8 | 9 | - [H3](https://h3geo.org/) 10 | - [rHEALPix](https://datastore.landcareresearch.co.nz/dataset/rhealpix-discrete-global-grid-system) 11 | - [S2](http://s2geometry.io/) 12 | 13 | And these geocode systems: 14 | 15 | - [Geohash](https://en.wikipedia.org/wiki/Geohash) 16 | - [Maidenhead Locator System](https://en.wikipedia.org/wiki/Maidenhead_Locator_System) 17 | 18 | Contributions (particularly for additional DGGSs), suggestions, bug reports and strongly worded letters are all welcome. 19 | 20 | ![Example use case for raster2dggs, showing how an input raster can be indexed at different DGGS resolutions, while retaining information in separate, named bands](docs/imgs/raster2dggs-example.png "Example use case for raster2dggs, showing how an input raster can be indexed at different H3 resolutions, while retaining information in separate, named bands") 21 | 22 | ## Installation 23 | 24 | `pip install raster2dggs` 25 | 26 | ## Usage 27 | 28 | ``` 29 | raster2dggs --help 30 | 31 | Usage: raster2dggs [OPTIONS] COMMAND [ARGS]... 32 | 33 | Options: 34 | --version Show the version and exit. 35 | --help Show this message and exit. 36 | 37 | Commands: 38 | geohash Ingest a raster image and index it using the Geohash... 39 | h3 Ingest a raster image and index it to the H3 DGGS. 40 | maidenhead Ingest a raster image and index it using the Maidenhead... 41 | rhp Ingest a raster image and index it to the rHEALPix DGGS. 42 | s2 Ingest a raster image and index it to the S2 DGGS. 43 | ``` 44 | 45 | ``` 46 | raster2dggs h3 --help 47 | 48 | Usage: raster2dggs h3 [OPTIONS] RASTER_INPUT OUTPUT_DIRECTORY 49 | 50 | Ingest a raster image and index it to the H3 DGGS. 51 | 52 | RASTER_INPUT is the path to input raster data; prepend with protocol like 53 | s3:// or hdfs:// for remote data. OUTPUT_DIRECTORY should be a directory, 54 | not a file, as it will be the write location for an Apache Parquet data 55 | store, with partitions equivalent to parent cells of target cells at a fixed 56 | offset. However, this can also be remote (use the appropriate prefix, e.g. 57 | s3://). 58 | 59 | Options: 60 | -v, --verbosity LVL Either CRITICAL, ERROR, WARNING, INFO or 61 | DEBUG [default: INFO] 62 | -r, --resolution [0|1|2|3|4|5|6|7|8|9|10|11|12|13|14|15] 63 | H3 resolution to index [required] 64 | -pr, --parent_res [0|1|2|3|4|5|6|7|8|9|10|11|12|13|14|15] 65 | H3 Parent resolution to index and aggregate 66 | to. Defaults to resolution - 6 67 | -u, --upscale INTEGER Upscaling factor, used to upsample input 68 | data on the fly; useful when the raster 69 | resolution is lower than the target DGGS 70 | resolution. Default (1) applies no 71 | upscaling. The resampling method controls 72 | interpolation. [default: 1] 73 | -c, --compression [snappy|gzip|zstd] 74 | Name of the compression to use when writing 75 | to Parquet. [default: snappy] 76 | -t, --threads INTEGER Number of threads to use when running in 77 | parallel. The default is determined based 78 | dynamically as the total number of available 79 | cores, minus one. [default: 11] 80 | -a, --aggfunc [count|mean|sum|prod|std|var|min|max|median|mode] 81 | Numpy aggregate function to apply when 82 | aggregating cell values after DGGS indexing, 83 | in case of multiple pixels mapping to the 84 | same DGGS cell. [default: mean] 85 | -d, --decimals INTEGER Number of decimal places to round values 86 | when aggregating. Use 0 for integer output. 87 | [default: 1] 88 | -o, --overwrite 89 | --warp_mem_limit INTEGER Input raster may be warped to EPSG:4326 if 90 | it is not already in this CRS. This setting 91 | specifies the warp operation's memory limit 92 | in MB. [default: 12000] 93 | --resampling [nearest|bilinear|cubic|cubic_spline|lanczos|average|mode|gauss|max|min|med|q1|q3|sum|rms] 94 | Input raster may be warped to EPSG:4326 if 95 | it is not already in this CRS. Or, if the 96 | upscale parameter is greater than 1, there 97 | is a need to resample. This setting 98 | specifies this resampling algorithm. 99 | [default: average] 100 | --tempdir PATH Temporary data is created during the 101 | execution of this program. This parameter 102 | allows you to control where this data will 103 | be written. 104 | --version Show the version and exit. 105 | --help Show this message and exit. 106 | ``` 107 | 108 | ## Visualising output 109 | 110 | Output is in the Apache Parquet format, a directory with one file per partition. Partitions are based on parent cell IDs, with the parent resolution determined as an offset from the target DGGS resolution. 111 | 112 | For a quick view of your output, you can read Apache Parquet with pandas, and then use h3-pandas and geopandas to convert this into a GeoPackage for visualisation in a desktop GIS, such as QGIS. The Apache Parquet output is indexed by the DGGS column, so it should be ready for association with other data prepared in the same DGGS. 113 | 114 |
115 | For H3 output... 116 | 117 | ```python 118 | >>> import pandas as pd 119 | >>> import h3pandas 120 | >>> o = pd.read_parquet('./tests/data/output/9/Sen2_Test') 121 | >>> o 122 | band B02 B03 B04 B05 B06 B07 B08 B8A B11 B12 123 | h3_09 124 | 89bb0981003ffff 9 27 16 62 175 197 228 247 102 36 125 | 89bb0981007ffff 10 30 17 66 185 212 238 261 113 40 126 | 89bb098100bffff 10 26 15 60 169 190 228 241 103 37 127 | 89bb098100fffff 11 29 17 66 181 203 243 257 109 39 128 | 89bb0981013ffff 8 26 16 58 172 199 220 244 98 34 129 | ... ... ... ... ... ... ... ... ... ... ... 130 | 89bb0d6eea7ffff 10 18 15 41 106 120 140 146 102 47 131 | 89bb0d6eeabffff 12 19 15 39 95 107 125 131 84 39 132 | 89bb0d6eeafffff 12 21 17 43 101 115 134 141 111 51 133 | 89bb0d6eeb7ffff 10 20 14 45 120 137 160 165 111 48 134 | 89bb0d6eebbffff 15 28 20 56 146 166 198 202 108 47 135 | 136 | [5656 rows x 10 columns] 137 | >>> o.h3.h3_to_geo_boundary().to_file('~/Downloads/Sen2_Test_h3-9.gpkg', driver='GPKG') 138 | ``` 139 |
140 | 141 |
142 | For rHEALPix output... 143 | 144 | For rHEALPix DGGS output, you can use [`rHP-Pandas`](https://github.com/manaakiwhenua/rHP-Pandas): 145 | 146 | ```python 147 | >>> import pandas as pd 148 | >>> import rhppandas 149 | >>> o = pd.read_parquet('./tests/data/output/11/Sen2_Test_rhp') 150 | >>> o 151 | band B02 B03 B04 B05 B06 B07 B08 B8A B11 B12 152 | rhp_11 153 | R88723652267 11 31 16 65 191 217 263 274 99 36 154 | R88723652268 11 30 15 66 190 214 258 269 96 34 155 | R88723652276 11 27 17 66 179 203 240 255 98 36 156 | R88723652277 13 30 19 68 179 204 246 260 108 41 157 | R88723652278 12 29 20 66 176 199 243 255 110 43 158 | ... ... ... ... ... ... ... ... ... ... ... 159 | R88727068804 22 39 41 81 151 167 182 203 166 84 160 | R88727068805 22 40 42 81 150 166 185 203 167 85 161 | R88727068806 23 41 43 83 156 175 188 211 164 83 162 | R88727068807 23 41 42 82 154 171 186 207 164 83 163 | R88727068808 22 39 43 80 146 163 177 198 165 83 164 | 165 | [223104 rows x 10 columns] 166 | >>> o.rhp.rhp_to_geo_boundary().to_file('~/Downloads/Sen2_Test_rhp-11.gpkg', driver='GPKG') 167 | ``` 168 |
169 | 170 |
171 | For S2 output... 172 | 173 | For S2 output, use [`s2sphere`](https://pypi.org/project/s2sphere/): 174 | 175 | ```python 176 | import pandas as pd 177 | import geopandas as gpd 178 | import s2sphere 179 | from shapely.geometry import Polygon 180 | 181 | df = pd.read_parquet('./tests/data/output/7/sample_tif_s2') 182 | df = df.reset_index() 183 | 184 | def s2id_to_polygon(s2_id_hex): 185 | # Parse the S2CellId 186 | cell_id = s2sphere.CellId.from_token(s2_id_hex) 187 | cell = s2sphere.Cell(cell_id) 188 | 189 | # Get the 4 vertices of the S2 cell 190 | vertices = [] 191 | for i in range(4): 192 | vertex = cell.get_vertex(i) 193 | # Convert to lat/lon degrees 194 | lat_lng = s2sphere.LatLng.from_point(vertex) 195 | vertices.append((lat_lng.lng().degrees, lat_lng.lat().degrees)) # (lon, lat) 196 | 197 | return Polygon(vertices) 198 | 199 | df['geometry'] = df['s2_15'].apply(s2id_to_polygon) 200 | gdf = gpd.GeoDataFrame(df, geometry='geometry', crs='EPSG:4326') # WGS84 201 | gdf.to_parquet('sample_tif_s2_geoparquet.parquet') 202 | ``` 203 |
204 | 205 |
206 | For Geohash output... 207 | 208 | For Geohash output, you can use [`python-geohash`](https://github.com/hkwi/python-geohash) or other similar Geohash library. Example: 209 | 210 | ```python 211 | import pandas as pd 212 | import geohash 213 | from shapely.geometry import Point, box 214 | import geopandas as gpd 215 | o = pd.read_parquet('./tests/data/output/8/sample_geohash') 216 | 217 | 218 | def geohash_to_geometry(gh, mode="polygon"): 219 | lat, lon, lat_err, lon_err = geohash.decode_exactly(gh) 220 | 221 | if mode == "point": 222 | return Point(lon, lat) 223 | elif mode == "polygon": 224 | return box(lon - lon_err, lat - lat_err, lon + lon_err, lat + lat_err) 225 | else: 226 | raise ValueError("mode must be 'point' or 'polygon'") 227 | 228 | o["geometry"] = o["geohash_08"].apply(lambda gh: geohash_to_geometry(gh, mode="polygon")) 229 | 230 | ''' 231 | band geohash_08 1 2 3 geometry 232 | 0 u170f2sq 0 0 0 POLYGON ((4.3238067626953125 52.16686248779297... 233 | 1 u170f2sr 0 0 0 POLYGON ((4.3238067626953125 52.16703414916992... 234 | 2 u170f2sw 0 0 0 POLYGON ((4.324150085449219 52.16686248779297,... 235 | 3 u170f2sx 0 0 0 POLYGON ((4.324150085449219 52.16703414916992,... 236 | 4 u170f2sy 0 0 0 POLYGON ((4.324493408203125 52.16686248779297,... 237 | ... ... .. .. .. ... 238 | 232720 u171mc2g 0 0 0 POLYGON ((4.472808837890625 52.258358001708984... 239 | 232721 u171mc2h 0 0 0 POLYGON ((4.471778869628906 52.25852966308594,... 240 | 232722 u171mc2k 0 0 0 POLYGON ((4.4721221923828125 52.25852966308594... 241 | 232723 u171mc2s 0 0 0 POLYGON ((4.472465515136719 52.25852966308594,... 242 | 232724 u171mc2u 0 0 0 POLYGON ((4.472808837890625 52.25852966308594,... 243 | 244 | [232725 rows x 5 columns] 245 | ''' 246 | 247 | gdf = gpd.GeoDataFrame(o, geometry="geometry", crs="EPSG:4326") 248 | gdf.to_file('sample.gpkg') 249 | ``` 250 |
251 | 252 | ## Installation 253 | 254 | PyPi: 255 | 256 | ```bash 257 | pip install raster2dggs 258 | ``` 259 | 260 | Conda environment: 261 | 262 | ```yaml 263 | name: raster2dggs 264 | channels: 265 | - conda-forge 266 | channel_priority: strict 267 | dependencies: 268 | - python>=3.11,<3.12 269 | - pip=23.1.* 270 | - gdal>=3.8.5 271 | - pyproj=3.6.* 272 | - pip: 273 | - raster2dggs>=0.3.0 274 | ``` 275 | 276 | 277 | 278 | ### For development 279 | 280 | In brief, to get started: 281 | 282 | - Install [Poetry](https://python-poetry.org/docs/basic-usage/) 283 | - Install [GDAL](https://gdal.org/) 284 | - If you're on Windows, `pip install gdal` may be necessary before running the subsequent commands. 285 | - On Linux, install GDAL 3.6+ according to your platform-specific instructions, including development headers, i.e. `libgdal-dev`. 286 | - Create the virtual environment with `poetry init`. This will install necessary dependencies. 287 | - Subsequently, the virtual environment can be re-activated with `poetry shell`. 288 | 289 | If you run `poetry install`, the CLI tool will be aliased so you can simply use `raster2dggs` rather than `poetry run raster2dggs`, which is the alternative if you do not `poetry install`. 290 | 291 | #### Code formatting 292 | 293 | [![Code style: black](https://img.shields.io/badge/code%20style-black-000000.svg)](https://github.com/psf/black) 294 | 295 | Please run `black .` before committing. 296 | 297 | #### Testing 298 | 299 | Two sample files have been uploaded to an S3 bucket with `s3:GetObject` public permission. 300 | 301 | - `s3://raster2dggs-test-data/Sen2_Test.tif` (sample Sentinel 2 imagery, 10 bands, rectangular, Int16, LZW compression, ~10x10m pixels, 68.6 MB) 302 | - `s3://raster2dggs-test-data/TestDEM.tif` (sample LiDAR-derived DEM, 1 band, irregular shape with null data, Float32, uncompressed, 10x10m pixels, 183.5 MB) 303 | 304 | You may use these for testing. However you can also test with local files too, which will be faster. A good, small (5 MB) sample image is available [here](https://github.com/mommermi/geotiff_sample). 305 | 306 | ## Example commands 307 | 308 | ```bash 309 | raster2dggs h3 --resolution 11 -d 0 s3://raster2dggs-test-data/Sen2_Test.tif ./tests/data/output/11/Sen2_Test 310 | ``` 311 | 312 | ```bash 313 | raster2dggs rhp --resolution 11 -d 0 s3://raster2dggs-test-data/Sen2_Test.tif ./tests/data/output/11/Sen2_Test_rhp 314 | ``` 315 | 316 | ```bash 317 | raster2dggs h3 --resolution 13 --compression zstd --resampling nearest -a median -d 1 -u 2 s3://raster2dggs-test-data/TestDEM.tif ./tests/data/output/13/TestDEM 318 | ``` 319 | 320 | ## Citation 321 | 322 | ```bibtex 323 | @software{raster2dggs, 324 | title={{raster2dggs}}, 325 | author={Ardo, James and Law, Richard}, 326 | url={https://github.com/manaakiwhenua/raster2dggs}, 327 | version={0.3.0}, 328 | date={2024-06-12} 329 | } 330 | ``` 331 | 332 | APA/Harvard 333 | 334 | > Ardo, J., & Law, R. (2024). raster2dggs (0.3.0) [Computer software]. https://github.com/manaakiwhenua/raster2dggs 335 | 336 | [![manaakiwhenua-standards](https://github.com/manaakiwhenua/raster2dggs/workflows/manaakiwhenua-standards/badge.svg)](https://github.com/manaakiwhenua/manaakiwhenua-standards) 337 | -------------------------------------------------------------------------------- /docs/imgs/raster2dggs-example.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/manaakiwhenua/raster2dggs/6f189ae9dd3f4b60182ce5f65e4b1936c37d35cf/docs/imgs/raster2dggs-example.png -------------------------------------------------------------------------------- /pyproject.toml: -------------------------------------------------------------------------------- 1 | [tool.poetry] 2 | name = "raster2dggs" 3 | version = "0.3.0" 4 | description = "" 5 | authors = ["James Ardo "] 6 | maintainers = ["Richard Law "] 7 | readme = "README.md" 8 | license = "LGPL-3.0-or-later" 9 | repository = "https://github.com/manaakiwhenua/raster2dggs" 10 | keywords = ["dggs", "raster", "h3", "rHEALPix", "cli"] 11 | classifiers = [ 12 | "Topic :: Scientific/Engineering", 13 | "Topic :: Scientific/Engineering :: GIS", 14 | "Topic :: Scientific/Engineering :: Image Processing", 15 | "Topic :: Scientific/Engineering :: Information Analysis" 16 | ] 17 | 18 | [tool.poetry.dependencies] 19 | python = "^3.12" 20 | gdal = "^3.8" 21 | geopandas = "^1.0" 22 | h3pandas = "^0.3" 23 | rioxarray = "^0.19" 24 | dask-geopandas = "^0.4" 25 | pyarrow = "^20.0" 26 | dask = "^2025.1" 27 | click = "^8.1" 28 | boto3 = "^1" 29 | tqdm = "^4" 30 | click-log = "^0.4" 31 | rasterio = "^1.4" 32 | dask-expr = "^2" 33 | numpy = "^2" 34 | rhppandas = "^0.1" 35 | rhealpixdggs = "^0.5" 36 | python-geohash = "^0.8" 37 | maidenhead = "^1.7" 38 | s2sphere = "^0.2" 39 | 40 | [tool.poetry.group.dev.dependencies] 41 | pytest = "^7.2.2" 42 | twine ="*" 43 | black = "*" 44 | 45 | [tool.poetry.scripts] 46 | raster2dggs = "raster2dggs.cli:main" 47 | 48 | [build-system] 49 | requires = ["poetry-core"] 50 | build-backend = "poetry.core.masonry.api" 51 | 52 | [tool.black] 53 | line-length = 88 -------------------------------------------------------------------------------- /raster2dggs/__init__.py: -------------------------------------------------------------------------------- 1 | __version__: str = "0.3.0" -------------------------------------------------------------------------------- /raster2dggs/cli.py: -------------------------------------------------------------------------------- 1 | import click 2 | 3 | from raster2dggs import __version__ 4 | from raster2dggs.h3 import h3 5 | from raster2dggs.rHP import rhp 6 | from raster2dggs.geohash import geohash 7 | from raster2dggs.maidenhead import maidenhead 8 | from raster2dggs.s2 import s2 9 | 10 | # If the program does terminal interaction, make it output a short 11 | # notice like this when it starts in an interactive mode: 12 | 13 | # Copyright (C) 14 | # This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 15 | # This is free software, and you are welcome to redistribute it 16 | # under certain conditions; type `show c' for details. 17 | 18 | 19 | @click.group() 20 | @click.version_option(version=__version__) 21 | def cli(): 22 | pass 23 | 24 | 25 | cli.add_command(h3) 26 | cli.add_command(rhp) 27 | cli.add_command(geohash) 28 | cli.add_command(maidenhead) 29 | cli.add_command(s2) 30 | 31 | 32 | def main(): 33 | cli() 34 | -------------------------------------------------------------------------------- /raster2dggs/common.py: -------------------------------------------------------------------------------- 1 | import os 2 | import errno 3 | import tempfile 4 | import logging 5 | import threading 6 | import rioxarray 7 | import dask 8 | import click_log 9 | 10 | import rasterio as rio 11 | import pandas as pd 12 | import pyarrow.parquet as pq 13 | 14 | from typing import Union, Callable 15 | from pathlib import Path 16 | from rasterio import crs 17 | from rasterio.vrt import WarpedVRT 18 | from rasterio.enums import Resampling 19 | from tqdm import tqdm 20 | from tqdm.dask import TqdmCallback 21 | import dask.dataframe as dd 22 | import xarray as xr 23 | 24 | from concurrent.futures import ThreadPoolExecutor, as_completed 25 | 26 | from urllib.parse import urlparse 27 | from rasterio.warp import calculate_default_transform 28 | 29 | import raster2dggs.constants as const 30 | 31 | LOGGER = logging.getLogger(__name__) 32 | click_log.basic_config(LOGGER) 33 | 34 | 35 | class ParentResolutionException(Exception): 36 | pass 37 | 38 | 39 | def check_resolutions(resolution: int, parent_res: int) -> None: 40 | if parent_res is not None and not int(parent_res) < int(resolution): 41 | raise ParentResolutionException( 42 | "Parent resolution ({pr}) must be less than target resolution ({r})".format( 43 | pr=parent_res, r=resolution 44 | ) 45 | ) 46 | 47 | 48 | def resolve_input_path(raster_input: Union[str, Path]) -> Union[str, Path]: 49 | if not Path(raster_input).exists(): 50 | if not urlparse(raster_input).scheme: 51 | LOGGER.warning( 52 | f"Input raster {raster_input} does not exist, and is not recognised as a remote URI" 53 | ) 54 | raise FileNotFoundError( 55 | errno.ENOENT, os.strerror(errno.ENOENT), raster_input 56 | ) 57 | # Quacks like a path to remote data 58 | raster_input = str(raster_input) 59 | else: 60 | raster_input = Path(raster_input) 61 | 62 | return raster_input 63 | 64 | 65 | def assemble_warp_args(resampling: str, warp_mem_limit: int) -> dict: 66 | warp_args: dict = { 67 | "resampling": Resampling._member_map_[resampling], 68 | "crs": crs.CRS.from_epsg( 69 | 4326 70 | ), # Input raster must be converted to WGS84 (4326) for DGGS indexing 71 | "warp_mem_limit": warp_mem_limit, 72 | } 73 | 74 | return warp_args 75 | 76 | 77 | def create_aggfunc(aggfunc: str) -> str: 78 | if aggfunc == "mode": 79 | logging.warning( 80 | "Mode aggregation: arbitrary behaviour: if there is more than one mode when aggregating, only the first value will be recorded." 81 | ) 82 | aggfunc = lambda x: pd.Series.mode(x)[0] 83 | 84 | return aggfunc 85 | 86 | 87 | def assemble_kwargs( 88 | upscale: int, 89 | compression: str, 90 | threads: int, 91 | aggfunc: str, 92 | decimals: int, 93 | warp_mem_limit: int, 94 | resampling: str, 95 | overwrite: bool, 96 | ) -> dict: 97 | kwargs = { 98 | "upscale": upscale, 99 | "compression": compression, 100 | "threads": threads, 101 | "aggfunc": aggfunc, 102 | "decimals": decimals, 103 | "warp_mem_limit": warp_mem_limit, 104 | "resampling": resampling, 105 | "overwrite": overwrite, 106 | } 107 | 108 | return kwargs 109 | 110 | 111 | def zero_padding(dggs: str) -> int: 112 | max_res_lookup = { 113 | "h3": const.MAX_H3, 114 | "rhp": const.MAX_RHP, 115 | "geohash": const.MAX_GEOHASH, 116 | "maidenhead": const.MAX_MAIDENHEAD, 117 | "s2": const.MAX_S2, 118 | } 119 | max_res = max_res_lookup.get(dggs) 120 | if max_res is None: 121 | raise ValueError(f"Unknown DGGS type: {dggs}") 122 | return len(str(max_res)) 123 | 124 | 125 | def get_parent_res(dggs: str, parent_res: Union[None, int], resolution: int) -> int: 126 | """ 127 | Uses a parent resolution, 128 | OR, 129 | Given a target resolution, returns our recommended parent resolution. 130 | 131 | Used for intermediate re-partioning. 132 | """ 133 | if not dggs in const.DEFAULT_DGGS_PARENT_RES.keys(): 134 | raise RuntimeError( 135 | "Unknown dggs {dggs}) - must be one of [ {options} ]".format( 136 | dggs=dggs, options=", ".join(const.DEFAULT_DGGS_PARENT_RES.keys()) 137 | ) 138 | ) 139 | return ( 140 | int(parent_res) 141 | if parent_res is not None 142 | else const.DEFAULT_DGGS_PARENT_RES[dggs] 143 | ) 144 | 145 | 146 | def address_boundary_issues( 147 | dggs: str, 148 | parent_groupby: Callable, 149 | pq_input: tempfile.TemporaryDirectory, 150 | output: Path, 151 | resolution: int, 152 | parent_res: int, 153 | **kwargs, 154 | ) -> Path: 155 | """ 156 | After "stage 1" processing, there is a DGGS cell and band value/s for each pixel in the input image. Partitions are based 157 | on raster windows. 158 | 159 | This function will re-partition based on parent cell IDs at a fixed offset from the target resolution. 160 | 161 | Once re-partitioned on this basis, values are aggregated at the target resolution, to account for multiple pixels mapping 162 | to the same cell. 163 | 164 | This re-partitioning is necessary to address the issue of the same cell IDs being present in different partitions 165 | of the original (i.e. window-based) partitioning. Using the nested structure of the DGGS is an useful property 166 | to address this problem. 167 | """ 168 | LOGGER.debug( 169 | f"Reading Stage 1 output ({pq_input}) and setting index for parent-based partitioning" 170 | ) 171 | with TqdmCallback(desc="Reading window partitions"): 172 | # Set index as parent cell 173 | pad_width = zero_padding(dggs) 174 | index_col = f"{dggs}_{parent_res:0{pad_width}d}" 175 | ddf = dd.read_parquet(pq_input).set_index(index_col) 176 | 177 | with TqdmCallback(desc="Counting parents"): 178 | # Count parents, to get target number of partitions 179 | uniqueparents = sorted(list(ddf.index.unique().compute())) 180 | 181 | LOGGER.debug( 182 | "Repartitioning into %d partitions, based on parent cells", 183 | len(uniqueparents) + 1, 184 | ) 185 | LOGGER.debug("Aggregating cell values where conflicts exist") 186 | 187 | with TqdmCallback(desc="Repartioning/aggregating"): 188 | ddf = ( 189 | ddf.repartition( # See "notes" on why divisions expects repetition of the last item https://docs.dask.org/en/stable/generated/dask.dataframe.DataFrame.repartition.html 190 | divisions=(uniqueparents + [uniqueparents[-1]]) 191 | ) 192 | .map_partitions( 193 | parent_groupby, resolution, kwargs["aggfunc"], kwargs["decimals"] 194 | ) 195 | .to_parquet( 196 | output, 197 | overwrite=kwargs["overwrite"], 198 | engine="pyarrow", 199 | write_index=True, 200 | append=False, 201 | name_function=lambda i: f"{uniqueparents[i]}.parquet", 202 | compression=kwargs["compression"], 203 | ) 204 | ) 205 | 206 | LOGGER.debug( 207 | "Stage 2 (parent cell repartioning) and Stage 3 (aggregation) complete" 208 | ) 209 | 210 | return output 211 | 212 | 213 | def initial_index( 214 | dggs: str, 215 | dggsfunc: Callable, 216 | parent_groupby: Callable, 217 | raster_input: Union[Path, str], 218 | output: Path, 219 | resolution: int, 220 | parent_res: Union[None, int], 221 | warp_args: dict, 222 | **kwargs, 223 | ) -> Path: 224 | """ 225 | Responsible for opening the raster_input, and performing DGGS indexing per window of a WarpedVRT. 226 | 227 | A WarpedVRT is used to enforce reprojection to https://epsg.io/4326, which is used for all DGGS indexing. 228 | 229 | It also allows on-the-fly resampling of the input, which is useful if the target DGGS resolution exceeds the resolution 230 | of the input. 231 | 232 | This function passes a path to a temporary directory (which contains the output of this "stage 1" processing) to 233 | a secondary function that addresses issues at the boundaries of raster windows. 234 | """ 235 | parent_res = get_parent_res(dggs, parent_res, resolution) 236 | LOGGER.info( 237 | "Indexing %s at %s resolution %d, parent resolution %d", 238 | raster_input, 239 | str(dggs), 240 | int(resolution), 241 | int(parent_res), 242 | ) 243 | 244 | with tempfile.TemporaryDirectory() as tmpdir: 245 | LOGGER.debug(f"Create temporary directory {tmpdir}") 246 | 247 | # https://rasterio.readthedocs.io/en/latest/api/rasterio.warp.html#rasterio.warp.calculate_default_transform 248 | with rio.Env(CHECK_WITH_INVERT_PROJ=True): 249 | with rio.open(raster_input) as src: 250 | LOGGER.debug("Source CRS: %s", src.crs) 251 | # VRT used to avoid additional disk use given the potential for reprojection to 4326 prior to DGGS indexing 252 | band_names = src.descriptions 253 | 254 | upscale_factor = kwargs["upscale"] 255 | if upscale_factor > 1: 256 | dst_crs = warp_args["crs"] 257 | transform, width, height = calculate_default_transform( 258 | src.crs, 259 | dst_crs, 260 | src.width, 261 | src.height, 262 | *src.bounds, 263 | dst_width=src.width * upscale_factor, 264 | dst_height=src.height * upscale_factor, 265 | ) 266 | upsample_args = dict( 267 | {"transform": transform, "width": width, "height": height} 268 | ) 269 | LOGGER.debug(upsample_args) 270 | else: 271 | upsample_args = dict({}) 272 | 273 | with WarpedVRT( 274 | src, src_crs=src.crs, **warp_args, **upsample_args 275 | ) as vrt: 276 | LOGGER.debug("VRT CRS: %s", vrt.crs) 277 | da: xr.Dataset = rioxarray.open_rasterio( 278 | vrt, 279 | lock=dask.utils.SerializableLock(), 280 | masked=True, 281 | default_name=const.DEFAULT_NAME, 282 | ).chunk(**{"y": "auto", "x": "auto"}) 283 | 284 | windows = [window for _, window in vrt.block_windows()] 285 | LOGGER.debug( 286 | "%d windows (the same number of partitions will be created)", 287 | len(windows), 288 | ) 289 | 290 | write_lock = threading.Lock() 291 | 292 | def process(window): 293 | sdf = da.rio.isel_window(window) 294 | 295 | result = dggsfunc( 296 | sdf, 297 | resolution, 298 | parent_res, 299 | vrt.nodata, 300 | band_labels=band_names, 301 | ) 302 | 303 | with write_lock: 304 | pq.write_to_dataset( 305 | result, 306 | root_path=tmpdir, 307 | compression=kwargs["compression"], 308 | ) 309 | 310 | return None 311 | 312 | with tqdm(total=len(windows), desc="Raster windows") as pbar: 313 | with ThreadPoolExecutor( 314 | max_workers=kwargs["threads"] 315 | ) as executor: 316 | futures = [ 317 | executor.submit(process, window) for window in windows 318 | ] 319 | for future in as_completed(futures): 320 | result = future.result() 321 | pbar.update(1) 322 | 323 | LOGGER.debug("Stage 1 (primary indexing) complete") 324 | return address_boundary_issues( 325 | dggs, 326 | parent_groupby, 327 | tmpdir, 328 | output, 329 | resolution, 330 | parent_res, 331 | **kwargs, 332 | ) 333 | -------------------------------------------------------------------------------- /raster2dggs/constants.py: -------------------------------------------------------------------------------- 1 | import multiprocessing 2 | import tempfile 3 | 4 | MIN_H3, MAX_H3 = 0, 15 5 | MIN_RHP, MAX_RHP = 0, 15 6 | MIN_GEOHASH, MAX_GEOHASH = 1, 12 7 | MIN_MAIDENHEAD, MAX_MAIDENHEAD = 1, 4 8 | MIN_S2, MAX_S2 = 0, 30 9 | 10 | DEFAULT_NAME: str = "value" 11 | 12 | DEFAULTS = { 13 | "upscale": 1, 14 | "compression": "snappy", 15 | "threads": (multiprocessing.cpu_count() - 1), 16 | "aggfunc": "mean", 17 | "decimals": 1, 18 | "warp_mem_limit": 12000, 19 | "resampling": "average", 20 | "tempdir": tempfile.tempdir, 21 | } 22 | 23 | DEFAULT_PARENT_OFFSET = 6 24 | 25 | DEFAULT_DGGS_PARENT_RES = { 26 | "h3": lambda resolution: max(MIN_H3, (resolution - DEFAULT_PARENT_OFFSET)), 27 | "rhp": lambda resolution: max(MIN_RHP, (resolution - DEFAULT_PARENT_OFFSET)), 28 | "geohash": lambda resolution: max( 29 | MIN_GEOHASH, (resolution - DEFAULT_PARENT_OFFSET) 30 | ), 31 | "maidenhead": lambda resolution: MIN_MAIDENHEAD, 32 | "s2": lambda resolution: max(MIN_S2, (resolution - DEFAULT_PARENT_OFFSET)), 33 | } 34 | -------------------------------------------------------------------------------- /raster2dggs/geohash.py: -------------------------------------------------------------------------------- 1 | from numbers import Number 2 | import numpy as np 3 | from pathlib import Path 4 | import tempfile 5 | from typing import Callable, Tuple, Union 6 | 7 | import click 8 | import click_log 9 | import pandas as pd 10 | import pyarrow as pa 11 | from rasterio.enums import Resampling 12 | import xarray as xr 13 | import geohash as gh 14 | 15 | import raster2dggs.constants as const 16 | import raster2dggs.common as common 17 | from raster2dggs import __version__ 18 | 19 | 20 | PAD_WIDTH = common.zero_padding("geohash") 21 | 22 | 23 | def _geohashfunc( 24 | sdf: xr.DataArray, 25 | precision: int, 26 | parent_precision: int, 27 | nodata: Number = np.nan, 28 | band_labels: Tuple[str] = None, 29 | ) -> pa.Table: 30 | """ 31 | Index a raster window to Geohash. 32 | Subsequent steps are necessary to resolve issues at the boundaries of windows. 33 | If windows are very small, or in strips rather than blocks, processing may be slower 34 | than necessary and the recommendation is to write different windows in the source raster. 35 | """ 36 | sdf: pd.DataFrame = sdf.to_dataframe().drop(columns=["spatial_ref"]).reset_index() 37 | subset: pd.DataFrame = sdf.dropna() 38 | subset = subset[subset.value != nodata] 39 | subset = pd.pivot_table( 40 | subset, values=const.DEFAULT_NAME, index=["x", "y"], columns=["band"] 41 | ).reset_index() 42 | # Primary Geohash index 43 | geohash = [ 44 | gh.encode(lat, lon, precision=precision) 45 | for lat, lon in zip(subset["y"], subset["x"]) 46 | ] # Vectorised 47 | # Secondary (parent) Geohash index, used later for partitioning 48 | geohash_parent = [gh[:parent_precision] for gh in geohash] 49 | subset = subset.drop(columns=["x", "y"]) 50 | subset[f"geohash_{precision:0{PAD_WIDTH}d}"] = pd.Series( 51 | geohash, index=subset.index 52 | ) 53 | subset[f"geohash_{parent_precision:0{PAD_WIDTH}d}"] = pd.Series( 54 | geohash_parent, index=subset.index 55 | ) 56 | # Rename bands 57 | bands = sdf["band"].unique() 58 | band_names = dict(zip(bands, map(lambda i: band_labels[i - 1], bands))) 59 | for k, v in band_names.items(): 60 | if band_names[k] is None: 61 | band_names[k] = str(bands[k - 1]) 62 | else: 63 | band_names = band_names 64 | subset = subset.rename(columns=band_names) 65 | return pa.Table.from_pandas(subset) 66 | 67 | 68 | def _geohash_parent_groupby( 69 | df, precision: int, aggfunc: Union[str, Callable], decimals: int 70 | ): 71 | """ 72 | Function for aggregating the Geohash values per parent partition. Each partition will be run through with a 73 | pandas .groupby function. This step is to ensure there are no duplicate Geohashes, which will happen when indexing a 74 | high resolution raster at a coarse Geohash precision. 75 | """ 76 | if decimals > 0: 77 | return ( 78 | df.groupby(f"geohash_{precision:0{PAD_WIDTH}d}") 79 | .agg(aggfunc) 80 | .round(decimals) 81 | ) 82 | else: 83 | return ( 84 | df.groupby(f"geohash_{precision:0{PAD_WIDTH}d}") 85 | .agg(aggfunc) 86 | .round(decimals) 87 | .astype("Int64") 88 | ) 89 | 90 | 91 | @click.command(context_settings={"show_default": True}) 92 | @click_log.simple_verbosity_option(common.LOGGER) 93 | @click.argument("raster_input", type=click.Path(), nargs=1) 94 | @click.argument("output_directory", type=click.Path(), nargs=1) 95 | @click.option( 96 | "-r", 97 | "--resolution", 98 | required=True, 99 | type=click.Choice(list(map(str, range(const.MIN_GEOHASH, const.MAX_GEOHASH + 1)))), 100 | help="Geohash precision to index (string length of the Geohashes used to define cells)", 101 | ) 102 | @click.option( 103 | "-pr", 104 | "--parent_res", 105 | required=False, 106 | type=click.Choice(list(map(str, range(const.MIN_GEOHASH, const.MAX_GEOHASH + 1)))), 107 | help="Geohash 'parent' precision to index and aggregate to. Defaults to precision - 6", 108 | ) 109 | @click.option( 110 | "-u", 111 | "--upscale", 112 | default=const.DEFAULTS["upscale"], 113 | type=int, 114 | help="Upscaling factor, used to upsample input data on the fly; useful when the raster resolution is lower than the target Geohash precision. Default (1) applies no upscaling. The resampling method controls interpolation.", 115 | ) 116 | @click.option( 117 | "-c", 118 | "--compression", 119 | default=const.DEFAULTS["compression"], 120 | type=click.Choice(["snappy", "gzip", "zstd"]), 121 | help="Name of the compression to use when writing to Parquet.", 122 | ) 123 | @click.option( 124 | "-t", 125 | "--threads", 126 | default=const.DEFAULTS["threads"], 127 | help="Number of threads to use when running in parallel. The default is determined based dynamically as the total number of available cores, minus one.", 128 | ) 129 | @click.option( 130 | "-a", 131 | "--aggfunc", 132 | default=const.DEFAULTS["aggfunc"], 133 | type=click.Choice( 134 | ["count", "mean", "sum", "prod", "std", "var", "min", "max", "median", "mode"] 135 | ), 136 | help="Numpy aggregate function to apply when aggregating cell values after DGGS indexing, in case of multiple pixels mapping to the same DGGS cell.", 137 | ) 138 | @click.option( 139 | "-d", 140 | "--decimals", 141 | default=const.DEFAULTS["decimals"], 142 | type=int, 143 | help="Number of decimal places to round values when aggregating. Use 0 for integer output.", 144 | ) 145 | @click.option("-o", "--overwrite", is_flag=True) 146 | @click.option( 147 | "--warp_mem_limit", 148 | default=const.DEFAULTS["warp_mem_limit"], 149 | type=int, 150 | help="Input raster may be warped to EPSG:4326 if it is not already in this CRS. This setting specifies the warp operation's memory limit in MB.", 151 | ) 152 | @click.option( 153 | "--resampling", 154 | default=const.DEFAULTS["resampling"], 155 | type=click.Choice(Resampling._member_names_), 156 | help="Input raster may be warped to EPSG:4326 if it is not already in this CRS. Or, if the upscale parameter is greater than 1, there is a need to resample. This setting specifies this resampling algorithm.", 157 | ) 158 | @click.option( 159 | "--tempdir", 160 | default=const.DEFAULTS["tempdir"], 161 | type=click.Path(), 162 | help="Temporary data is created during the execution of this program. This parameter allows you to control where this data will be written.", 163 | ) 164 | @click.version_option(version=__version__) 165 | def geohash( 166 | raster_input: Union[str, Path], 167 | output_directory: Union[str, Path], 168 | resolution: str, 169 | parent_res: str, 170 | upscale: int, 171 | compression: str, 172 | threads: int, 173 | aggfunc: str, 174 | decimals: int, 175 | overwrite: bool, 176 | warp_mem_limit: int, 177 | resampling: str, 178 | tempdir: Union[str, Path], 179 | ): 180 | """ 181 | Ingest a raster image and index it using the Geohash geocode system. 182 | 183 | RASTER_INPUT is the path to input raster data; prepend with protocol like s3:// or hdfs:// for remote data. 184 | OUTPUT_DIRECTORY should be a directory, not a file, as it will be the write location for an Apache Parquet data store, with partitions equivalent to parent cells of target cells at a fixed offset. However, this can also be remote (use the appropriate prefix, e.g. s3://). 185 | """ 186 | tempfile.tempdir = tempdir if tempdir is not None else tempfile.tempdir 187 | 188 | common.check_resolutions(resolution, parent_res) 189 | 190 | raster_input = common.resolve_input_path(raster_input) 191 | warp_args = common.assemble_warp_args(resampling, warp_mem_limit) 192 | aggfunc = common.create_aggfunc(aggfunc) 193 | kwargs = common.assemble_kwargs( 194 | upscale, 195 | compression, 196 | threads, 197 | aggfunc, 198 | decimals, 199 | warp_mem_limit, 200 | resampling, 201 | overwrite, 202 | ) 203 | 204 | common.initial_index( 205 | "geohash", 206 | _geohashfunc, 207 | _geohash_parent_groupby, 208 | raster_input, 209 | output_directory, 210 | int(resolution), 211 | parent_res, 212 | warp_args, 213 | **kwargs, 214 | ) 215 | -------------------------------------------------------------------------------- /raster2dggs/h3.py: -------------------------------------------------------------------------------- 1 | from numbers import Number 2 | import numpy as np 3 | from pathlib import Path 4 | import tempfile 5 | from typing import Callable, Tuple, Union 6 | 7 | import click 8 | import click_log 9 | import h3pandas # Necessary import despite lack of explicit use 10 | import pandas as pd 11 | import pyarrow as pa 12 | from rasterio.enums import Resampling 13 | import xarray as xr 14 | 15 | import raster2dggs.constants as const 16 | import raster2dggs.common as common 17 | from raster2dggs import __version__ 18 | 19 | PAD_WIDTH = common.zero_padding("h3") 20 | 21 | 22 | def _h3func( 23 | sdf: xr.DataArray, 24 | resolution: int, 25 | parent_res: int, 26 | nodata: Number = np.nan, 27 | band_labels: Tuple[str] = None, 28 | ) -> pa.Table: 29 | """ 30 | Index a raster window to H3. 31 | Subsequent steps are necessary to resolve issues at the boundaries of windows. 32 | If windows are very small, or in strips rather than blocks, processing may be slower 33 | than necessary and the recommendation is to write different windows in the source raster. 34 | """ 35 | sdf: pd.DataFrame = sdf.to_dataframe().drop(columns=["spatial_ref"]).reset_index() 36 | subset: pd.DataFrame = sdf.dropna() 37 | subset = subset[subset.value != nodata] 38 | subset = pd.pivot_table( 39 | subset, values=const.DEFAULT_NAME, index=["x", "y"], columns=["band"] 40 | ).reset_index() 41 | # Primary H3 index 42 | h3index = subset.h3.geo_to_h3(resolution, lat_col="y", lng_col="x").drop( 43 | columns=["x", "y"] 44 | ) 45 | # Secondary (parent) H3 index, used later for partitioning 46 | h3index = h3index.h3.h3_to_parent(parent_res).reset_index() 47 | # Renaming columns to actual band labels 48 | bands = sdf["band"].unique() 49 | band_names = dict(zip(bands, map(lambda i: band_labels[i - 1], bands))) 50 | for k, v in band_names.items(): 51 | if band_names[k] is None: 52 | band_names[k] = str(bands[k - 1]) 53 | else: 54 | band_names = band_names 55 | h3index = h3index.rename(columns=band_names) 56 | return pa.Table.from_pandas(h3index) 57 | 58 | 59 | def _h3_parent_groupby( 60 | df, resolution: int, aggfunc: Union[str, Callable], decimals: int 61 | ): 62 | """ 63 | Function for aggregating the h3 resolution values per parent partition. Each partition will be run through with a 64 | pandas .groupby function. This step is to ensure there are no duplicate h3 values, which will happen when indexing a 65 | high resolution raster at a coarser h3 resolution. 66 | """ 67 | if decimals > 0: 68 | return df.groupby(f"h3_{resolution:0{PAD_WIDTH}d}").agg(aggfunc).round(decimals) 69 | else: 70 | return ( 71 | df.groupby(f"h3_{resolution:0{PAD_WIDTH}d}") 72 | .agg(aggfunc) 73 | .round(decimals) 74 | .astype("Int64") 75 | ) 76 | 77 | 78 | @click.command(context_settings={"show_default": True}) 79 | @click_log.simple_verbosity_option(common.LOGGER) 80 | @click.argument("raster_input", type=click.Path(), nargs=1) 81 | @click.argument("output_directory", type=click.Path(), nargs=1) 82 | @click.option( 83 | "-r", 84 | "--resolution", 85 | required=True, 86 | type=click.Choice(list(map(str, range(const.MIN_H3, const.MAX_H3 + 1)))), 87 | help="H3 resolution to index", 88 | ) 89 | @click.option( 90 | "-pr", 91 | "--parent_res", 92 | required=False, 93 | type=click.Choice(list(map(str, range(const.MIN_H3, const.MAX_H3 + 1)))), 94 | help="H3 Parent resolution to index and aggregate to. Defaults to resolution - 6", 95 | ) 96 | @click.option( 97 | "-u", 98 | "--upscale", 99 | default=const.DEFAULTS["upscale"], 100 | type=int, 101 | help="Upscaling factor, used to upsample input data on the fly; useful when the raster resolution is lower than the target DGGS resolution. Default (1) applies no upscaling. The resampling method controls interpolation.", 102 | ) 103 | @click.option( 104 | "-c", 105 | "--compression", 106 | default=const.DEFAULTS["compression"], 107 | type=click.Choice(["snappy", "gzip", "zstd"]), 108 | help="Name of the compression to use when writing to Parquet.", 109 | ) 110 | @click.option( 111 | "-t", 112 | "--threads", 113 | default=const.DEFAULTS["threads"], 114 | help="Number of threads to use when running in parallel. The default is determined based dynamically as the total number of available cores, minus one.", 115 | ) 116 | @click.option( 117 | "-a", 118 | "--aggfunc", 119 | default=const.DEFAULTS["aggfunc"], 120 | type=click.Choice( 121 | ["count", "mean", "sum", "prod", "std", "var", "min", "max", "median", "mode"] 122 | ), 123 | help="Numpy aggregate function to apply when aggregating cell values after DGGS indexing, in case of multiple pixels mapping to the same DGGS cell.", 124 | ) 125 | @click.option( 126 | "-d", 127 | "--decimals", 128 | default=const.DEFAULTS["decimals"], 129 | type=int, 130 | help="Number of decimal places to round values when aggregating. Use 0 for integer output.", 131 | ) 132 | @click.option("-o", "--overwrite", is_flag=True) 133 | @click.option( 134 | "--warp_mem_limit", 135 | default=const.DEFAULTS["warp_mem_limit"], 136 | type=int, 137 | help="Input raster may be warped to EPSG:4326 if it is not already in this CRS. This setting specifies the warp operation's memory limit in MB.", 138 | ) 139 | @click.option( 140 | "--resampling", 141 | default=const.DEFAULTS["resampling"], 142 | type=click.Choice(Resampling._member_names_), 143 | help="Input raster may be warped to EPSG:4326 if it is not already in this CRS. Or, if the upscale parameter is greater than 1, there is a need to resample. This setting specifies this resampling algorithm.", 144 | ) 145 | @click.option( 146 | "--tempdir", 147 | default=const.DEFAULTS["tempdir"], 148 | type=click.Path(), 149 | help="Temporary data is created during the execution of this program. This parameter allows you to control where this data will be written.", 150 | ) 151 | @click.version_option(version=__version__) 152 | def h3( 153 | raster_input: Union[str, Path], 154 | output_directory: Union[str, Path], 155 | resolution: str, 156 | parent_res: str, 157 | upscale: int, 158 | compression: str, 159 | threads: int, 160 | aggfunc: str, 161 | decimals: int, 162 | overwrite: bool, 163 | warp_mem_limit: int, 164 | resampling: str, 165 | tempdir: Union[str, Path], 166 | ): 167 | """ 168 | Ingest a raster image and index it to the H3 DGGS. 169 | 170 | RASTER_INPUT is the path to input raster data; prepend with protocol like s3:// or hdfs:// for remote data. 171 | OUTPUT_DIRECTORY should be a directory, not a file, as it will be the write location for an Apache Parquet data store, with partitions equivalent to parent cells of target cells at a fixed offset. However, this can also be remote (use the appropriate prefix, e.g. s3://). 172 | """ 173 | tempfile.tempdir = tempdir if tempdir is not None else tempfile.tempdir 174 | 175 | common.check_resolutions(resolution, parent_res) 176 | 177 | raster_input = common.resolve_input_path(raster_input) 178 | warp_args = common.assemble_warp_args(resampling, warp_mem_limit) 179 | aggfunc = common.create_aggfunc(aggfunc) 180 | kwargs = common.assemble_kwargs( 181 | upscale, 182 | compression, 183 | threads, 184 | aggfunc, 185 | decimals, 186 | warp_mem_limit, 187 | resampling, 188 | overwrite, 189 | ) 190 | 191 | common.initial_index( 192 | "h3", 193 | _h3func, 194 | _h3_parent_groupby, 195 | raster_input, 196 | output_directory, 197 | int(resolution), 198 | parent_res, 199 | warp_args, 200 | **kwargs, 201 | ) 202 | -------------------------------------------------------------------------------- /raster2dggs/maidenhead.py: -------------------------------------------------------------------------------- 1 | from numbers import Number 2 | import numpy as np 3 | from pathlib import Path 4 | import tempfile 5 | from typing import Callable, Tuple, Union 6 | 7 | import click 8 | import click_log 9 | import pandas as pd 10 | import pyarrow as pa 11 | from rasterio.enums import Resampling 12 | import xarray as xr 13 | import maidenhead as mh 14 | 15 | import raster2dggs.constants as const 16 | import raster2dggs.common as common 17 | from raster2dggs import __version__ 18 | 19 | 20 | def _maidenheadfunc( 21 | sdf: xr.DataArray, 22 | level: int, 23 | parent_level: int, 24 | nodata: Number = np.nan, 25 | band_labels: Tuple[str] = None, 26 | ) -> pa.Table: 27 | """ 28 | Index a raster window to Maidenhead. 29 | Subsequent steps are necessary to resolve issues at the boundaries of windows. 30 | If windows are very small, or in strips rather than blocks, processing may be slower 31 | than necessary and the recommendation is to write different windows in the source raster. 32 | """ 33 | sdf: pd.DataFrame = sdf.to_dataframe().drop(columns=["spatial_ref"]).reset_index() 34 | subset: pd.DataFrame = sdf.dropna() 35 | subset = subset[subset.value != nodata] 36 | subset = pd.pivot_table( 37 | subset, values=const.DEFAULT_NAME, index=["x", "y"], columns=["band"] 38 | ).reset_index() 39 | # Primary Maidenhead index 40 | maidenhead = [ 41 | mh.to_maiden(lat, lon, level) for lat, lon in zip(subset["y"], subset["x"]) 42 | ] # Vectorised 43 | # Secondary (parent) Maidenhead index, used later for partitioning 44 | maidenhead_parent = [mh[: parent_level * 2] for mh in maidenhead] 45 | subset = subset.drop(columns=["x", "y"]) 46 | subset[f"maidenhead_{level}"] = pd.Series(maidenhead, index=subset.index) 47 | subset[f"maidenhead_{parent_level}"] = pd.Series( 48 | maidenhead_parent, index=subset.index 49 | ) 50 | # Rename bands 51 | bands = sdf["band"].unique() 52 | band_names = dict(zip(bands, map(lambda i: band_labels[i - 1], bands))) 53 | for k, v in band_names.items(): 54 | if band_names[k] is None: 55 | band_names[k] = str(bands[k - 1]) 56 | else: 57 | band_names = band_names 58 | subset = subset.rename(columns=band_names) 59 | return pa.Table.from_pandas(subset) 60 | 61 | 62 | def _maidenhead_parent_groupby( 63 | df, precision: int, aggfunc: Union[str, Callable], decimals: int 64 | ): 65 | """ 66 | Function for aggregating the Maidenhead values per parent partition. Each partition will be run through with a 67 | pandas .groupby function. This step is to ensure there are no duplicate Maidenhead indices, which will certainly happen when indexing most raster datasets as Maidenhead has low precision. 68 | """ 69 | if decimals > 0: 70 | return df.groupby(f"maidenhead_{precision}").agg(aggfunc).round(decimals) 71 | else: 72 | return ( 73 | df.groupby(f"maidenhead_{precision}") 74 | .agg(aggfunc) 75 | .round(decimals) 76 | .astype("Int64") 77 | ) 78 | 79 | 80 | @click.command(context_settings={"show_default": True}) 81 | @click_log.simple_verbosity_option(common.LOGGER) 82 | @click.argument("raster_input", type=click.Path(), nargs=1) 83 | @click.argument("output_directory", type=click.Path(), nargs=1) 84 | @click.option( 85 | "-r", 86 | "--resolution", 87 | required=True, 88 | type=click.Choice( 89 | list(map(str, range(const.MIN_MAIDENHEAD, const.MAX_MAIDENHEAD + 1))) 90 | ), 91 | help="Maidenhead level to index", 92 | ) 93 | @click.option( 94 | "-pr", 95 | "--parent_res", 96 | required=False, 97 | type=click.Choice( 98 | list(map(str, range(const.MIN_MAIDENHEAD, const.MAX_MAIDENHEAD + 1))) 99 | ), 100 | help="Maidenhead 'parent' level to index and aggregate to. Defaults to level 1", 101 | ) 102 | @click.option( 103 | "-u", 104 | "--upscale", 105 | default=const.DEFAULTS["upscale"], 106 | type=int, 107 | help="Upscaling factor, used to upsample input data on the fly; useful when the raster resolution is lower than the target Maidenhead precision. Default (1) applies no upscaling. The resampling method controls interpolation.", 108 | ) 109 | @click.option( 110 | "-c", 111 | "--compression", 112 | default=const.DEFAULTS["compression"], 113 | type=click.Choice(["snappy", "gzip", "zstd"]), 114 | help="Name of the compression to use when writing to Parquet.", 115 | ) 116 | @click.option( 117 | "-t", 118 | "--threads", 119 | default=const.DEFAULTS["threads"], 120 | help="Number of threads to use when running in parallel. The default is determined based dynamically as the total number of available cores, minus one.", 121 | ) 122 | @click.option( 123 | "-a", 124 | "--aggfunc", 125 | default=const.DEFAULTS["aggfunc"], 126 | type=click.Choice( 127 | ["count", "mean", "sum", "prod", "std", "var", "min", "max", "median", "mode"] 128 | ), 129 | help="Numpy aggregate function to apply when aggregating cell values after DGGS indexing, in case of multiple pixels mapping to the same DGGS cell.", 130 | ) 131 | @click.option( 132 | "-d", 133 | "--decimals", 134 | default=const.DEFAULTS["decimals"], 135 | type=int, 136 | help="Number of decimal places to round values when aggregating. Use 0 for integer output.", 137 | ) 138 | @click.option("-o", "--overwrite", is_flag=True) 139 | @click.option( 140 | "--warp_mem_limit", 141 | default=const.DEFAULTS["warp_mem_limit"], 142 | type=int, 143 | help="Input raster may be warped to EPSG:4326 if it is not already in this CRS. This setting specifies the warp operation's memory limit in MB.", 144 | ) 145 | @click.option( 146 | "--resampling", 147 | default=const.DEFAULTS["resampling"], 148 | type=click.Choice(Resampling._member_names_), 149 | help="Input raster may be warped to EPSG:4326 if it is not already in this CRS. Or, if the upscale parameter is greater than 1, there is a need to resample. This setting specifies this resampling algorithm.", 150 | ) 151 | @click.option( 152 | "--tempdir", 153 | default=const.DEFAULTS["tempdir"], 154 | type=click.Path(), 155 | help="Temporary data is created during the execution of this program. This parameter allows you to control where this data will be written.", 156 | ) 157 | @click.version_option(version=__version__) 158 | def maidenhead( 159 | raster_input: Union[str, Path], 160 | output_directory: Union[str, Path], 161 | resolution: str, 162 | parent_res: str, 163 | upscale: int, 164 | compression: str, 165 | threads: int, 166 | aggfunc: str, 167 | decimals: int, 168 | overwrite: bool, 169 | warp_mem_limit: int, 170 | resampling: str, 171 | tempdir: Union[str, Path], 172 | ): 173 | """ 174 | Ingest a raster image and index it using the Maidenhead Locator System (also known as QTH Locator and IARU Locator). 175 | 176 | RASTER_INPUT is the path to input raster data; prepend with protocol like s3:// or hdfs:// for remote data. 177 | OUTPUT_DIRECTORY should be a directory, not a file, as it will be the write location for an Apache Parquet data store, with partitions equivalent to parent cells of target cells at a fixed offset. However, this can also be remote (use the appropriate prefix, e.g. s3://). 178 | """ 179 | tempfile.tempdir = tempdir if tempdir is not None else tempfile.tempdir 180 | 181 | common.check_resolutions(resolution, parent_res) 182 | 183 | raster_input = common.resolve_input_path(raster_input) 184 | warp_args = common.assemble_warp_args(resampling, warp_mem_limit) 185 | aggfunc = common.create_aggfunc(aggfunc) 186 | kwargs = common.assemble_kwargs( 187 | upscale, 188 | compression, 189 | threads, 190 | aggfunc, 191 | decimals, 192 | warp_mem_limit, 193 | resampling, 194 | overwrite, 195 | ) 196 | 197 | common.initial_index( 198 | "maidenhead", 199 | _maidenheadfunc, 200 | _maidenhead_parent_groupby, 201 | raster_input, 202 | output_directory, 203 | int(resolution), 204 | parent_res, 205 | warp_args, 206 | **kwargs, 207 | ) 208 | -------------------------------------------------------------------------------- /raster2dggs/rHP.py: -------------------------------------------------------------------------------- 1 | from numbers import Number 2 | import numpy as np 3 | from pathlib import Path 4 | import tempfile 5 | from typing import Callable, Tuple, Union 6 | 7 | import click 8 | import click_log 9 | import rhppandas # Necessary import despite lack of explicit use 10 | import pandas as pd 11 | import pyarrow as pa 12 | from rasterio.enums import Resampling 13 | import xarray as xr 14 | 15 | import raster2dggs.constants as const 16 | import raster2dggs.common as common 17 | from raster2dggs import __version__ 18 | 19 | PAD_WIDTH = common.zero_padding("h3") 20 | 21 | 22 | def _rhpfunc( 23 | sdf: xr.DataArray, 24 | resolution: int, 25 | parent_res: int, 26 | nodata: Number = np.nan, 27 | band_labels: Tuple[str] = None, 28 | ) -> pa.Table: 29 | """ 30 | Index a raster window to rHEALPix. 31 | Subsequent steps are necessary to resolve issues at the boundaries of windows. 32 | If windows are very small, or in strips rather than blocks, processing may be slower 33 | than necessary and the recommendation is to write different windows in the source raster. 34 | """ 35 | sdf: pd.DataFrame = sdf.to_dataframe().drop(columns=["spatial_ref"]).reset_index() 36 | subset: pd.DataFrame = sdf.dropna() 37 | subset = subset[subset.value != nodata] 38 | subset = pd.pivot_table( 39 | subset, values=const.DEFAULT_NAME, index=["x", "y"], columns=["band"] 40 | ).reset_index() 41 | # Primary rHEALPix index 42 | rhpindex = subset.rhp.geo_to_rhp(resolution, lat_col="y", lng_col="x").drop( 43 | columns=["x", "y"] 44 | ) 45 | # Secondary (parent) rHEALPix index, used later for partitioning 46 | rhpindex = rhpindex.rhp.rhp_to_parent(parent_res).reset_index() 47 | # Renaming columns to actual band labels 48 | bands = sdf["band"].unique() 49 | band_names = dict(zip(bands, map(lambda i: band_labels[i - 1], bands))) 50 | for k, v in band_names.items(): 51 | if band_names[k] is None: 52 | band_names[k] = str(bands[k - 1]) 53 | else: 54 | band_names = band_names 55 | rhpindex = rhpindex.rename(columns=band_names) 56 | return pa.Table.from_pandas(rhpindex) 57 | 58 | 59 | def _rhp_parent_groupby( 60 | df, resolution: int, aggfunc: Union[str, Callable], decimals: int 61 | ): 62 | """ 63 | Function for aggregating the h3 resolution values per parent partition. Each partition will be run through with a 64 | pandas .groupby function. This step is to ensure there are no duplicate rHEALPix values, which will happen when indexing a 65 | high resolution raster at a coarser resolution. 66 | """ 67 | if decimals > 0: 68 | return ( 69 | df.groupby(f"rhp_{resolution:0{PAD_WIDTH}d}").agg(aggfunc).round(decimals) 70 | ) 71 | else: 72 | return ( 73 | df.groupby(f"rhp_{resolution:0{PAD_WIDTH}d}") 74 | .agg(aggfunc) 75 | .round(decimals) 76 | .astype("Int64") 77 | ) 78 | 79 | 80 | @click.command(context_settings={"show_default": True}) 81 | @click_log.simple_verbosity_option(common.LOGGER) 82 | @click.argument("raster_input", type=click.Path(), nargs=1) 83 | @click.argument("output_directory", type=click.Path(), nargs=1) 84 | @click.option( 85 | "-r", 86 | "--resolution", 87 | required=True, 88 | type=click.Choice(list(map(str, range(const.MIN_RHP, const.MAX_RHP + 1)))), 89 | help="rHEALPix resolution to index", 90 | ) 91 | @click.option( 92 | "-pr", 93 | "--parent_res", 94 | required=False, 95 | type=click.Choice(list(map(str, range(const.MIN_RHP, const.MAX_RHP + 1)))), 96 | help="rHEALPix Parent resolution to index and aggregate to. Defaults to resolution - 6", 97 | ) 98 | @click.option( 99 | "-u", 100 | "--upscale", 101 | default=const.DEFAULTS["upscale"], 102 | type=int, 103 | help="Upscaling factor, used to upsample input data on the fly; useful when the raster resolution is lower than the target DGGS resolution. Default (1) applies no upscaling. The resampling method controls interpolation.", 104 | ) 105 | @click.option( 106 | "-c", 107 | "--compression", 108 | default=const.DEFAULTS["compression"], 109 | type=click.Choice(["snappy", "gzip", "zstd"]), 110 | help="Name of the compression to use when writing to Parquet.", 111 | ) 112 | @click.option( 113 | "-t", 114 | "--threads", 115 | default=const.DEFAULTS["threads"], 116 | help="Number of threads to use when running in parallel. The default is determined based dynamically as the total number of available cores, minus one.", 117 | ) 118 | @click.option( 119 | "-a", 120 | "--aggfunc", 121 | default=const.DEFAULTS["aggfunc"], 122 | type=click.Choice( 123 | ["count", "mean", "sum", "prod", "std", "var", "min", "max", "median", "mode"] 124 | ), 125 | help="Numpy aggregate function to apply when aggregating cell values after DGGS indexing, in case of multiple pixels mapping to the same DGGS cell.", 126 | ) 127 | @click.option( 128 | "-d", 129 | "--decimals", 130 | default=const.DEFAULTS["decimals"], 131 | type=int, 132 | help="Number of decimal places to round values when aggregating. Use 0 for integer output.", 133 | ) 134 | @click.option("-o", "--overwrite", is_flag=True) 135 | @click.option( 136 | "--warp_mem_limit", 137 | default=const.DEFAULTS["warp_mem_limit"], 138 | type=int, 139 | help="Input raster may be warped to EPSG:4326 if it is not already in this CRS. This setting specifies the warp operation's memory limit in MB.", 140 | ) 141 | @click.option( 142 | "--resampling", 143 | default=const.DEFAULTS["resampling"], 144 | type=click.Choice(Resampling._member_names_), 145 | help="Input raster may be warped to EPSG:4326 if it is not already in this CRS. Or, if the upscale parameter is greater than 1, there is a need to resample. This setting specifies this resampling algorithm.", 146 | ) 147 | @click.option( 148 | "--tempdir", 149 | default=const.DEFAULTS["tempdir"], 150 | type=click.Path(), 151 | help="Temporary data is created during the execution of this program. This parameter allows you to control where this data will be written.", 152 | ) 153 | @click.version_option(version=__version__) 154 | def rhp( 155 | raster_input: Union[str, Path], 156 | output_directory: Union[str, Path], 157 | resolution: str, 158 | parent_res: str, 159 | upscale: int, 160 | compression: str, 161 | threads: int, 162 | aggfunc: str, 163 | decimals: int, 164 | overwrite: bool, 165 | warp_mem_limit: int, 166 | resampling: str, 167 | tempdir: Union[str, Path], 168 | ): 169 | """ 170 | Ingest a raster image and index it to the rHEALPix DGGS. 171 | 172 | RASTER_INPUT is the path to input raster data; prepend with protocol like s3:// or hdfs:// for remote data. 173 | OUTPUT_DIRECTORY should be a directory, not a file, as it will be the write location for an Apache Parquet data store, with partitions equivalent to parent cells of target cells at a fixed offset. However, this can also be remote (use the appropriate prefix, e.g. s3://). 174 | """ 175 | tempfile.tempdir = tempdir if tempdir is not None else tempfile.tempdir 176 | 177 | common.check_resolutions(resolution, parent_res) 178 | 179 | raster_input = common.resolve_input_path(raster_input) 180 | warp_args = common.assemble_warp_args(resampling, warp_mem_limit) 181 | aggfunc = common.create_aggfunc(aggfunc) 182 | kwargs = common.assemble_kwargs( 183 | upscale, 184 | compression, 185 | threads, 186 | aggfunc, 187 | decimals, 188 | warp_mem_limit, 189 | resampling, 190 | overwrite, 191 | ) 192 | 193 | common.initial_index( 194 | "rhp", 195 | _rhpfunc, 196 | _rhp_parent_groupby, 197 | raster_input, 198 | output_directory, 199 | int(resolution), 200 | parent_res, 201 | warp_args, 202 | **kwargs, 203 | ) 204 | -------------------------------------------------------------------------------- /raster2dggs/s2.py: -------------------------------------------------------------------------------- 1 | from numbers import Number 2 | import numpy as np 3 | from pathlib import Path 4 | import tempfile 5 | from typing import Callable, Tuple, Union 6 | 7 | import click 8 | import click_log 9 | import pandas as pd 10 | import pyarrow as pa 11 | from rasterio.enums import Resampling 12 | from s2sphere import LatLng, CellId 13 | import xarray as xr 14 | 15 | import raster2dggs.constants as const 16 | import raster2dggs.common as common 17 | from raster2dggs import __version__ 18 | 19 | PAD_WIDTH = common.zero_padding("s2") 20 | 21 | 22 | def _s2func( 23 | sdf: xr.DataArray, 24 | resolution: int, 25 | parent_res: int, 26 | nodata: Number = np.nan, 27 | band_labels: Tuple[str] = None, 28 | ) -> pa.Table: 29 | """ 30 | Index a raster window to S2. 31 | Subsequent steps are necessary to resolve issues at the boundaries of windows. 32 | If windows are very small, or in strips rather than blocks, processing may be slower 33 | than necessary and the recommendation is to write different windows in the source raster. 34 | """ 35 | sdf: pd.DataFrame = sdf.to_dataframe().drop(columns=["spatial_ref"]).reset_index() 36 | subset: pd.DataFrame = sdf.dropna() 37 | subset = subset[subset.value != nodata] 38 | subset = pd.pivot_table( 39 | subset, values=const.DEFAULT_NAME, index=["x", "y"], columns=["band"] 40 | ).reset_index() 41 | # S2 index 42 | cells = [ 43 | CellId.from_lat_lng(LatLng.from_degrees(lat, lon)) 44 | for lat, lon in zip(subset["y"], subset["x"]) 45 | ] 46 | s2 = [cell.parent(resolution).to_token() for cell in cells] 47 | s2_parent = [cell.parent(parent_res).to_token() for cell in cells] 48 | subset = subset.drop(columns=["x", "y"]) 49 | subset[f"s2_{resolution:0{PAD_WIDTH}d}"] = pd.Series(s2, index=subset.index) 50 | subset[f"s2_{parent_res:0{PAD_WIDTH}d}"] = pd.Series(s2_parent, index=subset.index) 51 | # Renaming columns to actual band labels 52 | bands = sdf["band"].unique() 53 | band_names = dict(zip(bands, map(lambda i: band_labels[i - 1], bands))) 54 | for k, v in band_names.items(): 55 | if band_names[k] is None: 56 | band_names[k] = str(bands[k - 1]) 57 | else: 58 | band_names = band_names 59 | subset = subset.rename(columns=band_names) 60 | return pa.Table.from_pandas(subset) 61 | 62 | 63 | def _s2_parent_groupby( 64 | df, resolution: int, aggfunc: Union[str, Callable], decimals: int 65 | ): 66 | """ 67 | Function for aggregating the S2 resolution values per parent partition. Each partition will be run through with a 68 | pandas .groupby function. This step is to ensure there are no duplicate S2 values, which will happen when indexing a 69 | high resolution raster at a coarser S2 resolution. 70 | """ 71 | if decimals > 0: 72 | return df.groupby(f"s2_{resolution:0{PAD_WIDTH}d}").agg(aggfunc).round(decimals) 73 | else: 74 | return ( 75 | df.groupby(f"s2_{resolution:0{PAD_WIDTH}d}") 76 | .agg(aggfunc) 77 | .round(decimals) 78 | .astype("Int64") 79 | ) 80 | 81 | 82 | @click.command(context_settings={"show_default": True}) 83 | @click_log.simple_verbosity_option(common.LOGGER) 84 | @click.argument("raster_input", type=click.Path(), nargs=1) 85 | @click.argument("output_directory", type=click.Path(), nargs=1) 86 | @click.option( 87 | "-r", 88 | "--resolution", 89 | required=True, 90 | type=click.Choice(list(map(str, range(const.MIN_S2, const.MAX_S2 + 1)))), 91 | help="S2 resolution to index", 92 | ) 93 | @click.option( 94 | "-pr", 95 | "--parent_res", 96 | required=False, 97 | type=click.Choice(list(map(str, range(const.MIN_S2, const.MAX_S2 + 1)))), 98 | help="S2 parent resolution to index and aggregate to. Defaults to resolution - 6", 99 | ) 100 | @click.option( 101 | "-u", 102 | "--upscale", 103 | default=const.DEFAULTS["upscale"], 104 | type=int, 105 | help="Upscaling factor, used to upsample input data on the fly; useful when the raster resolution is lower than the target DGGS resolution. Default (1) applies no upscaling. The resampling method controls interpolation.", 106 | ) 107 | @click.option( 108 | "-c", 109 | "--compression", 110 | default=const.DEFAULTS["compression"], 111 | type=click.Choice(["snappy", "gzip", "zstd"]), 112 | help="Name of the compression to use when writing to Parquet.", 113 | ) 114 | @click.option( 115 | "-t", 116 | "--threads", 117 | default=const.DEFAULTS["threads"], 118 | help="Number of threads to use when running in parallel. The default is determined based dynamically as the total number of available cores, minus one.", 119 | ) 120 | @click.option( 121 | "-a", 122 | "--aggfunc", 123 | default=const.DEFAULTS["aggfunc"], 124 | type=click.Choice( 125 | ["count", "mean", "sum", "prod", "std", "var", "min", "max", "median", "mode"] 126 | ), 127 | help="Numpy aggregate function to apply when aggregating cell values after DGGS indexing, in case of multiple pixels mapping to the same DGGS cell.", 128 | ) 129 | @click.option( 130 | "-d", 131 | "--decimals", 132 | default=const.DEFAULTS["decimals"], 133 | type=int, 134 | help="Number of decimal places to round values when aggregating. Use 0 for integer output.", 135 | ) 136 | @click.option("-o", "--overwrite", is_flag=True) 137 | @click.option( 138 | "--warp_mem_limit", 139 | default=const.DEFAULTS["warp_mem_limit"], 140 | type=int, 141 | help="Input raster may be warped to EPSG:4326 if it is not already in this CRS. This setting specifies the warp operation's memory limit in MB.", 142 | ) 143 | @click.option( 144 | "--resampling", 145 | default=const.DEFAULTS["resampling"], 146 | type=click.Choice(Resampling._member_names_), 147 | help="Input raster may be warped to EPSG:4326 if it is not already in this CRS. Or, if the upscale parameter is greater than 1, there is a need to resample. This setting specifies this resampling algorithm.", 148 | ) 149 | @click.option( 150 | "--tempdir", 151 | default=const.DEFAULTS["tempdir"], 152 | type=click.Path(), 153 | help="Temporary data is created during the execution of this program. This parameter allows you to control where this data will be written.", 154 | ) 155 | @click.version_option(version=__version__) 156 | def s2( 157 | raster_input: Union[str, Path], 158 | output_directory: Union[str, Path], 159 | resolution: str, 160 | parent_res: str, 161 | upscale: int, 162 | compression: str, 163 | threads: int, 164 | aggfunc: str, 165 | decimals: int, 166 | overwrite: bool, 167 | warp_mem_limit: int, 168 | resampling: str, 169 | tempdir: Union[str, Path], 170 | ): 171 | """ 172 | Ingest a raster image and index it to the S2 DGGS. 173 | 174 | RASTER_INPUT is the path to input raster data; prepend with protocol like s3:// or hdfs:// for remote data. 175 | OUTPUT_DIRECTORY should be a directory, not a file, as it will be the write location for an Apache Parquet data store, with partitions equivalent to parent cells of target cells at a fixed offset. However, this can also be remote (use the appropriate prefix, e.g. s3://). 176 | """ 177 | tempfile.tempdir = tempdir if tempdir is not None else tempfile.tempdir 178 | 179 | common.check_resolutions(resolution, parent_res) 180 | 181 | raster_input = common.resolve_input_path(raster_input) 182 | warp_args = common.assemble_warp_args(resampling, warp_mem_limit) 183 | aggfunc = common.create_aggfunc(aggfunc) 184 | kwargs = common.assemble_kwargs( 185 | upscale, 186 | compression, 187 | threads, 188 | aggfunc, 189 | decimals, 190 | warp_mem_limit, 191 | resampling, 192 | overwrite, 193 | ) 194 | 195 | common.initial_index( 196 | "s2", 197 | _s2func, 198 | _s2_parent_groupby, 199 | raster_input, 200 | output_directory, 201 | int(resolution), 202 | parent_res, 203 | warp_args, 204 | **kwargs, 205 | ) 206 | --------------------------------------------------------------------------------