├── .gitignore ├── LICENCE ├── README ├── TODO.txt ├── doc ├── index.html ├── osmdb.html ├── osmhistory.html └── pictures │ ├── osmhistory_josm1.png │ └── osmhistory_josm2.png ├── setup.py ├── src └── osm │ ├── __init__.py │ ├── multipolygon.py │ ├── osmdb.py │ ├── pyosm.py │ └── utils.py ├── tests ├── osmfiles │ ├── josm_download.osm │ └── multipolygon1.osm ├── test_multipolygon.py ├── test_osmdb ├── test_osmdb.py └── test_pyosm.py └── tools ├── osmhistory.py └── relation2gpx.py /.gitignore: -------------------------------------------------------------------------------- 1 | build 2 | *.pyc 3 | *~ 4 | tests/*.xml 5 | tests/*.osm 6 | tests/*.txt 7 | tests/*.gpx 8 | tests/testoutput/* 9 | -------------------------------------------------------------------------------- /LICENCE: -------------------------------------------------------------------------------- 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: -------------------------------------------------------------------------------- 1 | python-osm 2 | original version by Rory McCann (http://blog.technomancy.org/) 3 | modified by Christoph Lupprich (http://www.stopbeingcarbon.com) 4 | modified and extended by Werner Hoch (http://www.h-renrew.de) 5 | 6 | == DESCRIPTION 7 | 8 | python-osm contains tools to read Open Street Map Data (*.osm). 9 | It is splitted into several python classes: 10 | 11 | src/pyosm.py: 12 | base class that contains the datamodel of osm. It parses the osm 13 | file or data and puts every osm-object into pythonobjects. 14 | 15 | src/multipolygon.py: 16 | analyzes a multipolygon relation and provides a node-in-polygon check. 17 | This class can export a polygon files for osmosis, too. 18 | 19 | src/osmdb.py: 20 | offers an api to read osm objects from large or large compressed osm files 21 | like the planet. 22 | 23 | tools/relation2gpx.py: 24 | Exports one or more relations into a gpx file. This tool can be used to 25 | create gpx tracks for your gps-unit or to create maps with routes. 26 | 27 | tools/osmhistory.py: 28 | With this tool you can get an old versions of osm-objects at a given 29 | timestamp. (experimental, use with care) 30 | 31 | see also: doc/index.html for more documentation. 32 | -------------------------------------------------------------------------------- /TODO.txt: -------------------------------------------------------------------------------- 1 | * osmhistory: version id is wrong: setter method for pyosm 2 | * pbf-support 3 | * pbf object generator 4 | * osmdb: pbf-support 5 | * object generators for osmdb and bz2osmdb 6 | 7 | * relation2gpx: recursive relation support -------------------------------------------------------------------------------- /doc/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | python-osm documentation 5 | 6 | 7 | 8 |

python-osm documentation

9 | python-osm is a set of classes an tools for openstreetmap data and files. 10 | 11 |

src/osm/pyosm

12 | This is the base class that contains the data model of python-osm. 13 | It also contains a xml parser to read osm files. 14 |

15 | When called on commandline with an osm file as argument, the class prints a statistic of the file. 16 | 17 | 24 |
18 |
werner@linux-g0e5:~/osm/src/python-osm/src/osm> ./pyosm.py Rottweil.osm 
 19 | filename: Rottweil.osm
 20 |   Nodes:     3020
 21 |   Ways:      6
 22 |   Relations: 1
23 |
25 | 26 |

src/osm/multipolygon.py

27 | This class can be used to work with multipolygon relations. 28 | Beside the commandline options you can perform node in multipolygon checks. 29 | 30 |

multipolygon commandline

31 | When called on command line interface you can either check multipolygons for 32 | way gaps or create polygon files for osmosis. 33 | 34 | 44 |
35 |
usage: multipolygon.py --relation=ID [options]
 36 | load a multipolygon from the OSM-API or from an OSM file
 37 | export osmosis boundary polygon or check the multipolygon for errors
 38 |   -h, --help: print this usage message
 39 |   -i, --infile: osmfile to load
 40 |   -r, --relation: multipolygon relation id
 41 |   -m, --osmosispolygon: outfile for osmosis boundary polygon
 42 |   -j, --josmfile: outfile for josm boundary
 43 |         
45 | 46 |

multipolygon commandline examples

47 | Load a multipolygon with the OSM api and check it. 48 | 49 | 64 |
50 |
werner@linux-g0e5:~/osm/src/python-osm/src/osm> ./multipolygon.py -r 1164629
 51 | Multipolygon of Relation 1164629
 52 |   Outer Polygons (1):
 53 |     1: 682 Nodes
 54 |   Inner Polygons (6):
 55 |     1: 40 Nodes
 56 |     2: 21 Nodes
 57 |     3: 21 Nodes
 58 |     4: 39 Nodes
 59 |     5: 7 Nodes
 60 |     6: 11 Nodes
 61 |   Open Outer Ways (0):
 62 |   Open Inner Ways (0):
 63 |         
65 |

66 | 67 | To export relation with id=62578 as polygon file for osmosis: 68 | 69 | 72 |
70 |
werner@linux-g0e5:~/osm/src/python-osm/src/osm> ./multipolygon.py -r 62578 -m boundary.poly
71 |
73 |

74 | 75 | To create an empty josmfile with the tiled bounds of the multipolygon with id=289122 as polygon: 76 | 77 | 80 |
78 |
werner@linux-g0e5:~/osm/src/python-osm/src/osm> ./multipolygon.py -r 289122 -j josmfile.xml
79 |
81 | 82 |

src/osm/osmdb.py

83 | see osmdb for a detailed description. 84 | 85 |

tools/osmhistory.py

86 | see osmhistory for a detailed description. 87 | 88 |

tools/relation2gpx.py

89 | A tool to download relations from the OSM API and create gpx files. 90 | Each relation becomes a track (trk) and each way a track segment 91 | trkseg. 92 | The segments are not ordered. 93 | 94 |

relation2gpx.py commandline

95 | 96 | 103 |
97 |
usage: relation2gpx.py [-o GPXFILE] -r relation1,relation2,...
 98 | load relations from the OSM API and create gpx files
 99 |   -h, --help: print this help message
100 |   -o, --outfile: specify the filename of the gpx file
101 |   -r, --relations: comma seperated list of relations
102 |
104 | 105 |

relation2gpx.py examples

106 | Get relation 157289 (HW4 hiking route) and write it to default filename out.gpx 107 | 108 | 111 |
109 |
werner@linux-g0e5:~/osm/src/python-osm/tools> ./relation2gpx.py -r 157289
110 |
112 | 113 |
114 |
Werner Hoch
115 | 116 | 117 | Last modified: Sat Oct 13 11:23:24 CEST 2012 118 | 119 | 120 | 121 | -------------------------------------------------------------------------------- /doc/osmdb.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | osmdb: API for large OSM files 5 | 6 | 7 | 8 |

osmdb: API for large OSM files

9 | osmdb.py provides an possibility to extract osm objects from large openstreetmap files.

10 | The osmdb modul can be used as CLI program as http server or as python module. 11 | 12 |

command line options

13 | 14 | 25 |
15 |
osmdb.py Version 0.0.2
16 |   -h, --help: print this help information
17 |   --relations=outfile: split relations from input file
18 |   --ways_relations=outfile: split ways and relations from input file
19 |   --server=port: start a http-server with the given port
20 | Examples:
21 |   osmdb.py --relations=out.osm.bz2 germany.osm.bz2
22 |   osmdb.py --ways_relations=/dev/stdout planet-latest.osm
23 |   osmdb.py --server=8888 germany.osm
24 |
26 | The commandlines can be used to strip of the relations or the ways and realtions from a large 27 | osm or osm.bz2 file.
28 | This is usefull if you only need the relations of an osm file. 29 | 30 |

http server api

31 | After starting an http server with the following commandline ... 32 | 33 | 36 |
34 |
werner@linux-g0e5:~/osm/src/python-osm/src/osm> ./osmdb.py --server=8888 germany.osm
35 |
37 | ... you can access the osm file with http requests. 38 |

39 | Here's a list of all possible commands: 40 | 41 | 49 |
42 |
  nodes?nodes=id1,id2,...
43 |   ways?ways=id1,id2,...
44 |   relations?relations=id1,id2,...
45 |   ways?ways=id1,id2,...&mode=full
46 |   relations?relations=id1,id2,...&mode=full
47 |   relations?relations=id1,id2,...&mode=recursive
48 |
50 |

51 | 52 | To create http requests you can use the command line tool wget or any 53 | programming language you like.
54 | Here are some examples with wget: 55 | 56 | 57 | 67 |
58 |
wget -Oosmdb_nodes.xml http://localhost:8888/nodes?nodes=437498388,437498385,180721525
59 | 
60 | wget -Oosmdb_ways.xml http://localhost:8888/ways?ways=37426524,37426525,32466511
61 | wget -Oosmdb_ways_full.xml http://localhost:8888/ways?ways=37426524,37426525,32466511\&mode=full
62 | 
63 | wget -Oosmdb_relation.xml http://localhost:8888/relations?relations=167920,131414
64 | wget -Oosmdb_relation_full.xml http://localhost:8888/relations?relations=1111111\&mode=full
65 | wget -Oosmdb_relation_recursive.xml http://localhost:8888/relations?relations=1111111\&mode=recursive
66 |
68 | 69 | BTW: The relation 11111111 is the german boundary and it can be extracted from an uncompressed 70 | planet file in about 60 seconds. The resulting osm xml file contains 12 relations, 1172 ways and 54749 nodes. 71 | 72 |


73 |
Werner Hoch
74 | 75 | 76 | Last modified: Sat Jan 7 19:56:41 CET 2012 77 | 78 | 79 | 80 | -------------------------------------------------------------------------------- /doc/osmhistory.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | python-osm: osmhistory 5 | 6 | 7 | 8 |

python-osm: osmhistory

9 | 10 | osmhistory.py is a tool that can retrieve object data from 11 | the OpenStreetMap API at a given timestamp.

12 | 13 | The current OSM API supports the download of the current version 14 | of an object (e.g. a relation) with a single API call or over the 15 | JOSM remote control. 16 | 17 | 18 | 19 | 22 | 23 |
20 |
http://www.openstreetmap.org/api/0.6/relation/21628/full
21 |

24 | 25 | OSM-history can do the same but at any given timestamp. Thus you 26 | can get OSM-objects from a month ago, one year ago, or just the 27 | day before something bad happened with the osm objects. 28 | 29 | 30 | 31 | 34 | 35 |
32 |
./osmhistory.py -r 21628 -t 2009-10-01 -o relation_21628_2009-10-01.osm
33 |

36 | 37 | The command retrieves the relation 21628 at the 38 | timestamp 2009-10-01 and writes the output to the file 39 | relation_21628_2009-10-01.osm.

40 | 41 | In order to do that the script first searches (with a binary 42 | search) the matching version of the given OSM object. Then it 43 | collects all objects that are referenced by this object. e.g. a 44 | relation references other relations, ways and/or nodes. A way 45 | references nodes.

46 | 47 | All that objects are downloaded by the script, too. An example 48 | output of the script with the executed API calls looks like this: 49 | 50 | 51 | 52 | 77 | 78 |
53 |
bisect:relation21628
 54 |  bisect:/api/0.6/relations?relations=21628
 55 |  bisect:/api/0.6/relation/21628/4
 56 |  bisect:/api/0.6/relation/21628/6
 57 |  bisect:/api/0.6/relation/21628/5
 58 | bisect:way8022736
 59 |  bisect:/api/0.6/ways?ways=8022736
 60 |  bisect:/api/0.6/way/8022736/4
 61 |  bisect:/api/0.6/way/8022736/6
 62 |  bisect:/api/0.6/way/8022736/7
 63 | bisect:way19736185
 64 |  bisect:/api/0.6/ways?ways=19736185
 65 | [....]
 66 | bisect:node59975181
 67 |  bisect:/api/0.6/nodes?nodes=59975181
 68 | bisect:node362803235
 69 |  bisect:/api/0.6/nodes?nodes=362803235
 70 |  bisect:/api/0.6/node/362803235/4
 71 |  bisect:/api/0.6/node/362803235/2
 72 |  bisect:/api/0.6/node/362803235/3
 73 | bisect:node500348455
 74 |  bisect:/api/0.6/nodes?nodes=500348455
 75 | [...]
76 |

79 | 80 | After retrieving the history, you can compare the current version 81 | of the object and the historic version. You can load the two 82 | versions into different layers with JOSM. 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 |
new version in front of the old version old version in front of the current version, zoomed in

95 | 96 | As you can see on the left picture, the route of the relation has 97 | been changed. On the right picture, you can see the moved 98 | roundabout.

99 | 100 |

Revert the changes (experimental, not much tested)

101 | 102 | The historic version of the osm objects are prepared to revert the current osm object versions. 103 | To achieve this: 104 |
    105 |
  • I've set the object version attribute to the version of the current object.
  • 106 |
  • I've added an extra tag osmhistory:old_version_date at each modified object. 107 | The value of the tag contains the historic version and the date of that version.
  • 108 |
109 | 110 | If you delete that tag, the you get exactly the historic 111 | object. JOSM will add an action=modify attribute and the version 112 | attribute gets incremented. The reverted object will be uploaded 113 | with the next commit.

114 | 115 | Example of the historic osm file: 116 | 117 | 118 | 143 | 144 |
119 |
<node uid="110263" timestamp="2009-09-18T15:12:19Z" lon="9.5154672" visible="true" version="4" user="werner2101" lat="47.6790064" id="362803252">
120 |   <tag k="osmhistory:old_version_date" v="2_2009-10-01"></tag>
121 | </node>
122 | <way uid="110263" timestamp="2009-09-18T15:12:22Z" visible="true" version="17" user="werner2101" id="4675294">
123 |   <nd ref="29691653"></nd>
124 |   <nd ref="362606768"></nd>
125 | [...]
126 |   <tag k="maxspeed" v="50"></tag>
127 |   <tag k="ref" v="K 7726"></tag>
128 |   <tag k="highway" v="tertiary"></tag>
129 |   <tag k="osmhistory:old_version_date" v="16_2009-10-01"></tag>
130 | </way>
131 | <relation uid="110263" timestamp="2009-09-18T15:12:23Z" visible="true" version="7" user="werner2101" id="21628">
132 |   <member ref="4675294" role="" type="way"></member>
133 |   <member ref="8022729" role="" type="way"></member>
134 |   <member ref="8022735" role="" type="way"></member>
135 | [...]
136 |   <tag k="operator" v="Bodenseekreis"></tag>
137 |   <tag k="type" v="route"></tag>
138 |   <tag k="route" v="road"></tag>
139 |   <tag k="ref" v="K 7726"></tag>
140 |   <tag k="osmhistory:old_version_date" v="5_2009-10-01"></tag>
141 | </relation>
142 |

145 | 146 |

Integration into OSM API

147 | 148 | The current python implementation of that tool needs lots of api calls. Even if I could download 149 | more than one object of the current objects, the download and the binary search of older objects 150 | still produces lots of api calls. I'm not sure how long it would take to download large relations 151 | like the boundary of a country.

152 | 153 | If other osm users think that the tool is usefull, it's functionality should be included into 154 | the OSM api (which is written using Ruby on Rails). 155 | 156 |


157 |
Werner Hoch
158 | 159 | 160 | Last modified: Tue Dec 29 12:27:50 CET 2009 161 | 162 | 163 | 164 | -------------------------------------------------------------------------------- /doc/pictures/osmhistory_josm1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/werner2101/python-osm/f508807662f682bea574c57deac5ed202e92b357/doc/pictures/osmhistory_josm1.png -------------------------------------------------------------------------------- /doc/pictures/osmhistory_josm2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/werner2101/python-osm/f508807662f682bea574c57deac5ed202e92b357/doc/pictures/osmhistory_josm2.png -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | from distutils.core import setup 2 | 3 | setup( 4 | name = 'python-osm', 5 | version = '0.0.3', 6 | url = 'https://github.com/werner2101/python-osm', 7 | author = 'Werner Hoch', 8 | author_email = 'werner.ho@gmx.de', 9 | description = 'Provides model objects for OSM promitives and related tools', 10 | scripts = [ 11 | 'tools/osmhistory.py', 12 | 'tools/relation2gpx.py' 13 | ], 14 | py_modules = ['osm.pyosm', 15 | 'osm.multipolygon', 16 | 'osm.osmdb', 17 | 'osm.utils' 18 | ], 19 | package_dir = {'osm': 'src/osm'}, 20 | ) 21 | -------------------------------------------------------------------------------- /src/osm/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/werner2101/python-osm/f508807662f682bea574c57deac5ed202e92b357/src/osm/__init__.py -------------------------------------------------------------------------------- /src/osm/multipolygon.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | 3 | import sys 4 | import pyosm 5 | from utils import deg2num, num2deg 6 | import numpy 7 | 8 | try: 9 | #nxutils is only used in older matplotlib version (<1.2.x) 10 | import matplotlib.nxutils 11 | HAS_NXUTILS = True 12 | except: 13 | HAS_NXUTILS = False 14 | import matplotlib.path 15 | 16 | 17 | class multipolygon(object): 18 | 19 | def __init__(self, relation): 20 | self.relation = relation 21 | self.read_relation(self.relation) 22 | 23 | def read_relation(self, relation): 24 | """ 25 | read the relation and prepare the multipolygon object. 26 | """ 27 | members = self.recursive_members(relation) 28 | 29 | inner_ways = [] 30 | outer_ways = [] 31 | for obj,role in members: 32 | if type(obj) == pyosm.Way: 33 | if role in ['outer', '']: 34 | outer_ways.append(obj) 35 | elif role in ['inner']: 36 | inner_ways.append(obj) 37 | else: 38 | sys.stderr.write('Unknown role "%s" of way %i\n' % (role, obj.id)) 39 | elif type(obj) == pyosm.Node: 40 | sys.stderr.write('Node obj in role "%s" of node %i\n' % (role, obj.id)) 41 | 42 | self.inner_polygons, self.inner_ways = self.create_polygons(inner_ways) 43 | self.outer_polygons, self.outer_ways = self.create_polygons(outer_ways) 44 | 45 | 46 | def create_polygons(self, ways): 47 | """ 48 | sort the osm ways to inner and outer polygon way list. 49 | Connect all osm ways that belongs together into single polygon ways. 50 | """ 51 | ways = ways + [] ## list copy 52 | polygons = [] 53 | open_ways = [] 54 | 55 | endnodes = {} 56 | for w in ways: 57 | start = w.nodes[0] 58 | stop = w.nodes[-1] 59 | if start.id == stop.id: 60 | ## a closed way is a polygon 61 | polygons.append(w.nodes) 62 | continue 63 | if start.id in endnodes: 64 | endnodes[start.id].append(w) 65 | else: 66 | endnodes[start.id] = [w] 67 | if stop.id in endnodes: 68 | endnodes[stop.id].append(w) 69 | else: 70 | endnodes[stop.id] = [w] 71 | 72 | poly_nodes = [] 73 | 74 | while endnodes: 75 | way = iter(endnodes.values()).__next__()[0] 76 | startway = way 77 | endway = way 78 | poly_nodes.extend(way.nodes) 79 | while True: 80 | startnode = poly_nodes[0] 81 | stopnode = poly_nodes[-1] 82 | if startnode == stopnode: 83 | endnodes.pop(startnode.id) 84 | polygons.append(poly_nodes) 85 | poly_nodes = [] 86 | break 87 | 88 | if startway: 89 | ways = endnodes.pop(startnode.id) 90 | if len(ways) == 1: 91 | sys.stderr.write('open node %s of way %s\n' % (startnode.id, ways[0].id)) 92 | startway = None 93 | continue 94 | elif len(ways) == 2: 95 | if ways[0] == startway: 96 | appendway = ways[1] 97 | else: 98 | appendway = ways[0] 99 | if appendway.nodes[-1] == startnode: 100 | poly_nodes = appendway.nodes + poly_nodes 101 | else: 102 | poly_nodes = appendway.nodes[::-1] + poly_nodes 103 | startway = appendway 104 | continue 105 | else: 106 | sys.stderr.write('node with more than 2 ways %s\n' % (startnode.id)) 107 | 108 | if endway: 109 | ways = endnodes.pop(stopnode.id) 110 | if len(ways) == 1: 111 | sys.stderr.write('open node %s of way %s\n' % (stopnode.id, ways[0].id)) 112 | endway = None 113 | continue 114 | elif len(ways) == 2: 115 | if ways[0] == endway: 116 | appendway = ways[1] 117 | else: 118 | appendway = ways[0] 119 | if appendway.nodes[0] == stopnode: 120 | poly_nodes = poly_nodes + appendway.nodes 121 | else: 122 | poly_nodes = poly_nodes + appendway.nodes[::-1] 123 | endway = appendway 124 | continue 125 | else: 126 | sys.stderr.write('node with more than 2 ways %s\n' % (stopnode.id)) 127 | 128 | ## no way found to append 129 | open_ways.append(poly_nodes) 130 | poly_nodes = [] 131 | break 132 | 133 | return polygons, open_ways 134 | 135 | 136 | def recursive_members(self, relation): 137 | """ 138 | collect recursively all way/node members of a hierarchical multipolygon relation. 139 | returns a list of (obj,role) tuples of all member elements. 140 | """ 141 | todo_stack = [relation] 142 | members = [] 143 | recursive_relations = set() 144 | 145 | while todo_stack: 146 | current_relation = todo_stack.pop(0) 147 | 148 | if current_relation in recursive_relations: 149 | raise Exception('recursion loops in relation %i' % self.relation.id) 150 | recursive_relations.add(current_relation) 151 | 152 | for m in current_relation.members: 153 | obj, role = m 154 | if type(obj) == pyosm.Relation and role in ['inner','outer','']: 155 | todo_stack.append(obj) 156 | elif role in ['inner','outer','']: 157 | members.append(m) 158 | else: # drop all bad members like subarea, admin_centre 159 | pass 160 | 161 | return members 162 | 163 | def inside(self, nodes=[], points=[]): 164 | """ 165 | check if the nodes from the nodes list are inside the multipolygon 166 | """ 167 | if nodes: 168 | points = self.pointlist(nodes) 169 | matches = numpy.zeros(len(points)) 170 | for outerpoly in self.outer_polygons: 171 | outerpoints = self.pointlist(outerpoly) 172 | if HAS_NXUTILS: 173 | matches = matches + matplotlib.nxutils.points_inside_poly(points, outerpoints) 174 | else: 175 | matches = matches + matplotlib.path.Path(outerpoints).contains_points(points) 176 | for innerpoly in self.inner_polygons: 177 | innerpoints = self.pointlist(innerpoly) 178 | if HAS_NXUTILS: 179 | matches = matches - matplotlib.nxutils.points_inside_poly(points, innerpoints) 180 | else: 181 | matches = matches - matplotlib.path.Path(innerpoints).contains_points(points) 182 | return matches 183 | 184 | def pointlist(self, nodes): 185 | """ 186 | returns a list of (lon/lat) points of a given node list 187 | """ 188 | points = [] 189 | for node in nodes: 190 | points.append((float(node.lon), float(node.lat))) 191 | return points 192 | 193 | def write_osmosis_file(self, filename): 194 | """ 195 | create a boundary polygon for osmosis 196 | """ 197 | fid = open(filename, 'wt') 198 | n = 1 199 | fid.write('xxx\n') 200 | for op in self.outer_polygons: 201 | fid.write('%i\n' %(n)) 202 | for node in op: 203 | fid.write('\t%s\t%s\n' %(node.lon, node.lat)) 204 | fid.write('END\n') 205 | n += 1 206 | 207 | for ip in self.inner_polygons: 208 | fid.write('xxx\n') 209 | fid.write('!%i\n' %(n)) 210 | for node in ip: 211 | fid.write('\t%f\t%f\n' %(node.lat, node.lon)) 212 | fid.write('END\n') 213 | n += 1 214 | fid.write('END\n') 215 | fid.close() 216 | 217 | def write_josm_file(self, filename, tilezoom=14): 218 | """ 219 | create a osm file for the editor JOSM, that only contains the download boundary 220 | information. 221 | Load the file in JOSM and update the data. 222 | Note: Please do not missuse this function to download large areas with josm 223 | """ 224 | from shapely.geometry import LineString, Polygon 225 | 226 | f_out = open(filename,'w') 227 | f_out.write("\n") 228 | f_out.write("\n") 229 | 230 | for i, op in enumerate(self.outer_polygons): 231 | # create coordinate list and then a polygon 232 | plist = [(node.lat, node.lon) for node in op] 233 | outer_polygon = Polygon(LineString(plist)) 234 | 235 | if not outer_polygon.is_valid: 236 | raise ValueError('outer polygon no %i is not valid' % (i+1)) 237 | 238 | (minlat, minlon, maxlat, maxlon) = outer_polygon.bounds 239 | (x1, y2) = deg2num(minlat, minlon, tilezoom) 240 | (x2, y1) = deg2num(maxlat, maxlon, tilezoom) 241 | 242 | for ty in range(y1, y2 + 1): 243 | for tx in range(x1, x2 + 1): 244 | tile_rectangle = [num2deg(tx, ty, tilezoom), 245 | num2deg(tx+1, ty, tilezoom), 246 | num2deg(tx+1, ty+1, tilezoom), 247 | num2deg(tx, ty+1, tilezoom), 248 | num2deg(tx, ty, tilezoom)] 249 | tile_polygon = Polygon(tile_rectangle) 250 | 251 | if outer_polygon.contains(tile_polygon) or outer_polygon.intersects(tile_polygon): 252 | minlat = tile_rectangle[3][0] 253 | minlon = tile_rectangle[3][1] 254 | maxlat = tile_rectangle[1][0] 255 | maxlon = tile_rectangle[1][1] 256 | 257 | f_out.write(' \n' \ 258 | % (minlat-0.0000001, minlon-0.0000001, maxlat+0.0000001, maxlon+0.0000001)) 259 | 260 | f_out.write("\n") 261 | f_out.close 262 | 263 | def status(self): 264 | """ 265 | print the status of the multipolygon file. 266 | * number and list of outer/inner polygons 267 | * number and list of unclosed outer and inner polygons 268 | """ 269 | 270 | print ('Multipolygon of Relation %s' % (self.relation.id)) 271 | name = self.relation.tags.get('name', '') 272 | if name: 273 | print (' Name-Tag: ', name) 274 | print (' Outer Polygons (%i):' % len(self.outer_polygons)) 275 | for i, op in enumerate (self.outer_polygons): 276 | print (' %d: %d Nodes' %(i+1, len(op))) 277 | 278 | print (' Inner Polygons (%i):' % len(self.inner_polygons)) 279 | for i, ip in enumerate (self.inner_polygons): 280 | print (' %d: %d Nodes' %(i+1, len(ip))) 281 | 282 | print (' Open Outer Ways (%i):' % len(self.outer_ways)) 283 | for i, ow in enumerate (self.outer_ways): 284 | print (' %d: %d Nodes, id(Node[0])=%s, id(Node[-1])=%s' %(i+1, len(ow), ow[0].id, ow[-1].id)) 285 | 286 | print (' Open Inner Ways (%i):' % len(self.inner_ways)) 287 | for i, iw in enumerate (self.inner_ways): 288 | print (' %d: %d Nodes, id(Node[0])=%s, id(Node[-1])=%s' %(i+1, len(iw), iw[0].id, iw[-1].id)) 289 | 290 | 291 | def usage(): 292 | print ("usage: multipolygon.py --relation=ID [options]") 293 | print ("load a multipolygon from the OSM-API or from an OSM file") 294 | print ("export osmosis boundary polygon or check the multipolygon for errors") 295 | print ("-h, --help: print this usage message") 296 | print ("-i, --infile: osmfile to load") 297 | print ("-r, --relation: multipolygon relation id") 298 | print ("-m, --osmosispolygon: outfile for osmosis boundary polygon") 299 | print ("-j, --josmfile: outfile for josm boundary") 300 | 301 | 302 | #################### MAIN 303 | if __name__ == '__main__': 304 | import sys 305 | import getopt 306 | import urllib 307 | 308 | try: 309 | opts, args = getopt.getopt(sys.argv[1:], 'r:i:m:j:h', 310 | ['help', 'relation=', 'infile=', 'osmosispolygon=', 'josmfile=']) 311 | except getopt.GetoptError: 312 | usage() 313 | sys.exit() 314 | 315 | mode = None 316 | infile = None 317 | osmosisfile = None 318 | josmfile = None 319 | relation = None 320 | 321 | for o, a in opts: 322 | if o in ['-i', '--infile']: 323 | infile = a 324 | elif o in ['-r', '--relation']: 325 | relation = a 326 | elif o in ['-m', '--osmosispolygon']: 327 | osmosisfile = a 328 | elif o in ['-j', '--josmfile']: 329 | josmfile = a 330 | elif o in ['-h', '--help']: 331 | usage() 332 | sys.exit() 333 | 334 | API='http://www.openstreetmap.org/api/0.6' 335 | 336 | if infile: 337 | osmobj = pyosm.OSMXMLFile(infile) 338 | elif relation: 339 | osmfile = urllib.urlopen('%s/relation/%s/full' %(API,relation)) 340 | osmobj = pyosm.OSMXMLFile(osmfile) 341 | else: 342 | usage() 343 | sys.exit() 344 | 345 | mp = multipolygon(osmobj.relations[int(relation)]) 346 | 347 | if osmosisfile: 348 | mp.write_osmosis_file(osmosisfile) 349 | 350 | elif josmfile: 351 | mp.write_josm_file(josmfile) 352 | 353 | else: 354 | mp.status() 355 | 356 | 357 | -------------------------------------------------------------------------------- /src/osm/osmdb.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | 3 | import sys, os 4 | import math, re 5 | import bz2 6 | import logging 7 | if sys.version_info < (3,0): 8 | from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer 9 | else: 10 | from http.server import BaseHTTPRequestHandler, HTTPServer 11 | from xml.sax import handler, make_parser, parseString 12 | 13 | log = logging.getLogger(__name__) 14 | #################### CONSTANTS 15 | VERSION = "0.0.3" 16 | 17 | OSMHEAD = """""" \ 18 | """""" 19 | OSMTAIL = """""" 20 | 21 | LOGGING = False 22 | 23 | #################### CLASSES 24 | class SubobjectHandler(handler.ContentHandler): 25 | """ 26 | simple XML Handler for osm files that extracts nodes (nd) from ways 27 | and members from relations 28 | """ 29 | def __init__(self): 30 | self.relations = set([]) 31 | self.nodes = set([]) 32 | self.ways = set([]) 33 | 34 | def startElement(self, obj, attrs): 35 | if obj == 'nd': 36 | self.nodes.add(int(attrs['ref'])) 37 | return 38 | elif obj == 'member': 39 | if attrs['type'] == 'relation': 40 | self.relations.add(int(attrs['ref'])) 41 | elif attrs['type'] == 'way': 42 | self.ways.add(int(attrs['ref'])) 43 | elif attrs['type'] == 'node': 44 | self.nodes.add(int(attrs['ref'])) 45 | 46 | def endElement(self, obj): 47 | pass 48 | 49 | 50 | class Bisect(object): 51 | """ 52 | Helper class for binary search processes. 53 | """ 54 | def __init__(self, minindex, maxindex): 55 | self.min = minindex 56 | self.max = maxindex 57 | self.reset() 58 | 59 | def reset(self): 60 | """ 61 | Setup the Bisect class or reset it to the starting stage. 62 | """ 63 | self.increment = 2**int(math.log(self.max - self.min + 1, 2)) 64 | self.cursor = self.min + self.increment - 1 65 | self.increment //= 2 66 | return self.cursor 67 | 68 | def up(self): 69 | """ 70 | Move the cursor upwards in binary steps. 71 | """ 72 | if not self.increment: 73 | return None 74 | self.cursor += self.increment 75 | self.increment //= 2 76 | while self.cursor > self.max: 77 | self.down() 78 | return self.cursor 79 | 80 | def down(self): 81 | """ 82 | Move the cursor downwards in binary steps. 83 | """ 84 | if not self.increment: 85 | return None 86 | self.cursor -= self.increment 87 | self.increment //= 2 88 | return self.cursor 89 | 90 | def __str__(self): 91 | return "Bisect: min=%i, max=%i, cursor=%i, increment=%i" \ 92 | % (self.min, self.max, self.cursor, self.increment) 93 | 94 | 95 | class IndexBlock(object): 96 | """ 97 | Artificial index object to store information about the content 98 | of an file index. 99 | """ 100 | def __init__(self, fileindex): 101 | self.fileindex = fileindex 102 | self.first_type = None 103 | self.first_id = None 104 | self.valid = False 105 | 106 | def __str__(self): 107 | return "IndexBlock: fileindex=%s, first_type=%s, first_id=%s, valid=%s" \ 108 | % (self.fileindex, self.first_type, self.first_id, self.valid) 109 | 110 | class OsmDb(object): 111 | """ 112 | OsmDb offers random access to large osm files that cannot be loaded 113 | into memomry with the pyosm class. 114 | Basically it creates a file index on the fly and binary search system 115 | to find objects in large files really fast. 116 | """ 117 | def __init__(self, filename): 118 | self.filename = filename 119 | self._index = [] 120 | 121 | self._filesize = os.path.getsize(self.filename) 122 | self._filehandler = open(self.filename, 'rb') 123 | self._create_index() 124 | self._order = {'changeset': -1, 'node': 0, 'way': 1, 'relation': 2} 125 | 126 | def _create_index(self): 127 | """ 128 | Allocate index blocks without validating them. 129 | """ 130 | CNT = 100000 131 | self._index = [ IndexBlock( i * CNT ) for i in range(self._filesize // CNT - 1 ) ] 132 | 133 | def _validate(self, blk): 134 | """ 135 | Find the first object element in the block and update the block index. 136 | Returns False if the block has no object item. 137 | """ 138 | if blk.valid: 139 | return True 140 | 141 | self._filehandler.seek(blk.fileindex) 142 | while True: 143 | line = self._filehandler.readline() 144 | if line == False: ## EOF or Error 145 | return False 146 | else: 147 | for obj in ['node', 'way', 'relation','changeset']: 148 | if re.match('[ \t]*<%s id="[0-9]*" ' % obj, line): 149 | blk.first_type = obj 150 | blk.first_id = int(line.split('"')[1]) 151 | blk.valid = True 152 | return True 153 | 154 | def _get_block(self, objtype, objid): 155 | """ 156 | Search the index-block, that contains the given objtype and objid. 157 | This performs a binary search through the file. 158 | """ 159 | bisect = Bisect(0, len(self._index)-1) 160 | blocknr = bisect.reset() 161 | while True: 162 | blk = self._index[blocknr] 163 | if not self._validate(blk): 164 | self._index.pop(blocknr) 165 | log.debug("bad block: %s" % blocknr) 166 | bisect = Bisect(0, len(self._index)-1) 167 | blocknr = bisect.reset() 168 | continue 169 | 170 | log.debug("bisect Nr=%s, seeking %s=%s" %(blocknr, objtype, objid), str(blk)) 171 | 172 | res = cmp((self._order[objtype], objid), 173 | (self._order[blk.first_type], blk.first_id)) 174 | 175 | if res < 0: 176 | if blocknr != 0 and self._index[blocknr-1].valid: 177 | blk2 = self._index[blocknr-1] 178 | if blk2.valid and ((self._order[objtype], objid) >= \ 179 | (self._order[blk2.first_type], blk2.first_id)): 180 | return blk2 181 | blocknr = bisect.down() 182 | if blocknr == None: # blocknumber 0 183 | return blk 184 | elif res == 0: ## exact match (rare case) 185 | return blk 186 | else: 187 | if blocknr == len(self._index)-1: 188 | return blk 189 | blk2 = self._index[blocknr+1] 190 | if blk2.valid and ((self._order[objtype], objid) < \ 191 | (self._order[blk2.first_type], blk2.first_id)): 192 | return blk 193 | blocknr = bisect.up() 194 | 195 | def _checkline(self, line, objtype, objid): 196 | if re.match('\s* lastid + 1000: 346 | blk = self._get_block(objtype, objid) 347 | self._filehandler.seek(blk.fileindex) 348 | lastid = objid 349 | while True: 350 | line = self._filehandler.readline() 351 | if not line: 352 | break 353 | ret = self._checkline(line, objtype, objid) 354 | if ret == -2: 355 | continue 356 | elif ret == -1: 357 | continue 358 | elif ret == 0: 359 | datalines.append(line) 360 | break 361 | elif ret == 1: 362 | line = "" 363 | lastid = objid - 10000 364 | break 365 | if not line: 366 | continue 367 | if line[-3:] == '/>\n': 368 | continue 369 | while True: 370 | line = self._filehandler.readline() 371 | datalines.append(line) 372 | if re.match('[ \t]*' %objtype, line): 373 | break 374 | return ''.join(datalines) 375 | 376 | 377 | class Bz2Reader(object): 378 | """ 379 | Helper class to access a bz2-compressed file like an uncompressed file. 380 | """ 381 | def __init__(self, filehandler, bz2filehead, bz2filesize): 382 | self._filehandler = filehandler 383 | self.__filehead = bz2filehead 384 | self._filesize = bz2filesize 385 | 386 | def changeblock(self, bz2block): 387 | """ 388 | Reset the reader cursor to another block index. 389 | """ 390 | self.__blk = bz2block 391 | self.__bz2dc = bz2.BZ2Decompressor() 392 | self.__bz2dc.decompress(self.__filehead) 393 | self.__bz2cursor = self.__blk.fileindex 394 | self.__databuffer = "" 395 | self.__datacursor = 0 396 | 397 | def __readbz2(self, size): 398 | """ 399 | Read data with the given size from the bz2-file. 400 | The size is defined in the compressed context of the bz2-file 401 | """ 402 | self._filehandler.seek(self.__bz2cursor) 403 | if self.__bz2cursor == self._filesize - 5: 404 | return 'EOF' 405 | if self.__bz2cursor + size >= self._filesize - 5: 406 | size = self._filesize - self.__bz2cursor - 5 407 | datain = self._filehandler.read(size) 408 | while datain: 409 | try: 410 | self.__databuffer += self.__bz2dc.decompress(datain) 411 | except EOFError as msg: 412 | log.debug(msg, len(self.__bz2dc.unused_data)) 413 | if len(self.__bz2dc.unused_data) > 4: 414 | log.debug("unused head", self.__bz2dc.unused_data[:4]) 415 | datain = self.__bz2dc.unused_data 416 | self.__bz2dc = bz2.BZ2Decompressor() 417 | continue 418 | except Exception as msg: 419 | log.debug(msg) 420 | return False 421 | break 422 | 423 | self.__bz2cursor = self._filehandler.tell() 424 | return True 425 | 426 | def read(self, size): 427 | """ 428 | Read the given number of bytes from the bz2-file 429 | The size is defined in uncompressed bytes. 430 | """ 431 | while (len(self.__databuffer) - self.__datacursor) < size: 432 | res = self.__readbz2(size // 20) 433 | if res == 'EOF': 434 | data = self.__databuffer[self.__datacursor:] 435 | self.__databuffer = "" 436 | self.__datacusor = 0 437 | if data: 438 | return data 439 | else: 440 | return False 441 | if not res: 442 | return False 443 | 444 | data = self.__databuffer[self.__datacursor:self.__datacursor + size] 445 | self.__datacursor += size 446 | 447 | if self.__datacursor > 2*size: 448 | self.__databuffer = self.__databuffer[self.__datacursor:] 449 | self.__datacursor = 0 450 | 451 | return data 452 | 453 | def readline(self): 454 | """ 455 | Read a line from the bz2reader 456 | """ 457 | while True: 458 | ind = self.__databuffer.find('\n', self.__datacursor) 459 | if ind == -1: 460 | res = self.__readbz2(10000) 461 | if not res: 462 | return False 463 | elif res == 'EOF': 464 | return False 465 | else: 466 | line = self.__databuffer[self.__datacursor:ind] 467 | self.__datacursor = ind + 1 468 | break 469 | 470 | if self.__datacursor > 100000: 471 | self.__databuffer = self.__databuffer[self.__datacursor:] 472 | self.__datacursor = 0 473 | return line 474 | 475 | 476 | class Bz2OsmDb(OsmDb): 477 | """ 478 | Bz2OsmDb offers random access to large bz2 compressed osm files that 479 | cannot be loaded into memomry with the pyosm class. 480 | Basically it creates a file index on the fly and binary search system 481 | to find objects in large files really fast. 482 | The API is identical to the OsmDb class. 483 | Note: This class cannot access multistream bz2 files 484 | see http://bugs.python.org/issue1625 for details 485 | """ 486 | def __init__(self, bz2filename): 487 | self.bz2filename = bz2filename 488 | self._index = [] 489 | self._order = {'changeset': -1, 'node': 0, 'way': 1, 'relation': 2} 490 | self._filesize = os.path.getsize(self.bz2filename) 491 | self._filehandler = open(self.bz2filename, 'rb') 492 | self._bz2_filehead = self._filehandler.read(4) 493 | log.debug("file head:", str(self._bz2_filehead)) 494 | 495 | self._create_index() 496 | self._bz2reader = Bz2Reader(self._filehandler, self._bz2_filehead, self._filesize) 497 | 498 | def _create_index(self): 499 | """ 500 | Create an index for the compressed osm file 501 | """ 502 | BZ2_COMPRESSED_MAGIC = chr(0x31)+chr(0x41)+chr(0x59)+chr(0x26)+chr(0x53)+chr(0x59) 503 | READBLOCK_SIZE = 100000000 504 | log.debug("Bz2OsmDb: creating index") 505 | fin = self._filehandler 506 | block_nr = 0 507 | while True: 508 | cursor = 0 509 | fin.seek(block_nr * READBLOCK_SIZE) 510 | buf = fin.read(READBLOCK_SIZE+10) 511 | while True: 512 | found = buf.find(BZ2_COMPRESSED_MAGIC, cursor) 513 | if found == -1: 514 | break 515 | block = IndexBlock(block_nr * READBLOCK_SIZE + found) 516 | self._index.append(block) 517 | cursor = found + 2 518 | block_nr += 1 519 | if fin.tell() < block_nr * READBLOCK_SIZE: 520 | break 521 | 522 | log.debug("Bz2OsmDb: index complete: %d Blocks" % len(self._index)) 523 | 524 | def _validate(self, blk): 525 | """ 526 | Find the first object element in the block and update the block index. 527 | Returns False if the block has no object item. 528 | """ 529 | if blk.valid: 530 | return True 531 | 532 | self._bz2reader.changeblock(blk) 533 | while True: 534 | line = self._bz2reader.readline() 535 | if line == False: ## EOF or Error 536 | return False 537 | else: 538 | for obj in ['node', 'way', 'relation','changeset']: 539 | if re.match('[ \t]*<%s id="[0-9]*" ' % obj, line): 540 | blk.first_type = obj 541 | blk.first_id = int(line.split('"')[1]) 542 | blk.valid = True 543 | return True 544 | 545 | def write_relations(self, filename): 546 | """ 547 | Write all relations of the osm fileobject to the given filename. 548 | If the filename ends with ".bz2", then the relations will be compressed. 549 | With filename=/dev/stdout you can get a stream of all realations. 550 | """ 551 | log.debug("Bz2OsmDb: writing relations") 552 | OSMHEAD = """\n""" \ 553 | """""" 554 | blk = self._get_block('relation', 0) 555 | self._bz2reader.changeblock(blk) 556 | 557 | if filename[-4:] == '.bz2': 558 | fout = bz2.BZ2File(filename, 'w') 559 | else: 560 | fout = open(filename, 'w') 561 | 562 | while True: 563 | line = self._bz2reader.readline() 564 | if re.match('[ \t]*\n""" \ 584 | """""" 585 | blk = self._get_block('way', 0) 586 | self._bz2reader.changeblock(blk) 587 | 588 | if filename[-4:] == '.bz2': 589 | fout = bz2.BZ2File(filename, 'w') 590 | else: 591 | fout = open(filename, 'w') 592 | 593 | while True: 594 | line = self._bz2reader.readline() 595 | if re.match('[ \t]* lastid + 1000: 618 | blk = self._get_block(objtype, objid) 619 | self._bz2reader.changeblock(blk) 620 | lastid = objid 621 | while True: 622 | line = self._bz2reader.readline() 623 | if not line: 624 | break 625 | ret = self._checkline(line, objtype, objid) 626 | if ret == -2: 627 | continue 628 | if ret == -1: 629 | continue 630 | elif ret == 0: 631 | datalines.append(line) 632 | break 633 | elif ret == 1: 634 | line = "" 635 | break 636 | if not line: 637 | continue 638 | if line[-2:] == '/>': # object already complete 639 | continue 640 | while True: 641 | line = self._bz2reader.readline() 642 | datalines.append(line) 643 | if re.match('[ \t]*' %objtype, line): 644 | break 645 | return '\n'.join(datalines) + '\n' 646 | 647 | 648 | class OSMHttpHandler(BaseHTTPRequestHandler): 649 | """ 650 | HTTP handler URL commands from the HTTP server. 651 | """ 652 | def print_help(self): 653 | self.send_response(404) 654 | self.send_header('Content-type', 'text/html') 655 | self.end_headers() 656 | self.wfile.write("OSMDB File interface
") 657 | self.wfile.write("=====================

") 658 | self.wfile.write("valid commands are:

") 659 | self.wfile.write(" nodes?nodes=id1,id2,...
") 660 | self.wfile.write(" ways?ways=id1,id2,...
") 661 | self.wfile.write(" relations?relations=id1,id2,...
") 662 | self.wfile.write(" ways?ways=id1,id2,...&mode=full
") 663 | self.wfile.write(" relations?relations=id1,id2,...&mode=full
") 664 | self.wfile.write(" relations?relations=id1,id2,...&mode=recursive") 665 | return 666 | 667 | def do_GET(self): 668 | print (self.path) 669 | osm = self.server.osmdb 670 | toks = self.path.split('?') 671 | if len(toks) != 2: 672 | self.print_help() 673 | return 674 | else: 675 | command = toks[0] 676 | kvs = toks[1].split('&') 677 | args = dict([kv.split('=',1) for kv in kvs]) 678 | try: 679 | if command == '/nodes': 680 | nodes = [int(n) for n in args['nodes'].split(',')] 681 | data = osm.get_objects('node', nodes) 682 | elif command == '/ways': 683 | ways = [int(n) for n in args['ways'].split(',')] 684 | if args.get('mode','') == 'full': 685 | data = osm.get_objects_recursive('way', ways) 686 | else: 687 | data = osm.get_objects('way', ways) 688 | elif command == '/relations': 689 | relations = [int(n) for n in args['relations'].split(',')] 690 | if args.get('mode','') == 'full': 691 | data = osm.get_objects_recursive('relation', relations) 692 | elif args.get('mode','') == 'recursive': 693 | data = osm.get_objects_recursive('relation', relations, recursive=True) 694 | else: 695 | data = osm.get_objects('relation', relations) 696 | self.send_response(200) 697 | self.send_header('Content-type', 'text/xml') 698 | self.end_headers() 699 | self.wfile.write(OSMHEAD+'\n') 700 | self.wfile.write(data) 701 | self.wfile.write('
') 702 | return 703 | except IOError: 704 | self.send_error(404,'File Not Found: %s' % self.path) 705 | 706 | 707 | ################### FUNCTIONS 708 | def runserver(port, osmdb): 709 | """ 710 | Start the http-server with the given port and osmdb object. 711 | """ 712 | try: 713 | server = HTTPServer(('', port), OSMHttpHandler) 714 | server.osmdb = osmdb 715 | print ('started httpserver...') 716 | server.serve_forever() 717 | except KeyboardInterrupt: 718 | print ('^C received, shutting down server') 719 | server.socket.close() 720 | 721 | def usage(): 722 | print (sys.argv[0] + " Version " + VERSION) 723 | print (" -h, --help: print this help information") 724 | print (" --relations=outfile: split relations from input file") 725 | print (" --ways_relations=outfile: split ways and relations from input file") 726 | print (" --server=port: start a http-Server on Port") 727 | print ("Examples:") 728 | print (" osmdb.py --relations=out.osm.bz2 germany.osm.bz2") 729 | print (" osmdb.py --ways_relations=/dev/stdout planet-latest.osm") 730 | print (" osmdb.py --server=8888 germany.osm") 731 | 732 | #################### MAIN 733 | if __name__ == '__main__': 734 | import getopt 735 | 736 | try: 737 | opts, args = getopt.getopt(sys.argv[1:], 'h', 738 | ['relations=', 'ways_relations=', 'server=', 'help']) 739 | except getopt.GetoptError: 740 | usage() 741 | sys.exit() 742 | 743 | 744 | for o, a in opts: 745 | if o in ['--relations']: 746 | if len(args) != 1: 747 | usage() 748 | sys.exit(-1) 749 | outfile = a 750 | if os.path.splitext(args[0])[1] in ['.bz2','.BZ2']: 751 | osmdb = Bz2OsmDb(args[0]) 752 | else: 753 | osmdb = OsmDb(args[0]) 754 | osmdb.write_relations(outfile) 755 | sys.exit() 756 | elif o in ['--ways_relations']: 757 | if len(args) != 1: 758 | usage() 759 | sys.exit(-1) 760 | outfile = a 761 | if os.path.splitext(args[0])[1] in ['.bz2','.BZ2']: 762 | osmdb = Bz2OsmDb(args[0]) 763 | else: 764 | osmdb = OsmDb(args[0]) 765 | osmdb.write_ways_relations(outfile) 766 | sys.exit() 767 | elif o in ['--server']: 768 | if len(args) != 1: 769 | usage() 770 | sys.exit(-1) 771 | port = int(a) 772 | if os.path.splitext(args[0])[1] in ['.bz2','.BZ2']: 773 | osmdb = Bz2OsmDb(args[0]) 774 | else: 775 | osmdb = OsmDb(args[0]) 776 | runserver(port, osmdb) 777 | sys.exit() 778 | elif o in ['--help']: 779 | usage() 780 | sys.exit() 781 | -------------------------------------------------------------------------------- /src/osm/pyosm.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # Original version by Rory McCann (http://blog.technomancy.org/) 3 | # Modifications by Christoph Lupprich (http://www.stopbeingcarbon.com) 4 | # 5 | import xml.sax.saxutils 6 | import numpy 7 | import logging 8 | log = logging.getLogger("pyosm") 9 | 10 | 11 | #################### CLASSES 12 | class Attributes(object): 13 | """ 14 | common attributes for all object types 15 | """ 16 | __slot__ = ['timestamp', 'uid', 'user', 'visible', 'version', 'changeset'] 17 | 18 | def __init__(self, attrs): 19 | self.timestamp = attrs.get('timestamp','') 20 | self.version = attrs.get('version', '') 21 | self.changeset = attrs.get('changeset','') 22 | self.uid = attrs.get('uid','') 23 | self.user = attrs.get('user','') 24 | self.visible = attrs.get('visible','') 25 | 26 | def set_attr(self, name, value): 27 | if hasattr(self, name): 28 | setattr(self,name, value) 29 | else: 30 | raise KeyError 31 | 32 | def get(self, name, default=None): 33 | if hasattr(self, name): 34 | return getattr(self,name) 35 | else: 36 | return default 37 | 38 | def get_all(self): 39 | return {'timestamp': self.timestamp, 40 | 'version': self.version, 41 | 'changeset': self.changeset, 42 | 'uid': self.uid, 43 | 'user': self.user, 44 | 'visible': self.visible} 45 | 46 | 47 | class Node(object): 48 | __slot__ = ['id', 'lat', 'lon','__attrs', '__tags'] 49 | 50 | def __init__(self, attrs, tags=None, load_tags=True, load_attrs=True): 51 | self.lon = 0.0 52 | self.lat = 0.0 53 | self.__attrs = None 54 | self.__tags = None 55 | 56 | self.id = int(attrs.pop('id')) 57 | if attrs.get('visible', '') != 'false': 58 | self.lon = float(attrs.pop('lon')) 59 | self.lat = float(attrs.pop('lat')) 60 | 61 | if load_attrs: 62 | self.__attrs = Attributes(attrs) 63 | 64 | if load_tags: 65 | self.__tags = tags 66 | 67 | def __getattr__(self, name): 68 | if name == 'tags': 69 | return self.__tags 70 | elif self.__attrs: 71 | return self.__attrs.get(name) 72 | 73 | def __getitem__(self, name): 74 | if name == 'lat': 75 | return self.lat 76 | elif name == 'lon': 77 | return self.lon 78 | elif name == 'id': 79 | return self.id 80 | elif name == 'tags': 81 | return self.__tags 82 | 83 | def __cmp__(self, other): 84 | cmp_ref = cmp(self.tags.get('ref',''), other.tags.get('ref','')) 85 | if cmp_ref: 86 | return cmp_ref 87 | cmp_name = cmp(self.tags.get('name',''), other.tags.get('name','')) 88 | if cmp_name: 89 | return cmp_name 90 | return cmp(self.id, other.id) 91 | 92 | def set_attr(self, name, value): 93 | self.__attrs.set_attr(name, value) 94 | 95 | def attributes(self): 96 | d = {'id': repr(self.id), 97 | 'lat': repr(self.lat), 98 | 'lon': repr(self.lon)} 99 | if self.__attrs: 100 | d.update(self.__attrs.get_all()) 101 | return d 102 | 103 | def bbox(self, **kwargs): 104 | return (self.lat, self.lat, self.lon, self.lon) 105 | 106 | def __repr__(self): 107 | return "Node(attrs=%r, tags=%r)" % (self.attributes(), self.__tags) 108 | 109 | 110 | class Way(object): 111 | __slot__ = ['id', '__attrs','__tags','__nodes', 'osm_parent'] 112 | 113 | def __init__(self, attrs, tags=None, nodes=None, osm_parent=None, load_tags=True, load_attrs=True, load_nodes=True): 114 | self.__nodes = None 115 | self.__attrs = None 116 | self.__tags = None 117 | 118 | self.id = int(attrs.pop('id')) 119 | self.osm_parent = osm_parent 120 | 121 | if load_nodes: 122 | self.__nodes = numpy.asarray(nodes, dtype='int64') 123 | if load_attrs: 124 | self.__attrs = Attributes(attrs) 125 | if load_tags: 126 | self.__tags = tags 127 | 128 | def __getattr__(self, name): 129 | if name == 'nodes': 130 | return self.osm_parent.get_nodes(self.__nodes) 131 | elif name == 'nodeids': 132 | return list(self.__nodes) 133 | elif name == 'tags': 134 | return self.__tags 135 | elif self.__attrs: 136 | return self.__attrs.get(name) 137 | 138 | def __getitem__(self, name): 139 | if name == 'id': 140 | return self.id 141 | elif name == 'nodes': 142 | return self.osm_parent.get_nodes(self.__nodes) 143 | elif name == 'nodeids': 144 | return list(self.__nodes) 145 | elif name == 'tags': 146 | return self.__tags 147 | 148 | def __cmp__(self, other): 149 | cmp_ref = cmp(self.tags.get('ref',''), other.tags.get('ref','')) 150 | if cmp_ref: 151 | return cmp_ref 152 | cmp_name = cmp(self.tags.get('name',''), other.tags.get('name','')) 153 | if cmp_name: 154 | return cmp_name 155 | return cmp(self.id, other.id) 156 | 157 | def set_attr(self, name, value): 158 | self.__attrs.set_attr(name, value) 159 | 160 | def attributes(self): 161 | d = {'id': repr(self.id)} 162 | if self.__attrs: 163 | d.update(self.__attrs.get_all()) 164 | return d 165 | 166 | def distance(self): 167 | """ 168 | returns the distance of the way in meters 169 | """ 170 | if len(self.nodes) < 2: 171 | return 0.0 172 | lat = numpy.array([n.lat for n in self.nodes]) * numpy.pi / 180 173 | lon = numpy.array([n.lon for n in self.nodes]) * numpy.pi / 180 174 | lat1 = lat[:-1] 175 | lat2 = lat[1:] 176 | lon1 = lon[:-1] 177 | lon2 = lon[1:] 178 | 179 | #formula see: https://en.wikipedia.org/wiki/Great-circle_distance#Computational_formulas 180 | dist = numpy.arctan(numpy.sqrt((numpy.cos(lat2)*numpy.sin(abs(lon1-lon2)))**2 + (numpy.cos(lat1)*numpy.sin(lat2) - numpy.sin(lat1)*numpy.cos(lat2)*numpy.cos(lon1-lon2))**2) / (numpy.sin(lat1)*numpy.sin(lat2) + numpy.cos(lat1)*numpy.cos(lat2)*numpy.cos(lon1-lon2))) 181 | return numpy.sum(dist) * 6372795 182 | 183 | def bbox(self, **kwargs): 184 | lat = [n.lat for n in self.nodes] 185 | lon = [n.lon for n in self.nodes] 186 | return min(lat), max(lat), min(lon), max(lon) 187 | 188 | def __repr__(self): 189 | return "Way(attrs=%r, tags=%r, nodes=%r)" % (self.attributes(), self.__tags, list(self.__nodes)) 190 | 191 | 192 | class Relation(object): 193 | __slot__ = ['id', '__attrs','__tags','__members', 'osm_parent'] 194 | 195 | def __init__(self, attrs, tags=None, members=None, osm_parent=None, load_tags=True, load_attrs=True, load_members=True): 196 | self.__members = None 197 | self.__attrs = None 198 | self.__tags = None 199 | 200 | self.id = int(attrs.pop('id')) 201 | self.osm_parent = osm_parent 202 | 203 | if load_members: 204 | self.__members = numpy.array(members, dtype=[('type','|S1'),('id',' 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | 110 | 111 | 112 | 113 | 114 | 115 | 116 | 117 | 118 | 119 | 120 | 121 | 122 | 123 | 124 | 125 | 126 | 127 | 128 | 129 | 130 | 131 | 132 | 133 | 134 | 135 | 136 | 137 | 138 | 139 | 140 | 141 | 142 | 143 | 144 | 145 | 146 | 147 | 148 | 149 | 150 | 151 | 152 | 153 | 154 | 155 | 156 | 157 | 158 | 159 | 160 | 161 | 162 | 163 | 164 | 165 | 166 | 167 | 168 | 169 | 170 | 171 | 172 | 173 | 174 | 175 | 176 | 177 | 178 | 179 | 180 | 181 | 182 | 183 | 184 | 185 | 186 | 187 | 188 | 189 | 190 | 191 | 192 | 193 | 194 | 195 | 196 | 197 | 198 | 199 | 200 | 201 | 202 | 203 | 204 | 205 | 206 | 207 | 208 | 209 | 210 | 211 | 212 | 213 | 214 | 215 | 216 | 217 | 218 | 219 | 220 | 221 | 222 | 223 | 224 | 225 | 226 | 227 | 228 | 229 | 230 | 231 | 232 | 233 | 234 | 235 | 236 | 237 | 238 | 239 | 240 | 241 | 242 | 243 | 244 | 245 | 246 | 247 | 248 | 249 | 250 | 251 | 252 | 253 | 254 | 255 | 256 | 257 | 258 | 259 | 260 | 261 | 262 | 263 | 264 | 265 | 266 | 267 | 268 | 269 | 270 | 271 | 272 | 273 | 274 | 275 | 276 | 277 | 278 | 279 | 280 | 281 | 282 | 283 | 284 | 285 | 286 | 287 | 288 | 289 | 290 | 291 | 292 | 293 | 294 | 295 | 296 | 297 | 298 | 299 | 300 | 301 | 302 | 303 | 304 | 305 | 306 | 307 | 308 | 309 | 310 | 311 | 312 | 313 | 314 | 315 | 316 | 317 | 318 | 319 | 320 | 321 | 322 | 323 | 324 | 325 | 326 | 327 | 328 | 329 | 330 | 331 | 332 | 333 | 334 | 335 | 336 | 337 | 338 | 339 | 340 | 341 | 342 | 343 | 344 | 345 | 346 | 347 | 348 | 349 | 350 | 351 | 352 | 353 | 354 | 355 | 356 | 357 | 358 | 359 | 360 | 361 | 362 | 363 | 364 | 365 | 366 | 367 | 368 | 369 | 370 | 371 | 372 | 373 | 374 | 375 | 376 | 377 | 378 | 379 | 380 | 381 | 382 | 383 | 384 | 385 | 386 | 387 | 388 | 389 | 390 | 391 | 392 | 393 | 394 | 395 | 396 | 397 | 398 | 399 | 400 | 401 | 402 | 403 | 404 | 405 | 406 | 407 | 408 | 409 | 410 | 411 | 412 | 413 | 414 | 415 | 416 | 417 | 418 | 419 | 420 | 421 | 422 | 423 | 424 | 425 | 426 | 427 | 428 | 429 | 430 | 431 | 432 | 433 | 434 | 435 | 436 | 437 | 438 | 439 | 440 | 441 | 442 | 443 | 444 | 445 | 446 | 447 | 448 | 449 | 450 | 451 | 452 | 453 | 454 | 455 | 456 | 457 | 458 | 459 | 460 | 461 | 462 | 463 | 464 | 465 | 466 | 467 | 468 | 469 | 470 | 471 | 472 | 473 | 474 | 475 | 476 | 477 | 478 | 479 | 480 | 481 | 482 | 483 | 484 | 485 | 486 | 487 | 488 | 489 | 490 | 491 | 492 | 493 | 494 | 495 | 496 | 497 | 498 | 499 | 500 | 501 | 502 | 503 | 504 | 505 | 506 | 507 | 508 | 509 | 510 | 511 | 512 | 513 | 514 | 515 | 516 | 517 | 518 | 519 | 520 | 521 | 522 | 523 | 524 | 525 | 526 | 527 | 528 | 529 | 530 | 531 | 532 | 533 | 534 | 535 | 536 | 537 | 538 | 539 | 540 | 541 | 542 | 543 | 544 | 545 | 546 | 547 | 548 | 549 | 550 | 551 | 552 | 553 | 554 | 555 | 556 | 557 | 558 | 559 | 560 | 561 | 562 | 563 | 564 | 565 | 566 | 567 | 568 | 569 | 570 | 571 | 572 | 573 | 574 | 575 | 576 | 577 | 578 | -------------------------------------------------------------------------------- /tests/osmfiles/multipolygon1.osm: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | 107 | -------------------------------------------------------------------------------- /tests/test_multipolygon.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/python 2 | import os 3 | import sys 4 | import unittest 5 | 6 | srcDir = os.path.abspath('../src/osm') 7 | sys.path.insert(1, srcDir) 8 | 9 | import pyosm 10 | import multipolygon 11 | 12 | 13 | class OSMXMLFileTests(unittest.TestCase): 14 | def setUp(self): 15 | self.osm_file = 'osmfiles/multipolygon1.osm' 16 | self.osm = pyosm.OSMXMLFile(self.osm_file) 17 | 18 | def tearDown(self): 19 | pass 20 | 21 | def test_multipolygon(self): 22 | mp = multipolygon.multipolygon(self.osm.relations[179755]) 23 | mp.status() 24 | 25 | def test_josmfile(self): 26 | mp = multipolygon.multipolygon(self.osm.relations[179755]) 27 | mp.write_josm_file('testoutput/josmfile.xml') 28 | 29 | def test_osmosisfile(self): 30 | mp = multipolygon.multipolygon(self.osm.relations[179755]) 31 | mp.write_osmosis_file('testoutput/josmfile.xml') 32 | 33 | def test_point_in_polygon(self): 34 | mp = multipolygon.multipolygon(self.osm.relations[179755]) 35 | points = [(9.58533328102,47.66978302865), 36 | (9.58518367709,47.66978913432), 37 | (9.58497428566,47.66984484554), 38 | (9.58481320699,47.66985426283), 39 | (9.58466333116,47.66985520476), 40 | (9.58451372723,47.66986131043)] 41 | inside = mp.inside(points=points) 42 | self.assertAlmostEqual(inside.sum(), 4) 43 | 44 | 45 | if __name__ == '__main__': 46 | if not os.path.exists('testoutput'): 47 | os.mkdir('testoutput') 48 | unittest.main() 49 | -------------------------------------------------------------------------------- /tests/test_osmdb: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | #################### bz2osmdb commandlines 4 | echo TEST1 5 | echo "TEST1-----------------------" > test_osmdb_out.txt 6 | ../src/osm/osmdb.py --help >> test_osmdb_out.txt 7 | 8 | echo TEST2 9 | echo "TEST2-----------------------" >> test_osmdb_out.txt 10 | ../src/osm/osmdb.py --ways_relations=/dev/stdout ../../../osm_files/romania.osm.bz2| head >>test_osmdb_out.txt 11 | 12 | echo TEST3 13 | echo "TEST3-----------------------" >> test_osmdb_out.txt 14 | ../src/osm/osmdb.py --relations=/dev/stdout ../../../osm_files/romania.osm.bz2| head >>test_osmdb_out.txt 15 | 16 | echo TEST4 17 | echo "TEST4-----------------------" >> test_osmdb_out.txt 18 | ../src/osm/osmdb.py --relations=/dev/stdout ../../../osm_files/romania.osm.bz2| tail >>test_osmdb_out.txt 19 | 20 | #################### bz2osmdb server 21 | PORT=8888 22 | OSM_FILE=../../../osm_files/germany.osm.bz2 23 | ../src/osm/osmdb.py --server=$PORT $OSM_FILE & 24 | SERVER_PID=$! 25 | ## wait for server startup 26 | sleep 60 27 | 28 | wget -Obz2osmdb_nodes.xml http://localhost:$PORT/nodes?nodes=437498388,437498385,180721525 29 | 30 | wget -Obz2osmdb_ways.xml http://localhost:$PORT/ways?ways=37426524,37426525,32466511 31 | wget -Obz2osmdb_ways_full.xml http://localhost:$PORT/ways?ways=37426524,37426525,32466511\&mode=full 32 | 33 | wget -Obz2osmdb_relation.xml http://localhost:$PORT/relations?relations=167920,131414 34 | wget -Obz2osmdb_relation_full.xml http://localhost:$PORT/relations?relations=1111111\&mode=full 35 | wget -Obz2osmdb_relation_recursive.xml http://localhost:$PORT/relations?relations=1111111\&mode=recursive 36 | 37 | kill $SERVER_PID 38 | 39 | #################### osmdb commandlines 40 | OSM_FILE=/osm/germany.osm 41 | 42 | echo TEST5 43 | echo TEST5----------------------- >> test_osmdb_out.txt 44 | ../src/osm/osmdb.py --help >> test_osmdb_out.txt 45 | 46 | echo TEST5 47 | echo TEST5----------------------- >> test_osmdb_out.txt 48 | ../src/osm/osmdb.py --ways_relations=/dev/stdout $OSM_FILE | head >>test_osmdb_out.txt 49 | 50 | echo TEST6 51 | echo TEST6----------------------- >> test_osmdb_out.txt 52 | ../src/osm/osmdb.py --relations=/dev/stdout $OSM_FILE | head >>test_osmdb_out.txt 53 | 54 | #################### osmdb server 55 | PORT=8888 56 | ../src/osm/osmdb.py --server=$PORT $OSM_FILE & 57 | SERVER_PID=$! 58 | ## wait for server startup 59 | sleep 20 60 | 61 | wget -Oosmdb_nodes.xml http://localhost:$PORT/nodes?nodes=437498388,437498385,180721525 62 | 63 | wget -Oosmdb_ways.xml http://localhost:$PORT/ways?ways=37426524,37426525,32466511 64 | wget -Oosmdb_ways_full.xml http://localhost:$PORT/ways?ways=37426524,37426525,32466511\&mode=full 65 | 66 | wget -Oosmdb_relation.xml http://localhost:$PORT/relations?relations=167920,131414 67 | wget -Oosmdb_relation_full.xml http://localhost:$PORT/relations?relations=1111111\&mode=full 68 | wget -Oosmdb_relation_recursive.xml http://localhost:$PORT/relations?relations=1111111\&mode=recursive 69 | 70 | kill $SERVER_PID 71 | 72 | 73 | 74 | 75 | -------------------------------------------------------------------------------- /tests/test_osmdb.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/python 2 | import os 3 | import sys 4 | import unittest 5 | import logging 6 | 7 | srcDir = os.path.abspath('../src/osm') 8 | sys.path.insert(1, srcDir) 9 | 10 | import osmdb 11 | log = logging.getLogger(__name__) 12 | 13 | class OsmDbTests(unittest.TestCase): 14 | def setUp(self): 15 | # local uncompressed file of the planet file 16 | log.info('load planet') 17 | self.db = osmdb.OsmDb('/store/osm/planet-latest.osm') 18 | 19 | def tearDown(self): 20 | pass 21 | 22 | def test_get_objects(self): 23 | #db = osmdb.Bz2OsmDb('/store/osm/files/australia.osm.bz2') 24 | #db = osmdb.OsmDb('/store/osm/files/australia.osm') 25 | 26 | log.info('Node: small id') 27 | ret = self.db.get_objects('node',[1]) 28 | log.info(' return length %i', len(ret)) 29 | 30 | log.info('Node: regular ids') 31 | ret = self.db.get_objects('node',[579259,579260]) 32 | log.info(' return length %i', len(ret)) 33 | 34 | log.info('Node: large ids') 35 | ret = self.db.get_objects('node',[12345678900]) 36 | log.info(' return length %i', len(ret)) 37 | 38 | log.info('Way: small id') 39 | ret = self.db.get_objects('way',[1]) 40 | log.info(' return length %i', len(ret)) 41 | 42 | log.info('Way: regular ids') 43 | ret = self.db.get_objects('way',[174372276,168734042]) 44 | log.info(' return length %i', len(ret)) 45 | 46 | log.info('Way: large ids') 47 | ret = self.db.get_objects('way',[12345678900]) 48 | log.info(' return length %i', len(ret)) 49 | 50 | log.info('Relation: small id') 51 | ret = self.db.get_objects('relation',[1]) 52 | log.info(' return length %i', len(ret)) 53 | 54 | log.info('Relation: regular ids') 55 | ret = self.db.get_objects('relation',[6188]) 56 | log.info(' return length %i', len(ret)) 57 | 58 | log.info('Relation: large ids') 59 | ret = self.db.get_objects('relation',[12345678900]) 60 | log.info(' return length %i', len(ret)) 61 | 62 | log.info('Relation: regular id, recursive call') 63 | ret = self.db.get_objects_recursive('relation',[6188], True) 64 | log.info(' return length %i', len(ret)) 65 | 66 | 67 | class Bz2OsmDbTests(unittest.TestCase): 68 | def setUp(self): 69 | # local bz2 compressed file of australia file 70 | log.info('load australia') 71 | self.db = osmdb.Bz2OsmDb('/store/osm/files/australia.osm.bz2') 72 | 73 | def tearDown(self): 74 | pass 75 | 76 | def test_get_objects(self): 77 | log.info('Node: small id') 78 | ret = self.db.get_objects('node',[1]) 79 | log.info(' return length %i', len(ret)) 80 | 81 | log.info('Node: regular ids') 82 | ret = self.db.get_objects('node',[579259,579260]) 83 | log.info(' return length %i', len(ret)) 84 | 85 | log.info('Node: large ids') 86 | ret = self.db.get_objects('node',[12345678900]) 87 | log.info(' return length %i', len(ret)) 88 | 89 | log.info('Way: small id') 90 | ret = self.db.get_objects('way',[1]) 91 | log.info(' return length %i', len(ret)) 92 | 93 | log.info('Way: regular ids') 94 | ret = self.db.get_objects('way',[174372276,168734042]) 95 | log.info(' return length %i', len(ret)) 96 | 97 | log.info('Way: large ids') 98 | ret = self.db.get_objects('way',[12345678900]) 99 | log.info(' return length %i', len(ret)) 100 | 101 | log.info('Relation: small id') 102 | ret = self.db.get_objects('relation',[1]) 103 | log.info(' return length %i', len(ret)) 104 | 105 | log.info('Relation: regular ids') 106 | ret = self.db.get_objects('relation',[6188]) 107 | log.info(' return length %i', len(ret)) 108 | 109 | log.info('Relation: large ids') 110 | ret = self.db.get_objects('relation',[12345678900]) 111 | log.info(' return length %i', len(ret)) 112 | 113 | log.info('Relation: regular id, recursive call') 114 | ret = self.db.get_objects_recursive('relation',[6188], True) 115 | log.info(' return length %i', len(ret)) 116 | 117 | if __name__ == '__main__': 118 | logging.basicConfig(level=logging.INFO) 119 | unittest.main() 120 | -------------------------------------------------------------------------------- /tests/test_pyosm.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/python 2 | import os 3 | import sys 4 | import unittest 5 | import logging 6 | 7 | srcDir = os.path.abspath('../src/osm') 8 | sys.path.insert(1, srcDir) 9 | import pyosm 10 | 11 | log = logging.getLogger(__name__) 12 | 13 | class OSMXMLFileTests(unittest.TestCase): 14 | def setUp(self): 15 | self.osm_file = 'osmfiles/multipolygon1.osm' 16 | self.osm = pyosm.OSMXMLFile(self.osm_file) 17 | 18 | def tearDown(self): 19 | pass 20 | 21 | def test_osm_objects(self): 22 | self.osm.statistic() 23 | r = list(self.osm.relations.values())[-1] 24 | log.info('Single relation representation: %s', r) 25 | w = list(self.osm.ways.values())[-1] 26 | log.info('\nSingle way representation: %s', w) 27 | n = list(self.osm.nodes.values())[1] 28 | log.info('Single node representation: %s', n) 29 | 30 | log.info('Nodes of a Way: %s', w.nodes) 31 | log.info('Nodeids of a Way: %s', w.nodeids) 32 | 33 | log.info('Member Data of a Relation: %s', r.member_data) 34 | log.info('Members of a Relation: %s', r.members) 35 | 36 | def test_osm_itemgetter(self): 37 | log.info('relation item test:') 38 | r = list(self.osm.relations.values())[0] # get first relation 39 | for it in ['id','members','member_data','tags','bbox']: 40 | log.info(' %s=%s', it, r[it]) 41 | log.info('way item test:') 42 | w = list(self.osm.ways.values())[0] # get first way 43 | for it in ['id','nodes','nodeids','tags','bbox']: 44 | log.info(' %s=%s', it, w[it]) 45 | log.info('node item test:') 46 | n = list(self.osm.nodes.values())[0] # get first node 47 | for it in ['id','lat', 'lon','tags']: 48 | log.info(' %s=%s', it, n[it]) 49 | 50 | def test_merge_write(self): 51 | osm2 = pyosm.OSMXMLFile(filename='osmfiles/josm_download.osm') 52 | log.info('osm2 stat befor merge') 53 | osm2.statistic() 54 | osm2.merge(self.osm) 55 | log.info('osm2 stat after merge') 56 | osm2.statistic() 57 | osm2.write('testoutput/result_merge_write.osm') 58 | 59 | def test_geometry(self): 60 | log.info('geometry tests:') 61 | w = list(self.osm.ways.values())[0] # get first way 62 | log.info(' distance way0: %f' % w.distance()) 63 | log.info(' bbox way0: %s' % str(w.bbox())) 64 | r = list(self.osm.relations.values())[0] # get first relation 65 | log.info(' distance rel0: %f' % r.distance()) 66 | log.info(' bbox rel0: %s' % str(r.bbox())) 67 | germany = pyosm.OSMXMLFile('osmfiles/germany_borders.osm') 68 | rb = germany.relations[1111111] 69 | log.info(' border bbox %s' % str(rb.bbox())) 70 | log.info(' border bbox %s' % str(rb.bbox(recursive=True))) 71 | log.info(' border length %f' % rb.distance()) 72 | log.info(' border length recursive %f' % rb.distance(recursive=True)) 73 | log.info(' border length recursive %f' % rb.distance(recursive=True, roles=['outer',''])) 74 | 75 | 76 | if __name__ == '__main__': 77 | if not os.path.exists('testoutput'): 78 | os.mkdir('testoutput') 79 | logging.basicConfig(level=logging.INFO) 80 | unittest.main() -------------------------------------------------------------------------------- /tools/osmhistory.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | import sys, os 3 | import re, math 4 | import urllib 5 | import httplib 6 | 7 | PYOSM_DIR = os.path.join(os.path.dirname(__file__), '../src') 8 | sys.path.append(PYOSM_DIR) 9 | from osm import pyosm 10 | 11 | VERSION = "0.0.2" 12 | 13 | #################### CONSTANTS 14 | URL='www.openstreetmap.org' 15 | API='/api/0.6' 16 | 17 | #################### FUNCTIONS 18 | def elementhistory(date, relations, ways, nodes): 19 | osmhist = pyosm.OSMXMLFile() 20 | 21 | ## working stacks for all object types 22 | relation_stack = set([int(r) for r in relations]) 23 | way_stack = set([int(w) for w in ways]) 24 | node_stack = set([int(n) for n in nodes]) 25 | 26 | ## load recursively all missing relations 27 | while relation_stack: 28 | relid = relation_stack.pop() 29 | rel = bisect('relation', relid, date) 30 | osmhist.merge(rel) 31 | for mtype, mid, mrole in rel.relations[relid].member_data: 32 | if mtype == 'r': 33 | if mid not in osmhist.relations: 34 | relation_stack.add(mid) 35 | elif mtype == 'w': 36 | way_stack.add(mid) 37 | elif mtype == 'n': 38 | node_stack.add(mid) 39 | else: 40 | raise ValueError('Unknown member type: "%r"' % mtype) 41 | 42 | ## load all ways 43 | for wayid in way_stack: 44 | way = bisect('way', wayid, date) 45 | osmhist.merge(way) 46 | node_stack.update(way.ways[wayid].nodeids) 47 | 48 | ## load all nodes 49 | for nodeid in node_stack: 50 | node = bisect('node', nodeid, date) 51 | osmhist.merge(node) 52 | 53 | return osmhist 54 | 55 | 56 | def bisect(objtype, objid, date, maxversion=None ): 57 | conn = httplib.HTTPConnection(URL) 58 | osmobj = None 59 | minversion = 1 60 | log('bisect:' + objtype, objid) 61 | if not maxversion: 62 | url = '%s/%ss?%ss=%d' %(API, objtype, objtype, objid) 63 | else: 64 | url = '%s/%s/%d/%d' %(API, objtype, objid, maxversion) 65 | 66 | log(' bisect:', url) 67 | 68 | conn.request('GET', url) 69 | ans = conn.getresponse() 70 | content=ans.read() 71 | curr_osm = pyosm.OSMXMLFile(content=content) 72 | curr_obj = getobject(curr_osm, objtype, objid) 73 | newest_version = int(curr_obj.version) 74 | 75 | if curr_obj.timestamp < date: 76 | return curr_osm 77 | 78 | bysect_version = 2**int(math.log(int(curr_obj.version)-1,2)) 79 | bysect_step = bysect_version 80 | 81 | while bysect_step: 82 | url = '%s/%s/%d/%d' %(API, objtype, objid, bysect_version) 83 | log(' bisect:', url) 84 | conn.request('GET', url) 85 | ans = conn.getresponse() 86 | bysect_osm = pyosm.OSMXMLFile(content=ans.read()) 87 | bysect_obj = getobject(bysect_osm, objtype, objid) 88 | 89 | bysect_step = int(bysect_step / 2) 90 | if bysect_obj.timestamp < date: 91 | curr_osm = bysect_osm 92 | curr_obj = bysect_obj 93 | bysect_version += bysect_step 94 | while bysect_version >= newest_version and bysect_step: 95 | bysect_step = int(bysect_step / 2) 96 | bysect_version -= bysect_step 97 | else: 98 | bysect_version -= bysect_step 99 | 100 | if newest_version > int(curr_obj.version): 101 | curr_obj.tags['osmhistory:old_version_date'] = str(int(curr_obj.version)) + '_' + date 102 | curr_obj.set_attr('version', str(newest_version)) 103 | 104 | conn.close() 105 | return curr_osm 106 | 107 | def getobject(osmobj, objtype, objid): 108 | if objtype == 'node': 109 | obj = osmobj.nodes[objid] 110 | elif objtype == 'way': 111 | obj = osmobj.ways[objid] 112 | elif objtype == 'relation': 113 | obj = osmobj.relations[objid] 114 | else: 115 | raise ValueError 116 | 117 | return obj 118 | 119 | def log(s, ss=''): 120 | if True: 121 | sys.stdout.write(str(s) + str(ss) + '\n') 122 | 123 | 124 | def usage(): 125 | print sys.argv[0] + " Version " + VERSION 126 | print " -h, --help: print this help information" 127 | print " -t, --timestamp: date for the history. format: YYYY-MM-DD" 128 | print " -o, --outfile: filename for the output filename" 129 | print " -n, --nodes: comma separated list of node ids" 130 | print " -w, --ways: comma separated list of way ids" 131 | print " -r, --relations: comma separated list of relation ids" 132 | print "Examples:" 133 | print " osmhistory.py -t 2009-10-01 -w 13415127,26802382 -o foo.osm" 134 | print " osmhistory.py -t 2009-10-01 --relations=21328 -o rel_21628.osm" 135 | sys.exit() 136 | 137 | #################### MAIN 138 | if __name__ == '__main__': 139 | import getopt 140 | 141 | try: 142 | opts, args = getopt.getopt(sys.argv[1:], 'ht:o:r:w:n:', 143 | ['help', 'timestamp=', 'outfile=', 'relations=', 'ways=', 'nodes=']) 144 | except getopt.GetoptError: 145 | usage() 146 | 147 | ## default values 148 | outfile = 'out.osm' 149 | nodes = [] 150 | ways = [] 151 | relations = [] 152 | 153 | for o, a in opts: 154 | if o in ['-h', '--help']: 155 | usage() 156 | elif o in ['-t', '--timestamp']: 157 | if re.match('20[0-9]{2}-[0-9]{2}-[0-9]{2}$', a): 158 | date = a 159 | else: 160 | print 'Error: invalid date' 161 | usage() 162 | elif o in ['-o', '--outfile']: 163 | outfile = a 164 | elif o in ['-n', '--nodes']: 165 | if re.match('[1-9][0-9\,]*[0-9]$', a): 166 | nodes = a.split(',') 167 | else: 168 | print 'Error: invalid nodes list' 169 | usage() 170 | elif o in ['-w', '--ways']: 171 | if re.match('[1-9][0-9,]*[0-9]$', a): 172 | ways = a.split(',') 173 | else: 174 | print 'Error: invalid ways list' 175 | usage() 176 | elif o in ['-r', '--relations']: 177 | if re.match('[1-9][0-9,]*[0-9]$', a): 178 | relations = a.split(',') 179 | else: 180 | print 'Error: invalid relations list' 181 | usage() 182 | 183 | osm = elementhistory(date, relations, ways, nodes) 184 | osm.write(outfile) 185 | 186 | 187 | 188 | -------------------------------------------------------------------------------- /tools/relation2gpx.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | 3 | import sys, os 4 | import xml.dom.minidom 5 | 6 | PYOSM_DIR = os.path.join(os.path.dirname(__file__), '../src') 7 | sys.path.append(PYOSM_DIR) 8 | from osm import pyosm 9 | 10 | #################### CLASSES 11 | class osm_gpx_exporter(object): 12 | gpx_template = """ 13 | 16 | 17 | osm_gpx_exporter 18 | 19 | 20 | """ 21 | 22 | def __init__(self, gpx_filename): 23 | self.gpx_filename = gpx_filename 24 | self.init_gpx() 25 | 26 | def init_gpx(self): 27 | self.gpx_dom = xml.dom.minidom.parseString(self.gpx_template) 28 | self.gpx_root = self.gpx_dom.documentElement 29 | 30 | def append_relations(self, relations=[], recursive=True): 31 | """ 32 | append an osm object to a gpx track 33 | relation --> track (trk) 34 | way --> track segment (trkseg) 35 | node --> track point (trkpt) 36 | """ 37 | for rel in relations: 38 | trk = self.gpx_dom.createElement('trk') 39 | self.gpx_root.appendChild(trk) 40 | for m, role in rel.members: 41 | if type(m) != pyosm.Way: 42 | continue 43 | trkseg = self.gpx_dom.createElement('trkseg') 44 | trk.appendChild(trkseg) 45 | for node in m.nodes: 46 | trkpt = self.gpx_dom.createElement('trkpt') 47 | trkpt.setAttribute('lat', str(node.lat)) 48 | trkpt.setAttribute('lon', str(node.lon)) 49 | trkseg.appendChild(trkpt) 50 | 51 | def write(self): 52 | """ 53 | export the gpx_dom into a file 54 | """ 55 | open(self.gpx_filename,'wt').write(self.gpx_dom.toprettyxml(" ")) 56 | 57 | 58 | #################### FUNCTIONS 59 | def usage(): 60 | print "usage: relation2gpx.py [-o GPXFILE] -r relation1,relation2,..." 61 | print "load relations from the OSM API and create gpx files" 62 | print " -h, --help: print this help message" 63 | print " -o, --outfile: specify the filename of the gpx file" 64 | print " -r, --relations: commaseperated list of relations" 65 | 66 | 67 | #################### MAIN 68 | if __name__ == '__main__': 69 | import getopt 70 | import urllib 71 | 72 | try: 73 | opts, args = getopt.getopt(sys.argv[1:], 'o:r:', 74 | ['outfile=', 'relations=']) 75 | except getopt.GetoptError: 76 | usage() 77 | sys.exit(1) 78 | 79 | outfile='out.gpx' 80 | relids = [] 81 | 82 | for o, a in opts: 83 | if o in ['-o', '--outfile']: 84 | outfile = a 85 | elif o in ['-r', '--relations']: 86 | relids = a.split(',') 87 | elif o in ['-h', '--help']: 88 | usage() 89 | sys.exit() 90 | 91 | if not relids: 92 | usage() 93 | sys.exit(1) 94 | 95 | API='http://www.openstreetmap.org/api/0.6' 96 | gpx_exp = osm_gpx_exporter(outfile) 97 | 98 | for relid in relids: 99 | osmfile = urllib.urlopen('%s/relation/%s/full' %(API,relid)) 100 | osmobj = pyosm.OSMXMLFile(osmfile) 101 | gpx_exp.append_relations(osmobj.relations.values()) 102 | 103 | gpx_exp.write() 104 | 105 | 106 | --------------------------------------------------------------------------------