├── .github └── workflows │ ├── ci.yml │ ├── publish.yml │ └── security_audit.yml ├── .gitignore ├── Cargo.toml ├── LICENSE ├── README.md ├── examples ├── maximum_value.rs └── pagerank.rs └── src ├── graph_frame.rs ├── lib.rs └── pregel.rs /.github/workflows/ci.yml: -------------------------------------------------------------------------------- 1 | on: [push, pull_request] 2 | 3 | name: CI 4 | 5 | jobs: 6 | check: 7 | name: Check 8 | runs-on: ubuntu-latest 9 | strategy: 10 | matrix: 11 | rust: 12 | - stable 13 | - 1.68.0 14 | steps: 15 | - uses: actions/checkout@v2 16 | - uses: actions-rs/toolchain@v1 17 | with: 18 | profile: minimal 19 | toolchain: ${{ matrix.rust }} 20 | override: true 21 | - uses: actions-rs/cargo@v1 22 | with: 23 | command: check 24 | 25 | test: 26 | name: Test Suite 27 | runs-on: ubuntu-latest 28 | strategy: 29 | matrix: 30 | rust: 31 | - stable 32 | - 1.68.0 33 | steps: 34 | - uses: actions/checkout@v2 35 | - uses: actions-rs/toolchain@v1 36 | with: 37 | profile: minimal 38 | toolchain: ${{ matrix.rust }} 39 | override: true 40 | - uses: actions-rs/cargo@v1 41 | with: 42 | command: test 43 | - name: Install cargo-llvm-cov 44 | uses: taiki-e/install-action@cargo-llvm-cov 45 | - name: Generate code coverage 46 | run: cargo llvm-cov --all-features --workspace --lcov --output-path lcov.info 47 | - name: Codecov upload 48 | uses: codecov/codecov-action@v3 49 | with: 50 | files: ./lcov.info 51 | fail_ci_if_error: false 52 | 53 | 54 | fmt: 55 | name: Rustfmt 56 | runs-on: ubuntu-latest 57 | strategy: 58 | matrix: 59 | rust: 60 | - stable 61 | - 1.68.0 62 | steps: 63 | - uses: actions/checkout@v2 64 | - uses: actions-rs/toolchain@v1 65 | with: 66 | profile: minimal 67 | toolchain: ${{ matrix.rust }} 68 | override: true 69 | - run: rustup component add rustfmt 70 | - uses: actions-rs/cargo@v1 71 | with: 72 | command: fmt 73 | args: --all -- --check 74 | 75 | clippy: 76 | name: Clippy 77 | runs-on: ubuntu-latest 78 | strategy: 79 | matrix: 80 | rust: 81 | - stable 82 | - 1.68.0 83 | steps: 84 | - uses: actions/checkout@v2 85 | - uses: actions-rs/toolchain@v1 86 | with: 87 | profile: minimal 88 | toolchain: ${{ matrix.rust }} 89 | override: true 90 | - run: rustup component add clippy 91 | - uses: actions-rs/cargo@v1 92 | with: 93 | command: clippy 94 | args: -- -D warnings 95 | -------------------------------------------------------------------------------- /.github/workflows/publish.yml: -------------------------------------------------------------------------------- 1 | on: 2 | release: 3 | types: [published] 4 | 5 | name: Publish 6 | 7 | jobs: 8 | publish: 9 | name: Publish 10 | runs-on: ubuntu-latest 11 | steps: 12 | - uses: actions/checkout@v3 13 | - uses: actions-rs/toolchain@v1 14 | with: 15 | toolchain: stable 16 | override: true 17 | - uses: katyo/publish-crates@v2 18 | with: 19 | registry-token: ${{ secrets.CARGO_TOKEN }} 20 | -------------------------------------------------------------------------------- /.github/workflows/security_audit.yml: -------------------------------------------------------------------------------- 1 | on: 2 | schedule: 3 | - cron: '0 0 * * *' 4 | 5 | name: Security audit 6 | 7 | jobs: 8 | audit: 9 | runs-on: ubuntu-latest 10 | steps: 11 | - uses: actions/checkout@v2 12 | - uses: actions-rs/audit-check@v1 13 | with: 14 | token: ${{ secrets.GITHUB_TOKEN }} -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Generated by Cargo 2 | # will have compiled files and executables 3 | /target/ 4 | 5 | # Remove Cargo.lock from gitignore if creating an executable, leave it for libraries 6 | # More information here https://doc.rust-lang.org/cargo/guide/cargo-toml-vs-cargo-lock.html 7 | Cargo.lock 8 | 9 | # These are backup files generated by rustfmt 10 | **/*.rs.bk 11 | 12 | .idea -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "pregel-rs" 3 | version = "0.0.14" 4 | authors = ["Ángel Iglesias Préstamo "] 5 | description = "A Graph library written in Rust for implementing your own algorithms in a Pregel fashion" 6 | documentation = "https://docs.rs/crate/pregel-rs/latest" 7 | repository = "https://github.com/angelip2303/pregel-rs" 8 | readme = "README.md" 9 | license = "GPL-3.0-or-later" 10 | edition = "2021" 11 | keywords = ["pregel", "graph", "pagerank", "polars", "algorithms"] 12 | categories = ["algorithms", "database", "mathematics", "science"] 13 | 14 | [dependencies] 15 | polars = { version = "0.45.1", features = [ 16 | "lazy", 17 | "streaming", 18 | "parquet", 19 | "performant", 20 | "chunked_ids", 21 | ] } 22 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # `pregel-rs` 2 | 3 | [![CI](https://github.com/angelip2303/pregel-rs/actions/workflows/ci.yml/badge.svg)](https://github.com/angelip2303/pregel-rs/actions/workflows/ci.yml) 4 | [![codecov](https://codecov.io/gh/angelip2303/pregel-rs/branch/main/graph/badge.svg?token=8SCDSSPH13)](https://codecov.io/gh/angelip2303/pregel-rs) 5 | [![latest_version](https://img.shields.io/crates/v/pregel-rs)](https://crates.io/crates/pregel-rs) 6 | [![documentation](https://img.shields.io/docsrs/pregel-rs/latest)](https://docs.rs/pregel-rs/latest/pregel_rs/) 7 | 8 | `pregel-rs` is a Graph processing library written in Rust that features 9 | a Pregel-based Framework for implementing your own algorithms in a 10 | message-passing fashion. It is designed to be efficient and scalable, 11 | making it suitable for processing large-scale graphs. 12 | 13 | ## Features 14 | 15 | - _Pregel-based framework_: `pregel-rs` is a powerful graph processing model 16 | that allows users to implement graph algorithms in a message-passing fashion, 17 | where computation is performed on vertices and messages are passed along edges. 18 | `pregel-rs` provides a framework that makes it easy to implement graph 19 | algorithms using this model. 20 | 21 | - _Rust-based implementation_: `pregel-rs` is implemented in Rust, a systems 22 | programming language known for its safety, concurrency, and performance. 23 | Rust's strong type system and memory safety features help ensure that `pregel-rs` 24 | is robust and reliable. 25 | 26 | - _Efficient and scalable_: `pregel-rs` designed to be efficient and scalable, 27 | making it suitable for processing large-scale graphs. It uses parallelism and 28 | optimization techniques to minimize computation and communication overhead, 29 | allowing it to handle graphs with millions or even billions of vertices and edges. 30 | For us to achieve this, we have built it on top of [polars](https://github.com/pola-rs/polars) 31 | a blazingly fast DataFrames library implemented in Rust using Apache Arrow 32 | Columnar Format as the memory model. 33 | 34 | - _Graph abstraction_: `pregel-rs` provides a graph abstraction that makes 35 | it easy to represent and manipulate graphs in Rust. It supports both directed and 36 | undirected graphs, and provides methods for adding, removing, and querying vertices 37 | and edges. 38 | 39 | - _Customizable computation_: `pregel-rs` allows users to implement their own 40 | computation logic by defining vertex computation functions. This gives users the 41 | flexibility to implement their own graph algorithms and customize the behavior 42 | of `pregel-rs` to suit their specific needs. 43 | 44 | ## Getting started 45 | 46 | To get started with `pregel-rs`, you can follow these steps: 47 | 48 | 1. _Install Rust_: `pregel-rs` requires Rust to be installed on your system. 49 | You can install Rust by following the instructions on the official Rust website: 50 | https://www.rust-lang.org/tools/install 51 | 52 | 2. _Create a new Rust project_: Once Rust is installed, you can create a new Rust 53 | project using the Cargo package manager, which is included with Rust. You can 54 | create a new project by running the following command in your terminal: 55 | 56 | ```sh 57 | cargo new my_pregel_project 58 | ``` 59 | 60 | 3. _Add `pregel-rs` as a dependency_: Next, you need to add `pregel-rs` as a 61 | dependency in your `Cargo.toml` file, which is located in the root directory 62 | of your project. You can add the following line to your `Cargo.toml` file: 63 | 64 | ```toml 65 | [dependencies] 66 | pregel-rs = "0.0.13" 67 | ``` 68 | 69 | 4. _Implement your graph algorithm_: Now you can start implementing your graph 70 | algorithm using the `pregel-rs` framework. You can define your vertex computation 71 | functions and use the graph abstraction provided by `pregel-rs` to manipulate the graph. 72 | 73 | 5. _Build and run your project_: Once you have implemented your graph algorithm, you 74 | can build and run your project using the Cargo package manager. You can build your 75 | project by running the following command in your terminal: 76 | 77 | You could also run one of the examples to check how this library works: 78 | 79 | ```sh 80 | cargo build 81 | cargo run --example pagerank 82 | ``` 83 | 84 | ## Acknowledgments 85 | 86 | Read [Pregel: A System for Large-Scale Graph Processing](https://15799.courses.cs.cmu.edu/fall2013/static/papers/p135-malewicz.pdf) 87 | for a reference on how to implement your own Graph processing algorithms in a Pregel fashion. If you want to take some 88 | inspiration from some curated-sources, just explore the [/examples](https://github.com/angelip2303/graph-rs/tree/main/examples) 89 | folder of this repository. 90 | 91 | ## Related projects 92 | 93 | 1. [GraphX](https://github.com/apache/spark/tree/master/graphx) is a library enabling Graph processing in the context of 94 | Apache Spark. 95 | 2. [GraphFrames](https://github.com/graphframes/graphframes) is the DataFrame-based equivalent to GraphX. 96 | 97 | ## License 98 | 99 | Copyright © 2023 Ángel Iglesias Préstamo () 100 | 101 | This program is free software: you can redistribute it and/or modify 102 | it under the terms of the GNU General Public License as published by 103 | the Free Software Foundation, either version 3 of the License, or 104 | (at your option) any later version. 105 | 106 | This program is distributed in the hope that it will be useful, 107 | but WITHOUT ANY WARRANTY; without even the implied warranty of 108 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 109 | GNU General Public License for more details. 110 | 111 | You should have received a copy of the GNU General Public License 112 | along with this program. If not, see . 113 | 114 | **By contributing to this project, you agree to release your 115 | contributions under the same license.** 116 | -------------------------------------------------------------------------------- /examples/maximum_value.rs: -------------------------------------------------------------------------------- 1 | use polars::lazy::dsl::max_horizontal; 2 | use polars::prelude::*; 3 | use pregel_rs::graph_frame::GraphFrame; 4 | use pregel_rs::pregel::Column::{Custom, Object, Subject, VertexId}; 5 | use pregel_rs::pregel::{Column, MessageReceiver, PregelBuilder}; 6 | use std::error::Error; 7 | 8 | /// This Rust function uses the Pregel algorithm to find the maximum value in a 9 | /// graph. 10 | /// 11 | /// Returns: 12 | /// 13 | /// The `main` function is returning a `Result` with an empty `Ok` value and a `Box` 14 | /// containing a `dyn Error` trait object. The `println!` macro is being used to 15 | /// print the result of the `pregel.run()` method call to the console. 16 | fn main() -> Result<(), Box> { 17 | let edges = df![ 18 | Subject.as_ref() => [0, 1, 1, 2, 2, 3], 19 | Object.as_ref() => [1, 0, 3, 1, 3, 2], 20 | ]?; 21 | 22 | let vertices = df![ 23 | VertexId.as_ref() => [0, 1, 2, 3], 24 | Custom("value").as_ref() => [3, 6, 2, 1], 25 | ]?; 26 | 27 | let pregel = PregelBuilder::new(GraphFrame::new(vertices, edges)?) 28 | .max_iterations(4) 29 | .with_vertex_column(Custom("max_value")) 30 | .initial_message(col(Custom("value").as_ref())) 31 | .send_messages( 32 | MessageReceiver::Object, 33 | Column::subject(Custom("max_value")), 34 | ) 35 | .aggregate_messages(Column::msg(None).max()) 36 | .v_prog(max_horizontal([ 37 | col(Custom("max_value").as_ref()), 38 | Column::msg(None), 39 | ])?) 40 | .build(); 41 | 42 | Ok(println!("{}", pregel.run()?)) 43 | } 44 | -------------------------------------------------------------------------------- /examples/pagerank.rs: -------------------------------------------------------------------------------- 1 | use polars::prelude::*; 2 | use pregel_rs::graph_frame::GraphFrame; 3 | use pregel_rs::pregel::Column::{Custom, Object, Subject, VertexId}; 4 | use pregel_rs::pregel::{Column, MessageReceiver, PregelBuilder}; 5 | use std::error::Error; 6 | 7 | /// This Rust function implements the PageRank algorithm using the Pregel framework. 8 | /// 9 | /// Returns: 10 | /// 11 | /// The `main` function is returning a `Result` with an empty `Ok` value and a `Box` 12 | /// containing a `dyn Error` trait object. The `println!` macro is used to print the 13 | /// result of the `pregel.run()` method call to the console. 14 | fn main() -> Result<(), Box> { 15 | let edges = df![ 16 | Subject.as_ref() => [0, 0, 1, 2, 3, 4, 4, 4], 17 | Object.as_ref() => [1, 2, 2, 3, 3, 1, 2, 3], 18 | ]?; 19 | 20 | let vertices = GraphFrame::from_edges(edges.clone())?.out_degrees()?; 21 | 22 | let damping_factor = 0.85; 23 | let num_vertices: f64 = vertices.column(VertexId.as_ref())?.len() as f64; 24 | 25 | let pregel = PregelBuilder::new(GraphFrame::new(vertices, edges)?) 26 | .max_iterations(4) 27 | .with_vertex_column(Custom("rank")) 28 | .initial_message(lit(1.0 / num_vertices)) 29 | .send_messages( 30 | MessageReceiver::Subject, 31 | Column::subject(Column::Custom("rank")) / Column::subject(Column::Custom("out_degree")), 32 | ) 33 | .send_messages( 34 | MessageReceiver::Object, 35 | Column::subject(Custom("rank")) / Column::subject(Custom("out_degree")), 36 | ) 37 | .aggregate_messages(Column::msg(None).sum()) 38 | .v_prog( 39 | Column::msg(None) * lit(damping_factor) + lit((1.0 - damping_factor) / num_vertices), 40 | ) 41 | .build(); 42 | 43 | Ok(println!("{}", pregel.run()?)) 44 | } 45 | -------------------------------------------------------------------------------- /src/graph_frame.rs: -------------------------------------------------------------------------------- 1 | use crate::pregel::Column::{Custom, Object, Subject, VertexId}; 2 | use polars::prelude::*; 3 | use std::fmt::{Debug, Display, Formatter}; 4 | use std::{error, fmt}; 5 | 6 | /// The `GraphFrame` type is a struct containing two `DataFrame` fields, `vertices` 7 | /// and `edges`. 8 | /// 9 | /// Properties: 10 | /// 11 | /// * `vertices`: The `vertices` property is a `DataFrame` that represents the nodes 12 | /// in a graph. It must contain a column named Id. 13 | /// 14 | /// * `edges`: The `edges` property is a `DataFrame` that represents the edges of a 15 | /// graph. It must contain -- at least -- two columns: Src and Dst. 16 | #[derive(Clone)] 17 | pub struct GraphFrame { 18 | /// The `vertices` property is a `DataFrame` that represents the nodes in a graph. 19 | pub vertices: DataFrame, 20 | /// The `edges` property is a `DataFrame` that represents the edges of a graph. 21 | pub edges: DataFrame, 22 | } 23 | 24 | /// A new type alias `Result` that is equivalent to the 25 | /// `std::result::Result` type. This is a common pattern in 26 | /// Rust to create a shorthand for a longer type name. The `Result` type is used 27 | /// throughout the `GraphFrame` struct to represent the result of a function that 28 | /// can either return a value of type `T` or an error of type `GraphFrameError`. 29 | type Result = std::result::Result; 30 | 31 | /// `GraphFrameError` is an enum that represents the different types of errors that 32 | /// can occur when working with a `GraphFrame`. It has three variants: `DuckDbError`, 33 | /// `FromPolars` and `MissingColumn`. 34 | #[derive(Debug)] 35 | pub enum GraphFrameError { 36 | /// `FromPolars` is a variant of `GraphFrameError` that represents errors that 37 | /// occur when converting from a `PolarsError`. 38 | FromPolars(PolarsError), 39 | /// `MissingColumn` is a variant of `GraphFrameError` that represents errors that 40 | /// occur when a required column is missing from a DataFrame. 41 | MissingColumn(MissingColumnError), 42 | } 43 | 44 | /// This is an implementation of the `Display` trait for the `GraphFrameError` enum. 45 | /// It allows instances of the `GraphFrameError` enum to be formatted as strings 46 | /// when they need to be displayed to the user. The `fmt` method takes a mutable 47 | /// reference to a `Formatter` object and returns a `fmt::Result`. It matches on the 48 | /// enum variants and calls the `Display` trait's `fmt` method on the inner error 49 | /// object to format the error message. 50 | impl Display for GraphFrameError { 51 | fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { 52 | match self { 53 | GraphFrameError::FromPolars(error) => Display::fmt(error, f), 54 | GraphFrameError::MissingColumn(error) => Display::fmt(error, f), 55 | } 56 | } 57 | } 58 | 59 | /// This is an implementation of the `Error` trait for a custom error type 60 | /// `GraphFrameError`. It defines the `source` method which returns the underlying 61 | /// cause of the error as an optional reference to a `dyn error::Error` trait 62 | /// object. If the error is caused by a `FromPolars` error, it returns the reference 63 | /// to the underlying error. If the error is caused by a missing column, it returns 64 | /// `None`. 65 | impl error::Error for GraphFrameError { 66 | fn source(&self) -> Option<&(dyn error::Error + 'static)> { 67 | match *self { 68 | GraphFrameError::FromPolars(ref e) => Some(e), 69 | GraphFrameError::MissingColumn(_) => None, 70 | } 71 | } 72 | } 73 | 74 | /// `MissingColumnError` is an enum that represents errors that occur when a 75 | /// required column is missing from a DataFrame. The `Debug` trait allows for easy 76 | /// debugging of the enum by printing its values in a formatted way. 77 | #[derive(Debug)] 78 | pub enum MissingColumnError { 79 | /// `Id` is a variant of `MissingColumnError` that represents the error that 80 | /// occurs when the `VertexId` column is missing from a DataFrame. 81 | VertexId, 82 | /// `Src` is a variant of `MissingColumnError` that represents the error that 83 | /// occurs when the `Subject` column is missing from a DataFrame. 84 | Subject, 85 | /// `Dst` is a variant of `MissingColumnError` that represents the error that 86 | /// occurs when the `Object` column is missing from a DataFrame. 87 | Object, 88 | } 89 | 90 | impl Display for MissingColumnError { 91 | fn fmt(&self, f: &mut Formatter) -> fmt::Result { 92 | let message = |df, column: &str| format!("Missing column {} in {}", column, df); 93 | 94 | match self { 95 | MissingColumnError::VertexId => write!(f, "{}", message("vertices", VertexId.as_ref())), 96 | MissingColumnError::Subject => write!(f, "{}", message("edges", Subject.as_ref())), 97 | MissingColumnError::Object => write!(f, "{}", message("edges", Object.as_ref())), 98 | } 99 | } 100 | } 101 | 102 | impl From for GraphFrameError { 103 | fn from(err: PolarsError) -> GraphFrameError { 104 | GraphFrameError::FromPolars(err) 105 | } 106 | } 107 | 108 | impl GraphFrame { 109 | /// The function creates a new GraphFrame object with given vertices and edges 110 | /// DataFrames, checking for required columns. 111 | /// 112 | /// Arguments: 113 | /// 114 | /// * `vertices`: A DataFrame containing information about the vertices of the 115 | /// graph, such as their IDs and attributes. 116 | /// 117 | /// * `edges`: A DataFrame containing information about the edges in the graph. It 118 | /// should have columns named "src" and "dst" to represent the source and 119 | /// destination vertices of each edge. 120 | /// 121 | /// Returns: 122 | /// 123 | /// a `Result` where `Self` is the `GraphFrame` struct. The `Ok` variant of 124 | /// the `Result` contains an instance of `GraphFrame` initialized with the provided 125 | /// `vertices` and `edges` DataFrames. If any of the required columns (`Id`, `Src`, 126 | /// `Dst`) are missing in the DataFrames, the function returns an `Error`. 127 | pub fn new(vertices: DataFrame, edges: DataFrame) -> Result { 128 | if !vertices.get_column_names_str().contains(&VertexId.as_ref()) { 129 | return Err(GraphFrameError::MissingColumn(MissingColumnError::VertexId)); 130 | } 131 | if !edges.get_column_names_str().contains(&Subject.as_ref()) { 132 | return Err(GraphFrameError::MissingColumn(MissingColumnError::Subject)); 133 | } 134 | if !edges.get_column_names_str().contains(&Object.as_ref()) { 135 | return Err(GraphFrameError::MissingColumn(MissingColumnError::Object)); 136 | } 137 | 138 | Ok(GraphFrame { vertices, edges }) 139 | } 140 | 141 | /// This function creates a new `GraphFrame` from a given set of edges by selecting 142 | /// source and destination vertices and concatenating them into a unique set of 143 | /// vertices. 144 | /// 145 | /// Arguments: 146 | /// 147 | /// * `edges`: A DataFrame containing the edges of a graph, with at least two 148 | /// columns named "src" and "dst" representing the source and destination vertices 149 | /// of each edge. 150 | /// 151 | /// Returns: 152 | /// 153 | /// The `from_edges` function returns a `Result` where `Self` is the 154 | /// `GraphFrame` struct. 155 | pub fn from_edges(edges: DataFrame) -> Result { 156 | let subjects = edges 157 | .clone() // this is because cloning a DataFrame is cheap 158 | .lazy() 159 | .select([col(Subject.as_ref()).alias(VertexId.as_ref())]); 160 | let objects = edges 161 | .clone() // this is because cloning a DataFrame is cheap 162 | .lazy() 163 | .select([col(Object.as_ref()).alias(VertexId.as_ref())]); 164 | let vertices = concat([subjects, objects], Default::default())? 165 | .unique( 166 | Some(vec![VertexId.as_ref().to_string()]), 167 | UniqueKeepStrategy::First, 168 | ) 169 | .collect()?; 170 | 171 | GraphFrame::new(vertices, edges) 172 | } 173 | 174 | /// This function calculates the out-degree of each node in a graph represented by 175 | /// its edges. The out-degree of a node is defined as the number of out-going edges; 176 | /// that is, edges that have as a source the actual node, and as a destination any 177 | /// other node in a directed-graph. 178 | /// 179 | /// Returns: 180 | /// 181 | /// This function returns a `Result` containing a `DataFrame`. The `DataFrame` 182 | /// contains the out-degree of each node in the graph represented by the `Graph` 183 | /// object. The original `DataFrame` is preserved; that is, we extend it with 184 | /// the out-degrees of each node. 185 | pub fn out_degrees(self) -> PolarsResult { 186 | self.edges 187 | .lazy() 188 | .group_by([col(Subject.as_ref()).alias(VertexId.as_ref())]) 189 | .agg([col(Object.as_ref()) 190 | .count() 191 | .alias(Custom("out_degree").as_ref())]) 192 | .collect() 193 | } 194 | 195 | /// This function calculates the in-degree of each node in a graph represented by 196 | /// its edges. The out-degree of a node is defined as the number of incoming edges; 197 | /// that is, edges that have as a source any node, and as a destination the node 198 | /// itself in a directed-graph. 199 | /// 200 | /// Returns: 201 | /// 202 | /// This function returns a `Result` containing a `DataFrame`. The `DataFrame` 203 | /// contains the in-degree of each node in the graph represented by the `Graph` 204 | /// object. The original `DataFrame` is preserved; that is, we extend it with 205 | /// the in-degrees of each node. 206 | pub fn in_degrees(self) -> PolarsResult { 207 | self.edges 208 | .lazy() 209 | .group_by([col(Object.as_ref())]) 210 | .agg([col(Subject.as_ref()) 211 | .count() 212 | .alias(Custom("in_degree").as_ref())]) 213 | .collect() 214 | } 215 | } 216 | 217 | /// This is the implementation of the `Display` trait for a `GraphFrame` struct. 218 | /// This allows instances of the `GraphFrame` struct to be printed in a formatted 219 | /// way using the `println!` macro or other formatting macros. The `fmt` method is 220 | /// defined to format the output as a string that includes the vertices and edges of 221 | /// the graph. 222 | impl Display for GraphFrame { 223 | fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { 224 | write!( 225 | f, 226 | "GraphFrame:\nVertices:\n{}\nEdges:\n{}", 227 | self.vertices, self.edges 228 | ) 229 | } 230 | } 231 | 232 | #[cfg(test)] 233 | mod tests { 234 | use crate::graph_frame::{GraphFrame, GraphFrameError}; 235 | use crate::pregel::Column; 236 | use polars::prelude::*; 237 | 238 | fn graph() -> Result { 239 | let subjects = Series::new( 240 | Column::Subject.as_ref().into(), 241 | [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 242 | ) 243 | .into(); 244 | let objects = Series::new( 245 | Column::Object.as_ref().into(), 246 | [2, 3, 4, 5, 6, 7, 8, 9, 10, 1], 247 | ) 248 | .into(); 249 | GraphFrame::from_edges(DataFrame::new(vec![subjects, objects]).unwrap()) 250 | } 251 | 252 | #[test] 253 | fn test_from_edges() { 254 | let graph = graph().unwrap(); 255 | assert_eq!(graph.vertices.height(), 10); 256 | assert_eq!(graph.edges.height(), 10); 257 | } 258 | 259 | #[test] 260 | fn test_in_degree() { 261 | let in_degree = graph().unwrap().in_degrees().unwrap(); 262 | assert_eq!(in_degree.height(), 10); 263 | assert_eq!( 264 | in_degree 265 | .column("in_degree") 266 | .unwrap() 267 | .u32() 268 | .unwrap() 269 | .sum() 270 | .unwrap(), 271 | 10 272 | ); 273 | } 274 | 275 | #[test] 276 | fn test_out_degree() { 277 | let out_degree = graph().unwrap().out_degrees().unwrap(); 278 | assert_eq!(out_degree.height(), 10); 279 | assert_eq!( 280 | out_degree 281 | .column("out_degree") 282 | .unwrap() 283 | .u32() 284 | .unwrap() 285 | .sum() 286 | .unwrap(), 287 | 10 288 | ); 289 | } 290 | 291 | #[test] 292 | fn test_new_missing_vertex_id_column() { 293 | let vertices = 294 | DataFrame::new(vec![Series::new("not_vertex_id".into(), [1, 2, 3]).into()]).unwrap(); 295 | let subjects = Series::new(Column::Subject.as_ref().into(), [1, 2, 3]).into(); 296 | let objects = Series::new(Column::Object.as_ref().into(), [2, 3, 4]).into(); 297 | let edges = DataFrame::new(vec![subjects, objects]).unwrap(); 298 | match GraphFrame::new(vertices, edges) { 299 | Ok(_) => panic!("Should have failed"), 300 | Err(e) => assert_eq!(e.to_string(), "Missing column vertex_id in vertices"), 301 | } 302 | } 303 | 304 | #[test] 305 | fn test_new_missing_subject_column() { 306 | let vertices = DataFrame::new(vec![Series::new( 307 | Column::VertexId.as_ref().into(), 308 | [1, 2, 3], 309 | ) 310 | .into()]) 311 | .unwrap(); 312 | let subjects = Series::new("not_src".into(), [1, 2, 3]).into(); 313 | let objects = Series::new(Column::Object.as_ref().into(), [2, 3, 4]).into(); 314 | let edges = DataFrame::new(vec![subjects, objects]).unwrap(); 315 | match GraphFrame::new(vertices, edges) { 316 | Ok(_) => panic!("Should have failed"), 317 | Err(e) => assert_eq!(e.to_string(), "Missing column subject in edges"), 318 | } 319 | } 320 | 321 | #[test] 322 | fn test_new_missing_object_column() { 323 | let vertices = DataFrame::new(vec![Series::new( 324 | Column::VertexId.as_ref().into(), 325 | [1, 2, 3], 326 | ) 327 | .into()]) 328 | .unwrap(); 329 | let subjects = Series::new(Column::Subject.as_ref().into(), [1, 2, 3]).into(); 330 | let objects = Series::new("not_dst".into(), [2, 3, 4]).into(); 331 | let edges = DataFrame::new(vec![subjects, objects]).unwrap(); 332 | match GraphFrame::new(vertices, edges) { 333 | Ok(_) => panic!("Should have failed"), 334 | Err(e) => assert_eq!(e.to_string(), "Missing column object in edges"), 335 | } 336 | } 337 | } 338 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | #![doc = include_str!("../README.md")] 2 | /// This crate provides a graph data structure and a graph frame data structure. 3 | pub mod graph_frame; 4 | /// This crate provides a Pregel implementation for the `GraphFrame` data structure. 5 | pub mod pregel; 6 | -------------------------------------------------------------------------------- /src/pregel.rs: -------------------------------------------------------------------------------- 1 | use crate::graph_frame::GraphFrame; 2 | use polars::prelude::*; 3 | 4 | type FnBox<'a> = Box Expr + 'a>; 5 | 6 | /// This defines an enumeration type `ColumnIdentifier` in Rust. It has several 7 | /// variants: `VertexId`, `Subject`, `Predicate`, `Object`, `Edge`, `Msg`, `Pregel`, 8 | /// and `Custom` which takes a `String` parameter. This enum can be used to represent 9 | /// different types of columns in a data structure or database table for it to be used 10 | /// in a Pregel program. 11 | pub enum Column { 12 | /// The `VertexId` variant represents the column that contains the vertex IDs. 13 | VertexId, 14 | /// The `Subject` variant represents the column that contains the source vertex IDs. 15 | Subject, 16 | /// The `Predicate` variant represents the column that contains the IDs of the predicates. 17 | Predicate, 18 | /// The `Object` variant represents the column that contains the destination vertex IDs. 19 | Object, 20 | /// The `Edge` variant represents the column that contains the edge IDs. 21 | Edge, 22 | /// The `Msg` variant represents the column that contains the messages sent to a vertex. 23 | Msg, 24 | /// The `Pregel` variant represents the column that contains the messages sent to a vertex. 25 | Pregel, 26 | /// The `Custom` variant represents a column that is not one of the predefined columns. 27 | Custom(&'static str), 28 | } 29 | 30 | /// This is the implementation of the `AsRef` trait for the `Column` enum. This 31 | /// allows instances of the `Column` enum to be used as references to strings. The 32 | /// `as_ref` method returns a reference to a string that corresponds to the variant 33 | /// of the `Column` enum. If the variant is `Custom`, the string is the custom 34 | /// identifier provided as an argument to the variant. This allows the `Column` 35 | /// enum to be used as a reference to a string in a Pregel program. 36 | /// 37 | /// # Examples 38 | /// 39 | /// ```rust 40 | /// use polars::prelude::*; 41 | /// use pregel_rs::pregel::Column::{Custom, VertexId}; 42 | /// 43 | /// let vertices = df![ 44 | /// VertexId.as_ref() => [0, 1, 2, 3], 45 | /// Custom("value").as_ref() => [3, 6, 2, 1], 46 | /// ]; 47 | /// 48 | /// ``` 49 | impl AsRef for Column { 50 | fn as_ref(&self) -> &str { 51 | match self { 52 | Column::VertexId => "vertex_id", 53 | Column::Subject => "subject", 54 | Column::Predicate => "predicate", 55 | Column::Object => "object", 56 | Column::Edge => "edge", 57 | Column::Msg => "msg", 58 | Column::Pregel => "_pregel_msg_", 59 | Column::Custom(id) => id, 60 | } 61 | } 62 | } 63 | 64 | impl Column { 65 | fn alias(prefix: &Column, column_name: Column) -> String { 66 | format!("{}.{}", prefix.as_ref(), column_name.as_ref()) 67 | } 68 | 69 | /// This function returns an expression for a column identifier representing 70 | /// the source vertex in a Pregel graph. 71 | /// 72 | /// Arguments: 73 | /// 74 | /// * `column_name`: `column_name` is a parameter of type `ColumnIdentifier`. It is 75 | /// used to identify the name of a column in a table or data source. The `subject` 76 | /// function takes this parameter and returns an expression that represents the 77 | /// value of the column with the given name. 78 | /// 79 | /// Returns: 80 | /// 81 | /// The function `subject` returns an `Expr` which represents a reference to the source 82 | /// vertex ID column in a Pregel graph computation. The `Expr` is created using the 83 | /// `col` function and the `alias` method of the `Pregel` struct to generate the 84 | /// appropriate column name. 85 | pub fn subject(column_name: Column) -> Expr { 86 | col(&Self::alias(&Column::Subject, column_name)) 87 | } 88 | 89 | /// This function returns an expression for a column identifier representing 90 | /// the destination vertex in a Pregel graph. 91 | /// 92 | /// Arguments: 93 | /// 94 | /// * `column_name`: `column_name` is a parameter of type `ColumnIdentifier` which 95 | /// represents the name of a column in a table. It is used as an argument to the 96 | /// `object` function to create an expression that refers to the column with the given 97 | /// name in the context of a Pregel computation. 98 | /// 99 | /// Returns: 100 | /// 101 | /// The function `object` returns an expression that represents the value of the column 102 | /// with the given `column_name` in the context of a `Pregel` graph computation. The 103 | /// expression is created using the `col` function and the `alias` method of the 104 | /// `Pregel` struct to ensure that the column name is properly qualified. 105 | pub fn object(column_name: Column) -> Expr { 106 | col(&Self::alias(&Column::Object, column_name)) 107 | } 108 | 109 | /// This function returns an expression for a column name in a graph edge table. 110 | /// 111 | /// Arguments: 112 | /// 113 | /// * `column_name`: `column_name` is a parameter of type `ColumnIdentifier` which 114 | /// represents the name of a column in a graph edge table. The `edge` function 115 | /// returns an expression that refers to this column using the `col` function and 116 | /// the `alias` function from the `Pregel` struct. 117 | /// 118 | /// Returns: 119 | /// 120 | /// The function `edge` returns an `Expr` which represents a reference to a column 121 | /// in a graph edge table. The column name is passed as an argument to the function 122 | /// and is used to construct the full column identifier using the `Column::alias` 123 | /// method. 124 | pub fn edge(column_name: Column) -> Expr { 125 | col(&Self::alias(&Column::Edge, column_name)) 126 | } 127 | 128 | /// This function returns an expression for a column name, either using a default 129 | /// value or a specified value. 130 | /// 131 | /// Arguments: 132 | /// 133 | /// * `column_name`: An optional parameter of type `ColumnIdentifier`. It represents 134 | /// the name of a column in a table. If it is `None`, the function returns a 135 | /// reference to the `Pregel` column. If it is `Some(column_name)`, the function 136 | /// returns a reference to a column with the name 137 | /// 138 | /// Returns: 139 | /// 140 | /// an `Expr` which is either a reference to the `ColumnIdentifier::Pregel` column 141 | /// if `column_name` is `None`, or a reference to a column with an alias created by 142 | /// `Column::alias` if `column_name` is `Some`. 143 | pub fn msg(column_name: Option) -> Expr { 144 | match column_name { 145 | None => col(Column::Pregel.as_ref()), 146 | Some(column_name) => col(&Self::alias(&Column::Msg, column_name)), 147 | } 148 | } 149 | 150 | pub fn as_ptr(&self) -> PlSmallStr { 151 | self.as_ref().into() 152 | } 153 | } 154 | 155 | /// This defines a struct `SendMessage` in Rust. It has two properties: 156 | /// `message_direction` and `send_message`. The `message_direction` property 157 | /// is the identifier for the direction of the message. The `send_message` 158 | /// property is the function that determines which messages to send from a 159 | /// vertex to its neighbors. 160 | pub struct SendMessage<'a> { 161 | /// `message_direction` is the identifier for the direction of the message. 162 | pub message_direction: Expr, 163 | /// `send_message` is the function that determines which messages to send from a 164 | /// vertex to its neighbors. 165 | pub send_message: FnBox<'a>, 166 | } 167 | 168 | impl<'a> SendMessage<'a> { 169 | /// The function creates a new instance of the `SendMessage` struct with the 170 | /// specified message direction and send message expression. 171 | /// 172 | /// Arguments: 173 | /// 174 | /// * `message_direction`: An enum that specifies whether the message should be sent 175 | /// to the source vertex or the destination vertex of an edge. 176 | /// * `send_message`: `send_message` is an expression that represents the message 177 | /// that will be sent from a vertex to its neighbors during the Pregel computation. 178 | /// It can be any valid Rust expression that evaluates to a DataFrame. 179 | /// 180 | /// Returns: 181 | /// 182 | /// A new instance of the `SendMessage` struct. 183 | pub fn new(message_direction: MessageReceiver, send_message: FnBox) -> SendMessage { 184 | // We make this in this manner because we want to use the `src.id` and `edge.dst` columns 185 | // in the send_messages function. This is because how polars works, when joining DataFrames, 186 | // it will keep only the left-hand side of the joins, thus, we need to use the `src.id` and 187 | // `edge.dst` columns to get the correct vertex IDs. 188 | let message_direction = match message_direction { 189 | MessageReceiver::Subject => Column::subject(Column::VertexId), 190 | MessageReceiver::Object => Column::edge(Column::Object), 191 | }; 192 | let send_message = Box::new(send_message); 193 | // Now we create the `SendMessage` struct with everything set up. 194 | SendMessage { 195 | message_direction, 196 | send_message, 197 | } 198 | } 199 | } 200 | 201 | /// The Pregel struct represents a Pregel computation with various parameters and 202 | /// expressions. 203 | /// 204 | /// Properties: 205 | /// 206 | /// * `graph`: The `graph` property is a `GraphFrame` struct that represents the 207 | /// graph data structure used in the Pregel algorithm. It contains information about 208 | /// the vertices and edges of the graph. 209 | /// 210 | /// * `max_iterations`: The maximum number of iterations that the Pregel algorithm 211 | /// will run for. 212 | /// 213 | /// * `vertex_column`: `vertex_column` is a property of the `PregelBuilder` struct 214 | /// that represents the name of the column in the graph's vertex DataFrame that 215 | /// contains the vertex IDs. This column is used to identify and locate a column 216 | /// where we apply some of the provided operations during the Pregel computation. 217 | /// 218 | /// * `initial_message`: `initial_message` is an expression that defines the initial 219 | /// message that each vertex in the graph will receive before the computation 220 | /// starts. This message can be used to initialize the state of each vertex or to 221 | /// provide some initial information to the computation. 222 | /// 223 | /// * `send_messages`: `send_messages` is a tuple containing two expressions. The 224 | /// first expression represents the message sending function that determines whether 225 | /// the message will go from Src to Dst or vice-versa. The second expression 226 | /// represents the message sending function that determines which messages to send 227 | /// from a vertex to its neighbors. 228 | /// 229 | /// * `aggregate_messages`: `aggregate_messages` is an expression that defines how 230 | /// messages sent to a vertex should be aggregated. In Pregel, messages are sent 231 | /// from one vertex to another and can be aggregated before being processed by the 232 | /// receiving vertex. The `aggregate_messages` expression specifies how these 233 | /// messages should be combined. 234 | /// 235 | /// * `v_prog`: `v_prog` is an expression that defines the vertex program for the 236 | /// Pregel algorithm. It specifies the computation that each vertex performs during 237 | /// each iteration of the algorithm. The vertex program can take as input the current 238 | /// state of the vertex, the messages received from its neighbors or and any other 239 | /// relevant information. 240 | pub struct Pregel<'a> { 241 | /// The `graph` property is a `GraphFrame` struct that represents the 242 | /// graph data structure used in the Pregel algorithm. It contains information about 243 | /// the vertices and edges of the graph. 244 | graph: GraphFrame, 245 | /// The maximum number of iterations that the Pregel algorithm. 246 | max_iterations: u8, 247 | /// `vertex_column` is a property of the `PregelBuilder` struct that identifies 248 | /// and locates a column where we apply some of the provided operations during 249 | /// the Pregel computation. 250 | vertex_column: Column, 251 | /// `initial_message` is an expression that defines the initial message that 252 | /// each vertex in the graph will receive before the computation starts. 253 | initial_message: Expr, 254 | /// The `send_messages` property is a vector of `SendMessage` structs that represent 255 | /// the message sending functions. The `SendMessage` struct contains two expressions. 256 | /// The first expression represents the message sending function that determines whether 257 | /// the message will go from Src to Dst or vice-versa. The second expression represents 258 | /// the message sending function that determines which messages to send from a 259 | /// vertex to its neighbors. 260 | send_messages: Vec>, 261 | /// `aggregate_messages` is an expression that defines how messages sent to a 262 | /// vertex should be aggregated. In Pregel, messages are sent from one vertex 263 | /// to another and can be aggregated before being processed by the receiving 264 | /// vertex. The `aggregate_messages` expression specifies how these messages 265 | /// should be combined. 266 | aggregate_messages: FnBox<'a>, 267 | /// `v_prog` is an expression that defines the vertex program for the Pregel 268 | /// algorithm. It specifies the computation that each vertex performs during 269 | /// each iteration of the algorithm. The vertex program can take as input the 270 | /// current state of the vertex, the messages received from its neighbors or 271 | /// and any other relevant information. 272 | v_prog: FnBox<'a>, 273 | } 274 | 275 | /// The `PregelBuilder` struct represents a builder for configuring the Pregel 276 | /// algorithm to be executed on a given graph. 277 | /// 278 | /// Properties: 279 | /// 280 | /// * `graph`: The `graph` property is a `GraphFrame` struct that represents the 281 | /// graph data structure used in the Pregel algorithm. It contains information about 282 | /// the vertices and edges of the graph. 283 | /// 284 | /// * `max_iterations`: The maximum number of iterations that the Pregel algorithm 285 | /// will run for. 286 | /// 287 | /// * `vertex_column`: `vertex_column` is a property of the `PregelBuilder` struct 288 | /// that represents the name of the column in the graph's vertex DataFrame that 289 | /// contains the vertex IDs. This column is used to identify and locate a column 290 | /// where we apply some of the provided operations during the Pregel computation. 291 | /// 292 | /// * `initial_message`: `initial_message` is an expression that defines the initial 293 | /// message that each vertex in the graph will receive before the computation 294 | /// starts. This message can be used to initialize the state of each vertex or to 295 | /// provide some initial information to the computation. 296 | /// 297 | /// * `send_messages`: `send_messages` is a tuple containing two expressions. The 298 | /// first expression represents the message sending function that determines whether 299 | /// the message will go from Src to Dst or vice-versa. The second expression 300 | /// represents the message sending function that determines which messages to send 301 | /// from a vertex to its neighbors. 302 | /// 303 | /// * `aggregate_messages`: `aggregate_messages` is an expression that defines how 304 | /// messages sent to a vertex should be aggregated. In Pregel, messages are sent 305 | /// from one vertex to another and can be aggregated before being processed by the 306 | /// receiving vertex. The `aggregate_messages` expression specifies how these 307 | /// messages should be combined. 308 | /// 309 | /// * `v_prog`: `v_prog` is an expression that defines the vertex program for the 310 | /// Pregel algorithm. It specifies the computation that each vertex performs during 311 | /// each iteration of the algorithm. The vertex program can take as input the current 312 | /// state of the vertex, the messages received from its neighbors or and any other 313 | /// relevant information. 314 | pub struct PregelBuilder<'a> { 315 | /// The `graph` property is a `GraphFrame` struct that represents the 316 | /// graph data structure used in the Pregel algorithm. It contains information about 317 | /// the vertices and edges of the graph. 318 | graph: GraphFrame, 319 | /// The maximum number of iterations that the Pregel algorithm. 320 | max_iterations: u8, 321 | /// `vertex_column` is a property of the `PregelBuilder` struct that identifies 322 | /// and locates a column where we apply some of the provided operations during 323 | /// the Pregel computation. 324 | vertex_column: Column, 325 | /// `initial_message` is an expression that defines the initial message that 326 | /// each vertex in the graph will receive before the computation starts. 327 | initial_message: Expr, 328 | /// The `send_messages` property is a vector of `SendMessage` structs that represent 329 | /// the message sending functions. The `SendMessage` struct contains two expressions. 330 | /// The first expression represents the message sending function that determines whether 331 | /// the message will go from Src to Dst or vice-versa. The second expression represents 332 | /// the message sending function that determines which messages to send from a 333 | /// vertex to its neighbors. 334 | send_messages: Vec>, 335 | /// `aggregate_messages` is an expression that defines how messages sent to a 336 | /// vertex should be aggregated. In Pregel, messages are sent from one vertex 337 | /// to another and can be aggregated before being processed by the receiving 338 | /// vertex. The `aggregate_messages` expression specifies how these messages 339 | /// should be combined. 340 | aggregate_messages: FnBox<'a>, 341 | /// `v_prog` is an expression that defines the vertex program for the Pregel 342 | /// algorithm. It specifies the computation that each vertex performs during 343 | /// each iteration of the algorithm. The vertex program can take as input the 344 | /// current state of the vertex, the messages received from its neighbors or 345 | /// and any other relevant information. 346 | v_prog: FnBox<'a>, 347 | } 348 | 349 | /// This code is defining an enumeration type `MessageReceiver` in Rust with 350 | /// two variants: `Subject` and `Object`. This can be used to represent the source and 351 | /// destination of a message in a Pregel program. 352 | pub enum MessageReceiver { 353 | /// The `Subject` variant indicates that a message should go to the source of 354 | /// an edge. 355 | Subject, 356 | /// The `Object` variant indicates that a message should go to the destination 357 | /// of an edge. 358 | Object, 359 | } 360 | 361 | /// The above code is implementing the `From` trait for the `Column` enum, which 362 | /// allows creating a `Column` instance from a `MessageReceiver` instance. The 363 | /// `match` statement maps the `MessageReceiver` variants to the corresponding 364 | /// `Column` variants. 365 | impl From for Column { 366 | fn from(message_receiver: MessageReceiver) -> Column { 367 | match message_receiver { 368 | MessageReceiver::Subject => Column::Subject, 369 | MessageReceiver::Object => Column::Object, 370 | } 371 | } 372 | } 373 | 374 | impl<'a> PregelBuilder<'a> { 375 | /// This function creates a new instance of a PregelBuilder with default values. 376 | /// 377 | /// Arguments: 378 | /// 379 | /// * `graph`: The graph parameter is of type GraphFrame and represents the graph on 380 | /// which the Pregel algorithm will be executed. 381 | /// 382 | /// Returns: 383 | /// 384 | /// A new instance of the `PregelBuilder` struct. 385 | pub fn new(graph: GraphFrame) -> Self { 386 | PregelBuilder { 387 | graph, 388 | max_iterations: 10, 389 | vertex_column: Column::Custom("aux"), 390 | initial_message: Default::default(), 391 | send_messages: Default::default(), 392 | aggregate_messages: Box::new(Default::default), 393 | v_prog: Box::new(Default::default), 394 | } 395 | } 396 | 397 | /// This function sets the maximum number of iterations for the Pregel algorithm and 398 | /// returns the modified PregelBuilder. 399 | /// 400 | /// Arguments: 401 | /// 402 | /// * `max_iterations`: The `max_iterations` parameter is an unsigned 8-bit integer 403 | /// that represents the maximum number of iterations that the Pregel algorithm or 404 | /// process can perform. This method sets the `max_iterations` field of a struct to 405 | /// the provided value and returns the modified struct instance. 406 | /// 407 | /// Returns: 408 | /// 409 | /// The `max_iterations` method returns `Self`, which refers to the same struct 410 | /// instance that the method was called on. This allows for method chaining, where 411 | /// multiple methods can be called on the same struct instance in a single 412 | /// expression. 413 | pub fn max_iterations(mut self, max_iterations: u8) -> Self { 414 | self.max_iterations = max_iterations; 415 | self 416 | } 417 | 418 | /// This function sets the vertex column identifier for a struct and returns the 419 | /// struct. 420 | /// 421 | /// Arguments: 422 | /// 423 | /// * `vertex_column`: `vertex_column` is a parameter of type `ColumnIdentifier` 424 | /// which represents the column identifier for the vertex column in a graph 425 | /// database. The `with_vertex_column` method takes in a `ColumnIdentifier` value 426 | /// and sets it as the `vertex_column` property of the struct instance. It then 427 | /// returns 428 | /// 429 | /// Returns: 430 | /// 431 | /// The `with_vertex_column` method returns `Self`, which refers to the same struct 432 | /// instance that the method was called on. This allows for method chaining, where 433 | /// multiple methods can be called on the same struct instance in a single 434 | /// expression. 435 | pub fn with_vertex_column(mut self, vertex_column: Column) -> Self { 436 | self.vertex_column = vertex_column; 437 | self 438 | } 439 | 440 | /// This function sets the initial message for a Rust struct and returns the struct. 441 | /// 442 | /// Arguments: 443 | /// 444 | /// * `initial_message`: `initial_message` is a parameter of type `Expr` that is 445 | /// used in a method of a struct. The method takes ownership of `self` and returns 446 | /// it after setting the `initial_message` field of the struct to the value of the 447 | /// `initial_message` parameter. This method can be used 448 | /// 449 | /// Returns: 450 | /// 451 | /// The `initial_message` method returns `Self`, which refers to the same struct 452 | /// instance that the method was called on. This allows for method chaining, where 453 | /// multiple methods can be called on the same struct instance in a single 454 | /// expression. 455 | pub fn initial_message(mut self, initial_message: Expr) -> Self { 456 | self.initial_message = initial_message; 457 | self 458 | } 459 | 460 | /// This function sets the message sending behavior for a Pregel computation in 461 | /// Rust. Chaining this method allows for multiple message sending behaviors to be 462 | /// specified for a single Pregel computation. 463 | /// 464 | /// # Examples 465 | /// 466 | /// ```rust 467 | /// use polars::prelude::*; 468 | /// use pregel_rs::graph_frame::GraphFrame; 469 | /// use pregel_rs::pregel::Column; 470 | /// use pregel_rs::pregel::Column::{Custom, Object, VertexId, Subject}; 471 | /// use pregel_rs::pregel::{MessageReceiver, Pregel, PregelBuilder}; 472 | /// use std::error::Error; 473 | /// 474 | /// // Simple example of a Pregel algorithm where we chain several `send_messages` calls. In 475 | /// // this example, we send a message to the source of an edge and then to the destination of 476 | /// // the same edge. It has no real use case, but it demonstrates how to chain multiple calls. 477 | /// fn main() -> Result<(), Box> { 478 | /// 479 | /// let edges = df![ 480 | /// Subject.as_ref() => [0, 1, 1, 2, 2, 3], 481 | /// Object.as_ref() => [1, 0, 3, 1, 3, 2], 482 | /// ]?; 483 | /// 484 | /// let vertices = df![ 485 | /// VertexId.as_ref() => [0, 1, 2, 3], 486 | /// Custom("value").as_ref() => [3, 6, 2, 1], 487 | /// ]?; 488 | /// 489 | /// let pregel = PregelBuilder::new(GraphFrame::new(vertices, edges)?) 490 | /// .max_iterations(4) 491 | /// .with_vertex_column(Custom("aux")) 492 | /// .initial_message(lit(0)) 493 | /// .send_messages(MessageReceiver::Subject, lit(1)) 494 | /// .send_messages(MessageReceiver::Object, lit(-1)) 495 | /// .aggregate_messages(Column::msg(None).sum()) 496 | /// .v_prog(Column::msg(None) + lit(1)) 497 | /// .build(); 498 | /// 499 | /// Ok(println!("{:?}", pregel.run())) 500 | /// } 501 | /// ``` 502 | /// 503 | /// Arguments: 504 | /// 505 | /// * `to`: `to` is a parameter of type `MessageReceiver`. It represents the 506 | /// destination vertex or vertices to which messages will be sent during the 507 | /// computation. 508 | /// * `send_messages`: `send_messages` is a parameter of type `Expr`. It is used to 509 | /// specify the function that will be applied to each vertex in the graph to send 510 | /// messages to its neighboring vertices. 511 | /// 512 | /// Returns: 513 | /// 514 | /// The `send_messages` method returns `Self`, which refers to the same struct 515 | /// instance that the method was called on. This allows for method chaining, where 516 | /// multiple methods can be called on the same struct instance in a single 517 | /// expression. 518 | pub fn send_messages(mut self, to: MessageReceiver, send_messages: Expr) -> Self { 519 | self.send_messages.push(SendMessage::new( 520 | to, 521 | Box::new(move || send_messages.clone()), 522 | )); 523 | self 524 | } 525 | 526 | /// This is a Rust function that adds a new message to be sent to a message receiver 527 | /// using a closure that returns an expression. 528 | /// 529 | /// Arguments: 530 | /// 531 | /// * `to`: `to` is a parameter of type `MessageReceiver` which represents the 532 | /// recipient of the message being sent. It could be an email address, phone number, 533 | /// or any other means of communication. 534 | /// 535 | /// * `send_messages`: `send_messages` is a closure that takes no arguments and 536 | /// returns an `Expr`. It is used to generate the messages that will be sent to the 537 | /// `to` message receiver. The closure is passed as an argument to the 538 | /// `send_messages_function` method and is stored in a `SendMessage` struct 539 | /// 540 | /// Returns: 541 | /// 542 | /// The `Self` object is being returned, which allows for method chaining. 543 | pub fn send_messages_function( 544 | mut self, 545 | to: MessageReceiver, 546 | send_messages: impl FnMut() -> Expr + 'a, 547 | ) -> Self { 548 | self.send_messages 549 | .push(SendMessage::new(to, Box::new(send_messages))); 550 | self 551 | } 552 | 553 | /// This function sets the aggregate_messages field of a struct to a given 554 | /// expression and returns the struct. 555 | /// 556 | /// Arguments: 557 | /// 558 | /// * `aggregate_messages`: `aggregate_messages` is a parameter of type `Expr` that 559 | /// is used in a method of a struct. The method takes ownership of the struct 560 | /// instance (`self`) and assigns the value of `aggregate_messages` to the 561 | /// corresponding field of the struct. The method then returns the modified struct 562 | /// instance. This 563 | /// 564 | /// Returns: 565 | /// 566 | /// The `aggregate_messages` method returns `Self`, which refers to the same struct 567 | /// instance that the method was called on. This allows for method chaining, where 568 | /// multiple methods can be called on the same struct instance in a single 569 | /// expression. 570 | pub fn aggregate_messages(mut self, aggregate_messages: Expr) -> Self { 571 | self.aggregate_messages = Box::new(move || aggregate_messages.clone()); 572 | self 573 | } 574 | 575 | /// This function sets the aggregate_messages field of a struct to a closure that 576 | /// returns an Expr. 577 | /// 578 | /// Arguments: 579 | /// 580 | /// * `aggregate_messages`: `aggregate_messages` is a closure that takes no 581 | /// arguments and returns an `Expr` object. The closure is passed as an argument to 582 | /// the `aggregate_messages_function` method and is stored in the 583 | /// `self.aggregate_messages` field. The closure is expected to be implemented by 584 | /// the caller and will be used 585 | /// 586 | /// Returns: 587 | /// 588 | /// The `Self` object is being returned. This allows for method chaining, where 589 | /// multiple methods can be called on the same object in a single expression. 590 | pub fn aggregate_messages_function( 591 | mut self, 592 | aggregate_messages: impl FnMut() -> Expr + 'a, 593 | ) -> Self { 594 | self.aggregate_messages = Box::new(aggregate_messages); 595 | self 596 | } 597 | 598 | /// This function sets the value of a field in a struct and returns the struct 599 | /// itself. 600 | /// 601 | /// Arguments: 602 | /// 603 | /// * `v_prog`: `v_prog` is a parameter of type `Expr` that is being passed to a 604 | /// method called `v_prog`. The method takes ownership of `self` (which is of the 605 | /// same type as the struct or object that the method belongs to) and assigns the 606 | /// value of `v_prog` to 607 | /// 608 | /// Returns: 609 | /// 610 | /// The `v_prog` method returns `Self`, which refers to the same struct 611 | /// instance that the method was called on. This allows for method chaining, where 612 | /// multiple methods can be called on the same struct instance in a single 613 | /// expression. 614 | pub fn v_prog(mut self, v_prog: Expr) -> Self { 615 | self.v_prog = Box::new(move || v_prog.clone()); 616 | self 617 | } 618 | 619 | /// This is a Rust function that takes a closure that returns an expression and sets 620 | /// it as a field in a struct. 621 | /// 622 | /// Arguments: 623 | /// 624 | /// * `v_prog`: `v_prog` is a closure that takes no arguments and returns an `Expr` 625 | /// object. The closure is passed as an argument to the `v_prog_function` method. 626 | /// The `impl FnMut() -> Expr + 'a` syntax specifies that the closure must be 627 | /// mutable (`FnMut`) and that it must not capture any variables from the enclosing 628 | /// scope (`'a`). The closure is stored in the `self.v_prog` field of the struct. 629 | /// 630 | /// Returns: 631 | /// 632 | /// The `Self` object is being returned. This allows for method chaining, where 633 | /// multiple methods can be called on the same object in a single expression. 634 | pub fn v_prog_function(mut self, v_prog: impl FnMut() -> Expr + 'a) -> Self { 635 | self.v_prog = Box::new(v_prog); 636 | self 637 | } 638 | 639 | /// The function returns a Pregel struct with the specified properties. This is, 640 | /// Pregel structs are to be created using the `Builder Pattern`, a creational 641 | /// design pattern that provides a way to construct complex structs in a 642 | /// step-by-step manner, allowing for the creation of several different configurations 643 | /// or variations of the same struct without directly exposing the underlying 644 | /// complexity. It allows for flexibility in creating different variations of 645 | /// objects while keeping the construction process modular and manageable. 646 | /// 647 | /// # Examples 648 | /// 649 | /// ```rust 650 | /// use polars::prelude::*; 651 | /// use polars::lazy::dsl::max_horizontal; 652 | /// use pregel_rs::graph_frame::GraphFrame; 653 | /// use pregel_rs::pregel::Column; 654 | /// use pregel_rs::pregel::Column::{Custom, Object, VertexId, Subject}; 655 | /// use pregel_rs::pregel::{MessageReceiver, Pregel, PregelBuilder}; 656 | /// use std::error::Error; 657 | /// 658 | /// // Simple example of a Pregel algorithm that finds the maximum value in a graph. 659 | /// fn main() -> Result<(), Box> { 660 | /// let edges = df![ 661 | /// Subject.as_ref() => [0, 1, 1, 2, 2, 3], 662 | /// Object.as_ref() => [1, 0, 3, 1, 3, 2], 663 | /// ]?; 664 | /// 665 | /// let vertices = df![ 666 | /// VertexId.as_ref() => [0, 1, 2, 3], 667 | /// Custom("value").as_ref() => [3, 6, 2, 1], 668 | /// ]?; 669 | /// 670 | /// let pregel = PregelBuilder::new(GraphFrame::new(vertices, edges)?) 671 | /// .max_iterations(4) 672 | /// .with_vertex_column(Custom("max_value")) 673 | /// .initial_message(col(Custom("value").as_ref())) 674 | /// .send_messages(MessageReceiver::Object, Column::subject(Custom("max_value"))) 675 | /// .aggregate_messages(Column::msg(None).max()) 676 | /// .v_prog(max_horizontal([col(Custom("max_value").as_ref()), Column::msg(None)])?) 677 | /// .build(); 678 | /// 679 | /// Ok(println!("{}", pregel.run()?)) 680 | /// } 681 | /// ``` 682 | /// 683 | /// Returns: 684 | /// 685 | /// The `build` method is returning an instance of the `Pregel` struct with the 686 | /// values of the fields set to the values of the corresponding fields in the 687 | /// `Builder` struct. 688 | pub fn build(self) -> Pregel<'a> { 689 | Pregel { 690 | graph: self.graph, 691 | max_iterations: self.max_iterations, 692 | vertex_column: self.vertex_column, 693 | initial_message: self.initial_message, 694 | send_messages: self.send_messages, 695 | aggregate_messages: self.aggregate_messages, 696 | v_prog: self.v_prog, 697 | } 698 | } 699 | } 700 | 701 | impl<'a> Pregel<'a> { 702 | /// Represents the Pregel model for large-scale graph processing, introduced 703 | /// by Google in a paper titled "Pregel: A System for Large-Scale Graph 704 | /// Processing" in 2010. 705 | /// 706 | /// The Pregel model is a distributed computing model for processing graph data 707 | /// in a distributed and parallel manner. It is designed for efficiently processing 708 | /// large-scale graphs with billions or trillions of vertices and edges. 709 | /// 710 | /// # Components 711 | /// 712 | /// - Vertices: Represent the entities in the graph and store the local state 713 | /// of each entity. Vertices can perform computations and communicate with their 714 | /// neighboring vertices. 715 | /// 716 | /// - Edges: Represent the relationships between vertices and are used for 717 | /// communication between vertices during computation. 718 | /// 719 | /// - Computation: Each vertex performs a user-defined computation during each 720 | /// super-step, based on its local state and the messages received from its 721 | /// neighboring vertices. 722 | /// 723 | /// - Messages: Vertices can send messages to their neighboring vertices during 724 | /// each super-step, which are then delivered in the next super-step. Messages 725 | /// are used for communication and coordination between vertices. 726 | /// 727 | /// - Aggregators: functions that can be used to collect and aggregate 728 | /// information from vertices during computation. Aggregators allow for global 729 | /// coordination and information gathering across the entire graph. 730 | /// 731 | /// # Usage 732 | /// 733 | /// The Pregel model follows a sequence of super-step, where each super-step consists 734 | /// of computation, message exchange, and aggregation. Vertices perform their computations 735 | /// in parallel, and messages are exchanged between vertices to coordinate their activities. 736 | /// The computation continues in a series of super-steps until a termination condition is met. 737 | /// 738 | /// This Rust function provides an implementation of the Pregel model for graph processing, 739 | /// allowing users to run vertex-centric algorithms that operate on the local state 740 | /// of each vertex and communicate through messages. 741 | /// 742 | /// # Notes 743 | /// 744 | /// - This is a simplified example of the Pregel model and may require further customization 745 | /// based on the specific graph processing requirements. 746 | /// 747 | /// Returns: 748 | /// 749 | /// a `PolarsResult`, which is a result type that can either contain 750 | /// the resulting `DataFrame` or an error of type `PolarsError`. 751 | pub fn run(mut self) -> PolarsResult { 752 | // We create a DataFrame that contains the edges of the graph. This DataFrame is used to 753 | // compute the triplets of the graph, which are used to send messages to the neighboring 754 | // vertices of each vertex in the graph. For us to do so, we select all the columns of the 755 | // graph edges and we prefix them with the `Edge` column name. 756 | let edges = &self 757 | .graph 758 | .edges 759 | .lazy() 760 | .select([all().name().prefix(&format!("{}.", Column::Edge.as_ref()))]); 761 | // We create a DataFrame that contains the vertices of the graph 762 | let vertices = &self.graph.vertices.lazy(); 763 | // We start the execution of the algorithm from the super-step 0; that is, all the nodes 764 | // are set to active, and the initial messages are sent to each vertex in the graph. What's more, 765 | // The initial messages are stored in the `initial_message` column of the `current_vertices` DataFrame. 766 | // We use the `lazy` method to create a lazy DataFrame. This is done to avoid the execution of 767 | // the DataFrame until the end of the algorithm. 768 | let initial_message = &self.initial_message; 769 | let mut current_vertices = vertices 770 | .to_owned() 771 | .select([ 772 | all(), // we select all the columns of the graph vertices 773 | initial_message 774 | .to_owned() 775 | .alias(self.vertex_column.as_ref()), // initial message column name is set by the user 776 | ]) 777 | .collect()?; 778 | // After computing the super-step 0, we start the execution of the Pregel algorithm. This 779 | // execution is performed until all the nodes vote to halt, or the number of iterations is 780 | // greater than the maximum number of iterations set by the user at the initialization of 781 | // the model (see the `Pregel::new` method). We start by setting the number of iterations to 1. 782 | let mut iteration = 1; 783 | while iteration <= self.max_iterations { 784 | // TODO: check that nodes are not halted. 785 | // We create a DataFrame that contains the triplets of the graph. Those triplets are 786 | // computed by joining the `current_vertices` DataFrame with the `edges` DataFrame 787 | // first, and with the `current_vertices` second. The first join is performed on the `src` 788 | // column of the `edges` DataFrame and the `id` column of the `current_vertices` DataFrame. 789 | // The second join is performed on the `dst` column of the resulting DataFrame from the previous 790 | // join and the `id` column of the `current_vertices` DataFrame. 791 | let current_vertices_df = ¤t_vertices.lazy(); 792 | let triplets_df = current_vertices_df 793 | .to_owned() 794 | .select([all() 795 | .name() 796 | .prefix(&format!("{}.", Column::Subject.as_ref()))]) 797 | .inner_join( 798 | edges.to_owned().select([all()]), 799 | Column::subject(Column::VertexId), // src column of the current_vertices DataFrame 800 | Column::edge(Column::Subject), // src column of the edges DataFrame 801 | ) 802 | .inner_join( 803 | current_vertices_df.to_owned().select([all() 804 | .name() 805 | .prefix(&format!("{}.", Column::Object.as_ref()))]), 806 | Column::edge(Column::Object), // dst column of the resulting DataFrame 807 | Column::object(Column::VertexId), // id column of the current_vertices DataFrame 808 | ); 809 | // We create a DataFrame that contains the messages sent by the vertices. The messages 810 | // are computed by performing an aggregation on the `triplets_df` DataFrame. The aggregation 811 | // is performed on the `msg` column of the `triplets_df` DataFrame, and the aggregation 812 | // function is the one set by the user at the initialization of the model. 813 | // We create a tuple where we store the column names of the `send_messages` DataFrame. We use 814 | // the `alias` method to ensure that the column names are properly qualified. We also 815 | // do the same for the `aggregate_messages` Expr. And the same with the `v_prog` Expr. 816 | let (mut send_messages_ids, mut send_messages_msg): (Vec, Vec) = self 817 | .send_messages 818 | .iter_mut() 819 | .map(|send_message| { 820 | let message_direction = &send_message.message_direction; 821 | let send_message_expr = &mut send_message.send_message; 822 | ( 823 | message_direction 824 | .to_owned() 825 | .alias(&Column::alias(&Column::Msg, Column::VertexId)), 826 | send_message_expr().alias(Column::Pregel.as_ref()), 827 | ) 828 | }) 829 | .unzip(); 830 | let send_messages = &mut send_messages_ids; // we create a mutable reference to the `send_messages_ids` Vector 831 | let send_messages_msg_df = &mut send_messages_msg; // we create a mutable reference to the `send_messages_msg` Vector 832 | send_messages.append(send_messages_msg_df); // we append the `send_messages_msg` Vector to the `send_messages` Vector 833 | let aggregate_messages = &mut self.aggregate_messages; 834 | let message_df = triplets_df.select(send_messages); 835 | let aggregate_df = message_df 836 | .group_by([Column::msg(Some(Column::VertexId))]) 837 | .agg([aggregate_messages().alias(Column::Pregel.as_ref())]); 838 | // We Compute the new values for the vertices. Note that we have to check for possibly 839 | // null values after performing the outer join. This is, columns where the join key does 840 | // not exist in the source DataFrame. In case we find any; for example, given a certain 841 | // node having no incoming edges, we have to replace the null value by 0 for the aggregation 842 | // to work properly. 843 | let v_prog = &mut self.v_prog; 844 | let vertex_columns = current_vertices_df 845 | .to_owned() 846 | .full_join( 847 | aggregate_df, 848 | col(Column::VertexId.as_ref()), // id column of the current_vertices DataFrame 849 | Column::msg(Some(Column::VertexId)), // msg.id column of the message_df DataFrame 850 | ) 851 | .select(&[ 852 | col(Column::VertexId.as_ref()), 853 | v_prog().alias(self.vertex_column.as_ref()), 854 | ]); 855 | // We update the `current_vertices` DataFrame with the new values for the vertices. We 856 | // do so by performing an inner join between the `current_vertices` DataFrame and the 857 | // `vertex_columns` DataFrame. The join is performed on the `id` column of the 858 | // `current_vertices` DataFrame and the `id` column of the `vertex_columns` DataFrame. 859 | current_vertices = vertices 860 | .to_owned() 861 | .inner_join( 862 | vertex_columns, 863 | col(Column::VertexId.as_ref()), 864 | col(Column::VertexId.as_ref()), 865 | ) 866 | .with_comm_subplan_elim(false) 867 | .collect()?; 868 | 869 | iteration += 1; // increment the counter so we now which iteration is being executed 870 | } 871 | 872 | Ok(current_vertices) 873 | } 874 | } 875 | 876 | #[cfg(test)] 877 | mod tests { 878 | use crate::graph_frame::GraphFrame; 879 | use crate::pregel::Column::VertexId; 880 | use crate::pregel::{Column, MessageReceiver, Pregel, PregelBuilder, SendMessage}; 881 | use polars::lazy::dsl::max_horizontal; 882 | use polars::prelude::*; 883 | use std::error::Error; 884 | 885 | fn pagerank_graph() -> Result { 886 | let edges = match df![ 887 | Column::Subject.as_ref() => [0, 0, 1, 2, 3, 4, 4, 4], 888 | Column::Object.as_ref() => [1, 2, 2, 3, 3, 1, 2, 3], 889 | ] { 890 | Ok(edges) => edges, 891 | Err(_) => return Err(String::from("Error creating the edges DataFrame")), 892 | }; 893 | 894 | let graph = match GraphFrame::from_edges(edges.clone()) { 895 | Ok(graph) => graph, 896 | Err(_) => return Err(String::from("Error creating the vertices DataFrame")), 897 | }; 898 | 899 | let vertices = match graph.out_degrees() { 900 | Ok(vertices) => vertices, 901 | Err(_) => { 902 | return Err(String::from( 903 | "Error creating the vertices out degree DataFrame", 904 | )) 905 | } 906 | }; 907 | 908 | match GraphFrame::new(vertices, edges) { 909 | Ok(graph) => Ok(graph), 910 | Err(_) => Err(String::from("Error creating the graph")), 911 | } 912 | } 913 | 914 | fn pagerank_builder<'a>(iterations: u8) -> Result, Box> { 915 | let graph = pagerank_graph()?; 916 | let damping_factor = 0.85; 917 | let num_vertices: f64 = graph.vertices.column(Column::VertexId.as_ref())?.len() as f64; 918 | 919 | Ok(PregelBuilder::new(graph) 920 | .max_iterations(iterations) 921 | .with_vertex_column(Column::Custom("rank")) 922 | .initial_message(lit(1.0 / num_vertices)) 923 | .send_messages( 924 | MessageReceiver::Subject, 925 | Column::subject(Column::Custom("rank")) 926 | / Column::subject(Column::Custom("out_degree")), 927 | ) 928 | .send_messages( 929 | MessageReceiver::Object, 930 | Column::subject(Column::Custom("rank")) 931 | / Column::subject(Column::Custom("out_degree")), 932 | ) 933 | .aggregate_messages(Column::msg(None).sum()) 934 | .v_prog( 935 | Column::msg(None) * lit(damping_factor) 936 | + lit((1.0 - damping_factor) / num_vertices), 937 | ) 938 | .build()) 939 | } 940 | 941 | fn agg_pagerank(pagerank: Pregel) -> Result { 942 | let result = match pagerank.run() { 943 | Ok(result) => result, 944 | Err(_) => return Err(String::from("Error running the PageRank algorithm")), 945 | }; 946 | let rank = match result.column("rank") { 947 | Ok(rank) => rank, 948 | Err(_) => { 949 | return Err(String::from( 950 | "Error retrieving the rank column from the DataFrame", 951 | )) 952 | } 953 | }; 954 | let rank_f64 = match rank.f64() { 955 | Ok(rank_f64) => rank_f64, 956 | Err(_) => return Err(String::from("Error casting the rank column to f64")), 957 | }; 958 | 959 | match rank_f64.sum() { 960 | Some(aggregated_rank) => Ok(aggregated_rank), 961 | None => Err(String::from( 962 | "Error computing the aggregation of PageRank values", 963 | )), 964 | } 965 | } 966 | 967 | fn pagerank_helper(iterations: u8) -> Result<(), String> { 968 | let pagerank = match pagerank_builder(iterations) { 969 | Ok(pagerank) => pagerank, 970 | Err(_) => return Err(String::from("Error building the Pregel algorithm :(")), 971 | }; 972 | 973 | let agg_pagerank = match agg_pagerank(pagerank) { 974 | Ok(agg_pagerank) => agg_pagerank, 975 | Err(error) => return Err(error), 976 | }; 977 | 978 | if (agg_pagerank - 1.0).abs() < 10e-3 { 979 | Ok(()) 980 | } else { 981 | Err(String::from( 982 | "The sum of the aggregated PageRank values should be 1", 983 | )) 984 | } 985 | } 986 | 987 | #[test] 988 | fn test_pagerank() -> Result<(), String> { 989 | for i in 1..3 { 990 | pagerank_helper(i)?; 991 | } 992 | 993 | Ok(()) 994 | } 995 | 996 | fn max_value_graph() -> Result { 997 | let edges = match df![ 998 | Column::Subject.as_ref() => [0, 1, 1, 2, 2, 3], 999 | Column::Object.as_ref() => [1, 0, 3, 1, 3, 2], 1000 | ] { 1001 | Ok(edges) => edges, 1002 | Err(_) => return Err(String::from("Error creating the edges DataFrame")), 1003 | }; 1004 | 1005 | let vertices = match df![ 1006 | Column::VertexId.as_ref() => [0, 1, 2, 3], 1007 | Column::Custom("value").as_ref() => [3, 6, 2, 1], 1008 | ] { 1009 | Ok(vertices) => vertices, 1010 | Err(_) => return Err(String::from("Error creating the vertices DataFrame")), 1011 | }; 1012 | 1013 | match GraphFrame::new(vertices, edges) { 1014 | Ok(graph) => Ok(graph), 1015 | Err(_) => Err(String::from("Error creating the graph")), 1016 | } 1017 | } 1018 | 1019 | fn max_value_builder<'a>(iterations: u8) -> Result, String> { 1020 | Ok(Pregel { 1021 | graph: max_value_graph()?, 1022 | max_iterations: iterations, 1023 | vertex_column: Column::Custom("max_value"), 1024 | initial_message: col(Column::Custom("value").as_ref()), 1025 | send_messages: vec![SendMessage::new( 1026 | MessageReceiver::Object, 1027 | Box::new(|| Column::subject(Column::Custom("value"))), 1028 | )], 1029 | aggregate_messages: Box::new(|| Column::msg(None).max()), 1030 | v_prog: Box::new(|| { 1031 | max_horizontal([col(Column::Custom("max_value").as_ref()), Column::msg(None)]) 1032 | .unwrap() 1033 | }), 1034 | }) 1035 | } 1036 | 1037 | fn max_value_helper(iterations: u8) -> Result<(), String> { 1038 | let max_value = match max_value_builder(iterations) { 1039 | Ok(max_value) => max_value, 1040 | Err(_) => return Err(String::from("Error building the Pregel algorithm :(")), 1041 | }; 1042 | 1043 | let result = match max_value.run() { 1044 | Ok(result) => result, 1045 | Err(_) => return Err(String::from("Error running the Max algorithm")), 1046 | }; 1047 | 1048 | let max = match result.column("max_value") { 1049 | Ok(max) => max, 1050 | Err(_) => { 1051 | return Err(String::from( 1052 | "Error retrieving the max column from the DataFrame", 1053 | )) 1054 | } 1055 | }; 1056 | 1057 | let max_i32 = match max.i32() { 1058 | Ok(max_i32) => max_i32, 1059 | Err(_) => return Err(String::from("Error casting the max column to i32")), 1060 | }; 1061 | 1062 | match max_i32.max() { 1063 | Some(max) => { 1064 | // In case the maximum value is computed 1065 | if max == 6 { 1066 | // In case MAX equals to 6, that means that the algorithm has converged 1067 | Ok(()) 1068 | } else { 1069 | // In any other case, the algorithm has not converged: ERROR 1070 | Err(String::from("The maximum value should be 4")) 1071 | } 1072 | } 1073 | None => Err(String::from("Error computing the maximum value")), 1074 | } 1075 | } 1076 | 1077 | #[test] 1078 | fn test_max_value() -> Result<(), String> { 1079 | for i in 1..3 { 1080 | max_value_helper(i)?; 1081 | } 1082 | 1083 | Ok(()) 1084 | } 1085 | 1086 | #[test] 1087 | fn test_literals() -> Result<(), String> { 1088 | // We create a graph using the exact same vertices and edges as the one used in the 1089 | // MaxValue algorithm. The graph itself is not important, we just need to test the 1090 | // Pregel model. 1091 | let graph = max_value_graph()?; 1092 | 1093 | // We create a Pregel algorithm that computes nothing, just sends literals to all the vertices 1094 | // and then returns the same literal. Note that the algorithm computes nothing, but it is 1095 | // useful to test the Pregel model. 1096 | match PregelBuilder::new(graph) 1097 | .max_iterations(4) 1098 | .with_vertex_column(Column::Custom("aux")) 1099 | .initial_message(lit(0)) // we pass the Undefined state to all vertices 1100 | .send_messages(MessageReceiver::Subject, lit(0)) 1101 | .aggregate_messages(lit(0)) 1102 | .v_prog(lit(0)) 1103 | .build() 1104 | .run() 1105 | { 1106 | Ok(_) => Ok(()), 1107 | Err(_) => Err(String::from("Error running the algorithm")), 1108 | } 1109 | } 1110 | 1111 | #[test] 1112 | fn test_send_messages_src_dst() -> Result<(), String> { 1113 | let graph = pagerank_graph()?; 1114 | 1115 | let pregel = match PregelBuilder::new(graph) 1116 | .max_iterations(4) 1117 | .with_vertex_column(Column::Custom("aux")) 1118 | .initial_message(lit(0)) 1119 | .send_messages(MessageReceiver::Subject, lit(1)) 1120 | .send_messages(MessageReceiver::Object, lit(-1)) 1121 | .aggregate_messages(Column::msg(None).sum()) 1122 | .v_prog(Column::msg(None) + lit(1)) 1123 | .build() 1124 | .run() 1125 | { 1126 | Ok(pregel) => pregel, 1127 | Err(_) => return Err(String::from("Error running pregel")), 1128 | }; 1129 | 1130 | let sorted_pregel = match pregel.sort([VertexId.as_ref()], Default::default()) { 1131 | Ok(sorted_pregel) => sorted_pregel, 1132 | Err(_) => return Err(String::from("Error sorting the DataFrame")), 1133 | }; 1134 | 1135 | let ans = match sorted_pregel.column("aux") { 1136 | Ok(ans) => ans, 1137 | Err(_) => return Err(String::from("Error retrieving the column")), 1138 | }; 1139 | 1140 | let expected = Series::new("aux".into(), [3, 2, 2, 2, 4]).into(); 1141 | 1142 | if ans.eq(&expected) { 1143 | Ok(()) 1144 | } else { 1145 | Err(String::from("The resulting DataFrame is not correct")) 1146 | } 1147 | } 1148 | } 1149 | --------------------------------------------------------------------------------