├── LICENSE ├── README.md ├── __init__.py ├── bst.py ├── centroid.py ├── intersection.py ├── lcc.py ├── line_seg_eventqueue.py ├── line_seg_intersection.py ├── linesegment.py ├── multipolygon_util.py ├── neville.py ├── overlay.py ├── paths.py ├── plot_worldmap.py ├── point.py ├── point2line.py ├── point_in_polygon.py ├── point_in_polygon_winding.py ├── polygon_error.py ├── quick_convex_hull.py ├── shapex.py ├── sideplr.py ├── test_line_seg_intersection.py ├── test_overlay.py ├── test_projection.py ├── test_projection2.py ├── test_projection_other.py ├── transform1.py ├── transform2.py ├── transforms.py └── worldmap.py /LICENSE: -------------------------------------------------------------------------------- 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 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # :sunglasses: Code for geometric algorithms 2 | 3 | This is no formal installation for this package (or any packages in `gisalgs`). However, installing the code is not complicated. It is important to organize everything in a directory and each package such as `geom` is a subdirectory. Now suppose we use the directory at the root called `/lib` to store everything and we create a subfolder called `gisalgs` there. Under the `/lib/gisalgs` directory, create a subdirectory called `geom` and save all the files in this repository in geom. It will be essential to have the `__init__.py` in geom (this is just an empty file with the specific file name). Lastly, make sure to copy `__init__.py` to the parent directory (in this case, `/lib/gisalgs`). 4 | 5 | :zap: The following is an example of using modules in this repository: 6 | 7 | ```python 8 | import sys 9 | sys.path.append('/lib/gisalgs') 10 | 11 | from geom.point import * 12 | 13 | p, p1, p2 = Point(10,0), Point(0,100), Point(0,1) 14 | print(p.distance(p1)) 15 | print(p1) 16 | ``` 17 | -------------------------------------------------------------------------------- /__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gisalgs/geom/e18970aaa314987ae6e2350a9531263c69419576/__init__.py -------------------------------------------------------------------------------- /bst.py: -------------------------------------------------------------------------------- 1 | """ 2 | Binary search trees 3 | 4 | Contact: 5 | Ningchuan Xiao 6 | The Ohio State University 7 | Columbus, OH 8 | """ 9 | 10 | __author__ = "Ningchuan Xiao " 11 | 12 | class node(): 13 | def __init__(self, data, left, right): 14 | self.data = data 15 | self.left = left 16 | self.right = right 17 | def __repr__(self): 18 | return str(self.data) 19 | 20 | def search_bt(t, d, is_find_only=True): 21 | """ 22 | Input 23 | t: a node of a binary tree 24 | d: target data to be found in the tree 25 | is_find_only: True/False, specifying type of output 26 | 27 | Output 28 | the node that contans d or None if is_find_only is True, otherwise 29 | the node that should be the parent node of d 30 | """ 31 | if t is None: 32 | return 33 | if d < t.data: 34 | next = t.left 35 | else: 36 | next = t.right 37 | if t.data == d: 38 | if is_find_only: 39 | return t 40 | else: 41 | return 42 | if is_find_only==False and next is None: 43 | return t 44 | return search_bt(next, d, is_find_only) 45 | 46 | def insert(t, d): 47 | n = search_bt(t, d, False) 48 | if n is None: 49 | return 50 | n0 = node(d, left=None, right=None) 51 | if d < n.data: 52 | n.left = n0 53 | else: 54 | n.right = n0 55 | 56 | def bt(data): 57 | root = node(data=data[0], left=None, right=None) 58 | for d in data[1:]: 59 | insert(root, d) 60 | return root 61 | 62 | def search_bt_loop(t, d, is_find_only=True): 63 | """ 64 | similar to search_bt, but use a while loop instead of recursive 65 | """ 66 | while True: 67 | if t is None: 68 | return 69 | if t.data == d: 70 | if is_find_only: 71 | return t 72 | else: 73 | return 74 | if d < t.data: 75 | next = t.left 76 | else: 77 | next = t.right 78 | if not is_find_only and next is None: 79 | return t 80 | t = next 81 | 82 | def insert_loop(t, d): 83 | n = search_bt_loop(t, d, False) 84 | if n is None: 85 | return 86 | n0 = node(d, left=None, right=None) 87 | if d < n.data: 88 | n.left = n0 89 | else: 90 | n.right = n0 91 | 92 | def bt_loop(data): 93 | root = node(data=data[0], left=None, right=None) 94 | for d in data[1:]: 95 | insert_loop(root, d) 96 | return root 97 | 98 | def bt_print(t): 99 | if t.left: 100 | bt_print(t.left) 101 | print(t) 102 | if t.right: 103 | bt_print(t.right) 104 | 105 | def tree_print(t): 106 | """ 107 | This is adopted from the MIT OpenCourseWare at 108 | https://ocw.mit.edu/courses/6-006-introduction-to-algorithms-fall-2011/7f7ba1c1c85b1ec4bd58965bfe791489_bst.py 109 | 110 | The old link does not work: 111 | http://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-006-introduction-to-algorithms-fall-2011/readings/binary-search-trees/bst.py 112 | 113 | Now supports Python 3 114 | """ 115 | def tree_print_helper(t): 116 | if t is None: 117 | return [], 0, 0 118 | # label = str(t.key) 119 | label = str(t) 120 | leftstr, leftpos, leftwidth = tree_print_helper(t.left) 121 | rightstr, rightpos, rightwidth = tree_print_helper(t.right) 122 | middle = max(rightpos+leftwidth - leftpos+1, len(label), 2) # length 123 | pos = leftpos + middle // 2 # pos of current node 124 | width = leftpos + middle + rightwidth - rightpos 125 | while len(leftstr) 0: 65 | return False 66 | # testing: s1 endpoints on the same side of s2 67 | lsign = sideplr(s1.lp0, s2.lp0, s2.rp) 68 | rsign = sideplr(s1.rp, s2.lp0, s2.rp) 69 | if lsign*rsign > 0: 70 | return False 71 | return True 72 | 73 | if __name__ == "__main__": 74 | p1 = Point(1, 2) 75 | p2 = Point(3, 4) 76 | p3 = Point(2, 1) 77 | p4 = Point(1, 4) 78 | s1 = Segment(0, p1, p2) 79 | s2 = Segment(1, p3, p4) 80 | s3 = Segment(2, p1, p2) 81 | if test_intersect(s1, s2): 82 | print(getIntersectionPoint(s1, s2)) 83 | print(get_intersection_point(s1, s2)) 84 | print(s1==s2) 85 | print(s1==s3) 86 | -------------------------------------------------------------------------------- /lcc.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Implementation of Lambert Conformal Conic project and its use for State Plane Ohio South. 3 | 4 | Change history: 5 | 6 | November 6, 2024 - first release 7 | 8 | # example from Snyder p 295 9 | # LCC on sphere 10 | # Result should have: 0.2966785, 0.2462112 11 | R = 1 12 | lat1 = 33 13 | lat2 = 45 14 | lat0 = 23 15 | lon0 = -96 16 | lat = 35 17 | lon = -75 18 | easting = 0 19 | northing = 0 20 | 21 | lambert_conformal_conic(lon, lat, lon0, lat0, lat1, lat2, easting, northing, R) 22 | # (0.29667845994250686, 0.24621122933162676) 23 | 24 | # from pyproj - but on ellipsoid 25 | # >>> t.transform(40, -83) 26 | # (1828420.1096133376, 728840.80764274) 27 | 28 | spcs_ohio_south(-83, 40) 29 | # (1828770.2861412086, 730018.3205949441) 30 | 31 | # origin 32 | spcs_ohio_south(-82.5, 38) 33 | # (1968500.0, 0.0) 34 | 35 | Contact: 36 | Ningchuan Xiao 37 | The Ohio State University 38 | Columbus, OH 39 | ''' 40 | 41 | __author__ = 'Ningchuan Xiao ' 42 | 43 | 44 | from math import cos, sin, tan, radians, log, pi, e 45 | 46 | def sec(x): 47 | '''Secant Function''' 48 | return 1/cos(x) 49 | 50 | def cot(x): 51 | ''' 52 | Assume lat in radians 53 | ''' 54 | return 1/tan(x) 55 | 56 | 57 | def lambert_conformal_conic(lon, lat, lon0, lat0, lat1, lat2, easting, northing, R): 58 | ''' 59 | Lambert conformal conic 60 | formula from snyder 1987 (p 104-107) 61 | ''' 62 | lon, lat, lon0, lat0, lat1, lat2 = map(radians, [lon, lat, lon0, lat0, lat1, lat2]) 63 | 64 | n = log(cos(lat1)/cos(lat2)) / log(tan(pi/4 + lat2/2) / tan(pi/4 + lat1/2)) 65 | F = cos(lat1) * tan(pi/4 + lat1/2)**n / n 66 | rho = R * F / (tan(pi/4 + lat/2)**n) 67 | rho0 = R * F / tan(pi/4 + lat0/2)**n 68 | theta = n * (lon-lon0) 69 | 70 | x = rho * sin(theta) 71 | y = rho0 - rho * cos(theta) 72 | 73 | x += easting 74 | y += northing 75 | # msg = f'n={n} \nF={F} \nrho={rho}\nrho0={rho0}' 76 | # print(msg) 77 | return x, y 78 | 79 | 80 | def lambert_conformal_conic_wiki(lon, lat, lon0, lat0, lat1, lat2, easting, northing, R): 81 | ''' 82 | Lambert conformal conic 83 | formula from wikipedia 84 | ''' 85 | lon, lat, lon0, lat0, lat1, lat2 = map(radians, [lon, lat, lon0, lat0, lat1, lat2]) 86 | n = log(cos(lat1) * sec(lat2)) / log( tan(pi/4 + lat2/2) * cot(pi/4 + lat1/2)) 87 | F = cos(lat1) * tan(pi/4+lat1/2)**n / n 88 | rho = R * F * cot(pi/4+lat/2)**n 89 | rho0 = R * F * cot(pi/4+lat0/2)**n 90 | x = rho * sin(n*(lon-lon0)) 91 | y = rho0 - rho*cos(n*(lon-lon0)) 92 | x += easting 93 | y += northing 94 | return x, y 95 | 96 | def spcs_ohio_south(lon, lat): 97 | ''' 98 | State Plane Coordinate System - Ohio South 99 | Unit: feet 100 | ''' 101 | lon0 = -82.5 102 | lat0 = 38 103 | lat1 = 40.0333333333333 104 | lat2 = 38.7333333333333 105 | easting = 1968500 106 | northing = 0 107 | # earth radius as used in proj4 https://proj.org/en/9.4/usage/ellipsoids.html 108 | # converted to feet, as used in state plane 109 | R = 6370997.0 * 3.28084 110 | 111 | return lambert_conformal_conic(lon, lat, lon0, lat0, lat1, lat2, easting, northing, R) 112 | 113 | -------------------------------------------------------------------------------- /line_seg_eventqueue.py: -------------------------------------------------------------------------------- 1 | """ 2 | Python classes for Event and EventQueue for the Bentley-Ottmann algorithm. 3 | 4 | Contact: 5 | Ningchuan Xiao 6 | The Ohio State University 7 | Columbus, OH 8 | """ 9 | 10 | __author__ = "Ningchuan Xiao " 11 | 12 | from .point import * 13 | 14 | class Event: 15 | """ 16 | An event in the sweep line algorithm. Each Event object 17 | stores the event point and the line segments associated with the 18 | point. 19 | """ 20 | def __init__(self, p=None): 21 | self.edges = [] # line segments associated with the event 22 | self.p = p # event point 23 | def __repr__(self): 24 | return "{0}{1}".format(self.p,self.edges) 25 | 26 | class EventQueue: 27 | """ 28 | An event queue in the sweep line algorithm. 29 | """ 30 | def __init__(self, lset): 31 | """ 32 | Constructor of EventQueue. 33 | Input 34 | lset: a list of Segment objects. The left point of 35 | each segment is used to create an event 36 | Output 37 | A sorted list of events as a member of this class 38 | """ 39 | if lset == None: 40 | return 41 | self.events = [] 42 | for l in lset: 43 | e0 = Event(l.lp) 44 | inx = self.find(e0) 45 | if inx == -1: 46 | e0.edges.append(l) 47 | self.events.append(e0) 48 | else: 49 | self.events[inx].edges.append(l) 50 | e1 = Event(l.rp) 51 | if self.find(e1) == -1: 52 | self.events.append(e1) 53 | self.events.sort(key=lambda e: e.p) 54 | 55 | def add(self, e): 56 | """ 57 | Adds event e to the queue, updates the list of events 58 | """ 59 | self.events.append(e) 60 | self.events.sort(key=lambda e: e.p) 61 | 62 | def find(self, t): 63 | """ 64 | Returns the index of event t if it is in the queue. 65 | Otherwise, returns -1. 66 | """ 67 | if isinstance(t, Event): 68 | p = t.p 69 | elif isinstance(t, Point): 70 | p = t 71 | else: return -1 72 | for e in self.events: 73 | if p == e.p: 74 | return self.events.index(e) 75 | return -1 76 | 77 | def is_empty(self): 78 | return len(self.events) == 0 79 | -------------------------------------------------------------------------------- /line_seg_intersection.py: -------------------------------------------------------------------------------- 1 | """ 2 | Line segment intersections using the Bentley-Ottmann Algorithm. 3 | 4 | Contact: 5 | Ningchuan Xiao 6 | The Ohio State University 7 | Columbus, OH 8 | """ 9 | 10 | __author__ = "Ningchuan Xiao " 11 | 12 | import sys 13 | sys.path.append("..") 14 | from contrib.bintrees import AVLTree 15 | 16 | from .point import * 17 | from .intersection import * 18 | from .line_seg_eventqueue import * 19 | 20 | def get_edges(t, p): 21 | """ 22 | Gets the edges (segments) that contain point p as their right 23 | endpoint or in the interior 24 | """ 25 | lr = [] 26 | lc = [] 27 | for s in AVLTree(t): 28 | if s.rp == p: 29 | lr.append(s) 30 | elif s.lp == p and s.status == INTERIOR: 31 | lc.append(s) 32 | elif sideplr(p, s.lp, s.rp) == 0: 33 | lc.append(s) 34 | return lr, lc 35 | 36 | def get_lr(T, s): 37 | """ 38 | Returns the left and right neighbors (branches) of s in T. 39 | """ 40 | try: 41 | sl = T.floor_key(s) 42 | except KeyError: 43 | sl = None 44 | try: 45 | sr = T.ceiling_key(s) 46 | except KeyError: 47 | sr = None 48 | return sl, sr 49 | 50 | def get_lrmost(T, segs): 51 | """ 52 | Finds the leftmost and rightmost segments of segs in T 53 | """ 54 | l = [] 55 | for s in list(T): 56 | if s in segs: 57 | l.append(s) 58 | if len(l) < 1: 59 | return None, None 60 | return l[0], l[-1] 61 | 62 | def find_new_event(s1, s2, p, q): 63 | """ 64 | Tests if s1 intersects s2 at a point that is not in the event queue. 65 | When a new intersection point is found, a new event will be created 66 | and added to the event queue. 67 | 68 | Input: 69 | s1: line segment 70 | s2: line segment 71 | p: the point of the current event 72 | q: event queue 73 | 74 | Output: 75 | True if a new point is found, False otherwise 76 | 77 | Change: the content in the queue (q) may change. 78 | """ 79 | ip = intersectx(s1, s2) 80 | if ip is None: 81 | return False 82 | if q.find(ip) is not -1: 83 | return False 84 | if ip.x>p.x or (ip.x==p.x and ip.y >= p.y): 85 | e0 = Event() 86 | e0.p = ip 87 | e0.edges = [s1, s2] 88 | q.add(e0) 89 | return True 90 | 91 | def intersectx(s1, s2): 92 | """ 93 | Tests intersection of 2 input segments. If intersection is possible, 94 | the actual intersection point will be calculated and returned. 95 | """ 96 | if not test_intersect(s1, s2): 97 | return None 98 | p = getIntersectionPoint(s1, s2) # an intersection 99 | return p 100 | 101 | def intersections(psegs): 102 | """ 103 | Implementation of the Bentley-Ottmann algorithm. 104 | 105 | Input 106 | psegs: a list of segments 107 | 108 | Output 109 | intpoints: a list of intersection points 110 | """ 111 | eq = EventQueue(psegs) 112 | intpoints = [] 113 | T = AVLTree() 114 | L=[] 115 | while not eq.is_empty(): # for all events 116 | e = eq.events.pop(0) # remove the event 117 | p = e.p # get event point 118 | L = e.edges # segments with p as left end 119 | R,C = get_edges(T, p) # p: right (R) and interior (C) 120 | if len(L+R+C) > 1: # Intersection at p among L+R+C 121 | for s in L+R+C: 122 | if not s.contains(p): # if p is interior 123 | s.lp = p # change lp and 124 | s.status = INTERIOR # status 125 | intpoints.append(p) 126 | R,C = get_edges(T, p) 127 | for s in R+C: 128 | T.discard(s) 129 | for s in L+C: 130 | T.insert(s, str(s)) 131 | if len(L+C) == 0: 132 | s = R[0] 133 | if s is not None: 134 | sl, sr = get_lr(T, s) 135 | find_new_event(sl, sr, p, eq) 136 | else: 137 | sp, spp = get_lrmost(T, L+C) 138 | try: 139 | sl = T.prev_key(sp) 140 | except KeyError: # only on last key 141 | sl = None 142 | try: 143 | sr = T.succ_key(spp) 144 | except KeyError: # only on last key 145 | sr = None 146 | find_new_event(sl, sp, p, eq) 147 | find_new_event(sr, spp, p, eq) 148 | return intpoints 149 | -------------------------------------------------------------------------------- /linesegment.py: -------------------------------------------------------------------------------- 1 | from .point import * 2 | from .sideplr import * 3 | 4 | ## Two statuses of the left endpoint 5 | ENDPOINT = 0 ## original left endpoint 6 | INTERIOR = 1 ## interior in the segment 7 | 8 | class Segment: 9 | """ 10 | A class for line segments. 11 | """ 12 | def __init__(self, e, p0, p1, c=None): 13 | """ 14 | Constructor of Segment class. 15 | Input 16 | e: segment ID, an integer 17 | p0, p1: endpoints of segment, Point objects 18 | """ 19 | if p0>=p1: 20 | p0,p1 = p1,p0 # p0 is always left 21 | self.edge = e # ID, in all edges 22 | self.lp = p0 # left point 23 | self.lp0 = p0 # original left point 24 | self.rp = p1 # right point 25 | self.status = ENDPOINT # status of segment 26 | self.c = c # c: feature ID 27 | def __eq__(self, other): 28 | if isinstance(other, Segment): 29 | return (self.lp==other.lp and self.rp==other.rp)\ 30 | or (self.lp==other.rp and self.rp==other.lp) 31 | return NotImplemented 32 | def __ne__(self, other): 33 | result = self.__eq__(other) 34 | if result is NotImplemented: 35 | return result 36 | return not result 37 | def __lt__(self, other): 38 | if isinstance(other, Segment): 39 | if self.lp and other.lp: 40 | lr = sideplr(self.lp, other.lp, other.rp) 41 | if lr == 0: 42 | lrr = sideplr(self.rp, other.lp, other.rp) 43 | if other.lp.x < other.rp.x: 44 | return lrr > 0 45 | else: 46 | return lrr < 0 47 | else: 48 | if other.lp.x > other.rp.x: 49 | return lr < 0 50 | else: 51 | return lr > 0 52 | return NotImplemented 53 | def __gt__(self, other): 54 | result = self.__lt__(other) 55 | if result is NotImplemented: 56 | return result 57 | return not result 58 | def __repr__(self): 59 | return "{0}".format(self.edge) 60 | def contains(self, p): 61 | """ 62 | Returns none zero if segment has p as an endpoint 63 | """ 64 | if self.lp == p: 65 | return -1 66 | elif self.rp == p: 67 | return 1 68 | else: 69 | return 0 70 | -------------------------------------------------------------------------------- /multipolygon_util.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Functions that are convenient to handle geojson polygon or multipolygons. 3 | 4 | Change history: 5 | 6 | November 13, 2024 - first release 7 | 8 | Contact: 9 | Ningchuan Xiao 10 | The Ohio State University 11 | Columbus, OH 12 | ''' 13 | 14 | __author__ = 'Ningchuan Xiao ' 15 | 16 | import sys 17 | sys.path.append('..') 18 | 19 | from geom.point import * 20 | from geom.point_in_polygon import * 21 | 22 | def get_bounds(f): 23 | ''' 24 | Get the bounds of a multiplygon 25 | 26 | INPUT 27 | multipoly - a polygon or multipolygon geojson object 28 | 29 | OUTPUT 30 | xmin, xmax, ymin, ymax 31 | ''' 32 | def _get_bounds(a_poly): 33 | ''' 34 | a_poly is a polygon that may or may not have holes: 35 | [ [ [x,y], [x,y], ...], [ [x,y], ...] ] 36 | We only needs the outter ring to get the bounds 37 | ''' 38 | outter = a_poly[0] 39 | xcoords = [p[0] for p in outter] 40 | ycoords = [p[1] for p in outter] 41 | return min(xcoords), max(xcoords), min(ycoords), max(ycoords) 42 | 43 | if f['geometry']['type'] == 'Polygon': 44 | return _get_bounds(f['geometry']['coordinates']) 45 | elif f['geometry']['type'] != 'MultiPolygon': 46 | raise Exception('Must be a Polygon or MultiPolygon geometry') 47 | 48 | # initialize bounds using the coords of the first point 49 | xmin = xmax = f['geometry']['coordinates'][0][0][0][0] 50 | ymin = ymax = f['geometry']['coordinates'][0][0][0][1] 51 | 52 | for part in f['geometry']['coordinates']: 53 | x0, x1, y0, y1 = _get_bounds(part) 54 | xmin = min(xmin, x0) 55 | xmax = max(xmax, x1) 56 | ymin = min(ymin, y0) 57 | ymax = max(ymax, y1) 58 | 59 | return xmin, xmax, ymin, ymax 60 | 61 | 62 | def point_in_multipolygon(p, muly): 63 | ''' 64 | p - Point object or [x, y] 65 | muly - geojson multipolygon 66 | ''' 67 | def _point_in_poly(p, poly): 68 | ''' 69 | poly - polygon, may have holes: [ [ [x,y], [x,y]...], [ [x,y], [x,y],...] ] 70 | ''' 71 | # check the outter ring 72 | outter = [Point(p[0], p[1]) for p in poly[0]] 73 | if not pip_cross(p, outter)[0]: 74 | return False 75 | for ring in poly[1:]: 76 | r = [Point(p[0], p[1]) for p in ring] 77 | if pip_cross(p, r)[0]: # if p in a ring, return false 78 | return False 79 | return True 80 | # if p is in any part, return true 81 | for part in muly['geometry']['coordinates']: 82 | if _point_in_poly(p, part): 83 | return True 84 | 85 | return False 86 | 87 | def proj_multipoly(geo, proj_func): 88 | ''' 89 | Project the entire geojson multipolygon object 90 | 91 | INPUT: 92 | geo - a geojson object. Only multipolygons are handled here 93 | proj_func - the name a function that two coordinates (x, y) and return the projected coordinates 94 | 95 | OUTPUT: 96 | proj_geo - a projected geojson 97 | 98 | REQUIREMENTS 99 | Must have get_bounds(feature) 100 | 101 | EXAMPLE 102 | Assuming we have a geojson object loaded and it is called blkgrps: 103 | blkgrps_spcs = proj_multipoly(blkgrps, spcs_ohio_south) 104 | ''' 105 | proj_geo = { 106 | 'type': geo['type'], # this should be FeatureCollection 107 | 'features': [] 108 | } 109 | for f in geo['features']: 110 | if f['geometry']['type'] != 'MultiPolygon': 111 | raise Exception('Can only handle multipolygons') 112 | feature = { 113 | 'type': 'Feature', 114 | 'geometry': { 115 | 'type': 'MultiPolygon', 116 | 'coordinates': []}, 117 | 'properties': f['properties'] 118 | } 119 | geom = [] 120 | for part in f['geometry']['coordinates']: 121 | geom.append([[proj_func(p[0], p[1]) for p in ring] for ring in part]) 122 | feature['geometry']['coordinates'] = geom 123 | feature['bounds'] = get_bounds(feature) 124 | proj_geo['features'].append(feature) 125 | return proj_geo 126 | -------------------------------------------------------------------------------- /neville.py: -------------------------------------------------------------------------------- 1 | """ 2 | A Python program for the Neville's algorithm. 3 | 4 | Contact: 5 | Ningchuan Xiao 6 | The Ohio State University 7 | Columbus, OH 8 | """ 9 | 10 | __author__ = "Ningchuan Xiao " 11 | 12 | def neville(datax, datay, x): 13 | """ 14 | Finds an interpolated value using Neville's algorithm. 15 | 16 | Input 17 | datax: input x's in a list of size n 18 | datay: input y's in a list of size n 19 | x: the x value used for interpolation 20 | 21 | Output 22 | p[0]: the polynomial of degree n 23 | """ 24 | n = len(datax) 25 | p = n*[0] 26 | for k in range(n): 27 | for i in range(n-k): 28 | if k == 0: 29 | p[i] = datay[i] 30 | else: 31 | p[i] = ((x-datax[i+k])*p[i]+ \ 32 | (datax[i]-x)*p[i+1])/ \ 33 | (datax[i]-datax[i+k]) 34 | return p[0] 35 | -------------------------------------------------------------------------------- /overlay.py: -------------------------------------------------------------------------------- 1 | import sys 2 | sys.path.append("..") 3 | from contrib.dcel import * 4 | 5 | from .line_seg_intersection import * 6 | 7 | class OvearlayError(Exception): pass 8 | 9 | def update_intersect_dcel(hl, e): 10 | """ 11 | Updates the hedges related to e given a hedge list hl 12 | """ 13 | l = len(hl) 14 | if l<2: 15 | raise OvearlayError( 16 | "Overlay/DCEL error: single edge for vertex") 17 | big, small = l-1, 0 18 | for i in range(l): 19 | if e.angle > hl[i].angle: 20 | big,small = i-1,i 21 | break 22 | b,s = hl[big], hl[small] 23 | e.prevhedge = b.twin 24 | e.twin.nexthedge = s 25 | b.prevhedge = e.twin 26 | b.twin.nexthedge = e 27 | s.prevhedge = e.twin 28 | 29 | def handle_edge_vertex(L, R, C, p, D): 30 | e = C[0].edge 31 | v1 = Vertex(C[0].lp0.x, C[0].lp0.y)# get the hedges for e 32 | v2 = Vertex(C[0].rp.x, C[0].rp.y) 33 | e1, e2 = D.findhedges(v1, v2) # origins: ends of e 34 | e3 = Hedge(v1, Vertex(p.x, p.y)) # hedge, p as origin 35 | e4 = Hedge(v2, Vertex(p.x, p.y)) # hedge, p as origin 36 | # updating around endpoints of e: 37 | e1.twin = e3 38 | e3.twin = e1 39 | e2.twin = e4 40 | e4.twin = e2 41 | e3.nexthedge = e2.nexthedge 42 | e4.nexthedge = e1.nexthedge 43 | 44 | v = D.findvertex(p) # updating around p 45 | v.sortincident() 46 | hl = v.hedgelist 47 | update_intersect_dcel(v.hedgelist, e3) 48 | update_intersect_dcel(v.hedgelist, e4) 49 | # add two new hedges with p as origin 50 | v.hedgelist.append(e3) 51 | v.hedgelist.append(e4) 52 | # e1, e2 updated in D due to references 53 | D.hedges.append(e3) 54 | D.hedges.append(e4) 55 | 56 | def handle_edge_edge(L, R, C, p, D): 57 | pass 58 | 59 | def handle_vertex_vertex(L, R, C, p, D): 60 | pass 61 | 62 | def overlay(psegs, D): 63 | """ 64 | Overlays polygons from two maps. 65 | Input 66 | psegs: a list of Segments. The c attribute in each 67 | segment indicates the source map 68 | D: a partial DCEL with the original hedges and vertices 69 | Output 70 | intpoints: list of intersection points 71 | """ 72 | eq = EventQueue(psegs) 73 | intpoints = [] 74 | T = AVLTree() 75 | L=[] 76 | while not eq.is_empty(): # for all events 77 | e = eq.events.pop(0) # remove the event 78 | p = e.p # event point 79 | L = e.edges # segments with p as left end 80 | R,C = get_edges(T, p) # Intersection at p among L+R+C 81 | if len(L+R+C) > 1: 82 | for s in L+R+C: 83 | if not s.contains(p): 84 | s.lp = p 85 | s.status = INTERIOR 86 | intpoints.append(p) 87 | R,C = get_edges(T, p) 88 | c1 = (L+R+C)[0].c 89 | cross = False 90 | for l in L+R+C: 91 | if c1 is not l.c: 92 | cross = True 93 | break 94 | # Update its vertices and edge lists 95 | if cross is True: 96 | if len(C) == 1: # CASE 1: edge passes vertex 97 | handle_edge_vertex(L, R, C, p, D) 98 | if len(C) > 1: # CASE 2: edge crosses edge 99 | handle_edge_edge(L, R, C, p, D) 100 | if len(C) == 0: # CASE 3: vertex on vertex 101 | handle_vertex_vertex(L, R, C, p, D) 102 | for s in R+C: 103 | T.discard(s) 104 | for s in L+C: 105 | T.insert(s, 1) 106 | if len(L+C) == 0: 107 | s = R[0] 108 | if s is not None: 109 | sl, sr = get_lr(T, s) 110 | y = find_new_event(sl, sr, p, eq) 111 | else: 112 | lp, lpp = get_lrmost(T, L+C) 113 | try: 114 | sl = T.prev_key(lp) 115 | except KeyError: # only on last key 116 | sl = None 117 | try: 118 | sr = T.succ_key(lpp) 119 | except KeyError: # only on last key 120 | sr = None 121 | find_new_event(sl, lp, p, eq) 122 | find_new_event(sr, lpp, p, eq) 123 | return intpoints 124 | -------------------------------------------------------------------------------- /paths.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Functions that help create a Path object in matplotlib 3 | ''' 4 | 5 | from matplotlib.path import Path 6 | from matplotlib.patches import PathPatch 7 | 8 | def path_codes(n): 9 | codes = [Path.LINETO for i in range(n)] 10 | codes[0] = Path.MOVETO 11 | return codes 12 | 13 | def make_path(lines): 14 | '''Creates a matplotlib path. 15 | 16 | This function requires the following: 17 | from matplotlib.path import Path 18 | def path_codes 19 | 20 | Input: 21 | lines: [ [[x,y], [x,y],... ], [[x,y], [x,y],... ], [ [x,y], [x,y],... ] ] 22 | ----- exterior ---- ---- interior ----- ... 23 | Output: 24 | path: a Path object''' 25 | verts = [] 26 | for line in lines: 27 | verts.extend(line) 28 | codes = path_codes(len(lines[0])) 29 | for line in lines[1:]: 30 | codes += path_codes(len(line)) 31 | path = Path(verts, codes) 32 | return path 33 | 34 | if __name__ == '__main__': 35 | import sys 36 | sys.path.append('..') 37 | from geom.point import * 38 | from geom.point_in_polygon import * 39 | import matplotlib.pyplot as plt 40 | 41 | points1 = [ [0,0], [6,0], [5,4], [3,4], [2,3], [0,3], [1,2], [0,0]] 42 | points2 = [ [4,1], [3,3], [5,2], [5,1], [4,1] ] 43 | points3 = [ [1,1], [2,2], [3,1], [1,1]] 44 | 45 | polygon = [[Point(p[0], p[1]) for p in plg] for plg in [points1, points2, points3]] 46 | 47 | pts = [[1,1], [2,2], [4,2], [1,2.1], [0,2], [3,1.5], [2.5,1.5], [4,1], [5,2], [3,3], [2,1.1]] 48 | pts = [Point(p[0], p[1]) for p in pts] 49 | 50 | inout = lambda pip: 1 if pip is True else 0 51 | 52 | results = [inout(pip_cross2(p, polygon)[0]) for p in pts] 53 | 54 | path = make_path([points1] + [points2] + [points3]) 55 | patch = PathPatch(path, facecolor='#AAAAAA', edgecolor='grey', alpha=0.5) 56 | 57 | ax = plt.gca() 58 | ax.add_patch(patch) 59 | 60 | colors = [['red', 'blue'][i] for i in results] 61 | l2 = plt.scatter([p.x for p in pts], [p.y for p in pts], color=colors, s=15) 62 | labels = ['p%s'%(i+1) for i in range(len(pts))] 63 | for i, p in enumerate(pts): 64 | plt.text(p.x+0.1, p.y, labels[i], color='red') 65 | 66 | ax.set_aspect(1) 67 | plt.grid() 68 | 69 | plt.show() 70 | -------------------------------------------------------------------------------- /plot_worldmap.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Plot the world map using data prepared in worldmap.py. 3 | 4 | History 5 | October 23, 2023 6 | Change ax.add_line to ax.add_patch 7 | 8 | Contact: 9 | Ningchuan Xiao 10 | The Ohio State University 11 | Columbus, OH 12 | ''' 13 | 14 | import matplotlib.pyplot as plt 15 | 16 | def plot_world(ax, points, numgraticule, numline, color=None): 17 | ''' 18 | Uses the data prepared by worldmap.py to plot the world map. 19 | 20 | Input: 21 | ax: matplotlib axes 22 | points: a list of [ [ID, X, Y], [ID, X, Y], ...] 23 | numgraticule: the number of lines forming the graticule 24 | numline: the total number of line IDs 25 | color: if not None, the color used to draw coastlines (default: #5a5a5a) 26 | 27 | The user needs to import matplotlib.pyplot first and run plt.show() after calling this function. 28 | ''' 29 | 30 | for i in range(numline): 31 | if iother.x: 160 | return True 161 | elif self.x==other.x and self.y>other.y: 162 | return True 163 | return False 164 | return NotImplemented 165 | def __ge__(self, other): 166 | if isinstance(other, Point): 167 | if self > other or self == other: 168 | return True 169 | return False 170 | return NotImplemented 171 | def __le__(self, other): 172 | if isinstance(other, Point): 173 | if self < other or self == other: 174 | return True 175 | return False 176 | return NotImplemented 177 | def isvalid(self): 178 | if not isinstance(self.x, (int, float)) \ 179 | or not isinstance(self.y, (int, float)): 180 | return False 181 | return True 182 | def __str__(self): 183 | '''NaP: Not a point''' 184 | if not self.isvalid(): 185 | return 'NaP' 186 | fmtstr = f'({self.x}' if isinstance(self.x, int) else f'({self.x:.1f}' 187 | fmtstr += f', {self.y})' if isinstance(self.y, int) else f', {self.y:.1f})' 188 | # if isinstance(self.x, (int)): 189 | # fmtstr = f'({self.x}, ' 190 | # else: 191 | # fmtstr = f'({self.x:.1f}, ' 192 | # if isinstance(self.y, (int)): 193 | # fmtstr += f'{self.y})' 194 | # else: 195 | # fmtstr += f'{self.y:.1f})' 196 | return fmtstr 197 | def __repr__(self): 198 | # return f'Point({self.x}, {self.y})' 199 | return f'[{self.x}, {self.y}]' 200 | def distance(self, other): 201 | return sqrt((self.x-other.x)**2 + (self.y-other.y)**2) 202 | 203 | def __iter__(self): 204 | return self 205 | def __next__(self): 206 | if self.idx >= len(self): 207 | self.idx = 0 208 | raise StopIteration 209 | else: 210 | self.idx += 1 211 | return self[self.idx-1] 212 | -------------------------------------------------------------------------------- /point2line.py: -------------------------------------------------------------------------------- 1 | import math 2 | 3 | from .point import * 4 | 5 | def point2line(p, p1, p2): 6 | """ 7 | Calculate the distance from point to a line. 8 | Input 9 | p: the point 10 | p1 and p2: the two points that define a line 11 | Output 12 | d: distance from p to line p1p2 13 | """ 14 | x0 = float(p.x) 15 | y0 = float(p.y) 16 | x1 = float(p1.x) 17 | y1 = float(p1.y) 18 | x2 = float(p2.x) 19 | y2 = float(p2.y) 20 | dx = x1-x2 21 | dy = y1-y2 22 | a = dy 23 | b = -dx 24 | c = y1*dx - x1*dy 25 | if a==0 and b==0: # p1 and p2 are the same point 26 | d = math.sqrt((x1-x0)*(x1-x0) + (y1-y0)*(y1-y0)) 27 | else: 28 | d = abs(a*x0+b*y0+c)/math.sqrt(a*a+b*b) 29 | return d 30 | 31 | if __name__ == "__main__": 32 | p, p1, p2 = Point(10,0), Point(0,100), Point(0,1) #*@\label{point2line:l1} 33 | print(point2line(p, p1, p2)) 34 | p, p1, p2 = Point(0,10), Point(1000,0.001), Point(-100,0) 35 | print(point2line(p, p1, p2)) 36 | p, p1, p2 = Point(0,0), Point(0,10), Point(10,0) 37 | print(point2line(p, p1, p2)) 38 | p, p1, p2 = Point(0,0), Point(10,10), Point(10,10) 39 | print(point2line(p, p1, p2)) #*@\label{point2line:l2} 40 | 41 | -------------------------------------------------------------------------------- /point_in_polygon.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Determines whether a point is in a polygon. Code adopted 3 | from the C program in Graphics Gems IV by Haines (1994). 4 | 5 | Change history 6 | October 9, 2018 7 | All points on edge are counted as in 8 | 9 | October 10, 2017 10 | Use generic Python exception 11 | 12 | September 2017 13 | Python 3 14 | 15 | December 2016 16 | Add pip_cross2, which also works for complicated polygons 17 | with multiple parts or holes 18 | 19 | October 2016 20 | Removed function pip_cross0 21 | Changed <> to != 22 | Raise error if polygon is not closed (previous version modifies data) 23 | This requires polygon_error.py. 24 | Changed some variable names for better read 25 | 26 | October 2015 27 | A bug in previous code, pip_cross0, is fixed. 28 | ''' 29 | 30 | import math 31 | import sys 32 | sys.path.append('..') 33 | from geom.point import * 34 | 35 | def pip_cross(point, pgon): 36 | """ 37 | Input 38 | pgon: a list of points as the vertices for a polygon 39 | The polygon needs to be closed. Otherwise an error is raised. 40 | point: the point 41 | 42 | Ouput 43 | Returns a boolean value of True or False and the number 44 | of times the half line crosses the polygon boundary 45 | """ 46 | if pgon[0] != pgon[-1]: 47 | raise Exception('Polygon not closed') 48 | x, y = point.x, point.y 49 | N = len(pgon) 50 | crossing_count = 0 51 | is_point_inside = False 52 | for i in range(N-1): 53 | p1, p2 = pgon[i], pgon[i+1] 54 | yside1 = p1.y >= y 55 | yside2 = p2.y >= y 56 | xside1 = p1.x >= x 57 | xside2 = p2.x >= x 58 | if (p1.y == p2.y == y and (xside1 != xside2 or x == p1.x or x == p2.x)) or \ 59 | (p1.x == p2.x == x and (yside1 != yside2 or y == p1.y or y == p2.y)) or \ 60 | p1 == point or \ 61 | p2 == point: 62 | crossing_count = 1 63 | is_point_inside = True 64 | return is_point_inside, crossing_count 65 | if yside1 != yside2: 66 | if xside1 == xside2: 67 | if xside1: 68 | crossing_count += 1 69 | is_point_inside = not is_point_inside 70 | else: 71 | m = p2.x - (p2.y-y)*(p1.x-p2.x)/(p1.y-p2.y) 72 | if m == x: 73 | crossing_count = 1 74 | is_point_inside = True 75 | return is_point_inside, crossing_count 76 | elif m > x: 77 | crossing_count += 1 78 | is_point_inside = not is_point_inside 79 | return is_point_inside, crossing_count 80 | 81 | def _pip_cross(point, pgon): 82 | """ 83 | This will be used in pip_cross2 to handle polygons with multiple parts. It works as same as 84 | function pip_cross, except it has an option to return a third value to indicate special cases. 85 | 86 | Input 87 | pgon: a list of points as the vertices for a polygon 88 | The polygon needs to be closed. Otherwise an error is raised. 89 | point: the point 90 | 91 | Ouput 92 | Returns a touple of 93 | a boolean value of True or False 94 | 95 | the number of times the half line crosses the polygon boundary 96 | 97 | a boolean value indicate special case (True) or not (False) 98 | """ 99 | if pgon[0] != pgon[-1]: 100 | raise Exception('Polygon not closed') 101 | x, y = point.x, point.y 102 | N = len(pgon) 103 | crossing_count = 0 104 | is_point_inside = False 105 | for i in range(N-1): 106 | p1, p2 = pgon[i], pgon[i+1] 107 | yside1 = p1.y >= y 108 | yside2 = p2.y >= y 109 | xside1 = p1.x >= x 110 | xside2 = p2.x >= x 111 | if (p1.y == p2.y == y and (xside1 != xside2 or x == p1.x or x == p2.x)) or \ 112 | (p1.x == p2.x == x and (yside1 != yside2 or y == p1.y or y == p2.y)) or \ 113 | p1 == point or \ 114 | p2 == point: 115 | crossing_count = 1 116 | is_point_inside = True 117 | return is_point_inside, crossing_count, True 118 | if yside1 != yside2: 119 | if xside1 == xside2: 120 | if xside1: 121 | crossing_count += 1 122 | is_point_inside = not is_point_inside 123 | else: 124 | m = p2.x - (p2.y-y)*(p1.x-p2.x)/(p1.y-p2.y) 125 | if m == x: 126 | crossing_count = 1 127 | is_point_inside = True 128 | return is_point_inside, crossing_count, True 129 | elif m > x: 130 | crossing_count += 1 131 | is_point_inside = not is_point_inside 132 | return is_point_inside, crossing_count, False 133 | 134 | 135 | def pip_cross2(point, polygons): 136 | """ 137 | Input 138 | polygon: a list of lists, where each inner list contains points 139 | forming a part of a multipolygon. Each part must be 140 | closed, otherwise an error will be raised. 141 | Example of a polygon with two parts: 142 | [ [ [1, 2], [3, 4], [5, 3], [1, 2] ], 143 | [ [6, 6], [7, 7], [8, 6], [6, 6] ] ] 144 | point: the point 145 | 146 | Ouput 147 | Returns a boolean value of True or False and the number 148 | of times the half line crosses the polygon boundary 149 | """ 150 | x, y = point.x, point.y 151 | crossing_count = 0 152 | is_point_inside = False 153 | for pgon in polygons: 154 | if pgon[0] != pgon[-1]: 155 | raise Exception('Polygon not closed') 156 | a, b, c = _pip_cross(point, pgon) 157 | if c: 158 | return True, 1 159 | else: 160 | if a: 161 | is_point_inside = not is_point_inside 162 | crossing_count += b 163 | return is_point_inside, crossing_count 164 | 165 | if __name__ == "__main__": 166 | points = [ [0,10], [5,0], [10,10], [15,0], [20,10], 167 | [25,0], [30,20], [40,20], [45,0], [50,50], 168 | [40,40], [30,50], [25,20], [20,50], [15,10], 169 | [10,50], [8, 8], [4,50], [0,10] ] 170 | ppgon = [Point(p[0], p[1]) for p in points ] 171 | pts = [Point(10, 30), Point(10, 20), 172 | Point(20, 40), Point(5, 40)] 173 | for p in pts: 174 | result = pip_cross2(p, [ppgon]) 175 | if result[0] == True: 176 | print("Point", p, "is IN") 177 | else: 178 | print("Point", p, "is OUT") 179 | 180 | points = [ [0,10], [5,0], [10,10], [15,0], [20,10] ] 181 | ppgon = [Point(p[0], p[1]) for p in points ] 182 | try: 183 | x = pip_cross2(Point(10, 30), [ppgon]) 184 | except Exception as err: 185 | print(err) 186 | else: 187 | print(x[0]) 188 | 189 | # a polygon with holes 190 | points1 = [ [0,0], [6,0], [5,4], [3,4], [2,3], [0,3], [1,2], [0,0]] 191 | points2 = [ [4,1], [3,3], [5,2], [5,1], [4,1] ] 192 | points3 = [ [1,1], [2,2], [3,1], [1,1]] 193 | polygon = [[Point(p[0], p[1]) for p in plg] for plg in [points1, points2, points3]] 194 | pts = [[1,1], [2,2], [4,2], [1,2.1], [0,2], [3,1.5], [2.5,1.5], [4,1], [5,2], [3,3], [2,1.1]] 195 | pts = [Point(p[0], p[1]) for p in pts] 196 | print([pip_cross2(p, polygon)[0] for p in pts]) 197 | -------------------------------------------------------------------------------- /point_in_polygon_winding.py: -------------------------------------------------------------------------------- 1 | import math 2 | from point import * 3 | 4 | def is_left(p, p1, p2): 5 | """ 6 | Tests if point p is to the left of a line segement 7 | between p1 and p2 8 | Output 9 | 0 the point is on the line 10 | >0 p is to the left of the line 11 | <0 p is to the right of the line 12 | """ 13 | return (p2.x-p1.x)*(p.y-p1.y) - (p.x-p1.x)*(p2.y-p1.y) 14 | 15 | def pip_wn(point, pgon): 16 | """ 17 | Determines whether a point is in a polygon using the 18 | winding number algorithm using trigonometric functions. 19 | Code adopted from the C program in Graphics Gems IV 20 | (Haines 1994). 21 | Input 22 | point: the point 23 | pgon: a list of points as the vertices for a polygon 24 | Ouput 25 | Returns a boolean value of True or False and the number 26 | of times the half line crosses the polygon boundary 27 | """ 28 | if pgon[0] != pgon[-1]: 29 | pgon.append(pgon[0]) 30 | n = len(pgon) 31 | xp = point.x 32 | yp = point.y 33 | wn = 0 34 | for i in range(n-1): 35 | xi = pgon[i].x 36 | yi = pgon[i].y 37 | xi1 = pgon[i+1].x 38 | yi1 = pgon[i+1].y 39 | thi = (xp-xi)*(xp-xi1) + (yp-yi)*(yp-yi1) 40 | norm = (math.sqrt((xp-xi)**2+(yp-yi)**2) 41 | * math.sqrt((xp-xi1)**2+(yp-yi1)**2)) 42 | if thi != 0: 43 | thi = thi/norm 44 | thi = math.acos(thi) 45 | wn += thi 46 | wn /= 2*math.pi 47 | wn = int(wn) 48 | return wn is not 0, wn 49 | 50 | def pip_wn1(point, pgon): 51 | """ 52 | Determines whether a point is in a polygon using the 53 | winding number algorithm without trigonometric functions. 54 | Code adopted from the C program in Graphics Gems IV 55 | (Haines 1994). 56 | Input 57 | point: the point 58 | pgon: a list of points as the vertices for a polygon 59 | Ouput 60 | Returns a boolean value of True or False and the number 61 | of times the half line crosses the polygon boundary 62 | """ 63 | wn = 0 64 | n = len(pgon) 65 | for i in range(n-1): 66 | if pgon[i].y <= point.y: 67 | if pgon[i+1].y > point.y: 68 | if is_left(point, pgon[i], pgon[i+1])>0: 69 | wn += 1 70 | else: 71 | if pgon[i+1].y <= point.y: 72 | if is_left(point, pgon[i], pgon[i+1])<0: 73 | wn -= 1 74 | return wn is not 0, wn 75 | 76 | if __name__ == "__main__": 77 | pgon = [ [2,3], [7,4], [6,6], [4,2], [11,5], 78 | [5,11], [2,3] ] 79 | point = Point(6, 4) 80 | ppgon = [Point(p[0], p[1]) for p in pgon ] 81 | print pip_wn(point, ppgon) 82 | print pip_wn1(point, ppgon) 83 | -------------------------------------------------------------------------------- /polygon_error.py: -------------------------------------------------------------------------------- 1 | class PolygonError: 2 | """Basic error for point-in-polygon algorithms""" 3 | def __init__(self, msg): 4 | self.message = msg 5 | -------------------------------------------------------------------------------- /quick_convex_hull.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Quick convex hull 3 | https://en.wikipedia.org/wiki/Quickhull 4 | ''' 5 | 6 | from .point import * 7 | from .sideplr import * 8 | from .point2line import * 9 | 10 | def find_convex_hull(points): 11 | # Find the left- and right-most points in the data 12 | xmin = float('inf') 13 | xmax = -float('inf') 14 | for p in points: 15 | if p.x < xmin: 16 | xmin = p.x 17 | A = p 18 | if p.x > xmax: 19 | xmax = p.x 20 | B = p 21 | 22 | # these two points will be on the hull 23 | convex_hull = [A, B] 24 | 25 | # find the points on the right side of AB and put them in s1 26 | # find the points on the left side of AB and put them in s2 27 | s1 = [] 28 | s2 = [] 29 | for p in points[1:-2]: 30 | lr = sideplr(p, A, B) 31 | if lr > 0: 32 | s1.append(p) 33 | elif lr < 0: 34 | s2.append(p) 35 | 36 | # for each die, continuously find the point farthest from the line and add it to the hull 37 | # then insert that point in between the two points and do this again 38 | find_hull(convex_hull, s1, A, B) 39 | find_hull(convex_hull, s2, B, A) 40 | 41 | return convex_hull 42 | 43 | def find_hull(hull: list, sk, p, q): 44 | ''' 45 | Find points in sk that are on the convex hull. 46 | All points in sk must be on the right side of line pq 47 | ''' 48 | 49 | if not sk: 50 | return 51 | 52 | # find the farthest point from the line and add it to the hull 53 | maxdist = -1 54 | C = None 55 | for p1 in sk: 56 | dist = point2line(p1, p, q) 57 | if dist > maxdist: 58 | maxdist = dist 59 | C = p1 60 | i = hull.index(p) 61 | hull.insert(i, C) 62 | 63 | # find the points on the right side of line pC, and then line Cq 64 | # and call this function again 65 | s1 = [] 66 | s2 = [] 67 | for p1 in sk: 68 | if p1 == C: 69 | continue 70 | lr = sideplr(p1, p, C) 71 | if lr > 0: 72 | s1.append(p1) 73 | lr = sideplr(p1, C, q) 74 | if lr > 0: 75 | s2.append(p1) 76 | 77 | find_hull(hull, s1, p, C) 78 | find_hull(hull, s2, C, q) 79 | 80 | -------------------------------------------------------------------------------- /shapex.py: -------------------------------------------------------------------------------- 1 | ''' 2 | A class and related functions that handle reading of shapefiles 3 | 4 | It now only supports four types of shapefile: 5 | Point, MultiPoint (not tested), PolyLine, Polygon. 6 | 7 | History 8 | 9 | October 9, 2017 10 | Support slicing! 11 | 12 | October 8, 2017 13 | First version. 14 | Supports four types. 15 | No slicing 16 | 17 | Credit: the read_dbf method is adopted from http://code.activestate.com/recipes/362715/ 18 | 19 | Author 20 | Ningchuan Xiao 21 | ncxiao@gmail.com 22 | ''' 23 | 24 | from struct import unpack, calcsize 25 | from os.path import isfile 26 | from datetime import date 27 | 28 | shapefile_types = { 29 | 0: 'Null Shape', 30 | 1: 'Point', 31 | 3: 'PolyLine', 32 | 5: 'Polygon', 33 | 8: 'MultiPoint', 34 | 11: 'PointZ', 35 | 13: 'PolyLineZ', 36 | 15: 'PolygonZ', 37 | 18: 'MultiPointZ', 38 | 21: 'PointM', 39 | 23: 'PolyLineM', 40 | 25: 'PolygonM', 41 | 28: 'MultiPointM', 42 | 31: 'MultiPatch' 43 | } 44 | 45 | supported_types = [ 'Point', 'MultiPoint', 'PolyLine', 'Polygon' ] 46 | 47 | def clockwise(polygon): 48 | '''calculate 2*A 49 | polygon: [ [x, y], [x, y], ... ] 50 | 51 | polygon = [ [1, 0], [2,0], [2,2], [1,2], [1, 0] ] 52 | clockwise(polygon) # False 53 | polygon.reverse() 54 | clockwise(polygon) # True 55 | ''' 56 | if polygon[0] != polygon[-1]: 57 | return 58 | num_point = len(polygon) 59 | A = 0 60 | for i in range(num_point-1): 61 | p1 = polygon[i] 62 | p2 = polygon[i+1] 63 | ai = p1[0] * p2[1] - p2[0] * p1[1] 64 | A += ai 65 | return A<0 66 | 67 | class shapex: 68 | ''' 69 | A class for points in Cartesian coordinate systems. 70 | 71 | Examples 72 | 73 | >>> fname = '/Users/xiao/lib/gisalgs/data/uscnty48area.shp' 74 | >>> shp = shapex(fname) 75 | >>> print(shp[60]) 76 | ''' 77 | def __init__(self, fname): 78 | if not fname.endswith('.shp'): 79 | raise Exception('Need a .shp file.') 80 | self.fname_shp = fname 81 | self.fname_shx = fname[:-3]+'shx' 82 | self.fname_dbf = fname[:-3]+'dbf' 83 | if not isfile(self.fname_shp) or not isfile(self.fname_shx) or not isfile(self.fname_dbf): 84 | raise Exception('Need at least three files: .shp, .shx, .dbf') 85 | self.open_shapefile() 86 | 87 | def open_shapefile(self): 88 | self.f_shx = open(self.fname_shx, 'rb') 89 | h1 = unpack('>7i', self.f_shx.read(28)) 90 | h2 = unpack('<2i 8d', self.f_shx.read(72)) 91 | file_length = h1[-1] 92 | self.num_rec = (file_length-50)//4 93 | 94 | self.f_shp = open(self.fname_shp, 'rb') 95 | h1 = unpack('>7i', self.f_shp.read(28)) # BIG 96 | h2 = unpack('<2i 8d', self.f_shp.read(72)) # LITTLE 97 | 98 | self.file_length = h1[-1] 99 | self.version = h2[0] 100 | self.shape_type = shapefile_types[h2[1]] 101 | # self.xmin, self.ymin, self.xmax, self.ymax, self.zmin, self.zmax, self.mmin, self.mmax = h2[2:10] 102 | self.xmin = h2[2] 103 | self.ymin = h2[3] 104 | self.xmax = h2[4] 105 | self.ymax = h2[5] 106 | self.zmin = h2[6] 107 | self.zmax = h2[7] 108 | self.mmin = h2[8] 109 | self.mmax = h2[9] 110 | self.this_feature_num = 0 111 | # get (offset, content length) pairs from shx 112 | # remember each record has a header of 8 bytes 113 | index = unpack('>'+'i'*self.num_rec*2, self.f_shx.read(self.num_rec*4*4)) 114 | self.index = [(index[i]*2, index[i+1]*2) for i in range(0, len(index), 2)] 115 | 116 | # get schema, etc. 117 | self.f_dbf = open(self.fname_dbf, 'rb') 118 | dbf_numrec, lenheader = unpack('self.num_rec: 142 | raise Exception('Feature index out of range (' + str(i) + ')') 143 | pos = self.index[i] 144 | self.f_shp.seek(pos[0] + 8) # skip record hearder, which is not useful 145 | 146 | if self.shape_type == 'Polygon': 147 | feature = self.readpolygon() 148 | if self.shape_type == 'PolyLine': 149 | feature = self.readpolygon() 150 | if feature['geometry']['type'] == 'MultiPolygon': 151 | feature['geometry']['type'] = 'MultiLineString' 152 | else: 153 | feature['geometry']['type'] = 'LineString' 154 | if self.shape_type == 'Point': 155 | feature = self.readpoint() 156 | if self.shape_type == 'MultiPoint': 157 | feature = self.readmultipoint() 158 | 159 | # get properties here. 160 | properties = self.read_dbf(i) 161 | feature['properties'] = properties 162 | feature['id'] = i 163 | return feature 164 | else: 165 | raise TypeError('Invalid index') 166 | 167 | 168 | def robust_decode(self, bs): 169 | ''' 170 | https://stackoverflow.com/questions/24475393/unicodedecodeerror-ascii-codec-cant-decode-byte-0xc3-in-position-23-ordinal 171 | Convert a byte string to unicode. Try UTF8 first, if not working then latin1. 172 | ''' 173 | cr = None 174 | try: 175 | cr = bs.decode('utf8') 176 | except UnicodeDecodeError: 177 | cr = bs.decode('latin1') 178 | return cr 179 | 180 | def read_dbf(self, i): 181 | # Note: dtypes of D, L are note tested 182 | self.f_dbf.seek(self.dbf_header_length + i * self.formatsize) 183 | record = unpack(self.formatstr, self.f_dbf.read(self.formatsize)) 184 | if record[0] == ' ': 185 | return ' ' * self.formatsize 186 | result = [] 187 | for (name, dtype, size, deci), value in zip(self.fields, record): 188 | value = value.decode('latin1') 189 | # value = value.decode('ascii') // works for Python 2 190 | # value = self.robust_decode(value) 191 | if name == 'DeletionFlag': 192 | continue 193 | if dtype == 'N': 194 | value = value.replace('\0', '').lstrip() 195 | if value == '': 196 | value = 0 197 | elif deci: 198 | value = float(value) 199 | else: 200 | value = int(value) 201 | elif dtype == 'C': 202 | value = value.rstrip() 203 | elif dtype == 'D': 204 | y, m, d = int(value[:4]), int(value[4:6]), int(value[6:8]) 205 | value = date(y, m, d) 206 | elif dtype == 'L': 207 | value = (value in 'YyTt' and 'T') or (value in 'NnFf' and 'F') or '?' 208 | elif dtype == 'F': 209 | value = float(value) 210 | result.append(value) 211 | properties = {} 212 | for fi in range(1, len(self.fields)): 213 | properties[self.fields[fi][0]] = result[fi-1] 214 | return properties 215 | 216 | def readpoint(self): 217 | point = unpack('= self.num_rec: 288 | self.this_feature_num = 0 289 | raise StopIteration 290 | feature = self.__getitem__(self.this_feature_num) 291 | self.this_feature_num += 1 292 | return feature 293 | def close(self): 294 | self.f_shp.close() 295 | self.f_shx.close() 296 | self.f_dbf.close() 297 | 298 | @property 299 | def bounds(self): 300 | return(self.xmin, self.ymin, self.xmax, self.ymax) 301 | 302 | @property 303 | def schema(self): 304 | myschema = {} 305 | myschema['geometry'] = self.shape_type 306 | properties = [] 307 | for fi in range(1, len(self.fields)): 308 | name = self.fields[fi][0] 309 | f1 = self.fields[fi][1] 310 | f2 = self.fields[fi][2] 311 | dci = self.fields[fi][3] 312 | if f1 == 'C': 313 | fmt = 'str:' + str(f2) 314 | elif f1 == 'F': 315 | fmt = 'float:' + str(f2) + '.' + str(dci) 316 | elif f1 == 'N': 317 | if dci == 0: 318 | fmt = 'int:' + str(f2) 319 | else: 320 | fmt = 'float:' + str(f2) + '.' + str(dci) 321 | elif f1 == 'D': 322 | fmt = 'datetime' 323 | else: 324 | fmt = 'other' 325 | properties.append((name, fmt)) 326 | myschema['properties'] = properties 327 | return myschema 328 | 329 | if __name__ == '__main__': 330 | fname = '/Users/xiao/lib/gisalgs/data/uscnty48area.shp' 331 | fname = '/Users/xiao/lib/gisalgs/data/ne_110m_coastline.shp' 332 | # fname = '/Users/xiao/lib/gisalgs/data/ne_110m_populated_places.shp' 333 | # fname = '/Users/xiao/lib/gisalgs/data/ne_110m_admin_0_countries.shp' 334 | shp = shapex(fname) 335 | print('Number of fetures:', len(shp)) 336 | # this tests all the geometry types 337 | types = {} 338 | for f in shp: 339 | t = f['geometry']['type'] 340 | if t[:5] != 'Multi': 341 | if len(f['geometry']['coordinates']) > 1: 342 | t = t + '_Parts' 343 | if t not in types: 344 | types[t] = 1 345 | else: 346 | types[t] += 1 347 | print(types) 348 | 349 | print('Shape type:', shp.shape_type) 350 | print('Schema:\n', shp.schema) 351 | print('Bunds:\n', shp.bounds) 352 | shp.close() 353 | -------------------------------------------------------------------------------- /sideplr.py: -------------------------------------------------------------------------------- 1 | ''' 2 | A function testing the side of a point with respect to an oriented line 3 | 4 | History 5 | December 16, 2023 6 | Change the use of int to directly comparing signs 7 | 8 | Contact: 9 | Ningchuan Xiao 10 | The Ohio State University 11 | Columbus, OH 12 | ''' 13 | 14 | __author__ = "Ningchuan Xiao " 15 | 16 | from .point import * 17 | 18 | def sideplr(p, p1, p2): 19 | ''' 20 | Calculates the side of point p to the vector p1p2. 21 | 22 | Input 23 | p: the point 24 | p1, p2: the start and end points of the line 25 | 26 | Output 27 | -1: p is on the left side of p1p2 28 | 0: p is on the line of p1p2 29 | 1: p is on the right side of p1p2 30 | ''' 31 | lr = (p.x-p1.x)*(p2.y-p1.y)-(p2.x-p1.x)*(p.y-p1.y) 32 | if lr != 0: 33 | lr = 1 if lr>0 else -1 34 | return lr 35 | # return int((p.x-p1.x)*(p2.y-p1.y)-(p2.x-p1.x)*(p.y-p1.y)) 36 | 37 | if __name__ == "__main__": 38 | lr = {-1: 'left', 0: 'on the line', 1: 'right'} 39 | p=Point(1,1) 40 | p1=Point(0,0) 41 | p2=Point(1,0) 42 | print(f'Point {p} to line {p1}->{p2}: {lr[sideplr(p, p1, p2)]}') 43 | print(f'Point {p} to line {p2}->{p1}: {lr[sideplr(p, p2, p1)]}') 44 | p = Point(0.51, 0.00001) 45 | print(f'Point {p} to line {p1}->{p2}: {lr[sideplr(p, p1, p2)]}') 46 | print(f'Point {p} to line {p2}->{p1}: {lr[sideplr(p, p2, p1)]}') 47 | 48 | p = Point(3, 2.0001) 49 | p1 = Point(0, 1) 50 | p2 = Point(6, 3) 51 | print(f'Point {p} to line {p1}->{p2}: {lr[sideplr(p, p1, p2)]}') 52 | print(f'Point {p} to line {p2}->{p1}: {lr[sideplr(p, p2, p1)]}') 53 | -------------------------------------------------------------------------------- /test_line_seg_intersection.py: -------------------------------------------------------------------------------- 1 | from line_seg_intersection import * 2 | 3 | s = [ [[20,15],[0,16]], [[3,18],[2,3]], [[4,14],[6,19]], 4 | [[10,17],[0,6]], [[8,3],[5,10]], [[6,6],[11,9]], 5 | [[16,14],[10,6]], [[16,10],[10,11]], 6 | [[14,8],[16,12]] ] 7 | 8 | psegs = [Segment(i, Point(s[i][0][0], s[i][0][1]), 9 | Point(s[i][1][0], s[i][1][1])) 10 | for i in range(len(s))] 11 | 12 | ints = intersections(psegs) 13 | print "There are", len(ints), "intersection points:" 14 | print ints 15 | -------------------------------------------------------------------------------- /test_overlay.py: -------------------------------------------------------------------------------- 1 | from overlay import * 2 | from copy import deepcopy 3 | 4 | d=[ Dcel(), Dcel() ] 5 | 6 | pgon1 = [ [3,3], [9,3], [8,8], [4,8] ] 7 | edges1 = [ [0,1], [1,2], [2,3], [3,0] ] 8 | pgon2 = [ [1,1], [6,6], [10,2] ] 9 | edges2 = [ [0,1], [1,2], [2,0] ] 10 | 11 | d[0].load(pgon1, edges1) 12 | d[1].load(pgon2, edges2) 13 | 14 | D = Dcel() 15 | D.hedges = d[0].hedges + d[1].hedges 16 | D.vertices = d[0].vertices + d[1].vertices 17 | 18 | s1 = [] 19 | for i in range(len(pgon1)-1): 20 | s1.append([pgon1[i], pgon1[i+1]]) 21 | 22 | s1.append([pgon1[-1], pgon1[0]]) 23 | 24 | s2 = [] 25 | for i in range(len(pgon2)-1): 26 | s2.append([pgon2[i], pgon2[i+1]]) 27 | 28 | s2.append([pgon2[-1], pgon2[0]]) 29 | 30 | ps1 = [Segment(i, Point(s1[i][0][0],s1[i][0][1]), 31 | Point(s1[i][1][0],s1[i][1][1]), 0) for i in range(len(s1))] 32 | ps2 = [Segment(i+len(s1), Point(s2[i][0][0],s2[i][0][1]), 33 | Point(s2[i][1][0],s2[i][1][1]), 1) for i in range(len(s2))] 34 | s = ps1+ps2 35 | 36 | ints = overlay(s, D) 37 | 38 | # get all boundary cycles 39 | hl = deepcopy(D.hedges) 40 | while len(hl) is not 0: 41 | c = [] 42 | #print len(hl), ":", 43 | e0 = hl.pop() 44 | e = e0 45 | c.append(e) 46 | while True: 47 | print e, 48 | e1 = e.nexthedge 49 | if e1 is not e0: 50 | c.append(e1) 51 | hl.remove(e1) 52 | e = e1 53 | else: 54 | break 55 | print 56 | 57 | import pickle 58 | pickle.dump(D, open('mydcel.pickle', 'w')) 59 | -------------------------------------------------------------------------------- /test_projection.py: -------------------------------------------------------------------------------- 1 | """ 2 | Test drive for the Robinson projection. 3 | 4 | Contact: 5 | Ningchuan Xiao 6 | The Ohio State University 7 | Columbus, OH 8 | """ 9 | __author__ = "Ningchuan Xiao " 10 | 11 | from osgeo import ogr 12 | import matplotlib.pyplot as plt 13 | from transform1 import * 14 | from worldmap import * 15 | 16 | fname = '../data/ne_110m_coastline.shp' 17 | pp, numgraticule, numline = prep_projection_data(fname) 18 | 19 | points=[] 20 | for p in pp: 21 | p1 = transform1(p[1], p[2]) 22 | points.append([p[0], p1[0], p1[1]]) 23 | 24 | for i in range(numline): 25 | if i=n-sidelen: 57 | iright = min(n, i+sidelen+1) 58 | else: 59 | iright = i+sidelen+1 60 | return ileft, iright 61 | 62 | def transform1(lon, lat): 63 | """ 64 | Returns the transformation of lon and lat 65 | on the Robinson projection. 66 | Input 67 | lon: longitude 68 | lat: latitude 69 | Output 70 | x: x coordinate (origin at 0,0) 71 | y: y coordinate (origin at 0,0) 72 | """ 73 | n = len(latitudes) 74 | south = False 75 | if lat<0: 76 | south = True 77 | lat = abs(lat) 78 | if lat>90: 79 | return 80 | i = find_le(latitudes, lat) 81 | ileft, iright = get_interpolation_range(2, n, i) 82 | y = neville(latitudes[ileft:iright], 83 | B[ileft:iright], lat) 84 | if lat<=38: 85 | ileft, iright = get_interpolation_range(1, n, i) 86 | x = neville(latitudes[ileft:iright], 87 | A[ileft:iright], lat) 88 | y = 0.5072*y/2.0 89 | dx = x/360.0 90 | x = dx*lon 91 | if south: 92 | y = -1.0 * y 93 | return x, y 94 | -------------------------------------------------------------------------------- /transform2.py: -------------------------------------------------------------------------------- 1 | """ 2 | A Python program for the Mollweide projection. 3 | 4 | Contact: 5 | Ningchuan Xiao 6 | The Ohio State University 7 | Columbus, OH 8 | """ 9 | 10 | __author__ = "Ningchuan Xiao " 11 | 12 | from numpy import pi, cos, sin, radians, degrees, sqrt 13 | 14 | def opt_theta(lat, verbose=False): 15 | """ 16 | Finds optimal theta value using Newton-Raphson iteration. 17 | Input 18 | lat: the latitude value 19 | verbose: True to print intermediate output 20 | Output 21 | theta 22 | """ 23 | lat1 = radians(lat) 24 | theta = lat1 25 | while True: 26 | dtheta = -(theta+sin(theta)- 27 | pi*sin(lat1))/(1.0+cos(theta)) 28 | if verbose: 29 | print("theta =", degrees(theta)) 30 | print("delta =", degrees(dtheta)) 31 | if int(1000000*dtheta) == 0: 32 | break 33 | theta = theta+dtheta 34 | return theta/2.0 35 | 36 | def transform2(lon, lat, lon0=0, R=1.0): 37 | """ 38 | Returns the transformation of lon and lat 39 | on the Mollweide projection. 40 | 41 | Input 42 | lon: longitude 43 | lat: latitude 44 | lon0: central meridian 45 | R: radius of the globe 46 | 47 | Output 48 | x: x coordinate (origin at 0,0) 49 | y: y coordinate (origin at 0,0) 50 | """ 51 | lon1 = lon-lon0 52 | if lon0 != 0: 53 | if lon1>180: 54 | lon1 = -((180+lon0)+(lon1-180)) 55 | elif lon1<-180: 56 | lon1 = (180-lon0)-(lon1+180) 57 | theta = opt_theta(lat) 58 | x = sqrt(8.0)/pi*R*lon1*cos(theta) 59 | x = radians(x) 60 | y = sqrt(2.0)*R*sin(theta) 61 | return x, y 62 | -------------------------------------------------------------------------------- /transforms.py: -------------------------------------------------------------------------------- 1 | """ 2 | A Python program for the sinusoidal and equirectangular projections. 3 | 4 | Change history 5 | October 2018 6 | Replace numtp with math 7 | 8 | 9 | Contact: 10 | Ningchuan Xiao 11 | The Ohio State University 12 | Columbus, OH 13 | """ 14 | 15 | __author__ = "Ningchuan Xiao " 16 | 17 | from math import cos, radians 18 | 19 | def transform_sinusoidal(lon, lat, lon0=0): 20 | """ 21 | Returns the transformation of lon and lat on the Sinusoidal projection. 22 | 23 | Input 24 | lon: longitude in degrees 25 | lat: latitude in degrees 26 | lon0: central meridian in degrees 27 | 28 | Output 29 | x: x coordinate (origin at 0,0) 30 | y: y coordinate (origin at 0,0) 31 | """ 32 | lon1 = lon-lon0 33 | x = lon1 * cos(radians(lat)) 34 | y = lat 35 | return x, y 36 | 37 | def transform_equirectangular(lon, lat, lat0=0): 38 | """ 39 | Returns the transformation of lon and lat on the equirectangular projection, 40 | a.k.a. the equidistant cylindrical projection, geographic projection, or la 41 | carte parallelogrammatique projection. It is a special case of the plate carree 42 | projection 43 | 44 | Input 45 | lon: longitude in degrees 46 | lat: latitude in degrees (will not be used) 47 | lat0: standard parallel in degrees (true scale) 48 | 49 | Output 50 | x: x coordinate (origin at 0,0) 51 | y: y coordinate (origin at 0,0) 52 | 53 | """ 54 | x = lon * cos(radians(lat0)) 55 | y = lat 56 | return x, y 57 | -------------------------------------------------------------------------------- /worldmap.py: -------------------------------------------------------------------------------- 1 | """ 2 | Prepares data for projection transformation. 3 | 4 | History 5 | October 15, 2020 6 | Added a new function prep_projection_data_url_geojson 7 | to load geojson from a URL 8 | 9 | February 28, 2018 10 | Shapex is default 11 | 12 | October 10, 2017 13 | Now supports both shapex and OGR 14 | 15 | October 6, 2016 16 | Added default parameters for lat and lon bounds 17 | 18 | Contact: 19 | Ningchuan Xiao 20 | The Ohio State University 21 | Columbus, OH 22 | """ 23 | 24 | import sys 25 | sys.path.append('..') 26 | from geom.shapex import * 27 | import urllib.request as request 28 | import json 29 | 30 | try: 31 | from osgeo import ogr 32 | except ImportError: 33 | use_lib = 'SHAPEX' 34 | else: 35 | use_lib = 'OGR' 36 | 37 | def prep_projection_data_ogr(fname, lon0=-180, lon1=181, lat0=-90, lat1=91): 38 | points=[] 39 | linenum = 0 40 | for lat in range(lat0, lat1, 10): 41 | for lon in range(lon0, lon1, 10): 42 | points.append([linenum, lon, lat]) 43 | linenum += 1 44 | 45 | for lon in range(lon0, lon1, 10): 46 | for lat in range(lat0, lat1, 10): 47 | points.append([linenum, lon, lat]) 48 | linenum += 1 49 | 50 | numgraticule = linenum 51 | 52 | driveName = "ESRI Shapefile" 53 | driver = ogr.GetDriverByName(driveName) 54 | vector = driver.Open(fname, 0) 55 | layer = vector.GetLayer(0) 56 | 57 | for i in range(layer.GetFeatureCount()): 58 | f = layer.GetFeature(i) 59 | geom = f.GetGeometryRef() 60 | for i in range(geom.GetPointCount()): 61 | p = geom.GetPoint(i) 62 | points.append([linenum, p[0], p[1]]) 63 | linenum += 1 64 | 65 | # numline = max([p[0] for p in points]) + 1 66 | 67 | return points, numgraticule, linenum 68 | 69 | def prep_projection_data_shapex(fname, lon0=-180, lon1=181, lat0=-90, lat1=91): 70 | points=[] 71 | linenum = 0 72 | for lat in range(lat0, lat1, 10): 73 | for lon in range(lon0, lon1, 10): 74 | points.append([linenum, lon, lat]) 75 | linenum += 1 76 | 77 | for lon in range(lon0, lon1, 10): 78 | for lat in range(lat0, lat1, 10): 79 | points.append([linenum, lon, lat]) 80 | linenum += 1 81 | 82 | numgraticule = linenum 83 | 84 | shpdata = shapex(fname) 85 | for f in shpdata: 86 | geom = f['geometry']['coordinates'] 87 | for p in geom[0]: 88 | points.append([linenum, p[0], p[1]]) 89 | linenum += 1 90 | 91 | return points, numgraticule, linenum 92 | 93 | def prep_projection_data_geojson(fname, lon0=-180, lon1=181, lat0=-90, lat1=91): 94 | points=[] 95 | linenum = 0 96 | for lat in range(lat0, lat1, 10): 97 | for lon in range(lon0, lon1, 10): 98 | points.append([linenum, lon, lat]) 99 | linenum += 1 100 | 101 | for lon in range(lon0, lon1, 10): 102 | for lat in range(lat0, lat1, 10): 103 | points.append([linenum, lon, lat]) 104 | linenum += 1 105 | 106 | numgraticule = linenum 107 | 108 | with open(fname) as json_file: 109 | coastline_obj = json.loads(json_file.read()) 110 | 111 | for f in coastline_obj['features']: 112 | geom = f['geometry']['coordinates'] 113 | for p in geom[0]: 114 | points.append([linenum, p[0], p[1]]) 115 | linenum += 1 116 | 117 | return points, numgraticule, linenum 118 | 119 | def prep_projection_data_url_geojson(url, lon0=-180, lon1=181, lat0=-90, lat1=91): 120 | points=[] 121 | linenum = 0 122 | for lat in range(lat0, lat1, 10): 123 | for lon in range(lon0, lon1, 10): 124 | points.append([linenum, lon, lat]) 125 | linenum += 1 126 | 127 | for lon in range(lon0, lon1, 10): 128 | for lat in range(lat0, lat1, 10): 129 | points.append([linenum, lon, lat]) 130 | linenum += 1 131 | 132 | numgraticule = linenum 133 | 134 | with request.urlopen(url) as response: 135 | coastline_obj = json.loads(response.read()) 136 | 137 | for f in coastline_obj['features']: 138 | geom = f['geometry']['coordinates'] 139 | for p in geom[0]: 140 | points.append([linenum, p[0], p[1]]) 141 | linenum += 1 142 | 143 | return points, numgraticule, linenum 144 | 145 | 146 | def prep_projection_data(fname, lon0=-180, lon1=181, lat0=-90, lat1=91, _use_lib='SHAPEX'): 147 | if use_lib =='OGR' and _use_lib == 'OGR': 148 | return prep_projection_data_ogr(fname, lon0, lon1, lat0, lat1) 149 | elif _use_lib == 'URL': 150 | return prep_projection_data_url_geojson(fname, lon0, lon1, lat0, lat1) 151 | elif _use_lib == 'GEOJSON': 152 | return prep_projection_data_geojson(fname, lon0, lon1, lat0, lat1) 153 | else: 154 | return prep_projection_data_shapex(fname, lon0, lon1, lat0, lat1) 155 | 156 | if __name__ == '__main__': 157 | fname = '../data/ne_110m_coastline.shp' 158 | raw_points, numgraticule, numline = prep_projection_data(fname) 159 | print(len(raw_points)) 160 | print(numgraticule, numline) 161 | print(raw_points[0]) 162 | print(raw_points[3000]) 163 | --------------------------------------------------------------------------------