├── .gitignore ├── LICENSE ├── README.md ├── calculateDistance.py ├── calculateDistanceInt.py ├── input.txt ├── mutual_info.py ├── recursiveHierarchicalClustering.py ├── recursiveHierarchicalClusteringFast.py ├── servers.json ├── vis ├── .DS_Store ├── css │ ├── bootstrap.min.css │ └── whisper.css ├── fonts │ ├── glyphicons-halflings-regular.eot │ ├── glyphicons-halflings-regular.svg │ ├── glyphicons-halflings-regular.ttf │ ├── glyphicons-halflings-regular.woff │ └── glyphicons-halflings-regular.woff2 ├── js │ ├── bootstrap.min.js │ └── whisper.js └── multi_color.html └── visulization.py /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | env/ 12 | build/ 13 | develop-eggs/ 14 | dist/ 15 | downloads/ 16 | eggs/ 17 | .eggs/ 18 | lib/ 19 | lib64/ 20 | parts/ 21 | sdist/ 22 | var/ 23 | *.egg-info/ 24 | .installed.cfg 25 | *.egg 26 | 27 | # PyInstaller 28 | # Usually these files are written by a python script from a template 29 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 30 | *.manifest 31 | *.spec 32 | 33 | # Installer logs 34 | pip-log.txt 35 | pip-delete-this-directory.txt 36 | 37 | # Unit test / coverage reports 38 | htmlcov/ 39 | .tox/ 40 | .coverage 41 | .coverage.* 42 | .cache 43 | nosetests.xml 44 | coverage.xml 45 | *,cover 46 | .hypothesis/ 47 | 48 | # Translations 49 | *.mo 50 | *.pot 51 | 52 | # Django stuff: 53 | *.log 54 | local_settings.py 55 | 56 | # Flask stuff: 57 | instance/ 58 | .webassets-cache 59 | 60 | # Scrapy stuff: 61 | .scrapy 62 | 63 | # Sphinx documentation 64 | docs/_build/ 65 | 66 | # PyBuilder 67 | target/ 68 | 69 | # IPython Notebook 70 | .ipynb_checkpoints 71 | 72 | # pyenv 73 | .python-version 74 | 75 | # celery beat schedule file 76 | celerybeat-schedule 77 | 78 | # dotenv 79 | .env 80 | 81 | # virtualenv 82 | venv/ 83 | ENV/ 84 | 85 | # Spyder project settings 86 | .spyderproject 87 | 88 | # Rope project settings 89 | .ropeproject 90 | 91 | .DS_Store -------------------------------------------------------------------------------- /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 | {one line to give the program's name and a brief idea of what it does.} 635 | Copyright (C) {year} {name of author} 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 | {project} Copyright (C) {year} {fullname} 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 | # Recursive Hierarchical Clustering 2 | In this project, we build an unsupervised system to capture dominating user behaviors from clickstream data (traces of users’ click events), and visualize the detected behaviors in an intuitive manner. 3 | 4 | Our system identifies "clusters" of similar users by partitioning a similarity graph (nodes are users; edges are weighted by clickstream similarity). 5 | 6 | The partitioning process leverages **iterative feature pruning** to capture the natural hierarchy within user clusters and produce intuitive features for visualizing and understanding captured user behaviors. 7 | 8 | This script is used to perform user behavior clustering. Users are put into a hierarchy of clusters, each identified by a list of behavior patterns. 9 | 10 | --- 11 | 12 | ## Dependency 13 | Python library `numpy`, `scipy` is required. 14 | 15 | ## Usage 16 | The main file of this script is `recursiveHierarchicalClustering.py`. 17 | There are two ways of executing the script, through the command line interface or through python import. 18 | 19 | ### Command Line Interface 20 | 21 | ``` 22 | $> python recursiveHierarchicalClustering.py input.txt output/ 0.05 23 | ``` 24 | 25 | #### Arguments 26 | **inputPath**: specify the path to a files that contains information for the users to be clustered. Each line is represent a user. 27 | > user_id \t A(1)G(10) 28 | 29 | Where the `A` and `G` are actions and `1` and `10` are the frequencies of each action. The `user_id` grows from 1 to the total number of users. 30 | 31 | **outputPath**: The directory to place all temporary files as well as the final result. 32 | 33 | **sizeThreshold** (optional): Defines the minimum size of the cluster, that we are going to further divide. 34 | `0.05` means clusters containing less than 5% of the total instances is not going to be further splitted. 35 | 36 | 37 | ### Python Interface 38 | ```python 39 | import recursiveHierarchicalClustering as rhc 40 | data = rhc.getSidNgramMap(inputPath) 41 | matrixPath = '%smatrix.dat' % inputPath 42 | treeData = rhc.runDiana(outputPath, data, matrixPath) 43 | ``` 44 | 45 | Here treeData is the resulting cluster tree. Same as `output/result.json` if ran through CLI. 46 | 47 | ## Result 48 | **output/matrix.dat**: A distance matrix for the root level is stored to avoid repeated calculation. If the file is available, the scirpt will read in the matrix instead of calculating it again. The file format is a N*N distance matrix scaled to integer in the range of (0-100). 49 | 50 | **output/result.json**: Stores the clustering result, in the form of `['t', sub-cluster list, cluster info]` or `['l', user list, cluster info]`. 51 | 52 | * **Node type**: node type can be either `t` or `l`. `l` means leaf which means the cluster is not further split. `t` means tree meaning there are further splitting for the given cluster. 53 | * **Sub-cluster list**: a list of clusters that is the resulting clusters derived from splitting the current cluster. 54 | * **User list**: a list of user ids representing the users in the given cluster. 55 | * **Cluster info**: a dictionary containing meta data for the cluster. 56 | * **gini**: gini-coefficient for chi-square score value distribution, measures the skewness of feature importance distribution. 57 | * **sweetspot**: the modularity for the best `k` we picked when further splitting this cluster. 58 | * **exlusions**: a list of top features (ranked) that helps to distinguish the cluster from others. 59 | * **exclusionsScore**: the chi-square scores correspond to the top features listed in **exclusions**. 60 | 61 | ## Configuration 62 | This script is designed to be distributed on multiple machines with shared file system. However, it is also be configured to run locally. 63 | The configuration is stored in `server.json` in the following format: 64 | ```javascript 65 | { 66 | "threadNum": 5, 67 | "minPerSlice": 1000, 68 | "server": 69 | ["server1.example.com", "server2.example.com"] 70 | } 71 | ``` 72 | 73 | * **threadNum** specifies how many threads can be ran on each server. 74 | * **minPerSlice** specifies the minimum number of users each thread should handle. 75 | * **server** specifies the server to be used for matrix computation task. If you want to run it locally, specify it as `["localhost"]`. 76 | 77 | --- 78 | ## Visulization 79 | Along with the clustering, we also developed a visulization tool based on [D3.js](https://d3js.org/) in 80 | order to inspect the content of the resulting clusters. 81 | 82 | ### Generating data file 83 | To generate a json file readable by `D3.js`, you can run the following bash command: 84 | 85 | ``` 86 | $> python visulization.py output/result.json input.txt vis/vis.json 87 | ``` 88 | 89 | #### Arguments 90 | **result.json** is the output file of the recursive hierarchical clustering. 91 | 92 | **intput.txt** is the path to a files that contains information for the users to be clustered. Each line is represent a user. 93 | 94 | **vis.json** is the path to the final output. 95 | 96 | ### Running webserver 97 | To properly display the visulization, you need to set up a web server under folder `vis`: 98 | ``` 99 | $> python -m http.server 100 | ``` 101 | 102 | And then by visiting `http://localhost:8000/multi_color.html?json=vis.json` you will be able to look at the visulization for `vis.json`. 103 | 104 | --- 105 | ## Optimization 106 | A faster version is also available making better use of `numpy`'s support for 107 | matrix computation. 108 | 109 | This requires additional package of `sklearn`. 110 | 111 | 112 | ## Usage 113 | The main file of the faster implementation is `recursiveHierarchicalClusteringFast.py`. 114 | There are two ways of executing the script, through the command line interface or through python import. 115 | 116 | ### Command Line Interface 117 | 118 | ``` 119 | $> python recursiveHierarchicalClusteringFast.py input.txt output/ 0.05 120 | ``` 121 | 122 | ### Python Interface 123 | ```python 124 | import recursiveHierarchicalClustering as rhc 125 | import recursiveHierarchicalClusteringFast as rhcFast 126 | data = rhc.getSidNgramMap(inputPath) 127 | treeData = rhcFast.run(inputPath, data, outPath) 128 | ``` 129 | 130 | Here treeData is the resulting cluster tree. Same as `output/result.json` if ran through CLI. 131 | 132 | ### Frequently Asked Questions 133 | 1. In the paper, the sequences are modeled with timegap, e.g., `A(g1)B(g2)C(g1)A(g1)B`. Why is there no timegap information in the code sample but are `A`, `B` and `C` instead? 134 | 135 | **Answer:** 136 | 137 | The code in here is meant to be general-purpose, which allows for arbitrary features beyond action-gap-action. This means, `A` itself is a token for an action-gap-action tuple. For example, an input file representing clickstream features may look like this: 138 | ``` 139 | 1 A1A(7)A2C(6)B1A1B(5) 140 | 2 A1A(9)B1C(11)B1A1C(12)A2E(11) 141 | ... 142 | ``` 143 | Here, numbers represent bucktized timegap, whereas alphabetic characters represent actions. 144 | 145 | You can checkout [this issue](https://github.com/xychang/RecursiveHierarchicalClustering/issues/2) for more details in terms of visulization. 146 | 147 | 148 | --- 149 | ## Publication 150 | Gang Wang, Xinyi Zhang, Shiliang Tang, Haitao Zheng, Ben Y. Zhao. 151 | [Unsupervised Clickstream Clustering for User Behavior Analysis](http://www.cs.ucsb.edu/~ravenben/publications/pdf/clickstream-chi16.pdf). 152 | Proceedings of SIGCHI Conference on Human Factors in Computing Systems (CHI), San Jose, CA, May 2016. 153 | -------------------------------------------------------------------------------- /calculateDistance.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | """ 3 | This is used to compute distance matrix 4 | """ 5 | import multiprocessing 6 | import json 7 | import sys 8 | import math 9 | import subprocess 10 | import os 11 | import glob 12 | import pickle 13 | import time 14 | from array import * 15 | import datetime 16 | 17 | config = json.load(open('servers.json')) 18 | # thread number 19 | THREAD_NUM = config['threadNum'] 20 | 21 | # the minimum slice size 22 | MIN_SLICE = config['minPerSlice'] 23 | 24 | # the minimum size per server 25 | MIN_SERVER = THREAD_NUM * MIN_SLICE 26 | 27 | PI_VALUE = 3.141592653589793 28 | 29 | 30 | class myThread (multiprocessing.Process): 31 | 32 | def getSeqDist(self, dic1, dic2): 33 | """ 34 | Convert distance into the range of 0 - 100 35 | :type dic1: Dict{str: float} 36 | :type dic2: Dict{str: float} 37 | """ 38 | dist = 0 39 | 40 | gramset = list(set(dic1.keys()) | set(dic2.keys())) 41 | vlist1 = [dic1[g] if g in dic1 else 0 for g in gramset] 42 | vlist2 = [dic2[g] if g in dic2 else 0 for g in gramset] 43 | 44 | dist = 1.0001 - angle(vlist1, vlist2)/(PI_VALUE/2) 45 | 46 | if dist <= 0: 47 | dist = 0.00000001 48 | dist = float(dist)*100 49 | weight = int(dist)+1 50 | if weight > 100: 51 | weight = 100 52 | return 100 - weight 53 | 54 | def __init__(self, threadID, prefix, sid_seq, sfrom, sto, idfMap): 55 | self.threadID = threadID 56 | self.sid_seq = sid_seq 57 | self.sfrom = sfrom 58 | self.sto = sto 59 | self.idfMap = idfMap 60 | self.fo = open(prefix+'_'+str(sfrom[0]), 'w') 61 | multiprocessing.Process.__init__(self) 62 | 63 | def run(self): 64 | print('[LOG]: start new thread '+str(self.threadID)) 65 | for sidFrom in self.sfrom: 66 | dic1 = self.sid_seq[sidFrom] 67 | dists = [] 68 | for sidTo in self.sto: 69 | if sidFrom == sidTo: 70 | dists.append(0) 71 | continue 72 | dic2 = self.sid_seq[sidTo] 73 | 74 | dists.append(self.getSeqDist(dic1, dic2)) 75 | self.fo.write('\t'.join(map(str, dists)) + '\n') 76 | self.fo.close() 77 | 78 | 79 | def angle(v1, v2): 80 | """ 81 | Compute the polar distance between two vectors 82 | :type v1: List[float] 83 | :type v2: List[float] 84 | """ 85 | norm1 = 0 86 | norm2 = 0 87 | dotprod = 0 88 | for i in range(0, len(v1)): 89 | dotprod += v1[i]*v2[i] 90 | a = dotprod 91 | if a > 1: 92 | a = 1 93 | return math.acos(a) 94 | 95 | 96 | def calDist(inputPath, sidsPath, outputPath, tmpPrefix='', idfMapPath=None): 97 | """ 98 | :type intputPath: str 99 | - the path to the computed pattern dataset 100 | :type sidsPath: str 101 | - the path to two lists of sids that we need to calculate one as 102 | from and one as to 103 | :type outputPath: str 104 | - a path to specify where the final result is placed 105 | :type tmpPrefix: str (default: '') 106 | - a predix used so that temporary files have no conflict 107 | :type idfMapPath: str (default: None) 108 | - if the idf for each pattern is already computed, provide a path 109 | to avoid repeated computation 110 | """ 111 | print(('[LOG]: %s computing matrix for %s' % (datetime.datetime.now(), 112 | sidsPath.split('sid_')[0]))) 113 | # read the ngram file, generate a node list 114 | lineNum = 1 115 | sids = pickle.load(open(sidsPath,'rb')) 116 | 117 | fromSids = set(sids[0]) 118 | # in principle the toSids should be all sids 119 | toSids = set(sids[1]) 120 | 121 | startTime = time.time() 122 | 123 | # get the idfMap, if provided 124 | if (idfMapPath): 125 | idfMap = pickle.load(open(idfMapPath,'rb')) 126 | else: 127 | idfMap = None 128 | 129 | sid_seq = {} 130 | for line in open(inputPath): 131 | # get the sid 132 | sid = int(line.split('\t')[0]) 133 | if (sid not in toSids and sid not in fromSids): 134 | continue 135 | # get the ngram 136 | line = line.strip() 137 | line = line.split('\t')[1] 138 | # remove the trailing ) so that the spliting would not have an empty tail 139 | line = line[:-1].split(')') 140 | if idfMap: 141 | curSeq = [(item[0], int(idfMap[item[0]] * int(item[1]))) 142 | for item in [x.split('(') for x in line]] 143 | else: 144 | curSeq = [(item[0], int(item[1])) 145 | for item in [x.split('(') for x in line]] 146 | # normalized curSeq by its length 147 | lenSeq = math.sqrt(sum([x[1] ** 2 for x in curSeq])) 148 | sid_seq[sid] = dict([(x, y / lenSeq) for (x, y) in curSeq]) 149 | 150 | # slice fromSids into THREAD_NUM pieces 151 | if (len(fromSids) < MIN_SLICE * THREAD_NUM): 152 | step = MIN_SLICE 153 | else: 154 | step = len(fromSids) / THREAD_NUM + 1 155 | 156 | tid = 0 157 | threads = [] 158 | start = 0 159 | while start < len(fromSids): 160 | tid += 1 161 | thread = myThread(tid, '%s%sdist' % (outputPath, tmpPrefix), 162 | sid_seq, sids[0][start:start+step], sids[1], idfMap) 163 | thread.start() 164 | threads.append(thread) 165 | start += step 166 | 167 | # wait unitl thread ends 168 | for t in threads: 169 | t.join() 170 | 171 | # print('everything takes %.4fs' % (time.time() - startTime)) 172 | 173 | 174 | def partialMatrix(sids, idfMap, ngramPath, tmpPrefix, outputPath, 175 | realSid=False): 176 | """ 177 | at this point the outputPath should have been made 178 | calling this function returns a distance matrix 179 | :type sids: List[int] 180 | :type idfMap: Dict{str:float} 181 | - build a mapping between feature and features idf score 182 | :type ngramPath: str 183 | - the path to the computed pattern dataset 184 | :type tmpPrefix: str 185 | - a predix used so that temporary files have no conflict 186 | :type outputPath: str 187 | - a path to specify where the final result is placed 188 | :type realSid: bool 189 | - indicates whether the sid index is actually offset by 1, 190 | so that the lowest sid is 0 191 | """ 192 | servers = json.load(open('servers.json'))['server'] 193 | if not realSid: 194 | sids = [x + 1 for x in sids] 195 | total = len(sids) 196 | if (total < MIN_SERVER * len(servers)): 197 | step = MIN_SERVER 198 | else: 199 | step = total / len(servers) + 1 200 | processes = [] 201 | start = 0 202 | pickle.dump(idfMap, open('%s%sidf.pkl' % (outputPath, tmpPrefix), 'wb')) 203 | for server in servers: 204 | if (start >= total): 205 | break 206 | pickle.dump([sids[start:start+step], sids], open('%s%ssid_%s.pkl' % 207 | (outputPath, tmpPrefix, server), 'wb')) 208 | print(('[LOG]: starting in %s for %s' % (server, tmpPrefix))) 209 | if server == 'localhost': 210 | calDist(ngramPath, '%s%ssid_%s.pkl' % 211 | (outputPath, tmpPrefix, server), 212 | outputPath, tmpPrefix, '%s%sidf.pkl' % 213 | (outputPath, tmpPrefix)) 214 | else: 215 | processes.append(subprocess.Popen( 216 | ['ssh', server, 217 | ('cd %s\npython calculateDistance.py %s %s%ssid_%s.pkl' + 218 | ' %s %s %s%sidf.pkl') % 219 | (os.getcwd(), ngramPath, outputPath, 220 | tmpPrefix, server, outputPath, tmpPrefix, outputPath, 221 | tmpPrefix)])) 222 | start += step 223 | 224 | for process in processes: 225 | process.wait() 226 | 227 | files = sorted(glob.glob('%s%sdist_*' % (outputPath, tmpPrefix)), 228 | key=lambda x: int(x.split('_')[-1])) 229 | 230 | matrix = [] 231 | for fname in files: 232 | with open(fname) as infile: 233 | for line in infile: 234 | matrix.append(array('B', list(map(int, line.split('\t'))))) 235 | # print('[LOG]: merge finished for %s%s' % (outputPath, tmpPrefix)) 236 | 237 | for fname in glob.glob('%s%s*' % (outputPath, tmpPrefix)): 238 | os.remove(fname) 239 | # print('[LOG]: all tmp files removed for %s%s' % (outputPath, tmpPrefix)) 240 | print(('[LOG]: %s matrix computation finished for %s%s' % ( 241 | datetime.datetime.now(), outputPath, tmpPrefix))) 242 | 243 | return matrix 244 | 245 | 246 | def fullMatrix(inputPath, outputPath): 247 | """ 248 | this function is used to compute the full matrix, shouldn't be called 249 | :type inputPath: str 250 | - the path to the computed pattern dataset 251 | :type outputPath: str 252 | - a path to specify where the final result is placed 253 | """ 254 | outputFile = outputPath 255 | outputPathDir = outputPath[:outputPath.rfind('/')] 256 | try: 257 | print(('[LOG]: making directory %s' % outputPathDir)) 258 | os.mkdir(outputPathDir) 259 | except: 260 | pass 261 | servers = json.load(open('servers.json')) 262 | # get all the sids 263 | sids = [int(line.split('\t')[0]) for line in open(inputPath).readlines()] 264 | total = len(sids) 265 | if (total < MIN_SERVER * len(servers)): 266 | step = MIN_SERVER 267 | else: 268 | step = total / len(servers) + 1 269 | 270 | processes = [] 271 | start = 0 272 | for server in servers: 273 | if (start >= total): 274 | break 275 | pickle.dump([sids[start:start+step], sids], open('%ssid_%s.pkl' % 276 | (outputPath, server), 'w')) 277 | print(('starting in %s' % server)) 278 | processes.append(subprocess.Popen( 279 | ['ssh', server, 280 | 'cd %s\npython calculateDistance.py %s %ssid_%s.pkl %s' % 281 | (os.getcwd(), inputPath, outputPath, server, outputPath)])) 282 | start += step 283 | 284 | for process in processes: 285 | process.wait() 286 | 287 | print('all finished') 288 | 289 | # find subsetall1k -name "dist_*" | sort -t _ -k 2 -g | xargs cat > subsetall1k/all_dist.dat 290 | # subprocess.call(shlex.split('find %s -name "dist_*" | sort -t _ -k 2 -g | xargs cat > %s/all_dist.dat' % (outputPath, outputPath))) 291 | files = sorted(glob.glob('%sdist_*' % outputPath), 292 | key=lambda x: int(x.split('_')[-1])) 293 | print(files) 294 | with open(outputFile, 'w') as outfile: 295 | for fname in files: 296 | with open(fname) as infile: 297 | for line in infile: 298 | outfile.write(line) 299 | print('[LOG]: merge Finished') 300 | 301 | for fname in glob.glob('%sdist_*' % outputPath) + glob.glob('%ssid_*' % outputPath): 302 | os.remove(fname) 303 | 304 | print('[LOG]: all tmp files removed') 305 | 306 | 307 | if __name__ == "__main__": 308 | if (sys.argv[1] == 'full'): 309 | fullMatrix(sys.argv[2], sys.argv[3]) 310 | else: 311 | if (len(sys.argv) > 5): 312 | calDist(sys.argv[1], sys.argv[2], sys.argv[3], sys.argv[4], sys.argv[5]) 313 | else: 314 | calDist(sys.argv[1], sys.argv[2], sys.argv[3]) -------------------------------------------------------------------------------- /calculateDistanceInt.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | """ 3 | This is used to compute distance matrix 4 | It makes heavy use of numpy and thus runs faster 5 | """ 6 | 7 | import multiprocessing 8 | import json 9 | import sys 10 | import math 11 | import subprocess 12 | import os 13 | import glob 14 | import pickle 15 | import time 16 | from array import * 17 | import datetime 18 | import gc 19 | # import cProfile 20 | # import pstats 21 | # import line_profiler 22 | from scipy import sparse 23 | import numpy as np 24 | from sklearn import preprocessing 25 | from sklearn.utils import sparsefuncs 26 | 27 | 28 | config = json.load(open('servers.json')) 29 | # thread number 30 | THREAD_NUM = config['threadNum'] 31 | 32 | # the minimum slice size 33 | MIN_SLICE = config['minPerSlice'] 34 | 35 | # the minimum size per server 36 | MIN_SERVER = THREAD_NUM * MIN_SLICE 37 | 38 | PI_VALUE = 3.141592653589793 39 | 40 | 41 | class myThread (multiprocessing.Process): 42 | def __init__(self, threadID, prefix, matrix, sfrom, sto): 43 | # pr = line_profiler.LineProfiler() 44 | # self.pr = pr 45 | # pr.add_function(self.run) 46 | # pr.enable() 47 | 48 | self.threadID = threadID 49 | self.matrix = matrix 50 | self.sfrom = sfrom 51 | self.sto = sto 52 | # self.fo = gzip.open(prefix+'_'+str(srange[0])+'-'+ 53 | # str(srange[1])+'.gz', 'w') 54 | self.fo = prefix+'_'+str(sfrom[0]) 55 | multiprocessing.Process.__init__(self) 56 | 57 | # @profile 58 | def run(self): 59 | # pr = cProfile.Profile() 60 | print('[LOG]: start new thread '+str(self.threadID)) 61 | curTime = time.time() 62 | distM = self.matrix[self.sfrom].dot( 63 | self.matrix[self.sto].T).todense() 64 | distM = np.maximum( 65 | np.arccos(np.minimum(distM, np.ones(distM.shape))) / 66 | (PI_VALUE/200)-0.01, 67 | np.zeros(distM.shape)).astype(np.int8) 68 | 69 | # np.savetxt(self.fo, distM, fmt = '%d') 70 | np.save(self.fo + '.npy', distM) 71 | print(('[LOG]: thread %d finished after %d' % 72 | (self.threadID, time.time() - curTime))) 73 | 74 | # self.pr.disable() 75 | # # sortby = 'cumulative' 76 | # # pstats.Stats(pr).strip_dirs().sort_stats(sortby).print_stats() 77 | # self.pr.print_stats() 78 | 79 | 80 | def getSparseMatrix(idfMap, fromSids, toSids, inputPath): 81 | """ 82 | build a sparse matrix based on stream and feature 83 | :type idfMap: Dict{str:float} 84 | - build a mapping between feature and features idf score 85 | :type fromSids: List[int] 86 | :type toSids: List[int] 87 | :type inputPath: str 88 | - the path to the computed pattern dataset 89 | :rtype: a numpy matrix 90 | """ 91 | sidxs, fidxs, values, features = \ 92 | ngramToMatrix(inputPath, fromSids | toSids) 93 | 94 | featureDict = dict([(features[idx], idx) for idx in range(len(features))]) 95 | 96 | matrix = sparse.csr_matrix( 97 | (values, (sidxs, fidxs)), 98 | shape=(max(sidxs) + 1, len(features)), dtype=np.float64) 99 | 100 | featureWeight = [idfMap[feature] if feature in idfMap else 0 101 | for feature in features] 102 | 103 | # apply idf transformation to the matrix 104 | sparsefuncs.inplace_csr_column_scale(matrix, np.array(featureWeight)) 105 | 106 | # to maintain consistency with previous implementation, round the 107 | # result after applying idf 108 | matrix = matrix.floor() 109 | 110 | # apply normalization to the matrix 111 | matrix = preprocessing.normalize(matrix, copy=False) 112 | 113 | return matrix 114 | 115 | 116 | def calDist(inputPath, sidsPath, outputPath, tmpPrefix='', idfMapPath=None): 117 | """ 118 | :type intputPath: str 119 | - the path to the computed pattern dataset 120 | :type sidsPath: str 121 | - the path to two lists of sids that we need to calculate one as 122 | from and one as to 123 | :type outputPath: str 124 | - a path to specify where the final result is placed 125 | :type tmpPrefix: str (default: '') 126 | - a predix used so that temporary files have no conflict 127 | :type idfMapPath: str (default: None) 128 | - if the idf for each pattern is already computed, provide a path 129 | to avoid repeated computation 130 | """ 131 | print(('[LOG]: %s computing matrix for %s' % (datetime.datetime.now(), 132 | sidsPath.split('sid_')[0]))) 133 | # read the ngram file, generate a node list 134 | lineNum = 1 135 | sids = pickle.load(open(sidsPath)) 136 | 137 | fromSids = set(sids[0]) 138 | # in principle the toSids should be all sids 139 | toSids = set(sids[1]) 140 | 141 | startTime = time.time() 142 | 143 | # get the idfMap, if provided 144 | if (idfMapPath): 145 | idfMap = pickle.load(open(idfMapPath)) 146 | else: 147 | idfMap = None 148 | 149 | matrix = getSparseMatrix(idfMap, fromSids, toSids, inputPath) 150 | 151 | # slice fromSids into THREAD_NUM pieces 152 | if (len(fromSids) < MIN_SLICE * THREAD_NUM): 153 | step = MIN_SLICE 154 | else: 155 | step = len(fromSids) / THREAD_NUM + 1 156 | 157 | print(('[LOG]: %s preprocessing takes %.4fs' % 158 | (datetime.datetime.now(), time.time() - startTime))) 159 | 160 | tid = 0 161 | threads = [] 162 | start = 0 163 | while start < len(fromSids): 164 | tid += 1 165 | thread = myThread(tid, '%s%sdist' % (outputPath, tmpPrefix), 166 | matrix, sids[0][start:start+step], sids[1]) 167 | thread.start() 168 | threads.append(thread) 169 | start += step 170 | 171 | # wait unitl thread ends 172 | for t in threads: 173 | t.join() 174 | 175 | # print('everything takes %.4fs' % (time.time() - startTime)) 176 | 177 | 178 | def partialMatrix(sids, idfMap, ngramPath, tmpPrefix, outputPath, 179 | realSid=False): 180 | """ 181 | at this point the outputPath should have been made 182 | calling this function returns a distance matrix 183 | :type sids: List[int] 184 | :type idfMap: Dict{str:float} 185 | - build a mapping between feature and features idf score 186 | :type ngramPath: str 187 | - the path to the computed pattern dataset 188 | :type tmpPrefix: str 189 | - a predix used so that temporary files have no conflict 190 | :type outputPath: str 191 | - a path to specify where the final result is placed 192 | :type realSid: bool 193 | - indicates whether the sid index is actually offset by 1, 194 | so that the lowest sid is 0 195 | """ 196 | servers = json.load(open('servers.json'))['server'] 197 | if not realSid: 198 | sids = [x + 1 for x in sids] 199 | total = len(sids) 200 | 201 | if total < MIN_SLICE: 202 | # if the matrix is small enough to be handle by a single thread, avoid 203 | # writting files comlete to reduce overhead 204 | matrix = getSparseMatrix(idfMap, set(sids), set(sids), ngramPath) 205 | distM = matrix[sids].dot(matrix[sids].T).todense() 206 | distM = np.maximum( 207 | np.arccos(np.minimum(distM, np.ones(distM.shape))) / 208 | (PI_VALUE/200)-0.01, 209 | np.zeros(distM.shape)).astype(np.int8) 210 | return np.array(distM) 211 | 212 | if (total < MIN_SERVER * len(servers)): 213 | step = MIN_SERVER 214 | else: 215 | step = total / len(servers) + 1 216 | processes = [] 217 | start = 0 218 | pickle.dump(idfMap, open('%s%sidf.pkl' % (outputPath, tmpPrefix), 'w')) 219 | 220 | # if number of tasks is small enough, run it locally 221 | if total < MIN_SERVER: 222 | servers = ['localhost'] 223 | 224 | for server in servers: 225 | if (start >= total): 226 | break 227 | pickle.dump([sids[start:start+step], sids], open('%s%ssid_%s.pkl' % 228 | (outputPath, tmpPrefix, server), 'w')) 229 | print(('[LOG]: starting in %s for %s' % (server, tmpPrefix))) 230 | if server == 'localhost': 231 | calDist(ngramPath, '%s%ssid_%s.pkl' % 232 | (outputPath, tmpPrefix, server), 233 | outputPath, tmpPrefix, '%s%sidf.pkl' % 234 | (outputPath, tmpPrefix)) 235 | else: 236 | gc.collect() 237 | processes.append(subprocess.Popen( 238 | ['ssh', server, 239 | ('cd %s\npython calculateDistanceInt.py %s %s%ssid_%s.pkl' + 240 | ' %s %s %s%sidf.pkl') % 241 | (os.getcwd(), ngramPath, outputPath, 242 | tmpPrefix, server, outputPath, tmpPrefix, outputPath, 243 | tmpPrefix)])) 244 | start += step 245 | 246 | for process in processes: 247 | process.wait() 248 | 249 | print(('[LOG]: %s merge started for %s%s' % 250 | (datetime.datetime.now(), outputPath, tmpPrefix))) 251 | 252 | files = sorted(glob.glob('%s%sdist_*' % (outputPath, tmpPrefix)), 253 | key=lambda x: int(x.split('_')[-1][:-4])) 254 | 255 | matrix = np.concatenate(tuple([np.load(file) for file in files])) 256 | print(('[LOG]: %s merge finished for %s%s' % ( 257 | datetime.datetime.now(), outputPath, tmpPrefix))) 258 | 259 | for fname in glob.glob('%s%s*' % (outputPath, tmpPrefix)): 260 | os.remove(fname) 261 | # print('[LOG]: all tmp files removed for %s%s' % (outputPath, tmpPrefix)) 262 | print(('[LOG]: %s matrix computation finished for %s%s' % ( 263 | datetime.datetime.now(), outputPath, tmpPrefix))) 264 | 265 | return matrix 266 | 267 | 268 | def ngramToMatrix(inputPath, asids): 269 | """ 270 | convert all_sid_ngram data into a sparse matrix coordinates 271 | :type inputPath: str 272 | - the path to the computed pattern dataset 273 | :type asids: List[int] 274 | - the users we want to study 275 | """ 276 | fidx = [] 277 | values = [] 278 | sids = [] 279 | for line in open(inputPath): 280 | # get the sid 281 | sid = int(line.split('\t')[0]) 282 | if sid not in asids: 283 | continue 284 | # get the ngram 285 | line = line.strip() 286 | line = line.split('\t')[1] 287 | # remove the trailing ) so that the spliting would not have an 288 | # empty tail 289 | line = line[:-1].split(')') 290 | curSeq = [(item[0], int(item[1])) for item in 291 | [x.split('(') for x in line]] 292 | 293 | for feature, value in curSeq: 294 | # records.append((sid, feature, value)) 295 | sids.append(sid) 296 | fidx.append(feature) 297 | values.append(value) 298 | 299 | features = set(fidx) 300 | features = list(features) 301 | featureDict = dict([(features[idx], idx) for idx in range(len(features))]) 302 | fidx = [featureDict[fid] for fid in fidx] 303 | 304 | return sids, fidx, values, features 305 | 306 | 307 | if __name__ == "__main__": 308 | if (sys.argv[1] == 'coord'): 309 | ngramToMatrix(*sys.argv[2:]) 310 | else: 311 | if (len(sys.argv) > 5): 312 | calDist(sys.argv[1], sys.argv[2], sys.argv[3], sys.argv[4], sys.argv[5]) 313 | else: 314 | calDist(sys.argv[1], sys.argv[2], sys.argv[3]) -------------------------------------------------------------------------------- /input.txt: -------------------------------------------------------------------------------- 1 | 1 A(7)C(6)B(5)E(5)D(7)G(8)F(8)I(5)H(6)K(11)J(8)M(2)L(9)O(32)N(33) 2 | 2 A(9)C(11)B(12)E(11)D(9)G(10)F(10)I(9)H(6)K(10)J(8)M(3)L(12)O(49)N(29) 3 | 3 A(70)C(5)B(3)E(6)D(5)G(37)F(5)I(32)H(10)K(8)J(10)M(6)L(6)O(5)N(29) 4 | 4 A(4)G(5)F(1)I(5)H(1)K(1)J(1)M(1)O(1)N(2) 5 | 5 A(52)C(7)B(6)E(4)D(5)G(26)F(3)I(27)H(2)K(10)J(4)M(5)O(5)N(29) 6 | 6 A(85)C(4)B(12)E(5)D(9)G(58)F(9)I(48)H(9)K(14)J(15)M(10)L(6)O(7)N(71) 7 | 7 A(62)C(3)B(5)E(9)D(5)G(35)F(7)I(36)H(11)K(3)J(8)M(5)L(7)O(3)N(36) 8 | 8 A(1)C(2)B(3)E(11)D(3)G(6)F(2)I(3)H(11)K(5)J(5)M(5)L(12)O(9)N(2) 9 | 9 A(14)C(16)B(17)E(38)D(15)G(12)F(15)I(15)H(40)K(11)J(12)M(18)L(59)O(48)N(13) 10 | 10 A(11)C(21)B(12)E(38)D(18)G(11)F(10)I(15)H(41)K(15)J(14)M(12)L(74)O(46)N(13) 11 | 11 A(98)C(7)B(7)E(9)D(16)G(55)F(7)I(62)H(14)K(12)J(16)M(8)L(5)O(7)N(57) 12 | 12 A(26)C(7)B(5)E(2)D(3)G(15)F(2)I(13)H(5)K(4)J(2)M(4)L(2)O(4)N(18) 13 | 13 A(7)C(9)B(16)E(28)D(8)G(5)F(8)I(9)H(29)K(13)J(10)M(10)L(50)O(28)N(10) 14 | 14 A(6)C(4)B(3)E(13)D(5)G(3)F(3)I(2)H(20)K(7)J(5)M(6)L(21)O(19)N(8) 15 | 15 A(4)C(5)B(3)E(6)D(4)G(5)F(1)I(5)H(9)K(4)J(6)M(2)L(19)O(14)N(4) 16 | 16 A(77)C(9)B(10)E(7)D(7)G(37)F(17)I(41)H(6)K(14)J(4)M(11)L(11)O(7)N(42) 17 | 17 A(11)C(15)B(16)E(40)D(19)G(15)F(14)I(11)H(51)K(13)J(13)M(10)L(75)O(41)N(10) 18 | 18 A(34)C(5)B(3)E(5)G(20)F(6)I(15)H(6)K(3)J(4)M(4)L(4)O(2)N(10) 19 | 19 A(13)C(15)B(15)E(19)D(15)G(17)F(15)I(22)H(21)K(18)J(11)M(20)L(16)O(88)N(75) 20 | 20 A(48)C(1)B(4)E(5)D(2)G(14)F(6)I(19)H(3)K(3)J(4)M(3)L(2)O(2)N(20) 21 | 21 A(9)C(17)B(12)E(43)D(13)G(15)F(19)I(20)H(47)K(10)J(14)M(11)L(71)O(46)N(16) 22 | 22 A(48)C(6)B(4)E(4)D(6)G(26)F(9)I(29)H(5)K(7)J(8)M(4)L(3)O(5)N(31) 23 | 23 A(2)C(2)E(1)D(1)G(1)I(5)J(1)M(1)N(8) 24 | 24 A(60)C(9)B(4)E(3)D(1)G(36)F(5)I(27)H(7)K(5)J(5)M(8)L(9)O(5)N(26) 25 | 25 A(12)C(11)B(17)E(48)D(11)G(13)F(14)I(10)H(55)K(15)J(20)M(9)L(61)O(39)N(24) 26 | 26 A(2)B(5)E(7)D(1)G(3)F(1)I(5)H(4)K(2)J(1)M(5)L(8)O(8)N(2) 27 | 27 A(10)C(10)B(18)E(14)D(17)G(5)F(15)I(10)H(11)K(14)J(12)M(10)L(13)O(44)N(39) 28 | 28 A(74)C(10)B(7)E(9)D(13)G(44)F(11)I(33)H(6)K(8)J(4)M(2)L(8)O(7)N(40) 29 | 29 A(5)C(4)B(4)E(9)D(9)G(4)F(7)I(10)H(5)K(4)J(3)M(3)L(3)O(22)N(26) 30 | 30 A(18)C(18)B(18)E(13)D(25)G(17)F(19)I(21)H(14)K(10)J(14)M(18)L(22)O(67)N(90) 31 | 31 A(27)C(3)B(3)E(1)D(2)G(16)I(12)H(1)K(4)J(3)M(3)L(2)O(1)N(14) 32 | 32 A(81)C(7)B(5)E(7)D(5)G(19)F(8)I(27)H(1)K(4)J(7)M(4)L(10)O(10)N(47) 33 | 33 A(8)C(7)B(5)E(29)D(11)G(9)F(12)I(8)H(25)K(12)J(10)M(8)L(32)O(38)N(7) 34 | 34 A(11)C(9)B(6)E(25)D(9)G(12)F(9)I(10)H(24)K(7)J(9)M(10)L(35)O(31)N(7) 35 | 35 A(74)C(13)B(10)E(12)D(8)G(46)F(7)I(37)H(8)K(9)J(7)M(7)L(8)O(2)N(37) 36 | 36 A(93)C(13)B(12)E(11)D(8)G(54)F(5)I(49)H(10)K(12)J(7)M(9)L(9)O(10)N(50) 37 | 37 A(12)C(12)B(6)E(31)D(8)G(8)F(10)I(7)H(25)K(8)J(6)M(13)L(40)O(26)N(8) 38 | 38 A(103)C(5)B(7)E(9)D(8)G(40)F(6)I(50)H(7)K(7)J(11)M(9)L(8)O(6)N(47) 39 | 39 A(62)C(5)B(5)E(5)D(7)G(35)F(9)I(33)H(11)K(7)J(2)M(4)L(7)O(7)N(42) 40 | 40 A(2)B(1)D(3)G(1)F(2)H(4)L(4)O(4)N(1) 41 | 41 A(47)C(6)B(4)E(2)D(3)G(19)F(5)I(27)H(1)K(9)J(1)M(4)L(2)O(7)N(28) 42 | 42 A(65)C(9)B(3)E(4)D(2)G(31)F(7)I(35)H(7)K(3)J(3)M(5)L(8)O(6)N(34) 43 | 43 A(94)C(7)B(8)E(6)D(4)G(43)F(8)I(39)H(11)K(7)J(12)M(8)L(12)O(3)N(58) 44 | 44 A(73)C(9)B(6)E(8)D(5)G(41)F(8)I(32)H(3)K(12)J(1)M(10)L(5)O(3)N(44) 45 | 45 A(7)C(10)B(11)E(20)D(7)G(11)F(8)I(5)H(18)K(5)J(4)M(5)L(31)O(23)N(3) 46 | 46 A(9)C(1)B(3)E(1)D(2)G(8)F(1)I(10)K(4)J(3)M(1)N(2) 47 | 47 A(7)C(3)B(5)E(4)D(3)G(7)F(10)I(4)H(10)K(4)J(6)M(5)L(8)O(22)N(28) 48 | 48 A(14)C(19)B(20)E(47)D(11)G(21)F(14)I(18)H(47)K(24)J(14)M(14)L(83)O(38)N(14) 49 | 49 A(59)C(5)B(9)E(5)D(5)G(35)F(2)I(27)H(8)K(4)J(2)M(5)L(10)O(3)N(19) 50 | 50 A(93)C(5)B(6)E(7)D(11)G(51)F(12)I(51)H(12)K(7)J(11)M(5)L(8)O(5)N(61) 51 | 51 A(61)C(2)B(2)E(7)D(6)G(35)F(8)I(23)H(6)K(4)J(5)M(8)L(4)O(2)N(24) 52 | 52 A(11)C(13)B(15)E(13)D(17)G(9)F(12)I(16)H(15)K(18)J(17)M(8)L(18)O(57)N(53) 53 | 53 A(1)C(1)B(2)G(1)I(1)K(6)J(1)M(2)O(6)N(3) 54 | 54 A(52)C(3)B(2)E(6)D(7)G(21)F(4)I(26)H(5)K(4)J(8)M(5)L(7)O(2)N(29) 55 | 55 A(41)C(3)B(6)E(4)D(6)G(24)F(7)I(20)H(4)K(5)J(2)M(7)L(3)O(3)N(34) 56 | 56 A(2)C(7)B(8)E(8)D(4)G(5)F(4)I(6)H(6)K(6)J(3)M(4)L(4)O(15)N(30) 57 | 57 A(8)C(4)B(11)E(6)D(9)G(8)F(8)I(10)H(4)K(8)J(9)M(3)L(13)O(42)N(38) 58 | 58 A(50)C(9)B(2)E(9)D(4)G(26)F(5)I(29)H(4)K(2)J(2)M(7)L(3)O(5)N(31) 59 | 59 A(77)C(10)B(5)E(6)D(2)G(55)F(4)I(54)H(9)K(11)J(7)M(5)L(9)O(6)N(37) 60 | 60 A(82)C(11)B(7)E(6)D(13)G(42)F(13)I(43)H(9)K(10)J(9)M(8)L(7)O(10)N(34) 61 | 61 A(76)C(6)B(8)E(5)D(6)G(48)F(8)I(40)H(5)K(7)J(3)M(4)L(13)O(9)N(44) 62 | 62 A(4)B(3)F(1)H(4)M(1)L(6)O(2)N(2) 63 | 63 A(6)C(3)B(3)E(15)D(5)G(5)F(7)I(3)H(16)K(4)J(4)M(3)L(29)O(9)N(5) 64 | 64 A(43)C(3)B(4)E(1)D(6)G(30)F(4)I(26)H(2)K(5)J(4)M(1)L(3)O(4)N(27) 65 | 65 A(64)C(8)B(6)E(6)D(4)G(46)F(9)I(43)H(9)K(3)J(5)M(6)L(5)O(8)N(40) 66 | 66 A(3)C(1)D(1)G(5)I(2)H(1)J(2)N(2) 67 | 67 A(5)C(2)B(4)E(12)D(8)G(9)F(6)I(6)H(14)K(4)J(3)M(3)L(27)O(7)N(4) 68 | 68 A(2)C(4)B(2)E(9)D(3)G(3)F(2)I(2)H(6)K(6)J(4)M(2)L(20)O(12)N(3) 69 | 69 A(8)C(7)B(11)E(7)D(10)G(11)F(13)I(5)H(9)K(8)J(6)M(11)L(13)O(37)N(27) 70 | 70 A(59)C(5)B(9)E(6)D(3)G(32)F(10)I(35)H(10)K(5)J(13)M(10)L(4)O(5)N(37) 71 | 71 A(12)C(14)B(11)E(37)D(11)G(15)F(12)I(8)H(26)K(9)J(9)M(14)L(64)O(43)N(10) 72 | 72 A(3)C(6)B(5)E(20)D(3)G(3)F(4)I(4)H(16)K(4)J(6)M(7)L(25)O(15)N(3) 73 | 73 A(12)C(12)B(12)E(41)D(13)G(12)F(14)I(10)H(39)K(11)J(14)M(17)L(67)O(38)N(6) 74 | 74 A(85)C(7)B(8)E(9)D(9)G(46)F(6)I(41)H(10)K(6)J(7)M(7)L(8)O(11)N(49) 75 | 75 A(2)C(2)B(1)E(3)G(2)F(2)I(1)J(1)M(3)L(1)O(9)N(4) 76 | 76 A(39)C(4)B(2)E(1)D(4)G(19)F(5)I(17)H(3)K(5)J(5)M(6)L(1)O(4)N(13) 77 | 77 A(3)C(5)B(5)E(3)D(11)G(8)F(10)I(4)H(10)K(6)J(11)M(8)L(3)O(26)N(33) 78 | 78 A(41)C(2)B(4)E(4)D(6)G(22)F(3)I(25)H(6)K(7)J(4)M(7)L(4)O(3)N(27) 79 | 79 A(28)C(4)B(3)E(2)D(1)G(15)F(2)I(15)H(2)K(1)J(3)M(2)L(3)O(3)N(9) 80 | 80 A(41)C(6)B(5)E(2)D(3)G(25)F(7)I(23)H(6)K(2)J(6)M(8)L(3)O(4)N(13) 81 | 81 A(10)C(12)B(17)E(41)D(10)G(13)F(12)I(17)H(39)K(12)J(13)M(12)L(62)O(34)N(17) 82 | 82 A(10)C(8)B(12)E(7)D(11)G(8)F(9)I(5)H(7)K(10)J(3)M(8)L(9)O(30)N(37) 83 | 83 A(76)C(9)B(7)E(14)D(8)G(52)F(9)I(28)H(12)K(9)J(7)M(10)L(12)O(13)N(45) 84 | 84 A(8)C(7)B(4)E(15)D(2)G(3)F(6)I(4)H(13)K(2)J(6)M(3)L(21)O(11)N(5) 85 | 85 A(8)C(2)B(5)E(27)D(8)G(4)F(6)I(3)H(19)K(2)J(4)M(5)L(32)O(15)N(8) 86 | 86 A(1)C(1)B(1)E(1)D(1)I(3)L(1)O(3)N(2) 87 | 87 A(7)C(9)B(9)E(30)D(12)G(7)F(13)I(10)H(28)K(6)J(9)M(10)L(56)O(35)N(15) 88 | 88 A(49)C(4)B(10)E(7)D(4)G(25)F(4)I(35)H(4)K(3)J(2)M(5)L(7)O(4)N(33) 89 | 89 A(11)C(11)B(10)E(38)D(12)G(12)F(8)I(12)H(28)K(15)J(15)M(11)L(48)O(35)N(6) 90 | 90 A(84)C(10)B(13)E(8)D(9)G(46)F(9)I(42)H(9)K(9)J(10)M(15)L(7)O(8)N(43) 91 | 91 C(1)E(5)D(1)G(1)F(2)M(1)L(1)O(4) 92 | 92 A(5)C(1)B(1)E(5)D(6)G(2)F(2)I(8)H(3)K(3)J(2)M(1)O(19)N(17) 93 | 93 A(1)C(2)E(3)D(1)G(3)F(2)I(1)H(4)K(1)J(1)L(7)O(12)N(4) 94 | 94 A(4)C(3)B(1)E(1)D(1)G(4)F(2)I(3)H(1)K(2)J(2)O(2)N(4) 95 | 95 A(80)C(9)B(9)E(5)D(12)G(39)F(7)I(43)H(12)K(10)J(7)M(8)L(8)O(8)N(51) 96 | 96 A(12)C(20)B(15)E(14)D(27)G(14)F(27)I(7)H(19)K(13)J(9)M(20)L(19)O(78)N(76) 97 | 97 A(44)C(4)B(4)E(2)D(3)G(23)F(7)I(19)H(6)K(3)J(5)M(2)L(6)O(5)N(31) 98 | 98 A(19)C(11)B(18)E(45)D(18)G(21)F(13)I(19)H(51)K(16)J(17)M(17)L(82)O(42)N(10) 99 | 99 A(5)C(10)B(13)E(24)D(14)G(4)F(4)I(4)H(20)K(5)J(10)M(5)L(45)O(29)N(5) 100 | 100 A(18)C(13)B(19)E(49)D(16)G(16)F(15)I(13)H(35)K(15)J(17)M(16)L(79)O(35)N(22) 101 | 101 A(59)C(9)B(4)E(7)D(5)G(26)F(10)I(32)H(8)K(8)J(10)M(11)L(4)O(5)N(33) 102 | 102 A(37)C(6)B(4)E(4)D(4)G(28)F(4)I(16)H(4)K(2)J(3)M(4)L(6)O(2)N(32) 103 | 103 A(1)C(6)B(3)E(14)D(5)G(5)F(1)H(7)K(1)J(3)M(2)L(11)O(4)N(1) 104 | 104 A(15)C(15)B(16)E(39)D(17)G(4)F(16)I(7)H(39)K(9)J(16)M(19)L(52)O(38)N(13) 105 | 105 A(9)C(8)B(8)E(8)D(4)G(8)F(10)I(9)H(10)K(7)J(7)M(1)L(8)O(28)N(29) 106 | 106 A(12)C(11)B(9)E(30)D(11)G(9)F(13)I(15)H(28)K(10)J(11)M(5)L(50)O(21)N(6) 107 | 107 A(118)C(7)B(12)E(12)D(11)G(40)F(9)I(52)H(10)K(6)J(11)M(13)L(8)O(8)N(56) 108 | 108 A(85)C(12)B(5)E(16)D(4)G(54)F(7)I(47)H(7)K(9)J(9)M(9)L(7)O(11)N(40) 109 | 109 A(64)C(8)B(5)E(7)D(8)G(40)F(6)I(31)H(8)K(7)J(4)M(5)L(15)O(15)N(46) 110 | 110 A(10)C(11)B(12)E(31)D(6)G(10)F(9)I(9)H(19)K(6)J(10)M(9)L(53)O(19)N(8) 111 | 111 A(16)C(12)B(10)E(43)D(9)G(16)F(19)I(17)H(43)K(11)J(17)M(13)L(72)O(48)N(19) 112 | 112 A(12)C(13)B(19)E(11)D(12)G(20)F(21)I(17)H(18)K(14)J(17)M(22)L(18)O(63)N(82) 113 | 113 A(69)C(12)B(3)E(8)D(5)G(32)F(8)I(36)H(6)K(9)J(8)M(4)L(8)O(8)N(38) 114 | 114 A(80)C(5)B(9)E(4)D(5)G(36)F(8)I(47)H(7)K(4)J(7)M(5)L(10)O(5)N(30) 115 | 115 A(11)C(13)B(13)E(42)D(13)G(8)F(12)I(9)H(28)K(12)J(6)M(15)L(45)O(34)N(13) 116 | 116 A(15)C(11)B(5)E(7)D(5)G(6)F(12)I(8)H(10)K(13)J(15)M(8)L(8)O(44)N(41) 117 | 117 A(27)C(2)B(3)E(3)D(1)G(12)F(5)I(13)H(2)K(2)M(3)L(4)O(1)N(22) 118 | 118 A(12)C(22)B(22)E(12)D(19)G(17)F(21)I(20)H(22)K(19)J(19)M(9)L(20)O(72)N(84) 119 | 119 A(5)C(8)B(11)E(38)D(8)G(7)F(14)I(5)H(31)K(12)J(9)M(9)L(56)O(25)N(15) 120 | 120 A(1)C(1)B(2)D(1)F(1)H(3)K(1)L(2)O(2) 121 | 121 A(6)C(5)B(3)E(16)D(5)G(7)F(7)I(4)H(20)K(9)J(10)M(8)L(18)O(20)N(5) 122 | 122 A(71)C(9)B(11)E(11)D(4)G(34)F(8)I(33)H(7)K(7)J(11)M(8)L(10)O(5)N(47) 123 | 123 A(91)C(11)B(8)E(5)D(9)G(43)F(14)I(48)H(7)K(12)J(12)M(10)L(13)O(11)N(45) 124 | 124 A(75)C(5)B(10)E(11)D(11)G(44)F(5)I(38)H(4)K(18)J(7)M(12)L(7)O(7)N(41) 125 | 125 A(28)B(1)E(2)D(3)G(25)F(2)I(23)H(4)K(1)J(1)M(4)L(2)O(3)N(23) 126 | 126 A(48)C(6)B(3)E(5)D(1)G(29)F(11)I(23)H(5)K(8)J(4)M(4)L(7)O(4)N(23) 127 | 127 A(70)C(9)B(5)E(8)D(9)G(45)F(4)I(32)H(7)K(7)J(4)M(8)L(5)O(7)N(48) 128 | 128 A(13)C(19)B(14)E(48)D(17)G(11)F(16)I(16)H(42)K(10)J(17)M(14)L(86)O(50)N(13) 129 | 129 A(16)C(16)B(15)E(17)D(15)G(12)F(18)I(16)H(23)K(9)J(9)M(16)L(11)O(67)N(62) 130 | 130 A(34)C(4)B(3)E(3)D(3)G(23)F(3)I(15)H(1)K(2)J(1)M(5)L(3)O(3)N(24) 131 | 131 A(2)C(3)B(2)E(11)G(2)F(3)H(7)K(5)J(2)M(3)L(16)O(13)N(3) 132 | 132 A(45)C(4)B(2)E(3)D(1)G(24)F(4)I(20)H(2)K(5)J(6)M(3)L(2)O(3)N(22) 133 | 133 A(52)C(8)B(2)E(4)D(6)G(24)F(7)I(30)H(13)K(7)J(4)M(8)L(8)O(5)N(30) 134 | 134 C(2)B(2)E(3)D(1)G(1)F(2)I(1)H(2)K(3)J(6)M(4)L(13)O(6)N(1) 135 | 135 A(16)C(15)B(15)E(51)D(17)G(14)F(14)I(14)H(37)K(16)J(13)M(13)L(60)O(50)N(12) 136 | 136 A(8)C(9)B(3)E(11)D(6)G(6)F(6)I(4)H(11)K(2)J(3)M(6)L(32)O(7)N(1) 137 | 137 A(4)C(3)B(5)E(15)D(2)G(3)F(6)I(5)H(29)K(4)J(4)M(8)L(25)O(20)N(2) 138 | 138 A(8)G(2)F(2)I(5)H(1)J(2)M(1)L(2)O(2)N(2) 139 | 139 A(18)C(5)B(2)D(2)G(12)F(2)I(4)H(1)J(1)M(1)L(1)O(2)N(3) 140 | 140 A(4)C(10)B(8)E(30)D(5)G(10)F(10)I(7)H(25)K(14)J(8)M(8)L(41)O(23)N(5) 141 | 141 A(4)C(5)B(5)E(7)D(6)G(2)F(9)I(9)H(5)K(5)J(3)M(3)L(2)O(25)N(16) 142 | 142 A(9)C(16)B(11)E(43)D(16)G(7)F(15)I(9)H(36)K(14)J(9)M(7)L(55)O(49)N(13) 143 | 143 A(66)C(4)B(9)E(7)D(5)G(46)F(3)I(22)H(7)K(3)J(9)M(9)L(6)O(7)N(40) 144 | 144 A(10)C(10)B(20)E(10)D(30)G(14)F(16)I(13)H(16)K(13)J(19)M(15)L(15)O(54)N(63) 145 | 145 A(15)C(10)B(9)E(34)D(11)G(17)F(9)I(9)H(25)K(11)J(11)M(9)L(58)O(25)N(9) 146 | 146 A(68)C(6)B(4)E(6)D(4)G(38)F(6)I(38)H(5)K(4)J(7)M(5)L(6)O(4)N(38) 147 | 147 A(8)C(5)B(8)E(25)D(3)G(12)F(4)I(9)H(21)K(7)J(10)M(10)L(32)O(18)N(6) 148 | 148 A(47)C(1)B(4)E(4)D(6)G(22)F(7)I(22)H(4)K(3)J(7)M(7)L(2)O(2)N(31) 149 | 149 A(27)C(4)B(2)E(3)D(2)G(23)F(2)I(15)H(7)K(3)J(3)M(5)L(1)O(2)N(23) 150 | 150 C(1)E(1)H(4)K(1)L(5)O(2) 151 | 151 A(58)C(8)B(8)E(10)D(5)G(28)F(5)I(37)H(6)K(8)J(5)M(8)L(9)O(6)N(35) 152 | 152 A(40)C(4)B(3)E(3)D(1)G(22)F(2)I(16)H(3)K(2)J(7)M(3)L(9)O(2)N(23) 153 | 153 A(41)C(5)B(6)E(3)D(6)G(35)F(3)I(13)H(7)K(3)J(5)M(1)L(4)O(8)N(24) 154 | 154 A(4)C(9)B(4)E(20)D(5)G(7)F(5)I(6)H(24)K(9)J(9)M(6)L(27)O(9)N(11) 155 | 155 A(87)C(11)B(8)E(6)D(8)G(46)F(10)I(49)H(21)K(8)J(13)M(15)L(9)O(11)N(60) 156 | 156 A(10)C(2)B(1)E(1)D(2)G(7)F(2)I(14)H(1)K(1)J(1)M(1)L(1)N(9) 157 | 157 A(64)C(9)B(4)E(4)D(6)G(45)F(11)I(57)H(8)K(6)J(8)M(5)L(5)O(4)N(31) 158 | 158 A(76)C(5)B(10)E(7)D(6)G(38)F(5)I(37)H(7)K(8)J(8)M(4)L(16)O(8)N(45) 159 | 159 A(57)C(7)B(6)E(13)D(7)G(51)F(7)I(51)H(9)K(7)J(5)M(7)L(14)O(14)N(38) 160 | 160 A(73)C(11)B(15)E(11)D(11)G(52)F(8)I(45)H(13)K(6)J(4)M(6)L(11)O(14)N(43) 161 | 161 C(4)B(5)E(10)D(2)G(2)F(1)I(3)H(12)K(3)J(4)M(3)L(12)O(6)N(2) 162 | 162 A(22)C(1)B(1)E(6)D(5)G(17)F(2)I(19)H(6)K(2)J(1)M(4)L(2)O(4)N(15) 163 | 163 A(16)C(2)B(1)D(4)G(10)I(4)H(1)K(1)J(2)M(1)L(1)N(9) 164 | 164 A(46)C(4)B(1)E(4)D(4)G(34)F(3)I(36)H(5)K(2)J(2)M(4)L(9)O(4)N(37) 165 | 165 A(76)C(8)B(13)E(7)D(10)G(47)F(9)I(51)H(11)K(11)J(14)M(5)L(10)O(5)N(54) 166 | 166 C(3)B(2)E(1)D(1)H(4)K(2)M(1)L(6)O(1)N(1) 167 | 167 A(2)C(1)B(2)E(7)D(2)G(5)F(3)I(1)H(6)K(3)J(5)M(5)L(12)O(3) 168 | 168 A(78)C(10)B(5)E(7)D(6)G(39)F(9)I(42)H(13)K(7)J(6)M(11)L(11)O(10)N(50) 169 | 169 A(4)C(8)B(12)E(17)D(16)G(9)F(6)I(11)H(20)K(15)J(6)M(7)L(45)O(19)N(12) 170 | 170 A(75)C(12)B(5)E(9)D(12)G(41)F(8)I(51)H(11)K(7)J(9)M(5)L(6)O(9)N(54) 171 | 171 A(71)C(4)B(2)E(9)D(7)G(41)F(9)I(32)H(2)K(4)J(4)M(6)L(7)O(4)N(29) 172 | 172 A(2)C(3)B(2)E(7)D(2)G(2)F(3)I(6)H(14)K(5)J(5)M(6)L(12)O(21)N(8) 173 | 173 A(46)C(2)B(3)E(5)D(3)G(18)F(3)I(28)H(2)K(2)J(2)M(5)L(3)O(5)N(21) 174 | 174 A(55)C(5)B(7)E(8)D(5)G(27)F(6)I(31)H(8)K(7)M(6)L(7)O(5)N(34) 175 | 175 A(17)C(17)B(7)E(30)D(8)G(11)F(12)I(9)H(18)K(10)J(15)M(19)L(50)O(26)N(11) 176 | 176 A(53)C(4)B(6)E(5)D(4)G(37)F(5)I(27)H(10)K(2)J(7)M(5)L(5)O(7)N(37) 177 | 177 A(10)C(4)E(2)D(1)G(3)F(2)I(3)K(2)J(1)L(1)N(4) 178 | 178 A(5)C(6)B(10)E(29)D(8)G(12)F(6)I(7)H(34)K(6)J(8)M(9)L(44)O(29)N(16) 179 | 179 A(41)C(2)B(4)E(5)D(2)G(22)F(4)I(27)H(3)K(6)J(3)M(4)L(4)O(5)N(28) 180 | 180 A(46)C(5)B(7)E(6)D(5)G(35)F(6)I(31)H(5)K(6)J(8)M(6)L(9)O(7)N(21) 181 | 181 A(26)C(4)B(2)E(5)D(6)G(12)I(17)H(3)K(2)J(1)M(6)L(1)O(1)N(19) 182 | 182 A(16)E(4)G(12)F(2)I(11)H(3)K(1)J(1)M(1)O(2)N(15) 183 | 183 A(15)C(12)B(15)E(26)D(9)G(12)F(15)I(16)H(28)K(11)J(8)M(10)L(52)O(35)N(14) 184 | 184 A(22)C(3)B(4)E(1)D(3)G(17)F(5)I(12)H(3)K(3)J(5)M(3)L(5)O(4)N(13) 185 | 185 C(2)B(3)E(4)D(1)G(1)K(1)M(1)L(5)O(1)N(1) 186 | 186 A(23)C(11)B(21)E(41)D(14)G(16)F(11)I(6)H(32)K(13)J(16)M(15)L(60)O(45)N(12) 187 | 187 A(18)C(8)B(12)E(10)D(12)G(5)F(11)I(6)H(4)K(9)J(8)M(10)L(7)O(46)N(33) 188 | 188 A(52)C(3)B(2)E(10)D(4)G(39)F(3)I(33)H(5)K(8)J(5)M(6)L(1)O(5)N(19) 189 | 189 A(1)C(4)B(6)E(11)D(4)G(3)F(4)I(3)H(15)K(4)J(2)M(1)L(26)O(8)N(4) 190 | 190 A(92)C(5)B(9)E(12)D(9)G(62)F(6)I(41)H(10)K(9)J(9)M(14)L(6)O(4)N(59) 191 | 191 A(10)C(16)B(11)E(41)D(19)G(27)F(17)I(18)H(35)K(9)J(16)M(14)L(79)O(48)N(8) 192 | 192 A(7)C(8)B(10)E(7)D(12)G(15)F(9)I(8)H(19)K(19)J(11)M(16)L(8)O(62)N(39) 193 | 193 A(13)C(14)B(13)E(9)D(8)G(16)F(9)I(4)H(13)K(8)J(10)M(8)L(19)O(54)N(55) 194 | 194 A(62)C(7)B(9)E(5)D(6)G(34)F(4)I(39)H(12)K(8)J(8)M(6)L(7)O(3)N(41) 195 | 195 A(38)C(2)B(3)E(5)D(1)G(19)F(1)I(22)K(1)J(1)M(2)L(5)O(2)N(22) 196 | 196 A(15)C(8)B(12)E(46)D(7)G(10)F(13)I(15)H(33)K(23)J(16)M(16)L(56)O(42)N(17) 197 | 197 A(78)C(14)B(7)E(6)D(4)G(39)F(5)I(47)H(11)K(7)J(10)M(9)L(9)O(11)N(43) 198 | 198 A(18)C(17)B(16)E(22)D(21)G(22)F(12)I(14)H(19)K(13)J(17)M(23)L(26)O(74)N(70) 199 | 199 A(16)C(11)B(16)E(13)D(15)G(21)F(20)I(21)H(16)K(14)J(14)M(12)L(12)O(67)N(53) 200 | 200 B(1)E(2)D(3)G(1)I(2)H(2)J(1)M(2)L(6)O(5)N(2) 201 | -------------------------------------------------------------------------------- /mutual_info.py: -------------------------------------------------------------------------------- 1 | import math 2 | import numpy as np 3 | import scipy.stats 4 | import pickle 5 | import json 6 | import sys 7 | import cProfile 8 | import pstats 9 | import io 10 | from functools import reduce 11 | 12 | 13 | def avgStdWithZero(l, numZero): 14 | """ 15 | get the std of a list with trailing zeros 16 | :type l: List[int] 17 | :type numZero: int 18 | """ 19 | if len(l) == 0: 20 | return 0, 0 21 | avg = float(sum(l)) / (len(l) + numZero) 22 | error = 0.0 23 | for num in l: 24 | error += (num - avg) ** 2 25 | error += numZero * (avg ** 2) 26 | error = error / (len(l) + numZero) 27 | return avg, math.sqrt(error) 28 | 29 | 30 | def mutual_info(patternInCluster, allPatternInCluster, totalPattern, 31 | totalAllPattern): 32 | """ 33 | This function is not used 34 | get the mutual information score for a given cluster and given pattern 35 | :type patternInCluster: int 36 | - the number of occurence of this pattern in this cluster 37 | :type allPatternInCluster: int 38 | - the total number of occurences for all patterns in this cluster 39 | :type totalPattern: int 40 | - the total number of occurences of this pattern in all clusters 41 | :type totalAllPattern: int 42 | - the total number of occurences for all patterns in all clusters 43 | """ 44 | N = totalAllPattern 45 | D = patternInCluster 46 | B = allPatternInCluster - D 47 | C = totalPattern - D 48 | A = totalAllPattern - C - D - B 49 | 50 | very_small = 1.0/N/1000000 51 | 52 | tmpD = 1.0*N*D/((B+D)*(C+D))+very_small 53 | tmpC = 1.0*N*C/((C+D)*(A+C))+very_small 54 | tmpB = 1.0*N*B/((A+B)*(B+D))+very_small 55 | tmpA = 1.0*N*A/((A+B)*(A+C))+very_small 56 | 57 | muinfo = (1.0*D/N) * math.log(tmpD, 2) \ 58 | + (1.0*C/N) * math.log(tmpC, 2) \ 59 | + (1.0*B/N) * math.log(tmpB, 2) \ 60 | + (1.0*A/N) * math.log(tmpA, 2) 61 | 62 | return muinfo 63 | 64 | 65 | # @profile 66 | def chi_square(dist1, usersLeft1, dist2, usersLeft2): 67 | """ 68 | get the chi square score for a given cluster and given pattern 69 | :type dist1: List[int] 70 | - All the users' coutn of this pattern except those having 0 71 | :type usersLeft1: int 72 | - The number of users don't have this pattern 73 | :type dist2: List[int] 74 | - All the users' coutn of this pattern except those having 0 75 | :type usersLeft2: int 76 | - The number of users don't have this pattern 77 | dist1 is used to build the base bins that dist2 will be put into 78 | """ 79 | 80 | avg, s = avgStdWithZero(dist1, usersLeft1) 81 | avg2, s2 = avgStdWithZero(dist2, usersLeft2) 82 | s = s / 3.0 83 | if s == 0: 84 | if s2 == 0: 85 | return ((avg2 - avg) / avg) * (len(dist2) + usersLeft2) \ 86 | if not avg == 0 else 0 87 | else: 88 | # should be based on dist1 still, need to figure out how to select bins 89 | return chi_square(dist2, usersLeft2, dist1, usersLeft1) 90 | 91 | # print(s, avg) 92 | bins = [(idx, (idx + 1)) for idx in range(-18, 18)] 93 | bins = [((x * s + avg), (y * s + avg)) for (x, y) in bins] 94 | bins = [(-float('inf'), bins[0][0])] + bins 95 | bins += [(bins[-1][1], float('inf'))] 96 | 97 | # distribute samples from dist1 into bins 98 | # binMap = dict([(idx, len([1 for x in dist1 if bins[idx][0]<=x 37: 106 | x = 37 107 | binMap[x] += 1 108 | idxZero = int((- avg) / s + 19) 109 | idxZero = 0 if idxZero < 0 else 37 if idxZero > 37 else idxZero 110 | binMap[idxZero] += usersLeft1 111 | 112 | # merge bins that have less than 5 memebers 113 | for idx in range(1, len(bins))[::-1]: 114 | if (binMap[idx] < 5): 115 | binMap[idx - 1] += binMap[idx] 116 | del binMap[idx] 117 | bins[idx - 1] = (bins[idx - 1][0], bins[idx][1]) 118 | del bins[idx] 119 | # print('delete', idx) 120 | if (binMap[0] < 5): 121 | if len(binMap) == 1: 122 | # too few data to get chi-square 123 | return 0 124 | nextIdx = sorted(binMap.keys())[1] 125 | bins[0] = (bins[0][0], bins[1][1]) 126 | binMap[0] += binMap[nextIdx] 127 | del binMap[nextIdx] 128 | del bins[1] 129 | idxZero = [idx for idx in range(len(bins)) 130 | if bins[idx][0] <= 0 < bins[idx][1]][0] 131 | bins1 = [binMap[idx] for idx in sorted(binMap.keys())] 132 | # distribute sample from dist2 into bins 133 | bins2 = np.array([len([1 for x in dist2 134 | if bins[idx][0] <= x < bins[idx][1]]) 135 | for idx in range(len(bins))]) 136 | bins2[idxZero] += usersLeft2 137 | 138 | bins1 = np.array([x * float(usersLeft2 + len(dist2)) / 139 | (usersLeft1 + len(dist1)) for x in bins1]) 140 | chisqValue, pvalue = (scipy.stats.chisquare(bins2, f_exp=bins1)) 141 | return chisqValue 142 | 143 | 144 | def chi_square_feature(cid_pattern_list, cid_user_cnt, 145 | interested_cids=None, printEval=False): 146 | """ 147 | get a list of feature values, compute the one that distinguishes the 148 | most from distuributions in other clusters 149 | :type cid_pattern_list: Dict{int:Dict{str:List[int]}} 150 | - a dictionary for user's pattern count for each cluster 151 | - the first dictionary key is the cluster id 152 | - the second dictionary key is the pattern string 153 | - the value is a list of users' pattern count, excluding 0 154 | :type cid_user_cnt: Dist{int:int} 155 | - total number of users in each cluster 156 | :type interested_cids: List{int} (default: None) 157 | - a list of cluster ids that we want to compute chi_square for 158 | - None means compute for all clusters 159 | :type printEval: bool 160 | - whether output intermedirary result to tmp.txt 161 | :rtype: Dict{int: List[(str, float)]} 162 | - a map of cid and (feature, score) list 163 | """ 164 | if printEval: 165 | fout = open('tmp.txt', 'w') 166 | resultMap = {} 167 | for cid in cid_pattern_list: 168 | if interested_cids and cid not in interested_cids: 169 | continue 170 | scores = {} 171 | for pattern in cid_pattern_list[cid]: 172 | baselist = reduce( 173 | lambda x, y: x+y, 174 | [cid_pattern_list[curCid][pattern] 175 | for curCid in cid_pattern_list 176 | if not curCid == cid and pattern in cid_pattern_list[curCid]], 177 | []) 178 | usersLeftBase = sum([cid_user_cnt[curCid] 179 | for curCid in cid_user_cnt 180 | if not curCid == cid]) - len(baselist) 181 | curList = cid_pattern_list[cid][pattern] 182 | usersLeft = cid_user_cnt[cid] - len(curList) 183 | scores[pattern] = chi_square(baselist, usersLeftBase, 184 | curList, usersLeft) 185 | 186 | resultMap[cid] = sorted(list(scores.items()), 187 | key=lambda x: x[1], reverse=True) 188 | if printEval: 189 | fout.write('%s\t%s\n' % (cid, cid_user_cnt[cid])) 190 | for (feature, score) in resultMap[cid][:50]: 191 | fout.write('%s\t%s\n' % (feature, score)) 192 | fout.write('--------------------------\n') 193 | fout.flush() 194 | 195 | print(('%s\t%s' % (cid, cid_user_cnt[cid]))) 196 | for (feature, score) in resultMap[cid][:50]: 197 | print(('%s\t%s' % (feature, score))) 198 | print('--------------------------') 199 | 200 | return resultMap 201 | 202 | 203 | def mutual_info_feature(cid_pattern_cnt, cid_user_cnt=None, 204 | interested_cids=None): 205 | """ 206 | this is a modified version of the original print_mutual_info, 207 | now each feature is associated with a score instead of a binary has/has not 208 | :type cid_pattern_cnt: Dict{int: Dict{str:float}} 209 | - reacord for each cluster the sum of each features 210 | :type cid_user_cnt: Dist{int:int} (default: None) 211 | - total number of users in each cluster 212 | - None means the script will compute it itself 213 | :type interested_cids: List{int} (default: None) 214 | - a list of cluster ids that we want to compute chi_square for 215 | - None means compute for all clusters 216 | :rtype: Dict{int: List[(str, float)]} 217 | - a map of cid and (feature, score) list 218 | """ 219 | if not cid_user_cnt: 220 | cid_user_cnt = {} 221 | for cid in cid_pattern_cnt: 222 | # TODO: sum or max or avg pattern num * user num? 223 | cid_user_cnt[cid] = \ 224 | sum([x[1] for x in list(cid_pattern_cnt[cid].items())]) 225 | 226 | # compute a tmp dictionary: 227 | pattern_cid_cnt = {} 228 | for cid in cid_pattern_cnt: 229 | for w in cid_pattern_cnt[cid]: 230 | cnt = cid_pattern_cnt[cid][w] 231 | if w not in pattern_cid_cnt: 232 | pattern_cid_cnt[w] = {} 233 | pattern_cid_cnt[w][cid] = cnt 234 | 235 | total_pattern_cnt = {} 236 | for pattern in pattern_cid_cnt: 237 | total_pattern_cnt[pattern] = sum([x[1] for x in list(pattern_cid_cnt[pattern].items())]) 238 | 239 | print('how many patterns', len(pattern_cid_cnt)) 240 | 241 | print('mutual information...') 242 | 243 | """ 244 | # I (feature word, class c): 245 | # A: class !=c and feature !=f => the expected number of non-f features per user * total user not in c (*) 246 | # B: class =c and feature != f => the expected number of non-f features per user * total user in c (*) 247 | # C: class != c and feature =f => the expected number of feature f per user * total user not in c 248 | # D: class = c and feature = f => the expected number of feature f per user * total user in c 249 | # N = total number of samples => the total number of features (*) 250 | (*) - might need adjustment 251 | 252 | I = D/N * log (N *D) / (BD CD) ) 253 | + C/N * log (N *C) / (CD AC) ) 254 | + B/N * log (N *B) / (AB BD) ) 255 | + A/N * log (N *A) / (AB AC) ) 256 | 257 | pre compute: 258 | total number of node clas: class_count 259 | total number of node per feature: feature_count 260 | total number of node per-class, per-feature: class_featurecount 261 | """ 262 | 263 | N = totalFeatures = sum([x[1] for x in list(cid_user_cnt.items())]) 264 | 265 | resultMap = {} 266 | for cid in cid_pattern_cnt: 267 | if interested_cids and cid not in interested_cids: 268 | continue 269 | # for each feature, compute the mutual information 270 | scores = {} 271 | for feature in cid_pattern_cnt[cid]: 272 | D = cid_pattern_cnt[cid][feature] 273 | B = cid_user_cnt[cid] - D 274 | C = total_pattern_cnt[feature] - D 275 | A = totalFeatures - C - D - B 276 | 277 | very_small = 1.0/N/1000000 278 | 279 | tmpD = 1.0*N*D/((B+D)*(C+D))+very_small 280 | tmpC = 1.0*N*C/((C+D)*(A+C))+very_small 281 | tmpB = 1.0*N*B/((A+B)*(B+D))+very_small 282 | tmpA = 1.0*N*A/((A+B)*(A+C))+very_small 283 | 284 | muinfo = (1.0*D/N) * math.log(tmpD, 2) \ 285 | + (1.0*C/N) * math.log(tmpC, 2) \ 286 | + (1.0*B/N) * math.log(tmpB, 2) \ 287 | + (1.0*A/N) * math.log(tmpA, 2) 288 | 289 | scores[feature] = muinfo 290 | # fout.write('%s\t%s\n' % (cid, cid_user_cnt[cid])) 291 | resultMap[cid] = sorted(list(scores.items()), 292 | key=lambda x: x[1], reverse=True) 293 | # fout.write('%s\t%s\n' % (feature, score)) 294 | # fout.write('--------------------------\n') 295 | return resultMap 296 | 297 | # if __name__ == '__main__': 298 | # # testing only 299 | # print(mutual_info_feature(cPickle.load(open('cid_pattern_cnt.pkl')), 300 | # cPickle.load(open('cid_user_cnt.pkl')), 301 | # cPickle.load(open('interested_cids.pkl')))) 302 | 303 | 304 | def print_mutual_info(fname, cid_user_cnt, cid_pattern_cnt): 305 | """ 306 | This is legacy code, not used. For reference only 307 | compute a tmp dictionary 308 | """ 309 | pattern_cid_cnt = {} 310 | for cid in cid_pattern_cnt: 311 | for w in cid_pattern_cnt[cid]: 312 | cnt = cid_pattern_cnt[cid][w] 313 | if w not in pattern_cid_cnt: pattern_cid_cnt[w] = {} 314 | pattern_cid_cnt[w][cid] = cnt 315 | 316 | print('how many patterns', len(pattern_cid_cnt)) 317 | 318 | print('mutual information...') 319 | # mutual information 320 | """ 321 | # I (feature word, class c): 322 | # A: class !=c and feature !=f 323 | # B: class =c and feature != f 324 | # C: class != c and feature =f 325 | # D: class = c and feature = f 326 | # N = total number of samples 327 | 328 | I = D/N * log (N *D) / (BD CD) ) 329 | + C/N * log (N *C) / (CD AC) ) 330 | + B/N * log (N *B) / (AB BD) ) 331 | + A/N * log (N *A) / (AB AC) ) 332 | 333 | pre compute: 334 | total number of node clas: class_count 335 | total number of node per feature: feature_count 336 | total number of node per-class, per-feature: class_featurecount 337 | """ 338 | # total node 339 | N = 0 340 | for cid in cid_user_cnt: 341 | N+= cid_user_cnt[cid] 342 | 343 | print('total N', N) 344 | print('how many class?', len(cid_user_cnt)) 345 | 346 | fo = open(fname,'w') 347 | for cid in cid_pattern_cnt: 348 | w_mutual = {} 349 | w_D = {} 350 | w_C = {} 351 | 352 | for w in cid_pattern_cnt[cid]: 353 | cnt = cid_pattern_cnt[cid][w] 354 | # start to compute mutual info: 355 | # D: class = c and feature = f 356 | D = cnt 357 | # B: class =c and feature != f 358 | B = cid_user_cnt[cid] - cnt 359 | # C: class != c and feature =f 360 | C = 0 361 | for kid in pattern_cid_cnt[w]: 362 | if kid == cid: continue 363 | C += pattern_cid_cnt[w][kid] 364 | # A: class !=c and feature !=f 365 | A = N-(C+B+D) 366 | very_small = 1.0/N/1000000 367 | tmpD = 1.0*N*D/((B+D)*(C+D))+very_small 368 | tmpC = 1.0*N*C/((C+D)*(A+C))+very_small 369 | tmpB = 1.0*N*B/((A+B)*(B+D))+very_small 370 | tmpA = 1.0*N*A/((A+B)*(A+C))+very_small 371 | muinfo = (1.0*D/N) * math.log(tmpD,2) + (1.0*C/N) * math.log(tmpC,2) + (1.0*B/N) * math.log(tmpB,2) + (1.0*A/N) * math.log(tmpA,2) 372 | 373 | if (1.0*D/N) * math.log(tmpD,2) > 0: 374 | w_mutual[w] = muinfo 375 | w_D[w] = D 376 | w_C[w] = C 377 | 378 | # debug: 379 | """ 380 | if str(cid)=='4' and (w=='A8A6A' or w=='A5A'): 381 | print '========== debug cid=4, pattern=', w, 'mutual=', muinfo 382 | print 'D', (1.0*D/N) * math.log(tmpD,2) 383 | print 'C', (1.0*C/N) * math.log(tmpC,2) 384 | print 'B', (1.0*B/N) * math.log(tmpB,2) 385 | print 'A', (1.0*A/N) * math.log(tmpA,2) 386 | """ 387 | 388 | sortlist = sortlist = sorted(iter(w_mutual.items()), key=lambda k_v: (k_v[1],k_v[0])) 389 | sortlist.reverse() 390 | tmpcnt = 0 391 | # for understanding purpuse, let's print D and C as well 392 | fo.write('===== cid:%s, total users:%s ===================== \n' %(cid, cid_user_cnt[cid])) 393 | fo.write('format: pattern, mutual, D: class = c and feature =f, C: class != c and feature =f\n') 394 | for w, cnt in sortlist: 395 | D = w_D[w] 396 | C = w_C[w] 397 | fo.write('##%s\t%s\t%s\t%s\t%s\n' %(cid, w, cnt, D, C)) 398 | tmpcnt += 1 399 | if tmpcnt>10: break 400 | print('done for cluster', cid) 401 | fo.close() 402 | 403 | return 404 | 405 | -------------------------------------------------------------------------------- /recursiveHierarchicalClustering.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | """ 4 | the script to recursively run divisive hierchical clustering 5 | stopping each time at sweet spot 6 | for each iteration, exclude the defining features for each cluster 7 | 8 | # arguments 9 | 10 | arg1: path to a file containing the different ngram count mapping 11 | example: 12 | 10 \t A5A(1)y8y(29)... 13 | the first col is line number 14 | the second col is a list of pattern(count) 15 | 16 | arg2: path to a directory to put the output file 17 | 18 | arg3: sizeThreshold, defines the minimum size of the cluster, that we 19 | are going to further divide 20 | deafult: 0.05: means the size cannot be less than 5% of the total 21 | instances 22 | 23 | # result: 24 | 25 | resultDir/matrix.dat: store the pairwise distance matrix 26 | if the file exist before the scirpt is run, the script assume the matrix 27 | is correct and will read it in 28 | resultDir/result.json: store the clustering result 29 | the result is recorded in a nested list, in the form of: 30 | [type, list of sub-clusters, information about the cluster] 31 | """ 32 | 33 | import math 34 | import time 35 | import json 36 | from array import * 37 | import sys 38 | import os 39 | import numpy as np 40 | import calculateDistance 41 | import mutual_info 42 | from functools import reduce 43 | 44 | 45 | def getSidNgramMap(inputPath, sids=None): 46 | """ 47 | parse the sid ngram map 48 | :type inputPath: str 49 | - the path to two lists of sids that we need to calculate one as 50 | from and one as to 51 | :type sids: List[int] (default: None) 52 | - specify the clickstream we want to study, identified by id 53 | - None means all streams are used 54 | :rtype Dict{int:Dict{str:int}} 55 | - for each user, record the pattern and corresponding occurence # 56 | """ 57 | sid_seq = {} 58 | 59 | for line in open(inputPath): 60 | # get the sid 61 | sid = int(line.split('\t')[0]) 62 | if sids and sid not in sids: 63 | continue 64 | # get the ngram 65 | line = line.strip() 66 | line = line.split('\t')[1] 67 | # remove the trailing ) so that the spliting would not have an empty tail 68 | line = line[:-1].split(')') 69 | sid_seq[sid] = dict([(item[0], int(item[1])) 70 | for item in [x.split('(') for x in line]]) 71 | return sid_seq 72 | 73 | 74 | def splitCluster(clustervars, matrix): 75 | """ 76 | :type baseCluster: List[int] 77 | - take in the cluster to be splited as a list of stream index 78 | :type diameter: int (not used) 79 | :type baseSum: List[int] 80 | - the distance from each node to other nodes in the same 81 | cluster, used to save computation 82 | :type cid: int (cluster id, not used) 83 | :type matrix: List[List[int]] 84 | - distance matrix 85 | 86 | :rtype: (baseCluster, newCluster, baseSum) 87 | :rtype baseCluster: List[int] 88 | - a list of stream index in one part of the split 89 | :rtype newCluster: List[int] 90 | - a list of stream index in the other part of the split 91 | :rtype baseSum: List[int] 92 | - updated baseSum for the baseCluster 93 | """ 94 | baseCluster, diameter, baseSum, cid = clustervars 95 | newCluster = [] 96 | # the number of nodes in the base cluster 97 | baseNodes = totalNodes = len(baseCluster) 98 | sumDists = [] # store the sum of distance to the base cluster 99 | newDists = [] # store the sum of distance to the new cluster 100 | 101 | if (baseSum): 102 | sumDists = baseSum 103 | newDists = [0 for idx in range(totalNodes)] 104 | else: 105 | for node in baseCluster: 106 | sumDist = 0 107 | distRow = matrix[node] 108 | for nodeT in baseCluster: 109 | sumDist += distRow[nodeT] 110 | sumDists.append(sumDist) 111 | newDists.append(0) 112 | 113 | while baseNodes > 1: 114 | # we want to calculate sum(A)/len(A) - sum(B)/len(B) 115 | # where A is base and B is new 116 | # so we instead calculate 117 | # sum(A) * len(B) - sum(B) * len(A) = 118 | # (sum(T) - sum(B)) * len(B) - sum(B) * len(A) 119 | # note that baseNodes = len(A) + 1 120 | newNodes = totalNodes - baseNodes 121 | if baseNodes == totalNodes: 122 | difDist = sumDists 123 | maxIdx = np.argmax(difDist) 124 | maxValue = difDist[maxIdx] 125 | else: 126 | maxValue = 0 127 | for idx in range(len(sumDists)): 128 | sumT = sumDists[idx] 129 | sumB = newDists[idx] 130 | diff = (sumT-sumB) * newNodes - sumB * (baseNodes - 1) 131 | if diff > maxValue: 132 | maxValue = diff 133 | maxIdx = idx 134 | # [(sumT-sumB) * newNodes - sumB * (baseNodes - 1) 135 | # for (sumT, sumB) in zip(sumDists, newDists)] 136 | # print(difDist, sumDists, newDists) 137 | # find the node furthest away from the current cluster 138 | # maxIdx = np.argmax(difDist) 139 | # if (difDist[maxIdx] <= 0): 140 | if (maxValue <= 0): 141 | break 142 | newCluster.append(baseCluster[maxIdx]) 143 | 144 | # update the distance to new cluster for all nodes not in the cluster 145 | distRow = matrix[baseCluster[maxIdx]] 146 | newDists = [newDists[idx] + distRow[baseCluster[idx]] 147 | for idx in range(baseNodes) if not idx == maxIdx] 148 | baseNodes -= 1 149 | del sumDists[maxIdx] 150 | del baseCluster[maxIdx] 151 | 152 | baseSum = [sumT - sumB for (sumT, sumB) in zip(sumDists, newDists)] 153 | return (baseCluster, newCluster, baseSum) 154 | 155 | 156 | def getDia(cluster, matrix): 157 | """ 158 | given a matrix, possibly only part for the origianl matrix 159 | return the maxDistance 160 | :type cluster: List[int] 161 | - a list of stream index in the cluster 162 | :type matrix: List[List[int]] 163 | - distance matrix 164 | :rtype: int 165 | - the diameter of the cluster 166 | """ 167 | if (not matrix): 168 | return 0 169 | # cluster = [sidToIdx[idx] for idx in cluster] 170 | maxDis = 0 171 | for node in cluster: 172 | sumDist = 0 173 | distRow = matrix[node] 174 | for nodeT in cluster: 175 | if (maxDis < distRow[nodeT]): 176 | maxDis = distRow[nodeT] 177 | return maxDis 178 | 179 | 180 | def getIdf(sid_seq, sids): 181 | """ 182 | since we are going to use the tfidf frequency as the actual 183 | weight on each feature vector 184 | we need to calculate idf based on the users in the parent cluster 185 | and original frequency 186 | :type sid_seq: Dict{int:Dict{str:int}} 187 | - for each user, record the pattern and corresponding occurence # 188 | :type sids: List[int] 189 | - the users we want to study, identified by sid 190 | :rtype: Dict{str:float} 191 | - the idf value for all patterns 192 | """ 193 | # sids = [x + 1 for x in sids] 194 | feqMap = {} 195 | total = len(sids) 196 | for sid in sids: 197 | stotal = sum([x[1] for x in list(sid_seq[sid].items())]) 198 | for word in sid_seq[sid]: 199 | freq = sid_seq[sid][word] 200 | try: 201 | feqMap[word] += float(freq) / stotal 202 | except: 203 | feqMap[word] = float(freq) / stotal 204 | for word in feqMap: 205 | feqMap[word] = math.log(float(total) / feqMap[word]) 206 | return feqMap 207 | 208 | 209 | def getSweetSpotL(evalResults): 210 | """ 211 | the L-method is used to find out the sweetspot for defining features 212 | it is supposed to run iteratively until the sweetspot does not gets 213 | closer to 0. 214 | Assuming the input is a list of (x,y) 215 | returns the index of the cutting point in list 216 | ref: http://ieeexplore.ieee.org/xpls/abs_all.jsp?arnumber=1374239&tag=1 217 | :type evalResults: List[List[float]] 218 | :rtype: int 219 | """ 220 | if len(evalResults) == 0: 221 | return 0 222 | cutoff = currentKnee = evalResults[-1][0] 223 | lastKnee = currentKnee + 1 224 | 225 | while currentKnee < lastKnee: 226 | lastKnee = currentKnee 227 | currentKnee = LMethod([item for item in evalResults 228 | if item[0] <= cutoff]) 229 | cutoff = currentKnee * 2 230 | 231 | return currentKnee 232 | 233 | 234 | def linearReg(evalResults): 235 | """ 236 | tool used for finding out the defining feature threshold 237 | performs linear regression 238 | The input is a list of (x,y) 239 | :type evalResults: List[List[float]] 240 | :rtype: (m, c), residual 241 | return the resulting line of linear regression 242 | """ 243 | x = np.array([xv for (xv, yv) in evalResults]) 244 | y = np.array([yv for (xv, yv) in evalResults]) 245 | # print(x, y) 246 | A = np.vstack([x, np.ones(len(x))]).T 247 | result = np.linalg.lstsq(A, y) 248 | m, c = result[0] 249 | residual = result[1] 250 | # print(result) 251 | return ((m, c), residual if len(evalResults) > 2 else 0) 252 | 253 | 254 | def LMethod(evalResults): 255 | """ 256 | using the L-Method, find of the sweetspot for getting defining features 257 | The input is a list of (x,y) 258 | :type evalResults: List[List[float]] 259 | :rtype: float 260 | returns the x value of the sweet spot 261 | """ 262 | # print(len(evalResults)) 263 | if len(evalResults) < 4: 264 | return len(evalResults) 265 | # the partition point c goes from the second point to the -3'th point 266 | minResidual = np.inf 267 | minCons = None 268 | minCutoff = None 269 | for cidx in range(1, len(evalResults) - 2): 270 | (con1, residual1) = linearReg(evalResults[:cidx + 1]) 271 | (con2, residual2) = linearReg(evalResults[cidx + 1:]) 272 | if (residual1 + residual2) < minResidual: 273 | minCons = (con1, con2) 274 | minCutoff = cidx 275 | minResidual = residual1 + residual2 276 | if minCutoff is None: 277 | print(('minCutoff is None', evalResults)) 278 | return evalResults[minCutoff][0] 279 | 280 | 281 | def getHalfPoint(scores): 282 | """ 283 | assuming than the score distribution is linear initially 284 | then 3/4 of the scores should take up at least 1/2 of the L-method sweetspot 285 | this is an optimization technique 286 | :type scores: List[float] 287 | :rtype: int 288 | return the index after which we don't need to consider 289 | """ 290 | values = [x[1] for x in scores] 291 | total = sum(values) * 3 / 4 292 | cur = 0 293 | idx = 0 294 | for (idx, score) in scores: 295 | cur += score 296 | if cur > total: 297 | break 298 | # print('half point stats', idx, min(values), max(values)) 299 | return idx 300 | 301 | 302 | def getMutualInfoScore(clusters, sid_seq, idfMap, idxToSid, interestedCids, 303 | currentExclusions): 304 | """ 305 | used to calculate mutual information score for each feature 306 | cid_pattern_cnt records for each cluster the sum of each features 307 | :type clusters: List[tuple] 308 | - a list of cluster tuples for the clusters we wan to study 309 | :type sid_seq: Dict{int:Dict{str:int}} 310 | - for each user, record the pattern and corresponding occurence # 311 | :type idfMap: Dict{str:float} 312 | - the idf value for all patterns 313 | :type idxToSid: List[int] 314 | - map matrix index to stream id 315 | :type interestedCids: List[int] 316 | - cluster ids for clusters we want to study 317 | :type currentExclusions: List[str] 318 | - the patterns already pruned 319 | :rtype: Dict{int: List[(str, float)]} 320 | - a map of cid and (feature, score) list 321 | """ 322 | cid_pattern_cnt = {} 323 | cid_user_cnt = {} 324 | for cluster in clusters: 325 | cid = cluster[3] 326 | # get the sorted list of all sids in the cluster 327 | sids = sorted([idxToSid[nidx] for nidx in cluster[0]]) 328 | # sids = [x + 1 for x in sids] # add one to sid to get the actual sids 329 | feqMap = {} 330 | for sid in sids: 331 | for word in sid_seq[sid]: 332 | freq = sid_seq[sid][word] 333 | try: 334 | feqMap[word] += float(freq) 335 | # feqMap[word] += 1 336 | except: 337 | feqMap[word] = float(freq) 338 | # feqMap[word] = 1 339 | for word in currentExclusions: 340 | if word in feqMap: 341 | del feqMap[word] 342 | for word in feqMap: 343 | feqMap[word] *= idfMap[word] 344 | cid_pattern_cnt[cid] = feqMap 345 | cid_user_cnt[cid] = len(sids) 346 | return mutual_info.mutual_info_feature(cid_pattern_cnt, 347 | interested_cids=interestedCids) 348 | 349 | 350 | def getChiSquareScore(clusters, sid_seq, idfMap, idxToSid, interestedCids, 351 | currentExclusions): 352 | """ 353 | used to calculate chi square statistics for each feature 354 | :type clusters: List[tuple] 355 | - a list of cluster tuples for the clusters we wan to study 356 | :type sid_seq: Dict{int:Dict{str:int}} 357 | - for each user, record the pattern and corresponding occurence # 358 | :type idfMap: Dict{str:float} 359 | - the idf value for all patterns 360 | :type idxToSid: List[int] 361 | - map matrix index to stream id 362 | :type interestedCids: List[int] 363 | - cluster ids for clusters we want to study 364 | :type currentExclusions: List[str] 365 | - the patterns already pruned 366 | :rtype: Dict{int: List[(str, float)]} 367 | - a map of cid and (feature, score) list 368 | """ 369 | # chi_pattern_list records a list of feature weight for all instances 370 | # in the cluster 371 | cid_pattern_list = {} 372 | # chi_user_cnt records for each cluster the number of instances 373 | cid_user_cnt = {} 374 | for cluster in clusters: 375 | cid = cluster[3] 376 | # get the sorted list of all sids in the cluster 377 | sids = sorted([idxToSid[nidx] for nidx in cluster[0]]) 378 | # add one to sid to get the actual sids 379 | # sids = [x + 1 for x in sids] 380 | # print('in get chisquare') 381 | # print(sids) 382 | feqMap = {} 383 | for sid in sids: 384 | for word in sid_seq[sid]: 385 | if word in currentExclusions: 386 | continue 387 | idf = idfMap[word] 388 | freq = sid_seq[sid][word] 389 | try: 390 | feqMap[word].append(float(freq) * idf) 391 | except: 392 | feqMap[word] = [float(freq) * idf] 393 | for word in currentExclusions: 394 | if word in feqMap: 395 | del feqMap[word] 396 | cid_user_cnt[cid] = len(sids) 397 | cid_pattern_list[cid] = feqMap 398 | return mutual_info.chi_square_feature(cid_pattern_list, cid_user_cnt, 399 | interested_cids=interestedCids) 400 | 401 | 402 | def getExclusionMap(clusters, sid_seq, idfMap, idxToSid, interestedCids, 403 | currentExclusions=[]): 404 | """ 405 | determine which features to exclude 406 | :type clusters: List[tuple] 407 | - a list of cluster tuples for the clusters we wan to study 408 | :type sid_seq: Dict{int:Dict{str:int}} 409 | - for each user, record the pattern and corresponding occurence # 410 | :type idfMap: Dict{str:float} 411 | - the idf value for all patterns 412 | :type idxToSid: List[int] 413 | - map matrix index to stream id 414 | :type interestedCids: List[int] 415 | - cluster ids for clusters we want to study 416 | :type currentExclusions: List[str] 417 | - the patterns already pruned 418 | :rtype exclusionMap: Dict{int:List[str]} 419 | - list of features to exclude for each clusters 420 | :rtype exclusionScoreMap: Dict{int:List[float]} 421 | - score of the excluded feature for each clusters 422 | :rtype scoreMap: Dict{int:List[(str,float)]} 423 | - all the features and their scores for each clusters 424 | """ 425 | global excluTotal, excluLTotal 426 | # return dict([(row[3], []) for row in clusters]), {} 427 | excluStart = time.time() 428 | try: 429 | excluMethod = exclusionMethod 430 | except: 431 | excluMethod = 'chi' 432 | if excluMethod == 'chi': 433 | scoreMap = getChiSquareScore(clusters, sid_seq, idfMap, idxToSid, 434 | interestedCids, currentExclusions) 435 | elif excluMethod == 'mutual': 436 | scoreMap = getMutualInfoScore(clusters, sid_seq, idfMap, idxToSid, 437 | interestedCids, currentExclusions) 438 | else: 439 | return dict([(cid, []) for cid in interestedCids]), None 440 | # print('get exclusion taking %.4f' % (time.time() - excluStart)) 441 | excluTotal += time.time() - excluStart 442 | 443 | excluLStart = time.time() 444 | 445 | exclusionMap = {} 446 | exclusionScoreMap = {} 447 | # print('dumping score map') 448 | # json.dump(scoreMap, open('scoreMap.json', 'w')) 449 | for cid in scoreMap: 450 | # using the L method to determine sweetspot 451 | scores = [(idx, scoreMap[cid][idx][1]) 452 | for idx in range(len(scoreMap[cid]))] 453 | # get the point where 75% of all scores are covered 454 | halfpoint = getHalfPoint(scores) 455 | # if the estimated maximum cut point is higher, use it, 456 | # otherwise use 200 457 | # this is because we don't expect the number of features 458 | # to be more than 200 459 | # so the halfpoint is just a precausion in case extreme cases happens 460 | breakPoint = getSweetSpotL(scores[:max(200, 2 * halfpoint)]) 461 | # print('[LOG]: scores length %d, breakPoint %d' % (len(scores), breakPoint)) 462 | 463 | # print(breakPoint) 464 | exclusionMap[cid] = [scoreMap[cid][idx] 465 | for idx in range(int(breakPoint + 1)) 466 | if idx <= breakPoint and idx < len(scoreMap[cid])] 467 | # print(exclusionMap[cid]) 468 | exclusionScoreMap[cid] = [x[1] for x in exclusionMap[cid]] 469 | exclusionMap[cid] = [x[0] for x in exclusionMap[cid]] 470 | # print(exclusionMap) 471 | # exit(0) 472 | # print('get exclusion cut point taking %.4f' % (time.time() - excluLStart)) 473 | excluLTotal += time.time() - excluLStart 474 | 475 | return exclusionMap, exclusionScoreMap, scoreMap 476 | 477 | 478 | def modularityBasics(matrix): 479 | """ 480 | compute the basic values needed during modularity calculate 481 | so that we don't need to calculate it again and again 482 | :type matrix: List[List(int)] 483 | :rtype sumAll: int 484 | - the sum of all distances in the matrix 485 | :rtype sumEntries: List[int] 486 | - the sum of each row in the matrix 487 | """ 488 | sumAll = 0 489 | sumEntries = array('L') 490 | totalItems = len(matrix) 491 | rowIdx = 0 492 | for row in matrix: 493 | sumEntry = sum([100 - row[idx] for idx in range(totalItems) 494 | if not idx == rowIdx]) 495 | sumEntries.append(sumEntry) 496 | sumAll += sumEntry 497 | rowIdx += 1 498 | return (sumAll, sumEntries) 499 | 500 | 501 | def evaluateModularity(clusters, outPath, matrix, basicInfo): 502 | """ 503 | calculate the modularity given cluster division 504 | :type clusters: List[tuple] 505 | - a list of cluster tuples for the clusters we wan to study 506 | :type outPath: str (not used) 507 | :type matrix: List[List[int]] 508 | - distance matrix 509 | :type basicInfo: (sumAll, sumEntries) 510 | :type sumAll: int 511 | - the sum of all distances in the matrix 512 | :type sumEntries: List[int] 513 | - the sum of each row in the matrix 514 | :rtype: float 515 | """ 516 | # startTime = time.time() 517 | sumAll, sumEntries = basicInfo 518 | m = float(sumAll) 519 | firstEntry = 0 520 | secondEntry = 0 521 | for cluster in clusters: 522 | nodes = cluster[0] 523 | for nodeA in nodes: 524 | row = matrix[nodeA] 525 | for nodeB in nodes: 526 | firstEntry += 100 - row[nodeB] 527 | secondEntry += sumEntries[nodeA] * sumEntries[nodeB] 528 | for nodeA in nodes: 529 | firstEntry -= 100 - matrix[nodeA][nodeA] 530 | return (firstEntry - secondEntry / m) / m 531 | 532 | 533 | def evaluateModularityShift(clusterPair, matrix, basicInfo): 534 | """ 535 | the given cluster pair is the only change from the original clusterings 536 | which means this pair is splitted, calculate the resulting modularity 537 | so the firstEntry should shift by 538 | -2 * sum of (100-node) for each node pair in clusterA * clusterB space 539 | the secondEntry should shift by 540 | -2 * sum of sumEntries[A] * sumEntries[B] for each node pair in the 541 | clusterA * clusterB space 542 | :type clusterPair: List[List[int]] 543 | - two lists of user ids for two clusters resulted from split 544 | :type matrix: List[List[int]] 545 | - distance matrix 546 | :type basicInfo: (sumAll, sumEntries) 547 | :rtype: float 548 | """ 549 | sumAll, sumEntries = basicInfo 550 | m = float(sumAll) 551 | firstEntry = 0 552 | secondEntry = 0 553 | for nodeA in clusterPair[0]: 554 | row = matrix[nodeA] 555 | for nodeB in clusterPair[1]: 556 | firstEntry += 100 - row[nodeB] 557 | secondEntry += sumEntries[nodeA] * sumEntries[nodeB] 558 | return -2 * (firstEntry - secondEntry / m) / m 559 | 560 | 561 | def slidingMaxSweetSpot(evalResults, windowSize=5): 562 | """ 563 | finding the maximum according to moving window 564 | :type evalResults: Dict{int:float} 565 | - for each k, records the corresponding modularity 566 | :type windowSize: int 567 | :rtype: int 568 | - the index of the maximum value 569 | """ 570 | step = 1 571 | keys = [x[0] for x in list(evalResults.items())] 572 | start = min(keys) # + 0.5 * windowSize 573 | end = max(keys) # - 0.5 * windowSize 574 | if (start >= end): 575 | print('[WARNING]: window too large when trying to determine sweetspot') 576 | return (start + end) / 2 577 | maxEval = min([x[1] for x in list(evalResults.items())]) 578 | maxIdx = None 579 | while(start <= end): 580 | evals = [evalResults[idx] for idx in keys 581 | if start - 0.5*windowSize <= idx <= start + 0.5*windowSize] 582 | if len(evals) == 0: 583 | start += step 584 | continue 585 | avgEval = float(sum(evals)) / len(evals) 586 | # print start, avgEval 587 | if maxEval < avgEval: 588 | maxEval = avgEval 589 | maxIdx = start 590 | start += step 591 | return int(maxIdx + 0.5) 592 | 593 | 594 | def getSweetSpot(evalResults, windowSize=5): 595 | """ 596 | find out the best modularity, in this case, using slidingMaxSweetSpot 597 | :type evalResults: Dict{int:float} 598 | - for each k, records the corresponding modularity 599 | :type windowSize: int 600 | :rtype: int 601 | - the index of the maximum value 602 | """ 603 | result = slidingMaxSweetSpot(evalResults, windowSize) 604 | return result 605 | 606 | 607 | def excludeFeatures(idfMap, exclusions): 608 | """ 609 | change idfMap so that the features excluded have no weight 610 | :type idfMap: Dict{str:float} 611 | - the idf value for all patterns 612 | :type exclusions: List[str] 613 | - list of features excluded 614 | """ 615 | for feature in exclusions: 616 | idfMap[feature] = 0 617 | return idfMap 618 | 619 | 620 | def getGini(scoreList): 621 | """ 622 | get Gini coefficient of the chi-square / mutual info scores 623 | deterine whether it is skewed 624 | we assume that the input list is sorted reversely 625 | :type scoreList: List[float] 626 | :rtype: float 627 | """ 628 | totalScore = sum(scoreList) 629 | if totalScore == 0: return -1 630 | totalItem = len(scoreList) 631 | B = sum([scoreList[idx] * (0.5 + idx) for idx in range(totalItem)]) 632 | B = float(B) / totalScore / totalItem 633 | A = 0.5 - B 634 | return A / (A + B) 635 | 636 | 637 | # starting from full set 638 | def runDiana(outPath, sid_seq, matrix=None, matrixPath='tmpMatrix.dat', 639 | idxToSid=None, totalItems=None, exclusions=[], clusterNum=-1): 640 | """ 641 | Perform recursive hierarchical clustering 642 | :type outPath: str 643 | - the path to store the output and temporary file 644 | :type sid_seq: Dict{int:Dict{str:int}} 645 | - for each user, record the pattern and corresponding occurence # 646 | :type matrix: List[List[int]] (default: None) 647 | - distance matrix, None means to be computed 648 | :type matrixPath: str (default: tmpMatrix.dat) 649 | - the path to store the resulting matrix, if matrix already 650 | computed, provide it 651 | :type idxToSid: List[int] (default: None) 652 | - map matrix index to stream id, None means 1 to total instances 653 | :type totalItems: int (default: None) 654 | - total number of users to be clustered, None: the size of matrix 655 | :type exclusions: List[str] (default: []) 656 | - list of features excluded 657 | :type clusterNum: int (default: -1) 658 | - specify only when you don't want to be recursive computation 659 | and already know the number of clusters needed 660 | :rtype: a tree of the final clustering result 661 | """ 662 | global splitTotal 663 | global modularityTotal 664 | global matrixCompTotal 665 | 666 | startTime = time.time() 667 | 668 | # fEval = open('%seval.txt' % (outPath), 'a+') 669 | 670 | idfMap = None 671 | 672 | isRoot = False 673 | 674 | # if the distance matrix is not provided, we will assume that it is 675 | # the full matrix and try to generat it 676 | if not matrix: 677 | matrix = [] 678 | count = 1 679 | # isRoot = True 680 | rootResultPath = '%sroot_cluster.json' % \ 681 | outPath[:outPath.rindex('/') + 1] 682 | if not idxToSid: 683 | idxToSid = [x+1 for x in range(len(sid_seq))] 684 | 685 | if (matrixPath is None or not os.path.isfile(matrixPath)): 686 | # we don't need the full matrix 687 | # # write the full distance matrix 688 | # calculateDistance.fullMatrix(ngramPath, matrixPath) 689 | 690 | matrixStart = time.time() 691 | 692 | # generate the partical matrix and dump it into the file 693 | idfMap = excludeFeatures(getIdf(sid_seq, idxToSid), exclusions) 694 | matrix = calculateDistance.partialMatrix( 695 | idxToSid, idfMap, ngramPath, 'tmp_%s_root' % int(time.time()), 696 | outPath, True) 697 | if matrixPath: 698 | fout = open(matrixPath, 'w') 699 | for row in matrix: 700 | fout.write('%s\n' % ('\t'.join(map(str, row)))) 701 | fout.close() 702 | print(('computing matrix taking %fs' % (time.time() - matrixStart))) 703 | print(('matrix size %s' % len(matrix))) 704 | matrixCompTotal += time.time() - matrixStart 705 | else: 706 | # read the full distance matrix (after tf-idf) 707 | for line in open(matrixPath): 708 | matrix.append(array('B', list(map(int, line.split('\t'))))) 709 | count += 1 710 | if (count % 500 == 0): 711 | print(('%d lines read' % count)) 712 | 713 | # idf map will later be used in feature selection 714 | if not idfMap: 715 | idfMap = excludeFeatures(getIdf(sid_seq, idxToSid), exclusions) 716 | matrixBasics = modularityBasics(matrix) 717 | 718 | # for the full matrix, the sid is a faithful mapping 719 | if not idxToSid: 720 | idxToSid = [x+1 for x in range(len(matrix))] 721 | baseMatrix = matrix 722 | 723 | if not totalItems: 724 | totalItems = len(matrix) 725 | 726 | cid = 1 727 | clusters = [(list(range(len(matrix))), 100, None, cid)] 728 | 729 | # child Cid => parent Cid 730 | clusterHi = [] 731 | 732 | # record the evaluation metrics 733 | evalResults = {} 734 | 735 | # if the root cluster is already stored and calculated, just read it 736 | if isRoot and os.path.isfile(rootResultPath): 737 | rootResult = json.load(open(rootResultPath)) 738 | clusters = rootResult[0] 739 | sweetSpot = 0 740 | evalResults[0] = rootResult[1] 741 | else: 742 | # import cProfile 743 | # run until the biggest cluster is too small 744 | # TODO: add other stopping conditions, e.g. sweet spot 745 | # while clusters[-1][1]: 746 | # run untill there is a small cluster, then stop 747 | while clusters[-1][1] and \ 748 | len(clusters[-1][0]) > sizeThreshold * totalItems: 749 | # while clusters[-1][1]: 750 | # record the splitting tree 751 | parentCid = clusters[-1][3] 752 | clusterHi.append((parentCid, cid + 1, cid + 2)) 753 | 754 | splitStartTime = time.time() 755 | # cProfile.runctx('splitCluster(clusters.pop(), baseMatrix)', globals(), locals()) 756 | # exit(0) 757 | (clusterA, clusterB, baseSum) = ( 758 | splitCluster(clusters.pop(), baseMatrix)) 759 | # print('splitting cluster %f, %d' % (time.time() - splitStartTime, len(clusters))) 760 | splitTotal += time.time() - splitStartTime 761 | 762 | cid += 1 763 | clusters.append((clusterA, getDia(clusterA, baseMatrix), 764 | baseSum, cid)) 765 | cid += 1 766 | clusters.append((clusterB, getDia(clusterB, baseMatrix), 767 | None, cid)) 768 | 769 | # order first by diameter, then by size 770 | clusters = \ 771 | sorted(clusters, key=lambda x: (x[1], len(x[0])) 772 | if len(x[0]) > sizeThreshold * totalItems else (0, 0)) 773 | 774 | moduStartTime = time.time() 775 | if len(clusters) == 2: 776 | # if it is the first time to compute modularity 777 | evalResult = evaluateModularity(clusters, outPath, 778 | baseMatrix, matrixBasics) 779 | else: 780 | # if it is based on the previous scores 781 | evalResult = evalResults[len(clusters) - 1] + \ 782 | evaluateModularityShift((clusterA, clusterB), 783 | baseMatrix, matrixBasics) 784 | # print('evaluateClustersModularity %f' % (time.time() - moduStartTime)) 785 | modularityTotal += time.time() - moduStartTime 786 | # print(evalResult, moduResult, orgResult) 787 | evalResults[len(clusters)] = evalResult 788 | 789 | # if the clusterNum is specified, 790 | # do a simple clustering without hierarchy 791 | if clusterNum > 0: 792 | sweetSpot = clusterNum 793 | else: 794 | sweetSpot = getSweetSpot(evalResults) 795 | print(('[LOG]: split %s into %d clusters (modularity %f)' % 796 | (outPath, sweetSpot, evalResults[sweetSpot]))) 797 | 798 | # merge the clusters to the point of sweet spot 799 | clusterMap = dict([(row[3], row) for row in clusters]) 800 | while(len(clusters) > sweetSpot): 801 | (parentCid, childACid, childBCid) = clusterHi.pop() 802 | # dismeter doesn't matter, so put zero here 803 | clusterMap[parentCid] = \ 804 | (clusterMap[childACid][0] + clusterMap[childBCid][0], 805 | 0, None, parentCid) 806 | clusters.append(clusterMap[parentCid]) 807 | clusters.remove(clusterMap[childACid]) 808 | clusters.remove(clusterMap[childBCid]) 809 | 810 | if isRoot and not os.path.isfile(rootResultPath): 811 | json.dump([clusters, evalResults[sweetSpot]], 812 | open(rootResultPath, 'w')) 813 | 814 | # get the exclusion map according to the current clustering 815 | # excludeMap, scoreMap = getExclusionMap(clusters, sid_seq, idfMap, idxToSid, \ 816 | # [row[3] for row in clusters if len(row[0]) > sizeThreshold * totalItems], exclusions) 817 | excludeMap, exclusionScoreMap, scoreMap = \ 818 | getExclusionMap(clusters, sid_seq, idfMap, idxToSid, 819 | [row[3] for row in clusters], exclusions) 820 | # fEval.write(json.dumps(scoreMap)) 821 | 822 | # for each cluter, we start a new clustering 823 | results = [] 824 | # print([len(cluster[0]) for cluster in clusters]) 825 | for cidx in range(len(clusters)): 826 | row = clusters[cidx] 827 | idxs = row[0] # get the list of all node in the cluster 828 | # get the sorted list of all sids in the cluster 829 | sids = sorted([idxToSid[nidx] for nidx in idxs]) 830 | excludedFeatures = excludeMap[row[3]] 831 | excludedScores = exclusionScoreMap[row[3]] 832 | # if we want to continute cluster this subcluster 833 | if len(sids) > sizeThreshold * totalItems: 834 | newExclusions = exclusions + excludedFeatures 835 | # remove sids where the vector have all zeros 836 | newExclusionSet = set(newExclusions) 837 | oldLen = len(sids) 838 | 839 | def curFeatures(sid): 840 | return set(sid_seq[sid].keys()) 841 | 842 | excludedSids = [sid for sid in sids 843 | if len(curFeatures(sid) - newExclusionSet) == 0] 844 | sids = [sid for sid in sids 845 | if len(curFeatures(sid) - newExclusionSet) > 0] 846 | # print(oldLen, len(sids), len(excludedFeatures), excludedFeatures) 847 | # if the cluster size is too small after feature selection, 848 | # don't cluster it 849 | if not len(sids) > sizeThreshold * totalItems: 850 | result = ('l', sids + excludedSids, 851 | {'exclusions': excludedFeatures, 852 | 'exclusionsScore': excludedScores}) 853 | else: 854 | matrixStart = time.time() 855 | matrix = calculateDistance.partialMatrix( 856 | sids, 857 | excludeFeatures(getIdf(sid_seq, sids), newExclusions), 858 | ngramPath, 859 | 'tmp_%d' % row[3], '%st%d_' % (outPath, row[-1]), True) 860 | # print('computing matrix taking %fs' % (time.time() - matrixStart)) 861 | matrixCompTotal += time.time() - matrixStart 862 | # now that we have a new distance matrix, go and do another 863 | # round of clustering 864 | result = runDiana('%sp%d_' % (outPath, row[-1]), sid_seq, 865 | matrix, idxToSid=sids, totalItems=totalItems, 866 | exclusions=newExclusions) 867 | if len(result) > 2: 868 | info = result[2] 869 | else: 870 | info = {} 871 | # put the excluded sids back as a cluster 872 | if (len(excludedSids) > 0): 873 | result[1].append(('l', excludedSids, {'isExclude': True})) 874 | 875 | info['exclusions'] = excludedFeatures 876 | info['exclusionsScore'] = excludedScores 877 | # base on the score map, calculate the gini coefficient 878 | # score map format {cid:[(feature, score)]} 879 | info['gini'] = getGini([x[1] for x in scoreMap[row[3]]]) 880 | # fEval.write('gini %s : %f\n' % ('%sp%d_' % (outPath, row[3]), info['gini'])) 881 | result = (result[0], result[1], info) 882 | else: 883 | result = ('l', sids, {'exclusions': excludedFeatures, 884 | 'exclusionsScore': excludedScores}) 885 | 886 | results.append(result) 887 | 888 | return ('t', results, {'sweetspot': evalResults[sweetSpot]}) 889 | 890 | 891 | def richerTree(tree, sidUidM, startCid=1): 892 | """ 893 | This function is not called, because it is for clickstream use only! 894 | contructe a json representation of the final clustering result 895 | including uids, excluded features, gini coeff, etc. 896 | :type tree: the tree result from runDiana 897 | :type sidUidM: Dict{int:List[str]} 898 | - map sid to user ids, note that one sid can map to multiple users 899 | :type startCid: int 900 | - the numbering scheme of cluster id 901 | :rtype: a tree with nicer format, and map stream id back to user 902 | """ 903 | if tree[0] == 'l': 904 | if len(tree[1]) == 0: 905 | return startCid, None 906 | uids = reduce(lambda x, y: x + y, [sidUidM[sid] for sid in tree[1]]) 907 | if len(tree) == 3: 908 | result = tree[2] 909 | else: 910 | result = {} 911 | result['type'] = 'l' 912 | result['uids'] = uids 913 | # result['clusterId'] = startCid 914 | return startCid + 1, result 915 | subTrees = [] 916 | for subTree in tree[1]: 917 | startCid, newSubTree = richerTree(subTree, sidUidM, startCid) 918 | if newSubTree: 919 | subTrees.append(newSubTree) 920 | if len(tree) == 3: 921 | result = tree[2] 922 | else: 923 | result = {} 924 | result['type'] = 't' 925 | result['children'] = subTrees 926 | return startCid, result 927 | 928 | 929 | def run(sid_seq, outPath, matrixPath, sids, nPath): 930 | """ 931 | this function is a simpler version of the main function 932 | it is a wrapper around runDiana 933 | intended to be used for rhcBootstrap (my testing script) 934 | :type sid_seq: Dict{int:Dict{str:int}} 935 | - for each user, record the pattern and corresponding occurence # 936 | :type outPath: str 937 | - the path to store the output and temporary file 938 | :type matrixPath: str (default: tmpMatrix.dat) 939 | - the path to store the root matrix for this clustering 940 | :type sids: List[int] 941 | - the users we want to study, identified by sid 942 | :type nPath: str 943 | - the path to the computed pattern dataset 944 | """ 945 | global sizeThreshold 946 | global ngramPath 947 | ngramPath = nPath 948 | sizeThreshold = 0.05 949 | return runDiana(outPath, sid_seq, None, matrixPath, sorted(sids)) 950 | 951 | 952 | def create_output_dir(path): 953 | if not os.path.exists(path): 954 | os.makedirs(path) 955 | return True 956 | 957 | # store the total time needed to compute distance matrix 958 | matrixCompTotal = 0 959 | # store the total time needed to compute modularity 960 | modularityTotal = 0 961 | # store the total time needed to split clusters 962 | splitTotal = 0 963 | # store the total time needed to calculate feature scores for exclusion 964 | excluTotal = 0 965 | # store the total time needed to find the sweet spot to exclude feature 966 | excluLTotal = 0 967 | 968 | if __name__ == '__main__': 969 | 970 | ngramPath = sys.argv[1] 971 | outPath = sys.argv[2] 972 | sizeThreshold = float(sys.argv[3]) if len(sys.argv) > 3 else 0.05 973 | 974 | matrixPath = '%smatrix.dat' % outPath 975 | resultPath = '%sresult.json' % outPath 976 | 977 | startTime = time.time() 978 | create_output_dir(outPath) 979 | sid_seq = getSidNgramMap(ngramPath) 980 | print(('[LOG]: total users %d' % len(sid_seq))) 981 | treeData = runDiana(outPath, sid_seq, matrixPath=matrixPath) 982 | json.dump(treeData, open(resultPath, 'w')) 983 | print(('[STAT]: total time %f' % (time.time() - startTime))) 984 | print((('[STAT]: maxtrix com: %f, modularity: %f, split: %f, ' 985 | 'exclusion score: %f, exclusion cut: %f') % 986 | (matrixCompTotal, modularityTotal, splitTotal, excluTotal, 987 | excluLTotal))) 988 | -------------------------------------------------------------------------------- /recursiveHierarchicalClusteringFast.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | 3 | """ 4 | the script is a modification of recursiveHierarchicalClustering.py 5 | It make better use of the matrix computation in numpy 6 | and thus has improved speed 7 | 8 | # arguments 9 | 10 | arg1: path to a file containing the different ngram count mapping 11 | example: 12 | 10 \t A5A(1)y8y(29)... 13 | the first col is line number 14 | the second col is a list of pattern(count) 15 | 16 | arg2: path to a directory to put the output file 17 | 18 | arg3: sizeThreshold, defines the minimum size of the cluster, that we 19 | are going to further divide 20 | deafult: 0.05: means the size cannot be less than 5% of the total 21 | instances 22 | 23 | # result: 24 | 25 | resultDir/matrix.dat: store the pairwise distance matrix 26 | if the file exist before the scirpt is run, the script assume the matrix 27 | is correct and will read it in 28 | resultDir/result.json: store the clustering result 29 | the result is recorded in a nested list, in the form of: 30 | [type, list of sub-clusters, information about the cluster] 31 | """ 32 | 33 | import sys 34 | import json 35 | import time 36 | # import cProfile 37 | import pickle 38 | import numpy as np 39 | import recursiveHierarchicalClustering as rhc 40 | import calculateDistanceInt as calculateDistance 41 | import os 42 | 43 | class HCClustering: 44 | 45 | def __init__(self, matrix, sid_seq, outPath, exclusions, idxToSid, 46 | sizeThreshold, idfMap=None): 47 | self.matrix = matrix 48 | self.sizeThreshold = sizeThreshold 49 | self.maxDistance = 100 50 | self.sid_seq = sid_seq 51 | self.outPath = outPath 52 | self.exclusions = exclusions 53 | if not idxToSid: 54 | idxToSid = [x+1 for x in range(len(sid_seq))] 55 | self.idxToSid = idxToSid 56 | if not idfMap: 57 | idfMap = rhc.excludeFeatures(rhc.getIdf(sid_seq, idxToSid), exclusions) 58 | self.idfMap = idfMap 59 | 60 | def getDia(self, cid, cluster): 61 | """ 62 | find out cluster diameter 63 | :type cid: int 64 | - cluter id 65 | :type cluster: List[int] 66 | - all the stream ids in the cluster 67 | :rtype: int 68 | - the diameter of the cluster 69 | """ 70 | startTime = time.time() 71 | sumDists = self.sumEntriesMap[cid] 72 | maxIdx = np.argmax(sumDists) 73 | 74 | maxDist = np.max(self.matrix[cluster[maxIdx]][cluster]) 75 | total = len(cluster) 76 | for idx in range(len(cluster)): 77 | sumDist = sumDists[idx] 78 | # optimization: prune out rows inpossible to have diameter 79 | if (sumDist * 2) < (maxDist * total): 80 | continue 81 | curMax = np.max(self.matrix[cluster[idx]][cluster]) 82 | if curMax > maxDist: 83 | maxDist = curMax 84 | return maxDist 85 | 86 | def splitCluster(self, cluster_info): 87 | """ 88 | :type baseCluster: List[int] 89 | - take in the cluster to be splited as a list of stream index 90 | :type diameter: int (not used) 91 | :type cid: int (cluster id, not used) 92 | 93 | :rtype: (baseCluster, newCluster, sumEntryA, sumEntryB, sumAB) 94 | :rtype baseCluster: List[int] 95 | - a list of stream index in one part of the split (clusterA) 96 | :rtype newCluster: List[int] 97 | - a list of stream index in the other part of the split (clusterB) 98 | :rtype sumEntryA: List[int] 99 | - sum of each row for clusterA 100 | :rtype sumEntryB: List[int] 101 | - sum of each row for clusterB 102 | :rtype sumAB: float 103 | - sum of all pairwise distance between clusterA and clusterB 104 | """ 105 | (baseCluster, diameter, cid) = cluster_info 106 | newCluster = [] 107 | # the number of nodes in the base cluster 108 | baseNodes = totalNodes = len(baseCluster) 109 | sumDists = self.sumEntriesMap[cid] 110 | newDists = np.zeros(totalNodes, dtype=np.float64) 111 | 112 | # all reasoning about the process below is written in 113 | # recursiveHierarchicalClustering.py 114 | while baseNodes > 1: 115 | # print('%d nodes left' % baseNodes) 116 | newNodes = totalNodes - baseNodes 117 | if baseNodes == totalNodes: 118 | difDist = sumDists 119 | maxIdx = np.argmax(difDist) 120 | maxValue = difDist[maxIdx] 121 | else: 122 | diffs = (sumDists - newDists) * newNodes - \ 123 | newDists * (baseNodes - 1) 124 | maxIdx = np.argmax(diffs) 125 | maxValue = diffs[maxIdx] 126 | if maxValue <= 0: 127 | break 128 | newCluster.append(maxIdx) 129 | 130 | # update the distance to new cluster for all nodes not in the cluster 131 | newDists = newDists + self.matrix[baseCluster[maxIdx]][baseCluster] 132 | # ensure that nodes in the new cluster will never be selected 133 | newDists[maxIdx] += self.maxDistance * totalNodes 134 | baseNodes -= 1 135 | 136 | clusterAIdx = newCluster 137 | clusterBIdx = np.delete(np.arange(totalNodes), clusterAIdx) 138 | sumEntryA = (newDists - self.maxDistance * totalNodes)[clusterAIdx] 139 | sumEntryB = (sumDists - newDists)[clusterBIdx] 140 | 141 | sumAB = np.sum(newDists[clusterBIdx], dtype=np.float64) 142 | baseCluster = np.array(baseCluster) 143 | 144 | return list(baseCluster[newCluster]), list(baseCluster[clusterBIdx]),\ 145 | sumEntryA, sumEntryB, sumAB 146 | 147 | def modularityBasics(self): 148 | """ 149 | compute the basic values needed during modularity calculate 150 | so that we don't need to calculate it again and again 151 | :type matrix: List[List(int)] 152 | :rtype sumAll: int 153 | - the sum of all distances in the matrix 154 | :rtype sumEntries: List[int] 155 | - the sum of each row in the matrix 156 | """ 157 | sumEntries = (self.maxDistance * len(self.matrix) - 158 | np.sum(self.matrix, axis=1, dtype=np.float64) - 159 | self.maxDistance) 160 | sumAll = np.sum(sumEntries) 161 | self.sumAll = sumAll 162 | self.sumEntries = sumEntries 163 | return sumAll, sumEntries 164 | 165 | def evaluateModularity(self, clusters, sumEntries): 166 | """ 167 | calculate the modularity given cluster division 168 | :type clusters: List[tuple] 169 | - a list of cluster tuples for the clusters we wan to study 170 | :type sumEntries: List[int] 171 | - the sum of each row in the matrix 172 | :rtype: float 173 | """ 174 | m = self.sumAll 175 | # for each cluster, compute the modularity 176 | # firstEntry is the intra cluster distance 177 | # second entry is rowSums product for each node pair in cluster 178 | firstEntry = 0.0 179 | secondEntry = 0.0 180 | for cluster, sumEntry in zip(clusters, sumEntries): 181 | nodes = np.array(cluster) 182 | firstEntry += self.maxDistance * len(nodes) ** 2 - \ 183 | np.sum(sumEntry, dtype=np.float64) 184 | 185 | for nodeA in nodes: 186 | firstEntry -= self.maxDistance - self.matrix[nodeA][nodeA] 187 | sumRowCur = self.sumEntries[nodes] 188 | secondEntry += np.sum(sumRowCur) ** 2 189 | return (firstEntry - secondEntry / m) / m 190 | 191 | def evaluateModularityShift(self, clusterAB, sumAB): 192 | """ 193 | the reasoning is detailed in recursiveHierarchicalClustering.py 194 | :type clusterA: List[int] 195 | - user ids for the first cluster resulted from split 196 | :type clusterB: List[int] 197 | - user ids for the second cluster resulted from split 198 | :type matrix: List[List[int]] 199 | - distance matrix 200 | :type sumAB: float 201 | - sum of all pairwise distance between clusterA and clusterB 202 | :rtype: float 203 | """ 204 | (clusterA, clusterB) = clusterAB 205 | m = self.sumAll 206 | firstEntry = (self.maxDistance * len(clusterA) * len(clusterB) - sumAB) 207 | secondEntry = np.sum(self.sumEntries[clusterA]) \ 208 | * np.sum(self.sumEntries[clusterB]) 209 | return -2 * (firstEntry - secondEntry / m) / m 210 | 211 | def runDiana(self): 212 | """ 213 | Perform recursive hierarchical clustering 214 | """ 215 | global matrixCompTotal, splitTotal, modularityTotal, diaTotal 216 | global excluTotal 217 | 218 | M = self.matrix 219 | self.modularityBasics() 220 | print('[LOG]: finished calculating modularityBasics') 221 | 222 | # child Cid => parent Cid 223 | clusterHi = [] 224 | 225 | # record the evaluation metrics 226 | evalResults = {} 227 | 228 | cid = 1 229 | clusters = [(list(range(len(self.matrix))), self.maxDistance, cid)] 230 | 231 | # get a mapping from cid => list of row sums for all ids in cluster 232 | self.sumEntriesMap = {} 233 | self.sumEntriesMap[cid] = np.sum(self.matrix, axis=1, dtype=np.float64) 234 | 235 | while clusters[-1][1] and len(clusters[-1][0]) > self.sizeThreshold: 236 | parentCid = clusters[-1][2] 237 | # print('splitting %s\t%s' % (clusters[-1][1],clusters[-1][2])) 238 | clusterHi.append((parentCid, cid + 1, cid + 2)) 239 | 240 | curTime = time.time() 241 | (clusterA, clusterB, sumEntryA, sumEntryB, sumAB) = \ 242 | (self.splitCluster(clusters.pop())) 243 | splitTotal += time.time() - curTime 244 | 245 | curTime = time.time() 246 | cid += 1 247 | self.sumEntriesMap[cid] = sumEntryA 248 | clusters.append((clusterA, self.getDia(cid, clusterA), cid)) 249 | # clusters.append((clusterA, np.mean(sumEntryA) / len(clusterA), cid)) 250 | cid += 1 251 | self.sumEntriesMap[cid] = sumEntryB 252 | clusters.append((clusterB, self.getDia(cid, clusterB), cid)) 253 | # clusters.append((clusterB, np.mean(sumEntryB) / len(clusterB), cid)) 254 | diaTotal += time.time() - curTime 255 | 256 | curTime = time.time() 257 | clusters = \ 258 | sorted(clusters, key=lambda x: (x[1], len(x[0])) 259 | if len(x[0]) > self.sizeThreshold else (0, 0)) 260 | if len(clusters) == 2: 261 | # if it is the first time to compute modularity 262 | evalResult = self.evaluateModularity( 263 | (clusterA, clusterB), (sumEntryA, sumEntryB)) 264 | else: 265 | # if it is based on the previous scores 266 | evalResult = evalResults[len(clusters) - 1] + \ 267 | self.evaluateModularityShift((clusterA, clusterB), sumAB) 268 | modularityTotal += time.time() - curTime 269 | 270 | # print(sorted([len(x[0]) for x in clusters], reverse = True)) 271 | # print(len(clusters[-1][0])) 272 | evalResults[len(clusters)] = evalResult 273 | # print('cluster num is %d, modularity %f' % (len(clusters), evalResult)) 274 | 275 | # print(evalResults) 276 | sweetSpot = rhc.getSweetSpot(evalResults, 5) 277 | sweetSpot = sorted(list(evalResults.keys()), 278 | key=lambda x: abs(x - sweetSpot))[0] 279 | print(('[LOG]: sweetSpot is %d, modularity %f' % 280 | (sweetSpot, evalResults[sweetSpot]))) 281 | 282 | # merge the clusters to the point of sweet spot 283 | clusterMap = dict([(row[2], row) for row in clusters]) 284 | cids = [(row[2]) for row in clusters] 285 | while(len(cids) > sweetSpot): 286 | (parentCid, childACid, childBCid) = clusterHi.pop() 287 | # dismeter doesn't matter, so put zero here 288 | clusterMap[parentCid] = \ 289 | (clusterMap[childACid][0] + clusterMap[childBCid][0], 290 | 0, parentCid) 291 | cids.append(parentCid) 292 | cids.remove(childACid) 293 | cids.remove(childBCid) 294 | 295 | # reconstruct the cluster list after merging 296 | clusters = [(x[0], x[1], None, x[2]) for cid, x in list(clusterMap.items()) 297 | if cid in cids] 298 | 299 | # get the exclusion map according to the current clustering 300 | startTime = time.time() 301 | excludeMap, exclusionScoreMap, scoreMap = \ 302 | rhc.getExclusionMap(clusters, self.sid_seq, self.idfMap, 303 | self.idxToSid, [row[3] for row in clusters], 304 | self.exclusions) 305 | excluTotal += time.time() - startTime 306 | 307 | # for each cluster, we start a new clustering 308 | results = [] 309 | for cidx in range(len(clusters)): 310 | row = clusters[cidx] 311 | idxs = row[0] # get the list of all node in clusters 312 | sids = sorted([self.idxToSid[nidx] for nidx in idxs]) 313 | excludedFeatures = excludeMap[row[3]] 314 | excludedScores = exclusionScoreMap[row[3]] 315 | 316 | # if we want to continue cluster this subcluster 317 | if len(sids) > self.sizeThreshold: 318 | newExclusions = self.exclusions + excludedFeatures 319 | # remove sids where the vector have all zeros 320 | newExclusionSet = set(newExclusions) 321 | oldLen = len(sids) 322 | excludedSids = [sid for sid in sids if len( 323 | set(self.sid_seq[sid].keys()) - newExclusionSet) == 0] 324 | sids = [sid for sid in sids if len( 325 | set(self.sid_seq[sid].keys()) - newExclusionSet) > 0] 326 | # if the cluster size is too small after feature selection, 327 | # don't cluster it 328 | # or if the cluster diameter is 0 329 | if not len(sids) > self.sizeThreshold: 330 | result = ('l', sids + excludedSids, 331 | {'exclusions': excludedFeatures, 332 | 'exclusionsScore': excludedScores}) 333 | else: 334 | matrixStart = time.time() 335 | matrix = calculateDistance.partialMatrix( 336 | sids, 337 | rhc.excludeFeatures(rhc.getIdf(self.sid_seq, sids), 338 | newExclusions), 339 | ngramPath, 340 | 'tmp_%d' % row[3], 341 | '%st%d_' % (self.outPath, row[-1]), 342 | True) 343 | matrixCompTotal += time.time() - matrixStart 344 | # after the matrix is calculated, we need to handle a 345 | # speacial case where all entries in the matrix is zero, 346 | # besically means if the first row of the 347 | # matrix adds up to zero 348 | # if this is the case, do not split the cluster 349 | if np.sum(matrix[0]) == 0: 350 | result = ('l', sids + excludedSids, 351 | {'exclusions': excludedFeatures, 352 | 'exclusionsScore': excludedScores}) 353 | else: 354 | # now that we have a new distance matrix, go and 355 | # do another round of clustering 356 | result = HCClustering( 357 | matrix, 358 | sid_seq, 359 | '%sp%d_' % (self.outPath, row[-1]), 360 | newExclusions, 361 | sids, 362 | self.sizeThreshold).runDiana() 363 | if len(results) > 2: 364 | info = result[2] 365 | else: 366 | info = {} 367 | 368 | # put the excluded sids back as a cluster 369 | if (len(excludedSids) > 0): 370 | result[1].append(('l', excludedSids, 371 | {'isExclude': True})) 372 | 373 | info['exclusions'] = excludedFeatures 374 | info['exclusionsScore'] = excludedScores 375 | # base on the score map, calculate the gini coefficient 376 | # score map format {cid:[(feature, score)]} 377 | # info['gini'] = getGini([x[1] for x in scoreMap[row[3]]]) 378 | result = (result[0], result[1], info) 379 | else: 380 | result = ('l', sids, 381 | {'exclusions': excludedFeatures, 382 | 'exclusionsScore': excludedScores}) 383 | results.append(result) 384 | 385 | return(('t', results, {'sweetspot': evalResults[sweetSpot]})) 386 | 387 | 388 | def run(ngramPath, sid_seq, outPath): 389 | """ 390 | this function is a simpler version of the main function 391 | it is a wrapper around runDiana 392 | intended to be used for rhcBootstrap (my testing script) 393 | :type ngramPath: str 394 | - the path to the computed pattern dataset 395 | :type sid_seq: Dict{int:Dict{str:int}} 396 | - for each user, record the pattern and corresponding occurence # 397 | :type outPath: str 398 | - the path to store the output and temporary file 399 | """ 400 | global matrixCompTotal 401 | 402 | startTime = time.time() 403 | 404 | idxToSid = [x+1 for x in range(len(sid_seq))] 405 | 406 | idfMap = rhc.excludeFeatures(rhc.getIdf(sid_seq, idxToSid), []) 407 | 408 | matrix = calculateDistance.partialMatrix( 409 | idxToSid, idfMap, ngramPath, 'tmp_%sroot' % int(time.time()), 410 | outPath, True) 411 | 412 | print(('[LOG]: first matrixTime %f' % (time.time() - startTime))) 413 | matrixCompTotal += time.time() - startTime 414 | 415 | hc = HCClustering( 416 | matrix, sid_seq, outPath, [], idxToSid, 417 | sizeThreshold=0.05 * len(sid_seq), idfMap=idfMap) 418 | result = hc.runDiana() 419 | 420 | print(('[STAT]: total clustering time %f' % (time.time() - startTime))) 421 | return result 422 | 423 | 424 | # store the total time needed to compute distance matrix 425 | matrixCompTotal = 0 426 | # store the total time needed to compute modularity 427 | modularityTotal = 0 428 | # store the total time needed to split clusters 429 | splitTotal = 0 430 | # store the total time needed to compute cluster diameter 431 | diaTotal = 0 432 | # store the total time needed to find out feature exclusion 433 | excluTotal = 0 434 | 435 | def create_output_dir(path): 436 | if not os.path.exists(path): 437 | os.makedirs(path) 438 | return True 439 | 440 | if __name__ == '__main__': 441 | 442 | ngramPath = sys.argv[1] 443 | outPath = sys.argv[2] 444 | sizeThreshold = float(sys.argv[3]) if len(sys.argv) > 3 else 0.05 445 | create_output_dir(outPath) 446 | startTime = time.time() 447 | sid_seq = rhc.getSidNgramMap(ngramPath) 448 | print(('[LOG]: total users %d' % len(sid_seq))) 449 | result = run(ngramPath, sid_seq, outPath) 450 | 451 | json.dump(result, open('%sresult.json' % outPath, 'w')) 452 | 453 | print(('[STAT]: total time %f' % (time.time() - startTime))) 454 | print((('[STAT]: maxtrix com: %f, dismeter: %f, modularity: %f, split: %f, ' 455 | 'exclusion: %f') % 456 | (matrixCompTotal, diaTotal, modularityTotal, splitTotal, excluTotal))) 457 | -------------------------------------------------------------------------------- /servers.json: -------------------------------------------------------------------------------- 1 | { 2 | "threadNum": 5, 3 | "minPerSlice": 1000, 4 | "server": 5 | ["localhost"] 6 | } -------------------------------------------------------------------------------- /vis/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/xychang/RecursiveHierarchicalClustering/7ffb814797a832c88b1c61a48a5591ce9b86a46e/vis/.DS_Store -------------------------------------------------------------------------------- /vis/css/whisper.css: -------------------------------------------------------------------------------- 1 | /* 2 | A Bootstrap 3.1 affix sidebar template 3 | from http://bootply.com 4 | 5 | This CSS code should follow the 'bootstrap.css' 6 | in your HTML file. 7 | 8 | license: MIT 9 | author: bootply.com 10 | */ 11 | 12 | .label a{ 13 | color: white; 14 | } 15 | body { 16 | /*padding-top:50px;*/ 17 | } 18 | 19 | #masthead { 20 | /*min-height:250px;*/ 21 | } 22 | 23 | #masthead h1 { 24 | font-size: 30px; 25 | line-height: 1; 26 | padding-top:20px; 27 | } 28 | 29 | #masthead .well { 30 | margin-top:8%; 31 | margin-bottom: -1em; 32 | } 33 | 34 | @media screen and (min-width: 768px) { 35 | #masthead h1 { 36 | font-size: 50px; 37 | } 38 | } 39 | 40 | .navbar-bright { 41 | background-color:#111155; 42 | color:#fff; 43 | } 44 | 45 | .affix-top,.affix{ 46 | position: static; 47 | } 48 | 49 | @media (min-width: 979px) { 50 | #sidebar.affix-top { 51 | position: static; 52 | margin-top:30px; 53 | width:228px; 54 | } 55 | 56 | #sidebar.affix { 57 | position: fixed; 58 | top:70px; 59 | width:228px; 60 | } 61 | } 62 | 63 | #sidebar li.active { 64 | border:0 #eee solid; 65 | border-right-width:5px; 66 | } 67 | 68 | /** start css for visulization */ 69 | 70 | #packed-chart .node { 71 | cursor: pointer; 72 | } 73 | 74 | #packed-chart .node.selected { 75 | stroke: #000; 76 | stroke-width: 3px; 77 | } 78 | 79 | #packed-chart .node--leaf { 80 | fill: white; 81 | } 82 | 83 | svg .label { 84 | font: 11px "Helvetica Neue", Helvetica, Arial, sans-serif; 85 | text-anchor: middle; 86 | text-shadow: 0 1px 0 #fff, 1px 0 0 #fff, -1px 0 0 #fff, 0 -1px 0 #fff; 87 | } 88 | 89 | #packed-chart svg .label, 90 | #packed-chart .node--root{ 91 | pointer-events: none; 92 | } 93 | 94 | .detail{ 95 | border: 3px solid #000; 96 | position: absolute; 97 | padding: 1em; 98 | /*width: 40%; */ 99 | background: rgba(255,255,255,0.97); 100 | white-space: pre-wrap; 101 | } 102 | 103 | .features .label{ 104 | margin-right: 0em; 105 | padding: .4em .6em .5em; 106 | font-weight: 400; 107 | } 108 | 109 | .timegap{ 110 | padding: 0 0.4em; 111 | } 112 | 113 | .features{ 114 | padding: 0; 115 | } 116 | 117 | ul{ 118 | list-style-type: none; 119 | } 120 | 121 | .feature svg { 122 | margin: 0.4em 0 -0.6em 0.4em; 123 | } 124 | 125 | .btn-comment{ 126 | float: right; 127 | margin-top: -1em; 128 | } 129 | 130 | .summary{ 131 | padding-top: .5em; 132 | padding-bottom: .3em; 133 | } 134 | 135 | .feature .action-PopularFeed{ 136 | background-color: #49262F; 137 | } 138 | 139 | .feature .action-ViewWhisper{ 140 | background-color: #A38B76; 141 | } 142 | 143 | .feature .action-Login{ 144 | background-color: #73747A; 145 | } 146 | 147 | .feature .action-Notification{ 148 | background-color: #363743; 149 | } 150 | 151 | .feature .action-Heart{ 152 | background-color: #726669; 153 | } 154 | 155 | .feature .action-Reply{ 156 | background-color: #5A6396; 157 | } 158 | 159 | .feature .action-Chat{ 160 | background-color: #382A54; 161 | } 162 | 163 | .feature .action-BannedaUserInChat{ 164 | background-color: #456D82; 165 | } 166 | 167 | .feature .action-BannedFromChat{ 168 | background-color: #3C6E6B; 169 | } 170 | 171 | .feature .action-ImageSuggest{ 172 | background-color: #655280; 173 | } 174 | 175 | .feature .action-ImageSearch{ 176 | background-color: #895F87; 177 | } 178 | 179 | .feature .action-Flag{ 180 | background-color: #55567C; 181 | } 182 | 183 | .feature .action-LatestFeed{ 184 | background-color: #527A91; 185 | } 186 | 187 | .feature .action-SchoolFeed{ 188 | background-color: #576F87; 189 | } 190 | 191 | .feature .action-WhisperUpload{ 192 | background-color: #B8878B; 193 | } 194 | 195 | .feature .action-NearbyFeed{ 196 | background-color: #8D90B0; 197 | } 198 | 199 | #counter{ 200 | position: fixed; 201 | top: 0; 202 | left: 0; 203 | padding: .5em; 204 | background: rgba(255,255,255,0.8); 205 | } 206 | 207 | .btn-close{ 208 | position: absolute; 209 | top: 0; 210 | right: 0; 211 | } 212 | 213 | #counter .btn{ 214 | margin-left: 1em; 215 | } 216 | 217 | .local-avg{ 218 | color: rgba(255,0,0,1); 219 | } 220 | 221 | .global-avg{ 222 | color: rgba(0, 128, 128, 1); 223 | } 224 | 225 | .no-wrap{ 226 | white-space: nowrap; 227 | } 228 | 229 | ul{ 230 | padding-left: 0; 231 | } 232 | 233 | li{ 234 | margin-top: .3em; 235 | } 236 | 237 | .feature p.condensed .label{ 238 | /* this is a hackish fix, I don't know why there is this spacing between labels */ 239 | margin-right: -.36em; 240 | } 241 | 242 | div.inline{ 243 | display: inline-block; 244 | margin-right: 1em; 245 | } 246 | 247 | #helper svg{ 248 | margin: 0em 0 -.1em 0em; 249 | } 250 | 251 | .h3{ 252 | margin-top: 2.5em; 253 | } 254 | 255 | #packed-chart{ 256 | width: 800px; 257 | /*float: left;*/ 258 | } 259 | 260 | .table.table-nonfluid{ 261 | width: auto; 262 | } 263 | 264 | #helper-container{ 265 | /*z-index: 10;*/ 266 | /*background-color: rgba(255,255,255,0.97);*/ 267 | /*float: right;*/ 268 | /*float: right;*/ 269 | position: absolute; 270 | left: 800px; 271 | top: 0; 272 | min-width: 5em; 273 | max-width: 60em; 274 | pointer-events: none; 275 | } 276 | #display-helper.bg{ 277 | background-color: rgba(255,255,255,0.97); 278 | } 279 | 280 | #display-helper{ 281 | position: absolute; 282 | /*float: right;*/ 283 | /*top: -5em;*/ 284 | pointer-events: auto; 285 | right: 1.5em; 286 | padding: 0.5em .6em; 287 | font-size: 1.3em; 288 | z-index: 11; 289 | } 290 | #controller-helper{ 291 | float: right; 292 | } 293 | 294 | #helper{ 295 | float: right; 296 | padding: 2em 1.5em 2em 2em; 297 | width: 35em; 298 | /*max-height: 705px;*/ 299 | max-height: 435px; 300 | /*min-width: 25em;*/ 301 | /*max-width: 32em;*/ 302 | background-color: rgba(255,255,255,0.97); 303 | /*margin-right: .5em;*/ 304 | pointer-events: auto; 305 | overflow-y: scroll; 306 | } 307 | 308 | #helper.expand{ 309 | max-height: 830px; 310 | 311 | } 312 | 313 | ::-webkit-scrollbar { 314 | -webkit-appearance: none; 315 | width: 7px; 316 | } 317 | ::-webkit-scrollbar-thumb { 318 | border-radius: 4px; 319 | background-color: rgba(0, 0, 0, .5); 320 | -webkit-box-shadow: 0 0 1px rgba(255, 255, 255, .5); 321 | } 322 | 323 | .main-container{ 324 | /*position: relative;*/ 325 | } 326 | .main-container.expand{ 327 | min-width: 1412px; 328 | } 329 | 330 | .panel-body{ 331 | padding: 0 5em 0 3em; 332 | } 333 | 334 | ul.decorate{ 335 | list-style-type: inherit; 336 | padding-left: 1.5em; 337 | } 338 | 339 | #helper-more{ 340 | position: absolute; 341 | bottom: 0; 342 | text-align: center; 343 | width: 35em; 344 | right: 0; 345 | line-height: 2em; 346 | color: rgba(94,142,131,1); 347 | font-weight: 500; 348 | background-color: rgba(256,256,256, 0.85); 349 | } 350 | .disabled{ 351 | color: #888; 352 | } 353 | /*#packed-chart{ 354 | display: none; 355 | }*/ 356 | 357 | #icicle-chart{ 358 | display: none; 359 | margin-top: 1em; 360 | } 361 | 362 | #sunburst-chart{ 363 | display: none; 364 | } 365 | 366 | #treemap-chart{ 367 | display: none; 368 | } 369 | 370 | .label-btn{ 371 | margin-right: 2em; 372 | } 373 | 374 | #icicle-chart rect.selected{ 375 | stroke: black; 376 | stroke-width: 4; 377 | } 378 | 379 | #sunburst-chart path{ 380 | stroke: rgb(207, 252, 231); 381 | } 382 | 383 | #sunburst-chart path.selected{ 384 | stroke: black; 385 | stroke-width: 2; 386 | } 387 | 388 | #treemap-chart { 389 | margin-top: 1em; 390 | width: 760px; 391 | height: 560px; 392 | background: #ddd; 393 | } 394 | 395 | #treemap-chart .grandparent text { 396 | font-weight: bold; 397 | } 398 | 399 | #treemap-chart rect { 400 | /*fill: none;*/ 401 | stroke: #fff; 402 | } 403 | 404 | #treemap-chart .grandparent rect { 405 | stroke-width: 2px; 406 | } 407 | #treemap-chart rect.parent{ 408 | stroke-width: 4px; 409 | } 410 | 411 | #treemap-chart .grandparent rect { 412 | fill: orange; 413 | } 414 | 415 | #treemap-chart .grandparent:hover rect { 416 | fill: #ee9700; 417 | } 418 | 419 | #treemap-chart .children rect.parent, 420 | #treemap-chart .grandparent rect { 421 | cursor: pointer; 422 | } 423 | 424 | #treemap-chart .children rect.parent { 425 | /*fill: #bbb; 426 | fill-opacity: .5;*/ 427 | } 428 | 429 | #treemap-chart .children:hover rect.child { 430 | /*fill: #bbb; 431 | fill-opacity: .5;*/ 432 | } 433 | 434 | #controller ul li+li{ 435 | margin-top: 1em; 436 | border-top: 1px solid #bbb; 437 | } 438 | 439 | #controller{ 440 | margin-bottom: 0; 441 | width: 35em; 442 | pointer-events: auto; 443 | float: right; 444 | /*position: absolute;*/ 445 | /*top: 0px; */ 446 | /*left: 800px;*/ 447 | /*min-width: 5em;*/ 448 | /*width: 35em;*/ 449 | /*background-color: rgba(255,255,255,0.97);*/ 450 | } -------------------------------------------------------------------------------- /vis/fonts/glyphicons-halflings-regular.eot: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/xychang/RecursiveHierarchicalClustering/7ffb814797a832c88b1c61a48a5591ce9b86a46e/vis/fonts/glyphicons-halflings-regular.eot -------------------------------------------------------------------------------- /vis/fonts/glyphicons-halflings-regular.ttf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/xychang/RecursiveHierarchicalClustering/7ffb814797a832c88b1c61a48a5591ce9b86a46e/vis/fonts/glyphicons-halflings-regular.ttf -------------------------------------------------------------------------------- /vis/fonts/glyphicons-halflings-regular.woff: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/xychang/RecursiveHierarchicalClustering/7ffb814797a832c88b1c61a48a5591ce9b86a46e/vis/fonts/glyphicons-halflings-regular.woff -------------------------------------------------------------------------------- /vis/fonts/glyphicons-halflings-regular.woff2: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/xychang/RecursiveHierarchicalClustering/7ffb814797a832c88b1c61a48a5591ce9b86a46e/vis/fonts/glyphicons-halflings-regular.woff2 -------------------------------------------------------------------------------- /vis/js/bootstrap.min.js: -------------------------------------------------------------------------------- 1 | /*! 2 | * Bootstrap v3.3.5 (http://getbootstrap.com) 3 | * Copyright 2011-2015 Twitter, Inc. 4 | * Licensed under the MIT license 5 | */ 6 | if("undefined"==typeof jQuery)throw new Error("Bootstrap's JavaScript requires jQuery");+function(a){"use strict";var b=a.fn.jquery.split(" ")[0].split(".");if(b[0]<2&&b[1]<9||1==b[0]&&9==b[1]&&b[2]<1)throw new Error("Bootstrap's JavaScript requires jQuery version 1.9.1 or higher")}(jQuery),+function(a){"use strict";function b(){var a=document.createElement("bootstrap"),b={WebkitTransition:"webkitTransitionEnd",MozTransition:"transitionend",OTransition:"oTransitionEnd otransitionend",transition:"transitionend"};for(var c in b)if(void 0!==a.style[c])return{end:b[c]};return!1}a.fn.emulateTransitionEnd=function(b){var c=!1,d=this;a(this).one("bsTransitionEnd",function(){c=!0});var e=function(){c||a(d).trigger(a.support.transition.end)};return setTimeout(e,b),this},a(function(){a.support.transition=b(),a.support.transition&&(a.event.special.bsTransitionEnd={bindType:a.support.transition.end,delegateType:a.support.transition.end,handle:function(b){return a(b.target).is(this)?b.handleObj.handler.apply(this,arguments):void 0}})})}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var c=a(this),e=c.data("bs.alert");e||c.data("bs.alert",e=new d(this)),"string"==typeof b&&e[b].call(c)})}var c='[data-dismiss="alert"]',d=function(b){a(b).on("click",c,this.close)};d.VERSION="3.3.5",d.TRANSITION_DURATION=150,d.prototype.close=function(b){function c(){g.detach().trigger("closed.bs.alert").remove()}var e=a(this),f=e.attr("data-target");f||(f=e.attr("href"),f=f&&f.replace(/.*(?=#[^\s]*$)/,""));var g=a(f);b&&b.preventDefault(),g.length||(g=e.closest(".alert")),g.trigger(b=a.Event("close.bs.alert")),b.isDefaultPrevented()||(g.removeClass("in"),a.support.transition&&g.hasClass("fade")?g.one("bsTransitionEnd",c).emulateTransitionEnd(d.TRANSITION_DURATION):c())};var e=a.fn.alert;a.fn.alert=b,a.fn.alert.Constructor=d,a.fn.alert.noConflict=function(){return a.fn.alert=e,this},a(document).on("click.bs.alert.data-api",c,d.prototype.close)}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var d=a(this),e=d.data("bs.button"),f="object"==typeof b&&b;e||d.data("bs.button",e=new c(this,f)),"toggle"==b?e.toggle():b&&e.setState(b)})}var c=function(b,d){this.$element=a(b),this.options=a.extend({},c.DEFAULTS,d),this.isLoading=!1};c.VERSION="3.3.5",c.DEFAULTS={loadingText:"loading..."},c.prototype.setState=function(b){var c="disabled",d=this.$element,e=d.is("input")?"val":"html",f=d.data();b+="Text",null==f.resetText&&d.data("resetText",d[e]()),setTimeout(a.proxy(function(){d[e](null==f[b]?this.options[b]:f[b]),"loadingText"==b?(this.isLoading=!0,d.addClass(c).attr(c,c)):this.isLoading&&(this.isLoading=!1,d.removeClass(c).removeAttr(c))},this),0)},c.prototype.toggle=function(){var a=!0,b=this.$element.closest('[data-toggle="buttons"]');if(b.length){var c=this.$element.find("input");"radio"==c.prop("type")?(c.prop("checked")&&(a=!1),b.find(".active").removeClass("active"),this.$element.addClass("active")):"checkbox"==c.prop("type")&&(c.prop("checked")!==this.$element.hasClass("active")&&(a=!1),this.$element.toggleClass("active")),c.prop("checked",this.$element.hasClass("active")),a&&c.trigger("change")}else this.$element.attr("aria-pressed",!this.$element.hasClass("active")),this.$element.toggleClass("active")};var d=a.fn.button;a.fn.button=b,a.fn.button.Constructor=c,a.fn.button.noConflict=function(){return a.fn.button=d,this},a(document).on("click.bs.button.data-api",'[data-toggle^="button"]',function(c){var d=a(c.target);d.hasClass("btn")||(d=d.closest(".btn")),b.call(d,"toggle"),a(c.target).is('input[type="radio"]')||a(c.target).is('input[type="checkbox"]')||c.preventDefault()}).on("focus.bs.button.data-api blur.bs.button.data-api",'[data-toggle^="button"]',function(b){a(b.target).closest(".btn").toggleClass("focus",/^focus(in)?$/.test(b.type))})}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var d=a(this),e=d.data("bs.carousel"),f=a.extend({},c.DEFAULTS,d.data(),"object"==typeof b&&b),g="string"==typeof b?b:f.slide;e||d.data("bs.carousel",e=new c(this,f)),"number"==typeof b?e.to(b):g?e[g]():f.interval&&e.pause().cycle()})}var c=function(b,c){this.$element=a(b),this.$indicators=this.$element.find(".carousel-indicators"),this.options=c,this.paused=null,this.sliding=null,this.interval=null,this.$active=null,this.$items=null,this.options.keyboard&&this.$element.on("keydown.bs.carousel",a.proxy(this.keydown,this)),"hover"==this.options.pause&&!("ontouchstart"in document.documentElement)&&this.$element.on("mouseenter.bs.carousel",a.proxy(this.pause,this)).on("mouseleave.bs.carousel",a.proxy(this.cycle,this))};c.VERSION="3.3.5",c.TRANSITION_DURATION=600,c.DEFAULTS={interval:5e3,pause:"hover",wrap:!0,keyboard:!0},c.prototype.keydown=function(a){if(!/input|textarea/i.test(a.target.tagName)){switch(a.which){case 37:this.prev();break;case 39:this.next();break;default:return}a.preventDefault()}},c.prototype.cycle=function(b){return b||(this.paused=!1),this.interval&&clearInterval(this.interval),this.options.interval&&!this.paused&&(this.interval=setInterval(a.proxy(this.next,this),this.options.interval)),this},c.prototype.getItemIndex=function(a){return this.$items=a.parent().children(".item"),this.$items.index(a||this.$active)},c.prototype.getItemForDirection=function(a,b){var c=this.getItemIndex(b),d="prev"==a&&0===c||"next"==a&&c==this.$items.length-1;if(d&&!this.options.wrap)return b;var e="prev"==a?-1:1,f=(c+e)%this.$items.length;return this.$items.eq(f)},c.prototype.to=function(a){var b=this,c=this.getItemIndex(this.$active=this.$element.find(".item.active"));return a>this.$items.length-1||0>a?void 0:this.sliding?this.$element.one("slid.bs.carousel",function(){b.to(a)}):c==a?this.pause().cycle():this.slide(a>c?"next":"prev",this.$items.eq(a))},c.prototype.pause=function(b){return b||(this.paused=!0),this.$element.find(".next, .prev").length&&a.support.transition&&(this.$element.trigger(a.support.transition.end),this.cycle(!0)),this.interval=clearInterval(this.interval),this},c.prototype.next=function(){return this.sliding?void 0:this.slide("next")},c.prototype.prev=function(){return this.sliding?void 0:this.slide("prev")},c.prototype.slide=function(b,d){var e=this.$element.find(".item.active"),f=d||this.getItemForDirection(b,e),g=this.interval,h="next"==b?"left":"right",i=this;if(f.hasClass("active"))return this.sliding=!1;var j=f[0],k=a.Event("slide.bs.carousel",{relatedTarget:j,direction:h});if(this.$element.trigger(k),!k.isDefaultPrevented()){if(this.sliding=!0,g&&this.pause(),this.$indicators.length){this.$indicators.find(".active").removeClass("active");var l=a(this.$indicators.children()[this.getItemIndex(f)]);l&&l.addClass("active")}var m=a.Event("slid.bs.carousel",{relatedTarget:j,direction:h});return a.support.transition&&this.$element.hasClass("slide")?(f.addClass(b),f[0].offsetWidth,e.addClass(h),f.addClass(h),e.one("bsTransitionEnd",function(){f.removeClass([b,h].join(" ")).addClass("active"),e.removeClass(["active",h].join(" ")),i.sliding=!1,setTimeout(function(){i.$element.trigger(m)},0)}).emulateTransitionEnd(c.TRANSITION_DURATION)):(e.removeClass("active"),f.addClass("active"),this.sliding=!1,this.$element.trigger(m)),g&&this.cycle(),this}};var d=a.fn.carousel;a.fn.carousel=b,a.fn.carousel.Constructor=c,a.fn.carousel.noConflict=function(){return a.fn.carousel=d,this};var e=function(c){var d,e=a(this),f=a(e.attr("data-target")||(d=e.attr("href"))&&d.replace(/.*(?=#[^\s]+$)/,""));if(f.hasClass("carousel")){var g=a.extend({},f.data(),e.data()),h=e.attr("data-slide-to");h&&(g.interval=!1),b.call(f,g),h&&f.data("bs.carousel").to(h),c.preventDefault()}};a(document).on("click.bs.carousel.data-api","[data-slide]",e).on("click.bs.carousel.data-api","[data-slide-to]",e),a(window).on("load",function(){a('[data-ride="carousel"]').each(function(){var c=a(this);b.call(c,c.data())})})}(jQuery),+function(a){"use strict";function b(b){var c,d=b.attr("data-target")||(c=b.attr("href"))&&c.replace(/.*(?=#[^\s]+$)/,"");return a(d)}function c(b){return this.each(function(){var c=a(this),e=c.data("bs.collapse"),f=a.extend({},d.DEFAULTS,c.data(),"object"==typeof b&&b);!e&&f.toggle&&/show|hide/.test(b)&&(f.toggle=!1),e||c.data("bs.collapse",e=new d(this,f)),"string"==typeof b&&e[b]()})}var d=function(b,c){this.$element=a(b),this.options=a.extend({},d.DEFAULTS,c),this.$trigger=a('[data-toggle="collapse"][href="#'+b.id+'"],[data-toggle="collapse"][data-target="#'+b.id+'"]'),this.transitioning=null,this.options.parent?this.$parent=this.getParent():this.addAriaAndCollapsedClass(this.$element,this.$trigger),this.options.toggle&&this.toggle()};d.VERSION="3.3.5",d.TRANSITION_DURATION=350,d.DEFAULTS={toggle:!0},d.prototype.dimension=function(){var a=this.$element.hasClass("width");return a?"width":"height"},d.prototype.show=function(){if(!this.transitioning&&!this.$element.hasClass("in")){var b,e=this.$parent&&this.$parent.children(".panel").children(".in, .collapsing");if(!(e&&e.length&&(b=e.data("bs.collapse"),b&&b.transitioning))){var f=a.Event("show.bs.collapse");if(this.$element.trigger(f),!f.isDefaultPrevented()){e&&e.length&&(c.call(e,"hide"),b||e.data("bs.collapse",null));var g=this.dimension();this.$element.removeClass("collapse").addClass("collapsing")[g](0).attr("aria-expanded",!0),this.$trigger.removeClass("collapsed").attr("aria-expanded",!0),this.transitioning=1;var h=function(){this.$element.removeClass("collapsing").addClass("collapse in")[g](""),this.transitioning=0,this.$element.trigger("shown.bs.collapse")};if(!a.support.transition)return h.call(this);var i=a.camelCase(["scroll",g].join("-"));this.$element.one("bsTransitionEnd",a.proxy(h,this)).emulateTransitionEnd(d.TRANSITION_DURATION)[g](this.$element[0][i])}}}},d.prototype.hide=function(){if(!this.transitioning&&this.$element.hasClass("in")){var b=a.Event("hide.bs.collapse");if(this.$element.trigger(b),!b.isDefaultPrevented()){var c=this.dimension();this.$element[c](this.$element[c]())[0].offsetHeight,this.$element.addClass("collapsing").removeClass("collapse in").attr("aria-expanded",!1),this.$trigger.addClass("collapsed").attr("aria-expanded",!1),this.transitioning=1;var e=function(){this.transitioning=0,this.$element.removeClass("collapsing").addClass("collapse").trigger("hidden.bs.collapse")};return a.support.transition?void this.$element[c](0).one("bsTransitionEnd",a.proxy(e,this)).emulateTransitionEnd(d.TRANSITION_DURATION):e.call(this)}}},d.prototype.toggle=function(){this[this.$element.hasClass("in")?"hide":"show"]()},d.prototype.getParent=function(){return a(this.options.parent).find('[data-toggle="collapse"][data-parent="'+this.options.parent+'"]').each(a.proxy(function(c,d){var e=a(d);this.addAriaAndCollapsedClass(b(e),e)},this)).end()},d.prototype.addAriaAndCollapsedClass=function(a,b){var c=a.hasClass("in");a.attr("aria-expanded",c),b.toggleClass("collapsed",!c).attr("aria-expanded",c)};var e=a.fn.collapse;a.fn.collapse=c,a.fn.collapse.Constructor=d,a.fn.collapse.noConflict=function(){return a.fn.collapse=e,this},a(document).on("click.bs.collapse.data-api",'[data-toggle="collapse"]',function(d){var e=a(this);e.attr("data-target")||d.preventDefault();var f=b(e),g=f.data("bs.collapse"),h=g?"toggle":e.data();c.call(f,h)})}(jQuery),+function(a){"use strict";function b(b){var c=b.attr("data-target");c||(c=b.attr("href"),c=c&&/#[A-Za-z]/.test(c)&&c.replace(/.*(?=#[^\s]*$)/,""));var d=c&&a(c);return d&&d.length?d:b.parent()}function c(c){c&&3===c.which||(a(e).remove(),a(f).each(function(){var d=a(this),e=b(d),f={relatedTarget:this};e.hasClass("open")&&(c&&"click"==c.type&&/input|textarea/i.test(c.target.tagName)&&a.contains(e[0],c.target)||(e.trigger(c=a.Event("hide.bs.dropdown",f)),c.isDefaultPrevented()||(d.attr("aria-expanded","false"),e.removeClass("open").trigger("hidden.bs.dropdown",f))))}))}function d(b){return this.each(function(){var c=a(this),d=c.data("bs.dropdown");d||c.data("bs.dropdown",d=new g(this)),"string"==typeof b&&d[b].call(c)})}var e=".dropdown-backdrop",f='[data-toggle="dropdown"]',g=function(b){a(b).on("click.bs.dropdown",this.toggle)};g.VERSION="3.3.5",g.prototype.toggle=function(d){var e=a(this);if(!e.is(".disabled, :disabled")){var f=b(e),g=f.hasClass("open");if(c(),!g){"ontouchstart"in document.documentElement&&!f.closest(".navbar-nav").length&&a(document.createElement("div")).addClass("dropdown-backdrop").insertAfter(a(this)).on("click",c);var h={relatedTarget:this};if(f.trigger(d=a.Event("show.bs.dropdown",h)),d.isDefaultPrevented())return;e.trigger("focus").attr("aria-expanded","true"),f.toggleClass("open").trigger("shown.bs.dropdown",h)}return!1}},g.prototype.keydown=function(c){if(/(38|40|27|32)/.test(c.which)&&!/input|textarea/i.test(c.target.tagName)){var d=a(this);if(c.preventDefault(),c.stopPropagation(),!d.is(".disabled, :disabled")){var e=b(d),g=e.hasClass("open");if(!g&&27!=c.which||g&&27==c.which)return 27==c.which&&e.find(f).trigger("focus"),d.trigger("click");var h=" li:not(.disabled):visible a",i=e.find(".dropdown-menu"+h);if(i.length){var j=i.index(c.target);38==c.which&&j>0&&j--,40==c.which&&jdocument.documentElement.clientHeight;this.$element.css({paddingLeft:!this.bodyIsOverflowing&&a?this.scrollbarWidth:"",paddingRight:this.bodyIsOverflowing&&!a?this.scrollbarWidth:""})},c.prototype.resetAdjustments=function(){this.$element.css({paddingLeft:"",paddingRight:""})},c.prototype.checkScrollbar=function(){var a=window.innerWidth;if(!a){var b=document.documentElement.getBoundingClientRect();a=b.right-Math.abs(b.left)}this.bodyIsOverflowing=document.body.clientWidth
',trigger:"hover focus",title:"",delay:0,html:!1,container:!1,viewport:{selector:"body",padding:0}},c.prototype.init=function(b,c,d){if(this.enabled=!0,this.type=b,this.$element=a(c),this.options=this.getOptions(d),this.$viewport=this.options.viewport&&a(a.isFunction(this.options.viewport)?this.options.viewport.call(this,this.$element):this.options.viewport.selector||this.options.viewport),this.inState={click:!1,hover:!1,focus:!1},this.$element[0]instanceof document.constructor&&!this.options.selector)throw new Error("`selector` option must be specified when initializing "+this.type+" on the window.document object!");for(var e=this.options.trigger.split(" "),f=e.length;f--;){var g=e[f];if("click"==g)this.$element.on("click."+this.type,this.options.selector,a.proxy(this.toggle,this));else if("manual"!=g){var h="hover"==g?"mouseenter":"focusin",i="hover"==g?"mouseleave":"focusout";this.$element.on(h+"."+this.type,this.options.selector,a.proxy(this.enter,this)),this.$element.on(i+"."+this.type,this.options.selector,a.proxy(this.leave,this))}}this.options.selector?this._options=a.extend({},this.options,{trigger:"manual",selector:""}):this.fixTitle()},c.prototype.getDefaults=function(){return c.DEFAULTS},c.prototype.getOptions=function(b){return b=a.extend({},this.getDefaults(),this.$element.data(),b),b.delay&&"number"==typeof b.delay&&(b.delay={show:b.delay,hide:b.delay}),b},c.prototype.getDelegateOptions=function(){var b={},c=this.getDefaults();return this._options&&a.each(this._options,function(a,d){c[a]!=d&&(b[a]=d)}),b},c.prototype.enter=function(b){var c=b instanceof this.constructor?b:a(b.currentTarget).data("bs."+this.type);return c||(c=new this.constructor(b.currentTarget,this.getDelegateOptions()),a(b.currentTarget).data("bs."+this.type,c)),b instanceof a.Event&&(c.inState["focusin"==b.type?"focus":"hover"]=!0),c.tip().hasClass("in")||"in"==c.hoverState?void(c.hoverState="in"):(clearTimeout(c.timeout),c.hoverState="in",c.options.delay&&c.options.delay.show?void(c.timeout=setTimeout(function(){"in"==c.hoverState&&c.show()},c.options.delay.show)):c.show())},c.prototype.isInStateTrue=function(){for(var a in this.inState)if(this.inState[a])return!0;return!1},c.prototype.leave=function(b){var c=b instanceof this.constructor?b:a(b.currentTarget).data("bs."+this.type);return c||(c=new this.constructor(b.currentTarget,this.getDelegateOptions()),a(b.currentTarget).data("bs."+this.type,c)),b instanceof a.Event&&(c.inState["focusout"==b.type?"focus":"hover"]=!1),c.isInStateTrue()?void 0:(clearTimeout(c.timeout),c.hoverState="out",c.options.delay&&c.options.delay.hide?void(c.timeout=setTimeout(function(){"out"==c.hoverState&&c.hide()},c.options.delay.hide)):c.hide())},c.prototype.show=function(){var b=a.Event("show.bs."+this.type);if(this.hasContent()&&this.enabled){this.$element.trigger(b);var d=a.contains(this.$element[0].ownerDocument.documentElement,this.$element[0]);if(b.isDefaultPrevented()||!d)return;var e=this,f=this.tip(),g=this.getUID(this.type);this.setContent(),f.attr("id",g),this.$element.attr("aria-describedby",g),this.options.animation&&f.addClass("fade");var h="function"==typeof this.options.placement?this.options.placement.call(this,f[0],this.$element[0]):this.options.placement,i=/\s?auto?\s?/i,j=i.test(h);j&&(h=h.replace(i,"")||"top"),f.detach().css({top:0,left:0,display:"block"}).addClass(h).data("bs."+this.type,this),this.options.container?f.appendTo(this.options.container):f.insertAfter(this.$element),this.$element.trigger("inserted.bs."+this.type);var k=this.getPosition(),l=f[0].offsetWidth,m=f[0].offsetHeight;if(j){var n=h,o=this.getPosition(this.$viewport);h="bottom"==h&&k.bottom+m>o.bottom?"top":"top"==h&&k.top-mo.width?"left":"left"==h&&k.left-lg.top+g.height&&(e.top=g.top+g.height-i)}else{var j=b.left-f,k=b.left+f+c;jg.right&&(e.left=g.left+g.width-k)}return e},c.prototype.getTitle=function(){var a,b=this.$element,c=this.options;return a=b.attr("data-original-title")||("function"==typeof c.title?c.title.call(b[0]):c.title)},c.prototype.getUID=function(a){do a+=~~(1e6*Math.random());while(document.getElementById(a));return a},c.prototype.tip=function(){if(!this.$tip&&(this.$tip=a(this.options.template),1!=this.$tip.length))throw new Error(this.type+" `template` option must consist of exactly 1 top-level element!");return this.$tip},c.prototype.arrow=function(){return this.$arrow=this.$arrow||this.tip().find(".tooltip-arrow")},c.prototype.enable=function(){this.enabled=!0},c.prototype.disable=function(){this.enabled=!1},c.prototype.toggleEnabled=function(){this.enabled=!this.enabled},c.prototype.toggle=function(b){var c=this;b&&(c=a(b.currentTarget).data("bs."+this.type),c||(c=new this.constructor(b.currentTarget,this.getDelegateOptions()),a(b.currentTarget).data("bs."+this.type,c))),b?(c.inState.click=!c.inState.click,c.isInStateTrue()?c.enter(c):c.leave(c)):c.tip().hasClass("in")?c.leave(c):c.enter(c)},c.prototype.destroy=function(){var a=this;clearTimeout(this.timeout),this.hide(function(){a.$element.off("."+a.type).removeData("bs."+a.type),a.$tip&&a.$tip.detach(),a.$tip=null,a.$arrow=null,a.$viewport=null})};var d=a.fn.tooltip;a.fn.tooltip=b,a.fn.tooltip.Constructor=c,a.fn.tooltip.noConflict=function(){return a.fn.tooltip=d,this}}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var d=a(this),e=d.data("bs.popover"),f="object"==typeof b&&b;(e||!/destroy|hide/.test(b))&&(e||d.data("bs.popover",e=new c(this,f)),"string"==typeof b&&e[b]())})}var c=function(a,b){this.init("popover",a,b)};if(!a.fn.tooltip)throw new Error("Popover requires tooltip.js");c.VERSION="3.3.5",c.DEFAULTS=a.extend({},a.fn.tooltip.Constructor.DEFAULTS,{placement:"right",trigger:"click",content:"",template:''}),c.prototype=a.extend({},a.fn.tooltip.Constructor.prototype),c.prototype.constructor=c,c.prototype.getDefaults=function(){return c.DEFAULTS},c.prototype.setContent=function(){var a=this.tip(),b=this.getTitle(),c=this.getContent();a.find(".popover-title")[this.options.html?"html":"text"](b),a.find(".popover-content").children().detach().end()[this.options.html?"string"==typeof c?"html":"append":"text"](c),a.removeClass("fade top bottom left right in"),a.find(".popover-title").html()||a.find(".popover-title").hide()},c.prototype.hasContent=function(){return this.getTitle()||this.getContent()},c.prototype.getContent=function(){var a=this.$element,b=this.options;return a.attr("data-content")||("function"==typeof b.content?b.content.call(a[0]):b.content)},c.prototype.arrow=function(){return this.$arrow=this.$arrow||this.tip().find(".arrow")};var d=a.fn.popover;a.fn.popover=b,a.fn.popover.Constructor=c,a.fn.popover.noConflict=function(){return a.fn.popover=d,this}}(jQuery),+function(a){"use strict";function b(c,d){this.$body=a(document.body),this.$scrollElement=a(a(c).is(document.body)?window:c),this.options=a.extend({},b.DEFAULTS,d),this.selector=(this.options.target||"")+" .nav li > a",this.offsets=[],this.targets=[],this.activeTarget=null,this.scrollHeight=0,this.$scrollElement.on("scroll.bs.scrollspy",a.proxy(this.process,this)),this.refresh(),this.process()}function c(c){return this.each(function(){var d=a(this),e=d.data("bs.scrollspy"),f="object"==typeof c&&c;e||d.data("bs.scrollspy",e=new b(this,f)),"string"==typeof c&&e[c]()})}b.VERSION="3.3.5",b.DEFAULTS={offset:10},b.prototype.getScrollHeight=function(){return this.$scrollElement[0].scrollHeight||Math.max(this.$body[0].scrollHeight,document.documentElement.scrollHeight)},b.prototype.refresh=function(){var b=this,c="offset",d=0;this.offsets=[],this.targets=[],this.scrollHeight=this.getScrollHeight(),a.isWindow(this.$scrollElement[0])||(c="position",d=this.$scrollElement.scrollTop()),this.$body.find(this.selector).map(function(){var b=a(this),e=b.data("target")||b.attr("href"),f=/^#./.test(e)&&a(e);return f&&f.length&&f.is(":visible")&&[[f[c]().top+d,e]]||null}).sort(function(a,b){return a[0]-b[0]}).each(function(){b.offsets.push(this[0]),b.targets.push(this[1])})},b.prototype.process=function(){var a,b=this.$scrollElement.scrollTop()+this.options.offset,c=this.getScrollHeight(),d=this.options.offset+c-this.$scrollElement.height(),e=this.offsets,f=this.targets,g=this.activeTarget;if(this.scrollHeight!=c&&this.refresh(),b>=d)return g!=(a=f[f.length-1])&&this.activate(a);if(g&&b=e[a]&&(void 0===e[a+1]||b .dropdown-menu > .active").removeClass("active").end().find('[data-toggle="tab"]').attr("aria-expanded",!1),b.addClass("active").find('[data-toggle="tab"]').attr("aria-expanded",!0),h?(b[0].offsetWidth,b.addClass("in")):b.removeClass("fade"),b.parent(".dropdown-menu").length&&b.closest("li.dropdown").addClass("active").end().find('[data-toggle="tab"]').attr("aria-expanded",!0),e&&e()}var g=d.find("> .active"),h=e&&a.support.transition&&(g.length&&g.hasClass("fade")||!!d.find("> .fade").length);g.length&&h?g.one("bsTransitionEnd",f).emulateTransitionEnd(c.TRANSITION_DURATION):f(),g.removeClass("in")};var d=a.fn.tab;a.fn.tab=b,a.fn.tab.Constructor=c,a.fn.tab.noConflict=function(){return a.fn.tab=d,this};var e=function(c){c.preventDefault(),b.call(a(this),"show")};a(document).on("click.bs.tab.data-api",'[data-toggle="tab"]',e).on("click.bs.tab.data-api",'[data-toggle="pill"]',e)}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var d=a(this),e=d.data("bs.affix"),f="object"==typeof b&&b;e||d.data("bs.affix",e=new c(this,f)),"string"==typeof b&&e[b]()})}var c=function(b,d){this.options=a.extend({},c.DEFAULTS,d),this.$target=a(this.options.target).on("scroll.bs.affix.data-api",a.proxy(this.checkPosition,this)).on("click.bs.affix.data-api",a.proxy(this.checkPositionWithEventLoop,this)),this.$element=a(b),this.affixed=null,this.unpin=null,this.pinnedOffset=null,this.checkPosition()};c.VERSION="3.3.5",c.RESET="affix affix-top affix-bottom",c.DEFAULTS={offset:0,target:window},c.prototype.getState=function(a,b,c,d){var e=this.$target.scrollTop(),f=this.$element.offset(),g=this.$target.height();if(null!=c&&"top"==this.affixed)return c>e?"top":!1;if("bottom"==this.affixed)return null!=c?e+this.unpin<=f.top?!1:"bottom":a-d>=e+g?!1:"bottom";var h=null==this.affixed,i=h?e:f.top,j=h?g:b;return null!=c&&c>=e?"top":null!=d&&i+j>=a-d?"bottom":!1},c.prototype.getPinnedOffset=function(){if(this.pinnedOffset)return this.pinnedOffset;this.$element.removeClass(c.RESET).addClass("affix");var a=this.$target.scrollTop(),b=this.$element.offset();return this.pinnedOffset=b.top-a},c.prototype.checkPositionWithEventLoop=function(){setTimeout(a.proxy(this.checkPosition,this),1)},c.prototype.checkPosition=function(){if(this.$element.is(":visible")){var b=this.$element.height(),d=this.options.offset,e=d.top,f=d.bottom,g=Math.max(a(document).height(),a(document.body).height());"object"!=typeof d&&(f=e=d),"function"==typeof e&&(e=d.top(this.$element)),"function"==typeof f&&(f=d.bottom(this.$element));var h=this.getState(g,b,e,f);if(this.affixed!=h){null!=this.unpin&&this.$element.css("top","");var i="affix"+(h?"-"+h:""),j=a.Event(i+".bs.affix");if(this.$element.trigger(j),j.isDefaultPrevented())return;this.affixed=h,this.unpin="bottom"==h?this.getPinnedOffset():null,this.$element.removeClass(c.RESET).addClass(i).trigger(i.replace("affix","affixed")+".bs.affix")}"bottom"==h&&this.$element.offset({top:g-b-f})}};var d=a.fn.affix;a.fn.affix=b,a.fn.affix.Constructor=c,a.fn.affix.noConflict=function(){return a.fn.affix=d,this},a(window).on("load",function(){a('[data-spy="affix"]').each(function(){var c=a(this),d=c.data();d.offset=d.offset||{},null!=d.offsetBottom&&(d.offset.bottom=d.offsetBottom),null!=d.offsetTop&&(d.offset.top=d.offsetTop),b.call(c,d)})})}(jQuery); -------------------------------------------------------------------------------- /vis/multi_color.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Whisper Users 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 |
18 |
19 |
20 |
21 |
22 |
23 |
Scroll down for more
24 |
25 | 26 |
27 |
28 |

Visulization Configuration 29 | 30 |

31 | 32 |
33 |
34 |
    35 |
  • 36 |

    Visualization Style
    37 | Select your favorite method to visualize the cluster hierarchy.

    38 |
    39 | 40 | 41 | 42 | 43 |
    44 |
  • 45 |
  • 46 |

    Maximum Depth
    47 |

    48 |
    49 | 50 | 51 | 52 | 53 |
    54 | 55 |
  • 56 | 57 |
  • 58 |

    Cluster Color
    59 | The default coloring only reflects the depth of the cluster.
    60 | You can enable a color overlay to denote cluster compactness or modularity. 61 |
    Lower Value 62 | 63 | 64 | 65 | 66 |  Higher Value 67 |

    68 |
    69 | 70 | 71 | 72 |
    73 |
  • 74 | 75 |
76 | 77 |
78 |
79 |
80 | 81 |

Hierarchical Clusters

82 |

About This Tool

83 |

We build a tool to automatically discover the natural formation of user categories in Whisper, based on their behavior as captured by clickstream data. A user's clickstream is a sequence of click events generated by the user when she uses 84 | the app. At a high-level, we assume that human behavior would naturally form clusters or groups, because large user populations tend to break into different types of users according to their habits, goals, and personalities. Our tool 85 | seeks to discover these natural clusters among users, where each cluster represents a specific user type or behavioral pattern. To understand the meaning of these resulting clusters (since they are unlabeled and do not necessarily 86 | match preconceived categories), we identify key behavioral patterns for each cluster that are primarily responsible for distinguishing users in the cluster from others. These key patterns thus can serve as the cluster labels.

87 |

Our tool builds clusters hierarchically, where clusters are nested, and bigger clusters represent the higher level categories of users. Smaller, sub-clusters represent more fine-grained user types. The circle size represents 88 | the number of users in a cluster.

89 |

How to Use this Tool

90 |

The clusters displayed on the left are generated from 100k Whisper users' clickstreams. They represent the major user behavioral categories in Whisper. You can browse different clusters to understand the detailed user behavioral patterns. 91 | To reference the clusters easily, we add labels for the top-level clusters (the text at the bottom of each cluster). For example, the biggest cluster contains users who are likely to read whispers sequentially.

92 |

By double-clicking on any cluster, you can zoom in on the cluster for more focused inspection. To zoom out, simply double click on the current cluster.

93 |

Clicking on a cluster will pop up a window to show more detailed information about this cluster. Here, we explain how to read the information in the pop-up window. First, on the top of the window, it shows the ClusterID and the 94 | Number of Users in this cluster. Then, below that, we show a list of Action Patterns that can characterize the behaviors of users in the cluster. Each row contains one Action Pattern. These Action Patterns are ranked 95 | by their distinguishing power in classifying users in this cluster (more important patterns on top). We only display the most important Action Patterns in the pop-up window and the rest are omitted because they are significantly weaker.

96 |
    97 |
  • The first column shows the Rank of the Action Pattern. A pattern with a higher ranking means this pattern is more important in classifying users in this cluster.
  • 98 |
  • 99 |

    100 | This is an example Action Pattern: 101 | O 102 |

    103 |

    104 |
  • 105 |
  • 106 |

    The Frequency Distribution shows how frequently does the Action Pattern appear in users in this cluster versus outside the cluster.

    107 | 108 | 109 | 161 | 162 |
    110 | 111 | 112 | 113 | 114 | 115 | 116 | 117 | 118 | 119 | 120 | 121 | 122 | 123 | 124 | 125 | 126 | 127 | 128 | 129 | 130 | 131 | 132 | 133 | 134 | 135 | 136 | 137 | 138 | 139 | 140 | 141 | 142 | 143 | 144 | 145 | 146 | 147 | 148 | 149 | 150 | 151 | 152 | 153 | 154 | 155 | 156 | 157 | 158 | 159 | 160 |
    163 |

    You can see how users in this cluster are different from users outside of the cluster on this particular Action Pattern. The red bars show the pattern frequency distribution (PDF) for users 164 | within the selected cluster. As a baseline comparison, the green bars show the pattern frequency outside the cluster. In this example, 165 | the red distribution is more skewed to the right, indicating users in this cluster perform this activity more frequently than those outside (i.e., more likely to read whispers sequentially). The more different the two distributions 166 | are, the more useful the Pattern is to characterize users in this cluster. 167 |

    168 |
  • 169 |
  • 170 | Finally, the Score column shows the Chi-Square score of the Action Pattern. We rely on this score to rank Action Patterns (a higher score means the pattern is more important). Socres are colored from higher to lower. 172 |
  • 173 |
174 |
175 |
176 |
177 | -------------------------------------------------------------------------------- /visulization.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | """ 3 | the script to convert the resulting json file from RHC to one 4 | suited for visulization 5 | 6 | arguments 7 | 8 | arg1: path to the json file generated from RHC 9 | e.g. 'outpath/result.json' 10 | arg2: path to a file containing the different ngram count mapping 11 | e.g. 'input.txt' 12 | arg3: output path of the json file used for visulization 13 | e.g. 'vis/vis.json' 14 | """ 15 | 16 | import json 17 | import sys 18 | import numpy as np 19 | import recursiveHierarchicalClustering as rhc 20 | 21 | inPath = sys.argv[1] 22 | sid_ngram = sys.argv[2] 23 | outPath = sys.argv[3] 24 | 25 | # display 24 bins in visulization 26 | binCount = 24 27 | 28 | data = json.load(open(inPath)) 29 | sid_seq = rhc.getSidNgramMap(sid_ngram) 30 | 31 | 32 | def allUser(tree): 33 | """ output all users in the tree """ 34 | users = [] 35 | if (tree[0] == 'l'): 36 | return tree[1] 37 | for subTree in tree[1]: 38 | users.extend(allUser(subTree)) 39 | return users 40 | 41 | 42 | def getPatternDist(pattern, sids, sid_seq): 43 | """ 44 | get pattern distribution 45 | :type pattern: str 46 | :type sids: List[int] 47 | :type sid_seq: Dict{int:Dict{str:int}} 48 | - for each user, record the pattern and corresponding occurence # 49 | """ 50 | ratios = [] 51 | for sid in sids: 52 | totalPattern = sum([x[1] for x in list(sid_seq[sid].items())]) 53 | currentPattern = sid_seq[sid][pattern] if pattern in sid_seq[sid] else 0 54 | ratio = float(currentPattern) / totalPattern 55 | ratios.append(ratio) 56 | return ratios 57 | 58 | 59 | def getJsonChildren(tree, sid_seq, clusterId): 60 | """ 61 | given a (not leaf) tree, return the children filed of json 62 | :type tree: a tree / subtree 63 | :type sid_seq: Dict{int:Dict{str:int}} 64 | - for each user, record the pattern and corresponding occurence # 65 | :type clusterId: int 66 | - the current id used, to ensure that all clusters get their id 67 | """ 68 | if tree[0] == 'l': 69 | return None, clusterId 70 | if 'sweetspot' in tree[2] and tree[2]['sweetspot'] < 0.01: 71 | return None, clusterId 72 | 73 | subTrees = [] 74 | allSids = allUser(tree) 75 | sidsAll = [allUser(subTree) for subTree in tree[1]] 76 | 77 | for tidx in range(len(tree[1])): 78 | subTree = tree[1][tidx] 79 | sids = sidsAll[tidx] 80 | size = len(sids) 81 | children, clusterId = getJsonChildren(subTree, sid_seq, clusterId) 82 | name = '' 83 | info = {} 84 | if 'sweetspot' in subTree[2]: 85 | info['sweetspot'] = subTree[2]['sweetspot'] 86 | if 'gini' in subTree[2]: 87 | info['gini'] = subTree[2]['gini'] 88 | if 'isExclude' in subTree[2]: 89 | info['isExclude'] = subTree[2]['isExclude'] 90 | if 'exclusions' in subTree[2]: 91 | info['exclusions'] = subTree[2]['exclusions'] 92 | # for each excluded features, calculate the average within cluster 93 | # and out of cluster and also the distribution bins 94 | for eidx in range(len(info['exclusions'])): 95 | # the second entry can be a longer description of the feature 96 | # excluded 97 | info['exclusions'][eidx] = exclusions = \ 98 | [info['exclusions'][eidx]] * 2 99 | key = exclusions[0] 100 | localDists = getPatternDist(key, sids, sid_seq) 101 | globalDists = getPatternDist(key, list(set(allSids)-set(sids)), 102 | sid_seq) 103 | # so that max is counted in the last bin 104 | maxRange = max(localDists + globalDists) + 0.00000001 105 | # if the maxRange is too large, reduce it 106 | maxRange = min(maxRange, 107 | max(np.mean(localDists)+np.std(localDists)*2, 108 | np.mean(globalDists)+np.std(globalDists)*2)) 109 | minRange = min(localDists + globalDists) 110 | binSize = float(maxRange - minRange) / binCount 111 | localDists = [int((ratio - minRange) / binSize) 112 | for ratio in localDists] 113 | globalDists = [int((ratio - minRange) / binSize) 114 | for ratio in globalDists] 115 | localBins = [0] * binCount 116 | for ratio in localDists: 117 | if ratio >= binCount: 118 | ratio = binCount - 1 119 | localBins[ratio] += 1 120 | globalBins = [0] * binCount 121 | for ratio in globalDists: 122 | if ratio >= binCount: 123 | ratio = binCount - 1 124 | globalBins[ratio] += 1 125 | exclusions.append( 126 | [[float(x) / len(localDists) for x in localBins], 127 | [float(x) / len(globalDists) for x in globalBins]]) 128 | exclusions.append(subTree[2]['exclusionsScore'][eidx]) 129 | info['size'] = size 130 | info['id'] = clusterId 131 | clusterId += 1 132 | if children: 133 | subTrees.append({'name': name, 'children': children, 'info': info}) 134 | else: 135 | subTrees.append({'name': name, 'size': size, 'info': info}) 136 | return subTrees, clusterId 137 | 138 | 139 | def dumpLabels(treeData, sid_seq, outFile): 140 | """ 141 | actually transfer the dumped clustering into json readable from 142 | visulization tool 143 | :type treeData: a tree / subtree 144 | :type sid_seq: Dict{int:Dict{str:int}} 145 | - for each user, record the pattern and corresponding occurence # 146 | :type outFile: str 147 | - the path of the final json dump 148 | """ 149 | json.dump({'name': 'root', 150 | 'children': getJsonChildren(treeData, sid_seq, 1)[0]}, 151 | open(outFile, 'w')) 152 | 153 | dumpLabels(data, sid_seq, outPath) --------------------------------------------------------------------------------