diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..f2fff10 --- /dev/null +++ b/.gitignore @@ -0,0 +1,273 @@ +### Julia Gitignore + +# Files generated by invoking Julia with --code-coverage +*.jl.cov +*.jl.*.cov + +# Files generated by invoking Julia with --track-allocation +*.jl.mem + +# System-specific files and directories generated by the BinaryProvider and BinDeps packages +# They contain absolute paths specific to the host computer, and so should not be committed +deps/deps.jl +deps/build.log +deps/downloads/ +deps/usr/ +deps/src/ + +# Build artifacts for creating documentation generated by the Documenter package +docs/build/ +docs/site/ + +# File generated by Pkg, the package manager, based on a corresponding Project.toml +# It records a fixed state of all packages used by the project. As such, it should not be +# committed for packages, but should be committed for applications that require a static +# environment. +Manifest.toml + + +### Python Gitignore + +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] +*$py.class + +# C extensions +*.so + +# Distribution / packaging +.Python +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +wheels/ +share/python-wheels/ +*.egg-info/ +.installed.cfg +*.egg +MANIFEST + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.nox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*.cover +*.py,cover +.hypothesis/ +.pytest_cache/ +cover/ + +# Translations +*.mo +*.pot + +# Django stuff: +*.log +local_settings.py +db.sqlite3 +db.sqlite3-journal + +# Flask stuff: +instance/ +.webassets-cache + +# Scrapy stuff: +.scrapy + +# Sphinx documentation +docs/_build/ + +# PyBuilder +.pybuilder/ +target/ + +# Jupyter Notebook +.ipynb_checkpoints + +# IPython +profile_default/ +ipython_config.py + +# pyenv +# For a library or package, you might want to ignore these files since the code is +# intended to run in multiple environments; otherwise, check them in: +# .python-version + +# pipenv +# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. +# However, in case of collaboration, if having platform-specific dependencies or dependencies +# having no cross-platform support, pipenv may install dependencies that don't work, or not +# install all needed dependencies. +#Pipfile.lock + +# poetry +# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control. +# This is especially recommended for binary packages to ensure reproducibility, and is more +# commonly ignored for libraries. +# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control +#poetry.lock + +# pdm +# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control. +#pdm.lock +# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it +# in version control. +# https://pdm.fming.dev/#use-with-ide +.pdm.toml + +# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm +__pypackages__/ + +# Celery stuff +celerybeat-schedule +celerybeat.pid + +# SageMath parsed files +*.sage.py + +# Environments +.env +.venv +env/ +venv/ +ENV/ +env.bak/ +venv.bak/ + +# Spyder project settings +.spyderproject +.spyproject + +# Rope project settings +.ropeproject + +# mkdocs documentation +/site + +# mypy +.mypy_cache/ +.dmypy.json +dmypy.json + +# Pyre type checker +.pyre/ + +# pytype static type analyzer +.pytype/ + +# Cython debug symbols +cython_debug/ + +# PyCharm +# JetBrains specific template is maintained in a separate JetBrains.gitignore that can +# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore +# and can be added to the global gitignore or merged into this file. For a more nuclear +# option (not recommended) you can uncomment the following to ignore the entire idea folder. +#.idea/ + + +### JetBrains Gitignore + +# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio, WebStorm and Rider +# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839 + +# User-specific stuff +.idea/**/workspace.xml +.idea/**/tasks.xml +.idea/**/usage.statistics.xml +.idea/**/dictionaries +.idea/**/shelf + +# AWS User-specific +.idea/**/aws.xml + +# Generated files +.idea/**/contentModel.xml + +# Sensitive or high-churn files +.idea/**/dataSources/ +.idea/**/dataSources.ids +.idea/**/dataSources.local.xml +.idea/**/sqlDataSources.xml +.idea/**/dynamic.xml +.idea/**/uiDesigner.xml +.idea/**/dbnavigator.xml + +# Gradle +.idea/**/gradle.xml +.idea/**/libraries + +# Gradle and Maven with auto-import +# When using Gradle or Maven with auto-import, you should exclude module files, +# since they will be recreated, and may cause churn. Uncomment if using +# auto-import. +# .idea/artifacts +# .idea/compiler.xml +# .idea/jarRepositories.xml +# .idea/modules.xml +# .idea/*.iml +# .idea/modules +# *.iml +# *.ipr + +# CMake +cmake-build-*/ + +# Mongo Explorer plugin +.idea/**/mongoSettings.xml + +# File-based project format +*.iws + +# IntelliJ +out/ + +# mpeltonen/sbt-idea plugin +.idea_modules/ + +# JIRA plugin +atlassian-ide-plugin.xml + +# Cursive Clojure plugin +.idea/replstate.xml + +# SonarLint plugin +.idea/sonarlint/ + +# Crashlytics plugin (for Android Studio and IntelliJ) +com_crashlytics_export_strings.xml +crashlytics.properties +crashlytics-build.properties +fabric.properties + +# Editor-based Rest Client +.idea/httpRequests + +# Android studio 3.1+ serialized cache file +.idea/caches/build_file_checksums.ser + +*.DS_Store \ No newline at end of file diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md new file mode 100644 index 0000000..3e72a91 --- /dev/null +++ b/CODE_OF_CONDUCT.md @@ -0,0 +1,128 @@ +# Contributor Covenant Code of Conduct + +## Our Pledge + +We as members, contributors, and leaders pledge to make participation in our +community a harassment-free experience for everyone, regardless of age, body +size, visible or invisible disability, ethnicity, sex characteristics, gender +identity and expression, level of experience, education, socio-economic status, +nationality, personal appearance, race, religion, or sexual identity +and orientation. + +We pledge to act and interact in ways that contribute to an open, welcoming, +diverse, inclusive, and healthy community. + +## Our Standards + +Examples of behavior that contributes to a positive environment for our +community include: + +* Demonstrating empathy and kindness toward other people +* Being respectful of differing opinions, viewpoints, and experiences +* Giving and gracefully accepting constructive feedback +* Accepting responsibility and apologizing to those affected by our mistakes, + and learning from the experience +* Focusing on what is best not just for us as individuals, but for the + overall community + +Examples of unacceptable behavior include: + +* The use of sexualized language or imagery, and sexual attention or + advances of any kind +* Trolling, insulting or derogatory comments, and personal or political attacks +* Public or private harassment +* Publishing others' private information, such as a physical or email + address, without their explicit permission +* Other conduct which could reasonably be considered inappropriate in a + professional setting + +## Enforcement Responsibilities + +Community leaders are responsible for clarifying and enforcing our standards of +acceptable behavior and will take appropriate and fair corrective action in +response to any behavior that they deem inappropriate, threatening, offensive, +or harmful. + +Community leaders have the right and responsibility to remove, edit, or reject +comments, commits, code, wiki edits, issues, and other contributions that are +not aligned to this Code of Conduct, and will communicate reasons for moderation +decisions when appropriate. + +## Scope + +This Code of Conduct applies within all community spaces, and also applies when +an individual is officially representing the community in public spaces. +Examples of representing our community include using an official e-mail address, +posting via an official social media account, or acting as an appointed +representative at an online or offline event. + +## Enforcement + +Instances of abusive, harassing, or otherwise unacceptable behavior may be +reported to the community leaders responsible for enforcement at +the [AIDOS Lab](https://aidos.group/). +All complaints will be reviewed and investigated promptly and fairly. + +All community leaders are obligated to respect the privacy and security of the +reporter of any incident. + +## Enforcement Guidelines + +Community leaders will follow these Community Impact Guidelines in determining +the consequences for any action they deem in violation of this Code of Conduct: + +### 1. Correction + +**Community Impact**: Use of inappropriate language or other behavior deemed +unprofessional or unwelcome in the community. + +**Consequence**: A private, written warning from community leaders, providing +clarity around the nature of the violation and an explanation of why the +behavior was inappropriate. A public apology may be requested. + +### 2. Warning + +**Community Impact**: A violation through a single incident or series +of actions. + +**Consequence**: A warning with consequences for continued behavior. No +interaction with the people involved, including unsolicited interaction with +those enforcing the Code of Conduct, for a specified period of time. This +includes avoiding interactions in community spaces as well as external channels +like social media. Violating these terms may lead to a temporary or +permanent ban. + +### 3. Temporary Ban + +**Community Impact**: A serious violation of community standards, including +sustained inappropriate behavior. + +**Consequence**: A temporary ban from any sort of interaction or public +communication with the community for a specified period of time. No public or +private interaction with the people involved, including unsolicited interaction +with those enforcing the Code of Conduct, is allowed during this period. +Violating these terms may lead to a permanent ban. + +### 4. Permanent Ban + +**Community Impact**: Demonstrating a pattern of violation of community +standards, including sustained inappropriate behavior, harassment of an +individual, or aggression toward or disparagement of classes of individuals. + +**Consequence**: A permanent ban from any sort of public interaction within +the community. + +## Attribution + +This Code of Conduct is adapted from the [Contributor Covenant][homepage], +version 2.0, available at +https://www.contributor-covenant.org/version/2/0/code_of_conduct.html. + +Community Impact Guidelines were inspired by [Mozilla's code of conduct +enforcement ladder](https://github.com/mozilla/diversity). + +[homepage]: https://www.contributor-covenant.org + +For answers to common questions about this code of conduct, see the FAQ at +https://www.contributor-covenant.org/faq. Translations are available at +https://www.contributor-covenant.org/translations. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..59e069a --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,31 @@ +# How to contribute to `orchid` + +Thank you for being willing to contribute to `orchid`! Here are some +resources to get you started: + +- Check out [open issues](/issues) in case you are looking for things + to tackle. + +**When contributing code, please be aware that your contribution will +fall under the terms of the [license](https://github.com/aidos-lab/orchid/blob/master/LICENSE).** + +## Pull requests + +If you propose some changes, a pull request is the easiest way to +integrate them. Please be mindful of the coding conventions (see below) +and [write good commit messages](https://cbea.ms/git-commit/). + +## Coding conventions + +Above all, consider that this is *open source software*. It is meant +to be used and extended by many people. Be mindful of them by making +your code look nice and appealing to them. We cannot build upon some +module no one understands. + +As a way to obtain some consistency in all contributions, Python code +should at least be conform with [PEP +8](https://www.python.org/dev/peps/pep-0008/). + +```console +$ flake8 script.py +``` diff --git a/DATALICENSE b/DATALICENSE new file mode 100644 index 0000000..68c2856 --- /dev/null +++ b/DATALICENSE @@ -0,0 +1,441 @@ +The raw data underlying our hypergraphs is licensed as follows: +- aps-a, aps-av, aps-cv: usage requires separate permission from APS +- dblp, dblp-v: CC0 +- mus: out of copyright or free for commercial use +- ndc-ai, ndc-pc: CC0 +- sha: [CC-BY-NC](https://creativecommons.org/licenses/by-nc/4.0/) +- stex: [CC-BY-SA](https://creativecommons.org/licenses/by-sa/4.0/) + +To the extent permitted by these original licenses, we make all derived +data available under a [CC-BY-SA 4.0](https://creativecommons.org/licenses/by-sa/4.0/) +license, with the exception of the aps-* data (not shared) and the mus data, +which we share under a [CC-BY-NC 4.0](https://creativecommons.org/licenses/by-nc/4.0/) license. +The text of the CC-BY-SA 4.0 license is stated below. + +Attribution-ShareAlike 4.0 International + +======================================================================= + +Creative Commons Corporation ("Creative Commons") is not a law firm and +does not provide legal services or legal advice. Distribution of +Creative Commons public licenses does not create a lawyer-client or +other relationship. Creative Commons makes its licenses and related +information available on an "as-is" basis. Creative Commons gives no +warranties regarding its licenses, any material licensed under their +terms and conditions, or any related information. Creative Commons +disclaims all liability for damages resulting from their use to the +fullest extent possible. + +Using Creative Commons Public Licenses + +Creative Commons public licenses provide a standard set of terms and +conditions that creators and other rights holders may use to share +original works of authorship and other material subject to copyright +and certain other rights specified in the public license below. The +following considerations are for informational purposes only, are not +exhaustive, and do not form part of our licenses. + + Considerations for licensors: Our public licenses are + intended for use by those authorized to give the public + permission to use material in ways otherwise restricted by + copyright and certain other rights. Our licenses are + irrevocable. Licensors should read and understand the terms + and conditions of the license they choose before applying it. + Licensors should also secure all rights necessary before + applying our licenses so that the public can reuse the + material as expected. Licensors should clearly mark any + material not subject to the license. This includes other CC- + licensed material, or material used under an exception or + limitation to copyright. More considerations for licensors: + wiki.creativecommons.org/Considerations_for_licensors + + Considerations for the public: By using one of our public + licenses, a licensor grants the public permission to use the + licensed material under specified terms and conditions. If + the licensor's permission is not necessary for any reason--for + example, because of any applicable exception or limitation to + copyright--then that use is not regulated by the license. Our + licenses grant only permissions under copyright and certain + other rights that a licensor has authority to grant. Use of + the licensed material may still be restricted for other + reasons, including because others have copyright or other + rights in the material. A licensor may make special requests, + such as asking that all changes be marked or described. + Although not required by our licenses, you are encouraged to + respect those requests where reasonable. More considerations + for the public: + wiki.creativecommons.org/Considerations_for_licensees + +======================================================================= + +Creative Commons Attribution-ShareAlike 4.0 International Public +License + +By exercising the Licensed Rights (defined below), You accept and agree +to be bound by the terms and conditions of this Creative Commons +Attribution-ShareAlike 4.0 International Public License ("Public +License"). To the extent this Public License may be interpreted as a +contract, You are granted the Licensed Rights in consideration of Your +acceptance of these terms and conditions, and the Licensor grants You +such rights in consideration of benefits the Licensor receives from +making the Licensed Material available under these terms and +conditions. + + +Section 1 -- Definitions. + + a. Adapted Material means material subject to Copyright and Similar + Rights that is derived from or based upon the Licensed Material + and in which the Licensed Material is translated, altered, + arranged, transformed, or otherwise modified in a manner requiring + permission under the Copyright and Similar Rights held by the + Licensor. For purposes of this Public License, where the Licensed + Material is a musical work, performance, or sound recording, + Adapted Material is always produced where the Licensed Material is + synched in timed relation with a moving image. + + b. Adapter's License means the license You apply to Your Copyright + and Similar Rights in Your contributions to Adapted Material in + accordance with the terms and conditions of this Public License. + + c. BY-SA Compatible License means a license listed at + creativecommons.org/compatiblelicenses, approved by Creative + Commons as essentially the equivalent of this Public License. + + d. Copyright and Similar Rights means copyright and/or similar rights + closely related to copyright including, without limitation, + performance, broadcast, sound recording, and Sui Generis Database + Rights, without regard to how the rights are labeled or + categorized. For purposes of this Public License, the rights + specified in Section 2(b)(1)-(2) are not Copyright and Similar + Rights. + + e. Effective Technological Measures means those measures that, in the + absence of proper authority, may not be circumvented under laws + fulfilling obligations under Article 11 of the WIPO Copyright + Treaty adopted on December 20, 1996, and/or similar international + agreements. + + f. Exceptions and Limitations means fair use, fair dealing, and/or + any other exception or limitation to Copyright and Similar Rights + that applies to Your use of the Licensed Material. + + g. License Elements means the license attributes listed in the name + of a Creative Commons Public License. The License Elements of this + Public License are Attribution and ShareAlike. + + h. Licensed Material means the artistic or literary work, database, + or other material to which the Licensor applied this Public + License. + + i. Licensed Rights means the rights granted to You subject to the + terms and conditions of this Public License, which are limited to + all Copyright and Similar Rights that apply to Your use of the + Licensed Material and that the Licensor has authority to license. + + j. Licensor means the individual(s) or entity(ies) granting rights + under this Public License. + + k. Share means to provide material to the public by any means or + process that requires permission under the Licensed Rights, such + as reproduction, public display, public performance, distribution, + dissemination, communication, or importation, and to make material + available to the public including in ways that members of the + public may access the material from a place and at a time + individually chosen by them. + + l. Sui Generis Database Rights means rights other than copyright + resulting from Directive 96/9/EC of the European Parliament and of + the Council of 11 March 1996 on the legal protection of databases, + as amended and/or succeeded, as well as other essentially + equivalent rights anywhere in the world. + + m. You means the individual or entity exercising the Licensed Rights + under this Public License. Your has a corresponding meaning. + + +Section 2 -- Scope. + + a. License grant. + + 1. Subject to the terms and conditions of this Public License, + the Licensor hereby grants You a worldwide, royalty-free, + non-sublicensable, non-exclusive, irrevocable license to + exercise the Licensed Rights in the Licensed Material to: + + a. reproduce and Share the Licensed Material, in whole or + in part; and + + b. produce, reproduce, and Share Adapted Material. + + 2. Exceptions and Limitations. For the avoidance of doubt, where + Exceptions and Limitations apply to Your use, this Public + License does not apply, and You do not need to comply with + its terms and conditions. + + 3. Term. The term of this Public License is specified in Section + 6(a). + + 4. Media and formats; technical modifications allowed. The + Licensor authorizes You to exercise the Licensed Rights in + all media and formats whether now known or hereafter created, + and to make technical modifications necessary to do so. The + Licensor waives and/or agrees not to assert any right or + authority to forbid You from making technical modifications + necessary to exercise the Licensed Rights, including + technical modifications necessary to circumvent Effective + Technological Measures. For purposes of this Public License, + simply making modifications authorized by this Section 2(a) + (4) never produces Adapted Material. + + 5. Downstream recipients. + + a. Offer from the Licensor -- Licensed Material. Every + recipient of the Licensed Material automatically + receives an offer from the Licensor to exercise the + Licensed Rights under the terms and conditions of this + Public License. + + b. Additional offer from the Licensor -- Adapted Material. + Every recipient of Adapted Material from You + automatically receives an offer from the Licensor to + exercise the Licensed Rights in the Adapted Material + under the conditions of the Adapter's License You apply. + + c. No downstream restrictions. You may not offer or impose + any additional or different terms or conditions on, or + apply any Effective Technological Measures to, the + Licensed Material if doing so restricts exercise of the + Licensed Rights by any recipient of the Licensed + Material. + + 6. No endorsement. Nothing in this Public License constitutes or + may be construed as permission to assert or imply that You + are, or that Your use of the Licensed Material is, connected + with, or sponsored, endorsed, or granted official status by, + the Licensor or others designated to receive attribution as + provided in Section 3(a)(1)(A)(i). + + b. Other rights. + + 1. Moral rights, such as the right of integrity, are not + licensed under this Public License, nor are publicity, + privacy, and/or other similar personality rights; however, to + the extent possible, the Licensor waives and/or agrees not to + assert any such rights held by the Licensor to the limited + extent necessary to allow You to exercise the Licensed + Rights, but not otherwise. + + 2. Patent and trademark rights are not licensed under this + Public License. + + 3. To the extent possible, the Licensor waives any right to + collect royalties from You for the exercise of the Licensed + Rights, whether directly or through a collecting society + under any voluntary or waivable statutory or compulsory + licensing scheme. In all other cases the Licensor expressly + reserves any right to collect such royalties. + + +Section 3 -- License Conditions. + +Your exercise of the Licensed Rights is expressly made subject to the +following conditions. + + a. Attribution. + + 1. If You Share the Licensed Material (including in modified + form), You must: + + a. retain the following if it is supplied by the Licensor + with the Licensed Material: + + i. identification of the creator(s) of the Licensed + Material and any others designated to receive + attribution, in any reasonable manner requested by + the Licensor (including by pseudonym if + designated); + + ii. a copyright notice; + + iii. a notice that refers to this Public License; + + iv. a notice that refers to the disclaimer of + warranties; + + v. a URI or hyperlink to the Licensed Material to the + extent reasonably practicable; + + b. indicate if You modified the Licensed Material and + retain an indication of any previous modifications; and + + c. indicate the Licensed Material is licensed under this + Public License, and include the text of, or the URI or + hyperlink to, this Public License. + + 2. You may satisfy the conditions in Section 3(a)(1) in any + reasonable manner based on the medium, means, and context in + which You Share the Licensed Material. For example, it may be + reasonable to satisfy the conditions by providing a URI or + hyperlink to a resource that includes the required + information. + + 3. If requested by the Licensor, You must remove any of the + information required by Section 3(a)(1)(A) to the extent + reasonably practicable. + + b. ShareAlike. + + In addition to the conditions in Section 3(a), if You Share + Adapted Material You produce, the following conditions also apply. + + 1. The Adapter's License You apply must be a Creative Commons + license with the same License Elements, this version or + later, or a BY-SA Compatible License. + + 2. You must include the text of, or the URI or hyperlink to, the + Adapter's License You apply. You may satisfy this condition + in any reasonable manner based on the medium, means, and + context in which You Share Adapted Material. + + 3. You may not offer or impose any additional or different terms + or conditions on, or apply any Effective Technological + Measures to, Adapted Material that restrict exercise of the + rights granted under the Adapter's License You apply. + + +Section 4 -- Sui Generis Database Rights. + +Where the Licensed Rights include Sui Generis Database Rights that +apply to Your use of the Licensed Material: + + a. for the avoidance of doubt, Section 2(a)(1) grants You the right + to extract, reuse, reproduce, and Share all or a substantial + portion of the contents of the database; + + b. if You include all or a substantial portion of the database + contents in a database in which You have Sui Generis Database + Rights, then the database in which You have Sui Generis Database + Rights (but not its individual contents) is Adapted Material, + including for purposes of Section 3(b); and + + c. You must comply with the conditions in Section 3(a) if You Share + all or a substantial portion of the contents of the database. + +For the avoidance of doubt, this Section 4 supplements and does not +replace Your obligations under this Public License where the Licensed +Rights include other Copyright and Similar Rights. + + +Section 5 -- Disclaimer of Warranties and Limitation of Liability. + + a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE + EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS + AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF + ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS, + IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION, + WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR + PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS, + ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT + KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT + ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU. + + b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE + TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION, + NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT, + INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES, + COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR + USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN + ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR + DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR + IN PART, THIS LIMITATION MAY NOT APPLY TO YOU. + + c. The disclaimer of warranties and limitation of liability provided + above shall be interpreted in a manner that, to the extent + possible, most closely approximates an absolute disclaimer and + waiver of all liability. + + +Section 6 -- Term and Termination. + + a. This Public License applies for the term of the Copyright and + Similar Rights licensed here. However, if You fail to comply with + this Public License, then Your rights under this Public License + terminate automatically. + + b. Where Your right to use the Licensed Material has terminated under + Section 6(a), it reinstates: + + 1. automatically as of the date the violation is cured, provided + it is cured within 30 days of Your discovery of the + violation; or + + 2. upon express reinstatement by the Licensor. + + For the avoidance of doubt, this Section 6(b) does not affect any + right the Licensor may have to seek remedies for Your violations + of this Public License. + + c. For the avoidance of doubt, the Licensor may also offer the + Licensed Material under separate terms or conditions or stop + distributing the Licensed Material at any time; however, doing so + will not terminate this Public License. + + d. Sections 1, 5, 6, 7, and 8 survive termination of this Public + License. + + +Section 7 -- Other Terms and Conditions. + + a. The Licensor shall not be bound by any additional or different + terms or conditions communicated by You unless expressly agreed. + + b. Any arrangements, understandings, or agreements regarding the + Licensed Material not stated herein are separate from and + independent of the terms and conditions of this Public License. + + +Section 8 -- Interpretation. + + a. For the avoidance of doubt, this Public License does not, and + shall not be interpreted to, reduce, limit, restrict, or impose + conditions on any use of the Licensed Material that could lawfully + be made without permission under this Public License. + + b. To the extent possible, if any provision of this Public License is + deemed unenforceable, it shall be automatically reformed to the + minimum extent necessary to make it enforceable. If the provision + cannot be reformed, it shall be severed from this Public License + without affecting the enforceability of the remaining terms and + conditions. + + c. No term or condition of this Public License will be waived and no + failure to comply consented to unless expressly agreed to by the + Licensor. + + d. Nothing in this Public License constitutes or may be interpreted + as a limitation upon, or waiver of, any privileges and immunities + that apply to the Licensor or You, including from the legal + processes of any jurisdiction or authority. + + +======================================================================= + +Creative Commons is not a party to its public +licenses. Notwithstanding, Creative Commons may elect to apply one of +its public licenses to material it publishes and in those instances +will be considered the “Licensor.” The text of the Creative Commons +public licenses is dedicated to the public domain under the CC0 Public +Domain Dedication. Except for the limited purpose of indicating that +material is shared under a Creative Commons public license or as +otherwise permitted by the Creative Commons policies published at +creativecommons.org/policies, Creative Commons does not authorize the +use of the trademark "Creative Commons" or any other trademark or logo +of Creative Commons without its prior written consent including, +without limitation, in connection with any unauthorized modifications +to any of its public licenses or any other arrangements, +understandings, or agreements concerning use of licensed material. For +the avoidance of doubt, this paragraph does not form part of the +public licenses. + +Creative Commons may be contacted at creativecommons.org. diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..c81a94d --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2023 Sebastian Dalleiger, Corinna Coupette, and Bastian Rieck + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. \ No newline at end of file diff --git a/Project.toml b/Project.toml new file mode 100644 index 0000000..a35c8aa --- /dev/null +++ b/Project.toml @@ -0,0 +1,10 @@ +name = "Orchid" +uuid = "65b37873-18c8-4f67-ad9c-7e8325cd4959" +authors = ["Sebastian Dalleiger "] +version = "0.1.0" + +[deps] +LinearAlgebra = "37e2e46d-f89d-539d-b4ee-838fcccc9c8e" +OptimalTransport = "7e02d93a-ae51-4f58-b602-d97af76e3b33" +SparseArrays = "2f01184e-e22b-5df5-ae63-d93ebab69eaf" +ThreadsX = "ac1d9e8a-700a-412c-b207-f0111f4b6c0d" diff --git a/README.md b/README.md index f0fb343..ccd4223 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,210 @@ -# orchid +# Orchid 🌸 – Ollivier-Ricci Curvature for Hypergraphs: A Unified Framework -## Hypergraph Curvature for Hypergraphs: A Unified Framework + + + + + +
+ This repository provides a Julia library and a command-line interface that implements the Ollivier-Ricci Curvature for Hypergraphs in Data (Orchid) Framework.

+ This project is based on the research paper Ollivier-Ricci Curvature for Hypergraphs: A Unified Framework, published at ICLR 2023.

+ The full reproducibility package, including the data that can be shared, is available on Zenodo.

+ If you find this repository helpful, please consider citing our paper! +
+ Orchid Thumbnail +
+ +```bibtex +@inproceedings{coupette2023orchid, + title = {Ollivier-Ricci Curvature for Hypergraphs: A Unified Framework}, + author = {Corinna Coupette and Sebastian Dalleiger and Bastian Rieck}, + booktitle = {The Eleventh International Conference on Learning Representations (ICLR)}, + year = {2023}, + url = {https://openreview.net/forum?id=sPCKNl5qDps}, + doi = {10.48550/arXiv.2210.12048} +} +``` + +## Installation + +### Julia Library + +To install the Orchid Julia library: +```julia-repl +julia> using Pkg +julia> Pkg.add(url="https://github.com/aidos-lab/orchid.git") +``` +Alternatively, we can install Orchid from the command line: +```sh +julia -e 'using Pkg; Pkg.add(url="https://github.com/aidos-lab/orchid.git")' +``` + +### Command-Line Interface +To use the command-line interface, we additionally need `bin/orchid.jl` and its dependencies. +```sh +git clone https://github.com/aidos-lab/orchid +julia -e 'using Pkg; Pkg.add(path="./orchid"); Pkg.add.(["ArgParse", "JSON", "Glob", "CodecZlib"])' +``` + +## Usage + +### Julia REPL + +Assuming the hypergraph resides in variable `X`: + +```julia-repl +julia> using Orchid +julia> hypergraph_curvatures(DispersionUnweightedStar, AggregationMax, X, 0.01) + +help?> Orchid.hypergraph_curvatures +``` + +To inspect the results: + + hypergraph_curvatures + +### Arguments +- `disperser`: Dispersion (options: DisperseUnweightedClique, DisperseWeightedClique, or DisperseUnweightedStar – Orchid paper: μ) +- `aggregator`: Aggregation (options: AggregateMean, AggregateMax, or (AggregateMean, AggregateMax) – Orchid paper: AGG) +- `input`: Incidence-matrix or edge-list encoding of the hypergraph +- `alpha`: Self-dispersion weight (smoothing parameter corresponding to the laziness of the random walk – Orchid paper: α) +- `cost`: Cost computation strategy (options: CostOndemand^, CostMatrix) + + ^ useful for very large hyper graphs. + +### Command-Line Interface + +To use the command-line interface: + +```sh +chmod +x bin/orchid.jl +bin/orchid.jl --help +bin/orchid.jl --aggregation mean --dispersion WeightedClique -i data/toy.ihg.tsv -o results/toy.orc.json +bin/orchid.jl --aggregation max --dispersion UnweightedStar --alpha 0.1 -i data/toys.chg.tsv -o results/toys.orc.json +``` + +The first execution might take some time. + +### Bash Scripts + +For convenience, we provide bash scripts to perform the curvature computations in the configurations reported in the ICLR paper for the shareable datasets used in the paper as well as (for illustration) for tiny toy data. +Both scripts compute curvatures with alpha in {0.0,0.1,0.2,0.3,0.4,0.5} for all combinations of dispersion and aggregation: + +- `reproduce.sh`: Computation for `{dblp,ndc-ai,ndc-pc}.ihg.tsv` and `{dblp-v,mus,sha,stex,syn_hcm,syn_hcm-hsbm,syn_hnmp,syn_hsbm}.chg.tsv`; results are stored to `results` folder as gzip-compressed JSON files. +- `reproduce_toy.sh`: Computation for `toy.ihg.tsv` and `toys.chg.tsv`; results are stored to `results` folder as uncompressed JSON files. + +Note that `reproduce.sh`, when run as-is, will consume considerable computational resources. +The easiest way to restrict computation to smaller datasets or some parts of our configuration space is to redefine some of the arrays at the top of the script. + +## Experiments + +To evaluate our curvature results, we require additional python packages. +We recommend installing these into a virtual environment, the classic option being [venv](https://docs.python.org/3/library/venv.html). +```sh +pip install -r experiments/requirements.txt +``` + +For our clustering, MMD, and kPCA experiments on collections of hypergraphs, we first compute their curvatures. +```sh +bin/orchid.jl --aggregation mean --dispersion WeightedClique -i data/syn_hcm-hsbm.chg.tsv.gz -o results/syn_hcm-hsbm.orc.json.gz +``` +Then, we evaluate the collection of curvatures using the tools in `experiments/`. +```sh +python experiments/graph-clustering.py -k 2 -i results/syn_hcm-hsbm.orc.json.gz -o gc/syn_hcm-hsbm.gc.json.gz +python experiments/kpca.py -k 2 -i results/syn_hcm-hsbm.orc.json.gz -o kpca/syn_hcm-hsbm.kpca.json.gz +python experiments/mmd.py -i results/syn_hcm-hsbm.orc.json.gz -o mmd/syn_hcm-hsbm.mmd.json.gz +``` + +For our node-clustering experiments with individual hypergraphs, we proceed similarly, now computing curvatures before we cluster the nodes. +```sh +bin/orchid.jl --aggregation mean --dispersion WeightedClique -i data/dblp.ihg.tsv.gz -o results/dblp.orc.json.gz +python experiments/node-clustering.py -k 2 -i results/dblp.orc.json.gz -o nc/dblp.nc.json.gz +``` + +To produce the files containing the competing local features, which can be input to the experiment scripts in place of the curvature files: + +```sh +python experiments/features.py -i data/sha.chg.tsv.gz -o features/sha.chg.json.gz +``` + +## Data Formats used by the Command-Line Interface + +### Inputs + +The data underlying our experiments are provided in a concise tsv format which allows us, inter alia, to store an entire hypergraph collection in *one* file. +The files encoding *individual hypergraphs* end with `ihg.tsv[.gz]`. +The files encoding *collections of hypergraphs* end with `chg.tsv[.gz]`. +Nodes are assumed to be consecutive, *one-indexed* integers. + +#### Individual hypergraphs (ihg): {name}.ihg.tsv.gz + +Each row is a hyperedge, with the identifiers of nodes occurring in the hyperedge separated by `\t` characters. + +Example (`data/toy.ihg.tsv`): +```sh +1 2 3 4 5 +2 3 +5 7 3 6 +``` + +#### Collections of hypergraphs (chg): {name}.chg.tsv.gz + +Just like the format for individual hypergraphs, +except that now the *first* identifier in each row identifies the hypergraph to which the hyperedge belongs. + +Example (`data/toys.chg.tsv`): +```sh +2 1 2 3 4 5 +2 2 3 +2 5 7 3 6 +0 1 2 4 +0 1 3 5 +0 1 4 6 +0 6 4 2 5 +``` + +Note that Orchid will treat the hypergraphs in the order in which their unique identifiers appear in the input, so in the example above, the hypergraph with ID 2 will occur before the hypergraph with ID 0 in the results. +The example also illustrates that we do not assume the hypergraph identifiers to be one-indexed or consecutive. + +### Outputs + +Curvature files are (optionally: gzip-compressed) JSON files of the form: + +```sh +[ + { + "node_curvature_neighborhood":[...], + "directional_curvature":[ + [...i values...], + [...j values...], + [...k values...] + ], + "node_curvature_edges":[...], + "edge_curvature":[...], + "aggregation":"Orchid.AggregateMax", + "dispersion":"UnweightedStar", + "input":"../data/toys.chg.tsv", + "alpha":0.1 + }, + { + ... + } +] +``` + +That is, we provide a list of JSON objects, one for each input hypergraph. +If the input is an individual hypergraph, the list will just have one entry. +If the input is a collection of hypergraphs, the list will contain the hypergraphs in the order they were found in the input file. + +## Disclaimer + +We refactored the entire code base and introduced the {ihg,chg}.tsv[.gz] data format after ICLR 2023. +The material results are the same, but there might be small deviations in details. + +## Contributing + +Contributions to Orchid are welcome. +If you find any issues or have suggestions for improvements, please open an issue or submit a pull request in the GitHub repository: https://github.com/aidos-lab/orchid diff --git a/bin/orchid.jl b/bin/orchid.jl new file mode 100755 index 0000000..074da68 --- /dev/null +++ b/bin/orchid.jl @@ -0,0 +1,132 @@ +#!/usr/bin/env -S julia -O3 --threads=auto --check-bounds=no + +using Orchid +using SparseArrays +using LinearAlgebra +using Glob +using JSON +using ArgParse +using CodecZlib: GzipCompressor, GzipDecompressorStream + +parse_edgelist(fp) = [parse.(Int, split(r)) for r in readlines(fp) for s in split(r) if s != ""] +function parse_edgelist_collection(fp) + rc, y = Vector{Int}[], Int[] + for r in readlines(fp) + t = parse.(Int, split(r)) + push!(y, t[1]) + push!(rc, t[2:end]) + end + y, rc +end + +convert(m::AbstractSparseVector) = findnz(m) +convert(m::AbstractMatrix) = findnz(sparse(triu(m, 1))) +convert(m::Vector{<:Number}) = m +convert(m::Vector) = map(convert, m) +convert(s::Symbol) = String(s) +convert(s) = s + +function get_entry(r, a, input, dispersion, alpha) + (node_curvature_neighborhood = convert(r.node_curvature_neighborhood), + directional_curvature = convert(r.directional_curvature), + node_curvature_edges = convert(a.node_curvature_edges), + edge_curvature = convert(a.edge_curvature), + aggregation = convert(a.aggregation), + dispersion = convert(dispersion), + input = convert(input), + alpha = convert(alpha)) +end + +function run(input, dispersion, aggregation, alpha) + !(0 <= alpha <= 1) && throw("!(0 <= alpha <= 1)") + + D = Dict{String,Type}( + lowercase("UnweightedClique") => Orchid.DisperseUnweightedClique, + lowercase("WeightedClique") => Orchid.DisperseWeightedClique, + lowercase("UnweightedStar") => Orchid.DisperseUnweightedStar + )[lowercase(dispersion)] + A = Dict{String,Any}( + "mean" => Orchid.AggregateMean, + "max" => Orchid.AggregateMax, + "all" => (Orchid.AggregateMean, Orchid.AggregateMax) + )[lowercase(aggregation)] + + guess_cost_calc(E) = length(E) > 10_000 || maximum(e -> maximum(e; init=0), E) > 10_000 ? Orchid.CostOndemand : Orchid.CostMatrix + open_() = endswith(input, ".gz") ? GzipDecompressorStream(open(input)) : open(input) + + if occursin(".chg.tsv", input) + @info "Reading Hypergraphs" + y, rc = parse_edgelist_collection(open_()) + ys = unique(y) + Tot = length(ys) + results = [] + foreach(ys) do Y + @info "Importing Hypergraph $Y/$Tot" + E = rc[y.==Y] + r = Orchid.hypergraph_curvatures(D, A, E, alpha, guess_cost_calc(E)) + for a in r.aggregations + push!(results, get_entry(r, a, input, dispersion, alpha)) + end + end + results + else + @info "Importing Hypergraph" + E = parse_edgelist(open_()) + r = Orchid.hypergraph_curvatures(D, A, E, alpha, guess_cost_calc(E)) + map(r.aggregations) do a + get_entry(r, a, input, dispersion, alpha) + end + end +end + +function orchid_main(input::String, output::String="-"; dispersion::String="UnweightedClique", aggregation::String="All", alpha=0.1) + if !occursin("*", input) + results = run(input, dispersion, aggregation, alpha) + @info "Converting Curvatures to JSON" + j = JSON.json(results) + @info "Writing JSON to $output" + write(output == "-" ? stdout : open(output, "w"), endswith(output, "gz") ? transcode(GzipCompressor, j) : j * "\n") + else + @info "Globbing $input" + results = [a for input in glob(input) for a in run(input, dispersion, aggregation, alpha)] + @info "Converting Curvatures to JSON" + j = JSON.json(results) + @info "Writing JSON to $output" + write(output == "-" ? stdout : open(output, "w"), endswith(output, "gz") ? transcode(GzipCompressor, j) : j * "\n") + end +end + +function main() + s = ArgParseSettings(description=""" + This is a command line interface for the ORCHID hypergraph curvature framework described in + + Coupette, C., Dalleiger, S. and Rieck, B., + Ollivier-Ricci Curvature for Hypergraphs: A Unified Framework, + ICLR 2023, doi:10.48550/arXiv.2210.12048. + """) + @add_arg_table! s begin + "-i", "--input" + required = true + help = "Input hypergraph(s) in edgelist format (options: individual edgelist for one hypergraph, collection of edgelists [ext: chg.tsv[.gz]], or a globbing pattern ['*' in `input`] both for multiple hypergraphs)" + "-o", "--output" + required = false + default = "-" + help = "Output destination ['-' denotes stdout]" + "--dispersion" + default = "UnweightedClique" + help = "Dispersion (options: UnweightedClique, WeightedClique, or UnweightedStar)" + "--aggregation" + default = "Mean" + help = "Aggregation (options: Mean, Max, or All)" + "--alpha" + arg_type = Float64 + help = "Self-Dispersion Weight" + default = 0.0 + end + opts = parse_args(s) + + orchid_main(opts["input"], opts["output"]; dispersion=opts["dispersion"], aggregation=opts["aggregation"], alpha=opts["alpha"]) +end + +main() + diff --git a/data/toy.ihg.tsv b/data/toy.ihg.tsv new file mode 100644 index 0000000..ebaf98b --- /dev/null +++ b/data/toy.ihg.tsv @@ -0,0 +1,3 @@ +1 2 3 4 5 +2 3 +5 7 3 6 \ No newline at end of file diff --git a/data/toys.chg.tsv b/data/toys.chg.tsv new file mode 100644 index 0000000..ed14dd7 --- /dev/null +++ b/data/toys.chg.tsv @@ -0,0 +1,7 @@ +2 1 2 3 4 5 +2 2 3 +2 5 7 3 6 +0 1 2 4 +0 1 3 5 +0 1 4 6 +0 6 4 2 5 \ No newline at end of file diff --git a/experiments/common.py b/experiments/common.py new file mode 100644 index 0000000..435bcc1 --- /dev/null +++ b/experiments/common.py @@ -0,0 +1,67 @@ +import math + +import numpy as np +import ot +import pymp +from scipy.stats import wasserstein_distance +from sklearn.metrics import pairwise_distances + +# from multiprocessing import Pool +# def pmap(f, x, num_threads): +# with Pool(processes=num_threads) as p: +# p.map(f, x) + + +def eemdkernel(x, y, gamma): + return math.exp(-gamma * ot.lp.emd2_1d(x, y)) + + +def pmap(f, x, num_threads): + y = pymp.shared.list([None] * len(x)) + with pymp.Parallel(num_threads) as p: + for i in p.range(len(x)): + y[i] = f(x[i]) + return list(y) + + +def wasserstein_kernel(x, y, gamma): + return math.exp(-gamma * wasserstein_distance(x, y)) + + +def wasserstein_cluster_coeffcient(C, labels, n_jobs=1): + L = np.unique(labels) + intra, inter = np.zeros(len(L)), np.zeros((len(L), len(L))) + for i in range(len(L)): + Ki = pairwise_distances( + C[labels == L[i]], + metric=lambda a, b: wasserstein_distance(a, b), + n_jobs=n_jobs, + ) + intra[i] = Ki.sum() * 2 / max(len(Ki) * (len(Ki) - 1), 1) + for j in range(i + 1, len(L)): + Kij = pairwise_distances( + C[labels == L[i]], + Y=C[labels == L[j]], + metric=lambda a, b: wasserstein_distance(a, b), + n_jobs=n_jobs, + ) + inter[i][j] = Kij.sum() / np.prod(Kij.shape) + wcc = intra.sum() / (1 + inter.sum()) + return wcc, intra, inter + + +def _binning(C, bins): + def H(c): + h = np.histogram(c, bins)[0] + return h / sum(h) + + return list(pmap(H, C, 64)) + + +def curvature_histogram(C): + return _binning(C, [x / 100 for x in range(-200, 104, 5)]) + + +def feature_histogram(C): + x = [x for c in C for x in c] + return _binning(C, np.linspace(np.min(x), np.max(x), 61)) diff --git a/experiments/features.py b/experiments/features.py new file mode 100644 index 0000000..83d27ce --- /dev/null +++ b/experiments/features.py @@ -0,0 +1,106 @@ +import argparse +import gzip +import json +from collections import OrderedDict + +from scipy.sparse import csr_matrix + + +def compute_edge_cardinalities(M_csc): + edge_cardinalities = [int(M_csc[:, j].nnz) for j in range(M_csc.shape[-1])] + return edge_cardinalities + + +def compute_edge_neighborhood_sizes(M_csr, M_csc): + edge_neighborhood_sizes = [ + len(set(M_csr[M_csc[:, j].nonzero()[0]].nonzero()[-1])) + for j in range(M_csc.shape[-1]) + ] + return edge_neighborhood_sizes + + +def compute_node_degrees(M_csr): + node_degrees = [int(M_csr[i, :].nnz) for i in range(M_csr.shape[0])] + return node_degrees + + +def compute_node_neighborhood_sizes(M_csr, M_csc): + node_neighborhood_sizes = [ + len(set(M_csc[:, M_csr[i, :].nonzero()[-1]].nonzero()[0])) + for i in range(M_csr.shape[0]) + ] + return node_neighborhood_sizes + + +def compute_ihg_features(hypergraph_edges, input_file): + row_ind = [item for sublist in hypergraph_edges for item in sublist] + col_ind = [ + item + for sublist in [ + [idx] * len(sublist) for idx, sublist in enumerate(hypergraph_edges) + ] + for item in sublist + ] + data = [1] * len(col_ind) + M_csr = csr_matrix((data, (row_ind, col_ind))) + M_csc = M_csr.tocsc() + result = { + "edge_cardinality": compute_edge_cardinalities(M_csc), + "edge_neighborhood_size": compute_edge_neighborhood_sizes(M_csr, M_csc), + "node_degree": compute_node_degrees(M_csr), + "node_neighborhood_size": compute_node_neighborhood_sizes(M_csr, M_csc), + "input": input_file, + } + return result + + +def compute_chg_features(hypergraph_collection_edges, input_file): + result = [ + compute_ihg_features(hypergraph_edges, input_file) + for hypergraph_edges in hypergraph_collection_edges + ] + return result + + +def edge_to_nodes_zero_indexed(edge): + return [(int(node) - 1) for node in edge.strip().split("\t")] + + +def edge_strings_to_graph_collection(edge_strings): + graphs = OrderedDict() + for e in edge_strings: + edge = edge_to_nodes_zero_indexed(e) + if edge[0] not in graphs: + graphs[edge[0]] = [edge[1:]] + else: + graphs[edge[0]].append(edge[1:]) + edges = list(graphs.values()) + return edges + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument( + "--input", "-i", type=str, required=True, help="Input {ihg,chg} file" + ) + parser.add_argument( + "--output", "-o", type=str, required=True, help="Output destination" + ) + args = parser.parse_args() + i = args.input + o = args.output + + with (gzip.open(i, "rt") if ".gz" in i else open(i, "r")) as f: + edge_strings = f.read().strip().split("\n") + + if "ihg.tsv" in i: + edges = [edge_to_nodes_zero_indexed(edge) for edge in edge_strings] + result = compute_ihg_features(edges, i) + else: + edges = edge_strings_to_graph_collection(edge_strings) + result = compute_chg_features(edges, i) + + print( + json.dumps(result), + file=(gzip.open(o, "wt") if ".gz" in o else open(o, "wt")), + ) diff --git a/experiments/graph-clustering.py b/experiments/graph-clustering.py new file mode 100644 index 0000000..af2940a --- /dev/null +++ b/experiments/graph-clustering.py @@ -0,0 +1,159 @@ +import argparse +import gzip +import json +from glob import glob + +import numpy as np +from common import * +from sklearn.cluster import SpectralClustering +from sklearn.metrics.pairwise import rbf_kernel + + +def clustering(histogram, values, k, feature_name, gammas=[1]): + results = [] + for gamma in gammas: + spec = SpectralClustering( + n_clusters=k, + affinity="precomputed", + n_jobs=-1, + eigen_solver="lobpcg", + eigen_tol=1e-10, + assign_labels="cluster_qr", + # assign_labels="kmeans", + ) + + print("Spectral Clustering EWK") + G = pairwise_distances( + values, metric=lambda a, b: wasserstein_kernel(a, b, gamma), n_jobs=-1 + ) + y = spec.fit_predict(G) + wcc, intra, inter = wasserstein_cluster_coeffcient( + np.array(values), np.array(y), n_jobs=128 + ) + # print("EWK", feature_name, wcc, y) + results.append( + { + "method": "spectral_clustering", + "kernel": "wasserstein_kernel", + "kernel_hyperparameter": gamma, + "ncomponents": k, + "feature_name": feature_name, + "labels": y.tolist(), + "wasserstein_clustering_coefficient": { + "total": wcc, + "internal": intra.tolist(), + "external": inter.tolist(), + }, + } + ) + + print("Spectral Clustering EWK Histogram") + G = pairwise_distances( + histogram, metric=lambda a, b: eemdkernel(a, b, gamma), n_jobs=-1 + ) + y = spec.fit_predict(G) + wcc, intra, inter = wasserstein_cluster_coeffcient( + np.array(values), np.array(y), n_jobs=128 + ) + # print("EWK", feature_name, wcc, y) + results.append( + { + "method": "spectral_clustering", + "kernel": "emd_kernel", + "kernel_hyperparameter": gamma, + "ncomponents": k, + "feature_name": feature_name + "_hist", + "labels": y.tolist(), + "wasserstein_clustering_coefficient": { + "total": wcc, + "internal": intra.tolist(), + "external": inter.tolist(), + }, + } + ) + + print("Spectral Clustering RBF Histogram") + G = rbf_kernel(histogram, gamma=gamma) + y = spec.fit_predict(G) + wcc, intra, inter = wasserstein_cluster_coeffcient( + np.array(values), np.array(y), n_jobs=128 + ) + # print("RBF", feature_name + "_hist", wcc, y) + results.append( + { + "method": "spectral_clustering", + "kernel": "rbf_kernel", + "kernel_hyperparameter": gamma, + "ncomponents": k, + "feature_name": feature_name + "_hist", + "labels": y.tolist(), + "wasserstein_clustering_coefficient": { + "total": wcc, + "internal": intra.tolist(), + "external": inter.tolist(), + }, + } + ) + + return results + + +def run_curvatures(json_documents, output, k): + C = [ + np.array(j["directional_curvature"][2], dtype=np.float64) + for j in json_documents + ] + result = clustering(curvature_histogram(C), C, k, "directional_curvature") + for f in ["edge_curvature", "node_curvature_edges", "node_curvature_neighborhood"]: + C = [np.array(j[f], dtype=np.float64) for j in json_documents] + result += clustering(curvature_histogram(C), C, k, f) + print( + json.dumps(result), + file=(gzip.open(output, "wt") if ".gz" in output else open(output, "wt")), + ) + + +def run_features(json_documents, output, k): + result = [] + for f in [ + "edge_cardinality", + "edge_neighborhood_size", + "node_degree", + "node_neighborhood_size", + ]: + C = [np.array(j[f], dtype=np.float64) for j in json_documents] + result += clustering(feature_histogram(C), C, k, f) + print( + json.dumps(result), + file=(gzip.open(output, "wt") if ".gz" in output else open(output, "wt")), + ) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument( + "--input", "-i", type=str, required=True, help="Input curvature or feature file" + ) + parser.add_argument( + "--output", "-o", type=str, required=True, help="Output destination" + ) + parser.add_argument("--ncomponents", "-k", required=True, type=int) + args = parser.parse_args() + + if "*" in args.input: + jo = [ + json.load(gzip.open(i, "r") if ".gz" in i else open(i, "r")) + for i in glob(args.input) + ] + else: + jo = json.load( + gzip.open(args.input, "r") if ".gz" in args.input else open(args.input, "r") + ) + + if len(jo) == 0: + print("Warn: empty file list") + else: + if "edge_cardinality" in jo[0].keys(): + run_features(jo, args.output, args.ncomponents) + else: + run_curvatures(jo, args.output, args.ncomponents) diff --git a/experiments/hypergraphmodels.py b/experiments/hypergraphmodels.py new file mode 100644 index 0000000..5100944 --- /dev/null +++ b/experiments/hypergraphmodels.py @@ -0,0 +1,326 @@ +import gzip +import json +import math +import os +from itertools import chain + +import numpy as np +from scipy.sparse import csr_matrix + + +class HypergraphConfigurationModel: + def __init__(self, node_degrees, edge_cardinalities, seed, identifier=None): + assert sum(node_degrees) == sum( + edge_cardinalities + ), f"Sum of node degrees does not equal sum of edge cardinalities! {sum(node_degrees)} != {sum(edge_cardinalities)}" + self.seed = seed + self.random_state = np.random.RandomState(seed) + self.input_node_degrees = node_degrees + self.input_edge_cardinalities = edge_cardinalities + self.M_csr = self._generate_edges() + self.M_csc = self.M_csr.tocsc() + self.n = len(node_degrees) + self.m = len(edge_cardinalities) + self.node_degree = [int(self.M_csr[i, :].nnz) for i in range(self.n)] + self.edge_cardinality = [int(self.M_csc[:, j].nnz) for j in range(self.m)] + self.node_neighborhood_size = [ + len(set(self.M_csc[:, self.M_csr[i, :].nonzero()[-1]].nonzero()[0])) + for i in range(self.M_csr.shape[0]) + ] + self.edge_neighborhood_size = [ + len(set(self.M_csr[self.M_csc[:, j].nonzero()[0]].nonzero()[-1])) + for j in range(self.M_csc.shape[-1]) + ] + self.c = sum(self.node_degree) + self.identifier = identifier + + def _generate_edges(self): + row_ind = list( + chain.from_iterable([n] * d for n, d in enumerate(self.input_node_degrees)) + ) + col_ind = list( + chain.from_iterable( + [n] * d for n, d in enumerate(self.input_edge_cardinalities) + ) + ) + data = [1] * len(col_ind) + self.random_state.shuffle(row_ind) + self.random_state.shuffle(col_ind) + # csr_matrix ignores duplicate entries + return csr_matrix((data, (row_ind, col_ind))) + + def _get_filename(self): + return f"HCM_n-{self.n}_m-{self.m}_c-{self.c}_seed-{self.seed}" + + def _generate_ihg_tsv_string(self): + c2r = [ + list(map(lambda x: int(x + 1), self.M_csc[:, c].nonzero()[0])) + for c in range(self.M_csc.shape[-1]) + ] + if self.identifier is None: + return "\n".join(["\t".join(map(str, e)) for e in c2r]) + else: + return "\n".join( + [f"{self.identifier}\t" + "\t".join(map(str, e)) for e in c2r] + ) + + def write_ihg_tsv_gz(self, savepath): + c2r_string = self._generate_ihg_tsv_string() + os.makedirs(savepath, exist_ok=True) + with gzip.open( + f"{savepath}/{self._get_filename()}.ihg.tsv.gz", "wt", encoding="UTF-8" + ) as zipfile: + zipfile.write(c2r_string) + + def _generate_ihg_features(self): + features = { + "node_degree": self.node_degree, + "edge_cardinality": self.edge_cardinality, + "node_neighborhood_size": self.node_neighborhood_size, + "edge_neighborhood_size": self.edge_neighborhood_size, + "config": dict( + seed=self.seed, + original_node_degrees=self.input_node_degrees, + original_edge_cardinalities=self.input_edge_cardinalities, + ), + "filename": self._get_filename(), + } + if self.identifier is not None: + features["identifier"] = self.identifier + return features + + def write_ihg_features_gz(self, savepath): + with gzip.open( + f"{savepath}/{self._get_filename()}.ihg.json.gz", "wt", encoding="UTF-8" + ) as zipfile: + json.dump( + self._generate_ihg_features(), + zipfile, + ) + + def __repr__(self): + return f"" + + +class HnmpModel: + def __init__(self, n, m, p, seed, identifier=None): + self.seed = seed + self.random_state = np.random.RandomState(seed) + self.n = n + self.m = m + self.p = p + self.c = int(round(p * n * m)) + self.M_csr = self._generate_edges() + self.M_csc = self.M_csr.tocsc() + self.node_degree = [ + int(self.M_csr[i, :].nnz) for i in range(self.M_csr.shape[0]) + ] + self.edge_cardinality = [ + int(self.M_csc[:, j].nnz) for j in range(self.M_csr.shape[-1]) + ] + self.node_neighborhood_size = [ + len(set(self.M_csc[:, self.M_csr[i, :].nonzero()[-1]].nonzero()[0])) + for i in range(self.M_csr.shape[0]) + ] + self.edge_neighborhood_size = [ + len(set(self.M_csr[self.M_csc[:, j].nonzero()[0]].nonzero()[-1])) + for j in range(self.M_csc.shape[-1]) + ] + self.identifier = identifier + + def _generate_edges(self): + row_ind = list( + map( + int, self.random_state.choice(list(range(self.n)), self.c, replace=True) + ) + ) + col_ind = list( + map( + int, self.random_state.choice(list(range(self.m)), self.c, replace=True) + ) + ) + data = [1] * len(col_ind) + # csr_matrix ignores duplicate entries + return csr_matrix((data, (row_ind, col_ind))) + + def _generate_ihg_tsv_string(self): + c2r = [ + list(map(lambda x: int(x + 1), self.M_csc[:, c].nonzero()[0])) + for c in range(self.M_csc.shape[-1]) + ] + if self.identifier is None: + return "\n".join(["\t".join(map(str, e)) for e in c2r]) + else: + return "\n".join( + [f"{self.identifier}\t" + "\t".join(map(str, e)) for e in c2r] + ) + + def write_ihg_tsv_gz(self, savepath): + c2r_string = self._generate_ihg_tsv_string() + os.makedirs(savepath, exist_ok=True) + with gzip.open( + f"{savepath}/{self._get_filename()}.ihg.tsv.gz", "wt", encoding="UTF-8" + ) as zipfile: + zipfile.write(c2r_string) + + def _generate_ihg_features(self): + features = { + "node_degree": self.node_degree, + "edge_cardinality": self.edge_cardinality, + "node_neighborhood_size": self.node_neighborhood_size, + "edge_neighborhood_size": self.edge_neighborhood_size, + "config": dict( + seed=self.seed, + n=self.n, + m=self.m, + p=self.p, + ), + "filename": self._get_filename(), + } + if self.identifier is not None: + features["identifier"] = self.identifier + return features + + def write_ihg_features_gz(self, savepath): + with gzip.open( + f"{savepath}/{self._get_filename()}.ihg.json.gz", "wt", encoding="UTF-8" + ) as zipfile: + json.dump( + self._generate_ihg_features(), + zipfile, + ) + + def _get_filename(self): + return f"Hnmp_n-{self.n}_m-{self.m}_c-{self.c}_seed-{self.seed}" + + def __repr__(self): + return f"" + + +class HSBModel: + def __init__( + self, + node_community_sizes, + edge_community_sizes, + affinity_matrix, + seed, + with_hash=False, + identifier=None, + ): + self.seed = seed + self.random_state = np.random.RandomState(seed) + self.node_community_sizes = node_community_sizes + self.edge_community_sizes = edge_community_sizes + self.affinity_matrix = affinity_matrix + self.n_node_communities = len(self.node_community_sizes) + self.n_edge_communities = len(self.edge_community_sizes) + self.node_communities = list( + chain.from_iterable( + [n] * d for n, d in enumerate(self.node_community_sizes) + ), + ) + self.edge_communities = list( + chain.from_iterable( + [n] * d for n, d in enumerate(self.edge_community_sizes) + ), + ) + self.M_csr = self._generate_edges() + self.M_csc = self.M_csr.tocsc() + self.n = int(self.M_csr.shape[0]) + self.m = int(self.M_csr.shape[-1]) + self.c = int(self.M_csr.nnz) + self.with_hash = with_hash + self.node_degree = [int(self.M_csr[i, :].nnz) for i in range(self.n)] + self.edge_cardinality = [int(self.M_csc[:, j].nnz) for j in range(self.m)] + self.node_neighborhood_size = [ + len(set(self.M_csc[:, self.M_csr[i, :].nonzero()[-1]].nonzero()[0])) + for i in range(self.M_csr.shape[0]) + ] + self.edge_neighborhood_size = [ + len(set(self.M_csr[self.M_csc[:, j].nonzero()[0]].nonzero()[-1])) + for j in range(self.M_csc.shape[-1]) + ] + self.identifier = identifier + + def _generate_edges(self): + row_ind = list() + col_ind = list() + for node_idx, v in enumerate(self.node_communities): + affinities = self.affinity_matrix[v, :] + for comm_idx, (community_size, affinity) in enumerate( + zip(self.edge_community_sizes, affinities) + ): + n_edges_to_sample = int( + self.random_state.choice([math.ceil, math.floor])( + affinity * community_size + ) + ) + if n_edges_to_sample > 0: + edges_to_choose_from = [ + idx + for idx, e in enumerate(self.edge_communities) + if e == comm_idx + ] + edges_sampled = self.random_state.choice( + edges_to_choose_from, size=n_edges_to_sample, replace=False + ) + row_ind.extend([node_idx] * len(edges_sampled)) + col_ind.extend(edges_sampled) + data = [1] * len(col_ind) + # csr_matrix ignores duplicate entries + return csr_matrix((data, (row_ind, col_ind))) + + def _generate_ihg_tsv_string(self): + c2r = [ + list(map(lambda x: int(x + 1), self.M_csc[:, c].nonzero()[0])) + for c in range(self.M_csc.shape[-1]) + ] + if self.identifier is None: + return "\n".join(["\t".join(map(str, e)) for e in c2r]) + else: + return "\n".join( + [f"{self.identifier}\t" + "\t".join(map(str, e)) for e in c2r] + ) + + def write_ihg_tsv_gz(self, savepath): + c2r_string = self._generate_ihg_tsv_string() + os.makedirs(savepath, exist_ok=True) + with gzip.open( + f"{savepath}/{self._get_filename()}.ihg.tsv.gz", "wt", encoding="UTF-8" + ) as zipfile: + zipfile.write(c2r_string) + + def _generate_ihg_features(self): + features = { + "node_degree": self.node_degree, + "edge_cardinality": self.edge_cardinality, + "node_neighborhood_size": self.node_neighborhood_size, + "edge_neighborhood_size": self.edge_neighborhood_size, + "node_communities": list(map(lambda x: x + 1, self.node_communities)), + "edge_communities": list(map(lambda x: x + 1, self.edge_communities)), + "config": dict( + seed=self.seed, + node_community_sizes=self.node_community_sizes, + edge_community_sizes=self.edge_community_sizes, + affinity_matrix=self.affinity_matrix.tolist(), + ), + "filename": self._get_filename(), + } + if self.identifier is not None: + features["identifier"] = self.identifier + return features + + def write_ihg_features_gz(self, savepath): + with gzip.open( + f"{savepath}/{self._get_filename()}.ihg.json.gz", "wt", encoding="UTF-8" + ) as zipfile: + json.dump( + self._generate_ihg_features(), + zipfile, + ) + + def _get_filename(self): + return f"HSBM_n-{self.n}_m-{self.m}_c-{self.c}_nnc-{self.n_node_communities}_nmc-{self.n_edge_communities}_seed-{self.seed}{'' if not self.with_hash else '_h-' + str(hash(str(self.seed) + str(self.affinity_matrix.tolist())))}" + + def __repr__(self): + return f"" diff --git a/experiments/kpca.py b/experiments/kpca.py new file mode 100644 index 0000000..fa5b863 --- /dev/null +++ b/experiments/kpca.py @@ -0,0 +1,158 @@ +import argparse +import gzip +import json +from glob import glob + +import numpy as np +from common import * +from sklearn.decomposition import KernelPCA +from sklearn.metrics.pairwise import rbf_kernel +from sklearn.preprocessing import scale + + +def kpca(histogram, values, k, feature_name, gammas=[1]): + results = [] + for gamma in gammas: + print("kPCA EWK") + pca = KernelPCA(n_components=k, kernel="precomputed", tol=1e-5, max_iter=2000) + G = pairwise_distances( + values, metric=lambda a, b: wasserstein_kernel(a, b, gamma), n_jobs=-1 + ) + embedding = pca.fit_transform(G) + results.append( + { + "method": "KernelPCA", + "kernel": "wasserstein_kernel", + "kernel_hyperparameter": gamma, + "ncomponents": k, + "feature_name": feature_name, + "embedding": [e.tolist() for e in embedding], + } + ) + embedding = pca.fit_transform(scale(G)) + results.append( + { + "method": "KernelPCA", + "kernel": "wasserstein_kernel_scaled", + "kernel_hyperparameter": gamma, + "ncomponents": k, + "feature_name": feature_name, + "embedding": [e.tolist() for e in embedding], + } + ) + + print("kPCA EWK Histogram") + pca = KernelPCA(n_components=k, kernel="precomputed", tol=1e-5, max_iter=2000) + G = pairwise_distances( + histogram, metric=lambda a, b: eemdkernel(a, b, gamma), n_jobs=-1 + ) + embedding = pca.fit_transform(G) + results.append( + { + "method": "KernelPCA", + "kernel": "emd_kernel", + "kernel_hyperparameter": gamma, + "ncomponents": k, + "feature_name": feature_name + "_hist", + "embedding": [e.tolist() for e in embedding], + } + ) + embedding = pca.fit_transform(scale(G)) + results.append( + { + "method": "KernelPCA", + "kernel": "emd_kernel", + "kernel_hyperparameter": gamma, + "ncomponents": k, + "feature_name": feature_name + "_hist", + "embedding": [e.tolist() for e in embedding], + } + ) + + print("kPCA RBF Histogram") + D = rbf_kernel(histogram, gamma=gamma) + embedding = pca.fit_transform(D) + results.append( + { + "method": "KernelPCA", + "kernel": "rbf_kernel_binning", + "kernel_hyperparameter": gamma, + "ncomponents": k, + "feature_name": feature_name + "_hist", + "embedding": [e.tolist() for e in embedding], + } + ) + embedding = pca.fit_transform(scale(D)) + results.append( + { + "method": "KernelPCA", + "kernel": "rbf_kernel_scaled", + "kernel_hyperparameter": gamma, + "ncomponents": k, + "feature_name": feature_name + "_hist", + "embedding": [e.tolist() for e in embedding], + } + ) + return results + + +def run_curvatures(json_documents, output, k): + C = [ + np.array(j["directional_curvature"][2], dtype=np.float64) + for j in json_documents + ] + result = kpca(curvature_histogram(C), C, k, "directional_curvature") + for f in ["edge_curvature", "node_curvature_edges", "node_curvature_neighborhood"]: + # C = [np.array(j[f], dtype=np.float64) for j in json_documents] + C = np.array([j[f] for j in json_documents], dtype=np.float64) + result += kpca(curvature_histogram(C), C, k, f) + print( + json.dumps(result), + file=(gzip.open(output, "wt") if ".gz" in output else open(output, "wt")), + ) + + +def run_features(json_documents, output, k): + result = [] + for f in [ + "edge_cardinality", + "edge_neighborhood_size", + "node_degree", + "node_neighborhood_size", + ]: + C = np.array([j[f] for j in json_documents], dtype=np.float64) + result += kpca(feature_histogram(C), C, k, f) + print( + json.dumps(result), + file=(gzip.open(output, "wt") if ".gz" in output else open(output, "wt")), + ) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument( + "--input", "-i", type=str, required=True, help="Input curvature or feature file" + ) + parser.add_argument( + "--output", "-o", type=str, required=True, help="Output destination" + ) + parser.add_argument("--ncomponents", "-k", required=True, type=int) + args = parser.parse_args() + + if "*" in args.input: + jo = [ + json.load(gzip.open(i, "r") if ".gz" in i else open(i, "r")) + for i in glob(args.input) + ] + else: + jo = json.load( + gzip.open(args.input, "r") if ".gz" in args.input else open(args.input, "r") + ) + + if len(jo) == 0: + print("Warn: empty file list") + else: + if "edge_cardinality" in jo[0].keys(): + run_features(jo, args.output, args.ncomponents) + else: + run_curvatures(jo, args.output, args.ncomponents) diff --git a/experiments/mmd.py b/experiments/mmd.py new file mode 100644 index 0000000..f02b890 --- /dev/null +++ b/experiments/mmd.py @@ -0,0 +1,150 @@ +import argparse +import gzip +import json +from glob import glob +from itertools import combinations + +import numpy as np +from common import * +from scipy.stats import wasserstein_distance +from sklearn.metrics import pairwise_distances +from tqdm import tqdm + + +def mmd(x, y, sigma): + n = len(x) + xy = np.concatenate((x, y)) + K = np.exp((-1 / (2 * sigma**2)) * np.power(pairwise_distances(xy, xy), 2)) + XX, YY, XY = K[:n, :n], K[n:, n:], K[:n, n:] + return XX.mean() + YY.mean() - 2 * XY.mean() + + +def bootstrapping(x, y, fn, iterations=100): + n = len(x) + xy = np.concatenate((x, y)) + b = [] + for _ in tqdm(range(iterations)): # tqdm + xy = xy[np.random.permutation(len(xy))] + b.append(fn(xy[:n], xy[n:])) + return np.array(b) + + +def mmd_emd(C, feature_type): + def emd_bootstrapping(t): + i, j = t + m = wasserstein_distance(C[i], C[j]) + t = bootstrapping(C[i], C[j], lambda a, b: wasserstein_distance(a, b)) + return i, j, m, t, (t >= m).mean() + + print("Bootstrapping EMD on curvatures") + R = pmap(emd_bootstrapping, [t for t in combinations(range(len(C)), 2)], 16) + I = [r[0] for r in R] + J = [r[1] for r in R] + M = [r[2] for r in R] + P = [r[4] for r in R] + return { + "feature_type": feature_type, + "gamma": 1, + "metric_type": "wasserstein_distance", + "values": {"I": I, "J": J, "K": M, "pvalues": P}, + } + + +def mmd_experiments(C, feature_type, bins, gammas=[1]): + def hist(c): + h = np.histogram(c, bins)[0] + return h / sum(h) + + result = [mmd_emd(C, feature_type)] + for gamma in gammas: + + def mmd_bootstrapping(t): + i, j = t + m = mmd(hist(C[i]).reshape(-1, 1), hist(C[j]).reshape(-1, 1), gamma) + t = bootstrapping( + C[i], + C[j], + lambda a, b: mmd(hist(a).reshape(-1, 1), hist(b).reshape(-1, 1), gamma), + ) + return i, j, m, t, (t >= m).mean() + + print("Bootstrapping MMD on histograms") + R = pmap(mmd_bootstrapping, [t for t in combinations(range(len(C)), 2)], 16) + I = [r[0] for r in R] + J = [r[1] for r in R] + M = [r[2] for r in R] + P = [r[4] for r in R] + result.append( + { + "feature_type": feature_type, + "gamma": gamma, + "metric_type": "mmd", + "values": {"I": I, "J": J, "K": M, "pvalues": P}, + } + ) + + return result + + +def run_curvatures(json_documents, output): + bins = [x / 100 for x in range(-200, 104, 5)] + C = [ + np.array(j["directional_curvature"][2], dtype=np.float64) + for j in json_documents + ] + result = mmd_experiments(C, "directional_curvature", bins) + for f in ["edge_curvature", "node_curvature_edges", "node_curvature_neighborhood"]: + C = [np.array(j[f], dtype=np.float64) for j in json_documents] + result += mmd_experiments(C, f, bins) + print( + json.dumps(result), + file=(gzip.open(output, "wt") if ".gz" in output else open(output, "wt")), + ) + + +def run_features(json_documents, output): + result = [] + for f in [ + "edge_cardinality", + "edge_neighborhood_size", + "node_degree", + "node_neighborhood_size", + ]: + C = [np.array(j[f], dtype=np.float64) for j in json_documents] + lb = np.min([x for c in C for x in c]) + ub = np.max([x for c in C for x in c]) + bins = np.linspace(lb, ub, 61) + result += mmd_experiments(C, f, bins) + print( + json.dumps(result), + file=(gzip.open(output, "wt") if ".gz" in output else open(output, "wt")), + ) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument( + "--input", "-i", type=str, required=True, help="Input curvature or feature file" + ) + parser.add_argument( + "--output", "-o", type=str, required=True, help="Output destination" + ) + args = parser.parse_args() + + if "*" in args.input: + jo = [ + json.load(gzip.open(i, "r") if ".gz" in i else open(i, "r")) + for i in glob(args.input) + ] + else: + jo = json.load( + gzip.open(args.input, "r") if ".gz" in args.input else open(args.input, "r") + ) + + if len(jo) == 0: + print("Warn: empty file list") + else: + if "edge_cardinality" in jo[0].keys(): + run_features(jo, args.output) + else: + run_curvatures(jo, args.output) diff --git a/experiments/node-clustering.py b/experiments/node-clustering.py new file mode 100644 index 0000000..a8ff23e --- /dev/null +++ b/experiments/node-clustering.py @@ -0,0 +1,319 @@ +# pip install git+https://github.com/alan-turing-institute/SigNet.git +# doi.org/10.5281/zenodo.1435036 +import argparse +import gzip +import json + +import numpy as np +from common import * +from scipy.sparse import csr_matrix +from signet.cluster import Cluster +from sklearn.cluster import SpectralClustering + + +def exp_kernel(W, gamma): + return np.exp(-gamma * W) + + +def sncluster(sn, k, gamma, feature_name, kernel_name): + result = [] + y = sn.spectral_cluster_adjacency_reg(k=k) + result.append( + { + "method": "spectral_cluster_adjacency_reg", + "kernel": kernel_name, + "feature": feature_name, + "ncomponents": k, + "gamma": gamma, + "labels": y.tolist(), + } + ) + y = sn.spectral_cluster_bnc(k=k) + result.append( + { + "method": "spectral_cluster_bnc", + "kernel": kernel_name, + "feature": feature_name, + "ncomponents": k, + "gamma": gamma, + "labels": y.tolist(), + } + ) + y = sn.spectral_cluster_laplacian(k=k) + result.append( + { + "method": "spectral_cluster_laplacian", + "kernel": kernel_name, + "feature": feature_name, + "ncomponents": k, + "gamma": gamma, + "labels": y.tolist(), + } + ) + # y = sn.geproblem_adjacency(k=k) + # result.append({"method": "geproblem_adjacency", "kernel": kernel_name, "feature": feature_name, "ncomponents": k, "gamma": gamma, "labels": y.tolist()}) + y = sn.SPONGE(k=k) + result.append( + { + "method": "SPONGE", + "kernel": kernel_name, + "feature": feature_name, + "ncomponents": k, + "gamma": gamma, + "labels": y.tolist(), + } + ) + y = sn.SPONGE_sym(k=k) + result.append( + { + "method": "SPONGE_sym", + "kernel": kernel_name, + "feature": feature_name, + "ncomponents": k, + "gamma": gamma, + "labels": y.tolist(), + } + ) + # y = sn.spectral_cluster_bethe_hessian(k=k) + # result.append({"method": "spectral_cluster_bethe_hessian", "kernel": kernel_name, "feature": feature_name, "ncomponents": k, "gamma": gamma, "labels": y.tolist()}) + y = sn.SDP_cluster(k=k, normalisation="none") + result.append( + { + "method": "SDP_cluster", + "kernel": kernel_name, + "feature": feature_name, + "ncomponents": k, + "gamma": gamma, + "labels": y.tolist(), + } + ) + return result + + +def run_node_clustering(C, k): + spec = SpectralClustering( + n_clusters=k, + affinity="precomputed", + n_jobs=-1, + eigen_solver="lobpcg", + eigen_tol=1e-2, + assign_labels="cluster_qr", + ) + result = [] + + W = 1 - C + for gamma in [0.5, 1.0, 2.0, 1 / W.std()]: + spec = SpectralClustering( + n_clusters=k, + affinity="precomputed", + n_jobs=-1, + eigen_solver="lobpcg", + eigen_tol=1e-2, + assign_labels="cluster_qr", + ) + y = spec.fit_predict(exp_kernel(W, gamma)) + result.append( + { + "method": "SpectralClustering", + "kernel": "wasserstein_kernel", + "feature": "directional_wasserstein_distance", + "ncomponents": k, + "gamma": gamma, + "labels": y.tolist(), + } + ) + y = spec.fit_predict(C) + result.append( + { + "method": "SpectralClustering", + "kernel": "precomputed", + "feature": "directional_curvature", + "ncomponents": k, + "labels": y.tolist(), + } + ) + # y = spec.fit_predict(-C) + # result.append( + # { + # "method": "SpectralClustering", + # "kernel": "precomputed_inverted", + # "feature": "directional_curvature", + # "ncomponents": k, + # "labels": y.tolist(), + # } + # ) + D = pairwise_distances(C) + for gamma in [1.0, 1 / D.std()]: + Kern = exp_kernel(D, gamma) + spec = SpectralClustering( + n_clusters=k, + affinity="precomputed", + n_jobs=-1, + eigen_solver="lobpcg", + eigen_tol=1e-2, + assign_labels="cluster_qr", + ) + y = spec.fit_predict(Kern) + result.append( + { + "method": "SpectralClustering", + "kernel": "exp_kernel", + "feature": "directional_curvature", + "ncomponents": k, + "gamma": gamma, + "labels": y.tolist(), + } + ) + y = spec.fit_predict((C != 0) * Kern) + result.append( + { + "method": "SpectralClustering", + "kernel": "exp_kernel_adj", + "feature": "directional_curvature", + "ncomponents": k, + "gamma": gamma, + "labels": y.tolist(), + } + ) + + y = spec.fit_predict(1.0 * (C != 0)) + result.append( + { + "method": "SpectralClustering", + "kernel": "unweighted_adj", + "feature": "directional_curvature", + "ncomponents": k, + "gamma": gamma, + "labels": y.tolist(), + } + ) + result += sncluster( + Cluster((csr_matrix((1.0 * (C > 0))), csr_matrix(1.0 * (C < 0)))), + k, + 1, + "directional_curvature", + "unweighted_signed_adj", + ) + result += sncluster( + Cluster( + ( + csr_matrix(np.where(C > 0, C, 0 * C)), + csr_matrix(np.where(C < 0, -C, 0 * C)), + ) + ), + k, + 1, + "directional_curvature", + "weighted_signed_adj" + # Cluster((C * (C > 0), -C * (C < 0))), k, 1, feature_name, "weighted_signed_adj" + ) + return result + + +def run_curvatures(json_document, output, k): + IJK = json_document["directional_curvature"] + K, I, J = ( + np.array(IJK[2], dtype=np.float64), + np.array(IJK[0], dtype=np.int64), + np.array(IJK[1], dtype=np.int64), + ) + n = max(I.max(), J.max()) + C = csr_matrix((K, (I - 1, J - 1)), shape=(n, n)).toarray() + C = C + C.T + np.fill_diagonal(C, 1) + # C = np.array(json_document["directional_curvature"][2], dtype=np.float64) + result = run_node_clustering(C, k) + for f in ["node_curvature_edges", "node_curvature_neighborhood"]: + C = np.array(json_document[f], dtype=np.float64).reshape(-1, 1) + D = pairwise_distances(C) + for gamma in [1.0, 1 / D.std()]: + Kern = exp_kernel(D, gamma) + spec = SpectralClustering( + n_clusters=k, + affinity="precomputed", + n_jobs=-1, + eigen_solver="lobpcg", + eigen_tol=1e-2, + assign_labels="cluster_qr", + ) + y = spec.fit_predict(Kern) + result.append( + { + "method": "SpectralClustering", + "kernel": "rbfkernel", + "feature": f, + "ncomponents": k, + "gamma": gamma, + "labels": y.tolist(), + } + ) + y = spec.fit_predict((C != 0) * Kern) + result.append( + { + "method": "SpectralClustering", + "kernel": "rbfkernel", + "feature": f"adj-{f}", + "ncomponents": k, + "gamma": gamma, + "labels": y.tolist(), + } + ) + print( + json.dumps(result), + file=(gzip.open(output, "wt") if ".gz" in output else open(output, "wt")), + ) + + +def run_features(json_document, output, k): + result = [] + for feature in ["node_degree", "node_neighborhood_size"]: + d = np.array(json_document[feature]).reshape(-1, 1) + D = pairwise_distances(d) + for gamma in [0.5, 1.0, 2.0, 1 / D.std()]: + spec = SpectralClustering( + n_clusters=k, + affinity="precomputed", + n_jobs=-1, + eigen_solver="lobpcg", + eigen_tol=1e-2, + assign_labels="cluster_qr", + ) + y = spec.fit_predict(exp_kernel(D, gamma)) + result.append( + { + "method": "SpectralClustering", + "kernel": "rbfkernel", + "feature": feature, + "ncomponents": k, + "gamma": gamma, + "labels": y.tolist(), + } + ) + print( + json.dumps(result), + file=(gzip.open(output, "wt") if ".gz" in output else open(output, "wt")), + ) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument( + "--input", "-i", type=str, required=True, help="Input curvature or feature file" + ) + parser.add_argument( + "--output", "-o", type=str, required=True, help="Output destination" + ) + parser.add_argument("--ncomponents", "-k", required=True, type=int) + args = parser.parse_args() + + jo = json.load( + gzip.open(args.input, "r") if ".gz" in args.input else open(args.input, "r") + ) + + if len(jo) == 0: + print("Warn: empty file list") + else: + if "edge_cardinality" in jo.keys(): + run_features(jo, args.output, args.ncomponents) + else: + run_curvatures(jo, args.output, args.ncomponents) diff --git a/experiments/requirements.txt b/experiments/requirements.txt new file mode 100644 index 0000000..5de3b43 --- /dev/null +++ b/experiments/requirements.txt @@ -0,0 +1,14 @@ +# requirements from orchid experiments +numpy +scipy +sklearn +pymp-pypi +POT +signet @ git+https://github.com/alan-turing-institute/SigNet@master +# doi.org/10.5281/zenodo.1435036 +# requirements from other parts of the code +jupyterlab +matplotlib +pandas +seaborn +black[jupyter] \ No newline at end of file diff --git a/experiments/requirements_frozen.txt b/experiments/requirements_frozen.txt new file mode 100644 index 0000000..0ad1209 --- /dev/null +++ b/experiments/requirements_frozen.txt @@ -0,0 +1,126 @@ +# requirements from orchid experiments +numpy==1.24.3 +scipy==1.10.1 +sklearn==0.0.post5 +pymp-pypi==0.5.0 +POT==0.9.0 +SigNet @ git+https://github.com/alan-turing-institute/SigNet@32e3bf03dea9688f02f6c33728e5c1a7a8dbe5ce +# doi.org/10.5281/zenodo.1435036 +# requirements from other parts of the code +jupyterlab==4.0.1 +matplotlib==3.7.1 +pandas==2.0.2 +seaborn==0.12.2 +black==23.3.0 +## The following requirements were added by pip freeze: +anyio==3.7.0 +appnope==0.1.3 +argon2-cffi==21.3.0 +argon2-cffi-bindings==21.2.0 +arrow==1.2.3 +asttokens==2.2.1 +async-lru==2.0.2 +attrs==23.1.0 +Babel==2.12.1 +backcall==0.2.0 +beautifulsoup4==4.12.2 +bleach==6.0.0 +certifi==2023.5.7 +cffi==1.15.1 +charset-normalizer==3.1.0 +click==8.1.3 +comm==0.1.3 +contourpy==1.0.7 +cvxpy==1.3.1 +cycler==0.11.0 +debugpy==1.6.7 +decorator==5.1.1 +defusedxml==0.7.1 +ecos==2.0.12 +exceptiongroup==1.1.1 +executing==1.2.0 +fastjsonschema==2.17.1 +fonttools==4.39.4 +fqdn==1.5.1 +idna==3.4 +importlib-metadata==6.6.0 +importlib-resources==5.12.0 +ipykernel==6.23.1 +ipython==8.14.0 +isoduration==20.11.0 +jedi==0.18.2 +Jinja2==3.1.2 +joblib==1.2.0 +json5==0.9.14 +jsonpointer==2.3 +jsonschema==4.17.3 +jupyter-events==0.6.3 +jupyter-lsp==2.2.0 +jupyter_client==8.2.0 +jupyter_core==5.3.0 +jupyter_server==2.6.0 +jupyter_server_terminals==0.4.4 +jupyterlab-pygments==0.2.2 +jupyterlab_server==2.22.1 +kiwisolver==1.4.4 +MarkupSafe==2.1.3 +matplotlib-inline==0.1.6 +mistune==2.0.5 +mypy-extensions==1.0.0 +nbclient==0.8.0 +nbconvert==7.4.0 +nbformat==5.9.0 +nest-asyncio==1.5.6 +networkx==3.1 +notebook_shim==0.2.3 +osqp==0.6.3 +overrides==7.3.1 +packaging==23.1 +pandocfilters==1.5.0 +parso==0.8.3 +pathspec==0.11.1 +pexpect==4.8.0 +pickleshare==0.7.5 +Pillow==9.5.0 +platformdirs==3.5.1 +prometheus-client==0.17.0 +prompt-toolkit==3.0.38 +psutil==5.9.5 +ptyprocess==0.7.0 +pure-eval==0.2.2 +pycparser==2.21 +Pygments==2.15.1 +pyparsing==3.0.9 +pyrsistent==0.19.3 +python-dateutil==2.8.2 +python-json-logger==2.0.7 +pytz==2023.3 +PyYAML==6.0 +pyzmq==25.1.0 +qdldl==0.1.7 +requests==2.31.0 +rfc3339-validator==0.1.4 +rfc3986-validator==0.1.1 +scikit-learn==1.2.2 +scs==3.2.3 +Send2Trash==1.8.2 +six==1.16.0 +sniffio==1.3.0 +soupsieve==2.4.1 +stack-data==0.6.2 +terminado==0.17.1 +threadpoolctl==3.1.0 +tinycss2==1.2.1 +tokenize-rt==5.0.0 +tomli==2.0.1 +tornado==6.3.2 +traitlets==5.9.0 +typing_extensions==4.6.3 +tzdata==2023.3 +uri-template==1.2.0 +urllib3==2.0.3 +wcwidth==0.2.6 +webcolors==1.13 +webencodings==0.5.1 +websocket-client==1.5.2 +zipp==3.15.0 diff --git a/features/.gitkeep b/features/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/gc/.gitkeep b/gc/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/kpca/.gitkeep b/kpca/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/mmd/.gitkeep b/mmd/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/nc/.gitkeep b/nc/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/notebooks/preprocess_data.ipynb b/notebooks/preprocess_data.ipynb new file mode 100644 index 0000000..9a8269a --- /dev/null +++ b/notebooks/preprocess_data.ipynb @@ -0,0 +1,811 @@ +{ + "cells": [ + { + "cell_type": "code", + "execution_count": null, + "id": "cea24999-6a2a-4c62-95da-90f32c398e3e", + "metadata": {}, + "outputs": [], + "source": [ + "import gzip\n", + "import pandas as pd\n", + "from glob import glob" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "49c6e354-186c-42e1-a473-b12231523bfe", + "metadata": {}, + "outputs": [], + "source": [ + "def get_files(path, dataset):\n", + " return sorted(glob(f\"{path}/{dataset}/**.gz\"))" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "c8ba8772-5d3f-4b39-bb2c-6c5ba9e32717", + "metadata": {}, + "outputs": [], + "source": [ + "path = \"../data_raw\"" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "c8232460-3b5c-47d4-9a62-ed9c9fadce61", + "metadata": {}, + "outputs": [], + "source": [ + "datasets = [\n", + " \"aps-a\", \n", + " \"aps-av\", \n", + " \"aps-cv\", \n", + " \"dblp\", \n", + " \"dblp-v\", \n", + " \"mus\", \n", + " \"ndc-ai\", \n", + " \"ndc-pc\", \n", + " \"sha\", \n", + " \"stex\"\n", + "]" + ] + }, + { + "cell_type": "markdown", + "id": "1acda766-f90a-491a-aef9-2ab0aecf9d80", + "metadata": {}, + "source": [ + "### aps-a" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "b9ea7a22-3826-403e-bb89-99622324d7ba", + "metadata": { + "scrolled": true + }, + "outputs": [], + "source": [ + "dataset = \"aps-a\"\n", + "nodes = \"authors\"\n", + "dataset_type = \"ihg\"\n", + "files = get_files(path, dataset)\n", + "file = files[0]\n", + "with gzip.open(file) as f:\n", + " df = pd.read_csv(file)\n", + "df = df[[nodes]]" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "e90116a3-d496-4700-a31a-0e2e0c4adb5d", + "metadata": {}, + "outputs": [], + "source": [ + "df_filtered = df[~(df[nodes].fillna(\"\").map(len) < 3)].copy()\n", + "df_filtered[nodes] = df_filtered[nodes].map(eval)\n", + "n_cells_filled = len(df_filtered[nodes].explode())\n", + "n_edges = len(df_filtered)\n", + "\n", + "node_mapping = {x:idx for idx, x in enumerate(sorted(df_filtered[nodes].explode().unique()), start=1)}\n", + "n_nodes = len(node_mapping)\n", + "\n", + "print(\n", + " f\"n: {n_nodes}, m:{n_edges}\", \n", + " f\"c: {n_cells_filled}, c/nm: {n_cells_filled / (n_nodes * n_edges)}\"\n", + " )" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "435e9dfc-8982-4fbb-a672-a3e679d44e8b", + "metadata": {}, + "outputs": [], + "source": [ + "df_filtered[nodes] = df_filtered[nodes].map(lambda x:\"\\t\".join([str(node_mapping[y]) for y in x]))\n", + "df_filtered[nodes].to_csv(f\"../data/{dataset}.{dataset_type}.tsv.gz\", header=False, index=False)" + ] + }, + { + "cell_type": "markdown", + "id": "aa8e8d61-e6b9-4ba5-887d-83f86856977b", + "metadata": {}, + "source": [ + "### aps-av" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "ad16b39f-f94c-4c3a-8c83-63c7f8241499", + "metadata": {}, + "outputs": [], + "source": [ + "dataset = \"aps-av\"\n", + "dataset_type = \"chg\"\n", + "nodes = \"authors\"\n", + "files = get_files(path, dataset)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "18dbd2ae-cfc3-4384-95bc-f75c1099e95b", + "metadata": {}, + "outputs": [], + "source": [ + "dfs = list()\n", + "stats = list()\n", + "for idx,file in enumerate(files, start=1):\n", + " with gzip.open(file) as f:\n", + " df = pd.read_csv(file)\n", + " df = df[[nodes]]\n", + " df_filtered = df[~(df[nodes].fillna(\"\").map(len) < 3)].copy()\n", + " df_filtered[nodes] = df_filtered[nodes].map(eval)\n", + " n_cells_filled = len(df_filtered[nodes].explode())\n", + " n_edges = len(df_filtered)\n", + " node_mapping = {x:idx for idx, x in enumerate(sorted(df_filtered[nodes].explode().unique()), start=1)}\n", + " n_nodes = len(node_mapping)\n", + " df_filtered[nodes] = df_filtered[nodes].map(lambda x: f\"{idx}\\t\" + \"\\t\".join([str(node_mapping[y]) for y in x]))\n", + " dfs.append(df_filtered.copy())\n", + " stats.append((n_nodes, n_edges, n_cells_filled, n_cells_filled/(n_nodes * n_edges)))" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "5216301f-1eff-424d-9e26-dff79fd964b5", + "metadata": {}, + "outputs": [], + "source": [ + "print(f\"(n/m)_max: {[tup[0]/tup[1] for tup in [max(stats, key=lambda tup:tup[0]/tup[1])]][0]}\")\n", + "print(f\"(c/nm)_max: {[tup[-1] for tup in [max(stats, key=lambda tup:tup[-1])]][0]}\")" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "5cf3bb20-9e63-47db-8a5c-03b284d1e9ba", + "metadata": {}, + "outputs": [], + "source": [ + "pd.concat(dfs, ignore_index=True).to_csv(f\"../data/{dataset}.{dataset_type}.tsv.gz\", \n", + " header=False, index=False)" + ] + }, + { + "cell_type": "markdown", + "id": "7e314651-877f-4e75-b00d-3acbfc3da911", + "metadata": {}, + "source": [ + "### aps-cv" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "c9b4fa56-0d0a-400b-a79e-a3882b59c5b7", + "metadata": {}, + "outputs": [], + "source": [ + "dataset = \"aps-cv\"\n", + "dataset_type = \"chg\"\n", + "nodes = \"cited_doi\"\n", + "files = get_files(path, dataset)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "62bd8125-8f36-4838-bfbf-ce34bef7d178", + "metadata": {}, + "outputs": [], + "source": [ + "dfs = list()\n", + "stats = list()\n", + "for idx,file in enumerate(files, start=1):\n", + " with gzip.open(file) as f:\n", + " df = pd.read_csv(file)\n", + " df = df[[nodes]]\n", + " df_filtered = df[~(df[nodes].fillna(\"\").map(len) < 3)].copy()\n", + " df_filtered[nodes] = df_filtered[nodes].map(eval)\n", + " df_filtered = df_filtered[~(df_filtered[nodes].map(len) < 1)].copy()\n", + " n_cells_filled = len(df_filtered[nodes].explode())\n", + " n_edges = len(df_filtered)\n", + " node_mapping = {x:idx for idx, x in enumerate(sorted(df_filtered[nodes].explode().unique()), start=1)}\n", + " n_nodes = len(node_mapping)\n", + " df_filtered[nodes] = df_filtered[nodes].map(lambda x: f\"{idx}\\t\" + \"\\t\".join([str(node_mapping[y]) for y in x]))\n", + " dfs.append(df_filtered.copy())\n", + " stats.append((n_nodes, n_edges, n_cells_filled, n_cells_filled/(n_nodes * n_edges)))" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "0fc10250-c4c5-458f-bdd8-0eaddbecd24d", + "metadata": {}, + "outputs": [], + "source": [ + "print(f\"(n/m)_max: {[tup[0]/tup[1] for tup in [max(stats, key=lambda tup:tup[0]/tup[1])]][0]}\")\n", + "print(f\"(c/nm)_max: {[tup[-1] for tup in [max(stats, key=lambda tup:tup[-1])]][0]}\")" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "6faed488-a1ac-4d7d-ab97-08df2c1a9aaa", + "metadata": {}, + "outputs": [], + "source": [ + "pd.concat(dfs, ignore_index=True).to_csv(f\"../data/{dataset}.{dataset_type}.tsv.gz\", \n", + " header=False, index=False)" + ] + }, + { + "cell_type": "markdown", + "id": "a589aaa0-184d-45d5-8350-2865b3b477a7", + "metadata": {}, + "source": [ + "### dblp" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "8d1bc9c0-4c5d-48d3-8677-57256af0651b", + "metadata": {}, + "outputs": [], + "source": [ + "dataset = \"dblp\"\n", + "dataset_type = \"ihg\"\n", + "nodes = \"author\"\n", + "files = get_files(path, dataset)\n", + "file = files[0]\n", + "with gzip.open(file) as f:\n", + " df = pd.read_csv(file)\n", + "df = df[[nodes]]" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "7acfc145-9b13-445a-925c-48194ae5247f", + "metadata": {}, + "outputs": [], + "source": [ + "df_filtered = df[~(df[nodes].fillna(\"\").map(len) < 3)].copy()\n", + "df_filtered[nodes] = df_filtered[nodes].map(lambda x:x.split(\";\"))\n", + "df_filtered = df_filtered[~(df_filtered[nodes].map(len) < 1)].copy()\n", + "n_cells_filled = len(df_filtered[nodes].explode())\n", + "n_edges = len(df_filtered)\n", + "\n", + "node_mapping = {x:idx for idx, x in enumerate(sorted(df_filtered[nodes].explode().unique()), start=1)}\n", + "n_nodes = len(node_mapping)\n", + "\n", + "print(\n", + " f\"n: {n_nodes}, m:{n_edges}\", \n", + " f\"c: {n_cells_filled}, c/nm: {n_cells_filled / (n_nodes * n_edges)}\"\n", + " )" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "dda6980b-72d6-4121-b1bd-3149fb6e894f", + "metadata": {}, + "outputs": [], + "source": [ + "df_filtered[nodes] = df_filtered[nodes].map(lambda x:\"\\t\".join([str(node_mapping[y]) for y in x]))\n", + "df_filtered[nodes].to_csv(f\"../data/{dataset}.{dataset_type}.tsv.gz\", header=False, index=False)" + ] + }, + { + "cell_type": "markdown", + "id": "eb39d98d-0aa5-46d5-8695-21233c9cb476", + "metadata": {}, + "source": [ + "### dblp-v" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "dd718be9-2a5c-42fe-a236-1c84b6a38292", + "metadata": {}, + "outputs": [], + "source": [ + "dataset = \"dblp-v\"\n", + "dataset_type = \"chg\"\n", + "nodes = \"author\"\n", + "files = get_files(path, dataset)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "841f768f-cb6f-4bbf-9f71-84a3dfb7fa4d", + "metadata": {}, + "outputs": [], + "source": [ + "dfs = list()\n", + "stats = list()\n", + "for idx,file in enumerate(files, start=1):\n", + " with gzip.open(file) as f:\n", + " df = pd.read_csv(file)\n", + " df = df[[nodes]]\n", + " df_filtered = df[~(df[nodes].fillna(\"\").map(len) < 3)].copy()\n", + " df_filtered[nodes] = df_filtered[nodes].map(lambda x:x.split(\";\"))\n", + " df_filtered = df_filtered[~(df_filtered[nodes].map(len) < 1)].copy()\n", + " n_cells_filled = len(df_filtered[nodes].explode())\n", + " n_edges = len(df_filtered)\n", + " node_mapping = {x:idx for idx, x in enumerate(sorted(df_filtered[nodes].explode().unique()), start=1)}\n", + " n_nodes = len(node_mapping)\n", + " df_filtered[nodes] = df_filtered[nodes].map(lambda x: f\"{idx}\\t\" + \"\\t\".join([str(node_mapping[y]) for y in x]))\n", + " dfs.append(df_filtered.copy())\n", + " stats.append((n_nodes, n_edges, n_cells_filled, n_cells_filled/(n_nodes * n_edges)))" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "bd6332e1-2b2a-4fea-a53c-e6e6529afd39", + "metadata": {}, + "outputs": [], + "source": [ + "print(f\"(n/m)_max: {[tup[0]/tup[1] for tup in [max(stats, key=lambda tup:tup[0]/tup[1])]][0]}\")\n", + "print(f\"(c/nm)_max: {[tup[-1] for tup in [max(stats, key=lambda tup:tup[-1])]][0]}\")" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "c3b74b29-45fc-4b1c-bbaa-616ba093a83c", + "metadata": {}, + "outputs": [], + "source": [ + "pd.concat(dfs, ignore_index=True).to_csv(f\"../data/{dataset}.{dataset_type}.tsv.gz\", \n", + " header=False, index=False)" + ] + }, + { + "cell_type": "markdown", + "id": "093daf04-a5f8-4ecd-9f05-6942a02bc55f", + "metadata": {}, + "source": [ + "### mus" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "132d83e9-2ca0-47b8-83cb-37c76f222ace", + "metadata": {}, + "outputs": [], + "source": [ + "dataset = \"mus\"\n", + "dataset_type = \"chg\"\n", + "nodes = \"frequencies440\"\n", + "files = sorted(glob(f\"{path}/{dataset}/**.csv\"))" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "184586e6-e0f1-445b-bd6b-1aa52f03c859", + "metadata": {}, + "outputs": [], + "source": [ + "dfs = list()\n", + "stats = list()\n", + "for idx,file in enumerate(files, start=1):\n", + " with gzip.open(file) as f:\n", + " df = pd.read_csv(file)\n", + " df = df[[nodes]]\n", + " df_filtered = df[~(df[nodes].map(len) < 3)].copy()\n", + " df_filtered[nodes] = df_filtered[nodes].map(eval)\n", + " n_cells_filled = len(df_filtered[nodes].explode())\n", + " n_edges = len(df_filtered)\n", + " node_mapping = {x:idx for idx, x in enumerate(sorted(df_filtered[nodes].explode().unique()), start=1)}\n", + " n_nodes = len(node_mapping)\n", + " df_filtered[nodes] = df_filtered[nodes].map(lambda x: f\"{idx}\\t\" + \"\\t\".join([str(node_mapping[y]) for y in x]))\n", + " dfs.append(df_filtered.copy())\n", + " stats.append((n_nodes, n_edges, n_cells_filled, n_cells_filled/(n_nodes * n_edges)))" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "4647671f-afd1-4e03-8fdf-af3bdd9da5c9", + "metadata": {}, + "outputs": [], + "source": [ + "print(f\"(n/m)_max: {[tup[0]/tup[1] for tup in [max(stats, key=lambda tup:tup[0]/tup[1])]][0]}\")\n", + "print(f\"(c/nm)_max: {[tup[-1] for tup in [max(stats, key=lambda tup:tup[-1])]][0]}\")" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "8eac438b-72d3-4d74-8807-320802ac22bd", + "metadata": {}, + "outputs": [], + "source": [ + "pd.concat(dfs, ignore_index=True).to_csv(f\"../data/{dataset}.{dataset_type}.tsv.gz\", header=False, index=False)" + ] + }, + { + "cell_type": "markdown", + "id": "12888c24-8aa8-4c59-b3e6-1fd1748f514e", + "metadata": {}, + "source": [ + "### ndc-ai" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "4998e5da-8a01-43a4-bc22-260722b998d5", + "metadata": {}, + "outputs": [], + "source": [ + "dataset = \"ndc-ai\"\n", + "nodes = \"active_ingredients_names\"\n", + "dataset_type = \"ihg\"\n", + "files = get_files(path, dataset)\n", + "file = files[0]\n", + "with gzip.open(file) as f:\n", + " df = pd.read_csv(file)\n", + "df = df[[nodes]]" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "ab373592-c7a4-4b5d-8160-cd25289f2edd", + "metadata": {}, + "outputs": [], + "source": [ + "df_filtered = df[~(df[nodes].map(len) < 3)].copy()\n", + "df_filtered[nodes] = df_filtered[nodes].map(eval)\n", + "n_cells_filled = len(df_filtered[nodes].explode())\n", + "n_edges = len(df_filtered)\n", + "\n", + "node_mapping = {x:idx for idx, x in enumerate(sorted(df_filtered[nodes].explode().unique()), start=1)}\n", + "n_nodes = len(node_mapping)\n", + "\n", + "print(\n", + " f\"n: {n_nodes}, m:{n_edges}\", \n", + " f\"c: {n_cells_filled}, c/nm: {n_cells_filled / (n_nodes * n_edges)}\"\n", + " )" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "6bbd2689-6a5e-47bb-8453-6dfb169b8539", + "metadata": {}, + "outputs": [], + "source": [ + "df_filtered[nodes] = df_filtered[nodes].map(lambda x:\"\\t\".join([str(node_mapping[y]) for y in x]))\n", + "df_filtered[nodes].to_csv(f\"../data/{dataset}.{dataset_type}.tsv.gz\", header=False, index=False)" + ] + }, + { + "cell_type": "markdown", + "id": "7c1dac69-0000-4216-9197-10ce1820bda7", + "metadata": {}, + "source": [ + "### ndc-pc" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "76ac3932-846e-4f18-a405-65002e68834c", + "metadata": {}, + "outputs": [], + "source": [ + "dataset = \"ndc-pc\"\n", + "nodes = \"pharm_class\"\n", + "dataset_type = \"ihg\"\n", + "files = get_files(path, dataset)\n", + "file = files[0]\n", + "with gzip.open(file) as f:\n", + " df = pd.read_csv(file)\n", + "df = df[[nodes]]" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "4e05a60d-50c6-4c2a-8d43-7e3618c14af2", + "metadata": {}, + "outputs": [], + "source": [ + "df_filtered = df[~(df[nodes].fillna(\"\").map(len) < 3)].copy()\n", + "df_filtered[nodes] = df_filtered[nodes].map(eval)\n", + "n_cells_filled = len(df_filtered[nodes].explode())\n", + "n_edges = len(df_filtered)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "531a31d0-4efc-4d5d-bd94-296183e8f6e4", + "metadata": {}, + "outputs": [], + "source": [ + "node_mapping = {x:idx for idx, x in enumerate(sorted(df_filtered[nodes].explode().unique()), start=1)}\n", + "n_nodes = len(node_mapping)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "fbe5f0a8-7bdc-4182-841b-fbff03f32d12", + "metadata": {}, + "outputs": [], + "source": [ + "print(\n", + " f\"n: {n_nodes}, m:{n_edges}\", \n", + " f\"c: {n_cells_filled}, c/nm: {n_cells_filled / (n_nodes * n_edges)}\"\n", + " )" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "d181266f-500e-4bc4-bd9d-3c8ef81713f2", + "metadata": {}, + "outputs": [], + "source": [ + "df_filtered[nodes] = df_filtered[nodes].map(lambda x:\"\\t\".join([str(node_mapping[y]) for y in x]))\n", + "df_filtered[nodes].to_csv(f\"../data/{dataset}.{dataset_type}.tsv.gz\", header=False, index=False)" + ] + }, + { + "cell_type": "markdown", + "id": "9a478f84-a0ba-42e7-9137-f12c64a8ee6e", + "metadata": {}, + "source": [ + "### sha" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "700c38ae-db8f-4d99-9f1c-ad6a17f2b1a7", + "metadata": {}, + "outputs": [], + "source": [ + "dataset = \"sha\"\n", + "dataset_type = \"chg\"\n", + "nodes = \"onstage\"\n", + "files = sorted(glob(f\"{path}/{dataset}/**.csv\"))" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "ce2a5266-2517-40b8-8cdd-1541deb7c318", + "metadata": {}, + "outputs": [], + "source": [ + "dfs = list()\n", + "stats = list()\n", + "for idx,file in enumerate(files, start=1):\n", + " with gzip.open(file) as f:\n", + " df = pd.read_csv(file)\n", + " df = df[[nodes]]\n", + " df_filtered = df[~(df[nodes].map(len) < 3)].copy()\n", + " df_filtered[nodes] = df_filtered[nodes].map(lambda x:x.split())\n", + " df_filtered[nodes] = df_filtered[nodes].map(\n", + " lambda x: [elem for elem in x if not elem.split(\"_\")[0].isupper()]\n", + " )\n", + " df_filtered = df_filtered[~(df_filtered[nodes].map(len) < 1)].copy()\n", + " n_cells_filled = len(df_filtered[nodes].explode())\n", + " n_edges = len(df_filtered)\n", + " node_mapping = {x:idx for idx, x in enumerate(sorted(df_filtered[nodes].explode().unique()), start=1)}\n", + " n_nodes = len(node_mapping)\n", + " df_filtered[nodes] = df_filtered[nodes].map(lambda x: f\"{idx}\\t\" + \"\\t\".join([str(node_mapping[y]) for y in x]))\n", + " dfs.append(df_filtered.copy())\n", + " stats.append((n_nodes, n_edges, n_cells_filled, n_cells_filled/(n_nodes * n_edges)))" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "cead10b0-ec98-4e30-b3df-52cb4ad80b6e", + "metadata": {}, + "outputs": [], + "source": [ + "print(f\"(n/m)_max: {[tup[0]/tup[1] for tup in [max(stats, key=lambda tup:tup[0]/tup[1])]][0]}\")\n", + "print(f\"(c/nm)_max: {[tup[-1] for tup in [max(stats, key=lambda tup:tup[-1])]][0]}\")" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "0504302f-c657-42c6-921e-a8c2ded7c758", + "metadata": {}, + "outputs": [], + "source": [ + "pd.concat(dfs, ignore_index=True).to_csv(f\"../data/{dataset}.{dataset_type}.tsv.gz\", \n", + " header=False, index=False)" + ] + }, + { + "cell_type": "markdown", + "id": "f314b02d-db0d-44e5-a381-cf8e6f06b805", + "metadata": {}, + "source": [ + "### stex" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "9cbab1eb-a432-4533-aeba-52f16a446dcb", + "metadata": {}, + "outputs": [], + "source": [ + "dataset = \"stex\"\n", + "dataset_type = \"chg\"\n", + "nodes = \"tags\"\n", + "files = get_files(path, dataset)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "b41a1c5e-0dbf-4ff1-a1cb-46950bc02f5e", + "metadata": {}, + "outputs": [], + "source": [ + "dfs = list()\n", + "stats = list()\n", + "for idx,file in enumerate(files, start=1):\n", + " with gzip.open(file) as f:\n", + " df = pd.read_csv(file)\n", + " df_filtered = df[[nodes]].copy()\n", + " df_filtered[nodes] = df_filtered[nodes].map(eval)\n", + " n_cells_filled = len(df_filtered[nodes].explode())\n", + " n_edges = len(df_filtered)\n", + " node_mapping = {x:idx for idx, x in enumerate(sorted(df_filtered[nodes].explode().unique()), start=1)}\n", + " n_nodes = len(node_mapping)\n", + " df_filtered[nodes] = df_filtered[nodes].map(lambda x: f\"{idx}\\t\" + \"\\t\".join([str(node_mapping[y]) for y in x]))\n", + " dfs.append(df_filtered.copy())\n", + " stats.append((n_nodes, n_edges, n_cells_filled, n_cells_filled/(n_nodes * n_edges)))" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "e8339ec0-5209-41c4-b8bf-70a9bfa436a7", + "metadata": {}, + "outputs": [], + "source": [ + "print(f\"(n/m)_max: {[tup[0]/tup[1] for tup in [max(stats, key=lambda tup:tup[0]/tup[1])]][0]}\")\n", + "print(f\"(c/nm)_max: {[tup[-1] for tup in [max(stats, key=lambda tup:tup[-1])]][0]}\")" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "73a1fa9c-241f-41a7-b351-3475113a7f79", + "metadata": {}, + "outputs": [], + "source": [ + "pd.concat(dfs, ignore_index=True\n", + " ).to_csv(f\"../data/{dataset}.{dataset_type}.tsv.gz\", header=False, index=False)" + ] + }, + { + "cell_type": "markdown", + "id": "a1abab2b-8a11-4472-b56e-6a0bdfc4746b", + "metadata": {}, + "source": [ + "### syn" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "af0cfd97-acf4-4502-9e7d-80e7d57d97b5", + "metadata": {}, + "outputs": [], + "source": [ + "import json" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "4ca065f7-9cd9-4cad-8a46-1bb9662dc74b", + "metadata": {}, + "outputs": [], + "source": [ + "dataset_type = \"chg\"\n", + "syn_datasets = [\"syn_hcm\", \"syn_hnmp\", \"syn_hsbm\"]" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "0ca38461-d539-44d1-a7b7-8fe79437e800", + "metadata": {}, + "outputs": [], + "source": [ + "for dataset in syn_datasets:\n", + " files = get_files(path, dataset)\n", + " graph_strings = []\n", + " for idx,file in enumerate(files, start=1):\n", + " with gzip.open(file) as f:\n", + " data = json.load(f)\n", + " graph_strings.append(\"\\n\".join([f\"{idx}\\t\" + \"\\t\".join([str(x) for x in y]) for y in data[\"cr\"]]))\n", + " joined = \"\\n\".join(graph_strings)\n", + " \n", + " with gzip.open(f\"../data/{dataset}.{dataset_type}.tsv.gz\", \"wt\") as f:\n", + " f.write(joined)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "ea908d47-bebc-4874-835a-81c13eb7685c", + "metadata": {}, + "outputs": [], + "source": [ + "dataset_type = \"chg\"\n", + "\n", + "dataset = \"syn_hcm\"\n", + "files = get_files(path, \"syn_hcm\") + get_files(path, \"syn_hsbm\")\n", + "graph_strings = []\n", + "for idx,file in enumerate(files, start=1):\n", + " with gzip.open(file) as f:\n", + " data = json.load(f)\n", + " graph_strings.append(\"\\n\".join([f\"{idx}\\t\" + \"\\t\".join([str(x) for x in y]) for y in data[\"cr\"]]))\n", + "joined = \"\\n\".join(graph_strings)\n", + "dataset = \"syn_hcm-hsbm\"\n", + "with gzip.open(f\"../data/{dataset}.{dataset_type}.tsv.gz\", \"wt\") as f:\n", + " f.write(joined)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "1e031e06-31ed-42e6-b423-0b40c0c58f5e", + "metadata": {}, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3 (ipykernel)", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.9.6" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} diff --git a/orchid_thumbnail.png b/orchid_thumbnail.png new file mode 100644 index 0000000..65cb383 Binary files /dev/null and b/orchid_thumbnail.png differ diff --git a/reproduce.sh b/reproduce.sh new file mode 100755 index 0000000..bd10003 --- /dev/null +++ b/reproduce.sh @@ -0,0 +1,40 @@ +#!/usr/bin/env bash + +echo "Setting exit on error" +set -e + +ihgs=("dblp" "ndc-ai" "ndc-pc") +chgs=("mus" "dblp-v" "sha" "stex") +syn=("syn_hcm" "syn_hcm-hsbm" "syn_hnmp" "syn_hsbm") +dispersions=("UnweightedClique" "UnweightedStar" "WeightedClique") +alphas=(0.0 0.1 0.2 0.3 0.4 0.5) + +echo "Computing curvatures for individual hypergraphs..." +for dataset in "${ihgs[@]}"; do + for dispersion in "${dispersions[@]}"; do + for alpha in "${alphas[@]}"; do + #echo "results/$dataset.alpha-$alpha.dispersion-$dispersion.orc.json" + bin/orchid.jl --aggregation All --dispersion $dispersion --alpha $alpha -i data/$dataset.ihg.tsv.gz -o results/$dataset.alpha-$alpha.dispersion-$dispersion.orc.json.gz + done + done + done + +echo "Computing curvatures for real-world collections..." +for dataset in "${chgs[@]}"; do + for dispersion in "${dispersions[@]}"; do + for alpha in "${alphas[@]}"; do + #echo "results/$dataset.alpha-$alpha.dispersion-$dispersion.orc.json" + bin/orchid.jl --aggregation All --dispersion $dispersion --alpha $alpha -i data/$dataset.chg.tsv.gz -o results/$dataset.alpha-$alpha.dispersion-$dispersion.orc.json.gz + done + done + done + +echo "Computing curvatures for synthetic collections..." +for dataset in "${syn[@]}"; do + for dispersion in "${dispersions[@]}"; do + for alpha in "${alphas[@]}"; do + #echo "results/$dataset.alpha-$alpha.dispersion-$dispersion.orc.json" + bin/orchid.jl --aggregation All --dispersion $dispersion --alpha $alpha -i data/$dataset.chg.tsv.gz -o results/$dataset.alpha-$alpha.dispersion-$dispersion.orc.json.gz + done + done + done diff --git a/reproduce_toy.sh b/reproduce_toy.sh new file mode 100755 index 0000000..ef9f793 --- /dev/null +++ b/reproduce_toy.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash + +echo "Setting exit on error" +set -e + +dispersions=("UnweightedClique" "UnweightedStar" "WeightedClique") +alphas=(0.0 0.1 0.2 0.3 0.4 0.5) + +echo "Computing curvatures for toy hypergraphs..." +for dispersion in "${dispersions[@]}"; do + for alpha in "${alphas[@]}"; do + dataset="toy" + #echo "results/$dataset.alpha-$alpha.dispersion-$dispersion.orc.json" + bin/orchid.jl --aggregation All --dispersion $dispersion --alpha $alpha -i data/$dataset.ihg.tsv -o results/$dataset.alpha-$alpha.dispersion-$dispersion.orc.json + dataset="toys" + #echo "results/$dataset.alpha-$alpha.dispersion-$dispersion.orc.json" + bin/orchid.jl --aggregation All --dispersion $dispersion --alpha $alpha -i data/$dataset.chg.tsv -o results/$dataset.alpha-$alpha.dispersion-$dispersion.orc.json + done + done \ No newline at end of file diff --git a/results/toy.orc.json b/results/toy.orc.json new file mode 100644 index 0000000..0250495 --- /dev/null +++ b/results/toy.orc.json @@ -0,0 +1 @@ +[{"node_curvature_neighborhood":[0.6538635417819023,0.6317628100514412,0.49734097719192505,0.6534325331449509,0.5075953702131907,0.4238963822523753,0.4238963822523753],"directional_curvature":[[1,1,2,1,2,3,1,2,3,4,1,2,3,4,5,1,2,3,4,5,6],[2,3,3,4,4,4,5,5,5,5,6,6,6,6,6,7,7,7,7,7,7],[0.70588684,0.6035793,0.5227412,0.74663913,0.70542157,0.60232055,0.55934894,0.5930017,0.6866355,0.55934894,0.16665328,0.21210557,0.28438467,0.16665328,0.3236186,0.16665328,0.21210557,0.28438467,0.16665328,0.3236186,0.6636859]],"node_curvature_edges":[0.6284923553466797,0.5982777306011745,0.5362572182308544,0.6284923553466797,0.5392607847849528,0.4277213215827942,0.4277213215827942],"edge_curvature":[0.6284923553466797,0.6284923553466797,0.6284923553466797,0.6284923553466797,0.6284923553466797,0.5227411687374115,0.5227411687374115,0.4277213215827942,0.4277213215827942,0.4277213215827942,0.4277213215827942],"aggregation":"Orchid.AggregateMean","dispersion":"WeightedClique","input":"data/toy.ihg.tsv","alpha":0.0}] diff --git a/results/toys.orc.json b/results/toys.orc.json new file mode 100644 index 0000000..4873f87 --- /dev/null +++ b/results/toys.orc.json @@ -0,0 +1 @@ +[{"node_curvature_neighborhood":[0.6568305641412735,0.6141522526741028,0.4851046601931254,0.6563598960638046,0.5519833862781525,0.5297209322452545,0.5297209322452545],"directional_curvature":[[1,1,2,1,2,3,1,2,3,4,1,2,3,4,5,1,2,3,4,5,6],[2,3,3,4,4,4,5,5,5,5,6,6,6,6,6,7,7,7,7,7,7],[0.65270734,0.6276435,0.46268862,0.8721142,0.6508264,0.6276418,0.4748572,0.69038665,0.64007056,0.4748572,0.04998958,0.27477503,0.27629173,0.04998958,0.5158644,0.04998958,0.27477503,0.27629173,0.04998958,0.5158644,0.7970067]],"node_curvature_edges":[0.4626886248588562,0.4626886248588562,0.4005563259124756,0.4626886248588562,0.3694901764392853,0.27629172801971436,0.27629172801971436],"edge_curvature":[0.4626886248588562,0.4626886248588562,0.27629172801971436],"aggregation":"Orchid.AggregateMax","dispersion":"UnweightedStar","input":"data/toys.chg.tsv","alpha":0.1},{"node_curvature_neighborhood":[0.6557607263326645,0.7373448451980948,0.38752469420433044,0.6319586858153343,0.5747797340154648,0.7375936051830649],"directional_curvature":[[1,1,2,1,2,3,1,2,3,4,1,2,3,4,5],[2,3,3,4,4,4,5,5,5,5,6,6,6,6,6],[0.7768861,0.3500648,0.27498442,0.5997308,0.6765431,0.2999757,0.77523583,0.5481185,0.42498457,0.575732,0.7768861,0.9478317,0.27498448,0.6758288,0.5498278]],"node_curvature_edges":[0.5165087978045145,0.5739246308803558,0.35006481409072876,0.582526683807373,0.4490916430950165,0.5739246308803558],"edge_curvature":[0.5997307896614075,0.35006481409072876,0.5997307896614075,0.5481184720993042],"aggregation":"Orchid.AggregateMax","dispersion":"UnweightedStar","input":"data/toys.chg.tsv","alpha":0.1}] diff --git a/src/Orchid.jl b/src/Orchid.jl new file mode 100644 index 0000000..f355cb1 --- /dev/null +++ b/src/Orchid.jl @@ -0,0 +1,251 @@ +module Orchid + +using SparseArrays +import OptimalTransport, ThreadsX + +abstract type DisperseUnweightedClique end +abstract type DisperseWeightedClique end +abstract type DisperseUnweightedStar end + +function disperse(::Type{DisperseUnweightedClique}, node, alpha, neighbors, _...) + total = length(neighbors) + N = neighbors[node] + if isempty(N) || length(N) == 1 + sparsevec(Int64[node], Float64[1.0], total) + else + x = sparsevec(N, (1 - alpha) / (length(N) - 1), total) + x[node] = alpha + x + end +end + +function disperse(::Type{DisperseWeightedClique}, node, alpha, neighbors, rc, cr, rw::Vector, _...) + total = length(rc) + N = neighbors[node] + W = rw[node] + if isempty(N) || length(N) == 1 + sparsevec(Int64[node], Float64[1.0], total) + else + factor = (1 - alpha) / (sum(W) - W[findfirst(==(node), N)]) + x = sparsevec(N, W .* factor, total) + x[node] = alpha + x + end +end + +function disperse(::Type{DisperseUnweightedStar}, node, alpha, neighbors, rc, cr, _...) + total = length(rc) + dispersion = sparsevec(Int64[node], Float64[1.0], total) + k = 0 + for e in rc[node] + k += length(cr[e]) > 1 + for x in cr[e] + dispersion[x] += (1 - alpha) / (length(cr[e]) - 1) + end + end + if k > 0 + dispersion ./= k + end + dispersion[node] = alpha + dispersion +end + +abstract type CostMatrix end +abstract type CostOndemand end + +function prepare_cost_matrix(::Type{CostMatrix}, neighbors) + @info "Preparing Cost Matrix" + + K = length(neighbors) + C = fill(Int8(3), (K, K)) + Threads.@threads for m in 1:K + N = neighbors[m] + for n in N + C[n, m] = C[m, n] = 1 + end + for i = eachindex(N), j = i:length(N) + s, t = N[i], N[j] + if s != t && s != m && C[s, t] == 3 + C[t, s] = C[s, t] = 2 + end + end + C[m, m] = 0 + end + C +end + +function prepare_cost_matrix(::Type{CostOndemand}, neighbors) + @info "Preparing Ondemand Cost Computation" + ThreadsX.map(BitSet, neighbors) +end + +function any_bits(f, s::BitSet, t::BitSet) + a1, b1 = s.bits, s.offset + a2, b2 = t.bits, t.offset + l1, l2 = length(a1), length(a2) + bdiff = b2 - b1 + @inbounds for i = max(1, 1 + bdiff):min(l1, l2 + bdiff) + f(a1[i], a2[i-bdiff]) && return true + end + return false +end +# Efficiently checks whether Base.BitSets intersect using BitSet internals. +intersects(u::BitSet, v::BitSet) = any_bits((a, b) -> (a & b) != 0, u, v) + +@inbounds function truncated_cost(m::Int, n::Int, neighbors::Vector) + if n == m + 0 + elseif n in neighbors[m] + 1 + elseif intersects(neighbors[n], neighbors[m]) + 2 + else + 3 + end +end + +get_cost_submatrix(C::AbstractMatrix, U, V) = view(C, U, V) +get_cost_submatrix(neighbors::Union{Vector{BitSet},Vector{Vector{Int}}}, U, V) = Int8[truncated_cost(u, v, neighbors) for u in U, v in V] +function wasserstein(u, v, C, dispersions) + U, X = findnz(dispersions[u]) + V, Y = findnz(dispersions[v]) + C = get_cost_submatrix(C, U, V) + OptimalTransport.sinkhorn2(X, Y, C, 1e-1; maxiter=500, atol=1e-2) +end + +@inline mm(i, j) = i < j ? CartesianIndex(i, j) : CartesianIndex(j, i) + +abstract type AggregateMean end +abstract type AggregateMax end + +function aggregate(::Type{AggregateMean}, S::Vector, W) + s, n = 0.0, length(S) + (n <= 1) && return 0.0 + @inbounds for i = 1:n, j = (i+1):n + s += W[mm(S[i], S[j])] + end + s * 2 / (n * (n - 1)) +end + +function aggregate(::Type{AggregateMax}, S::Vector, W) + s, n = 0.0, length(S) + (n <= 1) && return 0.0 + @inbounds for i = 1:n, j = (i+1):n + s = max(s, W[mm(S[i], S[j])]) + end + s +end + +function node_curvature_neighborhood(i::Int, W, neighbors) + N = neighbors[i] + if length(N) <= 1 + 1.0 + else + sum(N) do j + j == i ? 0.0 : 1.0 - W[mm(i, j)] + end / (length(N) - 1) + end +end + +function node_curvature_edges(node, dist, rc) + degree = length(rc[node]) + if degree == 0 + 1.0 + else + sum(edge -> dist[edge], rc[node]) / degree + end +end + +function prepare_weights(rc, cr, neighbors) + ThreadsX.map(eachindex(neighbors)) do node + map(x -> sum(e -> x in e, view(cr, rc[node])), neighbors[node]) + end +end + +function neighborhoods(rc, cr) + ThreadsX.map(eachindex(rc)) do i + [x for c in rc[i] for x in cr[c]] |> unique + end +end + +function hypergraph_curvatures(dispersion::Type, aggregations, rc, cr, alpha, cost) + @info "Preparing Neighborhoods" + neighbors = neighborhoods(rc, cr) + + C = prepare_cost_matrix(cost, neighbors) + + @info "Preparing Dispersion" + rw = dispersion == DisperseWeightedClique ? prepare_weights(rc, cr, neighbors) : nothing + + @info "Computing Dispersions" + D = ThreadsX.map(n -> disperse(dispersion, n, alpha, neighbors, rc, cr, rw), eachindex(rc)) + + @info "Computing Directional Curvature" + w = zeros(Float32, length(rc), length(rc)) + ThreadsX.foreach(eachindex(rc)) do i + for j in (i+1):length(rc) + w[mm(j, i)] = wasserstein(i, j, C, D) + end + end + + @info "Computing Node Curvature Neighborhood" + nc = ThreadsX.map(n -> node_curvature_neighborhood(n, w, neighbors), eachindex(rc)) + + ac = map(aggregations) do aggregation + @info "Computing Edge Curvature" + ec = ThreadsX.map(e -> 1 - aggregate(aggregation, cr[e], w), eachindex(cr)) + + @info "Computing Node Curvature Edges" + nce = ThreadsX.map(n -> node_curvature_edges(n, ec, rc), eachindex(rc)) + + (aggregation=Symbol(aggregation), edge_curvature=ec, node_curvature_edges=nce) + end + + (dispersions=D, directional_curvature=1 .- w, node_curvature_neighborhood=nc, aggregations=ac) +end + +function edgelist_format(I::Vector{Int}, J::Vector{Int}, n::Int) + x = ThreadsX.collect(Int[] for _ in 1:n) + Threads.@threads for i in ThreadsX.unique(I) + x[i] = J[I.==i] + end + x +end + +function transpose_edgelist(cr::Vector{T}) where {T} + rc = [T() for _ in 1:maximum(e -> maximum(e; init=0), cr)] + for (j, e) in enumerate(cr), i in e + push!(rc[i], j) + end + filter!(!(isempty), rc) +end + +""" + hypergraph_curvatures + +# Arguments +- `dispersion`: Dispersion (options: DisperseUnweightedClique, DisperseWeightedClique, or DisperseUnweightedStar) +- `aggregation`: Aggregation (options: AggregateMean, AggregateMax, or (AggregateMean, AggregateMax)) +- `incidence`: Incidence matrix or edge lists encoding of the input hypergraph +- `alpha`: Self-dispersion weight +- `cost`: Cost computation method (options: CostOndemand, CostMatrix) +""" +function hypergraph_curvatures(dispersion::Type, aggregation::A, incidence::AbstractSparseMatrix, alpha::Float64, cost::Type) where {A} + @info "Preparing Input" + n, m = size(incidence) + I, J, _ = findnz(incidence) + rc, cr = edgelist_format(J, I, m), edgelist_format(I, J, n) + aggregation = hasmethod(length, Tuple{A}) ? aggregation : [aggregation] + hypergraph_curvatures(dispersion, aggregation, rc, cr, alpha, cost) +end + +function hypergraph_curvatures(dispersion::Type, aggregation::A, incidence::Vector{B}, alpha::Float64, cost::Type) where {A,B} + @info "Preparing Input" + rc, cr = transpose_edgelist(incidence), incidence + aggregation = hasmethod(length, Tuple{A}) ? aggregation : [aggregation] + hypergraph_curvatures(dispersion, aggregation, rc, cr, alpha, cost) +end + +export hypergraph_curvatures + +end # module Orchid