Repository: Artoria2e5/PRCoords Branch: master Commit: a853b1fc19ee Files: 51 Total size: 138.8 KB Directory structure: gitextract_j7s_ktue/ ├── .gitignore ├── .npmignore ├── .vscode/ │ └── settings.json ├── LICENSE.gplv3 ├── README.md ├── approx/ │ └── approx.ipynb ├── cpp/ │ ├── Makefile │ ├── badmath.hh │ ├── bench.cc │ ├── bench4.sh │ ├── bench_out/ │ │ ├── README.md │ │ ├── native_nick.md │ │ ├── native_stdsin.md │ │ ├── nick.md │ │ └── stdsin.md │ ├── demo.cc │ ├── libprcoords.cc │ └── prcoords.h ├── docs/ │ ├── demo.html │ ├── index.md │ └── proj4_plugin.js ├── haskell/ │ ├── PRCoords.cabal │ ├── PRCoords.hs │ └── Setup.hs ├── js/ │ ├── .npmignore │ ├── PRCoords.d.ts │ ├── PRCoords.js │ ├── misc/ │ │ ├── insane_is_in_china.js │ │ └── package.json │ └── package.json ├── julia/ │ ├── Project.toml │ └── src/ │ └── PRCoords.jl ├── lua/ │ └── PRCoords.lua ├── matlab/ │ ├── PRCoords.m │ ├── bd_gcj.m │ ├── bd_gcj_precise.m │ ├── bd_wgs.m │ ├── bd_wgs_precise.m │ ├── caijun_precise.m │ ├── gcj_bd.m │ ├── gcj_wgs.m │ ├── gcj_wgs_precise.m │ ├── wgs_bd.m │ └── wgs_gcj.m ├── package.json ├── pgsql/ │ ├── distance_agg.sql │ ├── prcoords.sql │ └── prcoords_postgis.sql ├── py/ │ ├── prcoords.py │ └── setup.py └── racket/ └── prcoords.rkt ================================================ FILE CONTENTS ================================================ ================================================ FILE: .gitignore ================================================ py/*/ cpp/*.exe cpp/*.a cpp/*.dll cpp/*.so cpp/*.o cpp/*.obj cpp/*.def cpp/*.lib cpp/*.exp node_modules julia/.vscode/settings.json cpp/nanobench.h cpp/bench cpp/demo ================================================ FILE: .npmignore ================================================ # npm sucks and i can only put things under git root /* !/js js/misc !/doc ================================================ FILE: .vscode/settings.json ================================================ { "files.associations": { "*.embeddedhtml": "html", "iostream": "cpp" } } ================================================ FILE: LICENSE.gplv3 ================================================ GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU General Public License is a free, copyleft license for software and other kinds of works. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Use with the GNU Affero General Public License. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. {one line to give the program's name and a brief idea of what it does.} Copyright (C) {year} {name of author} This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . Also add information on how to contact you by electronic and paper mail. If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: {project} Copyright (C) {year} {fullname} This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an "about box". You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see . The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read . ================================================ FILE: README.md ================================================ PRCoords ======== People's Rectified Coordinates (PRCoords) is a cross-language implementation of "public secret" Chinese coordinate obfuscation methods including GCJ-02 and BD-09, along with general deobfuscation methods previously established in [ChinaMapShift][], [eviltransform][], and [geoChina][]. (Referring to the process of replacing straight lines with wavy ones as a "transform" is euphemism overdone.) For a background on China's geographic obfuscation, see [Restrictions on geographic data in China](https://en.wikipedia.org/wiki/Restrictions_on_geographic_data_in_China#Coordinate_systems) and [中华人民共和国测绘限制](https://zh.wikipedia.org/wiki/中华人民共和国测绘限制) on Wikipedia. [ChinaMapShift]: https://gist.github.com/anonymous/e7c6f67555099180ce1ae8da4ba2c513 [geoChina]: https://github.com/caijun/geoChina/blob/master/R/cst.R [eviltransform]: https://github.com/googollee/eviltransform Languages --------- - [x] JavaScript ([`npm install prcoords`](https://www.npmjs.com/package/prcoords)) [![](https://data.jsdelivr.com/v1/package/npm/prcoords/badge)](https://www.jsdelivr.com/package/npm/prcoords) * Web demo: https://artoria2e5.github.io/PRCoords/demo * Now with AMD support and faux `__esModule` interop for Babel and TypeScript! - [x] Python ([`pip install prcoords`](https://pypi.org/project/prcoords/)) - [x] \(Obj-\)C/C++ (C ABI) * [x] Makefile with `install` - [ ] Ruby - [ ] Swift - [ ] C# - [x] Haskell (GCJ only; data structure incomplete) * need to move googollee/eviltransform#54 here sometime. - [ ] Java - [x] Matlab/Octave - [x] PGSQL - [ ] Typed Racket * is it done? (should I split them into submodules?) For languages not yet supported, we recommend you to check for [eviltransform][] (MIT) or [geoChina][] (GPLv3, R) instead. API --- PRCoord's APIs operate on, and returns, dedicated structures for coordinates. In API names, we generally refer to WGS-84 as `wgs`, GCJ-02 as `gcj`, and BD-09 (lat-lon) as `bd`. ### Inverse functions The obfuscations generally have these properties to maintain basic usefulness: 1. `obfs(coord)` is sort of close to `coord`. 2. `obfs(a) - obfs(b)` is usually close to `a - b`. (The closer `a` and `b` are to each other, the better it works.) In general two approaches of inverting the "forward" obfuscations, or working from `obfs(coord)` to `coord`, are implemented: * _Run it backwards_: `obfs(coord)` is never too far from `coord`, so just use  `obfs(obfs(coord)) - obfs(coord)` to estimate `obfs(coord) - coord`. * _Iterate a bit_: Get a rough `guess` somehow, and just use property 2 to estimate the remaining error as `obfs(guess) - obfs(coord)` and correct the `guess`. You can read on the demo page about how well these methods work from the `ΔRoundtrip` entry. Unless you are doing archival work, you generally don't have to iterate. ### The "in China" sanity check Typically PRCoords is only supposed to be ran on obfuscated input data, which are primarily Chinese coordinates. For this reason, initial implementations include this [very very rough](https://news.ycombinator.com/item?id=10965506) sanity check that spans a rectangular region on a mercator-projected map. This check can be overridden by passing a boolean value, or may be not at all implemented in certain languages if I am not in the right mood for doing silly things. There is an "insane" sanity check intended to approximate the range of Google and Baidu's distortion, intended for use by [IITC](https://iitc.me): [`js/insane_is_in_china.js`](https://github.com/Artoria2e5/PRCoords/blob/master/js/insane_is_in_china.js). It is basically a ray-casting polygon check with 70 vertices. You, as the caller, should still be responsible for telling whether a point is part of the gov-screwed Chinese data. FAQ --- ### Why another wheel? * Correctness * Public Domain * Clean API based on pairs of coordinates * Need to find a place for this sarcastic name ### Can the systems be described as WKT or proj-strings? Not directly as a datum, because in both representations a datum is either "sane" (no non-linearity in 3D, Helmert possible) or a big table of grids. It should be possible to describe the two CS with a `PROJECTION` entry as a `PROJCS`. Since a `PROJCS` cannot be nested in another, the BD transformation must be described using WGS84 and a fuzed GCJ-BD projection. The situation is similar with [Baidu "Meractor"](https://github.com/gumblex/cntms/commit/bbde4006adeb92f48da1ff7d1f88da393d382f8a).
Speculative WKT/PROJ4 ```js PROJCS["Baidu 2009, Pseudo-Mercator", GEOGCS["WGS 84", DATUM["WGS_1984", SPHEROID["WGS 84",6378137,298.257223563, AUTHORITY["EPSG","7030"]], AUTHORITY["EPSG","6326"]], PRIMEM["Greenwich",0, AUTHORITY["EPSG","8901"]], UNIT["degree",0.0174532925199433, AUTHORITY["EPSG","9122"]], AUTHORITY["EPSG","4326"]], PROJECTION["CN_Obfs_Baidu_2009_Mercator"], AXIS["x",east], AXIS["y",north], UNIT["metre",1, AUTHORITY["EPSG","9001"]], EXTENSION["PROJ4","+proj=baidumerc +units=m +nadgrids=@null +wktext +no_defs"], AUTHORITY["EPSG","888002"]] PROJCS["Chinese BSM 2002, Pseudo-Ellipsoidal", GEOGCS["WGS 84", AUTHORITY["EPSG","4326"]], PROJECTION["CN_Obfs_GCJ_2002_Ellipsoidal"], AXIS["longitude",east], AXIS["latitude",north], UNIT["degree",0.0174532925199433, AUTHORITY["EPSG","9122"]], EXTENSION["PROJ4","+proj=gcjlonglat +units=deg +nadgrids=@null +wktext +no_defs"], AUTHORITY["EPSG","888000"]] ```
The good people at proj4js has made their stuff [very easy to extend](https://github.com/proj4js/proj4js/issues/358). Here is [an example](https://runkit.com/artoria2e5/proj4-plugin-prcoords) (backed up in [`docs/proj4_plugin.js`](https://github.com/Artoria2e5/PRCoords/blob/master/docs/proj4_plugin.js) in case RunKit goes down) of how to add PRCoords support to proj4js. ### Should I use fast fp math? Yes. Nobody knows what the original looks like anyways, so what's wrong with letting the compiler recombine a bit more? You can't be more off than the one-meter random error (in "EMQ") anyways. Or tinker with 32-bit floats and fixed-point numbers. Or try approximation tools like [Sollya](http://sollya.gforge.inria.fr/) or [MC++](https://omega-icl.github.io/mcpp/). Really, just search on the Internet for "\ Taylor Chebyshev Model". You only need less than 1e-6 error on a [not-very-large slice](https://github.com/Artoria2e5/PRCoords/blob/a3a8bb8/js/PRCoords.js#L91) of the Earth anyways. I threw TaylorModels.jl at GCJ-02, and got ~~decent~~ results out of it. Still too lazy to put it in code though. Check out [approx/approx.ipynb](https://github.com/Artoria2e5/PRCoords/blob/master/approx/approx.ipynb). (Nope, not decent. Gotta do it properly some day, just don't use the notebook and expect it to work!) I tried another route with the C++ version using a devmaster user Nick's `sinpi()` approximation. It seems to be good enough for 1e-6: check out [cpp/bench_out](https://github.com/Artoria2e5/PRCoords/tree/master/cpp/bench_out) and [cpp/badmath.hh](https://github.com/Artoria2e5/PRCoords/blob/master/cpp/badmath.hh). Physical PRCoords ----------------- You can print out a minimal copy of PRCoords with [this PDF file](https://commons.wikimedia.org/wiki/File:PRcoords_Cheatsheet.pdf). I am working on some better options [in issue #2](https://github.com/Artoria2e5/PRCoords/issues/2). A fairly simple tote bag with an older version of the PDF is [available from Teespring](https://teespring.com/miniprcoords-tote-v1). Feel free to print and sell t-shirts with the PDF file! It is put in the Public Domain, so you don't have to pay me for that. You can always fund my subversive activities on [Patreon](https://www.patreon.com/artoria2e5) though. License ------- Unless otherwise mentioned, all files in this package, including this README file, are dual-licensed under: * [CC0 1.0 Public Domain Dedication](https://creativecommons.org/publicdomain/zero/1.0/) * [GNU General Public License (version 3 or up)](https://gnu.org/licenses/gpl.html) GPL is only included for fun here. Sources ------- * [Algorithm.Coords.Converter](https://archive.is/20130815104734/emq.googlecode.com/svn/emq/src/Algorithm/Coords/Converter.java) from [EMQ](https://code.google.com/archive/p/emq/) ([GitHub mirror](https://github.com/richardyu-au/emq)) is probably *the* GCJ leak. It is a JSP project "for demonstrating GIS systems", probably done by some government contractor. * There is some randomness in the GCJ deltas on both axes: one `sin` invocation and one LCG. Each add a maximum of 1 meter of error. * [on4wp7](https://archive.is/20150702191259/https://on4wp7.codeplex.com/SourceControl/changeset/view/21483%23353936) (2013) is the earliest rationalized GCJ (forward) implementation. No randomness is attempted. * [ChinaMapShift][] (2014) figured out the quick iterative inverse for GCJ. I learned about it via geoChina first and generalized it here. * BD-09 is not very well sourced, but [pycoordtrans](https://github.com/zxteloiv/pycoordtrans) (2014) seems to have it. See also -------- * [eviltransform][] is among the most popular cross-language soltions to the problem. It borrows its name directly from [EvilTransform.cs](https://github.com/Leask/EvilTransform/blob/master/EvilTransform.cs), an early refactored version of a raw-flesh Java implementation found in "[emq](https://code.google.com/archive/p/emq/)", some sort of government contractor GIS demo project. * Since June 2016, eviltransform contains numerous parameter errors that compromise its output, especially for BD-09. See googollee/eviltransform[#43](https://github.com/googollee/eviltransform/issues/43), [#53](https://github.com/googollee/eviltransform/pull/53) and [#44](https://github.com/googollee/eviltransform/issues/44) for corrections. As of June 2019 these problems are not fixed. * [geoChina][] by caijun is a clear, concise implementation written in R. It features the iterative method from ChinaMapShift. * I am planning on moving some of the comments on the algorithm found in [my initial JavaScript implementation](https://zh.wikipedia.org/wiki/User:Artoria2e5/PRCoords.js) to the [GitHub Wiki](https://github.com/Artoria2e5/PRCoords/wiki). I don't think anyone is going to be interested in copying comments on these idiocy when translating my implementation to other languages. * If you are doing a translation, consider only using the comments from the PDF. * [Ishisashi's writeup](https://chaoli.club/index.php/4777/0) on this subject. They wrote a super enhanced version of the demo too. Oh, and finally, here is an official [news report](https://archive.fo/20110804185923/http://cxzy.people.com.cn/GB/196034/14908095.html) on that particular *\[bleep\]* who came up with GCJ-02. ================================================ FILE: approx/approx.ipynb ================================================ { "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "Approximation\n", "=============\n", "\n", "Scroll down and you should find some approximations of the obfuscation code.\n", "I have no idea what evil forces compelled me to do this, but eh let's roll with it." ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [], "source": [ "using TaylorModels" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "GCJ-02\n", "------\n", "\n", "The `abs()` makes it impossible to feed into taylor, so I think I will just feed the trigs in. Splitting the x and y too, so we don't get a lot of zero in the coeffs.\n", "\n", "Let's start with... typing the formulae:" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [ { "data": { "text/plain": "e1 (generic function with 1 method)" }, "execution_count": 4, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Not gonna type these pi.\n", "spi(x) = sin(x * pi)\n", "\n", "# Just the core meter-level shite. 1 and 2 are to be fed to taylor.\n", "n0(x, y) = -100 + 0.1x*y + 0.2 * sqrt(abs(x))\n", "n1(x) = 2x + 20 / 3 * (2 * spi(6x) + 2 * spi(2x))\n", "n2(y) = 3y + 0.2y^2 + 20 / 3 * (2 * spi(y) + 4 * spi(y/3) + 16 * spi(y/12) + 32 * spi(y/30))\n", "\n", "e0(x, y) = 300 + 0.1x*y + 0.1 * sqrt(abs(x)) + 2y\n", "e1(x) = x + 0.1x^2 + 20 / 3 * (2 * spi(6x) + 2 * spi(2x) + 2 * spi(x) + 4 * spi(x/3) + 15 * spi(x/12) + 30 * spi(x/30))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Set up for TaylorModels:" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "n1tm = [337.103, 337.104] t + [-15434.3, -15434.2] t³ + [265489, 265490] t⁵ + [-4.894e+16, 4.894e+16]\n", "n2tm = [123.078, 123.079] t + [0.2, 0.200001] t² + [-74.3666, -74.3665] t³ + [34.2831, 34.2832] t⁵ + [-1.74906e+11, 1.74906e+11]\n", "e1tm = [453.04, 453.041] t + [0.1, 0.100001] t² + [-15508.6, -15508.5] t³ + [265523, 265524] t⁵ + [-4.89402e+16, 4.89402e+16]\n" ] } ], "source": [ "x_dom = -30..30\r\n", "y_dom = -30..20\r\n", "\r\n", "# 35,105 as the center of China. What can go wrong?\r\n", "x0 = 0\r\n", "y0 = 0\r\n", "\r\n", "ORDER = 6\r\n", "\r\n", "tmx = TaylorModel1(ORDER, interval(x0), x_dom)\r\n", "tmy = TaylorModel1(ORDER, interval(y0), y_dom)\r\n", "\r\n", "n1tm = n1(tmx)\r\n", "n2tm = n2(tmy)\r\n", "e1tm = e1(tmx)\r\n", "\r\n", "println(\"n1tm = \", n1tm)\r\n", "println(\"n2tm = \", n2tm)\r\n", "println(\"e1tm = \", e1tm)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Oh well, the last term is way better than what I expected. Let's export them as usual polynomials then." ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "n1t = 337.10321638291134 t - 15434.235503082582 t³ + 265489.0776448309 t⁵ + 𝒪(t⁷)\n", "n2t = 123.07865253720988 t + 0.2 t² - 74.36657685107961 t³ + 34.28315615652991 t⁵ + 𝒪(t⁷)\n", "e1t = 453.0402762665314 t + 0.1 t² - 15508.57959081323 t³ + 265523.36073126463 t⁵ + 𝒪(t⁷)\n" ] } ], "source": [ "function mid_tm(t::TaylorModel1)\r\n", " coeffs = map(x -> mid(x), t.pol.coeffs)\r\n", " order = t.pol.order\r\n", " return Taylor1(coeffs, order)\r\n", "end\r\n", "n1t = mid_tm(n1tm)\r\n", "n2t = mid_tm(n2tm)\r\n", "e1t = mid_tm(e1tm)\r\n", "println(\"n1t = \", n1t)\r\n", "println(\"n2t = \", n2t)\r\n", "println(\"e1t = \", e1t)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "These should be good enough to just translate into code. If you are allowing the compiler to reassoc, there should be no need of manually writing Horner and thinking about pipelines. The reduced number of operations might even make `f32` acceptable. I will eventually put it in the cpp thing and check it.\r\n", "\r\n", "The arclen stuff have the same `sqrt` issue, so it's not getting changed here.\r\n", "\r\n", "Okay, actually, **no**. The range of numbers means that `t^7` is ridiculously large. I should really throw this at MetaLibm-Lutetia\r\n", "and ask it to do the argument reduction for me...\r\n", "\r\n", "BD-09\r\n", "----\r\n", "We have a `sqrt` in `hypot`, so no. We can't fuze any operations here anyways.\r\n", "\r\n", "\r\n", "Plotting session\r\n", "----------------\r\n", "Oops UI can't install `Plots`. And I just realized the resulting numbers are\r\n", "unreasonably large. Oops." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] } ], "metadata": { "kernelspec": { "display_name": "Julia 1.5.0-rc1", "language": "julia", "name": "julia-1.5" }, "language_info": { "file_extension": ".jl", "mimetype": "application/julia", "name": "julia", "version": "1.5.0" }, "orig_nbformat": 2 }, "nbformat": 4, "nbformat_minor": 2 } ================================================ FILE: cpp/Makefile ================================================ CXXFLAGS = -O3 -funsafe-math-optimizations -fno-math-errno -std=c++0x -Wall -Wextra -fvisibility=hidden -fvisibility-inlines-hidden -DNDEBUG $(XCXXFLAGS) # "Cross compile" shite. In other words MinGW. # TARGET is Triplet PLUS THE HYPHEN! CC = $(TARGET)gcc CXX = $(TARGET)g++ AR ?= $(TARGET)ar DLLTOOL ?= $(TARGET)dlltool # for clang's llvm bitcode: CCAR=llvm-ar CCAR ?= gcc-ar # Override when using CYGWIN: make [target] LIB=cyg SO=dll # Override when using MinGW: make [target] LIB='' SO=dll TARGET=x86_64-w64-mingw32- LIB ?= lib SO ?= so # Installation DESTDIR ?= PREFIX ?= /usr/local # Path to the Microsoft Library Manager (LIB.exe) # Available from https://aka.ms/buildtools # Tends to be buried deep, e.g. C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Tools\MSVC\14.22.27905\bin\Hostx64\x64 # I recommend putting a shell script called lib.exe in /usr/local/bin to call it with "$@" # # Mingw-W64 has a genlib.exe for those who dare to try. It generates MSVC-style # __IMPORT_DESCRIPTOR_%s. Or maybe the ld -Wl,--out-implib will work with MSVC # too with __imp symbols only, who knows. # # Note that this is only meaningful for MinGW output: Cygwin/MSYS builds have # dependency for cygwin1.dll, which triggers address-clashes with MSVC's libs. # # cl /Fe:demo-cl.exe demo.cc prcoords.lib LIBEXE ?= LIB.exe # Or /machine:x86. LIBFLAGS ?= /machine:x64 all: libprcoords.a $(LIB)prcoords.$(SO) demoso prec_sample: demo demof demold windows: all $(LIB)prcoords.lib # We assume that your copy of "ar" supports the "s" option, # which does some ranlib work itself. libprcoords.a: libprcoords.o $(AR) rcs libprcoords.a libprcoords.o libprcoords-lto.a: libprcoords-lto.o $(CCAR) rcs libprcoords-lto.a libprcoords-lto.o $(LIB)prcoords.$(SO): libprcoords.o $(CC) -shared -o $(LIB)prcoords.$(SO) libprcoords.o libprcoords.o: libprcoords.cc badmath.hh $(CC) $(CXXFLAGS) -fPIC -c -DPRCOORDS_DLL -DPRCOORDS_DLL_EXPORTS libprcoords.cc libprcoords-lto.o: libprcoords.cc $(CC) $(CXXFLAGS) -flto -ffat-lto-objects -c libprcoords.cc -o libprcoords-lto.o # Import library generation for MSVC users (optional) $(LIB)prcoords.def: libprcoords.o $(DLLTOOL) --dllname $(LIB)prcoords.$(SO) -z $(LIB)prcoords.def --export-all-symbols libprcoords.o # Also spits out an .exp $(LIB)prcoords.lib: $(LIB)prcoords.def $(LIBEXE) $(LIBFLAGS) /nologo /def:$(LIB)prcoords.def /out:$(LIB)prcoords.lib demo: demo.cc libprcoords.cc $(CXX) $(CXXFLAGS) -DPRCOORDS_DEMO_FORCE_STANDALONE=1 -o demo demo.cc demof: demo.cc libprcoords.cc $(CXX) $(CXXFLAGS) -DPRCOORDS_DEMO_FORCE_STANDALONE=1 -DPRCOORDS_NUM=float -DPRCOORDS_STON=stof -o demof demo.cc demold: demo.cc libprcoords.cc $(CXX) $(CXXFLAGS) -DPRCOORDS_DEMO_FORCE_STANDALONE=1 -DPRCOORDS_NUM='long double' -DPRCOORDS_STON=stold -o demold demo.cc # Horray! We do not need import libraries. # FIXME: COMMAND NOT BUILDING ON MY NIXOS demoso: demo.cc $(LIB)prcoords.$(SO) $(CXX) $(CXXFLAGS) -L. -l:$(LIB)prcoords.$(SO) -o demoso -DPRCOORDS_DLL demo.cc nanobench.h: wget -O nanobench.h https://github.com/martinus/nanobench/raw/master/src/include/nanobench.h bench: libprcoords.o prcoords.h nanobench.h bench.cc $(CXX) $(CXXFLAGS) -DPRCOORDS_BENCH $(DEFS) -o bench libprcoords.o bench.cc .PHONY: clean help install uninstall install: all mkdir -p $(DESTDIR)$(PREFIX)/bin/prcoords-demo install -s demoso -- $(DESTDIR)$(PREFIX)/bin/prcoords-demo mkdir -p $(DESTDIR)$(PREFIX)/lib install -m 644 -- libprcoords.a $(LIB)prcoords.$(SO) $(DESTDIR)$(PREFIX)/lib uninstall: rm -f -- $(DESTDIR)$(PREFIX)/bin/prcoords-demo $(DESTDIR)$(PREFIX)/lib/libprcoords.a $(DESTDIR)$(PREFIX)/lib/$(LIB)prcoords.$(SO) clean: $(RM) demo demof demold *.exe *.a *.o *.def *.dll *.obj *.lib *.exp *.obj bench ================================================ FILE: cpp/badmath.hh ================================================ /** * Internal header for implementing "fast" sin(x*pi). */ #include namespace badmath { // what are you gonna do about it? x can't be too big! // this is supposed to turn into FMA where fast, and not invoke the fma() libc function otherwise. // like how Julia's muladd() works, but at the mercy of the compiler. template inline T red4(T x) { return -4 * std::nearbyint(x * 0.25) + x; } // devmaster user "Nick"'s approximation formula // https://web.archive.org/web/20171228230531/http://forum.devmaster.net/t/fast-and-accurate-sine-cosine/9648 template inline T sinpi_nick(T x) { x = red4(x * 2); // = 0 to 2pi; nick-magic works on units of 0.5pi T y = x * (2 - std::abs(x)); return y * (0.775 + 0.225 * std::abs(y)); } template inline T sinpi_std(T x) { return std::sin(x * M_PI); } template inline T sinpi(T x) { #ifndef PRCOORDS_NO_BADMATH return sinpi_nick(x); #else return sinpi_std(x); #endif } template inline T cospi(T x) { return sinpi(x + 0.5); } } ================================================ FILE: cpp/bench.cc ================================================ #include #include "badmath.hh" #include "prcoords.h" #define ANKERL_NANOBENCH_IMPLEMENT #include "nanobench.h" double uniform(ankerl::nanobench::Rng& rng, double a, double b){ return rng.uniform01() * (b - a) + a; } PRCoords rand_coord(ankerl::nanobench::Rng& rng){ return PRCoords{.lat = uniform(rng, -90, 90), .lon = uniform(rng, -180, 180)}; } int main(){ using namespace badmath; auto rng = ankerl::nanobench::Rng(); ankerl::nanobench::Bench().minEpochIterations(10000).run( "nop", [&]() { auto coord = rand_coord(rng); ankerl::nanobench::doNotOptimizeAway(coord); } ); ankerl::nanobench::Bench().minEpochIterations(10000).run( "wgs_gcj", [&]() { auto coord = rand_coord(rng); auto res = prcoords_wgs_gcj(coord); ankerl::nanobench::doNotOptimizeAway(res); } ); ankerl::nanobench::Bench().minEpochIterations(10000).run( "gcj_wgs", [&]() { auto coord = rand_coord(rng); auto res = prcoords_gcj_wgs(coord); ankerl::nanobench::doNotOptimizeAway(res); } ); ankerl::nanobench::Bench().minEpochIterations(10000).run( "gcj_wgs_bored", [&]() { auto coord = rand_coord(rng); auto res = prcoords_gcj_wgs_bored(coord); ankerl::nanobench::doNotOptimizeAway(res); } ); ankerl::nanobench::Bench().minEpochIterations(10000).run( "bd_wgs_bored", [&]() { auto coord = rand_coord(rng); auto res = prcoords_gcj_wgs_bored(coord); ankerl::nanobench::doNotOptimizeAway(res); } ); ankerl::nanobench::Bench().minEpochIterations(10000).run( "gcj_bd", [&]() { auto coord = rand_coord(rng); auto res = prcoords_gcj_bd(coord); ankerl::nanobench::doNotOptimizeAway(res); } ); return 0; } ================================================ FILE: cpp/bench4.sh ================================================ #!/bin/sh bench_to_file() { make clean make bench XCXXFLAGS="$1" ./bench > bench_out/$2.md } native='-march=native' stdsin='-DPRCOORDS_NO_BADMATH' if (( ! KEEP_GOVNOR )); then OL_GOVNOR=$(cat /sys/devices/system/cpu/cpu0/cpufreq/scaling_governor) echo performance | sudo tee /sys/devices/system/cpu/cpu*/cpufreq/scaling_governor fi bench_to_file "$native" 'native_nick' bench_to_file "$native $stdsin" 'native_stdsin' bench_to_file "" 'nick' bench_to_file "$stdsin" 'stdsin' if [[ -n $OL_GOVNOR ]]; then echo $OL_GOVNOR | sudo tee /sys/devices/system/cpu/cpu*/cpufreq/scaling_governor fi ================================================ FILE: cpp/bench_out/README.md ================================================ # bench_out All four files are made by nanobench; just do `./bench4.sh`. * `nick` is the version with Nick's fast sinpi. * `std` is the version with sinpi implemented by `std::sin(M_PI * x)`. * The ones with `native_` in front are built with `-march=native`. All the other flags are per Makefile: unsafe math optimizations, no math errno, you know the drill. The native versions are just 10% faster. The real win comes from using Nick's approximation, which quarters the runtime. There seems to be no real damage to the output. I mean, nick is at most 1e-3 off. That's appropriate when we are working in how many meters to shift a point. * Compiler: GCC 13.2.0 * CPU: Ryzen 5 3600 * OS: NixOS 24.05pre, Linux 6.6.28 ## Update: more agressive nicking I also applied Nick's approximation to the `arclen` calculation in GCJ. As expected of a more important divisor, some visible damage to the output is seen, but the magnitude remians in the 1e-6 range. I consider that acceptable given the performance gain (see the files!); it's now the default. \[That does make the `bored` conversion a bit pointless. Hmm, idk.\] `bd` calculation also now uses nick. It also gets benched. Going native seems to cause a 15% regression on `bd`, std or nick. Might be a good idea to look into that, or at least see what clang does. Anyone wishing to turn off nick can use the `-DPRCOORDS_NO_BADMATH` define. There *might* be a point in turning off nick for specific parts of the calculation, but I don't want to spend time on that. ================================================ FILE: cpp/bench_out/native_nick.md ================================================ Warning, results might be unstable: * CPU frequency scaling enabled: CPU 0 between 550.0 and 4,208.0 MHz Recommendations * Use 'pyperf system tune' before benchmarking. See https://github.com/psf/pyperf | ns/op | op/s | err% | ins/op | cyc/op | IPC | bra/op | miss% | total | benchmark |--------------------:|--------------------:|--------:|----------------:|----------------:|-------:|---------------:|--------:|----------:|:---------- | 4.12 | 242,648,826.64 | 0.4% | 22.00 | 16.60 | 1.325 | 0.00 | 0.0% | 0.01 | `nop` | 30.80 | 32,472,208.69 | 3.6% | 223.00 | 121.17 | 1.840 | 2.00 | 0.0% | 0.01 | `wgs_gcj` | 37.95 | 26,349,634.73 | 0.2% | 238.00 | 149.56 | 1.591 | 4.00 | 0.0% | 0.01 | `gcj_wgs` | 157.44 | 6,351,722.84 | 2.1% | 683.36 | 622.28 | 1.098 | 13.03 | 2.3% | 0.02 | `gcj_wgs_bored` | 154.01 | 6,493,059.75 | 1.3% | 683.44 | 613.84 | 1.113 | 13.03 | 2.3% | 0.02 | `bd_wgs_bored` | 70.30 | 14,224,263.54 | 3.0% | 360.39 | 274.90 | 1.311 | 49.20 | 3.0% | 0.01 | `gcj_bd` ================================================ FILE: cpp/bench_out/native_stdsin.md ================================================ Warning, results might be unstable: * CPU frequency scaling enabled: CPU 0 between 550.0 and 4,208.0 MHz Recommendations * Use 'pyperf system tune' before benchmarking. See https://github.com/psf/pyperf | ns/op | op/s | err% | ins/op | cyc/op | IPC | bra/op | miss% | total | benchmark |--------------------:|--------------------:|--------:|----------------:|----------------:|-------:|---------------:|--------:|----------:|:---------- | 4.09 | 244,330,932.16 | 0.5% | 22.00 | 16.60 | 1.325 | 0.00 | 0.0% | 0.01 | `nop` | 196.22 | 5,096,191.73 | 0.3% | 1,279.11 | 780.29 | 1.639 | 160.01 | 7.2% | 0.02 | `wgs_gcj` | 197.34 | 5,067,445.81 | 0.3% | 1,294.41 | 782.36 | 1.655 | 162.02 | 7.0% | 0.02 | `gcj_wgs` | 623.01 | 1,605,113.03 | 0.6% | 3,861.91 | 2,462.12 | 1.569 | 489.22 | 5.6% | 0.07 | `gcj_wgs_bored` | 622.11 | 1,607,439.62 | 0.4% | 3,856.47 | 2,461.61 | 1.567 | 488.46 | 5.6% | 0.08 | `bd_wgs_bored` | 89.76 | 11,141,416.00 | 0.3% | 540.45 | 356.74 | 1.515 | 77.21 | 5.5% | 0.01 | `gcj_bd` ================================================ FILE: cpp/bench_out/nick.md ================================================ Warning, results might be unstable: * CPU frequency scaling enabled: CPU 0 between 550.0 and 4,208.0 MHz Recommendations * Use 'pyperf system tune' before benchmarking. See https://github.com/psf/pyperf | ns/op | op/s | err% | ins/op | cyc/op | IPC | bra/op | miss% | total | benchmark |--------------------:|--------------------:|--------:|----------------:|----------------:|-------:|---------------:|--------:|----------:|:---------- | 3.25 | 307,628,660.33 | 0.4% | 22.00 | 12.97 | 1.696 | 0.00 | 0.0% | 0.01 | `nop` | 45.60 | 21,931,100.65 | 0.8% | 448.00 | 179.13 | 2.501 | 38.00 | 0.0% | 0.01 | `wgs_gcj` | 59.09 | 16,922,136.13 | 2.1% | 465.00 | 231.72 | 2.007 | 40.00 | 0.0% | 0.01 | `gcj_wgs` | 198.70 | 5,032,812.17 | 0.6% | 1,365.35 | 779.44 | 1.752 | 121.13 | 0.3% | 0.02 | `gcj_wgs_bored` | 197.66 | 5,059,121.12 | 0.5% | 1,364.69 | 774.35 | 1.762 | 121.07 | 0.2% | 0.02 | `bd_wgs_bored` | 58.40 | 17,123,351.22 | 0.4% | 391.40 | 227.11 | 1.723 | 55.21 | 2.7% | 0.01 | `gcj_bd` ================================================ FILE: cpp/bench_out/stdsin.md ================================================ Warning, results might be unstable: * CPU frequency scaling enabled: CPU 0 between 550.0 and 4,208.0 MHz Recommendations * Use 'pyperf system tune' before benchmarking. See https://github.com/psf/pyperf | ns/op | op/s | err% | ins/op | cyc/op | IPC | bra/op | miss% | total | benchmark |--------------------:|--------------------:|--------:|----------------:|----------------:|-------:|---------------:|--------:|----------:|:---------- | 3.24 | 308,253,800.28 | 0.2% | 22.00 | 12.97 | 1.696 | 0.00 | 0.0% | 0.01 | `nop` | 216.41 | 4,620,855.79 | 6.9% | 1,315.38 | 853.91 | 1.540 | 160.04 | 7.2% | 0.03 | :wavy_dash: `wgs_gcj` (Unstable with ~10,854.4 iters. Increase `minEpochIterations` to e.g. 108544) | 206.03 | 4,853,603.19 | 1.4% | 1,332.00 | 811.94 | 1.641 | 162.03 | 7.0% | 0.03 | `gcj_wgs` | 653.44 | 1,530,359.50 | 1.0% | 3,973.24 | 2,546.70 | 1.560 | 488.60 | 5.6% | 0.08 | `gcj_wgs_bored` | 653.92 | 1,529,245.44 | 0.6% | 3,976.15 | 2,533.60 | 1.569 | 488.87 | 5.6% | 0.08 | `bd_wgs_bored` | 93.34 | 10,713,089.73 | 0.4% | 543.42 | 361.83 | 1.502 | 77.21 | 5.5% | 0.01 | `gcj_bd` ================================================ FILE: cpp/demo.cc ================================================ /** * People's Rectified Coordinates, C++ demo. */ #if PRCOORDS_DEMO_FORCE_STANDALONE #include "libprcoords.cc" #else #include "prcoords.h" #endif #include #include #include #include using namespace std; #ifndef PRCOORDS_STON #define PRCOORDS_STON stod #endif std::string show_coord(PRCoords v) { std::stringstream stream; stream << std::fixed << std::setprecision(8) << v.lat << ", " << v.lon; return stream.str(); } PRCoords parse_coord(const string& s) { int cut = s.find(", "); return PRCoords{ PRCOORDS_STON(s.substr(0, cut)), PRCOORDS_STON(s.substr(cut + 1)) }; } int main(void) { string input; while (getline(cin, input)) { PRCoords v = std::move(parse_coord(input)); cout << "w2g\t" << show_coord(prcoords_wgs_gcj(v)) << endl << "w2b\t" << show_coord(prcoords_wgs_bd(v)) << endl << "g2b\t" << show_coord(prcoords_gcj_bd(v)) << endl << "g2wQ\t" << show_coord(prcoords_gcj_wgs(v)) << endl << "b2wQ\t" << show_coord(prcoords_bd_wgs(v)) << endl << "b2gQ\t" << show_coord(prcoords_bd_gcj(v)) << endl << "g2wP\t" << show_coord(prcoords_gcj_wgs_bored(v)) << endl << "b2wP\t" << show_coord(prcoords_bd_wgs_bored(v)) << endl << "b2gP\t" << show_coord(prcoords_bd_gcj_bored(v)) << endl << endl; } } ================================================ FILE: cpp/libprcoords.cc ================================================ /** * People's Rectified Coordinates, C++11 implementation * Should yield a C-compatible ABI. */ #include "prcoords.h" #include #include #include #include "badmath.hh" #ifndef M_PI #define M_PI ((PRCOORDS_NUM) (3.14159265358979323846L)) #endif // Assume #ifndef __has_builtin # define __has_builtin(x) 0 #endif #ifndef NDEBUG #define assume(R) assert(R) #elif __has_builtin(__builtin_assume) #define assume(R) __builtin_assume(R) #elif __has_builtin(__builtin_unreachable) #define assume(R) ((R) ? (void) 0 : __builtin_unreachable ()) #elif 1200 <= _MSC_VER #define assume(R) __assume(R) #else #define assume(R) ((void) 0) #endif #define assume_angle(x, a) assume(x >= -a && x <= a) #define assume_coord(c) do { \ assume_angle(c.lat, 90); \ assume_angle(c.lon, 180);\ } while(0) // enforces PRCOORDS_NUM using std::sin; using std::cos; using std::sqrt; using std::atan2; using std::pow; using std::fabs; using badmath::sinpi; using badmath::cospi; /// Krasovsky 1940 ellipsoid /// @const const static PRCOORDS_NUM GCJ_A = 6378245; const static PRCOORDS_NUM GCJ_EE = 0.00669342162296594323; // f = 1/298.3; e^2 = 2*f - f**2 const static PRCOORDS_NUM BD_DLAT = 0.0060; const static PRCOORDS_NUM BD_DLON = 0.0065; /// Epsilon to use for "exact" iterations. /// Wanna troll? Use Number.EPSILON. 1e-13 in 15 calls for gcj. /// @const const static PRCOORDS_NUM PRCOORDS_EPS = 1e-5; typedef PRCoords (*PRCOp)(PRCoords); /// These conversions are for bored people: too accurate to be useful /// given pseudo-random noises added to GCJ. /// /// Should we implement a 2-iter version? /// Just "wgs = wgs - (fwd(wgs) - bad);", repeated twice. template PRCOORDS_LOCAL static PRCoords bored_reverse_conversion(PRCoords bad) { assume_coord(bad); PRCoords wgs = rev(bad); PRCoords diff{INFINITY, INFINITY}; int i = 0; while ((fabs(diff.lat) + fabs(diff.lon)) > PRCOORDS_EPS && i++ < 10) { diff = fwd(wgs) - bad; wgs = wgs - diff; } return wgs; } extern "C" { PRCoords prcoords_wgs_gcj(PRCoords wgs) { assume_coord(wgs); PRCOORDS_NUM x = wgs.lon - 105, y = wgs.lat - 35; // These distortion functions accept (x = lon - 105, y = lat - 35). // They return distortions in terms of arc lengths, in meters. // // In other words, you can pretty much figure out how much you will be off // from WGS-84 just through evaulating them... // // For example, at the (mapped) center of China (105E, 35N), you get a // default deviation of <300, -100> meters. #ifndef APPROX PRCOORDS_NUM dLat_m = -100 + 2 * x + 3 * y + 0.2 * y * y + 0.1 * x * y + 0.2 * sqrt(fabs(x)) + ( 2 * sinpi(x * 6) + 2 * sinpi(x * 2) + 2 * sinpi(y) + 4 * sinpi(y / 3) + 16 * sinpi(y / 12) + 32 * sinpi(y / 30) ) * 20 / 3; PRCOORDS_NUM dLon_m = 300 + x + 2 * y + 0.1 * x * x + 0.1 * x * y + 0.1 * sqrt(fabs(x)) + ( 2 * sinpi(x * 6) + 2 * sinpi(x * 2) + 2 * sinpi(x) + 4 * sinpi(x / 3) + 15 * sinpi(x / 12) + 30 * sinpi(x / 30) ) * 20 / 3; #else // Approximation code from julia side. I should probably // extract the xy-to-ne thing, but that would mean making the whole // program templates. Not today. // FIXME: The coefficients are giving me ridiculously large numbers! PRCOORDS_NUM dLat_m = 0; PRCOORDS_NUM dLon_m = 0; #endif // NOTE: Using sinpi_nick causes the results to be off by 1e-6. // That's acceptable casualty. // Don't like it? Use PRCOORDS_NO_BADMATH. PRCOORDS_NUM radLat = wgs.lat / 180; PRCOORDS_NUM magic = 1 - GCJ_EE * pow(sinpi(radLat), 2); // just a common expr // [[:en:Latitude#Length_of_a_degree_of_latitude]] PRCOORDS_NUM lat_deg_arclen = (M_PI / 180) * (GCJ_A * (1 - GCJ_EE)) / pow(magic, 1.5); // [[:en:Longitude#Length_of_a_degree_of_longitude]] PRCOORDS_NUM lon_deg_arclen = (M_PI / 180) * (GCJ_A * cospi(radLat) / sqrt(magic)); // The screwers pack their deviations into degrees and disappear. // Note how they are mixing WGS-84 and Krasovsky 1940 ellipsoids here... return PRCoords{ wgs.lat + (dLat_m / lat_deg_arclen), wgs.lon + (dLon_m / lon_deg_arclen), }; } PRCoords prcoords_gcj_wgs(PRCoords gcj) { assume_coord(gcj); return gcj - (prcoords_wgs_gcj(gcj) - gcj); } PRCoords prcoords_gcj_bd(PRCoords gcj) { assume_coord(gcj); PRCOORDS_NUM x = gcj.lon; PRCOORDS_NUM y = gcj.lat; // trivia: pycoordtrans actually describes how these values are calculated PRCOORDS_NUM r = sqrt(x * x + y * y) + 0.00002 * sinpi(y * 3000 / 180); PRCOORDS_NUM t = atan2(y, x) + 0.000003 * cospi(x * 3000 / 180); // Hard-coded default deviations again! return PRCoords{ r * sin(t) + BD_DLAT, r * cos(t) + BD_DLON, }; } PRCoords prcoords_bd_gcj(PRCoords bd) { assume_coord(bd); PRCOORDS_NUM x = bd.lon - BD_DLON; PRCOORDS_NUM y = bd.lat - BD_DLAT; PRCOORDS_NUM r = sqrt(x * x + y * y) - 0.00002 * sinpi(y * 3000 / 180); PRCOORDS_NUM t = atan2(y, x) - 0.000003 * cospi(x * 3000 / 180); return PRCoords{ r * sin(t), r * cos(t), }; } PRCoords prcoords_wgs_bd(PRCoords wgs) { return prcoords_gcj_bd(prcoords_wgs_gcj(wgs)); } PRCoords prcoords_bd_wgs(PRCoords bd) { return prcoords_gcj_wgs(prcoords_bd_gcj(bd)); } PRCoords prcoords_gcj_wgs_bored(PRCoords gcj) { return bored_reverse_conversion(gcj); } PRCoords prcoords_bd_gcj_bored(PRCoords bd) { return bored_reverse_conversion(bd); } PRCoords prcoords_bd_wgs_bored(PRCoords bd) { return bored_reverse_conversion(bd); } } #if PRCOORDS_TEST #include #include std::string show_coord(PRCoords v) { return std::to_string(v.lat) + ", " + std::to_string(v.lon); } int main(void) { std::cout << std::is_pod::value << std::endl << show_coord(prcoords_wgs_gcj(PRCoords{35, 105})) << std::endl << show_coord(prcoords_wgs_bd(PRCoords{35, 105})) << std::endl << show_coord(prcoords_wgs_gcj(PRCoords{34, 106})) << std::endl << show_coord(prcoords_wgs_bd(PRCoords{34, 106})) << std::endl; } #endif ================================================ FILE: cpp/prcoords.h ================================================ /** * People's Rectified Coordinates, C/C++ Header. */ #ifndef PRCOORDS_H #define PRCOORDS_H /** May be changed to "long double" for bored folks * (need an "L" suffix on literals for the seriously bored) * "float" is not recommended */ #ifndef PRCOORDS_NUM #define PRCOORDS_NUM double #endif // Generic helper definitions for shared library support #if defined _WIN32 || defined __CYGWIN__ #define PRCOORDS_HELPER_DLL_IMPORT __declspec(dllimport) #define PRCOORDS_HELPER_DLL_EXPORT __declspec(dllexport) #define PRCOORDS_HELPER_DLL_LOCAL #else #if __GNUC__ >= 4 // works on clang lmao #define PRCOORDS_HELPER_DLL_IMPORT __attribute__ ((visibility ("default"))) #define PRCOORDS_HELPER_DLL_EXPORT __attribute__ ((visibility ("default"))) #define PRCOORDS_HELPER_DLL_LOCAL __attribute__ ((visibility ("hidden"))) #else #define PRCOORDS_HELPER_DLL_IMPORT #define PRCOORDS_HELPER_DLL_EXPORT #define PRCOORDS_HELPER_DLL_LOCAL #endif #endif #ifdef PRCOORDS_DLL // defined if PRCOORDS is compiled as a DLL #ifdef PRCOORDS_DLL_EXPORTS // defined if we are building the PRCOORDS DLL (instead of using it) #define PRCOORDS_API PRCOORDS_HELPER_DLL_EXPORT #else #define PRCOORDS_API PRCOORDS_HELPER_DLL_IMPORT #endif // PRCOORDS_DLL_EXPORTS #define PRCOORDS_LOCAL PRCOORDS_HELPER_DLL_LOCAL #else // PRCOORDS_DLL is not defined: this means PRCOORDS is a static lib. #define PRCOORDS_API #define PRCOORDS_LOCAL #endif // PRCOORDS_DLL #ifdef __cplusplus #define PRCOORDS_CONSTEXPR constexpr #if __cplusplus >= 201300L #define PRCOORDS_CONSTEXPR14 constexpr #else #define PRCOORDS_CONSTEXPR14 inline #endif // c++14, including 1y extern "C" { #else #include #define PRCOORDS_CONSTEXPR inline #endif typedef struct PRCoords { PRCOORDS_NUM lat, lon; } PRCoords; // make them pure /// GCJ APIs should all probably turn on china-checks. /// But we should allow some override.... Damn C. PRCOORDS_API PRCoords prcoords_wgs_gcj(PRCoords); PRCOORDS_API PRCoords prcoords_gcj_wgs(PRCoords); PRCOORDS_API PRCoords prcoords_gcj_bd(PRCoords); PRCOORDS_API PRCoords prcoords_bd_gcj(PRCoords); PRCOORDS_API PRCoords prcoords_wgs_bd(PRCoords); PRCOORDS_API PRCoords prcoords_bd_wgs(PRCoords); PRCOORDS_API PRCoords prcoords_gcj_wgs_bored(PRCoords); PRCOORDS_API PRCoords prcoords_bd_gcj_bored(PRCoords); PRCOORDS_API PRCoords prcoords_bd_wgs_bored(PRCoords); PRCOORDS_LOCAL static PRCOORDS_CONSTEXPR bool prcoords_in_china(const PRCoords& a) { // cut out some return a.lat >= 16.7414 && a.lon >= 72.004 && a.lat <= 55.8271 && a.lon <= 137.8347; } #ifdef __cplusplus } PRCOORDS_LOCAL inline PRCoords operator- (const PRCoords& a, const PRCoords& b) { return PRCoords { a.lat - b.lat, a.lon - b.lon }; } // for sorting // lat // | // -<-o---lon (quadrants III, IV and x < 0) // < | < PRCOORDS_LOCAL inline bool operator< (const PRCoords& a, const PRCoords& b) { return a.lat < b.lat || (a.lat == b.lat && a.lon < b.lon); } PRCOORDS_LOCAL inline bool operator> (const PRCoords& a, const PRCoords& b) { return b < a; } PRCOORDS_LOCAL inline bool operator<=(const PRCoords& a, const PRCoords& b) { return !(a > b); } PRCOORDS_LOCAL inline bool operator>=(const PRCoords& a, const PRCoords& b) { return !(a < b); } PRCOORDS_LOCAL inline bool operator==(const PRCoords& a, const PRCoords& b) { return a.lat == b.lat && a.lon == b.lon; } PRCOORDS_LOCAL inline bool operator!=(const PRCoords& a, const PRCoords& b) { return !(a == b); } #endif // __cplusplus #endif // header ================================================ FILE: docs/demo.html ================================================ People Rectify Coordinates

People Rectify Coordinates

With restrictions from the People’s Republic of China

Input

    • ;
    • .
    • ° ;
    • ° .

Results

Operation Result ΔObfs/m ΔRoundtrip/m
WGS → GCJ
WGS → BD
GCJ → WGS
BD → WGS
GCJ →cai WGS
BD →cai WGS
GCJ → BD
BD → GCJ
BD →cai GCJ

. Toggle sections: Notes, FAQ, footer. And print.

Notes

  1. Caijun’s iterative method is included for precise decoding. It's most useful for bored folks whose GPS data is pretty accurate and GCJ-02 obfuscation not tainted by the original LCPRNG.

    If you are doing Wikipedia or any kind of archival work, use it to avoid introducing extra error.

  2. BD is defined in terms of GCJ, hence the last three functions.
  3. This demo omits the “in China” sanity check. Data regarding Baidu’s behavior with overseas maps is needed for further decisions. Observations:
    • Unlike Google Maps, Baidu's map in Hong Kong is fully subject to BD-09 ∘ GCJ-02 chained distortions.
    • Coordinates in Russia, outside of the sanity check rectangle, uses WGS-84 or and/or friends.
    • TODO: check along the boundary.

FAQ

What is this all about?
The PRC government requires all local map services to use an obfuscated, deviation-orienated coordinate system. Click on the “restriction” link to read the full Wikipedia article.
Why should I care?
With half a kilometer of deviation, GCJ-02 and friends fucks up your Ingress games, causes crazy errors in elevation profiles along cycle routes, and cheerfully leads you into roadside ditches plus a bone fracture.
Why doesn’t Google/Bing correct its Chinese data served to global users?
I don’t know. Perhaps they are afraid of getting fined or further kicked out of China. Maybe try OpenStreetMap next time?
Why are you writing another implementation?
Because I got bored.
How does Caijun’s iterative method work?
Cai has explained the method in full in his R implementation. Go read it, or read Wikipedia.

Powered by PRCoords. Try playing with window.PRCoords in your console!

CC0
To the extent possible under law, Mingye Wang has waived all copyright and related or neighboring rights to People Rectify Coordinates. This work is published from: United States.

================================================ FILE: docs/index.md ================================================ Just go to the GitHub repo. ================================================ FILE: docs/proj4_plugin.js ================================================ // mirror of https://runkit.com/artoria2e5/proj4-plugin-prcoords const proj4 = require("proj4") const prcoords = require("prcoords") const noop = Function.prototype const DEG = Math.PI / 180 function xy_to_ll(p) { return { lon: p.x / DEG, lat: p.y / DEG } } function ll_to_xy(p) { return { x: p.lon * DEG, y: p.lat * DEG } } function xy_rename_ll(p) { return { lon: p.x, lat: p.y } } function ll_rename_xy(p) { return { x: p.lon, y: p.lat } } function wrap(f, ...args) { return (p) => ll_to_xy(f(xy_to_ll(p), ...args)) } // We lie our way to Baidu "Mercator". proj4.defs([ [ "_CLARK_MC", "+proj=merc +a=6378206.4 +b=6356583.8 +lat_ts=0.0 +lon_0=0.0 +x_0=0 +y_0=0 +k=1.0 +units=m +nadgrids=@null +wktext +no_defs", ], ["_CLARK_LL", "+proj=longlat +a=6378206.4 +b=6356583.8"], ]) proj4.Proj.projections.add({ init: noop, forward: wrap(prcoords.wgs_gcj), inverse: wrap(prcoords.gcj_wgs_bored), names: ["gcj", "gcj02", "CN_Obfs_GCJ_2002_Ellipsoidal"], }) proj4.Proj.projections.add({ init: noop, forward: wrap(prcoords.wgs_bd), inverse: wrap(prcoords.bd_wgs_bored), names: ["baidu", "bd09", "CN_Obfs_Baidu_2009_Ellipsoidal"], }) proj4.Proj.projections.add({ init: noop, forward: (p) => proj4("_CLARK_LL", "_CLARK_MC", ll_rename_xy(prcoords.wgs_bd(xy_to_ll(p)))), inverse: (p) => ll_to_xy( prcoords.bd_wgs_bored(xy_rename_ll(proj4("_CLARK_MC", "_CLARK_LL", p))), ), names: ["baidu", "bd09mc", "CN_Obfs_Baidu_2009_Mercator"], }) proj4.defs([ // Why isn't units=degrees working... work around with wrap() now. ["GCJ02", "+title=GCJ 02 (long/lat) +proj=gcj02 +units=degrees"], ["BD09", "+title=Baidu 2009 (long/lat) +proj=bd09 +units=degrees"], ["BD09MC", "+title=Baidu 2009 (Mercator) +proj=bd09mc +units=m"], ]) console.log([ // should be the same as https://artoria2e5.github.io/PRCoords/demo xy_to_ll(proj4("WGS84", "BD09", { x: 105, y: 35 })), xy_to_ll(proj4("WGS84", "GCJ02", { x: 105, y: 35 })), ]) console.log([ // should be very close to the original proj4( "BD09", "WGS84", ll_to_xy({ lat: 35.005403668456964, lon: 105.00966682831948 }), ), proj4( "GCJ02", "WGS84", ll_to_xy({ lat: 34.99909863223526, lon: 105.00328624145706 }), ), ]) console.log([ proj4("WGS84", "BD09MC", { x: 105, y: 35 }), proj4("BD09MC", "WGS84", { x: 11689750, y: 4139877 }), ]) ================================================ FILE: haskell/PRCoords.cabal ================================================ -- Initial prcoords.cabal generated by cabal init. For further -- documentation, see http://haskell.org/cabal/users-guide/ -- The name of the package. name: PRCoords -- The package version. See the Haskell package versioning policy (PVP) -- for standards guiding when and how versions should be incremented. -- http://www.haskell.org/haskellwiki/Package_versioning_policy -- PVP summary: +-+------- breaking API changes -- | | +----- non-breaking API additions -- | | | +--- code changes with no API change version: 0.1.0.0 -- A short (one-line) description of the package. synopsis: Library for GCJ-02 and BD-09 (de)obfuscation from/to WGS-84. May trigger mental episodes. description: People's Rectified Coordinates (PRCoords) is a cross-language implementation of "public secret" Chinese coordinate obfuscation methods including GCJ-02 and BD-09, along with general deobfuscation methods previously established in pycoordtrans, eviltransform, and geoChina. -- URL for the project homepage or repository. homepage: https://github.com/Artoria2e5/PRCoords -- The license under which the package is released. license: PublicDomain -- The file containing the license text. -- license-file: LICENSE -- The package author(s). author: Mingye Wang -- An email address to which users can send suggestions, bug reports, and -- patches. maintainer: arthur200126@gmail.com -- A copyright notice. -- copyright: category: Geography build-type: Simple -- Extra files to be distributed with the package, such as examples or a -- README. -- extra-source-files: -- Constraint on the version of Cabal needed to build this package. cabal-version: >=1.10 library -- Modules exported by the library. exposed-modules: PRCoords -- Modules included in this library but not exported. -- other-modules: -- LANGUAGE extensions used by modules in this package. other-extensions: BangPatterns -- Other library packages from which modules are imported. build-depends: base -- >=4.8 && <4.9 -- AC-Angle -- Directories containing source files. -- hs-source-dirs: -- Base language which the package is written in. default-language: Haskell2010 ================================================ FILE: haskell/PRCoords.hs ================================================ {-# LANGUAGE BangPatterns #-} {-# OPTIONS_GHC -fexcess-precision #-} {-# OPTIONS_GHC -optc-ffast-math -optllc--enable-unsafe-fp-math -optllc--enable-no-nans-fp-math -optllc--enable-no-infs-fp-math #-} --- | This module contains functions for generating People's Rectified Coordinates. --- Jeez, my naming is awful. module PRCoords where -- (wgsGcj, gcjBd, wgsBd, gcjWgs, bdGcj, bdWgsC, gcjWgsC, bdGcjC, bdWgsC, caijun) -- import Data.Angle -- import Numeric.FastMath data PCoords = PCoords { !lat :: Double , !lon :: Double } deriving (Eq, Ord, Show) subtractPCoords :: PCoords -> PCoords -> PCoords subtractPCoords a b = PCoords (lat a - lat b) (lon a - lon b) wgsGcj :: PCoords -> PCoords wgsGcj (PCoords lat lon) = PCoords (lat + dLat / arclenLat) (lon + dLon / arclenLon) where gcj_a = 6378245.0 -- <_ Krasovsky 1940 gcj_ee = 0.00669342162296594323 -- f = 1/2983; e^2 = 2*f - f**2 magic = 1 - gcj_ee * ((sin (pi * lat / 180)) ** 2) -- common expr arclenLat = (pi / 180) * (gcj_a * (1 - gcj_ee)) / (magic ** 1.5) arclenLon = (pi / 180) * (gcj_a * (cos (pi * lat / 180)) / (sqrt magic)) x = lon - 105 -- Here goes the deviation y = lat - 35 gcjTerm !v !f !n = n * (sin f * v * pi) -- check operator stuff later dLat = -100 + 2 * x + 3 * y + 0.2 * y ** 2 + 0.1 * x * y + 0.2 * (sqrt (abs x)) + (*) (20/3) ( gcjTerm x 6 2 + gcjTerm x 2 2 + gcjTerm y 1 2 + gcjTerm y (1/3) 4 + gcjTerm y (1/12) 16 + gcjTerm y (1/30) 32) dLon = 300 + 1 * x + 2 * y + 0.1 * x ** 2 + 0.1 * x * y + 0.1 * (sqrt (abs x)) + (*) (20/3) ( gcjTerm x 6 2 + gcjTerm x 2 2 + gcjTerm x 1 2 + gcjTerm x (1/3) 4 + gcjTerm x (1/12) 15 + gcjTerm y (1/30) 30) gcjWgs :: PCoords -> PCoords gcjWgs a = subtractPCoords a (subtractPCoords ga a) where ga = wgsGcj a caiFix :: (PCoords -> PCoords) -> PCoords -> PCoords -> Int -> PCoords caiFix fwd guess fwd_result iter | iter > 5 = better | (abs $ lon diff) + (abs $ lat diff) < 1E-5 = better | otherwise = caiFix fwd better fwd_result (iter+1) where fwd_guess = fwd guess diff = subtractPCoords fwd_guess fwd_result better = subtractPCoords guess diff caijun :: (PCoords -> PCoords) -> (PCoords -> PCoords) -> (PCoords -> PCoords) caijun fwd rev = (\x -> caiFix fwd (rev x) x 0) gcjWgsC :: PCoords -> PCoords gcjWgsC = caijun wgsGcj gcjWgs -- next: baidu ================================================ FILE: haskell/Setup.hs ================================================ import Distribution.Simple main = defaultMain ================================================ FILE: js/.npmignore ================================================ misc ================================================ FILE: js/PRCoords.d.ts ================================================ // Type definitions for PRCoords // Project: PRCoords export as namespace PRCoords export interface PRCoord { lat: number lon: number } export type PRCoordOp = (c: PRCoord, checkChina?: boolean) => PRCoord export function distance(a: PRCoord, b: PRCoord): number // We do not use the PRCO type to make it a bit more transparent on the IDE export function gcj_wgs(c: PRCoord, checkChina?: boolean): PRCoord export function wgs_gcj(c: PRCoord, checkChina?: boolean): PRCoord export function wgs_gcj_bored(c: PRCoord, checkChina?: boolean): PRCoord export function gcj_bd(c: PRCoord, __dummy__?: boolean): PRCoord export function bd_gcj(c: PRCoord, __dummy__?: boolean): PRCoord export function bd_gcj_bored(c: PRCoord, __dummy__?: boolean): PRCoord export function wgs_bd(c: PRCoord, checkChina?: boolean): PRCoord export function bd_wgs(c: PRCoord, checkChina?: boolean): PRCoord export function bd_wgs_bored(c: PRCoord, checkChina?: boolean): PRCoord export function __bored__(fwd: PRCoordOp, rev: PRCoordOp): PRCoordOp ================================================ FILE: js/PRCoords.js ================================================ ;(function (factory, scope) { "use strict" var res = factory() if (typeof module === 'object') { module.exports = res } else { if (typeof define === 'function' && define.amd) define('prcoords', function() { return res }) try { // Global can be undefined scope.PRCoords = res } catch(e) {} } })((function (){ "use strict" // /** * People's Rectified Coordinates * @file Utils for inserting valid WGS-84 coords from GCJ-02/BD-09 input * @author User:Artoria2e5 * @url https://github.com/Artoria2e5/PRCoords * * @see [[:en:GCJ-02]] * @see https://en.wikipedia.org/wiki/User:Artoria2e5/coord-notice * @see https://github.com/caijun/geoChina (GPLv3) * @see https://github.com/googollee/eviltransform (MIT) * @see https://on4wp7.codeplex.com/SourceControl/changeset/view/21483#353936 (Anonymous) * @see https://github.com/zxteloiv/pycoordtrans (BSD-3) * * @license CC0 * To the greatest extent possible, this implementation of obfuscations designed * in hope that they will screw y'all up is dedicated into the public domain * under CC0 1.0 . * * Happy geotagging/ingressing/whatever. * * To make my FSF membership shine brighter, this conversion implementation is * additionally licensed under GPLv3+: * @license GPLv3+ * @copyright 2016 Mingye Wang (User:Artoria2e5) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ /// Krasovsky 1940 ellipsoid /// @const var GCJ_A = 6378245 var GCJ_EE = 0.00669342162296594323 // f = 1/298.3; e^2 = 2*f - f**2 /// Epsilon to use for "exact" iterations. /// Wanna troll? Use Number.EPSILON. 1e-13 in 15 calls for gcj. /// @const var PRC_EPS = 1e-5 /// Baidu's artificial deviations /// @const var BD_DLAT = 0.0060 var BD_DLON = 0.0065 /// Mean Earth Radius /// @const var EARTH_R = 6371000 /// Distance for haversine method; suitable over short distances like /// conversion deviation checking function distance(a, b) { function hav(θ) { return Math.pow(Math.sin(θ/2), 2) } var Δ = _coord_diff(a, b) return 2 * EARTH_R * Math.asin(Math.sqrt( hav(Δ.lat * Math.PI / 180) + Math.cos(a.lat * Math.PI / 180) * Math.cos(b.lat * Math.PI / 180) * hav(Δ.lon * Math.PI / 180) )) } function sanity_in_china_p(coords) { return coords.lat >= 0.8293 && coords.lat <= 55.8271 && coords.lon >= 72.004 && coords.lon <= 137.8347 } function _coord_diff(a, b) { return { lat: a.lat - b.lat, lon: a.lon - b.lon, } } function _stringify(c) { return "(" + c.lat + ", " + c.lon + ")" } function wgs_gcj(wgs, checkChina) { if ((checkChina === undefined || checkChina) && !sanity_in_china_p(wgs)) { console.warn("Non-Chinese coords found, returning as-is: " + _stringify(wgs)) return wgs } var x = wgs.lon - 105, y = wgs.lat - 35 // These distortion functions accept (x = lon - 105, y = lat - 35). // They return distortions in terms of arc lengths, in meters. // // In other words, you can pretty much figure out how much you will be off // from WGS-84 just through evaulating them... // // For example, at the (mapped) center of China (105E, 35N), you get a // default deviation of <300, -100> meters. var dLat_m = -100 + 2 * x + 3 * y + 0.2 * y * y + 0.1 * x * y + 0.2 * Math.sqrt(Math.abs(x)) + ( 2 * Math.sin(x * 6 * Math.PI) + 2 * Math.sin(x * 2 * Math.PI) + 2 * Math.sin(y * Math.PI) + 4 * Math.sin(y / 3 * Math.PI) + 16 * Math.sin(y / 12 * Math.PI) + 32 * Math.sin(y / 30 * Math.PI) ) * 20 / 3 var dLon_m = 300 + x + 2 * y + 0.1 * x * x + 0.1 * x * y + 0.1 * Math.sqrt(Math.abs(x)) + ( 2 * Math.sin(x * 6 * Math.PI) + 2 * Math.sin(x * 2 * Math.PI) + 2 * Math.sin(x * Math.PI) + 4 * Math.sin(x / 3 * Math.PI) + 15 * Math.sin(x / 12 * Math.PI) + 30 * Math.sin(x / 30 * Math.PI) ) * 20 / 3 var radLat = wgs.lat / 180 * Math.PI var magic = 1 - GCJ_EE * Math.pow(Math.sin(radLat), 2) // just a common expr // [[:en:Latitude#Length_of_a_degree_of_latitude]] var lat_deg_arclen = (Math.PI / 180) * (GCJ_A * (1 - GCJ_EE)) / Math.pow(magic, 1.5) // [[:en:Longitude#Length_of_a_degree_of_longitude]] var lon_deg_arclen = (Math.PI / 180) * (GCJ_A * Math.cos(radLat) / Math.sqrt(magic)) // The screwers pack their deviations into degrees and disappear. // Note how they are mixing WGS-84 and Krasovsky 1940 ellipsoids here... return { lat: wgs.lat + (dLat_m / lat_deg_arclen), lon: wgs.lon + (dLon_m / lon_deg_arclen), } } // rev_transform_rough; accuracy ~2e-6 deg (meter-level) function gcj_wgs(gcj, checkChina) { return _coord_diff(gcj, _coord_diff(wgs_gcj(gcj, checkChina), gcj)) } function gcj_bd(gcj, __dummy__) { var x = gcj.lon var y = gcj.lat // trivia: pycoordtrans actually describes how these values are calculated var r = Math.sqrt(x * x + y * y) + 0.00002 * Math.sin(y * Math.PI * 3000 / 180) var θ = Math.atan2(y, x) + 0.000003 * Math.cos(x * Math.PI * 3000 / 180) // Hard-coded default deviations again! return { lat: r * Math.sin(θ) + BD_DLAT, lon: r * Math.cos(θ) + BD_DLON, } } // Yes, we can implement a "precise" one too. // accuracy ~1e-7 deg (decimeter-level; exceeds usual data accuracy) function bd_gcj(bd, __dummy__) { var x = bd.lon - BD_DLON var y = bd.lat - BD_DLAT // trivia: pycoordtrans actually describes how these values are calculated var r = Math.sqrt(x * x + y * y) - 0.00002 * Math.sin(y * Math.PI * 3000 / 180) var θ = Math.atan2(y, x) - 0.000003 * Math.cos(x * Math.PI * 3000 / 180) return { lat: r * Math.sin(θ), lon: r * Math.cos(θ), } } function bd_wgs(bd, checkChina) { return gcj_wgs(bd_gcj(bd), checkChina) } function wgs_bd(bd, checkChina) { return gcj_bd(wgs_gcj(bd, checkChina)) } // generic "bored function" factory, Caijun 2014 // gcj: 4 calls to wgs_gcj; ~0.1mm acc function __bored__(fwd, rev) { return function rev_bored(heck, checkChina) { if (checkChina === undefined) checkChina = true var curr = rev(heck, checkChina) var diff = {lat: Infinity, lon: Infinity} // Wait till we hit fixed point or get bored var i = 0 while (Math.max(Math.abs(diff.lat), Math.abs(diff.lon)) > PRC_EPS && i++ < 10) { diff = _coord_diff(fwd(curr, checkChina), heck) curr = _coord_diff(curr, diff) } return curr } } var exports = { distance: distance, wgs_gcj: wgs_gcj, gcj_wgs: gcj_wgs, gcj_bd: gcj_bd, bd_gcj: bd_gcj, wgs_bd: wgs_bd, bd_wgs: bd_wgs, // Precise functions using caijun 2014 method // // Why "bored"? Because they usually exceed source data accuracy -- the // original GCJ implementation contains noise from a linear-modulo PRNG, // and Baidu seems to do similar things with their API too. __bored__: __bored__, gcj_wgs_bored: __bored__(wgs_gcj, gcj_wgs), bd_gcj_bored: __bored__(gcj_bd, bd_gcj), bd_wgs_bored: __bored__(wgs_bd, bd_wgs), } // We can stub this out too if we are aiming for ES3, but then there are no // trailing commas Object.defineProperty(exports, '__esModule', { value: true }) return exports }), typeof self !== 'undefined' ? self : typeof this !== undefined ? this : globalThis) ================================================ FILE: js/misc/insane_is_in_china.js ================================================ (function(){ "use strict" // Insane version of the "is in China" check (70 points. I tried.) // // Dedicated to the Public Domain under CC0, except for pnpoly by // Wm. Randolph Franklin (BSD3) // // Incorrect use of this polygon can lead to adverse geopolitical issues. // This set of points is only intended to approximate the scope of a type of distortion, // and has nothing to do with any political entities. // // Also, screw geodetics. The Earth is flat according to this approximation. /// *** pnpoly *** /// // Copyright (c) 1970-2003, Wm. Randolph Franklin // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // 1. Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimers. // 2. Redistributions in binary form must reproduce the above // copyright notice in the documentation and/or other materials // provided with the distribution. // 3. The name of W. Randolph Franklin may not be used to endorse or // promote products derived from this Software without specific // prior written permission. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. function pnpoly(xs, ys, x, y) { if (! (xs.length === ys.length)) throw new Error("pnpoly: assert(xs.length === ys.length)") var inside = 0 // j records previous value. Also handles wrapping around. for (let i = 0, j = xs.length - 1; i < xs.length; j = i++) inside ^= (((ys[i] > y) !== (ys[j] > y)) && (x < (xs[j] - xs[i]) * (y - ys[i]) / (ys[j] - ys[i]) + xs[i])) // Let's make js as magical as C. Yay. return !!inside } /// ^^^ pnpoly ^^^ /// // We will need to filter out these points for Baidu. // (We will need South China Sea too.) var is_near_hkmo = function (lat, lon) { return 22 <= lat && lat <= 22.7 && 113.5 <= lon && lon <= 114.5 } // Well we now have indices for HK/MO. var HK_LENGTH = 12 // lon, lat var POINTS = [ // start hkmo 114.433722, 22.064310, 114.009458, 22.182105, 113.599275, 22.121763, 113.583463, 22.176002, 113.530900, 22.175318, 113.529542, 22.210608, 113.613377, 22.227435, 113.938514, 22.483714, 114.043449, 22.500274, 114.138506, 22.550640, 114.222984, 22.550960, 114.366803, 22.524255, // end hkmo 115.254019, 20.235733, 121.456316, 26.504442, 123.417261, 30.355685, 124.289197, 39.761103, 126.880509, 41.774504, 127.887261, 41.370015, 128.214602, 41.965359, 129.698745, 42.452788, 130.766139, 42.668534, 131.282487, 45.037051, 133.142361, 44.842986, 134.882453, 48.370596, 132.235531, 47.785403, 130.980075, 47.804860, 130.659026, 48.968383, 127.860252, 50.043973, 125.284310, 53.667091, 120.619316, 53.100485, 119.403751, 50.105903, 117.070862, 49.690388, 115.586019, 47.995542, 118.599613, 47.927785, 118.260771, 46.707335, 113.534759, 44.735134, 112.093739, 45.001999, 111.431259, 43.489381, 105.206324, 41.809510, 96.485703, 42.778692, 94.167961, 44.991668, 91.130430, 45.192938, 90.694601, 47.754437, 87.356293, 49.232005, 85.375791, 48.263928, 85.876055, 47.109272, 82.935423, 47.285727, 81.929808, 45.506317, 79.919457, 45.108122, 79.841455, 42.178752, 73.334917, 40.076332, 73.241805, 39.062331, 79.031902, 34.206413, 78.738395, 31.578004, 80.715812, 30.453822, 81.821692, 30.585965, 85.501663, 28.208463, 92.096061, 27.754241, 94.699781, 29.357171, 96.079442, 29.429559, 98.910308, 27.140660, 97.404057, 24.494701, 99.400021, 23.168966, 100.697449, 21.475914, 102.976870, 22.616482, 105.476997, 23.244292, 108.565621, 20.907735, 107.730505, 18.193406, 110.669856, 17.754550, ] var lats = POINTS.filter((ditch, i) => i % 2 == 1) var lons = POINTS.filter((ditch, i) => i % 2 == 0) POINTS = null // no need var bdlats = lats.slice(HK_LENGTH) var bdlons = lons.slice(HK_LENGTH) function isInGoogle(lat, lon) { // Yank out South China Sea if (lat <= 17.75455) return false; return pnpoly(lats, lons, lat, lon) } function isInBaidu(lat, lon) { // Yank out South China Sea, as: // 1. Nobody wants Baidu's crap Sansha data // 2. I am too lazy to add like four points if (lat <= 17.75455) return false; return pnpoly(bdlats, bdlons, lat, lon) } exports = {isInBaidu: isInBaidu, isInGoogle: isInGoogle} if (typeof module === "object" && module.exports) { module.exports = exports } else if (typeof window !== "undefined") { window.PRCoords = exports } })() ================================================ FILE: js/misc/package.json ================================================ { "name": "insane-in-china", "version": "0.0.1", "description": "Routine for deciding whether one coordiate might be affected by Chinese obfuscation.", "main": "insane_is_in_china.js", "repository": { "type": "git", "url": "https://github.com/Artoria2e5/PRCoords.git", "directory": "js/misc" }, "keywords": [ "gcj", "wgs", "bd", "baidu", "coordinates", "pnpoly" ], "author": "Mingye Wang (Artoria2e5) ", "license": "BSD-3-Clause", "bugs": { "url": "https://github.com/Artoria2e5/PRCoords/issues" } } ================================================ FILE: js/package.json ================================================ { "name": "prcoords", "version": "1.0.3-rc1", "description": "Chinese coordinate obfuscation methods (GCJ-02, BD-09) and inverses.", "main": "PRCoords.js", "repository": { "type": "git", "url": "https://github.com/Artoria2e5/PRCoords.git", "directory": "js", "//note": "Unused before I figure out what to do with docs and readme." }, "keywords": [ "gcj", "wgs", "bd", "baidu", "coordinates" ], "author": "Mingye Wang (Artoria2e5) ", "license": "CC0-1.0", "bugs": { "url": "https://github.com/Artoria2e5/PRCoords/issues" }, "dependencies": {} } ================================================ FILE: julia/Project.toml ================================================ name = "PRCoords" uuid = "0c59880a-3f55-4b0d-8a02-bd83932d11da" authors = ["Mingye Wang "] version = "0.1.0" ================================================ FILE: julia/src/PRCoords.jl ================================================ module PRCoords struct Coords lat::Float64 lon::Float64 end end # module ================================================ FILE: lua/PRCoords.lua ================================================ -- People's Rectified Coordinates -- https://github.com/Artoria2e5/PRCoords -- -- Dedicated to the Public Domain under CC0 -- Artoria2e5, 2017. PRCoords = { ["EARTH_R"] = 6371000 } -- Ray-casting polygon function PRCoords._in_poly(xs, ys, x, y) assert(#xs == #ys, "poly length don't match") local inside = false for i=1,#xs do if (ys[i] > y) ~= (ys[j] > y) and (x < (xs[j] - xs[i]) * (y - ys[i]) / (ys[j] - ys[i]) + xs[i]) then inside = (not inside) end end return inside end local function bind_poly(xs, ys) return function(x, y) return PRCoords._in_poly(xs, ys, x, y) end end function PRCoords.cdiff(a_lat, a_lon, b_lat, b_lon) return a_lat - b_lat, a_lon - b_lon end local function cerr(lat, lon) return abs(lat) + abs(lon) end function PRCoords.cdist(a_lat, a_lon, b_lat, b_lon) local function hav(theta) return math.sin(theta/2) ^ 2 end local delta_lat = a_lat - b_lat local delta_lon = a_lon - b_lon return 2 * PRCoords.EARTH_R * math.asin(math.sqrt( hav(delta_lat * math.pi / 180) + math.cos(a.lat * math.pi / 180) * math.cos(b.lat * math.pi / 180) * hav(delta_lon * math.pi / 180))) end function PRCoords.caijun(forward, reverse) return function(bad_lat, bad_lon) local guess_lat, guess_lon = reverse(bad_lat, bad_lon) local iter = 0 local diff_lat, diff_lon, tlat, tlon repeat tlat, tlon = forward(guess_lat, guess_lon) diff_lat, diff_lon = PRCoords.cdiff(tlat, tlon, bad_lat, bad_lon) guess_lat -= diff_lat guess_lon -= diff_lon iter += 1 until cerr(diff_lat, diff_lon) <= 1e-5 or iter >= 10 end end function PRCoords.wgs_gcj(wlat, wlon) local y, x = wlon - 105, wlat - 35 end ================================================ FILE: matlab/PRCoords.m ================================================ function v = PRCoords() %% People's Rectified Coordinates: Chinese geographic obfuscations %% Dedicated to the Public Domain under CC0. %% Mingye Wang (Artoria2e5), 2017, 2025. %% @url https://github.com/Artoria2e5/PRCoords v = "1.2.0"; end ================================================ FILE: matlab/bd_gcj.m ================================================ function g = bd_gcj (b) % Reverse the BD-09 distortion to GCJ-02 coordinates. x = b (2) - 0.0065; y = b (1) - 0.006; r = sqrt (x .* x + y .* y) - 0.00002 * sin (y * pi * 3000 / 180); theta = atan2 (y, x) - 0.000003 * cos (x * pi * 3000 / 180); gcj_lon = r .* cos (theta); gcj_lat = r .* sin (theta); g = [gcj_lat, gcj_lon]; endfunction ================================================ FILE: matlab/bd_gcj_precise.m ================================================ function g = bd_gcj_precise (b, tol, maxn) % Reverse the BD-09 distortion to GCJ-02 coordinates in a precise way. if nargin < 2 tol = 1e-13; end if nargin < 3 maxn = 10; end fun = caijun_precise (@gcj_bd, @bd_gcj); g = fun (b, tol, maxn); endfunction ================================================ FILE: matlab/bd_wgs.m ================================================ function w = bd_wgs (b) % Reverse the BD-09 distortion to WGS-84 coordinates. g = bd_gcj (b); w = gcj_wgs (g); endfunction ================================================ FILE: matlab/bd_wgs_precise.m ================================================ function w = bd_wgs_precise (b, tol, maxn) % Reverse the BD-09 distortion to WGS-84 coordinates in a precise way. if nargin < 2 tol = 1e-13; end if nargin < 3 maxn = 10; end fun = caijun_precise (@wgs_bd, @bd_wgs); w = fun (b, tol, maxn); endfunction ================================================ FILE: matlab/caijun_precise.m ================================================ function fun = caijun_precise (fwd, rev, o, tol, maxn) % usage: fun = caijun_precise (@fwd, @rev) % % With a precise forward obfuscation and a rough deobfuscation % function, construct a precise iterative deobfuscation function. % % A custom tolilon for "fixed point" detection can be specified % with the "tol" operand. The default value is 1e-4 degrees. % % A custon max iteration limit can be specified with the "maxn" % operand. The default value is 10 iterations. % % (caijun/geoChina; 2014) function c = rectify (o, tol, maxn) % Given obfuscated coords, % return something that appears much less wrong to us. c = rev (o); d = c - o; for i = 1:maxn if (max(abs(d (1))) + max(abs(d (2))) <= tol) break; end d = fwd(c) - o; c -= d; end endfunction fun = @rectify; endfunction ================================================ FILE: matlab/gcj_bd.m ================================================ function b = gcj_bd (g) % Apply the BD-09 distortion to GCJ-02 coordinates. x = g (2); y = g (1); r = sqrt (x .* x + y .* y) + 0.00002 * sin (y * pi * 3000 / 180); theta = atan2 (y, x) + 0.000003 * cos (x * pi * 3000 / 180); bd_lon = r .* cos (theta) + 0.0065; bd_lat = r .* sin (theta) + 0.006; b = [bd_lat, bd_lon]; endfunction ================================================ FILE: matlab/gcj_wgs.m ================================================ function w = gcj_wgs (g) % Reverse the GCJ-02 distortion in a rough way. gg = wgs_gcj (g); w = g * 2 - gg; endfunction ================================================ FILE: matlab/gcj_wgs_precise.m ================================================ function w = gcj_wgs_precise (g, tol, maxn) if nargin < 2 tol = 1e-13; end if nargin < 3 maxn = 10; end fun = caijun_precise (@wgs_gcj, @gcj_wgs); w = fun (g, tol, maxn); endfunction ================================================ FILE: matlab/wgs_bd.m ================================================ function b = wgs_bd (w) % Apply the BD-09 distortion to WGS-84 coordinates. g = wgs_gcj (w); b = gcj_bd (g); endfunction ================================================ FILE: matlab/wgs_gcj.m ================================================ function r = wgs_gcj (w) % Apply the GCJ-02 distortion to WGS-84 coordinates. wlat = w (1); wlon = w (2); % Krasovsky 1940 ellipsoid GCJ_A = 6378245; GCJ_EE = 0.00669342162296594323; % f = 1./298.3; e^2 = 2.*f - f.*.*2 % Deviation computation in meters, inlined. % [x, y] are relative coords from a common mapped "center" of China. x = wlat - 35; y = wlon - 105; dlat = -100 + 2 .* x + 3 .* y + 0.2 .* y .* y + 0.1 .* x .* y + ... 0.2 .* sqrt(abs(x)) + (2 .* sin(x .* 6 .* pi) + ... 2 .* sin(x .* 2 .* pi) + 2 .* sin(y .* pi) + 4 .* sin(y ./ 3 .* pi) + ... 16 .* sin(y ./ 12 .* pi) + 32 .* sin(y ./ 30 .* pi)) .* 20 ./ 3; dlon = 300 + x + 2 .* y + 0.1 .* x .* x + 0.1 .* x .* y + ... 0.1 .* sqrt(abs(x)) + (2 .* sin(x .* 6 .* pi) + ... 2 .* sin(x .* 2 .* pi) + 2 .* sin(x .* pi) + 4 .* sin(x ./ 3 .* pi) + ... 15 .* sin(x ./ 12 .* pi) + 30 .* sin(x ./ 30 .* pi)) .* 20 ./ 3; % Arc lengths for one degree on the wrong ellipsoid magic = 1 - GCJ_EE .* (sind(wlat) .^ 2); % A common expression arclen_1lat = pi / 180 .* (GCJ_A .* (1 - GCJ_EE)) ./ magic .^ 1.5; arclen_1lon = pi / 180 .* GCJ_A .* cosd(wlat) ./ magic .^ 0.5; % Pack deviations into degrees glat = wlat + dlat ./ arclen_1lat; glon = wlon + dlon ./ arclen_1lon; r = [glat, glon]; endfunction ================================================ FILE: package.json ================================================ { "name": "prcoords", "version": "1.0.5", "description": "Chinese coordinate obfuscation methods (GCJ-02, BD-09) and inverses.", "main": "js/PRCoords.js", "//": "Will this work with the repo? https://github.com/npm/npm/issues/2974", "repository": "github:Artoria2e5/PRCoords", "keywords": [ "gcj", "wgs", "bd", "baidu", "coordinates" ], "author": "Mingye Wang (Artoria2e5) ", "license": "CC0-1.0", "bugs": { "url": "https://github.com/Artoria2e5/PRCoords/issues" }, "dependencies": {} } ================================================ FILE: pgsql/distance_agg.sql ================================================ CREATE TYPE _geodistance_agg_state AS (distance double precision, lat double precision, lon double precision); CREATE FUNCTION public._geodistance_agg_sfunc (state _geodistance_agg_state, lat double precision, lon double precision) RETURNS _geodistance_agg_state AS $$ SELECT (CASE WHEN $1 IS NULL THEN 0 ELSE $1.distance+geodistance($1.lat, $1.lon, $2, $3) END), $2, $3 AS nextstate; $$ LANGUAGE SQL IMMUTABLE; CREATE FUNCTION public._geodistance_agg_ffunc (state _geodistance_agg_state) RETURNS double precision AS $$ SELECT $1.distance AS result; $$ LANGUAGE SQL IMMUTABLE; CREATE AGGREGATE geodistance_agg (double precision, double precision) ( SFUNC = _geodistance_agg_sfunc, STYPE = _geodistance_agg_state, FINALFUNC = _geodistance_agg_ffunc ); ================================================ FILE: pgsql/prcoords.sql ================================================ CREATE OR REPLACE FUNCTION public.geodistance (alat double precision, alng double precision, blat double precision, blng double precision) RETURNS double precision AS $$ SELECT 2 * 6371000 * asin( sqrt( sin(radians($3-$1)/2)^2 + sin(radians($4-$2)/2)^2 * cos(radians($1)) * cos(radians($3)) ) ) AS distance; $$ LANGUAGE SQL IMMUTABLE STRICT PARALLEL SAFE COST 100; CREATE OR REPLACE FUNCTION public.geodistance (a point, b point) RETURNS double precision AS $$ SELECT 2 * 6371000 * asin( sqrt( sin(radians($2[0]-$1[0])/2)^2 + sin(radians($2[1]-$1[1])/2)^2 * cos(radians($1[0])) * cos(radians($2[0])) ) ) AS distance; $$ LANGUAGE SQL IMMUTABLE STRICT PARALLEL SAFE COST 100; CREATE OR REPLACE FUNCTION public.wgs_gcj (wgs point) RETURNS point AS $$ DECLARE GCJ_A CONSTANT double precision := 6378245; GCJ_EE CONSTANT double precision := 0.00669342162296594323; x double precision; y double precision; dLat_m double precision; dLon_m double precision; radLat double precision; magic double precision; lat_deg_arclen double precision; lon_deg_arclen double precision; BEGIN x := wgs[1] - 105; y := wgs[0] - 35; dLat_m := (-100 + 2 * x + 3 * y + 0.2 * y * y + 0.1 * x * y + 0.2 * sqrt(abs(x)) + ( 2 * sin(x * 6 * pi()) + 2 * sin(x * 2 * pi()) + 2 * sin(y * pi()) + 4 * sin(y / 3 * pi()) + 16 * sin(y / 12 * pi()) + 32 * sin(y / 30 * pi()) ) * 20 / 3); dLon_m := (300 + x + 2 * y + 0.1 * x * x + 0.1 * x * y + 0.1 * sqrt(abs(x)) + ( 2 * sin(x * 6 * pi()) + 2 * sin(x * 2 * pi()) + 2 * sin(x * pi()) + 4 * sin(x / 3 * pi()) + 15 * sin(x / 12 * pi()) + 30 * sin(x / 30 * pi()) ) * 20 / 3); radLat := radians(wgs[0]); magic := 1 - GCJ_EE * power(sin(radLat), 2); lat_deg_arclen := radians((GCJ_A * (1 - GCJ_EE)) / power(magic, 1.5)); lon_deg_arclen = radians(GCJ_A * cos(radLat) / sqrt(magic)); RETURN (wgs[0] + (dLat_m / lat_deg_arclen), wgs[1] + (dLon_m / lon_deg_arclen)); END; $$ LANGUAGE plpgsql IMMUTABLE STRICT PARALLEL SAFE COST 150; CREATE OR REPLACE FUNCTION public.gcj_wgs (gcj point) RETURNS point AS $$ SELECT $1 - (wgs_gcj($1) - $1) AS wgs $$ LANGUAGE SQL IMMUTABLE STRICT PARALLEL SAFE COST 150; CREATE OR REPLACE FUNCTION public.gcj_wgs_bored (gcj point) RETURNS point AS $$ DECLARE MAXITER CONSTANT double precision := 10; PRC_EPS CONSTANT double precision := 1e-5; wgs point; old point; diff point; i smallint; BEGIN wgs = gcj_wgs(gcj); LOOP diff := (wgs - old); IF i < MAXITER AND (abs(diff[0]) > PRC_EPS OR abs(diff[1]) > PRC_EPS) THEN old := wgs; wgs := wgs - (wgs_gcj(wgs) - gcj); i := i + 1; ELSE RETURN wgs; END IF; END LOOP; END; $$ LANGUAGE plpgsql IMMUTABLE STRICT PARALLEL SAFE COST 450; CREATE OR REPLACE FUNCTION public.gcj_bd (gcj point) RETURNS point AS $$ DECLARE r double precision; t double precision; BEGIN r := sqrt(gcj[0] * gcj[0] + gcj[1] * gcj[1]) + 2e-5 * sin(3000 * radians(gcj[0])); t := atan2(gcj[0], gcj[1]) + 3e-6 * cos(3000 * radians(gcj[1])); RETURN point(r * sin(t) + 0.0060, r * cos(t) + 0.0065); END; $$ LANGUAGE plpgsql IMMUTABLE STRICT PARALLEL SAFE COST 100; ================================================ FILE: pgsql/prcoords_postgis.sql ================================================ -- Depends on PostGIS and prcoords.sql CREATE OR REPLACE FUNCTION public._latlng2geometry (p point) RETURNS geometry AS $$ SELECT ST_SetSRID(ST_MakePoint(p[1], p[0]), 4326); $$ LANGUAGE SQL IMMUTABLE STRICT PARALLEL SAFE; CREATE OR REPLACE FUNCTION public._geometry2latlng (p geometry) RETURNS point AS $$ BEGIN IF GeometryType(p) != 'POINT' THEN RAISE EXCEPTION 'Input geom must be a point. Currently is: %', GeometryType(p); ELSIF ST_SRID(p) != 4326 THEN RAISE EXCEPTION 'SRID of the input geom must be 4326. Currently is: %', ST_SRID(p); END IF; RETURN point(ST_Y($1), ST_X($1)); END; $$ LANGUAGE plpgsql IMMUTABLE STRICT PARALLEL SAFE; CREATE OR REPLACE FUNCTION public.wgs_gcj (wgs geometry) RETURNS geometry AS $$ SELECT _latlng2geometry(wgs_gcj(_geometry2latlng($1))) $$ LANGUAGE SQL IMMUTABLE STRICT PARALLEL SAFE; CREATE OR REPLACE FUNCTION public.gcj_wgs (gcj geometry) RETURNS geometry AS $$ SELECT _latlng2geometry(gcj_wgs(_geometry2latlng($1))) $$ LANGUAGE SQL IMMUTABLE STRICT PARALLEL SAFE; CREATE OR REPLACE FUNCTION public.gcj_bd (gcj geometry) RETURNS geometry AS $$ SELECT _latlng2geometry(gcj_bd(_geometry2latlng($1))) $$ LANGUAGE SQL IMMUTABLE STRICT PARALLEL SAFE; ================================================ FILE: py/prcoords.py ================================================ ''' People's Rectified [[T:Coord|Coordinates]] @file Utils for inserting valid WGS-84 coords from GCJ-02/BD-09 input @author User:Artoria2e5 @url https://github.com/Artoria2e5/PRCoords @see [[:en:GCJ-02]] @see https://github.com/caijun/geoChina (GPLv3) @see https://github.com/googollee/eviltransform (MIT) @see https://on4wp7.codeplex.com/SourceControl/changeset/view/21483#353936 (Anonymous) @see https://github.com/zxteloiv/pycoordtrans (BSD-3) @license CC0 To the greatest extent possible, this implementation of obfuscations designed in hope that they will screw y'all up is dedicated into the public domain under CC0 1.0 . Happy geotagging/ingressing/whatever. To make my FSF membership shine brighter, this conversion implementation is additionally licensed under GPLv3+: @license GPLv3+ @copyright 2016 Mingye Wang (User:Artoria2e5) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . ''' import math import warnings import collections # Krasovsky 1940 ellipsoid # @const GCJ_A = 6378245 GCJ_EE = 0.00669342162296594323 # f = 1/298.3; e^2 = 2*f - f**2 # Epsilon to use for "exact" iterations. # Wanna troll? Use Number.EPSILON. 1e-13 in 15 calls for gcj. # @const PRC_EPS = 1e-5 # Baidu's artificial deviations # @const BD_DLAT = 0.0060 BD_DLON = 0.0065 # Mean Earth Radius # @const EARTH_R = 6371000 class Coords(collections.namedtuple('Coords', 'lat lon')): def __add__(self, other): return Coords(self.lat + other.lat, self.lon + other.lon) def __sub__(self, other): return Coords(self.lat - other.lat, self.lon - other.lon) def __abs__(self): return math.hypot(*self) def distance(self, other): ''' Distance for haversine method; suitable over short distances like conversion deviation checking ''' hav = lambda theta: math.sin(theta / 2) ** 2 delta = self - other return 2 * EARTH_R * math.asin(math.sqrt( hav(math.radians(delta.lat)) + math.cos(math.radians(self.lat)) * math.cos(math.radians(other.lat)) * hav(math.radians(delta.lon)) )) def sanity_in_china_p(coords): return (0.8293 <= coords.lat <= 55.8271 and 72.004 <= coords.lon <= 137.8347) def wgs_gcj(wgs, check_china=True): wgs = Coords(*wgs) if check_china and not sanity_in_china_p(wgs): warnings.warn('Non-Chinese coords found, returning as-is: %r' % (wgs,)) return wgs x, y = wgs.lon - 105, wgs.lat - 35 # These distortion functions accept (x = lon - 105, y = lat - 35). # They return distortions in terms of arc lengths, in meters. # In other words, you can pretty much figure out how much you will be off # from WGS-84 just through evaulating them... # # For example, at the (mapped) center of China (105E, 35N), you get a # default deviation of <300, -100> meters. dLat_m = (-100 + 2 * x + 3 * y + 0.2 * y * y + 0.1 * x * y + 0.2 * math.sqrt(abs(x)) + ( 2 * math.sin(x * 6 * math.pi) + 2 * math.sin(x * 2 * math.pi) + 2 * math.sin(y * math.pi) + 4 * math.sin(y / 3 * math.pi) + 16 * math.sin(y / 12 * math.pi) + 32 * math.sin(y / 30 * math.pi) ) * 20 / 3) dLon_m = (300 + x + 2 * y + 0.1 * x * x + 0.1 * x * y + 0.1 * math.sqrt(abs(x)) + ( 2 * math.sin(x * 6 * math.pi) + 2 * math.sin(x * 2 * math.pi) + 2 * math.sin(x * math.pi) + 4 * math.sin(x / 3 * math.pi) + 15 * math.sin(x / 12 * math.pi) + 30 * math.sin(x / 30 * math.pi) ) * 20 / 3) radLat = math.radians(wgs.lat) magic = 1 - GCJ_EE * math.pow(math.sin(radLat), 2) # just a common expr # [[:en:Latitude#Length_of_a_degree_of_latitude]] lat_deg_arclen = math.radians((GCJ_A * (1 - GCJ_EE)) / math.pow(magic, 1.5)) # [[:en:Longitude#Length_of_a_degree_of_longitude]] lon_deg_arclen = math.radians(GCJ_A * math.cos(radLat) / math.sqrt(magic)) # The screwers pack their deviations into degrees and disappear. # Note how they are mixing WGS-84 and Krasovsky 1940 ellipsoids here... return Coords(wgs.lat + (dLat_m / lat_deg_arclen), wgs.lon + (dLon_m / lon_deg_arclen)) def gcj_wgs(gcj, check_china=True): '''rev_transform_rough; accuracy ~2e-6 deg (meter-level)''' gcj = Coords(*gcj) return gcj - (wgs_gcj(gcj, check_china) - gcj) def gcj_bd(gcj, _dummy=False): y, x = gcj # trivia: pycoordtrans actually describes how these values are calculated r = math.sqrt(x * x + y * y) + 0.00002 * math.sin(math.radians(y) * 3000) theta = math.atan2(y, x) + 0.000003 * math.cos(math.radians(x) * 3000) # Hard-coded default deviations again! return Coords(r * math.sin(theta) + BD_DLAT, r * math.cos(theta) + BD_DLON) # Yes, we can implement a "precise" one too. def bd_gcj(bd, _dummy=False): '''accuracy ~1e-7 deg (decimeter-level; exceeds usual data accuracy)''' bd = Coords(*bd) x = bd.lon - BD_DLON y = bd.lat - BD_DLAT # trivia: pycoordtrans actually describes how these values are calculated r = math.sqrt(x * x + y * y) - 0.00002 * math.sin(math.radians(y) * 3000) theta = math.atan2(y, x) - 0.000003 * math.cos(math.radians(x) * 3000) return Coords(r * math.sin(theta), r * math.cos(theta)) def bd_wgs(bd, check_china=True): return gcj_wgs(bd_gcj(bd), check_china) def wgs_bd(bd, check_china=True): return gcj_bd(wgs_gcj(bd, check_china)) def _bored(fwd, rev): ''' generic "bored function" factory, Caijun 2014 gcj: 4 calls to wgs_gcj; ~0.1mm acc ''' def rev_bored(bad, check_china=True): wgs = rev(bad) bad = Coords(*bad) diff = Coords(99, 99) # canary # Wait till we hit fixed point or get bored i = 0 while i < 10 and abs(diff) > PRC_EPS: diff = fwd(wgs, False) - bad wgs = wgs - diff i += 1 return wgs return rev_bored # Precise functions using caijun 2014 method # # Why "bored"? Because they usually exceed source data accuracy -- the # original GCJ implementation contains noise from a linear-modulo PRNG, # and Baidu seems to do similar things with their API too. gcj_wgs_bored = _bored(wgs_gcj, gcj_wgs) bd_gcj_bored = _bored(gcj_bd, bd_gcj) bd_wgs_bored = _bored(wgs_bd, bd_wgs) ================================================ FILE: py/setup.py ================================================ # This file is a part of PRCoords, a public-domain library from __future__ import with_statement from setuptools import setup description="Public Domain library for rectifying Chinese coordinates (gcj-02/bd-09)" try: with open("../README.md", "r") as f: long_description = f.read() except: # Will only happen with non-wheel archives and never on pypi long_description = description setup( name="prcoords", version="1.0.2", author="Mingye Wang", author_email="arthur200126@gmail.com", description=description, long_description=long_description, long_description_content_type="text/markdown", url="https://github.com/Artoria2e5/PRCoords", py_modules=["prcoords"], classifiers=[ "Programming Language :: Python :: 2", "Programming Language :: Python :: 3", "Development Status :: 5 - Production/Stable", "License :: CC0 1.0 Universal (CC0 1.0) Public Domain Dedication", "Operating System :: OS Independent", "Topic :: Scientific/Engineering :: GIS", ], ) ================================================ FILE: racket/prcoords.rkt ================================================ ;; People's Rectified Coordinates ;; Dedicated to the Public Domain under CC0 ;; No idea about the module stuff. ;; Will it handle my awful, collision-prone naming? ;;(module prcoords typed/racket ;; (provide latlon latlon-lat latlon-lon latlon? ;; Do I have to say these all? ;; I figured that before writing one for F#/Haskell/OCaml, ;; Writing one in parentheses first might be a good idea. ;; This sounds fun. #lang typed/racket ;; I could have added some more restrictions, but whatever. (struct latlon ([lat : Float] [lon : Float])) ;; I hear that those people in Haskell land use types to encode ;; more information. Should I do that? ;; These creepy x/y people... (define (latlon-from-complex [c : Float-Complex]) : latlon (latlon (imag-part c) (real-part c))) (define (latlon-to-complex [a : latlon]) : Float-Complex (make-rectangular (latlon-lon a) (latlon-lat a))) ;; This one is a little sloppy... (: dcoord (-> latlon latlon latlon)) (define (dcoord a b) (latlon (- (latlon-lat a) (latlon-lat b)) (- (latlon-lon a) (latlon-lon b)))) ;; For looking into errors (: dcoord-abs (-> latlon latlon Float)) (define (dcoord-abs a b) (max (abs (latlon-lat (dcoord a b))) (abs (latlon-lon (dcoord a b))))) ;; For estimating deviations (define (dist [a : latlon] [b : latlon]) : Float (let ([a-lat (degrees->radians (latlon-lat a))] [a-lon (degrees->radians (latlon-lon a))] [b-lat (degrees->radians (latlon-lat b))] [b-lon (degrees->radians (latlon-lon b))] [d-lat (degrees->radians (latlon-lat (dcoord a b)))] [d-lon (degrees->radians (latlon-lon (dcoord a b)))] [R 6371000.] [hav : (-> Float Float) (λ (theta) (* (sin (/ 2 theta)) (sin (/ 2 theta))))]) (* 2. R (cast (asin (sqrt (+ (hav d-lat) (* (hav d-lon) (cos a-lat) (cos b-lat))))) Float)))) ;; What, you want a polygon check? Not now. (: probably-bad (-> latlon Boolean)) (define (probably-bad a) (and #t ;; TODO #t #t #t)) ;; For your sanity, no functions will be defined with the ;; rough "sanity" check on by default. (: sanity-wrap (-> (-> latlon latlon) (-> latlon Boolean) (-> latlon latlon))) (define (sanity-wrap conv check) (λ ([a : latlon]) (if (check a) (conv a) a))) ;; Sometimes people are like... (: sanity-wrap-backward (-> (-> latlon latlon) (-> latlon Boolean) (-> latlon latlon))) (define (sanity-wrap-backward conv check) (λ ([a : latlon]) (let ([c (conv a)]) (if (check c) c a)))) ;; Finally a conversion. I understand that you have been ;; cursing for all these poorly-written BS. (: wgs-gcj (-> latlon latlon)) (define (wgs-gcj wgs) ; For (human) laziness (let* ([gcj-ee 0.00669342162296594323] ;; Krasovsky 1940, Not What You Use With WGS-84(TM) [gcj-a 6378245.] [x (- (latlon-lon wgs) 105.)] ;; Deviation params [y (- (latlon-lat wgs) 35.)] [dlat 0.] ;; Yay, huge expressions, not today [dlon 0.] [rlat (degrees->radians (latlon-lat wgs))] ;; This type checker is unhappy with... [mm (cast (- 1 (* gcj-ee (sin rlat) (sin rlat))) Positive-Flonum)] [arclat (exact->inexact (* (/ pi 180.) gcj-a (- 1 gcj-ee) (expt mm -1.5)))] [arclon (exact->inexact (* (/ pi 180.) gcj-a (cos rlat) (sqrt mm)))]) (latlon (+ (latlon-lat wgs) (/ dlat arclat)) (+ (latlon-lon wgs) (/ dlon arclon))))) ;; Do you really think I am gonna finish this? ;; A rough reverse function. (: gcj-wgs-rough (-> latlon latlon)) (define (gcj-wgs-rough gcj) (dcoord gcj (dcoord (wgs-gcj gcj) gcj))) ;; Cai's iteration. ;; Not now. Chill, it's just carrying four accumulators around and stuff. (define (caijun-iterate [fwd : (-> latlon latlon)] [rough-rev : (-> latlon latlon)] #:eps [eps : Float 1e-4] #:maxn [maxn : Integer 10]) (λ ([bad : latlon]) : latlon (letrec ([improve : (-> latlon latlon Integer latlon) (λ (curr prev i) ;; Fixing a sloppy part in js, etc.: ;; what happens if rough-rev is just an `id`? (if (or (and (< i maxn) (< (dcoord-abs curr prev) eps)) (= i 0)) (improve (dcoord curr (dcoord (fwd curr) bad)) curr (+ 1 i)) curr))]) (improve bad (rough-rev bad) 0)))) (define gcj-wgs : (-> latlon latlon) (caijun-iterate wgs-gcj gcj-wgs-rough)) ;; Baudu's Obfuscation. (define (gcj-bd [a : latlon]) : latlon (let ([bd-delta 0.0060+0.0065i] [c1 (latlon-to-complex a)] [lat (latlon-lat a)] [lon (latlon-lon a)]) (latlon-from-complex (+ (make-polar (+ (magnitude c1) (* 0.00002 (sin (* 3000. (degrees->radians lat))))) (+ (angle c1) (* 0.000003 (cos (* 3000. (degrees->radians lon)))))) bd-delta)))) (define (bd-gcj-rough [a : latlon]) : latlon (let* ([bd-delta 0.0060+0.0065i] [c1 (- (latlon-to-complex a) bd-delta)] [lat (imag-part c1)] [lon (real-part c1)]) (latlon-from-complex (make-polar (- (magnitude c1) (* 0.00002 (sin (* 3000. (degrees->radians lat))))) (- (angle c1) (* 0.000003 (cos (* 3000. (degrees->radians lon))))))))) (define bd-gcj : (-> latlon latlon) (caijun-iterate gcj-bd bd-gcj-rough)) (define (wgs-bd [a : latlon]) : latlon (gcj-bd (wgs-gcj a))) (define (bd-wgs-rough [a : latlon]) : latlon (gcj-wgs-rough (bd-gcj-rough a))) (define bd-wgs : (-> latlon latlon) (caijun-iterate wgs-bd bd-wgs-rough)) ;; Yay!