diff --git a/Python/shapeworks/shapeworks/network_analysis.py b/Python/shapeworks/shapeworks/network_analysis.py index c7bb48e1e0..30ba2cd898 100644 --- a/Python/shapeworks/shapeworks/network_analysis.py +++ b/Python/shapeworks/shapeworks/network_analysis.py @@ -6,6 +6,8 @@ import itertools import math import scipy +import scipy.sparse +import scipy.sparse.csgraph import spm1d import vtk from vtk.util.numpy_support import vtk_to_numpy @@ -53,6 +55,80 @@ def compute_particle_triangles(surface, points, min_vertices_per_point=10): return np.unique(np.sort(face_labels[distinct], axis=1), axis=0) +def particle_edges(tris): + """Unique particle-to-particle edges of the particle triangles.""" + edges = np.vstack([tris[:, [0, 1]], tris[:, [1, 2]], tris[:, [0, 2]]]) + return np.unique(np.sort(edges, axis=1), axis=0) + + +def signed_clusters(tvalues, threshold, edges): + """Find clusters of connected particles above threshold, and below -threshold, separately. + + Returns a cluster label per particle (-1 for none), the size of each cluster, and the sign of each + cluster. Positive and negative particles are never joined into one cluster. + """ + num_particles = len(tvalues) + labels = np.full(num_particles, -1, dtype=int) + sizes = [] + signs = [] + for sign, mask in ((1, tvalues > threshold), (-1, tvalues < -threshold)): + nodes = np.flatnonzero(mask) + if len(nodes) == 0: + continue + keep = mask[edges[:, 0]] & mask[edges[:, 1]] + kept = edges[keep] + graph = scipy.sparse.coo_matrix((np.ones(len(kept)), (kept[:, 0], kept[:, 1])), + shape=(num_particles, num_particles)) + _, components = scipy.sparse.csgraph.connected_components(graph, directed=False) + _, cluster, counts = np.unique(components[nodes], return_inverse=True, return_counts=True) + labels[nodes] = cluster + len(sizes) + sizes.extend(counts.tolist()) + signs.extend([sign] * len(counts)) + return labels, np.array(sizes, dtype=int), np.array(signs, dtype=int) + + +def one_sample_tvalues(data, signs): + """One-sample t statistics against zero for each sign flip. + + data is (particles, subjects) and signs is (flips, subjects) of +1/-1. Returns (particles, flips). + Flipping signs leaves each particle's sum of squares unchanged, so only the means are recomputed. + """ + n = data.shape[1] + means = data @ signs.T / n + sum_squares = np.sum(data ** 2, axis=1, keepdims=True) + variance = np.maximum(sum_squares - n * means ** 2, 0) / (n - 1) + with np.errstate(divide="ignore", invalid="ignore"): + return means / np.sqrt(variance / n) + + +def sign_flips(num_subjects, num_iterations, seed=0): + """Sign flips for a one-sample permutation test; the first row is the unflipped data. + + Uses every flip when there are no more than num_iterations of them, otherwise a random sample. + """ + if 2 ** num_subjects <= num_iterations: + bits = (np.arange(2 ** num_subjects)[:, None] >> np.arange(num_subjects)) & 1 + return 1 - 2 * bits + signs = np.random.default_rng(seed).choice([-1, 1], size=(num_iterations, num_subjects)) + signs[0] = 1 + return signs + + +def cluster_pvalues(sizes, max_sizes): + """Family-wise p-value of each cluster: the fraction of flips whose largest cluster is at least as large.""" + max_sizes = np.asarray(max_sizes) + return np.array([np.mean(max_sizes >= size) for size in sizes]) + + +def minimum_cluster_size(max_sizes, alpha): + """Smallest cluster size with a family-wise p-value of at most alpha.""" + descending = np.sort(np.asarray(max_sizes))[::-1] + allowed = int(np.floor(alpha * len(descending) + 1e-9)) + if allowed >= len(descending): + return 1 + return int(descending[allowed]) + 1 + + class NetworkAnalysis: def __init__(self, project): self.project = project @@ -68,6 +144,7 @@ def __init__(self, project): self.pvalue_threshold = 0.05 self.num_iterations = 10000 self.target_group_values = None + self.one_sample = False def set_run_1dspm(self, run_1dspm): self.flag_run_1dspm = run_1dspm @@ -89,6 +166,13 @@ def set_target_group_values(self, value1, value2): """Select the two group values to compare (required when the group has more than two values)""" self.target_group_values = [value1, value2] + def set_one_sample(self, one_sample): + """Test one group against zero instead of comparing two groups. + + The group is the first of the target group values, or all subjects when no group is set. + """ + self.one_sample = one_sample + def set_model_type(self, model_type): self.flag_model = model_type @@ -123,6 +207,8 @@ def compute_mean_shape(self): return mesh_points, mesh_normals, mean_shape, surface def run(self): + if self.one_sample: + return self.run_one_sample() project = self.project analyze = self.analyze num_pts = analyze.get_num_particles() @@ -992,3 +1078,126 @@ def run(self): self.particles = particles self.group = group self.pts_index = pts_index + + def run_one_sample(self): + """One-sample network analysis: where does the feature differ from zero? + + Each particle gets a one-sample t-test against zero. Particles beyond the cluster-forming threshold + (p-value threshold, one-sided per sign) are joined into clusters of connected particles, with positive + and negative clusters kept apart. Cluster sizes are compared with the largest cluster under random sign + flips of each subject's values, which controls the family-wise error at the cluster p-value. + """ + project = self.project + analyze = self.analyze + num_pts = analyze.get_num_particles() + if num_pts == 0: + raise ValueError("Project has no particles. Run Optimize before network analysis.") + + subjects = project.get_subjects() + group = self.target_group + if group: + if group not in project.get_group_names(): + raise ValueError(f"Group '{group}' not found in this project. " + f"Available groups: {project.get_group_names()}") + if self.target_group_values is None: + raise ValueError(f"Select the value of group '{group}' to test.") + value = self.target_group_values[0] + if value not in project.get_group_values(group): + raise ValueError(f"Group '{group}' has no value '{value}'. " + f"Available values: {project.get_group_values(group)}") + selected = [s for s, subject in enumerate(subjects) if subject.get_group_value(group) == value] + description = f"group '{group}' = '{value}'" + else: + selected = list(range(len(subjects))) + description = "all subjects" + + num_subjects = len(selected) + alpha = self.pvalue_of_interest + distinct = 2 ** (num_subjects - 1) if num_subjects > 0 else 0 + if distinct == 0 or 1 / distinct > alpha: + needed = int(math.ceil(math.log2(1 / alpha))) + 1 + raise ValueError(f"Too few subjects for a one-sample network analysis: {description} has {num_subjects}, " + f"and at least {needed} are needed to reach a cluster p-value of {alpha}.") + + sw_message(f"One-sample network analysis of feature '{self.target_feature}' for {description} " + f"({num_subjects} subjects), {num_pts} particles") + sw_message(f"Settings: {self.num_iterations} permutations, cluster p-value {alpha}, " + f"p-value threshold {self.pvalue_threshold}") + + mesh_points, mesh_normals, mean_shape, surface = self.compute_mean_shape() + + values = np.zeros((num_pts, num_subjects)) + for index, s in enumerate(selected): + sw_progress(0.1 * index / num_subjects, "Loading feature values") + features = analyze.get_subject_features(s, self.target_feature) + if features.size != num_pts: + raise ValueError( + f"Subject '{subjects[s].get_display_name()}' has {features.size} values for feature " + f"'{self.target_feature}', expected {num_pts} (one per particle). Check that this " + f"subject's mesh has a point data array named '{self.target_feature}'.") + values[:, index] = features.reshape(-1) + + # particles whose values are identical across subjects have no t statistic + particles = np.where(np.ptp(values, axis=1) > 0)[0] + if len(particles) == 0: + raise ValueError(f"Feature '{self.target_feature}' has no variation across subjects at any particle, " + "so there is nothing to test.") + if len(particles) < num_pts: + sw_message(f"Excluding {num_pts - len(particles)} of {num_pts} particles with no variation " + "across subjects") + data = values[particles, :] + + # per-particle permutation test (SPM1D), corrected for the number of particles + sw_message(f"Running per-particle permutation test on {len(particles)} particles") + sw_progress(0.1, "Running per-particle test") + snpm = spm1d.stats.nonparam.ttest(data.T, 0) + spm_iterations = min(self.num_iterations, snpm.nPermUnique) + snpmi = snpm.inference(max(alpha, 1 / spm_iterations), two_tailed=True, iterations=spm_iterations, + force_iterations=True) + spm_significant = np.where(np.abs(snpmi.z) >= snpmi.zstar, snpmi.z, 0) + + sw_message("Building particle connectivity") + edges = particle_edges(compute_particle_triangles(surface, mean_shape[particles, :])) + + threshold = scipy.stats.t.ppf(1 - self.pvalue_threshold, num_subjects - 1) + signs = sign_flips(num_subjects, self.num_iterations) + if len(signs) < self.num_iterations: + sw_message(f"Using all {len(signs)} sign flips, fewer than the {self.num_iterations} requested") + else: + sw_message(f"Running {len(signs)} random sign flips") + + max_sizes = np.zeros(len(signs), dtype=int) + chunk = 500 + for start in range(0, len(signs), chunk): + sw_progress(0.15 + 0.8 * start / len(signs), "Running sign flips") + tvalues = one_sample_tvalues(data, signs[start:start + chunk]) + for column in range(tvalues.shape[1]): + _, sizes, _ = signed_clusters(tvalues[:, column], threshold, edges) + max_sizes[start + column] = sizes.max() if len(sizes) else 0 + + tvalues = one_sample_tvalues(data, np.ones((1, num_subjects), dtype=int))[:, 0] + labels, sizes, cluster_signs = signed_clusters(tvalues, threshold, edges) + pvalues = cluster_pvalues(sizes, max_sizes) + min_cluster_size = minimum_cluster_size(max_sizes, alpha) + significant = np.flatnonzero(pvalues <= alpha) + network = np.where(np.isin(labels, significant), tvalues, 0) + + self.particle_network_values = np.zeros(num_pts) + self.particle_network_values[particles] = network + self.particle_spm_values = np.zeros(num_pts) + self.particle_spm_values[particles] = spm_significant + self.particles = particles + self.clusters = [{"size": int(sizes[c]), "sign": int(cluster_signs[c]), "pvalue": float(pvalues[c])} + for c in np.argsort(-sizes)] + self.min_cluster_size = min_cluster_size + + sw_progress(1.0, "Done") + sw_message(f"Per-particle result: {np.count_nonzero(spm_significant)} of {num_pts} particles significant " + f"(critical t = {float(snpmi.zstar):.3f})") + if len(significant) > 0: + parts = [f"{c['size']} particles, {'positive' if c['sign'] > 0 else 'negative'}, p = {c['pvalue']:.4g}" + for c in self.clusters if c["pvalue"] <= alpha] + sw_message(f"Network result: {np.count_nonzero(network)} of {num_pts} particles significant in " + f"{len(significant)} cluster(s) (minimum cluster size {min_cluster_size}): " + "; ".join(parts)) + else: + sw_message(f"Network result: no clusters reached the minimum cluster size of {min_cluster_size}") diff --git a/Studio/Analysis/AnalysisTool.cpp b/Studio/Analysis/AnalysisTool.cpp index fe22c3d853..f9e7a04f40 100644 --- a/Studio/Analysis/AnalysisTool.cpp +++ b/Studio/Analysis/AnalysisTool.cpp @@ -611,6 +611,7 @@ void AnalysisTool::network_analysis_clicked() { network_analysis_job_->set_pvalue_of_interest(ui_->network_pvalue_of_interest->text().toDouble()); network_analysis_job_->set_pvalue_threshold(ui_->network_pvalue_threshold->text().toDouble()); network_analysis_job_->set_num_iterations(ui_->network_iterations->text().toInt()); + network_analysis_job_->set_one_sample(ui_->network_one_sample->isChecked()); connect(network_analysis_job_.data(), &NetworkAnalysisJob::progress, this, &AnalysisTool::handle_network_analysis_progress); @@ -1214,6 +1215,7 @@ void AnalysisTool::load_settings() { ui_->network_pvalue_of_interest->setText(QString::number(pvalue_of_interest)); ui_->network_pvalue_threshold->setText( QString::number(static_cast(params.get("network_pvalue_threshold", 0.05)))); + ui_->network_one_sample->setChecked(params.get("network_one_sample", false)); ui_->mesh_warp_sample_spinbox->setValue(params.get(MESH_WARP_TEMPLATE_INDEX, -1)); ui_->warp_method_combo->setCurrentIndex(params.get(MESH_WARP_METHOD, preferences_.get_warp_method())); @@ -1238,6 +1240,7 @@ void AnalysisTool::store_settings() { params.set("network_iterations", ui_->network_iterations->text().toStdString()); params.set("network_pvalue_of_interest", ui_->network_pvalue_of_interest->text().toStdString()); params.set("network_pvalue_threshold", ui_->network_pvalue_threshold->text().toStdString()); + params.set("network_one_sample", ui_->network_one_sample->isChecked()); params.set("current_regression_column", ui_->regression_combo->currentText().toStdString()); session_->get_project()->set_parameters(Parameters::ANALYSIS_PARAMS, params); diff --git a/Studio/Analysis/AnalysisTool.ui b/Studio/Analysis/AnalysisTool.ui index 1516ff14cc..2da5aaf9f8 100644 --- a/Studio/Analysis/AnalysisTool.ui +++ b/Studio/Analysis/AnalysisTool.ui @@ -750,14 +750,24 @@ QWidget#particles_panel { - + + + + Test whether Group 1's feature differs from zero, instead of comparing Group 1 with Group 2. Use for features that are already a change within each subject, such as a signed rate between two timepoints. + + + One-sample (Group 1 vs. zero) + + + + Display - + @@ -780,7 +790,7 @@ QWidget#particles_panel { - + true @@ -799,7 +809,7 @@ QWidget#particles_panel { - + diff --git a/Studio/Job/NetworkAnalysisJob.cpp b/Studio/Job/NetworkAnalysisJob.cpp index 627c0e05cb..f63201a3cb 100644 --- a/Studio/Job/NetworkAnalysisJob.cpp +++ b/Studio/Job/NetworkAnalysisJob.cpp @@ -34,6 +34,7 @@ void NetworkAnalysisJob::run() { network_analysis.attr("set_pvalue_of_interest")(pvalue_of_interest_); network_analysis.attr("set_pvalue_threshold")(pvalue_threshold_); network_analysis.attr("set_num_iterations")(num_iterations_); + network_analysis.attr("set_one_sample")(one_sample_); py::object res = network_analysis.attr("run")(); @@ -73,6 +74,9 @@ void NetworkAnalysisJob::set_target_group_values(std::string value1, std::string target_group_value2_ = value2; } +//--------------------------------------------------------------------------- +void NetworkAnalysisJob::set_one_sample(bool one_sample) { one_sample_ = one_sample; } + //--------------------------------------------------------------------------- void NetworkAnalysisJob::set_pvalue_of_interest(double pvalue_of_interest) { pvalue_of_interest_ = pvalue_of_interest; } diff --git a/Studio/Job/NetworkAnalysisJob.h b/Studio/Job/NetworkAnalysisJob.h index 71c66a6cbc..fec1e5a69d 100644 --- a/Studio/Job/NetworkAnalysisJob.h +++ b/Studio/Job/NetworkAnalysisJob.h @@ -15,6 +15,8 @@ class NetworkAnalysisJob : public Job { //! Set the two group values to compare void set_target_group_values(std::string value1, std::string value2); + //! Test the first group value against zero instead of comparing two groups + void set_one_sample(bool one_sample); void set_pvalue_of_interest(double pvalue_of_interest); void set_pvalue_threshold(double pvalue_threshold); void set_num_iterations(int num_iterations); @@ -35,5 +37,6 @@ class NetworkAnalysisJob : public Job { double pvalue_of_interest_ = 0; double pvalue_threshold_ = 0; int num_iterations_ = 0; + bool one_sample_ = false; }; } // namespace shapeworks diff --git a/Testing/PythonTests/PythonTests.cpp b/Testing/PythonTests/PythonTests.cpp index 0ed99cc41e..805cac44b2 100644 --- a/Testing/PythonTests/PythonTests.cpp +++ b/Testing/PythonTests/PythonTests.cpp @@ -270,6 +270,10 @@ TEST(pythonTests, coverageTest) { run_test("coverage.py"); } +TEST(pythonTests, networkAnalysisOneSampleTest) { + run_test("network_analysis_one_sample.py"); +} + TEST(pythonTests, distanceTest) { run_test("distance.py"); } diff --git a/Testing/PythonTests/network_analysis_one_sample.py b/Testing/PythonTests/network_analysis_one_sample.py new file mode 100644 index 0000000000..33801771cb --- /dev/null +++ b/Testing/PythonTests/network_analysis_one_sample.py @@ -0,0 +1,80 @@ +import sys + +import numpy as np +import scipy.stats +from shapeworks import utils +from shapeworks.network_analysis import (cluster_pvalues, minimum_cluster_size, one_sample_tvalues, particle_edges, + sign_flips, signed_clusters) + +success = True + +SIDE = 24 +INDEX = np.arange(SIDE * SIDE).reshape(SIDE, SIDE) + + +def grid_edges(): + tris = [] + for i in range(SIDE - 1): + for j in range(SIDE - 1): + tris.append([INDEX[i, j], INDEX[i + 1, j], INDEX[i, j + 1]]) + tris.append([INDEX[i + 1, j], INDEX[i + 1, j + 1], INDEX[i, j + 1]]) + return particle_edges(np.array(tris)) + + +def smooth(field): + f = field.reshape(SIDE, SIDE, -1) + for _ in range(3): + f = (f + np.roll(f, 1, 0) + np.roll(f, -1, 0) + np.roll(f, 1, 1) + np.roll(f, -1, 1)) / 5 + return f.reshape(SIDE * SIDE, -1) + + +def tvaluesTest(): + data = np.random.default_rng(0).normal(size=(40, 9)) + signs = sign_flips(9, 100) + tvalues = one_sample_tvalues(data, signs) + return all(np.allclose(tvalues[:, k], scipy.stats.ttest_1samp(data * signs[k], 0, axis=1).statistic) + for k in (0, 5, 99)) and (signs[0] == 1).all() + + +def signFlipsTest(): + signs = sign_flips(5, 1000) + return signs.shape == (32, 5) and len({tuple(r) for r in signs}) == 32 and (signs[0] == 1).all() + + +def signedClustersTest(): + # a positive block next to a negative block must stay two clusters + tvalues = np.zeros(SIDE * SIDE) + tvalues[INDEX[2:6, 2:6].ravel()] = 3 + tvalues[INDEX[2:6, 6:9].ravel()] = -3 + labels, sizes, signs = signed_clusters(tvalues, 2, grid_edges()) + return sorted(zip(sizes.tolist(), signs.tolist())) == [(12, -1), (16, 1)] + + +def clusterInferenceTest(): + # a loss patch and a gain patch are found with the right signs, and noise alone finds nothing + rng = np.random.default_rng(1) + edges = grid_edges() + effect = np.zeros(SIDE * SIDE) + effect[INDEX[2:10, 2:10].ravel()] = -0.8 + effect[INDEX[14:22, 14:22].ravel()] = 0.8 + results = [] + for shift in (effect, np.zeros_like(effect)): + data = smooth(rng.normal(size=(SIDE * SIDE, 10))) + shift[:, None] + threshold = scipy.stats.t.ppf(0.95, 9) + signs = sign_flips(10, 2000) + tvalues = one_sample_tvalues(data, signs) + max_sizes = [max(signed_clusters(tvalues[:, k], threshold, edges)[1], default=0) for k in range(len(signs))] + labels, sizes, cluster_signs = signed_clusters(tvalues[:, 0], threshold, edges) + pvalues = cluster_pvalues(sizes, max_sizes) + results.append(sorted(cluster_signs[pvalues <= 0.05].tolist())) + if shift is effect and minimum_cluster_size(max_sizes, 0.05) > min(sizes[pvalues <= 0.05]): + return False + return results == [[-1, 1], []] + + +success &= utils.test(tvaluesTest) +success &= utils.test(signFlipsTest) +success &= utils.test(signedClustersTest) +success &= utils.test(clusterInferenceTest) + +sys.exit(not success) diff --git a/docs/about/release-notes.md b/docs/about/release-notes.md index 2155c35c89..0b93dc0c93 100644 --- a/docs/about/release-notes.md +++ b/docs/about/release-notes.md @@ -13,6 +13,7 @@ * *Show distance on surface* colors each sample's surface and particles by the per-vertex distance, so a bad region can be located and not just detected * Samples can be sorted by mean, median, p99 or max distance, or by how localized the error is, which surfaces swapped-correspondence cases whose mean distance still looks healthy; *Sort samples in view* applies the same ranking to the All Samples grid so the challenging shapes come up first, and clicking a row shows that sample on its own, or returns to all samples if it is already showing * The quality chart plots the ranked metric together with the tail of the distribution on a log axis, with median and p95 marked, so a small badly reconstructed patch stays visible even when it barely moves the mean + * Network analysis has a one-sample option that tests whether one group's feature differs from zero, for features that are already a change within each subject, such as a signed wear rate (#2738) * Result tables can be right-clicked to copy their contents to the clipboard as CSV, with the header row and proper quoting of values containing a comma or a quote ### Fixes diff --git a/docs/studio/studio-analyze.md b/docs/studio/studio-analyze.md index fc5b3c7e42..b22f1543b5 100644 --- a/docs/studio/studio-analyze.md +++ b/docs/studio/studio-analyze.md @@ -53,9 +53,16 @@ The Network Analysis tool provides a method to statistically analyze data captur | P-value Threshold | The initial p-value used to threshold particles as an initial step to the evaluation of cluster size. Only modify from 0.05 for adjusted statistical assumptions.| | Cluster P-value | The cluster p-value defines the p-value used to identify significant clusters for the group. Traditional statistics would assume a p-value of 0.05. | | Permutations | This is the number of permutations used in the analysis. The maximum value is driven by the sample size, however 10,000 is generally considered acceptably large.| +| One-sample | Test whether Group 1's feature differs from zero, instead of comparing Group 1 with Group 2. See below. | | Display | Choose to display Network Analysis output or SPM1D | +#### One-sample analysis + +Check **One-sample** when the feature is already a change within each subject, such as a signed wear rate between two timepoints, and the question is where it differs from zero. Only the subjects in Group 1 are analyzed. Each particle gets a one-sample t-test, and the cluster threshold comes from randomly flipping the sign of each subject's values, rather than shuffling group labels. Positive and negative clusters are found separately, so a region of loss next to a region of gain is not merged into one cluster. + +The feature must be signed, so that zero means no change. A feature that is never negative, such as an absolute distance, will appear significant everywhere. A two-sided test at a cluster p-value of 0.05 needs at least 6 subjects, because n subjects give only 2n-1 distinct sign flips. + After running the Network Analysis, you can enable the display of values with the "Display" checkbox: ![ShapeWorks Studio Network Analysis Display](../img/studio/studio_network_analysis_display.png)