├── .coveragerc
├── .github
└── workflows
│ ├── deploy.yml
│ ├── pre-commit.yml
│ └── run_tests.yml
├── .gitignore
├── .pre-commit-config.yaml
├── CONTRIBUTING.md
├── LICENSE
├── MANIFEST.in
├── README.rst
├── autoblack.sh
├── doc
├── Makefile
└── source
│ ├── conf.py
│ ├── index.rst
│ ├── installation.rst
│ ├── reference.rst
│ └── requirements.txt
├── graphtools
├── __init__.py
├── api.py
├── base.py
├── estimator.py
├── graphs.py
├── matrix.py
├── utils.py
└── version.py
├── requirements.txt
├── setup.cfg
├── setup.py
├── test
├── load_tests
│ └── __init__.py
├── test_api.py
├── test_data.py
├── test_estimator.py
├── test_exact.py
├── test_knn.py
├── test_landmark.py
├── test_matrix.py
├── test_mnn.py
└── test_utils.py
└── unittest.cfg
/.coveragerc:
--------------------------------------------------------------------------------
1 | [report]
2 | # Regexes for lines to exclude from consideration
3 | exclude_lines =
4 | # Have to re-enable the standard pragma
5 | pragma: no cover
6 |
7 | # Don't complain about missing debug-only code:
8 | def __repr__
9 | if self\.debug
10 |
11 | # Don't complain if tests don't hit defensive assertion code:
12 | raise AssertionError
13 | raise NotImplementedError
14 |
15 | # Don't complain if non-runnable code isn't run:
16 | if 0:
17 | if __name__ == .__main__.
18 |
--------------------------------------------------------------------------------
/.github/workflows/deploy.yml:
--------------------------------------------------------------------------------
1 | name: Publish Python 🐍 distributions 📦 to PyPI
2 |
3 | on:
4 | push:
5 | branches:
6 | - 'master'
7 | - 'test_deploy'
8 | tags:
9 | - '*'
10 |
11 | jobs:
12 | build-n-publish:
13 | name: Build and publish Python 🐍 distributions 📦 to PyPI
14 | runs-on: ubuntu-latest
15 |
16 | steps:
17 | - uses: actions/checkout@master
18 |
19 | - name: Set up Python 3.10
20 | uses: actions/setup-python@v3
21 | with:
22 | python-version: '3.10'
23 |
24 | - name: Install pypa/build
25 | run: >-
26 | python -m
27 | pip install
28 | build
29 | --user
30 |
31 | - name: Build a binary wheel and a source tarball
32 | run: >-
33 | python -m
34 | build
35 | --sdist
36 | --wheel
37 | --outdir dist/
38 | .
39 |
40 | - name: Publish distribution 📦 to Test PyPI
41 | uses: pypa/gh-action-pypi-publish@release/v1
42 | with:
43 | skip_existing: true
44 | password: ${{ secrets.test_pypi_password }}
45 | repository_url: https://test.pypi.org/legacy/
46 |
47 | - name: Publish distribution 📦 to PyPI
48 | if: startsWith(github.ref, 'refs/tags')
49 | uses: pypa/gh-action-pypi-publish@release/v1
50 | with:
51 | password: ${{ secrets.pypi_password }}
52 |
--------------------------------------------------------------------------------
/.github/workflows/pre-commit.yml:
--------------------------------------------------------------------------------
1 | name: pre-commit
2 | on:
3 | push:
4 | branches-ignore:
5 | - 'master'
6 | pull_request:
7 | types: [opened, synchronize, reopened, ready_for_review]
8 |
9 | concurrency:
10 | group: ${{ github.workflow }}-${{ github.ref }}
11 | cancel-in-progress: true
12 |
13 | jobs:
14 | pre-commit:
15 | runs-on: ubuntu-latest
16 |
17 | if: >-
18 | !endsWith(github.event.head_commit.message, '# ci skip') &&
19 | (
20 | startsWith(github.ref, 'refs/heads') ||
21 | github.event.pull_request.draft == false
22 | )
23 |
24 | steps:
25 |
26 | - uses: actions/checkout@v3
27 | with:
28 | fetch-depth: 0
29 |
30 | - name: Cache pre-commit
31 | uses: actions/cache@v3
32 | with:
33 | path: ~/.cache/pre-commit
34 | key: pre-commit-${{ hashFiles('.pre-commit-config.yaml') }}-
35 |
36 | - name: Run pre-commit
37 | id: precommit
38 | uses: pre-commit/action@v3.0.0
39 | continue-on-error: true
40 |
41 | - name: Commit files
42 | if: steps.precommit.outcome == 'failure' && startsWith(github.ref, 'refs/heads')
43 | run: |
44 | if [[ `git status --porcelain --untracked-files=no` ]]; then
45 | git config --local user.email "41898282+github-actions[bot]@users.noreply.github.com"
46 | git config --local user.name "github-actions[bot]"
47 | git add .
48 | git checkout -- .github/workflows
49 | git commit -m "pre-commit" -a
50 | fi
51 | shell: bash -ex {0}
52 |
53 | - name: Push changes
54 | if: steps.precommit.outcome == 'failure' && startsWith(github.ref, 'refs/heads')
55 | uses: ad-m/github-push-action@master
56 | with:
57 | github_token: ${{ secrets.GITHUB_TOKEN }}
58 | branch: ${{ github.ref }}
59 |
60 | - name: Check pre-commit
61 | if: steps.precommit.outcome == 'failure'
62 | uses: pre-commit/action@v3.0.0
63 |
--------------------------------------------------------------------------------
/.github/workflows/run_tests.yml:
--------------------------------------------------------------------------------
1 | name: Unit Tests
2 |
3 | on:
4 | push:
5 | branches-ignore:
6 | - 'test_deploy'
7 | pull_request:
8 | branches:
9 | - '*'
10 |
11 | concurrency:
12 | group: ${{ github.workflow }}-${{ github.ref }}
13 | cancel-in-progress: true
14 |
15 | jobs:
16 |
17 | run_tester:
18 | runs-on: ${{ matrix.config.os }}
19 | if: "!contains(github.event.head_commit.message, 'ci skip')"
20 |
21 | strategy:
22 | fail-fast: false
23 | matrix:
24 | config:
25 | - {name: '3.10', os: ubuntu-latest, python: '3.10' }
26 | - {name: '3.9', os: ubuntu-latest, python: '3.9' }
27 | - {name: '3.8', os: ubuntu-latest, python: '3.8' }
28 | - {name: '3.7', os: ubuntu-latest, python: '3.7' }
29 |
30 | steps:
31 |
32 | - uses: actions/checkout@v2
33 | with:
34 | fetch-depth: 0
35 |
36 | - name: Install system dependencies
37 | if: runner.os == 'Linux'
38 | run: |
39 | sudo apt-get update -qq
40 | sudo apt-get install -y libhdf5-dev libhdf5-serial-dev pandoc gfortran libblas-dev liblapack-dev llvm-dev
41 |
42 | - name: Set up Python
43 | uses: actions/setup-python@v2
44 | with:
45 | python-version: ${{ matrix.config.python }}
46 |
47 | - name: Cache Python packages
48 | uses: actions/cache@v2
49 | with:
50 | path: ${{ env.pythonLocation }}
51 | key: ${{runner.os}}-${{ matrix.config.python }}-pip-${{ env.pythonLocation }}-${{ hashFiles('setup.py') }}
52 | restore-keys: ${{runner.os}}-${{ matrix.config.python }}-pip-${{ env.pythonLocation }}-
53 |
54 | - name: Install package & dependencies
55 | run: |
56 | python -m pip install --upgrade pip
57 | pip install -U wheel setuptools
58 | pip install -U .[test]
59 | python -c "import graphtools"
60 |
61 | - name: Run tests
62 | run: |
63 | nose2 -vvv
64 |
65 | - name: Coveralls
66 | env:
67 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
68 | COVERALLS_SERVICE_NAME: github
69 | run: |
70 | coveralls
71 |
72 | - name: Upload check results on fail
73 | if: failure()
74 | uses: actions/upload-artifact@master
75 | with:
76 | name: ${{ matrix.config.name }}_results
77 | path: check
78 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | __pycache__
2 | *.pyc
3 | build
4 | dist
5 | *egg-info
6 | .coverage
7 | .eggs
8 |
9 | #syncthing
10 | .syncthing.*
11 |
12 | .DS_Store
13 |
--------------------------------------------------------------------------------
/.pre-commit-config.yaml:
--------------------------------------------------------------------------------
1 | repos:
2 | - repo: https://github.com/pre-commit/pre-commit-hooks
3 | rev: v3.3.0
4 | hooks:
5 | - id: check-yaml
6 | - id: end-of-file-fixer
7 | - id: trailing-whitespace
8 | exclude: \.(ai|gz)$
9 | - repo: https://github.com/timothycrosley/isort
10 | rev: 5.6.4
11 | hooks:
12 | - id: isort
13 | - repo: https://github.com/psf/black
14 | rev: 22.3.0
15 | hooks:
16 | - id: black
17 | args: ['--target-version=py36']
18 | - repo: https://github.com/pre-commit/mirrors-autopep8
19 | rev: v1.5.4
20 | hooks:
21 | - id: autopep8
22 | # - repo: https://gitlab.com/pycqa/flake8
23 | # rev: 3.8.4
24 | # hooks:
25 | # - id: flake8
26 | # additional_dependencies: ['hacking']
27 |
--------------------------------------------------------------------------------
/CONTRIBUTING.md:
--------------------------------------------------------------------------------
1 |
2 | Contributing to graphtools
3 | ============================
4 |
5 | There are many ways to contribute to `graphtools`, with the most common ones
6 | being contribution of code or documentation to the project. Improving the
7 | documentation is no less important than improving the library itself. If you
8 | find a typo in the documentation, or have made improvements, do not hesitate to
9 | submit a GitHub pull request.
10 |
11 | But there are many other ways to help. In particular answering queries on the
12 | [issue tracker](https://github.com/KrishnaswamyLab/graphtools/issues),
13 | investigating bugs, and [reviewing other developers' pull
14 | requests](https://github.com/KrishnaswamyLab/graphtools/pulls)
15 | are very valuable contributions that decrease the burden on the project
16 | maintainers.
17 |
18 | Another way to contribute is to report issues you're facing, and give a "thumbs
19 | up" on issues that others reported and that are relevant to you. It also helps
20 | us if you spread the word: reference the project from your blog and articles,
21 | link to it from your website, or simply star it in GitHub to say "I use it".
22 |
23 | Code Style and Testing
24 | ----------------------
25 |
26 | `graphtools` is maintained at close to 100% code coverage. Contributors are encouraged to write tests for their code, but if you do not know how to do so, please do not feel discouraged from contributing code! Others can always help you test your contribution.
27 |
28 | Code style is dictated by [`black`](https://pypi.org/project/black/#installation-and-usage). To automatically reformat your code when you run `git commit`, you can run `./autoblack.sh` in the root directory of this project to add a hook to your `git` repository.
29 |
30 | Code of Conduct
31 | ---------------
32 |
33 | We abide by the principles of openness, respect, and consideration of others
34 | of the Python Software Foundation: https://www.python.org/psf/codeofconduct/.
35 |
36 | Attribution
37 | ---------------
38 |
39 | This `CONTRIBUTING.md` was adapted from [scikit-learn](https://github.com/scikit-learn/scikit-learn/blob/master/CONTRIBUTING.md).
40 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------
/MANIFEST.in:
--------------------------------------------------------------------------------
1 | include LICENSE
2 |
--------------------------------------------------------------------------------
/README.rst:
--------------------------------------------------------------------------------
1 | ==========
2 | graphtools
3 | ==========
4 |
5 | .. image:: https://img.shields.io/pypi/v/graphtools.svg
6 | :target: https://pypi.org/project/graphtools/
7 | :alt: Latest PyPi version
8 | .. image:: https://anaconda.org/conda-forge/graphtools/badges/version.svg
9 | :target: https://anaconda.org/conda-forge/graphtools/
10 | :alt: Latest Conda version
11 | .. image:: https://img.shields.io/github/workflow/status/KrishnaswamyLab/graphtools/Unit%20Tests/master?label=Github%20Actions
12 | :target: https://travis-ci.com/KrishnaswamyLab/graphtools
13 | :alt: Github Actions Build
14 | .. image:: https://img.shields.io/readthedocs/graphtools.svg
15 | :target: https://graphtools.readthedocs.io/
16 | :alt: Read the Docs
17 | .. image:: https://coveralls.io/repos/github/KrishnaswamyLab/graphtools/badge.svg?branch=master
18 | :target: https://coveralls.io/github/KrishnaswamyLab/graphtools?branch=master
19 | :alt: Coverage Status
20 | .. image:: https://img.shields.io/twitter/follow/KrishnaswamyLab.svg?style=social&label=Follow
21 | :target: https://twitter.com/KrishnaswamyLab
22 | :alt: Twitter
23 | .. image:: https://img.shields.io/github/stars/KrishnaswamyLab/graphtools.svg?style=social&label=Stars
24 | :target: https://github.com/KrishnaswamyLab/graphtools/
25 | :alt: GitHub stars
26 | .. image:: https://img.shields.io/badge/code%20style-black-000000.svg
27 | :target: https://github.com/psf/black
28 | :alt: Code style: black
29 |
30 | Tools for building and manipulating graphs in Python.
31 |
32 | Installation
33 | ------------
34 |
35 | graphtools is available on `pip`. Install by running the following in a terminal::
36 |
37 | pip install --user graphtools
38 |
39 | Alternatively, graphtools can be installed using `Conda `_ (most easily obtained via the `Miniconda Python distribution `_)::
40 |
41 | conda install -c conda-forge graphtools
42 |
43 | Or, to install the latest version from github::
44 |
45 | pip install --user git+git://github.com/KrishnaswamyLab/graphtools.git
46 |
47 | Usage example
48 | -------------
49 |
50 | The `graphtools.Graph` class provides an all-in-one interface for k-nearest neighbors, mutual nearest neighbors, exact (pairwise distances) and landmark graphs.
51 |
52 | Use it as follows::
53 |
54 | from sklearn import datasets
55 | import graphtools
56 | digits = datasets.load_digits()
57 | G = graphtools.Graph(digits['data'])
58 | K = G.kernel
59 | P = G.diff_op
60 | G = graphtools.Graph(digits['data'], n_landmark=300)
61 | L = G.landmark_op
62 |
63 | Help
64 | ----
65 |
66 | If you have any questions or require assistance using graphtools, please contact us at https://krishnaswamylab.org/get-help
67 |
--------------------------------------------------------------------------------
/autoblack.sh:
--------------------------------------------------------------------------------
1 | cat <> .git/hooks/pre-commit
2 | #!/bin/sh
3 |
4 | set -e
5 |
6 | files=\$(git diff --staged --name-only --diff-filter=d -- "*.py")
7 |
8 | for file in \$files; do
9 | black -q \$file
10 | git add \$file
11 | done
12 | EOF
13 | chmod +x .git/hooks/pre-commit
14 |
--------------------------------------------------------------------------------
/doc/Makefile:
--------------------------------------------------------------------------------
1 | # Minimal makefile for Sphinx documentation
2 | #
3 |
4 | # You can set these variables from the command line.
5 | SPHINXOPTS =
6 | SPHINXBUILD = sphinx-build
7 | SPHINXPROJ = PHATE
8 | SOURCEDIR = source
9 | BUILDDIR = build
10 |
11 | # Put it first so that "make" without argument is like "make help".
12 | help:
13 | @$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)
14 |
15 | .PHONY: help Makefile
16 |
17 | # Catch-all target: route all unknown targets to Sphinx using the new
18 | # "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS).
19 | %: Makefile
20 | @$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)
21 |
--------------------------------------------------------------------------------
/doc/source/conf.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | #
4 | # PHATE documentation build configuration file, created by
5 | # sphinx-quickstart on Thu Mar 30 19:50:14 2017.
6 | #
7 | # This file is execfile()d with the current directory set to its
8 | # containing dir.
9 | #
10 | # Note that not all possible configuration values are present in this
11 | # autogenerated file.
12 | #
13 | # All configuration values have a default; values that are commented out
14 | # serve to show the default.
15 |
16 | # If extensions (or modules to document with autodoc) are in another directory,
17 | # add these directories to sys.path here. If the directory is relative to the
18 | # documentation root, use os.path.abspath to make it absolute, like shown here.
19 | #
20 | import os
21 | import sys
22 |
23 | root_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", ".."))
24 | sys.path.insert(0, root_dir)
25 | # print(sys.path)
26 |
27 | # -- General configuration ------------------------------------------------
28 |
29 | # If your documentation needs a minimal Sphinx version, state it here.
30 | #
31 | # needs_sphinx = '1.0'
32 |
33 | # Add any Sphinx extension module names here, as strings. They can be
34 | # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
35 | # ones.
36 | extensions = [
37 | "sphinx.ext.autodoc",
38 | "sphinx.ext.autosummary",
39 | "sphinx.ext.napoleon",
40 | "sphinx.ext.doctest",
41 | "sphinx.ext.coverage",
42 | "sphinx.ext.mathjax",
43 | "sphinx.ext.viewcode",
44 | "sphinxcontrib.bibtex",
45 | ]
46 |
47 | # Add any paths that contain templates here, relative to this directory.
48 | templates_path = ["ytemplates"]
49 |
50 | # The suffix(es) of source filenames.
51 | # You can specify multiple suffix as a list of string:
52 | #
53 | # source_suffix = ['.rst', '.md']
54 | source_suffix = ".rst"
55 |
56 | # The master toctree document.
57 | master_doc = "index"
58 |
59 | # General information about the project.
60 | project = "graphtools"
61 | copyright = "2018 Krishnaswamy Lab, Yale University"
62 | author = "Scott Gigante and Jay Stanley, Yale University"
63 |
64 | # The version info for the project you're documenting, acts as replacement for
65 | # |version| and |release|, also used in various other places throughout the
66 | # built documents.
67 | #
68 | version_py = os.path.join(root_dir, "graphtools", "version.py")
69 | # The full version, including alpha/beta/rc tags.
70 | release = open(version_py).read().strip().split("=")[-1].replace('"', "").strip()
71 | # The short X.Y version.
72 | version = release.split("-")[0]
73 |
74 | # The language for content autogenerated by Sphinx. Refer to documentation
75 | # for a list of supported languages.
76 | #
77 | # This is also used if you do content translation via gettext catalogs.
78 | # Usually you set "language" from the command line for these cases.
79 | language = None
80 |
81 | # List of patterns, relative to source directory, that match files and
82 | # directories to ignore when looking for source files.
83 | # This patterns also effect to html_static_path and html_extra_path
84 | exclude_patterns = []
85 |
86 | # The name of the Pygments (syntax highlighting) style to use.
87 | pygments_style = "sphinx"
88 |
89 | # If true, `todo` and `todoList` produce output, else they produce nothing.
90 | todo_include_todos = False
91 |
92 |
93 | # -- Options for HTML output ----------------------------------------------
94 |
95 | # The theme to use for HTML and HTML Help pages. See the documentation for
96 | # a list of builtin themes.
97 | #
98 | html_theme = "default"
99 |
100 | # Theme options are theme-specific and customize the look and feel of a theme
101 | # further. For a list of options available for each theme, see the
102 | # documentation.
103 | #
104 | # html_theme_options = {}
105 |
106 | # Add any paths that contain custom static files (such as style sheets) here,
107 | # relative to this directory. They are copied after the builtin static files,
108 | # so a file named "default.css" will overwrite the builtin "default.css".
109 | html_static_path = ["ystatic"]
110 |
111 |
112 | # -- Options for HTMLHelp output ------------------------------------------
113 |
114 | # Output file base name for HTML help builder.
115 | htmlhelp_basename = "graphtoolsdoc"
116 |
117 |
118 | # -- Options for LaTeX output ---------------------------------------------
119 |
120 | latex_elements = {
121 | # The paper size ('letterpaper' or 'a4paper').
122 | #
123 | # 'papersize': 'letterpaper',
124 | # The font size ('10pt', '11pt' or '12pt').
125 | #
126 | # 'pointsize': '10pt',
127 | # Additional stuff for the LaTeX preamble.
128 | #
129 | # 'preamble': '',
130 | # Latex figure (float) alignment
131 | #
132 | # 'figure_align': 'htbp',
133 | }
134 |
135 | # Grouping the document tree into LaTeX files. List of tuples
136 | # (source start file, target name, title,
137 | # author, documentclass [howto, manual, or own class]).
138 | latex_documents = [
139 | (
140 | master_doc,
141 | "graphtools.tex",
142 | "graphtools Documentation",
143 | "Scott Gigante and Jay Stanley, Yale University",
144 | "manual",
145 | ),
146 | ]
147 |
148 |
149 | # -- Options for manual page output ---------------------------------------
150 |
151 | # One entry per manual page. List of tuples
152 | # (source start file, name, description, authors, manual section).
153 | man_pages = [(master_doc, "graphtools", "graphtools Documentation", [author], 1)]
154 |
155 |
156 | # -- Options for Texinfo output -------------------------------------------
157 |
158 | # Grouping the document tree into Texinfo files. List of tuples
159 | # (source start file, target name, title, author,
160 | # dir menu entry, description, category)
161 | texinfo_documents = [
162 | (
163 | master_doc,
164 | "graphtools",
165 | "graphtools Documentation",
166 | author,
167 | "graphtools",
168 | "One line description of project.",
169 | "Miscellaneous",
170 | ),
171 | ]
172 |
--------------------------------------------------------------------------------
/doc/source/index.rst:
--------------------------------------------------------------------------------
1 | ===========================================================================
2 | graphtools
3 | ===========================================================================
4 |
5 | .. raw:: html
6 |
7 |
8 |
9 | .. raw:: html
10 |
11 |
12 |
13 | .. raw:: html
14 |
15 |
16 |
17 | .. raw:: html
18 |
19 |
20 |
21 | .. raw:: html
22 |
23 |
24 |
25 | .. raw:: html
26 |
27 |
28 |
29 | .. raw:: html
30 |
31 |
32 |
33 | .. raw:: html
34 |
35 |
36 |
37 | Tools for building and manipulating graphs in Python.
38 |
39 | .. toctree::
40 | :maxdepth: 2
41 |
42 | installation
43 | reference
44 |
45 | Quick Start
46 | ===========
47 |
48 | To use `graphtools`, create a `graphtools.Graph` class::
49 |
50 | from sklearn import datasets
51 | import graphtools
52 | digits = datasets.load_digits()
53 | G = graphtools.Graph(digits['data'])
54 | K = G.kernel
55 | P = G.diff_op
56 | G = graphtools.Graph(digits['data'], n_landmark=300)
57 | L = G.landmark_op
58 |
59 | To use `graphtools` with `pygsp`, create a `graphtools.Graph` class with `use_pygsp=True`::
60 |
61 | from sklearn import datasets
62 | import graphtools
63 | digits = datasets.load_digits()
64 | G = graphtools.Graph(digits['data'], use_pygsp=True)
65 | N = G.N
66 | W = G.W
67 | basis = G.compute_fourier_basis()
68 |
69 | Help
70 | ====
71 |
72 | If you have any questions or require assistance using graphtools, please contact us at https://krishnaswamylab.org/get-help
73 |
--------------------------------------------------------------------------------
/doc/source/installation.rst:
--------------------------------------------------------------------------------
1 | Installation
2 | ============
3 |
4 | Installation with `pip`
5 | ~~~~~~~~~~~~~~~~~~~~~~~
6 |
7 | Install graphtools using::
8 |
9 | pip install --user graphtools
10 |
11 | Installation from source
12 | ~~~~~~~~~~~~~~~~~~~~~~~~
13 |
14 | Install from source using::
15 |
16 | git clone git://github.com/KrishnaswamyLab/graphtools.git
17 | cd graphtools
18 | python setup.py install --user
19 |
--------------------------------------------------------------------------------
/doc/source/reference.rst:
--------------------------------------------------------------------------------
1 | Reference
2 | =========
3 |
4 | API
5 | ---
6 |
7 | .. automodule:: graphtools.api
8 | :members:
9 | :undoc-members:
10 | :inherited-members:
11 | :show-inheritance:
12 |
13 | Graph Classes
14 | -------------
15 |
16 | .. automodule:: graphtools.graphs
17 | :members:
18 | :undoc-members:
19 | :inherited-members:
20 | :show-inheritance:
21 |
22 | Base Classes
23 | ------------
24 |
25 | .. automodule:: graphtools.base
26 | :members:
27 | :undoc-members:
28 | :inherited-members:
29 | :show-inheritance:
30 |
31 | Utilities
32 | ---------
33 |
34 | .. automodule:: graphtools.utils
35 | :members:
36 | :undoc-members:
37 | :inherited-members:
38 | :show-inheritance:
39 |
--------------------------------------------------------------------------------
/doc/source/requirements.txt:
--------------------------------------------------------------------------------
1 | numpy>=1.10.0
2 | scipy>=0.18.0
3 | pygsp>=>=0.5.1
4 | scikit-learn>=0.19.1
5 | future
6 | sphinx
7 | sphinxcontrib-napoleon
8 | sphinxcontrib-bibtex
9 | tasklogger
10 | deprecated
11 |
--------------------------------------------------------------------------------
/graphtools/__init__.py:
--------------------------------------------------------------------------------
1 | from .api import from_igraph
2 | from .api import Graph
3 | from .api import read_pickle
4 | from .version import __version__
5 |
--------------------------------------------------------------------------------
/graphtools/api.py:
--------------------------------------------------------------------------------
1 | from . import base
2 | from . import graphs
3 | from scipy import sparse
4 |
5 | import numpy as np
6 | import pickle
7 | import pygsp
8 | import tasklogger
9 | import warnings
10 |
11 | _logger = tasklogger.get_tasklogger("graphtools")
12 |
13 |
14 | def Graph(
15 | data,
16 | n_pca=None,
17 | rank_threshold=None,
18 | knn=5,
19 | decay=40,
20 | bandwidth=None,
21 | bandwidth_scale=1.0,
22 | knn_max=None,
23 | anisotropy=0,
24 | distance="euclidean",
25 | thresh=1e-4,
26 | kernel_symm="+",
27 | theta=None,
28 | precomputed=None,
29 | beta=1,
30 | sample_idx=None,
31 | adaptive_k=None,
32 | n_landmark=None,
33 | n_svd=100,
34 | n_jobs=-1,
35 | verbose=False,
36 | random_state=None,
37 | graphtype="auto",
38 | use_pygsp=False,
39 | initialize=True,
40 | **kwargs,
41 | ):
42 | """Create a graph built on data.
43 |
44 | Automatically selects the appropriate DataGraph subclass based on
45 | chosen parameters.
46 | Selection criteria:
47 | - if `graphtype` is given, this will be respected
48 | - otherwise:
49 | -- if `sample_idx` is given, an MNNGraph will be created
50 | -- if `precomputed` is not given, and either `decay` is `None` or `thresh`
51 | is given, a kNNGraph will be created
52 | - otherwise, a TraditionalGraph will be created.
53 |
54 | Incompatibilities:
55 | - MNNGraph and kNNGraph cannot be precomputed
56 | - kNNGraph and TraditionalGraph do not accept sample indices
57 |
58 | Parameters
59 | ----------
60 | data : array-like, shape=[n_samples,n_features]
61 | accepted types: `numpy.ndarray`, `scipy.sparse.spmatrix`.
62 | TODO: accept pandas dataframes'
63 |
64 | n_pca : {`int`, `None`, `bool`, 'auto'}, optional (default: `None`)
65 | number of PC dimensions to retain for graph building.
66 | If n_pca in `[None, False, 0]`, uses the original data.
67 | If 'auto' or `True` then estimate using a singular value threshold
68 | Note: if data is sparse, uses SVD instead of PCA
69 | TODO: should we subtract and store the mean?
70 |
71 | rank_threshold : `float`, 'auto', optional (default: 'auto')
72 | threshold to use when estimating rank for
73 | `n_pca in [True, 'auto']`.
74 | If 'auto', this threshold is
75 | s_max * eps * max(n_samples, n_features)
76 | where s_max is the maximum singular value of the data matrix
77 | and eps is numerical precision. [press2007]_.
78 |
79 | knn : `int`, optional (default: 5)
80 | Number of nearest neighbors (including self) to use to build the graph
81 |
82 | decay : `int` or `None`, optional (default: 40)
83 | Rate of alpha decay to use. If `None`, alpha decay is not used and a vanilla
84 | k-Nearest Neighbors graph is returned.
85 |
86 | bandwidth : `float`, list-like,`callable`, or `None`, optional (default: `None`)
87 | Fixed bandwidth to use. If given, overrides `knn`. Can be a single
88 | bandwidth, list-like (shape=[n_samples]) of bandwidths for each
89 | sample, or a `callable` that takes in an `n x n` distance matrix and returns a
90 | a single value or list-like of length n (shape=[n_samples])
91 |
92 | bandwidth_scale : `float`, optional (default : 1.0)
93 | Rescaling factor for bandwidth.
94 |
95 | knn_max : `int` or `None`, optional (default : `None`)
96 | Maximum number of neighbors with nonzero affinity
97 |
98 | anisotropy : float, optional (default: 0)
99 | Level of anisotropy between 0 and 1
100 | (alpha in Coifman & Lafon, 2006)
101 |
102 | distance : `str`, optional (default: `'euclidean'`)
103 | Any metric from `scipy.spatial.distance` can be used
104 | distance metric for building kNN graph.
105 | TODO: actually sklearn.neighbors has even more choices
106 |
107 | thresh : `float`, optional (default: `1e-4`)
108 | Threshold above which to calculate alpha decay kernel.
109 | All affinities below `thresh` will be set to zero in order to save
110 | on time and memory constraints.
111 |
112 | kernel_symm : string, optional (default: '+')
113 | Defines method of kernel symmetrization.
114 | '+' : additive
115 | '*' : multiplicative
116 | 'mnn' : min-max MNN symmetrization
117 | 'none' : no symmetrization
118 |
119 | theta: float (default: None)
120 | Min-max symmetrization constant or matrix. Only used if kernel_symm='mnn'.
121 | K = `theta * min(K, K.T) + (1 - theta) * max(K, K.T)`
122 |
123 | precomputed : {'distance', 'affinity', 'adjacency', `None`}, optional (default: `None`)
124 | If the graph is precomputed, this variable denotes which graph
125 | matrix is provided as `data`.
126 | Only one of `precomputed` and `n_pca` can be set.
127 |
128 | beta: float, optional(default: 1)
129 | Multiply between - batch connections by beta
130 |
131 | sample_idx: array-like
132 | Batch index for MNN kernel
133 |
134 | adaptive_k : `{'min', 'mean', 'sqrt', 'none'}` (default: None)
135 | Weights MNN kernel adaptively using the number of cells in
136 | each sample according to the selected method.
137 |
138 | n_landmark : `int`, optional (default: 2000)
139 | number of landmarks to use
140 |
141 | n_svd : `int`, optional (default: 100)
142 | number of SVD components to use for spectral clustering
143 |
144 | random_state : `int` or `None`, optional (default: `None`)
145 | Random state for random PCA
146 |
147 | verbose : `bool`, optional (default: `True`)
148 | Verbosity.
149 | TODO: should this be an integer instead to allow multiple
150 | levels of verbosity?
151 |
152 | n_jobs : `int`, optional (default : 1)
153 | The number of jobs to use for the computation.
154 | If -1 all CPUs are used. If 1 is given, no parallel computing code is
155 | used at all, which is useful for debugging.
156 | For n_jobs below -1, (n_cpus + 1 + n_jobs) are used. Thus for
157 | n_jobs = -2, all CPUs but one are used
158 |
159 | graphtype : {'exact', 'knn', 'mnn', 'auto'} (Default: 'auto')
160 | Manually selects graph type. Only recommended for expert users
161 |
162 | use_pygsp : `bool` (Default: `False`)
163 | If true, inherits from `pygsp.graphs.Graph`.
164 |
165 | initialize : `bool` (Default: `True`)
166 | If True, initialize the kernel matrix on instantiation
167 |
168 | **kwargs : extra arguments for `pygsp.graphs.Graph`
169 |
170 | Returns
171 | -------
172 | G : `DataGraph`
173 |
174 | Raises
175 | ------
176 | ValueError : if selected parameters are incompatible.
177 |
178 | References
179 | ----------
180 | .. [press2007] W. Press, S. Teukolsky, W. Vetterling and B. Flannery,
181 | “Numerical Recipes (3rd edition)”,
182 | Cambridge University Press, 2007, page 795.
183 | """
184 | _logger.set_level(verbose)
185 | if sample_idx is not None and len(np.unique(sample_idx)) == 1:
186 | warnings.warn("Only one unique sample. Not using MNNGraph")
187 | sample_idx = None
188 | if graphtype == "mnn":
189 | graphtype = "auto"
190 | if graphtype == "auto":
191 | # automatic graph selection
192 | if sample_idx is not None:
193 | # only mnn does batch correction
194 | graphtype = "mnn"
195 | elif precomputed is not None:
196 | # precomputed requires exact graph
197 | graphtype = "exact"
198 | elif decay is None:
199 | # knn kernel
200 | graphtype = "knn"
201 | elif (thresh == 0 and knn_max is None) or callable(bandwidth):
202 | # compute full distance matrix
203 | graphtype = "exact"
204 | else:
205 | # decay kernel with nonzero threshold - knn is more efficient
206 | graphtype = "knn"
207 |
208 | # set base graph type
209 | if graphtype == "knn":
210 | basegraph = graphs.kNNGraph
211 | if precomputed is not None:
212 | raise ValueError(
213 | "kNNGraph does not support precomputed "
214 | "values. Use `graphtype='exact'` or "
215 | "`precomputed=None`"
216 | )
217 | if sample_idx is not None:
218 | raise ValueError(
219 | "kNNGraph does not support batch "
220 | "correction. Use `graphtype='mnn'` or "
221 | "`sample_idx=None`"
222 | )
223 |
224 | elif graphtype == "mnn":
225 | basegraph = graphs.MNNGraph
226 | if precomputed is not None:
227 | raise ValueError(
228 | "MNNGraph does not support precomputed "
229 | "values. Use `graphtype='exact'` and "
230 | "`sample_idx=None` or `precomputed=None`"
231 | )
232 | elif graphtype == "exact":
233 | basegraph = graphs.TraditionalGraph
234 | if sample_idx is not None:
235 | raise ValueError(
236 | "TraditionalGraph does not support batch "
237 | "correction. Use `graphtype='mnn'` or "
238 | "`sample_idx=None`"
239 | )
240 | else:
241 | raise ValueError(
242 | "graphtype '{}' not recognized. Choose from "
243 | "['knn', 'mnn', 'exact', 'auto']".format(graphtype)
244 | )
245 |
246 | # set add landmarks if necessary
247 | parent_classes = [basegraph]
248 | msg = "Building {} graph".format(graphtype)
249 | if n_landmark is not None:
250 | parent_classes.append(graphs.LandmarkGraph)
251 | msg = msg + " with landmarks"
252 | if use_pygsp:
253 | parent_classes.append(base.PyGSPGraph)
254 | if len(parent_classes) > 2:
255 | msg = msg + " with PyGSP inheritance"
256 | else:
257 | msg = msg + " and PyGSP inheritance"
258 |
259 | _logger.log_debug(msg)
260 |
261 | class_names = [p.__name__.replace("Graph", "") for p in parent_classes]
262 | try:
263 | Graph = eval("graphs." + "".join(class_names) + "Graph")
264 | except NameError:
265 | raise RuntimeError("unknown graph classes {}".format(parent_classes))
266 |
267 | params = kwargs
268 | for parent_class in parent_classes:
269 | for param in parent_class._get_param_names():
270 | try:
271 | params[param] = eval(param)
272 | except NameError:
273 | # keyword argument not specified above - no problem
274 | pass
275 |
276 | # build graph and return
277 | _logger.log_debug(
278 | "Initializing {} with arguments {}".format(
279 | parent_classes,
280 | ", ".join(
281 | [
282 | "{}='{}'".format(key, value)
283 | for key, value in params.items()
284 | if key != "data"
285 | ]
286 | ),
287 | )
288 | )
289 | return Graph(**params)
290 |
291 |
292 | def from_igraph(G, attribute="weight", **kwargs):
293 | """Convert an igraph.Graph to a graphtools.Graph
294 |
295 | Creates a graphtools.graphs.TraditionalGraph with a
296 | precomputed adjacency matrix
297 |
298 | Parameters
299 | ----------
300 | G : igraph.Graph
301 | Graph to be converted
302 | attribute : str, optional (default: "weight")
303 | attribute containing edge weights, if any.
304 | If None, unweighted graph is built
305 | kwargs
306 | keyword arguments for graphtools.Graph
307 |
308 | Returns
309 | -------
310 | G : graphtools.graphs.TraditionalGraph
311 | """
312 | if "precomputed" in kwargs:
313 | if kwargs["precomputed"] != "adjacency":
314 | warnings.warn(
315 | "Cannot build graph from igraph with precomputed={}. "
316 | "Use 'adjacency' instead.".format(kwargs["precomputed"]),
317 | UserWarning,
318 | )
319 | del kwargs["precomputed"]
320 | try:
321 | K = G.get_adjacency(attribute=attribute).data
322 | except ValueError as e:
323 | if str(e) == "Attribute does not exist":
324 | warnings.warn(
325 | "Edge attribute {} not found. "
326 | "Returning unweighted graph".format(attribute),
327 | UserWarning,
328 | )
329 | K = G.get_adjacency(attribute=None).data
330 | return Graph(sparse.coo_matrix(K), precomputed="adjacency", **kwargs)
331 |
332 |
333 | def read_pickle(path):
334 | """Load pickled Graphtools object (or any object) from file.
335 |
336 | Parameters
337 | ----------
338 | path : str
339 | File path where the pickled object will be loaded.
340 | """
341 | with open(path, "rb") as f:
342 | G = pickle.load(f)
343 |
344 | if not isinstance(G, base.BaseGraph):
345 | warnings.warn("Returning object that is not a graphtools.base.BaseGraph")
346 | elif isinstance(G, base.PyGSPGraph) and isinstance(G.logger, str):
347 | G.logger = pygsp.utils.build_logger(G.logger)
348 | return G
349 |
--------------------------------------------------------------------------------
/graphtools/estimator.py:
--------------------------------------------------------------------------------
1 | from . import api
2 | from . import base
3 | from . import graphs
4 | from . import matrix
5 | from . import utils
6 | from functools import partial
7 | from scipy import sparse
8 |
9 | import abc
10 | import numpy as np
11 | import pygsp
12 | import tasklogger
13 |
14 |
15 | def attribute(attr, default=None, doc=None, on_set=None):
16 | def getter(self, attr):
17 | try:
18 | return getattr(self, "_" + attr)
19 | except AttributeError:
20 | return default
21 |
22 | def setter(self, value, attr, on_set=None):
23 | if on_set is not None:
24 | if callable(on_set):
25 | on_set = [on_set]
26 | for fn in on_set:
27 | fn(**{attr: value})
28 | setattr(self, "_" + attr, value)
29 |
30 | return property(
31 | fget=partial(getter, attr=attr),
32 | fset=partial(setter, attr=attr, on_set=on_set),
33 | doc=doc,
34 | )
35 |
36 |
37 | _logger = tasklogger.get_tasklogger("graphtools")
38 |
39 |
40 | class GraphEstimator(object, metaclass=abc.ABCMeta):
41 | """Estimator which builds a graphtools Graph
42 |
43 | Parameters
44 | ----------
45 |
46 | knn : int, optional, default: 5
47 | number of nearest neighbors on which to build kernel
48 |
49 | decay : int, optional, default: 40
50 | sets decay rate of kernel tails.
51 | If None, alpha decaying kernel is not used
52 |
53 | n_landmark : int, optional, default: None
54 | number of landmarks to use in graph construction
55 |
56 | n_pca : int, optional, default: 100
57 | Number of principal components to use for calculating
58 | neighborhoods. For extremely large datasets, using
59 | n_pca < 20 allows neighborhoods to be calculated in
60 | roughly log(n_samples) time.
61 |
62 | distance : string, optional, default: 'euclidean'
63 | recommended values: 'euclidean', 'cosine', 'precomputed'
64 | Any metric from `scipy.spatial.distance` can be used
65 | distance metric for building kNN graph. Custom distance
66 | functions of form `f(x, y) = d` are also accepted. If 'precomputed',
67 | `data` should be an n_samples x n_samples distance or
68 | affinity matrix. Distance matrices are assumed to have zeros
69 | down the diagonal, while affinity matrices are assumed to have
70 | non-zero values down the diagonal. This is detected automatically using
71 | `data[0,0]`. You can override this detection with
72 | `distance='precomputed_distance'` or `distance='precomputed_affinity'`.
73 |
74 | n_jobs : integer, optional, default: 1
75 | The number of jobs to use for the computation.
76 | If -1 all CPUs are used. If 1 is given, no parallel computing code is
77 | used at all, which is useful for debugging.
78 | For n_jobs below -1, (n_cpus + 1 + n_jobs) are used. Thus for
79 | n_jobs = -2, all CPUs but one are used
80 |
81 | random_state : integer or numpy.RandomState, optional, default: None
82 | If an integer is given, it fixes the seed
83 | Defaults to the global `numpy` random number generator
84 |
85 | verbose : `int` or `boolean`, optional (default: 1)
86 | If `True` or `> 0`, print status messages
87 |
88 | n_svd : int, optional (default: 100)
89 | number of singular vectors to compute for landmarking
90 |
91 | thresh : float, optional (default: 1e-4)
92 | threshold below which to truncate kernel
93 |
94 | kwargs : additional arguments for graphtools.Graph
95 |
96 | Attributes
97 | ----------
98 |
99 | graph : graphtools.Graph
100 | """
101 |
102 | X = attribute("X", doc="Stored input data")
103 | graph = attribute("graph", doc="graphtools Graph object")
104 |
105 | @graph.setter
106 | def graph(self, G):
107 | self._graph = G
108 | if G is None:
109 | self._reset_graph()
110 |
111 | n_pca = attribute(
112 | "n_pca",
113 | default=100,
114 | on_set=partial(utils.check_if_not, None, utils.check_positive, utils.check_int),
115 | )
116 | random_state = attribute("random_state")
117 |
118 | knn = attribute("knn", default=5, on_set=[utils.check_positive, utils.check_int])
119 | decay = attribute("decay", default=40, on_set=utils.check_positive)
120 | distance = attribute(
121 | "distance",
122 | default="euclidean",
123 | on_set=partial(
124 | utils.check_in,
125 | [
126 | "euclidean",
127 | "precomputed",
128 | "cosine",
129 | "correlation",
130 | "cityblock",
131 | "l1",
132 | "l2",
133 | "manhattan",
134 | "braycurtis",
135 | "canberra",
136 | "chebyshev",
137 | "dice",
138 | "hamming",
139 | "jaccard",
140 | "kulsinski",
141 | "mahalanobis",
142 | "matching",
143 | "minkowski",
144 | "rogerstanimoto",
145 | "russellrao",
146 | "seuclidean",
147 | "sokalmichener",
148 | "sokalsneath",
149 | "sqeuclidean",
150 | "yule",
151 | "precomputed_affinity",
152 | "precomputed_distance",
153 | ],
154 | ),
155 | )
156 | n_svd = attribute(
157 | "n_svd",
158 | default=100,
159 | on_set=partial(utils.check_if_not, None, utils.check_positive, utils.check_int),
160 | )
161 | n_jobs = attribute(
162 | "n_jobs", on_set=partial(utils.check_if_not, None, utils.check_int)
163 | )
164 | verbose = attribute("verbose", default=0)
165 | thresh = attribute(
166 | "thresh",
167 | default=1e-4,
168 | on_set=partial(utils.check_if_not, 0, utils.check_positive),
169 | )
170 |
171 | n_landmark = attribute("n_landmark")
172 |
173 | @n_landmark.setter
174 | def n_landmark(self, n_landmark):
175 | self._n_landmark = n_landmark
176 | utils.check_if_not(
177 | None, utils.check_positive, utils.check_int, n_landmark=n_landmark
178 | )
179 | self._update_n_landmark(n_landmark)
180 |
181 | def _update_n_landmark(self, n_landmark):
182 | if self.graph is not None:
183 | n_landmark = self._parse_n_landmark(self.graph.data_nu, n_landmark)
184 | if (
185 | n_landmark is None and isinstance(self.graph, graphs.LandmarkGraph)
186 | ) or (
187 | n_landmark is not None
188 | and not isinstance(self.graph, graphs.LandmarkGraph)
189 | ):
190 | # new graph but the same kernel
191 | # there may be a better way to do this
192 | kernel = self.graph.kernel
193 | self.graph = None
194 | self.fit(self.X, initialize=False)
195 | self.graph._kernel = kernel
196 |
197 | def __init__(
198 | self,
199 | knn=5,
200 | decay=40,
201 | n_pca=100,
202 | n_landmark=None,
203 | random_state=None,
204 | distance="euclidean",
205 | n_svd=100,
206 | n_jobs=1,
207 | verbose=1,
208 | thresh=1e-4,
209 | **kwargs,
210 | ):
211 |
212 | if verbose is True:
213 | verbose = 1
214 | elif verbose is False:
215 | verbose = 0
216 |
217 | self.n_pca = n_pca
218 | self.n_landmark = n_landmark
219 | self.random_state = random_state
220 | self.knn = knn
221 | self.decay = decay
222 | self.distance = distance
223 | self.n_svd = n_svd
224 | self.n_jobs = n_jobs
225 | self.verbose = verbose
226 | self.thresh = thresh
227 | self.kwargs = kwargs
228 | self.logger = _logger
229 | _logger.set_level(self.verbose)
230 |
231 | def set_params(self, **params):
232 | for p in params:
233 | if not getattr(self, p) == params[p]:
234 | setattr(self, p, params[p])
235 | self._set_graph_params(**params)
236 |
237 | def _set_graph_params(self, **params):
238 | if self.graph is not None:
239 | try:
240 | if "n_pca" in params:
241 | params["n_pca"] = self._parse_n_pca(
242 | self.graph.data_nu, params["n_pca"]
243 | )
244 | if "n_svd" in params:
245 | params["n_svd"] = self._parse_n_svd(
246 | self.graph.data_nu, params["n_svd"]
247 | )
248 | if "n_landmark" in params:
249 | params["n_landmark"] = self._parse_n_landmark(
250 | self.graph.data_nu, params["n_landmark"]
251 | )
252 | self.graph.set_params(**params)
253 | except ValueError as e:
254 | _logger.log_debug("Reset graph due to {}".format(str(e)))
255 | self.graph = None
256 |
257 | @abc.abstractmethod
258 | def _reset_graph(self):
259 | """Trigger a reset of self.graph
260 |
261 | Any downstream effects of resetting the graph should override this function
262 | """
263 | raise NotImplementedError
264 |
265 | def _detect_precomputed_matrix_type(self, X):
266 | if isinstance(X, (sparse.coo_matrix, sparse.dia_matrix)):
267 | X = X.tocsr()
268 | if X[0, 0] == 0:
269 | return "distance"
270 | else:
271 | return "affinity"
272 |
273 | @staticmethod
274 | def _parse_n_landmark(X, n_landmark):
275 | if n_landmark is not None and n_landmark >= X.shape[0]:
276 | return None
277 | else:
278 | return n_landmark
279 |
280 | @staticmethod
281 | def _parse_n_pca(X, n_pca):
282 | if n_pca is not None and n_pca >= min(X.shape):
283 | return None
284 | else:
285 | return n_pca
286 |
287 | @staticmethod
288 | def _parse_n_svd(X, n_svd):
289 | if n_svd is not None and n_svd >= X.shape[0]:
290 | return X.shape[0] - 1
291 | else:
292 | return n_svd
293 |
294 | def _parse_input(self, X):
295 | # passing graphs as input
296 | if isinstance(X, base.BaseGraph):
297 | # we can keep this graph
298 | self.graph = X
299 | X = X.data
300 | # immutable graph properties override operator
301 | n_pca = self.graph.n_pca
302 | self.knn = self.graph.knn
303 | self.decay = self.graph.decay
304 | self.distance = self.graph.distance
305 | self.thresh = self.graph.thresh
306 | update_graph = False
307 | if isinstance(self.graph, graphs.TraditionalGraph):
308 | precomputed = self.graph.precomputed
309 | else:
310 | precomputed = None
311 | elif isinstance(X, pygsp.graphs.Graph):
312 | # convert pygsp to graphtools
313 | self.graph = None
314 | X = X.W
315 | precomputed = "adjacency"
316 | update_graph = False
317 | n_pca = None
318 | else:
319 | # data matrix
320 | update_graph = True
321 | if utils.is_Anndata(X):
322 | X = X.X
323 | if not callable(self.distance) and self.distance.startswith("precomputed"):
324 | if self.distance == "precomputed":
325 | # automatic detection
326 | precomputed = self._detect_precomputed_matrix_type(X)
327 | elif self.distance in ["precomputed_affinity", "precomputed_distance"]:
328 | precomputed = self.distance.split("_")[1]
329 | else:
330 | raise NotImplementedError
331 | n_pca = None
332 | else:
333 | precomputed = None
334 | n_pca = self._parse_n_pca(X, self.n_pca)
335 | return (
336 | X,
337 | n_pca,
338 | self._parse_n_landmark(X, self.n_landmark),
339 | precomputed,
340 | update_graph,
341 | )
342 |
343 | def _update_graph(self, X, precomputed, n_pca, n_landmark, **kwargs):
344 | if self.X is not None and not matrix.matrix_is_equivalent(X, self.X):
345 | """
346 | If the same data is used, we can reuse existing kernel and
347 | diffusion matrices. Otherwise we have to recompute.
348 | """
349 | self.graph = None
350 | else:
351 | self._update_n_landmark(n_landmark)
352 | self._set_graph_params(
353 | n_pca=n_pca,
354 | precomputed=precomputed,
355 | n_landmark=n_landmark,
356 | random_state=self.random_state,
357 | knn=self.knn,
358 | decay=self.decay,
359 | distance=self.distance,
360 | n_svd=self._parse_n_svd(self.X, self.n_svd),
361 | n_jobs=self.n_jobs,
362 | thresh=self.thresh,
363 | verbose=self.verbose,
364 | **(self.kwargs),
365 | )
366 | if self.graph is not None:
367 | _logger.log_info("Using precomputed graph and diffusion operator...")
368 |
369 | def fit(self, X, **kwargs):
370 | """Computes the graph
371 |
372 | Parameters
373 | ----------
374 | X : array, shape=[n_samples, n_features]
375 | input data with `n_samples` samples and `n_dimensions`
376 | dimensions. Accepted data types: `numpy.ndarray`,
377 | `scipy.sparse.spmatrix`, `pd.DataFrame`, `anndata.AnnData`. If
378 | `knn_dist` is 'precomputed', `data` should be a n_samples x
379 | n_samples distance or affinity matrix
380 |
381 | kwargs : additional arguments for graphtools.Graph
382 |
383 | Returns
384 | -------
385 | self : graphtools.estimator.GraphEstimator
386 | """
387 | X, n_pca, n_landmark, precomputed, update_graph = self._parse_input(X)
388 |
389 | if precomputed is None:
390 | _logger.log_info(
391 | "Building graph on {} samples and {} features.".format(
392 | X.shape[0], X.shape[1]
393 | )
394 | )
395 | else:
396 | _logger.log_info(
397 | "Building graph on precomputed {} matrix with {} samples.".format(
398 | precomputed, X.shape[0]
399 | )
400 | )
401 |
402 | if self.graph is not None and update_graph:
403 | self._update_graph(X, precomputed, n_pca, n_landmark)
404 |
405 | self.X = X
406 |
407 | if self.graph is None:
408 | with _logger.log_task("graph and diffusion operator"):
409 | self.graph = api.Graph(
410 | X,
411 | n_pca=n_pca,
412 | precomputed=precomputed,
413 | n_landmark=n_landmark,
414 | random_state=self.random_state,
415 | knn=self.knn,
416 | decay=self.decay,
417 | distance=self.distance,
418 | n_svd=self._parse_n_svd(self.X, self.n_svd),
419 | n_jobs=self.n_jobs,
420 | thresh=self.thresh,
421 | verbose=self.verbose,
422 | **(self.kwargs),
423 | **kwargs,
424 | )
425 | return self
426 |
--------------------------------------------------------------------------------
/graphtools/matrix.py:
--------------------------------------------------------------------------------
1 | from scipy import sparse
2 |
3 | import numbers
4 | import numpy as np
5 |
6 |
7 | def if_sparse(sparse_func, dense_func, *args, **kwargs):
8 | if sparse.issparse(args[0]):
9 | for arg in args[1:]:
10 | assert sparse.issparse(arg)
11 | return sparse_func(*args, **kwargs)
12 | else:
13 | return dense_func(*args, **kwargs)
14 |
15 |
16 | def sparse_minimum(X, Y):
17 | return X.minimum(Y)
18 |
19 |
20 | def sparse_maximum(X, Y):
21 | return X.maximum(Y)
22 |
23 |
24 | def elementwise_minimum(X, Y):
25 | return if_sparse(sparse_minimum, np.minimum, X, Y)
26 |
27 |
28 | def elementwise_maximum(X, Y):
29 | return if_sparse(sparse_maximum, np.maximum, X, Y)
30 |
31 |
32 | def dense_set_diagonal(X, diag):
33 | X[np.diag_indices(X.shape[0])] = diag
34 | return X
35 |
36 |
37 | def sparse_set_diagonal(X, diag):
38 | cls = type(X)
39 | if not isinstance(X, (sparse.lil_matrix, sparse.dia_matrix)):
40 | X = X.tocoo()
41 | X.setdiag(diag)
42 | return cls(X)
43 |
44 |
45 | def set_diagonal(X, diag):
46 | return if_sparse(sparse_set_diagonal, dense_set_diagonal, X, diag=diag)
47 |
48 |
49 | def set_submatrix(X, i, j, values):
50 | X[np.ix_(i, j)] = values
51 | return X
52 |
53 |
54 | def sparse_nonzero_discrete(X, values):
55 | if isinstance(
56 | X, (sparse.bsr_matrix, sparse.dia_matrix, sparse.dok_matrix, sparse.lil_matrix)
57 | ):
58 | X = X.tocsr()
59 | return dense_nonzero_discrete(X.data, values)
60 |
61 |
62 | def dense_nonzero_discrete(X, values):
63 | result = np.full_like(X, False, dtype=bool)
64 | for value in values:
65 | result = np.logical_or(result, X == value)
66 | return np.all(result)
67 |
68 |
69 | def nonzero_discrete(X, values):
70 | if isinstance(values, numbers.Number):
71 | values = [values]
72 | if 0 not in values:
73 | values.append(0)
74 | return if_sparse(sparse_nonzero_discrete, dense_nonzero_discrete, X, values=values)
75 |
76 |
77 | def to_array(X):
78 | if sparse.issparse(X):
79 | X = X.toarray()
80 | elif isinstance(X, np.matrix):
81 | X = X.A
82 | return X
83 |
84 |
85 | def matrix_is_equivalent(X, Y):
86 | """
87 | Checks matrix equivalence with numpy, scipy and pandas
88 | """
89 | return X is Y or (
90 | isinstance(X, Y.__class__)
91 | and X.shape == Y.shape
92 | and np.sum((X != Y).sum()) == 0
93 | )
94 |
--------------------------------------------------------------------------------
/graphtools/utils.py:
--------------------------------------------------------------------------------
1 | from . import matrix
2 | from deprecated import deprecated
3 |
4 | import numbers
5 | import warnings
6 |
7 | try:
8 | import pandas as pd
9 | except ImportError: # pragma: no cover
10 | # pandas not installed
11 | pass
12 |
13 | try:
14 | import anndata
15 | except ImportError: # pragma: no cover
16 | # anndata not installed
17 | pass
18 |
19 |
20 | def is_DataFrame(X):
21 | try:
22 | return isinstance(X, pd.DataFrame)
23 | except NameError: # pragma: no cover
24 | # pandas not installed
25 | return False
26 |
27 |
28 | def is_SparseDataFrame(X):
29 | try:
30 | pd
31 | except NameError: # pragma: no cover
32 | # pandas not installed
33 | return False
34 | with warnings.catch_warnings():
35 | warnings.filterwarnings(
36 | "ignore",
37 | "The SparseDataFrame class is removed from pandas. Accessing it from the top-level namespace will also be removed in the next version",
38 | FutureWarning,
39 | )
40 | try:
41 | return isinstance(X, pd.SparseDataFrame)
42 | except AttributeError:
43 | return False
44 |
45 |
46 | def is_Anndata(X):
47 | try:
48 | return isinstance(X, anndata.AnnData)
49 | except NameError: # pragma: no cover
50 | # anndata not installed
51 | return False
52 |
53 |
54 | def check_greater(x, **params):
55 | """Check that parameters are greater than x as expected
56 |
57 | Parameters
58 | ----------
59 |
60 | x : excepted boundary
61 | Checks not run if parameters are greater than x
62 |
63 | Raises
64 | ------
65 | ValueError : unacceptable choice of parameters
66 | """
67 | for p in params:
68 | if not isinstance(params[p], numbers.Number) or params[p] <= x:
69 | raise ValueError("Expected {} > {}, got {}".format(p, x, params[p]))
70 |
71 |
72 | def check_positive(**params):
73 | """Check that parameters are positive as expected
74 |
75 | Raises
76 | ------
77 | ValueError : unacceptable choice of parameters
78 | """
79 | return check_greater(0, **params)
80 |
81 |
82 | def check_int(**params):
83 | """Check that parameters are integers as expected
84 |
85 | Raises
86 | ------
87 | ValueError : unacceptable choice of parameters
88 | """
89 | for p in params:
90 | if not isinstance(params[p], numbers.Integral):
91 | raise ValueError("Expected {} integer, got {}".format(p, params[p]))
92 |
93 |
94 | def check_if_not(x, *checks, **params):
95 | """Run checks only if parameters are not equal to a specified value
96 |
97 | Parameters
98 | ----------
99 |
100 | x : excepted value
101 | Checks not run if parameters equal x
102 |
103 | checks : function
104 | Unnamed arguments, check functions to be run
105 |
106 | params : object
107 | Named arguments, parameters to be checked
108 |
109 | Raises
110 | ------
111 | ValueError : unacceptable choice of parameters
112 | """
113 | for p in params:
114 | if params[p] is not x and params[p] != x:
115 | [check(**{p: params[p]}) for check in checks]
116 |
117 |
118 | def check_in(choices, **params):
119 | """Checks parameters are in a list of allowed parameters
120 |
121 | Parameters
122 | ----------
123 |
124 | choices : array-like, accepted values
125 |
126 | params : object
127 | Named arguments, parameters to be checked
128 |
129 | Raises
130 | ------
131 | ValueError : unacceptable choice of parameters
132 | """
133 | for p in params:
134 | if params[p] not in choices:
135 | raise ValueError(
136 | "{} value {} not recognized. Choose from {}".format(
137 | p, params[p], choices
138 | )
139 | )
140 |
141 |
142 | def check_between(v_min, v_max, **params):
143 | """Checks parameters are in a specified range
144 |
145 | Parameters
146 | ----------
147 |
148 | v_min : float, minimum allowed value (inclusive)
149 |
150 | v_max : float, maximum allowed value (inclusive)
151 |
152 | params : object
153 | Named arguments, parameters to be checked
154 |
155 | Raises
156 | ------
157 | ValueError : unacceptable choice of parameters
158 | """
159 | check_greater(v_min, v_max=v_max)
160 | for p in params:
161 | if params[p] < v_min or params[p] > v_max:
162 | raise ValueError(
163 | "Expected {} between {} and {}, "
164 | "got {}".format(p, v_min, v_max, params[p])
165 | )
166 |
167 |
168 | @deprecated(version="1.5.0", reason="Use graphtools.matrix.if_sparse instead")
169 | def if_sparse(*args, **kwargs):
170 | return matrix.if_sparse(*args, **kwargs)
171 |
172 |
173 | @deprecated(version="1.5.0", reason="Use graphtools.matrix.sparse_minimum instead")
174 | def sparse_minimum(*args, **kwargs):
175 | return matrix.sparse_minimum(*args, **kwargs)
176 |
177 |
178 | @deprecated(version="1.5.0", reason="Use graphtools.matrix.sparse_maximum instead")
179 | def sparse_maximum(*args, **kwargs):
180 | return matrix.sparse_maximum(*args, **kwargs)
181 |
182 |
183 | @deprecated(version="1.5.0", reason="Use graphtools.matrix.elementwise_minimum instead")
184 | def elementwise_minimum(*args, **kwargs):
185 | return matrix.elementwise_minimum(*args, **kwargs)
186 |
187 |
188 | @deprecated(version="1.5.0", reason="Use graphtools.matrix.elementwise_maximum instead")
189 | def elementwise_maximum(*args, **kwargs):
190 | return matrix.elementwise_maximum(*args, **kwargs)
191 |
192 |
193 | @deprecated(version="1.5.0", reason="Use graphtools.matrix.dense_set_diagonal instead")
194 | def dense_set_diagonal(*args, **kwargs):
195 | return matrix.dense_set_diagonal(*args, **kwargs)
196 |
197 |
198 | @deprecated(version="1.5.0", reason="Use graphtools.matrix.sparse_set_diagonal instead")
199 | def sparse_set_diagonal(*args, **kwargs):
200 | return matrix.sparse_set_diagonal(*args, **kwargs)
201 |
202 |
203 | @deprecated(version="1.5.0", reason="Use graphtools.matrix.set_diagonal instead")
204 | def set_diagonal(*args, **kwargs):
205 | return matrix.set_diagonal(*args, **kwargs)
206 |
207 |
208 | @deprecated(version="1.5.0", reason="Use graphtools.matrix.set_submatrix instead")
209 | def set_submatrix(*args, **kwargs):
210 | return matrix.set_submatrix(*args, **kwargs)
211 |
212 |
213 | @deprecated(
214 | version="1.5.0", reason="Use graphtools.matrix.sparse_nonzero_discrete instead"
215 | )
216 | def sparse_nonzero_discrete(*args, **kwargs):
217 | return matrix.sparse_nonzero_discrete(*args, **kwargs)
218 |
219 |
220 | @deprecated(
221 | version="1.5.0", reason="Use graphtools.matrix.dense_nonzero_discrete instead"
222 | )
223 | def dense_nonzero_discrete(*args, **kwargs):
224 | return matrix.dense_nonzero_discrete(*args, **kwargs)
225 |
226 |
227 | @deprecated(version="1.5.0", reason="Use graphtools.matrix.nonzero_discrete instead")
228 | def nonzero_discrete(*args, **kwargs):
229 | return matrix.nonzero_discrete(*args, **kwargs)
230 |
231 |
232 | @deprecated(version="1.5.0", reason="Use graphtools.matrix.to_array instead")
233 | def to_array(*args, **kwargs):
234 | return matrix.to_array(*args, **kwargs)
235 |
236 |
237 | @deprecated(
238 | version="1.5.0", reason="Use graphtools.matrix.matrix_is_equivalent instead"
239 | )
240 | def matrix_is_equivalent(*args, **kwargs):
241 | return matrix.matrix_is_equivalent(*args, **kwargs)
242 |
--------------------------------------------------------------------------------
/graphtools/version.py:
--------------------------------------------------------------------------------
1 | __version__ = "1.5.3"
2 |
--------------------------------------------------------------------------------
/requirements.txt:
--------------------------------------------------------------------------------
1 | numpy>=1.14.0
2 | scipy>=1.1.0
3 | pygsp>=>=0.5.1
4 | scikit-learn>=0.20.0
5 | future
6 | tasklogger>=1.0
7 | Deprecated
8 |
--------------------------------------------------------------------------------
/setup.cfg:
--------------------------------------------------------------------------------
1 | [metadata]
2 | license-file = LICENSE
3 |
4 | [flake8]
5 | ignore =
6 | # top-level module docstring
7 | D100, D104,
8 | # space before: conflicts with black
9 | E203,
10 | # import not in alphabetical: conflicts with isort
11 | H306
12 | per-file-ignores =
13 | # imported but unused
14 | __init__.py: F401
15 | # missing docstring in public function for methods, metrics, datasets
16 | openproblems/tasks/*/*/*.py: D103, E203
17 | openproblems/tasks/*/*/__init__.py: F401, D103
18 | max-line-length = 88
19 | exclude =
20 | .git,
21 | __pycache__,
22 | build,
23 | dist,
24 | Snakefile
25 |
26 | [isort]
27 | profile = black
28 | force_single_line = true
29 | force_alphabetical_sort = true
30 |
--------------------------------------------------------------------------------
/setup.py:
--------------------------------------------------------------------------------
1 | from setuptools import setup
2 |
3 | import os
4 | import sys
5 |
6 | install_requires = [
7 | "numpy>=1.14.0",
8 | "scipy>=1.1.0",
9 | "pygsp>=0.5.1",
10 | "scikit-learn>=0.20.0",
11 | "future",
12 | "tasklogger>=1.0",
13 | "Deprecated",
14 | ]
15 |
16 | test_requires = [
17 | "nose",
18 | "nose2",
19 | "pandas",
20 | "coverage",
21 | "coveralls",
22 | "python-igraph",
23 | "parameterized",
24 | "anndata",
25 | ]
26 |
27 | if sys.version_info[0] == 3:
28 | test_requires += ["anndata"]
29 |
30 | doc_requires = ["sphinx", "sphinxcontrib-napoleon", "sphinxcontrib-bibtex"]
31 |
32 | if sys.version_info[:2] < (3, 5):
33 | raise RuntimeError("Python version >=3.5 required.")
34 | elif sys.version_info[:2] >= (3, 6):
35 | test_requires += ["black"]
36 |
37 | version_py = os.path.join(os.path.dirname(__file__), "graphtools", "version.py")
38 | version = open(version_py).read().strip().split("=")[-1].replace('"', "").strip()
39 |
40 | readme = open("README.rst").read()
41 |
42 | setup(
43 | name="graphtools",
44 | version=version,
45 | description="graphtools",
46 | author="Scott Gigante, Daniel Burkhardt, and Jay Stanley, Yale University",
47 | author_email="scott.gigante@yale.edu",
48 | packages=[
49 | "graphtools",
50 | ],
51 | license="GNU General Public License Version 2",
52 | install_requires=install_requires,
53 | extras_require={"test": test_requires, "doc": doc_requires},
54 | test_suite="nose2.collector.collector",
55 | long_description=readme,
56 | url="https://github.com/KrishnaswamyLab/graphtools",
57 | download_url="https://github.com/KrishnaswamyLab/graphtools/archive/v{}.tar.gz".format(
58 | version
59 | ),
60 | keywords=[
61 | "graphs",
62 | "big-data",
63 | "signal processing",
64 | "manifold-learning",
65 | ],
66 | classifiers=[
67 | "Development Status :: 4 - Beta",
68 | "Environment :: Console",
69 | "Framework :: Jupyter",
70 | "Intended Audience :: Developers",
71 | "Intended Audience :: Science/Research",
72 | "Natural Language :: English",
73 | "Operating System :: MacOS :: MacOS X",
74 | "Operating System :: Microsoft :: Windows",
75 | "Operating System :: POSIX :: Linux",
76 | "Programming Language :: Python :: 2",
77 | "Programming Language :: Python :: 2.7",
78 | "Programming Language :: Python :: 3",
79 | "Programming Language :: Python :: 3.5",
80 | "Programming Language :: Python :: 3.6",
81 | "Topic :: Scientific/Engineering :: Mathematics",
82 | ],
83 | )
84 |
--------------------------------------------------------------------------------
/test/load_tests/__init__.py:
--------------------------------------------------------------------------------
1 | from nose.tools import assert_raises_regex
2 | from nose.tools import assert_warns_regex
3 | from scipy.spatial.distance import cdist
4 | from scipy.spatial.distance import pdist
5 | from scipy.spatial.distance import squareform
6 | from sklearn import datasets
7 | from sklearn.decomposition import PCA
8 | from sklearn.decomposition import TruncatedSVD
9 |
10 | import graphtools
11 | import nose2
12 | import numpy as np
13 | import pandas as pd
14 | import pygsp
15 | import re
16 | import scipy.sparse as sp
17 | import warnings
18 |
19 |
20 | def assert_warns_message(expected_warning, expected_message, *args, **kwargs):
21 | expected_regex = re.escape(expected_message)
22 | return assert_warns_regex(expected_warning, expected_regex, *args, **kwargs)
23 |
24 |
25 | def assert_raises_message(expected_warning, expected_message, *args, **kwargs):
26 | expected_regex = re.escape(expected_message)
27 | return assert_raises_regex(expected_warning, expected_regex, *args, **kwargs)
28 |
29 |
30 | def reset_warnings():
31 | warnings.resetwarnings()
32 | warnings.simplefilter("error")
33 | ignore_numpy_warning()
34 | ignore_igraph_warning()
35 | ignore_joblib_warning()
36 |
37 |
38 | def ignore_numpy_warning():
39 | warnings.filterwarnings(
40 | "ignore",
41 | category=PendingDeprecationWarning,
42 | message="the matrix subclass is not the recommended way to represent "
43 | "matrices or deal with linear algebra ",
44 | )
45 |
46 |
47 | def ignore_igraph_warning():
48 | warnings.filterwarnings(
49 | "ignore",
50 | category=DeprecationWarning,
51 | message="The SafeConfigParser class has been renamed to ConfigParser "
52 | "in Python 3.2. This alias will be removed in future versions. Use "
53 | "ConfigParser directly instead",
54 | )
55 | warnings.filterwarnings(
56 | "ignore",
57 | category=DeprecationWarning,
58 | message="Using or importing the ABCs from 'collections' instead of from "
59 | "'collections.abc' is deprecated since Python 3.3, and in 3.9 it will stop working",
60 | )
61 | warnings.filterwarnings(
62 | "ignore",
63 | category=DeprecationWarning,
64 | message="Using or importing the ABCs from 'collections' instead of from "
65 | "'collections.abc' is deprecated since Python 3.3,and in 3.9 it will stop working",
66 | )
67 | warnings.filterwarnings(
68 | "ignore",
69 | category=DeprecationWarning,
70 | message="Using or importing the ABCs from 'collections' instead of from "
71 | "'collections.abc' is deprecated, and in 3.8 it will stop working",
72 | )
73 |
74 |
75 | def ignore_joblib_warning():
76 | warnings.filterwarnings(
77 | "ignore",
78 | category=DeprecationWarning,
79 | message="check_pickle is deprecated in joblib 0.12 and will be removed"
80 | " in 0.13",
81 | )
82 |
83 |
84 | reset_warnings()
85 |
86 | global digits
87 | global data
88 | digits = datasets.load_digits()
89 | data = digits["data"]
90 |
91 |
92 | def generate_swiss_roll(n_samples=1000, noise=0.5, seed=42):
93 | generator = np.random.RandomState(seed)
94 | t = 1.5 * np.pi * (1 + 2 * generator.rand(1, n_samples))
95 | x = t * np.cos(t)
96 | y = t * np.sin(t)
97 | sample_idx = generator.choice([0, 1], n_samples, replace=True)
98 | z = sample_idx
99 | t = np.squeeze(t)
100 | X = np.concatenate((x, y))
101 | X += noise * generator.randn(2, n_samples)
102 | X = X.T[np.argsort(t)]
103 | X = np.hstack((X, z.reshape(n_samples, 1)))
104 | return X, sample_idx
105 |
106 |
107 | def build_graph(
108 | data,
109 | n_pca=20,
110 | thresh=0,
111 | decay=10,
112 | knn=3,
113 | random_state=42,
114 | sparse=False,
115 | graph_class=graphtools.Graph,
116 | verbose=0,
117 | **kwargs,
118 | ):
119 | if sparse:
120 | data = sp.coo_matrix(data)
121 | return graph_class(
122 | data,
123 | thresh=thresh,
124 | n_pca=n_pca,
125 | decay=decay,
126 | knn=knn,
127 | random_state=42,
128 | verbose=verbose,
129 | **kwargs,
130 | )
131 |
--------------------------------------------------------------------------------
/test/test_api.py:
--------------------------------------------------------------------------------
1 | from __future__ import print_function
2 |
3 | from load_tests import assert_raises_message
4 | from load_tests import assert_warns_message
5 | from load_tests import build_graph
6 | from load_tests import data
7 |
8 | import graphtools
9 | import igraph
10 | import numpy as np
11 | import os
12 | import pickle
13 | import tempfile
14 |
15 |
16 | def test_from_igraph():
17 | n = 100
18 | m = 500
19 | K = np.zeros((n, n))
20 | for _ in range(m):
21 | e = np.random.choice(n, 2, replace=False)
22 | K[e[0], e[1]] = K[e[1], e[0]] = 1
23 | g = igraph.Graph.Adjacency(K.tolist())
24 | G = graphtools.from_igraph(g, attribute=None)
25 | G2 = graphtools.Graph(K, precomputed="adjacency")
26 | assert np.all(G.K == G2.K)
27 |
28 |
29 | def test_from_igraph_weighted():
30 | n = 100
31 | m = 500
32 | K = np.zeros((n, n))
33 | for _ in range(m):
34 | e = np.random.choice(n, 2, replace=False)
35 | K[e[0], e[1]] = K[e[1], e[0]] = np.random.uniform(0, 1)
36 | g = igraph.Graph.Weighted_Adjacency(K.tolist())
37 | G = graphtools.from_igraph(g)
38 | G2 = graphtools.Graph(K, precomputed="adjacency")
39 | assert np.all(G.K == G2.K)
40 |
41 |
42 | def test_from_igraph_invalid_precomputed():
43 | with assert_warns_message(
44 | UserWarning,
45 | "Cannot build graph from igraph with precomputed=affinity. Use 'adjacency' instead.",
46 | ):
47 | n = 100
48 | m = 500
49 | K = np.zeros((n, n))
50 | for _ in range(m):
51 | e = np.random.choice(n, 2, replace=False)
52 | K[e[0], e[1]] = K[e[1], e[0]] = 1
53 | g = igraph.Graph.Adjacency(K.tolist())
54 | G = graphtools.from_igraph(g, attribute=None, precomputed="affinity")
55 |
56 |
57 | def test_from_igraph_invalid_attribute():
58 | with assert_warns_message(
59 | UserWarning, "Edge attribute invalid not found. Returning unweighted graph"
60 | ):
61 | n = 100
62 | m = 500
63 | K = np.zeros((n, n))
64 | for _ in range(m):
65 | e = np.random.choice(n, 2, replace=False)
66 | K[e[0], e[1]] = K[e[1], e[0]] = 1
67 | g = igraph.Graph.Adjacency(K.tolist())
68 | G = graphtools.from_igraph(g, attribute="invalid")
69 |
70 |
71 | def test_to_pygsp():
72 | G = build_graph(data)
73 | G2 = G.to_pygsp()
74 | assert isinstance(G2, graphtools.graphs.PyGSPGraph)
75 | assert np.all(G2.K == G.K)
76 |
77 |
78 | def test_to_igraph():
79 | G = build_graph(data, use_pygsp=True)
80 | G2 = G.to_igraph()
81 | assert isinstance(G2, igraph.Graph)
82 | assert np.all(np.array(G2.get_adjacency(attribute="weight").data) == G.W)
83 | G3 = build_graph(data, use_pygsp=False)
84 | G2 = G3.to_igraph()
85 | assert isinstance(G2, igraph.Graph)
86 | assert np.all(np.array(G2.get_adjacency(attribute="weight").data) == G.W)
87 |
88 |
89 | def test_pickle_io_knngraph():
90 | G = build_graph(data, knn=5, decay=None)
91 | with tempfile.TemporaryDirectory() as tempdir:
92 | path = os.path.join(tempdir, "tmp.pkl")
93 | G.to_pickle(path)
94 | G_prime = graphtools.read_pickle(path)
95 | assert isinstance(G_prime, type(G))
96 |
97 |
98 | def test_pickle_io_traditionalgraph():
99 | G = build_graph(data, knn=5, decay=10, thresh=0)
100 | with tempfile.TemporaryDirectory() as tempdir:
101 | path = os.path.join(tempdir, "tmp.pkl")
102 | G.to_pickle(path)
103 | G_prime = graphtools.read_pickle(path)
104 | assert isinstance(G_prime, type(G))
105 |
106 |
107 | def test_pickle_io_landmarkgraph():
108 | G = build_graph(data, knn=5, decay=None, n_landmark=data.shape[0] // 2)
109 | L = G.landmark_op
110 | with tempfile.TemporaryDirectory() as tempdir:
111 | path = os.path.join(tempdir, "tmp.pkl")
112 | G.to_pickle(path)
113 | G_prime = graphtools.read_pickle(path)
114 | assert isinstance(G_prime, type(G))
115 | np.testing.assert_array_equal(L, G_prime._landmark_op)
116 |
117 |
118 | def test_pickle_io_pygspgraph():
119 | G = build_graph(data, knn=5, decay=None, use_pygsp=True)
120 | with tempfile.TemporaryDirectory() as tempdir:
121 | path = os.path.join(tempdir, "tmp.pkl")
122 | G.to_pickle(path)
123 | G_prime = graphtools.read_pickle(path)
124 | assert isinstance(G_prime, type(G))
125 | assert G_prime.logger.name == G.logger.name
126 |
127 |
128 | def test_pickle_bad_pickle():
129 | with assert_warns_message(
130 | UserWarning, "Returning object that is not a graphtools.base.BaseGraph"
131 | ):
132 | with tempfile.TemporaryDirectory() as tempdir:
133 | path = os.path.join(tempdir, "tmp.pkl")
134 | with open(path, "wb") as f:
135 | pickle.dump("hello world", f)
136 | G = graphtools.read_pickle(path)
137 |
138 |
139 | def test_to_pygsp_invalid_precomputed():
140 | with assert_warns_message(
141 | UserWarning,
142 | "Cannot build PyGSPGraph with precomputed=adjacency. Using 'affinity' instead.",
143 | ):
144 | G = build_graph(data)
145 | G2 = G.to_pygsp(precomputed="adjacency")
146 |
147 |
148 | def test_to_pygsp_invalid_use_pygsp():
149 | with assert_warns_message(
150 | UserWarning, "Cannot build PyGSPGraph with use_pygsp=False. Use True instead."
151 | ):
152 | G = build_graph(data)
153 | G2 = G.to_pygsp(use_pygsp=False)
154 |
155 |
156 | #####################################################
157 | # Check parameters
158 | #####################################################
159 |
160 |
161 | def test_unknown_parameter():
162 | with assert_raises_message(
163 | TypeError, "__init__() got an unexpected keyword argument 'hello'"
164 | ):
165 | build_graph(data, hello="world")
166 |
167 |
168 | def test_invalid_graphtype():
169 | with assert_raises_message(
170 | ValueError,
171 | "graphtype 'hello world' not recognized. Choose from ['knn', 'mnn', 'exact', 'auto']",
172 | ):
173 | build_graph(data, graphtype="hello world")
174 |
--------------------------------------------------------------------------------
/test/test_data.py:
--------------------------------------------------------------------------------
1 | from __future__ import print_function
2 |
3 | from load_tests import assert_raises_message
4 | from load_tests import assert_warns_message
5 | from load_tests import build_graph
6 | from load_tests import data
7 | from load_tests import graphtools
8 | from load_tests import nose2
9 | from load_tests import np
10 | from load_tests import pd
11 | from load_tests import pdist
12 | from load_tests import sp
13 | from load_tests import squareform
14 | from nose.tools import assert_raises_regex
15 |
16 | import numbers
17 | import warnings
18 |
19 | try:
20 | import anndata
21 | except (ImportError, SyntaxError):
22 | # python2 support is missing
23 | with warnings.catch_warnings():
24 | warnings.filterwarnings("always")
25 | warnings.warn("Warning: failed to import anndata", ImportWarning)
26 | pass
27 |
28 | #####################################################
29 | # Check parameters
30 | #####################################################
31 |
32 |
33 | def test_1d_data():
34 | with assert_raises_message(
35 | ValueError,
36 | "Expected 2D array, got 1D array instead (shape: ({},).)".format(data.shape[0]),
37 | ):
38 | build_graph(data[:, 0])
39 | with assert_raises_message(
40 | ValueError,
41 | "Reshape your data either using array.reshape(-1, 1) "
42 | "if your data has a single feature or array.reshape(1, -1) if "
43 | "it contains a single sample.".format(data.shape[0]),
44 | ):
45 | build_graph(data[:, 0])
46 |
47 |
48 | def test_3d_data():
49 | with assert_raises_message(
50 | ValueError,
51 | "Expected 2D array, got 3D array instead (shape: ({0}, 64, 1).)".format(
52 | data.shape[0]
53 | ),
54 | ):
55 | build_graph(data[:, :, None])
56 |
57 |
58 | def test_0_n_pca():
59 | assert build_graph(data, n_pca=0).n_pca is None
60 | assert build_graph(data, n_pca=False).n_pca is None
61 |
62 |
63 | def test_badstring_n_pca():
64 | with assert_raises_message(
65 | ValueError,
66 | "n_pca must be an integer 0 <= n_pca < min(n_samples,n_features), or in [None, False, True, 'auto'].",
67 | ):
68 | build_graph(data, n_pca="foobar")
69 |
70 |
71 | def test_uncastable_n_pca():
72 | with assert_raises_message(
73 | ValueError,
74 | "n_pca was not an instance of numbers.Number, could not be cast to False, and not None. Please supply an integer 0 <= n_pca < min(n_samples,n_features) or None",
75 | ):
76 | build_graph(data, n_pca=[])
77 |
78 |
79 | def test_negative_n_pca():
80 | with assert_raises_message(
81 | ValueError,
82 | "n_pca cannot be negative. Please supply an integer 0 <= n_pca < min(n_samples,n_features) or None",
83 | ):
84 | build_graph(data, n_pca=-1)
85 |
86 |
87 | def test_badstring_rank_threshold():
88 | with assert_raises_message(
89 | ValueError, "rank_threshold must be positive float or 'auto'."
90 | ):
91 | build_graph(data, n_pca=True, rank_threshold="foobar")
92 |
93 |
94 | def test_negative_rank_threshold():
95 | with assert_raises_message(
96 | ValueError, "rank_threshold must be positive float or 'auto'."
97 | ):
98 | build_graph(data, n_pca=True, rank_threshold=-1)
99 |
100 |
101 | def test_True_n_pca_large_threshold():
102 | with assert_raises_regex(
103 | ValueError,
104 | r"Supplied threshold ([0-9\.]*) was greater than maximum singular value ([0-9\.]*) for the data matrix",
105 | ):
106 | build_graph(data, n_pca=True, rank_threshold=np.linalg.norm(data) ** 2)
107 |
108 |
109 | def test_threshold_ignored():
110 | with assert_warns_message(
111 | RuntimeWarning,
112 | "n_pca = 10, therefore rank_threshold of -1 will not be used. To use rank thresholding, set n_pca = True",
113 | ):
114 | assert build_graph(data, n_pca=10, rank_threshold=-1).n_pca == 10
115 |
116 |
117 | def test_invalid_threshold_negative():
118 | with assert_raises_message(
119 | ValueError, "rank_threshold must be positive float or 'auto'."
120 | ):
121 | build_graph(data, n_pca=True, rank_threshold=-1)
122 |
123 |
124 | def test_invalid_threshold_list():
125 | with assert_raises_message(
126 | ValueError, "rank_threshold must be positive float or 'auto'."
127 | ):
128 | build_graph(data, n_pca=True, rank_threshold=[])
129 |
130 |
131 | def test_True_n_pca():
132 | assert isinstance(build_graph(data, n_pca=True).n_pca, numbers.Number)
133 |
134 |
135 | def test_True_n_pca_manual_rank_threshold():
136 | g = build_graph(data, n_pca=True, rank_threshold=0.1)
137 | assert isinstance(g.n_pca, numbers.Number)
138 | assert isinstance(g.rank_threshold, numbers.Number)
139 |
140 |
141 | def test_True_n_pca_auto_rank_threshold():
142 | g = build_graph(data, n_pca=True, rank_threshold="auto")
143 | assert isinstance(g.n_pca, numbers.Number)
144 | assert isinstance(g.rank_threshold, numbers.Number)
145 | next_threshold = np.sort(g.data_pca.singular_values_)[2]
146 | g2 = build_graph(data, n_pca=True, rank_threshold=next_threshold)
147 | assert g.n_pca > g2.n_pca
148 |
149 |
150 | def test_goodstring_rank_threshold():
151 | build_graph(data, n_pca=True, rank_threshold="auto")
152 | build_graph(data, n_pca=True, rank_threshold="AUTO")
153 |
154 |
155 | def test_string_n_pca():
156 | build_graph(data, n_pca="auto")
157 | build_graph(data, n_pca="AUTO")
158 |
159 |
160 | def test_fractional_n_pca():
161 | with assert_warns_message(
162 | RuntimeWarning, "Cannot perform PCA to fractional 1.5 dimensions. Rounding to 2"
163 | ):
164 | build_graph(data, n_pca=1.5)
165 |
166 |
167 | def test_too_many_n_pca():
168 | with assert_warns_message(
169 | RuntimeWarning,
170 | "Cannot perform PCA to {0} dimensions on data with min(n_samples, n_features) = {0}".format(
171 | data.shape[1]
172 | ),
173 | ):
174 | build_graph(data, n_pca=data.shape[1])
175 |
176 |
177 | def test_too_many_n_pca2():
178 | with assert_warns_message(
179 | RuntimeWarning,
180 | "Cannot perform PCA to {0} dimensions on data with min(n_samples, n_features) = {0}".format(
181 | data.shape[1] - 1
182 | ),
183 | ):
184 | build_graph(data[: data.shape[1] - 1], n_pca=data.shape[1] - 1)
185 |
186 |
187 | def test_precomputed_with_pca():
188 | with assert_warns_message(
189 | RuntimeWarning,
190 | "n_pca cannot be given on a precomputed graph. Setting n_pca=None",
191 | ):
192 | build_graph(squareform(pdist(data)), precomputed="distance", n_pca=20)
193 |
194 |
195 | #####################################################
196 | # Check data types
197 | #####################################################
198 |
199 |
200 | def test_pandas_dataframe():
201 | G = build_graph(pd.DataFrame(data))
202 | assert isinstance(G, graphtools.base.BaseGraph)
203 | assert isinstance(G.data, np.ndarray)
204 |
205 |
206 | def test_pandas_sparse_dataframe():
207 | try:
208 | X = pd.DataFrame(data).astype(pd.SparseDtype(float, fill_value=0))
209 | except AttributeError:
210 | X = pd.SparseDataFrame(data, default_fill_value=0)
211 | G = build_graph(X)
212 | assert isinstance(G, graphtools.base.BaseGraph)
213 | assert isinstance(G.data, sp.csr_matrix)
214 |
215 |
216 | def test_anndata():
217 | try:
218 | anndata
219 | except NameError:
220 | # not installed
221 | return
222 | G = build_graph(anndata.AnnData(data, dtype=data.dtype))
223 | assert isinstance(G, graphtools.base.BaseGraph)
224 | assert isinstance(G.data, np.ndarray)
225 |
226 |
227 | def test_anndata_sparse():
228 | try:
229 | anndata
230 | except NameError:
231 | # not installed
232 | return
233 | G = build_graph(anndata.AnnData(sp.csr_matrix(data), dtype=data.dtype))
234 | assert isinstance(G, graphtools.base.BaseGraph)
235 | assert isinstance(G.data, sp.csr_matrix)
236 |
237 |
238 | #####################################################
239 | # Check transform
240 | #####################################################
241 |
242 |
243 | def test_transform_dense_pca():
244 | G = build_graph(data, n_pca=20)
245 | assert np.all(G.data_nu == G.transform(G.data))
246 | with assert_raises_message(
247 | ValueError,
248 | "data of shape ({0},) cannot be transformed to graph built on data of shape ({0}, {1}). Expected shape ({0}, {1})".format(
249 | G.data.shape[0], G.data.shape[1]
250 | ),
251 | ):
252 | G.transform(G.data[:, 0])
253 | with assert_raises_message(
254 | ValueError,
255 | "data of shape ({0}, 1, 15) cannot be transformed to graph built on data of shape ({0}, {1}). Expected shape ({0}, {1})".format(
256 | G.data.shape[0], G.data.shape[1]
257 | ),
258 | ):
259 | G.transform(G.data[:, None, :15])
260 | with assert_raises_message(
261 | ValueError,
262 | "data of shape ({0}, 15) cannot be transformed to graph built on data of shape ({0}, {1}). Expected shape ({0}, {1})".format(
263 | G.data.shape[0], G.data.shape[1]
264 | ),
265 | ):
266 | G.transform(G.data[:, :15])
267 |
268 |
269 | def test_transform_dense_no_pca():
270 | G = build_graph(data, n_pca=None)
271 | assert np.all(G.data_nu == G.transform(G.data))
272 | with assert_raises_message(
273 | ValueError,
274 | "data of shape ({0},) cannot be transformed to graph built on data of shape ({0}, {1})".format(
275 | data.shape[0], data.shape[1]
276 | ),
277 | ):
278 | G.transform(G.data[:, 0])
279 | with assert_raises_message(
280 | ValueError,
281 | "data of shape ({0}, 1, 15) cannot be transformed to graph built on data of shape ({0}, {1})".format(
282 | data.shape[0], data.shape[1]
283 | ),
284 | ):
285 | G.transform(G.data[:, None, :15])
286 | with assert_raises_message(
287 | ValueError,
288 | "data of shape ({0}, 15) cannot be transformed to graph built on data of shape ({0}, {1})".format(
289 | data.shape[0], data.shape[1]
290 | ),
291 | ):
292 | G.transform(G.data[:, :15])
293 |
294 |
295 | def test_transform_sparse_pca():
296 | G = build_graph(data, sparse=True, n_pca=20)
297 | assert np.all(G.data_nu == G.transform(G.data))
298 | with assert_raises_message(
299 | ValueError,
300 | "data of shape ({0}, 1) cannot be transformed to graph built on data of shape ({0}, {1}). Expected shape ({0}, {1})".format(
301 | G.data.shape[0], G.data.shape[1]
302 | ),
303 | ):
304 | G.transform(sp.csr_matrix(G.data)[:, 0])
305 | with assert_raises_message(
306 | ValueError,
307 | "data of shape ({0}, 15) cannot be transformed to graph built on data of shape ({0}, {1}). Expected shape ({0}, {1})".format(
308 | G.data.shape[0], G.data.shape[1]
309 | ),
310 | ):
311 | G.transform(sp.csr_matrix(G.data)[:, :15])
312 |
313 |
314 | def test_transform_sparse_no_pca():
315 | G = build_graph(data, sparse=True, n_pca=None)
316 | assert np.sum(G.data_nu != G.transform(G.data)) == 0
317 | with assert_raises_message(
318 | ValueError,
319 | "data of shape {} cannot be transformed to graph built on data of shape {}".format(
320 | G.data.tocsr()[:, 0].shape, G.data.shape
321 | ),
322 | ):
323 | G.transform(sp.csr_matrix(G.data)[:, 0])
324 | with assert_raises_message(
325 | ValueError,
326 | "data of shape {} cannot be transformed to graph built on data of shape {}".format(
327 | G.data.tocsr()[:, :15].shape, G.data.shape
328 | ),
329 | ):
330 | G.transform(sp.csr_matrix(G.data)[:, :15])
331 |
332 |
333 | #####################################################
334 | # Check inverse transform
335 | #####################################################
336 |
337 |
338 | def test_inverse_transform_dense_pca():
339 | G = build_graph(data, n_pca=data.shape[1] - 1)
340 | np.testing.assert_allclose(G.data, G.inverse_transform(G.data_nu), atol=1e-12)
341 | np.testing.assert_allclose(
342 | G.data[:, -1, None], G.inverse_transform(G.data_nu, columns=-1), atol=1e-12
343 | )
344 | np.testing.assert_allclose(
345 | G.data[:, 5:7], G.inverse_transform(G.data_nu, columns=[5, 6]), atol=1e-12
346 | )
347 | with assert_raises_message(
348 | IndexError,
349 | "index {0} is out of bounds for axis 1 with size {0}".format(G.data.shape[1]),
350 | ):
351 | G.inverse_transform(G.data_nu, columns=data.shape[1])
352 | with assert_raises_message(
353 | ValueError,
354 | "data of shape ({0},) cannot be inverse transformed from graph built on reduced data of shape ({0}, {1})".format(
355 | G.data.shape[0], G.n_pca
356 | ),
357 | ):
358 | G.inverse_transform(G.data[:, 0])
359 | with assert_raises_message(
360 | ValueError,
361 | "data of shape ({0}, 1, 15) cannot be inverse transformed from graph built on reduced data of shape ({0}, {1})".format(
362 | G.data.shape[0], G.n_pca
363 | ),
364 | ):
365 | G.inverse_transform(G.data[:, None, :15])
366 | with assert_raises_message(
367 | ValueError,
368 | "data of shape ({0}, 15) cannot be inverse transformed from graph built on reduced data of shape ({0}, {1})".format(
369 | G.data.shape[0], G.n_pca
370 | ),
371 | ):
372 | G.inverse_transform(G.data[:, :15])
373 |
374 |
375 | def test_inverse_transform_sparse_svd():
376 | G = build_graph(data, sparse=True, n_pca=data.shape[1] - 1)
377 | np.testing.assert_allclose(data, G.inverse_transform(G.data_nu), atol=1e-12)
378 | np.testing.assert_allclose(
379 | data[:, -1, None], G.inverse_transform(G.data_nu, columns=-1), atol=1e-12
380 | )
381 | np.testing.assert_allclose(
382 | data[:, 5:7], G.inverse_transform(G.data_nu, columns=[5, 6]), atol=1e-12
383 | )
384 | with assert_raises_message(
385 | IndexError, "index 64 is out of bounds for axis 1 with size 64"
386 | ):
387 | G.inverse_transform(G.data_nu, columns=data.shape[1])
388 | with assert_raises_message(
389 | TypeError,
390 | "A sparse matrix was passed, but dense data is required. Use X.toarray() to convert to a dense numpy array.",
391 | ):
392 | G.inverse_transform(sp.csr_matrix(G.data)[:, 0])
393 | with assert_raises_message(
394 | TypeError,
395 | "A sparse matrix was passed, but dense data is required. Use X.toarray() to convert to a dense numpy array.",
396 | ):
397 | G.inverse_transform(sp.csr_matrix(G.data)[:, :15])
398 | with assert_raises_message(
399 | ValueError,
400 | "data of shape ({0},) cannot be inverse transformed from graph built on reduced data of shape ({0}, {1}). Expected shape ({0}, {1})".format(
401 | data.shape[0], G.n_pca
402 | ),
403 | ):
404 | G.inverse_transform(data[:, 0])
405 | with assert_raises_message(
406 | ValueError,
407 | "data of shape ({0}, 15) cannot be inverse transformed from graph built on reduced data of shape ({0}, {1}). Expected shape ({0}, {1})".format(
408 | data.shape[0], G.n_pca
409 | ),
410 | ):
411 | G.inverse_transform(data[:, :15])
412 |
413 |
414 | def test_inverse_transform_dense_no_pca():
415 | G = build_graph(data, n_pca=None)
416 | np.testing.assert_allclose(
417 | data[:, 5:7], G.inverse_transform(G.data_nu, columns=[5, 6]), atol=1e-12
418 | )
419 | assert np.all(G.data == G.inverse_transform(G.data_nu))
420 | with assert_raises_message(
421 | ValueError,
422 | "data of shape ({0},) cannot be inverse transformed from graph built on reduced data of shape ({0}, {1})".format(
423 | data.shape[0], G.data.shape[1]
424 | ),
425 | ):
426 | G.inverse_transform(G.data[:, 0])
427 | with assert_raises_message(
428 | ValueError,
429 | "data of shape ({0}, 1, 15) cannot be inverse transformed from graph built on reduced data of shape ({0}, {1})".format(
430 | data.shape[0], data.shape[1]
431 | ),
432 | ):
433 | G.inverse_transform(G.data[:, None, :15])
434 | with assert_raises_message(
435 | ValueError,
436 | "data of shape ({0}, 15) cannot be inverse transformed from graph built on reduced data of shape ({0}, {1})".format(
437 | data.shape[0], data.shape[1]
438 | ),
439 | ):
440 | G.inverse_transform(G.data[:, :15])
441 |
442 |
443 | def test_inverse_transform_sparse_no_pca():
444 | G = build_graph(data, sparse=True, n_pca=None)
445 | assert np.sum(G.data != G.inverse_transform(G.data_nu)) == 0
446 | with assert_raises_message(
447 | ValueError,
448 | "data of shape ({0}, 1) cannot be inverse transformed from graph built on reduced data of shape ({0}, {1})".format(
449 | G.data.shape[0], G.data.shape[1]
450 | ),
451 | ):
452 | G.inverse_transform(sp.csr_matrix(G.data)[:, 0])
453 | with assert_raises_message(
454 | ValueError,
455 | "data of shape ({0}, 15) cannot be inverse transformed from graph built on reduced data of shape ({0}, {1})".format(
456 | G.data.shape[0], G.data.shape[1]
457 | ),
458 | ):
459 | G.inverse_transform(sp.csr_matrix(G.data)[:, :15])
460 |
461 |
462 | #####################################################
463 | # Check adaptive PCA with rank thresholding
464 | #####################################################
465 |
466 |
467 | def test_transform_adaptive_pca():
468 | G = build_graph(data, n_pca=True, random_state=42)
469 | assert np.all(G.data_nu == G.transform(G.data))
470 | with assert_raises_message(
471 | ValueError,
472 | "data of shape ({0},) cannot be transformed to graph built on data of shape ({0}, {1}). Expected shape ({0}, {1})".format(
473 | G.data.shape[0], G.data.shape[1]
474 | ),
475 | ):
476 | G.transform(G.data[:, 0])
477 | with assert_raises_message(
478 | ValueError,
479 | "data of shape ({0}, 1, 15) cannot be transformed to graph built on data of shape ({0}, {1}). Expected shape ({0}, {1})".format(
480 | G.data.shape[0], G.data.shape[1]
481 | ),
482 | ):
483 | G.transform(G.data[:, None, :15])
484 | with assert_raises_message(
485 | ValueError,
486 | "data of shape ({0}, 15) cannot be transformed to graph built on data of shape ({0}, {1}). Expected shape ({0}, {1})".format(
487 | G.data.shape[0], G.data.shape[1]
488 | ),
489 | ):
490 | G.transform(G.data[:, :15])
491 |
492 | G2 = build_graph(data, n_pca=True, rank_threshold=G.rank_threshold, random_state=42)
493 | assert np.allclose(G2.data_nu, G2.transform(G2.data))
494 | assert np.allclose(G2.data_nu, G.transform(G.data))
495 |
496 | G3 = build_graph(data, n_pca=G2.n_pca, random_state=42)
497 |
498 | assert np.allclose(G3.data_nu, G3.transform(G3.data))
499 | assert np.allclose(G3.data_nu, G2.transform(G2.data))
500 |
501 |
502 | def test_transform_sparse_adaptive_pca():
503 | G = build_graph(data, sparse=True, n_pca=True, random_state=42)
504 | assert np.all(G.data_nu == G.transform(G.data))
505 | with assert_raises_message(
506 | ValueError,
507 | "data of shape ({0}, 1) cannot be transformed to graph built on data of shape ({0}, {1}). Expected shape ({0}, {1})".format(
508 | G.data.shape[0], G.data.shape[1]
509 | ),
510 | ):
511 | G.transform(sp.csr_matrix(G.data)[:, 0])
512 | with assert_raises_message(
513 | ValueError,
514 | "data of shape ({0}, 15) cannot be transformed to graph built on data of shape ({0}, {1}). Expected shape ({0}, {1})".format(
515 | G.data.shape[0], G.data.shape[1]
516 | ),
517 | ):
518 | G.transform(sp.csr_matrix(G.data)[:, :15])
519 |
520 | G2 = build_graph(
521 | data, sparse=True, n_pca=True, rank_threshold=G.rank_threshold, random_state=42
522 | )
523 | assert np.allclose(G2.data_nu, G2.transform(G2.data))
524 | assert np.allclose(G2.data_nu, G.transform(G.data))
525 |
526 | G3 = build_graph(data, sparse=True, n_pca=G2.n_pca, random_state=42)
527 | assert np.allclose(G3.data_nu, G3.transform(G3.data))
528 | assert np.allclose(G3.data_nu, G2.transform(G2.data))
529 |
530 |
531 | #############
532 | # Test API
533 | #############
534 |
535 |
536 | def test_set_params():
537 | G = graphtools.base.Data(data, n_pca=20)
538 | assert G.get_params() == {"n_pca": 20, "random_state": None}
539 | G.set_params(random_state=13)
540 | assert G.random_state == 13
541 | with assert_raises_message(
542 | ValueError, "Cannot update n_pca. Please create a new graph"
543 | ):
544 | G.set_params(n_pca=10)
545 | G.set_params(n_pca=G.n_pca)
546 |
--------------------------------------------------------------------------------
/test/test_estimator.py:
--------------------------------------------------------------------------------
1 | from load_tests import assert_raises_message
2 | from load_tests import data
3 | from parameterized import parameterized
4 | from scipy import sparse
5 |
6 | import anndata
7 | import graphtools
8 | import graphtools.estimator
9 | import numpy as np
10 | import pygsp
11 | import warnings
12 |
13 |
14 | class Estimator(graphtools.estimator.GraphEstimator):
15 | def _reset_graph(self):
16 | self.reset = True
17 |
18 |
19 | def test_estimator():
20 | E = Estimator(verbose=True)
21 | assert E.verbose == 1
22 | E = Estimator(verbose=False)
23 | assert E.verbose == 0
24 | E.fit(data)
25 | assert np.all(E.X == data)
26 | assert isinstance(E.graph, graphtools.graphs.kNNGraph)
27 | assert not isinstance(E.graph, graphtools.graphs.LandmarkGraph)
28 | assert not hasattr(E, "reset")
29 | # convert non landmark to landmark
30 | E.set_params(n_landmark=data.shape[0] // 2)
31 | assert E.reset
32 | assert isinstance(E.graph, graphtools.graphs.LandmarkGraph)
33 | del E.reset
34 | # convert landmark to non landmark
35 | E.set_params(n_landmark=None)
36 | assert E.reset
37 | assert not isinstance(E.graph, graphtools.graphs.LandmarkGraph)
38 | del E.reset
39 | # change parameters that force reset
40 | E.set_params(knn=E.knn * 2)
41 | assert E.reset
42 | assert E.graph is None
43 |
44 |
45 | @parameterized(
46 | [
47 | ("precomputed", 1 - np.eye(10), "distance"),
48 | ("precomputed", np.eye(10), "affinity"),
49 | ("precomputed", sparse.coo_matrix(1 - np.eye(10)), "distance"),
50 | ("precomputed", sparse.eye(10), "affinity"),
51 | ("precomputed_affinity", 1 - np.eye(10), "affinity"),
52 | ("precomputed_distance", np.ones((10, 10)), "distance"),
53 | ]
54 | )
55 | def test_precomputed(distance, X, precomputed):
56 | E = Estimator(verbose=False, distance=distance)
57 | with warnings.catch_warnings():
58 | warnings.filterwarnings("ignore", message="K should have a non-zero diagonal")
59 | E.fit(X)
60 | assert isinstance(E.graph, graphtools.graphs.TraditionalGraph)
61 | assert E.graph.precomputed == precomputed
62 |
63 |
64 | def test_graph_input():
65 | X = np.random.normal(0, 1, (10, 2))
66 | E = Estimator(verbose=0)
67 | G = graphtools.Graph(X)
68 | E.fit(G)
69 | assert E.graph == G
70 | G = graphtools.Graph(X, knn=2, decay=5, distance="cosine", thresh=0)
71 | E.fit(G)
72 | assert E.graph == G
73 | assert E.knn == G.knn
74 | assert E.decay == G.decay
75 | assert E.distance == G.distance
76 | assert E.thresh == G.thresh
77 | W = G.K - np.eye(X.shape[0])
78 | G = pygsp.graphs.Graph(W)
79 | E.fit(G, use_pygsp=True)
80 | assert np.all(E.graph.W.toarray() == W)
81 |
82 |
83 | def test_pca():
84 | X = np.random.normal(0, 1, (10, 6))
85 | E = Estimator(verbose=0)
86 | E.fit(X)
87 | G = E.graph
88 | E.set_params(n_pca=100)
89 | E.fit(X)
90 | assert E.graph is G
91 | E.set_params(n_pca=3)
92 | E.fit(X)
93 | assert E.graph is not G
94 | assert E.graph.n_pca == 3
95 |
96 |
97 | def test_anndata_input():
98 | X = np.random.normal(0, 1, (10, 2))
99 | E = Estimator(verbose=0)
100 | E.fit(X.astype(np.float32))
101 | E2 = Estimator(verbose=0)
102 | E2.fit(anndata.AnnData(X, dtype=X.dtype))
103 | np.testing.assert_allclose(
104 | E.graph.K.toarray(), E2.graph.K.toarray(), rtol=1e-6, atol=2e-7
105 | )
106 |
107 |
108 | def test_new_input():
109 | X = np.random.normal(0, 1, (10, 2))
110 | X2 = np.random.normal(0, 1, (10, 2))
111 | E = Estimator(verbose=0)
112 | E.fit(X)
113 | G = E.graph
114 | E.fit(X)
115 | assert E.graph is G
116 | E.fit(X.copy())
117 | assert E.graph is G
118 | E.n_landmark = 500
119 | E.fit(X)
120 | assert E.graph is G
121 | E.n_landmark = 5
122 | E.fit(X)
123 | assert np.all(E.graph.K.toarray() == G.K.toarray())
124 | G = E.graph
125 | E.fit(X2)
126 | assert E.graph is not G
127 |
--------------------------------------------------------------------------------
/test/test_exact.py:
--------------------------------------------------------------------------------
1 | from __future__ import print_function
2 |
3 | from load_tests import assert_raises_message
4 | from load_tests import assert_warns_message
5 | from load_tests import build_graph
6 | from load_tests import data
7 | from load_tests import graphtools
8 | from load_tests import nose2
9 | from load_tests import np
10 | from load_tests import PCA
11 | from load_tests import pdist
12 | from load_tests import pygsp
13 | from load_tests import sp
14 | from load_tests import squareform
15 | from load_tests import TruncatedSVD
16 | from nose.tools import assert_warns_regex
17 | from scipy.sparse.csgraph import shortest_path
18 |
19 | #####################################################
20 | # Check parameters
21 | #####################################################
22 |
23 |
24 | def test_sample_idx_and_precomputed():
25 | with assert_raises_message(
26 | ValueError,
27 | "MNNGraph does not support precomputed values. Use `graphtype='exact'` and `sample_idx=None` or `precomputed=None`",
28 | ):
29 | build_graph(
30 | squareform(pdist(data)),
31 | n_pca=None,
32 | sample_idx=np.arange(10),
33 | precomputed="distance",
34 | decay=10,
35 | )
36 |
37 |
38 | def test_precomputed_not_square():
39 | with assert_raises_message(
40 | ValueError, "Precomputed distance must be a square matrix. (1797, 64) was given"
41 | ):
42 | build_graph(data, n_pca=None, precomputed="distance", decay=10)
43 |
44 |
45 | def test_build_exact_with_sample_idx():
46 | with assert_raises_message(
47 | ValueError,
48 | "TraditionalGraph does not support batch correction. Use `graphtype='mnn'` or `sample_idx=None`",
49 | ):
50 | build_graph(data, graphtype="exact", sample_idx=np.arange(len(data)), decay=10)
51 |
52 |
53 | def test_precomputed_with_pca():
54 | with assert_warns_message(
55 | RuntimeWarning,
56 | "n_pca cannot be given on a precomputed graph. Setting n_pca=None",
57 | ):
58 | build_graph(squareform(pdist(data)), precomputed="distance", n_pca=20, decay=10)
59 |
60 |
61 | def test_exact_no_decay():
62 | with assert_raises_message(
63 | ValueError,
64 | "`decay` must be provided for a TraditionalGraph. For kNN kernel, use kNNGraph.",
65 | ):
66 | build_graph(data, graphtype="exact", decay=None)
67 |
68 |
69 | def test_exact_no_knn_no_bandwidth():
70 | with assert_raises_message(
71 | ValueError, "Either `knn` or `bandwidth` must be provided."
72 | ):
73 | build_graph(data, graphtype="exact", knn=None, bandwidth=None)
74 |
75 |
76 | def test_precomputed_negative():
77 | with assert_raises_message(
78 | ValueError, "Precomputed distance should be non-negative"
79 | ):
80 | build_graph(
81 | np.random.normal(0, 1, [200, 200]), precomputed="distance", n_pca=None
82 | )
83 |
84 |
85 | def test_precomputed_invalid():
86 | with assert_raises_message(
87 | ValueError,
88 | "Precomputed value invalid not recognized. Choose from ['distance', 'affinity', 'adjacency']",
89 | ):
90 | build_graph(
91 | np.random.uniform(0, 1, [200, 200]), precomputed="invalid", n_pca=None
92 | )
93 |
94 |
95 | def test_precomputed_nonzero_diagonal():
96 | with assert_warns_message(RuntimeWarning, "K should have a non-zero diagonal"):
97 | build_graph(np.zeros((10, 10)), precomputed="affinity", n_pca=None)
98 |
99 |
100 | def test_duplicate_data():
101 | with assert_warns_regex(
102 | RuntimeWarning,
103 | r"Detected zero distance between samples ([0-9and,\s]*). Consider removing duplicates to avoid errors in downstream processing.",
104 | ):
105 | build_graph(np.vstack([data, data[:10]]), n_pca=20, decay=10, thresh=0)
106 |
107 |
108 | def test_many_duplicate_data():
109 | with assert_warns_regex(
110 | RuntimeWarning,
111 | "Detected zero distance between ([0-9]*) pairs of samples. Consider removing duplicates to avoid errors in downstream processing.",
112 | ):
113 | build_graph(np.vstack([data, data]), n_pca=20, decay=10, thresh=0)
114 |
115 |
116 | def test_k_too_large():
117 | with assert_warns_message(
118 | UserWarning,
119 | "Cannot set knn ({0}) to be greater than n_samples - 2 ({1}). Setting knn={1}".format(
120 | data.shape[0] - 1, data.shape[0] - 2
121 | ),
122 | ):
123 | build_graph(data, n_pca=20, decay=10, knn=len(data) - 1, thresh=0)
124 |
125 |
126 | #####################################################
127 | # Check kernel
128 | #####################################################
129 |
130 |
131 | def test_exact_graph():
132 | k = 3
133 | a = 13
134 | n_pca = 20
135 | bandwidth_scale = 1.3
136 | data_small = data[np.random.choice(len(data), len(data) // 2, replace=False)]
137 | pca = PCA(n_pca, svd_solver="randomized", random_state=42).fit(data_small)
138 | data_small_nu = pca.transform(data_small)
139 | pdx = squareform(pdist(data_small_nu, metric="euclidean"))
140 | knn_dist = np.partition(pdx, k, axis=1)[:, :k]
141 | epsilon = np.max(knn_dist, axis=1) * bandwidth_scale
142 | weighted_pdx = (pdx.T / epsilon).T
143 | K = np.exp(-1 * weighted_pdx**a)
144 | W = K + K.T
145 | W = np.divide(W, 2)
146 | np.fill_diagonal(W, 0)
147 | G = pygsp.graphs.Graph(W)
148 | G2 = build_graph(
149 | data_small,
150 | thresh=0,
151 | n_pca=n_pca,
152 | decay=a,
153 | knn=k - 1,
154 | random_state=42,
155 | bandwidth_scale=bandwidth_scale,
156 | use_pygsp=True,
157 | )
158 | assert G.N == G2.N
159 | np.testing.assert_equal(G.dw, G2.dw)
160 | assert (G.W != G2.W).nnz == 0
161 | assert (G2.W != G.W).sum() == 0
162 | assert isinstance(G2, graphtools.graphs.TraditionalGraph)
163 | G2 = build_graph(
164 | pdx,
165 | n_pca=None,
166 | precomputed="distance",
167 | bandwidth_scale=bandwidth_scale,
168 | decay=a,
169 | knn=k - 1,
170 | random_state=42,
171 | use_pygsp=True,
172 | )
173 | assert G.N == G2.N
174 | np.testing.assert_equal(G.dw, G2.dw)
175 | assert (G.W != G2.W).nnz == 0
176 | assert (G2.W != G.W).sum() == 0
177 | assert isinstance(G2, graphtools.graphs.TraditionalGraph)
178 | G2 = build_graph(
179 | sp.coo_matrix(K),
180 | n_pca=None,
181 | precomputed="affinity",
182 | random_state=42,
183 | use_pygsp=True,
184 | )
185 | assert G.N == G2.N
186 | np.testing.assert_equal(G.dw, G2.dw)
187 | assert (G.W != G2.W).nnz == 0
188 | assert (G2.W != G.W).sum() == 0
189 | assert isinstance(G2, graphtools.graphs.TraditionalGraph)
190 | G2 = build_graph(
191 | K, n_pca=None, precomputed="affinity", random_state=42, use_pygsp=True
192 | )
193 | assert G.N == G2.N
194 | np.testing.assert_equal(G.dw, G2.dw)
195 | assert (G.W != G2.W).nnz == 0
196 | assert (G2.W != G.W).sum() == 0
197 | assert isinstance(G2, graphtools.graphs.TraditionalGraph)
198 | G2 = build_graph(
199 | W, n_pca=None, precomputed="adjacency", random_state=42, use_pygsp=True
200 | )
201 | assert G.N == G2.N
202 | np.testing.assert_equal(G.dw, G2.dw)
203 | assert (G.W != G2.W).nnz == 0
204 | assert (G2.W != G.W).sum() == 0
205 | assert isinstance(G2, graphtools.graphs.TraditionalGraph)
206 |
207 |
208 | def test_truncated_exact_graph():
209 | k = 3
210 | a = 13
211 | n_pca = 20
212 | thresh = 1e-4
213 | data_small = data[np.random.choice(len(data), len(data) // 2, replace=False)]
214 | pca = PCA(n_pca, svd_solver="randomized", random_state=42).fit(data_small)
215 | data_small_nu = pca.transform(data_small)
216 | pdx = squareform(pdist(data_small_nu, metric="euclidean"))
217 | knn_dist = np.partition(pdx, k, axis=1)[:, :k]
218 | epsilon = np.max(knn_dist, axis=1)
219 | weighted_pdx = (pdx.T / epsilon).T
220 | K = np.exp(-1 * weighted_pdx**a)
221 | K[K < thresh] = 0
222 | W = K + K.T
223 | W = np.divide(W, 2)
224 | np.fill_diagonal(W, 0)
225 | G = pygsp.graphs.Graph(W)
226 | G2 = build_graph(
227 | data_small,
228 | thresh=thresh,
229 | graphtype="exact",
230 | n_pca=n_pca,
231 | decay=a,
232 | knn=k - 1,
233 | random_state=42,
234 | use_pygsp=True,
235 | )
236 | assert G.N == G2.N
237 | np.testing.assert_equal(G.dw, G2.dw)
238 | assert (G.W != G2.W).nnz == 0
239 | assert (G2.W != G.W).sum() == 0
240 | assert isinstance(G2, graphtools.graphs.TraditionalGraph)
241 | G2 = build_graph(
242 | pdx,
243 | n_pca=None,
244 | precomputed="distance",
245 | thresh=thresh,
246 | decay=a,
247 | knn=k - 1,
248 | random_state=42,
249 | use_pygsp=True,
250 | )
251 | assert G.N == G2.N
252 | np.testing.assert_equal(G.dw, G2.dw)
253 | assert (G.W != G2.W).nnz == 0
254 | assert (G2.W != G.W).sum() == 0
255 | assert isinstance(G2, graphtools.graphs.TraditionalGraph)
256 | G2 = build_graph(
257 | K,
258 | n_pca=None,
259 | precomputed="affinity",
260 | thresh=thresh,
261 | random_state=42,
262 | use_pygsp=True,
263 | )
264 | assert G.N == G2.N
265 | np.testing.assert_equal(G.dw, G2.dw)
266 | assert (G.W != G2.W).nnz == 0
267 | assert (G2.W != G.W).sum() == 0
268 | assert isinstance(G2, graphtools.graphs.TraditionalGraph)
269 | G2 = build_graph(
270 | W, n_pca=None, precomputed="adjacency", random_state=42, use_pygsp=True
271 | )
272 | assert G.N == G2.N
273 | np.testing.assert_equal(G.dw, G2.dw)
274 | assert (G.W != G2.W).nnz == 0
275 | assert (G2.W != G.W).sum() == 0
276 | assert isinstance(G2, graphtools.graphs.TraditionalGraph)
277 |
278 |
279 | def test_truncated_exact_graph_sparse():
280 | k = 3
281 | a = 13
282 | n_pca = 20
283 | thresh = 1e-4
284 | data_small = data[np.random.choice(len(data), len(data) // 2, replace=False)]
285 | pca = TruncatedSVD(n_pca, random_state=42).fit(data_small)
286 | data_small_nu = pca.transform(data_small)
287 | pdx = squareform(pdist(data_small_nu, metric="euclidean"))
288 | knn_dist = np.partition(pdx, k, axis=1)[:, :k]
289 | epsilon = np.max(knn_dist, axis=1)
290 | weighted_pdx = (pdx.T / epsilon).T
291 | K = np.exp(-1 * weighted_pdx**a)
292 | K[K < thresh] = 0
293 | W = K + K.T
294 | W = np.divide(W, 2)
295 | np.fill_diagonal(W, 0)
296 | G = pygsp.graphs.Graph(W)
297 | G2 = build_graph(
298 | sp.coo_matrix(data_small),
299 | thresh=thresh,
300 | graphtype="exact",
301 | n_pca=n_pca,
302 | decay=a,
303 | knn=k - 1,
304 | random_state=42,
305 | use_pygsp=True,
306 | )
307 | assert G.N == G2.N
308 | np.testing.assert_allclose(G2.W.toarray(), G.W.toarray())
309 | assert isinstance(G2, graphtools.graphs.TraditionalGraph)
310 | G2 = build_graph(
311 | sp.bsr_matrix(pdx),
312 | n_pca=None,
313 | precomputed="distance",
314 | thresh=thresh,
315 | decay=a,
316 | knn=k - 1,
317 | random_state=42,
318 | use_pygsp=True,
319 | )
320 | assert G.N == G2.N
321 | np.testing.assert_equal(G.dw, G2.dw)
322 | assert (G.W != G2.W).nnz == 0
323 | assert (G2.W != G.W).sum() == 0
324 | assert isinstance(G2, graphtools.graphs.TraditionalGraph)
325 | G2 = build_graph(
326 | sp.lil_matrix(K),
327 | n_pca=None,
328 | precomputed="affinity",
329 | thresh=thresh,
330 | random_state=42,
331 | use_pygsp=True,
332 | )
333 | assert G.N == G2.N
334 | np.testing.assert_equal(G.dw, G2.dw)
335 | assert (G.W != G2.W).nnz == 0
336 | assert (G2.W != G.W).sum() == 0
337 | assert isinstance(G2, graphtools.graphs.TraditionalGraph)
338 | G2 = build_graph(
339 | sp.dok_matrix(W),
340 | n_pca=None,
341 | precomputed="adjacency",
342 | random_state=42,
343 | use_pygsp=True,
344 | )
345 | assert G.N == G2.N
346 | np.testing.assert_equal(G.dw, G2.dw)
347 | assert (G.W != G2.W).nnz == 0
348 | assert (G2.W != G.W).sum() == 0
349 | assert isinstance(G2, graphtools.graphs.TraditionalGraph)
350 |
351 |
352 | def test_truncated_exact_graph_no_pca():
353 | k = 3
354 | a = 13
355 | n_pca = None
356 | thresh = 1e-4
357 | data_small = data[np.random.choice(len(data), len(data) // 10, replace=False)]
358 | pdx = squareform(pdist(data_small, metric="euclidean"))
359 | knn_dist = np.partition(pdx, k, axis=1)[:, :k]
360 | epsilon = np.max(knn_dist, axis=1)
361 | weighted_pdx = (pdx.T / epsilon).T
362 | K = np.exp(-1 * weighted_pdx**a)
363 | K[K < thresh] = 0
364 | W = K + K.T
365 | W = np.divide(W, 2)
366 | np.fill_diagonal(W, 0)
367 | G = pygsp.graphs.Graph(W)
368 | G2 = build_graph(
369 | data_small,
370 | thresh=thresh,
371 | graphtype="exact",
372 | n_pca=n_pca,
373 | decay=a,
374 | knn=k - 1,
375 | random_state=42,
376 | use_pygsp=True,
377 | )
378 | assert G.N == G2.N
379 | np.testing.assert_equal(G.dw, G2.dw)
380 | assert (G.W != G2.W).nnz == 0
381 | assert (G2.W != G.W).sum() == 0
382 | assert isinstance(G2, graphtools.graphs.TraditionalGraph)
383 | G2 = build_graph(
384 | sp.csr_matrix(data_small),
385 | thresh=thresh,
386 | graphtype="exact",
387 | n_pca=n_pca,
388 | decay=a,
389 | knn=k - 1,
390 | random_state=42,
391 | use_pygsp=True,
392 | )
393 | assert G.N == G2.N
394 | np.testing.assert_equal(G.dw, G2.dw)
395 | assert (G.W != G2.W).nnz == 0
396 | assert (G2.W != G.W).sum() == 0
397 | assert isinstance(G2, graphtools.graphs.TraditionalGraph)
398 |
399 |
400 | def test_exact_graph_fixed_bandwidth():
401 | decay = 2
402 | knn = None
403 | bandwidth = 2
404 | n_pca = 20
405 | pca = PCA(n_pca, svd_solver="randomized", random_state=42).fit(data)
406 | data_nu = pca.transform(data)
407 | pdx = squareform(pdist(data_nu, metric="euclidean"))
408 | K = np.exp(-1 * (pdx / bandwidth) ** decay)
409 | K = K + K.T
410 | W = np.divide(K, 2)
411 | np.fill_diagonal(W, 0)
412 | G = pygsp.graphs.Graph(W)
413 | G2 = build_graph(
414 | data,
415 | n_pca=n_pca,
416 | graphtype="exact",
417 | knn=knn,
418 | decay=decay,
419 | bandwidth=bandwidth,
420 | random_state=42,
421 | thresh=0,
422 | use_pygsp=True,
423 | )
424 | assert isinstance(G2, graphtools.graphs.TraditionalGraph)
425 | assert G.N == G2.N
426 | np.testing.assert_allclose(G.dw, G2.dw)
427 | np.testing.assert_allclose((G2.W - G.W).data, 0, atol=1e-14)
428 | bandwidth = np.random.gamma(5, 0.5, len(data))
429 | K = np.exp(-1 * (pdx.T / bandwidth).T ** decay)
430 | K = K + K.T
431 | W = np.divide(K, 2)
432 | np.fill_diagonal(W, 0)
433 | G = pygsp.graphs.Graph(W)
434 | G2 = build_graph(
435 | data,
436 | n_pca=n_pca,
437 | graphtype="exact",
438 | knn=knn,
439 | decay=decay,
440 | bandwidth=bandwidth,
441 | random_state=42,
442 | thresh=0,
443 | use_pygsp=True,
444 | )
445 | assert isinstance(G2, graphtools.graphs.TraditionalGraph)
446 | assert G.N == G2.N
447 | np.testing.assert_allclose(G.dw, G2.dw)
448 | np.testing.assert_allclose((G2.W - G.W).data, 0, atol=1e-14)
449 |
450 |
451 | def test_exact_graph_callable_bandwidth():
452 | decay = 2
453 | knn = 5
454 |
455 | def bandwidth(x):
456 | return 2
457 |
458 | n_pca = 20
459 | thresh = 1e-4
460 | pca = PCA(n_pca, svd_solver="randomized", random_state=42).fit(data)
461 | data_nu = pca.transform(data)
462 | pdx = squareform(pdist(data_nu, metric="euclidean"))
463 | K = np.exp(-1 * (pdx / bandwidth(pdx)) ** decay)
464 | K[K < thresh] = 0
465 | K = K + K.T
466 | W = np.divide(K, 2)
467 | np.fill_diagonal(W, 0)
468 | G = pygsp.graphs.Graph(W)
469 | G2 = build_graph(
470 | data,
471 | n_pca=n_pca,
472 | knn=knn - 1,
473 | decay=decay,
474 | bandwidth=bandwidth,
475 | random_state=42,
476 | thresh=thresh,
477 | use_pygsp=True,
478 | )
479 | assert isinstance(G2, graphtools.graphs.TraditionalGraph)
480 | assert G.N == G2.N
481 | np.testing.assert_equal(G.dw, G2.dw)
482 | assert (G2.W != G.W).sum() == 0
483 | assert (G.W != G2.W).nnz == 0
484 |
485 | def bandwidth(x):
486 | return np.percentile(x, 10, axis=1)
487 |
488 | K = np.exp(-1 * (pdx / bandwidth(pdx)) ** decay)
489 | K[K < thresh] = 0
490 | K = K + K.T
491 | W = np.divide(K, 2)
492 | np.fill_diagonal(W, 0)
493 | G = pygsp.graphs.Graph(W)
494 | G2 = build_graph(
495 | data,
496 | n_pca=n_pca,
497 | knn=knn - 1,
498 | decay=decay,
499 | bandwidth=bandwidth,
500 | random_state=42,
501 | thresh=thresh,
502 | use_pygsp=True,
503 | )
504 | assert isinstance(G2, graphtools.graphs.TraditionalGraph)
505 | assert G.N == G2.N
506 | np.testing.assert_allclose(G.dw, G2.dw)
507 | np.testing.assert_allclose((G2.W - G.W).data, 0, atol=1e-14)
508 |
509 |
510 | #####################################################
511 | # Check anisotropy
512 | #####################################################
513 |
514 |
515 | def test_exact_graph_anisotropy():
516 | k = 3
517 | a = 13
518 | n_pca = 20
519 | anisotropy = 0.9
520 | data_small = data[np.random.choice(len(data), len(data) // 2, replace=False)]
521 | pca = PCA(n_pca, svd_solver="randomized", random_state=42).fit(data_small)
522 | data_small_nu = pca.transform(data_small)
523 | pdx = squareform(pdist(data_small_nu, metric="euclidean"))
524 | knn_dist = np.partition(pdx, k, axis=1)[:, :k]
525 | epsilon = np.max(knn_dist, axis=1)
526 | weighted_pdx = (pdx.T / epsilon).T
527 | K = np.exp(-1 * weighted_pdx**a)
528 | K = K + K.T
529 | K = np.divide(K, 2)
530 | d = K.sum(1)
531 | W = K / (np.outer(d, d) ** anisotropy)
532 | np.fill_diagonal(W, 0)
533 | G = pygsp.graphs.Graph(W)
534 | G2 = build_graph(
535 | data_small,
536 | thresh=0,
537 | n_pca=n_pca,
538 | decay=a,
539 | knn=k - 1,
540 | random_state=42,
541 | use_pygsp=True,
542 | anisotropy=anisotropy,
543 | )
544 | assert isinstance(G2, graphtools.graphs.TraditionalGraph)
545 | assert G.N == G2.N
546 | np.testing.assert_equal(G.dw, G2.dw)
547 | assert (G2.W != G.W).sum() == 0
548 | assert (G.W != G2.W).nnz == 0
549 | with assert_raises_message(ValueError, "Expected 0 <= anisotropy <= 1. Got -1"):
550 | build_graph(
551 | data_small,
552 | thresh=0,
553 | n_pca=n_pca,
554 | decay=a,
555 | knn=k - 1,
556 | random_state=42,
557 | use_pygsp=True,
558 | anisotropy=-1,
559 | )
560 | with assert_raises_message(ValueError, "Expected 0 <= anisotropy <= 1. Got 2"):
561 | build_graph(
562 | data_small,
563 | thresh=0,
564 | n_pca=n_pca,
565 | decay=a,
566 | knn=k - 1,
567 | random_state=42,
568 | use_pygsp=True,
569 | anisotropy=2,
570 | )
571 | with assert_raises_message(
572 | ValueError, "Expected 0 <= anisotropy <= 1. Got invalid"
573 | ):
574 | build_graph(
575 | data_small,
576 | thresh=0,
577 | n_pca=n_pca,
578 | decay=a,
579 | knn=k - 1,
580 | random_state=42,
581 | use_pygsp=True,
582 | anisotropy="invalid",
583 | )
584 |
585 |
586 | #####################################################
587 | # Check extra functionality
588 | #####################################################
589 |
590 |
591 | def test_shortest_path_affinity():
592 | np.random.seed(42)
593 | data_small = data[np.random.choice(len(data), len(data) // 4, replace=False)]
594 | G = build_graph(data_small, knn=5, decay=15)
595 | D = -1 * np.where(G.K != 0, np.log(np.where(G.K != 0, G.K, np.nan)), 0)
596 | P = shortest_path(D)
597 | # sklearn returns 0 if no path exists
598 | P[np.where(P == 0)] = np.inf
599 | # diagonal should actually be zero
600 | np.fill_diagonal(P, 0)
601 | np.testing.assert_allclose(
602 | P, G.shortest_path(distance="affinity"), atol=1e-4, rtol=1e-3
603 | )
604 | np.testing.assert_allclose(P, G.shortest_path(), atol=1e-4, rtol=1e-3)
605 |
606 |
607 | def test_shortest_path_affinity_precomputed():
608 | np.random.seed(42)
609 | data_small = data[np.random.choice(len(data), len(data) // 4, replace=False)]
610 | G = build_graph(data_small, knn=5, decay=15)
611 | G = graphtools.Graph(G.K, precomputed="affinity")
612 | D = -1 * np.where(G.K != 0, np.log(np.where(G.K != 0, G.K, np.nan)), 0)
613 | P = shortest_path(D)
614 | # sklearn returns 0 if no path exists
615 | P[np.where(P == 0)] = np.inf
616 | # diagonal should actually be zero
617 | np.fill_diagonal(P, 0)
618 | np.testing.assert_allclose(
619 | P, G.shortest_path(distance="affinity"), atol=1e-4, rtol=1e-3
620 | )
621 | np.testing.assert_allclose(P, G.shortest_path(), atol=1e-4, rtol=1e-3)
622 |
623 |
624 | def test_shortest_path_decay_constant():
625 | with assert_raises_message(
626 | NotImplementedError,
627 | "Graph shortest path with constant distance only implemented for unweighted graphs. For weighted graphs, use `distance='affinity'`.",
628 | ):
629 | data_small = data[np.random.choice(len(data), len(data) // 4, replace=False)]
630 | G = build_graph(data_small, knn=5, decay=15)
631 | G.shortest_path(distance="constant")
632 |
633 |
634 | def test_shortest_path_precomputed_decay_constant():
635 | with assert_raises_message(
636 | NotImplementedError,
637 | "Graph shortest path with constant distance only implemented for unweighted graphs. For weighted graphs, use `distance='affinity'`.",
638 | ):
639 | data_small = data[np.random.choice(len(data), len(data) // 4, replace=False)]
640 | G = build_graph(data_small, knn=5, decay=15)
641 | G = graphtools.Graph(G.K, precomputed="affinity")
642 | G.shortest_path(distance="constant")
643 |
644 |
645 | def test_shortest_path_decay_data():
646 | with assert_raises_message(
647 | NotImplementedError,
648 | "Graph shortest path with constant or data distance only implemented for unweighted graphs. For weighted graphs, use `distance='affinity'`.",
649 | ):
650 | data_small = data[np.random.choice(len(data), len(data) // 4, replace=False)]
651 | G = build_graph(data_small, knn=5, decay=15)
652 | G.shortest_path(distance="data")
653 |
654 |
655 | def test_shortest_path_precomputed_data():
656 | with assert_raises_message(
657 | ValueError,
658 | "Graph shortest path with data distance not valid for precomputed graphs. For precomputed graphs, use `distance='constant'` for unweighted graphs and `distance='affinity'` for weighted graphs.",
659 | ):
660 | data_small = data[np.random.choice(len(data), len(data) // 4, replace=False)]
661 | G = build_graph(data_small, knn=5, decay=15)
662 | G = graphtools.Graph(G.K, precomputed="affinity")
663 | G.shortest_path(distance="data")
664 |
665 |
666 | #####################################################
667 | # Check interpolation
668 | #####################################################
669 |
670 |
671 | def test_build_dense_exact_kernel_to_data(**kwargs):
672 | G = build_graph(data, decay=10, thresh=0)
673 | n = G.data.shape[0]
674 | K = G.build_kernel_to_data(data[: n // 2, :])
675 | assert K.shape == (n // 2, n)
676 | K = G.build_kernel_to_data(G.data, knn=G.knn + 1)
677 | np.testing.assert_equal(G.kernel - (K + K.T) / 2, 0)
678 | K = G.build_kernel_to_data(G.data_nu, knn=G.knn + 1)
679 | np.testing.assert_equal(G.kernel - (K + K.T) / 2, 0)
680 |
681 |
682 | def test_build_dense_exact_callable_bw_kernel_to_data(**kwargs):
683 | G = build_graph(data, decay=10, thresh=0, bandwidth=lambda x: x.mean(1))
684 | n = G.data.shape[0]
685 | K = G.build_kernel_to_data(data[: n // 2, :])
686 | assert K.shape == (n // 2, n)
687 | K = G.build_kernel_to_data(G.data, knn=G.knn + 1)
688 | np.testing.assert_equal(G.kernel - (K + K.T) / 2, 0)
689 | K = G.build_kernel_to_data(G.data_nu, knn=G.knn + 1)
690 | np.testing.assert_equal(G.kernel - (K + K.T) / 2, 0)
691 |
692 |
693 | def test_build_sparse_exact_kernel_to_data(**kwargs):
694 | G = build_graph(data, decay=10, thresh=0, sparse=True)
695 | n = G.data.shape[0]
696 | K = G.build_kernel_to_data(data[: n // 2, :])
697 | assert K.shape == (n // 2, n)
698 | K = G.build_kernel_to_data(G.data, knn=G.knn + 1)
699 | np.testing.assert_equal(G.kernel - (K + K.T) / 2, 0)
700 | K = G.build_kernel_to_data(G.data_nu, knn=G.knn + 1)
701 | np.testing.assert_equal(G.kernel - (K + K.T) / 2, 0)
702 |
703 |
704 | def test_exact_interpolate():
705 | G = build_graph(data, decay=10, thresh=0)
706 | with assert_raises_message(
707 | ValueError, "Either `transitions` or `Y` must be provided."
708 | ):
709 | G.interpolate(data)
710 | pca_data = PCA(2).fit_transform(data)
711 | transitions = G.extend_to_data(data)
712 | assert np.all(
713 | G.interpolate(pca_data, Y=data)
714 | == G.interpolate(pca_data, transitions=transitions)
715 | )
716 |
717 |
718 | def test_precomputed_interpolate():
719 | with assert_raises_message(ValueError, "Cannot extend kernel on precomputed graph"):
720 | G = build_graph(squareform(pdist(data)), n_pca=None, precomputed="distance")
721 | G.build_kernel_to_data(data)
722 |
723 |
724 | ####################
725 | # Test API
726 | ####################
727 |
728 |
729 | def test_verbose():
730 | print()
731 | print("Verbose test: Exact")
732 | build_graph(data, decay=10, thresh=0, verbose=True)
733 |
734 |
735 | def test_set_params():
736 | G = build_graph(data, decay=10, thresh=0)
737 | assert G.get_params() == {
738 | "n_pca": 20,
739 | "random_state": 42,
740 | "kernel_symm": "+",
741 | "theta": None,
742 | "knn": 3,
743 | "anisotropy": 0,
744 | "decay": 10,
745 | "bandwidth": None,
746 | "bandwidth_scale": 1,
747 | "distance": "euclidean",
748 | "precomputed": None,
749 | }
750 | with assert_raises_message(
751 | ValueError, "Cannot update knn. Please create a new graph"
752 | ):
753 | G.set_params(knn=15)
754 | with assert_raises_message(
755 | ValueError, "Cannot update decay. Please create a new graph"
756 | ):
757 | G.set_params(decay=15)
758 | with assert_raises_message(
759 | ValueError, "Cannot update distance. Please create a new graph"
760 | ):
761 | G.set_params(distance="manhattan")
762 | with assert_raises_message(
763 | ValueError, "Cannot update precomputed. Please create a new graph"
764 | ):
765 | G.set_params(precomputed="distance")
766 | with assert_raises_message(
767 | ValueError, "Cannot update bandwidth. Please create a new graph"
768 | ):
769 | G.set_params(bandwidth=5)
770 | with assert_raises_message(
771 | ValueError, "Cannot update bandwidth_scale. Please create a new graph"
772 | ):
773 | G.set_params(bandwidth_scale=5)
774 | G.set_params(
775 | knn=G.knn, decay=G.decay, distance=G.distance, precomputed=G.precomputed
776 | )
777 |
--------------------------------------------------------------------------------
/test/test_knn.py:
--------------------------------------------------------------------------------
1 | from __future__ import division
2 | from __future__ import print_function
3 |
4 | from load_tests import assert_raises_message
5 | from load_tests import assert_warns_message
6 | from load_tests import build_graph
7 | from load_tests import data
8 | from load_tests import datasets
9 | from load_tests import graphtools
10 | from load_tests import np
11 | from load_tests import PCA
12 | from load_tests import pygsp
13 | from load_tests import sp
14 | from load_tests import TruncatedSVD
15 | from nose.tools import assert_raises_regex
16 | from nose.tools import assert_warns_regex
17 | from scipy.sparse.csgraph import shortest_path
18 | from scipy.spatial.distance import pdist
19 | from scipy.spatial.distance import squareform
20 |
21 | import warnings
22 |
23 | #####################################################
24 | # Check parameters
25 | #####################################################
26 |
27 |
28 | def test_build_knn_with_exact_alpha():
29 | with assert_raises_message(
30 | ValueError,
31 | "Cannot instantiate a kNNGraph with `decay=None`, `thresh=0` and `knn_max=None`. Use a TraditionalGraph instead.",
32 | ):
33 | build_graph(data, graphtype="knn", decay=10, thresh=0)
34 |
35 |
36 | def test_build_knn_with_precomputed():
37 | with assert_raises_message(
38 | ValueError,
39 | "kNNGraph does not support precomputed values. Use `graphtype='exact'` or `precomputed=None`",
40 | ):
41 | build_graph(data, n_pca=None, graphtype="knn", precomputed="distance")
42 |
43 |
44 | def test_build_knn_with_sample_idx():
45 | with assert_raises_message(
46 | ValueError,
47 | "kNNGraph does not support batch correction. Use `graphtype='mnn'` or `sample_idx=None`",
48 | ):
49 | build_graph(data, graphtype="knn", sample_idx=np.arange(len(data)))
50 |
51 |
52 | def test_duplicate_data():
53 | with assert_warns_regex(
54 | RuntimeWarning,
55 | r"Detected zero distance between samples ([0-9and,\s]*). Consider removing duplicates to avoid errors in downstream processing.",
56 | ):
57 | build_graph(np.vstack([data, data[:9]]), n_pca=None, decay=10, thresh=1e-4)
58 |
59 |
60 | def test_duplicate_data_many():
61 | with assert_warns_regex(
62 | RuntimeWarning,
63 | "Detected zero distance between ([0-9]*) pairs of samples. Consider removing duplicates to avoid errors in downstream processing.",
64 | ):
65 | build_graph(np.vstack([data, data[:21]]), n_pca=None, decay=10, thresh=1e-4)
66 |
67 |
68 | def test_balltree_cosine():
69 | with assert_warns_message(
70 | UserWarning,
71 | "Metric cosine not valid for `sklearn.neighbors.BallTree`. Graph instantiation may be slower than normal.",
72 | ):
73 | build_graph(data, n_pca=20, decay=10, distance="cosine", thresh=1e-4)
74 |
75 |
76 | def test_k_too_large():
77 | with assert_warns_message(
78 | UserWarning,
79 | "Cannot set knn ({1}) to be greater than n_samples - 2 ({0}). Setting knn={0}".format(
80 | data.shape[0] - 2, data.shape[0] - 1
81 | ),
82 | ):
83 | build_graph(data, n_pca=20, decay=10, knn=len(data) - 1, thresh=1e-4)
84 |
85 |
86 | def test_knnmax_too_large():
87 | with assert_warns_message(
88 | UserWarning,
89 | "Cannot set knn_max (9) to be less than knn (10). Setting knn_max=10",
90 | ):
91 | build_graph(data, n_pca=20, decay=10, knn=10, knn_max=9, thresh=1e-4)
92 |
93 |
94 | def test_bandwidth_no_decay():
95 | with assert_warns_message(
96 | UserWarning, "`bandwidth` is not used when `decay=None`."
97 | ):
98 | build_graph(data, n_pca=20, decay=None, bandwidth=3, thresh=1e-4)
99 |
100 |
101 | def test_knn_no_knn_no_bandwidth():
102 | with assert_raises_message(
103 | ValueError, "Either `knn` or `bandwidth` must be provided."
104 | ):
105 | build_graph(data, graphtype="knn", knn=None, bandwidth=None, thresh=1e-4)
106 |
107 |
108 | def test_knn_graph_invalid_symm():
109 | with assert_raises_message(
110 | ValueError,
111 | "kernel_symm 'invalid' not recognized. Choose from '+', '*', 'mnn', or 'none'.",
112 | ):
113 | build_graph(data, graphtype="knn", knn=5, thresh=1e-4, kernel_symm="invalid")
114 |
115 |
116 | #####################################################
117 | # Check kernel
118 | #####################################################
119 |
120 |
121 | def test_knn_graph():
122 | k = 3
123 | n_pca = 20
124 | pca = PCA(n_pca, svd_solver="randomized", random_state=42).fit(data)
125 | data_nu = pca.transform(data)
126 | pdx = squareform(pdist(data_nu, metric="euclidean"))
127 | knn_dist = np.partition(pdx, k, axis=1)[:, :k]
128 | epsilon = np.max(knn_dist, axis=1)
129 | K = np.empty_like(pdx)
130 | for i in range(len(pdx)):
131 | K[i, pdx[i, :] <= epsilon[i]] = 1
132 | K[i, pdx[i, :] > epsilon[i]] = 0
133 |
134 | K = K + K.T
135 | W = np.divide(K, 2)
136 | np.fill_diagonal(W, 0)
137 | G = pygsp.graphs.Graph(W)
138 | G2 = build_graph(
139 | data, n_pca=n_pca, decay=None, knn=k - 1, random_state=42, use_pygsp=True
140 | )
141 | assert G.N == G2.N
142 | np.testing.assert_equal(G.dw, G2.dw)
143 | assert (G.W - G2.W).nnz == 0
144 | assert (G2.W - G.W).sum() == 0
145 | assert isinstance(G2, graphtools.graphs.kNNGraph)
146 |
147 | K2 = G2.build_kernel_to_data(G2.data_nu, knn=k)
148 | K2 = (K2 + K2.T) / 2
149 | assert (G2.K - K2).nnz == 0
150 | assert (
151 | G2.build_kernel_to_data(G2.data_nu, knn=data.shape[0]).nnz
152 | == data.shape[0] * data.shape[0]
153 | )
154 | with assert_warns_message(
155 | UserWarning,
156 | "Cannot set knn ({}) to be greater than "
157 | "n_samples ({}). Setting knn={}".format(
158 | data.shape[0] + 1, data.shape[0], data.shape[0]
159 | ),
160 | ):
161 | G2.build_kernel_to_data(
162 | Y=G2.data_nu,
163 | knn=data.shape[0] + 1,
164 | )
165 |
166 |
167 | def test_knn_graph_multiplication_symm():
168 | k = 3
169 | n_pca = 20
170 | pca = PCA(n_pca, svd_solver="randomized", random_state=42).fit(data)
171 | data_nu = pca.transform(data)
172 | pdx = squareform(pdist(data_nu, metric="euclidean"))
173 | knn_dist = np.partition(pdx, k, axis=1)[:, :k]
174 | epsilon = np.max(knn_dist, axis=1)
175 | K = np.empty_like(pdx)
176 | for i in range(len(pdx)):
177 | K[i, pdx[i, :] <= epsilon[i]] = 1
178 | K[i, pdx[i, :] > epsilon[i]] = 0
179 |
180 | W = K * K.T
181 | np.fill_diagonal(W, 0)
182 | G = pygsp.graphs.Graph(W)
183 | G2 = build_graph(
184 | data,
185 | n_pca=n_pca,
186 | decay=None,
187 | knn=k - 1,
188 | random_state=42,
189 | use_pygsp=True,
190 | kernel_symm="*",
191 | )
192 | assert G.N == G2.N
193 | np.testing.assert_equal(G.dw, G2.dw)
194 | assert (G.W - G2.W).nnz == 0
195 | assert (G2.W - G.W).sum() == 0
196 | assert isinstance(G2, graphtools.graphs.kNNGraph)
197 |
198 |
199 | def test_knn_graph_sparse():
200 | k = 3
201 | n_pca = 20
202 | pca = TruncatedSVD(n_pca, random_state=42).fit(data)
203 | data_nu = pca.transform(data)
204 | pdx = squareform(pdist(data_nu, metric="euclidean"))
205 | knn_dist = np.partition(pdx, k, axis=1)[:, :k]
206 | epsilon = np.max(knn_dist, axis=1)
207 | K = np.empty_like(pdx)
208 | for i in range(len(pdx)):
209 | K[i, pdx[i, :] <= epsilon[i]] = 1
210 | K[i, pdx[i, :] > epsilon[i]] = 0
211 |
212 | K = K + K.T
213 | W = np.divide(K, 2)
214 | np.fill_diagonal(W, 0)
215 | G = pygsp.graphs.Graph(W)
216 | G2 = build_graph(
217 | sp.coo_matrix(data),
218 | n_pca=n_pca,
219 | decay=None,
220 | knn=k - 1,
221 | random_state=42,
222 | use_pygsp=True,
223 | )
224 | assert G.N == G2.N
225 | np.testing.assert_allclose(G2.W.toarray(), G.W.toarray())
226 | assert isinstance(G2, graphtools.graphs.kNNGraph)
227 |
228 |
229 | def test_sparse_alpha_knn_graph():
230 | data = datasets.make_swiss_roll()[0]
231 | k = 5
232 | a = 0.45
233 | thresh = 0.01
234 | bandwidth_scale = 1.3
235 | pdx = squareform(pdist(data, metric="euclidean"))
236 | knn_dist = np.partition(pdx, k, axis=1)[:, :k]
237 | epsilon = np.max(knn_dist, axis=1) * bandwidth_scale
238 | pdx = (pdx.T / epsilon).T
239 | K = np.exp(-1 * pdx**a)
240 | K = K + K.T
241 | W = np.divide(K, 2)
242 | np.fill_diagonal(W, 0)
243 | G = pygsp.graphs.Graph(W)
244 | G2 = build_graph(
245 | data,
246 | n_pca=None, # n_pca,
247 | decay=a,
248 | knn=k - 1,
249 | thresh=thresh,
250 | bandwidth_scale=bandwidth_scale,
251 | random_state=42,
252 | use_pygsp=True,
253 | )
254 | assert np.abs(G.W - G2.W).max() < thresh
255 | assert G.N == G2.N
256 | assert isinstance(G2, graphtools.graphs.kNNGraph)
257 |
258 |
259 | def test_knnmax():
260 | data = datasets.make_swiss_roll()[0]
261 | k = 5
262 | k_max = 10
263 | a = 0.45
264 | thresh = 0
265 |
266 | with warnings.catch_warnings():
267 | warnings.filterwarnings("ignore", "K should be symmetric", RuntimeWarning)
268 | G = build_graph(
269 | data,
270 | n_pca=None, # n_pca,
271 | decay=a,
272 | knn=k - 1,
273 | knn_max=k_max - 1,
274 | thresh=0,
275 | random_state=42,
276 | kernel_symm=None,
277 | )
278 | assert np.all((G.K > 0).sum(axis=1) == k_max)
279 |
280 | pdx = squareform(pdist(data, metric="euclidean"))
281 | knn_dist = np.partition(pdx, k, axis=1)[:, :k]
282 | knn_max_dist = np.max(np.partition(pdx, k_max, axis=1)[:, :k_max], axis=1)
283 | epsilon = np.max(knn_dist, axis=1)
284 | pdx_scale = (pdx.T / epsilon).T
285 | K = np.where(pdx <= knn_max_dist[:, None], np.exp(-1 * pdx_scale**a), 0)
286 | K = K + K.T
287 | W = np.divide(K, 2)
288 | np.fill_diagonal(W, 0)
289 | G = pygsp.graphs.Graph(W)
290 | G2 = build_graph(
291 | data,
292 | n_pca=None, # n_pca,
293 | decay=a,
294 | knn=k - 1,
295 | knn_max=k_max - 1,
296 | thresh=0,
297 | random_state=42,
298 | use_pygsp=True,
299 | )
300 | assert isinstance(G2, graphtools.graphs.kNNGraph)
301 | assert G.N == G2.N
302 | assert np.all(G.dw == G2.dw)
303 | assert (G.W - G2.W).nnz == 0
304 |
305 |
306 | def test_thresh_small():
307 | data = datasets.make_swiss_roll()[0]
308 | G = graphtools.Graph(data, thresh=1e-30)
309 | assert G.thresh == np.finfo("float").eps
310 |
311 |
312 | def test_no_initialize():
313 | G = graphtools.Graph(data, thresh=1e-4, initialize=False)
314 | assert not hasattr(G, "_kernel")
315 | G.K
316 | assert hasattr(G, "_kernel")
317 |
318 |
319 | def test_knn_graph_fixed_bandwidth():
320 | k = None
321 | decay = 5
322 | bandwidth = 10
323 | bandwidth_scale = 1.3
324 | n_pca = 20
325 | thresh = 1e-4
326 | pca = PCA(n_pca, svd_solver="randomized", random_state=42).fit(data)
327 | data_nu = pca.transform(data)
328 | pdx = squareform(pdist(data_nu, metric="euclidean"))
329 | K = np.exp(-1 * np.power(pdx / (bandwidth * bandwidth_scale), decay))
330 | K[K < thresh] = 0
331 | K = K + K.T
332 | W = np.divide(K, 2)
333 | np.fill_diagonal(W, 0)
334 | G = pygsp.graphs.Graph(W)
335 | G2 = build_graph(
336 | data,
337 | n_pca=n_pca,
338 | decay=decay,
339 | bandwidth=bandwidth,
340 | bandwidth_scale=bandwidth_scale,
341 | knn=k,
342 | random_state=42,
343 | thresh=thresh,
344 | search_multiplier=2,
345 | use_pygsp=True,
346 | )
347 | assert isinstance(G2, graphtools.graphs.kNNGraph)
348 | np.testing.assert_array_equal(G.N, G2.N)
349 | np.testing.assert_array_equal(G.d, G2.d)
350 | np.testing.assert_allclose(
351 | (G.W - G2.W).data, np.zeros_like((G.W - G2.W).data), atol=1e-14
352 | )
353 | bandwidth = np.random.gamma(20, 0.5, len(data))
354 | K = np.exp(-1 * (pdx.T / (bandwidth * bandwidth_scale)).T ** decay)
355 | K[K < thresh] = 0
356 | K = K + K.T
357 | W = np.divide(K, 2)
358 | np.fill_diagonal(W, 0)
359 | G = pygsp.graphs.Graph(W)
360 | G2 = build_graph(
361 | data,
362 | n_pca=n_pca,
363 | decay=decay,
364 | bandwidth=bandwidth,
365 | bandwidth_scale=bandwidth_scale,
366 | knn=k,
367 | random_state=42,
368 | thresh=thresh,
369 | use_pygsp=True,
370 | )
371 | assert isinstance(G2, graphtools.graphs.kNNGraph)
372 | np.testing.assert_array_equal(G.N, G2.N)
373 | np.testing.assert_allclose(G.dw, G2.dw, atol=1e-14)
374 | np.testing.assert_allclose(
375 | (G.W - G2.W).data, np.zeros_like((G.W - G2.W).data), atol=1e-14
376 | )
377 |
378 |
379 | def test_knn_graph_callable_bandwidth():
380 | with assert_raises_message(
381 | NotImplementedError,
382 | "Callable bandwidth is only supported by graphtools.graphs.TraditionalGraph.",
383 | ):
384 | k = 3
385 | decay = 5
386 |
387 | def bandwidth(x):
388 | return 2
389 |
390 | n_pca = 20
391 | thresh = 1e-4
392 | build_graph(
393 | data,
394 | n_pca=n_pca,
395 | knn=k - 1,
396 | decay=decay,
397 | bandwidth=bandwidth,
398 | random_state=42,
399 | thresh=thresh,
400 | graphtype="knn",
401 | )
402 |
403 |
404 | def test_knn_graph_sparse_no_pca():
405 | with assert_warns_message(
406 | UserWarning, "cannot use tree with sparse input: using brute force"
407 | ):
408 | build_graph(
409 | sp.coo_matrix(data),
410 | n_pca=None, # n_pca,
411 | decay=10,
412 | knn=3,
413 | thresh=1e-4,
414 | random_state=42,
415 | use_pygsp=True,
416 | )
417 |
418 |
419 | #####################################################
420 | # Check anisotropy
421 | #####################################################
422 |
423 |
424 | def test_knn_graph_anisotropy():
425 | k = 3
426 | a = 13
427 | n_pca = 20
428 | anisotropy = 0.9
429 | thresh = 1e-4
430 | data_small = data[np.random.choice(len(data), len(data) // 2, replace=False)]
431 | pca = PCA(n_pca, svd_solver="randomized", random_state=42).fit(data_small)
432 | data_small_nu = pca.transform(data_small)
433 | pdx = squareform(pdist(data_small_nu, metric="euclidean"))
434 | knn_dist = np.partition(pdx, k, axis=1)[:, :k]
435 | epsilon = np.max(knn_dist, axis=1)
436 | weighted_pdx = (pdx.T / epsilon).T
437 | K = np.exp(-1 * weighted_pdx**a)
438 | K[K < thresh] = 0
439 | K = K + K.T
440 | K = np.divide(K, 2)
441 | d = K.sum(1)
442 | W = K / (np.outer(d, d) ** anisotropy)
443 | np.fill_diagonal(W, 0)
444 | G = pygsp.graphs.Graph(W)
445 | G2 = build_graph(
446 | data_small,
447 | n_pca=n_pca,
448 | thresh=thresh,
449 | decay=a,
450 | knn=k - 1,
451 | random_state=42,
452 | use_pygsp=True,
453 | anisotropy=anisotropy,
454 | )
455 | assert isinstance(G2, graphtools.graphs.kNNGraph)
456 | assert G.N == G2.N
457 | np.testing.assert_allclose(G.dw, G2.dw, atol=1e-14, rtol=1e-14)
458 | np.testing.assert_allclose((G2.W - G.W).data, 0, atol=1e-14, rtol=1e-14)
459 |
460 |
461 | #####################################################
462 | # Check interpolation
463 | #####################################################
464 |
465 |
466 | def test_build_dense_knn_kernel_to_data():
467 | G = build_graph(data, decay=None)
468 | n = G.data.shape[0]
469 | K = G.build_kernel_to_data(data[: n // 2, :], knn=G.knn + 1)
470 | assert K.shape == (n // 2, n)
471 | K = G.build_kernel_to_data(G.data, knn=G.knn + 1)
472 | assert (G.kernel - (K + K.T) / 2).nnz == 0
473 | K = G.build_kernel_to_data(G.data_nu, knn=G.knn + 1)
474 | assert (G.kernel - (K + K.T) / 2).nnz == 0
475 |
476 |
477 | def test_build_sparse_knn_kernel_to_data():
478 | G = build_graph(data, decay=None, sparse=True)
479 | n = G.data.shape[0]
480 | K = G.build_kernel_to_data(data[: n // 2, :], knn=G.knn + 1)
481 | assert K.shape == (n // 2, n)
482 | K = G.build_kernel_to_data(G.data, knn=G.knn + 1)
483 | assert (G.kernel - (K + K.T) / 2).nnz == 0
484 | K = G.build_kernel_to_data(G.data_nu, knn=G.knn + 1)
485 | assert (G.kernel - (K + K.T) / 2).nnz == 0
486 |
487 |
488 | def test_knn_interpolate():
489 | G = build_graph(data, decay=None)
490 | with assert_raises_message(
491 | ValueError, "Either `transitions` or `Y` must be provided."
492 | ):
493 | G.interpolate(data)
494 | pca_data = PCA(2).fit_transform(data)
495 | transitions = G.extend_to_data(data)
496 | np.testing.assert_equal(
497 | G.interpolate(pca_data, Y=data),
498 | G.interpolate(pca_data, transitions=transitions),
499 | )
500 |
501 |
502 | def test_knn_interpolate_wrong_shape():
503 | G = build_graph(data, n_pca=10, decay=None)
504 | with assert_raises_message(
505 | ValueError, "Expected a 2D matrix. Y has shape ({},)".format(data.shape[0])
506 | ):
507 | G.extend_to_data(data[:, 0])
508 | with assert_raises_message(
509 | ValueError,
510 | "Expected a 2D matrix. Y has shape ({}, {}, 1)".format(
511 | data.shape[0], data.shape[1]
512 | ),
513 | ):
514 | G.extend_to_data(data[:, :, None])
515 | with assert_raises_message(
516 | ValueError, "Y must be of shape either (n, 64) or (n, 10)"
517 | ):
518 | G.extend_to_data(data[:, : data.shape[1] // 2])
519 | G = build_graph(data, n_pca=None, decay=None)
520 | with assert_raises_message(ValueError, "Y must be of shape (n, 64)"):
521 | G.extend_to_data(data[:, : data.shape[1] // 2])
522 |
523 |
524 | #################################################
525 | # Check extra functionality
526 | #################################################
527 |
528 |
529 | def test_shortest_path_constant():
530 | data_small = data[np.random.choice(len(data), len(data) // 4, replace=False)]
531 | G = build_graph(data_small, knn=5, decay=None)
532 | P = shortest_path(G.K)
533 | # sklearn returns 0 if no path exists
534 | P[np.where(P == 0)] = np.inf
535 | # diagonal should actually be zero
536 | np.fill_diagonal(P, 0)
537 | np.testing.assert_equal(P, G.shortest_path(distance="constant"))
538 |
539 |
540 | def test_shortest_path_precomputed_constant():
541 | data_small = data[np.random.choice(len(data), len(data) // 4, replace=False)]
542 | G = build_graph(data_small, knn=5, decay=None)
543 | G = graphtools.Graph(G.K, precomputed="affinity")
544 | P = shortest_path(G.K)
545 | # sklearn returns 0 if no path exists
546 | P[np.where(P == 0)] = np.inf
547 | # diagonal should actually be zero
548 | np.fill_diagonal(P, 0)
549 | np.testing.assert_equal(P, G.shortest_path(distance="constant"))
550 | np.testing.assert_equal(P, G.shortest_path())
551 |
552 |
553 | def test_shortest_path_data():
554 | data_small = data[np.random.choice(len(data), len(data) // 4, replace=False)]
555 | G = build_graph(data_small, knn=5, decay=None)
556 | D = squareform(pdist(G.data_nu)) * np.where(G.K.toarray() > 0, 1, 0)
557 | P = shortest_path(D)
558 | # sklearn returns 0 if no path exists
559 | P[np.where(P == 0)] = np.inf
560 | # diagonal should actually be zero
561 | np.fill_diagonal(P, 0)
562 | np.testing.assert_allclose(P, G.shortest_path(distance="data"))
563 | np.testing.assert_allclose(P, G.shortest_path())
564 |
565 |
566 | def test_shortest_path_no_decay_affinity():
567 | with assert_raises_message(
568 | ValueError,
569 | "Graph shortest path with affinity distance only valid for weighted graphs. For unweighted graphs, use `distance='constant'` or `distance='data'`.",
570 | ):
571 | data_small = data[np.random.choice(len(data), len(data) // 4, replace=False)]
572 | G = build_graph(data_small, knn=5, decay=None)
573 | G.shortest_path(distance="affinity")
574 |
575 |
576 | def test_shortest_path_precomputed_no_decay_affinity():
577 | with assert_raises_message(
578 | ValueError,
579 | "Graph shortest path with affinity distance only valid for weighted graphs. For unweighted graphs, use `distance='constant'` or `distance='data'`.",
580 | ):
581 | data_small = data[np.random.choice(len(data), len(data) // 4, replace=False)]
582 | G = build_graph(data_small, knn=5, decay=None)
583 | G = graphtools.Graph(G.K, precomputed="affinity")
584 | G.shortest_path(distance="affinity")
585 |
586 |
587 | def test_shortest_path_precomputed_no_decay_data():
588 | with assert_raises_message(
589 | ValueError,
590 | "Graph shortest path with data distance not valid for precomputed graphs. For precomputed graphs, use `distance='constant'` for unweighted graphs and `distance='affinity'` for weighted graphs.",
591 | ):
592 | data_small = data[np.random.choice(len(data), len(data) // 4, replace=False)]
593 | G = build_graph(data_small, knn=5, decay=None)
594 | G = graphtools.Graph(G.K, precomputed="affinity")
595 | G.shortest_path(distance="data")
596 |
597 |
598 | def test_shortest_path_invalid():
599 | with assert_raises_message(
600 | ValueError,
601 | "Expected `distance` in ['constant', 'data', 'affinity']. Got invalid",
602 | ):
603 | data_small = data[np.random.choice(len(data), len(data) // 4, replace=False)]
604 | G = build_graph(data_small, knn=5, decay=None)
605 | G.shortest_path(distance="invalid")
606 |
607 |
608 | ####################
609 | # Test API
610 | ####################
611 |
612 |
613 | def test_verbose():
614 | print()
615 | print("Verbose test: kNN")
616 | build_graph(data, decay=None, verbose=True)
617 |
618 |
619 | def test_set_params():
620 | G = build_graph(data, decay=None)
621 | assert G.get_params() == {
622 | "n_pca": 20,
623 | "random_state": 42,
624 | "kernel_symm": "+",
625 | "theta": None,
626 | "anisotropy": 0,
627 | "knn": 3,
628 | "knn_max": None,
629 | "decay": None,
630 | "bandwidth": None,
631 | "bandwidth_scale": 1,
632 | "distance": "euclidean",
633 | "thresh": 0,
634 | "n_jobs": -1,
635 | "verbose": 0,
636 | }, G.get_params()
637 | G.set_params(n_jobs=4)
638 | assert G.n_jobs == 4
639 | assert G.knn_tree.n_jobs == 4
640 | G.set_params(random_state=13)
641 | assert G.random_state == 13
642 | G.set_params(verbose=2)
643 | assert G.verbose == 2
644 | G.set_params(verbose=0)
645 | with assert_raises_message(
646 | ValueError, "Cannot update knn. Please create a new graph"
647 | ):
648 | G.set_params(knn=15)
649 | with assert_raises_message(
650 | ValueError, "Cannot update knn_max. Please create a new graph"
651 | ):
652 | G.set_params(knn_max=15)
653 | with assert_raises_message(
654 | ValueError, "Cannot update decay. Please create a new graph"
655 | ):
656 | G.set_params(decay=10)
657 | with assert_raises_message(
658 | ValueError, "Cannot update distance. Please create a new graph"
659 | ):
660 | G.set_params(distance="manhattan")
661 | with assert_raises_message(
662 | ValueError, "Cannot update thresh. Please create a new graph"
663 | ):
664 | G.set_params(thresh=1e-3)
665 | with assert_raises_message(
666 | ValueError, "Cannot update theta. Please create a new graph"
667 | ):
668 | G.set_params(theta=0.99)
669 | with assert_raises_message(
670 | ValueError, "Cannot update kernel_symm. Please create a new graph"
671 | ):
672 | G.set_params(kernel_symm="*")
673 | with assert_raises_message(
674 | ValueError, "Cannot update anisotropy. Please create a new graph"
675 | ):
676 | G.set_params(anisotropy=0.7)
677 | with assert_raises_message(
678 | ValueError, "Cannot update bandwidth. Please create a new graph"
679 | ):
680 | G.set_params(bandwidth=5)
681 | with assert_raises_message(
682 | ValueError, "Cannot update bandwidth_scale. Please create a new graph"
683 | ):
684 | G.set_params(bandwidth_scale=5)
685 | G.set_params(
686 | knn=G.knn,
687 | decay=G.decay,
688 | thresh=G.thresh,
689 | distance=G.distance,
690 | theta=G.theta,
691 | anisotropy=G.anisotropy,
692 | kernel_symm=G.kernel_symm,
693 | )
694 |
--------------------------------------------------------------------------------
/test/test_landmark.py:
--------------------------------------------------------------------------------
1 | from __future__ import print_function
2 |
3 | from load_tests import assert_raises_message
4 | from load_tests import assert_warns_message
5 | from load_tests import build_graph
6 | from load_tests import data
7 | from load_tests import digits
8 | from load_tests import generate_swiss_roll
9 | from load_tests import graphtools
10 | from load_tests import nose2
11 | from load_tests import np
12 |
13 | import pygsp
14 |
15 | #####################################################
16 | # Check parameters
17 | #####################################################
18 |
19 |
20 | def test_build_landmark_with_too_many_landmarks():
21 | with assert_raises_message(
22 | ValueError,
23 | "n_landmark ({0}) >= n_samples ({0}). Use kNNGraph instead".format(
24 | data.shape[0]
25 | ),
26 | ):
27 | build_graph(data, n_landmark=len(data))
28 |
29 |
30 | def test_build_landmark_with_too_few_points():
31 | with assert_warns_message(
32 | RuntimeWarning,
33 | "n_svd (100) >= n_samples (50) Consider using kNNGraph or lower n_svd",
34 | ):
35 | build_graph(data[:50], n_landmark=25, n_svd=100)
36 |
37 |
38 | #####################################################
39 | # Check kernel
40 | #####################################################
41 |
42 |
43 | def test_landmark_exact_graph():
44 | n_landmark = 100
45 | # exact graph
46 | G = build_graph(
47 | data,
48 | n_landmark=n_landmark,
49 | thresh=0,
50 | n_pca=20,
51 | decay=10,
52 | knn=5 - 1,
53 | random_state=42,
54 | )
55 | assert G.landmark_op.shape == (n_landmark, n_landmark)
56 | assert isinstance(G, graphtools.graphs.TraditionalGraph)
57 | assert isinstance(G, graphtools.graphs.LandmarkGraph)
58 | assert G.transitions.shape == (data.shape[0], n_landmark)
59 | assert G.clusters.shape == (data.shape[0],)
60 | assert len(np.unique(G.clusters)) <= n_landmark
61 | signal = np.random.normal(0, 1, [n_landmark, 10])
62 | interpolated_signal = G.interpolate(signal)
63 | assert interpolated_signal.shape == (data.shape[0], signal.shape[1])
64 | G._reset_landmarks()
65 | # no error on double delete
66 | G._reset_landmarks()
67 |
68 |
69 | def test_landmark_knn_graph():
70 | np.random.seed(42)
71 | n_landmark = 500
72 | # knn graph
73 | G = build_graph(
74 | data, n_landmark=n_landmark, n_pca=20, decay=None, knn=5 - 1, random_state=42
75 | )
76 | n_landmark_out = G.landmark_op.shape[0]
77 | assert n_landmark_out <= n_landmark
78 | assert n_landmark_out >= n_landmark - 3
79 | assert G.transitions.shape == (data.shape[0], n_landmark_out), G.transitions.shape
80 | assert G.landmark_op.shape == (n_landmark_out, n_landmark_out)
81 | assert isinstance(G, graphtools.graphs.kNNGraph)
82 | assert isinstance(G, graphtools.graphs.LandmarkGraph)
83 |
84 |
85 | def test_landmark_mnn_graph():
86 | n_landmark = 150
87 | X, sample_idx = generate_swiss_roll()
88 | # mnn graph
89 | G = build_graph(
90 | X,
91 | n_landmark=n_landmark,
92 | thresh=1e-5,
93 | n_pca=None,
94 | decay=10,
95 | knn=5 - 1,
96 | random_state=42,
97 | sample_idx=sample_idx,
98 | )
99 | assert G.clusters.shape == (X.shape[0],)
100 | assert G.landmark_op.shape == (n_landmark, n_landmark)
101 | assert isinstance(G, graphtools.graphs.MNNGraph)
102 | assert isinstance(G, graphtools.graphs.LandmarkGraph)
103 |
104 |
105 | #####################################################
106 | # Check PyGSP
107 | #####################################################
108 |
109 |
110 | def test_landmark_exact_pygsp_graph():
111 | n_landmark = 100
112 | # exact graph
113 | G = build_graph(
114 | data,
115 | n_landmark=n_landmark,
116 | thresh=0,
117 | n_pca=10,
118 | decay=10,
119 | knn=3 - 1,
120 | random_state=42,
121 | use_pygsp=True,
122 | )
123 | assert G.landmark_op.shape == (n_landmark, n_landmark)
124 | assert isinstance(G, graphtools.graphs.TraditionalGraph)
125 | assert isinstance(G, graphtools.graphs.LandmarkGraph)
126 | assert isinstance(G, pygsp.graphs.Graph)
127 |
128 |
129 | def test_landmark_knn_pygsp_graph():
130 | n_landmark = 500
131 | # knn graph
132 | G = build_graph(
133 | data,
134 | n_landmark=n_landmark,
135 | n_pca=10,
136 | decay=None,
137 | knn=3 - 1,
138 | random_state=42,
139 | use_pygsp=True,
140 | )
141 | assert G.landmark_op.shape == (n_landmark, n_landmark)
142 | assert isinstance(G, graphtools.graphs.kNNGraph)
143 | assert isinstance(G, graphtools.graphs.LandmarkGraph)
144 | assert isinstance(G, pygsp.graphs.Graph)
145 |
146 |
147 | def test_landmark_mnn_pygsp_graph():
148 | n_landmark = 150
149 | X, sample_idx = generate_swiss_roll()
150 | # mnn graph
151 | G = build_graph(
152 | X,
153 | n_landmark=n_landmark,
154 | thresh=1e-3,
155 | n_pca=None,
156 | decay=10,
157 | knn=3 - 1,
158 | random_state=42,
159 | sample_idx=sample_idx,
160 | use_pygsp=True,
161 | )
162 | assert G.landmark_op.shape == (n_landmark, n_landmark)
163 | assert isinstance(G, graphtools.graphs.MNNGraph)
164 | assert isinstance(G, graphtools.graphs.LandmarkGraph)
165 | assert isinstance(G, pygsp.graphs.Graph)
166 |
167 |
168 | #####################################################
169 | # Check interpolation
170 | #####################################################
171 |
172 |
173 | # TODO: add interpolation tests
174 |
175 |
176 | #############
177 | # Test API
178 | #############
179 |
180 |
181 | def test_verbose():
182 | print()
183 | print("Verbose test: Landmark")
184 | build_graph(data, decay=None, n_landmark=500, verbose=True).landmark_op
185 |
186 |
187 | def test_set_params():
188 | G = build_graph(data, n_landmark=500, decay=None)
189 | G.landmark_op
190 | assert G.get_params() == {
191 | "n_pca": 20,
192 | "random_state": 42,
193 | "kernel_symm": "+",
194 | "theta": None,
195 | "n_landmark": 500,
196 | "anisotropy": 0,
197 | "knn": 3,
198 | "knn_max": None,
199 | "decay": None,
200 | "bandwidth": None,
201 | "bandwidth_scale": 1,
202 | "distance": "euclidean",
203 | "thresh": 0,
204 | "n_jobs": -1,
205 | "verbose": 0,
206 | }
207 | G.set_params(n_landmark=300)
208 | assert G.landmark_op.shape == (300, 300)
209 | G.set_params(n_landmark=G.n_landmark, n_svd=G.n_svd)
210 | assert hasattr(G, "_landmark_op")
211 | G.set_params(n_svd=50)
212 | assert not hasattr(G, "_landmark_op")
213 |
--------------------------------------------------------------------------------
/test/test_matrix.py:
--------------------------------------------------------------------------------
1 | from load_tests import assert_warns_message
2 | from load_tests import data
3 | from parameterized import parameterized
4 | from scipy import sparse
5 |
6 | import graphtools
7 | import graphtools.matrix
8 | import graphtools.utils
9 | import numpy as np
10 |
11 |
12 | @parameterized(
13 | [
14 | (np.array,),
15 | (sparse.csr_matrix,),
16 | (sparse.csc_matrix,),
17 | (sparse.bsr_matrix,),
18 | (sparse.lil_matrix,),
19 | (sparse.coo_matrix,),
20 | ]
21 | )
22 | def test_nonzero_discrete(matrix_class):
23 | X = np.random.choice([0, 1, 2], p=[0.95, 0.025, 0.025], size=(100, 100))
24 | X = matrix_class(X)
25 | assert graphtools.matrix.nonzero_discrete(X, [1, 2])
26 | assert not graphtools.matrix.nonzero_discrete(X, [1, 3])
27 |
28 |
29 | @parameterized([(0,), (1e-4,)])
30 | def test_nonzero_discrete_knngraph(thresh):
31 | G = graphtools.Graph(data, n_pca=10, knn=5, decay=None, thresh=thresh)
32 | assert graphtools.matrix.nonzero_discrete(G.K, [0.5, 1])
33 |
34 |
35 | @parameterized([(0,), (1e-4,)])
36 | def test_nonzero_discrete_decay_graph(thresh):
37 | G = graphtools.Graph(data, n_pca=10, knn=5, decay=15, thresh=thresh)
38 | assert not graphtools.matrix.nonzero_discrete(G.K, [0.5, 1])
39 |
40 |
41 | def test_nonzero_discrete_constant():
42 | assert graphtools.matrix.nonzero_discrete(2, [1, 2])
43 | assert not graphtools.matrix.nonzero_discrete(2, [1, 3])
44 |
45 |
46 | def test_if_sparse_deprecated():
47 | with assert_warns_message(
48 | DeprecationWarning,
49 | "Call to deprecated function (or staticmethod) if_sparse. (Use graphtools.matrix.if_sparse instead) -- Deprecated since version 1.5.0.",
50 | ):
51 | graphtools.utils.if_sparse(lambda x: x, lambda x: x, np.zeros((4, 4)))
52 |
53 |
54 | def test_sparse_minimum_deprecated():
55 | with assert_warns_message(
56 | DeprecationWarning,
57 | "Call to deprecated function (or staticmethod) sparse_minimum. (Use graphtools.matrix.sparse_minimum instead) -- Deprecated since version 1.5.0.",
58 | ):
59 | graphtools.utils.sparse_minimum(
60 | sparse.csr_matrix((4, 4)), sparse.bsr_matrix((4, 4))
61 | )
62 |
63 |
64 | def test_sparse_maximum_deprecated():
65 | with assert_warns_message(
66 | DeprecationWarning,
67 | "Call to deprecated function (or staticmethod) sparse_maximum. (Use graphtools.matrix.sparse_maximum instead) -- Deprecated since version 1.5.0.",
68 | ):
69 | graphtools.utils.sparse_maximum(
70 | sparse.csr_matrix((4, 4)), sparse.bsr_matrix((4, 4))
71 | )
72 |
73 |
74 | def test_elementwise_minimum_deprecated():
75 | with assert_warns_message(
76 | DeprecationWarning,
77 | "Call to deprecated function (or staticmethod) elementwise_minimum. (Use graphtools.matrix.elementwise_minimum instead) -- Deprecated since version 1.5.0.",
78 | ):
79 | graphtools.utils.elementwise_minimum(
80 | sparse.csr_matrix((4, 4)), sparse.bsr_matrix((4, 4))
81 | )
82 |
83 |
84 | def test_elementwise_maximum_deprecated():
85 | with assert_warns_message(
86 | DeprecationWarning,
87 | "Call to deprecated function (or staticmethod) elementwise_maximum. (Use graphtools.matrix.elementwise_maximum instead) -- Deprecated since version 1.5.0.",
88 | ):
89 | graphtools.utils.elementwise_maximum(
90 | sparse.csr_matrix((4, 4)), sparse.bsr_matrix((4, 4))
91 | )
92 |
93 |
94 | def test_dense_set_diagonal_deprecated():
95 | with assert_warns_message(
96 | DeprecationWarning,
97 | "Call to deprecated function (or staticmethod) dense_set_diagonal. (Use graphtools.matrix.dense_set_diagonal instead) -- Deprecated since version 1.5.0.",
98 | ):
99 | graphtools.utils.dense_set_diagonal(np.zeros((4, 4)), 1)
100 |
101 |
102 | def test_sparse_set_diagonal_deprecated():
103 | with assert_warns_message(
104 | DeprecationWarning,
105 | "Call to deprecated function (or staticmethod) sparse_set_diagonal. (Use graphtools.matrix.sparse_set_diagonal instead) -- Deprecated since version 1.5.0.",
106 | ):
107 | graphtools.utils.sparse_set_diagonal(sparse.csr_matrix((4, 4)), 1)
108 |
109 |
110 | def test_set_diagonal_deprecated():
111 | with assert_warns_message(
112 | DeprecationWarning,
113 | "Call to deprecated function (or staticmethod) set_diagonal. (Use graphtools.matrix.set_diagonal instead) -- Deprecated since version 1.5.0.",
114 | ):
115 | graphtools.utils.set_diagonal(np.zeros((4, 4)), 1)
116 |
117 |
118 | def test_set_submatrix_deprecated():
119 | with assert_warns_message(
120 | DeprecationWarning,
121 | "Call to deprecated function (or staticmethod) set_submatrix. (Use graphtools.matrix.set_submatrix instead) -- Deprecated since version 1.5.0.",
122 | ):
123 | graphtools.utils.set_submatrix(
124 | sparse.lil_matrix((4, 4)), [1, 2], [0, 1], np.array([[1, 2], [3, 4]])
125 | )
126 |
127 |
128 | def test_sparse_nonzero_discrete_deprecated():
129 | with assert_warns_message(
130 | DeprecationWarning,
131 | "Call to deprecated function (or staticmethod) sparse_nonzero_discrete. (Use graphtools.matrix.sparse_nonzero_discrete instead) -- Deprecated since version 1.5.0.",
132 | ):
133 | graphtools.utils.sparse_nonzero_discrete(sparse.csr_matrix((4, 4)), [1])
134 |
135 |
136 | def test_dense_nonzero_discrete_deprecated():
137 | with assert_warns_message(
138 | DeprecationWarning,
139 | "Call to deprecated function (or staticmethod) dense_nonzero_discrete. (Use graphtools.matrix.dense_nonzero_discrete instead) -- Deprecated since version 1.5.0.",
140 | ):
141 | graphtools.utils.dense_nonzero_discrete(np.zeros((4, 4)), [1])
142 |
143 |
144 | def test_nonzero_discrete_deprecated():
145 | with assert_warns_message(
146 | DeprecationWarning,
147 | "Call to deprecated function (or staticmethod) nonzero_discrete. (Use graphtools.matrix.nonzero_discrete instead) -- Deprecated since version 1.5.0.",
148 | ):
149 | graphtools.utils.nonzero_discrete(np.zeros((4, 4)), [1])
150 |
151 |
152 | def test_to_array_deprecated():
153 | with assert_warns_message(
154 | DeprecationWarning,
155 | "Call to deprecated function (or staticmethod) to_array. (Use graphtools.matrix.to_array instead) -- Deprecated since version 1.5.0.",
156 | ):
157 | graphtools.utils.to_array([1])
158 |
159 |
160 | def test_matrix_is_equivalent_deprecated():
161 | with assert_warns_message(
162 | DeprecationWarning,
163 | "Call to deprecated function (or staticmethod) matrix_is_equivalent. (Use graphtools.matrix.matrix_is_equivalent instead) -- Deprecated since version 1.5.0.",
164 | ):
165 | graphtools.utils.matrix_is_equivalent(
166 | sparse.csr_matrix((4, 4)), sparse.bsr_matrix((4, 4))
167 | )
168 |
--------------------------------------------------------------------------------
/test/test_mnn.py:
--------------------------------------------------------------------------------
1 | from __future__ import print_function
2 |
3 | from load_tests import assert_raises_message
4 | from load_tests import assert_warns_message
5 | from load_tests import build_graph
6 | from load_tests import cdist
7 | from load_tests import data
8 | from load_tests import digits
9 | from load_tests import generate_swiss_roll
10 | from load_tests import graphtools
11 | from load_tests import nose2
12 | from load_tests import np
13 | from load_tests import pd
14 | from load_tests import pygsp
15 | from scipy.linalg import norm
16 |
17 | import warnings
18 |
19 | #####################################################
20 | # Check parameters
21 | #####################################################
22 |
23 |
24 | def test_sample_idx_and_precomputed():
25 | with assert_raises_message(
26 | ValueError,
27 | "MNNGraph does not support precomputed values. Use `graphtype='exact'` and `sample_idx=None` or `precomputed=None`",
28 | ):
29 | build_graph(data, n_pca=None, sample_idx=np.arange(10), precomputed="distance")
30 |
31 |
32 | def test_sample_idx_wrong_length():
33 | with assert_raises_message(
34 | ValueError,
35 | "sample_idx (10) must be the same length as data ({})".format(data.shape[0]),
36 | ):
37 | build_graph(data, graphtype="mnn", sample_idx=np.arange(10))
38 |
39 |
40 | def test_sample_idx_unique():
41 | with assert_raises_message(
42 | ValueError, "sample_idx must contain more than one unique value"
43 | ):
44 | build_graph(
45 | data, graph_class=graphtools.graphs.MNNGraph, sample_idx=np.ones(len(data))
46 | )
47 | with assert_warns_message(
48 | UserWarning, "Only one unique sample. Not using MNNGraph"
49 | ):
50 | build_graph(data, sample_idx=np.ones(len(data)), graphtype="mnn")
51 |
52 |
53 | def test_sample_idx_none():
54 | with assert_raises_message(
55 | ValueError,
56 | "sample_idx must be given. For a graph without batch correction, use kNNGraph.",
57 | ):
58 | build_graph(data, graphtype="mnn", sample_idx=None)
59 |
60 |
61 | def test_build_mnn_with_precomputed():
62 | with assert_raises_message(
63 | ValueError,
64 | "MNNGraph does not support precomputed values. Use `graphtype='exact'` and `sample_idx=None` or `precomputed=None`",
65 | ):
66 | build_graph(data, n_pca=None, graphtype="mnn", precomputed="distance")
67 |
68 |
69 | def test_mnn_with_matrix_theta():
70 | with assert_raises_message(
71 | TypeError, "Expected `theta` as a float. Got ."
72 | ):
73 | n_sample = len(np.unique(digits["target"]))
74 | # square matrix theta of the wrong size
75 | build_graph(
76 | data,
77 | thresh=0,
78 | n_pca=20,
79 | decay=10,
80 | knn=5,
81 | random_state=42,
82 | sample_idx=digits["target"],
83 | kernel_symm="mnn",
84 | theta=np.tile(np.linspace(0, 1, n_sample), n_sample).reshape(
85 | n_sample, n_sample
86 | ),
87 | )
88 |
89 |
90 | def test_mnn_with_vector_theta():
91 | with assert_raises_message(
92 | TypeError, "Expected `theta` as a float. Got ."
93 | ):
94 | n_sample = len(np.unique(digits["target"]))
95 | # vector theta
96 | build_graph(
97 | data,
98 | thresh=0,
99 | n_pca=20,
100 | decay=10,
101 | knn=5,
102 | random_state=42,
103 | sample_idx=digits["target"],
104 | kernel_symm="mnn",
105 | theta=np.linspace(0, 1, n_sample - 1),
106 | )
107 |
108 |
109 | def test_mnn_with_unbounded_theta():
110 | with assert_raises_message(
111 | ValueError, "theta 2 not recognized. Expected a float between 0 and 1"
112 | ):
113 | build_graph(
114 | data,
115 | thresh=0,
116 | n_pca=20,
117 | decay=10,
118 | knn=5,
119 | random_state=42,
120 | sample_idx=digits["target"],
121 | kernel_symm="mnn",
122 | theta=2,
123 | )
124 |
125 |
126 | def test_mnn_with_string_theta():
127 | with assert_raises_message(
128 | TypeError, "Expected `theta` as a float. Got ."
129 | ):
130 | build_graph(
131 | data,
132 | thresh=0,
133 | n_pca=20,
134 | decay=10,
135 | knn=5,
136 | random_state=42,
137 | sample_idx=digits["target"],
138 | kernel_symm="mnn",
139 | theta="invalid",
140 | )
141 |
142 |
143 | def test_mnn_with_gamma():
144 | with assert_warns_message(FutureWarning, "gamma is deprecated. Setting theta=0.9"):
145 | build_graph(
146 | data,
147 | thresh=0,
148 | n_pca=20,
149 | decay=10,
150 | knn=5,
151 | random_state=42,
152 | sample_idx=digits["target"],
153 | kernel_symm="mnn",
154 | gamma=0.9,
155 | )
156 |
157 |
158 | def test_mnn_with_kernel_symm_gamma():
159 | with assert_warns_message(
160 | FutureWarning, "kernel_symm='gamma' is deprecated. Setting kernel_symm='mnn'"
161 | ):
162 | build_graph(
163 | data,
164 | thresh=0,
165 | n_pca=20,
166 | decay=10,
167 | knn=5,
168 | random_state=42,
169 | sample_idx=digits["target"],
170 | kernel_symm="gamma",
171 | theta=0.9,
172 | )
173 |
174 |
175 | def test_mnn_with_kernel_symm_invalid():
176 | with assert_raises_message(
177 | ValueError,
178 | "kernel_symm 'invalid' not recognized. Choose from '+', '*', 'mnn', or 'none'.",
179 | ):
180 | build_graph(
181 | data,
182 | thresh=0,
183 | n_pca=20,
184 | decay=10,
185 | knn=5,
186 | random_state=42,
187 | sample_idx=digits["target"],
188 | kernel_symm="invalid",
189 | theta=0.9,
190 | )
191 |
192 |
193 | def test_mnn_with_kernel_symm_theta():
194 | with assert_warns_message(
195 | FutureWarning, "kernel_symm='theta' is deprecated. Setting kernel_symm='mnn'"
196 | ):
197 | build_graph(
198 | data,
199 | thresh=0,
200 | n_pca=20,
201 | decay=10,
202 | knn=5,
203 | random_state=42,
204 | sample_idx=digits["target"],
205 | kernel_symm="theta",
206 | theta=0.9,
207 | )
208 |
209 |
210 | def test_mnn_with_theta_and_kernel_symm_not_theta():
211 | with assert_warns_message(
212 | UserWarning, "kernel_symm='+' but theta is not None. Setting kernel_symm='mnn'."
213 | ):
214 | build_graph(
215 | data,
216 | thresh=0,
217 | n_pca=20,
218 | decay=10,
219 | knn=5,
220 | random_state=42,
221 | sample_idx=digits["target"],
222 | kernel_symm="+",
223 | theta=0.9,
224 | )
225 |
226 |
227 | def test_mnn_with_kernel_symmm_theta_and_no_theta():
228 | with assert_warns_message(
229 | UserWarning, "kernel_symm='mnn' but theta not given. Defaulting to theta=1."
230 | ):
231 | build_graph(
232 | data,
233 | thresh=0,
234 | n_pca=20,
235 | decay=10,
236 | knn=5,
237 | random_state=42,
238 | sample_idx=digits["target"],
239 | kernel_symm="mnn",
240 | )
241 |
242 |
243 | def test_mnn_adaptive_k():
244 | with assert_warns_message(
245 | DeprecationWarning, "`adaptive_k` has been deprecated. Using fixed knn."
246 | ):
247 | build_graph(
248 | data,
249 | thresh=0,
250 | n_pca=20,
251 | decay=10,
252 | knn=5,
253 | random_state=42,
254 | sample_idx=digits["target"],
255 | kernel_symm="mnn",
256 | theta=0.9,
257 | adaptive_k="sqrt",
258 | )
259 |
260 |
261 | def test_single_sample_idx_warning():
262 | with assert_warns_message(
263 | UserWarning, "Only one unique sample. Not using MNNGraph"
264 | ):
265 | build_graph(data, sample_idx=np.repeat(1, len(data)))
266 |
267 |
268 | def test_single_sample_idx():
269 | with warnings.catch_warnings():
270 | warnings.filterwarnings(
271 | "ignore", "Only one unique sample. Not using MNNGraph", UserWarning
272 | )
273 | G = build_graph(data, sample_idx=np.repeat(1, len(data)))
274 | G2 = build_graph(data)
275 | np.testing.assert_array_equal(G.K, G2.K)
276 |
277 |
278 | def test_mnn_with_non_zero_indexed_sample_idx():
279 | X, sample_idx = generate_swiss_roll()
280 | G = build_graph(
281 | X,
282 | sample_idx=sample_idx,
283 | kernel_symm="mnn",
284 | theta=0.5,
285 | n_pca=None,
286 | use_pygsp=True,
287 | )
288 | sample_idx += 1
289 | G2 = build_graph(
290 | X,
291 | sample_idx=sample_idx,
292 | kernel_symm="mnn",
293 | theta=0.5,
294 | n_pca=None,
295 | use_pygsp=True,
296 | )
297 | assert G.N == G2.N
298 | assert np.all(G.d == G2.d)
299 | assert (G.W != G2.W).nnz == 0
300 | assert (G2.W != G.W).sum() == 0
301 | assert isinstance(G2, graphtools.graphs.MNNGraph)
302 |
303 |
304 | def test_mnn_with_string_sample_idx():
305 | X, sample_idx = generate_swiss_roll()
306 | G = build_graph(
307 | X,
308 | sample_idx=sample_idx,
309 | kernel_symm="mnn",
310 | theta=0.5,
311 | n_pca=None,
312 | use_pygsp=True,
313 | )
314 | sample_idx = np.where(sample_idx == 0, "a", "b")
315 | G2 = build_graph(
316 | X,
317 | sample_idx=sample_idx,
318 | kernel_symm="mnn",
319 | theta=0.5,
320 | n_pca=None,
321 | use_pygsp=True,
322 | )
323 | assert G.N == G2.N
324 | assert np.all(G.d == G2.d)
325 | assert (G.W != G2.W).nnz == 0
326 | assert (G2.W != G.W).sum() == 0
327 | assert isinstance(G2, graphtools.graphs.MNNGraph)
328 |
329 |
330 | #####################################################
331 | # Check kernel
332 | #####################################################
333 |
334 |
335 | def test_mnn_graph_no_decay():
336 | X, sample_idx = generate_swiss_roll()
337 | theta = 0.9
338 | k = 10
339 | a = None
340 | metric = "euclidean"
341 | beta = 0.2
342 | samples = np.unique(sample_idx)
343 |
344 | K = np.zeros((len(X), len(X)))
345 | K[:] = np.nan
346 | K = pd.DataFrame(K)
347 |
348 | for si in samples:
349 | X_i = X[sample_idx == si] # get observations in sample i
350 | for sj in samples:
351 | batch_k = k + 1 if si == sj else k
352 | X_j = X[sample_idx == sj] # get observation in sample j
353 | pdx_ij = cdist(X_i, X_j, metric=metric) # pairwise distances
354 | kdx_ij = np.sort(pdx_ij, axis=1) # get kNN
355 | e_ij = kdx_ij[:, batch_k - 1] # dist to kNN
356 | k_ij = np.where(pdx_ij <= e_ij[:, None], 1, 0) # apply knn kernel
357 | if si == sj:
358 | K.iloc[sample_idx == si, sample_idx == sj] = (k_ij + k_ij.T) / 2
359 | else:
360 | # fill out values in K for NN on diagonal
361 | K.iloc[sample_idx == si, sample_idx == sj] = k_ij
362 |
363 | Kn = K.copy()
364 | for i in samples:
365 | curr_K = K.iloc[sample_idx == i, sample_idx == i]
366 | i_norm = norm(curr_K, 1, axis=1)
367 | for j in samples:
368 | if i == j:
369 | continue
370 | else:
371 | curr_K = K.iloc[sample_idx == i, sample_idx == j]
372 | curr_norm = norm(curr_K, 1, axis=1)
373 | scale = np.minimum(1, i_norm / curr_norm) * beta
374 | Kn.iloc[sample_idx == i, sample_idx == j] = (
375 | curr_K.values * scale[:, None]
376 | )
377 |
378 | K = Kn
379 | W = np.array((theta * np.minimum(K, K.T)) + ((1 - theta) * np.maximum(K, K.T)))
380 | np.fill_diagonal(W, 0)
381 | G = pygsp.graphs.Graph(W)
382 | G2 = graphtools.Graph(
383 | X,
384 | knn=k,
385 | decay=a,
386 | beta=beta,
387 | kernel_symm="mnn",
388 | theta=theta,
389 | distance=metric,
390 | sample_idx=sample_idx,
391 | thresh=0,
392 | use_pygsp=True,
393 | )
394 | assert G.N == G2.N
395 | np.testing.assert_array_equal(G.dw, G2.dw)
396 | np.testing.assert_array_equal((G.W - G2.W).data, 0)
397 | assert isinstance(G2, graphtools.graphs.MNNGraph)
398 |
399 |
400 | def test_mnn_graph_decay():
401 | X, sample_idx = generate_swiss_roll()
402 | theta = 0.9
403 | k = 10
404 | a = 20
405 | metric = "euclidean"
406 | beta = 0.2
407 | samples = np.unique(sample_idx)
408 |
409 | K = np.zeros((len(X), len(X)))
410 | K[:] = np.nan
411 | K = pd.DataFrame(K)
412 |
413 | for si in samples:
414 | X_i = X[sample_idx == si] # get observations in sample i
415 | for sj in samples:
416 | batch_k = k if si == sj else k - 1
417 | X_j = X[sample_idx == sj] # get observation in sample j
418 | pdx_ij = cdist(X_i, X_j, metric=metric) # pairwise distances
419 | kdx_ij = np.sort(pdx_ij, axis=1) # get kNN
420 | e_ij = kdx_ij[:, batch_k] # dist to kNN
421 | pdxe_ij = pdx_ij / e_ij[:, np.newaxis] # normalize
422 | k_ij = np.exp(-1 * (pdxe_ij**a)) # apply alpha-decaying kernel
423 | if si == sj:
424 | K.iloc[sample_idx == si, sample_idx == sj] = (k_ij + k_ij.T) / 2
425 | else:
426 | # fill out values in K for NN on diagonal
427 | K.iloc[sample_idx == si, sample_idx == sj] = k_ij
428 |
429 | Kn = K.copy()
430 | for i in samples:
431 | curr_K = K.iloc[sample_idx == i, sample_idx == i]
432 | i_norm = norm(curr_K, 1, axis=1)
433 | for j in samples:
434 | if i == j:
435 | continue
436 | else:
437 | curr_K = K.iloc[sample_idx == i, sample_idx == j]
438 | curr_norm = norm(curr_K, 1, axis=1)
439 | scale = np.minimum(1, i_norm / curr_norm) * beta
440 | Kn.iloc[sample_idx == i, sample_idx == j] = (
441 | curr_K.values * scale[:, None]
442 | )
443 |
444 | K = Kn
445 | W = np.array((theta * np.minimum(K, K.T)) + ((1 - theta) * np.maximum(K, K.T)))
446 | np.fill_diagonal(W, 0)
447 | G = pygsp.graphs.Graph(W)
448 | G2 = graphtools.Graph(
449 | X,
450 | knn=k,
451 | decay=a,
452 | beta=beta,
453 | kernel_symm="mnn",
454 | theta=theta,
455 | distance=metric,
456 | sample_idx=sample_idx,
457 | thresh=0,
458 | use_pygsp=True,
459 | )
460 | assert G.N == G2.N
461 | np.testing.assert_array_equal(G.dw, G2.dw)
462 | np.testing.assert_array_equal((G.W - G2.W).data, 0)
463 | assert isinstance(G2, graphtools.graphs.MNNGraph)
464 |
465 |
466 | #####################################################
467 | # Check interpolation
468 | #####################################################
469 |
470 |
471 | # TODO: add interpolation tests
472 |
473 |
474 | def test_verbose():
475 | X, sample_idx = generate_swiss_roll()
476 | print()
477 | print("Verbose test: MNN")
478 | build_graph(
479 | X, sample_idx=sample_idx, kernel_symm="mnn", theta=0.5, n_pca=None, verbose=True
480 | )
481 |
482 |
483 | def test_set_params():
484 | X, sample_idx = generate_swiss_roll()
485 | G = build_graph(
486 | X, sample_idx=sample_idx, kernel_symm="mnn", theta=0.5, n_pca=None, thresh=1e-4
487 | )
488 | assert G.get_params() == {
489 | "n_pca": None,
490 | "random_state": 42,
491 | "kernel_symm": "mnn",
492 | "theta": 0.5,
493 | "anisotropy": 0,
494 | "beta": 1,
495 | "knn": 3,
496 | "decay": 10,
497 | "bandwidth": None,
498 | "distance": "euclidean",
499 | "thresh": 1e-4,
500 | "n_jobs": 1,
501 | }
502 | G.set_params(n_jobs=4)
503 | assert G.n_jobs == 4
504 | for graph in G.subgraphs:
505 | assert graph.n_jobs == 4
506 | assert graph.knn_tree.n_jobs == 4
507 | G.set_params(random_state=13)
508 | assert G.random_state == 13
509 | for graph in G.subgraphs:
510 | assert graph.random_state == 13
511 | G.set_params(verbose=2)
512 | assert G.verbose == 2
513 | for graph in G.subgraphs:
514 | assert graph.verbose == 2
515 | G.set_params(verbose=0)
516 | with assert_raises_message(
517 | ValueError, "Cannot update knn. Please create a new graph"
518 | ):
519 | G.set_params(knn=15)
520 | with assert_raises_message(
521 | ValueError, "Cannot update decay. Please create a new graph"
522 | ):
523 | G.set_params(decay=15)
524 | with assert_raises_message(
525 | ValueError, "Cannot update distance. Please create a new graph"
526 | ):
527 | G.set_params(distance="manhattan")
528 | with assert_raises_message(
529 | ValueError, "Cannot update thresh. Please create a new graph"
530 | ):
531 | G.set_params(thresh=1e-3)
532 | with assert_raises_message(
533 | ValueError, "Cannot update beta. Please create a new graph"
534 | ):
535 | G.set_params(beta=0.2)
536 | G.set_params(
537 | knn=G.knn, decay=G.decay, thresh=G.thresh, distance=G.distance, beta=G.beta
538 | )
539 |
--------------------------------------------------------------------------------
/test/test_utils.py:
--------------------------------------------------------------------------------
1 | from load_tests import assert_raises_message
2 |
3 | import graphtools
4 |
5 |
6 | def test_check_in():
7 | graphtools.utils.check_in(["hello", "world"], foo="hello")
8 | with assert_raises_message(
9 | ValueError, "foo value bar not recognized. Choose from ['hello', 'world']"
10 | ):
11 | graphtools.utils.check_in(["hello", "world"], foo="bar")
12 |
13 |
14 | def test_check_int():
15 | graphtools.utils.check_int(foo=5)
16 | graphtools.utils.check_int(foo=-5)
17 | with assert_raises_message(ValueError, "Expected foo integer, got 5.3"):
18 | graphtools.utils.check_int(foo=5.3)
19 |
20 |
21 | def test_check_positive():
22 | graphtools.utils.check_positive(foo=5)
23 | with assert_raises_message(ValueError, "Expected foo > 0, got -5"):
24 | graphtools.utils.check_positive(foo=-5)
25 | with assert_raises_message(ValueError, "Expected foo > 0, got 0"):
26 | graphtools.utils.check_positive(foo=0)
27 |
28 |
29 | def test_check_if_not():
30 | graphtools.utils.check_if_not(-5, graphtools.utils.check_positive, foo=-5)
31 | with assert_raises_message(ValueError, "Expected foo > 0, got -5"):
32 | graphtools.utils.check_if_not(-4, graphtools.utils.check_positive, foo=-5)
33 |
34 |
35 | def test_check_between():
36 | graphtools.utils.check_between(-5, -3, foo=-4)
37 | with assert_raises_message(ValueError, "Expected foo between -5 and -3, got -6"):
38 | graphtools.utils.check_between(-5, -3, foo=-6)
39 | with assert_raises_message(ValueError, "Expected v_max > -3, got -5"):
40 | graphtools.utils.check_between(-3, -5, foo=-6)
41 |
--------------------------------------------------------------------------------
/unittest.cfg:
--------------------------------------------------------------------------------
1 | [unittest]
2 | verbose = True
3 |
4 | [coverage]
5 | always-on = True
6 | coverage = graphtools
7 |
--------------------------------------------------------------------------------