├── LICENSE.txt ├── README.md ├── pandashp.py ├── pandaspyomo.py ├── pyomotools.py ├── shapelytools.py ├── shptools.py └── skeletrontools.py /LICENSE.txt: -------------------------------------------------------------------------------- 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 -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Python-Tools 2 | 3 | This is a collection of small modules that I often/sometimes/not anymore use for my day-to-day scripting needs. I keep them in a separate directory that I [keep always on the Python search path](http://stackoverflow.com/q/17806673/2375855) so that I can include them like installed site-packages. 4 | 5 | ## Installation(ish) 6 | 7 | I just clone this repo into the directory that is returned by the following Python snippet: 8 | 9 | ```python 10 | import site 11 | print(site.USER_SITE) 12 | ``` 13 | 14 | Depending on your operating system and Python version, this evaluates to 15 | 16 | Windows, Python 3.5: C:\Users\ojdo\AppData\Roaming\Python\Python35\site-packages 17 | Linux, Python 2.7: /home/ojdo/.local/Python27/site-packages 18 | Linux, Python 3.5: /home/ojdo/.local/lib/python3.5/site-packages 19 | 20 | Anyway, open a terminal in that directory (create it if necessary) and clone this repo into that directory: 21 | 22 | git clone https://github.com/ojdo/python-tools.git . 23 | 24 | You should now be able to import any of the following packages. Depending on what you need, you might alternatively just grab one of these files/functions. 25 | 26 | ## Useful packages 27 | 28 | ### pandashp 29 | 30 | Basically my private implementation of a [GeoPandas](http://geopandas.org/) `GeoFrame`. This module provides two functions, `read_shp` and `write_shp`. The first one reads an ESRI shapefile to a pandas DataFrame, saving the geometry information (Points, Lines, Polygons) in the column `geometry`. The second function does the reverse. These functions do not care about transformations, much different to GeoPandas. I plan to migrate to using Geopandas myself, so better don't use these two functions. 31 | 32 | **However**, there is utility function `find_closest_edge`, which looks deceptively simple but took some time to get this "clean". It performs an operation similar to ArcGIS's [Near](http://desktop.arcgis.com/en/arcmap/latest/tools/analysis-toolbox/near.htm) for the special case of matching point features to their nearest line passing by. It heavily relies on several functions implemented in my other toolbox `shapelytools`. 33 | 34 | #### Dependencies 35 | - [pandas](http://pandas.pydata.org/) 36 | - [pyshp](https://github.com/GeospatialPython/pyshp) 37 | - [shapely](https://pypi.python.org/pypi/Shapely) (and `shapelytools` below) 38 | 39 | 40 | ### shapelytools 41 | 42 | Many handy small functions dealing with collections of shapely objects, i.e. points, lines and polygons. I use them to script small geographic algorithms on my own. The module implements a naive nearest neighbor algorithm, pruning of short line segments, finding isolated endpoints among a list of possibly touching lines. 43 | 44 | :!: **Note:** shapely is not aware of geographic coordinates! So while some of these functions might work with lat/lon coordinates in degrees, I use them mainly in projected coordinate systems with x/y coordinates in metres. So use something like GeoPandas' `to_crs` function to convert your geographic (lat, lon) data to a projected (x, y) coordinate system before using anything from this package. 45 | 46 | #### Dependencies 47 | - [shapely](https://pypi.python.org/pypi/Shapely) 48 | 49 | 50 | ### skeletrontools 51 | 52 | Wrapper module that provides function `skeletonize`, which reads in a pandashp DataFrame of road segments and returns a simplified version of it. The most expensive step is the skeletonization of a buffered version of this road network, decorated with some pre- and postprocessing steps. 53 | 54 | #### Dependencies 55 | - `pandashp` above 56 | - [Skeletron](https://pypi.python.org/pypi/Skeletron/0.9.2) and its dependencies, i.e. [qhull](http://qhull.org/) 57 | 58 | 59 | ## Deprecated 60 | 61 | ### pandaspyomo 62 | 63 | Provides functions like `get_entity` to read data from coopr.pyomo models to pandas DataFrames. (Un)fortunately, pyomo changed its internals some time around the 3.5 release version, so these functions don't work with current pyomo versions. See [urbs](https://github.com/tum-ens/urbs) for an up-to-date version of these functions. 64 | 65 | #### Dependencies 66 | - [Coopr](https://software.sandia.gov/trac/coopr/wiki/WikiStart) 67 | - [pandas](http://pandas.pydata.org/) 68 | 69 | 70 | ### pyomotools 71 | 72 | Archive for some misc functions needed for migrating [urbs](https://github.com/tum-ens/urbs) from GAMS to Python. Function `read_xls` for example implements automatic detection of Capital lettre column titles for onset detection. I don't use it any longer, but its functions might remain useful in other contexts. 73 | 74 | #### Dependencies 75 | - [pandas](http://pandas.pydata.org/) 76 | 77 | 78 | ### shptools 79 | 80 | Convenience wrapper of pyshp, including automatic type detection (numeric, string) when reading/writing shapefiles. Might be not needed anymore, but was quite handy when written. This is the predecessor to my `pandashp` toolbox, which itself now is partially unneeded because of GeoPandas. 81 | 82 | #### Dependencies 83 | - [pyshp](https://github.com/GeospatialPython/pyshp) 84 | - [shapely](https://pypi.python.org/pypi/Shapely) (and `shapelytools`) 85 | -------------------------------------------------------------------------------- /pandashp.py: -------------------------------------------------------------------------------- 1 | """ pandashp: read/write shapefiles to/from special DataFrames 2 | 3 | Offers two functions read_shp and write_shp that convert ESRI shapefiles to 4 | pandas DataFrames that can be manipulated at will and then written back to 5 | shapefiles. Opens up data manipulation capabilities beyond a simple GIS field 6 | calculator. 7 | 8 | Usage: 9 | import pandashp as pdshp 10 | # calculate population density from shapefile of cities (stupid, I know) 11 | cities = pdshp.read_shp('cities_germany_projected') 12 | cities['popdens'] = cities['population'] / cities['area'] 13 | pdshp.write_shp(cities, 'cities_germany_projected_popdens') 14 | 15 | """ 16 | 17 | try: 18 | from itertools import izip as zip 19 | except ImportError: # zip is a builtin in Python 3.x 20 | pass 21 | import numpy as np 22 | import pandas as pd 23 | import shapefile 24 | import shapelytools 25 | import warnings 26 | from shapely.geometry import LineString, Point, Polygon 27 | 28 | def read_shp(filename): 29 | """Read shapefile to dataframe w/ geometry. 30 | 31 | Args: 32 | filename: ESRI shapefile name to be read (without .shp extension) 33 | 34 | Returns: 35 | pandas DataFrame with column geometry, containing individual shapely 36 | Geometry objects (i.e. Point, LineString, Polygon) depending on 37 | the shapefiles original shape type 38 | 39 | """ 40 | sr = shapefile.Reader(filename) 41 | 42 | cols = sr.fields[:] # [:] = duplicate field list 43 | if cols[0][0] == 'DeletionFlag': 44 | cols.pop(0) 45 | cols = [col[0] for col in cols] # extract field name only 46 | cols.append('geometry') 47 | 48 | records = [row for row in sr.iterRecords()] 49 | 50 | if sr.shapeType == shapefile.POLYGON: 51 | geometries = [Polygon(shape.points) 52 | if len(shape.points) > 2 else np.NaN # invalid geometry 53 | for shape in sr.iterShapes()] 54 | elif sr.shapeType == shapefile.POLYLINE: 55 | geometries = [LineString(shape.points) for shape in sr.iterShapes()] 56 | elif sr.shapeType == shapefile.POINT: 57 | geometries = [Point(*shape.points[0]) for shape in sr.iterShapes()] 58 | else: 59 | raise NotImplementedError 60 | 61 | data = [r+[g] for r,g in zip(records, geometries)] 62 | 63 | df = pd.DataFrame(data, columns=cols) 64 | df = df.convert_objects(convert_numeric=True) 65 | 66 | if np.NaN in geometries: 67 | # drop invalid geometries 68 | df = df.dropna(subset=['geometry']) 69 | num_skipped = len(geometries) - len(df) 70 | warnings.warn('Skipped {} invalid geometrie(s).'.format(num_skipped)) 71 | return df 72 | 73 | def write_shp(filename, dataframe, write_index=True): 74 | """Write dataframe w/ geometry to shapefile. 75 | 76 | Args: 77 | filename: ESRI shapefile name to be written (without .shp extension) 78 | dataframe: a pandas DataFrame with column geometry and homogenous 79 | shape types (Point, LineString, or Polygon) 80 | write_index: add index as column to attribute tabel (default: true) 81 | 82 | Returns: 83 | Nothing. 84 | 85 | """ 86 | 87 | df = dataframe.copy() 88 | if write_index: 89 | df.reset_index(inplace=True) 90 | 91 | # split geometry column from dataframe 92 | geometry = df.pop('geometry') 93 | 94 | # write geometries to shp/shx, according to geometry type 95 | if isinstance(geometry.iloc[0], Point): 96 | sw = shapefile.Writer(shapefile.POINT) 97 | for point in geometry: 98 | sw.point(point.x, point.y) 99 | 100 | elif isinstance(geometry.iloc[0], LineString): 101 | sw = shapefile.Writer(shapefile.POLYLINE) 102 | for line in geometry: 103 | sw.line([list(line.coords)]) 104 | 105 | elif isinstance(geometry.iloc[0], Polygon): 106 | sw = shapefile.Writer(shapefile.POLYGON) 107 | for polygon in geometry: 108 | sw.poly([list(polygon.exterior.coords)]) 109 | else: 110 | raise NotImplementedError 111 | 112 | # add fields for dbf 113 | for k, column in enumerate(df.columns): 114 | column = str(column) # unicode strings freak out pyshp, so remove u'..' 115 | 116 | if np.issubdtype(df.dtypes[k], np.number): 117 | # detect and convert integer-only columns 118 | if (df[column] % 1 == 0).all(): 119 | df[column] = df[column].astype(np.integer) 120 | 121 | # now create the appropriate fieldtype 122 | if np.issubdtype(df.dtypes[k], np.floating): 123 | sw.field(column, 'N', decimal=5) 124 | else: 125 | sw.field(column, 'I', decimal=0) 126 | else: 127 | sw.field(column) 128 | 129 | # add records to dbf 130 | for record in df.itertuples(): 131 | sw.record(*record[1:]) # drop first tuple element (=index) 132 | 133 | sw.save(filename) 134 | 135 | 136 | def match_vertices_and_edges(vertices, edges, vertex_cols=('Vertex1', 'Vertex2')): 137 | """Adds unique IDs to vertices and corresponding edges. 138 | 139 | Identifies, which nodes coincide with the endpoints of edges and creates 140 | matching IDs for matching points, thus creating a node-edge graph whose 141 | edges are encoded purely by node ID pairs. The optional argument 142 | vertex_cols specifies which DataFrame columns of edges are added, default 143 | is 'Vertex1' and 'Vertex2'. 144 | 145 | Args: 146 | vertices: pandas DataFrame with geometry column of type Point 147 | edges: pandas DataFrame with geometry column of type LineString 148 | vertex_cols: tuple of 2 strings for the IDs numbers 149 | 150 | Returns: 151 | Nothing, the mathing IDs are added to the columns vertex_cols in 152 | argument edges 153 | """ 154 | 155 | vertex_indices = [] 156 | for e, line in enumerate(edges.geometry): 157 | edge_endpoints = [] 158 | for k, vertex in enumerate(vertices.geometry): 159 | if line.touches(vertex) or line.intersects(vertex): 160 | edge_endpoints.append(vertices.index[k]) 161 | 162 | if len(edge_endpoints) == 0: 163 | warnings.warn("edge " + str(e) + " has no endpoints: " + str(edge_endpoints)) 164 | elif len(edge_endpoints) == 1: 165 | warnings.warn("edge " + str(e) + " has only 1 endpoint: " + str(edge_endpoints)) 166 | 167 | vertex_indices.append(edge_endpoints) 168 | 169 | edges[vertex_cols[0]] = pd.Series([min(n1n2) for n1n2 in vertex_indices], 170 | index=edges.index) 171 | edges[vertex_cols[1]] = pd.Series([max(n1n2) for n1n2 in vertex_indices], 172 | index=edges.index) 173 | 174 | def find_closest_edge(polygons, edges, to_attr='index', column='nearest'): 175 | """Find closest edge for centroid of polygons. 176 | 177 | Args: 178 | polygons: a pandas DataFrame with geometry column of Polygons 179 | edges: a pandas DataFrame with geometry column of LineStrings 180 | to_attr: a column name in DataFrame edges (default: index) 181 | column: a column name to be added/overwrite in DataFrame polygons with 182 | the value of column to_attr from the nearest edge in edges 183 | 184 | Returns: 185 | a list of LineStrings connecting polygons' centroids with the nearest 186 | point in in edges. Side effect: polygons recieves new column with the 187 | attribute value of nearest edge. Warning: if column exists, it is 188 | overwritten. 189 | """ 190 | 191 | connecting_lines = [] 192 | nearest_indices = [] 193 | centroids = [b.centroid for b in polygons['geometry']] 194 | 195 | for centroid in centroids: 196 | nearest_edge, _, nearest_index = shapelytools.closest_object( 197 | edges['geometry'], centroid) 198 | nearest_point = shapelytools.project_point_to_object(centroid, nearest_edge) 199 | 200 | connecting_lines.append(LineString(tuple(centroid.coords) + 201 | tuple(nearest_point.coords))) 202 | 203 | nearest_indices.append(edges[to_attr][nearest_index]) 204 | 205 | polygons[column] = pd.Series(nearest_indices, index=polygons.index) 206 | 207 | return pd.DataFrame({'geometry': connecting_lines}) 208 | 209 | def bounds(df): 210 | """Return a DataFrame of minx, miny, maxx, maxy of each geometry.""" 211 | bounds = np.array([geom.bounds for geom in df.geometry]) 212 | return pd.DataFrame(bounds, 213 | columns=['minx', 'miny', 'maxx', 'maxy'], 214 | index=df.index) 215 | 216 | def total_bounds(df): 217 | """Return bounding box (minx, miny, maxx, maxy) of all geometries. """ 218 | b = bounds(df) 219 | return (b['minx'].min(), 220 | b['miny'].min(), 221 | b['maxx'].max(), 222 | b['maxy'].max()) 223 | -------------------------------------------------------------------------------- /pandaspyomo.py: -------------------------------------------------------------------------------- 1 | """ pandaspyomo: read data from coopr.pyomo models to pandas DataFrames 2 | 3 | Pyomo is a GAMS-like model description language for mathematical 4 | optimization problems. This module provides functions to read data from 5 | Pyomo model instances and result objects. Use list_entities to get a list 6 | of all entities (sets, params, variables, objectives or constraints) inside a 7 | pyomo instance, before get its contents by get_entity (or get_entities). 8 | 9 | Usage: 10 | import pandaspyomo as pdpo 11 | pdpo.list_entities(instance, 'var') 12 | [('EprOut', ['time', 'process', 'commodity', 'commodity']), ... 13 | ('EprIn', ['time', 'process', 'commodity', 'commodity'])] 14 | epr = pdpo.get_entities(instance, ['EprOut', 'EprInt']) 15 | ... 16 | 17 | """ 18 | 19 | import coopr.pyomo as pyomo 20 | import pandas as pd 21 | 22 | def get_entity(instance, name): 23 | """ Return a DataFrame for an entity in model instance. 24 | 25 | Args: 26 | instance: a Pyomo ConcreteModel instance 27 | name: name of a Set, Param, Var, Constraint or Objective 28 | 29 | Returns: 30 | a single-columned Pandas DataFrame with domain as index 31 | """ 32 | 33 | # retrieve entity, its type and its onset names 34 | entity = instance.__getattribute__(name) 35 | labels = _get_onset_names(entity) 36 | 37 | # extract values 38 | if isinstance(entity, pyomo.Set): 39 | # Pyomo sets don't have values, only elements 40 | results = pd.DataFrame([(v, 1) for v in entity.value]) 41 | 42 | # for unconstrained sets, the column label is identical to their index 43 | # hence, make index equal to entity name and append underscore to name 44 | # (=the later column title) to preserve identical index names for both 45 | # unconstrained supersets 46 | if not labels: 47 | labels = [name] 48 | name = name+'_' 49 | 50 | elif isinstance(entity, pyomo.Param): 51 | if entity.dim() > 1: 52 | results = pd.DataFrame([v[0]+(v[1],) for v in entity.iteritems()]) 53 | else: 54 | results = pd.DataFrame(entity.iteritems()) 55 | else: 56 | # create DataFrame 57 | if entity.dim() > 1: 58 | # concatenate index tuples with value if entity has 59 | # multidimensional indices v[0] 60 | results = pd.DataFrame( 61 | [v[0]+(v[1].value,) for v in entity.iteritems()]) 62 | else: 63 | # otherwise, create tuple from scalar index v[0] 64 | results = pd.DataFrame( 65 | [(v[0], v[1].value) for v in entity.iteritems()]) 66 | 67 | # check for duplicate onset names and append one to several "_" to make 68 | # them unique, e.g. ['sit', 'sit', 'com'] becomes ['sit', 'sit_', 'com'] 69 | for k, label in enumerate(labels): 70 | if label in labels[:k]: 71 | labels[k] = labels[k] + "_" 72 | 73 | if not results.empty: 74 | # name columns according to labels + entity name 75 | results.columns = labels + [name] 76 | results.set_index(labels, inplace=True) 77 | 78 | return results 79 | 80 | 81 | def get_entities(instance, names): 82 | """ Return one DataFrame with entities in columns and a common index. 83 | 84 | Works only on entities that share a common domain (set or set_tuple), which 85 | is used as index of the returned DataFrame. 86 | 87 | Args: 88 | instance: a Pyomo ConcreteModel instance 89 | names: list of entity names (as returned by list_entities) 90 | 91 | Returns: 92 | a Pandas DataFrame with entities as columns and domains as index 93 | """ 94 | 95 | df = pd.DataFrame() 96 | for name in names: 97 | other = get_entity(instance, name) 98 | 99 | if df.empty: 100 | df = other 101 | else: 102 | index_names_before = df.index.names 103 | 104 | df = df.join(other, how='outer') 105 | 106 | if index_names_before != df.index.names: 107 | df.index.names = index_names_before 108 | 109 | return df 110 | 111 | 112 | def list_entities(instance, entity_type): 113 | """ Return list of sets, params, variables, constraints or objectives 114 | 115 | Args: 116 | instance: a Pyomo ConcreteModel object 117 | entity_type: "set", "par", "var", "con" or "obj" 118 | 119 | Returns: 120 | DataFrame of entities 121 | 122 | Example: 123 | >>> data = read_excel('mimo-example.xlsx') 124 | >>> model = create_model(data, range(1,25)) 125 | >>> list_entities(model, 'obj') #doctest: +NORMALIZE_WHITESPACE 126 | Description Domain 127 | Name 128 | obj minimize(cost = sum of all cost types) [] 129 | 130 | """ 131 | 132 | # helper function to discern entities by type 133 | def filter_by_type(entity, entity_type): 134 | if entity_type == 'set': 135 | return isinstance(entity, pyomo.Set) and not entity.virtual 136 | elif entity_type == 'par': 137 | return isinstance(entity, pyomo.Param) 138 | elif entity_type == 'var': 139 | return isinstance(entity, pyomo.Var) 140 | elif entity_type == 'con': 141 | return isinstance(entity, pyomo.Constraint) 142 | elif entity_type == 'obj': 143 | return isinstance(entity, pyomo.Objective) 144 | else: 145 | raise ValueError("Unknown entity_type '{}'".format(entity_type)) 146 | 147 | # iterate through all model components and keep only 148 | iter_entities = instance.__dict__.iteritems() 149 | entities = sorted( 150 | (name, entity.doc, _get_onset_names(entity)) 151 | for (name, entity) in iter_entities 152 | if filter_by_type(entity, entity_type)) 153 | 154 | # if something was found, wrap tuples in DataFrame, otherwise return empty 155 | if entities: 156 | entities = pd.DataFrame(entities, 157 | columns=['Name', 'Description', 'Domain']) 158 | entities.set_index('Name', inplace=True) 159 | else: 160 | entities = pd.DataFrame() 161 | return entities 162 | 163 | 164 | def _get_onset_names(entity): 165 | """ 166 | Example: 167 | >>> data = read_excel('mimo-example.xlsx') 168 | >>> model = create_model(data, range(1,25)) 169 | >>> _get_onset_names(model.e_co_stock) 170 | ['t', 'sit', 'com', 'com_type'] 171 | """ 172 | # get column titles for entities from domain set names 173 | labels = [] 174 | 175 | if isinstance(entity, pyomo.Set): 176 | if entity.dimen > 1: 177 | # N-dimensional set tuples, possibly with nested set tuples within 178 | if entity.domain: 179 | domains = entity.domain.set_tuple 180 | else: 181 | domains = entity.set_tuple 182 | 183 | for domain_set in domains: 184 | labels.extend(_get_onset_names(domain_set)) 185 | 186 | elif entity.dimen == 1: 187 | if entity.domain: 188 | # 1D subset; add domain name 189 | labels.append(entity.domain.name) 190 | else: 191 | # unrestricted set; add entity name 192 | labels.append(entity.name) 193 | else: 194 | # no domain, so no labels needed 195 | pass 196 | 197 | elif isinstance(entity, (pyomo.Param, pyomo.Var, pyomo.Constraint, 198 | pyomo.Objective)): 199 | if entity.dim() > 0 and entity._index: 200 | labels = _get_onset_names(entity._index) 201 | else: 202 | # zero dimensions, so no onset labels 203 | pass 204 | 205 | else: 206 | raise ValueError("Unknown entity type!") 207 | 208 | return labels -------------------------------------------------------------------------------- /pyomotools.py: -------------------------------------------------------------------------------- 1 | """ pyomotools: common helper functions for pyomo model creation """ 2 | from datetime import datetime 3 | import pandas as pd 4 | import xlrd 5 | 6 | __all__ = ["now", "read_xls"] 7 | 8 | def now(mydateformat='%Y%m%dT%H%M%S'): 9 | """ Return current datetime as string. 10 | 11 | Just a shorthand to abbreviate the common task to obtain the current 12 | datetime as a string, e.g. for result versioning. 13 | 14 | Args: 15 | mydateformat: optional format string (default: '%Y%m%dT%H%M%S') 16 | 17 | Returns: 18 | datetime.now(), formated to string with argument mydateformat, e.g. 19 | YYYYMMDDThhmmss ==> 20131007H123456 20 | """ 21 | return datetime.now().strftime(mydateformat) 22 | 23 | 24 | def read_xls(filename, sheets=[]): 25 | """ Convert Excel file to dict of pandas DataFrames. 26 | 27 | Parses all spreadsheets within an Excel file using pandas.ExcelFile.parse, 28 | if its top left cell is not empty. The first row is expected to contain 29 | column titles. Titles starting with uppercase lettres are used as index 30 | columns in the resulting DataFrame. Here is a short example summarizing 31 | these specifications: 32 | 33 | Process CoIn CoOut | cap eff ... avail 34 | ------------------------------------------- 35 | PP Coal Elec | 100 0.90 ... 24 36 | WT Wind Elec | 300 0.95 ... 10 37 | PV Solar Elec | 200 0.92 ... 8 38 | 39 | A spreadsheet is skipped if a) it is completely empty or b) has an empty 40 | first row. 41 | 42 | Args: 43 | filename: an Excel spreadsheet filename 44 | 45 | Returns: 46 | dict of pandas DataFrames with sheet names as keys 47 | """ 48 | 49 | dfs = {} 50 | xls = pd.ExcelFile(filename) 51 | for sheet in xls.book.sheets(): 52 | # skip sheet if list of sheets was specified 53 | if sheets and sheet.name not in sheets: 54 | continue 55 | 56 | # extract the sheet's first row to check for emptiness 57 | first_row = sheet.row_slice(0) 58 | 59 | # skip a spreadsheet if completely empty or its first cell is blank 60 | if not first_row \ 61 | or first_row[0].ctype in (xlrd.XL_CELL_BLANK, xlrd.XL_CELL_EMPTY): 62 | continue 63 | 64 | # otherwise determine column numbers of titles starting with an 65 | # uppercase lettre while skipping empty columns 66 | uppercase_columns = [k for k, column_title in enumerate(first_row) 67 | if column_title.value 68 | and column_title.value[0].isupper()] 69 | 70 | # parse those columns to a pandas DataFrame 71 | df = xls.parse(sheet.name, index_col=uppercase_columns) 72 | 73 | # and prune any columns with only NaN values 74 | # these are mainly empty columns 75 | dfs[sheet.name] = df.dropna(axis=1, how='all') 76 | 77 | return dfs -------------------------------------------------------------------------------- /shapelytools.py: -------------------------------------------------------------------------------- 1 | from shapely.geometry import (box, LineString, MultiLineString, MultiPoint, 2 | Point, Polygon) 3 | import shapely.ops 4 | 5 | def endpoints_from_lines(lines): 6 | """Return list of terminal points from list of LineStrings.""" 7 | 8 | all_points = [] 9 | for line in lines: 10 | for i in [0, -1]: # start and end point 11 | all_points.append(line.coords[i]) 12 | 13 | unique_points = set(all_points) 14 | 15 | return [Point(p) for p in unique_points] 16 | 17 | def vertices_from_lines(lines): 18 | """Return list of unique vertices from list of LineStrings.""" 19 | 20 | vertices = [] 21 | for line in lines: 22 | vertices.extend(list(line.coords)) 23 | return [Point(p) for p in set(vertices)] 24 | 25 | 26 | def prune_short_lines(lines, min_length): 27 | """Remove lines from a LineString DataFrame shorter than min_length. 28 | 29 | Deletes all lines from a list of LineStrings or a MultiLineString 30 | that have a total length of less than min_length. Vertices of touching 31 | lines are contracted towards the centroid of the removed line. 32 | 33 | Args: 34 | lines: list of LineStrings or a MultiLineString 35 | min_length: minimum length of a single LineString to be preserved 36 | 37 | Returns: 38 | the pruned pandas DataFrame 39 | """ 40 | pruned_lines = [line for line in lines] # converts MultiLineString to list 41 | to_prune = [] 42 | 43 | for i, line in enumerate(pruned_lines): 44 | if line.length < min_length: 45 | to_prune.append(i) 46 | for n in neighbors(pruned_lines, line): 47 | contact_point = line.intersection(pruned_lines[n]) 48 | pruned_lines[n] = bend_towards(pruned_lines[n], 49 | where=contact_point, 50 | to=line.centroid) 51 | 52 | return [line for i, line in enumerate(pruned_lines) if i not in to_prune] 53 | 54 | 55 | def neighbors(lines, of): 56 | """Find the indices in a list of LineStrings that touch a given LineString. 57 | 58 | Args: 59 | lines: list of LineStrings in which to search for neighbors 60 | of: the LineString which must be touched 61 | 62 | Returns: 63 | list of indices, so that all lines[indices] touch the LineString of 64 | """ 65 | return [k for k, line in enumerate(lines) if line.touches(of)] 66 | 67 | 68 | def bend_towards(line, where, to): 69 | """Move the point where along a line to the point at location to. 70 | 71 | Args: 72 | line: a LineString 73 | where: a point ON the line (not necessarily a vertex) 74 | to: a point NOT on the line where the nearest vertex will be moved to 75 | 76 | Returns: 77 | the modified (bent) line 78 | """ 79 | 80 | if not line.contains(where) and not line.touches(where): 81 | raise ValueError('line does not contain the point where.') 82 | 83 | coords = line.coords[:] 84 | # easy case: where is (within numeric precision) a vertex of line 85 | for k, vertex in enumerate(coords): 86 | if where.almost_equals(Point(vertex)): 87 | # move coordinates of the vertex to destination 88 | coords[k] = to.coords[0] 89 | return LineString(coords) 90 | 91 | # hard case: where lies between vertices of line, so 92 | # find nearest vertex and move that one to point to 93 | _, min_k = min((where.distance(Point(vertex)), k) 94 | for k, vertex in enumerate(coords)) 95 | coords[min_k] = to.coords[0] 96 | return LineString(coords) 97 | 98 | 99 | def snappy_endings(lines, max_distance): 100 | """Snap endpoints of lines together if they are at most max_length apart. 101 | 102 | Args: 103 | lines: a list of LineStrings or a MultiLineString 104 | max_distance: maximum distance two endpoints may be joined together 105 | """ 106 | 107 | # initialize snapped lines with list of original lines 108 | # snapping points is a MultiPoint object of all vertices 109 | snapped_lines = [line for line in lines] 110 | snapping_points = vertices_from_lines(snapped_lines) 111 | 112 | # isolated endpoints are going to snap to the closest vertex 113 | isolated_endpoints = find_isolated_endpoints(snapped_lines) 114 | 115 | # only move isolated endpoints, one by one 116 | for endpoint in isolated_endpoints: 117 | # find all vertices within a radius of max_distance as possible 118 | target = nearest_neighbor_within(snapping_points, endpoint, 119 | max_distance) 120 | 121 | # do nothing if no target point to snap to is found 122 | if not target: 123 | continue 124 | 125 | # find the LineString to modify within snapped_lines and update it 126 | for i, snapped_line in enumerate(snapped_lines): 127 | if endpoint.touches(snapped_line): 128 | snapped_lines[i] = bend_towards(snapped_line, where=endpoint, 129 | to=target) 130 | break 131 | 132 | # also update the corresponding snapping_points 133 | for i, snapping_point in enumerate(snapping_points): 134 | if endpoint.equals(snapping_point): 135 | snapping_points[i] = target 136 | break 137 | 138 | # post-processing: remove any resulting lines of length 0 139 | snapped_lines = [s for s in snapped_lines if s.length > 0] 140 | 141 | return snapped_lines 142 | 143 | 144 | def nearest_neighbor_within(others, point, max_distance): 145 | """Find nearest point among others up to a maximum distance. 146 | 147 | Args: 148 | others: a list of Points or a MultiPoint 149 | point: a Point 150 | max_distance: maximum distance to search for the nearest neighbor 151 | 152 | Returns: 153 | A shapely Point if one is within max_distance, None otherwise 154 | """ 155 | search_region = point.buffer(max_distance) 156 | interesting_points = search_region.intersection(MultiPoint(others)) 157 | 158 | if not interesting_points: 159 | closest_point = None 160 | elif isinstance(interesting_points, Point): 161 | closest_point = interesting_points 162 | else: 163 | distances = [point.distance(ip) for ip in interesting_points 164 | if point.distance(ip) > 0] 165 | closest_point = interesting_points[distances.index(min(distances))] 166 | 167 | return closest_point 168 | 169 | 170 | def find_isolated_endpoints(lines): 171 | """Find endpoints of lines that don't touch another line. 172 | 173 | Args: 174 | lines: a list of LineStrings or a MultiLineString 175 | 176 | Returns: 177 | A list of line end Points that don't touch any other line of lines 178 | """ 179 | 180 | isolated_endpoints = [] 181 | for i, line in enumerate(lines): 182 | other_lines = lines[:i] + lines[i+1:] 183 | for q in [0,-1]: 184 | endpoint = Point(line.coords[q]) 185 | if any(endpoint.touches(another_line) 186 | for another_line in other_lines): 187 | continue 188 | else: 189 | isolated_endpoints.append(endpoint) 190 | return isolated_endpoints 191 | 192 | def closest_object(geometries, point): 193 | """Find the nearest geometry among a list, measured from fixed point. 194 | 195 | Args: 196 | geometries: a list of shapely geometry objects 197 | point: a shapely Point 198 | 199 | Returns: 200 | Tuple (geom, min_dist, min_index) of the geometry with minimum distance 201 | to point, its distance min_dist and the list index of geom, so that 202 | geom = geometries[min_index]. 203 | """ 204 | min_dist, min_index = min((point.distance(geom), k) 205 | for (k, geom) in enumerate(geometries)) 206 | 207 | return geometries[min_index], min_dist, min_index 208 | 209 | 210 | def project_point_to_line(point, line_start, line_end): 211 | """Find nearest point on a straight line, measured from given point. 212 | 213 | Args: 214 | point: a shapely Point object 215 | line_start: the line starting point as a shapely Point 216 | line_end: the line end point as a shapely Point 217 | 218 | Returns: 219 | a shapely Point that lies on the straight line closest to point 220 | 221 | Source: http://gis.stackexchange.com/a/438/19627 222 | """ 223 | line_magnitude = line_start.distance(line_end) 224 | 225 | u = ((point.x - line_start.x) * (line_end.x - line_start.x) + 226 | (point.y - line_start.y) * (line_end.y - line_start.y)) \ 227 | / (line_magnitude ** 2) 228 | 229 | # closest point does not fall within the line segment, 230 | # take the shorter distance to an endpoint 231 | if u < 0.00001 or u > 1: 232 | ix = point.distance(line_start) 233 | iy = point.distance(line_end) 234 | if ix > iy: 235 | return line_end 236 | else: 237 | return line_start 238 | else: 239 | ix = line_start.x + u * (line_end.x - line_start.x) 240 | iy = line_start.y + u * (line_end.y - line_start.y) 241 | return Point([ix, iy]) 242 | 243 | def pairs(lst): 244 | """Iterate over a list in overlapping pairs. 245 | 246 | Args: 247 | lst: an iterable/list 248 | 249 | Returns: 250 | Yields a pair of consecutive elements (lst[k], lst[k+1]) of lst. Last 251 | call yields (lst[-2], lst[-1]). 252 | 253 | Example: 254 | lst = [4, 7, 11, 2] 255 | pairs(lst) yields (4, 7), (7, 11), (11, 2) 256 | 257 | Source: 258 | http://stackoverflow.com/questions/1257413/1257446#1257446 259 | """ 260 | i = iter(lst) 261 | prev = next(i) 262 | for item in i: 263 | yield prev, item 264 | prev = item 265 | 266 | 267 | def project_point_to_object(point, geometry): 268 | """Find nearest point in geometry, measured from given point. 269 | 270 | Args: 271 | point: a shapely Point 272 | geometry: a shapely geometry object (LineString, Polygon) 273 | 274 | Returns: 275 | a shapely Point that lies on geometry closest to point 276 | """ 277 | nearest_point = None 278 | min_dist = float("inf") 279 | 280 | if isinstance(geometry, Polygon): 281 | for seg_start, seg_end in pairs(list(geometry.exterior.coords)): 282 | line_start = Point(seg_start) 283 | line_end = Point(seg_end) 284 | 285 | intersection_point = project_point_to_line(point, line_start, line_end) 286 | cur_dist = point.distance(intersection_point) 287 | 288 | if cur_dist < min_dist: 289 | min_dist = cur_dist 290 | nearest_point = intersection_point 291 | 292 | elif isinstance(geometry, LineString): 293 | for seg_start, seg_end in pairs(list(geometry.coords)): 294 | line_start = Point(seg_start) 295 | line_end = Point(seg_end) 296 | 297 | intersection_point = project_point_to_line(point, line_start, line_end) 298 | cur_dist = point.distance(intersection_point) 299 | 300 | if cur_dist < min_dist: 301 | min_dist = cur_dist 302 | nearest_point = intersection_point 303 | else: 304 | raise NotImplementedError("project_point_to_object not implemented for"+ 305 | " geometry type '" + geometry.type + "'.") 306 | return nearest_point 307 | 308 | 309 | def one_linestring_per_intersection(lines): 310 | """ Move line endpoints to intersections of line segments. 311 | 312 | Given a list of touching or possibly intersecting LineStrings, return a 313 | list LineStrings that have their endpoints at all crossings and 314 | intersecting points and ONLY there. 315 | 316 | Args: 317 | a list of LineStrings or a MultiLineString 318 | 319 | Returns: 320 | a list of LineStrings 321 | """ 322 | lines_merged = shapely.ops.linemerge(lines) 323 | 324 | # intersecting multiline with its bounding box somehow triggers a first 325 | bounding_box = box(*lines_merged.bounds) 326 | 327 | # perform linemerge (one linestring between each crossing only) 328 | # if this fails, write function to perform this on a bbox-grid and then 329 | # merge the result 330 | lines_merged = lines_merged.intersection(bounding_box) 331 | lines_merged = shapely.ops.linemerge(lines_merged) 332 | return lines_merged 333 | 334 | 335 | def linemerge(linestrings_or_multilinestrings): 336 | """ Merge list of LineStrings and/or MultiLineStrings. 337 | 338 | Given a list of LineStrings and possibly MultiLineStrings, merge all of 339 | them to a single MultiLineString. 340 | 341 | Args: 342 | list of LineStrings and/or MultiLineStrings 343 | 344 | Returns: 345 | a merged LineString or MultiLineString 346 | """ 347 | lines = [] 348 | for line in linestrings_or_multilinestrings: 349 | if isinstance(line, MultiLineString): 350 | # line is a multilinestring, so append its components 351 | lines.extend(line) 352 | else: 353 | # line is a line, so simply append it 354 | lines.append(line) 355 | 356 | return shapely.ops.linemerge(lines) 357 | 358 | -------------------------------------------------------------------------------- /shptools.py: -------------------------------------------------------------------------------- 1 | import itertools 2 | import shapefile 3 | from shapely.geometry import Polygon, MultiLineString, LineString, Point 4 | import pdb 5 | 6 | def read_shp(filename): 7 | """Read contents of a shapefile to a shapely geometry object. 8 | 9 | Usage: 10 | geometries = read_shp(filename) 11 | (geometries, records, fields) = read_shp(filename) 12 | 13 | Arguments: 14 | filename shapefile name 15 | 16 | Returns: 17 | geometries list of shapely geometries (Polygon, LineString, ...) 18 | records list of records (list of values), one per geometry 19 | fields list of fieldnames of a record 20 | """ 21 | sr = shapefile.Reader(filename) 22 | 23 | if sr.shapeType == shapefile.POLYGON: 24 | shapes = sr.shapes() 25 | geometries = [Polygon(shape.points) for shape in shapes] 26 | 27 | fields = sr.fields[:] 28 | if fields[0][0] == 'DeletionFlag': 29 | fields.pop(0) 30 | fields = [field[0] for field in fields] # extract field name only 31 | 32 | records = [] 33 | for record in sr.records(): 34 | for i, value in enumerate(record): 35 | try: 36 | record[i] = float(value) # convert record values to numeric... 37 | except ValueError: 38 | pass # ... if possible 39 | 40 | records.append(record) 41 | 42 | return (geometries, records, fields) 43 | 44 | elif sr.shapeType == shapefile.POLYLINE: 45 | shapes = sr.shapes() 46 | geometries = [LineString(shape.points) for shape in shapes] 47 | 48 | fields = sr.fields[:] # [:] = duplicate field list 49 | if fields[0][0] == 'DeletionFlag': 50 | fields.pop(0) 51 | fields = [field[0] for field in fields] # extract field name only 52 | 53 | records = [] 54 | for record in sr.records(): 55 | for i, value in enumerate(record): 56 | try: 57 | record[i] = float(value) # convert record values to numeric... 58 | except ValueError: 59 | pass # ... if possible 60 | 61 | records.append(record) 62 | 63 | return (geometries, records, fields) 64 | 65 | 66 | elif sr.shapeType == shapefile.MULTIPOINT: 67 | raise NotImplementedError 68 | 69 | else: 70 | raise NotImplementedError 71 | 72 | 73 | 74 | 75 | 76 | def write_shp(filename, geometry, records=[], fields=[]): 77 | """Write a single shapely MultiLineString or Polygon to a shapefile. 78 | 79 | Argument geometry may also be a list of LineString objects. In that case, 80 | each entry may have associated data in the optional records list. If 81 | records is given, fields is the list of fieldnames for the value list in 82 | each record. 83 | 84 | Usage: 85 | write_shp(filename, geometry, records=[], fields=[]) 86 | 87 | Arguments: 88 | filename filename of shapefile 89 | geometry a shapely geometry (MultiLineString, Polygon, ...) 90 | records optional list of list of values, one per geometry 91 | fields optional (implied by records) list of fieldnames 92 | """ 93 | 94 | # SINGLE MULTILINESTRING 95 | if isinstance(geometry, MultiLineString): 96 | sw = shapefile.Writer(shapefile.POLYLINE) 97 | 98 | # fields 99 | sw.field("length") 100 | sw.field("start-x") 101 | sw.field("start-y") 102 | sw.field("end-x") 103 | sw.field("end-y") 104 | sw.field("npoints") 105 | 106 | # geometry and record 107 | for line in geometry: 108 | sw.line([list(line.coords)]) 109 | sw.record(line.length, 110 | line.coords[0][0], 111 | line.coords[0][1], 112 | line.coords[-1][0], 113 | line.coords[-1][1], 114 | len(line.coords)) 115 | sw.save(filename) 116 | 117 | # SINGLE POLYGON 118 | elif isinstance(geometry, Polygon): 119 | # data 120 | parts = [list(geometry.exterior.coords)] 121 | parts.extend(list(interior.coords) for interior in geometry.interiors) 122 | 123 | sw = shapefile.Writer(shapefile.POLYGON) 124 | sw.field("area") 125 | sw.poly(parts) 126 | sw.record(geometry.area) 127 | sw.save(filename) 128 | 129 | # LISTS 130 | elif isinstance(geometry, list): 131 | 132 | # check for fields and records 133 | if (fields and not records) or (not fields and records): 134 | raise ValueError('Arguments records and fields must both be provided.') 135 | 136 | if records and (len(fields) != len(records[0])): 137 | raise ValueError('Length of fields and records do not match.') 138 | 139 | # derive field types based on record values 140 | field_type = {} 141 | precision = {} 142 | for i, field in enumerate(fields): 143 | if all(type(record[i]) in [int, long] for record in records): 144 | field_type[field] = 'N' # integers 145 | precision[field] = 0 146 | elif all(type(record[i]) in [int, long, float] for record in records): 147 | field_type[field] = 'N' # numeric 148 | precision[field] = 5 149 | else: 150 | field_type[field] = 'C' # string (characters) 151 | precision[field] = 0 152 | 153 | 154 | # LIST OF LINESTRINGS 155 | if isinstance(geometry[0], LineString): 156 | sw = shapefile.Writer(shapefile.POLYLINE) 157 | 158 | # fields 159 | for field in fields: 160 | sw.field(field, field_type[field], decimal=precision[field]) 161 | 162 | if not fields: 163 | # add dummy length field and prepare records for it 164 | records = [[line.length] for line in geometry] 165 | sw.field('length', 'N', decimal=5) 166 | 167 | # geometry and records 168 | for line, record in itertools.izip(geometry, records): 169 | sw.line([list(line.coords)]) 170 | sw.record(*record) 171 | 172 | sw.save(filename) 173 | 174 | # LIST OF POLYGONS 175 | elif isinstance(geometry[0], Polygon): 176 | sw = shapefile.Writer(shapefile.POLYGON) 177 | 178 | # fields 179 | for field in fields: 180 | sw.field(field, field_type[field], decimal=precision[field]) 181 | 182 | # geometry and records 183 | for polygon, record in itertools.izip(geometry, records): 184 | sw.poly([list(polygon.exterior.coords)]) 185 | sw.record(*record) 186 | 187 | sw.save(filename) 188 | 189 | # LIST OF POINTS 190 | elif isinstance(geometry[0], Point): 191 | sw = shapefile.Writer(shapefile.POINT) 192 | 193 | # fields 194 | for field in fields: 195 | sw.field(field, field_type[field], decimal=precision[field]) 196 | 197 | if not fields: 198 | # add dummy length field and prepare records for it 199 | records = [[point.x, point.y] for point in geometry] 200 | sw.field('x', 'N', decimal=5) 201 | sw.field('y', 'N', decimal=5) 202 | 203 | # shapes and records 204 | for point, record in itertools.izip(geometry, records): 205 | sw.point(point.x, point.y) 206 | sw.record(*record) 207 | 208 | # save 209 | sw.save(filename) 210 | 211 | 212 | else: 213 | raise NotImplementedError 214 | 215 | else: 216 | raise NotImplementedError 217 | 218 | 219 | -------------------------------------------------------------------------------- /skeletrontools.py: -------------------------------------------------------------------------------- 1 | from shapely.geometry import Polygon, LineString, Point, box 2 | 3 | import Skeletron 4 | import pandashp 5 | import shapely.ops 6 | 7 | def select_biggest_polygon_from_multipolygon(multi_polygon): 8 | """Return the polygon with the biggest exterior length from a multipolygon.""" 9 | if isinstance(multi_polygon, Polygon): 10 | return multi_polygon 11 | 12 | component_lengths = [poly.exterior.length for poly in multi_polygon] 13 | biggest_component_index = component_lengths.index(max(component_lengths)) 14 | return multi_polygon[biggest_component_index] 15 | 16 | 17 | def extract_lines_from_graph(graphs): 18 | lines = [] 19 | for graph in graphs: 20 | for line_dict in graph.edge.values(): 21 | if line_dict: 22 | for k in line_dict.keys(): 23 | lines.append(line_dict[k]['line']) 24 | return lines 25 | 26 | def skeletonize(roads, buffer_length=60, 27 | dissolve_length=30, 28 | simplify_length=30, 29 | buffer_resolution=2, 30 | psg_length=150): 31 | """Uses qhull to find simplified road network for given DataFrame of roads. 32 | 33 | Args: 34 | roads pandashp DataFrame of shapely LINESTRINGs (projected) 35 | buffer_length optional roughly equivalent to amount of generalization 36 | dissolve_length optional (def: 30) considerably smaller than buffer_length 37 | simplify_length optional 38 | buffer_resolution optional 39 | psg_length optional (default: 150) Skeletron algorithm length 40 | """ 41 | 42 | # buffer and merge streets 43 | streets_buffered = [way['geometry'].buffer(buffer_length, buffer_resolution) 44 | for _, way in roads.iterrows()] 45 | streets_buffered_merged = shapely.ops.cascaded_union(streets_buffered) 46 | 47 | # the union now has several connected components 48 | # select the component with the longest circumference (=exterior.length) 49 | # and undo the buffer operation and repeat the selection process 50 | streets_buffered_merged = select_biggest_polygon_from_multipolygon(streets_buffered_merged) 51 | streets_buffered_merged = streets_buffered_merged.buffer(-dissolve_length) 52 | streets_buffered_merged = select_biggest_polygon_from_multipolygon(streets_buffered_merged) 53 | streets_buffered_merged_simplified = streets_buffered_merged.simplify(simplify_length) 54 | 55 | # then calculate skeleton (expensive but necessary) 56 | street_graphs = Skeletron.polygon_skeleton_graphs(streets_buffered_merged_simplified,psg_length) 57 | street_lines = extract_lines_from_graph(street_graphs) 58 | 59 | # merge list of lines to MultiLine 60 | street_lines_merged = shapely.ops.linemerge(street_lines) 61 | 62 | # intersecting multiline with its bounding box somehow triggers a first 63 | whole_city = box(*street_lines_merged.bounds) 64 | 65 | # perform linemerge (one linestring between each crossing only) 66 | # if this fails, write function to perform this on a bbox-grid and then 67 | # merge the result 68 | street_lines_merged_intersect = street_lines_merged.intersection(whole_city) 69 | street_lines_merged_intersect_merged = shapely.ops.linemerge(street_lines_merged_intersect) 70 | 71 | # and remove zigzaging (for smoother plots) 72 | streets = street_lines_merged_intersect_merged.simplify(simplify_length) 73 | return streets --------------------------------------------------------------------------------