diff --git a/docs/404.html b/docs/404.html deleted file mode 100644 index 465de02..0000000 --- a/docs/404.html +++ /dev/null @@ -1,90 +0,0 @@ - - -
- - - - -LICENSE.md
- Version 3, 29 June 2007
Copyright © 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.
-The GNU General Public License is a free, copyleft license for software and other kinds of works.
-The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program–to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too.
-When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things.
-To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others.
-For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights.
-Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it.
-For the developers’ and authors’ protection, the GPL clearly explains that there is no warranty for this free software. For both users’ and authors’ sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions.
-Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users’ freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users.
-Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free.
-The precise terms and conditions for copying, distribution and modification follow.
-“This License” refers to version 3 of the GNU General Public License.
-“Copyright” also means copyright-like laws that apply to other kinds of works, such as semiconductor masks.
-“The Program” refers to any copyrightable work licensed under this License. Each licensee is addressed as “you”. “Licensees” and “recipients” may be individuals or organizations.
-To “modify” a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a “modified version” of the earlier work or a work “based on” the earlier work.
-A “covered work” means either the unmodified Program or a work based on the Program.
-To “propagate” a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well.
-To “convey” a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying.
-An interactive user interface displays “Appropriate Legal Notices” to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion.
-The “source code” for a work means the preferred form of the work for making modifications to it. “Object code” means any non-source form of a work.
-A “Standard Interface” means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language.
-The “System Libraries” of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A “Major Component”, in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it.
-The “Corresponding Source” for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work’s System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work.
-The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source.
-The Corresponding Source for a work in source code form is that same work.
-All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law.
-You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you.
-Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary.
-No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures.
-When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work’s users, your or third parties’ legal rights to forbid circumvention of technological measures.
-You may convey verbatim copies of the Program’s source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program.
-You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee.
-You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions:
-A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an “aggregate” if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation’s users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate.
-You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways:
-A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work.
-A “User Product” is either (1) a “consumer product”, which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, “normally used” refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product.
-“Installation Information” for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made.
-If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM).
-The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network.
-Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying.
-“Additional permissions” are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions.
-When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission.
-Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms:
-All other non-permissive additional terms are considered “further restrictions” within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying.
-If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms.
-Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way.
-You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11).
-However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation.
-Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice.
-Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10.
-You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so.
-Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License.
-An “entity transaction” is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party’s predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts.
-You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it.
-A “contributor” is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor’s “contributor version”.
-A contributor’s “essential patent claims” are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, “control” includes the right to grant patent sublicenses in a manner consistent with the requirements of this License.
-Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor’s essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version.
-In the following three paragraphs, a “patent license” is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To “grant” such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party.
-If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. “Knowingly relying” means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient’s use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid.
-If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it.
-A patent license is “discriminatory” if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007.
-Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law.
-If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program.
-Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such.
-The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns.
-Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License “or any later version” applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation.
-If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy’s public statement of acceptance of a version permanently authorizes you to choose that version for the Program.
-Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version.
-THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
-IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
-If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee.
-END OF TERMS AND CONDITIONS
-If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms.
-To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the “copyright” line and a pointer to where the full notice is found.
-<one line to give the program's name and a brief idea of what it does.>
-Copyright (C) <year> <name of author>
-
-This program is free software: you can redistribute it and/or modify
-it under the terms of the GNU General Public License as published by
-the Free Software Foundation, either version 3 of the License, or
-(at your option) any later version.
-
-This program is distributed in the hope that it will be useful,
-but WITHOUT ANY WARRANTY; without even the implied warranty of
-MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-GNU General Public License for more details.
-
-You should have received a copy of the GNU General Public License
-along with this program. If not, see <http://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
-If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode:
-<program> Copyright (C) <year> <name of author>
-for details type 'show w'.
- This program comes with ABSOLUTELY NO WARRANTY;
- This is free software, and you are welcome to redistribute it'show c' for details. under certain conditions; type
The hypothetical commands show w
and show c
should show the appropriate parts of the General Public License. Of course, your program’s commands might be different; for a GUI interface, you would use an “about box”.
You should also get your employer (if you work as a programmer) or school, if any, to sign a “copyright disclaimer” for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see <http://www.gnu.org/licenses/>.
-The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read <http://www.gnu.org/philosophy/why-not-lgpl.html>.
-vignettes/SpatialExperiment.Rmd
- SpatialExperiment.Rmd
-my_cols <-c("#D55E00", "#CC79A7","#E69F00","#0072B2","#009E73","#F0E442","#56B4E9","#000000")
-names(my_cols) <- as.character(seq(my_cols))
Our package poem
can be easily integrated into a
-workflow with SpatialExperiment
objects. Here we use the
-Visium_humanDLPFC
dataset from package
-STexampleData
for illustration. Load it:
-spe <- Visium_humanDLPFC()
-spe
-## class: SpatialExperiment
-## dim: 33538 4992
-## metadata(0):
-## assays(1): counts
-## rownames(33538): ENSG00000243485 ENSG00000237613 ... ENSG00000277475
-## ENSG00000268674
-## rowData names(3): gene_id gene_name feature_type
-## colnames(4992): AAACAACGAATAGTTC-1 AAACAAGTATCTCCCA-1 ...
-## TTGTTTGTATTACACG-1 TTGTTTGTGTAAATTC-1
-## colData names(8): barcode_id sample_id ... reference cell_count
-## reducedDimNames(0):
-## mainExpName: NULL
-## altExpNames(0):
-## spatialCoords names(2) : pxl_col_in_fullres pxl_row_in_fullres
-## imgData names(4): sample_id image_id data scaleFactor
From this SpatialExperiment
object, we take the location
-information (accessible via spatialCoords
) and the manual
-annotation in colData
and store them as a dataframe:
-data <- data.frame(spatialCoords(spe))
-data$reference <- colData(spe)$reference
-data <- na.omit(data)
-data$reference <- factor(data$reference, levels=c("WM", "Layer6", "Layer5",
- "Layer4", "Layer3", "Layer2",
- "Layer1"))
The manual annotation looks like this:
-
-p1 <- ggplot(data) +
- geom_point(aes(x = pxl_col_in_fullres, y = -pxl_row_in_fullres, color = reference), size=0.3) +
- labs(x = "", y = "", color="", title="Manual annotation") +
- theme_minimal() +
- scale_color_manual(values = unname(my_cols)) +
- theme(
- legend.box.background = element_rect(fill = "grey90", color = "black", size = 0.1),
- legend.box.margin = margin(-1, -1, -1, -1),
- axis.title.x=element_blank(),
- legend.position = "bottom",
- legend.box.spacing = margin(0),
- axis.text.x=element_blank(),
- axis.ticks.x=element_blank(),
- axis.text.y=element_blank(),
- axis.ticks.y=element_blank(),
- panel.spacing.x = unit(-0.5, "cm"),
- panel.grid.major = element_blank(),
- panel.grid.minor = element_blank(),
- plot.title = element_text(hjust = 0.5, size=12, margin = margin(b = 5, t = 15))) +
- guides(color = guide_legend(keywidth = 1, keyheight = 0.8, override.aes = list(size = 3)))
-
-p1
We then generate some hypothetical domain detection predictions by -randomly permuting the manual annotation.
-
-set.seed(123) # For reproducibility
-
-# Given a factor vector representing clustering results, simulate clustering variations including merging two clusters and adding random noise.
-simulate_clustering_variation <- function(clusters, split_cluster = NULL, merge_clusters = NULL, noise_level = 0.1) {
- # Convert to numeric for easier manipulation
- merge_clusters <- which(levels(clusters) %in% merge_clusters)
- clusters <- as.numeric(clusters)
-
- # 1. Merging two clusters
- if (!is.null(merge_clusters)) {
- clusters[clusters %in% merge_clusters] <- merge_clusters[1] # Rename both to the same label
- }
-
- # 2. Adding random noise
- n <- length(clusters)
- n_noise <- round(n * noise_level) # Number of elements to replace
- if (n_noise > 0) {
- noise_indices <- sample(seq_len(n), n_noise) # Random indices to replace
- existing_levels <- unique(clusters)
- clusters[noise_indices] <- sample(existing_levels, n_noise, replace = TRUE) # Replace with random levels
- }
-
- # Convert back to factor and return
- factor(clusters)
-}
Below we simulate some prediction results with random noise as well -as merging or splitting of domains:
-
-# P1: add random noise
-data$P1 <- simulate_clustering_variation(
- data$reference,
- noise_level = 0.1
-)
-
-# P2: split Layer 3 into 2 domains, add random noise
-data$P2 <- as.numeric(data$reference)
-data$P2[data$reference=="Layer3" & data$pxl_col_in_fullres < 8000] <- 8
-data$P2 <- factor(as.numeric(factor(data$P2)))
-
-data$P2 <- simulate_clustering_variation(
- data$P2,
- noise_level = 0.1
-)
-
-# P3: merge Layer 4 and Layer 5, add random noise
-data$P3 <- simulate_clustering_variation(
- data$reference,
- merge_clusters = c("Layer4", "Layer5"),
- noise_level = 0.1
-)
If we visualize them:
-
-p2 <- data %>% pivot_longer(cols=-c("pxl_col_in_fullres","pxl_row_in_fullres"),
- names_to="prediction", values_to="domain") %>%
- dplyr::filter(prediction != "reference") %>%
- ggplot() +
- geom_point(aes(x = pxl_col_in_fullres, y = -pxl_row_in_fullres, color = domain), size=0.4) +
- facet_wrap(~prediction, nrow=2) +
- labs(x = "", y = "", color="", title="") +
- theme_minimal() +
- scale_color_manual(values = unname(my_cols)) +
- theme(
- legend.box.background = element_rect(fill = "grey90", color = "black", size = 0.1),
- legend.box.margin = margin(-1, -1, -1, -1),
- axis.title.x=element_blank(),
- legend.position = "bottom",
- legend.justification=c(0, 0),
- legend.box.spacing = margin(0),
- axis.text.x=element_blank(),
- axis.ticks.x=element_blank(),
- axis.text.y=element_blank(),
- axis.ticks.y=element_blank(),
- panel.spacing.x = unit(-0.5, "cm"),
- panel.grid.major = element_blank(),
- panel.grid.minor = element_blank(),
- plot.title = element_text(hjust = 0.5, size=10)) +
- guides(color = guide_legend(keywidth = 1, keyheight = 0.8, override.aes = list(size = 3)))
-
-ggdraw() +
- draw_plot(p2 + theme(plot.margin = margin(0, 2, 2, 2))) + # Main plot
- draw_plot(p1, x = 0.5, y = -0.01, width = 0.5, height = 0.56) # Inset plot
We can compare P1-P3 to the manual annotation using external spatial -metrics.
-Let’s first calculate two dataset-level metrics, SpatialARI and -SpatialAccuracy:
-
-res3 <- getSpatialExternalMetrics(true=data$reference, pred=data$P3,
- location=data[,c("pxl_col_in_fullres","pxl_row_in_fullres")], level="dataset",
- metrics=c("SpatialARI","SpatialAccuracy"), k=6,
- fuzzy_true = TRUE, fuzzy_pred = FALSE)
-
-res2 <- getSpatialExternalMetrics(true=data$reference, pred=data$P2,
- location=data[,c("pxl_col_in_fullres","pxl_row_in_fullres")], level="dataset",
- metrics=c("SpatialARI","SpatialAccuracy"), k=6,
- fuzzy_true = TRUE, fuzzy_pred = FALSE)
-
-res1 <- getSpatialExternalMetrics(true=data$reference, pred=data$P1,
- location=data[,c("pxl_col_in_fullres","pxl_row_in_fullres")], level="dataset",
- metrics=c("SpatialARI","SpatialAccuracy"), k=6,
- fuzzy_true = TRUE, fuzzy_pred = FALSE)
-
-cbind(bind_rows(list(res1, res2, res3), .id="P")) %>%
- pivot_longer(cols=c("SpatialARI", "SpatialAccuracy"),
- names_to="metric", values_to="value") %>%
- ggplot(aes(x=P, y=value, group=metric)) +
- geom_point(size=3, aes(color=P)) +
- facet_wrap(~metric, scales = "free") +
- theme_bw() + labs(x="Prediction")
We can further calculate the class/cluster-level metrics, SpatialAWH -and SpatialAWC, to get more insights about the errors our predictions -make:
-
-res3 <- getSpatialExternalMetrics(true=data$reference, pred=data$P3,
- location=data[,c("pxl_col_in_fullres","pxl_row_in_fullres")], level="class",
- metrics=c("SpatialAWH","SpatialAWC"), k=6,
- fuzzy_true = TRUE, fuzzy_pred = FALSE)
-
-res2 <- getSpatialExternalMetrics(true=data$reference, pred=data$P2,
- location=data[,c("pxl_col_in_fullres","pxl_row_in_fullres")], level="class",
- metrics=c("SpatialAWH","SpatialAWC"), k=6,
- fuzzy_true = TRUE, fuzzy_pred = FALSE)
-
-res1 <- getSpatialExternalMetrics(true=data$reference, pred=data$P1,
- location=data[,c("pxl_col_in_fullres","pxl_row_in_fullres")], level="class",
- metrics=c("SpatialAWH","SpatialAWC"), k=6,
- fuzzy_true = TRUE, fuzzy_pred = FALSE)
-res1
-## SpatialAWH SpatialAWC class cluster
-## 1 NA 0.7963689 1 NA
-## 2 NA 0.8145576 2 NA
-## 3 NA 0.7561886 3 NA
-## 4 NA 0.8184988 4 NA
-## 5 NA 0.7949846 5 NA
-## 6 NA 0.8179805 6 NA
-## 7 NA 0.7884382 7 NA
-## 8 0.7704762 NA NA 1
-## 9 0.8727733 NA NA 2
-## 10 0.8274801 NA NA 3
-## 11 0.5853277 NA NA 4
-## 12 0.8989078 NA NA 5
-## 13 0.6277691 NA NA 6
-## 14 0.6240081 NA NA 7
Note that the indices in columns “class” and “cluster” correspond to
-the levels of original factors passed to true
and
-pred
. We align them back to the previous factor values, and
-then plot them in heatmap:
-awh1 <- na.omit(res1[,c("SpatialAWH", "cluster")]) %>% mutate(cluster = levels(data$P1)[cluster])
-awh2 <- na.omit(res2[,c("SpatialAWH", "cluster")]) %>% mutate(cluster = levels(data$P2)[cluster])
-awh3 <- na.omit(res3[,c("SpatialAWH", "cluster")]) %>% mutate(cluster = levels(data$P3)[cluster])
-
-awh <- cbind(bind_rows(list(awh1, awh2, awh3), .id="P")) %>%
- pivot_wider(names_from = cluster, values_from = SpatialAWH) %>%
- subset(select = -c(P))
-awh <- as.matrix(awh)
-rownames(awh) <- c("P1", "P2", "P3")
-awh <- awh[,c("1", "2", "3", "4", "5", "6", "7", "8")]
-
-awh <- data.frame(awh)
-colnames(awh) <- 1:8
-awh$prediction <- rownames(awh)
-
-
-p4 <- awh %>% pivot_longer(cols=-c("prediction"), names_to="cluster", values_to = "AWH") %>%
- mutate(prediction = factor(prediction), cluster=factor(cluster)) %>%
- ggplot(aes(cluster, prediction, fill=AWH)) +
- geom_tile() +
- scale_fill_distiller(palette = "RdPu") +
- labs(x="Predicted domain", y="")
-awc1 <- na.omit(res1[,c("SpatialAWC", "class")]) %>% mutate(class = levels(data$reference)[class])
-awc2 <- na.omit(res2[,c("SpatialAWC", "class")]) %>% mutate(class = levels(data$reference)[class])
-awc3 <- na.omit(res3[,c("SpatialAWC", "class")]) %>% mutate(class = levels(data$reference)[class])
-
-awc <- cbind(bind_rows(list(awc1, awc2, awc3), .id="P")) %>%
- pivot_wider(names_from = class, values_from = SpatialAWC) %>%
- subset(select = -c(P))
-awc <- as.matrix(awc)
-rownames(awc) <- c("P1", "P2", "P3")
-
-
-awc <- data.frame(awc)
-awc$prediction <- rownames(awc)
-
-
-p5 <- awc %>% pivot_longer(cols=-c("prediction"), names_to="class", values_to = "AWC") %>%
- mutate(prediction = factor(prediction), class=factor(class)) %>%
- ggplot(aes(class, prediction, fill=AWC)) +
- geom_tile() +
- scale_fill_distiller(palette = "RdPu") +
- labs(x="Annotated domain", y="")
The class-level AWC highlights that in P2, Layer3 has low -completeness. This align with our simulation that Layer3 is splitted -into 3 clusters in P2. Similarly, the cluster-level AWH highlights that -in P3, cluster 3 has low homogeneity, consistent with the merging of -layer 4 and 5.
-One can also calculate element-level metric, SPC, for -visualization.
-
-res1 <- cbind(getSpatialExternalMetrics(true=data$reference, pred=data$P1,
- location=data[,c("pxl_col_in_fullres","pxl_row_in_fullres")], level="element",
- metrics=c("SpatialSPC"), k=6,
- fuzzy_true = TRUE, fuzzy_pred = FALSE, useNegatives = FALSE),
- data[,c("pxl_col_in_fullres", "pxl_row_in_fullres")])
-
-res2 <- cbind(getSpatialExternalMetrics(true=data$reference, pred=data$P2,
- location=data[,c("pxl_col_in_fullres","pxl_row_in_fullres")], level="element",
- metrics=c("SpatialSPC"), k=6,
- fuzzy_true = TRUE, fuzzy_pred = FALSE, useNegatives = FALSE),
- data[,c("pxl_col_in_fullres", "pxl_row_in_fullres")])
-
-res3 <- cbind(getSpatialExternalMetrics(true=data$reference, pred=data$P3,
- location=data[,c("pxl_col_in_fullres","pxl_row_in_fullres")], level="element",
- metrics=c("SpatialSPC"), k=6,
- fuzzy_true = TRUE, fuzzy_pred = FALSE, useNegatives = FALSE),
- data[,c("pxl_col_in_fullres", "pxl_row_in_fullres")])
-
-
-cbind(bind_rows(list(res1, res2, res3), .id="P")) %>%
- pivot_longer(cols=c("SpatialSPC"),
- names_to="metric", values_to="value") %>%
- ggplot(aes(x = pxl_col_in_fullres, y = - pxl_row_in_fullres, color = value)) +
- scale_colour_gradient(high="white", low ="deeppink4") +
- geom_point(size=0.3) +
- facet_wrap(~P, scales = "free") +
- theme_bw() + labs(x="Prediction", y="", color="SpatialSPC")
-This clear highlights the low concordance regions in each prediction as -expected.
-When the manual annotation is not available, one can use internal -metrics, CHAOS, ELSA and PAS, to understand the domain continuity and -local homogeneity for a domain detection result. To illustrate this, we -simulate P4 and P5 with 20% and 30% random noise, respectively.
-
-# P4: add 20% random noise
-data$P4 <- simulate_clustering_variation(
- data$reference,
- noise_level = 0.2
-)
-
-# P5: add 30% random noise
-data$P5 <- simulate_clustering_variation(
- data$reference,
- noise_level = 0.3
-)
We calculate the internal spatial metrics for P1-P5:
-
-internal <-lapply(setNames(c("reference","P1","P2","P3","P4","P5"), c("reference","P1","P2","P3","P4","P5")),
- function(x){getSpatialInternalMetrics(data[[x]], location=data[,c("pxl_col_in_fullres","pxl_row_in_fullres")],
- k=6, level="dataset",
- metrics=c("PAS", "ELSA", "CHAOS"))})
-## the specified variable is considered as categorical...
-## the specified variable is considered as categorical...
-## the specified variable is considered as categorical...
-## the specified variable is considered as categorical...
-## the specified variable is considered as categorical...
-## the specified variable is considered as categorical...
-internal <- bind_rows(internal,.id = "prediction")
-internal %>%
- pivot_longer(cols=-c("prediction"),
- names_to="metric", values_to="value") %>%
- filter(metric %in% c("ELSA", "PAS", "CHAOS")) %>%
- ggplot(aes(x=prediction, y=value, group=metric)) +
- geom_point(size=3, aes(color=prediction)) +
- facet_wrap(~metric, scales = "free") +
- theme_bw() + labs(x="", color="") +
- theme(legend.position="None",
- axis.text.x = element_text(angle = 45, vjust = 0.5, hjust = 1))
The lower the scores, the smoother the predictions. As expected, the -smoothness decrease from P3 to P5 as the noise level increase.
-The internal metrics can also be calculated at the element level. For -example we can calculate the element-wise ELSA score, which is a score -for local diversity and can be regarded as edge detector:
-
-internal <-lapply(setNames(c("reference","P1","P2","P3","P4","P5"), c("reference","P1","P2","P3","P4","P5")),
- function(x){cbind(
- getSpatialInternalMetrics(data[[x]],
- location = data[,c("pxl_col_in_fullres","pxl_row_in_fullres")],
- k=6, level="element", metrics=c( "ELSA")),
- data[,c("pxl_col_in_fullres", "pxl_row_in_fullres")])})
-## the specified variable is considered as categorical...
-## the specified variable is considered as categorical...
-## the specified variable is considered as categorical...
-## the specified variable is considered as categorical...
-## the specified variable is considered as categorical...
-## the specified variable is considered as categorical...
-internal <- bind_rows(internal,.id = "prediction")
-
-internal %>%
- ggplot(aes(x = pxl_col_in_fullres, y = - pxl_row_in_fullres, color = ELSA)) +
- scale_colour_gradient(low="white", high="deeppink4") +
- geom_point(size=0.4) +
- facet_wrap(~prediction, scales = "free") +
- theme_bw() + labs(x="", y="", color="ELSA")
-sessionInfo()
-## R version 4.4.2 (2024-10-31)
-## Platform: x86_64-pc-linux-gnu
-## Running under: Ubuntu 22.04.5 LTS
-##
-## Matrix products: default
-## BLAS: /usr/lib/x86_64-linux-gnu/blas/libblas.so.3.10.0
-## LAPACK: /usr/lib/x86_64-linux-gnu/lapack/liblapack.so.3.10.0
-##
-## locale:
-## [1] LC_CTYPE=en_US.UTF-8 LC_NUMERIC=C
-## [3] LC_TIME=en_US.UTF-8 LC_COLLATE=en_US.UTF-8
-## [5] LC_MONETARY=en_US.UTF-8 LC_MESSAGES=en_US.UTF-8
-## [7] LC_PAPER=en_US.UTF-8 LC_NAME=C
-## [9] LC_ADDRESS=C LC_TELEPHONE=C
-## [11] LC_MEASUREMENT=en_US.UTF-8 LC_IDENTIFICATION=C
-##
-## time zone: Europe/Zurich
-## tzcode source: system (glibc)
-##
-## attached base packages:
-## [1] stats4 stats graphics grDevices utils datasets methods
-## [8] base
-##
-## other attached packages:
-## [1] tidyr_1.3.1 dplyr_1.1.4
-## [3] STexampleData_1.12.3 ExperimentHub_2.12.0
-## [5] AnnotationHub_3.12.0 BiocFileCache_2.12.0
-## [7] dbplyr_2.5.0 SpatialExperiment_1.14.0
-## [9] SingleCellExperiment_1.26.0 SummarizedExperiment_1.34.0
-## [11] Biobase_2.64.0 GenomicRanges_1.56.1
-## [13] GenomeInfoDb_1.40.1 IRanges_2.38.1
-## [15] S4Vectors_0.42.1 BiocGenerics_0.50.0
-## [17] MatrixGenerics_1.16.0 matrixStats_1.3.0
-## [19] cowplot_1.1.3 ggplot2_3.5.1
-## [21] poem_0.99.2 BiocStyle_2.32.1
-##
-## loaded via a namespace (and not attached):
-## [1] RColorBrewer_1.1-3 rstudioapi_0.16.0 jsonlite_1.8.8
-## [4] wk_0.9.4 magrittr_2.0.3 magick_2.8.4
-## [7] farver_2.1.2 rmarkdown_2.27 fs_1.6.4
-## [10] zlibbioc_1.50.0 ragg_1.3.2 vctrs_0.6.5
-## [13] spdep_1.3-6 memoise_2.0.1 elsa_1.1-28
-## [16] terra_1.5-21 htmltools_0.5.8.1 S4Arrays_1.4.1
-## [19] curl_5.2.1 BiocNeighbors_1.22.0 raster_3.5-15
-## [22] s2_1.1.7 SparseArray_1.4.8 sass_0.4.9
-## [25] spData_2.3.3 KernSmooth_2.23-24 bslib_0.8.0
-## [28] htmlwidgets_1.6.4 desc_1.4.3 cachem_1.1.0
-## [31] igraph_2.1.1 mime_0.12 lifecycle_1.0.4
-## [34] pkgconfig_2.0.3 Matrix_1.7-0 R6_2.5.1
-## [37] fastmap_1.2.0 GenomeInfoDbData_1.2.12 rbibutils_2.3
-## [40] aricode_1.0.3 clue_0.3-65 digest_0.6.36
-## [43] colorspace_2.1-1 AnnotationDbi_1.66.0 textshaping_0.3.6
-## [46] RSQLite_2.3.7 labeling_0.4.3 filelock_1.0.3
-## [49] fansi_1.0.6 httr_1.4.7 abind_1.4-5
-## [52] compiler_4.4.2 proxy_0.4-27 bit64_4.0.5
-## [55] withr_3.0.1 BiocParallel_1.38.0 DBI_1.2.3
-## [58] highr_0.11 MASS_7.3-61 rappdirs_0.3.3
-## [61] DelayedArray_0.30.1 rjson_0.2.21 classInt_0.4-10
-## [64] bluster_1.14.0 tools_4.4.2 units_0.8-0
-## [67] glue_1.8.0 dbscan_1.2-0 grid_4.4.2
-## [70] sf_1.0-6 cluster_2.1.6 generics_0.1.3
-## [73] gtable_0.3.5 clevr_0.1.2 class_7.3-22
-## [76] fclust_2.1.1.1 sp_2.1-4 utf8_1.2.4
-## [79] XVector_0.44.0 BiocVersion_3.19.1 pillar_1.9.0
-## [82] lattice_0.22-6 bit_4.0.5 deldir_2.0-4
-## [85] tidyselect_1.2.1 Biostrings_2.72.1 knitr_1.48
-## [88] bookdown_0.40 xfun_0.46 UCSC.utils_1.0.0
-## [91] yaml_2.3.10 boot_1.3-30 evaluate_0.24.0
-## [94] codetools_0.2-20 tibble_3.2.1 mclustcomp_0.3.3
-## [97] BiocManager_1.30.23 cli_3.6.3 systemfonts_1.1.0
-## [100] Rdpack_2.6.1 munsell_0.5.1 jquerylib_0.1.4
-## [103] Rcpp_1.0.13 png_0.1-8 parallel_4.4.2
-## [106] pkgdown_2.1.1 blob_1.2.4 scales_1.3.0
-## [109] e1071_1.7-9 purrr_1.0.2 crayon_1.5.3
-## [112] rlang_1.1.4 KEGGREST_1.44.1
vignettes/fuzzy_metrics.Rmd
- fuzzy_metrics.Rmd
-data("sp_toys")
-data <- sp_toys
-s <- 3
-st <- 1
-p0 <- ggplot(data, aes(x, y,
- color=label)) +
- geom_point(size=s, alpha=0.5) + scale_y_reverse() + theme_bw() +
- geom_point(shape = 1, size = s, stroke = st, aes(color=label)) +
- labs(x="",y="", title="GT1")
-
-
-p1 <- ggplot(data, aes(x, y,
- color=label)) +
- geom_point(size=s, alpha=0.5) + scale_y_reverse() + theme_bw() +
- geom_point(shape = 1, size = s, stroke = st, aes(color=p1)) +
- labs(x="",y="", title="P1")
-
-
-p2 <- ggplot(data, aes(x, y,
- color=label)) +
- geom_point(size=s, alpha=0.5) + scale_y_reverse() + theme_bw() +
- geom_point(shape = 1, size = s, stroke = st, aes(color=p2)) +
- labs(x="",y="", title="P2")
-
-p3 <- ggplot(data, aes(x, y,
- color=label)) +
- geom_point(size=s, alpha=0.5) + scale_y_reverse() + theme_bw() +
- geom_point(shape = 1, size = s, stroke = st, aes(color=p3)) +
- labs(x="",y="", title="P3")
-
-ps1 <- plot_grid(
- p0 + theme(legend.position = "none", plot.title = element_text(hjust = 0.5), plot.margin = margin(5, 2, -2, 0),
- axis.text.x = element_blank(), axis.text.y = element_blank(),axis.ticks.x = element_blank(), axis.ticks.y = element_blank()),
- p1 + theme(legend.position = "none", plot.title = element_text(hjust = 0.5), plot.margin = margin(5, 2, -2, 0),
- axis.text.x = element_blank(), axis.text.y = element_blank(),axis.ticks.x = element_blank(), axis.ticks.y = element_blank()),
- p2 + theme(legend.position = "none", plot.title = element_text(hjust = 0.5), plot.margin = margin(5, 2, -2, 0),
- axis.text.x = element_blank(), axis.text.y = element_blank(),axis.ticks.x = element_blank(), axis.ticks.y = element_blank()),
- p3 + theme(legend.position = "none", plot.title = element_text(hjust = 0.5), plot.margin = margin(5, 2, -2, 0),
- axis.text.x = element_blank(), axis.text.y = element_blank(),axis.ticks.x = element_blank(), axis.ticks.y = element_blank()),
- ncol = 4)
-plot(ps1)
-gt1 <- getFuzzyLabel(data$label, data[,c("x","y")], k=6, alpha=0.5)
-gt1
-## 1 2
-## 1 0.0000000 1.0000000
-## 2 0.0000000 1.0000000
-## 3 0.0000000 1.0000000
-## 4 0.1428571 0.8571429
-## 5 0.6666667 0.3333333
-## 6 1.0000000 0.0000000
-## 7 1.0000000 0.0000000
-## 8 1.0000000 0.0000000
-## 9 1.0000000 0.0000000
-## 10 1.0000000 0.0000000
-## 11 1.0000000 0.0000000
-## 12 1.0000000 0.0000000
-## 13 1.0000000 0.0000000
-## 14 1.0000000 0.0000000
-## 15 1.0000000 0.0000000
-## 16 0.0000000 1.0000000
-## 17 0.0000000 1.0000000
-## 18 0.0000000 1.0000000
-## 19 0.1666667 0.8333333
-## 20 0.8333333 0.1666667
-## 21 1.0000000 0.0000000
-## 22 1.0000000 0.0000000
-## 23 1.0000000 0.0000000
-## 24 1.0000000 0.0000000
-## 25 1.0000000 0.0000000
-## 26 1.0000000 0.0000000
-## 27 1.0000000 0.0000000
-## 28 1.0000000 0.0000000
-## 29 1.0000000 0.0000000
-## 30 1.0000000 0.0000000
-## 31 0.0000000 1.0000000
-## 32 0.0000000 1.0000000
-## 33 0.0000000 1.0000000
-## 34 0.0000000 1.0000000
-## 35 0.1666667 0.8333333
-## 36 0.8333333 0.1666667
-## 37 1.0000000 0.0000000
-## 38 1.0000000 0.0000000
-## 39 1.0000000 0.0000000
-## 40 1.0000000 0.0000000
-## 41 1.0000000 0.0000000
-## 42 1.0000000 0.0000000
-## 43 1.0000000 0.0000000
-## 44 1.0000000 0.0000000
-## 45 1.0000000 0.0000000
-## 46 0.0000000 1.0000000
-## 47 0.0000000 1.0000000
-## 48 0.0000000 1.0000000
-## 49 0.0000000 1.0000000
-## 50 0.1666667 0.8333333
-## 51 0.8333333 0.1666667
-## 52 1.0000000 0.0000000
-## 53 1.0000000 0.0000000
-## 54 1.0000000 0.0000000
-## 55 1.0000000 0.0000000
-## 56 1.0000000 0.0000000
-## 57 1.0000000 0.0000000
-## 58 1.0000000 0.0000000
-## 59 1.0000000 0.0000000
-## 60 1.0000000 0.0000000
-## 61 0.0000000 1.0000000
-## 62 0.0000000 1.0000000
-## 63 0.0000000 1.0000000
-## 64 0.0000000 1.0000000
-## 65 0.0000000 1.0000000
-## 66 0.1666667 0.8333333
-## 67 0.8333333 0.1666667
-## 68 1.0000000 0.0000000
-## 69 1.0000000 0.0000000
-## 70 1.0000000 0.0000000
-## 71 1.0000000 0.0000000
-## 72 1.0000000 0.0000000
-## 73 1.0000000 0.0000000
-## 74 1.0000000 0.0000000
-## 75 1.0000000 0.0000000
-## 76 0.0000000 1.0000000
-## 77 0.0000000 1.0000000
-## 78 0.0000000 1.0000000
-## 79 0.0000000 1.0000000
-## 80 0.0000000 1.0000000
-## 81 0.1666667 0.8333333
-## 82 0.8333333 0.1666667
-## 83 1.0000000 0.0000000
-## 84 1.0000000 0.0000000
-## 85 1.0000000 0.0000000
-## 86 1.0000000 0.0000000
-## 87 1.0000000 0.0000000
-## 88 1.0000000 0.0000000
-## 89 1.0000000 0.0000000
-## 90 1.0000000 0.0000000
-## 91 0.0000000 1.0000000
-## 92 0.0000000 1.0000000
-## 93 0.0000000 1.0000000
-## 94 0.0000000 1.0000000
-## 95 0.0000000 1.0000000
-## 96 0.0000000 1.0000000
-## 97 0.1666667 0.8333333
-## 98 0.8333333 0.1666667
-## 99 1.0000000 0.0000000
-## 100 1.0000000 0.0000000
-## 101 1.0000000 0.0000000
-## 102 1.0000000 0.0000000
-## 103 1.0000000 0.0000000
-## 104 1.0000000 0.0000000
-## 105 1.0000000 0.0000000
-## 106 0.0000000 1.0000000
-## 107 0.0000000 1.0000000
-## 108 0.0000000 1.0000000
-## 109 0.0000000 1.0000000
-## 110 0.0000000 1.0000000
-## 111 0.0000000 1.0000000
-## 112 0.1666667 0.8333333
-## 113 0.8333333 0.1666667
-## 114 1.0000000 0.0000000
-## 115 1.0000000 0.0000000
-## 116 1.0000000 0.0000000
-## 117 1.0000000 0.0000000
-## 118 1.0000000 0.0000000
-## 119 1.0000000 0.0000000
-## 120 1.0000000 0.0000000
-## 121 0.0000000 1.0000000
-## 122 0.0000000 1.0000000
-## 123 0.0000000 1.0000000
-## 124 0.0000000 1.0000000
-## 125 0.0000000 1.0000000
-## 126 0.0000000 1.0000000
-## 127 0.0000000 1.0000000
-## 128 0.1666667 0.8333333
-## 129 0.8333333 0.1666667
-## 130 1.0000000 0.0000000
-## 131 1.0000000 0.0000000
-## 132 1.0000000 0.0000000
-## 133 1.0000000 0.0000000
-## 134 1.0000000 0.0000000
-## 135 1.0000000 0.0000000
-## 136 0.0000000 1.0000000
-## 137 0.0000000 1.0000000
-## 138 0.0000000 1.0000000
-## 139 0.0000000 1.0000000
-## 140 0.0000000 1.0000000
-## 141 0.0000000 1.0000000
-## 142 0.0000000 1.0000000
-## 143 0.1666667 0.8333333
-## 144 0.8333333 0.1666667
-## 145 1.0000000 0.0000000
-## 146 1.0000000 0.0000000
-## 147 1.0000000 0.0000000
-## 148 1.0000000 0.0000000
-## 149 1.0000000 0.0000000
-## 150 1.0000000 0.0000000
-## 151 0.0000000 1.0000000
-## 152 0.0000000 1.0000000
-## 153 0.0000000 1.0000000
-## 154 0.0000000 1.0000000
-## 155 0.0000000 1.0000000
-## 156 0.0000000 1.0000000
-## 157 0.0000000 1.0000000
-## 158 0.0000000 1.0000000
-## 159 0.1666667 0.8333333
-## 160 0.8333333 0.1666667
-## 161 1.0000000 0.0000000
-## 162 1.0000000 0.0000000
-## 163 1.0000000 0.0000000
-## 164 1.0000000 0.0000000
-## 165 1.0000000 0.0000000
-## 166 0.0000000 1.0000000
-## 167 0.0000000 1.0000000
-## 168 0.0000000 1.0000000
-## 169 0.0000000 1.0000000
-## 170 0.0000000 1.0000000
-## 171 0.0000000 1.0000000
-## 172 0.0000000 1.0000000
-## 173 0.0000000 1.0000000
-## 174 0.1666667 0.8333333
-## 175 0.8333333 0.1666667
-## 176 1.0000000 0.0000000
-## 177 1.0000000 0.0000000
-## 178 1.0000000 0.0000000
-## 179 1.0000000 0.0000000
-## 180 1.0000000 0.0000000
-## 181 0.0000000 1.0000000
-## 182 0.0000000 1.0000000
-## 183 0.0000000 1.0000000
-## 184 0.0000000 1.0000000
-## 185 0.0000000 1.0000000
-## 186 0.0000000 1.0000000
-## 187 0.0000000 1.0000000
-## 188 0.0000000 1.0000000
-## 189 0.0000000 1.0000000
-## 190 0.1666667 0.8333333
-## 191 0.8333333 0.1666667
-## 192 1.0000000 0.0000000
-## 193 1.0000000 0.0000000
-## 194 1.0000000 0.0000000
-## 195 1.0000000 0.0000000
-## 196 0.0000000 1.0000000
-## 197 0.0000000 1.0000000
-## 198 0.0000000 1.0000000
-## 199 0.0000000 1.0000000
-## 200 0.0000000 1.0000000
-## 201 0.0000000 1.0000000
-## 202 0.0000000 1.0000000
-## 203 0.0000000 1.0000000
-## 204 0.0000000 1.0000000
-## 205 0.1666667 0.8333333
-## 206 0.8333333 0.1666667
-## 207 1.0000000 0.0000000
-## 208 1.0000000 0.0000000
-## 209 1.0000000 0.0000000
-## 210 1.0000000 0.0000000
-## 211 0.0000000 1.0000000
-## 212 0.0000000 1.0000000
-## 213 0.0000000 1.0000000
-## 214 0.0000000 1.0000000
-## 215 0.0000000 1.0000000
-## 216 0.0000000 1.0000000
-## 217 0.0000000 1.0000000
-## 218 0.0000000 1.0000000
-## 219 0.0000000 1.0000000
-## 220 0.0000000 1.0000000
-## 221 0.1666667 0.8333333
-## 222 0.8333333 0.1666667
-## 223 1.0000000 0.0000000
-## 224 1.0000000 0.0000000
-## 225 1.0000000 0.0000000
-## 226 0.0000000 1.0000000
-## 227 0.0000000 1.0000000
-## 228 0.0000000 1.0000000
-## 229 0.0000000 1.0000000
-## 230 0.0000000 1.0000000
-## 231 0.0000000 1.0000000
-## 232 0.0000000 1.0000000
-## 233 0.0000000 1.0000000
-## 234 0.0000000 1.0000000
-## 235 0.0000000 1.0000000
-## 236 0.2857143 0.7142857
-## 237 0.8571429 0.1428571
-## 238 1.0000000 0.0000000
-## 239 1.0000000 0.0000000
-## 240 1.0000000 0.0000000
a comparison of any clustering result with itself achieves the -maximum of the index.
-
-fuzzyPartitionMetrics(gt1, gt1)
-## $NDC
-## [1] 1
-##
-## $ACI
-## [1] 1
-##
-## $fuzzyWH
-## $fuzzyWH$global
-## [1] 1
-##
-## $fuzzyWH$perPartition
-## 1 2
-## 1 1
-##
-##
-## $fuzzyWC
-## $fuzzyWC$global
-## [1] 1
-##
-## $fuzzyWC$perPartition
-## 1 2
-## 1 1
-##
-##
-## $fuzzyAWH
-## $fuzzyAWH$global
-## [1] 1
-##
-## $fuzzyAWH$perPartition
-## 1 2
-## 1 1
-##
-##
-## $fuzzyAWC
-## $fuzzyAWC$global
-## [1] 1
-##
-## $fuzzyAWC$perPartition
-## 1 2
-## 1 1
-fuzzyHardMetrics(data$label, gt1, data$label)
-## $NDC
-## [1] 1
-##
-## $ACI
-## [1] 1
-##
-## $fuzzyWH
-## $fuzzyWH$global
-## [1] 1
-##
-## $fuzzyWH$perPartition
-## 1 2
-## 1 1
-##
-##
-## $fuzzyWC
-## $fuzzyWC$global
-## [1] 1
-##
-## $fuzzyWC$perPartition
-## 1 2
-## 1 1
-##
-##
-## $fuzzyAWH
-## $fuzzyAWH$global
-## [1] 1
-##
-## $fuzzyAWH$perPartition
-## 1 2
-## 1 1
-##
-##
-## $fuzzyAWC
-## $fuzzyAWC$global
-## [1] 1
-##
-## $fuzzyAWC$perPartition
-## 1 2
-## 1 1
-sessionInfo()
-## R version 4.4.2 (2024-10-31)
-## Platform: x86_64-pc-linux-gnu
-## Running under: Ubuntu 22.04.5 LTS
-##
-## Matrix products: default
-## BLAS: /usr/lib/x86_64-linux-gnu/blas/libblas.so.3.10.0
-## LAPACK: /usr/lib/x86_64-linux-gnu/lapack/liblapack.so.3.10.0
-##
-## locale:
-## [1] LC_CTYPE=en_US.UTF-8 LC_NUMERIC=C
-## [3] LC_TIME=en_US.UTF-8 LC_COLLATE=en_US.UTF-8
-## [5] LC_MONETARY=en_US.UTF-8 LC_MESSAGES=en_US.UTF-8
-## [7] LC_PAPER=en_US.UTF-8 LC_NAME=C
-## [9] LC_ADDRESS=C LC_TELEPHONE=C
-## [11] LC_MEASUREMENT=en_US.UTF-8 LC_IDENTIFICATION=C
-##
-## time zone: Europe/Zurich
-## tzcode source: system (glibc)
-##
-## attached base packages:
-## [1] stats graphics grDevices utils datasets methods base
-##
-## other attached packages:
-## [1] cowplot_1.1.3 ggplot2_3.5.1 poem_0.99.2 BiocStyle_2.32.1
-##
-## loaded via a namespace (and not attached):
-## [1] tidyselect_1.2.1 dplyr_1.1.4 farver_2.1.2
-## [4] fastmap_1.2.0 bluster_1.14.0 digest_0.6.36
-## [7] lifecycle_1.0.4 sf_1.0-6 cluster_2.1.6
-## [10] terra_1.5-21 magrittr_2.0.3 compiler_4.4.2
-## [13] rlang_1.1.4 sass_0.4.9 tools_4.4.2
-## [16] mclustcomp_0.3.3 igraph_2.1.1 utf8_1.2.4
-## [19] yaml_2.3.10 knitr_1.48 labeling_0.4.3
-## [22] htmlwidgets_1.6.4 sp_2.1-4 classInt_0.4-10
-## [25] BiocParallel_1.38.0 KernSmooth_2.23-24 fclust_2.1.1.1
-## [28] elsa_1.1-28 withr_3.0.1 BiocGenerics_0.50.0
-## [31] desc_1.4.3 grid_4.4.2 stats4_4.4.2
-## [34] fansi_1.0.6 e1071_1.7-9 colorspace_2.1-1
-## [37] aricode_1.0.3 scales_1.3.0 MASS_7.3-61
-## [40] cli_3.6.3 rmarkdown_2.27 ragg_1.3.2
-## [43] generics_0.1.3 rstudioapi_0.16.0 spdep_1.3-6
-## [46] DBI_1.2.3 cachem_1.1.0 proxy_0.4-27
-## [49] parallel_4.4.2 BiocManager_1.30.23 s2_1.1.7
-## [52] vctrs_0.6.5 boot_1.3-30 Matrix_1.7-0
-## [55] jsonlite_1.8.8 spData_2.3.3 bookdown_0.40
-## [58] clevr_0.1.2 S4Vectors_0.42.1 BiocNeighbors_1.22.0
-## [61] clue_0.3-65 systemfonts_1.1.0 jquerylib_0.1.4
-## [64] units_0.8-0 glue_1.8.0 pkgdown_2.1.1
-## [67] codetools_0.2-20 gtable_0.3.5 deldir_2.0-4
-## [70] raster_3.5-15 munsell_0.5.1 tibble_3.2.1
-## [73] pillar_1.9.0 htmltools_0.5.8.1 R6_2.5.1
-## [76] wk_0.9.4 textshaping_0.3.6 Rdpack_2.6.1
-## [79] evaluate_0.24.0 lattice_0.22-6 highr_0.11
-## [82] rbibutils_2.3 bslib_0.8.0 class_7.3-22
-## [85] Rcpp_1.0.13 xfun_0.46 fs_1.6.4
-## [88] pkgconfig_2.0.3
vignettes/poem.Rmd
- poem.Rmd
-if (!requireNamespace("devtools", quietly = TRUE))
- install.packages("devtools")
-devtools::install_github("RoseYuan/poem")
This package provides multiple approaches for comparing two -partitions1 of the same dataset, and evaluating the -alignment between a dataset’s embedding/graph representations and its -partition.
-Besides, this package further offers methods for comparing two fuzzy -partitions2 as well as for comparing a hard partition -with a fuzzy partition. This allows the evaluation of fuzzy partition -results by assessing its agreement to a fuzzy or a hard ground-truth -partition.
-Finally, the package implements visualization and evaluation metrics -tailored for domain detection in spatially-resolved -omics data. These -include especially external evaluation metrics (i.e. based on a -comparison to ground truth labels), but also internal metrics.
-The package poem includes many metrics to perform different -kinds of evaluations, and these metrics can be retrieved via 6 main -wrapper functions. Unless specified, “partition” means “hard” partition. -They are:
-getEmbeddingMetrics()
: Metrics to compare an embedding
-of data points to a partition of these data points.getGraphMetrics()
: Metrics to compare a graph
-(e.g. kNN/sNN) to a partition, where nodes in the graph are data points
-in the partition.getPartitionMetrics()
: Metrics to compare two
-partitions of the same dataset.getfuzzyPartitionMetrics()
: Metrics to compare two
-fuzzy partitions, or to compare between a fuzzy and a hard partition of
-the same dataset.getSpatialExternalMetrics()
: External metrics for
-evaluating spatial clustering results in a spatial-aware fashion. For
-non-spatial-aware evaluation, one can directly use
-getPartitionMetrics()
.getSpatialInternalMetrics()
: Internal metrics for
-evaluating spatial clustering results in a spatial-aware fashion.There are 3 different levels where one can perform the -above-mentioned evaluation: element-level, class-level, and -dataset-level. Element-level evaluation reports metric values for each -data point; Class-level evaluation reports metrics for each classes3 or -clusters4; and dataset-level evaluation returns a -single metric value for the whole dataset.
-The following table illustrates available metrics at different -evaluation levels, and the main functions used to retrieve them.
- - - -To showcase the main functions, we will use some simulated datasets -as examples in this vignette.
-The two datasets, g1
and g2
, both contain
-80 data points with x
and y
coordinates and of
-4 different classes.
-data(toyExamples)
-g1 <- toyExamples[toyExamples$graph=="graph1",]
-g2 <- toyExamples[toyExamples$graph=="graph2",]
-head(g1)
-## graph x y class
-## 641 graph1 -0.6290416 -0.487293 class1
-## 642 graph1 -2.5646982 -1.742079 class1
-## 643 graph1 -1.6368716 -1.911560 class1
-## 644 graph1 -1.3671374 -2.120897 class1
-## 645 graph1 -1.5957317 -3.194329 class1
-## 646 graph1 -2.1061245 -1.388003 class1
If we plot them out:
-
-ggplot(rbind(g1,g2), aes(x,y,color=class, shape=class)) +
- geom_point() +
- facet_wrap(~graph) +
- theme_bw()
Let’s assume g1
and g2
contain two
-different embeddings of the same set of objects. A “good” embedding
-should put objects of the same class together, and objects of different
-class apart. Since we know the ground-truth class of each object, one
-can evaluation such “goodness” of an embedding by calculating embedding
-evaluation metrics. One can calculate such metrics element-wise, for
-each class/cluster, or for the whole dataset.
For example, at the element level, one can calculate the Silhouette
-Width by specifying level="element"
and
-metrics=c("SW")
:
-sw <- getEmbeddingMetrics(x=g1[,c("x","y")], labels=g1$class, metrics=c("SW"),
- level="element")
-head(sw)
-## class SW
-## 641 class1 0.2986628
-## 642 class1 0.5818507
-## 643 class1 0.6299871
-## 644 class1 0.5867285
-## 645 class1 0.5191290
-## 646 class1 0.5679847
The output will be a data.frame
containing the metric
-values for the specified level.
-g1$sw <- getEmbeddingMetrics(x=g1[,c("x","y")], labels=g1$class,
- metrics=c("SW"), level="element")$SW
-g2$sw <- getEmbeddingMetrics(x=g2[,c("x","y")], labels=g2$class,
- metrics=c("SW"), level="element")$SW
-ggplot(rbind(g1,g2), aes(x, y, color=sw, shape=class)) +
- geom_point() +
- facet_wrap(~graph) +
- theme_bw()
One can also evaluate at each class level, by specifying
-level="class"
. Check ?getEmbeddingMetrics
to
-see what are the allowed metrics at the class level. For example:
-cl <- getEmbeddingMetrics(x=g1[,c("x","y")], labels=g1$class,
- metrics=c("dbcv", "meanSW"), level="class")
-head(cl)
-## class meanSW dbcv
-## 1 class1 0.4240817 -0.37367780
-## 2 class2 0.4897828 -0.34617982
-## 3 class3 0.5021555 0.07752233
-## 4 class4 0.5957709 0.26757842
-res1 <- getEmbeddingMetrics(x=g1[,c("x","y")], labels=g1$class,
- metrics=c("dbcv", "meanSW"), level="class")
-res2 <- getEmbeddingMetrics(x=g2[,c("x","y")], labels=g2$class,
- metrics=c("dbcv", "meanSW"), level="class")
-
-bind_rows(list(graph1=res1, graph2=res2), .id="graph") %>%
- pivot_longer(cols=c("meanSW","dbcv"), names_to="metric",values_to="value") %>%
-ggplot(aes(class, value, fill=graph, group=graph)) +
- geom_bar(position = "dodge", stat = "identity") +
- facet_wrap(~metric) +
- theme_bw()
Similarly, one can evaluate at the dataset level by specifying
-level="dataset"
. For example:
-getEmbeddingMetrics(x=g1[,c("x","y")], labels=g1$class, level="dataset",
- metrics=c("meanSW", "meanClassSW", "pnSW", "minClassSW",
- "cdbw", "cohesion", "compactness", "sep", "dbcv"))
-## meanSW meanClassSW pnSW minClassSW cdbw cohesion compactness
-## 1 0.5029477 0.5029477 0.0375 0.4240817 0.0553208 0.2732925 0.2800803
-## sep dbcv
-## 1 0.7227335 -0.09368922
Instead of directly using the distances or densities in the embedding
-space for evaluation, one may want to evaluate from a connectivity stand
-point by looking at the graph structure constructed from the above
-datasets. getGraphMetrics()
can perform k nearest neighbor
-(KNN) graph or shared nearest neighbor graph (SNN) construction from an
-embedding and then apply graph-based evaluation metrics.
-# Some functions for plotting
-plotGraphs <- function(d, k=7){
- gn <- dplyr::bind_rows(lapply(split(d[,-1],d$graph), FUN=function(d1){
- nn <- emb2knn(as.matrix(d1[,c("x","y")]), k=k)
- g <- poem:::.nn2graph(nn, labels=d1$class)
- ggnetwork(g, layout=as.matrix(d1[,1:2]), scale=FALSE)
- }), .id="graph")
- ggplot(gn, aes(x = x, y = y, xend = xend, yend = yend)) + theme_blank() +
- theme(legend.position = "right") + geom_edges(alpha=0.5, colour="grey") +
- geom_nodes(aes(colour=class, shape=class), size=2) + facet_wrap(~graph, nrow=1)
-}
For our examples g1
and g2
, the constructed
-graphs will look like:
Use ?getGraphMetrics()
to check optional arguments for
-KNN/SNN graph construction.
Similarly, level
can be "element"
,
-"class"
or "dataset"
.
-getGraphMetrics(x=g1[,c("x","y")], labels=g1$class, metrics=c("PWC","ISI"),
- level="class", directed=FALSE, k=7, shared=FALSE)
-## class PWC ISI
-## class1 class1 0.05 1.186272
-## class2 class2 0.10 1.224188
-## class3 class3 0.05 1.149098
-## class4 class4 0.05 1.251146
-res1 <- getGraphMetrics(x=g1[,c("x","y")], labels=g1$class,metrics=c("PWC","ISI"), level="class", directed=FALSE, k=7, shared=FALSE)
-res2 <- getGraphMetrics(x=g2[,c("x","y")], labels=g2$class, metrics=c("PWC","ISI"), level="class", directed=FALSE, k=7, shared=FALSE)
-
-bind_rows(list(graph1=res1, graph2=res2), .id="graph") %>%
- pivot_longer(cols=c("PWC","ISI"), names_to="metric",values_to="value") %>%
-ggplot(aes(class, value, fill=graph, group=graph)) +
- geom_bar(position = "dodge", stat = "identity") +
- facet_wrap(~metric) +
- theme_bw()
Alternatively, getGraphMetrics()
can take an
-igraph object as x
, which enables the application
-of the evaluation metrics to a general graph, or a list of nearest
-neighbors as x
, to accelerate the computation for large
-datasets.
We construct SNN graph from g1 and g2 embeddings, and then apply -Louvain algorithm to get partitions out of them.
-
-k <- 7
-r <- 0.5
-snn1 <- emb2snn(as.matrix(g1[,c("x","y")]), k=k)
-snn2 <- emb2snn(as.matrix(g2[,c("x","y")]), k=k)
-g1$cluster <- factor(igraph::cluster_louvain(snn1, resolution = r)$membership)
-g2$cluster <- factor(igraph::cluster_louvain(snn2, resolution = r)$membership)
-
-ggplot(rbind(g1,g2), aes(x,y,color=cluster, shape=class)) +
- geom_point() +
- facet_wrap(~graph) +
- theme_bw()
We then compare the predictions with the known labels using the -partition metrics:
-
-# for g1
-getPartitionMetrics(true=g1$class, pred=g1$cluster, level="dataset",
- metrics = c("RI", "WC", "WH", "ARI", "AWC", "AWH",
- "FM", "AMI"))
-## RI WC WH ARI AWC AWH FM AMI
-## 1 0.9636076 0.925 0.9237845 0.9004285 0.9012088 0.8996496 0.9624922 0.8872892
-
-# for g2
-getPartitionMetrics(true=g2$class, pred=g2$cluster, level="dataset",
- metrics = c("RI", "WC", "WH", "ARI", "AWC", "AWH",
- "FM", "AMI"))
-## RI WC WH ARI AWC AWH FM AMI
-## 1 0.721519 0.95 0.4616368 0.4400954 0.9010025 0.2911552 0.6501669 0.4193846
Note that for class-level metrics, some are reported per class, while -some (specifically, “WH”, “AWH) are reported per cluster.
-
-getPartitionMetrics(true=g1$class, pred=g2$cluster, level="class")
-## WC AWC FM class WH AWH cluster
-## 1 0.9 0.802005 0.6551724 class1 NA NA <NA>
-## 2 0.9 0.802005 0.6551724 class2 NA NA <NA>
-## 3 1.0 1.000000 0.6451613 class3 NA NA <NA>
-## 4 1.0 1.000000 0.6451613 class4 NA NA <NA>
-## 5 NA NA NA <NA> 0.4864865 0.3238739 1
-## 6 NA NA NA <NA> 0.4413473 0.2644406 2
For comparing two fuzzy partitions or comparing a fuzzy partition to
-a hard patition, one can use
-getFuzzyPartitionMetrics()
.
The fuzzy reprensentation of a partion should look like the -following, where each row is a data point, and the value is the class -memberships to each class. Each row sums up to 1.
-
-fuzzyTrue <- matrix(c(
- 0.95, 0.025, 0.025,
- 0.98, 0.01, 0.01,
- 0.96, 0.02, 0.02,
- 0.95, 0.04, 0.01,
- 0.95, 0.01, 0.04,
- 0.99, 0.005, 0.005,
- 0.025, 0.95, 0.025,
- 0.97, 0.02, 0.01,
- 0.025, 0.025, 0.95),
- ncol = 3, byrow=TRUE)
-# a hard truth:
-hardTrue <- apply(fuzzyTrue,1,FUN=which.max)
-# some predicted labels:
-hardPred <- c(1,1,1,1,1,1,2,2,2)
-getFuzzyPartitionMetrics(hardPred=hardPred, hardTrue=hardTrue,
- fuzzyTrue=fuzzyTrue, nperms=3, level="class")
-## fuzzyWC fuzzyAWC class fuzzyWH fuzzyAWH cluster
-## 1 0.7195238 0.3542847 1 NA NA NA
-## 2 1.0000000 NaN 2 NA NA NA
-## 3 1.0000000 NaN 3 NA NA NA
-## 4 NA NA NA 1.00000000 1.0000000 1
-## 5 NA NA NA 0.06166667 -0.8064171 2
By using the input hardPred
, hardTrue
,
-fuzzyPred
, fuzzyTrue
, one can control whether
-the fuzzy or hard version of the two partitions is used in comparison.
-For example, when fuzzyTrue
and fuzzyPred
are
-not NULL
, metrics for comparing two fuzzy partitions will
-be used.
We use another toy example dataset in the package,
-sp_toys
, to illustrate spatial clustering evaluation.
-data(sp_toys)
-s <- 3
-st <- 1
-p1 <- ggplot(sp_toys, aes(x, y,
- color=label)) +
- geom_point(size=s, alpha=0.5) + scale_y_reverse() + theme_bw() +
- geom_point(shape = 1, size = s, stroke = st, aes(color=p1)) +
- labs(x="",y="", title="P1")
-
-p0 <- ggplot(sp_toys, aes(x, y,
- color=label)) +
- geom_point(size=s, alpha=0.5) + scale_y_reverse() + theme_bw() +
- geom_point(shape = 1, size = s, stroke = st, aes(color=label)) +
- labs(x="",y="", title="C")
-p2 <- ggplot(sp_toys, aes(x, y,
- color=label)) +
- geom_point(size=s, alpha=0.5) + scale_y_reverse() + theme_bw() +
- geom_point(shape = 1, size = s, stroke = st, aes(color=p2)) +
- labs(x="",y="", title="P2")
-
-plot_grid(p0 + theme(legend.position = "none",
- plot.title = element_text(hjust = 0.5)),
- p1 + theme(legend.position = "none",
- plot.title = element_text(hjust = 0.5)),
- p2 + theme(legend.position = "none",
- plot.title = element_text(hjust = 0.5)), ncol = 3)
Here in C, the spots are colored by the ground-truth class. In P1 and -P2, the color inside each spot is according to the ground-truth class, -while the color of the border is according to clustering predictions. P1 -and P2 misclassified the same amount of red spots into the blue -cluster.
-Let’s quantify this by calculating external spatial metrics:
-
-getSpatialExternalMetrics(true=sp_toys$label, pred=sp_toys$p1,
- location=sp_toys[,c("x","y")], level="dataset",
- metrics=c("SpatialARI","SpatialAccuracy"),
- fuzzy_true = TRUE, fuzzy_pred = FALSE)
-## SpatialARI SpatialAccuracy
-## 1 0.7871135 0.956746
By specifying fuzzy_true
and fuzzy_pred
,
-one can control whether the fuzzy or hard version of true
-and pred
is used in comparison. If fuzzy_true
-or fuzzy_pred
is TRUE
, the spatial
-neighborhood information will be used to construct the fuzzy
-representation of the class/cluster memberships.
-getSpatialExternalMetrics(true=sp_toys$label, pred=sp_toys$p1,
- location=sp_toys[,c("x","y")], level="class")
-## SpatialWH SpatialAWH SpatialWC SpatialAWC class cluster
-## 1 NA NA 0.8078698 0.5929504 1 NA
-## 2 NA NA 1.0000000 1.0000000 2 NA
-## 3 1.0000000 1.0000000 NA NA NA 1
-## 4 0.8323893 0.6493279 NA NA NA 2
-res1.1 <- getSpatialExternalMetrics(true=sp_toys$label, pred=sp_toys$p1,
- location=sp_toys[,c("x","y")], level="dataset",
- metrics=c("SpatialARI","SpatialAccuracy"),
- fuzzy_true = TRUE, fuzzy_pred = FALSE)
-res2.1 <- getSpatialExternalMetrics(true=sp_toys$label, pred=sp_toys$p2,
- location=sp_toys[,c("x","y")], level="dataset",
- metrics=c("SpatialARI","SpatialAccuracy"),
- fuzzy_true = TRUE, fuzzy_pred = FALSE)
-res1.2 <- getPartitionMetrics(true=sp_toys$label, pred=sp_toys$p1,
- level="dataset", metrics=c("ARI"))
-res2.2 <- getPartitionMetrics(true=sp_toys$label, pred=sp_toys$p2,
- level="dataset", metrics=c("ARI"))
-cbind(bind_rows(list(res1.1, res2.1), .id="P"),
- bind_rows(list(res1.2, res2.2), .id="P")) %>%
- pivot_longer(cols=c("SpatialARI", "SpatialAccuracy", "ARI"),
- names_to="metric", values_to="value") %>%
- ggplot(aes(x=P, y=value, group=metric)) +
- geom_point(size=3, aes(color=P)) +
- facet_wrap(~metric) +
- theme_bw() + labs(x="Prediction")
When the evaluation is non-spatial-aware, P1 and P2 get the same ARI -score. However, with spatial-aware metrics like SpatialARI and -SpatialAccuracy, P2 gets a higher scores than P1.
-Last but not least, there are internal metrics for spatial clustering -evaluation:
-
-sp_toys$c_elsa <- getSpatialInternalMetrics(label=sp_toys$label,
- location=sp_toys[,c("x","y")], level="element",
- metrics=c("ELSA"))$ELSA
-## the specified variable is considered as categorical...
-sp_toys$p1_elsa <- getSpatialInternalMetrics(label=sp_toys$p1,
- location=sp_toys[,c("x","y")], level="element",
- metrics=c("ELSA"))$ELSA
-## the specified variable is considered as categorical...
-sp_toys$p2_elsa <- getSpatialInternalMetrics(label=sp_toys$p2,
- location=sp_toys[,c("x","y")], level="element",
- metrics=c("ELSA"))$ELSA
-## the specified variable is considered as categorical...
-s <- 3
-st <- 1
-p1 <- ggplot(sp_toys, aes(x, y,
- color=p1_elsa)) +
- geom_point(size=s, alpha=0.5) + scale_y_reverse() + theme_bw() +
- labs(x="",y="", title="P1", color="ELSA") +
- scico::scale_color_scico(palette = "roma", limits = c(0, 1), direction=-1)
-
-p0 <- ggplot(sp_toys, aes(x, y,
- color=c_elsa)) +
- geom_point(size=s, alpha=0.5) + scale_y_reverse() + theme_bw() +
- labs(x="",y="", title="C", color="ELSA") +
- scico::scale_color_scico(palette = "roma", limits = c(0, 1), direction=-1)
-p2 <- ggplot(sp_toys, aes(x, y,
- color=p2_elsa)) +
- geom_point(size=s, alpha=0.5) + scale_y_reverse() + theme_bw() +
- labs(x="",y="", title="P2", color="ELSA") +
- scico::scale_color_scico(palette = "roma", limits = c(0, 1), direction=-1)
-
-plot_grid(p0 + theme(plot.title = element_text(hjust = 0.5)),
- p1 + theme(plot.title = element_text(hjust = 0.5)),
- p2 + theme(plot.title = element_text(hjust = 0.5)),
- nrow=1, rel_width=c(1,1,1))
-sessionInfo()
-## R version 4.4.2 (2024-10-31)
-## Platform: x86_64-pc-linux-gnu
-## Running under: Ubuntu 22.04.5 LTS
-##
-## Matrix products: default
-## BLAS: /usr/lib/x86_64-linux-gnu/blas/libblas.so.3.10.0
-## LAPACK: /usr/lib/x86_64-linux-gnu/lapack/liblapack.so.3.10.0
-##
-## locale:
-## [1] LC_CTYPE=en_US.UTF-8 LC_NUMERIC=C
-## [3] LC_TIME=en_US.UTF-8 LC_COLLATE=en_US.UTF-8
-## [5] LC_MONETARY=en_US.UTF-8 LC_MESSAGES=en_US.UTF-8
-## [7] LC_PAPER=en_US.UTF-8 LC_NAME=C
-## [9] LC_ADDRESS=C LC_TELEPHONE=C
-## [11] LC_MEASUREMENT=en_US.UTF-8 LC_IDENTIFICATION=C
-##
-## time zone: Europe/Zurich
-## tzcode source: system (glibc)
-##
-## attached base packages:
-## [1] stats graphics grDevices utils datasets methods base
-##
-## other attached packages:
-## [1] cowplot_1.1.3 igraph_2.1.1 ggnetwork_0.5.13 tidyr_1.3.1
-## [5] dplyr_1.1.4 ggplot2_3.5.1 poem_0.99.2 BiocStyle_2.32.1
-##
-## loaded via a namespace (and not attached):
-## [1] tidyselect_1.2.1 farver_2.1.2 fastmap_1.2.0
-## [4] bluster_1.14.0 digest_0.6.36 lifecycle_1.0.4
-## [7] sf_1.0-6 cluster_2.1.6 terra_1.5-21
-## [10] dbscan_1.2-0 magrittr_2.0.3 compiler_4.4.2
-## [13] rlang_1.1.4 sass_0.4.9 tools_4.4.2
-## [16] mclustcomp_0.3.3 utf8_1.2.4 yaml_2.3.10
-## [19] knitr_1.48 labeling_0.4.3 htmlwidgets_1.6.4
-## [22] sp_2.1-4 classInt_0.4-10 scico_1.5.0
-## [25] BiocParallel_1.38.0 KernSmooth_2.23-24 fclust_2.1.1.1
-## [28] elsa_1.1-28 withr_3.0.1 purrr_1.0.2
-## [31] BiocGenerics_0.50.0 desc_1.4.3 grid_4.4.2
-## [34] stats4_4.4.2 fansi_1.0.6 e1071_1.7-9
-## [37] colorspace_2.1-1 aricode_1.0.3 scales_1.3.0
-## [40] MASS_7.3-61 cli_3.6.3 rmarkdown_2.27
-## [43] ragg_1.3.2 generics_0.1.3 rstudioapi_0.16.0
-## [46] spdep_1.3-6 DBI_1.2.3 cachem_1.1.0
-## [49] proxy_0.4-27 parallel_4.4.2 BiocManager_1.30.23
-## [52] s2_1.1.7 vctrs_0.6.5 boot_1.3-30
-## [55] Matrix_1.7-0 jsonlite_1.8.8 spData_2.3.3
-## [58] bookdown_0.40 clevr_0.1.2 S4Vectors_0.42.1
-## [61] BiocNeighbors_1.22.0 clue_0.3-65 crosstalk_1.2.1
-## [64] systemfonts_1.1.0 jquerylib_0.1.4 units_0.8-0
-## [67] glue_1.8.0 pkgdown_2.1.1 codetools_0.2-20
-## [70] DT_0.33 gtable_0.3.5 deldir_2.0-4
-## [73] raster_3.5-15 munsell_0.5.1 tibble_3.2.1
-## [76] pillar_1.9.0 htmltools_0.5.8.1 R6_2.5.1
-## [79] wk_0.9.4 textshaping_0.3.6 Rdpack_2.6.1
-## [82] evaluate_0.24.0 lattice_0.22-6 highr_0.11
-## [85] rbibutils_2.3 bslib_0.8.0 class_7.3-22
-## [88] Rcpp_1.0.13 xfun_0.46 fs_1.6.4
-## [91] pkgconfig_2.0.3
vignettes/table.rmd
- table.rmd
-Min_level - | --Metric - | --Calculation - | -
---|---|---|
-dataset - | --Rand Index (RI) - | --; -the ratio of the sum of true positive and true negative pairs to the -total number of object pairs. - | -
-class/cluster - | --Wallace Homogeneity (WH) - | --; -the ratio of the true positive pairs to the total number of object pairs -that are in the same cluster in -. - | -
-class/cluster - | --Wallace Completeness (WC) - | --; -the ratio of the true positive pairs to the total number of object pairs -that are in the same classes in -. - | -
-dataset - | --Adjusted Rand Index (ARI) - | --; -adjusting RI by accounting for the expected similarity of all pairings -due to chance using the Permutation Model for clusterings. ARI is the -harmonic mean of AWH and AWC. - | -
-dataset - | --Normalized Class Size Rand Index (NCR) - | --A normalized version of RI, where each concordance quantities are -divided by the maximum possible concordance values for their respective -class. - | -
-dataset - | --Mutual Information (MI) - | --; -the difference between the shannon entropy of - -and the conditional entropy of - -given -. - | -
-class/cluster - | --Adjusted Wallace Homogeneity (AWH), Adjusted Wallace Completeness (AWC), -and Adjusted Mutual Information (AMI) - | --Chance adjusted version of WH, WC and MI, respectively. For a metric M, -the chance adjusted version of it is -. - | -
-dataset - | --(Entropy-based) Homogeneity (EH) - | -- -if -, - -otherwise; the ratio of MI to the individual entropy of -. - | -
-dataset - | --(Entropy-based) Completeness (EC) - | -- -if -, - -otherwise; the ratio of MI to the individual entropy of -. - | -
-class/cluster - | --V Measure (VM) - | --; -the harmonic mean between EH and EC. It is identical to normalized -mutual information (NMI) when arithmetic mean is used for averaging in -NMI calculation. - | -
-class/cluster - | --(weighted average) F Measure (wFM) - | --Here we calculate weighted F1-score, where the weights are based on the -sizes of classes. - | -
-Min_level - | --Metric - | --Calculation - | -
---|---|---|
-dataset - | --Silhouette score - | --, -where - -is the mean distance between a sample and the nearest class that the -sample is not a part of, and - -is the mean intra-class distance. - | -
-dataset - | --Composed Density between and within Clusters (CDbw) - | --The CDbw index consists of three main components: cohesion, compactness, -and separation between clusters. It uses multiple representative points -selected from each cluster to calculate intra-cluster density and -between-cluster distances, reflecting the geometry of the clusters and -capturing changes in intra-cluster density. - | -
-dataset - | --Density Based Clustering Validation index (DBCV) - | --A density-based index that computes the least dense region inside a -cluster and the most dense region between the clusters, to measure the -within and between cluster density connectedness of clusters. - | -
-Min_level - | --Metric - | --Calculation - | -
---|---|---|
-dataset - | --Modularity - | --For a given graph partition, it quantifies the number of edges within -communities relative to what would be expected by random chance. -, -where - -is the number of edges, - -is the adjacency matrix of the graph, - -is the (weighted) degree of -, - -is the resolution parameter, and - -is - -if - -and - -are in the same community else -. - | -
-element - | --Local Inverse Simpson’s Index (LISI) - | --For a given node in a weighted kNN graph, the expected number of nodes -needed to be sampled before two nodes are drawn from the same classes -within its neighborhood. - | -
-element - | --Neighborhood Purity (NP) - | --For each node in a graph, the proportion of its neighborhood that is of -the same class as it. - | -
-element - | --Proportion of Weakly Connected (PWC) - | --For a given community in a graph, the proportion of nodes that have more -connections to the outside of the community than the inside of the -community. - | -
-element - | --Cohesion - | --The minimum number of nodes that must be removed to split a graph. - | -
-class/cluster - | --Adhesion - | --The minimum number of edges that must be removed to split a graph. - | -
-class/cluster - | --Adjusted Mean Shortest Path (AMSP) - | --A measure of the disconnectness and spread of the subgraph connecting -elements of a given class. If the graph subclass is disconnected, the -mean shortest path of each connected subgraph - -are summed. -, -where - -is the mean shortest path and - -is the number of nodes of the given class. Note that the normalization -for size is only approximative, and only applicable for kNN graphs. - | -
-class/cluster - | --Neighborhood Class Enrichment (NCE) - | --The log2 fold-enrichment (i.e. over-representation) of the node’s class -among its nearest neighbors, over the expected given its relative -abundance. - | -
-Min_level - | --Metric - | --Calculation - | -
---|---|---|
-class/cluster - | --Percentage of Abnormal Spots (PAS) - | --PAS measures the percentage of abnormal spots, which is defined as spots -with a spatial domain label differing from more than half of its nearest -neighbors. - | -
-class/cluster - | --Spatial Chaos Score (CHAOS) - | --CHAOS is the mean length of the graph edges in the 1-nearest neighbor -(1NN) graph for each domain averaged across domains. - | -
-element - | --Entropy-based Local indicator of Spatial Association (ELSA) - | --For a site -, -, -where - -summarizes the dissimilarity between site - -and the neighbouring sites, and - -quantifies the diversity of the categories within the neighbourhood of -site -. - | -
-dataset - | --Spatial RI, ARI, WH, WC, AWH, and AWC - | --Spatial versions of the pair-sorting indices, based on fuzzy versions of -the metrics. Specifically, we use the Normalized Degree of Concordance -(NDC, see Hullermeier et al., 2012) and the Adjusted Concordance Index -(ACI, see D’Errico et al., 2021) as fuzzy versions of RI and ARI -respectively, and developed fuzzy versions of the other metrics using -the same logic. In the spatial context, we first make a fuzzy version of -the true labels based on the spatial neighborhood, and then track the -maximum pair concordance between the predicted labels and either the -hard or fuzzy ground truth. - | -
-element - | --Spot-wise Pair Concordance (SPC) - | --The proportion, for each spot, of the pairs it forms with all other -spots that are concordant (i.e. in the same partition or not in both) -across the clustering and ground truth. This value will be the same for -all spots that share the same combination of cluster and class, and is -especially useful for visualization. A variant of this can be computed -that ignores negative pairs (i.e. that are discordant in both the -clustering and ground truth). When negative pairs are included, the -average of SPC equals to the Rand Index. - | -
-element - | --Spatial SPC - | --Like the non-spatial Spot-wise Pair Concordance, with the difference -that the clustering is evaluated against both a ‘hard’ and ‘fuzzy’ -version of the ground truth, as for the computation of the Spatial -versions of the pair-sorting indices. - | -
-dataset - | --Spatial Set Matching Accuracy - | --An accuracy that downweights misclassifications based on the spatial -neighborhood. Instead of counting as zero in the accuracy computation, -the misclassified node counts as the proportion of its spatial -neighborhood that is of node’s predicted class. - | -
-sessionInfo()
## R version 4.4.2 (2024-10-31)
-## Platform: x86_64-pc-linux-gnu
-## Running under: Ubuntu 22.04.5 LTS
-##
-## Matrix products: default
-## BLAS: /usr/lib/x86_64-linux-gnu/blas/libblas.so.3.10.0
-## LAPACK: /usr/lib/x86_64-linux-gnu/lapack/liblapack.so.3.10.0
-##
-## locale:
-## [1] LC_CTYPE=en_US.UTF-8 LC_NUMERIC=C
-## [3] LC_TIME=en_US.UTF-8 LC_COLLATE=en_US.UTF-8
-## [5] LC_MONETARY=en_US.UTF-8 LC_MESSAGES=en_US.UTF-8
-## [7] LC_PAPER=en_US.UTF-8 LC_NAME=C
-## [9] LC_ADDRESS=C LC_TELEPHONE=C
-## [11] LC_MEASUREMENT=en_US.UTF-8 LC_IDENTIFICATION=C
-##
-## time zone: Europe/Zurich
-## tzcode source: system (glibc)
-##
-## attached base packages:
-## [1] stats graphics grDevices utils datasets methods base
-##
-## other attached packages:
-## [1] BiocStyle_2.32.1
-##
-## loaded via a namespace (and not attached):
-## [1] vctrs_0.6.5 svglite_2.1.3 cli_3.6.3
-## [4] knitr_1.48 rlang_1.1.4 xfun_0.46
-## [7] stringi_1.8.4 textshaping_0.3.6 jsonlite_1.8.8
-## [10] glue_1.8.0 colorspace_2.1-1 htmltools_0.5.8.1
-## [13] ragg_1.3.2 sass_0.4.9 scales_1.3.0
-## [16] rmarkdown_2.27 munsell_0.5.1 evaluate_0.24.0
-## [19] jquerylib_0.1.4 kableExtra_1.4.0 fastmap_1.2.0
-## [22] yaml_2.3.10 lifecycle_1.0.4 bookdown_0.40
-## [25] stringr_1.5.1 BiocManager_1.30.23 compiler_4.4.2
-## [28] fs_1.6.4 htmlwidgets_1.6.4 rstudioapi_0.16.0
-## [31] systemfonts_1.1.0 digest_0.6.36 viridisLite_0.4.2
-## [34] R6_2.5.1 magrittr_2.0.3 bslib_0.8.0
-## [37] tools_4.4.2 xml2_1.3.6 pkgdown_2.1.1
-## [40] cachem_1.1.0 desc_1.4.3
-