├── LICENSE
├── README.md
├── code_for_figures
├── benchmarking
│ ├── .DS_Store
│ ├── notebooks
│ │ ├── .DS_Store
│ │ ├── brain
│ │ │ ├── get_ground_truth.ipynb
│ │ │ ├── graphst_results.ipynb
│ │ │ ├── knn_results.ipynb
│ │ │ ├── radius_results.ipynb
│ │ │ ├── stagate_results.ipynb
│ │ │ └── utag_results.ipynb
│ │ ├── gut
│ │ │ ├── get_ground_truth.ipynb
│ │ │ ├── graphst_results.ipynb
│ │ │ ├── knn_results.ipynb
│ │ │ ├── radius_results.ipynb
│ │ │ ├── stagate_results.ipynb
│ │ │ └── utag_results.ipynb
│ │ ├── plot_performance.ipynb
│ │ └── simulation
│ │ │ ├── get_ground_truth.ipynb
│ │ │ ├── graphst_results.ipynb
│ │ │ ├── knn_results.ipynb
│ │ │ ├── radius_results.ipynb
│ │ │ ├── stagate_results.ipynb
│ │ │ └── utag_results.ipynb
│ └── scripts
│ │ ├── .DS_Store
│ │ ├── brain
│ │ ├── brain_graphst.sh
│ │ ├── brain_knn.sh
│ │ ├── brain_radius.sh
│ │ ├── brain_stagate.sh
│ │ ├── brain_utag.sh
│ │ └── performance_brain.sh
│ │ ├── graphst_.py
│ │ ├── gut
│ │ ├── gut_graphst.sh
│ │ ├── gut_knn.sh
│ │ ├── gut_radius.sh
│ │ ├── gut_stagate.sh
│ │ ├── gut_utag.sh
│ │ └── performance_gut.sh
│ │ ├── knn.py
│ │ ├── modified_existing_methods
│ │ ├── graphst
│ │ │ └── GraphST_mod.py
│ │ ├── stagate
│ │ │ └── utils.py
│ │ └── utag
│ │ │ └── segmentation.py
│ │ ├── radius.py
│ │ ├── simulation
│ │ ├── performance_simulation.sh
│ │ ├── simulation_graphst.sh
│ │ ├── simulation_knn.sh
│ │ ├── simulation_radius.sh
│ │ ├── simulation_stagate.sh
│ │ └── simulation_utag.sh
│ │ ├── stagate_.py
│ │ └── utag_.py
└── generalization
│ ├── .DS_Store
│ ├── brain
│ ├── concat.ipynb
│ ├── length_scales.ipynb
│ ├── n_pcs.ipynb
│ ├── nmf.ipynb
│ ├── schematic.ipynb
│ ├── shuffling.ipynb
│ ├── xspecies.ipynb
│ └── xtech.ipynb
│ └── gut
│ └── xcondition.ipynb
├── docs
├── imgs
│ ├── github_idea_1_dark.png
│ ├── github_idea_1_light.png
│ ├── github_idea_2_dark.png
│ ├── github_idea_2_light.png
│ ├── github_obstacle_1_dark.png
│ ├── github_obstacle_1_light.png
│ ├── github_obstacle_2_dark.png
│ └── github_obstacle_2_light.png
└── tutorials
│ └── tutorial.ipynb
├── pyproject.toml
└── src
└── spin
├── __init__.py
├── cli.py
└── spin.py
/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 | .
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # SPIN: spatial integration of spatially resolved transcriptomics (SRT) data
2 | [](https://doi.org/10.1101/2023.06.30.547258) ⬅️ manuscript
3 | [](https://doi.org/10.5281/zenodo.13883268) ⬅️ data
4 |
5 | SPIN is a simple, Scanpy-based implementation of the subsampling and smoothing approach described in the manuscript *Mitigating autocorrelation during spatially resolved transcriptomics data analysis*. It enables the alignment and analysis of transcriptionally defined tissue regions across multiple SRT datasets, regardless of morphology or experimental technology, using conventional single-cell tools. Here we include information regarding:
6 |
7 | 1. A conceptual overview of the approach
8 | 2. Package requirements
9 | 3. Installation instructions
10 | 4. Basic usage principles
11 |
12 | For examples of downstream analysis (e.g. differentially expressed gene analysis and trajectory inference), see the [tutorial](docs/tutorials/tutorial.ipynb) notebook. For further details on SPIN parameters, import SPIN into Python as shown below and run `help(spin)`.
13 |
14 | ## 1. Conceptual overview
15 | * Conventional single-cell analysis can identify molecular *cell types* by considering each cell individually.
16 | * However, it does not incorporate spatial information.
17 |
18 |
19 |
20 |
21 |
22 |
23 | * Arguably the simplest way to incorporate spatial information and identify molecular *tissue regions* is to spatially smooth gene expression features across neighboring cells in the tissue.
24 | * This can be done by setting the features of each cell to the average of its spatial neighborhood.
25 |
26 |
27 |
28 |
29 |
30 |
31 | * However, a problem arises when smoothed representations of each cell are compared to one another.
32 | * Physically adjacent cells will have almost identical neighborhoods and thus almost identical smoothed representations.
33 |
34 |
35 |
36 |
37 |
38 |
39 | * Thus, we end up with nearest neighbors in feature space that are just nearest neighbors in physical space.
40 | * Because conventional methods for downstream anlaysis rely on the nearest neighbors graph in feature space, this leads to reconstruction of physical space in latent space rather than representing the true underlying large scale molecular patterns.
41 | * Here, we implement an approach in which each cell's spatial neighborhood is randomly subsampled before averaging, allowing the *exact neighborhood* composition to vary while still maintaining the *general molecular* composition.
42 |
43 |
44 |
45 |
46 |
47 |
48 | Ultimately, this approach enables the application of conventional single-cell tools to spatial molecular features in SRT data, yielding regional analogies for each tool. For more details and examples, please refer to the manuscript and [tutorial](docs/tutorials/tutorial.ipynb).
49 |
50 | ## 2. Requirements:
51 |
52 | ### Software:
53 | * Tested on MacOS (Monterey, Ventura) and Linux (Red Hat Enterprise Linux 7).
54 | * Command Line Tools is required for `pip` installing this package from GitHub. While it comes standard on most machines, those without it may encounter an `xcrun: error` when following the installation instructions below. See [here](https://apple.stackexchange.com/questions/254380/why-am-i-getting-an-invalid-active-developer-path-when-attempting-to-use-git-a) for simple instructions on how to install it.
55 | * Python >= 3.9
56 | * The only dependency is Scanpy. For details, see [`pyproject.toml`](pyproject.toml).
57 |
58 | ### Data:
59 | * One or more SRT datasets in `.h5ad` format
60 | * An expression matrix under `.X` (both sparse and dense representations supported)
61 | * Spatial coordinates under `.obsm` (key can be specified with argument `spatial_key`)
62 | * Batch information
63 | * If multiple batches in single dataset, batch labels provided under column in `.obs` with column name `batch_key`.
64 | * If multiple batches in separate datasets, batch labels for each dataset provided as input.
65 |
66 | ## 3. Installation
67 |
68 | ### From GitHub:
69 | ```
70 | pip install git+https://github.com/wanglab-broad/spin@main
71 | ```
72 | Takes ~5 mins.
73 |
74 | ## 4. Usage
75 | ### In Python:
76 | Consider the marmoset and mouse data from the manuscript which we provide as a demo:
77 | ```python
78 | import scanpy as sc
79 |
80 | adata_marmoset = sc.read(
81 | 'data/marmoset.h5ad',
82 | backup_url='https://zenodo.org/record/8092024/files/marmoset.h5ad?download=1'
83 | )
84 | adata_mouse = sc.read(
85 | 'data/mouse.h5ad',
86 | backup_url='https://zenodo.org/record/8092024/files/mouse.h5ad?download=1'
87 | )
88 | ```
89 |
90 | These datasets can be spatially integrated and clustered using `spin`. The `batch_key` argument corresponds to the name of a new column in `adata.obs` that stores the batch labels for each dataset. The `batch_labels` argument is a list of these batch labels in the same order as the input AnnDatas:
91 | ```python
92 | from spin import spin
93 |
94 | adata = spin(
95 | adatas=[adata_marmoset, adata_mouse],
96 | batch_key='species',
97 | batch_labels=['marmoset', 'mouse'],
98 | resolution=0.7
99 | )
100 | ```
101 | This performs the following steps:
102 | * `integrate`:
103 | 1. Subsampling and smoothing of each dataset individually (stored under `adata.layers['smooth']`)
104 | 2. Joint PCA across both smoothed datasets
105 | 3. Integration of the resulting PCs using Harmony (stored under `adata.obsm['X_pca_spin']`)
106 | * `cluster`:
107 | 1. Latent nearest neighbor search
108 | 2. Leiden clustering with a resolution of 0.7 (stored under `adata.obs['region']`)
109 | 3. UMAP (stored under `adata.obsm['X_umap_spin']`)
110 |
111 | Note that `spin` can equivalently take as input a single AnnData containing multiple labeled batches. It can also take a single AnnData containing one batch for finding regions in a single dataset. For examples, see the [tutorial](docs/tutorials/tutorial.ipynb).
112 |
113 |
114 | The resulting region clusters can then be visualized using standard Scanpy functions:
115 | ```python
116 | # In physical space
117 | sc.set_figure_params(figsize=(7,5))
118 | sc.pl.embedding(adata, basis='spatial', color='region')
119 |
120 | # In UMAP space
121 | sc.set_figure_params(figsize=(4,4))
122 | sc.pl.embedding(adata, basis='X_umap_spin', color='region')
123 | ```
124 | Downstream analysis (e.g. DEG analysis, trajectory inference) can then be performed using standard Scanpy functions as well.
125 | For examples of downstream analysis, see the [tutorial](docs/tutorials/tutorial.ipynb).
126 | For further details on the parameters of `spin`, import SPIN into Python as shown above and run `help(spin)`.
127 |
128 | ### From the shell:
129 | SPIN can be executed from the shell using the `spin` command as shown below (the path is identified automatically; see [`spin_cli`](src/spin/cli.py) and [`pyproject.toml`](pyproject.toml))
130 |
131 | Shell submission requires a read path to the relevant dataset(s) as well as a write path for the output dataset. Otherwise, provide the same parameters you would when running in Python as above:
132 | ```python
133 | spin \
134 | --adata_paths data/marmoset.h5ad data/mouse.h5ad \
135 | --write_path data/marmoset_mouse_spin.h5ad \
136 | --batch_key species \
137 | --batch_labels marmoset mouse \
138 | --resolution "0.7"
139 | ```
140 |
141 | Just as when running in Python, a single AnnData containing multiple batches can be passed in instead, as well as just a single dataset containing a single batch.
142 |
--------------------------------------------------------------------------------
/code_for_figures/benchmarking/.DS_Store:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/wanglab-broad/spin/53c174bfcc029f2614bf381f3d61557f3e1824d1/code_for_figures/benchmarking/.DS_Store
--------------------------------------------------------------------------------
/code_for_figures/benchmarking/notebooks/.DS_Store:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/wanglab-broad/spin/53c174bfcc029f2614bf381f3d61557f3e1824d1/code_for_figures/benchmarking/notebooks/.DS_Store
--------------------------------------------------------------------------------
/code_for_figures/benchmarking/scripts/.DS_Store:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/wanglab-broad/spin/53c174bfcc029f2614bf381f3d61557f3e1824d1/code_for_figures/benchmarking/scripts/.DS_Store
--------------------------------------------------------------------------------
/code_for_figures/benchmarking/scripts/brain/brain_graphst.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 |
3 | #$ -l h_vmem=80G
4 | #$ -l h_rt=01:30:00
5 | #$ -o /stanley/WangLab/kamal/outputs/spin/reviews/brain/graphst/
6 | #$ -j y
7 | #$ -t 1-110
8 |
9 | source /broad/software/scripts/useuse
10 | reuse Anaconda3
11 | source activate /stanley/WangLab/kamal/envs/graphst/
12 |
13 | sample_rates=($(seq 0 0.1 1))
14 | random_seeds=($(seq 0 1 10))
15 | # random_seeds=($(seq 0 0)) # test using a single random seed
16 |
17 | n_sample_rates=${#sample_rates[@]}
18 | sample_rate=${sample_rates[($((SGE_TASK_ID-1))%$n_sample_rates)]}
19 | random_seed=${random_seeds[($((SGE_TASK_ID-1))/$n_sample_rates)]}
20 |
21 | k_physical=50
22 | k_latent=15
23 |
24 | python /stanley/WangLab/kamal/code/projects/spin/reviews/scripts/graphst_.py \
25 | --read_path /stanley/WangLab/kamal/data/projects/spin/reviews/brain/adata.h5ad \
26 | --sample_rate $sample_rate \
27 | --k_physical $k_physical \
28 | --k_latent $k_latent \
29 | --leiden_res "0.2" \
30 | --write_path /stanley/WangLab/kamal/data/projects/spin/reviews/results/brain/graphst/reconstructions_${sample_rate}_${k_physical}physical_${k_latent}latent/ \
31 | --random_seed $random_seed \
32 | --n_epochs 50 \
--------------------------------------------------------------------------------
/code_for_figures/benchmarking/scripts/brain/brain_knn.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 |
3 | #$ -l h_vmem=16G
4 | #$ -l h_rt=01:30:00
5 | #$ -o /stanley/WangLab/kamal/outputs/spin/reviews/brain/knn/
6 | #$ -j y
7 | #$ -t 1-110
8 |
9 | source /broad/software/scripts/useuse
10 | reuse Anaconda3
11 | source activate /stanley/WangLab/kamal/envs/xax
12 |
13 | sample_rates=($(seq 0 0.1 1))
14 | random_seeds=($(seq 0 1 10))
15 | # random_seeds=($(seq 0 0)) # test using a single random seed
16 |
17 | n_sample_rates=${#sample_rates[@]}
18 | sample_rate=${sample_rates[($((SGE_TASK_ID-1))%$n_sample_rates)]}
19 | random_seed=${random_seeds[($((SGE_TASK_ID-1))/$n_sample_rates)]}
20 |
21 | k_physical=50
22 | k_latent=15
23 |
24 | python /stanley/WangLab/kamal/code/projects/spin/reviews/scripts/knn.py \
25 | --read_path /stanley/WangLab/kamal/data/projects/spin/reviews/brain/adata.h5ad \
26 | --sample_rate $sample_rate \
27 | --k_physical $k_physical \
28 | --k_latent $k_latent \
29 | --n_pcs 50 \
30 | --leiden_res "0.2" \
31 | --write_path /stanley/WangLab/kamal/data/projects/spin/reviews/results/brain/knn/reconstructions_${sample_rate}_${k_physical}physical_${k_latent}latent/ \
32 | --random_seed $random_seed
--------------------------------------------------------------------------------
/code_for_figures/benchmarking/scripts/brain/brain_radius.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 |
3 | #$ -l h_vmem=16G
4 | #$ -l h_rt=01:30:00
5 | #$ -o /stanley/WangLab/kamal/outputs/spin/reviews/brain/radius/
6 | #$ -j y
7 | #$ -t 1-110
8 |
9 | source /broad/software/scripts/useuse
10 | reuse Anaconda3
11 | source activate /stanley/WangLab/kamal/envs/xax
12 |
13 | sample_rates=($(seq 0 0.1 1))
14 | random_seeds=($(seq 0 1 10))
15 | # random_seeds=($(seq 0 0)) # test using a single random seed
16 |
17 | n_sample_rates=${#sample_rates[@]}
18 | sample_rate=${sample_rates[($((SGE_TASK_ID-1))%$n_sample_rates)]}
19 | random_seed=${random_seeds[($((SGE_TASK_ID-1))/$n_sample_rates)]}
20 |
21 | radius=550
22 | k_latent=15
23 |
24 | python /stanley/WangLab/kamal/code/projects/spin/reviews/scripts/radius.py \
25 | --read_path /stanley/WangLab/kamal/data/projects/spin/reviews/brain/adata.h5ad \
26 | --sample_rate $sample_rate \
27 | --radius $radius \
28 | --k_latent $k_latent \
29 | --n_pcs 50 \
30 | --leiden_res "0.2" \
31 | --write_path /stanley/WangLab/kamal/data/projects/spin/reviews/results/brain/radius/reconstructions_${sample_rate}_${radius}radius_${k_latent}latent/ \
32 | --random_seed $random_seed
--------------------------------------------------------------------------------
/code_for_figures/benchmarking/scripts/brain/brain_stagate.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 |
3 | #$ -l h_vmem=64G
4 | #$ -l h_rt=02:00:00
5 | #$ -o /stanley/WangLab/kamal/outputs/spin/reviews/brain/stagate/
6 | #$ -j y
7 | #$ -t 1-110
8 |
9 | source /broad/software/scripts/useuse
10 | reuse Anaconda3
11 | source activate /stanley/WangLab/kamal/envs/stagate_pyg/
12 |
13 | sample_rates=($(seq 0 0.1 1))
14 | random_seeds=($(seq 0 1 10))
15 | # random_seeds=($(seq 0 0)) # test using a single random seed
16 |
17 | n_sample_rates=${#sample_rates[@]}
18 | sample_rate=${sample_rates[($((SGE_TASK_ID-1))%$n_sample_rates)]}
19 | random_seed=${random_seeds[($((SGE_TASK_ID-1))/$n_sample_rates)]}
20 |
21 | k_physical=50
22 | k_latent=15
23 |
24 | python /stanley/WangLab/kamal/code/projects/spin/reviews/scripts/stagate_.py \
25 | --read_path /stanley/WangLab/kamal/data/projects/spin/reviews/brain/adata.h5ad \
26 | --sample_rate $sample_rate \
27 | --k_physical $k_physical \
28 | --k_latent $k_latent \
29 | --leiden_res "0.2" \
30 | --write_path /stanley/WangLab/kamal/data/projects/spin/reviews/results/brain/stagate/reconstructions_${sample_rate}_${k_physical}physical_${k_latent}latent/ \
31 | --random_seed $random_seed
--------------------------------------------------------------------------------
/code_for_figures/benchmarking/scripts/brain/brain_utag.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 |
3 | #$ -l h_vmem=86G
4 | #$ -l h_rt=02:30:00
5 | #$ -o /stanley/WangLab/kamal/outputs/spin/reviews/brain/utag/
6 | #$ -j y
7 | #$ -t 1-110
8 |
9 | source /broad/software/scripts/useuse
10 | reuse Anaconda3
11 | source activate /stanley/WangLab/bridget/envs/utag/
12 |
13 | sample_rates=($(seq 0 0.1 1))
14 | random_seeds=($(seq 0 1 10))
15 | # random_seeds=($(seq 0 0)) # test using a single random seed
16 |
17 | n_sample_rates=${#sample_rates[@]}
18 | sample_rate=${sample_rates[($((SGE_TASK_ID-1))%$n_sample_rates)]}
19 | random_seed=${random_seeds[($((SGE_TASK_ID-1))/$n_sample_rates)]}
20 |
21 | radius=550
22 | k_latent=15
23 |
24 | python /stanley/WangLab/kamal/code/projects/spin/reviews/scripts/utag_.py \
25 | --read_path /stanley/WangLab/kamal/data/projects/spin/reviews/brain/adata.h5ad \
26 | --sample_rate $sample_rate \
27 | --radius $radius \
28 | --k_latent $k_latent \
29 | --n_pcs 50 \
30 | --leiden_res "0.2" \
31 | --write_path /stanley/WangLab/kamal/data/projects/spin/reviews/results/brain/utag/reconstructions_${sample_rate}_${radius}radius_${k_latent}latent/ \
32 | --random_seed $random_seed
--------------------------------------------------------------------------------
/code_for_figures/benchmarking/scripts/brain/performance_brain.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 |
3 | tissue=brain
4 |
5 | methods=(knn radius utag stagate graphst)
6 | jobids=(42435516 42435533 42435534 42435535 42435536)
7 | n_methods="${#methods[@]}"
8 |
9 | # Write job resource metrics to disk
10 | for i in $(seq 0 $((n_methods-1))); do
11 | method=${methods[i]}
12 | jobid=${jobids[i]}
13 | write_path=/stanley/WangLab/kamal/data/projects/spin/reviews/results/${tissue}/${method}/
14 | performance=${write_path}performance_${tissue}_${method}_${jobid}.txt
15 | echo "Writing $performance"
16 | touch $performance
17 | nonsub_tasks=($(seq 11 11 110)) # only compare using non-subsampling runs
18 | for task in ${nonsub_tasks[@]}; do
19 | qacct -j $jobid -t $task >> $performance;
20 | done;
21 | done
22 | echo "Done"
--------------------------------------------------------------------------------
/code_for_figures/benchmarking/scripts/graphst_.py:
--------------------------------------------------------------------------------
1 | import logging
2 | import os
3 | import argparse
4 |
5 | from GraphST import GraphST_mod
6 | import torch
7 | import scanpy as sc
8 | import numpy as np
9 | from sklearn.neighbors import NearestNeighbors
10 | from sklearn.decomposition import PCA
11 | import scipy as sp
12 | from sklearn.cluster import KMeans
13 | from sklearn.metrics import adjusted_rand_score
14 |
15 |
16 | def smooth(
17 | adata,
18 | k_physical,
19 | sample_rate,
20 | n_epochs,
21 | learning_rate,
22 | alpha,
23 | beta,
24 | gamma,
25 | random_seed,
26 | ):
27 |
28 | # Find latent neighbors
29 | nbrs = NearestNeighbors(n_neighbors=k_physical).fit(adata.obsm['spatial'])
30 | A = nbrs.kneighbors_graph()
31 | adata.obsp['spatial_connectivities'] = A.copy()
32 |
33 | # Subsample
34 | if sample_rate:
35 | adata.obsp['spatial_connectivities_subsampled'] = A.copy()
36 | for i in range(len(adata)):
37 | nbr_idxs = adata.obsp['spatial_connectivities'][i].nonzero()[1]
38 | idxs_to_drop = np.random.choice(
39 | nbr_idxs,
40 | size=int(len(nbr_idxs)*(1-sample_rate)),
41 | replace=False,
42 | )
43 | for j in idxs_to_drop:
44 | adata.obsp['spatial_connectivities_subsampled'][i,j] = 0
45 | adata.obsp['spatial_connectivities_subsampled'].eliminate_zeros()
46 | else:
47 | adata.obsp['spatial_connectivities_subsampled'] = np.eye(adata.shape[0])
48 |
49 | # Store in GraphST-readable format
50 | adata.obsm['adj'] = adata.obsp['spatial_connectivities_subsampled']
51 | adata.obsm['graph_neigh'] = adata.obsp['spatial_connectivities_subsampled']
52 |
53 | # Avoid preprocessing (method consistency argument; choosing simplicity)
54 | adata.var['highly_variable'] = np.ones(adata.shape[1], dtype=bool)
55 |
56 | # Train model
57 | device = torch.device('cpu')
58 | model = GraphST_mod.GraphST(
59 | adata,
60 | datatype='Stereo',
61 | device=device,
62 | epochs=n_epochs,
63 | learning_rate=learning_rate,
64 | alpha=alpha,
65 | beta=beta,
66 | gamma=gamma,
67 | )
68 | adata = model.train()
69 | adata.obsm['X_smoothed'] = adata.obsm['emb'].copy()
70 |
71 | return adata
72 |
73 |
74 | def binary_search_leiden(
75 | adata,
76 | leiden_res,
77 | n_regions,
78 | jitter=0.1
79 | ):
80 | sc.tl.leiden(adata, resolution=leiden_res, neighbors_key='smoothed')
81 | n_clusters = len(adata.obs['leiden'].unique())
82 | lo, hi = 0, 5
83 | iters = 0
84 | while n_clusters != n_regions:
85 | if n_clusters < n_regions:
86 | lo = leiden_res
87 | leiden_res = (leiden_res+hi)/2
88 | elif n_clusters > n_regions:
89 | hi = leiden_res
90 | leiden_res = (leiden_res+lo)/2
91 | iters += 1
92 | if iters > 10:
93 | leiden_res += np.random.choice([-1,1]) * jitter
94 | hi += jitter
95 | lo -= max(0,jitter)
96 | sc.tl.leiden(adata, resolution=leiden_res, neighbors_key='smoothed')
97 | n_clusters = len(adata.obs['leiden'].unique())
98 | print(leiden_res, n_clusters, flush=True)
99 | print()
100 |
101 |
102 | def cluster(
103 | adata,
104 | n_pcs,
105 | k_latent,
106 | n_regions,
107 | leiden_res,
108 | ):
109 |
110 | # Calculate latent representation
111 | pca = PCA(n_components=n_pcs)
112 | adata.obsm['X_smoothed_pca'] = pca.fit_transform(adata.obsm['X_smoothed'])
113 |
114 | # Find latent neighbors
115 | nbrs = NearestNeighbors(n_neighbors=k_latent).fit(adata.obsm['X_smoothed_pca'])
116 | adata.obsp['smoothed_connectivities'] = nbrs.kneighbors_graph(mode='connectivity')
117 | adata.obsp['smoothed_distances'] = nbrs.kneighbors_graph(mode='distance')
118 |
119 | # Add metadata expected by Scanpy's Leiden and UMAP
120 | adata.uns['smoothed'] = {'connectivities_key': 'smoothed_connectivities',
121 | 'distances_key': 'smoothed_distances',
122 | 'params': {
123 | 'n_neighbors': k_latent,
124 | 'method': 'umap',
125 | 'random_state': 0,
126 | 'metric': 'euclidean',
127 | 'use_rep': 'X_smoothed_pca'
128 | }
129 | }
130 |
131 | # Perform k-means clustering
132 | kmeans = KMeans(n_clusters=n_regions, n_init=10)
133 | kmeans.fit(adata.obsm['X_smoothed_pca'])
134 | adata.obs['kmeans'] = kmeans.labels_.astype(str)
135 |
136 | # Perform Leiden clustering
137 | binary_search_leiden(adata, leiden_res, n_regions)
138 |
139 |
140 | def quantify(adata, n_regions):
141 |
142 | # Quantify spatial reconstruction
143 | Cp = adata.obsp['spatial_connectivities']
144 | Cl = adata.obsp['smoothed_connectivities']
145 | recon_score = Cp.multiply(Cl).count_nonzero() / (Cp+Cl).count_nonzero()
146 |
147 | # Quantify k-means accuracy
148 | kmeans_ari = adjusted_rand_score(adata.obs['region_true'], adata.obs['kmeans'])
149 |
150 | # Quantify Leiden accuracy
151 | leiden_ari = adjusted_rand_score(adata.obs['region_true'], adata.obs['leiden'])
152 |
153 | return recon_score, kmeans_ari, leiden_ari
154 |
155 |
156 | def main(
157 | read_path,
158 | sample_rate,
159 | k_physical,
160 | k_latent,
161 | n_pcs,
162 | leiden_res,
163 | write_path,
164 | random_seed,
165 | decimals,
166 | n_epochs,
167 | learning_rate,
168 | alpha,
169 | beta,
170 | gamma,
171 | ):
172 |
173 | # Initialize logger
174 | logger = logging.getLogger('GraphST')
175 | logger.setLevel(logging.INFO)
176 | formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
177 | ch = logging.StreamHandler()
178 | ch.setLevel(logging.INFO)
179 | ch.setFormatter(formatter)
180 | logger.addHandler(ch)
181 |
182 | # Set random seed
183 | np.random.seed(random_seed)
184 |
185 | # Load data
186 | logger.info(f'Loading data from {read_path}')
187 | adata = sc.read_h5ad(read_path)
188 | n_regions = len(adata.obs['region_true'].unique())
189 |
190 | # Smooth
191 | logger.info('Smoothing')
192 | logger.info(f'\tsample_rate={sample_rate}')
193 | logger.info(f'\trandom_seed={random_seed}')
194 | adata = smooth(
195 | adata,
196 | k_physical,
197 | sample_rate,
198 | n_epochs,
199 | learning_rate,
200 | alpha,
201 | beta,
202 | gamma,
203 | random_seed,
204 | )
205 |
206 | # Cluster
207 | logger.info('Clustering')
208 | cluster(adata, n_pcs, k_latent, n_regions, leiden_res)
209 |
210 | # Quantify results
211 | logger.info('Quantifying results')
212 | recon_score, kmeans_ari, leiden_ari = quantify(adata, n_regions)
213 |
214 | # Write results to disk
215 | os.makedirs(write_path, exist_ok=True)
216 | results = f'{np.round(recon_score, decimals=decimals)}_' + \
217 | f'{np.round(kmeans_ari, decimals=decimals)}_' + \
218 | f'{np.round(leiden_ari, decimals=decimals)}'
219 | filename_txt = f'{random_seed}_{results}.txt'
220 | write_path_txt = os.path.join(write_path, filename_txt)
221 | logger.info(f'Writing results to {write_path_txt}')
222 | f = open(write_path_txt, 'a')
223 | f.close()
224 |
225 | # Write example AnnData to disk
226 | if random_seed == 0:
227 | filename_adata = f'adata_{sample_rate}.h5ad'
228 | write_path_adata = os.path.join(write_path, filename_adata)
229 | logger.info(f'Saving AnnData to {write_path_adata}')
230 | adata.write(write_path_adata)
231 |
232 | logger.info('Done')
233 |
234 |
235 | if __name__=='__main__':
236 |
237 | parser = argparse.ArgumentParser()
238 | parser.add_argument('--read_path', type=str)
239 | parser.add_argument('--sample_rate', type=float, default=None)
240 | parser.add_argument('--k_physical', type=int, default=50)
241 | parser.add_argument('--k_latent', type=int, default=15)
242 | parser.add_argument('--n_pcs', type=int)
243 | parser.add_argument('--leiden_res', type=float)
244 | parser.add_argument('--write_path', type=str)
245 | parser.add_argument('--random_seed', type=int)
246 | parser.add_argument('--decimals', type=int, default=5)
247 | parser.add_argument('--n_epochs', type=int, default=100)
248 | parser.add_argument('--learning_rate', type=float, default=0.001)
249 | parser.add_argument('--alpha', type=float, default=10)
250 | parser.add_argument('--beta', type=float, default=1)
251 | parser.add_argument('--gamma', type=float, default=1)
252 | args = parser.parse_args()
253 |
254 | main(
255 | args.read_path,
256 | args.sample_rate,
257 | args.k_physical,
258 | args.k_latent,
259 | args.n_pcs,
260 | args.leiden_res,
261 | args.write_path,
262 | args.random_seed,
263 | args.decimals,
264 | args.n_epochs,
265 | args.learning_rate,
266 | args.alpha,
267 | args.beta,
268 | args.gamma,
269 | )
--------------------------------------------------------------------------------
/code_for_figures/benchmarking/scripts/gut/gut_graphst.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 |
3 | #$ -l h_vmem=400G
4 | #$ -l h_rt=04:00:00
5 | #$ -o /stanley/WangLab/kamal/outputs/spin/reviews/gut/graphst/
6 | #$ -j y
7 | #$ -t 1-110
8 |
9 | source /broad/software/scripts/useuse
10 | reuse Anaconda3
11 | source activate /stanley/WangLab/kamal/envs/graphst/
12 |
13 | sample_rates=($(seq 0 0.1 1))
14 | random_seeds=($(seq 0 1 10))
15 | # random_seeds=($(seq 0 0)) # test using a single random seed
16 |
17 | n_sample_rates=${#sample_rates[@]}
18 | sample_rate=${sample_rates[($((SGE_TASK_ID-1))%$n_sample_rates)]}
19 | random_seed=${random_seeds[($((SGE_TASK_ID-1))/$n_sample_rates)]}
20 |
21 | k_physical=50
22 | k_latent=15
23 |
24 | python /stanley/WangLab/kamal/code/projects/spin/reviews/scripts/graphst_.py \
25 | --read_path /stanley/WangLab/kamal/data/projects/spin/reviews/gut/adata.h5ad \
26 | --sample_rate $sample_rate \
27 | --k_physical $k_physical \
28 | --k_latent $k_latent \
29 | --leiden_res "0.2" \
30 | --write_path /stanley/WangLab/kamal/data/projects/spin/reviews/results/gut/graphst/reconstructions_${sample_rate}_${k_physical}physical_${k_latent}latent/ \
31 | --random_seed $random_seed \
32 | --n_epochs 50 \
--------------------------------------------------------------------------------
/code_for_figures/benchmarking/scripts/gut/gut_knn.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 |
3 | #$ -l h_vmem=48G
4 | #$ -l h_rt=02:00:00
5 | #$ -o /stanley/WangLab/kamal/outputs/spin/reviews/gut/knn/
6 | #$ -j y
7 | #$ -t 1-110
8 |
9 | source /broad/software/scripts/useuse
10 | reuse Anaconda3
11 | source activate /stanley/WangLab/kamal/envs/xax
12 |
13 | sample_rates=($(seq 0 0.1 1))
14 | random_seeds=($(seq 0 1 10))
15 | # random_seeds=($(seq 0 0)) # test using a single random seed
16 |
17 | n_sample_rates=${#sample_rates[@]}
18 | sample_rate=${sample_rates[($((SGE_TASK_ID-1))%$n_sample_rates)]}
19 | random_seed=${random_seeds[($((SGE_TASK_ID-1))/$n_sample_rates)]}
20 |
21 | k_physical=50
22 | k_latent=15
23 |
24 | python /stanley/WangLab/kamal/code/projects/spin/reviews/scripts/knn.py \
25 | --read_path /stanley/WangLab/kamal/data/projects/spin/reviews/gut/adata.h5ad \
26 | --sample_rate $sample_rate \
27 | --k_physical $k_physical \
28 | --k_latent $k_latent \
29 | --n_pcs 50 \
30 | --leiden_res "0.2" \
31 | --write_path /stanley/WangLab/kamal/data/projects/spin/reviews/results/gut/knn/reconstructions_${sample_rate}_${k_physical}physical_${k_latent}latent/ \
32 | --random_seed $random_seed
--------------------------------------------------------------------------------
/code_for_figures/benchmarking/scripts/gut/gut_radius.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 |
3 | #$ -l h_vmem=48G
4 | #$ -l h_rt=02:00:00
5 | #$ -o /stanley/WangLab/kamal/outputs/spin/reviews/gut/radius/
6 | #$ -j y
7 | #$ -t 1-110
8 |
9 | source /broad/software/scripts/useuse
10 | reuse Anaconda3
11 | source activate /stanley/WangLab/kamal/envs/xax
12 |
13 | sample_rates=($(seq 0 0.1 1))
14 | random_seeds=($(seq 0 1 10))
15 | # random_seeds=($(seq 0 0)) # test using a single random seed
16 |
17 | n_sample_rates=${#sample_rates[@]}
18 | sample_rate=${sample_rates[($((SGE_TASK_ID-1))%$n_sample_rates)]}
19 | random_seed=${random_seeds[($((SGE_TASK_ID-1))/$n_sample_rates)]}
20 |
21 | radius=260 # ~ 50 nbrs
22 | k_latent=15
23 |
24 | python /stanley/WangLab/kamal/code/projects/spin/reviews/scripts/radius.py \
25 | --read_path /stanley/WangLab/kamal/data/projects/spin/reviews/gut/adata.h5ad \
26 | --sample_rate $sample_rate \
27 | --radius $radius \
28 | --k_latent $k_latent \
29 | --n_pcs 50 \
30 | --leiden_res "0.2" \
31 | --write_path /stanley/WangLab/kamal/data/projects/spin/reviews/results/gut/radius/reconstructions_${sample_rate}_${radius}radius_${k_latent}latent/ \
32 | --random_seed $random_seed
--------------------------------------------------------------------------------
/code_for_figures/benchmarking/scripts/gut/gut_stagate.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 |
3 | #$ -l h_vmem=120G
4 | #$ -l h_rt=05:00:00
5 | #$ -o /stanley/WangLab/kamal/outputs/spin/reviews/gut/stagate/
6 | #$ -j y
7 | #$ -t 1-110
8 |
9 | source /broad/software/scripts/useuse
10 | reuse Anaconda3
11 | source activate /stanley/WangLab/kamal/envs/stagate_pyg/
12 |
13 | sample_rates=($(seq 0 0.1 1))
14 | random_seeds=($(seq 0 1 10))
15 | # random_seeds=($(seq 0 0)) # test using a single random seed
16 |
17 | n_sample_rates=${#sample_rates[@]}
18 | sample_rate=${sample_rates[($((SGE_TASK_ID-1))%$n_sample_rates)]}
19 | random_seed=${random_seeds[($((SGE_TASK_ID-1))/$n_sample_rates)]}
20 |
21 | k_physical=50
22 | k_latent=15
23 |
24 | python /stanley/WangLab/kamal/code/projects/spin/reviews/scripts/stagate_.py \
25 | --read_path /stanley/WangLab/kamal/data/projects/spin/reviews/gut/adata.h5ad \
26 | --sample_rate $sample_rate \
27 | --k_physical $k_physical \
28 | --k_latent $k_latent \
29 | --leiden_res "0.2" \
30 | --write_path /stanley/WangLab/kamal/data/projects/spin/reviews/results/gut/stagate/reconstructions_${sample_rate}_${k_physical}physical_${k_latent}latent/ \
31 | --random_seed $random_seed
--------------------------------------------------------------------------------
/code_for_figures/benchmarking/scripts/gut/gut_utag.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 |
3 | #$ -l h_vmem=256G
4 | #$ -l h_rt=01:30:00
5 | #$ -o /stanley/WangLab/kamal/outputs/spin/reviews/gut/utag/
6 | #$ -j y
7 | #$ -t 1-110
8 |
9 | source /broad/software/scripts/useuse
10 | reuse Anaconda3
11 | source activate /stanley/WangLab/bridget/envs/utag/
12 |
13 | sample_rates=($(seq 0 0.1 1))
14 | random_seeds=($(seq 0 1 10))
15 | # random_seeds=($(seq 0 0)) # test using a single random seed
16 |
17 | n_sample_rates=${#sample_rates[@]}
18 | sample_rate=${sample_rates[($((SGE_TASK_ID-1))%$n_sample_rates)]}
19 | random_seed=${random_seeds[($((SGE_TASK_ID-1))/$n_sample_rates)]}
20 |
21 | radius=260 # ~ 50 nbrs
22 | k_latent=15
23 |
24 | python /stanley/WangLab/kamal/code/projects/spin/reviews/scripts/utag_.py \
25 | --read_path /stanley/WangLab/kamal/data/projects/spin/reviews/gut/adata.h5ad \
26 | --sample_rate $sample_rate \
27 | --radius $radius \
28 | --k_latent $k_latent \
29 | --n_pcs 50 \
30 | --leiden_res "0.2" \
31 | --write_path /stanley/WangLab/kamal/data/projects/spin/reviews/results/gut/utag/reconstructions_${sample_rate}_${radius}radius_${k_latent}latent/ \
32 | --random_seed $random_seed
--------------------------------------------------------------------------------
/code_for_figures/benchmarking/scripts/gut/performance_gut.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 |
3 | tissue=gut
4 |
5 | methods=(knn radius utag stagate graphst)
6 | jobids=(42437430 42437787 42437788 42437789 42437790)
7 | n_methods="${#methods[@]}"
8 |
9 | # Write job resource metrics to disk
10 | for i in $(seq 0 $((n_methods-1))); do
11 | method=${methods[i]}
12 | jobid=${jobids[i]}
13 | write_path=/stanley/WangLab/kamal/data/projects/spin/reviews/results/${tissue}/${method}/
14 | performance=${write_path}performance_${tissue}_${method}_${jobid}.txt
15 | echo "Writing $performance"
16 | touch $performance
17 | nonsub_tasks=($(seq 11 11 110)) # only compare using non-subsampling runs
18 | for task in ${nonsub_tasks[@]}; do
19 | qacct -j $jobid -t $task >> $performance;
20 | done;
21 | done
22 | echo "Done"
--------------------------------------------------------------------------------
/code_for_figures/benchmarking/scripts/knn.py:
--------------------------------------------------------------------------------
1 | import logging
2 | import os
3 | import argparse
4 |
5 | import scanpy as sc
6 | import numpy as np
7 | from sklearn.neighbors import NearestNeighbors
8 | from sklearn.decomposition import PCA
9 | import scipy as sp
10 | from sklearn.cluster import KMeans
11 | from sklearn.metrics import adjusted_rand_score
12 |
13 |
14 | def smooth(
15 | adata,
16 | k_physical,
17 | subsample_rate,
18 | ):
19 |
20 | # Get neighbor info
21 | nbrs = NearestNeighbors(n_neighbors=k_physical).fit(adata.obsm['spatial'])
22 | A = nbrs.kneighbors_graph()
23 | adata.obsp['spatial_connectivities'] = A.copy()
24 |
25 | # Subsample
26 | if subsample_rate:
27 | adata.obsp['spatial_connectivities_subsampled'] = A.copy()
28 | for i in range(len(adata)):
29 | nbr_idxs = adata.obsp['spatial_connectivities'][i].nonzero()[1]
30 | idxs_to_drop = np.random.choice(
31 | nbr_idxs,
32 | size=int(len(nbr_idxs)*(1-subsample_rate)),
33 | replace=False,
34 | )
35 | for j in idxs_to_drop:
36 | adata.obsp['spatial_connectivities_subsampled'][i,j] = 0
37 | adata.obsp['spatial_connectivities_subsampled'].eliminate_zeros()
38 | else:
39 | adata.obsp['spatial_connectivities_subsampled'] = np.eye(adata.shape[0])
40 |
41 | # Smooth
42 | adata.obsm['X_smoothed'] = adata.obsp['spatial_connectivities_subsampled'] @ adata.X
43 |
44 |
45 | def binary_search_leiden(
46 | adata,
47 | leiden_res,
48 | n_regions,
49 | jitter=0.1
50 | ):
51 | sc.tl.leiden(adata, resolution=leiden_res, neighbors_key='smoothed')
52 | n_clusters = len(adata.obs['leiden'].unique())
53 | lo, hi = 0, 3
54 | iters = 0
55 | while n_clusters != n_regions:
56 | if n_clusters < n_regions:
57 | lo = leiden_res
58 | leiden_res = (leiden_res+hi)/2
59 | elif n_clusters > n_regions:
60 | hi = leiden_res
61 | leiden_res = (leiden_res+lo)/2
62 | iters += 1
63 | if iters > 20:
64 | leiden_res += np.random.choice([-1,1]) * jitter
65 | # hi += jitter
66 | # lo -= max(0,jitter)
67 | sc.tl.leiden(adata, resolution=leiden_res, neighbors_key='smoothed')
68 | n_clusters = len(adata.obs['leiden'].unique())
69 | print(leiden_res, n_clusters, flush=True)
70 | print()
71 |
72 |
73 | def cluster(
74 | adata,
75 | n_pcs,
76 | k_latent,
77 | n_regions,
78 | leiden_res,
79 | ):
80 |
81 | # Calculate latent representation
82 | pca = PCA(n_components=n_pcs)
83 | adata.obsm['X_smoothed_pca'] = pca.fit_transform(adata.obsm['X_smoothed'])
84 |
85 | # Find latent neighbors
86 | nbrs = NearestNeighbors(n_neighbors=k_latent).fit(adata.obsm['X_smoothed_pca'])
87 | adata.obsp['smoothed_connectivities'] = nbrs.kneighbors_graph(mode='connectivity')
88 | adata.obsp['smoothed_distances'] = nbrs.kneighbors_graph(mode='distance')
89 |
90 | # Add metadata expected by Scanpy's Leiden and UMAP
91 | adata.uns['smoothed'] = {'connectivities_key': 'smoothed_connectivities',
92 | 'distances_key': 'smoothed_distances',
93 | 'params': {
94 | 'n_neighbors': k_latent,
95 | 'method': 'umap',
96 | 'random_state': 0,
97 | 'metric': 'euclidean',
98 | 'use_rep': 'X_smoothed_pca'
99 | }
100 | }
101 |
102 | # Perform k-means clustering
103 | kmeans = KMeans(n_clusters=n_regions, n_init=10)
104 | kmeans.fit(adata.obsm['X_smoothed_pca'])
105 | adata.obs['kmeans'] = kmeans.labels_.astype(str)
106 |
107 | # Perform Leiden clustering
108 | binary_search_leiden(adata, leiden_res, n_regions)
109 |
110 |
111 | def quantify(adata, n_regions):
112 |
113 | # Quantify spatial reconstruction
114 | Cp = adata.obsp['spatial_connectivities']
115 | Cl = adata.obsp['smoothed_connectivities']
116 | recon_score = Cp.multiply(Cl).count_nonzero() / (Cp+Cl).count_nonzero()
117 |
118 | # Quantify k-means accuracy
119 | kmeans_ari = adjusted_rand_score(adata.obs['region_true'], adata.obs['kmeans'])
120 |
121 | # Quantify Leiden accuracy
122 | leiden_ari = adjusted_rand_score(adata.obs['region_true'], adata.obs['leiden'])
123 |
124 | return recon_score, kmeans_ari, leiden_ari
125 |
126 |
127 | def main(
128 | read_path,
129 | sample_rate,
130 | k_physical,
131 | k_latent,
132 | n_pcs,
133 | leiden_res,
134 | write_path,
135 | random_seed,
136 | decimals,
137 | ):
138 |
139 | # Initialize logger
140 | logger = logging.getLogger('kNN')
141 | logger.setLevel(logging.INFO)
142 | formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
143 | ch = logging.StreamHandler()
144 | ch.setLevel(logging.INFO)
145 | ch.setFormatter(formatter)
146 | logger.addHandler(ch)
147 |
148 | # Set random seed
149 | np.random.seed(random_seed)
150 |
151 | # Load data
152 | logger.info(f'Loading data from {read_path}')
153 | adata = sc.read_h5ad(read_path)
154 | n_regions = len(adata.obs['region_true'].unique())
155 |
156 | # Smooth
157 | logger.info('Smoothing')
158 | logger.info(f'\tsample_rate={sample_rate}')
159 | logger.info(f'\trandom_seed={random_seed}')
160 | smooth(adata, k_physical, sample_rate)
161 |
162 | # Cluster
163 | logger.info('Clustering')
164 | cluster(adata, n_pcs, k_latent, n_regions, leiden_res)
165 |
166 | # Quantify results
167 | logger.info('Quantifying results')
168 | recon_score, kmeans_ari, leiden_ari = quantify(adata, n_regions)
169 |
170 | # Write results to disk
171 | os.makedirs(write_path, exist_ok=True)
172 | results = f'{np.round(recon_score, decimals=decimals)}_' + \
173 | f'{np.round(kmeans_ari, decimals=decimals)}_' + \
174 | f'{np.round(leiden_ari, decimals=decimals)}'
175 | filename_txt = f'{random_seed}_{results}.txt'
176 | write_path_txt = os.path.join(write_path, filename_txt)
177 | logger.info(f'Writing results to {write_path_txt}')
178 | f = open(write_path_txt, 'a')
179 | f.close()
180 |
181 | # Write example AnnData to disk
182 | filename_adata = f'adata_{sample_rate}.h5ad'
183 | write_path_adata = os.path.join(write_path, filename_adata)
184 | if not os.path.exists(write_path_adata):
185 | logger.info(f'Saving AnnData to {write_path_adata}')
186 | adata.write(write_path_adata)
187 |
188 | logger.info('Done')
189 |
190 |
191 | if __name__=='__main__':
192 |
193 | parser = argparse.ArgumentParser()
194 | parser.add_argument('--read_path', type=str)
195 | parser.add_argument('--sample_rate', type=float, default=None)
196 | parser.add_argument('--k_physical', type=int, default=50)
197 | parser.add_argument('--k_latent', type=int, default=15)
198 | parser.add_argument('--n_pcs', type=int)
199 | parser.add_argument('--leiden_res', type=float)
200 | parser.add_argument('--write_path', type=str)
201 | parser.add_argument('--random_seed', type=int)
202 | parser.add_argument('--decimals', type=int, default=5)
203 | args = parser.parse_args()
204 |
205 | main(
206 | args.read_path,
207 | args.sample_rate,
208 | args.k_physical,
209 | args.k_latent,
210 | args.n_pcs,
211 | args.leiden_res,
212 | args.write_path,
213 | args.random_seed,
214 | args.decimals,
215 | )
--------------------------------------------------------------------------------
/code_for_figures/benchmarking/scripts/modified_existing_methods/graphst/GraphST_mod.py:
--------------------------------------------------------------------------------
1 | import torch
2 | from .preprocess import preprocess_adj, preprocess_adj_sparse, preprocess, construct_interaction, construct_interaction_KNN, add_contrastive_label, get_feature, permutation, fix_seed
3 | import time
4 | import random
5 | import numpy as np
6 | from .model import Encoder, Encoder_sparse, Encoder_map, Encoder_sc
7 | from tqdm import tqdm
8 | from torch import nn
9 | import torch.nn.functional as F
10 | from scipy.sparse.csc import csc_matrix
11 | from scipy.sparse.csr import csr_matrix
12 | import pandas as pd
13 |
14 | class GraphST():
15 | def __init__(self,
16 | adata,
17 | adata_sc = None,
18 | device= torch.device('cpu'),
19 | learning_rate=0.001,
20 | learning_rate_sc = 0.01,
21 | weight_decay=0.00,
22 | epochs=600,
23 | dim_input=3000,
24 | dim_output=64,
25 | random_seed = 41,
26 | alpha = 10,
27 | beta = 1,
28 | gamma = 1,
29 | theta = 0.1,
30 | lamda1 = 10,
31 | lamda2 = 1,
32 | deconvolution = False,
33 | datatype = '10X'
34 | ):
35 | '''\
36 |
37 | Parameters
38 | ----------
39 | adata : anndata
40 | AnnData object of spatial data.
41 | adata_sc : anndata, optional
42 | AnnData object of scRNA-seq data. adata_sc is needed for deconvolution. The default is None.
43 | device : string, optional
44 | Using GPU or CPU? The default is 'cpu'.
45 | learning_rate : float, optional
46 | Learning rate for ST representation learning. The default is 0.001.
47 | learning_rate_sc : float, optional
48 | Learning rate for scRNA representation learning. The default is 0.01.
49 | weight_decay : float, optional
50 | Weight factor to control the influence of weight parameters. The default is 0.00.
51 | epochs : int, optional
52 | Epoch for model training. The default is 600.
53 | dim_input : int, optional
54 | Dimension of input feature. The default is 3000.
55 | dim_output : int, optional
56 | Dimension of output representation. The default is 64.
57 | random_seed : int, optional
58 | Random seed to fix model initialization. The default is 41.
59 | alpha : float, optional
60 | Weight factor to control the influence of reconstruction loss in representation learning.
61 | The default is 10.
62 | beta : float, optional
63 | Weight factor to control the influence of contrastive loss in representation learning.
64 | The default is 1.
65 | lamda1 : float, optional
66 | Weight factor to control the influence of reconstruction loss in mapping matrix learning.
67 | The default is 10.
68 | lamda2 : float, optional
69 | Weight factor to control the influence of contrastive loss in mapping matrix learning.
70 | The default is 1.
71 | deconvolution : bool, optional
72 | Deconvolution task? The default is False.
73 | datatype : string, optional
74 | Data type of input. Our model supports 10X Visium ('10X'), Stereo-seq ('Stereo'), and Slide-seq/Slide-seqV2 ('Slide') data.
75 | Returns
76 | -------
77 | The learned representation 'self.emb_rec'.
78 |
79 | '''
80 | self.adata = adata.copy()
81 | self.device = device
82 | self.learning_rate=learning_rate
83 | self.learning_rate_sc = learning_rate_sc
84 | self.weight_decay=weight_decay
85 | self.epochs=epochs
86 | self.random_seed = random_seed
87 | self.alpha = alpha
88 | self.beta = beta
89 | self.gamma = gamma
90 | self.theta = theta
91 | self.lamda1 = lamda1
92 | self.lamda2 = lamda2
93 | self.deconvolution = deconvolution
94 | self.datatype = datatype
95 |
96 | fix_seed(self.random_seed)
97 |
98 | if 'highly_variable' not in adata.var.keys():
99 | preprocess(self.adata)
100 |
101 | if 'adj' not in adata.obsm.keys():
102 | if self.datatype in ['Stereo', 'Slide']:
103 | construct_interaction_KNN(self.adata)
104 | else:
105 | construct_interaction(self.adata)
106 |
107 | if 'label_CSL' not in adata.obsm.keys():
108 | add_contrastive_label(self.adata)
109 |
110 | if 'feat' not in adata.obsm.keys():
111 | get_feature(self.adata)
112 |
113 | self.features = torch.FloatTensor(self.adata.obsm['feat'].copy()).to(self.device)
114 | self.features_a = torch.FloatTensor(self.adata.obsm['feat_a'].copy()).to(self.device)
115 | self.label_CSL = torch.FloatTensor(self.adata.obsm['label_CSL']).to(self.device)
116 | self.adj = self.adata.obsm['adj']
117 | self.graph_neigh = torch.FloatTensor(self.adata.obsm['graph_neigh'].copy() + np.eye(self.adj.shape[0])).to(self.device)
118 |
119 | self.dim_input = self.features.shape[1]
120 | self.dim_output = dim_output
121 |
122 | if self.datatype in ['Stereo', 'Slide']:
123 | #using sparse
124 | print('Building sparse matrix ...')
125 | self.adj = preprocess_adj_sparse(self.adj).to(self.device)
126 | else:
127 | # standard version
128 | self.adj = preprocess_adj(self.adj)
129 | self.adj = torch.FloatTensor(self.adj).to(self.device)
130 |
131 | if self.deconvolution:
132 | self.adata_sc = adata_sc.copy()
133 |
134 | if isinstance(self.adata.X, csc_matrix) or isinstance(self.adata.X, csr_matrix):
135 | self.feat_sp = adata.X.toarray()[:, ]
136 | else:
137 | self.feat_sp = adata.X[:, ]
138 | if isinstance(self.adata_sc.X, csc_matrix) or isinstance(self.adata_sc.X, csr_matrix):
139 | self.feat_sc = self.adata_sc.X.toarray()[:, ]
140 | else:
141 | self.feat_sc = self.adata_sc.X[:, ]
142 |
143 | # fill nan as 0
144 | self.feat_sc = pd.DataFrame(self.feat_sc).fillna(0).values
145 | self.feat_sp = pd.DataFrame(self.feat_sp).fillna(0).values
146 |
147 | self.feat_sc = torch.FloatTensor(self.feat_sc).to(self.device)
148 | self.feat_sp = torch.FloatTensor(self.feat_sp).to(self.device)
149 |
150 | if self.adata_sc is not None:
151 | self.dim_input = self.feat_sc.shape[1]
152 |
153 | self.n_cell = adata_sc.n_obs
154 | self.n_spot = adata.n_obs
155 |
156 | def train(self):
157 | if self.datatype in ['Stereo', 'Slide']:
158 | self.model = Encoder_sparse(self.dim_input, self.dim_output, self.graph_neigh).to(self.device)
159 | else:
160 | self.model = Encoder(self.dim_input, self.dim_output, self.graph_neigh).to(self.device)
161 | self.loss_CSL = nn.BCEWithLogitsLoss()
162 |
163 | self.optimizer = torch.optim.Adam(self.model.parameters(), self.learning_rate,
164 | weight_decay=self.weight_decay)
165 |
166 | print('Begin to train ST data...')
167 | self.model.train()
168 |
169 | for epoch in tqdm(range(self.epochs)):
170 | self.model.train()
171 |
172 | self.features_a = permutation(self.features)
173 | self.hiden_feat, self.emb, ret, ret_a = self.model(self.features, self.features_a, self.adj)
174 |
175 | self.loss_sl_1 = self.loss_CSL(ret, self.label_CSL)
176 | self.loss_sl_2 = self.loss_CSL(ret_a, self.label_CSL)
177 | self.loss_feat = F.mse_loss(self.features, self.emb)
178 |
179 | loss = self.alpha*self.loss_feat + self.beta*self.loss_sl_1 + self.gamma*self.loss_sl_2
180 |
181 | self.optimizer.zero_grad()
182 | loss.backward()
183 | self.optimizer.step()
184 |
185 | print("Optimization finished for ST data!")
186 |
187 | with torch.no_grad():
188 | self.model.eval()
189 | if self.deconvolution:
190 | self.emb_rec = self.model(self.features, self.features_a, self.adj)[1]
191 |
192 | return self.emb_rec
193 | else:
194 | if self.datatype in ['Stereo', 'Slide']:
195 | self.emb_rec = self.model(self.features, self.features_a, self.adj)[1]
196 | self.emb_rec = F.normalize(self.emb_rec, p=2, dim=1).detach().cpu().numpy()
197 | else:
198 | self.emb_rec = self.model(self.features, self.features_a, self.adj)[1].detach().cpu().numpy()
199 | self.adata.obsm['emb'] = self.emb_rec
200 |
201 | return self.adata
202 |
203 | def train_sc(self):
204 | self.model_sc = Encoder_sc(self.dim_input, self.dim_output).to(self.device)
205 | self.optimizer_sc = torch.optim.Adam(self.model_sc.parameters(), lr=self.learning_rate_sc)
206 |
207 | print('Begin to train scRNA data...')
208 | for epoch in tqdm(range(self.epochs)):
209 | self.model_sc.train()
210 |
211 | emb = self.model_sc(self.feat_sc)
212 | loss = F.mse_loss(emb, self.feat_sc)
213 |
214 | self.optimizer_sc.zero_grad()
215 | loss.backward()
216 | self.optimizer_sc.step()
217 |
218 | print("Optimization finished for cell representation learning!")
219 |
220 | with torch.no_grad():
221 | self.model_sc.eval()
222 | emb_sc = self.model_sc(self.feat_sc)
223 |
224 | return emb_sc
225 |
226 | def train_map(self):
227 | emb_sp = self.train()
228 | emb_sc = self.train_sc()
229 |
230 | self.adata.obsm['emb_sp'] = emb_sp.detach().cpu().numpy()
231 | self.adata_sc.obsm['emb_sc'] = emb_sc.detach().cpu().numpy()
232 |
233 | # Normalize features for consistence between ST and scRNA-seq
234 | emb_sp = F.normalize(emb_sp, p=2, eps=1e-12, dim=1)
235 | emb_sc = F.normalize(emb_sc, p=2, eps=1e-12, dim=1)
236 |
237 | self.model_map = Encoder_map(self.n_cell, self.n_spot).to(self.device)
238 |
239 | self.optimizer_map = torch.optim.Adam(self.model_map.parameters(), lr=self.learning_rate, weight_decay=self.weight_decay)
240 |
241 | print('Begin to learn mapping matrix...')
242 | for epoch in tqdm(range(self.epochs)):
243 | self.model_map.train()
244 | self.map_matrix = self.model_map()
245 |
246 | loss_recon, loss_NCE = self.loss(emb_sp, emb_sc)
247 |
248 | loss = self.lamda1*loss_recon + self.lamda2*loss_NCE
249 |
250 | self.optimizer_map.zero_grad()
251 | loss.backward()
252 | self.optimizer_map.step()
253 |
254 | print("Mapping matrix learning finished!")
255 |
256 | # take final softmax w/o computing gradients
257 | with torch.no_grad():
258 | self.model_map.eval()
259 | emb_sp = emb_sp.cpu().numpy()
260 | emb_sc = emb_sc.cpu().numpy()
261 | map_matrix = F.softmax(self.map_matrix, dim=1).cpu().numpy() # dim=1: normalization by cell
262 |
263 | self.adata.obsm['emb_sp'] = emb_sp
264 | self.adata_sc.obsm['emb_sc'] = emb_sc
265 | self.adata.obsm['map_matrix'] = map_matrix.T # spot x cell
266 |
267 | return self.adata, self.adata_sc
268 |
269 | def loss(self, emb_sp, emb_sc):
270 | '''\
271 | Calculate loss
272 |
273 | Parameters
274 | ----------
275 | emb_sp : torch tensor
276 | Spatial spot representation matrix.
277 | emb_sc : torch tensor
278 | scRNA cell representation matrix.
279 |
280 | Returns
281 | -------
282 | Loss values.
283 |
284 | '''
285 | # cell-to-spot
286 | map_probs = F.softmax(self.map_matrix, dim=1) # dim=0: normalization by cell
287 | self.pred_sp = torch.matmul(map_probs.t(), emb_sc)
288 |
289 | loss_recon = F.mse_loss(self.pred_sp, emb_sp, reduction='mean')
290 | loss_NCE = self.Noise_Cross_Entropy(self.pred_sp, emb_sp)
291 |
292 | return loss_recon, loss_NCE
293 |
294 | def Noise_Cross_Entropy(self, pred_sp, emb_sp):
295 | '''\
296 | Calculate noise cross entropy. Considering spatial neighbors as positive pairs for each spot
297 |
298 | Parameters
299 | ----------
300 | pred_sp : torch tensor
301 | Predicted spatial gene expression matrix.
302 | emb_sp : torch tensor
303 | Reconstructed spatial gene expression matrix.
304 |
305 | Returns
306 | -------
307 | loss : float
308 | Loss value.
309 |
310 | '''
311 |
312 | mat = self.cosine_similarity(pred_sp, emb_sp)
313 | k = torch.exp(mat).sum(axis=1) - torch.exp(torch.diag(mat, 0))
314 |
315 | # positive pairs
316 | p = torch.exp(mat)
317 | p = torch.mul(p, self.graph_neigh).sum(axis=1)
318 |
319 | ave = torch.div(p, k)
320 | loss = - torch.log(ave).mean()
321 |
322 | return loss
323 |
324 | def cosine_similarity(self, pred_sp, emb_sp): #pres_sp: spot x gene; emb_sp: spot x gene
325 | '''\
326 | Calculate cosine similarity based on predicted and reconstructed gene expression matrix.
327 | '''
328 |
329 | M = torch.matmul(pred_sp, emb_sp.T)
330 | Norm_c = torch.norm(pred_sp, p=2, dim=1)
331 | Norm_s = torch.norm(emb_sp, p=2, dim=1)
332 | Norm = torch.matmul(Norm_c.reshape((pred_sp.shape[0], 1)), Norm_s.reshape((emb_sp.shape[0], 1)).T) + -5e-12
333 | M = torch.div(M, Norm)
334 |
335 | if torch.any(torch.isnan(M)):
336 | M = torch.where(torch.isnan(M), torch.full_like(M, 0.4868), M)
337 |
338 | return M
339 |
--------------------------------------------------------------------------------
/code_for_figures/benchmarking/scripts/modified_existing_methods/stagate/utils.py:
--------------------------------------------------------------------------------
1 | import pandas as pd
2 | import numpy as np
3 | import sklearn.neighbors
4 | import scipy.sparse as sp
5 | import seaborn as sns
6 | import matplotlib.pyplot as plt
7 |
8 | import torch
9 | from torch_geometric.data import Data
10 |
11 | def Transfer_pytorch_Data(adata):
12 | G_df = adata.uns['Spatial_Net'].copy()
13 | cells = np.array(adata.obs_names)
14 | cells_id_tran = dict(zip(cells, range(cells.shape[0])))
15 | G_df['Cell1'] = G_df['Cell1'].map(cells_id_tran)
16 | G_df['Cell2'] = G_df['Cell2'].map(cells_id_tran)
17 |
18 | G = sp.coo_matrix((np.ones(G_df.shape[0]), (G_df['Cell1'], G_df['Cell2'])), shape=(adata.n_obs, adata.n_obs))
19 | G = G + sp.eye(G.shape[0])
20 |
21 | edgeList = np.nonzero(G)
22 | if type(adata.X) == np.ndarray:
23 | data = Data(edge_index=torch.LongTensor(np.array(
24 | [edgeList[0], edgeList[1]])), x=torch.FloatTensor(adata.X)) # .todense()
25 | else:
26 | data = Data(edge_index=torch.LongTensor(np.array(
27 | [edgeList[0], edgeList[1]])), x=torch.FloatTensor(adata.X.todense())) # .todense()
28 | return data
29 |
30 | def Batch_Data(adata, num_batch_x, num_batch_y, spatial_key=['X', 'Y'], plot_Stats=False):
31 | Sp_df = adata.obs.loc[:, spatial_key].copy()
32 | Sp_df = np.array(Sp_df)
33 | batch_x_coor = [np.percentile(Sp_df[:, 0], (1/num_batch_x)*x*100) for x in range(num_batch_x+1)]
34 | batch_y_coor = [np.percentile(Sp_df[:, 1], (1/num_batch_y)*x*100) for x in range(num_batch_y+1)]
35 |
36 | Batch_list = []
37 | for it_x in range(num_batch_x):
38 | for it_y in range(num_batch_y):
39 | min_x = batch_x_coor[it_x]
40 | max_x = batch_x_coor[it_x+1]
41 | min_y = batch_y_coor[it_y]
42 | max_y = batch_y_coor[it_y+1]
43 | temp_adata = adata.copy()
44 | temp_adata = temp_adata[temp_adata.obs[spatial_key[0]].map(lambda x: min_x <= x <= max_x)]
45 | temp_adata = temp_adata[temp_adata.obs[spatial_key[1]].map(lambda y: min_y <= y <= max_y)]
46 | Batch_list.append(temp_adata)
47 | if plot_Stats:
48 | f, ax = plt.subplots(figsize=(1, 3))
49 | plot_df = pd.DataFrame([x.shape[0] for x in Batch_list], columns=['#spot/batch'])
50 | sns.boxplot(y='#spot/batch', data=plot_df, ax=ax)
51 | sns.stripplot(y='#spot/batch', data=plot_df, ax=ax, color='red', size=5)
52 | return Batch_list
53 |
54 | def Cal_Spatial_Net(adata, rad_cutoff=None, k_cutoff=None, model='Radius', verbose=True, sample_rate=None):
55 | """\
56 | Construct the spatial neighbor networks.
57 |
58 | Parameters
59 | ----------
60 | adata
61 | AnnData object of scanpy package.
62 | rad_cutoff
63 | radius cutoff when model='Radius'
64 | k_cutoff
65 | The number of nearest neighbors when model='KNN'
66 | model
67 | The network construction model. When model=='Radius', the spot is connected to spots whose distance is less than rad_cutoff. When model=='KNN', the spot is connected to its first k_cutoff nearest neighbors.
68 |
69 | Returns
70 | -------
71 | The spatial networks are saved in adata.uns['Spatial_Net']
72 | """
73 |
74 | assert(model in ['Radius', 'KNN'])
75 | if verbose:
76 | print('------Calculating spatial graph...')
77 | coor = pd.DataFrame(adata.obsm['spatial'])
78 | coor.index = adata.obs.index
79 | coor.columns = ['imagerow', 'imagecol']
80 |
81 | if model == 'Radius':
82 | nbrs = sklearn.neighbors.NearestNeighbors(radius=rad_cutoff).fit(coor)
83 | distances, indices = nbrs.radius_neighbors(coor, return_distance=True)
84 | KNN_list = []
85 | for it in range(indices.shape[0]):
86 | KNN_list.append(pd.DataFrame(zip([it]*indices[it].shape[0], indices[it], distances[it])))
87 |
88 | if model == 'KNN':
89 | nbrs = sklearn.neighbors.NearestNeighbors(n_neighbors=k_cutoff+1).fit(coor)
90 | distances, indices = nbrs.kneighbors(coor)
91 | if sample_rate:
92 | #if subsample:
93 | np.random.seed(0)
94 | n_samples = int(k_cutoff * sample_rate)
95 | indices = np.array([np.random.choice(idxs, size=n_samples, replace=False)
96 | for idxs in indices])
97 | distances = np.array([np.random.choice(dists, size=n_samples, replace=False)
98 | for dists in distances])
99 | KNN_list = []
100 | for it in range(indices.shape[0]):
101 | KNN_list.append(pd.DataFrame(zip([it]*indices.shape[1],indices[it,:], distances[it,:])))
102 |
103 | KNN_df = pd.concat(KNN_list)
104 | KNN_df.columns = ['Cell1', 'Cell2', 'Distance']
105 |
106 | Spatial_Net = KNN_df.copy()
107 | Spatial_Net = Spatial_Net.loc[Spatial_Net['Distance']>0,]
108 | id_cell_trans = dict(zip(range(coor.shape[0]), np.array(coor.index), ))
109 | Spatial_Net['Cell1'] = Spatial_Net['Cell1'].map(id_cell_trans)
110 | Spatial_Net['Cell2'] = Spatial_Net['Cell2'].map(id_cell_trans)
111 | if verbose:
112 | print('The graph contains %d edges, %d cells.' %(Spatial_Net.shape[0], adata.n_obs))
113 | print('%.4f neighbors per cell on average.' %(Spatial_Net.shape[0]/adata.n_obs))
114 |
115 | adata.uns['Spatial_Net'] = Spatial_Net
116 |
117 |
118 | def Cal_Spatial_Net_3D(adata, rad_cutoff_2D, rad_cutoff_Zaxis,
119 | key_section='Section_id', section_order=None, verbose=True):
120 | """\
121 | Construct the spatial neighbor networks.
122 |
123 | Parameters
124 | ----------
125 | adata
126 | AnnData object of scanpy package.
127 | rad_cutoff_2D
128 | radius cutoff for 2D SNN construction.
129 | rad_cutoff_Zaxis
130 | radius cutoff for 2D SNN construction for consturcting SNNs between adjacent sections.
131 | key_section
132 | The columns names of section_ID in adata.obs.
133 | section_order
134 | The order of sections. The SNNs between adjacent sections are constructed according to this order.
135 |
136 | Returns
137 | -------
138 | The 3D spatial networks are saved in adata.uns['Spatial_Net'].
139 | """
140 | adata.uns['Spatial_Net_2D'] = pd.DataFrame()
141 | adata.uns['Spatial_Net_Zaxis'] = pd.DataFrame()
142 | num_section = np.unique(adata.obs[key_section]).shape[0]
143 | if verbose:
144 | print('Radius used for 2D SNN:', rad_cutoff_2D)
145 | print('Radius used for SNN between sections:', rad_cutoff_Zaxis)
146 | for temp_section in np.unique(adata.obs[key_section]):
147 | if verbose:
148 | print('------Calculating 2D SNN of section ', temp_section)
149 | temp_adata = adata[adata.obs[key_section] == temp_section, ]
150 | Cal_Spatial_Net(
151 | temp_adata, rad_cutoff=rad_cutoff_2D, verbose=False)
152 | temp_adata.uns['Spatial_Net']['SNN'] = temp_section
153 | if verbose:
154 | print('This graph contains %d edges, %d cells.' %
155 | (temp_adata.uns['Spatial_Net'].shape[0], temp_adata.n_obs))
156 | print('%.4f neighbors per cell on average.' %
157 | (temp_adata.uns['Spatial_Net'].shape[0]/temp_adata.n_obs))
158 | adata.uns['Spatial_Net_2D'] = pd.concat(
159 | [adata.uns['Spatial_Net_2D'], temp_adata.uns['Spatial_Net']])
160 | for it in range(num_section-1):
161 | section_1 = section_order[it]
162 | section_2 = section_order[it+1]
163 | if verbose:
164 | print('------Calculating SNN between adjacent section %s and %s.' %
165 | (section_1, section_2))
166 | Z_Net_ID = section_1+'-'+section_2
167 | temp_adata = adata[adata.obs[key_section].isin(
168 | [section_1, section_2]), ]
169 | Cal_Spatial_Net(
170 | temp_adata, rad_cutoff=rad_cutoff_Zaxis, verbose=False)
171 | spot_section_trans = dict(
172 | zip(temp_adata.obs.index, temp_adata.obs[key_section]))
173 | temp_adata.uns['Spatial_Net']['Section_id_1'] = temp_adata.uns['Spatial_Net']['Cell1'].map(
174 | spot_section_trans)
175 | temp_adata.uns['Spatial_Net']['Section_id_2'] = temp_adata.uns['Spatial_Net']['Cell2'].map(
176 | spot_section_trans)
177 | used_edge = temp_adata.uns['Spatial_Net'].apply(
178 | lambda x: x['Section_id_1'] != x['Section_id_2'], axis=1)
179 | temp_adata.uns['Spatial_Net'] = temp_adata.uns['Spatial_Net'].loc[used_edge, ]
180 | temp_adata.uns['Spatial_Net'] = temp_adata.uns['Spatial_Net'].loc[:, [
181 | 'Cell1', 'Cell2', 'Distance']]
182 | temp_adata.uns['Spatial_Net']['SNN'] = Z_Net_ID
183 | if verbose:
184 | print('This graph contains %d edges, %d cells.' %
185 | (temp_adata.uns['Spatial_Net'].shape[0], temp_adata.n_obs))
186 | print('%.4f neighbors per cell on average.' %
187 | (temp_adata.uns['Spatial_Net'].shape[0]/temp_adata.n_obs))
188 | adata.uns['Spatial_Net_Zaxis'] = pd.concat(
189 | [adata.uns['Spatial_Net_Zaxis'], temp_adata.uns['Spatial_Net']])
190 | adata.uns['Spatial_Net'] = pd.concat(
191 | [adata.uns['Spatial_Net_2D'], adata.uns['Spatial_Net_Zaxis']])
192 | if verbose:
193 | print('3D SNN contains %d edges, %d cells.' %
194 | (adata.uns['Spatial_Net'].shape[0], adata.n_obs))
195 | print('%.4f neighbors per cell on average.' %
196 | (adata.uns['Spatial_Net'].shape[0]/adata.n_obs))
197 |
198 | def Stats_Spatial_Net(adata):
199 | import matplotlib.pyplot as plt
200 | Num_edge = adata.uns['Spatial_Net']['Cell1'].shape[0]
201 | Mean_edge = Num_edge/adata.shape[0]
202 | plot_df = pd.value_counts(pd.value_counts(adata.uns['Spatial_Net']['Cell1']))
203 | plot_df = plot_df/adata.shape[0]
204 | fig, ax = plt.subplots(figsize=[3,2])
205 | plt.ylabel('Percentage')
206 | plt.xlabel('')
207 | plt.title('Number of Neighbors (Mean=%.2f)'%Mean_edge)
208 | ax.bar(plot_df.index, plot_df)
209 |
210 | def mclust_R(adata, num_cluster, modelNames='EEE', used_obsm='STAGATE', random_seed=2020):
211 | """\
212 | Clustering using the mclust algorithm.
213 | The parameters are the same as those in the R package mclust.
214 | """
215 |
216 | np.random.seed(random_seed)
217 | import rpy2.robjects as robjects
218 | robjects.r.library("mclust")
219 |
220 | import rpy2.robjects.numpy2ri
221 | rpy2.robjects.numpy2ri.activate()
222 | r_random_seed = robjects.r['set.seed']
223 | r_random_seed(random_seed)
224 | rmclust = robjects.r['Mclust']
225 |
226 | res = rmclust(rpy2.robjects.numpy2ri.numpy2rpy(adata.obsm[used_obsm]), num_cluster, modelNames)
227 | mclust_res = np.array(res[-2])
228 |
229 | adata.obs['mclust'] = mclust_res
230 | adata.obs['mclust'] = adata.obs['mclust'].astype('int')
231 | adata.obs['mclust'] = adata.obs['mclust'].astype('category')
232 | return adata
233 |
--------------------------------------------------------------------------------
/code_for_figures/benchmarking/scripts/modified_existing_methods/utag/segmentation.py:
--------------------------------------------------------------------------------
1 | import typing as tp
2 | import warnings
3 | import os
4 |
5 | import scanpy as sc
6 | import squidpy as sq
7 | import numpy as np
8 | import pandas as pd
9 | import matplotlib.pyplot as plt
10 | from tqdm import tqdm
11 | import anndata
12 | import parmap
13 |
14 | from utag.types import Path, Array, AnnData
15 | from utag.utils import sparse_matrix_dstack
16 |
17 |
18 | def utag_mod(
19 | adata: AnnData,
20 | random_state: int,
21 | channels_to_use: tp.Sequence[str] = None,
22 | slide_key: tp.Optional[str] = "Slide",
23 | save_key: str = "UTAG Label",
24 | filter_by_variance: bool = False,
25 | max_dist: float = 0.1,
26 | normalization_mode: str = "l1_norm",
27 | keep_spatial_connectivity: bool = False,
28 | pca_kwargs: tp.Dict[str, tp.Any] = dict(n_comps=10),
29 | apply_umap: bool = False,
30 | umap_kwargs: tp.Dict[str, tp.Any] = dict(),
31 | apply_clustering: bool = True,
32 | clustering_method: tp.Sequence[str] = ["leiden", "kmeans"],
33 | resolution: float = 0.5,
34 | n_regions: int = 4,
35 | leiden_kwargs: tp.Dict[str, tp.Any] = None,
36 | parallel: bool = True,
37 | processes: int = None,
38 | sample_rate: float = 1.0
39 | ) -> AnnData:
40 | """
41 | Discover tissue architechture in single-cell imaging data
42 | by combining phenotypes and positional information of cells.
43 |
44 | Parameters
45 | ----------
46 | adata: AnnData
47 | AnnData object with spatial positioning of cells in obsm 'spatial' slot.
48 | channels_to_use: Optional[Sequence[str]]
49 | An optional sequence of strings used to subset variables to use.
50 | Default (None) is to use all variables.
51 | max_dist: float
52 | Maximum distance to cut edges within a graph.
53 | Should be adjusted depending on resolution of images.
54 | For imaging mass cytometry, where resolution is 1um, 20 often gives good results.
55 | Default is 20.
56 | slide_key: {str, None}
57 | Key of adata.obs containing information on the batch structure of the data.
58 | In general, for image data this will often be a variable indicating the image
59 | so image-specific effects are removed from data.
60 | Default is "Slide".
61 | save_key: str
62 | Key to be added to adata object holding the UTAG clusters.
63 | Depending on the values of `clustering_method` and `resolutions`,
64 | the final keys will be of the form: {save_key}_{method}_{resolution}".
65 | Default is "UTAG Label".
66 | filter_by_variance: bool
67 | Whether to filter vairiables by variance.
68 | Default is False, which keeps all variables.
69 | max_dist: float
70 | Recommended values are between 20 to 50 depending on magnification.
71 | Default is 20.
72 | normalization_mode: str
73 | Method to normalize adjacency matrix.
74 | Default is "l1_norm", any other value will not use normalization.
75 | keep_spatial_connectivity: bool
76 | Whether to keep sparse matrices of spatial connectivity and distance in the obsp attribute of the
77 | resulting anndata object. This could be useful in downstream applications.
78 | Default is not to (False).
79 | pca_kwargs: Dict[str, Any]
80 | Keyword arguments to be passed to scanpy.pp.pca for dimensionality reduction after message passing.
81 | Default is to pass n_comps=10, which uses 10 Principal Components.
82 | apply_umap: bool
83 | Whether to build a UMAP representation after message passing.
84 | Default is False.
85 | umap_kwargs: Dict[str, Any]
86 | Keyword arguments to be passed to scanpy.tl.umap for dimensionality reduction after message passing.
87 | Default is 10.0.
88 | apply_clustering: bool
89 | Whether to cluster the message passed matrix.
90 | Default is True.
91 | resolution: float
92 | What resolution should the methods in `clustering_method` be run at.
93 | leiden_kwargs: dict[str, Any]
94 | Keyword arguments to pass to scanpy.tl.leiden.
95 | parallel: bool
96 | Whether to run message passing part of algorithm in parallel.
97 | Will accelerate the process but consume more memory.
98 | Default is True.
99 | processes: int
100 | Number of processes to use in parallel.
101 | Default is to use all available (-1).
102 |
103 | Returns
104 | -------
105 | adata: AnnData
106 | AnnData object with UTAG domain predictions for each cell in adata.obs, column `save_key`.
107 | """
108 | ad = adata.copy()
109 | np.random.seed(random_state)
110 |
111 | if channels_to_use:
112 | ad = ad[:, channels_to_use]
113 |
114 | if filter_by_variance:
115 | ad = low_variance_filter(ad)
116 |
117 | if isinstance(clustering_method, list):
118 | clustering_method = [m.upper() for m in clustering_method]
119 | elif isinstance(clustering_method, str):
120 | clustering_method = [clustering_method.upper()]
121 | else:
122 | print(
123 | "Invalid Clustering Method. Clustering Method Should Either be a string or a list"
124 | )
125 | return
126 | assert all(m in ["LEIDEN", "PARC", "KMEANS"] for m in clustering_method)
127 |
128 | if "PARC" in clustering_method:
129 | from parc import PARC # early fail if not available
130 | if "KMEANS" in clustering_method:
131 | from sklearn.cluster import KMeans
132 |
133 | print("Applying UTAG Algorithm...", flush=True)
134 | if slide_key:
135 | ads = [
136 | ad[ad.obs[slide_key] == slide].copy() for slide in ad.obs[slide_key].unique()
137 | ]
138 | ad_list = parmap.map(
139 | _parallel_message_pass,
140 | ads,
141 | radius=max_dist,
142 |
143 | coord_type="generic",
144 | set_diag=True,
145 | mode=normalization_mode,
146 | pm_pbar=True,
147 | pm_parallel=parallel,
148 | pm_processes=processes,
149 | )
150 | ad_result = anndata.concat(ad_list)
151 | if keep_spatial_connectivity:
152 | ad_result.obsp["spatial_connectivities"] = sparse_matrix_dstack(
153 | [x.obsp["spatial_connectivities"] for x in ad_list]
154 | )
155 | ad_result.obsp["spatial_distances"] = sparse_matrix_dstack(
156 | [x.obsp["spatial_distances"] for x in ad_list]
157 | )
158 | else:
159 | sq.gr.spatial_neighbors(ad, radius=max_dist, coord_type="generic", set_diag=True)
160 | ad_result = custom_message_passing(ad, mode=normalization_mode, sample_rate=sample_rate)
161 |
162 | if apply_clustering:
163 | if "n_comps" in pca_kwargs:
164 | if pca_kwargs["n_comps"] > ad_result.shape[1]:
165 | pca_kwargs["n_comps"] = ad_result.shape[1] - 1
166 | print(
167 | f"Overwriding provided number of PCA dimensions to match number of features: {pca_kwargs['n_comps']}"
168 | )
169 | pca_kwargs["n_comps"] = int(pca_kwargs["n_comps"])
170 | sc.tl.pca(ad_result, **pca_kwargs)
171 | sc.pp.neighbors(ad_result)
172 |
173 | if apply_umap:
174 | print("Running UMAP on Input Dataset...", flush=True)
175 | sc.tl.umap(ad_result, **umap_kwargs)
176 |
177 | res_key1 = "leiden"
178 | res_key3 = "kmeans"
179 |
180 | if "LEIDEN" in clustering_method:
181 |
182 | def binary_search_leiden(adata, leiden_res, n_regions, kwargs):
183 | sc.tl.leiden(adata, resolution=leiden_res)
184 | n_clusters = len(adata.obs['leiden'].unique())
185 | lo, hi = 0, 5
186 | while n_clusters != n_regions:
187 | if n_clusters < n_regions:
188 | lo = leiden_res
189 | leiden_res = (leiden_res+hi)/2
190 | elif n_clusters > n_regions:
191 | hi = leiden_res
192 | leiden_res = (leiden_res+lo)/2
193 | sc.tl.leiden(adata, resolution=leiden_res)
194 | n_clusters = len(adata.obs['leiden'].unique())
195 | print(leiden_res, n_clusters, flush=True)
196 |
197 | print(f"Applying Leiden Clustering...", flush=True)
198 | kwargs = dict()
199 | kwargs.update(leiden_kwargs or {})
200 |
201 | binary_search_leiden(ad_result, resolution, n_regions, kwargs)
202 |
203 | add_probabilities_to_centroid(ad_result, res_key1)
204 |
205 | if "KMEANS" in clustering_method:
206 | print(f"Applying K-means Clustering...", flush=True)
207 | kmeans = KMeans(n_clusters=n_regions, random_state=random_state).fit(ad_result.obsm["X_pca"])
208 | ad_result.obs[res_key3] = pd.Categorical(kmeans.labels_.astype(str))
209 | add_probabilities_to_centroid(ad_result, res_key3)
210 |
211 | return ad_result
212 |
213 |
214 | def _parallel_message_pass(
215 | ad: AnnData,
216 | radius: float,
217 | coord_type: str,
218 | set_diag: bool,
219 | mode: str,
220 | sample_rate: float,
221 | ):
222 | sq.gr.spatial_neighbors(ad, radius=radius, coord_type=coord_type, set_diag=set_diag)
223 | ad = custom_message_passing(ad, mode=mode, sample_rate=sample_rate)
224 | return ad
225 |
226 |
227 | def custom_message_passing(adata: AnnData, mode: str = "l1_norm", sample_rate=1) -> AnnData:
228 | from scipy.linalg import sqrtm
229 | from scipy.sparse import csr_matrix
230 |
231 | if sample_rate == 0:
232 | adata.obsp['spatial_connectivities'] = np.eye(adata.shape[0])
233 | #print(adata.obsp['spatial_connectivities'], flush=0)
234 | elif sample_rate < 1:
235 | A = adata.obsp['spatial_connectivities']
236 | n_cells = A.shape[0]
237 | A_subsampled = np.zeros((n_cells,n_cells))
238 |
239 | for i in range(n_cells):
240 | nbr_idxs = A[i].nonzero()[1]
241 | n_samples = int(len(nbr_idxs) * sample_rate)
242 | nbr_idxs_subsampled = np.random.choice(nbr_idxs, size=n_samples, replace=False)
243 | for j in nbr_idxs_subsampled:
244 | A_subsampled[i,j] = 1
245 | print(len(nbr_idxs), flush=True)
246 | print(n_samples, flush=True)
247 | adata.obsp['spatial_connectivities'] = A_subsampled
248 |
249 | adata.obsp['spatial_connectivities'] = csr_matrix(adata.obsp['spatial_connectivities'])
250 |
251 | if mode == "l1_norm":
252 | A = adata.obsp["spatial_connectivities"]
253 | A_mod = np.asarray(A + np.eye(A.shape[0]))
254 | from sklearn.preprocessing import normalize
255 | affinity = normalize(A_mod, axis=1, norm="l1")
256 | else:
257 | # Plain A_mod multiplication
258 | A = adata.obsp["spatial_connectivities"]
259 | affinity = A
260 |
261 | adata.obsm['X_smoothed'] = affinity @ adata.X
262 | return adata
263 |
264 |
265 | def low_variance_filter(adata: AnnData) -> AnnData:
266 | return adata[:, adata.var["std"] > adata.var["std"].median()]
267 |
268 |
269 | def add_probabilities_to_centroid(
270 | adata: AnnData, col: str, name_to_output: str = None
271 | ) -> AnnData:
272 | from utag.utils import z_score
273 | from scipy.special import softmax
274 |
275 | if name_to_output is None:
276 | name_to_output = col + "_probabilities"
277 |
278 | mean = z_score(adata.to_df()).groupby(adata.obs[col]).mean()
279 | probs = softmax(adata.to_df() @ mean.T, axis=1)
280 | adata.obsm[name_to_output] = probs
281 | return adata
282 |
283 |
284 | def evaluate_performance(
285 | adata: AnnData,
286 | batch_key: str = "Slide",
287 | truth_key: str = "DOM_argmax",
288 | pred_key: str = "cluster",
289 | method: str = "rand",
290 | ) -> Array:
291 | assert method in ["rand", "homogeneity"]
292 | from sklearn.metrics import rand_score, homogeneity_score
293 |
294 | score_list = []
295 | for key in adata.obs[batch_key].unique():
296 | batch = adata[adata.obs[batch_key] == key]
297 | if method == "rand":
298 | score = rand_score(batch.obs[truth_key], batch.obs[pred_key])
299 | elif method == "homogeneity":
300 | score = homogeneity_score(batch.obs[truth_key], batch.obs[pred_key])
301 | score_list.append(score)
302 | return score_list
303 |
--------------------------------------------------------------------------------
/code_for_figures/benchmarking/scripts/radius.py:
--------------------------------------------------------------------------------
1 | import logging
2 | import os
3 | import argparse
4 |
5 | import scanpy as sc
6 | import numpy as np
7 | from sklearn.neighbors import NearestNeighbors
8 | from sklearn.decomposition import PCA
9 | import scipy as sp
10 | from sklearn.cluster import KMeans
11 | from sklearn.metrics import adjusted_rand_score
12 |
13 |
14 | def smooth(
15 | adata,
16 | radius,
17 | subsample_rate,
18 | ):
19 |
20 | # Get neighbor info
21 | nbrs = NearestNeighbors(radius=radius).fit(adata.obsm['spatial'])
22 | A = nbrs.radius_neighbors_graph()
23 | adata.obsp['spatial_connectivities'] = A.copy()
24 |
25 | # Subsample
26 | if subsample_rate:
27 | adata.obsp['spatial_connectivities_subsampled'] = A.copy()
28 | for i in range(len(adata)):
29 | nbr_idxs = adata.obsp['spatial_connectivities'][i].nonzero()[1]
30 | idxs_to_drop = np.random.choice(
31 | nbr_idxs,
32 | size=int(len(nbr_idxs)*(1-subsample_rate)),
33 | replace=False,
34 | )
35 | for j in idxs_to_drop:
36 | adata.obsp['spatial_connectivities_subsampled'][i,j] = 0
37 | adata.obsp['spatial_connectivities_subsampled'].eliminate_zeros()
38 | else:
39 | adata.obsp['spatial_connectivities_subsampled'] = np.eye(adata.shape[0])
40 |
41 | # Smooth
42 | adata.obsm['X_smoothed'] = adata.obsp['spatial_connectivities_subsampled'] @ adata.X
43 |
44 |
45 | def binary_search_leiden(
46 | adata,
47 | leiden_res,
48 | n_regions,
49 | jitter=0.1
50 | ):
51 | sc.tl.leiden(adata, resolution=leiden_res, neighbors_key='smoothed')
52 | n_clusters = len(adata.obs['leiden'].unique())
53 | lo, hi = 0, 5
54 | iters = 0
55 | while n_clusters != n_regions:
56 | if n_clusters < n_regions:
57 | lo = leiden_res
58 | leiden_res = (leiden_res+hi)/2
59 | elif n_clusters > n_regions:
60 | hi = leiden_res
61 | leiden_res = (leiden_res+lo)/2
62 | iters += 1
63 | if iters > 10:
64 | leiden_res += np.random.choice([-1,1]) * jitter
65 | hi += jitter
66 | lo -= max(0,jitter)
67 | sc.tl.leiden(adata, resolution=leiden_res, neighbors_key='smoothed')
68 | n_clusters = len(adata.obs['leiden'].unique())
69 | print(leiden_res, n_clusters, flush=True)
70 | print()
71 |
72 |
73 | def cluster(
74 | adata,
75 | n_pcs,
76 | k_latent,
77 | n_regions,
78 | leiden_res,
79 | ):
80 |
81 | # Calculate latent representation
82 | pca = PCA(n_components=n_pcs)
83 | adata.obsm['X_smoothed_pca'] = pca.fit_transform(adata.obsm['X_smoothed'])
84 |
85 | # Find latent neighbors
86 | nbrs = NearestNeighbors(n_neighbors=k_latent).fit(adata.obsm['X_smoothed_pca'])
87 | adata.obsp['smoothed_connectivities'] = nbrs.kneighbors_graph(mode='connectivity')
88 | adata.obsp['smoothed_distances'] = nbrs.kneighbors_graph(mode='distance')
89 |
90 | # Add metadata expected by Scanpy's Leiden and UMAP
91 | adata.uns['smoothed'] = {'connectivities_key': 'smoothed_connectivities',
92 | 'distances_key': 'smoothed_distances',
93 | 'params': {
94 | 'n_neighbors': k_latent,
95 | 'method': 'umap',
96 | 'random_state': 0,
97 | 'metric': 'euclidean',
98 | 'use_rep': 'X_smoothed_pca'
99 | }
100 | }
101 |
102 | # Perform k-means clustering
103 | kmeans = KMeans(n_clusters=n_regions, n_init=10)
104 | kmeans.fit(adata.obsm['X_smoothed_pca'])
105 | adata.obs['kmeans'] = kmeans.labels_.astype(str)
106 |
107 | # Perform Leiden clustering
108 | binary_search_leiden(adata, leiden_res, n_regions)
109 |
110 |
111 | def quantify(adata, n_regions):
112 |
113 | # Quantify spatial reconstruction
114 | Cp = adata.obsp['spatial_connectivities']
115 | Cl = adata.obsp['smoothed_connectivities']
116 | recon_score = Cp.multiply(Cl).count_nonzero() / (Cp+Cl).count_nonzero()
117 |
118 | # Quantify k-means accuracy
119 | kmeans_ari = adjusted_rand_score(adata.obs['region_true'], adata.obs['kmeans'])
120 |
121 | # Quantify Leiden accuracy
122 | leiden_ari = adjusted_rand_score(adata.obs['region_true'], adata.obs['leiden'])
123 |
124 | return recon_score, kmeans_ari, leiden_ari
125 |
126 |
127 | def main(
128 | read_path,
129 | sample_rate,
130 | radius,
131 | k_latent,
132 | n_pcs,
133 | leiden_res,
134 | write_path,
135 | random_seed,
136 | decimals,
137 | ):
138 |
139 | # Initialize logger
140 | logger = logging.getLogger('Radius')
141 | logger.setLevel(logging.INFO)
142 | formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
143 | ch = logging.StreamHandler()
144 | ch.setLevel(logging.INFO)
145 | ch.setFormatter(formatter)
146 | logger.addHandler(ch)
147 |
148 | # Set random seed
149 | np.random.seed(random_seed)
150 |
151 | # Load data
152 | logger.info(f'Loading data from {read_path}')
153 | adata = sc.read_h5ad(read_path)
154 | n_regions = len(adata.obs['region_true'].unique())
155 |
156 | # Smooth
157 | logger.info('Smoothing')
158 | logger.info(f'\tsample_rate={sample_rate}')
159 | logger.info(f'\trandom_seed={random_seed}')
160 | smooth(adata, radius, sample_rate)
161 |
162 | # Cluster
163 | logger.info('Clustering')
164 | cluster(adata, n_pcs, k_latent, n_regions, leiden_res)
165 |
166 | # Quantify results
167 | logger.info('Quantifying results')
168 | recon_score, kmeans_ari, leiden_ari = quantify(adata, n_regions)
169 |
170 | # Write results to disk
171 | os.makedirs(write_path, exist_ok=True)
172 | results = f'{np.round(recon_score, decimals=decimals)}_' + \
173 | f'{np.round(kmeans_ari, decimals=decimals)}_' + \
174 | f'{np.round(leiden_ari, decimals=decimals)}'
175 | filename_txt = f'{random_seed}_{results}.txt'
176 | write_path_txt = os.path.join(write_path, filename_txt)
177 | logger.info(f'Writing results to {write_path_txt}')
178 | f = open(write_path_txt, 'a')
179 | f.close()
180 |
181 | # Write example AnnData to disk
182 | if random_seed == 0:
183 | filename_adata = f'adata_{sample_rate}.h5ad'
184 | write_path_adata = os.path.join(write_path, filename_adata)
185 | logger.info(f'Saving AnnData to {write_path_adata}')
186 | adata.write(write_path_adata)
187 |
188 | logger.info('Done')
189 |
190 |
191 | if __name__=='__main__':
192 |
193 | parser = argparse.ArgumentParser()
194 | parser.add_argument('--read_path', type=str)
195 | parser.add_argument('--sample_rate', type=float, default=None)
196 | parser.add_argument('--radius', type=float, default=None)
197 | parser.add_argument('--k_latent', type=int, default=50)
198 | parser.add_argument('--n_pcs', type=int)
199 | parser.add_argument('--leiden_res', type=float)
200 | parser.add_argument('--write_path', type=str)
201 | parser.add_argument('--random_seed', type=int)
202 | parser.add_argument('--decimals', type=int, default=5)
203 | args = parser.parse_args()
204 |
205 | main(
206 | args.read_path,
207 | args.sample_rate,
208 | args.radius,
209 | args.k_latent,
210 | args.n_pcs,
211 | args.leiden_res,
212 | args.write_path,
213 | args.random_seed,
214 | args.decimals,
215 | )
--------------------------------------------------------------------------------
/code_for_figures/benchmarking/scripts/simulation/performance_simulation.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 |
3 | tissue=simulation
4 |
5 | simulation_methods=(knn radius utag stagate graphst)
6 | simulation_jobids=(42429477 42429759 42429768 42430818 42430894)
7 | n_methods="${#simulation_methods[@]}"
8 |
9 | # Write job resource metrics to disk
10 | for i in $(seq 0 $((n_methods-1))); do
11 | method=${simulation_methods[i]}
12 | jobid=${simulation_jobids[i]}
13 | write_path=/stanley/WangLab/kamal/data/projects/spin/reviews/results/${tissue}/${method}/
14 | performance=${write_path}performance_${tissue}_${method}_${jobid}.txt
15 | echo "Writing $performance"
16 | touch $performance
17 | nonsub_tasks=($(seq 11 11 110)) # only compare using non-subsampling runs
18 | for task in ${nonsub_tasks[@]}; do
19 | qacct -j $jobid -t $task >> $performance;
20 | done;
21 | done
22 | echo "Done"
--------------------------------------------------------------------------------
/code_for_figures/benchmarking/scripts/simulation/simulation_graphst.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 |
3 | #$ -l h_vmem=16G
4 | #$ -l h_rt=00:10:00
5 | #$ -o /stanley/WangLab/kamal/outputs/spin/reviews/simulation/graphst/
6 | #$ -j y
7 | #$ -t 1-110
8 |
9 | source /broad/software/scripts/useuse
10 | reuse Anaconda3
11 | source activate /stanley/WangLab/kamal/envs/graphst/
12 |
13 | sample_rates=($(seq 0 0.1 1))
14 | random_seeds=($(seq 0 1 10))
15 | # random_seeds=($(seq 0 0)) # test using a single random seed
16 |
17 | n_sample_rates=${#sample_rates[@]}
18 | sample_rate=${sample_rates[($((SGE_TASK_ID-1))%$n_sample_rates)]}
19 | random_seed=${random_seeds[($((SGE_TASK_ID-1))/$n_sample_rates)]}
20 |
21 | k_physical=50
22 | k_latent=15
23 |
24 | python /stanley/WangLab/kamal/code/projects/spin/reviews/scripts/graphst_.py \
25 | --read_path /stanley/WangLab/kamal/data/projects/spin/reviews/simulation/adata.h5ad \
26 | --sample_rate $sample_rate \
27 | --k_physical $k_physical \
28 | --k_latent $k_latent \
29 | --leiden_res "0.2" \
30 | --write_path /stanley/WangLab/kamal/data/projects/spin/reviews/results/simulation/graphst/reconstructions_${sample_rate}_${k_physical}physical_${k_latent}latent/ \
31 | --random_seed $random_seed \
32 | --n_epochs 50 \
--------------------------------------------------------------------------------
/code_for_figures/benchmarking/scripts/simulation/simulation_knn.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 |
3 | #$ -l h_vmem=8G
4 | #$ -l h_rt=00:30:00
5 | #$ -o /stanley/WangLab/kamal/outputs/spin/reviews/simulation/knn/
6 | #$ -j y
7 | #$ -t 1-110
8 |
9 | source /broad/software/scripts/useuse
10 | reuse Anaconda3
11 | source activate /stanley/WangLab/kamal/envs/xax
12 |
13 | sample_rates=($(seq 0 0.1 1))
14 | random_seeds=($(seq 0 1 10))
15 | # random_seeds=($(seq 0 0)) # test using a single random seed
16 |
17 | n_sample_rates=${#sample_rates[@]}
18 | sample_rate=${sample_rates[($((SGE_TASK_ID-1))%$n_sample_rates)]}
19 | random_seed=${random_seeds[($((SGE_TASK_ID-1))/$n_sample_rates)]}
20 |
21 | k_physical=50
22 | k_latent=15
23 |
24 | python /stanley/WangLab/kamal/code/projects/spin/reviews/scripts/knn.py \
25 | --read_path /stanley/WangLab/kamal/data/projects/spin/reviews/simulation/adata.h5ad \
26 | --sample_rate $sample_rate \
27 | --k_physical $k_physical \
28 | --k_latent $k_latent \
29 | --n_pcs 50 \
30 | --leiden_res "0.2" \
31 | --write_path /stanley/WangLab/kamal/data/projects/spin/reviews/results/simulation/knn/reconstructions_${sample_rate}_${k_physical}physical_${k_latent}latent/ \
32 | --random_seed $random_seed
--------------------------------------------------------------------------------
/code_for_figures/benchmarking/scripts/simulation/simulation_radius.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 |
3 | #$ -l h_vmem=8G
4 | #$ -l h_rt=00:30:00
5 | #$ -o /stanley/WangLab/kamal/outputs/spin/reviews/simulation/radius/
6 | #$ -j y
7 | #$ -t 1-110
8 |
9 | source /broad/software/scripts/useuse
10 | reuse Anaconda3
11 | source activate /stanley/WangLab/kamal/envs/xax
12 |
13 | sample_rates=($(seq 0 0.1 1))
14 | random_seeds=($(seq 0 1 10))
15 | # random_seeds=($(seq 0 0)) # test using a single random seed
16 |
17 | n_sample_rates=${#sample_rates[@]}
18 | sample_rate=${sample_rates[($((SGE_TASK_ID-1))%$n_sample_rates)]}
19 | random_seed=${random_seeds[($((SGE_TASK_ID-1))/$n_sample_rates)]}
20 |
21 | radius=0.1
22 | k_latent=15
23 |
24 | python /stanley/WangLab/kamal/code/projects/spin/reviews/scripts/radius.py \
25 | --read_path /stanley/WangLab/kamal/data/projects/spin/reviews/simulation/adata.h5ad \
26 | --sample_rate $sample_rate \
27 | --radius $radius \
28 | --k_latent $k_latent \
29 | --n_pcs 50 \
30 | --leiden_res "0.2" \
31 | --write_path /stanley/WangLab/kamal/data/projects/spin/reviews/results/simulation/radius/reconstructions_${sample_rate}_${radius}radius_${k_latent}latent/ \
32 | --random_seed $random_seed
--------------------------------------------------------------------------------
/code_for_figures/benchmarking/scripts/simulation/simulation_stagate.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 |
3 | #$ -l h_vmem=16G
4 | #$ -l h_rt=00:10:00
5 | #$ -o /stanley/WangLab/kamal/outputs/spin/reviews/simulation/stagate/
6 | #$ -j y
7 | #$ -t 1-110
8 |
9 | source /broad/software/scripts/useuse
10 | reuse Anaconda3
11 | source activate /stanley/WangLab/kamal/envs/stagate_pyg/
12 |
13 | sample_rates=($(seq 0 0.1 1))
14 | random_seeds=($(seq 0 1 10))
15 | # random_seeds=($(seq 0 0)) # test using a single random seed
16 |
17 | n_sample_rates=${#sample_rates[@]}
18 | sample_rate=${sample_rates[($((SGE_TASK_ID-1))%$n_sample_rates)]}
19 | random_seed=${random_seeds[($((SGE_TASK_ID-1))/$n_sample_rates)]}
20 |
21 | k_physical=50
22 | k_latent=15
23 |
24 | python /stanley/WangLab/kamal/code/projects/spin/reviews/scripts/stagate_.py \
25 | --read_path /stanley/WangLab/kamal/data/projects/spin/reviews/simulation/adata.h5ad \
26 | --sample_rate $sample_rate \
27 | --k_physical $k_physical \
28 | --k_latent $k_latent \
29 | --leiden_res "0.2" \
30 | --write_path /stanley/WangLab/kamal/data/projects/spin/reviews/results/simulation/stagate/reconstructions_${sample_rate}_${k_physical}physical_${k_latent}latent/ \
31 | --random_seed $random_seed
--------------------------------------------------------------------------------
/code_for_figures/benchmarking/scripts/simulation/simulation_utag.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 |
3 | #$ -l h_vmem=16G
4 | #$ -l h_rt=00:10:00
5 | #$ -o /stanley/WangLab/kamal/outputs/spin/reviews/simulation/utag/
6 | #$ -j y
7 | #$ -t 1-110
8 |
9 | source /broad/software/scripts/useuse
10 | reuse Anaconda3
11 | source activate /stanley/WangLab/bridget/envs/utag/
12 |
13 | sample_rates=($(seq 0 0.1 1))
14 | random_seeds=($(seq 0 1 10))
15 | # random_seeds=($(seq 0 0)) # test using a single random seed
16 |
17 | n_sample_rates=${#sample_rates[@]}
18 | sample_rate=${sample_rates[($((SGE_TASK_ID-1))%$n_sample_rates)]}
19 | random_seed=${random_seeds[($((SGE_TASK_ID-1))/$n_sample_rates)]}
20 |
21 | radius=0.1
22 | k_latent=15
23 |
24 | python /stanley/WangLab/kamal/code/projects/spin/reviews/scripts/utag_.py \
25 | --read_path /stanley/WangLab/kamal/data/projects/spin/reviews/simulation/adata.h5ad \
26 | --sample_rate $sample_rate \
27 | --radius $radius \
28 | --k_latent $k_latent \
29 | --n_pcs 50 \
30 | --leiden_res "0.2" \
31 | --write_path /stanley/WangLab/kamal/data/projects/spin/reviews/results/simulation/utag/reconstructions_${sample_rate}_${radius}radius_${k_latent}latent/ \
32 | --random_seed $random_seed
--------------------------------------------------------------------------------
/code_for_figures/benchmarking/scripts/stagate_.py:
--------------------------------------------------------------------------------
1 | import logging
2 | import os
3 | import argparse
4 |
5 | import STAGATE_pyG_sub
6 | import scanpy as sc
7 | import numpy as np
8 | from sklearn.neighbors import NearestNeighbors
9 | from sklearn.decomposition import PCA
10 | import scipy as sp
11 | from sklearn.cluster import KMeans
12 | from sklearn.metrics import adjusted_rand_score
13 |
14 |
15 | def smooth(
16 | adata,
17 | k_physical,
18 | sample_rate,
19 | n_epochs,
20 | alpha,
21 | random_seed,
22 | ):
23 |
24 | # Get neighbors
25 | STAGATE_pyG_sub.Cal_Spatial_Net(
26 | adata,
27 | model='KNN',
28 | k_cutoff=k_physical,
29 | sample_rate=sample_rate,
30 | )
31 |
32 | # Train model
33 | adata = STAGATE_pyG_sub.train_STAGATE(
34 | adata,
35 | n_epochs=n_epochs,
36 | key_added='stagate',
37 | alpha=alpha,
38 | random_seed=random_seed,
39 | )
40 |
41 | return adata
42 |
43 |
44 | def binary_search_leiden(
45 | adata,
46 | leiden_res,
47 | n_regions,
48 | jitter=0.1
49 | ):
50 | sc.tl.leiden(adata, resolution=leiden_res, neighbors_key='smoothed')
51 | n_clusters = len(adata.obs['leiden'].unique())
52 | lo, hi = 0, 5
53 | iters = 0
54 | while n_clusters != n_regions:
55 | if n_clusters < n_regions:
56 | lo = leiden_res
57 | leiden_res = (leiden_res+hi)/2
58 | elif n_clusters > n_regions:
59 | hi = leiden_res
60 | leiden_res = (leiden_res+lo)/2
61 | iters += 1
62 | if iters > 10:
63 | leiden_res += np.random.choice([-1,1]) * jitter
64 | hi += jitter
65 | lo -= max(0,jitter)
66 | sc.tl.leiden(adata, resolution=leiden_res, neighbors_key='smoothed')
67 | n_clusters = len(adata.obs['leiden'].unique())
68 | print(leiden_res, n_clusters, flush=True)
69 | print()
70 |
71 |
72 | def cluster(
73 | adata,
74 | n_pcs,
75 | k_latent,
76 | n_regions,
77 | leiden_res,
78 | ):
79 |
80 | # Find latent neighbors
81 | nbrs = NearestNeighbors(n_neighbors=k_latent).fit(adata.obsm['stagate'])
82 | adata.obsp['smoothed_connectivities'] = nbrs.kneighbors_graph(mode='connectivity')
83 | adata.obsp['smoothed_distances'] = nbrs.kneighbors_graph(mode='distance')
84 |
85 | # Add metadata expected by Scanpy's Leiden and UMAP
86 | adata.uns['smoothed'] = {'connectivities_key': 'smoothed_connectivities',
87 | 'distances_key': 'smoothed_distances',
88 | 'params': {
89 | 'n_neighbors': k_latent,
90 | 'method': 'umap',
91 | 'random_state': 0,
92 | 'metric': 'euclidean',
93 | 'use_rep': 'stagate'
94 | }
95 | }
96 |
97 | # Perform k-means clustering
98 | kmeans = KMeans(n_clusters=n_regions, n_init=10)
99 | kmeans.fit(adata.obsm['stagate'])
100 | adata.obs['kmeans'] = kmeans.labels_.astype(str)
101 |
102 | # Perform Leiden clustering
103 | binary_search_leiden(adata, leiden_res, n_regions)
104 |
105 |
106 | def quantify(adata, n_regions):
107 |
108 | # Quantify spatial reconstruction
109 | Cp = adata.obsp['spatial_connectivities']
110 | Cl = adata.obsp['smoothed_connectivities']
111 | recon_score = Cp.multiply(Cl).count_nonzero() / (Cp+Cl).count_nonzero()
112 |
113 | # Quantify k-means accuracy
114 | kmeans_ari = adjusted_rand_score(adata.obs['region_true'], adata.obs['kmeans'])
115 |
116 | # Quantify Leiden accuracy
117 | leiden_ari = adjusted_rand_score(adata.obs['region_true'], adata.obs['leiden'])
118 |
119 | return recon_score, kmeans_ari, leiden_ari
120 |
121 |
122 | def main(
123 | read_path,
124 | sample_rate,
125 | k_physical,
126 | k_latent,
127 | n_pcs,
128 | leiden_res,
129 | write_path,
130 | random_seed,
131 | decimals,
132 | n_epochs,
133 | alpha,
134 | ):
135 |
136 | # Initialize logger
137 | logger = logging.getLogger('STAGATE')
138 | logger.setLevel(logging.INFO)
139 | formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
140 | ch = logging.StreamHandler()
141 | ch.setLevel(logging.INFO)
142 | ch.setFormatter(formatter)
143 | logger.addHandler(ch)
144 |
145 | # Set random seed
146 | np.random.seed(random_seed)
147 |
148 | # Load data
149 | logger.info(f'Loading data from {read_path}')
150 | adata = sc.read_h5ad(read_path)
151 | n_regions = len(adata.obs['region_true'].unique())
152 |
153 | # Smooth
154 | logger.info('Smoothing')
155 | logger.info(f'\tsample_rate={sample_rate}')
156 | logger.info(f'\trandom_seed={random_seed}')
157 | adata = smooth(adata, k_physical, sample_rate, n_epochs, alpha, random_seed)
158 |
159 | # Cluster
160 | logger.info('Clustering')
161 | cluster(adata, n_pcs, k_latent, n_regions, leiden_res)
162 |
163 | # Quantify results
164 | logger.info('Quantifying results')
165 | recon_score, kmeans_ari, leiden_ari = quantify(adata, n_regions)
166 |
167 | # Write results to disk
168 | os.makedirs(write_path, exist_ok=True)
169 | results = f'{np.round(recon_score, decimals=decimals)}_' + \
170 | f'{np.round(kmeans_ari, decimals=decimals)}_' + \
171 | f'{np.round(leiden_ari, decimals=decimals)}'
172 | filename_txt = f'{random_seed}_{results}.txt'
173 | write_path_txt = os.path.join(write_path, filename_txt)
174 | logger.info(f'Writing results to {write_path_txt}')
175 | f = open(write_path_txt, 'a')
176 | f.close()
177 |
178 | # Write example AnnData to disk
179 | if random_seed == 0:
180 | filename_adata = f'adata_{sample_rate}.h5ad'
181 | write_path_adata = os.path.join(write_path, filename_adata)
182 | logger.info(f'Saving AnnData to {write_path_adata}')
183 | adata.write(write_path_adata)
184 |
185 | logger.info('Done')
186 |
187 |
188 | if __name__=='__main__':
189 |
190 | parser = argparse.ArgumentParser()
191 | parser.add_argument('--read_path', type=str)
192 | parser.add_argument('--sample_rate', type=float, default=None)
193 | parser.add_argument('--k_physical', type=int, default=50)
194 | parser.add_argument('--k_latent', type=int, default=15)
195 | parser.add_argument('--n_pcs', type=int)
196 | parser.add_argument('--leiden_res', type=float)
197 | parser.add_argument('--write_path', type=str)
198 | parser.add_argument('--random_seed', type=int)
199 | parser.add_argument('--decimals', type=int, default=5)
200 | parser.add_argument('--n_epochs', type=int, default=50)
201 | parser.add_argument('--alpha', type=float, default=0)
202 | args = parser.parse_args()
203 |
204 | main(
205 | args.read_path,
206 | args.sample_rate,
207 | args.k_physical,
208 | args.k_latent,
209 | args.n_pcs,
210 | args.leiden_res,
211 | args.write_path,
212 | args.random_seed,
213 | args.decimals,
214 | args.n_epochs,
215 | args.alpha
216 | )
--------------------------------------------------------------------------------
/code_for_figures/benchmarking/scripts/utag_.py:
--------------------------------------------------------------------------------
1 | import logging
2 | import os
3 | import argparse
4 |
5 | from utag.segmentation import utag_mod
6 | import scanpy as sc
7 | import numpy as np
8 | from sklearn.neighbors import NearestNeighbors
9 | from sklearn.decomposition import PCA
10 | import scipy as sp
11 | from sklearn.cluster import KMeans
12 | from sklearn.metrics import adjusted_rand_score
13 |
14 |
15 | def smooth(
16 | adata,
17 | radius,
18 | sample_rate,
19 | random_seed,
20 | ):
21 |
22 | adata = utag_mod(
23 | adata=adata,
24 | max_dist=radius,
25 | sample_rate=sample_rate,
26 | random_state=random_seed,
27 | slide_key=None,
28 | apply_clustering=False,
29 | apply_umap=False,
30 | )
31 |
32 | return adata
33 |
34 |
35 | def binary_search_leiden(
36 | adata,
37 | leiden_res,
38 | n_regions,
39 | jitter=0.1
40 | ):
41 | sc.tl.leiden(adata, resolution=leiden_res, neighbors_key='smoothed')
42 | n_clusters = len(adata.obs['leiden'].unique())
43 | lo, hi = 0, 5
44 | iters = 0
45 | while n_clusters != n_regions:
46 | if n_clusters < n_regions:
47 | lo = leiden_res
48 | leiden_res = (leiden_res+hi)/2
49 | elif n_clusters > n_regions:
50 | hi = leiden_res
51 | leiden_res = (leiden_res+lo)/2
52 | iters += 1
53 | if iters > 10:
54 | leiden_res += np.random.choice([-1,1]) * jitter
55 | hi += jitter
56 | lo -= max(0,jitter)
57 | sc.tl.leiden(adata, resolution=leiden_res, neighbors_key='smoothed')
58 | n_clusters = len(adata.obs['leiden'].unique())
59 | print(leiden_res, n_clusters, flush=True)
60 | print()
61 |
62 |
63 | def cluster(
64 | adata,
65 | n_pcs,
66 | k_latent,
67 | n_regions,
68 | leiden_res,
69 | ):
70 |
71 | # Calculate latent representation
72 | pca = PCA(n_components=n_pcs)
73 | adata.obsm['X_smoothed_pca'] = pca.fit_transform(adata.obsm['X_smoothed'])
74 |
75 | # Find latent neighbors
76 | nbrs = NearestNeighbors(n_neighbors=k_latent).fit(adata.obsm['X_smoothed_pca'])
77 | adata.obsp['smoothed_connectivities'] = nbrs.kneighbors_graph(mode='connectivity')
78 | adata.obsp['smoothed_distances'] = nbrs.kneighbors_graph(mode='distance')
79 |
80 | # Add metadata expected by Scanpy's Leiden and UMAP
81 | adata.uns['smoothed'] = {'connectivities_key': 'smoothed_connectivities',
82 | 'distances_key': 'smoothed_distances',
83 | 'params': {
84 | 'n_neighbors': k_latent,
85 | 'method': 'umap',
86 | 'random_state': 0,
87 | 'metric': 'euclidean',
88 | 'use_rep': 'X_smoothed_pca'
89 | }
90 | }
91 |
92 | # Perform k-means clustering
93 | kmeans = KMeans(n_clusters=n_regions, n_init=10)
94 | kmeans.fit(adata.obsm['X_smoothed_pca'])
95 | adata.obs['kmeans'] = kmeans.labels_.astype(str)
96 |
97 | # Perform Leiden clustering
98 | binary_search_leiden(adata, leiden_res, n_regions)
99 |
100 |
101 | def quantify(adata, n_regions):
102 |
103 | # Quantify spatial reconstruction
104 | Cp = adata.obsp['spatial_connectivities']
105 | Cl = adata.obsp['smoothed_connectivities']
106 | recon_score = Cp.multiply(Cl).count_nonzero() / (Cp+Cl).count_nonzero()
107 |
108 | # Quantify k-means accuracy
109 | kmeans_ari = adjusted_rand_score(adata.obs['region_true'], adata.obs['kmeans'])
110 |
111 | # Quantify Leiden accuracy
112 | leiden_ari = adjusted_rand_score(adata.obs['region_true'], adata.obs['leiden'])
113 |
114 | return recon_score, kmeans_ari, leiden_ari
115 |
116 |
117 | def main(
118 | read_path,
119 | sample_rate,
120 | radius,
121 | k_latent,
122 | n_pcs,
123 | leiden_res,
124 | write_path,
125 | random_seed,
126 | decimals,
127 | ):
128 |
129 | # Initialize logger
130 | logger = logging.getLogger('UTAG')
131 | logger.setLevel(logging.INFO)
132 | formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
133 | ch = logging.StreamHandler()
134 | ch.setLevel(logging.INFO)
135 | ch.setFormatter(formatter)
136 | logger.addHandler(ch)
137 |
138 | # Set random seed
139 | np.random.seed(random_seed)
140 |
141 | # Load data
142 | logger.info(f'Loading data from {read_path}')
143 | adata = sc.read_h5ad(read_path)
144 | n_regions = len(adata.obs['region_true'].unique())
145 |
146 | # Smooth
147 | logger.info('Smoothing')
148 | logger.info(f'\tsample_rate={sample_rate}')
149 | logger.info(f'\trandom_seed={random_seed}')
150 | adata = smooth(adata, radius, sample_rate, random_seed)
151 |
152 | # Cluster
153 | logger.info('Clustering')
154 | cluster(adata, n_pcs, k_latent, n_regions, leiden_res)
155 |
156 | # Quantify results
157 | logger.info('Quantifying results')
158 | recon_score, kmeans_ari, leiden_ari = quantify(adata, n_regions)
159 |
160 | # Write results to disk
161 | os.makedirs(write_path, exist_ok=True)
162 | results = f'{np.round(recon_score, decimals=decimals)}_' + \
163 | f'{np.round(kmeans_ari, decimals=decimals)}_' + \
164 | f'{np.round(leiden_ari, decimals=decimals)}'
165 | filename_txt = f'{random_seed}_{results}.txt'
166 | write_path_txt = os.path.join(write_path, filename_txt)
167 | logger.info(f'Writing results to {write_path_txt}')
168 | f = open(write_path_txt, 'a')
169 | f.close()
170 |
171 | # Write example AnnData to disk
172 | if random_seed == 0:
173 | filename_adata = f'adata_{sample_rate}.h5ad'
174 | write_path_adata = os.path.join(write_path, filename_adata)
175 | logger.info(f'Saving AnnData to {write_path_adata}')
176 | adata.write(write_path_adata)
177 |
178 | logger.info('Done')
179 |
180 |
181 | if __name__=='__main__':
182 |
183 | parser = argparse.ArgumentParser()
184 | parser.add_argument('--read_path', type=str)
185 | parser.add_argument('--sample_rate', type=float, default=None)
186 | parser.add_argument('--radius', type=float, default=None)
187 | parser.add_argument('--k_latent', type=int, default=50)
188 | parser.add_argument('--n_pcs', type=int)
189 | parser.add_argument('--leiden_res', type=float)
190 | parser.add_argument('--write_path', type=str)
191 | parser.add_argument('--random_seed', type=int)
192 | parser.add_argument('--decimals', type=int, default=5)
193 | args = parser.parse_args()
194 |
195 | main(
196 | args.read_path,
197 | args.sample_rate,
198 | args.radius,
199 | args.k_latent,
200 | args.n_pcs,
201 | args.leiden_res,
202 | args.write_path,
203 | args.random_seed,
204 | args.decimals,
205 | )
--------------------------------------------------------------------------------
/code_for_figures/generalization/.DS_Store:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/wanglab-broad/spin/53c174bfcc029f2614bf381f3d61557f3e1824d1/code_for_figures/generalization/.DS_Store
--------------------------------------------------------------------------------
/code_for_figures/generalization/gut/xcondition.ipynb:
--------------------------------------------------------------------------------
1 | {
2 | "cells": [
3 | {
4 | "cell_type": "code",
5 | "execution_count": null,
6 | "metadata": {},
7 | "outputs": [],
8 | "source": [
9 | "import scanpy as sc\n",
10 | "import numpy as np\n",
11 | "from matplotlib.patches import Rectangle\n",
12 | "import seaborn as sns \n",
13 | "import matplotlib.pyplot as plt\n",
14 | "import os \n",
15 | "from scipy.stats import mannwhitneyu"
16 | ]
17 | },
18 | {
19 | "cell_type": "markdown",
20 | "metadata": {},
21 | "source": [
22 | "## Load data and set up params"
23 | ]
24 | },
25 | {
26 | "cell_type": "code",
27 | "execution_count": null,
28 | "metadata": {},
29 | "outputs": [],
30 | "source": [
31 | "adata = sc.read_h5ad('/stanley/WangLab/kamal/data/mouse/gut/ileum_spin_filtered.h5ad')\n",
32 | "basepath = '/stanley/WangLab/kamal/code/remote_notebooks/gut_xcondition/figures_kamal/'\n",
33 | "dpi = 300\n",
34 | "ctypes = adata.obs['general_annos'].unique()\n",
35 | "ctype_cmap = {ctypes[i]:sc.pl.palettes.default_102[i] for i in range(len(ctypes))}\n",
36 | "region_cmap = {str(i):sc.pl.palettes.default_102[i] for i in range(100)}\n",
37 | "figsize = (7,4.5)"
38 | ]
39 | },
40 | {
41 | "cell_type": "code",
42 | "execution_count": null,
43 | "metadata": {},
44 | "outputs": [],
45 | "source": [
46 | "adata"
47 | ]
48 | },
49 | {
50 | "cell_type": "code",
51 | "execution_count": null,
52 | "metadata": {},
53 | "outputs": [],
54 | "source": [
55 | "# Get vmin and vmax of gene expression across samples for colorbar normalization\n",
56 | "def getMinMax(adata, gene, layer='smooth'):\n",
57 | " return (adata[:,gene].layers[layer].min(), adata[:,gene].layers[layer].max())"
58 | ]
59 | },
60 | {
61 | "attachments": {},
62 | "cell_type": "markdown",
63 | "metadata": {},
64 | "source": [
65 | "# Full tissue slices"
66 | ]
67 | },
68 | {
69 | "cell_type": "markdown",
70 | "metadata": {},
71 | "source": [
72 | "## Tissue and latent colored by cell type"
73 | ]
74 | },
75 | {
76 | "cell_type": "code",
77 | "execution_count": null,
78 | "metadata": {},
79 | "outputs": [],
80 | "source": [
81 | "sc.set_figure_params(figsize=figsize)\n",
82 | "sc.pl.embedding(adata, basis='spatial', color='general_annos', palette=ctype_cmap, s=3, title='', legend_loc=None, return_fig=True)\n",
83 | "plt.axis('off')\n",
84 | "figname = f'tissue_colored_by_celltype.png'\n",
85 | "savepath = os.path.join(basepath, figname)\n",
86 | "plt.savefig(savepath, bbox_inches='tight', transparent=True, dpi=dpi)"
87 | ]
88 | },
89 | {
90 | "cell_type": "code",
91 | "execution_count": null,
92 | "metadata": {},
93 | "outputs": [],
94 | "source": [
95 | "sc.set_figure_params(figsize=(5,5))\n",
96 | "sc.pl.embedding(adata, basis='X_umap', color='general_annos', palette=ctype_cmap, s=3, title='', legend_loc='', return_fig=True)\n",
97 | "plt.axis('off')\n",
98 | "figname = f'latent_colored_by_celltype.png'\n",
99 | "savepath = os.path.join(basepath, figname)\n",
100 | "plt.savefig(savepath, bbox_inches='tight', transparent=True, dpi=dpi)"
101 | ]
102 | },
103 | {
104 | "cell_type": "code",
105 | "execution_count": null,
106 | "metadata": {},
107 | "outputs": [],
108 | "source": [
109 | "sc.set_figure_params(figsize=(5,5))\n",
110 | "sc.pl.embedding(adata, basis='X_umap', color='sample', s=3, title='', legend_loc='', return_fig=True)\n",
111 | "plt.axis('off')\n",
112 | "figname = f'latent_colored_by_condition_celltype.png'\n",
113 | "savepath = os.path.join(basepath, figname)\n",
114 | "plt.savefig(savepath, bbox_inches='tight', transparent=True, dpi=dpi)"
115 | ]
116 | },
117 | {
118 | "cell_type": "code",
119 | "execution_count": null,
120 | "metadata": {},
121 | "outputs": [],
122 | "source": [
123 | "sc.set_figure_params(figsize=(5,5))\n",
124 | "random_idxs = np.random.choice(np.arange(len(adata)), size=len(adata), replace=False)\n",
125 | "sc.pl.embedding(adata[random_idxs], basis='X_umap', color='sample', s=3, title='', legend_loc='', return_fig=True)\n",
126 | "plt.axis('off')\n",
127 | "figname = f'latent_colored_by_condition_celltype.png'\n",
128 | "savepath = os.path.join(basepath, figname)\n",
129 | "plt.savefig(savepath, bbox_inches='tight', transparent=True, dpi=dpi)"
130 | ]
131 | },
132 | {
133 | "cell_type": "code",
134 | "execution_count": null,
135 | "metadata": {},
136 | "outputs": [],
137 | "source": [
138 | "sc.set_figure_params(figsize=(10,10))\n",
139 | "sc.pl.embedding(adata, basis='X_umap', color='general_annos', palette=ctype_cmap, s=10, title='', legend_loc='on data')"
140 | ]
141 | },
142 | {
143 | "cell_type": "code",
144 | "execution_count": null,
145 | "metadata": {},
146 | "outputs": [],
147 | "source": [
148 | "sc.set_figure_params(figsize=(10,10))\n",
149 | "sc.pl.embedding(adata, basis='X_umap', color='sample', s=10, title='')"
150 | ]
151 | },
152 | {
153 | "cell_type": "markdown",
154 | "metadata": {},
155 | "source": [
156 | "## Tissue and latent colored by region"
157 | ]
158 | },
159 | {
160 | "cell_type": "code",
161 | "execution_count": null,
162 | "metadata": {},
163 | "outputs": [],
164 | "source": [
165 | "sc.set_figure_params(figsize=figsize)\n",
166 | "sc.pl.embedding(adata, basis='spatial', color='region', palette=region_cmap, s=3, title='', legend_loc=None, return_fig=True)\n",
167 | "plt.axis('off')\n",
168 | "figname = f'tissue_colored_by_region.png'\n",
169 | "savepath = os.path.join(basepath, figname)\n",
170 | "plt.savefig(savepath, bbox_inches='tight', transparent=True, dpi=dpi)"
171 | ]
172 | },
173 | {
174 | "cell_type": "code",
175 | "execution_count": null,
176 | "metadata": {},
177 | "outputs": [],
178 | "source": [
179 | "sc.set_figure_params(figsize=(5,5))\n",
180 | "sc.pl.embedding(adata, basis='X_umap_spin', color='region', palette=region_cmap, s=3, title='', legend_loc=None, return_fig=True)\n",
181 | "plt.axis('off')\n",
182 | "figname = f'latent_colored_by_region.png'\n",
183 | "savepath = os.path.join(basepath, figname)\n",
184 | "plt.savefig(savepath, bbox_inches='tight', transparent=True, dpi=dpi)"
185 | ]
186 | },
187 | {
188 | "cell_type": "code",
189 | "execution_count": null,
190 | "metadata": {},
191 | "outputs": [],
192 | "source": [
193 | "sc.set_figure_params(figsize=(5,5))\n",
194 | "sc.pl.embedding(adata, basis='X_umap_spin', color='sample', s=3, title='', legend_loc=None, return_fig=True)\n",
195 | "plt.axis('off')\n",
196 | "figname = f'latent_colored_by_condition.png'\n",
197 | "savepath = os.path.join(basepath, figname)\n",
198 | "plt.savefig(savepath, bbox_inches='tight', transparent=True, dpi=dpi)"
199 | ]
200 | },
201 | {
202 | "cell_type": "code",
203 | "execution_count": null,
204 | "metadata": {},
205 | "outputs": [],
206 | "source": [
207 | "sc.set_figure_params(figsize=(5,5))\n",
208 | "random_idxs = np.random.choice(np.arange(len(adata)), size=len(adata), replace=False)\n",
209 | "sc.pl.embedding(adata[random_idxs], basis='X_umap_spin', color='sample', s=3, title='', legend_loc=None, return_fig=True)\n",
210 | "plt.axis('off')\n",
211 | "figname = f'latent_colored_by_condition.png'\n",
212 | "savepath = os.path.join(basepath, figname)\n",
213 | "plt.savefig(savepath, bbox_inches='tight', transparent=True, dpi=dpi)"
214 | ]
215 | },
216 | {
217 | "cell_type": "markdown",
218 | "metadata": {},
219 | "source": [
220 | "# Zooms"
221 | ]
222 | },
223 | {
224 | "attachments": {},
225 | "cell_type": "markdown",
226 | "metadata": {},
227 | "source": [
228 | "## Get zoom regions"
229 | ]
230 | },
231 | {
232 | "cell_type": "code",
233 | "execution_count": null,
234 | "metadata": {},
235 | "outputs": [],
236 | "source": [
237 | "def get_zoom(adata, x, y, width, height, theta):\n",
238 | " x1, x2 = x, x+width\n",
239 | " y1, y2 = y, y+height\n",
240 | " R = np.array([\n",
241 | " [np.cos(theta), -np.sin(theta)],\n",
242 | " [np.sin(theta), np.cos(theta)]\n",
243 | " ])\n",
244 | " rdata = adata.copy()\n",
245 | " rdata.obsm['spatial'] = rdata.obsm['spatial'] @ R.T\n",
246 | " zoomdata = rdata[rdata.obsm['spatial'][:,0]>x1]\n",
247 | " zoomdata = zoomdata[zoomdata.obsm['spatial'][:,0]y1]\n",
249 | " zoomdata = zoomdata[zoomdata.obsm['spatial'][:,1]=3.2,<4"]
3 | build-backend = "flit_core.buildapi"
4 |
5 | [project]
6 | name = "spin"
7 | version = "0.0.1"
8 | description = "SPatial INtegration of spatially resolved transcriptomics data"
9 | authors = [
10 | {name = "Kamal Maher", email = "kmaher@mit.edu"},
11 | ]
12 | readme = {file = "README.md", content-type="text/markdown"}
13 | license = {file = "LICENSE"}
14 | requires-python = ">=3.9"
15 | dependencies = [
16 | "scanpy[leiden,harmony]",
17 | ]
18 |
19 | [tool.setuptools]
20 | package-dir = {"" = "src"}
21 | include-package-data = true
22 |
23 | [project.scripts]
24 | spin = "spin.cli:spin_cli"
25 |
--------------------------------------------------------------------------------
/src/spin/__init__.py:
--------------------------------------------------------------------------------
1 | """
2 | Spatially integrate spatially resolved transcriptomics (SRT) datasets.
3 | """
4 |
5 | from .spin import spin
6 |
--------------------------------------------------------------------------------
/src/spin/cli.py:
--------------------------------------------------------------------------------
1 | """
2 | Command-line interface for using SPIN from the shell.
3 | """
4 |
5 | import argparse
6 |
7 | from .spin import spin
8 |
9 |
10 | def spin_cli():
11 |
12 | # Parse arguments
13 | parser = argparse.ArgumentParser(
14 | description='SPatially INtegrate and cluster one or more spatially resolved \
15 | transcriptomics datasets'
16 | )
17 | parser.add_argument('--adata_paths', type=str, nargs='+', default=None)
18 | parser.add_argument('--write_path', type=str, default=None)
19 | parser.add_argument('--batch_key', type=str, default=None)
20 | parser.add_argument('--batch_labels', type=str, nargs='+', default=None)
21 | parser.add_argument('--n_nbrs', type=int, nargs='+', default=30)
22 | parser.add_argument('--n_samples', type=int, nargs='+', default=None)
23 | parser.add_argument('--spatial_key', type=str, default='spatial')
24 | parser.add_argument('--n_pcs', type=int, default=50)
25 | parser.add_argument('--svd_solver', default='randomized')
26 | parser.add_argument('--pca_key', default='X_pca_spin')
27 | parser.add_argument('--region_key', default='region')
28 | parser.add_argument('--umap_key', default='X_umap_spin')
29 | parser.add_argument('--resolution', type=float, default=0.5)
30 | parser.add_argument('--verbose', type=bool, default=True)
31 | parser.add_argument('--random_state', type=int, default=0)
32 | args = parser.parse_args()
33 |
34 | # Run SPIN
35 | spin(
36 | adata_paths=args.adata_paths,
37 | write_path=args.write_path,
38 | batch_key=args.batch_key,
39 | batch_labels=args.batch_labels,
40 | n_nbrs=args.n_nbrs,
41 | n_samples=args.n_samples,
42 | spatial_key=args.spatial_key,
43 | n_pcs=args.n_pcs,
44 | svd_solver=args.svd_solver,
45 | pca_key=args.pca_key,
46 | region_key=args.region_key,
47 | umap_key=args.umap_key,
48 | resolution=args.resolution,
49 | verbose=args.verbose,
50 | random_state=args.random_state,
51 | )
52 |
--------------------------------------------------------------------------------
/src/spin/spin.py:
--------------------------------------------------------------------------------
1 | """
2 | SPatially INtegrate spatially resolved transcriptomics (SRT) datasets.
3 | """
4 |
5 | from __future__ import annotations
6 |
7 | import logging
8 | from typing import Optional, Collection
9 |
10 | import scanpy as sc
11 | import numpy as np
12 | from sklearn.neighbors import NearestNeighbors
13 | from sklearn.decomposition import PCA
14 | from anndata import AnnData
15 |
16 |
17 | # Create logger
18 | logger = logging.getLogger('SPIN')
19 | logger.setLevel(logging.INFO)
20 | formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
21 | ch = logging.StreamHandler()
22 | ch.setLevel(logging.INFO)
23 | ch.setFormatter(formatter)
24 | logger.addHandler(ch)
25 |
26 |
27 | def spin(
28 | adatas: Optional[Collection[AnnData] | AnnData] = None,
29 | adata_paths: Optional[Collection[str]] = None,
30 | write_path: Optional[str] = None,
31 | batch_key: Optional[str] = None,
32 | batch_labels: Optional[Collection[str]] = None,
33 | n_nbrs: Collection[int] | int = 30,
34 | n_samples: Collection[Optional[int]] | Optional[int] = None,
35 | spatial_key: str = 'spatial',
36 | n_pcs: int = 50,
37 | svd_solver: str = 'randomized',
38 | pca_key: str = 'X_pca_spin',
39 | region_key: str = 'region',
40 | umap_key: str = 'X_umap_spin',
41 | resolution: float = 0.5,
42 | verbose: bool = True,
43 | random_state: int = 0,
44 | ):
45 | """\
46 | Spatially integrate and cluster SRT data using SPIN.
47 |
48 | Parameters
49 | ----------
50 | adatas
51 | One or more SRT datasets.
52 | Assumed to be have been normalized prior.
53 | adata_paths
54 | Paths to one or more SRT datasets.
55 | write_path
56 | Path to write integrated data to.
57 | batch_key
58 | The key to batch information within `adata.obs`.
59 | batch_labels
60 | Labels corresponding to each batch. Relevant when integrating across multiple
61 | `adatas`. Will be stored under `adata.obs[]`.
62 | n_nbrs
63 | Number of nearest neighbors to find for each cell.
64 | n_samples
65 | Number of random neighbor samples used for averaging.
66 | spatial_key
67 | The key to spatial coordinates within `adata.obsm`.
68 | n_pcs
69 | Number of PCs to calculate for dimension reduction.
70 | svd_solver
71 | SVD solver to use.
72 | pca_key
73 | The key to store PCA output under within `adata.obsm`.
74 | region_key
75 | The key to store region labels under within `adata.obs`.
76 | umap_key
77 | The key to store UMAP output under within `adata.obsm`.
78 | resolution
79 | Resolution for Leiden clustering
80 | verbose
81 | Display updates on function progress.
82 | random_state
83 | Random seed used for smoothing, PCA, and Harmony.
84 | """
85 | adata_source_types = np.array([type(adatas), type(adata_paths)])
86 | n_adata_sources = np.sum(adata_source_types==type(None))
87 | assert n_adata_sources == 1, "Requires either a list of paths or a list of AnnDatas"
88 |
89 | # Read data
90 | if adata_paths:
91 | adatas = []
92 | for path in adata_paths:
93 | if verbose:
94 | logger.info(f'Reading {path}')
95 | adatas.append(sc.read_h5ad(path))
96 |
97 | # Integrate spatial features across samples
98 | adata = _integrate(
99 | adatas,
100 | batch_key=batch_key,
101 | batch_labels=batch_labels,
102 | n_nbrs=n_nbrs,
103 | n_samples=n_samples,
104 | spatial_key=spatial_key,
105 | n_pcs=n_pcs,
106 | svd_solver=svd_solver,
107 | pca_key=pca_key,
108 | random_state=random_state,
109 | verbose=verbose,
110 | )
111 |
112 | # Cluster integrated samples to find regions
113 | adata = _cluster(
114 | adata,
115 | pca_key=pca_key,
116 | region_key=region_key,
117 | umap_key=umap_key,
118 | resolution=resolution,
119 | verbose=verbose,
120 | )
121 |
122 | # Write data
123 | if write_path:
124 | adata.write(write_path)
125 | if verbose:
126 | logger.info(f'Written to {write_path}')
127 | else:
128 | return adata
129 |
130 |
131 | def _integrate(
132 | adatas: Collection[AnnData] | AnnData,
133 | batch_key: Optional[str] = None,
134 | batch_labels: Optional[Collection[str]] = None,
135 | n_nbrs: Collection[int] | int = 30,
136 | n_samples: Collection[Optional[int]] | Optional[int] = None,
137 | spatial_key: str = 'spatial',
138 | n_pcs: int = 50,
139 | svd_solver: str = 'randomized',
140 | pca_key: str = 'X_pca_spin',
141 | random_state: int = 0,
142 | verbose: bool = True,
143 | ) -> AnnData:
144 | """\
145 | Smooth and integrate SRT datasets.
146 |
147 | Parameters
148 | ----------
149 | adatas
150 | One or more SRT datasets.
151 | Assumed to be have been normalized prior.
152 | batch_key
153 | The key to batch information within `adata.obs`. Relevant when integrating across
154 | multiple samples.
155 | If only analyzing a single sample, leave as `None`.
156 | batch_labels
157 | Labels corresponding to each adata. Will be stored under `adata.obs[]`.
158 | Required if passing in multiple adatas. Otherwise, leave as `None`.
159 | n_nbrs
160 | Number of nearest neighbors to find for each cell.
161 | Either provide n_nbrs for each dataset or a single n_nbrs for all datasets.
162 | Needs to be the same length as n_samples.
163 | n_samples
164 | Number of random neighbor samples used for averaging.
165 | Either provide n_samples for each dataset or a single n_samples for all datasets.
166 | Needs to be the same length as n_nbrs.
167 | spatial_key
168 | The key to spatial coordinates within `adata.obsm`.
169 | n_pcs
170 | Number of PCs to calculate for dimension reduction.
171 | svd_solver
172 | SVD solver to use.
173 | pca_key
174 | The key to store PCA output under within `adata.obsm`.
175 | random_state
176 | Random seed used for smoothing, PCA, and Harmony.
177 | verbose
178 | Display updates on function progress.
179 |
180 | Returns
181 | -------
182 | Copy of adata input containing integrated spatial expression PCs.
183 | """
184 | # Handle non-Collection input (e.g. single AnnData, n_nbrs, and/or n_samples)
185 | if type(adatas) == AnnData:
186 | adatas = [adatas]
187 | if type(n_nbrs) == int:
188 | n_nbrs = [n_nbrs]
189 | if (type(n_samples) == int) or (n_samples == None):
190 | n_samples = [n_samples]
191 |
192 | # Split single AnnData by batch, if batch_key provided
193 | n_adatas = len(adatas)
194 | if (n_adatas == 1):
195 | if batch_key:
196 | if verbose:
197 | logger.info(f'Splitting adata by `{batch_key}`')
198 | batch_labels = adatas[0].obs[batch_key].unique()
199 | adatas = [adatas[0][adatas[0].obs[batch_key]==batch] for batch in batch_labels]
200 | n_adatas = len(adatas)
201 |
202 | # If single n_nbrs/n_samples for multiple batches, clone
203 | if len(n_nbrs) < n_adatas:
204 | n_nbrs *= n_adatas
205 | if len(n_samples) < n_adatas:
206 | n_samples *= n_adatas
207 |
208 | # Smooth each batch independently
209 | if verbose:
210 | logger.info('Smoothing')
211 | for i in range(n_adatas):
212 | _get_nbrs(
213 | adatas[i],
214 | n_nbrs[i],
215 | spatial_key,
216 | )
217 | _smooth(
218 | adatas[i],
219 | n_samples[i],
220 | random_state,
221 | )
222 |
223 | # Concatenate batches and add metadata
224 | if n_adatas > 1:
225 | adata = sc.concat(adatas, keys=batch_labels, label=batch_key, join='inner')
226 | adata.uns['n_nbrs'] = [adatas[i].uns['n_nbrs'] for i in range(n_adatas)]
227 | adata.uns['n_samples'] = [adatas[i].uns['n_samples'] for i in range(n_adatas)]
228 | else:
229 | adata = adatas[0]
230 |
231 | # Run PCA
232 | if verbose:
233 | logger.info('Performing PCA')
234 | pca = PCA(n_components=n_pcs, svd_solver=svd_solver, random_state=random_state)
235 | adata.obsm[pca_key] = pca.fit_transform(adata.layers['smooth'])
236 | adata.varm[pca_key] = pca.components_.T
237 |
238 | # Integrate PCs
239 | if batch_labels:
240 | if verbose:
241 | logger.info('Integrating')
242 | sc.external.pp.harmony_integrate(
243 | adata,
244 | batch_key,
245 | basis=pca_key,
246 | adjusted_basis=pca_key,
247 | random_state=random_state,
248 | verbose=verbose,
249 | )
250 | if verbose:
251 | logger.info('Integration complete')
252 |
253 | return adata.copy() # copying necessary for multiple runs on single AnnData
254 |
255 |
256 | def _cluster(
257 | adata: AnnData,
258 | pca_key: str = 'X_pca_spin',
259 | region_key: str = 'region',
260 | umap_key: str = 'X_umap_spin',
261 | resolution: float = 0.5,
262 | verbose: bool = True,
263 | ) -> AnnData:
264 | """\
265 | Create nearest neighbors graph in latent space and perform UMAP and Leiden.
266 |
267 | Parameters
268 | --------
269 | adata
270 | SRT dataset
271 | pca_key
272 | The key to PCA output within `adata.obsm`.
273 | region_key
274 | The key to store region labels under within `adata.obs`.
275 | umap_key
276 | The key to store UMAP output under within `adata.obsm`.
277 | resolution
278 | Resolution for Leiden clustering.
279 | verbose
280 | Display updates on function progress.
281 |
282 | Returns
283 | --------
284 | Copy of adata input containing region cluster labels and UMAP coordinates
285 | """
286 | if verbose:
287 | logger.info('Finding latent neighbors')
288 | sc.pp.neighbors(
289 | adata,
290 | use_rep=pca_key,
291 | key_added=region_key,
292 | )
293 | if umap_key:
294 | if verbose:
295 | logger.info('Performing UMAP')
296 | umap = sc.tl.umap(
297 | adata,
298 | neighbors_key=region_key,
299 | copy=True,
300 | ).obsm['X_umap']
301 | adata.obsm[umap_key] = umap
302 | if verbose:
303 | logger.info('Leiden clustering')
304 | sc.tl.leiden(
305 | adata,
306 | resolution=resolution,
307 | key_added=region_key,
308 | neighbors_key=region_key,
309 | )
310 | if verbose:
311 | logger.info('Clustering complete')
312 |
313 | return adata.copy()
314 |
315 |
316 | def _get_nbrs(
317 | adata: AnnData,
318 | n_nbrs: int,
319 | spatial_key: str,
320 | ) -> np.ndarray:
321 | """\
322 | Find spatial nearest neighbors of each cell.
323 |
324 | Parameters
325 | ----------
326 | adata
327 | SRT dataset.
328 | n_nbrs
329 | Number of nearest neighbors to find for each cell.
330 | spatial_key
331 | The key to spatial coordinates within `adata.obsm`.
332 |
333 | Returns
334 | -------
335 | Updates `adata` with the following fields:
336 |
337 | `.obsm['nbr_idxs']`:
338 | Matrix of neighbor indices of shape `n_obs` × `n_nbrs`
339 | `.uns['n_nbrs']`:
340 | Number of neighbors used
341 | `.uns['spatial_key']`:
342 | The key to `.obsm` for the domain used to find neighbors
343 | """
344 | # Find spatial nearest neighbors
345 | coordinates = adata.obsm[spatial_key]
346 | nbrs = NearestNeighbors(n_neighbors=n_nbrs)
347 | nbrs.fit(coordinates)
348 | _, nbr_idxs = nbrs.kneighbors(coordinates)
349 |
350 | # Save metadata
351 | adata.obsm['nbr_idxs'] = nbr_idxs
352 | adata.uns['n_nbrs'] = n_nbrs
353 | adata.uns['spatial_key'] = spatial_key
354 |
355 |
356 | def _smooth(
357 | adata: AnnData,
358 | n_samples: Optional[int],
359 | random_state: int,
360 | ) -> np.ndarray:
361 | """\
362 | Set each cell's representation to the average of its randomly-subsampled neighborhood.
363 |
364 | Parameters
365 | ----------
366 | adata
367 | SRT dataset.
368 | nbr_idxs
369 | Matrix of neighbor indices of shape `n_obs` × `n_nbrs`. Rows correspond to cells
370 | and columns to the adata indices of their nearest neighbors.
371 | n_samples
372 | Number of random neighbor samples used for averaging.
373 | If None, sample 1/3 of n_nbrs, which is inferred from `nbr_idxs`.
374 | random_state
375 | Random seed for randomly subsampling neighborhoods.
376 |
377 | Returns
378 | -------
379 | Updates `adata.layers` with the following fields:
380 |
381 | `smooth`:
382 | Smoothed data matrix of shape `n_obs` × `n_vars`
383 | `n_samples`:
384 | Number of random neighbor samples used for averaging
385 | """
386 | # Randomly subsample each cell's neighborhood
387 | if not n_samples:
388 | n_samples = adata.obsm['nbr_idxs'].shape[1] // 3
389 | np.random.seed(random_state)
390 | nbr_idxs_sampled = np.array([
391 | np.random.choice(idxs, size=n_samples, replace=False)
392 | for idxs in adata.obsm['nbr_idxs']
393 | ])
394 |
395 | # Set each cell's representation to the average of its subsampled neighborhood
396 | X_smooth = np.zeros(adata.X.shape)
397 | for nth_nbrs in np.array(nbr_idxs_sampled).T:
398 | X_smooth += adata.X[nth_nbrs] / n_samples
399 |
400 | # Save metadata
401 | adata.obsm['nbr_idxs_sampled'] = nbr_idxs_sampled
402 | adata.layers['smooth'] = np.array(X_smooth) # in case adata.X is sparse
403 | adata.uns['n_samples'] = n_samples
404 |
--------------------------------------------------------------------------------