Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
209 changes: 209 additions & 0 deletions Python/shapeworks/shapeworks/network_analysis.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand All @@ -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
Expand All @@ -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

Expand Down Expand Up @@ -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()
Expand Down Expand Up @@ -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}")
3 changes: 3 additions & 0 deletions Studio/Analysis/AnalysisTool.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down Expand Up @@ -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<double>(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()));
Expand All @@ -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);
Expand Down
18 changes: 14 additions & 4 deletions Studio/Analysis/AnalysisTool.ui
Original file line number Diff line number Diff line change
Expand Up @@ -750,14 +750,24 @@ QWidget#particles_panel {
</property>
</widget>
</item>
<item row="4" column="0" colspan="2">
<item row="4" column="0" colspan="3">
<widget class="QCheckBox" name="network_one_sample">
<property name="toolTip">
<string>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.</string>
</property>
<property name="text">
<string>One-sample (Group 1 vs. zero)</string>
</property>
</widget>
</item>
<item row="5" column="0" colspan="2">
<widget class="QCheckBox" name="network_analysis_display">
<property name="text">
<string>Display</string>
</property>
</widget>
</item>
<item row="4" column="2">
<item row="5" column="2">
<widget class="QWidget" name="network_display_option_widget" native="true">
<layout class="QGridLayout" name="gridLayout_22">
<item row="0" column="0">
Expand All @@ -780,7 +790,7 @@ QWidget#particles_panel {
</layout>
</widget>
</item>
<item row="5" column="0" colspan="3">
<item row="6" column="0" colspan="3">
<widget class="QPushButton" name="network_analysis_button">
<property name="enabled">
<bool>true</bool>
Expand All @@ -799,7 +809,7 @@ QWidget#particles_panel {
</property>
</widget>
</item>
<item row="6" column="0" colspan="3">
<item row="7" column="0" colspan="3">
<widget class="QWidget" name="network_progress_widget" native="true">
<layout class="QGridLayout" name="gridLayout_23">
<item row="2" column="0">
Expand Down
4 changes: 4 additions & 0 deletions Studio/Job/NetworkAnalysisJob.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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")();

Expand Down Expand Up @@ -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; }

Expand Down
3 changes: 3 additions & 0 deletions Studio/Job/NetworkAnalysisJob.h
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand All @@ -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
4 changes: 4 additions & 0 deletions Testing/PythonTests/PythonTests.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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");
}
Expand Down
Loading
Loading