├── LICENSE ├── README.md ├── __init__.py ├── apply_defenses.py ├── attackmodule.py ├── automated_pipeline.py ├── defense_mechanisms.py ├── getJson.py ├── pipelineJson.json ├── plot_privacy_gain.py ├── plot_utilities.py ├── preprocess_df.py ├── privacy_gain.py ├── region_extraction_functions.py ├── reqs.txt ├── safecast_extra_functions.py ├── source_data ├── radiocells_template.csv ├── safecast_template_for_defenses.csv └── safecst_template_data_for_priors.csv └── utility_functions.py /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # MCSAuditing 2 | 3 | This tool implements the evaluation framework described in the paper 4 | 5 | _On (The Lack Of) Location Privacy in Crowdsourcing Applications_ by Spyros Boukoros (TU Darmstadt), Mathias Humbert (SDSC, ETHZ/EPFL), Stefan Katzenbeisser (TU Darmstadt/U. Passau), and Carmela Troncoso (EPFL). USENIX Security Symposium 2019 6 | 7 | Link to the paper: https://arxiv.org/abs/1901.04923 8 | 9 | 10 | --- 11 | 12 | ## How to set the parameters of the tool 13 | 14 | The main files that need tweaking are the 15 | - \_\_init\_\_.py 16 | - pipelineJson.json 17 | 18 | 19 | ### \_\_init\_\_.py: 20 | 21 | You have to change the path in the section "Required paths for applying defenses" [\_\_init\_\_.py#L24](__init__.py#L24) 22 | 23 | `mypath`: the path to the folder of your project 24 | 25 | `original_csv_file`: the path to your dataset. This file *needs* to be called original.csv 26 | 27 | `priors_csv`: the path to the dataset that will be used for calculating the prior probabilities of locations. 28 | This file is relevant only for defenses that are augmented with optimal remapping. 29 | This file *needs* to be called `data_for_priors.csv`. 30 | 31 | ### pipelineJson.json 32 | 33 | This file includes parameters abou the attacks, and the datasets used. 34 | 35 | If you wand to run the tool on all of your dataset, then place *needs* to be call "World.". 36 | Otherwise, you can change it to whatever you want however, then you need to specify a *valid* polygon for the extraction. 37 | 38 | **Detailed**: 39 | 40 | `Place`: World if no region extraction otherwise free to choose 41 | 42 | `dataset_used`: the name of you dataset. In this tool, we provide two datasets and their utility functions. Those are the "Safecast" and 43 | "Radiocells" datasets. The variable name is case sensitive. If you specify your own dataset name, you will not be able to use the utility 44 | functions of these datasets. However, you can tweak the tool to include your own funtion. 45 | 46 | `minpoints`: the DBSCAN's parameter minimum points 47 | 48 | `maxdistance`: DBSCAN's parameter maximum distance among points 49 | 50 | `maxpois`: The top N clusters that should be kept 51 | 52 | `starttime`: Keep only measurement that start from this time 53 | 54 | `endtime`: and end this time. Basically, the last two parameters filter the dataset. 55 | 56 | `advanced_clustering`: Whether to use standard clustering parameters (value=0) or adjustable(value=1). 57 | 58 | `min_allowed_points`: When using adjustable clustering, the minimum limit points are allowed to reach. 59 | 60 | `max_allowed_distance`: When using adjustable clustering, the maximum distance allowed. 61 | 62 | `original_min_points`: When using adjustable clustering, the value can replace the initial minpoints. 63 | 64 | `Polygon`: This *needs* to be a valid (closed) polygon and the edges need to be in the form of (latitude, longitude). 65 | 66 | See here for various polygons --> https://download.geofabrik.de/. 67 | However, the above link provides the polygons in the opposite order (longitude, latitude). If you use such polygons 68 | make sure you reverse the edges. 69 | 70 | 71 | ## How to run the tool 72 | 73 | The main functions that automates everything is inside the 74 | `automated_pipeline.py` file and is called *runpipeline*. 75 | ``` 76 | python automated_pipeline.py 77 | ``` 78 | 79 | 80 | ## Explanation 81 | When you call runpipeline, the tool 82 | 83 | #### first step: 84 | 1. extracts the region, 85 | 2. computes the priors if any, 86 | 3. apply all defenses to the location data. 87 | 4. The tool saves the defense files in a folder called defenses. 88 | 89 | You can select which defenses you want in the file `apply_defenses.py`. 90 | 91 | #### second step: 92 | The tool calculates all users original privacy in spatial terms and POIs. 93 | 94 | In order to do so, rellies on the attackscript inside the `attackmodule.py`. If you wish to change the attackm, modify this file. 95 | 96 | In addition, the tool relies on OSM to collect POIs. Currently it uses a public server that if under load starts blocking requests. The tool has defenses for this and tries again after x seconds. 97 | 98 | However, you could also use your own OSM server by modifying the line `api = overpy.Overpass(url='your url')` inside the `privacy_gain.py` file. 99 | 100 | Then, the tool applies the attacks also on the defense files. All resulting files are pickled and saved in the privacyloss folder. 101 | 102 | #### third step: 103 | The tool, if Safecast or Radiocells are specified (and correct files are provided), calculates the utility loss. 104 | 105 | As the tool relies on a specific order of the files it finds, (the columns in the csv should be in specific order), we provide templates for the Radiocells and the Safecast datasets. The graphs are saved in the plots folder. 106 | 107 | #### fourth step: 108 | The tool calculates the privacy gains and plots it. Again, this is a demonstration on the datasets of the paper. 109 | 110 | The privacy gain folder with each user's privacy gain is saved in the privacyloss folder. The graphs however are stored in the plots folder. 111 | -------------------------------------------------------------------------------- /__init__.py: -------------------------------------------------------------------------------- 1 | from getJson import * 2 | from shapely.geometry import Point, Polygon 3 | 4 | RADIANT_TO_KM_CONSTANT = 6371.0088 5 | 6 | cfg = get() 7 | 8 | # Get all json values 9 | place = cfg['place'] 10 | dataset_used = cfg['dataset_used'] 11 | polygon = Polygon(cfg['Polygon']) 12 | minpoints = int(cfg['minpoints']) 13 | maxdistance = float(cfg['maxdistance']) 14 | maxpois = int(cfg['maxpois']) 15 | starttime = int(cfg['starttime']) 16 | endtime = int(cfg['endtime']) 17 | advanced_clustering = int(cfg['advanced_clustering']) 18 | min_allowed_points = int(cfg['min_allowed_points']) 19 | max_allowed_distance = int(cfg['max_allowed_distance']) 20 | original_min_points = int(cfg['original_min_points']) 21 | 22 | ############################################# 23 | # 24 | # Required paths for applying defenses 25 | # 26 | ############################################ 27 | mypath = "folder_of_the_project" 28 | original_csv_file = "path_to_original_file_with_data" # this file needs to be called original.csv 29 | priors_csv = "path_to_data_priors" # this file needs to be called data_for_priors.csv 30 | 31 | ################################################## 32 | # 33 | # Better not to touch below this part 34 | # 35 | # 36 | ################################################ 37 | ORIGIN = mypath + "/data/" 38 | DATA_PATH = ORIGIN + place + "/" 39 | 40 | #The original file after we have extracted all coords in a polygon needs to be called 'for_defenses.csv', 41 | # but feel free to change 42 | datapath_to_original_file = ORIGIN + place + "/" + "for_defenses.csv" 43 | priors_transformed_path = ORIGIN + place + "/" + "priors.csv" 44 | 45 | defenses_path_place = mypath + "/defences/"+place+"/" 46 | defenses_path = mypath + "/defences/" 47 | 48 | # Required paths for privacyloss calculations 49 | filespath = defenses_path 50 | 51 | writeplace = place + '''{}_points_{}dist'''.format(int(minpoints), int(maxdistance)) 52 | 53 | if advanced_clustering == 1: 54 | writeplace = writeplace + '''_advancedClustering''' 55 | else: 56 | writeplace = writeplace + '''_standardClustering''' 57 | 58 | utilities_plot = mypath + "/plots/" 59 | privacyloss_path = mypath + "/privacyloss/" 60 | privacyloss_plots = privacyloss_path + "plots/" 61 | DATA_BASE_WRITE_UTILITY = privacyloss_path + writeplace + "/" 62 | original_pickle = privacyloss_path + "{}/original.pickle".format(writeplace) 63 | 64 | 65 | def return_write_path(thisplace): 66 | 67 | writeplace = thisplace + '''{}_points_{}dist'''.format(int(minpoints), int(maxdistance)) 68 | 69 | if advanced_clustering == 1: 70 | writeplace = writeplace + '''_advancedClustering''' 71 | else: 72 | writeplace = writeplace + '''_standardClustering''' 73 | 74 | return writeplace -------------------------------------------------------------------------------- /apply_defenses.py: -------------------------------------------------------------------------------- 1 | import gc 2 | import os 3 | import sys 4 | import scipy.spatial 5 | import cPickle as pickle 6 | import multiprocessing as mp 7 | 8 | from defense_mechanisms import * 9 | from safecast_extra_functions import calc_avg, PreCompute 10 | from utility_functions import radiocells_find_antenna 11 | from region_extraction_functions import extract_region, compute_prior 12 | from __init__ import (place, 13 | polygon, 14 | defenses_path, dataset_used, 15 | DATA_PATH, 16 | datapath_to_original_file,original_csv_file, priors_csv, priors_transformed_path) 17 | 18 | 19 | polygon = polygon.buffer(0) # fix minor issues with the polygons 20 | print place 21 | 22 | if 'World' not in place: 23 | print polygon.is_valid # check if the supplied polygon is valid 24 | 25 | 26 | def apply_mechanisms(preparations): 27 | ensure_dir(DATA_PATH) 28 | dataset = place 29 | 30 | # the list with the mechanisms to be applied 31 | # and their parameters 32 | MECHANISMS = [('lap', 1.6, 0.05,0), # params ==" name, lambda, epsilon, optimal remapping true/false" 33 | ('lap', 1.6, 0.150,0), 34 | ('lap', 1.6, 0.3,0), 35 | ('geoindtraces', 1.6, 0.05, 30), # params ==" name, lambda, epsilon, radius" 36 | ('geoindtraces', 1.6, 0.05, 60), 37 | ('geoindtraces', 1.6, 0.05, 90), 38 | ('release', 30), # params ==" name, radius" 39 | ('release', 60), 40 | ('release', 90), 41 | ('random', 40), # params ==" name, percent" 42 | ('random', 60), 43 | ('random', 80), 44 | ('rounding',2), # params ==" name, rounding digits" 45 | ('rounding',3), 46 | ('rounding',4), 47 | ('lap', 1.6, 0.05, 1), # params ==" name, lambda, epsilon, optimal remapping true/false" 48 | ('lap', 1.6, 0.15, 1), 49 | ('lap', 1.6, 0.3, 1)] 50 | # 51 | 52 | ##################################################################### 53 | # Do preparation stuff if specified 54 | if preparations: 55 | print dataset 56 | print ('Safecast' == dataset_used) 57 | print("Extracting region and applying filters") 58 | extract_region(original_csv_file,DATA_PATH, datapath_to_original_file,polygon, place) 59 | PreDestination_original = defenses_path + dataset + "/" # prepare path string 60 | ensure_dir(PreDestination_original) 61 | 62 | print('I will now create the priors') 63 | if os.path.isfile(priors_csv): 64 | compute_prior(priors_csv, priors_transformed_path) 65 | X = np.loadtxt(priors_transformed_path, skiprows=1, usecols=(0, 1), delimiter=",") 66 | # convert locations to cartesian using the center of the earth 67 | cartesianCoords = [] 68 | print('Starting transforming to cartesian coordinates') 69 | for i in X: 70 | cartesianCoords.append(cartesian(i)) 71 | cartesianCoords = np.asarray(cartesianCoords) 72 | tree = scipy.spatial.cKDTree(cartesianCoords, leafsize=4000) 73 | priorX = np.loadtxt(priors_transformed_path, skiprows=1, usecols=(2,), delimiter=",") 74 | priorX.shape = (priorX.shape[0], 1) # priorX must be a matrix of one column 75 | print "Dumping stuff with pickle.." 76 | with open(DATA_PATH + 'priorX.pickle', 'wb') as handle: 77 | pickle.dump(priorX, handle) 78 | with open(DATA_PATH + 'KDtree.pickle', 'wb') as handle: 79 | pickle.dump(tree, handle) 80 | with open(DATA_PATH + 'X.pickle', 'wb') as handle: 81 | pickle.dump(X, handle) 82 | else: 83 | print('No priors file') 84 | 85 | if 'Safecast' == dataset_used: 86 | calc_avg(original_csv_file, PreDestination_original + dataset + ".avg.csv") 87 | print "Interpolating data..." 88 | PreCompute(PreDestination_original + dataset + ".avg.csv", PreDestination_original + dataset + ".pickle", 89 | PreDestination_original + dataset + ".interpolated.csv", PreDestination_original + place + ".avg.csv") 90 | elif 'Radiocells' == dataset_used: 91 | radiocells_find_antenna(original_csv_file, PreDestination_original + dataset + ".avg.csv") 92 | else: 93 | print('No utility function selected') 94 | gc.collect() 95 | 96 | 97 | 98 | ###################################################################################################### 99 | 100 | pool = mp.Pool(1) # Specify on how many cores this should happen 101 | funclist = [] 102 | 103 | for df in MECHANISMS: 104 | print df 105 | f = pool.apply_async(parallel, [[df], defenses_path, datapath_to_original_file, DATA_PATH, PreDestination_original]) 106 | funclist.append(f) 107 | 108 | result = [] 109 | for f in funclist: 110 | result.append(f.get()) 111 | 112 | return 0 113 | 114 | 115 | def parallel(MECHANISMS, defenses_path, datapath_to_original_file, DATA_PATH, PreDestination_original ): 116 | 117 | DESTINATION = "" 118 | for mechanism in MECHANISMS: 119 | 120 | if mechanism[0] == 'rounding': 121 | method = mechanism[0] 122 | parameter = mechanism[1] 123 | print "\n Method: " + method + " Rounding to : " + str(parameter)+ " digits" 124 | # Calculate private data 125 | print "Calculating private data..." 126 | dataset = "rounded_" + str(parameter) + "_digits" # e.g. osaka_rounded_5_digits 127 | PreDestination = defenses_path + dataset + "/" 128 | ensure_dir(PreDestination) 129 | DESTINATION= PreDestination + dataset +".csv" 130 | apply_rounding(datapath_to_original_file, DESTINATION, parameter) 131 | 132 | elif mechanism[0] == 'lap': 133 | 134 | method = mechanism[0] 135 | lamdaprv = math.log(mechanism[1]) 136 | radius = mechanism[2] 137 | REMAPPING = mechanism[3] 138 | dataset = "geoind_lamda_" + str(mechanism[1]) + "_radius_"+ str(radius) + "_method_" + method 139 | if REMAPPING: 140 | dataset += "_remapping" 141 | PreDestination = defenses_path + dataset + "/" 142 | ensure_dir(PreDestination) 143 | DESTINATION = PreDestination + dataset + ".csv" 144 | with open(DATA_PATH + 'X.pickle', 'rb') as handle: 145 | X = pickle.load(handle) 146 | with open(DATA_PATH + 'priorX.pickle', 'rb') as handle: 147 | priorX = pickle.load(handle) 148 | with open(DATA_PATH + 'KDtree.pickle', 'rb') as handle: 149 | tree = pickle.load(handle) 150 | 151 | 152 | apply_geoind(datapath_to_original_file, DESTINATION, method, lamdaprv, radius, priorX, X,tree, 1) 153 | 154 | elif REMAPPING and ('Tokyo' not in place): 155 | return 156 | 157 | else: 158 | print 'Doing Geoind' 159 | PreDestination = defenses_path + dataset + "/" 160 | ensure_dir(PreDestination) 161 | DESTINATION = PreDestination + dataset + ".csv" 162 | apply_geoind(datapath_to_original_file, DESTINATION, method, lamdaprv, radius, 0, 0, 0) 163 | 164 | elif mechanism[0] == 'geoindtraces': 165 | method = mechanism[0] 166 | lamdaprv = math.log(mechanism[1]) 167 | radius = mechanism[2] 168 | distance = mechanism[3] 169 | print "\n Method: " + method + " using : " + str(distance) + " meters distance" 170 | # Calculate private data 171 | print "Calculating private data..." 172 | dataset = "geoind_traces_" + str(mechanism[1]) + "_radius_"+ str(radius) + "_distance_" + str(distance) 173 | PreDestination = defenses_path + dataset+ "/" 174 | ensure_dir(PreDestination) 175 | DESTINATION = PreDestination + dataset + ".csv" 176 | geoind_traces(datapath_to_original_file, DESTINATION, lamdaprv, radius, distance) 177 | 178 | elif mechanism[0] == 'random': 179 | method = mechanism[0] 180 | perc = mechanism[1] 181 | print "\n Method: " + method + " using : " + str(perc) + " percent" 182 | # Calculate private data 183 | print "Calculating private data..." 184 | dataset = "random_sample_" + str(perc) + "_percent" # e.g. osaka_rounded_5_digits 185 | PreDestination = defenses_path + dataset+ "/" 186 | ensure_dir(PreDestination) 187 | DESTINATION = PreDestination + dataset + ".csv" 188 | apply_random_percent(datapath_to_original_file, DESTINATION, perc) 189 | 190 | elif mechanism[0] == 'release': 191 | method = mechanism[0] 192 | step = mechanism[1] 193 | print "\n Method: " + method + " using : " + str(step) + " meters as step" 194 | # Calculate private data 195 | print "Calculating private data..." 196 | dataset = "spacex_" + str(step) + "_meters" # e.g. osaka_rounded_5_digits 197 | PreDestination = defenses_path + dataset + "/" 198 | ensure_dir(PreDestination) 199 | DESTINATION = PreDestination + dataset + ".csv" 200 | apply_space_x(datapath_to_original_file, DESTINATION, float(step)) 201 | else: 202 | print "Something wrong" 203 | exit(-1) 204 | 205 | if 'Safecast' == dataset_used: 206 | calc_avg(DESTINATION, PreDestination + dataset + ".avg.csv") 207 | print "Interpolating data..." 208 | PreCompute(PreDestination + dataset + ".avg.csv", PreDestination + dataset + ".pickle", 209 | PreDestination + dataset + ".interpolated.csv", PreDestination_original + place + ".avg.csv") 210 | elif 'Radiocells' == dataset_used: 211 | radiocells_find_antenna(DESTINATION, PreDestination + dataset + ".avg.csv") 212 | else: 213 | print('No utility function selected') 214 | gc.collect() 215 | return 0 216 | 217 | 218 | def ensure_dir(file_path): 219 | directory = os.path.dirname(file_path) 220 | if not os.path.exists(directory): 221 | os.makedirs(directory) 222 | return 223 | 224 | 225 | if __name__ == "__main__": 226 | # parse command line argument to figure out whether or not to filter the original safecast CSV 227 | do_preparation = False 228 | if len(sys.argv) > 1: 229 | do_preparation = (sys.argv[1] == "--do_preparation") 230 | apply_mechanisms(do_preparation) 231 | -------------------------------------------------------------------------------- /attackmodule.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import pandas as pd 3 | from sklearn.cluster import DBSCAN 4 | from __init__ import RADIANT_TO_KM_CONSTANT 5 | 6 | 7 | 8 | def attackscript(minpoints, mindistance, maxpois, coords,coords_with_date): 9 | if len(coords) == 0: 10 | print "No coords found :/" 11 | exit(-1) 12 | mindistance = mindistance / 1000.0 # necessary for the calculation in meters 13 | epsilon = mindistance / RADIANT_TO_KM_CONSTANT 14 | # This part can be changed to whatever the user prefers. 15 | # in this scenario we use the dbscan 16 | cluster_labels = dbscan(epsilon, minpoints, coords) 17 | try: 18 | num_clusters = len(set(cluster_labels)) # get the number of clusters 19 | if num_clusters == 1 or num_clusters ==0: 20 | return 0, 0 21 | else: 22 | clusters_with_date = pd.Series( 23 | sorted([coords_with_date[cluster_labels == n] for n in range(0, min(maxpois, num_clusters - 1))], 24 | key=lambda x: len(x), reverse=True)) 25 | 26 | return clusters_with_date, num_clusters 27 | except TypeError: 28 | return 0,0 29 | 30 | def dbscan(epsilon, minpoints, coords): 31 | db = DBSCAN(eps=epsilon, min_samples=minpoints, algorithm='ball_tree', metric='haversine', leaf_size=100).fit( 32 | np.radians(coords)) 33 | return db.labels_ # get the label on which cluster every point belongs to 34 | 35 | 36 | -------------------------------------------------------------------------------- /automated_pipeline.py: -------------------------------------------------------------------------------- 1 | import privacy_gain 2 | import plot_privacy_gain 3 | 4 | from apply_defenses import * 5 | from multiprocessing import freeze_support 6 | from plot_utilities import * 7 | from __init__ import dataset_used 8 | # the main automation function 9 | # runs the defenses and 10 | # calculates privacy loss 11 | 12 | 13 | def runpipeline(): 14 | 15 | # extract region and apply defenses 16 | apply_mechanisms(1) # apply defenses 17 | 18 | # Calculate users' privacy before and after defenses 19 | privacy_gain.main_privacy_gain(1) # ca lculate privacy loss 20 | 21 | # Calculate utility loss 22 | if 'Safecast' == dataset_used: 23 | safecast_utility() 24 | elif 'Radiocells' == dataset_used: 25 | radiocells_utility() 26 | else: 27 | pass 28 | 29 | 30 | # Calculate privacy gains and plot them 31 | plot_privacy_gain.create_colormap() 32 | plot_privacy_gain.parseuserdefs() 33 | plot_privacy_gain.plotscatter() 34 | return 0 35 | 36 | 37 | if __name__ == "__main__": 38 | runpipeline() 39 | -------------------------------------------------------------------------------- /defense_mechanisms.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import math 3 | import random 4 | from numpy.random import random_sample 5 | from scipy.special import lambertw 6 | import pandas as pd 7 | from cHaversine import haversine 8 | from sklearn.metrics.pairwise import pairwise_distances 9 | import time 10 | import csv 11 | from __init__ import RADIANT_TO_KM_CONSTANT 12 | import threading 13 | 14 | pd.options.mode.chained_assignment = None # default='warn' 15 | 16 | mylockprint = threading.RLock() 17 | 18 | def printmsg(text): 19 | with mylockprint: 20 | print text 21 | return 22 | 23 | 24 | ############################################################### 25 | # 26 | # Apply privacy by simply rounding the coordinates to N_DIGITS 27 | # 28 | # 29 | ############################################################## 30 | def apply_rounding(DATA_PATH, DESTINATION_ROUNDING, N_DIGITS): 31 | df = pd.read_csv(DATA_PATH) 32 | df = df.round({'Latitude': N_DIGITS, 'Longitude': N_DIGITS}) 33 | # df.Latitude = df.Latitude*10000 34 | # df.Longitude = df.Longitude*10000 # we multiply with 10000 in order to save it as interger and not lose precission 35 | floatformat = '%.{}f'.format(N_DIGITS) 36 | df.to_csv(DESTINATION_ROUNDING, index=False, float_format=floatformat) 37 | 38 | return 0 39 | 40 | 41 | def checkcoords(lat,lng): 42 | return (lat >=- 90 and lat <= 90) and ( lng >= -180 and lng <=180) 43 | 44 | 45 | ############################################################### 46 | # 47 | # Apply privacy by simply taking a random sub sample 48 | # 49 | # 50 | ############################################################## 51 | def apply_random_percent(DATA_PATH, DESTINATION, perc): 52 | time.sleep(0.1) 53 | np.random.seed(None) 54 | random.seed(None) 55 | df = pd.read_csv(DATA_PATH) 56 | groups = df.sort_values(['User ID', 'Captured Time']) 57 | with open(DESTINATION, 'wb+') as writerlocation: 58 | writer_geoind = csv.writer(writerlocation, delimiter=",") 59 | writer_geoind.writerow(df.columns) 60 | for index, row in groups.iterrows(): 61 | if flip_biased_coin(perc): writer_geoind.writerow(row.values) 62 | return 0 63 | 64 | 65 | def flip_biased_coin(perc): 66 | return 1 if random.random() < perc/100. else 0 67 | 68 | 69 | ############################################################### 70 | # 71 | # Apply privacy by letting points have a distance of x meters 72 | # 73 | # 74 | ############################################################## 75 | def apply_space_x(DATA_PATH, DESTINATION_SPACEX, desdistance): 76 | df = pd.read_csv(DATA_PATH) 77 | df = df.sort_values(by='Captured Time') 78 | grouped = df.groupby('User ID') 79 | tmpdf = [] 80 | for name, group in grouped: 81 | tmpdf.append(spacex(group, desdistance)) 82 | dfinal = pd.concat(tmpdf) 83 | dfinal.to_csv(DESTINATION_SPACEX, index=False) 84 | return 0 85 | 86 | 87 | def spacex(dfmain, desdistance): 88 | # previous to next point only if in logical time and space 89 | place = zip(dfmain.Latitude.values, dfmain.Longitude.values) 90 | dates = dfmain['Captured Time'].values 91 | dates = pd.to_datetime(dates) 92 | keep = [0] 93 | i = 1 94 | while i < dfmain.__len__() - 1: 95 | if haversine(place[keep[-1]], place[i]) > desdistance or dates[keep[-1]].date() != dates[i].date(): 96 | keep.append(i) 97 | i += 1 98 | 99 | if keep:np1 = np.array(keep) 100 | else : return 101 | 102 | return dfmain.iloc[np1] 103 | 104 | 105 | ############################# 106 | # Geoind mechanism 107 | 108 | def apply_geoind(DATA_PATH, DESTINATION_GEOIND, method, lamdaprv, radius, priorX, X,tree, OPTIMAL_REMAPPING): 109 | time.sleep(0.5) 110 | np.random.seed(None) # required for initialazation 111 | epsilon = float(lamdaprv / radius) 112 | newradius = -1. / epsilon * (np.real(lambertw((0.99 - 1) / math.e, k=-1)) + 1) 113 | cartesianCoords = X 114 | nopoiscnt = 0 115 | 116 | with open(DATA_PATH, "rb") as openedata: ## applies the noise in every line in the input file 117 | with open(DESTINATION_GEOIND, 'wb+') as writerlocation: 118 | startwhole = time.time() 119 | reader = csv.reader(openedata, delimiter=",") 120 | writer_geoind = csv.writer(writerlocation, delimiter=",") 121 | 122 | for i, line in enumerate(reader): 123 | startpoint = time.time() 124 | if i == 0: 125 | # Skip the header line 126 | writer_geoind.writerow(line) 127 | continue 128 | try: 129 | lat = float(line[3]) 130 | lng = float(line[4]) 131 | if not checkcoords(lat,lng): print "Wrong coordinates in the geoind", exit(-1) 132 | 133 | # Apply geoind... 134 | loc_original = np.array([lat, lng]) # original location 135 | r, theta = compute_noise(epsilon) 136 | loc_noise = addVectorToPos(loc_original, r, theta) 137 | 138 | # ...with optimal remapping 139 | if OPTIMAL_REMAPPING: 140 | loc_noise_cartesian = cartesian(loc_noise) 141 | index = tree.query_ball_point(loc_noise_cartesian, p=2.0, r=newradius) 142 | if len(index) == 0: 143 | nopoiscnt += 1 144 | # print "No suitable point found around", loc_noise 145 | loc_output = loc_noise 146 | line[3] = round(loc_output[0], 5) 147 | line[4] = round(loc_output[1], 5) 148 | writer_geoind.writerow(line) 149 | continue 150 | 151 | 152 | distances = pairwise_distances([loc_noise_cartesian], cartesianCoords[index]) 153 | tmparray = np.zeros(shape=distances[0].shape) 154 | dist1 = np.vstack((distances[0], tmparray)) 155 | startPost = time.time() 156 | posteriorX = priorX[index] * np.exp(-epsilon * dist1.transpose()) 157 | sumPostX = np.copy(posteriorX[:, 1]) 158 | posteriorX = np.multiply(priorX[index], 159 | np.exp(np.multiply(-epsilon, dist1.transpose()))) 160 | 161 | posteriorX = np.divide(posteriorX[:, 1], np.sum(sumPostX)) 162 | 163 | if np.sum(posteriorX) > 1.000000001 or np.sum(posteriorX) < 0.999999999: 164 | print "posterior problem" 165 | 166 | # print numpy.sum(posteriorX) 167 | loc_optimal = compute_geometric_median(posteriorX[:], X[index]) # optimal remapping 168 | if np.isnan(loc_optimal[0]) or np.isnan(loc_optimal[1]): 169 | loc_output = loc_noise 170 | else: 171 | loc_output = loc_optimal 172 | 173 | # ...without optimal remapping 174 | else: 175 | loc_output = loc_noise 176 | 177 | # write output (with same precision as in original data) 178 | line[3] = round(loc_output[0], 5) 179 | line[4] = round(loc_output[1], 5) 180 | 181 | writer_geoind.writerow(line) 182 | 183 | except Exception as e: 184 | print("Error: line[{}]: {} ; {}".format(i, line, e)) 185 | 186 | 187 | def geoind_traces(data_path, destination_path, lamdaprv,radius, desdistance): 188 | time.sleep(0.2) 189 | np.random.seed(None) 190 | place_to_write = destination_path 191 | epsilon = float(lamdaprv / radius) 192 | df = pd.read_csv(data_path) 193 | groups = df.sort_values(['User ID', 'Captured Time']) 194 | with open(place_to_write, 'wb+') as writerlocation: 195 | writer_geoind = csv.writer(writerlocation, delimiter=",") 196 | writer_geoind.writerow(df.columns) 197 | last_user = -1 198 | last_lat = -1 199 | last_lon = -1 200 | last_noisy_lat = -1 201 | last_noisy_lon = -1 202 | 203 | for index, row in groups.iterrows(): 204 | if row['User ID'] != last_user: 205 | last_user = row['User ID'] 206 | last_lat = row['Latitude'] 207 | last_lon = row['Longitude'] 208 | row['Latitude'], row['Longitude'] = geo_ind(row['Latitude'], row['Longitude'], epsilon) 209 | last_noisy_lat = row['Latitude'] 210 | last_noisy_lon = row['Longitude'] 211 | elif haversine((last_lat, last_lon), (row['Latitude'], row['Longitude'])) > desdistance: 212 | flag = 1 213 | last_lat = row['Latitude'] 214 | last_lon = row['Longitude'] 215 | row['Latitude'], row['Longitude'] = geo_ind(row['Latitude'], row['Longitude'], epsilon) 216 | last_noisy_lat = row['Latitude'] 217 | last_noisy_lon = row['Longitude'] 218 | else: 219 | row['Latitude'], row['Longitude'] = last_noisy_lat, last_noisy_lon 220 | 221 | writer_geoind.writerow(row.values) 222 | 223 | 224 | def geo_ind(lat, lon, epsilon): 225 | loc_original = np.array([lat, lon]) # original location 226 | r, theta = compute_noise(epsilon) 227 | loc_noise = addVectorToPos(loc_original, r, theta) 228 | return round(loc_noise[0], 5), round(loc_noise[1], 5) 229 | 230 | 231 | ######################################### 232 | # 233 | # Add the generated doise directly on the 234 | # gps coordinates 235 | # 236 | ######################################### 237 | def addVectorToPos(pos, distance, angle): 238 | ang_distance = distance / RADIANT_TO_KM_CONSTANT 239 | lat1 = rad_of_deg(pos[0]) 240 | lon1 = rad_of_deg(pos[1]) 241 | 242 | lat2 = math.asin( math.sin(lat1) * math.cos(ang_distance) + 243 | math.cos(lat1) * math.sin(ang_distance) * math.cos(angle)) 244 | lon2 = lon1 + math.atan2( 245 | math.sin(angle) * math.sin(ang_distance) * math.cos(lat1), 246 | math.cos(ang_distance) - math.sin(lat1) * math.sin(lat2) ) 247 | lon2 = (lon2 + 3 * math.pi) % (2 * math.pi) - math.pi #normalise to -180..+180 248 | return deg_of_rad(lat2), deg_of_rad(lon2) 249 | 250 | 251 | ############################################# 252 | # 253 | # Usefule for the addVectorToPos function 254 | # 255 | ############################################ 256 | def rad_of_deg(ang): return ang * math.pi / 180 257 | 258 | 259 | def deg_of_rad(ang): return ang * 180 / math.pi 260 | 261 | 262 | def compute_noise(param): 263 | epsilon = param 264 | theta = random_sample() * 2 * math.pi 265 | r = -1. / epsilon * (np.real(lambertw((random_sample() - 1) / math.e, k=-1)) + 1) 266 | return r, theta 267 | 268 | 269 | def cartesian(coords): 270 | lat=np.radians(coords[0]) 271 | lon=np.radians(coords[1]) 272 | x = RADIANT_TO_KM_CONSTANT * np.cos(lat) * np.cos(lon) 273 | y = RADIANT_TO_KM_CONSTANT * np.cos(lat) * np.sin(lon) 274 | return np.array([x, y]) 275 | 276 | 277 | def compute_geometric_median(probabilities_input, values_input): 278 | # Computes the geometric median. Weiszfeld's algorithm 279 | probabilities = np.copy(probabilities_input) 280 | values = np.copy(values_input) 281 | 282 | values = values[probabilities > 0] # remove entries of values with probability of 0 283 | probabilities = probabilities[probabilities > 0] # remove zero entries 284 | geo_median_old = np.array([float("inf"), float("inf")]) 285 | geo_median = np.dot(probabilities.transpose(), values) # Initial estimation is the mean 286 | nIter = 0 287 | while (check_condition(geo_median, geo_median_old)) and (nIter < 200): 288 | 289 | distance_matrix = pairwise_distances([geo_median], values) 290 | distance_matrix = distance_matrix[0] 291 | # Return if there is a zero value in distance_matrix 292 | if np.any(distance_matrix == 0): 293 | #print "emerg brake", nIter 294 | return geo_median 295 | # print len(distance_matrix) 296 | geo_median_old = geo_median 297 | div = np.divide(probabilities, distance_matrix) 298 | geo_median = np.divide(np.dot(div, values), np.dot(div, np.ones_like(values))) 299 | nIter += 1 300 | return geo_median 301 | 302 | 303 | def check_condition(geo_median, geo_median_old): 304 | return np.linalg.norm(geo_median - geo_median_old) > 1e-3 305 | -------------------------------------------------------------------------------- /getJson.py: -------------------------------------------------------------------------------- 1 | import json 2 | import sys 3 | 4 | def get(): 5 | try: 6 | with open("pipelineJson.json") as config_file: 7 | return json.load(config_file) 8 | except: 9 | sys.stderr.write("No pipelineJson file found. Please adjust the settings.") 10 | exit(-1) 11 | 12 | -------------------------------------------------------------------------------- /pipelineJson.json: -------------------------------------------------------------------------------- 1 | { 2 | "place" : "World", 3 | "dataset_used": "Radiocells", 4 | "minpoints" : 100, 5 | "maxdistance" : 30, 6 | "maxpois" : 5, 7 | "starttime" : 9, 8 | "endtime" : 17, 9 | 10 | 11 | "advanced_clustering" : 0, 12 | "min_allowed_points" : 10, 13 | "max_allowed_distance" : 60, 14 | "original_min_points" : 80, 15 | 16 | "Polygon" :[[ 35.789916, 139.895402], [35.881347, 138.976238], 17 | [35.335782, 139.562698], [35.441517, 139.850289]] 18 | } -------------------------------------------------------------------------------- /plot_privacy_gain.py: -------------------------------------------------------------------------------- 1 | import pandas as pd 2 | import cPickle as pickle 3 | import os 4 | import matplotlib.pyplot as plt 5 | import matplotlib.patches as mpatches 6 | import numpy as np 7 | 8 | from pylab import plot, show, savefig, xlim, figure, hold, ylim, legend, boxplot, setp, axes 9 | from matplotlib.lines import Line2D 10 | from __init__ import (starttime, endtime, place,minpoints, maxdistance, 11 | writeplace, DATA_BASE_WRITE_UTILITY,defenses_path,original_pickle,advanced_clustering, mypath, 12 | datapath_to_original_file, privacyloss_path,utilities_plot, 13 | return_write_path) 14 | 15 | 16 | plt.rc('font', family='serif', serif='Times') 17 | plt.rc('text', usetex=True) 18 | SMALL_SIZE = 9 19 | MEDIUM_SIZE = 11 20 | BIGGER_SIZE = 11 21 | 22 | plt.rc('font', size=MEDIUM_SIZE) # controls default text sizes 23 | plt.rc('axes', titlesize=MEDIUM_SIZE) # fontsize of the axes title 24 | plt.rc('axes', labelsize=MEDIUM_SIZE) # fontsize of the x and y labels 25 | plt.rc('xtick', labelsize=MEDIUM_SIZE) # fontsize of the tick labels 26 | plt.rc('ytick', labelsize=MEDIUM_SIZE) # fontsize of the tick labels 27 | plt.rc('legend', fontsize=MEDIUM_SIZE) # legend fontsize 28 | plt.rc('figure', titlesize=MEDIUM_SIZE) # fontsize of the figure title 29 | rotation = 45 30 | width = 8.2 31 | height = 6 32 | flierprops = dict(marker='.', markerfacecolor='k', markersize=2, 33 | linestyle='none', markeredgecolor='k') 34 | 35 | 36 | def parseuserdefs(): 37 | # load up original meas and inter 38 | cities=['World'] 39 | 40 | savename='cities' 41 | if advanced_clustering: 42 | savename = savename+'advanced' 43 | else: 44 | savename = savename+'standard' 45 | cities_dict = {} 46 | defs = ['geoind[1.6, 0.05]', 47 | 'geoind[1.6, 0.15]', 48 | 'geoind[1.6, 0.3]', 49 | 'remap[1.6, 0.05]', 50 | 'remap[1.6, 0.15]', 51 | 'remap[1.6, 0.3]', 52 | 'rnd_sample[40]', 53 | 'rnd_sample[60]', 54 | 'rnd_sample[80]', 55 | 'rounded_2_digits', 56 | 'rounded_3_digits', 57 | 'rounded[4]', 58 | 'geoind_traces[1.6, 0.05, 30.0]', 59 | 'geoind_traces[1.6, 0.05, 60.0]', 60 | 'geoind_traces[1.6, 0.05, 90.0]', 61 | 'spacex[30.0]', 62 | 'spacex[60.0]', 63 | 'spacex[90.0]'] 64 | 65 | new_name_defs = ['GeoInd: 50m', 66 | 'GeoInd: 150m', 67 | 'GeoInd: 300m', 68 | 'GeoInd-OR: 50m', 69 | 'GeoInd-OR: 150m', 70 | 'GeoInd-OR: 300m', 71 | 'Random: 40%', 72 | 'Random: 60%', 73 | 'Random: 80%', 74 | 'Rounding: 2', 75 | 'Rounding: 3', 76 | 'Rounding: 4', 77 | 'Release-GeoInd: 30m', 78 | 'Release-GeoInd: 60m', 79 | 'Release-GeoInd: 90m', 80 | 'Release: 30m', 81 | 'Release: 60m', 82 | 'Release: 90m'] 83 | 84 | print 'original pickle loaded' 85 | 86 | for citynum, city in enumerate(cities): 87 | cities_dict[city] = {} 88 | thisplace = city 89 | writeplace = return_write_path(city) 90 | 91 | print '''I will read from {}'''.format(writeplace) 92 | # place = 'Tokyobak' 93 | DATA_PATH = privacyloss_path + writeplace + "/" 94 | print DATA_PATH 95 | original_file_toread = datapath_to_original_file 96 | dfmain = pd.read_csv(original_file_toread) 97 | print 'original file read' 98 | 99 | df = dfmain[((pd.to_datetime(dfmain['Captured Time']) + ( 100 | pd.to_timedelta(dfmain['offset'] / 60, unit='h'))).dt.hour > starttime) & 101 | ((pd.to_datetime(dfmain['Captured Time']) + ( 102 | pd.to_timedelta(dfmain['offset'] / 60, unit='h'))).dt.hour < endtime) & 103 | ((pd.to_datetime(dfmain['Captured Time']) + ( 104 | pd.to_timedelta(dfmain['offset'] / 60, unit='h'))).dt.dayofweek < 5)] 105 | 106 | print 'hours changed and parsed' 107 | 108 | with open(original_pickle, "rb+") as f: 109 | doriginal = pickle.load(f) 110 | 111 | listorig = doriginal.keys() 112 | a = set(listorig) 113 | 114 | for defidx,item in enumerate(defs): 115 | print defidx, item 116 | cities_dict[city][new_name_defs[defidx]]={} 117 | cities_dict[city][new_name_defs[defidx]]['topusers'] = {} 118 | cities_dict[city][new_name_defs[defidx]]['medusers'] = {} 119 | cities_dict[city][new_name_defs[defidx]]['lowusers'] = {} 120 | 121 | cities_dict[city][new_name_defs[defidx]]['topusers']['clusters'] = {} 122 | cities_dict[city][new_name_defs[defidx]]['medusers']['clusters'] = {} 123 | cities_dict[city][new_name_defs[defidx]]['lowusers']['clusters'] = {} 124 | 125 | cities_dict[city][new_name_defs[defidx]]['topusers']['pois'] = {} 126 | cities_dict[city][new_name_defs[defidx]]['medusers']['pois'] = {} 127 | cities_dict[city][new_name_defs[defidx]]['lowusers']['pois'] = {} 128 | 129 | cities_dict[city][new_name_defs[defidx]]['topusers']['clusters']['precision'] = {} 130 | cities_dict[city][new_name_defs[defidx]]['medusers']['clusters']['precision'] = {} 131 | cities_dict[city][new_name_defs[defidx]]['lowusers']['clusters']['precision'] = {} 132 | cities_dict[city][new_name_defs[defidx]]['topusers']['clusters']['recall'] = {} 133 | cities_dict[city][new_name_defs[defidx]]['medusers']['clusters']['recall'] = {} 134 | cities_dict[city][new_name_defs[defidx]]['lowusers']['clusters']['recall'] = {} 135 | 136 | cities_dict[city][new_name_defs[defidx]]['topusers']['pois']['precision'] = {} 137 | cities_dict[city][new_name_defs[defidx]]['medusers']['pois']['precision'] = {} 138 | cities_dict[city][new_name_defs[defidx]]['lowusers']['pois']['precision'] = {} 139 | cities_dict[city][new_name_defs[defidx]]['topusers']['pois']['recall'] = {} 140 | cities_dict[city][new_name_defs[defidx]]['medusers']['pois']['recall'] = {} 141 | cities_dict[city][new_name_defs[defidx]]['lowusers']['pois']['recall'] = {} 142 | 143 | try: 144 | with open(os.path.join(DATA_PATH, item + '.pickle'), "rb+") as f: 145 | dfake = pickle.load(f) 146 | except IOError as e: 147 | print e 148 | continue 149 | 150 | listfake = dfake.keys() 151 | b = set(listfake) 152 | c = list(a.intersection(b)) 153 | 154 | topusers = [] 155 | medusers = [] 156 | lowusers = [] 157 | topuserspois = [] 158 | meduserspois = [] 159 | lowuserspois = [] 160 | fdrlist_pois = [] 161 | recall_list_pois = [] 162 | precisionlist_pois = [] 163 | 164 | if c: 165 | for idx, i in enumerate(c): 166 | counts = len(df[df['User ID'] == i].index) 167 | 168 | try: 169 | 170 | intersection = (doriginal[i]['Polygon'].intersection(dfake[i]['Polygon'])).area 171 | fdr = ( dfake[i]['Polygon'].area - intersection ) / dfake[i]['Polygon'].area 172 | precision = 1-fdr 173 | recall = intersection / doriginal[i]['Polygon'].area 174 | 175 | if counts > 50000: 176 | topusers.append((precision, recall)) 177 | elif counts > 10000: 178 | medusers.append((precision, recall)) 179 | else: 180 | lowusers.append((precision, recall)) 181 | 182 | except ZeroDivisionError: 183 | pass 184 | 185 | poisb4 = doriginal[i]['Node_Ids'] 186 | poisb4 = [elem for elem in poisb4 if elem != []] 187 | poisb4 = [j for elem in poisb4 for j in elem] 188 | poisafter = dfake[i]['Node_Ids'] 189 | poisafter = [elem for elem in poisafter if elem != []] 190 | poisafter = [j for elem in poisafter for j in elem] 191 | try: 192 | poisb4 = [j for elem in poisb4 for j in elem] 193 | except TypeError: 194 | pass 195 | try: 196 | poisafter = [j for elem in poisafter for j in elem] 197 | except TypeError: 198 | pass 199 | 200 | try: 201 | 202 | tp_pois = float(len(set(poisb4) - (set(poisb4) - set(poisafter)))) 203 | fdr_pois = (float(len(poisafter)) - tp_pois) / len(poisafter) 204 | precision_pois = 1 - fdr_pois 205 | recall_pois = tp_pois / len(poisb4) 206 | if counts > 50000: 207 | topuserspois.append((precision_pois, recall_pois)) 208 | elif counts > 10000: 209 | meduserspois.append((precision_pois, recall_pois)) 210 | else: 211 | lowuserspois.append((precision_pois, recall_pois)) 212 | 213 | except ZeroDivisionError: 214 | pass 215 | 216 | try: 217 | cities_dict[city][new_name_defs[defidx]]['topusers']['clusters']['precision'] = zip(*topusers)[0] 218 | cities_dict[city][new_name_defs[defidx]]['topusers']['clusters']['recall'] = zip(*topusers)[1] 219 | 220 | except IndexError as err: 221 | pass 222 | try: 223 | cities_dict[city][new_name_defs[defidx]]['medusers']['clusters']['precision'] = zip(*medusers)[0] 224 | cities_dict[city][new_name_defs[defidx]]['medusers']['clusters']['recall'] = zip(*medusers)[1] 225 | 226 | except IndexError as err: 227 | pass 228 | 229 | try: 230 | cities_dict[city][new_name_defs[defidx]]['lowusers']['clusters']['precision'] = zip(*lowusers)[0] 231 | cities_dict[city][new_name_defs[defidx]]['lowusers']['clusters']['recall'] = zip(*lowusers)[1] 232 | 233 | except IndexError as err: 234 | pass 235 | 236 | 237 | 238 | try: 239 | cities_dict[city][new_name_defs[defidx]]['topusers']['pois']['precision'] = zip(*topuserspois)[0] 240 | cities_dict[city][new_name_defs[defidx]]['topusers']['pois']['recall'] = zip(*topuserspois)[1] 241 | 242 | except IndexError as err: 243 | pass 244 | try: 245 | cities_dict[city][new_name_defs[defidx]]['medusers']['pois']['precision'] = zip(*meduserspois)[0] 246 | cities_dict[city][new_name_defs[defidx]]['medusers']['pois']['recall'] = zip(*meduserspois)[1] 247 | 248 | except IndexError as err: 249 | pass 250 | 251 | try: 252 | cities_dict[city][new_name_defs[defidx]]['lowusers']['pois']['precision'] = zip(*lowuserspois)[0] 253 | cities_dict[city][new_name_defs[defidx]]['lowusers']['pois']['recall'] = zip(*lowuserspois)[1] 254 | 255 | except IndexError as err: 256 | pass 257 | 258 | with open(privacyloss_path+"clustersimgafinal{}.pickle".format(savename),"wb+")as f: 259 | pickle.dump(cities_dict,f) 260 | 261 | 262 | def plotscatter(): 263 | cities = ['World'] 264 | myfigure, axes = plt.subplots(2, 3, sharey='all', figsize=(width, height)) 265 | disc_dict = {} 266 | savename='cities' 267 | if advanced_clustering: 268 | savename = savename+'advanced' 269 | else: 270 | savename = savename+'standard' 271 | 272 | defs = ['GeoInd: 50m', 273 | 'GeoInd: 150m', 274 | 'GeoInd: 300m', 275 | 'GeoInd-OR: 50m', 276 | 'GeoInd-OR: 150m', 277 | 'GeoInd-OR: 300m', 278 | 'Random: 40%', 279 | 'Random: 60%', 280 | 'Random: 80%', 281 | 'Rounding: 2', 282 | 'Rounding: 3', 283 | 'Rounding: 4', 284 | 'Release-GeoInd: 30m', 285 | 'Release-GeoInd: 60m', 286 | 'Release-GeoInd: 90m', 287 | 'Release: 30m', 288 | 'Release: 60m', 289 | 'Release: 90m'] 290 | 291 | with open(mypath + "cm.pickle", "rb+") as f: 292 | cmap = pickle.load(f) 293 | print 'colors loaded' 294 | legend_elements = [] 295 | legendpois_elements = [] 296 | for defidx, item in enumerate(defs): 297 | legend_elements.append(Line2D([0], [0], color=cmap[item], label=defs[defidx])) 298 | 299 | legendpois_elements = [Line2D([], [], linestyle='None', marker='^', color='k', label='$x > 50K$'), 300 | Line2D([], [], linestyle='None', marker='o', color='k', label='$10K < x < 50K$'), 301 | Line2D([], [], linestyle='None', marker='+', color='k', label='$x < 10K$')] 302 | 303 | with open(privacyloss_path+"clustersimgafinal{}.pickle".format(savename), "rb") as mypickleplot: 304 | d = pickle.load(mypickleplot) 305 | print 'image file read' 306 | 307 | for citynum ,city in enumerate(cities): 308 | print city 309 | disc_dict[city] = {} 310 | 311 | if 'Tokyo' in city: 312 | total = 30 313 | elif 'Fukushima' in city: 314 | total = 104 315 | else: 316 | total = 537 317 | 318 | disc_dict[city]['total'] = total 319 | 320 | for defense in d[city].keys(): 321 | 322 | if not 'GeoInd' in defense: pass 323 | print "------------",defense 324 | try: 325 | axes[0,citynum].scatter(list(d[city][defense]['topusers']['clusters']['precision']), 326 | list(d[city][defense]['topusers']['clusters']['recall']), c=cmap[defense], s=26, marker="^") 327 | except KeyError as err: 328 | print err 329 | 330 | try: 331 | axes[0, citynum].scatter(list(d[city][defense]['medusers']['clusters']['precision']), 332 | list(d[city][defense]['medusers']['clusters']['recall']), c=cmap[defense], s=26, marker="o") 333 | except KeyError as err: 334 | print err 335 | 336 | try: 337 | axes[0, citynum].scatter(list(d[city][defense]['lowusers']['clusters']['precision']), 338 | list(d[city][defense]['lowusers']['clusters']['recall']), c=cmap[defense], s=26, marker="+") 339 | except KeyError as err: 340 | print err 341 | 342 | disc_dict[city][defense] = disc_dict[city]['total'] - (len(d[city][defense]['lowusers']['clusters']['precision']) + 343 | len(d[city][defense]['medusers']['clusters']['precision']) + 344 | len(d[city][defense]['topusers']['clusters']['precision']) ) 345 | 346 | axes[0,citynum].spines["top"].set_visible(False) 347 | axes[0,citynum].spines["bottom"].set_visible(True) 348 | axes[0,citynum].spines["right"].set_visible(False) 349 | axes[0,citynum].spines["left"].set_visible(True) 350 | axes[0,citynum].set(xlim=[-0.1, 1.1], 351 | ylim=[-0.1, 1.1], 352 | aspect=1, 353 | xticks = [0,0.25,0.5,0.75,1]) 354 | 355 | for citynum, city in enumerate(cities): 356 | print city 357 | 358 | for defense in d[city].keys(): 359 | 360 | print "------------",defense 361 | try: 362 | axes[1, citynum].scatter(list(d[city][defense]['topusers']['pois']['precision']), 363 | list(d[city][defense]['topusers']['pois']['recall']), c=cmap[defense], 364 | s=26, marker="^") 365 | except KeyError as err: 366 | print err 367 | 368 | try: 369 | axes[1, citynum].scatter(list(d[city][defense]['medusers']['pois']['precision']), 370 | list(d[city][defense]['medusers']['pois']['recall']), c=cmap[defense], 371 | s=26, marker="o") 372 | except KeyError as err: 373 | print err 374 | 375 | try: 376 | axes[1, citynum].scatter(list(d[city][defense]['lowusers']['pois']['precision']), 377 | list(d[city][defense]['lowusers']['pois']['recall']), c=cmap[defense], 378 | s=26, marker="+") 379 | except KeyError as err: 380 | print err 381 | 382 | axes[1,citynum].spines["top"].set_visible(False) 383 | axes[1,citynum].spines["bottom"].set_visible(True) 384 | axes[1,citynum].spines["right"].set_visible(False) 385 | axes[1,citynum].spines["left"].set_visible(True) 386 | axes[1,citynum].set(xlim=[-0.1, 1.1], 387 | ylim=[-0.1, 1.1], 388 | aspect=1, 389 | xticks=[0, 0.25, 0.5, 0.75, 1]) 390 | 391 | mylegend = plt.figlegend(bbox_to_anchor=(0.5, 0.97), loc='upper center', ncol=6, labelspacing=0., 392 | handles=legend_elements, title='Defenses', prop={'size': 9}) 393 | myfigure.text(0.5, 0.04, 'Precision', ha='center') 394 | myfigure.text(0.06, 0.5, 'Recall', va='center', rotation='vertical') 395 | 396 | myfigure.text(0.035, 0.3, 'POIs', va='center', rotation='vertical') 397 | myfigure.text(0.035, 0.7, 'Spatial', va='center', rotation='vertical') 398 | 399 | myfigure.text(0.235, 0.469, 'Tokyo', ha='center') 400 | myfigure.text(0.517, 0.469, 'Fukushima', ha='center') 401 | myfigure.text(0.785, 0.469, 'World', ha='center') 402 | 403 | #mylegend2 = plt.figlegend(bbox_to_anchor=(0.5, 0.89), loc='upper center', labelspacing=0., 404 | #handles=legendpois_elements, title='Amount of Measurements (x)', ncol=3) 405 | leg_lines = mylegend.get_lines() 406 | plt.setp(leg_lines, linewidth=3) 407 | mylegend.get_frame().set_alpha(0) 408 | mylegend.get_frame().set_edgecolor('white') 409 | 410 | plt.savefig(utilities_plot+'privacy_gain_{}.png'.format(savename),dpi=360, transparent =True, frameon= False,bbox_inches='tight') 411 | 412 | #plt.show() 413 | for i in disc_dict.keys(): 414 | print i 415 | for j in disc_dict[i].keys(): 416 | print j, ":", disc_dict[i][j] 417 | 418 | 419 | def create_colormap(): 420 | new_colors = {'GeoInd-OR: 50m': 'orange', 421 | 'GeoInd-OR: 150m': 'coral', 422 | 'GeoInd-OR: 300m': 'red', 423 | 'GeoInd: 50m': 'silver', 424 | 'GeoInd: 150m': 'gray', 425 | 'GeoInd: 300m': 'k', 426 | 'Random: 40%': 'lightgreen', 427 | 'Random: 60%': 'yellowgreen', 428 | 'Random: 80%': 'g', 429 | 'Release: 60m': 'aqua', 430 | 'Release: 90m': 'b', 431 | 'Release: 30m': 'skyblue', 432 | 'Rounding: 2': 'violet', 433 | 'Rounding: 3': 'fuchsia', 434 | 'Rounding: 4': 'deeppink', 435 | 'Release-GeoInd: 30m':'yellow', 436 | 'Release-GeoInd: 60m':'y', 437 | 'Release-GeoInd: 90m':'olive'} 438 | 439 | with open(mypath+"cm.pickle", "wb+") as f: 440 | pickle.dump(new_colors,f) 441 | 442 | 443 | if __name__ == "__main__": 444 | create_colormap() 445 | parseuserdefs() 446 | plotscatter() 447 | -------------------------------------------------------------------------------- /plot_utilities.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import pandas as pd 3 | import matplotlib 4 | import matplotlib.pyplot as plt 5 | 6 | from cHaversine import haversine 7 | from __init__ import defenses_path, place, filespath, DATA_PATH, utilities_plot 8 | from apply_defenses import ensure_dir 9 | 10 | 11 | def safecast_utility(): 12 | ensure_dir(utilities_plot) 13 | 14 | plt.rc('font', family='serif', serif='Times') 15 | plt.rc('text', usetex=True) 16 | SMALL_SIZE = 9 17 | MEDIUM_SIZE = 10 18 | BIGGER_SIZE = 11 19 | 20 | plt.rc('font', size=MEDIUM_SIZE) # controls default text sizes 21 | plt.rc('axes', titlesize=MEDIUM_SIZE) # fontsize of the axes title 22 | plt.rc('axes', labelsize=MEDIUM_SIZE) # fontsize of the x and y labels 23 | plt.rc('xtick', labelsize=MEDIUM_SIZE) # fontsize of the tick labels 24 | plt.rc('ytick', labelsize=MEDIUM_SIZE) # fontsize of the tick labels 25 | plt.rc('legend', fontsize=MEDIUM_SIZE) # legend fontsize 26 | plt.rc('figure', titlesize=MEDIUM_SIZE) # fontsize of the figure title 27 | flierprops = dict(marker='+', markerfacecolor='r', markersize=0.3, 28 | linestyle='none', markeredgecolor='r') 29 | 30 | boxprops = dict(linestyle='--') 31 | medianprops = dict(linestyle='-', linewidth=2.5, color='k') 32 | 33 | rotation = 45 34 | width = 4.5 35 | height = 3.5 36 | defs = ['geoind_lamda_1.6_radius_0.05_method_lap', 37 | 'geoind_lamda_1.6_radius_0.15_method_lap', 38 | 'geoind_lamda_1.6_radius_0.3_method_lap', 39 | 'geoind_lamda_1.6_radius_0.05_method_lap_remapping', 40 | 'geoind_lamda_1.6_radius_0.15_method_lap_remapping', 41 | 'geoind_lamda_1.6_radius_0.3_method_lap_remapping', 42 | 'geoind_traces_1.6_radius_0.05_distance_30', 43 | 'geoind_traces_1.6_radius_0.05_distance_60', 44 | 'geoind_traces_1.6_radius_0.05_distance_90', 45 | 'random_sample_80_percent', 46 | 'random_sample_60_percent', 47 | 'random_sample_40_percent', 48 | 'rounded_4_digits', 49 | 'rounded_3_digits', 50 | 'rounded_2_digits', 51 | 'spacex_30_meters', 52 | 'spacex_60_meters', 53 | 'spacex_90_meters'] 54 | 55 | new_name_defs = ['GeoInd: 50m', 56 | 'GeoInd: 150m', 57 | 'GeoInd: 300m', 58 | 'GeoInd-OR: 50m', 59 | 'GeoInd-OR: 150m', 60 | 'GeoInd-OR: 300m', 61 | 'Release-GeoInd: 30m', 62 | 'Release-GeoInd: 60m', 63 | 'Release-GeoInd: 90m', 64 | 'Random: 80%', 65 | 'Random: 60%', 66 | 'Random: 40%', 67 | 'Rounding: 4', 68 | 'Rounding: 3', 69 | 'Rounding: 2', 70 | 'Release: 30m', 71 | 'Release: 60m', 72 | 'Release: 90m'] 73 | 74 | data_to_plot = [] 75 | data_to_plot_ushv = [] 76 | data_to_plot_mape = [] 77 | names = [] 78 | vals = [] 79 | origpath = defenses_path + '/{}/'.format(place)+place+'.interpolated.csv' 80 | orig = pd.read_csv(origpath, header = None) 81 | oricat = orig.values.ravel() 82 | oricat = (oricat/350.0)*8.760 83 | oricat = np.array(oricat.tolist()) 84 | 85 | dfs= [] 86 | allparams = [] 87 | plotpure = [] 88 | plotpure.append(orig.values.ravel()) 89 | namestmp = [] 90 | namestmp.append('original') 91 | categorical = [] 92 | for defidx,item in enumerate(defs): 93 | try: 94 | df = pd.read_csv(defenses_path + '/{}/{}.interpolated.csv'.format(item, item),header = None) 95 | except IOError as e: 96 | print e 97 | continue 98 | plotpure.append((df.values.ravel()).round(3)) 99 | ss = df.subtract(orig) 100 | defcat = ss.values.ravel() 101 | defcat = (defcat/350.0)*8.760 # safecast radiation transformation 102 | defcat = np.array(defcat.tolist()) 103 | ss = ss.abs() 104 | ss = ss.values 105 | ss = ss.ravel() 106 | data_to_plot.append(np.round(ss, decimals=2)) 107 | data_to_plot_ushv.append((ss/350.0).round(3)) 108 | tt = orig.subtract(df) 109 | tt = tt.div(orig) 110 | tt = tt.abs() 111 | tt = tt*100 112 | tt =tt.values 113 | tt = tt.ravel() 114 | data_to_plot_mape.append(tt.round(3)) 115 | names.append(new_name_defs[defidx]) 116 | namestmp.append(new_name_defs[defidx]) 117 | vals.append(np.count_nonzero(~np.isnan(ss))) 118 | 119 | ##### difference 120 | fig1 = plt.figure(1,figsize=(width,height)) 121 | 122 | # Create an axes instance 123 | ax1 = fig1.gca() 124 | 125 | # Create the boxplot 126 | bp1 = ax1.boxplot(data_to_plot,flierprops=flierprops,boxprops=boxprops, medianprops=medianprops, 127 | widths = 0.35, patch_artist=False, showmeans = False)#, boxprops=dict(facecolor="lightblue")) 128 | 129 | ax1.set_xticklabels(names, rotation=rotation, ha='right', minor=False) 130 | ax1.spines["top"].set_visible(False) 131 | ax1.spines["bottom"].set_visible(False) 132 | ax1.spines["right"].set_visible(False) 133 | ax1.spines["left"].set_visible(False) 134 | 135 | ax1.set_yscale('symlog', linthreshy=10) 136 | minax,maxax = ax1.set_ylim(10 ** -6, 10 ** 5) 137 | 138 | ax1.set_ylabel('cpm') 139 | 140 | fig1.tight_layout() 141 | 142 | plt.savefig(utilities_plot +place+'Absolute_Difference.png',dpi=360, transparent =True, frameon= False) 143 | 144 | 145 | def radiocells_utility(): 146 | ensure_dir(utilities_plot) 147 | 148 | plt.rc('font', family='serif', serif='Times') 149 | plt.rc('text', usetex=True) 150 | flierprops = dict(marker='+', markerfacecolor='r', markersize=0.3, 151 | linestyle='none', markeredgecolor='r') 152 | 153 | boxprops = dict(linestyle='--') 154 | medianprops = dict(linestyle='-', linewidth=2.5, color='k') 155 | SMALL_SIZE = 9 156 | MEDIUM_SIZE = 10 157 | BIGGER_SIZE = 11 158 | plt.rc('font', size=MEDIUM_SIZE) # controls default text sizes 159 | plt.rc('axes', titlesize=MEDIUM_SIZE) # fontsize of the axes title 160 | plt.rc('axes', labelsize=MEDIUM_SIZE) # fontsize of the x and y labels 161 | plt.rc('xtick', labelsize=MEDIUM_SIZE) # fontsize of the tick labels 162 | plt.rc('ytick', labelsize=MEDIUM_SIZE) # fontsize of the tick labels 163 | plt.rc('legend', fontsize=MEDIUM_SIZE) # legend fontsize 164 | plt.rc('figure', titlesize=MEDIUM_SIZE) # fontsize of the figure title 165 | rotation = 45 166 | width = 4.5 167 | height = 3.5 168 | 169 | defs = ['geoind_lamda_1.6_radius_0.05_method_lap', 170 | 'geoind_lamda_1.6_radius_0.15_method_lap', 171 | 'geoind_lamda_1.6_radius_0.3_method_lap', 172 | 'geoind_lamda_1.6_radius_0.05_method_lap_remapping', 173 | 'geoind_lamda_1.6_radius_0.15_method_lap_remapping', 174 | 'geoind_lamda_1.6_radius_0.3_method_lap_remapping', 175 | 'geoind_traces_1.6_radius_0.05_distance_30', 176 | 'geoind_traces_1.6_radius_0.05_distance_60', 177 | 'geoind_traces_1.6_radius_0.05_distance_90', 178 | 'random_sample_80_percent', 179 | 'random_sample_60_percent', 180 | 'random_sample_40_percent', 181 | 'rounded_4_digits', 182 | 'rounded_3_digits', 183 | 'rounded_2_digits', 184 | 'spacex_30_meters', 185 | 'spacex_60_meters', 186 | 'spacex_90_meters'] 187 | 188 | new_name_defs = ['GeoInd: 50m', 189 | 'GeoInd: 150m', 190 | 'GeoInd: 300m', 191 | 'GeoInd-OR: 50m', 192 | 'GeoInd-OR: 150m', 193 | 'GeoInd-OR: 300m', 194 | 'Release-GeoInd: 30m', 195 | 'Release-GeoInd: 60m', 196 | 'Release-GeoInd: 90m', 197 | 'Random: 80%', 198 | 'Random: 60%', 199 | 'Random: 40%', 200 | 'Rounding: 4', 201 | 'Rounding: 3', 202 | 'Rounding: 2', 203 | 'Release: 30m', 204 | 'Release: 60m', 205 | 'Release: 90m'] 206 | 207 | 208 | cities = ['World'] 209 | 210 | for city in cities: 211 | place = city 212 | origpath = defenses_path + place+'/{}.avg.csv'.format(place) 213 | thispath = defenses_path 214 | print 'reading {}'.format(origpath) 215 | dorig = pd.read_csv(origpath,dtype={'mcc': int, 'mnc': int}) 216 | print dorig 217 | print defenses_path 218 | boxplots = [] 219 | names=[] 220 | for defidx, item in enumerate(defs): 221 | try: 222 | ddef = pd.read_csv(thispath + '/{}/{}.avg.csv'.format(item, item),dtype={'mcc': int, 'mnc': int}) 223 | print(ddef) 224 | 225 | except IOError as e: 226 | print e 227 | continue 228 | 229 | df = pd.merge(dorig, ddef, how='inner', on=['mcc', 'mnc', 'lac', 'Cellid']) 230 | tmp = [] 231 | for row in df.itertuples(): 232 | tmp.append(int(haversine((row[5], row[6]), (row[7], row[8])))) 233 | boxplots.append(tmp) 234 | names.append(new_name_defs[defidx]) 235 | ##### difference 236 | fig5 = plt.figure(1, figsize=(width, height)) 237 | # Create an axes instance 238 | ax5 = fig5.gca() 239 | 240 | # Create the boxplot 241 | bp = ax5.boxplot(boxplots, boxprops=boxprops,flierprops=flierprops, medianprops=medianprops, 242 | widths=0.35, patch_artist=False) 243 | ax5.set_xticklabels(names, rotation=rotation, ha='right', minor=False) 244 | ax5.spines["top"].set_visible(False) 245 | ax5.spines["bottom"].set_visible(False) 246 | ax5.spines["right"].set_visible(False) 247 | ax5.spines["left"].set_visible(False) 248 | plt.title('Utility loss in Radiocells dataset'.format(city)) 249 | plt.ylabel('Meters') 250 | plt.tight_layout() 251 | plt.savefig(utilities_plot + 'radiocells_utilityloss.png', dpi=360, transparent =False, frameon= False) 252 | #plt.show() 253 | plt.gcf().clear() 254 | fig5.gca().clear() 255 | -------------------------------------------------------------------------------- /preprocess_df.py: -------------------------------------------------------------------------------- 1 | import pandas as pd 2 | 3 | from __init__ import starttime, endtime,place 4 | 5 | pd.options.mode.chained_assignment = None # default='warn' 6 | 7 | #################################### 8 | # filters the dataset and applies the offset 9 | # required for most types of operations that involve time 10 | # 11 | # 12 | def preprocess(dfmain): 13 | 14 | #if 'World' not in place: 15 | dfmain['Captured Time'] = pd.to_datetime(dfmain['Captured Time'], format='%Y-%m-%d %H:%M:%S') 16 | df = dfmain[((pd.to_datetime(dfmain['Captured Time']) + ( 17 | pd.to_timedelta(dfmain['offset'] / 60, unit='h'))).dt.hour > starttime) & 18 | ((pd.to_datetime(dfmain['Captured Time']) + ( 19 | pd.to_timedelta(dfmain['offset'] / 60, unit='h'))).dt.hour < endtime) & 20 | ((pd.to_datetime(dfmain['Captured Time']) + ( 21 | pd.to_timedelta(dfmain['offset'] / 60, unit='h'))).dt.dayofweek < 5)] 22 | 23 | return df 24 | -------------------------------------------------------------------------------- /privacy_gain.py: -------------------------------------------------------------------------------- 1 | import os 2 | import re 3 | import threading 4 | import overpy 5 | import time 6 | import random 7 | import multiprocessing 8 | import cPickle as pickle 9 | 10 | from attackmodule import * 11 | from shapely.geometry import Point, Polygon, MultiPolygon 12 | from shapely.ops import cascaded_union 13 | from mpl_toolkits.basemap import pyproj as pyproj 14 | from preprocess_df import * 15 | from multiprocessing import Manager 16 | from multiprocessing import freeze_support 17 | #from multiprocessing import Manager, freeze_support 18 | from functools import partial 19 | from concurrent.futures import TimeoutError 20 | from pebble import ProcessPool, ProcessExpired 21 | from __init__ import (place, 22 | minpoints, maxdistance,maxpois,starttime,endtime,original_min_points, 23 | writeplace, defenses_path,DATA_BASE_WRITE_UTILITY, datapath_to_original_file, 24 | advanced_clustering, min_allowed_points, max_allowed_distance) 25 | 26 | 27 | def main_privacy_gain(arg): 28 | freeze_support() 29 | mylockcl = threading.RLock() 30 | mylockprint = threading.RLock() 31 | manager = Manager() 32 | api = overpy.Overpass() 33 | wgs84 = pyproj.Proj("+init=EPSG:4326") 34 | osm3857 = pyproj.Proj("+init=EPSG:3857") 35 | #dictd = manager.dict() 36 | dictd = {} 37 | 38 | def mainprivacyloss(initcalc): 39 | ensure_dir(DATA_BASE_WRITE_UTILITY) 40 | 41 | defs = ['geoind[1.6, 0.05]', 42 | 'geoind[1.6, 0.15]', 43 | 'geoind[1.6, 0.3]', 44 | 'remap[1.6, 0.05]', 45 | 'remap[1.6, 0.15]', 46 | 'remap[1.6, 0.3]', 47 | 'rnd_sample[40]', 48 | 'rnd_sample[60]', 49 | 'rnd_sample[80]', 50 | 'rounded[3]', 51 | 'rounded[2]', 52 | 'rounded[4]', 53 | 'geoind_traces[1.6, 0.05, 30.0]', 54 | 'geoind_traces[1.6, 0.05, 60.0]', 55 | 'geoind_traces[1.6, 0.05, 90.0]', 56 | 'spacex[30.0]', 57 | 'spacex[60.0]', 58 | 'spacex[90.0]'] 59 | 60 | 61 | ################# 62 | ## 63 | ## Calculate the original cluster polygons per user 64 | ## 65 | ## 66 | ####################### 67 | existinglist = existingfiles() 68 | existinglist = [i.split('tmp')[0] for i in existinglist] 69 | 70 | if initcalc == 1: ## Calculate the original privacy for every user 71 | dfmain = pd.read_csv(datapath_to_original_file) 72 | print('read original') 73 | savedict(dfmain, 'original', starttime, endtime, minpoints, maxdistance, maxpois, 0,[]) 74 | 75 | # Load users original privacy files 76 | if os.path.isfile(DATA_BASE_WRITE_UTILITY + 'original' + '.pickle'): 77 | with open(DATA_BASE_WRITE_UTILITY + 'original' + '.pickle', 'rb') as handle: 78 | original_users = pickle.load(handle) 79 | original_users = original_users.keys() 80 | else: 81 | print 'Could not load original privacy file' 82 | exit(-1) 83 | 84 | print "original users loaded" 85 | 86 | # For every defense file, calculate the privacy loss 87 | for root, dirs, files in os.walk(defenses_path): 88 | names = [] 89 | if 'bak' in os.path.basename(root):continue # check for old files 90 | 91 | if ("geoind" in os.path.basename(root)) and ('traces' not in os.path.basename(root)): 92 | params = [float(s) for s in re.findall(r'-?\d+\.?\d*', os.path.basename(root))] 93 | if "remapping" in os.path.basename(root): 94 | keyword = "remap"+str(params) 95 | else: 96 | keyword = "geoind"+str(params) 97 | 98 | elif "rounded" in os.path.basename(root): 99 | 100 | params = [int(s) for s in re.findall(r'-?\d+\.?\d*', os.path.basename(root))] 101 | keyword = "rounded"+str(params) 102 | 103 | elif "random" in os.path.basename(root): 104 | params = [int(s) for s in re.findall(r'-?\d+\.?\d*', os.path.basename(root))] 105 | keyword = "rnd_sample"+str(params) 106 | 107 | elif "spacex" in os.path.basename(root): 108 | params = [float(s) for s in re.findall(r'-?\d+\.?\d*', os.path.basename(root))] 109 | keyword = "spacex"+str(params) 110 | 111 | elif "traces" in os.path.basename(root): 112 | params = [float(s) for s in re.findall(r'-?\d+\.?\d*', os.path.basename(root))] 113 | keyword = "geoind_traces"+str(params) 114 | 115 | else: 116 | print "thats not a defense" 117 | continue 118 | 119 | for file in files: 120 | #avoid recalculating the original files 121 | if ("Tokyo" in file) or ("Fukushima" in file) or ("original" in file): # do not load the original files, only the defenses (which are named after the defense) 122 | print "Skipping", file, keyword 123 | continue 124 | 125 | # case where not rounded as we can create clusters 126 | if (".csv" in file) and ('avg' not in file ) and ('interpolated' not in file) \ 127 | and ('bak' not in file) and (keyword != 0) \ 128 | and (keyword not in existinglist) and (keyword in defs): 129 | print root 130 | print '-------------------',file 131 | print keyword 132 | 133 | dictd.clear() 134 | df = pd.read_csv(os.path.join(root, file)) #read the file 135 | if 'rounded' not in file: 136 | savedict(df, keyword, starttime, endtime, minpoints, maxdistance, maxpois, 0,original_users) 137 | elif ('rounded' in file) and ('4' in file): 138 | savedict(df, keyword, starttime, endtime, minpoints, maxdistance, maxpois, 0,original_users) 139 | else: 140 | keyword = "rounded_" + str(params[0]) + "_digits" 141 | savedict(df, keyword, starttime, endtime, minpoints, maxdistance, maxpois, 1,original_users) 142 | names.append(keyword+str(params)) 143 | else: 144 | print "Skipping", file, keyword 145 | return 0 146 | 147 | 148 | 149 | ############################# 150 | # function that manages the saving part of the privacy loss 151 | # decides on what to perform based on the keyword provided 152 | # 153 | 154 | def savedict(dfmain, keyword, starttime, endtime, minpoints, maxdistance, maxpois, rounded,original_users): 155 | 156 | df = preprocess(dfmain) # preprocess the file, depending on the preferences one has in the init file 157 | 158 | if 'original' in keyword: 159 | original_users = df['User ID'].unique().tolist() # get unique users who have clusters 160 | #print 'i am the original file' 161 | print original_users 162 | 163 | if not rounded : 164 | print('starting dict users for original') 165 | dictclusters(df, minpoints, maxdistance, maxpois, keyword, original_users) 166 | with open(DATA_BASE_WRITE_UTILITY + keyword + '.pickle', 'wb') as handle: 167 | #pickle.dump(dict(dictd), handle) 168 | pickle.dump(dictd, handle) 169 | else: 170 | print 'ok, going good' 171 | cluster_rounded(df, original_users, keyword) 172 | 173 | with open(DATA_BASE_WRITE_UTILITY + keyword + '.pickle', 'wb') as handle: 174 | #pickle.dump(dict(dictd), handle) 175 | pickle.dump(dictd, handle) 176 | 177 | return 178 | 179 | 180 | def dictclusters(df, minpoints, maxdistance, maxpois, keyword, original_users): 181 | dfgrouped = df.groupby(['User ID']) 182 | mylist = [] 183 | for name, group in dfgrouped: 184 | if name in original_users: 185 | mylist.append((name,group)) 186 | clusterfunc((name, group), minpoints, maxdistance, maxpois, keyword) 187 | 188 | #packedargs = partial(clusterfunc, minpoints=minpoints, 189 | # maxdistance = maxdistance, 190 | # maxpois=maxpois, 191 | # keyword = keyword) 192 | #callWorkers( packedargs, mylist ) 193 | #myQueue.empty() 194 | return 195 | 196 | def callWorkers( packedargs, mylist): 197 | 198 | num_fetch_threads = 3 199 | printmsg("Working on {} threads".format(num_fetch_threads)) 200 | pool = multiprocessing.Pool(processes=num_fetch_threads) 201 | result_list = pool.map(packedargs, mylist) 202 | pool.close() 203 | pool.join() 204 | #with ProcessPool(max_workers=1) as pool: 205 | # future = pool.map(packedargs, mylist, timeout=9000) 206 | # iterator = future.result() 207 | # print('when i reture') 208 | # while True: 209 | # try: 210 | # result = next(iterator) 211 | # except StopIteration: 212 | # break 213 | # except TimeoutError as error: 214 | # print("function took longer than %d seconds" % error.args[1]) 215 | # except ProcessExpired as error: 216 | # print("%s. Exit code: %d" % (error, error.exitcode)) 217 | # except Exception as error: 218 | # print("function raised %s" % error) 219 | # print(error.message) # Python's traceback of remote process 220 | 221 | printmsg( '######################################### Done ###########################################################') 222 | return 0 223 | 224 | def clusterfunc(item, minpoints, maxdistance, maxpois, keyword): 225 | name = item[0] 226 | group = item[1] 227 | printmsg( "{} on item {}".format(multiprocessing.current_process(), name)) 228 | num_clusters = 0 229 | num_of_tries = 0 230 | nodesnum= 0 231 | tmp_max_distance = maxdistance 232 | tmp_min_points = minpoints 233 | spotsorigwgs84 = [] 234 | tmptags = [] 235 | nodeids = [] 236 | 237 | lat = group.Latitude.values 238 | lon = group.Longitude.values 239 | datetimes = pd.to_datetime(group['Captured Time'].values) 240 | coords = np.array(list(zip(lat, lon))) # get a list with all coordinatess 241 | coords_with_date = np.array(list(zip(lat, lon, datetimes))) 242 | 243 | if len(coords) == 0: 244 | print "No coords found!" 245 | return 246 | 247 | if 'original' in keyword: 248 | clusters_with_date, num_clusters = attackscript(tmp_min_points, tmp_max_distance, maxpois, coords,coords_with_date) 249 | 250 | elif advanced_clustering: 251 | clusters_with_date, num_clusters = attackscript(tmp_min_points, tmp_max_distance, maxpois, coords,coords_with_date) 252 | else: 253 | clusters_with_date, num_clusters = attackscript(tmp_min_points, tmp_max_distance, maxpois, coords,coords_with_date) 254 | 255 | #if you fail to create clusters maybe just let it go 256 | if num_clusters == 0: 257 | printmsg('Cant make clusters for this user: {}'.format(name)) 258 | return 259 | 260 | for idx, cluster in enumerate(clusters_with_date): 261 | #parse coordinates 262 | fulldates = zip(*cluster)[2] 263 | dates = [j.date() for j in fulldates] 264 | distdates = len(set(dates)) 265 | diff = ((max(fulldates) - min(fulldates)).total_seconds())/60. 266 | if distdates == 1 and diff< 30: 267 | printmsg('''Cant create cluster for user {} as he has {} distdates with {} minutes'''.format(name, distdates, diff)) 268 | continue 269 | 270 | xorig = cluster[:, 0] 271 | yorig = cluster[:, 1] 272 | lonsorig, latsorig = pyproj.transform(wgs84, osm3857, yorig, xorig) 273 | xyorigwgs84 = zip(latsorig, lonsorig) 274 | pointsorigwgs84 = [Point(a, b) for a, b in xyorigwgs84] 275 | #draw a buffer around each point 276 | spotsorigwgs84.append([p.buffer(tmp_max_distance) for p in pointsorigwgs84]) 277 | # flat out spots 278 | if len(spotsorigwgs84) == 0: return 279 | listorigwgs84 = [] 280 | for i in spotsorigwgs84: 281 | for j in i: 282 | listorigwgs84.append(j) 283 | multiorigwgs84 = cascaded_union(listorigwgs84) 284 | multiorigwgs84 = multiorigwgs84.buffer(0) 285 | #print type(multiorigwgs84) 286 | 287 | if "MultiPolygon" not in str(type(multiorigwgs84)): 288 | # plot polygon 289 | extorig = multiorigwgs84.exterior.xy 290 | lons, lats = pyproj.transform(osm3857, wgs84, extorig[1], extorig[0]) 291 | # query osm 292 | c = zip(lats, lons) 293 | textquery = string_format(c) 294 | result= querypoly(textquery) 295 | try: 296 | if result != 0: 297 | for j in result.nodes: 298 | tmptags.append(j.tags) 299 | nodeids.append(result.node_ids) 300 | nodesnum = result.nodes.__len__() 301 | except ValueError: 302 | pass 303 | else: 304 | for i in multiorigwgs84: 305 | extorig = i.exterior.xy 306 | lons, lats = pyproj.transform(osm3857, wgs84, extorig[1], extorig[0]) 307 | # query osm 308 | c = zip(lats, lons) 309 | textquery = string_format(c) 310 | result = querypoly(textquery) 311 | try: 312 | if result !=0: 313 | for j in result.nodes: 314 | tmptags.append(j.tags) 315 | nodeids.append(result.node_ids) 316 | nodesnum += result.nodes.__len__() 317 | except ValueError: 318 | pass 319 | 320 | atomic_operation(multiorigwgs84, name, tmptags, nodesnum, nodeids) 321 | return 322 | 323 | def adaptive_clustering_params(keyword, iteration, minpoints, maxdistance): 324 | if 'geoind' in keyword or 'remap' in keyword: 325 | return minpoints, maxdistance+10 326 | elif 'rnd_sample' in keyword: 327 | return minpoints-10, maxdistance 328 | elif 'spacex' in keyword: 329 | if minpoints >= min_allowed_points:return minpoints-10, maxdistance 330 | elif maxdistance<=max_allowed_distance: return minpoints, maxdistance+10 331 | else: print "something wrong with spacex" 332 | elif 'rounded' in keyword: 333 | return minpoints-10, maxdistance 334 | else: 335 | print '''something wrong with keywords and min/max points/distace''' 336 | 337 | 338 | ############### 339 | # Function to query to osm server for information 340 | # returns information inside a provided polygon 341 | # 342 | def querypoly(textquery): 343 | tries = 1 344 | while tries < 15: 345 | try: 346 | result = api.query("""[timeout:1500][maxsize:2147483648];node(poly:"{}")["amenity" ~ ".+"];out skel;""".format(textquery)) 347 | return result 348 | except overpy.exception.OverPyException as e: 349 | printmsg("{} Caught exception when querying for poly. This was the {} try".format(multiprocessing.current_process(), tries)) 350 | print e 351 | if "Timeout" in e: 352 | tries += 2 353 | else: 354 | tries +=1 355 | 356 | slp = random.randint(tries*1, tries*2) 357 | printmsg("Sleeping for {} seconds".format(slp)) 358 | time.sleep(slp) 359 | return 0 360 | 361 | 362 | ################################### 363 | #Query the osm server for information withing a certain distance from a point 364 | # 365 | # 366 | # 367 | def queryaround(radius, lat, lon): 368 | tries=1 369 | while tries < 15: 370 | try: 371 | #printmsg("""Query looks like this,[timeout : 120];node(around:{},{},{})["amenity" ~ ".+"];out;""".format(radius, lat, lon) ) 372 | result = api.query("""[timeout:1500][maxsize:2147483648];node(around:{},{},{})["amenity" ~ ".+"];out skel;""".format(radius, lat, lon)) 373 | return result 374 | except overpy.exception.OverPyException as e: 375 | printmsg("{} Caught exception when querying for around. This was the {} try".format(multiprocessing.current_process(), tries)) 376 | print e 377 | if "Timeout" in e: 378 | tries += 2 379 | else: 380 | tries += 1 381 | 382 | slp = random.randint(tries*1, tries*2) 383 | printmsg("Sleeping for {} seconds".format(slp)) 384 | time.sleep(slp) 385 | return 0 386 | 387 | 388 | 389 | ############################ 390 | # 391 | # Convert the osm query to text 392 | # Its required for querying the server 393 | def string_format(l): 394 | string = "" 395 | cnt=1 396 | for i in l: 397 | if cnt ==1: 398 | string = string + "{} {}".format(repr(round(i[0], 4)),repr(round(i[1], 4))) 399 | else: 400 | string = string + " {} {}".format(repr(round(i[0], 4)), repr(round(i[1], 4))) 401 | cnt+=1 402 | return string 403 | 404 | def radiuspois(name, radius): 405 | tmptags = [] 406 | #print radius 407 | lat = float(name[0]) 408 | lon = float(name[1]) 409 | if str(lat)[::-1].find('.')>5 or str(lon)[::-1].find('.')>5: 410 | print (lat,lon) 411 | nodesnum=0 412 | nodeids = [] 413 | lonswgs84, latswgs84 = pyproj.transform(wgs84, osm3857, lon, lat) 414 | p = Point(latswgs84, lonswgs84) 415 | p = p.buffer(radius) 416 | poly = Polygon(p.exterior) 417 | 418 | result = queryaround(radius, lat, lon) 419 | if result != 0 and result.nodes!=[]: 420 | for j in result.nodes: 421 | tmptags.append(j.tags) 422 | nodeids.append(result.node_ids) 423 | nodesnum += result.nodes.__len__() 424 | atomic_operation(poly, str((lat,lon)), tmptags, nodesnum, nodeids) 425 | return 0 426 | 427 | def ensure_dir(file_path): 428 | directory = os.path.dirname(file_path) 429 | if not os.path.exists(directory): 430 | os.makedirs(directory) 431 | return 432 | 433 | def printmsg(text): 434 | with mylockprint: 435 | print text 436 | return 437 | 438 | def atomic_operation(multipolygon, name, tags, poislen,nodeids): 439 | dictd[name] = {"Polygon": multipolygon, "Nodes": tags, "Num_of_nodes": poislen, "Node_Ids": nodeids} 440 | #print dictd.keys() 441 | #print "returning" 442 | return dictd 443 | 444 | def existingfiles(): 445 | tmp = [] 446 | for root, dirs, files in os.walk(DATA_BASE_WRITE_UTILITY): 447 | for singlefile in files: 448 | main, ext = os.path.splitext(singlefile) 449 | 450 | tmp.append(main) 451 | print tmp 452 | return tmp 453 | 454 | def deletefiles(string, param): 455 | for root, dirs, files in os.walk(DATA_BASE_WRITE_UTILITY): 456 | for singlefile in files: 457 | main, ext = os.path.splitext(singlefile) 458 | if ((string in main) and (param in main)): 459 | print 'I will delete', singlefile 460 | os.remove(os.path.join(root,singlefile)) 461 | print 'done' 462 | 463 | return 0 464 | 465 | def cluster_rounded(df, original_users,keyword): 466 | rounddigits = 0 467 | 468 | if '3' in keyword: 469 | rounddigits = 3 470 | elif '2' in keyword: 471 | rounddigits = 2 472 | else: 473 | printmsg("wrong radius from keyword, exiting") 474 | exit(-1) 475 | dfgrouped = df.groupby(['User ID']) 476 | mylist = [] 477 | for name, group in dfgrouped: 478 | tmptags = [] 479 | nodeids = [] 480 | this_user_multipolygon = [] 481 | this_user_multipolygon_3857 = [] 482 | coords = [] 483 | nodesnum = 0 484 | 485 | print name 486 | group = group.groupby(['Latitude', 'Longitude']).size().reindex().sort_values().tail(maxpois) 487 | 488 | for i in group.iteritems(): 489 | tmp_points = return_square_verticres((i[0][0], i[0][1]), rounddigits ) 490 | this_user_multipolygon.append(Polygon(tmp_points)) 491 | xorig = [] 492 | yorig = [] 493 | 494 | for point in tmp_points: 495 | xorig.append(point[0]) 496 | yorig.append(point[1]) 497 | 498 | lonsorig, latsorig = pyproj.transform(wgs84, osm3857, yorig, xorig) 499 | coords_3857 = zip(latsorig, lonsorig) 500 | this_user_multipolygon_3857.append(Polygon(coords_3857)) 501 | 502 | this_user_multipolygon_wgs84 = MultiPolygon(this_user_multipolygon) 503 | this_user_multipolygon_wgs84 = this_user_multipolygon_wgs84.buffer(0) 504 | 505 | this_user_multipolygon_3857 = MultiPolygon(this_user_multipolygon_3857) 506 | this_user_multipolygon_3857 = this_user_multipolygon_3857.buffer(0) 507 | 508 | if "MultiPolygon" not in str(type(this_user_multipolygon_wgs84)): 509 | # plot polygon 510 | extorig = this_user_multipolygon_wgs84.exterior.xy 511 | lats = extorig[0] 512 | lons = extorig[1] 513 | # query osm 514 | c = zip(lats, lons) 515 | textquery = string_format(c) 516 | result = querypoly(textquery) 517 | try: 518 | if result != 0: 519 | for j in result.nodes: 520 | tmptags.append(j.tags) 521 | nodeids.append(result.node_ids) 522 | nodesnum = result.nodes.__len__() 523 | except ValueError: 524 | pass 525 | else: 526 | for i in this_user_multipolygon_wgs84: 527 | extorig = i.exterior.xy 528 | lats = extorig[0] 529 | lons = extorig[1] 530 | 531 | c = zip(lats, lons) 532 | textquery = string_format(c) 533 | result = querypoly(textquery) 534 | print textquery 535 | print '\n' 536 | try: 537 | if result != 0: 538 | for j in result.nodes: 539 | tmptags.append(j.tags) 540 | nodeids.append(result.node_ids) 541 | nodesnum += result.nodes.__len__() 542 | except ValueError: 543 | pass 544 | atomic_operation(this_user_multipolygon_3857, name, tmptags, nodesnum, nodeids) 545 | 546 | def return_square_verticres(center, round_digits): 547 | if round_digits == 2: 548 | half_side = 0.005 549 | elif round_digits == 3: 550 | half_side =0.0005 551 | else: 552 | print 'wrong digits' 553 | exit() 554 | x = center[1] 555 | y = center[0] 556 | p2 = (y-half_side,x+half_side) 557 | p3 = (y+half_side, x+half_side) 558 | p1 = (y-half_side, x-half_side) 559 | p4 = ( y+half_side, x-half_side) 560 | #print p1,p2,p3,p4 561 | return p1,p2,p3,p4 562 | 563 | mainprivacyloss(arg) 564 | 565 | 566 | if __name__ == "__main__": 567 | pass -------------------------------------------------------------------------------- /region_extraction_functions.py: -------------------------------------------------------------------------------- 1 | import os 2 | import numpy as np 3 | import pandas as pd 4 | import multiprocessing 5 | 6 | from functools import partial 7 | from shapely.geometry import Point 8 | 9 | pd.options.mode.chained_assignment = None # default='warn' 10 | 11 | 12 | ################################################ 13 | ## 14 | ## Functions to pre process the large csv 15 | ## limit the coordinates 16 | ## 17 | ## 18 | ################################################ 19 | def extract_region(OriginCsv, DATA_PATH, DESTINATION_DEFENSES, polygon, place): 20 | print "Removing previous file" 21 | if os.path.isfile(DESTINATION_DEFENSES): 22 | os.remove(DESTINATION_DEFENSES) 23 | 24 | if os.path.isfile(DATA_PATH + "wholeArea.csv"): 25 | os.remove(DATA_PATH + "wholeArea.csv") 26 | 27 | tmp = [] 28 | cnt = 0 29 | # read the file in chunks 30 | # otherwise it may fill the whole ram 31 | for chunk in pd.read_csv(OriginCsv, iterator = True, chunksize=1000000): 32 | #if cnt % 5 == 0: 33 | #print cnt,'out of ', 64000000/1000000 34 | tmp.append(applypolygon(chunk,polygon,place)) 35 | cnt += 1 36 | df = pd.concat(tmp,ignore_index= True) 37 | print 'Read original csv' 38 | df = funcusers(df, DATA_PATH, polygon,place) 39 | df.to_csv(DESTINATION_DEFENSES, index=False) 40 | return 0 41 | 42 | 43 | def funcusers(df, DATA_PATH, polygon,place): 44 | # first create the file with the whole place area 45 | print 'will now try to parallelize' 46 | dfwholeplace = parallelize_dataframe(df, applypolygon, polygon, place) 47 | if not os.path.isfile(DATA_PATH + "wholeArea.csv"): 48 | dfwholeplace.to_csv(DATA_PATH + "wholeArea.csv", header='column_names', index=False) 49 | else: # else it exists so append without writing the header 50 | dfwholeplace.to_csv(DATA_PATH + "wholeArea.csv", mode='a', header=False, index=False) 51 | return dfwholeplace 52 | 53 | 54 | ################################### 55 | # When dataframes a too large 56 | # we can parallelize 57 | # 58 | ################################## 59 | def parallelize_dataframe(df, func, poly,place): 60 | 61 | df_split = np.array_split(df, multiprocessing.cpu_count()-1) 62 | print 'Original file split' 63 | pool = multiprocessing.Pool(multiprocessing.cpu_count()-1) 64 | print "im working on {} cores".format(multiprocessing.cpu_count()-1) 65 | applypolygon_partial = partial(func, polygon=poly, place=place) 66 | #print "partial was successful" 67 | tmp = [] 68 | tmp.append(pool.map(applypolygon_partial, df_split)) 69 | df = pd.concat(tmp[0], ignore_index=True) 70 | pool.close() 71 | pool.join() 72 | return df 73 | 74 | 75 | ############################################# 76 | # Return only coordinates within a polygon 77 | # If World is selected, return all 78 | # 79 | # 80 | ############################################# 81 | def applypolygon(dfmini,polygon, place): 82 | #print "here!!" 83 | dfmini = dfmini.dropna(axis=0, subset=['offset']) 84 | if 'World' not in place: 85 | dfmini = dfmini[dfmini.apply(lambda row: Point(row['Latitude'], row['Longitude']).within(polygon), axis=1)] 86 | return dfmini 87 | 88 | 89 | ######################################### 90 | # Computs the prior probability of a file 91 | # 92 | ######################################## 93 | def compute_prior(SOURCE_DATA, PRIORS_PATH): 94 | #We will calculate the probability of a user being at a 95 | #certain location 96 | df = pd.read_csv(SOURCE_DATA, error_bad_lines = False) 97 | df['Latitude'] = df['Latitude'].apply(lambda x: round(x, 3)) 98 | df['Longitude'] = df['Longitude'].apply(lambda x: round(x, 3)) 99 | dfprob = df.groupby(['Latitude', 'Longitude']).size().reset_index().rename(columns={0: 'PriorX'}) 100 | dfprob['PriorX'] = dfprob['PriorX'] / dfprob['PriorX'].sum() 101 | dfprob = dfprob.drop_duplicates() 102 | dfprob.to_csv(PRIORS_PATH, index=False) 103 | -------------------------------------------------------------------------------- /reqs.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/spring-epfl/MCSAuditing/daafc3fbd0c2c62fec9620cf2518e0e8a5efdac0/reqs.txt -------------------------------------------------------------------------------- /safecast_extra_functions.py: -------------------------------------------------------------------------------- 1 | import time 2 | import os 3 | import numpy as np 4 | import pandas as pd 5 | import csv 6 | 7 | from scipy.interpolate import griddata 8 | from shapely.geometry import Point 9 | from shapely.ops import cascaded_union 10 | from functools import partial 11 | import multiprocessing 12 | pd.options.mode.chained_assignment = None # default='warn' 13 | 14 | 15 | # Calculate average for same x/y coordiantes 16 | def calc_avg(inputname, output): 17 | df = pd.read_csv(inputname) 18 | df['Latitude'] = df['Latitude'].apply(lambda x: round(x, 6)) 19 | df['Longitude'] = df['Longitude'].apply(lambda x: round(x, 6)) 20 | ss = df[['Latitude', 'Longitude', 'Value']].groupby(by=['Latitude', 'Longitude']).agg(['mean','count']).reset_index() 21 | ss.columns = ['lat_avg','lon_avg','cpm_avg','n'] 22 | ss.to_csv(output, index=False) 23 | return 0 24 | 25 | 26 | def LoadSafecastData(filename, CPMclip, latmin, latmax, lonmin, lonmax): 27 | # Load data 28 | 29 | data = csv.reader(open(filename)) 30 | # Read the column names from the first line of the file 31 | fields = data.next() 32 | x = [] 33 | y = [] 34 | z = [] 35 | zraw = [] 36 | # Process data 37 | for row in data: 38 | # Zip together the field names and values 39 | items = zip(fields, row) 40 | # Add the value to our dictionary 41 | item = {} 42 | for (name, value) in items: 43 | item[name] = value.strip() 44 | 45 | # Ignore if outside limits 46 | if not ((float(item["lat_avg"])>latmin) and (float(item["lat_avg"])lonmin) and (float(item["lon_avg"])CPMclip: cpm=CPMclip # clip 53 | 54 | x.append(float(item["lon_avg"])) 55 | y.append(float(item["lat_avg"])) 56 | z.append(float(cpm)) 57 | 58 | npts = len(x) 59 | print "%s measurements loaded." % npts 60 | 61 | x = np.array(x) 62 | y = np.array(y) 63 | z = np.array(z) 64 | zraw = np.array(zraw) 65 | 66 | return npts, x, y, z, zraw 67 | 68 | 69 | def PreCompute(safecastDataset, output, output_csv,original, safecastDatasetCPMThreashold=20000, safecastGridsize=1500): 70 | # Setup: loading data... 71 | #print safecastDataset 72 | 73 | nx, ny = safecastGridsize, safecastGridsize # grid size 74 | 75 | 76 | original_df = pd.read_csv(original) 77 | 78 | latmin = original_df['lat_avg'].min() 79 | latmax = original_df['lat_avg'].max() 80 | lonmin = original_df['lon_avg'].min() 81 | lonmax = original_df['lon_avg'].max() 82 | print safecastDataset 83 | print latmin, latmax, lonmin, lonmax 84 | 85 | 86 | 87 | 88 | npts, x, y, z, zraw = LoadSafecastData(safecastDataset, safecastDatasetCPMThreashold, latmin, latmax, lonmin, lonmax) 89 | 90 | # Compute area with missing data 91 | print "Compute area with missing data" 92 | start = time.time() 93 | measures = np.vstack((x,y)).T 94 | print "Time to vpstack: ", time.time() - start 95 | #start = time.time() 96 | #points = [Point(a,b) for a, b in measures] 97 | #print "Time to points: ", time.time() - start 98 | #start = time.time() 99 | #spots = [p.buffer(0.04) for p in points] # 0.04 degree ~ 1km radius 100 | #print "Time to spots: ", time.time() - start 101 | #start = time.time() 102 | ## Perform a cascaded union of the polygon spots, dissolving them into a 103 | ## collection of polygon patches 104 | # 105 | #missing = cascaded_union(spots) 106 | #print "Time to cascade union: ", time.time() - start 107 | 108 | # Create the grid 109 | print "Create the grid" 110 | #xil = np.linspace(x.min(), x.max(), nx) 111 | #yil = np.linspace(y.min(), y.max(), ny) 112 | 113 | xil = np.linspace(lonmin, lonmax, nx) 114 | yil = np.linspace(latmin, latmax, ny) 115 | xi, yi = np.meshgrid(xil, yil) 116 | 117 | ## Attention, even though it says nearest, we calculate the linear as its waaay faster 118 | 119 | # Calculate the griddata 120 | print "Calculate the griddata (%d x %d)" % (nx, ny) 121 | t1 = time.clock() 122 | try: 123 | zi = griddata(measures, z, (xi, yi), method='nearest') # Original: interp='nn' 124 | except RuntimeError as e: 125 | print e 126 | print "x: " + str(x) + "y: " + str(y) + "z: " + str(z) 127 | 128 | grid = zi.reshape((ny, nx)) 129 | print "Interpolation done in",time.clock()-t1,'seconds.' 130 | 131 | #toSave = [npts, x, y, z, zraw, xil, yil, grid, missing] 132 | #cPickle.dump(toSave,open(output,'wb'),-1) 133 | #print "Griddata saved (" + output + ")." 134 | #print "Also save grid as csv for utility calculation" 135 | out = csv.writer(open(output_csv, 'wb')) 136 | out.writerows(grid) 137 | print "Griddata saved as csv (" + output_csv + ")." 138 | 139 | return 0 140 | 141 | -------------------------------------------------------------------------------- /source_data/radiocells_template.csv: -------------------------------------------------------------------------------- 1 | Captured Time,Cellid,offset,Latitude,Longitude,act,exportver,hdg,lac,manufacturer,mcc,mnc,model,revision,spe,ss,rxlev,swid,swver,User ID 2 | -------------------------------------------------------------------------------- /source_data/safecast_template_for_defenses.csv: -------------------------------------------------------------------------------- 1 | ID,User ID,Captured Time,Latitude,Longitude,Value,Unit,Device ID,offset 2 | -------------------------------------------------------------------------------- /source_data/safecst_template_data_for_priors.csv: -------------------------------------------------------------------------------- 1 | ID,User ID,Captured Time,Latitude,Longitude,Value,Unit,Device ID,offset 2 | -------------------------------------------------------------------------------- /utility_functions.py: -------------------------------------------------------------------------------- 1 | import time 2 | import os 3 | import numpy as np 4 | import pandas as pd 5 | import csv 6 | import matplotlib.pyplot as plt 7 | 8 | from scipy.interpolate import griddata 9 | from shapely.geometry import Point 10 | from shapely.ops import cascaded_union 11 | from functools import partial 12 | import multiprocessing 13 | pd.options.mode.chained_assignment = None # default='warn' 14 | 15 | 16 | # Calculate average for same x/y coordiantes 17 | def calc_avg(inputname, output): 18 | df = pd.read_csv(inputname) 19 | df['Latitude'] = df['Latitude'].apply(lambda x: round(x, 6)) 20 | df['Longitude'] = df['Longitude'].apply(lambda x: round(x, 6)) 21 | ss = df[['Latitude', 'Longitude', 'Value']].groupby(by=['Latitude', 'Longitude']).agg(['mean','count']).reset_index() 22 | ss.columns = ['lat_avg','lon_avg','cpm_avg','n'] 23 | ss.to_csv(output, index=False) 24 | return 0 25 | 26 | 27 | def LoadSafecastData(filename, CPMclip, latmin, latmax, lonmin, lonmax): 28 | # Load data 29 | 30 | data = csv.reader(open(filename)) 31 | # Read the column names from the first line of the file 32 | fields = data.next() 33 | x = [] 34 | y = [] 35 | z = [] 36 | zraw = [] 37 | # Process data 38 | for row in data: 39 | # Zip together the field names and values 40 | items = zip(fields, row) 41 | # Add the value to our dictionary 42 | item = {} 43 | for (name, value) in items: 44 | item[name] = value.strip() 45 | 46 | # Ignore if outside limits 47 | if not ((float(item["lat_avg"])>latmin) and (float(item["lat_avg"])lonmin) and (float(item["lon_avg"])CPMclip: cpm=CPMclip # clip 54 | 55 | x.append(float(item["lon_avg"])) 56 | y.append(float(item["lat_avg"])) 57 | z.append(float(cpm)) 58 | 59 | npts = len(x) 60 | print "%s measurements loaded." % npts 61 | 62 | x = np.array(x) 63 | y = np.array(y) 64 | z = np.array(z) 65 | zraw = np.array(zraw) 66 | 67 | return npts, x, y, z, zraw 68 | 69 | 70 | def PreCompute(safecastDataset, output, output_csv,original, safecastDatasetCPMThreashold=20000, safecastGridsize=1500): 71 | # Setup: loading data... 72 | #print safecastDataset 73 | 74 | nx, ny = safecastGridsize, safecastGridsize # grid size 75 | 76 | 77 | original_df = pd.read_csv(original) 78 | 79 | latmin = original_df['lat_avg'].min() 80 | latmax = original_df['lat_avg'].max() 81 | lonmin = original_df['lon_avg'].min() 82 | lonmax = original_df['lon_avg'].max() 83 | print safecastDataset 84 | print latmin, latmax, lonmin, lonmax 85 | 86 | 87 | 88 | 89 | npts, x, y, z, zraw = LoadSafecastData(safecastDataset, safecastDatasetCPMThreashold, latmin, latmax, lonmin, lonmax) 90 | 91 | # Compute area with missing data 92 | print "Compute area with missing data" 93 | start = time.time() 94 | measures = np.vstack((x,y)).T 95 | print "Time to vpstack: ", time.time() - start 96 | #start = time.time() 97 | #points = [Point(a,b) for a, b in measures] 98 | #print "Time to points: ", time.time() - start 99 | #start = time.time() 100 | #spots = [p.buffer(0.04) for p in points] # 0.04 degree ~ 1km radius 101 | #print "Time to spots: ", time.time() - start 102 | #start = time.time() 103 | ## Perform a cascaded union of the polygon spots, dissolving them into a 104 | ## collection of polygon patches 105 | # 106 | #missing = cascaded_union(spots) 107 | #print "Time to cascade union: ", time.time() - start 108 | 109 | # Create the grid 110 | print "Create the grid" 111 | #xil = np.linspace(x.min(), x.max(), nx) 112 | #yil = np.linspace(y.min(), y.max(), ny) 113 | 114 | xil = np.linspace(lonmin, lonmax, nx) 115 | yil = np.linspace(latmin, latmax, ny) 116 | xi, yi = np.meshgrid(xil, yil) 117 | 118 | ## Attention, even though it says nearest, we calculate the linear as its waaay faster 119 | 120 | # Calculate the griddata 121 | print "Calculate the griddata (%d x %d)" % (nx, ny) 122 | t1 = time.clock() 123 | try: 124 | zi = griddata(measures, z, (xi, yi), method='nearest') # Original: interp='nn' 125 | except RuntimeError as e: 126 | print e 127 | print "x: " + str(x) + "y: " + str(y) + "z: " + str(z) 128 | 129 | grid = zi.reshape((ny, nx)) 130 | print "Interpolation done in",time.clock()-t1,'seconds.' 131 | 132 | #toSave = [npts, x, y, z, zraw, xil, yil, grid, missing] 133 | #cPickle.dump(toSave,open(output,'wb'),-1) 134 | #print "Griddata saved (" + output + ")." 135 | #print "Also save grid as csv for utility calculation" 136 | out = csv.writer(open(output_csv, 'wb')) 137 | out.writerows(grid) 138 | print "Griddata saved as csv (" + output_csv + ")." 139 | 140 | return 0 141 | 142 | 143 | def radiocells_find_antenna(path, utility_path): 144 | 145 | df = pd.read_csv(path, dtype = {'mcc': str, 'mnc': str}) 146 | dutility = df.groupby(['mcc', 'mnc', 'lac', 'Cellid'])['Latitude', 'Longitude'].mean().reset_index() 147 | dutility.to_csv(utility_path, index=False) 148 | return 149 | 150 | 151 | 152 | 153 | --------------------------------------------------------------------------------