├── .gitignore ├── LICENSE ├── README.md ├── code ├── CRep.py ├── README.md ├── analyse_results.ipynb ├── cv_functions.py ├── generate_data.py ├── generative_model_reciprocity.py ├── main.py ├── main_cv.py ├── setting_CRep.yaml ├── setting_CRep0.yaml ├── setting_CRepnc.yaml ├── setting_syn_data.yaml ├── test.py ├── test_cv.py └── tools.py ├── data ├── input │ ├── setting111.yaml │ ├── syn111.dat │ └── theta_gt111.npz └── output │ ├── 5-fold_cv │ ├── setting_CRep.yaml │ ├── syn111_cv.csv │ ├── theta_0K3_test.npz │ ├── theta_1K3_test.npz │ ├── theta_2K3_test.npz │ ├── theta_3K3_test.npz │ ├── theta_4K3_test.npz │ ├── theta_CRep_0K3.npz │ ├── theta_CRep_1K3.npz │ ├── theta_CRep_2K3.npz │ ├── theta_CRep_3K3.npz │ └── theta_CRep_4K3.npz │ ├── setting_CRep.yaml │ ├── theta_CRep.npz │ └── theta_test.npz └── requirements.txt /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | *__pycache__ 3 | *.py[cod] 4 | *$py.class 5 | *pyc 6 | *.DS_Store* 7 | # Distribution / packaging 8 | .Python 9 | build/ 10 | develop-eggs/ 11 | dist/ 12 | downloads/ 13 | eggs/ 14 | .eggs/ 15 | lib/ 16 | .idea 17 | # Jupyter Notebook 18 | .ipynb_checkpoints 19 | -------------------------------------------------------------------------------- /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 | # CRep: reciprocity and community detection in networks 2 | Python implementation of CRep algorithm described in: 3 | 4 | - [1] Safdari H., Contisciani M. & De Bacco C. (2021). *Generative model for reciprocity and community detection in networks*, Phys. Rev. Research 3, 023209. 5 | 6 | This is a new probabilistic generative model and efficient algorithm to model reciprocity in directed networks. It assigns latent variables as community memberships to nodes and a reciprocity parameter to the whole network and it formalizes the assumption that a directed interaction is more likely to occur if an individual has already observed an interaction towards her.
7 | 8 | If you use this code please cite [1]. 9 | 10 | The paper can be found [here](https://journals.aps.org/prresearch/abstract/10.1103/PhysRevResearch.3.023209) (_Published version, open access_) or [here](https://arxiv.org/abs/2012.08215) (_preprint_). 11 | 12 | Copyright (c) 2020 [Hadiseh Safdari](https://github.com/hds-safdari), [Martina Contisciani](https://www.is.mpg.de/person/mcontisciani) and [Caterina De Bacco](http://cdebacco.com). 13 | 14 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 15 | 16 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 17 | 18 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON INFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 19 | 20 | ## What's included 21 | - `code` : Contains the Python implementation of CRep algorithm, the code for performing the cross-validation procedure and the code for generating benchmark synthetic data with intrinsic community structure and given reciprocity value. 22 | - `data/input` : Contains an example of directed network having an intrinsic community structure and a given reciprocity value, and some example files to initialize the latent variables. They are synthetic data. 23 | - `data/output` : Contains some results to test the code. 24 | 25 | ## Requirements 26 | The project has been developed using Python 3.9 with the packages contained in *requirements.txt*. We suggest to create a virtual environment with 27 | `python3.9 -m venv --copies CRep`, activate it with `source CRep/bin/activate`, and install all the dependencies by running (inside `CRep` directory): 28 | 29 | `pip install -r requirements.txt` 30 | 31 | ## Test 32 | You can run tests to reproduce results contained in `data/output` by running (inside `code` directory): 33 | 34 | ```bash 35 | python -m unittest test.py 36 | python -m unittest test_cv.py 37 | ``` 38 | 39 | ## Usage 40 | To test the program on the given example file, type: 41 | 42 | ```bash 43 | cd code 44 | python main.py 45 | ``` 46 | 47 | It will use the sample network contained in `./data/input`. The adjacency matrix *syn111.dat* represents a directed, weighted network with **N=600** nodes, **K=3** equal-size unmixed communities with an **assortative** structure and reciprocity parameter **eta=0.5**. 48 | 49 | ### Parameters 50 | - **-a** : Model configuration to use (CRep, CRepnc, CRep0), *(default='CRep')*. 51 | - **-K** : Number of communities, *(default=3)*. 52 | - **-A** : Input file name of the adjacency matrix, *(default='syn111.dat')*. 53 | - **-f** : Path of the input folder, *(default='../data/input/')*. 54 | - **-e** : Name of the source of the edge, *(default='source')*. 55 | - **-t** : Name of the target of the edge, *(default='target')*. 56 | - **-d** : Flag to force a dense transformation of the adjacency matrix, *(default=False)*. 57 | - **-F** : Flag to choose the convergence method, *(default='log')*. 58 | 59 | You can find a list by running (inside `code` directory): 60 | 61 | ```bash 62 | python main.py --help 63 | ``` 64 | 65 | ## Input format 66 | The network should be stored in a *.dat* file. An example of rows is 67 | 68 | `node1 node2 3`
69 | `node1 node3 1` 70 | 71 | where the first and second columns are the _source_ and _target_ nodes of the edge, respectively; the third column tells if there is an edge and the weight. In this example the edge node1 --> node2 exists with weight 3, and the edge node1 --> node3 exists with weight 1. 72 | 73 | Other configuration settings can be set by modifying the *setting\_\*_.yaml* files: 74 | 75 | - *setting\_syn_data.yaml* : contains the setting to generate synthetic data 76 | - *setting\_CRep.yaml* : contains the setting to run the algorithm CRep 77 | - *setting\_CRepnc.yaml* : contains the setting to run the algorithm CRep without normalization constraints on the membership parameters 78 | - *setting\_CRep0.yaml* : contains the setting to run the algorithm CRep without considering the reciprocity effect 79 | 80 | ## Output 81 | The algorithm returns a compressed file inside the `data/output` folder. To load and print the out-going membership matrix: 82 | 83 | ```bash 84 | import numpy as np 85 | theta = np.load('theta_Crep.npz') 86 | print(theta['u']) 87 | ``` 88 | 89 | _theta_ contains the two $N\times K$ membership matrices **u** *('u')* and **v** *('v')*, the $1\times K \times K$ (or $1\times K$ if assortative=True) affinity tensor **w** *('w')*, the reciprocity coefficient **$\eta$** *('eta')*, the total number of iterations *('max_it')*, the value of the maximum pseudo log-likelihood *('maxPSL')* and the nodes of the network *('nodes')*. 90 | 91 | For an example `jupyter notebook` importing the data, see `code/analyse_results.ipynb`. 92 | -------------------------------------------------------------------------------- /code/CRep.py: -------------------------------------------------------------------------------- 1 | """ 2 | Class definition of CRep, the algorithm to perform inference in networks with reciprocity. 3 | The latent variables are related to community memberships and reciprocity value. 4 | """ 5 | 6 | from __future__ import print_function 7 | import time 8 | import sys 9 | import sktensor as skt 10 | import numpy as np 11 | from termcolor import colored 12 | 13 | 14 | class CRep: 15 | def __init__(self, N=100, L=1, K=2, undirected=False, assortative=False, 16 | rseed=0, inf=1e10, err_max=1e-8, err=0.01, N_real=1, tolerance=0.0001, decision=10, max_iter=500, 17 | initialization=0, fix_eta=False, fix_communities=False, fix_w=False, constrained=True, 18 | eta0=None, files='../data/input/synthetic/theta.npz', 19 | verbose=False, out_inference=False, out_folder='../data/output/', end_file='.dat'): 20 | self.N = N # number of nodes 21 | self.L = L # number of layers 22 | self.K = K # number of communities 23 | self.undirected = undirected # flag to call the undirected network 24 | self.assortative = assortative # if True, the network is assortative 25 | self.rseed = rseed # random seed for the initialization 26 | self.inf = inf # initial value of the pseudo log-likelihood 27 | self.err_max = err_max # minimum value for the parameters 28 | self.err = err # noise for the initialization 29 | self.N_real = N_real # number of iterations with different random initialization 30 | self.tolerance = tolerance # tolerance parameter for convergence 31 | self.decision = decision # convergence parameter 32 | self.max_iter = max_iter # maximum number of EM steps before aborting 33 | self.fix_eta = fix_eta # if True, the eta parameter is fixed 34 | self.fix_communities = fix_communities # if True, keep the communities u and v fixed 35 | self.fix_w = fix_w # if True, keep the affinity tensor fixed 36 | self.constrained = constrained # if True, use the configuration with constraints on the updates 37 | self.files = files # path of the input files for u, v, w (when initialization>0) 38 | self.verbose = verbose # flag to print details 39 | self.out_inference = out_inference # flag for storing the inferred parameters 40 | self.out_folder = out_folder # path for storing the output 41 | self.end_file = end_file # output file suffix 42 | if initialization not in {0, 1, 2, 3}: # indicator for choosing how to initialize u, v and w 43 | raise ValueError('The initialization parameter can be either 0, 1, 2 or 3. It is used as an indicator to ' 44 | 'initialize the membership matrices u and v and the affinity matrix w. If it is 0, they ' 45 | 'will be generated randomly; 1 means only the affinity matrix w will be uploaded from ' 46 | 'file; 2 implies the membership matrices u and v will be uploaded from file and 3 all u, ' 47 | 'v and w will be initialized through an input file.') 48 | self.initialization = initialization 49 | if eta0 is not None: 50 | if (eta0 < 0) or (eta0 > 1): 51 | raise ValueError('The reciprocity coefficient eta0 has to be in [0, 1]!') 52 | self.eta0 = eta0 # initial value for the reciprocity coefficient 53 | if self.fix_eta: 54 | if self.eta0 is None: 55 | raise ValueError('If fix_eta=True, provide a value for eta0.') 56 | if self.fix_w: 57 | if self.initialization not in {1, 3}: 58 | raise ValueError('If fix_w=True, the initialization has to be either 1 or 3.') 59 | if self.fix_communities: 60 | if self.initialization not in {2, 3}: 61 | raise ValueError('If fix_communities=True, the initialization has to be either 2 or 3.') 62 | 63 | if self.initialization > 0: 64 | self.theta = np.load(self.files, allow_pickle=True) 65 | if self.initialization == 1: 66 | dfW = self.theta['w'] 67 | self.L = dfW.shape[0] 68 | self.K = dfW.shape[1] 69 | elif self.initialization == 2: 70 | dfU = self.theta['u'] 71 | self.N, self.K = dfU.shape 72 | else: 73 | dfW = self.theta['w'] 74 | dfU = self.theta['u'] 75 | self.L = dfW.shape[0] 76 | self.K = dfW.shape[1] 77 | self.N = dfU.shape[0] 78 | assert self.K == dfU.shape[1] 79 | 80 | if self.undirected: 81 | if not (self.fix_eta and self.eta0 == 0): 82 | raise ValueError('If undirected=True, the parameter eta has to be fixed equal to 0.') 83 | 84 | # values of the parameters used during the update 85 | self.u = np.zeros((self.N, self.K), dtype=float) # out-going membership 86 | self.v = np.zeros((self.N, self.K), dtype=float) # in-going membership 87 | self.eta = 0. # reciprocity coefficient 88 | 89 | # values of the parameters in the previous iteration 90 | self.u_old = np.zeros((self.N, self.K), dtype=float) # out-going membership 91 | self.v_old = np.zeros((self.N, self.K), dtype=float) # in-going membership 92 | self.eta_old = 0. # reciprocity coefficient 93 | 94 | # final values after convergence --> the ones that maximize the pseudo log-likelihood 95 | self.u_f = np.zeros((self.N, self.K), dtype=float) # out-going membership 96 | self.v_f = np.zeros((self.N, self.K), dtype=float) # in-going membership 97 | self.eta_f = 0. # reciprocity coefficient 98 | 99 | # values of the affinity tensor 100 | if self.assortative: # purely diagonal matrix 101 | self.w = np.zeros((self.L, self.K), dtype=float) 102 | self.w_old = np.zeros((self.L, self.K), dtype=float) 103 | self.w_f = np.zeros((self.L, self.K), dtype=float) 104 | else: 105 | self.w = np.zeros((self.L, self.K, self.K), dtype=float) 106 | self.w_old = np.zeros((self.L, self.K, self.K), dtype=float) 107 | self.w_f = np.zeros((self.L, self.K, self.K), dtype=float) 108 | 109 | if self.fix_eta: 110 | self.eta = self.eta_old = self.eta_f = self.eta0 111 | 112 | def fit(self, data, data_T, data_T_vals, nodes, flag_conv, mask=None): 113 | """ 114 | Model directed networks by using a probabilistic generative model that assume community parameters and 115 | reciprocity coefficient. The inference is performed via EM algorithm. 116 | 117 | Parameters 118 | ---------- 119 | data : ndarray/sptensor 120 | Graph adjacency tensor. 121 | data_T: None/sptensor 122 | Graph adjacency tensor (transpose) - if sptensor. 123 | data_T_vals : None/ndarray 124 | Array with values of entries A[j, i] given non-zero entry (i, j) - if ndarray. 125 | nodes : list 126 | List of nodes IDs. 127 | flag_conv : str 128 | If 'log' the convergence is based on the log-likelihood values; if 'deltas' the convergence is 129 | based on the differences in the parameters values. The latter is suggested when the dataset 130 | is big (N > 1000 ca.). 131 | mask : ndarray 132 | Mask for selecting the held out set in the adjacency tensor in case of cross-validation. 133 | 134 | Returns 135 | ------- 136 | u_f : ndarray 137 | Out-going membership matrix. 138 | v_f : ndarray 139 | In-coming membership matrix. 140 | w_f : ndarray 141 | Affinity tensor. 142 | eta_f : float 143 | Reciprocity coefficient. 144 | maxL : float 145 | Maximum pseudo log-likelihood. 146 | final_it : int 147 | Total number of iterations. 148 | """ 149 | 150 | maxL = -self.inf # initialization of the maximum pseudo log-likelihood 151 | 152 | if data_T is None: 153 | E = np.sum(data) # weighted sum of edges (needed in the denominator of eta) 154 | data_T = np.einsum('aij->aji', data) 155 | data_T_vals = get_item_array_from_subs(data_T, data.nonzero()) 156 | # pre-processing of the data to handle the sparsity 157 | data = preprocess(data) 158 | data_T = preprocess(data_T) 159 | else: 160 | E = np.sum(data.vals) 161 | 162 | # save the indexes of the nonzero entries 163 | if isinstance(data, skt.dtensor): 164 | subs_nz = data.nonzero() 165 | elif isinstance(data, skt.sptensor): 166 | subs_nz = data.subs 167 | 168 | rng = np.random.RandomState(self.rseed) 169 | 170 | for r in range(self.N_real): 171 | 172 | self._initialize(rng=rng, nodes=nodes) 173 | 174 | self._update_old_variables() 175 | self._update_cache(data, data_T_vals, subs_nz) 176 | 177 | # convergence local variables 178 | coincide, it = 0, 0 179 | convergence = False 180 | loglik = self.inf 181 | 182 | if self.verbose: 183 | print(f'Updating realization {r} ...') 184 | time_start = time.time() 185 | # --- single step iteration update --- 186 | while np.logical_and(not convergence, it < self.max_iter): 187 | # main EM update: updates memberships and calculates max difference new vs old 188 | delta_u, delta_v, delta_w, delta_eta = self._update_em(data, data_T_vals, subs_nz, denominator=E) 189 | if flag_conv == 'log': 190 | it, loglik, coincide, convergence = self._check_for_convergence(data, it, loglik, coincide, 191 | convergence, data_T=data_T, 192 | mask=mask) 193 | if self.verbose: 194 | if not it % 100: 195 | print(f'Nreal = {r} - Pseudo Log-likelihood = {loglik} - iterations = {it} - ' 196 | f'time = {np.round(time.time() - time_start, 2)} seconds') 197 | elif flag_conv == 'deltas': 198 | it, coincide, convergence = self._check_for_convergence_delta(it, coincide, delta_u, delta_v, 199 | delta_w, delta_eta, convergence) 200 | if self.verbose: 201 | if not it % 100: 202 | print(f'Nreal = {r} - iterations = {it} - ' 203 | f'time = {np.round(time.time() - time_start, 2)} seconds') 204 | else: 205 | raise ValueError('flag_conv can be either log or deltas!') 206 | 207 | if flag_conv == 'log': 208 | if maxL < loglik: 209 | self._update_optimal_parameters() 210 | maxL = loglik 211 | self.final_it = it 212 | conv = convergence 213 | elif flag_conv == 'deltas': 214 | loglik = self._PSLikelihood(data, data_T=data_T, mask=mask) 215 | if maxL < loglik: 216 | self._update_optimal_parameters() 217 | maxL = loglik 218 | self.final_it = it 219 | conv = convergence 220 | if self.verbose: 221 | print(f'Nreal = {r} - Pseudo Log-likelihood = {loglik} - iterations = {it} - ' 222 | f'time = {np.round(time.time() - time_start, 2)} seconds\n') 223 | 224 | # end cycle over realizations 225 | 226 | self.maxPSL = maxL 227 | if np.logical_and(self.final_it == self.max_iter, not conv): 228 | # convergence not reaches 229 | try: 230 | print(colored('Solution failed to converge in {0} EM steps!'.format(self.max_iter), 'blue')) 231 | except: 232 | print('Solution failed to converge in {0} EM steps!'.format(self.max_iter)) 233 | 234 | if self.out_inference: 235 | self.output_results(nodes) 236 | 237 | return self.u_f, self.v_f, self.w_f, self.eta_f, maxL 238 | 239 | def _initialize(self, rng, nodes): 240 | """ 241 | Random initialization of the parameters u, v, w, eta. 242 | 243 | Parameters 244 | ---------- 245 | rng : RandomState 246 | Container for the Mersenne Twister pseudo-random number generator. 247 | nodes : list 248 | List of nodes IDs. 249 | """ 250 | 251 | if rng is None: 252 | rng = np.random.RandomState(self.rseed) 253 | 254 | if self.eta0 is not None: 255 | self.eta = self.eta0 256 | else: 257 | if self.verbose: 258 | print('eta is initialized randomly.') 259 | self._randomize_eta(rng=rng) 260 | 261 | if self.initialization == 0: 262 | if self.verbose: 263 | print('u, v and w are initialized randomly.') 264 | self._randomize_w(rng=rng) 265 | self._randomize_u_v(rng=rng) 266 | 267 | elif self.initialization == 1: 268 | if self.verbose: 269 | print(f'w is initialized using the input file: {self.files}.') 270 | print('u and v are initialized randomly.') 271 | self._initialize_w(rng) 272 | self._randomize_u_v(rng=rng) 273 | 274 | elif self.initialization == 2: 275 | if self.verbose: 276 | print(f'u and v are initialized using the input file: {self.files}.') 277 | print('w is initialized randomly.') 278 | self._initialize_u(rng, nodes) 279 | self._initialize_v(rng, nodes) 280 | self._randomize_w(rng=rng) 281 | 282 | elif self.initialization == 3: 283 | if self.verbose: 284 | print(f'u, v and w are initialized using the input file: {self.files}.') 285 | self._initialize_u(rng, nodes) 286 | self._initialize_v(rng, nodes) 287 | self._initialize_w(rng) 288 | 289 | def _randomize_eta(self, rng): 290 | """ 291 | Generate a random number in (0, 1.). 292 | 293 | Parameters 294 | ---------- 295 | rng : RandomState 296 | Container for the Mersenne Twister pseudo-random number generator. 297 | """ 298 | 299 | if rng is None: 300 | rng = np.random.RandomState(self.rseed) 301 | self.eta = rng.random_sample(1)[0] 302 | 303 | def _randomize_w(self, rng): 304 | """ 305 | Assign a random number in (0, 1.) to each entry of the affinity tensor w. 306 | 307 | Parameters 308 | ---------- 309 | rng : RandomState 310 | Container for the Mersenne Twister pseudo-random number generator. 311 | """ 312 | 313 | if rng is None: 314 | rng = np.random.RandomState(self.rseed) 315 | for i in range(self.L): 316 | for k in range(self.K): 317 | if self.assortative: 318 | self.w[i, k] = rng.random_sample(1) 319 | else: 320 | for q in range(k, self.K): 321 | if q == k: 322 | self.w[i, k, q] = rng.random_sample(1) 323 | else: 324 | self.w[i, k, q] = self.w[i, q, k] = self.err * rng.random_sample(1) 325 | 326 | def _randomize_u_v(self, rng): 327 | """ 328 | Assign a random number in (0, 1.) to each entry of the membership matrices u and v, and normalize each row. 329 | 330 | Parameters 331 | ---------- 332 | rng : RandomState 333 | Container for the Mersenne Twister pseudo-random number generator. 334 | """ 335 | 336 | if rng is None: 337 | rng = np.random.RandomState(self.rseed) 338 | self.u = rng.random_sample(self.u.shape) 339 | row_sums = self.u.sum(axis=1) 340 | self.u[row_sums > 0] /= row_sums[row_sums > 0, np.newaxis] 341 | 342 | if not self.undirected: 343 | self.v = rng.random_sample(self.v.shape) 344 | row_sums = self.v.sum(axis=1) 345 | self.v[row_sums > 0] /= row_sums[row_sums > 0, np.newaxis] 346 | else: 347 | self.v = self.u 348 | 349 | def _initialize_u(self, rng, nodes): 350 | """ 351 | Initialize out-going membership matrix u from file. 352 | 353 | Parameters 354 | ---------- 355 | rng : RandomState 356 | Container for the Mersenne Twister pseudo-random number generator. 357 | nodes : list 358 | List of nodes IDs. 359 | """ 360 | 361 | self.u = self.theta['u'] 362 | assert np.array_equal(nodes, self.theta['nodes']) 363 | 364 | max_entry = np.max(self.u) 365 | self.u += max_entry * self.err * rng.random_sample(self.u.shape) 366 | 367 | def _initialize_v(self, rng, nodes): 368 | """ 369 | Initialize in-coming membership matrix v from file. 370 | 371 | Parameters 372 | ---------- 373 | rng : RandomState 374 | Container for the Mersenne Twister pseudo-random number generator. 375 | nodes : list 376 | List of nodes IDs. 377 | """ 378 | 379 | if self.undirected: 380 | self.v = self.u 381 | else: 382 | self.v = self.theta['v'] 383 | assert np.array_equal(nodes, self.theta['nodes']) 384 | 385 | max_entry = np.max(self.v) 386 | self.v += max_entry * self.err * rng.random_sample(self.v.shape) 387 | 388 | def _initialize_w(self, rng): 389 | """ 390 | Initialize affinity tensor w from file. 391 | 392 | Parameters 393 | ---------- 394 | rng : RandomState 395 | Container for the Mersenne Twister pseudo-random number generator. 396 | """ 397 | 398 | if self.assortative: 399 | self.w = self.theta['w'] 400 | assert self.w.shape == (self.L, self.K) 401 | else: 402 | self.w = self.theta['w'] 403 | 404 | max_entry = np.max(self.w) 405 | self.w += max_entry * self.err * rng.random_sample(self.w.shape) 406 | 407 | def _update_old_variables(self): 408 | """ 409 | Update values of the parameters in the previous iteration. 410 | """ 411 | 412 | self.u_old[self.u > 0] = np.copy(self.u[self.u > 0]) 413 | self.v_old[self.v > 0] = np.copy(self.v[self.v > 0]) 414 | self.w_old[self.w > 0] = np.copy(self.w[self.w > 0]) 415 | self.eta_old = np.copy(self.eta) 416 | 417 | def _update_cache(self, data, data_T_vals, subs_nz): 418 | """ 419 | Update the cache used in the em_update. 420 | 421 | Parameters 422 | ---------- 423 | data : sptensor/dtensor 424 | Graph adjacency tensor. 425 | data_T_vals : ndarray 426 | Array with values of entries A[j, i] given non-zero entry (i, j). 427 | subs_nz : tuple 428 | Indices of elements of data that are non-zero. 429 | """ 430 | 431 | self.lambda0_nz = self._lambda0_nz(subs_nz) 432 | self.M_nz = self.lambda0_nz + self.eta * data_T_vals 433 | self.M_nz[self.M_nz == 0] = 1 434 | if isinstance(data, skt.dtensor): 435 | self.data_M_nz = data[subs_nz] / self.M_nz 436 | elif isinstance(data, skt.sptensor): 437 | self.data_M_nz = data.vals / self.M_nz 438 | self.data_M_nz[self.M_nz == 0] = 0 439 | 440 | def _lambda0_nz(self, subs_nz): 441 | """ 442 | Compute the mean lambda0_ij for only non-zero entries. 443 | 444 | Parameters 445 | ---------- 446 | subs_nz : tuple 447 | Indices of elements of data that are non-zero. 448 | 449 | Returns 450 | ------- 451 | nz_recon_I : ndarray 452 | Mean lambda0_ij for only non-zero entries. 453 | """ 454 | 455 | if not self.assortative: 456 | nz_recon_IQ = np.einsum('Ik,Ikq->Iq', self.u[subs_nz[1], :], self.w[subs_nz[0], :, :]) 457 | else: 458 | nz_recon_IQ = np.einsum('Ik,Ik->Ik', self.u[subs_nz[1], :], self.w[subs_nz[0], :]) 459 | nz_recon_I = np.einsum('Iq,Iq->I', nz_recon_IQ, self.v[subs_nz[2], :]) 460 | 461 | return nz_recon_I 462 | 463 | def _update_em(self, data, data_T_vals, subs_nz, denominator=None): 464 | """ 465 | Update parameters via EM procedure. 466 | 467 | Parameters 468 | ---------- 469 | data : sptensor/dtensor 470 | Graph adjacency tensor. 471 | data_T_vals : ndarray 472 | Array with values of entries A[j, i] given non-zero entry (i, j). 473 | subs_nz : tuple 474 | Indices of elements of data that are non-zero. 475 | denominator : float 476 | Denominator used in the update of the eta parameter. 477 | 478 | Returns 479 | ------- 480 | d_u : float 481 | Maximum distance between the old and the new membership matrix u. 482 | d_v : float 483 | Maximum distance between the old and the new membership matrix v. 484 | d_w : float 485 | Maximum distance between the old and the new affinity tensor w. 486 | d_eta : float 487 | Maximum distance between the old and the new reciprocity coefficient eta. 488 | """ 489 | 490 | if not self.fix_eta: 491 | d_eta = self._update_eta(data, data_T_vals, denominator=denominator) 492 | else: 493 | d_eta = 0. 494 | self._update_cache(data, data_T_vals, subs_nz) 495 | 496 | if not self.fix_communities: 497 | d_u = self._update_U(subs_nz) 498 | self._update_cache(data, data_T_vals, subs_nz) 499 | else: 500 | d_u = 0. 501 | 502 | if self.undirected: 503 | self.v = self.u 504 | self.v_old = self.v 505 | d_v = d_u 506 | self._update_cache(data, data_T_vals, subs_nz) 507 | else: 508 | if not self.fix_communities: 509 | d_v = self._update_V(subs_nz) 510 | self._update_cache(data, data_T_vals, subs_nz) 511 | else: 512 | d_v = 0. 513 | 514 | if not self.fix_w: 515 | if not self.assortative: 516 | d_w = self._update_W(subs_nz) 517 | else: 518 | d_w = self._update_W_assortative(subs_nz) 519 | self._update_cache(data, data_T_vals, subs_nz) 520 | else: 521 | d_w = 0 522 | 523 | return d_u, d_v, d_w, d_eta 524 | 525 | def _update_eta(self, data, data_T_vals, denominator=None): 526 | """ 527 | Update reciprocity coefficient eta. 528 | 529 | Parameters 530 | ---------- 531 | data : sptensor/dtensor 532 | Graph adjacency tensor. 533 | data_T_vals : ndarray 534 | Array with values of entries A[j, i] given non-zero entry (i, j). 535 | denominator : float 536 | Denominator used in the update of the eta parameter. 537 | 538 | Returns 539 | ------- 540 | dist_eta : float 541 | Maximum distance between the old and the new reciprocity coefficient eta. 542 | """ 543 | 544 | if denominator is None: 545 | Deta = data.sum() 546 | else: 547 | Deta = denominator 548 | 549 | self.eta *= (self.data_M_nz * data_T_vals).sum() / Deta 550 | 551 | dist_eta = abs(self.eta - self.eta_old) 552 | self.eta_old = np.copy(self.eta) 553 | 554 | return dist_eta 555 | 556 | def _update_U(self, subs_nz): 557 | """ 558 | Update out-going membership matrix. 559 | 560 | Parameters 561 | ---------- 562 | subs_nz : tuple 563 | Indices of elements of data that are non-zero. 564 | 565 | Returns 566 | ------- 567 | dist_u : float 568 | Maximum distance between the old and the new membership matrix u. 569 | """ 570 | 571 | self.u = self.u_old * self._update_membership(subs_nz, 1) 572 | 573 | if not self.constrained: 574 | Du = np.einsum('iq->q', self.v) 575 | if not self.assortative: 576 | w_k = np.einsum('akq->kq', self.w) 577 | Z_uk = np.einsum('q,kq->k', Du, w_k) 578 | else: 579 | w_k = np.einsum('ak->k', self.w) 580 | Z_uk = np.einsum('k,k->k', Du, w_k) 581 | non_zeros = Z_uk > 0. 582 | self.u[:, Z_uk == 0] = 0. 583 | self.u[:, non_zeros] /= Z_uk[np.newaxis, non_zeros] 584 | else: 585 | row_sums = self.u.sum(axis=1) 586 | self.u[row_sums > 0] /= row_sums[row_sums > 0, np.newaxis] 587 | 588 | low_values_indices = self.u < self.err_max # values are too low 589 | self.u[low_values_indices] = 0. # and set to 0. 590 | 591 | dist_u = np.amax(abs(self.u - self.u_old)) 592 | self.u_old = np.copy(self.u) 593 | 594 | return dist_u 595 | 596 | def _update_V(self, subs_nz): 597 | """ 598 | Update in-coming membership matrix. 599 | Same as _update_U but with: 600 | data <-> data_T 601 | w <-> w_T 602 | u <-> v 603 | 604 | Parameters 605 | ---------- 606 | subs_nz : tuple 607 | Indices of elements of data that are non-zero. 608 | 609 | Returns 610 | ------- 611 | dist_v : float 612 | Maximum distance between the old and the new membership matrix v. 613 | """ 614 | 615 | self.v *= self._update_membership(subs_nz, 2) 616 | 617 | if not self.constrained: 618 | Dv = np.einsum('iq->q', self.u) 619 | if not self.assortative: 620 | w_k = np.einsum('aqk->qk', self.w) 621 | Z_vk = np.einsum('q,qk->k', Dv, w_k) 622 | else: 623 | w_k = np.einsum('ak->k', self.w) 624 | Z_vk = np.einsum('k,k->k', Dv, w_k) 625 | non_zeros = Z_vk > 0 626 | self.v[:, Z_vk == 0] = 0. 627 | self.v[:, non_zeros] /= Z_vk[np.newaxis, non_zeros] 628 | else: 629 | row_sums = self.v.sum(axis=1) 630 | self.v[row_sums > 0] /= row_sums[row_sums > 0, np.newaxis] 631 | 632 | low_values_indices = self.v < self.err_max # values are too low 633 | self.v[low_values_indices] = 0. # and set to 0. 634 | 635 | dist_v = np.amax(abs(self.v - self.v_old)) 636 | self.v_old = np.copy(self.v) 637 | 638 | return dist_v 639 | 640 | def _update_W(self, subs_nz): 641 | """ 642 | Update affinity tensor. 643 | 644 | Parameters 645 | ---------- 646 | subs_nz : tuple 647 | Indices of elements of data that are non-zero. 648 | 649 | Returns 650 | ------- 651 | dist_w : float 652 | Maximum distance between the old and the new affinity tensor w. 653 | """ 654 | 655 | uttkrp_DKQ = np.zeros_like(self.w) 656 | 657 | UV = np.einsum('Ik,Iq->Ikq', self.u[subs_nz[1], :], self.v[subs_nz[2], :]) 658 | uttkrp_I = self.data_M_nz[:, np.newaxis, np.newaxis] * UV 659 | for k in range(self.K): 660 | for q in range(self.K): 661 | uttkrp_DKQ[:, k, q] += np.bincount(subs_nz[0], weights=uttkrp_I[:, k, q], minlength=self.L) 662 | 663 | self.w *= uttkrp_DKQ 664 | 665 | Z = np.einsum('k,q->kq', self.u.sum(axis=0), self.v.sum(axis=0))[np.newaxis, :, :] 666 | non_zeros = Z > 0 667 | self.w[non_zeros] /= Z[non_zeros] 668 | 669 | low_values_indices = self.w < self.err_max # values are too low 670 | self.w[low_values_indices] = 0. # and set to 0. 671 | 672 | dist_w = np.amax(abs(self.w - self.w_old)) 673 | self.w_old = np.copy(self.w) 674 | 675 | return dist_w 676 | 677 | def _update_W_assortative(self, subs_nz): 678 | """ 679 | Update affinity tensor (assuming assortativity). 680 | 681 | Parameters 682 | ---------- 683 | subs_nz : tuple 684 | Indices of elements of data that are non-zero. 685 | 686 | Returns 687 | ------- 688 | dist_w : float 689 | Maximum distance between the old and the new affinity tensor w. 690 | """ 691 | 692 | uttkrp_DKQ = np.zeros_like(self.w) 693 | 694 | UV = np.einsum('Ik,Ik->Ik', self.u[subs_nz[1], :], self.v[subs_nz[2], :]) 695 | uttkrp_I = self.data_M_nz[:, np.newaxis] * UV 696 | for k in range(self.K): 697 | uttkrp_DKQ[:, k] += np.bincount(subs_nz[0], weights=uttkrp_I[:, k], minlength=self.L) 698 | 699 | self.w *= uttkrp_DKQ 700 | 701 | Z = ((self.u_old.sum(axis=0)) * (self.v_old.sum(axis=0)))[np.newaxis, :] 702 | non_zeros = Z > 0 703 | self.w[non_zeros] /= Z[non_zeros] 704 | 705 | low_values_indices = self.w < self.err_max # values are too low 706 | self.w[low_values_indices] = 0. # and set to 0. 707 | 708 | dist_w = np.amax(abs(self.w - self.w_old)) 709 | self.w_old = np.copy(self.w) 710 | 711 | return dist_w 712 | 713 | def _update_membership(self, subs_nz, m): 714 | """ 715 | Return the Khatri-Rao product (sparse version) used in the update of the membership matrices. 716 | 717 | Parameters 718 | ---------- 719 | subs_nz : tuple 720 | Indices of elements of data that are non-zero. 721 | m : int 722 | Mode in which the Khatri-Rao product of the membership matrix is multiplied with the tensor: if 1 it 723 | works with the matrix u; if 2 it works with v. 724 | 725 | Returns 726 | ------- 727 | uttkrp_DK : ndarray 728 | Matrix which is the result of the matrix product of the unfolding of the tensor and the 729 | Khatri-Rao product of the membership matrix. 730 | """ 731 | 732 | if not self.assortative: 733 | uttkrp_DK = sp_uttkrp(self.data_M_nz, subs_nz, m, self.u, self.v, self.w) 734 | else: 735 | uttkrp_DK = sp_uttkrp_assortative(self.data_M_nz, subs_nz, m, self.u, self.v, self.w) 736 | 737 | return uttkrp_DK 738 | 739 | def _check_for_convergence(self, data, it, loglik, coincide, convergence, data_T=None, mask=None): 740 | """ 741 | Check for convergence by using the pseudo log-likelihood values. 742 | 743 | Parameters 744 | ---------- 745 | data : sptensor/dtensor 746 | Graph adjacency tensor. 747 | it : int 748 | Number of iteration. 749 | loglik : float 750 | Pseudo log-likelihood value. 751 | coincide : int 752 | Number of time the update of the pseudo log-likelihood respects the tolerance. 753 | convergence : bool 754 | Flag for convergence. 755 | data_T : sptensor/dtensor 756 | Graph adjacency tensor (transpose). 757 | mask : ndarray 758 | Mask for selecting the held out set in the adjacency tensor in case of cross-validation. 759 | 760 | Returns 761 | ------- 762 | it : int 763 | Number of iteration. 764 | loglik : float 765 | Pseudo log-likelihood value. 766 | coincide : int 767 | Number of time the update of the pseudo log-likelihood respects the tolerance. 768 | convergence : bool 769 | Flag for convergence. 770 | """ 771 | 772 | if it % 10 == 0: 773 | old_L = loglik 774 | loglik = self._PSLikelihood(data, data_T=data_T, mask=mask) 775 | if abs(loglik - old_L) < self.tolerance: 776 | coincide += 1 777 | else: 778 | coincide = 0 779 | if coincide > self.decision: 780 | convergence = True 781 | it += 1 782 | 783 | return it, loglik, coincide, convergence 784 | 785 | def _check_for_convergence_delta(self, it, coincide, du, dv, dw, de, convergence): 786 | """ 787 | Check for convergence by using the maximum distances between the old and the new parameters values. 788 | 789 | Parameters 790 | ---------- 791 | it : int 792 | Number of iteration. 793 | coincide : int 794 | Number of time the update of the log-likelihood respects the tolerance. 795 | du : float 796 | Maximum distance between the old and the new membership matrix U. 797 | dv : float 798 | Maximum distance between the old and the new membership matrix V. 799 | dw : float 800 | Maximum distance between the old and the new affinity tensor W. 801 | de : float 802 | Maximum distance between the old and the new eta parameter. 803 | convergence : bool 804 | Flag for convergence. 805 | 806 | Returns 807 | ------- 808 | it : int 809 | Number of iteration. 810 | coincide : int 811 | Number of time the update of the log-likelihood respects the tolerance. 812 | convergence : bool 813 | Flag for convergence. 814 | """ 815 | 816 | if du < self.tolerance and dv < self.tolerance and dw < self.tolerance and de < self.tolerance: 817 | coincide += 1 818 | else: 819 | coincide = 0 820 | if coincide > self.decision: 821 | convergence = True 822 | it += 1 823 | 824 | return it, coincide, convergence 825 | 826 | def _PSLikelihood(self, data, data_T, mask=None): 827 | """ 828 | Compute the pseudo log-likelihood of the data. 829 | 830 | Parameters 831 | ---------- 832 | data : sptensor/dtensor 833 | Graph adjacency tensor. 834 | data_T : sptensor/dtensor 835 | Graph adjacency tensor (transpose). 836 | mask : ndarray 837 | Mask for selecting the held out set in the adjacency tensor in case of cross-validation. 838 | 839 | Returns 840 | ------- 841 | l : float 842 | Pseudo log-likelihood value. 843 | """ 844 | 845 | self.lambda0_ija = self._lambda0_full(self.u, self.v, self.w) 846 | 847 | if mask is not None: 848 | sub_mask_nz = mask.nonzero() 849 | if isinstance(data, skt.dtensor): 850 | l = -self.lambda0_ija[sub_mask_nz].sum() - self.eta * data_T[sub_mask_nz].sum() 851 | elif isinstance(data, skt.sptensor): 852 | l = -self.lambda0_ija[sub_mask_nz].sum() - self.eta * data_T.toarray()[sub_mask_nz].sum() 853 | else: 854 | if isinstance(data, skt.dtensor): 855 | l = -self.lambda0_ija.sum() - self.eta * data_T.sum() 856 | elif isinstance(data, skt.sptensor): 857 | l = -self.lambda0_ija.sum() - self.eta * data_T.vals.sum() 858 | logM = np.log(self.M_nz) 859 | if isinstance(data, skt.dtensor): 860 | Alog = data[data.nonzero()] * logM 861 | elif isinstance(data, skt.sptensor): 862 | Alog = data.vals * logM 863 | 864 | l += Alog.sum() 865 | 866 | if np.isnan(l): 867 | print("PSLikelihood is NaN!!!!") 868 | sys.exit(1) 869 | else: 870 | return l 871 | 872 | def _lambda0_full(self, u, v, w): 873 | """ 874 | Compute the mean lambda0 for all entries. 875 | 876 | Parameters 877 | ---------- 878 | u : ndarray 879 | Out-going membership matrix. 880 | v : ndarray 881 | In-coming membership matrix. 882 | w : ndarray 883 | Affinity tensor. 884 | 885 | Returns 886 | ------- 887 | M : ndarray 888 | Mean lambda0 for all entries. 889 | """ 890 | 891 | if w.ndim == 2: 892 | M = np.einsum('ik,jk->ijk', u, v) 893 | M = np.einsum('ijk,ak->aij', M, w) 894 | else: 895 | M = np.einsum('ik,jq->ijkq', u, v) 896 | M = np.einsum('ijkq,akq->aij', M, w) 897 | return M 898 | 899 | def _update_optimal_parameters(self): 900 | """ 901 | Update values of the parameters after convergence. 902 | """ 903 | 904 | self.u_f = np.copy(self.u) 905 | self.v_f = np.copy(self.v) 906 | self.w_f = np.copy(self.w) 907 | self.eta_f = np.copy(self.eta) 908 | 909 | def output_results(self, nodes): 910 | """ 911 | Output results. 912 | 913 | Parameters 914 | ---------- 915 | nodes : list 916 | List of nodes IDs. 917 | """ 918 | 919 | outfile = self.out_folder + 'theta' + self.end_file 920 | np.savez_compressed(outfile + '.npz', u=self.u_f, v=self.v_f, w=self.w_f, eta=self.eta_f, max_it=self.final_it, 921 | maxPSL=self.maxPSL, nodes=nodes) 922 | print(f'\nInferred parameters saved in: {outfile + ".npz"}') 923 | print('To load: theta=np.load(filename), then e.g. theta["u"]') 924 | 925 | 926 | def sp_uttkrp(vals, subs, m, u, v, w): 927 | """ 928 | Compute the Khatri-Rao product (sparse version). 929 | 930 | Parameters 931 | ---------- 932 | vals : ndarray 933 | Values of the non-zero entries. 934 | subs : tuple 935 | Indices of elements that are non-zero. It is a n-tuple of array-likes and the length of tuple n must be 936 | equal to the dimension of tensor. 937 | m : int 938 | Mode in which the Khatri-Rao product of the membership matrix is multiplied with the tensor: if 1 it 939 | works with the matrix u; if 2 it works with v. 940 | u : ndarray 941 | Out-going membership matrix. 942 | v : ndarray 943 | In-coming membership matrix. 944 | w : ndarray 945 | Affinity tensor. 946 | 947 | Returns 948 | ------- 949 | out : ndarray 950 | Matrix which is the result of the matrix product of the unfolding of the tensor and the Khatri-Rao product 951 | of the membership matrix. 952 | """ 953 | 954 | if m == 1: 955 | D, K = u.shape 956 | out = np.zeros_like(u) 957 | elif m == 2: 958 | D, K = v.shape 959 | out = np.zeros_like(v) 960 | 961 | for k in range(K): 962 | tmp = vals.copy() 963 | if m == 1: # we are updating u 964 | tmp *= (w[subs[0], k, :].astype(tmp.dtype) * v[subs[2], :].astype(tmp.dtype)).sum(axis=1) 965 | elif m == 2: # we are updating v 966 | tmp *= (w[subs[0], :, k].astype(tmp.dtype) * u[subs[1], :].astype(tmp.dtype)).sum(axis=1) 967 | out[:, k] += np.bincount(subs[m], weights=tmp, minlength=D) 968 | 969 | return out 970 | 971 | 972 | def sp_uttkrp_assortative(vals, subs, m, u, v, w): 973 | """ 974 | Compute the Khatri-Rao product (sparse version) with the assumption of assortativity. 975 | 976 | Parameters 977 | ---------- 978 | vals : ndarray 979 | Values of the non-zero entries. 980 | subs : tuple 981 | Indices of elements that are non-zero. It is a n-tuple of array-likes and the length of tuple n must be 982 | equal to the dimension of tensor. 983 | m : int 984 | Mode in which the Khatri-Rao product of the membership matrix is multiplied with the tensor: if 1 it 985 | works with the matrix u; if 2 it works with v. 986 | u : ndarray 987 | Out-going membership matrix. 988 | v : ndarray 989 | In-coming membership matrix. 990 | w : ndarray 991 | Affinity tensor. 992 | 993 | Returns 994 | ------- 995 | out : ndarray 996 | Matrix which is the result of the matrix product of the unfolding of the tensor and the Khatri-Rao product 997 | of the membership matrix. 998 | """ 999 | 1000 | if m == 1: 1001 | D, K = u.shape 1002 | out = np.zeros_like(u) 1003 | elif m == 2: 1004 | D, K = v.shape 1005 | out = np.zeros_like(v) 1006 | 1007 | for k in range(K): 1008 | tmp = vals.copy() 1009 | if m == 1: # we are updating u 1010 | tmp *= w[subs[0], k].astype(tmp.dtype) * v[subs[2], k].astype(tmp.dtype) 1011 | elif m == 2: # we are updating v 1012 | tmp *= w[subs[0], k].astype(tmp.dtype) * u[subs[1], k].astype(tmp.dtype) 1013 | out[:, k] += np.bincount(subs[m], weights=tmp, minlength=D) 1014 | 1015 | return out 1016 | 1017 | 1018 | def get_item_array_from_subs(A, ref_subs): 1019 | """ 1020 | Get values of ref_subs entries of a dense tensor. 1021 | Output is a 1-d array with dimension = number of non zero entries. 1022 | """ 1023 | 1024 | return np.array([A[a, i, j] for a, i, j in zip(*ref_subs)]) 1025 | 1026 | 1027 | def preprocess(A): 1028 | """ 1029 | Pre-process input data tensor. 1030 | If the input is sparse, returns an int sptensor. Otherwise, returns an int dtensor. 1031 | 1032 | Parameters 1033 | ---------- 1034 | A : ndarray 1035 | Input data (tensor). 1036 | 1037 | Returns 1038 | ------- 1039 | A : sptensor/dtensor 1040 | Pre-processed data. If the input is sparse, returns an int sptensor. Otherwise, returns an int dtensor. 1041 | """ 1042 | 1043 | if not A.dtype == np.dtype(int).type: 1044 | A = A.astype(int) 1045 | if np.logical_and(isinstance(A, np.ndarray), is_sparse(A)): 1046 | A = sptensor_from_dense_array(A) 1047 | else: 1048 | A = skt.dtensor(A) 1049 | 1050 | return A 1051 | 1052 | 1053 | def is_sparse(X): 1054 | """ 1055 | Check whether the input tensor is sparse. 1056 | It implements a heuristic definition of sparsity. A tensor is considered sparse if: 1057 | given 1058 | M = number of modes 1059 | S = number of entries 1060 | I = number of non-zero entries 1061 | then 1062 | N > M(I + 1) 1063 | 1064 | Parameters 1065 | ---------- 1066 | X : ndarray 1067 | Input data. 1068 | 1069 | Returns 1070 | ------- 1071 | Boolean flag: true if the input tensor is sparse, false otherwise. 1072 | """ 1073 | 1074 | M = X.ndim 1075 | S = X.size 1076 | I = X.nonzero()[0].size 1077 | 1078 | return S > (I + 1) * M 1079 | 1080 | 1081 | def sptensor_from_dense_array(X): 1082 | """ 1083 | Create an sptensor from a ndarray or dtensor. 1084 | Parameters 1085 | ---------- 1086 | X : ndarray 1087 | Input data. 1088 | 1089 | Returns 1090 | ------- 1091 | sptensor from a ndarray or dtensor. 1092 | """ 1093 | 1094 | subs = X.nonzero() 1095 | vals = X[subs] 1096 | 1097 | return skt.sptensor(subs, vals, shape=X.shape, dtype=X.dtype) 1098 | -------------------------------------------------------------------------------- /code/README.md: -------------------------------------------------------------------------------- 1 | # CRep: Python code 2 | Copyright (c) 2020 [Hadiseh Safdari](https://github.com/hds-safdari), [Martina Contisciani](https://www.is.mpg.de/person/mcontisciani) and [Caterina De Bacco](http://cdebacco.com). 3 | 4 | Implements the algorithm described in: 5 | 6 | [1] Safdari H., Contisciani M. & De Bacco C. (2021). *Generative model for reciprocity and community detection in networks*, Phys. Rev. Research 3, 023209. 7 | 8 | If you use this code please cite this [article](https://journals.aps.org/prresearch/abstract/10.1103/PhysRevResearch.3.023209) (_Published version, open access_). 9 | 10 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 13 | 14 | THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON INFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 15 | 16 | 17 | ## Files 18 | - `main.py` : General version of the algorithm. It performs the inference in the given single-layer directed network. It infers latent variables as community memberships to nodes and a reciprocity parameter to the whole network. 19 | - `CRep.py` : Class definition of CRep, the algorithm to perform inference in networks with reciprocity. The latent variables are related to community memberships and reciprocity value. This code is optimized to use sparse matrices. 20 | - `generate_data.py` : Code for generating the benchmark synthetic data with an intrinsic community structure and a given reciprocity value. 21 | - `generative_model_reciprocity.py` : Class definition of the reciprocity generative model with the member functions required. It builds a directed, possibly weighted, network. It contains functions to generate networks with an intrinsic community structure and a given reciprocity value, with reciprocity-only or without reciprocity. 22 | - `tools.py` : Contains non-class functions for handling the data. 23 | - `main_cv.py` : Code for performing a k-fold cross-validation procedure, in order to estimate the hyperparameter **K** (number of communities). It runs with a given K and returns a csv file summarizing the results over all folds. The output file contains the value of the pseudo log-likelihood, the regular AUC and the conditional AUC of the link prediction, both in the train and in test sets. 24 | - `cv_functions.py` : Contains functions for performing the k-fold cross-validation procedure. 25 | - `test.py` : Code for testing the main algorithm. 26 | - `test_cv.py` : Code for testing the cross-validation procedure. 27 | - `setting_syn_data.yaml` : Setting to generate synthetic data (input for *generate_data.py*). 28 | - `setting_CRep.yaml` : Setting to run the algorithm CRep (input for *main.py* and *main\_cv.py*). 29 | - `setting_CRepnc.yaml` : Setting to run the algorithm CRep without normalization constraints on the membership parameters (input for *main.py* and *main\_cv.py*). 30 | - `setting_CRep0.yaml` : Setting to run the algorithm CRep without considering the reciprocity effect (input for *main.py* and *main\_cv.py*). 31 | - `analyse_results.ipynb` : Example jupyter notebook to import the output results. 32 | 33 | ## Usage 34 | To test the program on the given example file, type 35 | 36 | ```bash 37 | python main.py 38 | ``` 39 | 40 | It will use the sample network contained in `./data/input`. The adjacency matrix *syn111.dat* represents a directed, weighted network with **N=600** nodes, **K=3** equal-size unmixed communities with an **assortative** structure and reciprocity parameter **eta=0.5**. 41 | 42 | ### Parameters 43 | - **-a** : Model configuration to use (CRep, CRepnc, CRep0), *(default='CRep')*. 44 | - **-K** : Number of communities, *(default=3)*. 45 | - **-A** : Input file name of the adjacency matrix, *(default='syn111.dat')*. 46 | - **-f** : Path of the input folder, *(default='../data/input/')*. 47 | - **-e** : Name of the source of the edge, *(default='source')*. 48 | - **-t** : Name of the target of the edge, *(default='target')*. 49 | - **-d** : Flag to force a dense transformation of the adjacency matrix, *(default=False)*. 50 | - **-F** : Flag to choose the convergence method, *(default='log')*. 51 | 52 | You can find a list by running (inside `code` directory): 53 | 54 | ```bash 55 | python main.py --help 56 | ``` 57 | 58 | ## Input format 59 | The network should be stored in a *.dat* file. An example of rows is 60 | 61 | `node1 node2 3`
62 | `node1 node3 1` 63 | 64 | where the first and second columns are the _source_ and _target_ nodes of the edge, respectively; the third column tells if there is an edge and the weight. In this example the edge node1 --> node2 exists with weight 3, and the edge node1 --> node3 exists with weight 1. 65 | 66 | ## Output 67 | The algorithm returns a compressed file inside the `./data/output` folder. To load and print the out-going membership matrix: 68 | 69 | ```bash 70 | import numpy as np 71 | theta = np.load('theta_Crep.npz') 72 | print(theta['u']) 73 | ``` 74 | 75 | _theta_ contains the two NxK membership matrices **u** *('u')* and **v** *('v')*, the 1xKxK (or 1xK if assortative=True) affinity tensor **w** *('w')*, the reciprocity coefficient **$\eta$** *('eta')*, the total number of iterations *('max_it')*, the value of the maximum pseudo log-likelihood *('maxPSL')* and the nodes of the network *('nodes')*. 76 | 77 | For an example `jupyter notebook` importing the data, see *analyse_results.ipynb*. 78 | -------------------------------------------------------------------------------- /code/analyse_results.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "### Analyse output results" 8 | ] 9 | }, 10 | { 11 | "cell_type": "code", 12 | "execution_count": 1, 13 | "metadata": {}, 14 | "outputs": [], 15 | "source": [ 16 | "import numpy as np\n", 17 | "import matplotlib.pyplot as plt" 18 | ] 19 | }, 20 | { 21 | "cell_type": "code", 22 | "execution_count": 2, 23 | "metadata": {}, 24 | "outputs": [], 25 | "source": [ 26 | "filename = '../data/output/theta_CRep.npz'\n", 27 | "theta = np.load(filename)" 28 | ] 29 | }, 30 | { 31 | "cell_type": "code", 32 | "execution_count": 3, 33 | "metadata": {}, 34 | "outputs": [], 35 | "source": [ 36 | "u,v,w,eta = theta['u'],theta['v'],theta['w'],theta['eta']" 37 | ] 38 | }, 39 | { 40 | "cell_type": "code", 41 | "execution_count": 4, 42 | "metadata": {}, 43 | "outputs": [ 44 | { 45 | "data": { 46 | "text/plain": [ 47 | "array([[0. , 1. , 0. ],\n", 48 | " [0. , 0.66901078, 0.33098922],\n", 49 | " [0. , 0.73152525, 0.26847475],\n", 50 | " ...,\n", 51 | " [0.92174939, 0.07825061, 0. ],\n", 52 | " [1. , 0. , 0. ],\n", 53 | " [1. , 0. , 0. ]])" 54 | ] 55 | }, 56 | "execution_count": 4, 57 | "metadata": {}, 58 | "output_type": "execute_result" 59 | } 60 | ], 61 | "source": [ 62 | "u" 63 | ] 64 | }, 65 | { 66 | "cell_type": "code", 67 | "execution_count": 5, 68 | "metadata": {}, 69 | "outputs": [ 70 | { 71 | "data": { 72 | "text/plain": [ 73 | "array([[0. , 0.68693478, 0.31306522],\n", 74 | " [0. , 1. , 0. ],\n", 75 | " [0. , 0. , 1. ],\n", 76 | " ...,\n", 77 | " [0. , 0. , 1. ],\n", 78 | " [1. , 0. , 0. ],\n", 79 | " [1. , 0. , 0. ]])" 80 | ] 81 | }, 82 | "execution_count": 5, 83 | "metadata": {}, 84 | "output_type": "execute_result" 85 | } 86 | ], 87 | "source": [ 88 | "v" 89 | ] 90 | }, 91 | { 92 | "cell_type": "code", 93 | "execution_count": 6, 94 | "metadata": {}, 95 | "outputs": [ 96 | { 97 | "data": { 98 | "text/plain": [ 99 | "array([[0.0226852 , 0.02808736, 0.03392388]])" 100 | ] 101 | }, 102 | "execution_count": 6, 103 | "metadata": {}, 104 | "output_type": "execute_result" 105 | } 106 | ], 107 | "source": [ 108 | "w" 109 | ] 110 | }, 111 | { 112 | "cell_type": "code", 113 | "execution_count": 7, 114 | "metadata": {}, 115 | "outputs": [ 116 | { 117 | "data": { 118 | "text/plain": [ 119 | "array(0.44088065)" 120 | ] 121 | }, 122 | "execution_count": 7, 123 | "metadata": {}, 124 | "output_type": "execute_result" 125 | } 126 | ], 127 | "source": [ 128 | "eta" 129 | ] 130 | } 131 | ], 132 | "metadata": { 133 | "kernelspec": { 134 | "display_name": "Python 3", 135 | "language": "python", 136 | "name": "python3" 137 | }, 138 | "language_info": { 139 | "codemirror_mode": { 140 | "name": "ipython", 141 | "version": 3 142 | }, 143 | "file_extension": ".py", 144 | "mimetype": "text/x-python", 145 | "name": "python", 146 | "nbconvert_exporter": "python", 147 | "pygments_lexer": "ipython3", 148 | "version": "3.7.4" 149 | } 150 | }, 151 | "nbformat": 4, 152 | "nbformat_minor": 4 153 | } 154 | -------------------------------------------------------------------------------- /code/cv_functions.py: -------------------------------------------------------------------------------- 1 | """ 2 | Functions used in the k-fold cross-validation procedure. 3 | """ 4 | 5 | import CRep as CREP 6 | import numpy as np 7 | from sklearn import metrics 8 | import yaml 9 | 10 | 11 | def PSloglikelihood(B, u, v, w, eta, mask=None): 12 | """ 13 | Compute the pseudo log-likelihood of the data. 14 | 15 | Parameters 16 | ---------- 17 | B : ndarray 18 | Graph adjacency tensor. 19 | u : ndarray 20 | Out-going membership matrix. 21 | v : ndarray 22 | In-coming membership matrix. 23 | w : ndarray 24 | Affinity tensor. 25 | eta : float 26 | Reciprocity coefficient. 27 | mask : ndarray 28 | Mask for selecting the held out set in the adjacency tensor in case of cross-validation. 29 | 30 | Returns 31 | ------- 32 | Pseudo log-likelihood value. 33 | """ 34 | 35 | if mask is None: 36 | M = _lambda0_full(u, v, w) 37 | M += (eta * B[0, :, :].T)[np.newaxis, :, :] 38 | logM = np.zeros(M.shape) 39 | logM[M > 0] = np.log(M[M > 0]) 40 | return (B * logM).sum() - M.sum() 41 | else: 42 | M = _lambda0_full(u, v, w)[mask > 0] 43 | M += (eta * B[0, :, :].T)[np.newaxis, :, :][mask > 0] 44 | logM = np.zeros(M.shape) 45 | logM[M > 0] = np.log(M[M > 0]) 46 | return (B[mask > 0] * logM).sum() - M.sum() 47 | 48 | 49 | def _lambda0_full(u, v, w): 50 | """ 51 | Compute the mean lambda0 for all entries. 52 | 53 | Parameters 54 | ---------- 55 | u : ndarray 56 | Out-going membership matrix. 57 | v : ndarray 58 | In-coming membership matrix. 59 | w : ndarray 60 | Affinity tensor. 61 | 62 | Returns 63 | ------- 64 | M : ndarray 65 | Mean lambda0 for all entries. 66 | """ 67 | 68 | if w.ndim == 2: 69 | M = np.einsum('ik,jk->ijk', u, v) 70 | M = np.einsum('ijk,ak->aij', M, w) 71 | else: 72 | M = np.einsum('ik,jq->ijkq', u, v) 73 | M = np.einsum('ijkq,akq->aij', M, w) 74 | 75 | return M 76 | 77 | 78 | def transpose_ij(M): 79 | """ 80 | Compute the transpose of a matrix. 81 | 82 | Parameters 83 | ---------- 84 | M : ndarray 85 | Numpy matrix. 86 | 87 | Returns 88 | ------- 89 | Transpose of the matrix. 90 | """ 91 | 92 | return np.einsum('aij->aji', M) 93 | 94 | 95 | def calculate_expectation(u, v, w, eta=0.0): 96 | """ 97 | Compute the expectations, e.g. the parameters of the marginal distribution m_{ij}. 98 | 99 | Parameters 100 | ---------- 101 | u : ndarray 102 | Out-going membership matrix. 103 | v : ndarray 104 | In-coming membership matrix. 105 | w : ndarray 106 | Affinity tensor. 107 | eta : float 108 | Reciprocity coefficient. 109 | 110 | Returns 111 | ------- 112 | M : ndarray 113 | Matrix whose elements are m_{ij}. 114 | """ 115 | 116 | lambda0 = _lambda0_full(u, v, w) 117 | lambda0T = transpose_ij(lambda0) 118 | M = (lambda0 + eta * lambda0T) / (1. - eta * eta) 119 | 120 | return M 121 | 122 | 123 | def calculate_conditional_expectation(B, u, v, w, eta=0.0, mean=None): 124 | """ 125 | Compute the conditional expectations, e.g. the parameters of the conditional distribution lambda_{ij}. 126 | 127 | Parameters 128 | ---------- 129 | B : ndarray 130 | Graph adjacency tensor. 131 | u : ndarray 132 | Out-going membership matrix. 133 | v : ndarray 134 | In-coming membership matrix. 135 | w : ndarray 136 | Affinity tensor. 137 | eta : float 138 | Reciprocity coefficient. 139 | mean : ndarray 140 | Matrix with mean entries. 141 | 142 | Returns 143 | ------- 144 | Matrix whose elements are lambda_{ij}. 145 | """ 146 | 147 | if mean is None: 148 | return _lambda0_full(u, v, w) + eta * transpose_ij(B) # conditional expectation (knowing A_ji) 149 | else: 150 | return _lambda0_full(u, v, w) + eta * transpose_ij(mean) 151 | 152 | 153 | def calculate_AUC(pred, data0, mask=None): 154 | """ 155 | Return the AUC of the link prediction. It represents the probability that a randomly chosen missing connection 156 | (true positive) is given a higher score by our method than a randomly chosen pair of unconnected vertices 157 | (true negative). 158 | 159 | Parameters 160 | ---------- 161 | pred : ndarray 162 | Inferred values. 163 | data0 : ndarray 164 | Given values. 165 | mask : ndarray 166 | Mask for selecting a subset of the adjacency tensor. 167 | 168 | Returns 169 | ------- 170 | AUC value. 171 | """ 172 | 173 | data = (data0 > 0).astype('int') 174 | if mask is None: 175 | fpr, tpr, thresholds = metrics.roc_curve(data.flatten(), pred.flatten()) 176 | else: 177 | fpr, tpr, thresholds = metrics.roc_curve(data[mask > 0], pred[mask > 0]) 178 | 179 | return metrics.auc(fpr, tpr) 180 | 181 | 182 | def shuffle_indices_all_matrix(N, L, rseed=10): 183 | """ 184 | Shuffle the indices of the adjacency tensor. 185 | 186 | Parameters 187 | ---------- 188 | N : int 189 | Number of nodes. 190 | L : int 191 | Number of layers. 192 | rseed : int 193 | Random seed. 194 | 195 | Returns 196 | ------- 197 | indices : ndarray 198 | Indices in a shuffled order. 199 | """ 200 | 201 | n_samples = int(N * N) 202 | indices = [np.arange(n_samples) for _ in range(L)] 203 | rng = np.random.RandomState(rseed) 204 | for l in range(L): 205 | rng.shuffle(indices[l]) 206 | 207 | return indices 208 | 209 | 210 | def extract_mask_kfold(indices, N, fold=0, NFold=5): 211 | """ 212 | Extract a non-symmetric mask using KFold cross-validation. It contains pairs (i,j) but possibly not (j,i). 213 | KFold means no train/test sets intersect across the K folds. 214 | 215 | Parameters 216 | ---------- 217 | indices : ndarray 218 | Indices of the adjacency tensor in a shuffled order. 219 | N : int 220 | Number of nodes. 221 | fold : int 222 | Current fold. 223 | NFold : int 224 | Number of total folds. 225 | 226 | Returns 227 | ------- 228 | mask : ndarray 229 | Mask for selecting the held out set in the adjacency tensor. 230 | """ 231 | 232 | L = len(indices) 233 | mask = np.zeros((L, N, N), dtype=bool) 234 | for l in range(L): 235 | n_samples = len(indices[l]) 236 | test = indices[l][fold * (n_samples // NFold):(fold + 1) * (n_samples // NFold)] 237 | mask0 = np.zeros(n_samples, dtype=bool) 238 | mask0[test] = 1 239 | mask[l] = mask0.reshape((N, N)) 240 | 241 | return mask 242 | 243 | 244 | def fit_model(B, B_T, data_T_vals, nodes, N, L, algo, K, flag_conv, **conf): 245 | """ 246 | Model directed networks by using a probabilistic generative model that assume community parameters and 247 | reciprocity coefficient. The inference is performed via EM algorithm. 248 | 249 | Parameters 250 | ---------- 251 | B : ndarray 252 | Graph adjacency tensor. 253 | B_T : None/sptensor 254 | Graph adjacency tensor (transpose). 255 | data_T_vals : None/ndarray 256 | Array with values of entries A[j, i] given non-zero entry (i, j). 257 | nodes : list 258 | List of nodes IDs. 259 | N : int 260 | Number of nodes. 261 | L : int 262 | Number of layers. 263 | algo : str 264 | Configuration to use (CRep, CRepnc, CRep0). 265 | K : int 266 | Number of communities. 267 | flag_conv : str 268 | If 'log' the convergence is based on the log-likelihood values; if 'deltas' the convergence is 269 | based on the differences in the parameters values. The latter is suggested when the dataset 270 | is big (N > 1000 ca.). 271 | 272 | Returns 273 | ------- 274 | u_f : ndarray 275 | Out-going membership matrix. 276 | v_f : ndarray 277 | In-coming membership matrix. 278 | w_f : ndarray 279 | Affinity tensor. 280 | eta_f : float 281 | Reciprocity coefficient. 282 | maxPSL : float 283 | Maximum pseudo log-likelihood. 284 | mod : obj 285 | The CRep object. 286 | """ 287 | 288 | # setting to run the algorithm 289 | with open(conf['out_folder'] + '/setting_' + algo + '.yaml', 'w') as f: 290 | yaml.dump(conf, f) 291 | 292 | mod = CREP.CRep(N=N, L=L, K=K, **conf) 293 | uf, vf, wf, nuf, maxPSL = mod.fit(data=B, data_T=B_T, data_T_vals=data_T_vals, flag_conv=flag_conv, nodes=nodes) 294 | 295 | return uf, vf, wf, nuf, maxPSL, mod 296 | 297 | 298 | def calculate_opt_func(B, algo_obj=None, mask=None, assortative=False): 299 | """ 300 | Compute the optimal value for the pseudo log-likelihood with the inferred parameters. 301 | 302 | Parameters 303 | ---------- 304 | B : ndarray 305 | Graph adjacency tensor. 306 | algo_obj : obj 307 | The CRep object. 308 | mask : ndarray 309 | Mask for selecting a subset of the adjacency tensor. 310 | assortative : bool 311 | Flag to use an assortative mode. 312 | 313 | Returns 314 | ------- 315 | Maximum pseudo log-likelihood value 316 | """ 317 | 318 | B_test = B.copy() 319 | if mask is not None: 320 | B_test[np.logical_not(mask)] = 0. 321 | 322 | if not assortative: 323 | return PSloglikelihood(B, algo_obj.u_f, algo_obj.v_f, algo_obj.w_f, algo_obj.eta_f, mask=mask) 324 | else: 325 | L = B.shape[0] 326 | K = algo_obj.w_f.shape[-1] 327 | w = np.zeros((L, K, K)) 328 | for l in range(L): 329 | w1 = np.zeros((K, K)) 330 | np.fill_diagonal(w1, algo_obj.w_f[l]) 331 | w[l, :, :] = w1.copy() 332 | return PSloglikelihood(B, algo_obj.u_f, algo_obj.v_f, w, algo_obj.eta_f, mask=mask) 333 | -------------------------------------------------------------------------------- /code/generate_data.py: -------------------------------------------------------------------------------- 1 | """ 2 | It generates n synthetic samples of a network having an intrinsic community structure and a given reciprocity value. 3 | It uses the given yaml setting file. 4 | """ 5 | 6 | import generative_model_reciprocity as gm 7 | import yaml 8 | import os 9 | from argparse import ArgumentParser 10 | import numpy as np 11 | 12 | 13 | def main_generate_data(): 14 | 15 | p = ArgumentParser() 16 | p.add_argument('-s', '--setting', type=str, default='setting_syn_data.yaml') # file with the setting 17 | p.add_argument('-n', '--samples', type=int, default=1) # number of synthetic samples 18 | args = p.parse_args() 19 | 20 | prng = np.random.RandomState(seed=17) # set seed random number generator 21 | 22 | with open(args.setting) as f: 23 | conf = yaml.load(f, Loader=yaml.FullLoader) 24 | 25 | out_folder = conf['out_folder'] 26 | if not os.path.exists(out_folder): 27 | os.makedirs(out_folder) 28 | 29 | for sn in range(args.samples): 30 | conf['seed'] += prng.randint(500) 31 | with open(out_folder + 'setting'+str(conf['seed'])+'.yaml', 'w') as f: 32 | yaml.dump(conf, f) 33 | conf['outfile_adj'] = 'syn' + str(conf['seed']) + '.dat' 34 | gen = gm.GM_reciprocity(**conf) 35 | _ = gen.reciprocity_planted_network() 36 | 37 | 38 | if __name__ == '__main__': 39 | main_generate_data() 40 | -------------------------------------------------------------------------------- /code/generative_model_reciprocity.py: -------------------------------------------------------------------------------- 1 | """ 2 | Class definition of the reciprocity generative model with the member functions required. 3 | It builds a directed, possibly weighted, network. 4 | """ 5 | 6 | import numpy as np 7 | import networkx as nx 8 | import pandas as pd 9 | import scipy.sparse as sparse 10 | import math 11 | import tools as tl 12 | 13 | 14 | class GM_reciprocity: 15 | def __init__(self, N, K, eta=0.5, k=3, ExpM=None, over=0., corr=0., seed=0, alpha=0.1, ag=0.1, beta=0.1, 16 | Normalization=0, structure='assortative', end_file='', out_folder='../data/output/real_data/cv/', 17 | output_parameters=False, output_adj=False, outfile_adj='None', verbose=False): 18 | self.N = N # number of nodes 19 | self.K = K # number of communities 20 | self.k = k # average degree 21 | self.seed = seed # random seed 22 | self.alpha = alpha # parameter of the Dirichlet distribution 23 | self.ag = ag # alpha parameter of the Gamma distribution 24 | self.beta = beta # beta parameter of the Gamma distribution 25 | self.end_file = end_file # output file suffix 26 | self.out_folder = out_folder # path for storing the output 27 | self.output_parameters = output_parameters # flag for storing the parameters 28 | self.output_adj = output_adj # flag for storing the generated adjacency matrix 29 | self.outfile_adj = outfile_adj # name for saving the adjacency matrix 30 | self.verbose = verbose # flag to print details 31 | if (eta < 0) or (eta >= 1): # reciprocity coefficient 32 | raise ValueError('The reciprocity coefficient eta has to be in [0, 1)!') 33 | self.eta = eta 34 | if ExpM is None: # expected number of edges 35 | self.ExpM = int(self.N * self.k / 2.) 36 | else: 37 | self.ExpM = int(ExpM) 38 | self.k = 2 * self.ExpM / float(self.N) 39 | if (over < 0) or (over > 1): # fraction of nodes with mixed membership 40 | raise ValueError('The over parameter has to be in [0, 1]!') 41 | self.over = over 42 | if (corr < 0) or (corr > 1): # correlation between u and v synthetically generated 43 | raise ValueError('The correlation parameter corr has to be in [0, 1]!') 44 | self.corr = corr 45 | if Normalization not in {0, 1}: # indicator for choosing how to generate the latent variables 46 | raise ValueError('The Normalization parameter can be either 0 or 1! It is used as an indicator for ' 47 | 'generating the membership matrices u and v from a Dirichlet or a Gamma distribution, ' 48 | 'respectively. It is used when there is overlapping.') 49 | self.Normalization = Normalization 50 | if structure not in {'assortative', 'disassortative'}: # structure of the affinity matrix W 51 | raise ValueError('The structure of the affinity matrix w can be either assortative or disassortative!') 52 | self.structure = structure 53 | 54 | def reciprocity_planted_network(self, parameters=None): 55 | """ 56 | Generate a directed, possibly weighted network by using the reciprocity generative model. 57 | Can be used to generate benchmarks for networks with reciprocity. 58 | 59 | Steps: 60 | 1. Generate the latent variables. 61 | 2. Extract A_ij entries (network edges) from a Poisson distribution; 62 | its mean depends on the latent variables. 63 | 64 | Parameters 65 | ---------- 66 | parameters: object 67 | Latent variables u, v, w and eta. 68 | 69 | Returns 70 | ------- 71 | G: MultiDigraph 72 | MultiDiGraph NetworkX object. 73 | """ 74 | 75 | prng = np.random.RandomState(self.seed) # set seed random number generator 76 | 77 | ''' 78 | Set latent variables u, v, w 79 | ''' 80 | 81 | if parameters is not None: 82 | self.u, self.v, self.w, self.eta = parameters 83 | else: 84 | # equal-size unmixed group membership 85 | size = int(self.N / self.K) 86 | self.u = np.zeros((self.N, self.K)) 87 | self.v = np.zeros((self.N, self.K)) 88 | for i in range(self.N): 89 | q = int(math.floor(float(i) / float(size))) 90 | if q == self.K: 91 | self.u[i:, self.K - 1] = 1. 92 | self.v[i:, self.K - 1] = 1. 93 | else: 94 | for j in range(q * size, q * size + size): 95 | self.u[j, q] = 1. 96 | self.v[j, q] = 1. 97 | self.w = affinity_matrix(structure=self.structure, N=self.N, K=self.K, a=0.1, b=0.3) 98 | 99 | # in case of overlapping 100 | if self.over != 0.: 101 | overlapping = int(self.N * self.over) # number of nodes belonging to more communities 102 | ind_over = np.random.randint(len(self.u), size=overlapping) 103 | if self.Normalization == 0: 104 | # u and v from a Dirichlet distribution 105 | self.u[ind_over] = prng.dirichlet(self.alpha * np.ones(self.K), overlapping) 106 | self.v[ind_over] = self.corr * self.u[ind_over] + (1. - self.corr) * \ 107 | prng.dirichlet(self.alpha * np.ones(self.K), overlapping) 108 | if self.corr == 1.: 109 | assert np.allclose(self.u, self.v) 110 | if self.corr > 0: 111 | self.v = tl.normalize_nonzero_membership(self.v) 112 | elif self.Normalization == 1: 113 | # u and v from a Gamma distribution 114 | self.u[ind_over] = prng.gamma(self.ag, 1. / self.beta, size=(overlapping, self.K)) 115 | self.v[ind_over] = self.corr * self.u[ind_over] + (1. - self.corr) * \ 116 | prng.gamma(self.ag, 1. / self.beta, size=(overlapping, self.K)) 117 | self.u = tl.normalize_nonzero_membership(self.u) 118 | self.v = tl.normalize_nonzero_membership(self.v) 119 | 120 | M0 = Exp_ija_matrix(self.u, self.v, self.w) # whose elements are lambda0_{ij} 121 | np.fill_diagonal(M0, 0) 122 | 123 | c = (self.ExpM * (1. - self.eta)) / M0.sum() # constant to enforce sparsity 124 | 125 | MM = (M0 + self.eta * transpose_ij(M0)) / (1. - self.eta * self.eta) # whose elements are m_{ij} 126 | Mt = transpose_ij(MM) 127 | MM0 = M0.copy() # to be not influenced by c_lambda 128 | 129 | if parameters is None: 130 | self.w *= c # only w is impact by that, u and v have a constraint, their sum over k should sum to 1 131 | M0 *= c 132 | M0t = transpose_ij(M0) # whose elements are lambda0_{ji} 133 | 134 | M = (M0 + self.eta * M0t) / (1. - self.eta * self.eta) # whose elements are m_{ij} 135 | np.fill_diagonal(M, 0) 136 | 137 | rw = self.eta + ((MM0 * Mt + self.eta * Mt ** 2).sum() / MM.sum()) # expected reciprocity 138 | 139 | ''' 140 | Generate network G (and adjacency matrix A) using the latent variables, 141 | with the generative model (A_ij,A_ji) ~ P(A_ij|u,v,w,eta) P(A_ji|A_ij,u,v,w,eta) 142 | ''' 143 | 144 | G = nx.MultiDiGraph() 145 | for i in range(self.N): 146 | G.add_node(i) 147 | 148 | counter, totM = 0, 0, 149 | for i in range(self.N): 150 | for j in range(i + 1, self.N): 151 | r = prng.rand(1)[0] 152 | if r < 0.5: 153 | A_ij = prng.poisson(M[i, j], 1)[0] # draw A_ij from P(A_ij) = Poisson(m_ij) 154 | if A_ij > 0: 155 | G.add_edge(i, j, weight=A_ij) 156 | lambda_ji = M0[j, i] + self.eta * A_ij 157 | A_ji = prng.poisson(lambda_ji, 1)[0] # draw A_ji from P(A_ji|A_ij) = Poisson(lambda0_ji + eta*A_ij) 158 | if A_ji > 0: 159 | G.add_edge(j, i, weight=A_ji) 160 | else: 161 | A_ji = prng.poisson(M[j, i], 1)[0] # draw A_ij from P(A_ij) = Poisson(m_ij) 162 | if A_ji > 0: 163 | G.add_edge(j, i, weight=A_ji) 164 | lambda_ij = M0[i, j] + self.eta * A_ji 165 | A_ij = prng.poisson(lambda_ij, 1)[0] # draw A_ji from P(A_ji|A_ij) = Poisson(lambda0_ji + eta*A_ij) 166 | if A_ij > 0: 167 | G.add_edge(i, j, weight=A_ij) 168 | counter += 1 169 | totM += A_ij + A_ji 170 | 171 | # keep largest connected component 172 | Gc = max(nx.weakly_connected_components(G), key=len) 173 | nodes_to_remove = set(G.nodes()).difference(Gc) 174 | G.remove_nodes_from(list(nodes_to_remove)) 175 | 176 | nodes = list(G.nodes()) 177 | self.u = self.u[nodes] 178 | self.v = self.v[nodes] 179 | self.N = len(nodes) 180 | 181 | A = nx.to_scipy_sparse_matrix(G, nodelist=nodes, weight='weight') 182 | 183 | Sparsity_cof = np.round(2 * G.number_of_edges() / float(G.number_of_nodes()), 3) 184 | 185 | ave_w_deg = np.round(2 * totM / float(G.number_of_nodes()), 3) 186 | 187 | reciprocity_c = np.round(tl.reciprocal_edges(G), 3) 188 | 189 | if self.verbose: 190 | print(f'Number of links in the upper triangular matrix: {sparse.triu(A, k=1).nnz}\n' 191 | f'Number of links in the lower triangular matrix: {sparse.tril(A, k=-1).nnz}') 192 | print(f'Sum of weights in the upper triangular matrix: {np.round(sparse.triu(A, k=1).sum(), 2)}\n' 193 | f'Sum of weights in the lower triangular matrix: {np.round(sparse.tril(A, k=-1).sum(), 2)}\n' 194 | f'Number of possible unordered pairs: {counter}') 195 | print(f'Removed {len(nodes_to_remove)} nodes, because not part of the largest connected component') 196 | print(f'Number of nodes: {G.number_of_nodes()} \n' 197 | f'Number of edges: {G.number_of_edges()}') 198 | print(f'Average degree (2E/N): {Sparsity_cof}') 199 | print(f'Average weighted degree (2M/N): {ave_w_deg}') 200 | print(f'Expected reciprocity: {np.round(rw, 3)}') 201 | print(f'Reciprocity (intended as the proportion of bi-directional edges over the unordered pairs): ' 202 | f'{reciprocity_c}\n') 203 | 204 | if self.output_parameters: 205 | self.output_results(nodes) 206 | 207 | if self.output_adj: 208 | self.output_adjacency(G, outfile=self.outfile_adj) 209 | 210 | return G 211 | 212 | def planted_network_cond_independent(self, parameters=None): 213 | """ 214 | Generate a directed, possibly weighted network without using reciprocity. 215 | It uses conditionally independent A_ij from a Poisson | (u,v,w). 216 | 217 | Parameters 218 | ---------- 219 | parameters: object 220 | Latent variables u, v and w. 221 | 222 | Returns 223 | ------- 224 | G: MultiDigraph 225 | MultiDiGraph NetworkX object. 226 | """ 227 | 228 | prng = np.random.RandomState(self.seed) # set seed random number generator 229 | 230 | ''' 231 | Set latent variables u,v,w 232 | ''' 233 | 234 | if parameters is not None: 235 | self.u, self.v, self.w = parameters 236 | else: 237 | # equal-size unmixed group membership 238 | size = int(self.N / self.K) 239 | self.u = np.zeros((self.N, self.K)) 240 | self.v = np.zeros((self.N, self.K)) 241 | for i in range(self.N): 242 | q = int(math.floor(float(i) / float(size))) 243 | if q == self.K: 244 | self.u[i:, self.K - 1] = 1. 245 | self.v[i:, self.K - 1] = 1. 246 | else: 247 | for j in range(q * size, q * size + size): 248 | self.u[j, q] = 1. 249 | self.v[j, q] = 1. 250 | self.w = affinity_matrix(structure=self.structure, N=self.N, K=self.K, a=0.1, b=0.3) 251 | 252 | # in case of overlapping 253 | if self.over != 0.: 254 | overlapping = int(self.N * self.over) # number of nodes belonging to more communities 255 | ind_over = np.random.randint(len(self.u), size=overlapping) 256 | if self.Normalization == 0: 257 | # u and v from a Dirichlet distribution 258 | self.u[ind_over] = prng.dirichlet(self.alpha * np.ones(self.K), overlapping) 259 | self.v[ind_over] = self.corr * self.u[ind_over] + (1. - self.corr) * \ 260 | prng.dirichlet(self.alpha * np.ones(self.K), overlapping) 261 | if self.corr == 1.: 262 | assert np.allclose(self.u, self.v) 263 | if self.corr > 0: 264 | self.v = tl.normalize_nonzero_membership(self.v) 265 | elif self.Normalization == 1: 266 | # u and v from a Gamma distribution 267 | self.u[ind_over] = prng.gamma(self.ag, 1. / self.beta, size=(overlapping, self.K)) 268 | self.v[ind_over] = self.corr * self.u[ind_over] + (1. - self.corr) * \ 269 | prng.gamma(self.ag, 1. / self.beta, size=(overlapping, self.K)) 270 | self.u = tl.normalize_nonzero_membership(self.u) 271 | self.v = tl.normalize_nonzero_membership(self.v) 272 | 273 | M0 = Exp_ija_matrix(self.u, self.v, self.w) # whose elements are lambda0_{ij} 274 | np.fill_diagonal(M0, 0) 275 | M0t = transpose_ij(M0) # whose elements are lambda0_{ji} 276 | 277 | rw = (M0 * M0t).sum() / M0.sum() # expected reciprocity 278 | 279 | c = self.ExpM / float(M0.sum()) # constant to enforce sparsity 280 | if parameters is None: 281 | self.w *= c # only w is impact by that, u and v have a constraint, their sum over k should sum to 1 282 | 283 | ''' 284 | Generate network G (and adjacency matrix A) using the latent variable, 285 | with the generative model (A_ij) ~ P(A_ij|u,v,w) 286 | ''' 287 | 288 | G = nx.MultiDiGraph() 289 | for i in range(self.N): 290 | G.add_node(i) 291 | 292 | totM = 0 293 | for i in range(self.N): 294 | for j in range(self.N): 295 | if i != j: # no self-loops 296 | A_ij = prng.poisson(c * M0[i, j], 1)[0] # draw A_ij from P(A_ij) = Poisson(c*m_ij) 297 | if A_ij > 0: 298 | G.add_edge(i, j, weight=A_ij) 299 | totM += A_ij 300 | 301 | nodes = list(G.nodes()) 302 | 303 | # keep largest connected component 304 | Gc = max(nx.weakly_connected_components(G), key=len) 305 | nodes_to_remove = set(G.nodes()).difference(Gc) 306 | G.remove_nodes_from(list(nodes_to_remove)) 307 | 308 | nodes = list(G.nodes()) 309 | self.u = self.u[nodes] 310 | self.v = self.v[nodes] 311 | self.N = len(nodes) 312 | 313 | A = nx.to_scipy_sparse_matrix(G, nodelist=nodes, weight='weight') 314 | 315 | Sparsity_cof = np.round(2 * G.number_of_edges() / float(G.number_of_nodes()), 3) 316 | 317 | ave_w_deg = np.round(2 * totM / float(G.number_of_nodes()), 3) 318 | 319 | reciprocity_c = np.round(tl.reciprocal_edges(G), 3) 320 | 321 | if self.verbose: 322 | print(f'Number of links in the upper triangular matrix: {sparse.triu(A, k=1).nnz}\n' 323 | f'Number of links in the lower triangular matrix: {sparse.tril(A, k=-1).nnz}') 324 | print(f'Sum of weights in the upper triangular matrix: {np.round(sparse.triu(A, k=1).sum(), 2)}\n' 325 | f'Sum of weights in the lower triangular matrix: {np.round(sparse.tril(A, k=-1).sum(), 2)}') 326 | print(f'Removed {len(nodes_to_remove)} nodes, because not part of the largest connected component') 327 | print(f'Number of nodes: {G.number_of_nodes()} \n' 328 | f'Number of edges: {G.number_of_edges()}') 329 | print(f'Average degree (2E/N): {Sparsity_cof}') 330 | print(f'Average weighted degree (2M/N): {ave_w_deg}') 331 | print(f'Expected reciprocity: {np.round(rw, 3)}') 332 | print(f'Reciprocity (intended as the proportion of bi-directional edges over the unordered pairs): ' 333 | f'{reciprocity_c}\n') 334 | 335 | if self.output_parameters: 336 | self.output_results(nodes) 337 | 338 | if self.output_adj: 339 | self.output_adjacency(G, outfile=self.outfile_adj) 340 | 341 | return G 342 | 343 | def planted_network_reciprocity_only(self, p=None): 344 | """ 345 | Generate a directed, possibly weighted network using only reciprocity. 346 | One of the directed-edges is generated with probability p, the other with eta*A_ji, 347 | i.e. as in Erdos-Renyi reciprocity. 348 | 349 | Parameters 350 | ---------- 351 | p: float 352 | Probability to generate one of the directed-edge. 353 | 354 | Returns 355 | ------- 356 | G: MultiDigraph 357 | MultiDiGraph NetworkX object. 358 | """ 359 | 360 | prng = np.random.RandomState(self.seed) # set seed random number generator 361 | 362 | if p is None: 363 | p = (1. - self.eta) * self.k * 0.5 / (self.N - 1.) 364 | 365 | ''' 366 | Generate network G (and adjacency matrix A) 367 | ''' 368 | 369 | G = nx.MultiDiGraph() 370 | for i in range(self.N): 371 | G.add_node(i) 372 | 373 | totM = 0 374 | for i in range(self.N): 375 | for j in range(i + 1, self.N): 376 | A0 = prng.poisson(p, 1)[0] 377 | A1 = prng.poisson(p + A0, 1)[0] 378 | r = prng.rand(1)[0] 379 | if r < 0.5: 380 | if A0 > 0: 381 | G.add_edge(i, j, weight=A0) 382 | if A1 > 0: 383 | G.add_edge(j, i, weight=A1) 384 | else: 385 | if A0 > 0: 386 | G.add_edge(j, i, weight=A0) 387 | if A1 > 0: 388 | G.add_edge(i, j, weight=A1) 389 | totM += A0 + A1 390 | 391 | # keep largest connected component 392 | Gc = max(nx.weakly_connected_components(G), key=len) 393 | nodes_to_remove = set(G.nodes()).difference(Gc) 394 | G.remove_nodes_from(list(nodes_to_remove)) 395 | 396 | nodes = list(G.nodes()) 397 | self.N = len(nodes) 398 | 399 | A = nx.to_scipy_sparse_matrix(G, nodelist=nodes, weight='weight') 400 | 401 | Sparsity_cof = np.round(2 * G.number_of_edges() / float(G.number_of_nodes()), 3) 402 | 403 | ave_w_deg = np.round(2 * totM / float(G.number_of_nodes()), 3) 404 | 405 | reciprocity_c = np.round(tl.reciprocal_edges(G), 3) 406 | 407 | if self.verbose: 408 | print(f'Number of links in the upper triangular matrix: {sparse.triu(A, k=1).nnz}\n' 409 | f'Number of links in the lower triangular matrix: {sparse.tril(A, k=-1).nnz}') 410 | print(f'Sum of weights in the upper triangular matrix: {np.round(sparse.triu(A, k=1).sum(), 2)}\n' 411 | f'Sum of weights in the lower triangular matrix: {np.round(sparse.tril(A, k=-1).sum(), 2)}') 412 | print(f'Removed {len(nodes_to_remove)} nodes, because not part of the largest connected component') 413 | print(f'Number of nodes: {G.number_of_nodes()} \n' 414 | f'Number of edges: {G.number_of_edges()}') 415 | print(f'Average degree (2E/N): {Sparsity_cof}') 416 | print(f'Average weighted degree (2M/N): {ave_w_deg}') 417 | print(f'Reciprocity (intended as the proportion of bi-directional edges over the unordered pairs): ' 418 | f'{reciprocity_c}\n') 419 | 420 | if self.output_adjacency: 421 | self.output_adjacency(G, outfile=self.outfile_adj) 422 | 423 | return G 424 | 425 | def output_results(self, nodes): 426 | """ 427 | Output results in a compressed file. 428 | 429 | Parameters 430 | ---------- 431 | nodes : list 432 | List of nodes IDs. 433 | """ 434 | 435 | output_parameters = self.out_folder + 'theta_gt' + str(self.seed) + self.end_file 436 | np.savez_compressed(output_parameters + '.npz', u=self.u, v=self.v, w=self.w, eta=self.eta, nodes=nodes) 437 | if self.verbose: 438 | print(f'Parameters saved in: {output_parameters}.npz') 439 | print('To load: theta=np.load(filename), then e.g. theta["u"]') 440 | 441 | def output_adjacency(self, G, outfile=None): 442 | """ 443 | Output the adjacency matrix. Default format is space-separated .csv with 3 columns: 444 | node1 node2 weight 445 | 446 | Parameters 447 | ---------- 448 | G: MultiDigraph 449 | MultiDiGraph NetworkX object. 450 | outfile: str 451 | Name of the adjacency matrix. 452 | """ 453 | 454 | if outfile is None: 455 | outfile = 'syn' + str(self.seed) + '_k' + str(int(self.k)) + '.dat' 456 | 457 | edges = list(G.edges(data=True)) 458 | try: 459 | data = [[u, v, d['weight']] for u, v, d in edges] 460 | except: 461 | data = [[u, v, 1] for u, v, d in edges] 462 | 463 | df = pd.DataFrame(data, columns=['source', 'target', 'w'], index=None) 464 | df.to_csv(self.out_folder + outfile, index=False, sep=' ') 465 | if self.verbose: 466 | print(f'Adjacency matrix saved in: {self.out_folder + outfile}') 467 | 468 | 469 | def Exp_ija_matrix(u, v, w): 470 | """ 471 | Compute the mean lambda0_ij for all entries. 472 | 473 | Parameters 474 | ---------- 475 | u : ndarray 476 | Out-going membership matrix. 477 | v : ndarray 478 | In-coming membership matrix. 479 | w : ndarray 480 | Affinity matrix. 481 | 482 | Returns 483 | ------- 484 | M : ndarray 485 | Mean lambda0_ij for all entries. 486 | """ 487 | 488 | M = np.einsum('ik,jq->ijkq', u, v) 489 | M = np.einsum('ijkq,kq->ij', M, w) 490 | 491 | return M 492 | 493 | 494 | def transpose_ij(M): 495 | """ 496 | Compute the transpose of a matrix. 497 | 498 | Parameters 499 | ---------- 500 | M : ndarray 501 | Numpy matrix. 502 | 503 | Returns 504 | ------- 505 | Transpose of the matrix. 506 | """ 507 | 508 | return np.einsum('ij->ji', M) 509 | 510 | 511 | def affinity_matrix(structure='assortative', N=100, K=2, a=0.1, b=0.3): 512 | """ 513 | Return the KxK affinity matrix w with probabilities between and within groups. 514 | 515 | Parameters 516 | ---------- 517 | structure : string 518 | Structure of the network, e.g. assortative, disassortative. 519 | N : int 520 | Number of nodes. 521 | K : int 522 | Number of communities. 523 | a : float 524 | Parameter for secondary probabilities. 525 | b : float 526 | Parameter for third probabilities. 527 | 528 | Returns 529 | ------- 530 | p : ndarray 531 | Array with probabilities between and within groups. Element (k,q) gives the density of edges going from the 532 | nodes of group k to nodes of group q. 533 | """ 534 | 535 | b *= a 536 | p1 = K / N 537 | if structure == 'assortative': 538 | p = p1 * a * np.ones((K, K)) # secondary-probabilities 539 | np.fill_diagonal(p, p1 * np.ones(K)) # primary-probabilities 540 | 541 | elif structure == 'disassortative': 542 | p = p1 * np.ones((K, K)) # primary-probabilities 543 | np.fill_diagonal(p, a * p1 * np.ones(K)) # secondary-probabilities 544 | 545 | # print(f'Affinity matrix w: \n{p}') 546 | 547 | return p 548 | -------------------------------------------------------------------------------- /code/main.py: -------------------------------------------------------------------------------- 1 | """ 2 | Performing the inference in the given single-layer directed network. 3 | Implementation of CRep algorithm. 4 | """ 5 | 6 | import yaml 7 | import time 8 | import os 9 | import tools as tl 10 | import CRep as CREP 11 | import numpy as np 12 | import sktensor as skt 13 | from argparse import ArgumentParser 14 | 15 | 16 | def main(): 17 | p = ArgumentParser() 18 | p.add_argument('-a', '--algorithm', type=str, choices=['Crep', 'Crepnc', 'Crep0'], default='CRep') # configuration 19 | p.add_argument('-K', '--K', type=int, default=3) # number of communities 20 | p.add_argument('-A', '--adj', type=str, default='syn111.dat') # name of the network 21 | p.add_argument('-f', '--in_folder', type=str, default='../data/input/') # path of the input network 22 | p.add_argument('-e', '--ego', type=str, default='source') # name of the source of the edge 23 | p.add_argument('-t', '--alter', type=str, default='target') # name of the target of the edge 24 | p.add_argument('-d', '--force_dense', type=bool, default=False) # flag to force a dense transformation in input 25 | p.add_argument('-F', '--flag_conv', type=str, choices=['log', 'deltas'], default='log') # flag for convergence 26 | args = p.parse_args() 27 | 28 | # setting to run the algorithm 29 | with open('setting_' + args.algorithm + '.yaml') as f: 30 | conf = yaml.load(f, Loader=yaml.FullLoader) 31 | if not os.path.exists(conf['out_folder']): 32 | os.makedirs(conf['out_folder']) 33 | with open(conf['out_folder'] + '/setting_' + args.algorithm + '.yaml', 'w') as f: 34 | yaml.dump(conf, f) 35 | 36 | ''' 37 | Import data 38 | ''' 39 | network = args.in_folder + args.adj # network complete path 40 | A, B, B_T, data_T_vals = tl.import_data(network, ego=args.ego, alter=args.alter, 41 | force_dense=args.force_dense, header=0) 42 | nodes = A[0].nodes() 43 | 44 | valid_types = [np.ndarray, skt.dtensor, skt.sptensor] 45 | assert any(isinstance(B, vt) for vt in valid_types) 46 | 47 | ''' 48 | Run CRep 49 | ''' 50 | print(f'\n### Run {args.algorithm} ###') 51 | 52 | time_start = time.time() 53 | model = CREP.CRep(N=A[0].number_of_nodes(), L=len(A), K=args.K, **conf) 54 | _ = model.fit(data=B, data_T=B_T, data_T_vals=data_T_vals, flag_conv=args.flag_conv, nodes=nodes) 55 | 56 | print(f'\nTime elapsed: {np.round(time.time() - time_start, 2)} seconds.') 57 | 58 | 59 | if __name__ == '__main__': 60 | main() 61 | -------------------------------------------------------------------------------- /code/main_cv.py: -------------------------------------------------------------------------------- 1 | """ 2 | Main function to implement cross-validation given a number of communities. 3 | 4 | - Hold-out part of the dataset (pairs of edges labeled by unordered pairs (i,j)); 5 | - Infer parameters on the training set; 6 | - Calculate performance measures in the test set (AUC). 7 | """ 8 | 9 | # TODO: optimize for big matrices (so when the input would be done with force_dense=False) 10 | 11 | import csv 12 | import os 13 | import pickle 14 | from argparse import ArgumentParser 15 | import cv_functions as cvfun 16 | import numpy as np 17 | import tools as tl 18 | import yaml 19 | import sktensor as skt 20 | import time 21 | 22 | 23 | def main(): 24 | p = ArgumentParser() 25 | p.add_argument('-a', '--algorithm', type=str, choices=['Crep', 'Crepnc', 'Crep0'], default='CRep') # configuration 26 | p.add_argument('-K', '--K', type=int, default=3) # number of communities 27 | p.add_argument('-A', '--adj', type=str, default='syn111.dat') # name of the network 28 | p.add_argument('-f', '--in_folder', type=str, default='../data/input/') # path of the input network 29 | p.add_argument('-o', '--out_folder', type=str, default='../data/output/5-fold_cv/') # path to store outputs 30 | p.add_argument('-e', '--ego', type=str, default='source') # name of the source of the edge 31 | p.add_argument('-t', '--alter', type=str, default='target') # name of the target of the edge 32 | # p.add_argument('-d', '--force_dense', type=bool, default=True) # flag to force a dense transformation in input 33 | p.add_argument('-F', '--flag_conv', type=str, choices=['log', 'deltas'], default='log') # flag for convergence 34 | p.add_argument('-N', '--NFold', type=int, default=5) # number of fold to perform cross-validation 35 | p.add_argument('-m', '--out_mask', type=bool, default=False) # flag to output the masks 36 | p.add_argument('-r', '--out_results', type=bool, default=True) # flag to output the results in a csv file 37 | p.add_argument('-i', '--out_inference', type=bool, default=True) # flag to output the inferred parameters 38 | args = p.parse_args() 39 | 40 | prng = np.random.RandomState(seed=17) # set seed random number generator 41 | 42 | ''' 43 | Cross validation parameters and set up output directory 44 | ''' 45 | NFold = args.NFold 46 | out_mask = args.out_mask 47 | out_results = args.out_results 48 | 49 | out_folder = args.out_folder 50 | if not os.path.exists(out_folder): 51 | os.makedirs(out_folder) 52 | 53 | ''' 54 | Model parameters 55 | ''' 56 | K = args.K 57 | network = args.in_folder + args.adj # network complete path 58 | algorithm = args.algorithm # algorithm to use to generate the samples 59 | adjacency = args.adj.split('.dat')[0] # name of the network without extension 60 | with open('setting_' + algorithm + '.yaml') as f: 61 | conf = yaml.load(f, Loader=yaml.FullLoader) 62 | conf['out_folder'] = out_folder 63 | conf['out_inference'] = args.out_inference 64 | 65 | ''' 66 | Import data 67 | ''' 68 | A, B, B_T, data_T_vals = tl.import_data(network, ego=args.ego, alter=args.alter, force_dense=True, header=0) 69 | nodes = A[0].nodes() 70 | valid_types = [np.ndarray, skt.dtensor, skt.sptensor] 71 | assert any(isinstance(B, vt) for vt in valid_types) 72 | 73 | print('\n### CV procedure ###') 74 | comparison = [0 for _ in range(11)] 75 | comparison[0] = K 76 | 77 | # save the results 78 | if out_results: 79 | out_file = out_folder + adjacency + '_cv.csv' 80 | if not os.path.isfile(out_file): # write header 81 | with open(out_file, 'w') as outfile: 82 | wrtr = csv.writer(outfile, delimiter=',', quotechar='"') 83 | wrtr.writerow(['K', 'fold', 'rseed', 'eta', 'auc_train', 'auc_test', 'auc_cond_train', 'auc_cond_test', 84 | 'opt_func_train', 'opt_func_test', 'max_it']) 85 | outfile = open(out_file, 'a') 86 | wrtr = csv.writer(outfile, delimiter=',', quotechar='"') 87 | print(f'Results will be saved in: {out_file}') 88 | 89 | time_start = time.time() 90 | L = B.shape[0] 91 | N = B.shape[-1] 92 | 93 | rseed = prng.randint(1000) 94 | indices = cvfun.shuffle_indices_all_matrix(N, L, rseed=rseed) 95 | init_end_file = conf['end_file'] 96 | 97 | for fold in range(NFold): 98 | print('\nFOLD ', fold) 99 | comparison[1], comparison[2] = fold, rseed 100 | 101 | mask = cvfun.extract_mask_kfold(indices, N, fold=fold, NFold=NFold) 102 | if out_mask: 103 | outmask = out_folder + 'mask_f' + str(fold) + '_' + adjacency + '.pkl' 104 | print(f'Mask saved in: {outmask}') 105 | with open(outmask, 'wb') as f: 106 | pickle.dump(np.where(mask > 0), f) 107 | 108 | ''' 109 | Set up training dataset 110 | ''' 111 | B_train = B.copy() 112 | B_train[mask > 0] = 0 113 | 114 | ''' 115 | Run CRep on the training 116 | ''' 117 | tic = time.time() 118 | conf['end_file'] = init_end_file + '_' + str(fold) + 'K' + str(K) 119 | u, v, w, eta, maxPSL, algo_obj = cvfun.fit_model(B_train, B_T, data_T_vals, nodes=nodes, N=N, L=L, K=K, 120 | algo=algorithm, flag_conv=args.flag_conv, **conf) 121 | 122 | ''' 123 | Output performance results 124 | ''' 125 | comparison[3] = eta 126 | M = cvfun.calculate_expectation(u, v, w, eta=eta) 127 | comparison[4] = cvfun.calculate_AUC(M, B, mask=np.logical_not(mask)) 128 | comparison[5] = cvfun.calculate_AUC(M, B, mask=mask) 129 | M_cond = cvfun.calculate_conditional_expectation(B, u, v, w, eta=eta) 130 | comparison[6] = cvfun.calculate_AUC(M_cond, B, mask=np.logical_not(mask)) 131 | comparison[7] = cvfun.calculate_AUC(M_cond, B, mask=mask) 132 | comparison[9] = cvfun.calculate_opt_func(B, algo_obj, mask=mask, assortative=conf['assortative']) 133 | comparison[8] = maxPSL 134 | comparison[10] = algo_obj.final_it 135 | 136 | print(f'Time elapsed: {np.round(time.time() - tic, 2)} seconds.') 137 | 138 | if out_results: 139 | wrtr.writerow(comparison) 140 | outfile.flush() 141 | 142 | if out_results: 143 | outfile.close() 144 | 145 | print(f'\nTime elapsed: {np.round(time.time() - time_start, 2)} seconds.') 146 | 147 | 148 | if __name__ == '__main__': 149 | main() 150 | -------------------------------------------------------------------------------- /code/setting_CRep.yaml: -------------------------------------------------------------------------------- 1 | N_real: 5 2 | tolerance: 0.0001 3 | decision: 10 4 | max_iter: 1000 5 | rseed: 0 6 | inf: 10000000000.0 7 | err_max: 0.000000000001 8 | err: 0.1 9 | initialization: 0 10 | undirected: False 11 | verbose: False 12 | out_inference: True 13 | out_folder: "../data/output/" 14 | end_file: "_CRep" 15 | assortative: True 16 | eta0: null 17 | fix_eta: False 18 | constrained: True 19 | files: '../data/input/theta_gt111.npz' 20 | -------------------------------------------------------------------------------- /code/setting_CRep0.yaml: -------------------------------------------------------------------------------- 1 | N_real: 5 2 | tolerance: 0.0001 3 | decision: 10 4 | max_iter: 1000 5 | rseed: 0 6 | inf: 10000000000.0 7 | err_max: 0.000000000001 8 | err: 0.1 9 | initialization: 0 10 | undirected: False 11 | verbose: False 12 | out_inference: True 13 | out_folder: "../data/output/" 14 | end_file: "_CRep0" 15 | assortative: True 16 | eta0: 0 17 | fix_eta: True 18 | constrained: True 19 | files: '../data/input/synthetic/theta.npz' 20 | -------------------------------------------------------------------------------- /code/setting_CRepnc.yaml: -------------------------------------------------------------------------------- 1 | N_real: 5 2 | tolerance: 0.0001 3 | decision: 10 4 | max_iter: 1000 5 | rseed: 0 6 | inf: 10000000000.0 7 | err_max: 0.000000000001 8 | err: 0.1 9 | initialization: 0 10 | undirected: False 11 | verbose: False 12 | out_inference: True 13 | out_folder: "../data/output/" 14 | end_file: "_CRepnc" 15 | assortative: True 16 | eta0: null 17 | fix_eta: False 18 | constrained: False 19 | files: '../data/input/synthetic/theta.npz' 20 | -------------------------------------------------------------------------------- /code/setting_syn_data.yaml: -------------------------------------------------------------------------------- 1 | N: 600 2 | K: 3 3 | eta: 0.5 4 | k: 20 5 | ExpM: null 6 | over: 0. 7 | corr: 0. 8 | seed: 0 9 | alpha: 0.1 10 | ag: 0.1 11 | beta: 0.1 12 | Normalization: 0 13 | structure: "assortative" 14 | end_file: "" 15 | out_folder: '../data/input/' 16 | output_parameters: True 17 | output_adj: True 18 | outfile_adj: null 19 | verbose: True -------------------------------------------------------------------------------- /code/test.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | import numpy as np 3 | import CRep as CREP 4 | import yaml 5 | import tools as tl 6 | 7 | 8 | class Test(unittest.TestCase): 9 | """ 10 | The basic class that inherits unittest.TestCase 11 | """ 12 | algorithm = 'CRep' 13 | K = 3 14 | in_folder = '../data/input/' 15 | out_folder = '../data/output/' 16 | end_file = '_test' 17 | adj = 'syn111.dat' 18 | ego = 'source' 19 | alter = 'target' 20 | force_dense = False 21 | flag_conv = 'log' 22 | 23 | ''' 24 | Import data 25 | ''' 26 | network = in_folder + adj # network complete path 27 | A, B, B_T, data_T_vals = tl.import_data(network, ego=ego, alter=alter, force_dense=force_dense, header=0) 28 | nodes = A[0].nodes() 29 | 30 | ''' 31 | Setting to run the algorithm 32 | ''' 33 | with open('setting_' + algorithm + '.yaml') as f: 34 | conf = yaml.load(f, Loader=yaml.FullLoader) 35 | conf['end_file'] = end_file 36 | 37 | model = CREP.CRep(N=A[0].number_of_nodes(), L=len(A), K=K, **conf) 38 | 39 | # test case function to check the crep.set_name function 40 | def test_import_data(self): 41 | print("Start import data test\n") 42 | if self.force_dense: 43 | self.assertTrue(self.B.sum() > 0) 44 | print('B has ', self.B.sum(), ' total weight.') 45 | else: 46 | self.assertTrue(self.B.vals.sum() > 0) 47 | print('B has ', self.B.vals.sum(), ' total weight.') 48 | 49 | # test case function to check the Person.get_name function 50 | def test_running_algorithm(self): 51 | print("\nStart running algorithm test\n") 52 | 53 | _ = self.model.fit(data=self.B, data_T=self.B_T, data_T_vals=self.data_T_vals, flag_conv=self.flag_conv, 54 | nodes=self.nodes) 55 | 56 | theta = np.load(self.model.out_folder+'theta'+self.model.end_file+'.npz') 57 | thetaGT = np.load(self.model.out_folder+'theta_'+self.algorithm+'.npz') 58 | 59 | print(np.where(thetaGT['u'] != theta['u'])) 60 | 61 | self.assertTrue(np.array_equal(self.model.u_f, theta['u'])) 62 | self.assertTrue(np.array_equal(self.model.v_f, theta['v'])) 63 | self.assertTrue(np.array_equal(self.model.w_f, theta['w'])) 64 | self.assertTrue(np.array_equal(self.model.eta_f, theta['eta'])) 65 | 66 | self.assertTrue(np.array_equal(thetaGT['u'], theta['u'])) 67 | self.assertTrue(np.array_equal(thetaGT['v'], theta['v'])) 68 | self.assertTrue(np.array_equal(thetaGT['w'], theta['w'])) 69 | self.assertTrue(np.array_equal(thetaGT['eta'], theta['eta'])) 70 | 71 | 72 | if __name__ == '__main__': 73 | # begin the unittest.main() 74 | unittest.main() 75 | -------------------------------------------------------------------------------- /code/test_cv.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | import numpy as np 3 | import tools as tl 4 | import cv_functions as cvfun 5 | import yaml 6 | 7 | 8 | class Test(unittest.TestCase): 9 | """ 10 | The basic class that inherits unittest.TestCase 11 | """ 12 | algorithm = 'CRep' 13 | K = 3 14 | in_folder = '../data/input/' 15 | out_folder = '../data/output/5-fold_cv/' 16 | end_file = '_test' 17 | adj = 'syn111.dat' 18 | ego = 'source' 19 | alter = 'target' 20 | # force_dense = True 21 | flag_conv = 'log' 22 | NFold = 5 23 | out_mask = False 24 | out_results = True 25 | out_inference = True 26 | 27 | prng = np.random.RandomState(seed=17) # set seed random number generator 28 | rseed = prng.randint(1000) 29 | 30 | ''' 31 | Setting to run the algorithm 32 | ''' 33 | with open('setting_' + algorithm + '.yaml') as f: 34 | conf = yaml.load(f, Loader=yaml.FullLoader) 35 | conf['out_folder'] = out_folder 36 | 37 | ''' 38 | Import data 39 | ''' 40 | network = in_folder + adj # network complete path 41 | A, B, B_T, data_T_vals = tl.import_data(network, ego=ego, alter=alter, force_dense=True, header=0) 42 | nodes = A[0].nodes() 43 | 44 | def test_running_algorithm(self): 45 | print("\nStart running algorithm test\n") 46 | 47 | L = self.B.shape[0] 48 | N = self.B.shape[1] 49 | 50 | indices = cvfun.shuffle_indices_all_matrix(N, L, rseed=self.rseed) 51 | 52 | for fold in range(self.NFold): 53 | mask = cvfun.extract_mask_kfold(indices, N, fold=fold, NFold=self.NFold) 54 | 55 | ''' 56 | Set up training dataset 57 | ''' 58 | B_train = self.B.copy() 59 | print(B_train.shape, mask.shape) 60 | B_train[mask > 0] = 0 61 | 62 | self.conf['end_file'] = '_' + str(fold) + 'K' + str(self.K) + self.end_file 63 | u, v, w, eta, maxPSL, algo_obj = cvfun.fit_model(B_train, self.B_T, self.data_T_vals, nodes=self.nodes, 64 | N=N, L=L, K=self.K, algo=self.algorithm, 65 | flag_conv=self.flag_conv, **self.conf) 66 | 67 | ''' 68 | Load parameters 69 | ''' 70 | theta = np.load(self.out_folder+'theta_'+str(fold)+'K'+str(self.K)+self.end_file+'.npz') 71 | thetaGT = np.load(self.out_folder+'theta_'+str(self.algorithm)+'_'+str(fold)+'K'+str(self.K)+'.npz') 72 | 73 | self.assertTrue(np.array_equal(u, theta['u'])) 74 | self.assertTrue(np.array_equal(v, theta['v'])) 75 | self.assertTrue(np.array_equal(w, theta['w'])) 76 | self.assertTrue(np.array_equal(algo_obj.eta_f, theta['eta'])) 77 | 78 | self.assertTrue(np.array_equal(thetaGT['u'], theta['u'])) 79 | self.assertTrue(np.array_equal(thetaGT['v'], theta['v'])) 80 | self.assertTrue(np.array_equal(thetaGT['w'], theta['w'])) 81 | self.assertTrue(np.array_equal(thetaGT['eta'], theta['eta'])) 82 | 83 | 84 | if __name__ == '__main__': 85 | # begin the unittest.main() 86 | unittest.main() 87 | -------------------------------------------------------------------------------- /code/tools.py: -------------------------------------------------------------------------------- 1 | """ 2 | Functions for handling the data. 3 | """ 4 | 5 | import networkx as nx 6 | import numpy as np 7 | import pandas as pd 8 | import sktensor as skt 9 | 10 | 11 | def import_data(dataset, ego='source', alter='target', force_dense=True, header=None): 12 | """ 13 | Import data, i.e. the adjacency matrix, from a given folder. 14 | 15 | Return the NetworkX graph and its numpy adjacency matrix. 16 | 17 | Parameters 18 | ---------- 19 | dataset : str 20 | Path of the input file. 21 | ego : str 22 | Name of the column to consider as source of the edge. 23 | alter : str 24 | Name of the column to consider as target of the edge. 25 | force_dense : bool 26 | If set to True, the algorithm is forced to consider a dense adjacency tensor. 27 | header : int 28 | Row number to use as the column names, and the start of the data. 29 | 30 | Returns 31 | ------- 32 | A : list 33 | List of MultiDiGraph NetworkX objects. 34 | B : ndarray/sptensor 35 | Graph adjacency tensor. 36 | B_T : None/sptensor 37 | Graph adjacency tensor (transpose). 38 | data_T_vals : None/ndarray 39 | Array with values of entries A[j, i] given non-zero entry (i, j). 40 | """ 41 | 42 | # read adjacency file 43 | df_adj = pd.read_csv(dataset, sep='\s+', header=header) 44 | print('{0} shape: {1}'.format(dataset, df_adj.shape)) 45 | 46 | A = read_graph(df_adj=df_adj, ego=ego, alter=alter, noselfloop=True) 47 | 48 | nodes = list(A[0].nodes()) 49 | 50 | # save the network in a tensor 51 | if force_dense: 52 | B, rw = build_B_from_A(A, nodes=nodes) 53 | B_T, data_T_vals = None, None 54 | else: 55 | B, B_T, data_T_vals, rw = build_sparse_B_from_A(A) 56 | 57 | print_graph_stat(A, rw) 58 | 59 | return A, B, B_T, data_T_vals 60 | 61 | 62 | def read_graph(df_adj, ego='source', alter='target', noselfloop=True): 63 | """ 64 | Create the graph by adding edges and nodes. 65 | It assumes that columns of layers are from l+2 (included) onwards. 66 | 67 | Return the list MultiDiGraph NetworkX objects. 68 | 69 | Parameters 70 | ---------- 71 | df_adj : DataFrame 72 | Pandas DataFrame object containing the edges of the graph. 73 | ego : str 74 | Name of the column to consider as source of the edge. 75 | alter : str 76 | Name of the column to consider as target of the edge. 77 | noselfloop : bool 78 | If set to True, the algorithm removes the self-loops. 79 | 80 | Returns 81 | ------- 82 | A : list 83 | List of MultiDiGraph NetworkX objects. 84 | """ 85 | 86 | # build nodes 87 | egoID = df_adj[ego].unique() 88 | alterID = df_adj[alter].unique() 89 | nodes = list(set(egoID).union(set(alterID))) 90 | nodes.sort() 91 | 92 | L = df_adj.shape[1] - 2 # number of layers 93 | # build the NetworkX graph: create a list of graphs, as many graphs as there are layers 94 | A = [nx.MultiDiGraph() for _ in range(L)] 95 | # set the same set of nodes and order over all layers 96 | for l in range(L): 97 | A[l].add_nodes_from(nodes) 98 | 99 | for index, row in df_adj.iterrows(): 100 | v1 = row[ego] 101 | v2 = row[alter] 102 | for l in range(L): 103 | if row[l + 2] > 0: 104 | if A[l].has_edge(v1, v2): 105 | A[l][v1][v2][0]['weight'] += int(row[l + 2]) # the edge already exists -> no parallel edge created 106 | else: 107 | A[l].add_edge(v1, v2, weight=int(row[l + 2])) 108 | 109 | # remove self-loops 110 | if noselfloop: 111 | print('Removing self loops') 112 | for l in range(L): 113 | A[l].remove_edges_from(list(nx.selfloop_edges(A[l]))) 114 | 115 | return A 116 | 117 | 118 | def print_graph_stat(A, rw): 119 | """ 120 | Print the statistics of the graph A. 121 | 122 | Parameters 123 | ---------- 124 | A : list 125 | List of MultiDiGraph NetworkX objects. 126 | rw : list 127 | List whose elements are reciprocity (considering the weights of the edges) values, one per each layer. 128 | """ 129 | 130 | L = len(A) 131 | N = A[0].number_of_nodes() 132 | print('Number of nodes =', N) 133 | print('Number of layers =', L) 134 | 135 | print('Number of edges and average degree in each layer:') 136 | for l in range(L): 137 | E = A[l].number_of_edges() 138 | k = 2 * float(E) / float(N) 139 | M = np.sum([d['weight'] for u, v, d in list(A[l].edges(data=True))]) 140 | kW = 2 * float(M) / float(N) 141 | 142 | print(f'E[{l}] = {E} - = {np.round(k, 3)}') 143 | print(f'M[{l}] = {M} - = {np.round(kW, 3)}') 144 | print(f'Reciprocity (networkX) = {np.round(nx.reciprocity(A[l]), 3)}') 145 | print(f'Reciprocity (intended as the proportion of bi-directional edges over the unordered pairs) = ' 146 | f'{np.round(reciprocal_edges(A[l]), 3)}') 147 | print(f'Reciprocity (considering the weights of the edges) = {np.round(rw[l], 3)}') 148 | 149 | 150 | def build_B_from_A(A, nodes=None): 151 | """ 152 | Create the numpy adjacency tensor of a networkX graph. 153 | 154 | Parameters 155 | ---------- 156 | A : list 157 | List of MultiDiGraph NetworkX objects. 158 | nodes : list 159 | List of nodes IDs. 160 | 161 | Returns 162 | ------- 163 | B : ndarray 164 | Graph adjacency tensor. 165 | rw : list 166 | List whose elements are reciprocity (considering the weights of the edges) values, one per each layer. 167 | """ 168 | 169 | N = A[0].number_of_nodes() 170 | if nodes is None: 171 | nodes = list(A[0].nodes()) 172 | B = np.empty(shape=[len(A), N, N]) 173 | rw = [] 174 | for l in range(len(A)): 175 | B[l, :, :] = nx.to_numpy_array(A[l], weight='weight', dtype=int, nodelist=nodes) 176 | rw.append(np.multiply(B[l], B[l].T).sum() / B[l].sum()) 177 | 178 | return B, rw 179 | 180 | 181 | def build_sparse_B_from_A(A): 182 | """ 183 | Create the sptensor adjacency tensor of a networkX graph. 184 | 185 | Parameters 186 | ---------- 187 | A : list 188 | List of MultiDiGraph NetworkX objects. 189 | 190 | Returns 191 | ------- 192 | data : sptensor 193 | Graph adjacency tensor. 194 | data_T : sptensor 195 | Graph adjacency tensor (transpose). 196 | v_T : ndarray 197 | Array with values of entries A[j, i] given non-zero entry (i, j). 198 | rw : list 199 | List whose elements are reciprocity (considering the weights of the edges) values, one per each layer. 200 | """ 201 | 202 | N = A[0].number_of_nodes() 203 | L = len(A) 204 | rw = [] 205 | 206 | d1 = np.array((), dtype='int64') 207 | d2, d2_T = np.array((), dtype='int64'), np.array((), dtype='int64') 208 | d3, d3_T = np.array((), dtype='int64'), np.array((), dtype='int64') 209 | v, vT, v_T = np.array(()), np.array(()), np.array(()) 210 | for l in range(L): 211 | b = nx.to_scipy_sparse_array(A[l]) 212 | b_T = nx.to_scipy_sparse_array(A[l]).transpose() 213 | rw.append(np.sum(b.multiply(b_T))/np.sum(b)) 214 | nz = b.nonzero() 215 | nz_T = b_T.nonzero() 216 | d1 = np.hstack((d1, np.array([l] * len(nz[0])))) 217 | d2 = np.hstack((d2, nz[0])) 218 | d2_T = np.hstack((d2_T, nz_T[0])) 219 | d3 = np.hstack((d3, nz[1])) 220 | d3_T = np.hstack((d3_T, nz_T[1])) 221 | v = np.hstack((v, np.array([b[i, j] for i, j in zip(*nz)]))) 222 | vT = np.hstack((vT, np.array([b_T[i, j] for i, j in zip(*nz_T)]))) 223 | v_T = np.hstack((v_T, np.array([b[j, i] for i, j in zip(*nz)]))) 224 | subs_ = (d1, d2, d3) 225 | subs_T_ = (d1, d2_T, d3_T) 226 | data = skt.sptensor(subs_, v, shape=(L, N, N), dtype=v.dtype) 227 | data_T = skt.sptensor(subs_T_, vT, shape=(L, N, N), dtype=vT.dtype) 228 | 229 | return data, data_T, v_T, rw 230 | 231 | 232 | def reciprocal_edges(G): 233 | """ 234 | Compute the proportion of bi-directional edges, by considering the unordered pairs. 235 | 236 | Parameters 237 | ---------- 238 | G: MultiDigraph 239 | MultiDiGraph NetworkX object. 240 | 241 | Returns 242 | ------- 243 | reciprocity: float 244 | Reciprocity value, intended as the proportion of bi-directional edges over the unordered pairs. 245 | """ 246 | 247 | n_all_edge = G.number_of_edges() 248 | n_undirected = G.to_undirected().number_of_edges() # unique pairs of edges, i.e. edges in the undirected graph 249 | n_overlap_edge = (n_all_edge - n_undirected) # number of undirected edges reciprocated in the directed network 250 | 251 | if n_all_edge == 0: 252 | raise nx.NetworkXError("Not defined for empty graphs.") 253 | 254 | reciprocity = float(n_overlap_edge) / float(n_undirected) 255 | 256 | return reciprocity 257 | 258 | 259 | def can_cast(string): 260 | """ 261 | Verify if one object can be converted to integer object. 262 | 263 | Parameters 264 | ---------- 265 | string : int or float or str 266 | Name of the node. 267 | 268 | Returns 269 | ------- 270 | bool : bool 271 | If True, the input can be converted to integer object. 272 | """ 273 | 274 | try: 275 | int(string) 276 | return True 277 | except ValueError: 278 | return False 279 | 280 | 281 | def normalize_nonzero_membership(u): 282 | """ 283 | Given a matrix, it returns the same matrix normalized by row. 284 | 285 | Parameters 286 | ---------- 287 | u: ndarray 288 | Numpy Matrix. 289 | 290 | Returns 291 | ------- 292 | The matrix normalized by row. 293 | """ 294 | 295 | den1 = u.sum(axis=1, keepdims=True) 296 | nzz = den1 == 0. 297 | den1[nzz] = 1. 298 | 299 | return u / den1 300 | -------------------------------------------------------------------------------- /data/input/setting111.yaml: -------------------------------------------------------------------------------- 1 | ExpM: null 2 | K: 3 3 | N: 600 4 | Normalization: 0 5 | ag: 0.1 6 | alpha: 0.1 7 | beta: 0.1 8 | corr: 0.0 9 | end_file: '' 10 | eta: 0.5 11 | k: 20 12 | out_folder: ../data/input/ 13 | outfile_adj: null 14 | output_adj: true 15 | output_parameters: true 16 | over: 0.0 17 | seed: 111 18 | structure: assortative 19 | verbose: true 20 | -------------------------------------------------------------------------------- /data/input/theta_gt111.npz: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mcontisc/CRep/286e56a39a0a95181bfebd8e8eb96b614dafa76b/data/input/theta_gt111.npz -------------------------------------------------------------------------------- /data/output/5-fold_cv/setting_CRep.yaml: -------------------------------------------------------------------------------- 1 | N_real: 5 2 | assortative: true 3 | constrained: true 4 | decision: 10 5 | end_file: _4K3_test 6 | err: 0.1 7 | err_max: 1.0e-12 8 | eta0: null 9 | files: ../data/input/theta_gt111.npz 10 | fix_eta: false 11 | inf: 10000000000.0 12 | initialization: 0 13 | max_iter: 1000 14 | out_folder: ../data/output/5-fold_cv/ 15 | out_inference: true 16 | rseed: 0 17 | tolerance: 0.0001 18 | undirected: false 19 | verbose: false 20 | -------------------------------------------------------------------------------- /data/output/5-fold_cv/syn111_cv.csv: -------------------------------------------------------------------------------- 1 | K,fold,rseed,eta,auc_train,auc_test,auc_cond_train,auc_cond_test,opt_func_train,opt_func_test,max_it 2 | 3,0,623,0.34450780895354066,0.7357956061904156,0.6431951069025217,0.8644220192265917,0.7730123610462685,-18834.94381488201,-3438.707471119684,1000 3 | 3,1,623,0.34969550348108364,0.706802046864056,0.6064551644130902,0.8603468628767448,0.7346084232804233,-18875.0841499074,-3450.015939354893,651 4 | 3,2,623,0.3599626759523616,0.7060443755969068,0.5882220201581183,0.8601274876998479,0.7160829809919951,-18777.639870169412,-3480.266685876016,471 5 | 3,3,623,0.3563177533646485,0.7075971592020338,0.5894315176609548,0.860625257711535,0.732398520174079,-18725.337471532228,-3544.56033815658,521 6 | 3,4,623,0.35199272216813915,0.731800436164251,0.6443309676975304,0.8652655318514253,0.7729335828495194,-19055.316878897367,-3327.6275534005563,1000 -------------------------------------------------------------------------------- /data/output/5-fold_cv/theta_0K3_test.npz: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mcontisc/CRep/286e56a39a0a95181bfebd8e8eb96b614dafa76b/data/output/5-fold_cv/theta_0K3_test.npz -------------------------------------------------------------------------------- /data/output/5-fold_cv/theta_1K3_test.npz: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mcontisc/CRep/286e56a39a0a95181bfebd8e8eb96b614dafa76b/data/output/5-fold_cv/theta_1K3_test.npz -------------------------------------------------------------------------------- /data/output/5-fold_cv/theta_2K3_test.npz: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mcontisc/CRep/286e56a39a0a95181bfebd8e8eb96b614dafa76b/data/output/5-fold_cv/theta_2K3_test.npz -------------------------------------------------------------------------------- /data/output/5-fold_cv/theta_3K3_test.npz: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mcontisc/CRep/286e56a39a0a95181bfebd8e8eb96b614dafa76b/data/output/5-fold_cv/theta_3K3_test.npz -------------------------------------------------------------------------------- /data/output/5-fold_cv/theta_4K3_test.npz: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mcontisc/CRep/286e56a39a0a95181bfebd8e8eb96b614dafa76b/data/output/5-fold_cv/theta_4K3_test.npz -------------------------------------------------------------------------------- /data/output/5-fold_cv/theta_CRep_0K3.npz: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mcontisc/CRep/286e56a39a0a95181bfebd8e8eb96b614dafa76b/data/output/5-fold_cv/theta_CRep_0K3.npz -------------------------------------------------------------------------------- /data/output/5-fold_cv/theta_CRep_1K3.npz: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mcontisc/CRep/286e56a39a0a95181bfebd8e8eb96b614dafa76b/data/output/5-fold_cv/theta_CRep_1K3.npz -------------------------------------------------------------------------------- /data/output/5-fold_cv/theta_CRep_2K3.npz: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mcontisc/CRep/286e56a39a0a95181bfebd8e8eb96b614dafa76b/data/output/5-fold_cv/theta_CRep_2K3.npz -------------------------------------------------------------------------------- /data/output/5-fold_cv/theta_CRep_3K3.npz: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mcontisc/CRep/286e56a39a0a95181bfebd8e8eb96b614dafa76b/data/output/5-fold_cv/theta_CRep_3K3.npz -------------------------------------------------------------------------------- /data/output/5-fold_cv/theta_CRep_4K3.npz: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mcontisc/CRep/286e56a39a0a95181bfebd8e8eb96b614dafa76b/data/output/5-fold_cv/theta_CRep_4K3.npz -------------------------------------------------------------------------------- /data/output/setting_CRep.yaml: -------------------------------------------------------------------------------- 1 | N_real: 5 2 | assortative: true 3 | constrained: true 4 | decision: 10 5 | end_file: _CRep 6 | err: 0.1 7 | err_max: 1.0e-12 8 | eta0: null 9 | files: ../data/input/theta_gt111.npz 10 | fix_eta: false 11 | inf: 10000000000.0 12 | initialization: 0 13 | max_iter: 1000 14 | out_folder: ../data/output/ 15 | out_inference: true 16 | rseed: 0 17 | tolerance: 0.0001 18 | undirected: false 19 | verbose: false 20 | -------------------------------------------------------------------------------- /data/output/theta_CRep.npz: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mcontisc/CRep/286e56a39a0a95181bfebd8e8eb96b614dafa76b/data/output/theta_CRep.npz -------------------------------------------------------------------------------- /data/output/theta_test.npz: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mcontisc/CRep/286e56a39a0a95181bfebd8e8eb96b614dafa76b/data/output/theta_test.npz -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | numpy==1.22.0 2 | pandas 3 | scikit-learn 4 | scikit-tensor-py3 5 | scipy==1.10.0 6 | networkx 7 | argparse 8 | termcolor 9 | pyyaml 10 | pytest --------------------------------------------------------------------------------