├── LICENSE ├── README.md ├── images └── workflow.jpg ├── requirements.txt ├── scCube ├── __init__.py ├── model.py ├── sccube.py ├── utils.py └── visualization.py ├── setup.py └── tutorial ├── API.md ├── customized_TME.ipynb ├── customized_basis_patterns.ipynb ├── customized_complex_patterns.ipynb ├── demo_data ├── MERFISH_0.06_adata.h5ad ├── MERFISH_n0.29_adata.h5ad ├── customized_bc.pth ├── customized_bc_adata.h5ad ├── demo_sc_data.csv └── demo_sc_meta.csv ├── demo_image.ipynb ├── demo_merfish_other.ipynb ├── demo_merfish_own.ipynb ├── demo_spot.ipynb ├── statistics.md ├── tutorial_3d.ipynb ├── tutorial_bc.ipynb ├── tutorial_dlpfc.ipynb ├── tutorial_merfish.ipynb ├── tutorial_pattern.ipynb ├── tutorial_resolution.ipynb ├── tutorial_specified.ipynb ├── tutorial_starmap.ipynb └── tutorial_subtype.ipynb /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # scCube v2.0.1 2 | 3 | ## Simulating multiple variability in spatially resolved transcriptomics 4 | 5 | [![python >=3.8](https://img.shields.io/badge/python-%3E%3D3.8-brightgreen)](https://www.python.org/) [![DOI](https://zenodo.org/badge/637091543.svg)](https://zenodo.org/doi/10.5281/zenodo.10483806) 6 | 7 | scCube is a Python package for independent, reproducible, and platform-diverse simulation of spatially-resolved transcriptomic data 8 | 9 | ![avatar](images/workflow.jpg) 10 | ## Major updates in v2.0.0 11 | 1. **scCube now allows users to consider the heterogeneity within cell types and generate the spatial patterns of cell subtypes flexibly:** 12 | * [Simulation of the variability of spatial patterns within cell types](tutorial/tutorial_subtype.ipynb) 13 | 2. **scCube now allows users to generate more interpretable spatial patterns in a customized manner:** 14 | * [Simulation of biologically interpretable spatial basis patterns](tutorial/customized_basis_patterns.ipynb) 15 | * [Simulation of highly customized complex spatial patterns](tutorial/customized_complex_patterns.ipynb) 16 | * [Demonstration on simulating the tumor-immune microenvironment of TNBC with three archetypical subtypes](tutorial/customized_TME.ipynb) 17 | 18 | ## Requirements and Installation 19 | [![anndata 0.8.0](https://img.shields.io/badge/anndata-0.8.0-success)](https://pypi.org/project/anndata/) [![numpy 1.23.5](https://img.shields.io/badge/numpy-1.23.5-important)](https://pypi.org/project/numpy/) [![pandas 1.5.3](https://img.shields.io/badge/pandas-1.5.3-critical)](https://pypi.org/project/pandas/) [![scanpy 1.9.1](https://img.shields.io/badge/scanpy-1.9.1-informational)](https://github.com/scverse/scanpy) [![pot 0.8.2](https://img.shields.io/badge/pot-0.8.2-blueviolet)](https://pypi.org/project/POT/) [![matplotlib 3.6.3](https://img.shields.io/badge/matplotlib-3.6.3-ff69b4)](https://pypi.org/project/matplotlib/) [![seaborn 0.12.2](https://img.shields.io/badge/seaborn-0.12.2-9cf)](https://pypi.org/project/seaborn/) [![tqdm 4.64.1](https://img.shields.io/badge/tqdm-4.64.1-lightgrey)](https://pypi.org/project/tqdm/) 20 | 21 | ### Create and activate Python environment 22 | For scCube, the Python version need is over 3.8. If you have installed Python3.6 or Python3.7, consider installing Anaconda, and then you can create a new environment. 23 | ``` 24 | conda create -n sccube python=3.8 25 | conda activate sccube 26 | ``` 27 | ### Install pytorch 28 | The version of pytorch should be suitable to the CUDA version of your machine. You can find the appropriate version on the [PyTorch website](https://pytorch.org/get-started/locally/). 29 | Here is an example with CUDA11.6: 30 | ``` 31 | pip install torch --extra-index-url https://download.pytorch.org/whl/cu116 32 | ``` 33 | ### Install other requirements 34 | ``` 35 | cd scCube-main 36 | pip install -r requirements.txt 37 | ``` 38 | ### Install scCube 39 | ``` 40 | python setup.py build 41 | python setup.py install 42 | ``` 43 | 44 | ## Quick Start (Training new models directly) 45 | scCube requires a **data** file (gene expression profiles) and a **meta** file (cell type/domain annotations) as the input, which can be stored as either `.csv` (read by pandas) or `.h5ad` (loaded by scanpy) formats. We have included two toy datasets in the [tutorial/demo_data folder](tutorial/demo_data) of this repository as examples to show how to use scCube. 46 | 47 | Reference-based simulation: 48 | * [Demonstration of scCube on simulating mouse hypothalamus MERFISH data (same as the spatial reference)](tutorial/demo_merfish_own.ipynb) 49 | * [Demonstration of scCube on simulating mouse hypothalamus MERFISH data (different from the spatial reference)](tutorial/demo_merfish_other.ipynb) 50 | 51 | Reference-free simulation: 52 | * [Demonstration of scCube on generating simulated spot-based SRT data](tutorial/demo_spot.ipynb) 53 | * [Demonstration of scCube on generating simulated imaging-based SRT data](tutorial/demo_image.ipynb) 54 | 55 | For more details about the format of input and the description of parameters, see [here](tutorial/API.md). 56 | 57 | ## Trained models and datasets 58 | In the current version, scCube includes about **300** trained models of various tissues derived from four human and mouse scRNA-seq atlas (Tabula Muris, Tabula Sapiens, MCA, and HCL) as well as high-quality SRT datasets. Detailed information about these models and datasets can be found [here](tutorial/statistics.md). 59 | 60 | ## Tutorials (loading trained models provided by scCube) 61 | Additional step-by-step tutorials are now available! Users can employ the trained models conveniently through the Python package to generate the new gene expression profiles of specific tissues. We provide the following tutorials as examples: 62 | 63 | Reference-based simulation: 64 | * [Using scCube to simulate the mouse hypothalamus MERFISH data](tutorial/tutorial_merfish.ipynb) 65 | * [Using scCube to simulate the human DLPFC 10x Visium data](tutorial/tutorial_dlpfc.ipynb) 66 | * [Using scCube to simulate the mouse cortex STARmap data](tutorial/tutorial_starmap.ipynb) 67 | * [Using scCube to simulate the human breast cancer ST data](tutorial/tutorial_bc.ipynb) 68 | 69 | Reference-free simulation: 70 | * [Using scCube to simulate diverse spatial patterns](tutorial/tutorial_pattern.ipynb) 71 | * [Using scCube to simulate 3D spatial patterns](tutorial/tutorial_3d.ipynb) 72 | * [Using scCube to simulate spatial patterns for user-specified cell types](tutorial/tutorial_specified.ipynb) 73 | * [Using scCube to simulate the variability of resolution and spot arrangement of spot-based SRT data](tutorial/tutorial_resolution.ipynb) 74 | 75 | 76 | 77 | ## About 78 | scCube was developed by Jingyang Qian. Should you have any questions, please contact Jingyang Qian at qianjingyang@zju.edu.cn. 79 | 80 | ## References 81 | Qian, J., Bao, H., Shao, X. et al. Simulating multiple variability in spatially resolved transcriptomics with scCube. Nat Commun 15, 5021 (2024). [https://doi.org/10.1038/s41467-024-49445-0](https://doi.org/10.1038/s41467-024-49445-0) 82 | 83 | 84 | -------------------------------------------------------------------------------- /images/workflow.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ZJUFanLab/scCube/d5b423d296da17d0fd5b4d12e92262167a642445/images/workflow.jpg -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | anndata==0.8.0 2 | numpy==1.23.5 3 | pandas==1.5.3 4 | scanpy==1.9.1 5 | pot==0.8.2 6 | tqdm>=4.66.3 7 | matplotlib==3.6.3 8 | seaborn==0.12.2 9 | scipy<=1.13.1 10 | -------------------------------------------------------------------------------- /scCube/__init__.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | # @Time : 2022/7/13 3:25 下午 4 | # @Author : qjy 5 | # @Site : 6 | # @File : __init__.py.py 7 | # @Software: PyCharm 8 | 9 | 10 | __author__ = "Jingyang Qian" 11 | __email__ = "qianjingyang@zju.edu.cn" 12 | 13 | from .utils import * 14 | from .sccube import * 15 | from .model import * 16 | from .visualization import * 17 | -------------------------------------------------------------------------------- /scCube/model.py: -------------------------------------------------------------------------------- 1 | import torch 2 | import torch.nn as nn 3 | import torch.nn.functional as F 4 | import numpy as np 5 | from torch.autograd import Variable 6 | import torch.optim as optim 7 | 8 | 9 | # **************************************************************************** 10 | # ******************************** VAE *************************************** 11 | # **************************************************************************** 12 | class VAE(nn.Module): 13 | def __init__(self, embedding_size, hidden_size_list: list, mid_hidden): 14 | super(VAE, self).__init__() 15 | self.embedding_size = embedding_size 16 | self.hidden_size_list = hidden_size_list 17 | self.mid_hidden = mid_hidden 18 | 19 | self.enc_feature_size_list = [self.embedding_size] + self.hidden_size_list + [self.mid_hidden * 2] 20 | self.dec_feature_size_list = [self.embedding_size] + self.hidden_size_list + [self.mid_hidden] 21 | 22 | self.encoder = nn.ModuleList( 23 | [nn.Linear(self.enc_feature_size_list[i], self.enc_feature_size_list[i + 1]) for i in 24 | range(len(self.enc_feature_size_list) - 1)]) 25 | self.decoder = nn.ModuleList( 26 | [nn.Linear(self.dec_feature_size_list[i], self.dec_feature_size_list[i - 1]) for i in 27 | range(len(self.dec_feature_size_list) - 1, 0, -1)]) 28 | 29 | def encode(self, x): 30 | for i, layer in enumerate(self.encoder): 31 | x = self.encoder[i](x) 32 | if i != len(self.encoder) - 1: 33 | x = F.relu(x) 34 | return x 35 | 36 | def decode(self, x): 37 | for i, layer in enumerate(self.decoder): 38 | x = self.decoder[i](x) 39 | # if i != len(self.decoder) - 1: # 考虑去除,防止负数出现 40 | x = F.relu(x) 41 | return x 42 | 43 | def reparameterize(self, mu, logvar): 44 | std = torch.exp(0.5 * logvar) # var => std 45 | eps = torch.randn_like(std) 46 | return eps * std + mu 47 | 48 | def forward(self, x, used_device): 49 | x = x.to(used_device) 50 | encoder_output = self.encode(x) 51 | mu, sigma = torch.chunk(encoder_output, 2, dim=1) # mu, log_var 52 | hidden = self.reparameterize(mu, sigma) 53 | x_hat = self.decode(hidden) 54 | kl_div = 0.5 * torch.sum(torch.exp(sigma) + torch.pow(mu, 2) - 1 - sigma) / (x.shape[0] * x.shape[1]) 55 | return x_hat, kl_div 56 | 57 | 58 | # **************************************************************************** 59 | # ***************************** CLASSIFIER *********************************** 60 | # **************************************************************************** 61 | def weights_init(m): 62 | classname = m.__class__.__name__ 63 | if classname.find('Linear') != -1: 64 | m.weight.data.normal_(0.0, 0.02) 65 | m.bias.data.fill_(0) 66 | elif classname.find('BatchNorm') != -1: 67 | m.weight.data.normal_(1.0, 0.02) 68 | m.bias.data.fill_(0) 69 | 70 | 71 | class CLASSIFIER: 72 | # 先用全连接层分类器 73 | # 使用nn.NLLLoss()作为损失函数,配合logsoftmax实现对于类别的划分(类别概率大->全连接层输出高->softmax接近1->logsoftmax接近0->NLLLose小) 74 | def __init__(self, _input_dim, _nclass, dic, SemSize, dataloader='', used_device='', _lr=0.001, _nepoch=20): 75 | self.input_dim = _input_dim 76 | self.nclass = _nclass 77 | self.used_device = used_device 78 | self.model = LINEAR_LOGSOFTMAX(self.input_dim, self.nclass).to(self.used_device) 79 | self.model.apply(weights_init) 80 | self.criterion = nn.NLLLoss().to(self.used_device) 81 | self.dic = dic 82 | self.nepoch = _nepoch 83 | self.optimizer = optim.Adam(self.model.parameters(), lr=_lr, betas=(0.5, 0.999)) 84 | self.dataloader = dataloader 85 | self.SemSize = SemSize 86 | 87 | self.one_hot_embed = torch.zeros(len(self.dic), self.SemSize) 88 | self._one_hot_construct() 89 | 90 | self._pretrain() 91 | 92 | def _pretrain(self): 93 | min_loss = 10000 94 | for epoch in range(self.nepoch): 95 | loss_item = [] 96 | for batch_idx, data in enumerate(self.dataloader): 97 | cell_feature, label = data # dim of cell sample cell ,label should map to embedding, which dim=dim_noise 98 | cell_feature = torch.tensor(cell_feature, dtype=torch.float32).to(self.used_device) 99 | label = torch.LongTensor(label).to(self.used_device) 100 | self.model.zero_grad() 101 | inputv = Variable(cell_feature) 102 | labelv = Variable(label) 103 | output = self.model(inputv) 104 | loss = self.criterion(output, labelv) # 哪个是label哪个的logsoftmax就要小 105 | loss.backward() 106 | self.optimizer.step() 107 | loss_item.append(loss.item()) 108 | 109 | loss_item = np.mean(loss_item) 110 | if loss_item < min_loss: 111 | min_loss = loss_item 112 | 113 | # torch.save(self.model.state_dict(), 114 | # osp.join(self.args.save, self.args.name + '_pretrain_classification_epoch_' + 115 | # str(self.nepoch) + '.pth')) 116 | print("classification pretrain min loss:", min_loss) 117 | 118 | def _one_hot_construct(self): 119 | for i in range(len(self.dic)): 120 | self.one_hot_embed[i][i] = 1 121 | 122 | def classifier_embed(self, label): 123 | # 先用one-hot编码 124 | return self.one_hot_embed[label] 125 | 126 | 127 | class LINEAR_LOGSOFTMAX(nn.Module): # 使用logsoftmax作为分类结果。越接近0说明越真实 128 | def __init__(self, input_dim, nclass): 129 | super(LINEAR_LOGSOFTMAX, self).__init__() 130 | self.fc = nn.Linear(input_dim, nclass) 131 | self.logic = nn.LogSoftmax(dim=1) 132 | 133 | def forward(self, x): 134 | o = self.logic(self.fc(x)) 135 | return o 136 | 137 | 138 | # **************************************************************************** 139 | # ******************************** MLP_G ************************************* 140 | # **************************************************************************** 141 | class MLP_G(nn.Module): 142 | def __init__(self, SemSize, NoiseSize, NGH, FeaSize): 143 | super(MLP_G, self).__init__() 144 | self.fc1 = nn.Linear(SemSize + NoiseSize, NGH) 145 | self.fc2 = nn.Linear(NGH, FeaSize) 146 | self.lrelu = nn.LeakyReLU(0.2, True) 147 | # self.prelu = nn.PReLU() 148 | self.relu = nn.ReLU(True) 149 | 150 | self.apply(weights_init) 151 | 152 | def forward(self, noise, sem): 153 | h = torch.cat((noise, sem), 1) 154 | h = self.lrelu(self.fc1(h)) 155 | h = self.relu(self.fc2(h)) 156 | return h 157 | 158 | 159 | # **************************************************************************** 160 | # ****************************** MLP_CRITIC ********************************** 161 | # **************************************************************************** 162 | class MLP_CRITIC(nn.Module): 163 | def __init__(self, SemSize, NDH, FeaSize): 164 | super(MLP_CRITIC, self).__init__() 165 | self.fc1 = nn.Linear(FeaSize + SemSize, NDH) 166 | # self.fc2 = nn.Linear(opt.ndh, opt.ndh) 167 | self.fc2 = nn.Linear(NDH, 1) 168 | self.lrelu = nn.LeakyReLU(0.2, True) 169 | 170 | self.apply(weights_init) 171 | 172 | def forward(self, x, sem): 173 | 174 | h = torch.cat((x, sem), 1) 175 | h = self.lrelu(self.fc1(h)) 176 | h = self.fc2(h) 177 | return h -------------------------------------------------------------------------------- /scCube/sccube.py: -------------------------------------------------------------------------------- 1 | from .utils import * 2 | import numpy as np 3 | import pandas as pd 4 | import torch 5 | import ot 6 | import scanpy as sc 7 | import anndata as ad 8 | from collections import Counter 9 | from typing import Optional 10 | import os 11 | import os.path as osp 12 | from pandas import DataFrame 13 | from anndata import AnnData 14 | import warnings 15 | 16 | warnings.filterwarnings("ignore") 17 | 18 | 19 | class scCube: 20 | def __init__(self): 21 | pass 22 | 23 | def pre_process(self, 24 | sc_data: DataFrame, 25 | sc_meta: DataFrame, 26 | is_normalized: bool = True, 27 | ): 28 | 29 | """ 30 | pre-process input data, make sure it's normalized 31 | :param sc_data: DataFrame of input data 32 | :param sc_meta: DataFrame of input meta 33 | :param is_normalized: whether normalized 34 | :return: AnnData of data 35 | """ 36 | assert sc_meta.shape[0] == sc_data.shape[1], "shape data no match!!!" 37 | 38 | sc_adata = ad.AnnData(sc_data.T) 39 | sc_adata.obs = sc_meta 40 | 41 | if not is_normalized: 42 | print("the input is count matrix, normalizing it firstly...") 43 | sc.pp.normalize_total(sc_adata, target_sum=1e4) 44 | sc.pp.log1p(sc_adata) 45 | 46 | return sc_adata 47 | 48 | def train_vae_and_generate_cell(self, 49 | sc_adata: AnnData, 50 | celltype_key: str, 51 | cell_key: str, 52 | target_num: Optional[dict] = None, 53 | batch_size: int = 512, 54 | epoch_num: int = 10000, 55 | lr: float = 0.0001, 56 | hidden_size: int = 128, 57 | save_model: bool = True, 58 | save_path: str = '', 59 | project_name: str = '', 60 | used_device: str = 'cuda:0' 61 | ): 62 | """ 63 | train VAE model to generate cells 64 | :param sc_adata: AnnData of data 65 | :param celltype_key: the column name of `cell types` in meta 66 | :param cell_key: the column name of `cell` in meta 67 | :param target_num: target number of cells to generate, if `target_num=None`, generate cells by the proportion 68 | of cell types of the input data 69 | :param batch_size: batch size of training 70 | :param epoch_num: epoch number of training 71 | :param lr: learning reta of training 72 | :param hidden_size: hidden size of VAE model 73 | :param save_model: save trained VAE model or not 74 | :param save_path: save path 75 | :param project_name: name of trained VAE model 76 | :param used_device: device name, `cpu` or `cuda` 77 | :return: DataFrame of generated cell meta and data 78 | """ 79 | res_list = self.__parpare_generate(sc_adata, celltype_key, cell_key, target_num) 80 | print('begin vae training...') 81 | # ********************* training ********************* 82 | net = train_vae(res_list, 83 | batch_size=batch_size, 84 | epoch_num=epoch_num, 85 | lr=lr, 86 | hidden_size=hidden_size, 87 | used_device=used_device) 88 | print('vae training done!') 89 | 90 | if save_model: 91 | print("saving the trained vae model...") 92 | path_save = os.path.join(save_path, f"{project_name}.pth") 93 | if not osp.exists(save_path): 94 | os.makedirs(save_path) 95 | torch.save(net.state_dict(), path_save) 96 | print(f"save trained vae in {path_save}.") 97 | 98 | # ********************* generating ********************* 99 | generate_sc_meta, generate_sc_data = generate_vae(net, 100 | res_list, 101 | used_device=used_device) 102 | 103 | return generate_sc_meta, generate_sc_data 104 | 105 | def train_cgan_and_generate_cell(self, 106 | sc_adata: AnnData, 107 | celltype_key: str, 108 | cell_key: str, 109 | target_num: Optional[dict] = None, 110 | batch_size: int = 512, 111 | epoch_num: int = 5000, 112 | lr: float = 0.0001, 113 | SemSize: int = 256, 114 | NoiseSize: int = 256, 115 | save_model: bool = True, 116 | save_path: str = '', 117 | project_name: str = '', 118 | used_device: str = 'cuda:0' 119 | ): 120 | 121 | """ 122 | train CGAN model to generate cells 123 | :param sc_adata: AnnData of data 124 | :param celltype_key: the column name of `cell types` in meta 125 | :param cell_key: the column name of `cell` in meta 126 | :param target_num: target number of cells to generate, if `target_num=None`, generate cells by the proportion 127 | of cell types of the input data 128 | :param batch_size: batch size of training 129 | :param epoch_num: epoch number of training 130 | :param lr: learning reta of training 131 | :param SemSize: dim of embedding of class, eg:256 132 | :param NoiseSize: dim of noise, eg:256 133 | :param save_model: save trained VAE model or not 134 | :param save_path: save path 135 | :param project_name: name of trained VAE model 136 | :param used_device: device name, `cpu` or `cuda` 137 | :return: DataFrame of generated cell meta and data 138 | """ 139 | 140 | res_list = self.__parpare_generate(sc_adata, celltype_key, cell_key, target_num) 141 | print('begin cgan training...') 142 | # ********************* training ********************* 143 | pretrain_cls, netD, netG = train_cgan(res_list, 144 | batch_size=batch_size, 145 | epoch_num=epoch_num, 146 | lr=lr, 147 | SemSize=SemSize, 148 | NoiseSize=NoiseSize, 149 | used_device=used_device) 150 | print('cgan training done!') 151 | 152 | if save_model: 153 | print("saving the trained cgan model...") 154 | path_save_g = os.path.join(save_path, f"{project_name}_G.pth") 155 | path_save_d = os.path.join(save_path, f"{project_name}_D.pth") 156 | if not osp.exists(save_path): 157 | os.makedirs(save_path) 158 | 159 | torch.save(netG.state_dict(), path_save_g) 160 | torch.save(netD.state_dict(), path_save_d) 161 | 162 | print(f"save trained netG in {path_save_g}.") 163 | print(f"save trained netD in {path_save_d}.") 164 | 165 | # ********************* generating ********************* 166 | generate_sc_meta, generate_sc_data = generate_cgan(netG, 167 | pretrain_cls, 168 | res_list, 169 | NoiseSize=NoiseSize, 170 | used_device=used_device) 171 | 172 | return generate_sc_meta, generate_sc_data 173 | 174 | def load_vae_and_generate_cell(self, 175 | sc_adata: AnnData, 176 | celltype_key: str, 177 | cell_key: str, 178 | target_num: Optional[dict] = None, 179 | hidden_size: int = 128, 180 | load_path: str = '', 181 | used_device: str = 'cuda:0' 182 | ): 183 | """ 184 | load trained VAE model to generate cells 185 | :param sc_adata: AnnData of data 186 | :param celltype_key: the column name of `cell types` in meta 187 | :param cell_key: the column name of `cell` in meta 188 | :param target_num: target number of cells to generate, if `target_num=None`, generate cells by the proportion 189 | of cell types of the input data 190 | :param hidden_size: hidden size of VAE model, make sure it's same as the trained VAE model 191 | :param load_path: load path 192 | :param used_device: device name, `cpu` or `cuda` 193 | :return: DataFrame of generated cell meta and data 194 | """ 195 | 196 | res_list = self.__parpare_generate(sc_adata, celltype_key, cell_key, target_num) 197 | print(f'loading model from {load_path}') 198 | # ********************* loading ********************* 199 | net = load_vae(res_list, 200 | hidden_size=hidden_size, 201 | load_path=load_path, 202 | used_device=used_device) 203 | print('vae loading done!') 204 | 205 | # ********************* generating ********************* 206 | generate_sc_meta, generate_sc_data = generate_vae(net, 207 | res_list, 208 | used_device=used_device) 209 | 210 | return generate_sc_meta, generate_sc_data 211 | 212 | def load_cgan_and_generate_cell(self, 213 | sc_adata: AnnData, 214 | celltype_key: str, 215 | cell_key: str, 216 | target_num: Optional[dict] = None, 217 | batch_size: int = 512, 218 | SemSize: int = 256, 219 | NoiseSize: int = 256, 220 | load_path: str = '', 221 | used_device: str = 'cuda:0' 222 | ): 223 | 224 | """ 225 | load trained CGAN model to generate cells 226 | :param sc_adata: AnnData of data 227 | :param celltype_key: the column name of `cell types` in meta 228 | :param cell_key: the column name of `cell` in meta 229 | :param target_num: target number of cells to generate, if `target_num=None`, generate cells by the proportion 230 | of cell types of the input data 231 | :param batch_size: batch size of LINEAR_LOGSOFTMAX training 232 | :param SemSize: dim of embedding of class, eg:256 233 | :param NoiseSize: dim of noise, eg:256 234 | :param load_path: load path 235 | :param used_device: device name, `cpu` or `cuda` 236 | :return: DataFrame of generated cell meta and data 237 | """ 238 | 239 | res_list = self.__parpare_generate(sc_adata, celltype_key, cell_key, target_num) 240 | print(f'loading model from {load_path}') 241 | # ********************* loading ********************* 242 | netG = load_cgan(res_list, 243 | load_path=load_path, 244 | SemSize=SemSize, 245 | NoiseSize=NoiseSize, 246 | used_device=used_device) 247 | print('cgan loading done!') 248 | 249 | # ********************* pretrain cls ********************* 250 | dataloader = DataLoader(myDataset(single_cell=res_list[1], label=res_list[2]), batch_size=batch_size, 251 | shuffle=True) 252 | pretrain_cls = CLASSIFIER(res_list[0], len(set(res_list[2])), res_list[6], SemSize, dataloader, used_device, 253 | _lr=0.001, _nepoch=200) 254 | 255 | for p in pretrain_cls.model.parameters(): # set requires_grad to False 256 | p.requires_grad = False 257 | 258 | # ********************* generating ********************* 259 | generate_sc_meta, generate_sc_data = generate_cgan(netG, 260 | pretrain_cls, 261 | res_list, 262 | NoiseSize=NoiseSize, 263 | used_device=used_device) 264 | 265 | return generate_sc_meta, generate_sc_data 266 | 267 | def generate_pattern_custom_mixing(self, 268 | sc_adata: AnnData, 269 | generate_cell_num: int = 5000, 270 | celltype_key: str = 'Cell_type', 271 | cell_key: str = 'Cell', 272 | set_seed: bool = False, 273 | seed: int = 12345, 274 | spatial_size: int = 30, 275 | select_celltype: Optional[list] = None, 276 | prop_list: Optional[list] = None, 277 | hidden_size: int = 128, 278 | load_path: str = '', 279 | used_device: str = 'cuda:0' 280 | ): 281 | 282 | spattern_generator = SPatternGeneratorCustom(sc_adata=sc_adata, cell_num=generate_cell_num, 283 | celltype_key=celltype_key, set_seed=set_seed, seed=seed, 284 | spatial_size=spatial_size, select_celltype=select_celltype) 285 | spatial_pattern = spattern_generator.simulate_mixing(prop_list=prop_list) 286 | 287 | generate_sc_meta, generate_sc_data = self.__generate_custom_helper(sc_adata=sc_adata, 288 | spatial_pattern=spatial_pattern, 289 | celltype_key=celltype_key, 290 | cell_key=cell_key, 291 | hidden_size=hidden_size, 292 | load_path=load_path, 293 | used_device=used_device) 294 | 295 | return generate_sc_meta, generate_sc_data 296 | 297 | def generate_pattern_custom_cluster(self, 298 | sc_adata: AnnData, 299 | generate_cell_num: int = 5000, 300 | celltype_key: str = 'Cell_type', 301 | cell_key: str = 'Cell', 302 | set_seed: bool = False, 303 | seed: int = 12345, 304 | spatial_size: int = 30, 305 | select_celltype: Optional[list] = None, 306 | shape_list: list = ['Circle', 'Oval'], 307 | cluster_celltype_list: list = [], 308 | cluster_purity_list: list = [], 309 | infiltration_celltype_list: list = [[]], 310 | infiltration_prop_list: list = [[]], 311 | background_celltype: list = [], 312 | background_prop: Optional[list] = None, 313 | center_x_list: list = [20, 10], 314 | center_y_list: list = [20, 10], 315 | a_list: list = [15, 20], 316 | b_list: list = [10, 15], 317 | theta_list: list = [np.pi / 4, np.pi / 4], 318 | scale_value_list: list = [4.8, 4.8], 319 | twist_value_list: list = [0.5, 0.5], 320 | hidden_size: int = 128, 321 | load_path: str = '', 322 | used_device: str = 'cuda:0'): 323 | 324 | spattern_generator = SPatternGeneratorCustom(sc_adata=sc_adata, cell_num=generate_cell_num, 325 | celltype_key=celltype_key, set_seed=set_seed, seed=seed, 326 | spatial_size=spatial_size, select_celltype=select_celltype) 327 | spatial_pattern = spattern_generator.simulate_cluster(shape_list=shape_list, 328 | cluster_celltype_list=cluster_celltype_list, 329 | cluster_purity_list=cluster_purity_list, 330 | infiltration_celltype_list=infiltration_celltype_list, 331 | infiltration_prop_list=infiltration_prop_list, 332 | background_celltype=background_celltype, 333 | background_prop=background_prop, 334 | center_x_list=center_x_list, 335 | center_y_list=center_y_list, 336 | a_list=a_list, 337 | b_list=b_list, 338 | theta_list=theta_list, 339 | scale_value_list=scale_value_list, 340 | twist_value_list=twist_value_list) 341 | 342 | generate_sc_meta, generate_sc_data = self.__generate_custom_helper(sc_adata=sc_adata, 343 | spatial_pattern=spatial_pattern, 344 | celltype_key=celltype_key, 345 | cell_key=cell_key, 346 | hidden_size=hidden_size, 347 | load_path=load_path, 348 | used_device=used_device) 349 | 350 | return generate_sc_meta, generate_sc_data 351 | 352 | def generate_pattern_custom_ring(self, 353 | sc_adata: AnnData, 354 | generate_cell_num: int = 5000, 355 | celltype_key: str = 'Cell_type', 356 | cell_key: str = 'Cell', 357 | set_seed: bool = False, 358 | seed: int = 12345, 359 | spatial_size: int = 30, 360 | select_celltype: Optional[list] = None, 361 | shape_list: list = ['Circle', 'Oval'], 362 | ring_celltype_list: list = [], 363 | ring_purity_list: list = [], 364 | infiltration_celltype_list: list = [[]], 365 | infiltration_prop_list: list = [[]], 366 | background_celltype: list = [], 367 | background_prop: Optional[list] = None, 368 | center_x_list: list = [20, 10], 369 | center_y_list: list = [20, 10], 370 | a_list: list = [15, 20], 371 | b_list: list = [10, 15], 372 | theta_list: list = [np.pi / 4, np.pi / 4], 373 | ring_width_list: list = [[2, 3], [2]], 374 | hidden_size: int = 128, 375 | load_path: str = '', 376 | used_device: str = 'cuda:0'): 377 | 378 | spattern_generator = SPatternGeneratorCustom(sc_adata=sc_adata, cell_num=generate_cell_num, 379 | celltype_key=celltype_key, set_seed=set_seed, seed=seed, 380 | spatial_size=spatial_size, select_celltype=select_celltype) 381 | 382 | spatial_pattern = spattern_generator.simulate_ring(shape_list=shape_list, 383 | ring_celltype_list=ring_celltype_list, 384 | ring_purity_list=ring_purity_list, 385 | infiltration_celltype_list=infiltration_celltype_list, 386 | infiltration_prop_list=infiltration_prop_list, 387 | background_celltype=background_celltype, 388 | background_prop=background_prop, 389 | center_x_list=center_x_list, 390 | center_y_list=center_y_list, 391 | ring_width_list=ring_width_list, 392 | a_list=a_list, 393 | b_list=b_list, 394 | theta_list=theta_list) 395 | 396 | generate_sc_meta, generate_sc_data = self.__generate_custom_helper(sc_adata=sc_adata, 397 | spatial_pattern=spatial_pattern, 398 | celltype_key=celltype_key, 399 | cell_key=cell_key, 400 | hidden_size=hidden_size, 401 | load_path=load_path, 402 | used_device=used_device) 403 | 404 | return generate_sc_meta, generate_sc_data 405 | 406 | def generate_pattern_custom_stripes(self, 407 | sc_adata: AnnData, 408 | generate_cell_num: int = 5000, 409 | celltype_key: str = 'Cell_type', 410 | cell_key: str = 'Cell', 411 | set_seed: bool = False, 412 | seed: int = 12345, 413 | spatial_size: int = 30, 414 | select_celltype: Optional[list] = None, 415 | y1_list: list = [None, None], 416 | y2_list: list = [None, None], 417 | stripe_width_list: list = [2, 3], 418 | stripe_celltype_list: list = [], 419 | stripe_purity_list: list = [], 420 | infiltration_celltype_list: list = [[]], 421 | infiltration_prop_list: list = [[]], 422 | background_celltype: list = [], 423 | background_prop: Optional[list] = None, 424 | hidden_size: int = 128, 425 | load_path: str = '', 426 | used_device: str = 'cuda:0'): 427 | 428 | spattern_generator = SPatternGeneratorCustom(sc_adata=sc_adata, cell_num=generate_cell_num, 429 | celltype_key=celltype_key, set_seed=set_seed, seed=seed, 430 | spatial_size=spatial_size, select_celltype=select_celltype) 431 | 432 | spatial_pattern = spattern_generator.simulate_stripes(y1_list=y1_list, 433 | y2_list=y2_list, 434 | stripe_width_list=stripe_width_list, 435 | stripe_purity_list=stripe_purity_list, 436 | stripe_celltype_list=stripe_celltype_list, 437 | infiltration_celltype_list=infiltration_celltype_list, 438 | infiltration_prop_list=infiltration_prop_list, 439 | background_celltype=background_celltype, 440 | background_prop=background_prop) 441 | 442 | generate_sc_meta, generate_sc_data = self.__generate_custom_helper(sc_adata=sc_adata, 443 | spatial_pattern=spatial_pattern, 444 | celltype_key=celltype_key, 445 | cell_key=cell_key, 446 | hidden_size=hidden_size, 447 | load_path=load_path, 448 | used_device=used_device) 449 | 450 | return generate_sc_meta, generate_sc_data 451 | 452 | def generate_pattern_custom_complex(self, 453 | sc_adata: AnnData, 454 | spa_pattern_base: DataFrame, 455 | spa_pattern_add: DataFrame, 456 | celltype_key: str = 'Cell_type', 457 | cell_key: str = 'Cell', 458 | background_celltype: list = [], 459 | hidden_size: int = 128, 460 | load_path: str = '', 461 | used_device: str = 'cuda:0' 462 | ): 463 | 464 | assert spa_pattern_base.shape[0] == spa_pattern_add.shape[0], \ 465 | 'the row number of `spa_pattern_base` and `spa_pattern_add` should be same!' 466 | 467 | spatial_pattern1 = spa_pattern_add.copy() 468 | spatial_pattern2 = spa_pattern_base.copy() 469 | spatial_pattern1 = spatial_pattern1.sort_values(by=['point_x', 'point_y']) 470 | spatial_pattern2 = spatial_pattern2.sort_values(by=['point_x', 'point_y']) 471 | spatial_pattern1 = spatial_pattern1.reset_index() 472 | spatial_pattern2 = spatial_pattern2.reset_index() 473 | 474 | for i in range(spatial_pattern1.shape[0]): 475 | if spatial_pattern1.loc[i, celltype_key] in background_celltype and spatial_pattern2.loc[i, celltype_key] \ 476 | not in background_celltype: 477 | spatial_pattern1.loc[i, celltype_key] = spatial_pattern2.loc[i, celltype_key] 478 | 479 | generate_sc_meta, generate_sc_data = self.__generate_custom_helper(sc_adata=sc_adata, 480 | spatial_pattern=spatial_pattern1, 481 | celltype_key=celltype_key, 482 | cell_key=cell_key, 483 | hidden_size=hidden_size, 484 | load_path=load_path, 485 | used_device=used_device) 486 | 487 | return generate_sc_meta, generate_sc_data 488 | 489 | def generate_pattern_random(self, 490 | generate_sc_data: DataFrame, 491 | generate_sc_meta: DataFrame, 492 | celltype_key: str = 'Cell_type', 493 | set_seed: bool = False, 494 | seed: int = 12345, 495 | spatial_cell_type: Optional[list] = None, 496 | spatial_dim: int = 2, 497 | spatial_size: int = 30, 498 | delta: float = 25, 499 | lamda: float = 0.75, 500 | is_split: bool = True, 501 | split_coord: str = 'point_z', 502 | slice_num: int = 5, 503 | ): 504 | """ 505 | generate random spatial patterns of cells with default spatial autocorrelation function 506 | :param generate_sc_data: DataFrame of generated sc data 507 | :param generate_sc_meta: DataFrame of generated sc meta 508 | :param celltype_key: column name of celltype 509 | :param set_seed: whether to set seed for reproducible simulation 510 | :param seed: seed number 511 | :param spatial_cell_type: the selected cell types with spatial patterns, if`spatial_cell_type=None`, 512 | all cell types would be assigned spatial patterns 513 | :param spatial_dim: spatial dimensionality, `2` or `3` 514 | :param spatial_size: the scope for spatial autocorrelation function, larger value will yield finer spatial 515 | patterns, but also will take more running time 516 | :param delta: larger value will yield more continued spatial patterns 517 | :param lamda: 0-1, larger value will yield more clear spatial patterns 518 | :param is_split: whether to spilt the 3-D generated spatial patterns into a series of 2-D spatial patterns, 519 | only works when `spatial_dim=3` 520 | :param split_coord: the split coordinate axis, only works when `spatial_dim=3` and `is_split=True` 521 | :param slice_num: the targeted number of 2-D slices, only works when `spatial_dim=3` and `is_split=True` 522 | :return: generate_sc_data, generate_sc_meta_new 523 | """ 524 | 525 | spattern_generator = SPatternGenerator() 526 | generate_sc_meta_new = spattern_generator.run(generate_meta=generate_sc_meta, 527 | set_seed=set_seed, 528 | seed=seed, 529 | celltype_key=celltype_key, 530 | spatial_cell_type=spatial_cell_type, 531 | spatial_dim=spatial_dim, 532 | spatial_size=spatial_size, 533 | delta=delta, 534 | lamda=lamda) 535 | 536 | generate_sc_meta_new = generate_sc_meta_new.loc[generate_sc_data.columns, ] 537 | if spatial_dim == 3 and is_split: 538 | generate_sc_meta_new = self.__split_3d_coord(generate_sc_meta_new, 539 | split_coord=split_coord, 540 | n_slice=slice_num) 541 | 542 | return generate_sc_data, generate_sc_meta_new 543 | 544 | def generate_spot_data_random(self, 545 | generate_sc_data: DataFrame, 546 | generate_sc_meta: DataFrame, 547 | platform: str = 'ST', 548 | gene_type: str = 'whole', 549 | min_cell: int = 10, 550 | n_gene: Optional[int] = None, 551 | n_cell: int = 10, 552 | count_threshold: Optional[float] = None): 553 | 554 | """ 555 | generate spot-based data 556 | :param generate_sc_data: DataFrame of generated sc data 557 | :param generate_sc_meta: DataFrame of generated sc meta 558 | :param platform: only works when `is_spot=True`, `ST` -- square neighborhood structure; 559 | `Visium` -- hexagonal neighborhood structure; `Slide` -- random neighborhood structure 560 | :param gene_type: the type of genes to generate, `whole` -- the whole genes; 561 | `hvg` -- the highly variable genes; `marker` -- the marker genes of each cell type; 562 | `random` -- the randomly selected genes 563 | :param min_cell: filter the genes expressed in fewer than `min_cell` cells before selected genes, 564 | only works when `gene_type='random', 'hvg', or 'marker'` 565 | :param n_gene: the number of genes to select, only works when `gene_type='random', 'hvg', or 'marker'` 566 | :param n_cell: the mean number of cells per spot 567 | :param count_threshold: sparsity calibration, reset the expression values below this threshold to zero 568 | :return: st_data, st_meta, st_index 569 | """ 570 | 571 | st_data, st_meta, st_index = generate_spot_data(generate_meta=generate_sc_meta, 572 | generate_data=generate_sc_data, 573 | spatial_dim=2, 574 | platform=platform, 575 | gene_type=gene_type, 576 | min_cell=min_cell, 577 | n_gene=n_gene, 578 | n_cell=n_cell, 579 | count_threshold=count_threshold 580 | ) 581 | 582 | return st_data, st_meta, st_index 583 | 584 | def generate_image_data_random(self, 585 | generate_sc_data: DataFrame, 586 | generate_sc_meta: DataFrame, 587 | gene_type: str = 'whole', 588 | min_cell: int = 10, 589 | n_gene: Optional[int] = None, 590 | count_threshold: Optional[float] = None,): 591 | """ 592 | generate image-based data 593 | :param generate_sc_data: DataFrame of generated sc data 594 | :param generate_sc_meta: DataFrame of generated sc meta 595 | :param gene_type: the type of genes to generate, `whole` -- the whole genes; 596 | `hvg` -- the highly variable genes; `marker` -- the marker genes of each cell type; 597 | `random` -- the randomly selected genes 598 | :param min_cell: filter the genes expressed in fewer than `min_cell` cells before selected genes, 599 | only works when `gene_type='random', 'hvg', or 'marker'` 600 | :param n_gene: the number of genes to select, only works when `gene_type='random', 'hvg', or 'marker'` 601 | :param count_threshold: sparsity calibration, reset the expression values below this threshold to zero 602 | :return: st_data, st_meta, st_index 603 | """ 604 | 605 | st_data, st_meta, st_index = generate_image_data(generate_meta=generate_sc_meta, 606 | generate_data=generate_sc_data, 607 | gene_type=gene_type, 608 | min_cell=min_cell, 609 | n_gene=n_gene, 610 | count_threshold=count_threshold 611 | ) 612 | 613 | return st_data, st_meta, st_index 614 | 615 | def generate_subtype_pattern_random(self, 616 | generate_sc_data: DataFrame, 617 | generate_sc_meta: DataFrame, 618 | set_seed: bool = False, 619 | seed: int = 12345, 620 | celltype_key: str = 'Cell_type', 621 | select_cell_type: str = '', 622 | subtype_key: str = '', 623 | spatial_dim: int = 2, 624 | subtype_delta: float = 25, 625 | ): 626 | """ 627 | generate spatial pattern for specific subtypes 628 | :param generate_sc_data: DataFrame of generated sc data 629 | :param generate_sc_meta: DataFrame of generated sc meta 630 | :param set_seed: whether to set seed for reproducible simulation 631 | :param seed: seed number 632 | :param celltype_key: column name of celltype 633 | :param select_cell_type: the select cell types to generate subtype spatial patterns 634 | :param subtype_key: columns of subtype 635 | :param spatial_dim: spatial dimensionality, `2` or `3` 636 | :param subtype_delta: spatial pattern delta, large--big spatial pattern 637 | :return: generate_sc_data_sub, generate_sc_meta_sub 638 | """ 639 | 640 | spattern_generator = SPatternGeneratorSubtype() 641 | generate_sc_meta_sub = spattern_generator.run(generate_meta=generate_sc_meta, 642 | set_seed=set_seed, 643 | seed=seed, 644 | celltype_key=celltype_key, 645 | select_cell_type=select_cell_type, 646 | subtype_key=subtype_key, 647 | spatial_dim=spatial_dim, 648 | delta=subtype_delta) 649 | 650 | generate_sc_data_sub = generate_sc_data[generate_sc_meta_sub.index] 651 | 652 | return generate_sc_data_sub, generate_sc_meta_sub 653 | 654 | def generate_pattern_reference(self, 655 | sc_adata: AnnData, 656 | generate_sc_data: DataFrame, 657 | generate_sc_meta: DataFrame, 658 | celltype_key: list, 659 | spatial_key: list, 660 | cost_metric: str = 'sqeuclidean'): 661 | """ 662 | generate real spatial patterns of cells based on ST data 663 | :param sc_adata: AnnData of data 664 | :param generate_sc_data: DataFrame of generated sc data 665 | :param generate_sc_meta: DataFrame of generated sc meta 666 | :param celltype_key: the column name of `cell type` in meta 667 | :param spatial_key: the column name of `spatial coordinates` in meta 668 | :param cost_metric: the cost distance between generate_sc_data and real_data, `sqeuclidean` by default. 669 | On numpy the function also accepts from the scipy.spatial.distance.cdist function : ‘braycurtis’, ‘canberra’, ‘ 670 | chebyshev’, ‘cityblock’, ‘correlation’, ‘cosine’, ‘dice’, ‘euclidean’, ‘hamming’, ‘jaccard’, ‘kulsinski’, 671 | ‘mahalanobis’, ‘matching’, ‘minkowski’, ‘rogerstanimoto’, ‘russellrao’, ‘seuclidean’, ‘sokalmichener’, 672 | ‘sokalsneath’, ‘sqeuclidean’, ‘wminkowski’, ‘yule’. 673 | :return: generate_sc_data, generate_sc_meta 674 | """ 675 | 676 | # real_data = sc_adata.X 677 | # generate_data = np.array(generate_sc_data.T) 678 | real_meta = sc_adata.obs 679 | 680 | coord = pd.DataFrame() 681 | for i in list(set(real_meta[celltype_key])): 682 | sc_adata_tmp = sc_adata[sc_adata.obs[celltype_key].isin([i])] 683 | real_data_tmp = np.array(sc_adata_tmp.X) 684 | real_meta_tmp = sc_adata_tmp.obs 685 | 686 | generate_meta_tmp = generate_sc_meta.loc[generate_sc_meta['Cell_type'] == i] 687 | generate_meta_tmp.set_index('Cell') 688 | generate_data_tmp = generate_sc_data.iloc[:, generate_meta_tmp.index] 689 | generate_data_tmp = np.array(generate_data_tmp.T) 690 | 691 | m = real_data_tmp.shape[0] 692 | n = generate_data_tmp.shape[0] 693 | a, b = np.ones((m,)) / m, np.ones((n,)) / n # uniform distribution on samples 694 | 695 | # loss matrix 696 | M = ot.dist(real_data_tmp, generate_data_tmp, metric=cost_metric) 697 | 698 | G = ot.emd(a, b, M) 699 | 700 | x_new = [] 701 | y_new = [] 702 | for i in range(n): 703 | x_tmp = real_meta_tmp.loc[real_meta_tmp.index[G[:, i].argmax()]][spatial_key[0]] 704 | y_tmp = real_meta_tmp.loc[real_meta_tmp.index[G[:, i].argmax()]][spatial_key[1]] 705 | x_new.append(x_tmp) 706 | y_new.append(y_tmp) 707 | 708 | coord_new = pd.DataFrame({spatial_key[0]: x_new, spatial_key[1]: y_new}, index=generate_meta_tmp.index) 709 | # TODO:pandas2.0 append is deprecated, 710 | # change to `coord = pd.concat([coord, pd.DataFrame([coord_new])], ignore_index=True)` 711 | coord = coord.append(coord_new) 712 | 713 | coord = coord.loc[generate_sc_meta.index,] 714 | generate_sc_meta = pd.concat([generate_sc_meta, coord], axis=1, join='outer') 715 | 716 | return generate_sc_data, generate_sc_meta 717 | 718 | def __parpare_generate(self, 719 | sc_adata: AnnData, 720 | celltype_key: str = 'Cell_type', 721 | cell_key: str = 'Cell', 722 | target_num: Optional[dict] = None, 723 | ): 724 | 725 | single_cell = sc_adata.X 726 | 727 | index_2_gene = sc_adata.var_names.tolist() 728 | feature_size = single_cell.shape[1] 729 | 730 | breed = sc_adata.obs[celltype_key] 731 | breed_np = breed.values 732 | breed_set = set(breed_np) 733 | breed_2_list = list(breed_set) 734 | # sort by the first letter of the cell type to sure that the target_num is consistent with the breed_2_list 735 | breed_2_list = sorted(breed_2_list) 736 | dic = {} 737 | label = [] 738 | 739 | for i in range(len(breed_set)): 740 | dic[breed_2_list[i]] = i 741 | 742 | cell = sc_adata.obs[cell_key].values 743 | for i in range(cell.shape[0]): 744 | label.append(dic[breed_np[i]]) 745 | 746 | label = np.array(label) 747 | 748 | if target_num is None: 749 | print("generating by the proportion of cell types of the input scRNA-seq data...") 750 | cell_target_num = dict(Counter(breed_np)) 751 | else: 752 | print("generating by the targeted proportion of cell types...") 753 | cell_target_num = target_num 754 | input_breed_2_list = sorted(list(cell_target_num.keys())) 755 | assert input_breed_2_list == breed_2_list, \ 756 | "the cell type in targeted number list isn't same as it in scRNA-seq meta file!!!" 757 | 758 | # label index the data size of corresponding target 759 | cell_number_target_num = {} 760 | for k, v in cell_target_num.items(): 761 | cell_number_target_num[dic[k]] = v 762 | 763 | res_list = [] 764 | res_list.extend((feature_size, single_cell, label, breed_2_list, index_2_gene, cell_number_target_num, dic)) 765 | 766 | return res_list 767 | 768 | def __split_3d_coord(self, 769 | obj: DataFrame, 770 | split_coord: str = 'point_x', 771 | n_slice: int = 10, 772 | ): 773 | """ 774 | Split 3d coordinates to n 2d-slices 775 | :param obj: DataFrame of meta 776 | :param split_coord: The coordinate to split 777 | :param n_slice: The number of slices to split 778 | :return: New DataFrame with slice information 779 | """ 780 | min_range = int(np.floor(obj[split_coord].min())) 781 | max_range = int(np.ceil(obj[split_coord].max())) 782 | grid_seq = [i / n_slice for i in range(min_range, int(max_range * (n_slice + 1)), max_range)] 783 | 784 | obj['slice'] = "unassigned" 785 | for i in range(0, obj.shape[0]): 786 | x = obj.loc[obj.index[i], split_coord] 787 | obj.iloc[i, 5] = get_min_grid_index(select_min_grid(x, grid_seq), grid_seq) 788 | 789 | return obj 790 | 791 | def __generate_custom_helper(self, 792 | sc_adata: AnnData, 793 | spatial_pattern: DataFrame, 794 | celltype_key: str = 'Cell_type', 795 | cell_key: str = 'Cell', 796 | hidden_size: int = 128, 797 | load_path: str = '', 798 | used_device: str = 'cuda:0' 799 | ): 800 | celltype_list = list(set(sc_adata.obs[celltype_key])) 801 | target_num = spatial_pattern[celltype_key].value_counts().reindex(celltype_list, fill_value=0).to_dict() 802 | res_list = self.__parpare_generate(sc_adata, celltype_key, cell_key, target_num) 803 | 804 | print(f'loading model from {load_path}') 805 | # ********************* loading ********************* 806 | net = load_vae(res_list, 807 | hidden_size=hidden_size, 808 | load_path=load_path, 809 | used_device=used_device) 810 | print('vae loading done!') 811 | 812 | # ********************* generating ********************* 813 | generate_sc_meta, generate_sc_data = generate_vae(net, res_list, used_device=used_device) 814 | generate_sc_meta = generate_sc_meta.sort_values(celltype_key) 815 | spatial_pattern = spatial_pattern.sort_values(celltype_key) 816 | generate_sc_meta['point_x'] = spatial_pattern['point_x'].values 817 | generate_sc_meta['point_y'] = spatial_pattern['point_y'].values 818 | generate_sc_data = generate_sc_data[generate_sc_meta[cell_key]] 819 | 820 | return generate_sc_meta, generate_sc_data 821 | -------------------------------------------------------------------------------- /scCube/visualization.py: -------------------------------------------------------------------------------- 1 | import operator 2 | 3 | import matplotlib.colors as clr 4 | import matplotlib.pyplot as plt 5 | import pandas as pd 6 | import numpy as np 7 | from pandas import DataFrame 8 | from typing import Optional, Tuple, Sequence, Union 9 | import seaborn as sns 10 | 11 | 12 | def plot_spatial_pattern_scatter( 13 | obj: DataFrame, 14 | figwidth: float = 8, 15 | figheight: float = 8, 16 | dim: int = 2, 17 | x: str = "point_x", 18 | y: str = "point_y", 19 | z: Optional[str] = None, 20 | label: Optional[str] = None, 21 | palette: Optional[list] = None, 22 | colormap: str = 'rainbow', 23 | size: float = 10, 24 | alpha: float = 1, 25 | ): 26 | """ 27 | Plot scatter plot of cell type spatial pattern 28 | :param obj: DataFrame of meta 29 | :param figwidth: Figure width 30 | :param figheight: Figure height 31 | :param dim: Spatial dimensionality 32 | :param x: The name of column containing x coordinate 33 | :param y: The name of column containing y coordinate 34 | :param z: The name of column containing z coordinate, only use when 'dim = 3' 35 | :param label: The name of column containing cell type information, if 'label == None', plot coordinates without 36 | cell type information only 37 | :param palette: List of colors used, if 'palette == None', plot scatter plot with colormap colors 38 | :param colormap: The name of cmap 39 | :param size: The size of point 40 | :param alpha: The transparency of point 41 | :return: fig 42 | """ 43 | 44 | if label is None: 45 | if dim == 2: 46 | fig, ax = plt.subplots(figsize=(figwidth, figheight)) 47 | ax.scatter( 48 | obj[x], 49 | obj[y], 50 | s=size, 51 | alpha=alpha) 52 | ax.set_xlabel(x) 53 | ax.set_ylabel(y) 54 | elif dim == 3: 55 | fig = plt.figure(figsize=(figwidth, figheight)) 56 | ax = fig.add_subplot(projection='3d') 57 | ax.scatter( 58 | obj[x], 59 | obj[y], 60 | obj[z], 61 | s=size, 62 | alpha=alpha) 63 | ax.set_xlabel(x) 64 | ax.set_ylabel(y) 65 | ax.set_zlabel(z) 66 | plt.title("Spatial coordinates of generated data") 67 | 68 | else: 69 | label_list = sorted(list(obj[label].unique())) 70 | if palette is None: 71 | color_map = plt.cm.get_cmap(colormap, len(label_list)) 72 | palette = [clr.rgb2hex(color_map(i)) for i in range(color_map.N)] 73 | else: 74 | assert len(palette) >= len(label_list), "The number of colors provided is too few!!" 75 | 76 | if dim == 2: 77 | fig, ax = plt.subplots(figsize=(figwidth, figheight)) 78 | for i in range(len(label_list)): 79 | ax.scatter( 80 | obj.loc[obj[label] == label_list[i], x], 81 | obj.loc[obj[label] == label_list[i], y], 82 | color=palette[i], 83 | label=label_list[i], 84 | s=size, 85 | alpha=alpha) 86 | 87 | ax.set_xlabel(x) 88 | ax.set_ylabel(y) 89 | 90 | elif dim == 3: 91 | fig = plt.figure(figsize=(figwidth, figheight)) 92 | ax = fig.add_subplot(projection='3d') 93 | for i in range(len(label_list)): 94 | ax.scatter( 95 | obj.loc[obj[label] == label_list[i], x], 96 | obj.loc[obj[label] == label_list[i], y], 97 | obj.loc[obj[label] == label_list[i], z], 98 | color=palette[i], 99 | label=label_list[i], 100 | s=size, 101 | alpha=alpha) 102 | 103 | ax.set_xlabel(x) 104 | ax.set_ylabel(y) 105 | ax.set_zlabel(z) 106 | 107 | plt.title("Spatial pattern of generated data") 108 | plt.legend(bbox_to_anchor=(1, 0.5), loc='center left', 109 | ncol=(1 if len(label_list) <= 14 else 2 if len(label_list) <= 30 else 3), frameon=False) 110 | 111 | return fig 112 | 113 | 114 | def plot_spatial_pattern_density( 115 | obj: DataFrame, 116 | figwidth: float = 8, 117 | figheight: float = 8, 118 | x: str = "point_x", 119 | y: str = "point_y", 120 | show_celltype: Optional[str] = None, 121 | label: str = "Cell_type", 122 | colormap: str = 'Blues', 123 | fill: bool = True, 124 | ): 125 | """ 126 | Plot density plot of cell type spatial pattern 127 | :param obj: DataFrame of meta 128 | :param figwidth: Figure width 129 | :param figheight: Figure height 130 | :param x: The name of column containing x coordinate 131 | :param y: The name of column containing y coordinate 132 | :param show_celltype: The cell type selected to plot separately, if 'show_celltype == None', 133 | plot all cell type together 134 | :param label: The name of column containing cell type information 135 | :param colormap: The name of cmap 136 | :param fill: If 'fill = True', fill in the area between bivariate contours 137 | :return: fig 138 | """ 139 | 140 | label_list = sorted(list(obj[label].unique())) 141 | if show_celltype is None: 142 | fig, axes = plt.subplots(2, int(np.ceil(len(label_list) / 2)), figsize=(figwidth, figheight)) 143 | palette = sns.color_palette(colormap, len(label_list)) 144 | for ax, s, ct in zip(axes.flat, palette, label_list): 145 | # Create a cubehelix colormap to use with kdeplot 146 | # colormap = sns.cubehelix_palette(start=s, light=1, as_cmap=True) 147 | colormap = sns.light_palette(s, as_cmap=True) 148 | 149 | x_new = obj.loc[obj[label] == ct, x] 150 | y_new = obj.loc[obj[label] == ct, y] 151 | 152 | sns.kdeplot( 153 | x=x_new, 154 | y=y_new, 155 | cmap=colormap, 156 | fill=fill, 157 | ax=ax, 158 | ) 159 | ax.set_title(ct) 160 | plt.tight_layout() 161 | plt.suptitle('The density of each cell type', fontsize=16, y=1) 162 | 163 | else: 164 | assert show_celltype in label_list, "The selected cell type does not exist!!" 165 | fig = sns.jointplot( 166 | data=obj.loc[obj[label] == show_celltype, ], 167 | x=x, 168 | y=y, 169 | kind='kde', 170 | cmap=colormap, 171 | fill=fill, 172 | height=figheight, 173 | width=figwidth) 174 | 175 | fig.fig.suptitle('The density of ' + show_celltype, fontsize=16, y=1.05) 176 | 177 | return fig 178 | 179 | 180 | def get_palette(categories, cmap): 181 | """ 182 | Generate dictionary mapping categories to color. 183 | """ 184 | cc = plt.cm.get_cmap(cmap, len(categories)) 185 | colors = [clr.rgb2hex(cc(i)) for i in range(cc.N)] 186 | cmap_new = clr.ListedColormap(colors) 187 | palette = {x: cmap_new(i) for i, x in enumerate(categories)} 188 | return palette 189 | 190 | 191 | # https://github.com/racng/scatterpie 192 | def pie_marker( 193 | ratios: Sequence[float], 194 | res: int = 50, 195 | direction: str = "+", 196 | start: float = 0.0, 197 | ) -> Tuple[list, list]: 198 | """ 199 | Create each slice of pie as a separate marker. 200 | Parameters: 201 | ratios(list): List of ratios that add up to 1. 202 | res: Number of points around the circle. 203 | direction: '+' for counter-clockwise, or '-' for clockwise. 204 | start: Starting position in radians. 205 | Returns: 206 | xys, ss: Tuple of list of xy points and sizes of each slice in the pie marker. 207 | """ 208 | 209 | if np.abs(np.sum(ratios) - 1) > 0.01: 210 | print("Warning: Ratios do not add up to 1.") 211 | 212 | if direction == '+': 213 | op = operator.add 214 | elif direction == '-': 215 | op = operator.sub 216 | 217 | xys = [] # list of xy points of each slice 218 | ss = [] # list of size of each slice 219 | start = float(start) 220 | for ratio in ratios: 221 | # points on the circle including the origin (0,0) and the slice 222 | end = op(start, 2 * np.pi * ratio) 223 | n = round(ratio * res) # number of points forming the arc 224 | x = [0] + np.cos(np.linspace(start, end, n)).tolist() 225 | y = [0] + np.sin(np.linspace(start, end, n)).tolist() 226 | xy = np.column_stack([x, y]) 227 | xys.append(xy) 228 | ss.append(np.abs(xy).max()) 229 | start = end 230 | 231 | return xys, ss 232 | 233 | 234 | def plot_spot_scatterpie( 235 | obj: DataFrame, 236 | figwidth: float = 8, 237 | figheight: float = 8, 238 | x: str = "spot_x", 239 | y: str = "spot_y", 240 | # cols: Optional[list] = None, 241 | palette: Optional[dict] = None, 242 | colormap: str = 'rainbow', 243 | res: int = 50, 244 | direction: str = "+", 245 | start: float = 0.0, 246 | size=100, 247 | edgecolor="none", 248 | ): 249 | """ 250 | Plot scatterpie plot of spot-based data 251 | :param obj: DataFrame of cell type proportion per spot 252 | :param figwidth: Figure width 253 | :param figheight: Figure height 254 | :param x: The name of column containing x coordinate 255 | :param y: The name of column containing y coordinate 256 | :param palette: Dict of color of each cell type, if 'palette == None', plot scatterpie plot with colormap colors 257 | :param colormap: The name of cmap 258 | :param res: Number of points around the circle 259 | :param direction: '+' for counter-clockwise, or '-' for clockwise 260 | :param start: Starting position in radians 261 | :param size: The size of point 262 | :param edgecolor: The edge color of point 263 | :return: ax 264 | """ 265 | 266 | # make copy of dataframe and set xy as index 267 | obj = obj.copy().set_index([x, y]) 268 | label_list = obj.columns 269 | obj = obj.reset_index() 270 | 271 | if palette is None: 272 | palette = get_palette(label_list, colormap) 273 | 274 | ratios = obj[label_list].to_records(index=False).tolist() 275 | colors = [palette[cat] for cat in label_list] 276 | 277 | _, ax = plt.subplots(figsize=(figwidth, figheight)) 278 | # make pie marker for each unique set of ratios 279 | df = pd.DataFrame({'x': obj[x].values, 'y': obj[y].values, 'ratios': ratios}) 280 | df.ratios = df.ratios.apply(tuple) 281 | gb = df.groupby("ratios") 282 | for ratio in gb.groups: 283 | group = gb.get_group(ratio) 284 | xys, ss = pie_marker(ratio, res=res, direction=direction, start=start) 285 | for xy, s, color in zip(xys, ss, colors): 286 | # plot non-zero slices 287 | if s != 0: 288 | ax.scatter(group.x, group.y, marker=xy, s=[s * s * size], facecolor=color, edgecolor=edgecolor) 289 | 290 | handles = [plt.scatter([], [], color=palette[i], label=i) for i in label_list] 291 | ax.legend(handles=handles, bbox_to_anchor=(1, 0.5), loc='center left', 292 | ncol=(1 if len(label_list) <= 14 else 2 if len(label_list) <= 30 else 3), borderaxespad=0, frameon=False) 293 | 294 | return ax 295 | 296 | 297 | def plot_spot_prop( 298 | obj: DataFrame, 299 | figwidth: float = 8, 300 | figheight: float = 8, 301 | x: str = "spot_x", 302 | y: str = "spot_y", 303 | colormap: str = 'viridis', 304 | show_celltype: Union[list, str] = "", 305 | size=100, 306 | alpha=1, 307 | ): 308 | """ 309 | Plot scatter plot of proportion of selected cell type 310 | :param obj: DataFrame of cell type proportion per spot 311 | :param figwidth: Figure width 312 | :param figheight: Figure height 313 | :param x: The name of column containing x coordinate 314 | :param y: The name of column containing y coordinate 315 | :param colormap: The name of cmap 316 | :param show_celltype: The cell type selected to plot 317 | :param size: The size of point 318 | :param alpha: The transparency of point 319 | :return: fig 320 | """ 321 | 322 | x_new = obj[x] 323 | y_new = obj[y] 324 | if type(show_celltype) == str: 325 | cell_type = obj[show_celltype] 326 | fig, ax = plt.subplots(figsize=(figwidth, figheight)) 327 | g = ax.scatter(x_new, y_new, s=size, cmap=colormap, c=cell_type, alpha=alpha) 328 | ax.set_xlabel(x) 329 | ax.set_ylabel(y) 330 | ax.set_title(show_celltype) 331 | fig.colorbar(g) 332 | 333 | elif type(show_celltype) == list: 334 | cell_type_list = sorted(show_celltype) 335 | 336 | fig, axes = plt.subplots(1, len(cell_type_list), figsize=(figwidth, figheight)) 337 | 338 | for i in range(len(cell_type_list)): 339 | cell_type_tmp = obj[cell_type_list[i]] 340 | g = axes[i].scatter(x_new, y_new, s=size, cmap=colormap, c=cell_type_tmp, alpha=alpha) 341 | axes[i].set_xlabel(x) 342 | axes[i].set_ylabel(y) 343 | axes[i].set_title(cell_type_list[i]) 344 | fig.colorbar(g, ax=axes[i]) 345 | 346 | plt.tight_layout() 347 | 348 | return g 349 | 350 | 351 | def plot_gene_scatter( 352 | data: DataFrame, 353 | obj: DataFrame, 354 | figwidth: float = 8, 355 | figheight: float = 8, 356 | dim: int = 2, 357 | label: str = 'Cell', 358 | normalize: bool = True, 359 | x: str = "point_x", 360 | y: str = "point_y", 361 | z: str = "point_z", 362 | show_gene: str = "", 363 | colormap: str = 'viridis', 364 | size: float = 10, 365 | alpha: float = 1 366 | ): 367 | """ 368 | Plot scatter plot of spatial expression pattern of selected gene 369 | :param data: DataFrame of data 370 | :param obj: DataFrame of meta 371 | :param figwidth: Figure width 372 | :param figheight: Figure height 373 | :param dim: Spatial dimensionality 374 | :param label: The name of column containing cell/spot name 375 | :param normalize: If 'normalize = True', normalizing expression value to [0, 1] 376 | :param x: The name of column containing x coordinate 377 | :param y: The name of column containing y coordinate 378 | :param z: The name of column containing z coordinate 379 | :param show_gene: The gene selected to plot 380 | :param colormap: The name of cmap 381 | :param size: The size of point 382 | :param alpha: The transparency of point 383 | :return: fig 384 | """ 385 | 386 | obj.index = list(obj[label]) 387 | gene_exp = np.array(data.T[show_gene]) 388 | 389 | if normalize: 390 | gene_exp = (gene_exp - gene_exp.min()) / (gene_exp.max() - gene_exp.min()) 391 | 392 | if dim == 2: 393 | fig, ax = plt.subplots(figsize=(figwidth, figheight)) 394 | 395 | x_new = obj[x] 396 | y_new = obj[y] 397 | g = ax.scatter(x_new, y_new, s=size, cmap=colormap, c=gene_exp, alpha=alpha) 398 | ax.set_xlabel(x) 399 | ax.set_ylabel(y) 400 | fig.colorbar(g) 401 | elif dim == 3: 402 | fig = plt.figure(figsize=(figwidth, figheight)) 403 | ax = fig.add_subplot(projection='3d') 404 | 405 | x_new = obj[x] 406 | y_new = obj[y] 407 | z_new = obj[z] 408 | g = ax.scatter(x_new, y_new, z_new, s=size, cmap=colormap, c=gene_exp, alpha=alpha) 409 | ax.set_xlabel(x) 410 | ax.set_ylabel(y) 411 | ax.set_zlabel(z) 412 | pos = ax.get_position() 413 | ax2 = fig.add_axes([pos.xmax + 0.25, pos.ymin, 0.03, 0.7 * (pos.ymax - pos.ymin)]) 414 | fig.colorbar(g, cax=ax2) 415 | 416 | plt.title(show_gene) 417 | plt.tight_layout() 418 | 419 | return g 420 | 421 | 422 | def plot_spot_histplot( 423 | obj: DataFrame, 424 | figwidth: float = 8, 425 | figheight: float = 8, 426 | label: str = 'spot', 427 | n_bins: int = 20 428 | ): 429 | """ 430 | Plot histplot of spot-based data to investigate cell number per spot 431 | :param obj: DataFrame of cell-spot index 432 | :param figwidth: Figure width 433 | :param figheight: Figure height 434 | :param label: The name of column containing spot name 435 | :param n_bins: The number of equal-width bins in the range 436 | :return: fig 437 | """ 438 | 439 | x = np.array(obj[label].value_counts()) 440 | mu = np.mean(x) 441 | sigma = np.std(x, ddof=1) 442 | 443 | fig, ax = plt.subplots(figsize=(figwidth, figheight)) 444 | # the histogram of the data 445 | n, bins, patches = ax.hist(x, n_bins, density=True) 446 | # # add a 'best fit' line 447 | # y = ((1 / (np.sqrt(2 * np.pi) * sigma)) * np.exp(-0.5 * (1 / sigma * (bins - mu)) ** 2)) 448 | # ax.plot(bins, y, '--') 449 | ax.set_xlabel('Cell number per spot') 450 | ax.set_ylabel('Density') 451 | ax.set_title(r'$\mu='+ str(round(mu, 2)) + '$, $\sigma='+ str(round(sigma, 2)) + '$') 452 | 453 | # Tweak spacing to prevent clipping of ylabel 454 | fig.tight_layout() 455 | 456 | return fig 457 | 458 | 459 | def plot_slice_scatter( 460 | obj: DataFrame, 461 | figwidth: float = 8, 462 | figheight: float = 8, 463 | x: str = "point_x", 464 | y: str = "point_y", 465 | label: str = 'Cell_type', 466 | palette: Optional[list] = None, 467 | colormap: str = 'rainbow', 468 | size: float = 10, 469 | alpha: float = 1 470 | ): 471 | """ 472 | Plot 2d scatter plot of cell type spatial pattern of each slices from 3d data 473 | :param obj: DataFrame of meta 474 | :param figwidth: Figure width 475 | :param figheight: Figure height 476 | :param x: The name of column containing x coordinate 477 | :param y: The name of column containing y coordinate 478 | :param label: The name of column containing cell type information 479 | :param palette: List of colors used, if 'palette == None', plot scatter plot with colormap colors 480 | :param colormap: The name of cmap 481 | :param size: The size of point 482 | :param alpha: The transparency of point 483 | :return: fig 484 | """ 485 | slice_id = sorted(list(np.unique(obj['slice'].values))) 486 | label_list = sorted(list(np.unique(obj[label].values))) 487 | if palette is None: 488 | color_map = plt.cm.get_cmap(colormap, len(label_list)) 489 | palette = [clr.rgb2hex(color_map(i)) for i in range(color_map.N)] 490 | else: 491 | assert len(palette) >= len(label_list), "The number of colors provided is too few!!" 492 | 493 | fig, axes = plt.subplots(1, len(slice_id), figsize=(figwidth, figheight)) 494 | 495 | for i in range(len(slice_id)): 496 | for j in range(len(label_list)): 497 | axes[i].scatter( 498 | obj.loc[(obj['slice'] == slice_id[i]) & (obj[label] == label_list[j]), x], 499 | obj.loc[(obj['slice'] == slice_id[i]) & (obj[label] == label_list[j]), y], 500 | color=palette[j], 501 | label=label_list[j], 502 | s=size, 503 | alpha=alpha) 504 | 505 | axes[i].set_xlabel(x) 506 | axes[i].set_ylabel(y) 507 | axes[i].set_title('Slice ' + str(slice_id[i])) 508 | 509 | plt.tight_layout() 510 | plt.legend(bbox_to_anchor=(1, 0.5), loc='center left', 511 | ncol=(1 if len(label_list) <= 14 else 2 if len(label_list) <= 30 else 3), borderaxespad=0, frameon=False) 512 | 513 | return fig 514 | 515 | 516 | def plot_slice_gene_scatter( 517 | data: DataFrame, 518 | obj: DataFrame, 519 | figwidth: float = 8, 520 | figheight: float = 8, 521 | x: str = "point_x", 522 | y: str = "point_y", 523 | label: str = 'Cell_type', 524 | normalize: bool = True, 525 | show_gene: str = "", 526 | colormap: str = 'viridis', 527 | size: float = 10, 528 | alpha: float = 1 529 | ): 530 | """ 531 | Plot 2d scatter plot of spatial expression pattern of selected gene of each slices from 3d data 532 | :param data: DataFrame of data 533 | :param obj: DataFrame of meta 534 | :param figwidth: Figure width 535 | :param figheight: Figure height 536 | :param x: The name of column containing x coordinate 537 | :param y: The name of column containing y coordinate 538 | :param label: The name of column containing cell type information 539 | :param normalize: If 'normalize = True', normalizing expression value to [0, 1] 540 | :param show_gene: The gene selected to plot 541 | :param colormap: The name of cmap 542 | :param size: The size of point 543 | :param alpha: The transparency of point 544 | :return: fig 545 | """ 546 | slice_id = sorted(list(np.unique(obj['slice'].values))) 547 | fig, axes = plt.subplots(1, len(slice_id), figsize=(figwidth, figheight)) 548 | 549 | for i in range(len(slice_id)): 550 | obj_new = obj.loc[obj['slice'] == slice_id[i], ] 551 | data_new = data.T.iloc[obj_new.index].T 552 | gene_exp = np.array(data_new.T[show_gene]) 553 | 554 | if normalize: 555 | gene_exp = (gene_exp - gene_exp.min()) / (gene_exp.max() - gene_exp.min()) 556 | 557 | x_new = obj_new[x] 558 | y_new = obj_new[y] 559 | g = axes[i].scatter(x_new, y_new, s=size, cmap=colormap, c=gene_exp, alpha=alpha) 560 | axes[i].set_xlabel(x) 561 | axes[i].set_ylabel(y) 562 | axes[i].set_title(show_gene + ' (Slice ' + str(slice_id[i]) + ')') 563 | fig.colorbar(g, ax=axes[i]) 564 | 565 | plt.tight_layout() 566 | 567 | return g 568 | 569 | 570 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | from setuptools import setup, find_packages 2 | 3 | 4 | setup( 5 | name="scCube", 6 | version="2.0.0", 7 | author='Jingyang Qian', 8 | author_email='qianjingyang@zju.edu.cn', 9 | url='https://github.com/ZJUFanLab/scCube', 10 | packages=find_packages(), 11 | install_requires=[], 12 | zip_safe=False, 13 | python_requires='>=3.8', 14 | license='GNU General Public License v3.0', 15 | ) 16 | 17 | 18 | -------------------------------------------------------------------------------- /tutorial/API.md: -------------------------------------------------------------------------------- 1 | ## API Reference 2 | ### Input data format (`.csv` or `.h5ad`) 3 | 4 | 1. Data file: a `.csv` file with genes as rows and cells/spots as column 5 | 6 | | |Cell1|Cell2|Cell3|...|CellN| 7 | | :-----: | :-----: | :-----: | :-----: | :-----: | :-----: | 8 | | Gene1 | 1 | 2 | 1 | ... | 0 | 9 | | Gene2 | 4 | 1 | 0 | ... | 4 | 10 | | ... | ... | ... | ... | ... | ... | 11 | | GeneN | 0 | 0 | 2 | ... | 0 | 12 | 13 | **** 14 | 2. Meta file: a `.csv` file with cell/spot ID and celltype/domain annotation columns 15 | * The column containing cell ID should be named `Cell` 16 | * the column containing the labels should be named `Cell_type` 17 | 18 | | |Cell|Cell_type| 19 | | :-----: | :-----: | :-----: | 20 | | Cell1 | Cell1 | T cell | 21 | | Cell2 | Cell2 | B cell | 22 | | ... | ... | ... | 23 | | CellN | CellN | Monocyte | 24 | 25 | **** 26 | 27 | ### Parameter description 28 | #### gene expression simulation functions: 29 | ##### pre-processing 30 | ```python 31 | import scCube 32 | from scCube import scCube 33 | from scCube.visualization import * 34 | from scCube.utils import * 35 | 36 | model = scCube() 37 | sc_adata = model.pre_process( 38 | sc_data=sc_data, 39 | sc_meta=sc_meta, 40 | is_normalized=False 41 | ) 42 | ``` 43 | **Parameters** 44 | 45 | **sc_data**: _DataFrame_ 46 | 47 |  DataFrame of input data 48 | 49 | **sc_meta**: _DataFrame_ 50 | 51 |  DataFrame of input meta 52 | 53 | **is_normalized**: _bool, default: `False`_ 54 | 55 |  Whether the input data is normalized or not. If `is_normalized=False`, the input data will be normalized by scCube first. 56 | 57 | **** 58 | 59 | ##### train vae model and generate gene expression 60 | ```python 61 | generate_sc_meta, generate_sc_data = model.train_vae_and_generate_cell( 62 | sc_adata=sc_adata, 63 | celltype_key='Cell_type', 64 | cell_key='Cell', 65 | target_num=None, 66 | batch_size=512, 67 | epoch_num=10000, 68 | lr=0.0001, 69 | hidden_size=128, 70 | save_model=True, 71 | save_path=save_path, 72 | project_name=model_name, 73 | used_device='cuda:0' 74 | ) 75 | ``` 76 | **Parameters** 77 | 78 | **sc_adata**: _AnnData_ 79 | 80 |  AnnData of pre-processed data 81 | 82 | **celltype_key**: _str_ 83 | 84 |  The column name of `cell labels` in meta 85 | 86 | **cell_key**: _str_ 87 | 88 |  The column name of `cell` in meta 89 | 90 | **target_num**: _Optional[dict], default: `None`_ 91 | 92 |  Target number of cells to generate, if `target_num=None`, generate cells by the proportion of cell types of the input data. 93 | 94 | **batch_size**: _int, default: `512`_ 95 | 96 |  Batch size of training 97 | 98 | **epoch_num**: _int, default: `10000`_ 99 | 100 |  Epoch number of training 101 | 102 | **lr**: _float, default: `0.0001`_ 103 | 104 |  Learning reta of training 105 | 106 | **hidden_size**: _int, default: `128`_ 107 | 108 |  Hidden size of VAE model 109 | 110 | **save_model**: _bool, default: `True`_ 111 | 112 |  Whether save trained VAE model or not 113 | 114 | **save_path**: _str_ 115 | 116 |  The save path 117 | 118 | **project_name**: _str_ 119 | 120 |  The name of trained VAE model 121 | 122 | **used_device**: _str, default: `cuda:0`_ 123 | 124 |  Device name, `cpu` or `cuda` 125 | 126 | **** 127 | 128 | ##### load VAE model and generate gene expression 129 | ```python 130 | generate_sc_meta, generate_sc_data = model.load_vae_and_generate_cell( 131 | sc_adata=sc_adata, 132 | celltype_key='Cell_type', 133 | cell_key='Cell', 134 | target_num=None, 135 | hidden_size=128, 136 | load_path=load_path, 137 | used_device='cuda:0' 138 | ) 139 | ``` 140 | **Parameters** 141 | 142 | **sc_adata**: _AnnData_ 143 | 144 |  AnnData of pre-processed data 145 | 146 | **celltype_key**: _str_ 147 | 148 |  The column name of `cell labels` in meta 149 | 150 | **cell_key**: _str_ 151 | 152 |  The column name of `cell` in meta 153 | 154 | **target_num**: _Optional[dict], default: `None`_ 155 | 156 |  Target number of cells to generate, if `target_num=None`, generate cells by the proportion of cell types of the input data. 157 | 158 | **hidden_size**: _int, default: `128`_ 159 | 160 |  Hidden size of VAE model 161 | 162 | **load_path**: _str_ 163 | 164 |  The load path 165 | 166 | **used_device**: _str, default: `cuda:0`_ 167 | 168 |  Device name, `cpu` or `cuda` 169 | 170 | **** 171 | 172 | #### spatial pattern simulation functions: 173 | ##### generate random spatial patterns for cell types with reference-free strategy 174 | ```python 175 | generate_sc_data, generate_sc_meta = model.generate_pattern_random( 176 | generate_sc_data=generate_sc_data, 177 | generate_sc_meta=generate_sc_meta, 178 | celltype_key='Cell_type', 179 | set_seed=False, 180 | seed=12345, 181 | spatial_cell_type=None, 182 | spatial_dim=2, 183 | spatial_size=30, 184 | delta=25, 185 | lamda=0.75, 186 | is_split=True, 187 | split_coord='point_z', 188 | slice_num=5,) 189 | ``` 190 | **Parameters** 191 | 192 | **generate_sc_data**: _DataFrame_ 193 | 194 |  DataFrame of generated data 195 | 196 | **generate_sc_meta**: _DataFrame_ 197 | 198 |  DataFrame of generated meta 199 | 200 | **celltype_key**: _str_ 201 | 202 |  The column name of `cell labels` in meta 203 | 204 | **set_seed**: _bool, default: `False`_ 205 | 206 |  Whether to set seed for reproducible simulation 207 | 208 | **seed**: _int, default: `12345`_ 209 | 210 |  The seed number 211 | 212 | **spatial_cell_type**: _ Optional[list], default: `None`_ 213 | 214 |  The selected cell types with spatial patterns, if`spatial_cell_type=None`, all cell types would be assigned spatial patterns 215 | 216 | **spatial_dim**: _int, default: `2`_ 217 | 218 |  The spatial dimensionality, `2` or `3` 219 | 220 | **spatial_size**: _int, default: `30`_ 221 | 222 |  The scope for simulated spatial patterns, the large values will take more running time 223 | 224 | **delta**: _float, default: `25`_ 225 | 226 |  The larger value will tend to form spatial patterns with greater connectivity 227 | 228 | **lamda**: _float, default: `0.75`_ 229 | 230 |  The larger values will tend to form clearer spatial patterns 231 | 232 | **is_split**: _bool, default: `True`_ 233 | 234 |  Whether to spilt the 3D generated spatial patterns into a series of 2D spatial patterns, only works when `spatial_dim=3` 235 | 236 | **split_coord**: _str, default: `point_z`_ 237 | 238 |  The name of split coordinate axis, only works when `spatial_dim=3` and `is_split=True` 239 | 240 | **slice_num**: _int, default: `5`_ 241 | 242 |  The targeted number of 2D slices, only works when `spatial_dim=3` and `is_split=True` 243 | 244 | **** 245 | 246 | ##### generate random spatial patterns for cell subtypes with reference-free strategy 247 | ```python 248 | generate_sc_data_sub, generate_sc_meta_sub = model.generate_subtype_pattern_random( 249 | generate_sc_data=generate_sc_data, 250 | generate_sc_meta=generate_sc_meta, 251 | celltype_key='Cell_type', 252 | select_cell_type='', 253 | subtype_key='', 254 | set_seed=False, 255 | seed=12345, 256 | spatial_dim=2, 257 | subtype_delta=25,) 258 | ``` 259 | **Parameters** 260 | 261 | **generate_sc_data**: _DataFrame_ 262 | 263 |  DataFrame of generated data 264 | 265 | **generate_sc_meta**: _DataFrame_ 266 | 267 |  DataFrame of generated meta 268 | 269 | **celltype_key**: _str_ 270 | 271 |  The column name of `cell labels` in meta 272 | 273 | **select_cell_type**: _str_ 274 | 275 |  the select cell types to generate subtype spatial patterns 276 | 277 | **subtype_key**: _str_ 278 | 279 |  The column name of `cell sub-labels` in meta 280 | 281 | **set_seed**: _bool, default: `False`_ 282 | 283 |  Whether to set seed for reproducible simulation 284 | 285 | **seed**: _int, default: `12345`_ 286 | 287 |  The seed number 288 | 289 | **spatial_dim**: _int, default: `2`_ 290 | 291 |  The spatial dimensionality, `2` or `3` 292 | 293 | **subtype_delta**: _int, default: `25`_ 294 | 295 |  The larger value will tend to form spatial patterns with greater connectivity 296 | 297 | **** 298 | 299 | 300 | ##### generate spot-based SRT data with reference-free strategy by combined simulated gene expression profiles and spatial patterns 301 | ```python 302 | st_data, st_meta, st_index = model.generate_spot_data_random( 303 | generate_sc_data=generate_sc_data, 304 | generate_sc_meta=generate_sc_meta, 305 | platform='ST', 306 | gene_type='whole', 307 | min_cell=10, 308 | n_gene=None, 309 | n_cell=10,) 310 | ``` 311 | **Parameters** 312 | 313 | **generate_sc_data**: _DataFrame_ 314 | 315 |  DataFrame of generated data 316 | 317 | **generate_sc_meta**: _DataFrame_ 318 | 319 |  DataFrame of generated meta 320 | 321 | **platform**: _str, default: `ST`_ 322 | 323 |  Spot arrangement, `ST` -- square neighborhood structure; `Visium` -- hexagonal neighborhood structure; `Slide` -- random neighborhood structure 324 | 325 | **gene_type**: _str, default: `whole`_ 326 | 327 |  The type of genes to generate, `whole` -- the whole genes; `hvg` -- the highly variable genes; `marker` -- the marker genes of each cell type; `random` -- the randomly selected genes 328 | 329 | **min_cell**: _int, default: `10`_ 330 | 331 |  Filter the genes expressed in fewer than `min_cell` cells before selected genes, only works when `gene_type='random', 'hvg', or 'marker'` 332 | 333 | **n_gene**: _Optional[int], default: `None`_ 334 | 335 |  The number of genes to select, only works when `gene_type='random', 'hvg', or 'marker'` 336 | 337 | **n_cell**: _int, default: `10`_ 338 | 339 |  The average number of cells per spot, only works when `is_spot=True` 340 | **** 341 | 342 | ##### generate image-based SRT data with reference-free strategy by combined simulated gene expression profiles and spatial patterns 343 | ```python 344 | st_data, st_meta, st_index = model.generate_spot_data_random( 345 | generate_sc_data=generate_sc_data, 346 | generate_sc_meta=generate_sc_meta, 347 | gene_type='whole', 348 | min_cell=10, 349 | n_gene=None,) 350 | ``` 351 | **Parameters** 352 | 353 | **generate_sc_data**: _DataFrame_ 354 | 355 |  DataFrame of generated data 356 | 357 | **generate_sc_meta**: _DataFrame_ 358 | 359 |  DataFrame of generated meta 360 | 361 | **gene_type**: _str, default: `whole`_ 362 | 363 |  The type of genes to generate, `whole` -- the whole genes; `hvg` -- the highly variable genes; `marker` -- the marker genes of each cell type; `random` -- the randomly selected genes 364 | 365 | **min_cell**: _int, default: `10`_ 366 | 367 |  Filter the genes expressed in fewer than `min_cell` cells before selected genes, only works when `gene_type='random', 'hvg', or 'marker'` 368 | 369 | **n_gene**: _Optional[int], default: `None`_ 370 | 371 |  The number of genes to select, only works when `gene_type='random', 'hvg', or 'marker'` 372 | 373 | **** 374 | 375 | ##### generate customized spatial patterns for cell types with reference-free strategy (mixing patterns) 376 | ```python 377 | generate_sc_data, generate_sc_meta = model.generate_pattern_custom_mixing( 378 | sc_adata=sc_adata, 379 | generate_cell_num=5000, 380 | celltype_key='Cell_type', 381 | cell_key='Cell', 382 | set_seed=False, 383 | seed=12345, 384 | spatial_size=30, 385 | select_celltype=None, 386 | prop_list=None, 387 | hidden_size=128, 388 | load_path='', 389 | used_device=cuda:0,) 390 | ``` 391 | **Parameters** 392 | 393 | **sc_adata**: _AnnData_ 394 | 395 |  AnnData of reference data 396 | 397 | **generate_cell_num**: _int_ 398 | 399 |  cell number to generate 400 | 401 | **celltype_key**: _str_ 402 | 403 |  The column name of `cell labels` in `sc_adata.obs` 404 | 405 | **cell_key**: _str_ 406 | 407 |  The column name of `cell` in `sc_adata.obs` 408 | 409 | **set_seed**: _bool, default: `False`_ 410 | 411 |  Whether to set seed for reproducible simulation 412 | 413 | **seed**: _int, default: `12345`_ 414 | 415 |  The seed number 416 | 417 | **spatial_size**: _int, default: `30`_ 418 | 419 |  The scope for simulated spatial patterns 420 | 421 | **select_celltype**: _Optional[list], default: `None`_ 422 | 423 |  The selected cell types for simulation, if`select_celltype=None`, all cell types would be selected 424 | 425 | **prop_list**: _Optional[list], default: `None`_ 426 | 427 |  The proportion of selected cell types 428 | 429 | 430 | **hidden_size**: _int, default: `128`_ 431 | 432 |  Hidden size of VAE model 433 | 434 | **load_path**: _str_ 435 | 436 |  The load path 437 | 438 | **used_device**: _str, default: `cuda:0`_ 439 | 440 |  Device name, `cpu` or `cuda` 441 | **** 442 | 443 | ##### generate customized spatial patterns for cell types with reference-free strategy (clustered patterns) 444 | ```python 445 | generate_sc_data, generate_sc_meta = model.generate_pattern_custom_cluster( 446 | sc_adata=sc_adata, 447 | generate_cell_num=5000, 448 | celltype_key='Cell_type', 449 | cell_key='Cell', 450 | set_seed=False, 451 | seed=12345, 452 | spatial_size=30, 453 | select_celltype=None, 454 | shape_list=['Circle', 'Oval'], 455 | cluster_celltype_list=[], 456 | cluster_purity_list=[], 457 | infiltration_celltype_list=[[]], 458 | infiltration_prop_list=[[]], 459 | background_celltype=[], 460 | background_prop=None, 461 | center_x_list=[20, 10], 462 | center_y_list=[20, 10], 463 | a_list=[15, 20], 464 | b_list=[10, 15], 465 | theta_list=[np.pi / 4, np.pi / 4], 466 | scale_value_list=[4.8, 4.8], 467 | twist_value_list=[0.5, 0.5], 468 | hidden_size=128, 469 | load_path='', 470 | used_device='cuda:0') 471 | ``` 472 | **Parameters** 473 | 474 | **sc_adata**: _AnnData_ 475 | 476 |  AnnData of reference data 477 | 478 | **generate_cell_num**: _int_ 479 | 480 |  cell number to generate 481 | 482 | **celltype_key**: _str_ 483 | 484 |  The column name of `cell labels` in `sc_adata.obs` 485 | 486 | **cell_key**: _str_ 487 | 488 |  The column name of `cell` in `sc_adata.obs` 489 | 490 | **set_seed**: _bool, default: `False`_ 491 | 492 |  Whether to set seed for reproducible simulation 493 | 494 | **seed**: _int, default: `12345`_ 495 | 496 |  The seed number 497 | 498 | **spatial_size**: _int, default: `30`_ 499 | 500 |  The scope for simulated spatial patterns 501 | 502 | **select_celltype**: _Optional[list], default: `None`_ 503 | 504 |  The selected cell types for simulation, if`select_celltype=None`, all cell types would be selected 505 | 506 | **shape_list**: _list_ 507 | 508 |  The shapes for simulation, `Circle`, `Oval`, or `Irregular` 509 | 510 | **cluster_celltype_list**: _list_ 511 | 512 |  The selected cell types for clustered shapes, the length must be equal to `shape_list` 513 | 514 | **cluster_purity_list**: _list_ 515 | 516 |  The purity of each clustered shape 517 | 518 | **infiltration_celltype_list**: _list_ 519 | 520 |  The infiltrating cell types in each clustered shape 521 | 522 | **infiltration_prop_list**: _list_ 523 | 524 |  The proportion of each infiltrating cell type in each clustered shape 525 | 526 | **background_celltype**: _list_ 527 | 528 |  The cell types considered as background 529 | 530 | **background_prop**: _Optional[list], default: `None`_ 531 | 532 |  The proportion of cell types considered as background, if`background_prop=None`, each background cell type follows an equal proportion 533 | 534 | **center_x_list**: _list_ 535 | 536 |  The position of the center of each clustered shapes on the X-axis 537 | 538 | **center_y_list**: _list_ 539 | 540 |  The position of the center of each clustered shapes on the Y-axis 541 | 542 | **a_list**: _list_ 543 | 544 |  The major axis of each clustered shapes 545 | 546 | **b_list**: _list_ 547 | 548 |  The minor axis of each clustered shapes 549 | 550 | **theta_list**: _list_ 551 | 552 |  The direction of each clustered shapes 553 | 554 | **scale_value_list**: _list_ 555 | 556 |  The scale factor of each clustered shapes used to control the shape of each cluster, only works when shape is `irregualr` 557 | 558 | **twist_value_list**: _list_ 559 | 560 |  The twist degree of each clustered shapes used to control the shape of each cluster, only works when shape is `irregualr` 561 | 562 | **hidden_size**: _int, default: `128`_ 563 | 564 |  Hidden size of VAE model 565 | 566 | **load_path**: _str_ 567 | 568 |  The load path 569 | 570 | **used_device**: _str, default: `cuda:0`_ 571 | 572 |  Device name, `cpu` or `cuda` 573 | **** 574 | 575 | ##### generate customized spatial patterns for cell types with reference-free strategy (cell rings patterns) 576 | ```python 577 | generate_sc_data, generate_sc_meta = model.generate_pattern_custom_ring( 578 | sc_adata=sc_adata, 579 | generate_cell_num=5000, 580 | celltype_key='Cell_type', 581 | cell_key='Cell', 582 | set_seed=False, 583 | seed=12345, 584 | spatial_size=30, 585 | select_celltype=None, 586 | shape_list=['Circle', 'Oval'], 587 | ring_celltype_list=[], 588 | ring_purity_list=[], 589 | infiltration_celltype_list=[[]], 590 | infiltration_prop_list=[[]], 591 | background_celltype=[], 592 | background_prop=None, 593 | center_x_list=[20, 10], 594 | center_y_list=[20, 10], 595 | a_list=[15, 20], 596 | b_list=[10, 15], 597 | theta_list=[np.pi / 4, np.pi / 4], 598 | ring_width_list=[[2, 3], [2]], 599 | hidden_size=128, 600 | load_path='', 601 | used_device='cuda:0') 602 | ``` 603 | **Parameters** 604 | 605 | **sc_adata**: _AnnData_ 606 | 607 |  AnnData of reference data 608 | 609 | **generate_cell_num**: _int_ 610 | 611 |  cell number to generate 612 | 613 | **celltype_key**: _str_ 614 | 615 |  The column name of `cell labels` in `sc_adata.obs` 616 | 617 | **cell_key**: _str_ 618 | 619 |  The column name of `cell` in `sc_adata.obs` 620 | 621 | **set_seed**: _bool, default: `False`_ 622 | 623 |  Whether to set seed for reproducible simulation 624 | 625 | **seed**: _int, default: `12345`_ 626 | 627 |  The seed number 628 | 629 | **spatial_size**: _int, default: `30`_ 630 | 631 |  The scope for simulated spatial patterns 632 | 633 | **select_celltype**: _Optional[list], default: `None`_ 634 | 635 |  The selected cell types for simulation, if`select_celltype=None`, all cell types would be selected 636 | 637 | **shape_list**: _list_ 638 | 639 |  The shapes for simulation, `Circle`, `Oval`, or `Irregular` 640 | 641 | **ring_celltype_list**: _list_ 642 | 643 |  The selected cell types for cell rings shapes, the length must be equal to `shape_list` 644 | 645 | **ring_purity_list**: _list_ 646 | 647 |  The purity of each cell rings shape 648 | 649 | **infiltration_celltype_list**: _list_ 650 | 651 |  The infiltrating cell types in each cell rings shape 652 | 653 | **infiltration_prop_list**: _list_ 654 | 655 |  The proportion of each infiltrating cell type in each cell rings shape 656 | 657 | **background_celltype**: _list_ 658 | 659 |  The cell types considered as background 660 | 661 | **background_prop**: _Optional[list], default: `None`_ 662 | 663 |  The proportion of cell types considered as background, if`background_prop=None`, each background cell type follows an equal proportion 664 | 665 | **center_x_list**: _list_ 666 | 667 |  The position of the center of each cell rings shapes on the X-axis 668 | 669 | **center_y_list**: _list_ 670 | 671 |  The position of the center of each cell rings shapes on the Y-axis 672 | 673 | **a_list**: _list_ 674 | 675 |  The major axis of each cell rings shapes 676 | 677 | **b_list**: _list_ 678 | 679 |  The minor axis of each cell rings shapes 680 | 681 | **theta_list**: _list_ 682 | 683 |  The direction of each cell rings shapes 684 | 685 | **ring_width_list**: _list_ 686 | 687 |  The width of each cell rings shape 688 | 689 | **hidden_size**: _int, default: `128`_ 690 | 691 |  Hidden size of VAE model 692 | 693 | **load_path**: _str_ 694 | 695 |  The load path 696 | 697 | **used_device**: _str, default: `cuda:0`_ 698 | 699 |  Device name, `cpu` or `cuda` 700 | **** 701 | 702 | ##### generate customized spatial patterns for cell types with reference-free strategy (stripes patterns) 703 | ```python 704 | generate_sc_data, generate_sc_meta = model.generate_pattern_custom_stripes( 705 | sc_adata=sc_adata, 706 | generate_cell_num=5000, 707 | celltype_key='Cell_type', 708 | cell_key='Cell', 709 | set_seed=False, 710 | seed=12345, 711 | spatial_size=30, 712 | select_celltype=None, 713 | y1_list=[None, None], 714 | y2_list=[None, None], 715 | stripe_width_list=[2, 3], 716 | stripe_purity_list=[], 717 | infiltration_celltype_list=[[]], 718 | infiltration_prop_list=[[]], 719 | background_celltype=[], 720 | background_prop=None, 721 | hidden_size=128, 722 | load_path='', 723 | used_device='cuda:0') 724 | ``` 725 | **Parameters** 726 | 727 | **sc_adata**: _AnnData_ 728 | 729 |  AnnData of reference data 730 | 731 | **generate_cell_num**: _int_ 732 | 733 |  cell number to generate 734 | 735 | **celltype_key**: _str_ 736 | 737 |  The column name of `cell labels` in `sc_adata.obs` 738 | 739 | **cell_key**: _str_ 740 | 741 |  The column name of `cell` in `sc_adata.obs` 742 | 743 | **set_seed**: _bool, default: `False`_ 744 | 745 |  Whether to set seed for reproducible simulation 746 | 747 | **seed**: _int, default: `12345`_ 748 | 749 |  The seed number 750 | 751 | **spatial_size**: _int, default: `30`_ 752 | 753 |  The scope for simulated spatial patterns 754 | 755 | **select_celltype**: _Optional[list], default: `None`_ 756 | 757 |  The selected cell types for simulation, if`select_celltype=None`, all cell types would be selected 758 | 759 | **y1_list**: _list_ 760 | 761 |  The endpoints of simulated stripes, if `y1_list=[None]`, scCube would choose endpoints randomly in the scope of spatial patterns 762 | 763 | **y2_list**: _list_ 764 | 765 |  The endpoints of simulated stripes, if `y2_list=[None]`, scCube would choose endpoints randomly in the scope of spatial patterns 766 | 767 | **stripe_celltype_list**: _list_ 768 | 769 |  The selected cell types for stripe shapes, the length must be equal to `y1_list` or `y2_list` 770 | 771 | **stripe_width_list**: _list_ 772 | 773 |  The width for each stripe shape, the length must be equal to `stripe_celltype_list` 774 | 775 | **stripe_purity_list**: _list_ 776 | 777 |  The purity of each stripe shape 778 | 779 | **infiltration_celltype_list**: _list_ 780 | 781 |  The infiltrating cell types in each stripe shape 782 | 783 | **infiltration_prop_list**: _list_ 784 | 785 |  The proportion of each infiltrating cell type in each stripe shape 786 | 787 | **background_celltype**: _list_ 788 | 789 |  The cell types considered as background 790 | 791 | **background_prop**: _Optional[list], default: `None`_ 792 | 793 |  The proportion of cell types considered as background, if`background_prop=None`, each background cell type follows an equal proportion 794 | 795 | **hidden_size**: _int, default: `128`_ 796 | 797 |  Hidden size of VAE model 798 | 799 | **load_path**: _str_ 800 | 801 |  The load path 802 | 803 | **used_device**: _str, default: `cuda:0`_ 804 | 805 |  Device name, `cpu` or `cuda` 806 | **** 807 | 808 | ##### generate customized spatial patterns for cell types with reference-free strategy (complex patterns) 809 | ```python 810 | generate_sc_data, generate_sc_meta = model.generate_pattern_custom_complex( 811 | sc_adata=sc_adata, 812 | spa_pattern_base, 813 | spa_pattern_add, 814 | celltype_key='Cell_type', 815 | cell_key='Cell', 816 | background_celltype=[], 817 | hidden_size=128, 818 | load_path='', 819 | used_device='cuda:0') 820 | ``` 821 | **Parameters** 822 | 823 | **sc_adata**: _AnnData_ 824 | 825 |  AnnData of reference data 826 | 827 | **spa_pattern_base**: _DataFrame_ 828 | 829 |  The base spatial patterns (for example, mixing cell populations, cell clusters, or cell rings) 830 | 831 | **spa_pattern_add**: _DataFrame_ 832 | 833 |  The added spatial patterns overlaid on the base spatial patterns (for example, stripes) 834 | 835 | **celltype_key**: _str_ 836 | 837 |  The column name of `cell labels` in `sc_adata.obs` 838 | 839 | **cell_key**: _str_ 840 | 841 |  The column name of `cell` in `sc_adata.obs` 842 | 843 | **background_celltype**: _list_ 844 | 845 |  The cell types considered as background 846 | 847 | **background_prop**: _Optional[list], default: `None`_ 848 | 849 |  The proportion of cell types considered as background, the background cell type must be same in the base and added spatial patterns 850 | 851 | **hidden_size**: _int, default: `128`_ 852 | 853 |  Hidden size of VAE model 854 | 855 | **load_path**: _str_ 856 | 857 |  The load path 858 | 859 | **used_device**: _str, default: `cuda:0`_ 860 | 861 |  Device name, `cpu` or `cuda` 862 | **** 863 | 864 | 865 | ##### generate spatial patterns with reference-based strategy 866 | ```python 867 | generate_sc_data, generate_sc_meta = model.generate_pattern_reference( 868 | sc_adata=sc_adata, 869 | generate_sc_data=generate_sc_data, 870 | generate_sc_meta=generate_sc_meta, 871 | celltype_key='Cell_type', 872 | spatial_key=['x', 'y'], 873 | cost_metric='sqeuclidean' 874 | ) 875 | ``` 876 | **Parameters** 877 | 878 | **sc_adata**: _AnnData_ 879 | 880 |  AnnData of reference data 881 | 882 | **generate_sc_data**: _DataFrame_ 883 | 884 |  DataFrame of generated data 885 | 886 | **generate_sc_meta**: _DataFrame_ 887 | 888 |  DataFrame of generated meta 889 | 890 | **celltype_key**: _str_ 891 | 892 |  The column name of `cell labels` in meta 893 | 894 | **spatial_key**: _list_ 895 | 896 |  The column name of `spatial coordinates` in meta 897 | 898 | **cost_metric**: _str, defalut: `sqeuclidean`_ 899 | 900 |  The cost distance between generate_sc_data and real_data, `sqeuclidean` by default. On numpy the function also accepts from the scipy.spatial.distance.cdist function : ‘braycurtis’, ‘canberra’, ‘chebyshev’, ‘cityblock’, ‘correlation’, ‘cosine’, ‘dice’, ‘euclidean’, ‘hamming’, ‘jaccard’, ‘kulsinski’, ‘mahalanobis’, ‘matching’, ‘minkowski’, ‘rogerstanimoto’, ‘russellrao’, ‘seuclidean’, ‘sokalmichener’, ‘sokalsneath’, ‘sqeuclidean’, ‘wminkowski’, ‘yule’. 901 | 902 | **** 903 | 904 | #### visualization functions: 905 | ##### Plot scatter plot of cell type spatial pattern 906 | ```python 907 | p = plot_spatial_pattern_scatter( 908 | obj=generate_sc_meta, 909 | figwidth=8, 910 | figheight=8, 911 | dim=2, 912 | x="point_x", 913 | y="point_y", 914 | z=None, 915 | label=None, 916 | palette=None, 917 | colormap='rainbow', 918 | size=10, 919 | alpha=1, 920 | ) 921 | plt.show(p) 922 | ``` 923 | **Parameters** 924 | 925 | **obj**: _DataFrame_ 926 | 927 |  DataFrame of generated meta 928 | 929 | **figwidth**: _float, default: `8`_ 930 | 931 |  Figure width 932 | 933 | **figheight**: _float, default: `8`_ 934 | 935 |  Figure height 936 | 937 | **dim**: _int, defalut: `2`_ 938 | 939 |  Spatial dimensionality 940 | 941 | **x**: _str, defalut: `point_x`_ 942 | 943 |  The name of column containing x coordinate 944 | 945 | **y**: _str, defalut: `point_y`_ 946 | 947 |  The name of column containing y coordinate 948 | 949 | **z**: _Optional[str], default: `None`_ 950 | 951 |  The name of column containing z coordinate, only use when 'dim = 3' 952 | 953 | **label**: _Optional[str], default: `None`_ 954 | 955 |  The name of column containing cell type information, if 'label=None', plot coordinates without cell type information only. 956 | 957 | **palette**: _Optional[list], default: `None`_ 958 | 959 |  List of colors used, if 'palette=None', plot scatter plot with colormap colors 960 | 961 | **colormap**: str, default: `rainbow`_ 962 | 963 |  The name of cmap 964 | 965 | **size**: _float, default: `10`_ 966 | 967 |  The size of point 968 | 969 | **alpha**: _float, default: `1`_ 970 | 971 |  The transparency of point 972 | 973 | **** 974 | 975 | ##### Plot density plot of cell type spatial pattern 976 | ```python 977 | p = plot_spatial_pattern_density( 978 | obj=generate_sc_meta, 979 | figwidth=8, 980 | figheight=8, 981 | x="point_x", 982 | y="point_y", 983 | label="Cell_type", 984 | show_celltype=None, 985 | colormap='Blues', 986 | fill=True, 987 | ) 988 | plt.show(p) 989 | ``` 990 | **Parameters** 991 | 992 | **obj**: _DataFrame_ 993 | 994 |  DataFrame of generated meta 995 | 996 | **figwidth**: _float, default: `8`_ 997 | 998 |  Figure width 999 | 1000 | **figheight**: _float, default: `8`_ 1001 | 1002 |  Figure height 1003 | 1004 | **x**: _str, defalut: `point_x`_ 1005 | 1006 |  The name of column containing x coordinate 1007 | 1008 | **y**: _str, defalut: `point_y`_ 1009 | 1010 |  The name of column containing y coordinate 1011 | 1012 | **label**: _str, default: `Cell_type`_ 1013 | 1014 |  The name of column containing cell type information, if 'label=None', plot coordinates without cell type information only. 1015 | 1016 | **show_celltype**: _Optional[str], default: `None`_ 1017 | 1018 |  The cell type selected to plot separately, if 'show_celltype=None', plot all cell type together 1019 | 1020 | **colormap**: str, default: `Blues`_ 1021 | 1022 |  The name of cmap 1023 | 1024 | **fill**: _bool, default: `True`_ 1025 | 1026 |  If 'fill=True', fill in the area between bivariate contours 1027 | 1028 | **** 1029 | 1030 | ##### Plot scatterpie plot of spot-based data 1031 | ```python 1032 | p = plot_spot_scatterpie( 1033 | obj=prop, 1034 | figwidth=8, 1035 | figheight=8, 1036 | x="spot_x", 1037 | y="spot_y", 1038 | palette=None, 1039 | colormap='rainbow', 1040 | res=50, 1041 | direction="+", 1042 | start=0.0, 1043 | size=100, 1044 | edgecolor="none", 1045 | ) 1046 | plt.show(p) 1047 | ``` 1048 | **Parameters** 1049 | 1050 | **obj**: _DataFrame_ 1051 | 1052 |  DataFrame of cell type proportion per spot 1053 | 1054 | **figwidth**: _float, default: `8`_ 1055 | 1056 |  Figure width 1057 | 1058 | **figheight**: _float, default: `8`_ 1059 | 1060 |  Figure height 1061 | 1062 | **x**: _str, defalut: `spot_x`_ 1063 | 1064 |  The name of column containing x coordinate 1065 | 1066 | **y**: _str, defalut: `spot_y`_ 1067 | 1068 |  The name of column containing y coordinate 1069 | 1070 | **palette**: _Optional[dict], default: `None`_ 1071 | 1072 |  Dict of color of each cell type, if 'palette == None', plot scatterpie plot with colormap colors 1073 | 1074 | **colormap**: str, default: `rainbow`_ 1075 | 1076 |  The name of cmap 1077 | 1078 | **res**: _int, default: `50`_ 1079 | 1080 |  Number of points around the circle 1081 | 1082 | **direction**: _str, default: `+`_ 1083 | 1084 |  '+' for counter-clockwise, or '-' for clockwise 1085 | 1086 | **start**: _flost, default: `0.0`_ 1087 | 1088 |  Starting position in radians 1089 | 1090 | **size**: _float, default: `100`_ 1091 | 1092 |  The size of point 1093 | 1094 | **edgecolor**: _str, default: `none`_ 1095 | 1096 |  The edge color of point 1097 | 1098 | **** 1099 | 1100 | ##### Plot scatter plot of proportion of selected cell type 1101 | ```python 1102 | p = plot_spot_prop( 1103 | obj=prop, 1104 | figwidth=8, 1105 | figheight=8, 1106 | x="spot_x", 1107 | y="spot_y", 1108 | colormap='viridis', 1109 | show_celltype= "", 1110 | size=100, 1111 | alpha=1, 1112 | ) 1113 | plt.show(p) 1114 | ``` 1115 | **Parameters** 1116 | 1117 | **obj**: _DataFrame_ 1118 | 1119 |  DataFrame of cell type proportion per spot 1120 | 1121 | **figwidth**: _float, default: `8`_ 1122 | 1123 |  Figure width 1124 | 1125 | **figheight**: _float, default: `8`_ 1126 | 1127 |  Figure height 1128 | 1129 | **x**: _str, defalut: `spot_x`_ 1130 | 1131 |  The name of column containing x coordinate 1132 | 1133 | **y**: _str, defalut: `spot_y`_ 1134 | 1135 |  The name of column containing y coordinate 1136 | 1137 | **colormap**: str, default: `viridis`_ 1138 | 1139 |  The name of cmap 1140 | 1141 | **show_celltype**: _Union[list, str]_ 1142 | 1143 |  The cell type selected to plot 1144 | 1145 | **size**: _float, default: `100`_ 1146 | 1147 |  The size of point 1148 | 1149 | **alpha**: _float, default: `1`_ 1150 | 1151 |  The transparency of point 1152 | 1153 | **** 1154 | 1155 | ##### Plot scatter plot of spatial expression pattern of selected gene 1156 | ```python 1157 | p = plot_gene_scatter( 1158 | data=generate_sc_data, 1159 | obj=generate_sc_meta_new, 1160 | figwidth=8, 1161 | figheight=8, 1162 | dim=2, 1163 | label='Cell', 1164 | normalize=True, 1165 | x="point_x", 1166 | y="point_y", 1167 | z="point_z", 1168 | colormap='viridis', 1169 | show_gene: str = "", 1170 | size=10, 1171 | alpha=1, 1172 | ) 1173 | plt.show(p) 1174 | ``` 1175 | **Parameters** 1176 | 1177 | **data**: _DataFrame_ 1178 | 1179 |  DataFrame of generate data 1180 | 1181 | **obj**: _DataFrame_ 1182 | 1183 |  DataFrame of generate meta 1184 | 1185 | **figwidth**: _float, default: `8`_ 1186 | 1187 |  Figure width 1188 | 1189 | **figheight**: _float, default: `8`_ 1190 | 1191 |  Figure height 1192 | 1193 | **dim**: _int, default: `2`_ 1194 | 1195 |  Spatial dimensionality 1196 | 1197 | **label**: _str, default: `Cell`_ 1198 | 1199 |  The name of column containing cell/spot name 1200 | 1201 | **normalize**: _bool, default: `True`_ 1202 | 1203 |  If 'normalize=True', normalizing expression value to [0, 1] 1204 | 1205 | **x**: _str, defalut: `point_x`_ 1206 | 1207 |  The name of column containing x coordinate 1208 | 1209 | **y**: _str, defalut: `point_x`_ 1210 | 1211 |  The name of column containing y coordinate 1212 | 1213 | **z**: _Optional[str], default: `None`_ 1214 | 1215 |  The name of column containing z coordinate, only use when 'dim = 3' 1216 | 1217 | **colormap**: str, default: `viridis`_ 1218 | 1219 |  The name of cmap 1220 | 1221 | **show_gene**: _str_ 1222 | 1223 |  The gene selected to plot 1224 | 1225 | **size**: _float, default: `10`_ 1226 | 1227 |  The size of point 1228 | 1229 | **alpha**: _float, default: `1`_ 1230 | 1231 |  The transparency of point 1232 | 1233 | **** 1234 | 1235 | ##### Plot histplot of spot-based data to investigate cell number per spot 1236 | ```python 1237 | p = plot_gene_scatter( 1238 | obj=st_index, 1239 | figwidth=8, 1240 | figheight=8, 1241 | label='spot', 1242 | n_bin=20 1243 | ) 1244 | plt.show(p) 1245 | ``` 1246 | **Parameters** 1247 | 1248 | **obj**: _DataFrame_ 1249 | 1250 |  DataFrame of cell-spot index 1251 | 1252 | **figwidth**: _float, default: `8`_ 1253 | 1254 |  Figure width 1255 | 1256 | **figheight**: _float, default: `8`_ 1257 | 1258 |  Figure height 1259 | 1260 | **label**: _str, default: `spot`_ 1261 | 1262 |  The name of column containing spot name 1263 | 1264 | **n_bins**: int, default: `20`_ 1265 | 1266 |  The number of equal-width bins in the range 1267 | 1268 | **** 1269 | 1270 | ##### Plot 2d scatter plot of cell type spatial pattern of each slices from 3d data 1271 | ```python 1272 | p = plot_slice_scatter( 1273 | obj=generate_sc_meta, 1274 | figwidth=8, 1275 | figheight=8, 1276 | x="point_x", 1277 | y="point_y", 1278 | label='Cell_type', 1279 | palette=None, 1280 | colormap='rainbow', 1281 | size=10, 1282 | alpha=1 1283 | ) 1284 | plt.show(p) 1285 | ``` 1286 | **Parameters** 1287 | 1288 | **obj**: _DataFrame_ 1289 | 1290 |  DataFrame of generated meta 1291 | 1292 | **figwidth**: _float, default: `8`_ 1293 | 1294 |  Figure width 1295 | 1296 | **figheight**: _float, default: `8`_ 1297 | 1298 |  Figure height 1299 | 1300 | **x**: _str, defalut: `point_x`_ 1301 | 1302 |  The name of column containing x coordinate 1303 | 1304 | **y**: _str, defalut: `point_y`_ 1305 | 1306 |  The name of column containing y coordinate 1307 | 1308 | **label**: _str, default: `Cell_type`_ 1309 | 1310 |  The name of column containing cell type information 1311 | 1312 | **palette**: _Optional[list], default: `None`_ 1313 | 1314 |  List of colors used, if 'palette=None', plot scatter plot with colormap colors 1315 | 1316 | **colormap**: str, default: `rainbow`_ 1317 | 1318 |  The name of cmap 1319 | 1320 | **size**: _float, default: `10`_ 1321 | 1322 |  The size of point 1323 | 1324 | **alpha**: _float, default: `1`_ 1325 | 1326 |  The transparency of point 1327 | 1328 | **** 1329 | 1330 | ##### Plot 2d scatter plot of spatial expression pattern of selected gene of each slices from 3d data 1331 | ```python 1332 | p = plot_slice_gene_scatter( 1333 | data=generate_sc_data, 1334 | obj=generate_sc_meta, 1335 | figwidth=8, 1336 | figheight=8, 1337 | x="point_x", 1338 | y="point_y", 1339 | label='Cell_type', 1340 | normalize=True, 1341 | show_gene="", 1342 | colormap='viridis', 1343 | size=10, 1344 | alpha=1 1345 | ) 1346 | plt.show(p) 1347 | ``` 1348 | **Parameters** 1349 | 1350 | **data**: _DataFrame_ 1351 | 1352 |  DataFrame of generated data 1353 | 1354 | **obj**: _DataFrame_ 1355 | 1356 |  DataFrame of generated meta 1357 | 1358 | **figwidth**: _float, default: `8`_ 1359 | 1360 |  Figure width 1361 | 1362 | **figheight**: _float, default: `8`_ 1363 | 1364 |  Figure height 1365 | 1366 | **x**: _str, defalut: `point_x`_ 1367 | 1368 |  The name of column containing x coordinate 1369 | 1370 | **y**: _str, defalut: `point_y`_ 1371 | 1372 |  The name of column containing y coordinate 1373 | 1374 | **label**: _str, default: `Cell_type`_ 1375 | 1376 |  The name of column containing cell type information 1377 | 1378 | **normalize**: _bool, default: `True`_ 1379 | 1380 |  If 'normalize=True', normalizing expression value to [0, 1] 1381 | 1382 | **show_gene**: _str_ 1383 | 1384 |  The gene selected to plot 1385 | 1386 | **colormap**: str, default: `viridis`_ 1387 | 1388 |  The name of cmap 1389 | 1390 | **size**: _float, default: `10`_ 1391 | 1392 |  The size of point 1393 | 1394 | **alpha**: _float, default: `1`_ 1395 | 1396 |  The transparency of point 1397 | 1398 | **** 1399 | 1400 | 1401 | 1402 | 1403 | -------------------------------------------------------------------------------- /tutorial/demo_data/MERFISH_0.06_adata.h5ad: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ZJUFanLab/scCube/d5b423d296da17d0fd5b4d12e92262167a642445/tutorial/demo_data/MERFISH_0.06_adata.h5ad -------------------------------------------------------------------------------- /tutorial/demo_data/MERFISH_n0.29_adata.h5ad: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ZJUFanLab/scCube/d5b423d296da17d0fd5b4d12e92262167a642445/tutorial/demo_data/MERFISH_n0.29_adata.h5ad -------------------------------------------------------------------------------- /tutorial/demo_data/customized_bc.pth: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ZJUFanLab/scCube/d5b423d296da17d0fd5b4d12e92262167a642445/tutorial/demo_data/customized_bc.pth -------------------------------------------------------------------------------- /tutorial/demo_data/customized_bc_adata.h5ad: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ZJUFanLab/scCube/d5b423d296da17d0fd5b4d12e92262167a642445/tutorial/demo_data/customized_bc_adata.h5ad -------------------------------------------------------------------------------- /tutorial/demo_data/demo_sc_meta.csv: -------------------------------------------------------------------------------- 1 | "","Cell","Cell_type" 2 | "C_1","C_1","fibroblast" 3 | "C_2","C_2","professional antigen presenting cell" 4 | "C_3","C_3","fibroblast" 5 | "C_4","C_4","endothelial cell" 6 | "C_5","C_5","endothelial cell" 7 | "C_6","C_6","endothelial cell" 8 | "C_7","C_7","endothelial cell" 9 | "C_8","C_8","erythrocyte" 10 | "C_9","C_9","professional antigen presenting cell" 11 | "C_10","C_10","erythrocyte" 12 | "C_11","C_11","fibroblast" 13 | "C_12","C_12","endothelial cell" 14 | "C_13","C_13","endothelial cell" 15 | "C_14","C_14","fibroblast" 16 | "C_15","C_15","erythrocyte" 17 | "C_16","C_16","endothelial cell" 18 | "C_17","C_17","endothelial cell" 19 | "C_18","C_18","professional antigen presenting cell" 20 | "C_19","C_19","professional antigen presenting cell" 21 | "C_20","C_20","endothelial cell" 22 | "C_21","C_21","endothelial cell" 23 | "C_22","C_22","erythrocyte" 24 | "C_23","C_23","erythrocyte" 25 | "C_24","C_24","erythrocyte" 26 | "C_25","C_25","erythrocyte" 27 | "C_26","C_26","fibroblast" 28 | "C_27","C_27","erythrocyte" 29 | "C_28","C_28","endothelial cell" 30 | "C_29","C_29","erythrocyte" 31 | "C_30","C_30","fibroblast" 32 | "C_31","C_31","professional antigen presenting cell" 33 | "C_32","C_32","endothelial cell" 34 | "C_33","C_33","endothelial cell" 35 | "C_34","C_34","fibroblast" 36 | "C_35","C_35","endothelial cell" 37 | "C_36","C_36","endothelial cell" 38 | "C_37","C_37","professional antigen presenting cell" 39 | "C_38","C_38","professional antigen presenting cell" 40 | "C_39","C_39","fibroblast" 41 | "C_40","C_40","endothelial cell" 42 | "C_41","C_41","endothelial cell" 43 | "C_42","C_42","professional antigen presenting cell" 44 | "C_43","C_43","endothelial cell" 45 | "C_44","C_44","endothelial cell" 46 | "C_45","C_45","endothelial cell" 47 | "C_46","C_46","erythrocyte" 48 | "C_47","C_47","erythrocyte" 49 | "C_48","C_48","endothelial cell" 50 | "C_49","C_49","endothelial cell" 51 | "C_50","C_50","erythrocyte" 52 | "C_51","C_51","erythrocyte" 53 | "C_52","C_52","erythrocyte" 54 | "C_53","C_53","erythrocyte" 55 | "C_54","C_54","fibroblast" 56 | "C_55","C_55","endothelial cell" 57 | "C_56","C_56","endothelial cell" 58 | "C_57","C_57","endothelial cell" 59 | "C_58","C_58","endothelial cell" 60 | "C_59","C_59","endothelial cell" 61 | "C_60","C_60","endothelial cell" 62 | "C_61","C_61","erythrocyte" 63 | "C_62","C_62","professional antigen presenting cell" 64 | "C_63","C_63","professional antigen presenting cell" 65 | "C_64","C_64","endothelial cell" 66 | "C_65","C_65","endothelial cell" 67 | "C_66","C_66","endothelial cell" 68 | "C_67","C_67","professional antigen presenting cell" 69 | "C_68","C_68","endothelial cell" 70 | "C_69","C_69","endothelial cell" 71 | "C_70","C_70","fibroblast" 72 | "C_71","C_71","professional antigen presenting cell" 73 | "C_72","C_72","endothelial cell" 74 | "C_73","C_73","endothelial cell" 75 | "C_74","C_74","endothelial cell" 76 | "C_75","C_75","professional antigen presenting cell" 77 | "C_76","C_76","professional antigen presenting cell" 78 | "C_77","C_77","endothelial cell" 79 | "C_78","C_78","endothelial cell" 80 | "C_79","C_79","erythrocyte" 81 | "C_80","C_80","erythrocyte" 82 | "C_81","C_81","endothelial cell" 83 | "C_82","C_82","erythrocyte" 84 | "C_83","C_83","fibroblast" 85 | "C_84","C_84","endothelial cell" 86 | "C_85","C_85","endothelial cell" 87 | "C_86","C_86","endothelial cell" 88 | "C_87","C_87","endothelial cell" 89 | "C_88","C_88","professional antigen presenting cell" 90 | "C_89","C_89","endothelial cell" 91 | "C_90","C_90","professional antigen presenting cell" 92 | "C_91","C_91","fibroblast" 93 | "C_92","C_92","endothelial cell" 94 | "C_93","C_93","endothelial cell" 95 | "C_94","C_94","endothelial cell" 96 | "C_95","C_95","fibroblast" 97 | "C_96","C_96","fibroblast" 98 | "C_97","C_97","endothelial cell" 99 | "C_98","C_98","professional antigen presenting cell" 100 | "C_99","C_99","erythrocyte" 101 | "C_100","C_100","endothelial cell" 102 | "C_101","C_101","endothelial cell" 103 | "C_102","C_102","fibroblast" 104 | "C_103","C_103","fibroblast" 105 | "C_104","C_104","erythrocyte" 106 | "C_105","C_105","endothelial cell" 107 | "C_106","C_106","erythrocyte" 108 | "C_107","C_107","fibroblast" 109 | "C_108","C_108","erythrocyte" 110 | "C_109","C_109","erythrocyte" 111 | "C_110","C_110","fibroblast" 112 | "C_111","C_111","fibroblast" 113 | "C_112","C_112","endothelial cell" 114 | "C_113","C_113","endothelial cell" 115 | "C_114","C_114","professional antigen presenting cell" 116 | "C_115","C_115","endothelial cell" 117 | "C_116","C_116","fibroblast" 118 | "C_117","C_117","professional antigen presenting cell" 119 | "C_118","C_118","endothelial cell" 120 | "C_119","C_119","endothelial cell" 121 | "C_120","C_120","erythrocyte" 122 | "C_121","C_121","erythrocyte" 123 | "C_122","C_122","endothelial cell" 124 | "C_123","C_123","erythrocyte" 125 | "C_124","C_124","endothelial cell" 126 | "C_125","C_125","endothelial cell" 127 | "C_126","C_126","fibroblast" 128 | "C_127","C_127","endothelial cell" 129 | "C_128","C_128","erythrocyte" 130 | "C_129","C_129","erythrocyte" 131 | "C_130","C_130","erythrocyte" 132 | "C_131","C_131","endothelial cell" 133 | "C_132","C_132","professional antigen presenting cell" 134 | "C_133","C_133","erythrocyte" 135 | "C_134","C_134","endothelial cell" 136 | "C_135","C_135","professional antigen presenting cell" 137 | "C_136","C_136","endothelial cell" 138 | "C_137","C_137","endothelial cell" 139 | "C_138","C_138","fibroblast" 140 | "C_139","C_139","endothelial cell" 141 | "C_140","C_140","fibroblast" 142 | "C_141","C_141","endothelial cell" 143 | "C_142","C_142","fibroblast" 144 | "C_143","C_143","professional antigen presenting cell" 145 | "C_144","C_144","endothelial cell" 146 | "C_145","C_145","endothelial cell" 147 | "C_146","C_146","fibroblast" 148 | "C_147","C_147","endothelial cell" 149 | "C_148","C_148","endothelial cell" 150 | "C_149","C_149","erythrocyte" 151 | "C_150","C_150","fibroblast" 152 | "C_151","C_151","fibroblast" 153 | "C_152","C_152","endothelial cell" 154 | "C_153","C_153","endothelial cell" 155 | "C_154","C_154","erythrocyte" 156 | "C_155","C_155","erythrocyte" 157 | "C_156","C_156","erythrocyte" 158 | "C_157","C_157","fibroblast" 159 | "C_158","C_158","professional antigen presenting cell" 160 | "C_159","C_159","erythrocyte" 161 | "C_160","C_160","professional antigen presenting cell" 162 | "C_161","C_161","endothelial cell" 163 | "C_162","C_162","endothelial cell" 164 | "C_163","C_163","endothelial cell" 165 | "C_164","C_164","fibroblast" 166 | "C_165","C_165","erythrocyte" 167 | "C_166","C_166","endothelial cell" 168 | "C_167","C_167","professional antigen presenting cell" 169 | "C_168","C_168","erythrocyte" 170 | "C_169","C_169","endothelial cell" 171 | "C_170","C_170","endothelial cell" 172 | "C_171","C_171","erythrocyte" 173 | "C_172","C_172","endothelial cell" 174 | "C_173","C_173","fibroblast" 175 | "C_174","C_174","professional antigen presenting cell" 176 | "C_175","C_175","endothelial cell" 177 | "C_176","C_176","erythrocyte" 178 | "C_177","C_177","endothelial cell" 179 | "C_178","C_178","erythrocyte" 180 | "C_179","C_179","erythrocyte" 181 | "C_180","C_180","erythrocyte" 182 | "C_181","C_181","erythrocyte" 183 | "C_182","C_182","erythrocyte" 184 | "C_183","C_183","fibroblast" 185 | "C_184","C_184","erythrocyte" 186 | "C_185","C_185","erythrocyte" 187 | "C_186","C_186","erythrocyte" 188 | "C_187","C_187","endothelial cell" 189 | "C_188","C_188","erythrocyte" 190 | "C_189","C_189","endothelial cell" 191 | "C_190","C_190","endothelial cell" 192 | "C_191","C_191","professional antigen presenting cell" 193 | "C_192","C_192","fibroblast" 194 | "C_193","C_193","endothelial cell" 195 | "C_194","C_194","fibroblast" 196 | "C_195","C_195","endothelial cell" 197 | "C_196","C_196","professional antigen presenting cell" 198 | "C_197","C_197","endothelial cell" 199 | "C_198","C_198","endothelial cell" 200 | "C_199","C_199","endothelial cell" 201 | "C_200","C_200","professional antigen presenting cell" 202 | "C_201","C_201","endothelial cell" 203 | "C_202","C_202","fibroblast" 204 | "C_203","C_203","endothelial cell" 205 | "C_204","C_204","endothelial cell" 206 | "C_205","C_205","erythrocyte" 207 | "C_206","C_206","erythrocyte" 208 | "C_207","C_207","erythrocyte" 209 | "C_208","C_208","erythrocyte" 210 | "C_209","C_209","erythrocyte" 211 | "C_210","C_210","fibroblast" 212 | "C_211","C_211","endothelial cell" 213 | "C_212","C_212","endothelial cell" 214 | "C_213","C_213","endothelial cell" 215 | "C_214","C_214","endothelial cell" 216 | "C_215","C_215","endothelial cell" 217 | "C_216","C_216","erythrocyte" 218 | "C_217","C_217","endothelial cell" 219 | "C_218","C_218","endothelial cell" 220 | "C_219","C_219","fibroblast" 221 | "C_220","C_220","erythrocyte" 222 | "C_221","C_221","endothelial cell" 223 | "C_222","C_222","endothelial cell" 224 | "C_223","C_223","endothelial cell" 225 | "C_224","C_224","fibroblast" 226 | "C_225","C_225","professional antigen presenting cell" 227 | "C_226","C_226","endothelial cell" 228 | "C_227","C_227","fibroblast" 229 | "C_228","C_228","endothelial cell" 230 | "C_229","C_229","endothelial cell" 231 | "C_230","C_230","erythrocyte" 232 | "C_231","C_231","endothelial cell" 233 | "C_232","C_232","professional antigen presenting cell" 234 | "C_233","C_233","endothelial cell" 235 | "C_234","C_234","endothelial cell" 236 | "C_235","C_235","professional antigen presenting cell" 237 | "C_236","C_236","endothelial cell" 238 | "C_237","C_237","endothelial cell" 239 | "C_238","C_238","endothelial cell" 240 | "C_239","C_239","professional antigen presenting cell" 241 | "C_240","C_240","fibroblast" 242 | "C_241","C_241","endothelial cell" 243 | "C_242","C_242","fibroblast" 244 | "C_243","C_243","endothelial cell" 245 | "C_244","C_244","endothelial cell" 246 | "C_245","C_245","endothelial cell" 247 | "C_246","C_246","professional antigen presenting cell" 248 | "C_247","C_247","fibroblast" 249 | "C_248","C_248","endothelial cell" 250 | "C_249","C_249","erythrocyte" 251 | "C_250","C_250","fibroblast" 252 | "C_251","C_251","erythrocyte" 253 | "C_252","C_252","endothelial cell" 254 | "C_253","C_253","professional antigen presenting cell" 255 | "C_254","C_254","erythrocyte" 256 | "C_255","C_255","erythrocyte" 257 | "C_256","C_256","endothelial cell" 258 | "C_257","C_257","endothelial cell" 259 | "C_258","C_258","endothelial cell" 260 | "C_259","C_259","fibroblast" 261 | "C_260","C_260","professional antigen presenting cell" 262 | "C_261","C_261","fibroblast" 263 | "C_262","C_262","endothelial cell" 264 | "C_263","C_263","professional antigen presenting cell" 265 | "C_264","C_264","fibroblast" 266 | "C_265","C_265","professional antigen presenting cell" 267 | "C_266","C_266","endothelial cell" 268 | "C_267","C_267","endothelial cell" 269 | "C_268","C_268","endothelial cell" 270 | "C_269","C_269","endothelial cell" 271 | "C_270","C_270","professional antigen presenting cell" 272 | "C_271","C_271","erythrocyte" 273 | "C_272","C_272","endothelial cell" 274 | "C_273","C_273","endothelial cell" 275 | "C_274","C_274","erythrocyte" 276 | "C_275","C_275","professional antigen presenting cell" 277 | "C_276","C_276","endothelial cell" 278 | "C_277","C_277","erythrocyte" 279 | "C_278","C_278","erythrocyte" 280 | "C_279","C_279","erythrocyte" 281 | "C_280","C_280","erythrocyte" 282 | "C_281","C_281","erythrocyte" 283 | "C_282","C_282","erythrocyte" 284 | "C_283","C_283","fibroblast" 285 | "C_284","C_284","endothelial cell" 286 | "C_285","C_285","endothelial cell" 287 | "C_286","C_286","endothelial cell" 288 | "C_287","C_287","professional antigen presenting cell" 289 | "C_288","C_288","endothelial cell" 290 | "C_289","C_289","erythrocyte" 291 | "C_290","C_290","fibroblast" 292 | "C_291","C_291","fibroblast" 293 | "C_292","C_292","professional antigen presenting cell" 294 | "C_293","C_293","professional antigen presenting cell" 295 | "C_294","C_294","endothelial cell" 296 | "C_295","C_295","erythrocyte" 297 | "C_296","C_296","professional antigen presenting cell" 298 | "C_297","C_297","professional antigen presenting cell" 299 | "C_298","C_298","endothelial cell" 300 | "C_299","C_299","endothelial cell" 301 | "C_300","C_300","professional antigen presenting cell" 302 | "C_301","C_301","fibroblast" 303 | "C_302","C_302","endothelial cell" 304 | "C_303","C_303","fibroblast" 305 | "C_304","C_304","erythrocyte" 306 | "C_305","C_305","erythrocyte" 307 | "C_306","C_306","erythrocyte" 308 | "C_307","C_307","endothelial cell" 309 | "C_308","C_308","endothelial cell" 310 | "C_309","C_309","erythrocyte" 311 | "C_310","C_310","fibroblast" 312 | "C_311","C_311","erythrocyte" 313 | "C_312","C_312","endothelial cell" 314 | "C_313","C_313","erythrocyte" 315 | "C_314","C_314","professional antigen presenting cell" 316 | "C_315","C_315","endothelial cell" 317 | "C_316","C_316","endothelial cell" 318 | "C_317","C_317","endothelial cell" 319 | "C_318","C_318","endothelial cell" 320 | "C_319","C_319","professional antigen presenting cell" 321 | "C_320","C_320","endothelial cell" 322 | "C_321","C_321","endothelial cell" 323 | "C_322","C_322","professional antigen presenting cell" 324 | "C_323","C_323","endothelial cell" 325 | "C_324","C_324","endothelial cell" 326 | "C_325","C_325","endothelial cell" 327 | "C_326","C_326","professional antigen presenting cell" 328 | "C_327","C_327","erythrocyte" 329 | "C_328","C_328","endothelial cell" 330 | "C_329","C_329","endothelial cell" 331 | "C_330","C_330","erythrocyte" 332 | "C_331","C_331","erythrocyte" 333 | "C_332","C_332","erythrocyte" 334 | "C_333","C_333","erythrocyte" 335 | "C_334","C_334","erythrocyte" 336 | "C_335","C_335","erythrocyte" 337 | "C_336","C_336","endothelial cell" 338 | "C_337","C_337","endothelial cell" 339 | "C_338","C_338","professional antigen presenting cell" 340 | "C_339","C_339","endothelial cell" 341 | "C_340","C_340","fibroblast" 342 | "C_341","C_341","fibroblast" 343 | "C_342","C_342","endothelial cell" 344 | "C_343","C_343","endothelial cell" 345 | "C_344","C_344","endothelial cell" 346 | "C_345","C_345","fibroblast" 347 | "C_346","C_346","endothelial cell" 348 | "C_347","C_347","endothelial cell" 349 | "C_348","C_348","fibroblast" 350 | "C_349","C_349","professional antigen presenting cell" 351 | "C_350","C_350","fibroblast" 352 | "C_351","C_351","endothelial cell" 353 | "C_352","C_352","professional antigen presenting cell" 354 | "C_353","C_353","professional antigen presenting cell" 355 | "C_354","C_354","endothelial cell" 356 | "C_355","C_355","endothelial cell" 357 | "C_356","C_356","endothelial cell" 358 | "C_357","C_357","fibroblast" 359 | "C_358","C_358","fibroblast" 360 | "C_359","C_359","erythrocyte" 361 | "C_360","C_360","erythrocyte" 362 | "C_361","C_361","erythrocyte" 363 | "C_362","C_362","fibroblast" 364 | "C_363","C_363","professional antigen presenting cell" 365 | "C_364","C_364","endothelial cell" 366 | "C_365","C_365","endothelial cell" 367 | "C_366","C_366","endothelial cell" 368 | "C_367","C_367","professional antigen presenting cell" 369 | "C_368","C_368","endothelial cell" 370 | "C_369","C_369","endothelial cell" 371 | "C_370","C_370","professional antigen presenting cell" 372 | "C_371","C_371","endothelial cell" 373 | "C_372","C_372","fibroblast" 374 | "C_373","C_373","professional antigen presenting cell" 375 | "C_374","C_374","endothelial cell" 376 | "C_375","C_375","endothelial cell" 377 | "C_376","C_376","endothelial cell" 378 | "C_377","C_377","professional antigen presenting cell" 379 | "C_378","C_378","endothelial cell" 380 | "C_379","C_379","endothelial cell" 381 | "C_380","C_380","erythrocyte" 382 | "C_381","C_381","endothelial cell" 383 | "C_382","C_382","fibroblast" 384 | "C_383","C_383","erythrocyte" 385 | "C_384","C_384","fibroblast" 386 | "C_385","C_385","endothelial cell" 387 | "C_386","C_386","fibroblast" 388 | "C_387","C_387","endothelial cell" 389 | "C_388","C_388","endothelial cell" 390 | "C_389","C_389","endothelial cell" 391 | "C_390","C_390","endothelial cell" 392 | "C_391","C_391","fibroblast" 393 | "C_392","C_392","fibroblast" 394 | "C_393","C_393","endothelial cell" 395 | "C_394","C_394","fibroblast" 396 | "C_395","C_395","endothelial cell" 397 | "C_396","C_396","erythrocyte" 398 | "C_397","C_397","endothelial cell" 399 | "C_398","C_398","fibroblast" 400 | "C_399","C_399","endothelial cell" 401 | "C_400","C_400","endothelial cell" 402 | "C_401","C_401","fibroblast" 403 | "C_402","C_402","fibroblast" 404 | "C_403","C_403","endothelial cell" 405 | "C_404","C_404","endothelial cell" 406 | "C_405","C_405","endothelial cell" 407 | "C_406","C_406","endothelial cell" 408 | "C_407","C_407","fibroblast" 409 | "C_408","C_408","erythrocyte" 410 | --------------------------------------------------------------------------------