├── .gitignore
├── .readthedocs.yaml
├── App_network_view.JPG
├── CITATION.cff
├── COPD_PI_test.py
├── LICENSE
├── ModellingFrameworks_v7.png
├── ModellingFrameworks_white.png
├── PathIntegrateGraphic.png
├── README.md
├── docs
├── docs
│ ├── gendocs_docs
│ │ └── reference
│ │ │ └── pathintegrate.md
│ ├── images
│ │ └── ModellingFrameworks_white.png
│ ├── index.md
│ └── input.md
└── mkdocs.yml
├── mkgendocs.yml
├── pages
├── About.py
├── DetailsView.py
└── __init__.py
├── plot_functs.py
├── quickstart.ipynb
├── requirements.txt
├── root_cmap.csv
├── setup.py
└── src
└── pathintegrate
├── __init__.py
├── app.py
├── data
├── ReactomePathwaysRelation.txt
├── Reactome_Homo_sapiens_pathways_multiomics_R85.gmt
├── copd_pvals.csv
├── metabolomics_example.csv
└── proteomics_example.csv
├── pathintegrate.py
├── plot.py
└── utils.py
/.gitignore:
--------------------------------------------------------------------------------
1 | # Byte-compiled / optimized / DLL files
2 | __pycache__/
3 | *.py[cod]
4 | *$py.class
5 |
6 | # C extensions
7 | *.so
8 |
9 | # Distribution / packaging
10 | .Python
11 | build/
12 | develop-eggs/
13 | dist/
14 | downloads/
15 | eggs/
16 | .eggs/
17 | lib/
18 | lib64/
19 | parts/
20 | sdist/
21 | var/
22 | wheels/
23 | share/python-wheels/
24 | *.egg-info/
25 | .installed.cfg
26 | *.egg
27 | MANIFEST
28 |
29 | # PyInstaller
30 | # Usually these files are written by a python script from a template
31 | # before PyInstaller builds the exe, so as to inject date/other infos into it.
32 | *.manifest
33 | *.spec
34 |
35 | # Installer logs
36 | pip-log.txt
37 | pip-delete-this-directory.txt
38 |
39 | # Unit test / coverage reports
40 | htmlcov/
41 | .tox/
42 | .nox/
43 | .coverage
44 | .coverage.*
45 | .cache
46 | nosetests.xml
47 | coverage.xml
48 | *.cover
49 | *.py,cover
50 | .hypothesis/
51 | .pytest_cache/
52 | cover/
53 |
54 | # Translations
55 | *.mo
56 | *.pot
57 |
58 | # Django stuff:
59 | *.log
60 | local_settings.py
61 | db.sqlite3
62 | db.sqlite3-journal
63 |
64 | # Flask stuff:
65 | instance/
66 | .webassets-cache
67 |
68 | # Scrapy stuff:
69 | .scrapy
70 |
71 | # Sphinx documentation
72 | docs/_build/
73 |
74 | # PyBuilder
75 | .pybuilder/
76 | target/
77 |
78 | # Jupyter Notebook
79 | .ipynb_checkpoints
80 |
81 | # IPython
82 | profile_default/
83 | ipython_config.py
84 |
85 | # pyenv
86 | # For a library or package, you might want to ignore these files since the code is
87 | # intended to run in multiple environments; otherwise, check them in:
88 | # .python-version
89 |
90 | # pipenv
91 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
92 | # However, in case of collaboration, if having platform-specific dependencies or dependencies
93 | # having no cross-platform support, pipenv may install dependencies that don't work, or not
94 | # install all needed dependencies.
95 | #Pipfile.lock
96 |
97 | # poetry
98 | # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
99 | # This is especially recommended for binary packages to ensure reproducibility, and is more
100 | # commonly ignored for libraries.
101 | # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
102 | #poetry.lock
103 |
104 | # pdm
105 | # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
106 | #pdm.lock
107 | # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
108 | # in version control.
109 | # https://pdm.fming.dev/#use-with-ide
110 | .pdm.toml
111 |
112 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
113 | __pypackages__/
114 |
115 | # Celery stuff
116 | celerybeat-schedule
117 | celerybeat.pid
118 |
119 | # SageMath parsed files
120 | *.sage.py
121 |
122 | # Environments
123 | .env
124 | .venv
125 | env/
126 | venv/
127 | ENV/
128 | env.bak/
129 | venv.bak/
130 |
131 | # Spyder project settings
132 | .spyderproject
133 | .spyproject
134 |
135 | # Rope project settings
136 | .ropeproject
137 |
138 | # mkdocs documentation
139 | /site
140 |
141 | # mypy
142 | .mypy_cache/
143 | .dmypy.json
144 | dmypy.json
145 |
146 | # Pyre type checker
147 | .pyre/
148 |
149 | # pytype static type analyzer
150 | .pytype/
151 |
152 | # Cython debug symbols
153 | cython_debug/
154 |
155 | # PyCharm
156 | # JetBrains specific template is maintained in a separate JetBrains.gitignore that can
157 | # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
158 | # and can be added to the global gitignore or merged into this file. For a more nuclear
159 | # option (not recommended) you can uncomment the following to ignore the entire idea folder.
160 | #.idea/
161 |
--------------------------------------------------------------------------------
/.readthedocs.yaml:
--------------------------------------------------------------------------------
1 | # Required
2 | version: 2
3 |
4 | build:
5 | os: ubuntu-20.04
6 | tools:
7 | python: "3.10"
8 |
9 | mkdocs:
10 | configuration: docs/mkdocs.yml
11 |
12 | # Optionally declare the Python requirements required to build your docs
13 | python:
14 | install:
15 | - requirements: requirements.txt
--------------------------------------------------------------------------------
/App_network_view.JPG:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/cwieder/PathIntegrate/f3071a7fb93cc866cec98bee9874782918d9cc53/App_network_view.JPG
--------------------------------------------------------------------------------
/CITATION.cff:
--------------------------------------------------------------------------------
1 | cff-version: 1.2.0
2 | message: "If you use this software, please cite it as below."
3 | authors:
4 | - family-names: "Wieder"
5 | given-names: "Cecilia"
6 | orcid: "https://orcid.org/0000-0003-1548-4346"
7 | - family-names: "Popham"
8 | given-names: "Jude"
9 | orcid: "https://orcid.org/0009-0004-1116-1034"
10 | title: "PathIntegrate Unsupervised"
11 | version: 1.0.0
12 | doi: 10.5281/zenodo.14060723
13 | date-released: 2024-11-09
14 | url: "https://github.com/cwieder/PathIntegrate"
15 |
--------------------------------------------------------------------------------
/COPD_PI_test.py:
--------------------------------------------------------------------------------
1 | import pandas as pd
2 | import numpy as np
3 | import pathintegrate
4 | import sspa
5 |
6 |
7 | md = pd.read_csv('H:/Documents/pathway-integration/COPDgene/COPDgene_phonotype.txt', sep='\t')
8 | prot = pd.read_csv('H:/Documents/pathway-integration/COPDgene/COPDgene_proteomics_UniProt.csv', index_col=0)
9 | metab = pd.read_csv('H:/Documents/pathway-integration/COPDgene/COPDgene_metabolomics_CHEBI_mapped.csv', index_col=0)
10 | trans = pd.read_csv('D:/COPDgene/Processed/COPDgene_transcriptomics_filt_Q1_scaled.csv', index_col=0)
11 | metab['Group'] = metab.index.map(dict(zip(md['sid'], md["COPD"])))
12 |
13 | metab = metab[metab['Group'].isin([0, 1])]
14 | intersect_samples = set(metab.index.tolist()) & set(prot.index.tolist()) & set(trans.index.tolist())
15 | prot = prot.loc[intersect_samples, :]
16 | metab = metab.loc[intersect_samples, :]
17 | trans = trans.loc[intersect_samples, :]
18 |
19 | mo_paths_all = pd.read_csv('D:/Pathway_databases\Reactome_multi_omics_ChEBI_Uniprot_Ensembl.csv', index_col=0, dtype=object)
20 |
21 | pi_model = pathintegrate.PathIntegrate(omics_data={'Metabolomics': metab, 'Proteomics':prot.iloc[:, :-1], 'Transcriptomics': trans.iloc[:, :-1]},
22 | metadata=metab['Group'],
23 | pathway_source=mo_paths_all,
24 | sspa_scoring='svd',
25 | min_coverage=2)
26 |
27 | copdgene_multi_view = pi_model.MultiView(ncomp=4)
28 |
29 | # launch the pathwy network explorer on a local server
30 | pathintegrate.launch_network_app(copdgene_multi_view, mo_paths_all)
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/ModellingFrameworks_v7.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/cwieder/PathIntegrate/f3071a7fb93cc866cec98bee9874782918d9cc53/ModellingFrameworks_v7.png
--------------------------------------------------------------------------------
/ModellingFrameworks_white.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/cwieder/PathIntegrate/f3071a7fb93cc866cec98bee9874782918d9cc53/ModellingFrameworks_white.png
--------------------------------------------------------------------------------
/PathIntegrateGraphic.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/cwieder/PathIntegrate/f3071a7fb93cc866cec98bee9874782918d9cc53/PathIntegrateGraphic.png
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # PathIntegrate
2 | PathIntegrate Python package for pathway-based multi-omics data integration
3 |
4 | 
5 | [](https://doi.org/10.5281/zenodo.14060723)
6 | [](https://www.gnu.org/licenses/gpl-3.0)
7 | 
8 |
9 |
10 | 
11 |
12 | #### Abstract
13 | >As terabytes of multi-omics data are being generated, there is an ever-increasing need for methods facilitating the integration and interpretation of such data. Current multi-omics integration methods typically output lists, clusters, or subnetworks of molecules related to an outcome. Even with expert domain knowledge, discerning the biological processes involved is a time-consuming activity. Here we propose PathIntegrate, a method for integrating multi-omics datasets based on pathways, designed to exploit knowledge of biological systems and thus provide interpretable models for such studies. PathIntegrate employs single-sample pathway analysis to transform multi-omics datasets from the molecular to the pathway-level, and applies a predictive single-view or multi-view model to integrate the data. Model outputs include multi-omics pathways ranked by their contribution to the outcome prediction, the contribution of each omics layer, and the importance of each molecule in a pathway.
14 |
15 | ## Features
16 | - Pathway-based multi-omics data integration using PathIntegrate Multi-View and Single-View models
17 | - Multi-View model: Integrates multiple omics datasets using a shared pathway-based latent space
18 | - Single-View model: Integrates multi-omics data into one set of multi-omics pathway scores and applies an SKlearn-compatible predictive model
19 | - Pathway importance
20 | - Sample prediction
21 | - NEW unsupervised SingleView models (dimensionality reduction and clustering in the pathway space)
22 | - SKlearn-like API for easy integration into existing pipelines
23 | - Support for multiple pathway databases, including KEGG, Reactome, PathBank, and custom GMT files
24 | - Support for multiple pathway scoring methods available via the [sspa](https://github.com/cwieder/py-ssPA) package
25 | - Cytoscape Network Viewer app for visualizing pathway-based multi-omics data integration results
26 |
27 | 
28 |
29 | ## System requirements
30 | ### Hardware
31 | At least 8BG RAM recommended. PathIntegrate models can run on a Google Colab notebook server (see walkthrough tutorial below with example data).
32 |
33 | ### Software
34 | PathIntegrate has been tested on MacOs, Windows 10 and Linux. Python 3.10 or higher is required. Python dependencies are listed in the requirements.txt file.
35 |
36 | ## Installation
37 | ```bash
38 | pip install PathIntegrate
39 | ```
40 |
41 | ## Tutorials and documentation
42 | Please see our Quickstart guide on [Google Colab](https://colab.research.google.com/drive/1MmGJp8I4JaIgFGNihYjaa4KJqYTGzdtv?usp=sharing)
43 |
44 | Full documentation and function reference for PathIntegrate can be found via our [ReadTheDocs page](https://cwieder.github.io/PathIntegrate/)
45 |
46 | ## Citing PathIntegrate
47 | If you use PathIntegrate in your research, please consider citing our paper:
48 | ```bibtex
49 | @article{Wieder2024,
50 | author = {Cecilia Wieder and Juliette Cooke and Clement Frainay and Nathalie Poupin and Russell Bowler and Fabien Jourdan and Katerina J. Kechris and Rachel P.J. Lai and Timothy Ebbels},
51 | doi = {10.1371/JOURNAL.PCBI.1011814},
52 | issue = {3},
53 | journal = {PLOS Computational Biology},
54 | month = {3},
55 | pages = {e1011814},
56 | pmid = {38527092},
57 | publisher = {Public Library of Science},
58 | title = {PathIntegrate: Multivariate modelling approaches for pathway-based multi-omics data integration},
59 | volume = {20},
60 | url = {https://journals.plos.org/ploscompbiol/article?id=10.1371/journal.pcbi.1011814},
61 | year = {2024},
62 | }
63 | ```
64 |
65 | ## PathIntegrate applications
66 | Check out the following papers to see how PathIntegrate has been used in research:
67 | - [Time-resolved, integrated multi-omic analysis reveals central role of amino acid pathways for defense responses in Arabidopsis thaliana](https://www.biorxiv.org/content/10.1101/2024.08.27.609849v1.full)
68 |
69 | ## License
70 | GNU GPL v3
71 |
72 | ## Contributors
73 | - Jude Popham @[judepops](https://github.com/judepops)
--------------------------------------------------------------------------------
/docs/docs/gendocs_docs/reference/pathintegrate.md:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/cwieder/PathIntegrate/f3071a7fb93cc866cec98bee9874782918d9cc53/docs/docs/gendocs_docs/reference/pathintegrate.md
--------------------------------------------------------------------------------
/docs/docs/images/ModellingFrameworks_white.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/cwieder/PathIntegrate/f3071a7fb93cc866cec98bee9874782918d9cc53/docs/docs/images/ModellingFrameworks_white.png
--------------------------------------------------------------------------------
/docs/docs/index.md:
--------------------------------------------------------------------------------
1 | # PathIntegrate
2 | PathIntegrate Python package for pathway-based multi-omics data integration
3 |
4 | 
5 |
6 | ## Features
7 | - Pathway-based multi-omics data integration using PathIntegrate Multi-View and Single-View models
8 | - Multi-View model: Integrates multiple omics datasets using a shared pathway-based latent space
9 | - Single-View model: Integrates multi-omics data into one set of multi-omics pathway scores and applies an SKlearn-compatible predictive model
10 | - Pathway importance
11 | - Sample prediction
12 | - SKlearn-like API for easy integration into existing pipelines
13 | - Support for multiple pathway databases, including KEGG and Reactome
14 | - Support for multiple pathway scoring methods available via the [sspa](https://github.com/cwieder/py-ssPA) package
15 | - Cytoscape Network Viewer app for visualizing pathway-based multi-omics data integration results
16 |
17 | 
18 |
19 | ## Installation
20 | ```bash
21 | pip install PathIntegrate
22 | ```
23 |
24 | ## Tutorials and documentation
25 | Please see our Quickstart guide on [Google Colab](https://colab.research.google.com/drive/1MmGJp8I4JaIgFGNihYjaa4KJqYTGzdtv?usp=sharing)
26 |
27 |
28 | ## Citing PathIntegrate
29 | If you use PathIntegrate in your research, please cite our paper:
30 | ```bibtex
31 | PathIntegrate: Multivariate modelling approaches for pathway-based multi-omics data integration
32 |
33 | Cecilia Wieder, Juliette Cooke, Clement Frainay, Nathalie Poupin, Jacob G. Bundy, Russell Bowler, Fabien Jourdan, Katerina J. Kechris, Rachel PJ Lai, Timothy Ebbels
34 |
35 | Manuscript in preparation
36 | ```
--------------------------------------------------------------------------------
/docs/docs/input.md:
--------------------------------------------------------------------------------
1 | # Input data for PathIntegrate
2 |
3 | ## Omics data
4 | Each multi-omics dataset should be in the form of a pandas DataFrame with samples as rows and molecules as columns. The index of the DataFrame should be the sample IDs, and the columns should be the molecule IDs.
5 |
6 | The molecule IDs should match those of the desired pathway database (i.e. ChEBI IDs, UniProt IDs, and ENSEMBL genes for Reactome; and KEGG IDs for KEGG). The values in the DataFrame should be the molecule abundances for each sample.
7 |
8 | !!! note
9 |
10 | The omics data should be pre-processed before inputting into PathIntegrate. PathIntgrate will automatically standardise the data, but it is recommended to log-transform the data before inputting into PathIntegrate.
11 |
12 |
13 | | sample_id | 1372 | 16610 | 72665 | 30915 | 37373 | Group |
14 | | ----------- | -------- | -------- | -------- | -------- | -------- | --------- |
15 | | INCOV092-BL | 1.541009 | 1.228611 | 1.224076 | 1.962028 | 0.652984 | COVID |
16 | | INCOV107-BL | 0.910486 | 2.169111 | 2.819585 | 1.234384 | 1.453066 | COVID |
17 | | INCOV020-BL | 0.831297 | 0.23298 | 2.126393 | 0.861793 | 2.877589 | COVID |
18 | | INCOV035-BL | 1.862011 | 0.792962 | 1.434183 | 1.223473 | 0.706152 | COVID |
19 | | INCOV122-BL | 1.416927 | 2.493762 | 1.77004 | 0.888144 | 0.693444 | Non-covid |
20 | | INCOV084-BL | 1.622171 | 1.021112 | 2.323956 | 0.573877 | 0.764003 | Non-covid |
21 | | INCOV086-BL | 1.610941 | 1.205343 | 0.83498 | 2.600065 | 1.700068 | Non-covid |
22 | | INCOV133-BL | 0.83727 | 2.144127 | 1.24222 | 1.035411 | 2.037335 | Non-covid |
23 |
24 | ## Pathways
25 | Pathways should be in the form of a pandas DataFrame with pathways as rows and molecules as columns. The index of the DataFrame should be the pathway IDs, and the columns should be the molecule IDs. The first column should be the pathway names or descriptions.
26 |
27 | Pathways can be from any pathway database, but the molecule IDs should match those of the omics data.
28 |
29 | Each pathway can either contain molecules from a single omics, or a combination of omics.
30 |
31 | !!! note
32 |
33 | Pathways can be downloaded using the [sspa package](github.com/cwieder/py-ssPA)
34 |
35 | | | Pathway_name | 0 | 1 | 2 | 3 | 4 |
36 | | - | ------------ | ------ | ------ | ------ | ------ | ------ |
37 | | 1 | Pathway_52 | Q13554 | P61289 | P05114 | P62081 | P54760 |
38 | | 2 | Pathway_53 | Q9Y243 | P17252 | | | |
39 | | 3 | Pathway_54 | 16708 | P06732 | P61289 | O00220 | O75914 |
40 | | 4 | Pathway_55 | O15264 | P25786 | | | |
41 | | 5 | Pathway_56 | P07858 | P62979 | Q9Y625 | P14778 | P12314 |
42 | | 6 | Pathway_57 | P18510 | P15260 | Q13557 | P32942 | P04818 |
43 | | 7 | Pathway_58 | P00738 | P37023 | P01588 | P63098 | P05362 |
44 | | 8 | Pathway_59 | P52798 | P15498 | | | |
--------------------------------------------------------------------------------
/docs/mkdocs.yml:
--------------------------------------------------------------------------------
1 | site_name: PathIntegrate Docs
2 |
3 | theme:
4 | name: "material"
5 | palette:
6 | primary: teal
7 | accent: teal
8 |
9 | docs_dir: 'docs'
10 | site_dir: 'site'
11 |
12 | markdown_extensions:
13 | - pymdownx.arithmatex:
14 | generic: true
15 | - admonition
16 | - pymdownx.details
17 | - pymdownx.superfences:
18 | custom_fences:
19 | - name: mermaid
20 | class: mermaid
21 | format: !!python/name:pymdownx.superfences.fence_code_format
22 |
23 |
24 | extra_javascript:
25 | - javascripts/mathjax.js
26 | - https://polyfill.io/v3/polyfill.min.js?features=es6
27 | - https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js
28 |
29 |
30 | plugins:
31 | - search
32 | - mkdocstrings:
33 | default_handler: python
34 | handlers:
35 | python:
36 | rendering:
37 | show_source: false
38 | options:
39 | docstring_style: google
40 | docstring_options:
41 | ignore_init_summary: no
42 | merge_init_into_class: no
43 | show_submodules: yes
44 |
45 | nav:
46 | - Home: index.md
47 | - Input data: input.md
48 | # - Tutorials:
49 | # - tutorials.md
50 | # - ssPA and SKLearn:
51 | # - gendocs_docs/reference/sklearn_sspa.md
52 | - Reference:
53 | - gendocs_docs/reference/pathintegrate.md
54 | # - gendocs_docs/reference/download_pathways.md
55 | # - gendocs_docs/reference/load_pathways.md
56 | # - gendocs_docs/reference/utils.md
57 | # - Pathway analysis:
58 | # - gendocs_docs/reference/ORA.md
59 | # - gendocs_docs/reference/GSEA.md
60 | # - Single sample methods:
61 | # - gendocs_docs/reference/SVD.md
62 | # - gendocs_docs/reference/kPCA.md
63 | # - gendocs_docs/reference/ssClustPA.md
64 | # - gendocs_docs/reference/ssGSEA.md
65 | # - gendocs_docs/reference/zscore.md
66 |
67 |
--------------------------------------------------------------------------------
/mkgendocs.yml:
--------------------------------------------------------------------------------
1 | sources_dir: docs/docs/gendocs_docs
2 | templates_dir: docs/docs/gendocs_templates
3 | repo: https://github.com/cwieder/pathintegrate
4 | version: master
5 |
6 | pages:
7 |
8 | - page: "reference/pathintegrate.md"
9 | source: "src/pathintegrate/pathintegrate.py"
10 | # functions:
11 | # - MultiView
12 | # - SingleView
13 | classes:
14 | - PathIntegrate
15 |
16 | # - page: "reference/identifier_conversion.md"
17 | # source: "src/sspa/identifier_conversion.py"
18 | # functions:
19 | # - identifier_conversion
20 | # - map_identifiers
21 |
22 | # - page: "reference/load_pathways.md"
23 | # source: "src/sspa/process_pathways.py"
24 | # functions:
25 | # - process_reactome
26 | # - process_kegg
27 | # - process_gmt
28 |
29 | # - page: "reference/utils.md"
30 | # source: "src/sspa/utils.py"
31 | # functions:
32 | # - load_example_data
33 | # - t_tests
34 | # - pathwaydf_to_dict
35 |
36 | # - page: "reference/ORA.md"
37 | # source: "src/sspa/sspa_ora.py"
38 | # classes:
39 | # - sspa_ora
40 |
41 | # - page: "reference/GSEA.md"
42 | # source: "src/sspa/sspa_gsea.py"
43 | # functions:
44 | # - sspa_gsea
45 |
46 | # - page: "reference/SVD.md"
47 | # source: "src/sspa/sspa_svd.py"
48 | # classes:
49 | # - sspa_SVD
50 |
51 | # - page: "reference/kPCA.md"
52 | # source: "src/sspa/sspa_kpca.py"
53 | # classes:
54 | # - sspa_KPCA
55 |
56 | # - page: "reference/ssClustPA.md"
57 | # source: "src/sspa/sspa_cluster.py"
58 | # classes:
59 | # - sspa_ssClustPA
60 |
61 | # # - page: "reference/GSVA.md"
62 | # # source: "src/sspa/sspa_gsva.py"
63 | # # functions:
64 | # # - sspa_gsva
65 |
66 | # - page: "reference/ssGSEA.md"
67 | # source: "src/sspa/sspa_ssGSEA.py"
68 | # classes:
69 | # - sspa_ssGSEA
70 |
71 | # - page: "reference/zscore.md"
72 | # source: "src/sspa/sspa_zscore.py"
73 | # classes:
74 | # - sspa_zscore
--------------------------------------------------------------------------------
/pages/About.py:
--------------------------------------------------------------------------------
1 | # import packages
2 | import pandas as pd
3 | import numpy as np
4 | import dash
5 | from dash import Dash, html, dcc, Input, Output, State, ctx
6 | import plotly.express as px
7 | import dash_cytoscape as cyto
8 | import matplotlib.pyplot as plt
9 | import matplotlib.colors as mcolors
10 | import seaborn as sns
11 | import networkx as nx
12 | import dash_bootstrap_components as dbc
13 | import matplotlib.cm as cm
14 | import matplotlib as matplotlib
15 | import svgwrite
16 | from datauri import DataURI
17 | from dash_bootstrap_components._components.Container import Container
18 | from pathlib import Path
19 | dash.register_page(__name__, path='/about')
20 |
21 |
22 | layout = html.Div(children=[
23 | html.H1(children='About'),
24 |
25 | html.Div(children='''
26 | This is our Home page content.
27 | '''),
28 |
29 | ])
--------------------------------------------------------------------------------
/pages/DetailsView.py:
--------------------------------------------------------------------------------
1 | # import packages
2 | import pandas as pd
3 | import numpy as np
4 | import dash
5 | from dash import Dash, html, dcc, Input, Output, State, ctx
6 | import plotly.express as px
7 | import dash_cytoscape as cyto
8 | import matplotlib.pyplot as plt
9 | import matplotlib.colors as mcolors
10 | import seaborn as sns
11 | import networkx as nx
12 | import dash_bootstrap_components as dbc
13 | import matplotlib.cm as cm
14 | import matplotlib as matplotlib
15 | import svgwrite
16 | from datauri import DataURI
17 | from dash_bootstrap_components._components.Container import Container
18 | from pathlib import Path
19 | dash.register_page(__name__, path='/details')
20 |
21 |
22 | layout = html.Div(children=[
23 | html.H1(children='Pathway details view'),
24 |
25 | html.Div(children='''
26 | This is our Home page content.
27 | '''),
28 |
29 | ])
--------------------------------------------------------------------------------
/pages/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/cwieder/PathIntegrate/f3071a7fb93cc866cec98bee9874782918d9cc53/pages/__init__.py
--------------------------------------------------------------------------------
/plot_functs.py:
--------------------------------------------------------------------------------
1 | import matplotlib.pyplot as plt
2 | import seaborn as sns
3 | import pandas as pd
4 | import numpy as np
5 | from cmcrameri import cm
6 |
7 | sns.set_style('ticks')
8 |
9 | def plot_block_importance(model):
10 | plt.figure(figsize=(7, 5))
11 | sns.heatmap(model.A_corrected_*100, cmap='cmc.devon_r', linewidth=5, square=True,
12 | cbar_kws={'label': '% variance explained in Y'},
13 | annot=True,
14 | vmin=0,
15 | vmax=100)
16 | plt.yticks([i + 0.5 for i in range(0, len(model.A_corrected_))], model.omics_names)
17 | plt.xticks([i+0.5 for i in range(0, 5)], [str(n+1) + ': ' + str(np.around(i*100, 1))+'%' for n, i in enumerate(model.explained_var_y_)])
18 | # plt.xticks([i+0.5 for i in range(0, 5)], range(1, 6))
19 | plt.xlabel('Component % explained variance in Y')
20 | plt.ylabel('Omics view')
21 | plt.tight_layout()
22 | # plt.savefig('../Figures/MBPLS_COPD_Model1_3o_block_importance.png', dpi=300)
23 | plt.show()
--------------------------------------------------------------------------------
/requirements.txt:
--------------------------------------------------------------------------------
1 | cmcrameri==1.3
2 | dash==2.14.1
3 | dash_bootstrap_components==1.5.0
4 | dash_cytoscape==0.3.0
5 | datauri==1.0.0
6 | matplotlib==3.8.1
7 | mbpls==1.0.4
8 | networkx==3.2.1
9 | numpy==1.26.1
10 | pandas==2.1.2
11 | plotly==5.18.0
12 | scikit_learn==1.3.2
13 | scipy==1.11.3
14 | seaborn==0.13.0
15 | setuptools==68.0.0
16 | sspa>=1.0.1
17 | statsmodels==0.14.0
18 | svgwrite==1.4.3
19 |
--------------------------------------------------------------------------------
/root_cmap.csv:
--------------------------------------------------------------------------------
1 | ,0
2 | R-HSA-1640170,#f77189
3 | R-HSA-5653656,#f77467
4 | R-HSA-9609507,#f17b32
5 | R-HSA-73894,#da8a32
6 | R-HSA-9709957,#c89332
7 | R-HSA-397014,#b99932
8 | R-HSA-162582,#ab9e31
9 | R-HSA-8953897,#9ba331
10 | R-HSA-9748784,#89a731
11 | R-HSA-1266738,#6ead31
12 | R-HSA-112316,#34b331
13 | R-HSA-8953854,#33b16a
14 | R-HSA-392499,#34b082
15 | R-HSA-1643685,#35ae92
16 | R-HSA-400253,#35ad9f
17 | R-HSA-69306,#36aca9
18 | R-HSA-382551,#37abb4
19 | R-HSA-5357801,#38aac0
20 | R-HSA-9612973,#39a8ce
21 | R-HSA-109582,#3ba5e3
22 | R-HSA-168256,#5e9ef4
23 | R-HSA-1430728,#8c94f4
24 | R-HSA-8963743,#ab89f4
25 | R-HSA-1500931,#c77df4
26 | R-HSA-1474244,#e36bf4
27 | R-HSA-4839726,#f55fe7
28 | R-HSA-74160,#f565ce
29 | R-HSA-1852241,#f669b9
30 | R-HSA-1474165,#f66da3
31 |
--------------------------------------------------------------------------------
/setup.py:
--------------------------------------------------------------------------------
1 | from setuptools import setup
2 | from pathlib import Path
3 | this_directory = Path(__file__).parent
4 | long_description = (this_directory / "README.md").read_text()
5 |
6 |
7 | setup(
8 | name='PathIntegrate',
9 | version='1.0.2',
10 | packages=['pathintegrate'],
11 | package_dir={'':'src'},
12 | url='https://github.com/cwieder/PathIntegrate',
13 | license='GNU 3.0',
14 | author='Cecilia Wieder',
15 | author_email='cw2019@ic.ac.uk',
16 | description='PathIntegrate: multivariate modelling approaches for pathway-based muti-omics integration',
17 | long_description=long_description,
18 | long_description_content_type='text/markdown',
19 | package_data={'pathintegrate': ['data/*']},
20 | classifiers=[
21 | 'Programming Language :: Python',
22 | 'Programming Language :: Python :: 3',
23 | 'Programming Language :: Python :: 3.10',
24 | ],
25 | install_requires=[
26 | 'cmcrameri',
27 | 'dash',
28 | 'dash-bootstrap-components',
29 | 'dash-cytoscape',
30 | 'datauri',
31 | 'mbpls',
32 | 'scikit-learn',
33 | 'networkx',
34 | 'setuptools',
35 | 'sspa>=1.0.1',
36 | 'statsmodels',
37 | 'svgwrite'
38 | ],
39 | )
40 |
--------------------------------------------------------------------------------
/src/pathintegrate/__init__.py:
--------------------------------------------------------------------------------
1 | from pkg_resources import get_distribution
2 | __version__ = get_distribution('pathintegrate').version
3 |
4 | from .pathintegrate import PathIntegrate
5 | from .app import launch_network_app
6 | from .plot import *
7 | from .utils import *
--------------------------------------------------------------------------------
/src/pathintegrate/app.py:
--------------------------------------------------------------------------------
1 | # PathIntegrate network explorer app
2 | # Takes a PathIntegrate model as input
3 |
4 | # import packages
5 | import pandas as pd
6 | import numpy as np
7 | import dash
8 | from dash import Dash, html, dcc, Input, Output, State, ctx
9 | import plotly.express as px
10 | import dash_cytoscape as cyto
11 | import matplotlib.pyplot as plt
12 | import matplotlib.colors as mcolors
13 | import seaborn as sns
14 | import networkx as nx
15 | import dash_bootstrap_components as dbc
16 | import matplotlib.cm as cm
17 | import matplotlib as matplotlib
18 | from dash_bootstrap_components._components.Container import Container
19 | from pathlib import Path
20 | from dash.exceptions import PreventUpdate
21 | from plotly.subplots import make_subplots
22 | import plotly.graph_objects as go
23 | import cmcrameri as cmc
24 | import pkg_resources
25 | import matplotlib.colorbar as cbar
26 | import base64
27 | from io import BytesIO
28 |
29 |
30 | # Save downloads to default Downloads folder
31 | downloads_path = str(Path.home() / "Downloads")
32 |
33 | # Load extra layouts
34 | cyto.load_extra_layouts()
35 |
36 | # Set stylesheet
37 | app = Dash(__name__, external_stylesheets=[dbc.themes.YETI], use_pages=False)
38 |
39 | # generate node colours based on model attributes
40 | def get_hex_colors(values, cmap):
41 | norm = plt.Normalize(min(values), max(values))
42 | cmap = plt.cm.get_cmap(cmap) # Change the colormap here as desired
43 |
44 | hex_colors = [mcolors.rgb2hex(cmap(norm(value))) for value in values]
45 | return hex_colors
46 |
47 | # find parent pathway for each pathway
48 | def find_root(G,child):
49 | parent = list(G.predecessors(child))
50 | if len(parent) == 0:
51 | return child
52 | else:
53 | return find_root(G, parent[0])
54 |
55 | # load the pathway database file from the data folder
56 | stream = pkg_resources.resource_stream(__name__, 'data/ReactomePathwaysRelation.txt')
57 | hierarchy = pd.read_csv(stream, sep='\t', header=None)
58 | hierarchy_hsa = hierarchy[hierarchy[0].str.contains('HSA')]
59 | hierarchy_hsa_parents = np.setdiff1d(hierarchy_hsa[0], hierarchy_hsa[1])
60 | hierarchy_hsa_all = pd.concat([hierarchy_hsa, pd.DataFrame([hierarchy_hsa_parents, hierarchy_hsa_parents], index=[0, 1]).T])
61 |
62 | # the default graph is the pathway hierarchy coloured by root pathway membership as defined by Reactome
63 | G = nx.from_pandas_edgelist(hierarchy_hsa, source=0, target=1, create_using=nx.DiGraph())
64 | hierarchy_hsa_all['Root'] = [find_root(G, i) for i in hierarchy_hsa_all[1]]
65 | root_cmap = dict(zip(set(hierarchy_hsa_all['Root']), sns.color_palette("husl", len(set(hierarchy_hsa_all['Root']))).as_hex()))
66 |
67 | cy_mo = nx.readwrite.json_graph.cytoscape_data(G)
68 |
69 | # another figure for the network legend
70 | def get_colorbar_image(values, cmap_name, title):
71 | fig, ax = plt.subplots(figsize=(6, 1))
72 | fig.subplots_adjust(bottom=0.5)
73 |
74 | norm = plt.Normalize(min(values), max(values))
75 | cmap = plt.cm.get_cmap(cmap_name) # Change the colormap here as desired
76 | # norm = mcolors.Normalize(vmin=min(values), vmax=max(values))
77 |
78 | cbar.ColorbarBase(ax, cmap=cmap, norm=norm, orientation='horizontal')
79 | ax.set_title(title)
80 |
81 | # Save the figure to a BytesIO object
82 | buf = BytesIO()
83 | plt.savefig(buf, format='png', bbox_inches='tight')
84 | plt.close(fig)
85 | buf.seek(0)
86 |
87 | return buf
88 |
89 |
90 | def encode_image(image):
91 | return base64.b64encode(image.read()).decode('ascii')
92 |
93 |
94 | # Network layout configuration
95 | SIDEBAR_STYLE = {
96 | "position": "fixed",
97 | "top": 0,
98 | "left": 0,
99 | "bottom": 0,
100 | "width": "16rem",
101 | "padding": "1rem",
102 | "padding-top": "5rem",
103 | "background-color": "#BBDEFB",
104 | # "padding": "6rem 1rem 2rem",
105 | }
106 | CONTENT_STYLE = {
107 | "margin-left": "16rem",
108 | "margin-right": "16rem",
109 | # "padding": "1rem 1rem",
110 | "padding-top": "4rem",
111 | "padding-bottom": "1rem",
112 | "padding-left": "1rem",
113 | "padding-right": "1rem",
114 | # "border":"2px black solid"
115 | "background-color": "#FFFFFF",
116 | }
117 |
118 | sidebar = html.Div(
119 | [
120 |
121 | html.P("Network options"),
122 | html.Hr(),
123 |
124 | html.P(
125 | "Layout option"
126 | ),
127 | dcc.Dropdown(
128 | id='dropdown-update-layout',
129 | value='random',
130 | clearable=False,
131 | options=[
132 | {'label': name.capitalize(), 'value': name}
133 | for name in ['random', 'cose', 'circle', 'grid', 'concentric', 'cola']
134 | ]),
135 | html.P(
136 | "Colour nodes by"
137 | ),
138 | dcc.Dropdown(
139 | id='dropdown-update-node-color',
140 | value='Hierarchy',
141 | clearable=False,
142 | options=[
143 | {'label': name.capitalize(), 'value': name}
144 | for name in ['Hierarchy', 'Feature importance', 'VIP (MultiView only)']
145 | ]),
146 | # html.P(
147 | # "Show omics"
148 | # ),
149 | # dcc.Dropdown(
150 | # id='dropdown-update-omics',
151 | # value='multi-omics',
152 | # clearable=False,
153 | # options=[
154 | # {'label': name.capitalize(), 'value': name}
155 | # for name in ['metabolomics', 'proteomics', 'multi-omics']
156 | # ]),
157 | html.P(
158 | "Export network"
159 | ),
160 |
161 | dbc.Button("SVG", color="primary", id='btn-get-svg'),
162 | dbc.Button("PNG", color="primary", id='btn-get-png'),
163 | dbc.Button("Network", color="primary", id='btn-get-gml'),
164 | dcc.Download(id="download-network")
165 | ],
166 | style=SIDEBAR_STYLE,
167 | )
168 |
169 |
170 |
171 |
172 | navbar = dbc.NavbarSimple(
173 | # children=[
174 | # dbc.NavItem(dbc.NavLink("Home", href="/")),
175 | # dbc.DropdownMenu(
176 | # children=[
177 | # dbc.DropdownMenuItem("Detail view", href="/details"),
178 | # dbc.DropdownMenuItem("About", href="/about"),
179 |
180 | # ],
181 | # nav=True,
182 | # in_navbar=True,
183 | # label="More",
184 | # ),
185 | # ],
186 | brand="PathIntegrate multi-omics pathway network explorer",
187 | brand_href="#",
188 | color="primary",
189 | dark=True,
190 | fixed='top',
191 | style={
192 | # "position": "fixed",
193 | # "top": 0,
194 | # "right": 0,
195 | # "bottom": 0,
196 | # "padding-bottom": "2rem",
197 | # "width": "20rem",
198 | # "padding": "2rem 1rem",
199 | # "background-color": "#BBDEFB",
200 | # "padding": "6rem 1rem 2rem",
201 | },
202 | )
203 |
204 | # default stylesheet
205 | default_stylesheet = [
206 | {
207 | 'selector': 'node',
208 | 'style': {
209 | 'background-color': 'data(color)',
210 | 'shape': 'ellipse',
211 | # 'label': 'data(label)',
212 | 'text-wrap': 'wrap',
213 | 'text-background-color': 'yellow',
214 | 'text-max-width': '120px',
215 | 'width': 'data(MO_coverage)',
216 | 'height':'data(MO_coverage)',
217 | 'text-justification': 'auto',
218 | 'font-family': ['Verdana', 'Roboto', 'Arial'],
219 | 'font-size': '0px'
220 | }
221 | },
222 | {
223 | 'selector': 'edge',
224 | 'style': {
225 | 'line-color': '#A3C4BC'
226 | }
227 | }
228 | ]
229 |
230 |
231 |
232 | # Callback for updating the graph layout
233 | @app.callback(Output('mo_graph', 'layout'), Input('dropdown-update-layout', 'value'))
234 | def update_layout(layout):
235 | return {
236 | 'name': layout,
237 | 'animate': True
238 | }
239 |
240 | # callback for updating node colour
241 | @app.callback(Output('mo_graph', 'stylesheet'),
242 | Input('dropdown-update-node-color', 'value'))
243 | def update_stylesheet(node_value):
244 | node_value_color = {'Hierarchy': 'data(color)', 'Feature importance': 'data(BetaColour)', 'VIP (MultiView only)': 'data(VIPColour)'}
245 |
246 | new_styles = [
247 | {
248 | 'selector': 'node',
249 | 'style': {
250 | 'background-color': node_value_color[node_value],
251 | 'border-width': '1px',
252 | 'border-color': 'black',
253 | 'background-fit': 'cover',
254 | 'height': 'data(MO_coverage)',
255 | 'width':'data(MO_coverage)'
256 | # 'background-image': bg_img[node_value]
257 | }
258 | },
259 | {
260 | 'selector': 'edge',
261 | 'style': {
262 | 'line-color': '#A3C4BC'
263 | }
264 | }]
265 |
266 |
267 | return default_stylesheet + new_styles
268 |
269 |
270 | @app.callback(Output('cytoscape-mouseoverNodeData-output-name', 'children'),
271 | Input('mo_graph', 'mouseoverNodeData'))
272 | def displayTapNodeData(data):
273 | if data:
274 | return data['label']
275 |
276 | @app.callback(Output('cytoscape-mouseoverNodeData-output-root', 'children'),
277 | Input('mo_graph', 'mouseoverNodeData'))
278 | def displayTapNodeData(data):
279 | if data:
280 | return data['Root']
281 |
282 | @app.callback(Output('cytoscape-mouseoverNodeData-output-coverage', 'children'),
283 | Input('mo_graph', 'mouseoverNodeData'))
284 | def displayTapNodeData(data):
285 | if data:
286 | return data['Coverage']
287 |
288 |
289 | # Download image
290 | @app.callback(
291 | Output("mo_graph", "generateImage"),
292 | [
293 | Input("btn-get-svg", "n_clicks"),
294 | Input("btn-get-png", "n_clicks")
295 | ])
296 | def get_image(get_clicks_svg, get_clicks_png):
297 |
298 | # File type to output of 'svg, 'png', 'jpg', or 'jpeg' (alias of 'jpg')
299 |
300 | # 'store': Stores the image data in 'imageData' !only jpg/png are supported
301 | # 'download'`: Downloads the image as a file with all data handling
302 | # 'both'`: Stores image data and downloads image as file.
303 | ftype='png'
304 | action = 'store'
305 |
306 | if ctx.triggered:
307 | if ctx.triggered_id != "tabs":
308 | action = "download"
309 | ftype = ctx.triggered_id.split("-")[-1]
310 | print(ftype)
311 |
312 | return {
313 | 'type': ftype,
314 | 'action': action
315 | }
316 |
317 | @app.callback(
318 | Output("download-network", "data"),
319 | Input("btn-get-gml", "n_clicks"),
320 | prevent_initial_call=True,
321 | )
322 | def download_network(n_clicks):
323 | download_path = downloads_path+"/PathIntegrate_network.gml"
324 | nx.write_gml(MO_graph, download_path)
325 | print("Network .gml file saved to: "+download_path)
326 |
327 | return nx.write_gml(MO_graph, download_path)
328 |
329 |
330 | @app.callback([Output("fig_molecular", "figure"),
331 | Output("pathway_selected", "children")],
332 | Input("dropdown", "value"))
333 | def update_bar_chart(pathway):
334 | if modelname == 'MultiView':
335 | pathways_dfs = []
336 | for k, v in molecule_importances.items():
337 | try:
338 | pdf = v[pathway]
339 | pdf = pdf.add_suffix(k)
340 | pathways_dfs.append(pdf)
341 | except KeyError:
342 | pass
343 |
344 | pathway_df_molec = pd.concat(pathways_dfs, axis=1)
345 | fig = make_subplots(rows=1, cols=len(pathways_dfs), shared_xaxes='rows')
346 |
347 | for i in range(0, len(pathways_dfs)):
348 | fig.add_trace(go.Bar(x=pathway_df_molec.index, y=pathway_df_molec.iloc[:,i], name=pathway_df_molec.columns[i]), row=1, col=i+1)
349 |
350 | return fig, name_dict[pathway]
351 | else:
352 | pathway_df_molec = molecule_importances[pathway]
353 | fig = go.Figure()
354 | fig.add_trace(go.Bar(x=pathway_df_molec.index.tolist(), y=pathway_df_molec['PC1_Loadings']))
355 | return fig, name_dict[pathway]
356 | # molecule level vis
357 | # @app.callback(
358 | # Output("bar-plot", "figure"),
359 | # Input("input-pathway", "value"))
360 | # def update_bar_chart(data):
361 | # if data:
362 | # mean_vals = metab.loc[:, metab.columns.isin(mo_paths_dict[data] + ['Group'])].groupby('Group').mean()
363 | # mean_vals_long = mean_vals.melt(ignore_index=False).reset_index()
364 | # fig = px.bar(mean_vals_long, x="variable", y="value",
365 | # color="Group", barmode="group")
366 | # return fig
367 |
368 | # update legend coloubar based on selected node colour
369 | @app.callback(Output('colorbar-image', 'src'),
370 | Input('dropdown-update-node-color', 'value'))
371 | def update_legend(node_value):
372 | # Generate the colorbar image in memory based on selected
373 | if node_value == 'Hierarchy':
374 | # hide the legend for hierarchy - do not display
375 | return None
376 |
377 | elif node_value == 'Feature importance':
378 | if modelname == 'MultiView':
379 | colorbar_image = get_colorbar_image(cmaps['Beta_cmap'][0], cmaps['Beta_cmap'][1], 'Beta')
380 | elif modelname == 'SingleView':
381 | if ['Beta_cmap' in cmaps]:
382 | colorbar_image = get_colorbar_image(cmaps['Beta_cmap'][0], cmaps['Beta_cmap'][1], 'Beta')
383 | elif ['Importance_cmap' in cmaps]:
384 | colorbar_image = get_colorbar_image(cmaps['Importance_cmap'][0], cmaps['Importance_cmap'][1],'Feature importance')
385 |
386 | # Encode the image to base64
387 | encoded_image = encode_image(colorbar_image)
388 | # Return the image source for the html.Img component
389 | return 'data:image/png;base64,{}'.format(encoded_image)
390 |
391 | elif node_value == 'VIP (MultiView only)':
392 | if modelname == 'MultiView':
393 | colorbar_image = get_colorbar_image(cmaps['VIP_cmap'][0], cmaps['VIP_cmap'][1],'VIP (scaled)')
394 | # Encode the image to base64
395 | encoded_image = encode_image(colorbar_image)
396 | # Return the image source for the html.Img component
397 | return 'data:image/png;base64,{}'.format(encoded_image)
398 | else:
399 | return None
400 |
401 |
402 | cmaps = {}
403 |
404 | # start local server
405 | def launch_network_app(pi_model, pathway_source, hierarchy_source='preloaded', p_values=None, **kwargs):
406 | global pathways_accessible
407 |
408 | # Add model attributes to network
409 | global name_dict
410 | name_dict = dict(zip(pathway_source.index, pathway_source['Pathway_name']))
411 | G.add_nodes_from([(node, {'Name': attr, 'label': attr}) for (node, attr) in name_dict.items()])
412 |
413 | global modelname
414 | modelname = pi_model.name
415 |
416 |
417 | if pi_model.name == 'MultiView':
418 | pathways_accessible = list(set(sum([i.columns.tolist() for i in pi_model.sspa_scores.values()], [])))
419 | # add beta as node colour
420 | betas_cmap = dict(zip(pathways_accessible, get_hex_colors(pi_model.beta, 'RdBu')))
421 | G.add_nodes_from([(node, {'BetaColour': attr}) for (node, attr) in betas_cmap.items()])
422 |
423 | # add vip as node colour
424 | vip_cmap = dict(zip(pathways_accessible, get_hex_colors(pi_model.vip['VIP_scaled'].tolist(), 'Blues')))
425 | G.add_nodes_from([(node, {'VIPColour': attr}) for (node, attr) in vip_cmap.items()])
426 |
427 | cmaps['VIP_cmap'] = [pi_model.vip['VIP_scaled'].tolist(), 'Blues']
428 | cmaps['Beta_cmap'] = [pi_model.beta, 'RdBu']
429 |
430 |
431 | if pi_model.name == 'SingleView':
432 | pathways_accessible = pi_model.sspa_scores.columns.tolist()
433 | # add beta as node colour
434 |
435 | # if logistic or svm use coef_ attribute
436 | # if random forest use feature_importances_
437 | if hasattr(pi_model, 'coef_'):
438 | betas_cmap = dict(zip(pathways_accessible, get_hex_colors(pi_model.coef_[0], 'RdBu')))
439 | G.add_nodes_from([(node, {'BetaColour': attr}) for (node, attr) in betas_cmap.items()])
440 | cmaps['Beta_cmap'] = [pi_model.coef_[0], 'RdBu']
441 | elif hasattr(pi_model, 'feature_importances_'):
442 | betas_cmap = dict(zip(pathways_accessible, get_hex_colors(pi_model.feature_importances_, 'Blues')))
443 | G.add_nodes_from([(node, {'BetaColour': attr}) for (node, attr) in betas_cmap.items()])
444 | cmaps['Importane_cmap'] = [pi_model.feature_importances_, 'Blues']
445 |
446 | # filter root pathways for pathways accessible by the model
447 | hierarchy_hsa_all_filt = hierarchy_hsa_all[hierarchy_hsa_all[1].isin(pathways_accessible)]
448 | root_cmap = dict(zip(set(hierarchy_hsa_all_filt['Root']), sns.color_palette("husl", len(set(hierarchy_hsa_all_filt['Root']))).as_hex()))
449 |
450 | G.add_nodes_from([(node, {'Root': attr,
451 | 'RootCol': root_cmap[attr],
452 | 'color': root_cmap[attr],
453 | 'RootName': name_dict[attr]}) for (node, attr) in dict(zip(hierarchy_hsa_all_filt[1], hierarchy_hsa_all_filt['Root'])).items()])
454 | G.add_nodes_from([(node, {'MO_coverage': np.sqrt(attr)*2.5}) for (node, attr) in pi_model.coverage.items()])
455 | G.add_nodes_from([(node, {'Coverage': attr}) for (node, attr) in pi_model.coverage.items()])
456 | if p_values:
457 | pval_cmap = dict(zip(p_values.keys(), get_hex_colors(p_values.values(), 'cmc.lajolla_r')))
458 | G.add_nodes_from([(node, {'PvalColour': attr}) for (node, attr) in pval_cmap.items()])
459 |
460 | # add molecular importances for plotting
461 | global molecule_importances
462 | if hasattr(pi_model, 'molecular_importance'):
463 | molecule_importances = pi_model.molecular_importance
464 |
465 | # only show nodes with sufficient coverage
466 | global MO_graph
467 | MO_graph = G.subgraph(pathways_accessible)
468 | cy_mo = nx.readwrite.json_graph.cytoscape_data(MO_graph)
469 | # network generation
470 | content = html.Div(
471 | cyto.Cytoscape(
472 | id='mo_graph',
473 | layout={'name': 'random'},
474 | style={'width': '100%', 'height': '800px'},
475 | elements=cy_mo['elements']['nodes'] + cy_mo['elements']['edges'],
476 | stylesheet=default_stylesheet
477 | ),
478 | # style=CONTENT_STYLE
479 | )
480 |
481 |
482 |
483 | legend_panel = html.Div(children=[
484 | html.Center([
485 | html.Img(id='colorbar-image')
486 | ])
487 | ])
488 |
489 | sidebar2 = html.Div(
490 | [html.P("Node information"),
491 | html.Hr(),
492 | dbc.ListGroup(
493 | [
494 | dbc.ListGroupItem(
495 | html.Div(
496 | [html.P("Pathway name"), html.P(id='cytoscape-mouseoverNodeData-output-name')
497 | ])),
498 | dbc.ListGroupItem(html.Div(
499 | [html.P("Parent pathway"), html.P(id='cytoscape-mouseoverNodeData-output-root')
500 | ])),
501 | dbc.ListGroupItem(html.Div(
502 | [html.P("Coverage"), html.P(id='cytoscape-mouseoverNodeData-output-coverage')
503 | ])),
504 | ]),
505 |
506 | html.Br(),
507 | # Legend for node colours
508 | html.P("Node colour legend"),
509 | html.Hr(),
510 | # make a legend for the root pathway colours
511 | html.Div([
512 | html.P("Root pathway"),
513 | dbc.ListGroup(
514 | [
515 | dbc.ListGroupItem(
516 | html.Div(
517 | [html.P(i), html.P(name_dict[i])
518 | ], style={'background-color': root_cmap[i]})
519 | ) for i in root_cmap.keys()
520 | ]),
521 | ]),
522 | html.Br(),
523 |
524 | ],
525 | style={
526 | "position": "fixed",
527 | "top": 0,
528 | "right": 0,
529 | "bottom": 0,
530 | "width": "16rem",
531 | "padding": "1rem",
532 | "padding-top": "5rem",
533 | "background-color": "#BBDEFB",
534 | },
535 | )
536 |
537 |
538 |
539 | app.layout = html.Div([
540 | navbar,
541 | sidebar,
542 | sidebar2,
543 | dcc.Tabs([
544 | dcc.Tab(label='Network', children=[
545 | legend_panel,
546 | content,
547 | ]),
548 | dcc.Tab(label='Molecular importance', children=[
549 | html.Div([
550 | html.Br(),
551 | html.H4(
552 | "Select a pathway from the dropdown menu to view molecular importance:"),
553 | dcc.Dropdown(pathways_accessible,
554 | pathways_accessible[0],
555 | placeholder="Select a pathway",
556 | id="dropdown"),
557 | html.Br(),
558 | html.P(id="pathway_selected")
559 | ]),
560 | dcc.Graph(id="fig_molecular"),
561 |
562 | ]),
563 | ])
564 | ],
565 | style=CONTENT_STYLE
566 |
567 | )
568 |
569 | # app.layout = dbc.Container([
570 | # html.Div([ dcc.Location(id="url",refresh=False),
571 | # navbar,
572 | # sidebar,
573 | # content,
574 | # sidebar2,
575 | # ]),],fluid=True)
576 | # app.layout = html.Div([dcc.Location(id="url"), navbar, sidebar, content, sidebar2])
577 | app.run()
578 |
579 |
580 |
581 |
--------------------------------------------------------------------------------
/src/pathintegrate/pathintegrate.py:
--------------------------------------------------------------------------------
1 | import pandas as pd
2 | import numpy as np
3 | import sklearn.decomposition
4 | import sspa
5 | import sklearn
6 | from mbpls.mbpls import MBPLS
7 | from pathintegrate.app import launch_network_app
8 | from sklearn.preprocessing import StandardScaler
9 | from sklearn.pipeline import Pipeline
10 | from sklearn.model_selection import cross_val_score, GridSearchCV
11 | import scipy
12 | import seaborn as sns
13 | import matplotlib.pyplot as plt
14 | import requests
15 | import json
16 | from sklearn.metrics import confusion_matrix
17 | import plotly.graph_objects as go
18 | from io import BytesIO
19 | import base64
20 |
21 | class PathIntegrate:
22 | '''PathIntegrate class for multi-omics pathway integration.
23 |
24 | Args:
25 | omics_data (dict): Dictionary of omics data. Keys are omics names, values are pandas DataFrames containing omics data where rows contain samples and columns reprsent features.
26 | metadata (pandas.Series): Metadata for samples. Index is sample names, values are class labels.
27 | pathway_source (pandas.DataFrame): GMT style pathway source data. Must contain column 'Pathway_name'.
28 | sspa_scoring (object, optional): Scoring method for ssPA. Defaults to sspa.sspa_SVD. Options are sspa.sspa_SVD, sspa.sspa_ssGSEA, sspa.sspa_KPCA, sspa.sspa_ssClustPA, sspa.sspa_zscore.
29 | min_coverage (int, optional): Minimum number of molecules required in a pathway. Defaults to 3.
30 |
31 | Attributes:
32 | omics_data (dict): Dictionary of omics data. Keys are omics names, values are pandas DataFrames.
33 | omics_data_scaled (dict): Dictionary of omics data scaled to mean 0 and unit variance. Keys are omics names, values are pandas DataFrames.
34 | metadata (pandas.Series): Metadata for samples. Index is sample names, values are class labels.
35 | pathway_source (pandas.DataFrame): Pathway source data.
36 | pathway_dict (dict): Dictionary of pathways. Keys are pathway names, values are lists of molecules.
37 | sspa_scoring (object): Scoring method for SSPA.
38 | min_coverage (int): Minimum number of molecules required to cover a pathway.
39 | sspa_method (object): SSPA scoring method.
40 | sspa_scores_mv (dict): Dictionary of SSPA scores for each omics data. Keys are omics names, values are pandas DataFrames.
41 | sspa_scores_sv (pandas.DataFrame): SSPA scores for all omics data concatenated.
42 | coverage (dict): Dictionary of pathway coverage. Keys are pathway names, values are number of omics covering the pathway.
43 | mv (object): Fitted MultiView model.
44 | sv (object): Fitted SingleView model.
45 | labels (pandas.Series): Class labels for samples. Index is sample names, values are class labels.
46 | '''
47 |
48 | def __init__(self, omics_data:dict, metadata, pathway_source, sspa_scoring=sspa.sspa_SVD, min_coverage=3):
49 | self.omics_data = omics_data
50 | self.omics_data_scaled = {k: pd.DataFrame(StandardScaler().fit_transform(v), columns=v.columns, index=v.index) for k, v in self.omics_data.items()}
51 | self.metadata = metadata
52 | self.pathway_source = pathway_source
53 | self.pathway_dict = sspa.utils.pathwaydf_to_dict(pathway_source)
54 | self.sspa_scoring = sspa_scoring
55 | self.min_coverage = min_coverage
56 |
57 | # sspa_methods = {'svd': sspa.sspa_SVD, 'ssGSEA': sspa.sspa_ssGSEA, 'kpca': sspa.sspa_KPCA, 'ssClustPA': sspa.sspa_ssClustPA, 'zscore': sspa.sspa_zscore}
58 | self.sspa_method = self.sspa_scoring
59 | self.sspa_scores_mv = None
60 | self.sspa_scores_sv = None
61 | self.coverage = self.get_multi_omics_coverage()
62 |
63 | self.mv = None
64 | self.sv = None
65 | self.sv_us = None
66 |
67 | self.labels = self.metadata
68 |
69 | def get_multi_omics_coverage(self):
70 | all_molecules = sum([i.columns.tolist() for i in self.omics_data.values()], [])
71 | coverage = {k: len(set(all_molecules).intersection(set(v))) for k, v in self.pathway_dict.items()}
72 | return coverage
73 |
74 | def MultiView(self, ncomp=2):
75 | """Fits a PathIntegrate MultiView model using MBPLS.
76 |
77 | Args:
78 | ncomp (int, optional): Number of components. Defaults to 2.
79 |
80 | Returns:
81 | object: Fitted PathIntegrate MultiView model.
82 | """
83 |
84 | print('Generating pathway scores...')
85 | sspa_scores_ = [self.sspa_method(self.pathway_source, self.min_coverage) for i in self.omics_data_scaled.values()]
86 | sspa_scores = [sspa_scores_[n].fit_transform(i) for n, i in enumerate(self.omics_data_scaled.values())]
87 | # sspa_scores = [self.sspa_method(self.pathway_source, self.min_coverage).fit_transform(i) for i in self.omics_data_scaled.values()]
88 | # sspa_scores = [self.sspa_method(i, self.pathway_source, self.min_coverage, return_molecular_importance=True) for i in self.omics_data.values()]
89 |
90 | self.sspa_scores_mv = dict(zip(self.omics_data.keys(), sspa_scores))
91 | print('Fitting MultiView model')
92 | try:
93 | mv = MBPLS(n_components=ncomp)
94 | mv.fit([i.copy(deep=True) for i in self.sspa_scores_mv.values()], self.labels)
95 | except ValueError:
96 | print('Error: binary class labels are required for Multi-View (mbpls) model')
97 |
98 | # compute VIP and scale VIP across omics
99 | vip_scores = VIP_multiBlock(mv.W_, mv.Ts_, mv.P_, mv.V_)
100 | vip_df = pd.DataFrame(vip_scores, index=sum([i.columns.tolist() for i in self.sspa_scores_mv.values()], []))
101 | vip_df['Name'] = vip_df.index.map(dict(zip(self.pathway_source.index, self.pathway_source['Pathway_name'])))
102 | vip_df['Source'] = sum([[k] * v.shape[1] for k, v in self.sspa_scores_mv.items()], [])
103 | vip_df['VIP_scaled'] = vip_df.groupby('Source')[0].transform(lambda x: StandardScaler().fit_transform(x.values[:,np.newaxis]).ravel())
104 | vip_df['VIP'] = vip_scores
105 | mv.name = 'MultiView'
106 |
107 | # only some sspa methods can return the molecular importance
108 | if hasattr(sspa_scores_[0], 'molecular_importance'):
109 | mv.molecular_importance = dict(zip(self.omics_data.keys(), [i.molecular_importance for i in sspa_scores_]))
110 | mv.beta = mv.beta_.flatten()
111 | mv.vip = vip_df
112 | mv.omics_names = list(self.omics_data.keys())
113 | mv.sspa_scores = self.sspa_scores_mv
114 | mv.coverage = self.coverage
115 | self.mv = mv
116 |
117 | return self.mv
118 |
119 | def SingleView(self, model=sklearn.linear_model.LogisticRegression, model_params=None):
120 | """Fits a PathIntegrate SingleView model using an SKLearn-compatible predictive model.
121 |
122 | Args:
123 | model (object, optional): SKlearn prediction model class. Defaults to sklearn.linear_model.LogisticRegression.
124 | model_params (_type_, optional): Model-specific hyperparameters. Defaults to None.
125 |
126 | Returns:
127 | object: Fitted PathIntegrate SingleView model.
128 | """
129 |
130 | concat_data = pd.concat(self.omics_data_scaled.values(), axis=1)
131 | print('Generating pathway scores...')
132 |
133 | sspa_scores = self.sspa_method(self.pathway_source, self.min_coverage)
134 | self.sspa_scores_sv = sspa_scores.fit_transform(concat_data)
135 |
136 | if model_params:
137 | sv = model(**model_params) # ** this is inputed into the scikit learn model
138 | else:
139 | sv = model()
140 | print('Fitting SingleView model')
141 |
142 | # fitting the model
143 |
144 | sv.fit(X=self.sspa_scores_sv, y=self.labels)
145 | sv.sspa_scores = self.sspa_scores_sv
146 | sv.name = 'SingleView'
147 | sv.coverage = self.coverage
148 |
149 | # only some sspa methods can return the molecular importance
150 | if hasattr(sspa_scores, 'molecular_importance'):
151 | sv.molecular_importance = sspa_scores.molecular_importance
152 | self.sv = sv
153 |
154 | return self.sv
155 |
156 |
157 | def SingleViewClust(self, model=sklearn.cluster.KMeans,n_clusters_range=(2, 10), model_params=None, use_pca=True, pca_params=None, consensus_clustering=False, n_runs=10, auto_n_clusters=False, subsample_fraction=0.8, return_plot=False, return_ground_truth_plot=False, return_confusion_matrix=False, return_metrics_table=False):
158 | """
159 | Fits a PathIntegrate SingleView Unsupervised model using an SKLearn-compatible KMeans model.
160 | Credit: Jude Popham
161 |
162 | Args:
163 | model (object, optional): SKLearn clustering model class. Defaults to sklearn.cluster.KMeans.
164 | model_params (dict, optional): Model-specific hyperparameters. Defaults to None.
165 | use_pca (bool, optional): Whether to perform PCA before clustering. Defaults to False.
166 | pca_params (dict, optional): PCA-specific hyperparameters. Defaults to None.
167 | consensus_clustering (bool, optional): Whether to perform consensus clustering. Defaults to False.
168 | n_runs (int, optional): Number of runs for consensus clustering. Defaults to 10.
169 | auto_n_clusters (bool, optional): Automatically determine the optimal number of clusters. Defaults to False.
170 | n_clusters_range (tuple, optional): Range of cluster numbers to evaluate for optimal clusters. Defaults to (2, 10).
171 | subsample_fraction (float, optional): Fraction of samples to use for each consensus clustering run. Defaults to 0.8.
172 | return_plot (bool, optional): Whether to return a plot of the clustering result. Defaults to False.
173 | return_ground_truth_plot (bool, optional): Whether to return a plot comparing the clustering result with ground truth. Defaults to False.
174 | return_confusion_matrix (bool, optional): Whether to return a plot comparing different clustering algorithms. Defaults to False.
175 | return_metrics_table (bool, optional): Whether to return a table of clustering evaluation metrics. Defaults to False.
176 |
177 | Returns:
178 | object: Fitted PathIntegrate SingleView Clustering model with various plots saved inside.
179 |
180 | """
181 |
182 | # function to normalise the metrics later on
183 | def normalize_score(score, score_min, score_max):
184 | return (score - score_min) / (score_max - score_min)
185 |
186 | # forming the concatenated data
187 | concat_data = pd.concat(self.omics_data_scaled.values(), axis=1)
188 | print('Generating pathway scores...')
189 | sspa_scores = self.sspa_method(self.pathway_source, self.min_coverage)
190 | self.sspa_scores_sv = sspa_scores.fit_transform(concat_data)
191 | combined_data_scaled = StandardScaler().fit_transform(self.sspa_scores_sv)
192 | combined_data_final = pd.DataFrame(combined_data_scaled, index=self.sspa_scores_sv.index, columns=self.sspa_scores_sv.columns)
193 | self.sspa_scores_sv = combined_data_final
194 |
195 | # if using PCA
196 | if use_pca:
197 | print('Performing PCA...')
198 | if pca_params is None:
199 | pca_params = {'n_components': min(concat_data.shape[1], 50)}
200 | pca = sklearn.decomposition.PCA(**pca_params)
201 | pca_components = pca.fit_transform(self.sspa_scores_sv)
202 | component_names = [f'PC{i+1}' for i in range(pca_components.shape[1])]
203 | self.sspa_scores_sv = pd.DataFrame(data=pca_components, columns=component_names, index=self.sspa_scores_sv.index)
204 | else:
205 | print('Not Using PCA...')
206 |
207 | # if no model parameters
208 | if model_params is None:
209 | model_params = {}
210 |
211 | # if automatically determining clusters
212 | if auto_n_clusters:
213 | print('Determining optimal number of clusters...')
214 | best_score = -1
215 | best_n_clusters = None
216 | silhouette_scores = []
217 | for n_clusters in range(*n_clusters_range):
218 | sv_clust = model(n_clusters=n_clusters, **model_params)
219 | labels = sv_clust.fit_predict(self.sspa_scores_sv)
220 | silhouette_avg = sklearn.metrics.silhouette_score(self.sspa_scores_sv, labels)
221 | silhouette_scores.append(silhouette_avg)
222 | if silhouette_avg > best_score:
223 | best_score = silhouette_avg
224 | best_n_clusters = n_clusters
225 | model_params['n_clusters'] = best_n_clusters
226 | print(f'Optimal number of clusters determined: {best_n_clusters}')
227 |
228 | # if using consensus clustering
229 | # please provide subsample size
230 | if consensus_clustering and n_runs > 0:
231 | n_samples = self.sspa_scores_sv.shape[0]
232 | consensus_matrix = np.zeros((n_samples, n_samples))
233 | for run in range(n_runs):
234 | print(f'Run {run + 1}/{n_runs}')
235 | subsample_idx = np.random.choice(n_samples, int(subsample_fraction * n_samples), replace=False)
236 | subsample_data = self.sspa_scores_sv.iloc[subsample_idx]
237 | sv_clust = model(**(model_params or {}))
238 | labels = sv_clust.fit_predict(subsample_data)
239 | for i in range(len(subsample_idx)):
240 | for j in range(i + 1, len(subsample_idx)):
241 | if labels[i] == labels[j]:
242 | consensus_matrix[subsample_idx[i], subsample_idx[j]] += 1
243 | consensus_matrix[subsample_idx[j], subsample_idx[i]] += 1
244 | consensus_matrix /= n_runs
245 | consensus_labels = model(n_clusters=model_params['n_clusters']).fit_predict(consensus_matrix)
246 | else:
247 | sv_clust = model(**(model_params or {}))
248 | consensus_labels = sv_clust.fit_predict(self.sspa_scores_sv)
249 |
250 | # saving the variables in the object
251 | self.sv_clust = sv_clust
252 | self.sv_clust.sspa_scores = self.sspa_scores_sv
253 | self.sv_clust.labels_ = consensus_labels
254 | self.sv_clust.name = 'SingleViewClust'
255 |
256 | print('Calculating clustering metrics...')
257 |
258 | # various metrics caluclated
259 | silhouette_avg = sklearn.metrics.silhouette_score(self.sspa_scores_sv, consensus_labels)
260 | calinski_harabasz = sklearn.metrics.calinski_harabasz_score(self.sspa_scores_sv, consensus_labels)
261 | davies_bouldin = sklearn.metrics.davies_bouldin_score(self.sspa_scores_sv, consensus_labels)
262 |
263 | # normalising their scores using the previous function
264 | silhouette_norm = normalize_score(silhouette_avg, -1, 1)
265 | calinski_harabasz_norm = normalize_score(calinski_harabasz, 0, np.max([calinski_harabasz]))
266 | davies_bouldin_norm = normalize_score(davies_bouldin, 0, np.max([davies_bouldin]))
267 | davies_bouldin_norm = 1 - davies_bouldin_norm
268 | combined_score = (silhouette_norm + calinski_harabasz_norm + davies_bouldin_norm) / 3
269 |
270 | # saving the metrics
271 | self.sv_clust.metrics = {
272 | 'Silhouette_Score': silhouette_avg,
273 | }
274 |
275 | # creating a clustering plot
276 | if return_plot:
277 | consensus_labels_series = pd.Series(consensus_labels, index=self.sspa_scores_sv.index, name='Consensus_Cluster')
278 | sspa_scores_labels = self.sspa_scores_sv
279 | sspa_scores_labels['Consensus_Cluster'] = consensus_labels_series
280 | fig_clust = plt.figure(figsize=(10, 8))
281 | sns.scatterplot(x=sspa_scores_labels.iloc[:, 0], y=sspa_scores_labels.iloc[:, 1], hue=sspa_scores_labels['Consensus_Cluster'], palette='coolwarm', s=100, edgecolor='black')
282 | plt.title('Clustering Results', fontsize=20)
283 | plt.xlabel('Component 1', fontsize=16)
284 | plt.ylabel('Component 2', fontsize=16)
285 | plt.xticks(fontsize=14)
286 | plt.yticks(fontsize=14)
287 | plt.legend(title='Cluster', title_fontsize=16, fontsize=14)
288 | plt.grid(True)
289 | plt.show()
290 | sv_clust.clusters_plot = fig_clust
291 |
292 | # creating a ground truth plot for comparison
293 | if return_ground_truth_plot:
294 | metadata_pca = self.metadata.to_frame(name='Who_Group')
295 | sspa_scores_meta = pd.concat([self.sspa_scores_sv, metadata_pca], axis=1)
296 | fig_ground = plt.figure(figsize=(10, 8))
297 | sns.scatterplot(x=sspa_scores_meta.iloc[:, 0], y=sspa_scores_meta.iloc[:, 1], hue=sspa_scores_meta['Who_Group'], palette='coolwarm', s=100, edgecolor='black')
298 | plt.title('Ground Truth Labels', fontsize=20)
299 | plt.xlabel('Component 1', fontsize=16)
300 | plt.ylabel('Component 2', fontsize=16)
301 | plt.xticks(fontsize=14)
302 | plt.yticks(fontsize=14)
303 | plt.legend(title='Ground Truth', title_fontsize=16, fontsize=14)
304 | plt.grid(True)
305 | plt.show()
306 | sv_clust.ground_truth_plot = fig_ground
307 |
308 | # creating a confusion matrix to compare labels
309 | if return_confusion_matrix:
310 | metadata_pca = self.metadata.to_frame(name='Who_Group')
311 | sspa_scores_meta = pd.concat([self.sspa_scores_sv, metadata_pca], axis=1)
312 | consensus_labels_series = pd.Series(consensus_labels, index=sspa_scores_meta.index, name='Consensus_Cluster')
313 | sspa_scores_meta['Consensus_Cluster'] = consensus_labels_series
314 | confusion_df = pd.crosstab(sspa_scores_meta['Who_Group'], sspa_scores_meta['Consensus_Cluster'])
315 | normalized_confusion_df = confusion_df.div(confusion_df.sum(axis=1), axis=0)
316 | fig = go.Figure(data=go.Heatmap(
317 | z=normalized_confusion_df.values,
318 | x=normalized_confusion_df.columns,
319 | y=normalized_confusion_df.index,
320 | colorscale='Blues',
321 | text=confusion_df.values,
322 | texttemplate="%{text}",
323 | hovertemplate="True Label: %{y}
Predicted: %{x}
Count: %{text}",
324 | colorbar=dict(title="Normalized Value")
325 | ))
326 | fig.update_layout(
327 | title=dict(
328 | text="Confusion Matrix: Cluster vs Ground Truth Label",
329 | font=dict(size=24)
330 | ),
331 | xaxis_title=dict(
332 | text="Predicted Cluster",
333 | font=dict(size=18)
334 | ),
335 | yaxis_title=dict(
336 | text="Ground Truth Label",
337 | font=dict(size=18)
338 | ),
339 | xaxis=dict(
340 | tickmode='array',
341 | tickvals=list(range(len(confusion_df.columns))),
342 | ticktext=confusion_df.columns,
343 | tickfont=dict(size=14)
344 | ),
345 | yaxis=dict(
346 | tickmode='array',
347 | tickvals=list(range(len(confusion_df.index))),
348 | ticktext=confusion_df.index,
349 | tickfont=dict(size=14)
350 | ),
351 | height=600,
352 | width=800
353 | )
354 | fig.show()
355 |
356 | # calculating the ari score and adding this to the metrics (if confusion matrix is created)
357 | ari_score = sklearn.metrics.adjusted_rand_score(sspa_scores_meta['Who_Group'], sspa_scores_meta['Consensus_Cluster'])
358 | self.sv_clust.metrics['Adjusted_Rand_Index'] = ari_score
359 | sv_clust.confusion_matrix = fig
360 |
361 | # if the metrics table is requested
362 | if return_metrics_table:
363 | metrics_df = pd.DataFrame(self.sv_clust.metrics, index=[0])
364 | metrics_df = metrics_df.T.reset_index()
365 | metrics_df.columns = ['Metric', 'Value']
366 | custom_palette = ['red' if i % 2 == 0 else 'blue' for i in range(len(metrics_df))]
367 | fig_metrics = plt.figure(figsize=(10, 8))
368 | ax = sns.barplot(y='Metric', x='Value', data=metrics_df, palette=custom_palette)
369 | for index, value in enumerate(metrics_df['Value']):
370 | plt.text(value / 2, index, f'{value:.2f}', color='white', ha='center', va='center', fontsize=18, weight='bold')
371 | plt.ylabel('Metric', fontsize=18)
372 | plt.xlabel('Value', fontsize=18)
373 | plt.xticks(fontsize=18)
374 | plt.yticks(fontsize=18)
375 | plt.tight_layout()
376 | plt.show()
377 | sv_clust.metrics_plot = fig_metrics
378 |
379 | print('Finished')
380 |
381 | # creating a new sspa_scores object with clusters
382 | self.sv_clust.sspa_scores_clusters = self.sspa_scores_sv
383 |
384 | return self.sv_clust
385 |
386 |
387 | def SingleViewDimRed(self, model=sklearn.decomposition.PCA, model_params=None, return_pca_plot=False,return_tsne_plot = False, return_biplot=False, return_loadings_plot=False, return_tsne_density_plot=False ,metadata_continuous=False):
388 | """
389 | Applies a dimensionality reduction technique to the input data.
390 | Credit: Jude Popham
391 |
392 | Args:
393 | model (object, optional): The dimensionality reduction model to use. Defaults to sklearn.decomposition.PCA.
394 | model_params (dict, optional): Model-specific hyperparameters. Defaults to None.
395 | return_pca_plot (bool, optional): Whether to return a PCA scatter plot of the first two principal components.
396 | return_tsne_plot (bool, optional): Whether to return a t-SNE scatter plot of the first two components.
397 | return_biplot (bool, optional): Whether to return a biplot (PCA plot with loadings).
398 | return_loadings_plot (bool, optional): Whether to return a plot of the top loadings for each component.
399 | return_tsne_density_plot (bool, optional): Whether to return a t-SNE scatter plot with a density overlay.
400 | metadata_continuous (bool, optional): Whether metadata is continuous or categorical.
401 |
402 | Returns:
403 | object: Fitted dimensionality reduction model with reduced data and optional plots.
404 | """
405 |
406 | # creating concatenated and data
407 | concat_data = pd.concat(self.omics_data_scaled.values(), axis=1)
408 | print('Generating pathway scores...')
409 | sspa_scores = self.sspa_method(self.pathway_source, self.min_coverage)
410 | self.sspa_scores_sv = sspa_scores.fit_transform(concat_data)
411 | if model_params is None:
412 | model_params = {}
413 | sv_dim = model(**model_params) if model_params else model()
414 | print('Fitting SingleView Dimensionality Reduction model')
415 |
416 | # setging the model parameters depending on the model used (PCA or t-SNE)
417 | if sklearn.decomposition.PCA:
418 | if return_biplot or return_loadings_plot:
419 | if model_params.get('n_components', 2) != 2:
420 | print("Warning: n_components has been set to 2 for the biplot.")
421 | model_params['n_components'] = 2
422 | else:
423 | model_params['n_components'] = 2
424 | sv_dim = model(**model_params)
425 |
426 | # scaling data and fitting the models
427 | if model == sklearn.decomposition.PCA:
428 | reduced_data_scaled = StandardScaler().fit_transform(self.sspa_scores_sv)
429 | reduced_data_sspa = pd.DataFrame(reduced_data_scaled, columns=self.sspa_scores_sv.columns)
430 | reduced_data = sv_dim.fit_transform(reduced_data_sspa)
431 | explained_variance = sv_dim.explained_variance_ratio_ if hasattr(sv_dim, 'explained_variance_ratio_') else None
432 | else:
433 | reduced_data = sv_dim.fit_transform(self.sspa_scores_sv)
434 | explained_variance = None
435 |
436 | # saving to the dim object
437 | sv_dim.reduced_data = reduced_data
438 | sv_dim.explained_variance = explained_variance
439 | sv_dim.sspa_scores_pca = self.sspa_scores_sv
440 | sv_dim.name = 'SingleViewDimRed'
441 |
442 | # incorporating metadata and setting it on a continuous scale if necessary
443 | pca_df = pd.DataFrame(data=reduced_data[:, :2], columns=['PC1', 'PC2'])
444 | metadata_pca = self.metadata.to_frame(name='Metadata').reset_index(drop=True)
445 | if metadata_continuous:
446 | metadata_pca['Meta_Group_Midpoint'] = metadata_pca['Metadata'].apply(self.convert_range_to_midpoint)
447 | pca_df_named = pd.concat([pca_df, metadata_pca], axis=1)
448 | pca_df_named = pca_df_named.sort_values('Meta_Group_Midpoint').reset_index(drop=True)
449 | pca_df_named = pca_df_named.drop(columns=['Meta_Group_Midpoint'])
450 | else:
451 | pca_df_named = pd.concat([pca_df, metadata_pca], axis=1)
452 | if return_tsne_plot or return_tsne_density_plot:
453 | tsne_df = pd.DataFrame(data=reduced_data[:, :2], columns=['Component 1', 'Component 2'])
454 | metadata_pca['Meta_Group_Midpoint'] = metadata_pca['Metadata'].apply(self.convert_range_to_midpoint)
455 | tsne_df_named = pd.concat([tsne_df, metadata_pca], axis=1)
456 | tsne_df_named = tsne_df_named.sort_values('Meta_Group_Midpoint').reset_index(drop=True)
457 | tsne_df_named = tsne_df_named.drop(columns=['Meta_Group_Midpoint'])
458 |
459 | # if returning tsne plot
460 | if return_tsne_plot:
461 | if model != sklearn.manifold.TSNE:
462 | raise ValueError("Error: Please use sklearn.manifold.TSNE for t-SNE plots.")
463 | sns.set_style("white")
464 | fig_tsne = plt.figure()
465 | sns.set_style("white")
466 | sns.scatterplot(data=tsne_df_named, x='Component 1', y='Component 2', hue='Metadata', palette='coolwarm', s=100, edgecolor='black')
467 | plt.title('t-SNE of Integrated Data (First 2 Components)')
468 | plt.xlabel('Component 1')
469 | plt.ylabel('Component 2')
470 | plt.legend(title='Metadata Group')
471 | plt.grid(True)
472 | plt.show()
473 | sv_dim.tsne_plot = fig_tsne
474 |
475 | # if returning tsne density plot
476 | if return_tsne_density_plot:
477 | if model != sklearn.manifold.TSNE:
478 | raise ValueError("Error: Please use sklearn.manifold.TSNE for t-SNE plots.")
479 | sns.set_style("white")
480 | fig_tsne_density = plt.figure(figsize=(10, 8))
481 | sns.scatterplot(data=tsne_df_named, x='Component 1', y='Component 2', hue='Metadata', s=50, edgecolor='black', alpha=0.6, palette="coolwarm")
482 | sns.kdeplot(data=tsne_df_named, x='Component 1', y='Component 2', hue='Metadata', fill=True, alpha=0.3, palette="coolwarm")
483 | plt.title('t-SNE of Integrated Data with Density Overlay')
484 | plt.xlabel('Component 1')
485 | plt.ylabel('Component 2')
486 | plt.legend(title='Metadata Group')
487 | plt.grid(True)
488 | plt.show()
489 | sv_dim.tsne_density_plot = fig_tsne_density
490 |
491 | # if a biplot or loadings plot is requested - need to convert pathways to names
492 | if return_loadings_plot or return_biplot:
493 | if model != sklearn.decomposition.PCA:
494 | raise ValueError("Error: Please use sklearn.decomposition.PCA to examine loadings.")
495 | loadings_df = pd.DataFrame(sv_dim.components_.T, columns=['Component 1', 'Component 2'], index=reduced_data_sspa.columns)
496 |
497 | # function to download a kegg conversion file - reactome conversion file is already within code
498 | url = "https://rest.kegg.jp/get/br:br08901/json"
499 | response = requests.get(url)
500 | if response.status_code == 200:
501 | hierarchy_json = response.json()
502 | with open('br08901.json', 'w') as f:
503 | json.dump(hierarchy_json, f, indent=4)
504 | else:
505 | print("Failed to retrieve data. Status code:", response.status_code)
506 | def create_id_name_mapping(node):
507 | id_name_mapping = {}
508 | if 'children' in node:
509 | for child in node['children']:
510 | id_name_mapping.update(create_id_name_mapping(child))
511 | else:
512 | pathway_id, pathway_name = node['name'].split(' ', 1)
513 | id_name_mapping[pathway_id] = pathway_name.strip()
514 | return id_name_mapping
515 | pathway_mapping = create_id_name_mapping(hierarchy_json)
516 |
517 | # extracting the top pathway loadings
518 | top_loadings_pc1 = loadings_df['Component 1'].sort_values(key=abs, ascending=False).head(10)
519 | top_loadings_pc2 = loadings_df['Component 2'].sort_values(key=abs, ascending=False).head(10)
520 | top_loadings = pd.concat([top_loadings_pc1, top_loadings_pc2])
521 | sv_dim.loadings_df = loadings_df
522 |
523 | # creating a PCA plot
524 | if return_pca_plot:
525 | sns.set_style("white")
526 | fig_pca = plt.figure()
527 | sns.scatterplot(data=pca_df_named, x='PC1', y='PC2', hue='Metadata', palette="coolwarm", s=100, edgecolor='black')
528 | plt.title('PCA of Integrated Data (First 2 Principal Components)')
529 | plt.xlabel('Principal Component 1')
530 | plt.ylabel('Principal Component 2')
531 | plt.legend(title='Metadata Group')
532 | plt.grid(True)
533 | plt.show()
534 | sv_dim.pca_plot = fig_pca
535 |
536 | # creatign a biplot
537 | if return_biplot:
538 | scaling_factor = 200
539 | sns.set_style("white")
540 | fig_biplot = plt.figure(figsize=(10, 8))
541 | sns.scatterplot(data=pca_df_named, x='PC1', y='PC2', hue='Metadata', s=100, edgecolor='black', alpha=0.2, legend=False)
542 | for variable in top_loadings.index:
543 | color = 'red' if variable in top_loadings_pc1.index else 'blue'
544 | plt.arrow(0, 0, loadings_df.loc[variable, 'Component 1'] * scaling_factor,
545 | loadings_df.loc[variable, 'Component 2'] * scaling_factor,
546 | color=color, alpha=0.8, head_width=0.5, linewidth=2)
547 | plt.text(loadings_df.loc[variable, 'Component 1'] * scaling_factor * 1.15,
548 | loadings_df.loc[variable, 'Component 2'] * scaling_factor * 1.15,
549 | variable, color='black', ha='center', va='center', fontsize=10)
550 | plt.xticks(fontsize=14)
551 | plt.yticks(fontsize=14)
552 | plt.title('Biplot of PCA with Top 10 Loadings Highlighted')
553 | plt.xlabel('Principal Component 1')
554 | plt.ylabel('Principal Component 2')
555 | plt.grid(True)
556 | plt.show()
557 | sv_dim.biplot = fig_biplot
558 |
559 | # creating a loadings plot
560 | if return_loadings_plot:
561 | fig_loadings_plot = plt.figure(figsize=(12, 10))
562 | index_mapping = self.pathway_source['Pathway_name'].to_dict()
563 | def rename_index(index):
564 | if index.startswith('R-HSA'):
565 | return index_mapping.get(index, index)
566 | else:
567 | return pathway_mapping.get(index, index)
568 | loadings_df.index = [rename_index(idx) for idx in loadings_df.index]
569 | top_loadings_pc1 = loadings_df['Component 1'].sort_values(key=abs, ascending=False).head(10)
570 | top_loadings_pc2 = loadings_df['Component 2'].sort_values(key=abs, ascending=False).head(10)
571 | top_loadings = pd.concat([top_loadings_pc1, top_loadings_pc2])
572 | colors = ['red' if variable in top_loadings_pc1.index else 'blue' for variable in top_loadings.index]
573 | top_loadings.plot(kind='barh', color=colors, width=0.3)
574 | plt.title('Top 5 Loadings for PC1 and PC2', fontsize=24)
575 | plt.xlabel('Loading Value', fontsize=20)
576 | plt.ylabel('', fontsize=30)
577 | plt.axvline(0, color='black', linewidth=0.1)
578 | plt.xticks(rotation=45, fontsize=18)
579 | plt.yticks(fontsize=30)
580 | plt.show()
581 | sv_dim.loadings_plot = fig_loadings_plot
582 |
583 | sv_dim.metadata_pca = metadata_pca
584 | self.sv_dim = sv_dim
585 |
586 | return self.sv_dim
587 |
588 | # function to convert ranges to midpoints
589 | def convert_range_to_midpoint(self, value):
590 | """
591 | Converts a range like '10-20' into its midpoint value '15'.
592 | """
593 | if isinstance(value, str) and '-' in value:
594 | try:
595 | start, end = map(float, value.split('-'))
596 | return (start + end) / 2
597 | except ValueError:
598 | return value
599 | return value
600 |
601 | def SingleViewCV(self, model=sklearn.linear_model.LogisticRegression, model_params=None, cv_params=None):
602 | '''Cross-validation for SingleView model.
603 |
604 | Args:
605 | model (object, optional): SKlearn prediction model class. Defaults to sklearn.linear_model.LogisticRegression.
606 | model_params (_type_, optional): Model-specific hyperparameters. Defaults to None.
607 | cv_params (dict, optional): Cross-validation parameters. Defaults to None.
608 | Returns:
609 | object: Cross-validation results.
610 |
611 | '''
612 | # concatenate omics - unscaled to avoid data leakage
613 | concat_data = pd.concat(self.omics_data.values(), axis=1)
614 |
615 | # Set up sklearn pipeline
616 | pipe_sv = sklearn.pipeline.Pipeline([
617 | ('Scaler', StandardScaler().set_output(transform="pandas")),
618 | ('sspa', self.sspa_method(self.pathway_source, self.min_coverage)),
619 | ('sv', model(**model_params))
620 | ])
621 |
622 | cv_res = cross_val_score(pipe_sv, X=concat_data, y=self.labels, **cv_params)
623 | return cv_res
624 |
625 | def SingleViewGridSearchCV(self, param_grid, model=sklearn.linear_model.LogisticRegression, grid_search_params=None):
626 | '''Grid search cross-validation for SingleView model.
627 |
628 | Args:
629 | param_grid (dict): Grid search parameters.
630 | model (object, optional): SKlearn prediction model class. Defaults to sklearn.linear_model.LogisticRegression.
631 | grid_search_params (dict, optional): Grid search parameters. Defaults to None.
632 |
633 | Returns:
634 | object: GridSearchCV object.
635 |
636 | '''
637 | # concatenate omics - unscaled to avoid data leakage
638 | concat_data = pd.concat(self.omics_data.values(), axis=1)
639 |
640 | # Set up sklearn pipeline
641 | pipe_sv = sklearn.pipeline.Pipeline([
642 | ('Scaler', StandardScaler().set_output(transform="pandas")),
643 | ('sspa', self.sspa_method(self.pathway_source, self.min_coverage)),
644 | ('model', model())
645 | ])
646 |
647 | # Set up cross-validation
648 | grid_search = GridSearchCV(pipe_sv, param_grid=param_grid, **grid_search_params)
649 | grid_search.fit(X=concat_data, y=self.labels)
650 | return grid_search
651 |
652 | # only 1 model so one parameter way to grid search pca components
653 | # advantage of multi view is interpretation of contribution
654 |
655 | def MultiViewCV(self):
656 | '''Cross-validation for MultiView model.
657 |
658 | Returns:
659 | object: Cross-validation results.
660 | '''
661 |
662 | # Set up sklearn pipeline
663 | pipe_mv = sklearn.pipeline.Pipeline([
664 | ('sspa', self.sspa_method(self.pathway_source, self.min_coverage)),
665 | ('mbpls', MBPLS(n_components=2))
666 | ])
667 |
668 | # Set up cross-validation
669 | cv_res = cross_val_score(pipe_mv, X=[i.copy(deep=True) for i in self.omics_data.values()], y=self.labels)
670 | return cv_res
671 |
672 | def MultiViewGridSearchCV(self):
673 | raise NotImplementedError('See tutorial for Multi-View latent variable optimisation approach')
674 |
675 |
676 | def VIP_multiBlock(x_weights, x_superscores, x_loadings, y_loadings):
677 | """Calculate VIP scores for multi-block PLS.
678 |
679 | Args:
680 | x_weights (list): List of x weights.
681 | x_superscores (list): List of x superscores.
682 | x_loadings (list): List of x loadings.
683 | y_loadings (list): List of y loadings.
684 |
685 | Returns:
686 | numpy.ndarray: VIP scores for each feature across all blocks. Features are in original order.
687 | """
688 | # stack the weights from all blocks
689 | weights = np.vstack(x_weights)
690 | # calculate product of sum of squares of superscores and y loadings
691 | sumsquares = np.sum(x_superscores**2, axis=0) * np.sum(y_loadings**2, axis=0)
692 | # p = number of variables - stack the loadings from all blocks
693 | p = np.vstack(x_loadings).shape[0]
694 |
695 | # VIP is a weighted sum of squares of PLS weights
696 | vip_scores = np.sqrt(p * np.sum(sumsquares*(weights**2), axis=1) / np.sum(sumsquares))
697 | return vip_scores
698 |
699 |
700 |
--------------------------------------------------------------------------------
/src/pathintegrate/plot.py:
--------------------------------------------------------------------------------
1 | # plotting functions
2 |
3 | import numpy as np
4 | import pandas as pd
5 | import matplotlib.pyplot as plt
6 | import seaborn as sns
7 |
8 | def omics_view_importance(pi_model, outfile=None):
9 | """Plot the importance of each omics view in the MultiView model
10 |
11 | Args:
12 | pi_model (object): Fitted PathIntegrate multi-view model.
13 | """
14 | plt.figure(figsize=(7, 5))
15 | block_importance = pd.DataFrame(pi_model.A_corrected_*100, index=pi_model.omics_names, columns=range(0, pi_model.A_corrected_.shape[1]))
16 | pev_per_lv = np.round(pi_model.explained_var_y_, 2)*100
17 | sns.heatmap(
18 | data=block_importance,
19 | cmap='Blues',
20 | annot=True,
21 | fmt='.2f',
22 | linewidths=.5,
23 | square=True,
24 | vmin=0,
25 | vmax=100)
26 |
27 | plt.ylabel('Omics view')
28 | plt.xticks([i+0.5 for i in range(0, pi_model.A_corrected_.shape[1])], [str(n+1) + ': ' + str(i)+'%' for n, i in enumerate(pev_per_lv)])
29 | plt.xlabel('Percentage explained in Y per LV')
30 | plt.title('Omics view importance')
31 |
32 | plt.tight_layout()
33 | if outfile:
34 | plt.savefig(outfile)
35 | plt.show()
36 |
37 |
38 | # def top_n_pathways(pi_model, n_top_paths=10, outfile=None):
39 |
40 | # if pi_model.mv:
41 | # pass
42 |
43 | # elif pi_model.sv:
44 | # paths_df = pi_model.feature_importances_.sort_values(ascending=False).head(n_top_paths)
45 | # sns.barplot()
46 |
47 | # plt.tight_layout()
48 | # if outfile:
49 | # plt.savefig(outfile)
50 | # plt.show()
51 |
--------------------------------------------------------------------------------
/src/pathintegrate/utils.py:
--------------------------------------------------------------------------------
1 | import pandas as pd
2 | import numpy as np
3 | import pkg_resources
4 | import scipy.stats as stats
5 | import statsmodels.api as sm
6 |
7 | def load_example_data(omicstype):
8 | """
9 | Loads example datasets
10 |
11 | Args:
12 | omicstype (str): type of omics for example data.
13 | Available options are "metabolomics" or "proteomics".
14 | Data are from Su et al 2020 https://doi.org/10.1016/j.cell.2020.10.037.
15 |
16 | Returns:
17 | pre-processed omics data matrix consisting of m samples and n entities (metabolites/genes) in the form of a pandas DataFrame.
18 | Contains one of more metadata columns at the end.
19 | """
20 |
21 | if omicstype == "metabolomics":
22 | stream = pkg_resources.resource_stream(__name__, 'data/metabolomics_example.csv')
23 | f = pd.read_csv(stream, index_col=0, encoding='latin-1')
24 | return f
25 | if omicstype == "proteomics":
26 | stream = pkg_resources.resource_stream(__name__, 'data/proteomics_example.csv')
27 | f = pd.read_csv(stream, index_col=0, encoding='latin-1')
28 | return f
29 |
--------------------------------------------------------------------------------