risk-network 0.0.3__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
risk/risk.py ADDED
@@ -0,0 +1,379 @@
1
+ """
2
+ risk/risk
3
+ ~~~~~~~~~
4
+ """
5
+
6
+ from typing import Any, Dict
7
+
8
+ import networkx as nx
9
+ import pandas as pd
10
+
11
+ from risk.annotations import AnnotationsIO, define_top_annotations
12
+ from risk.log import params, print_header
13
+ from risk.neighborhoods import (
14
+ define_domains,
15
+ get_network_neighborhoods,
16
+ process_neighborhoods,
17
+ trim_domains_and_top_annotations,
18
+ )
19
+ from risk.network import NetworkIO, NetworkGraph, NetworkPlotter
20
+ from risk.stats import compute_permutation, calculate_significance_matrices
21
+
22
+
23
+ class RISK(NetworkIO, AnnotationsIO):
24
+ """RISK: A class for network analysis and visualization.
25
+
26
+ The RISK class integrates functionalities for loading networks, processing annotations,
27
+ and performing network-based statistical analysis, such as neighborhood significance testing.
28
+ """
29
+
30
+ def __init__(
31
+ self,
32
+ compute_sphere: bool = True,
33
+ surface_depth: float = 0.0,
34
+ min_edges_per_node: int = 0,
35
+ include_edge_weight: bool = True,
36
+ weight_label: str = "weight",
37
+ ):
38
+ """Initialize the RISK class with configuration settings.
39
+
40
+ Args:
41
+ compute_sphere (bool, optional): Whether to map nodes to a sphere. Defaults to True.
42
+ surface_depth (float, optional): Surface depth for the sphere. Defaults to 0.0.
43
+ min_edges_per_node (int, optional): Minimum number of edges per node. Defaults to 0.
44
+ include_edge_weight (bool, optional): Whether to include edge weights in calculations. Defaults to True.
45
+ weight_label (str, optional): Label for edge weights. Defaults to "weight".
46
+ """
47
+ # Initialize and log network parameters
48
+ params.initialize()
49
+ params.log_network(
50
+ compute_sphere=compute_sphere,
51
+ surface_depth=surface_depth,
52
+ min_edges_per_node=min_edges_per_node,
53
+ include_edge_weight=include_edge_weight,
54
+ weight_label=weight_label,
55
+ )
56
+ # Initialize parent classes
57
+ NetworkIO.__init__(
58
+ self,
59
+ compute_sphere=compute_sphere,
60
+ surface_depth=surface_depth,
61
+ min_edges_per_node=min_edges_per_node,
62
+ include_edge_weight=include_edge_weight,
63
+ weight_label=weight_label,
64
+ )
65
+ AnnotationsIO.__init__(self)
66
+
67
+ # Set class attributes
68
+ self.compute_sphere = compute_sphere
69
+ self.surface_depth = surface_depth
70
+ self.min_edges_per_node = min_edges_per_node
71
+ self.include_edge_weight = include_edge_weight
72
+ self.weight_label = weight_label
73
+
74
+ @property
75
+ def params(self):
76
+ """Access the logged parameters."""
77
+ return params
78
+
79
+ def load_neighborhoods(
80
+ self,
81
+ network: nx.Graph,
82
+ annotations: Dict[str, Any],
83
+ distance_metric: str = "dijkstra",
84
+ louvain_resolution: float = 0.1,
85
+ edge_length_threshold: float = 0.5,
86
+ score_metric: str = "sum",
87
+ null_distribution: str = "network",
88
+ num_permutations: int = 1000,
89
+ random_seed: int = 888,
90
+ max_workers: int = 1,
91
+ ) -> Dict[str, Any]:
92
+ """Load significant neighborhoods for the network.
93
+
94
+ Args:
95
+ network (nx.Graph): The network graph.
96
+ annotations (pd.DataFrame): The matrix of annotations associated with the network.
97
+ distance_metric (str, optional): Distance metric for neighborhood analysis. Defaults to "dijkstra".
98
+ louvain_resolution (float, optional): Resolution parameter for Louvain clustering. Defaults to 0.1.
99
+ edge_length_threshold (float, optional): Edge length threshold for neighborhood analysis. Defaults to 0.5.
100
+ score_metric (str, optional): Scoring metric for neighborhood significance. Defaults to "sum".
101
+ null_distribution (str, optional): Distribution used for permutation tests. Defaults to "network".
102
+ num_permutations (int, optional): Number of permutations for significance testing. Defaults to 1000.
103
+ random_seed (int, optional): Seed for random number generation. Defaults to 888.
104
+ max_workers (int, optional): Maximum number of workers for parallel computation. Defaults to 1.
105
+
106
+ Returns:
107
+ dict: Computed significance of neighborhoods.
108
+ """
109
+ print_header("Running permutation test")
110
+ # Log neighborhood analysis parameters
111
+ params.log_neighborhoods(
112
+ distance_metric=distance_metric,
113
+ louvain_resolution=louvain_resolution,
114
+ edge_length_threshold=edge_length_threshold,
115
+ score_metric=score_metric,
116
+ null_distribution=null_distribution,
117
+ num_permutations=num_permutations,
118
+ random_seed=random_seed,
119
+ max_workers=max_workers,
120
+ )
121
+
122
+ # Display the chosen distance metric
123
+ if distance_metric == "louvain":
124
+ for_print_distance_metric = f"louvain (resolution={louvain_resolution})"
125
+ else:
126
+ for_print_distance_metric = distance_metric
127
+ print(f"Distance metric: '{for_print_distance_metric}'")
128
+ print(f"Edge length threshold: {edge_length_threshold}")
129
+ # Compute neighborhoods based on the network and distance metric
130
+ neighborhoods = get_network_neighborhoods(
131
+ network,
132
+ distance_metric,
133
+ edge_length_threshold,
134
+ louvain_resolution=louvain_resolution,
135
+ random_seed=random_seed,
136
+ )
137
+
138
+ # Log and display permutation test settings
139
+ print(f"Null distribution: '{null_distribution}'")
140
+ print(f"Neighborhood scoring metric: '{score_metric}'")
141
+ print(f"Number of permutations: {num_permutations}")
142
+ print(f"Random seed: {random_seed}")
143
+ print(f"Maximum workers: {max_workers}")
144
+ # Run the permutation test to compute neighborhood significance
145
+ neighborhood_significance = compute_permutation(
146
+ neighborhoods=neighborhoods,
147
+ annotations=annotations["matrix"],
148
+ score_metric=score_metric,
149
+ null_distribution=null_distribution,
150
+ num_permutations=num_permutations,
151
+ random_seed=random_seed,
152
+ max_workers=max_workers,
153
+ )
154
+
155
+ return neighborhood_significance
156
+
157
+ def load_graph(
158
+ self,
159
+ network: nx.Graph,
160
+ annotations: Dict[str, Any],
161
+ neighborhoods: Dict[str, Any],
162
+ tail: str = "right", # OPTIONS: "right" (enrichment), "left" (depletion), "both"
163
+ pval_cutoff: float = 0.01, # OPTIONS: Any value between 0 to 1
164
+ fdr_cutoff: float = 0.9999, # OPTIONS: Any value between 0 to 1
165
+ impute_depth: int = 1,
166
+ prune_threshold: float = 0.0,
167
+ linkage_criterion: str = "distance",
168
+ linkage_method: str = "average",
169
+ linkage_metric: str = "yule",
170
+ min_cluster_size: int = 5,
171
+ max_cluster_size: int = 1000,
172
+ ) -> NetworkGraph:
173
+ """Load and process the network graph, defining top annotations and domains.
174
+
175
+ Args:
176
+ network (nx.Graph): The network graph.
177
+ annotations (pd.DataFrame): DataFrame containing annotation data for the network.
178
+ neighborhoods (dict): Neighborhood enrichment data.
179
+ tail (str, optional): Type of significance tail ("right", "left", "both"). Defaults to "right".
180
+ pval_cutoff (float, optional): P-value cutoff for significance. Defaults to 0.01.
181
+ fdr_cutoff (float, optional): FDR cutoff for significance. Defaults to 0.9999.
182
+ impute_depth (int, optional): Depth for imputing neighbors. Defaults to 1.
183
+ prune_threshold (float, optional): Distance threshold for pruning neighbors. Defaults to 0.0.
184
+ linkage_criterion (str, optional): Clustering criterion for defining domains. Defaults to "distance".
185
+ linkage_method (str, optional): Clustering method to use. Defaults to "average".
186
+ linkage_metric (str, optional): Metric to use for calculating distances. Defaults to "yule".
187
+ min_cluster_size (int, optional): Minimum size for clusters. Defaults to 5.
188
+ max_cluster_size (int, optional): Maximum size for clusters. Defaults to 1000.
189
+
190
+ Returns:
191
+ NetworkGraph: A fully initialized and processed NetworkGraph object.
192
+ """
193
+ # Log the parameters and display headers
194
+ print_header("Finding significant neighborhoods")
195
+ params.log_graph(
196
+ tail=tail,
197
+ pval_cutoff=pval_cutoff,
198
+ fdr_cutoff=fdr_cutoff,
199
+ impute_depth=impute_depth,
200
+ prune_threshold=prune_threshold,
201
+ linkage_criterion=linkage_criterion,
202
+ linkage_method=linkage_method,
203
+ linkage_metric=linkage_metric,
204
+ min_cluster_size=min_cluster_size,
205
+ max_cluster_size=max_cluster_size,
206
+ )
207
+
208
+ print(f"P-value cutoff: {pval_cutoff}")
209
+ print(f"FDR BH cutoff: {fdr_cutoff}")
210
+ print(
211
+ f"Significance tail: '{tail}' ({'enrichment' if tail == 'right' else 'depletion' if tail == 'left' else 'both'})"
212
+ )
213
+ # Calculate significant neighborhoods based on the provided parameters
214
+ significant_neighborhoods = calculate_significance_matrices(
215
+ neighborhoods["depletion_pvals"],
216
+ neighborhoods["enrichment_pvals"],
217
+ tail=tail,
218
+ pval_cutoff=pval_cutoff,
219
+ fdr_cutoff=fdr_cutoff,
220
+ )
221
+
222
+ print_header("Processing neighborhoods")
223
+ # Process neighborhoods by imputing and pruning based on the given settings
224
+ processed_neighborhoods = process_neighborhoods(
225
+ network=network,
226
+ neighborhoods=significant_neighborhoods,
227
+ impute_depth=impute_depth,
228
+ prune_threshold=prune_threshold,
229
+ )
230
+
231
+ print_header("Finding top annotations")
232
+ print(f"Min cluster size: {min_cluster_size}")
233
+ print(f"Max cluster size: {max_cluster_size}")
234
+ # Define top annotations based on processed neighborhoods
235
+ top_annotations = self._define_top_annotations(
236
+ network=network,
237
+ annotations=annotations,
238
+ neighborhoods=processed_neighborhoods,
239
+ min_cluster_size=min_cluster_size,
240
+ max_cluster_size=max_cluster_size,
241
+ )
242
+
243
+ print_header(f"Optimizing distance threshold for domains")
244
+ # Define domains in the network using the specified clustering settings
245
+ domains = self._define_domains(
246
+ neighborhoods=processed_neighborhoods,
247
+ top_annotations=top_annotations,
248
+ linkage_criterion=linkage_criterion,
249
+ linkage_method=linkage_method,
250
+ linkage_metric=linkage_metric,
251
+ )
252
+ # Trim domains and top annotations based on cluster size constraints
253
+ top_annotations, domains, trimmed_domains = trim_domains_and_top_annotations(
254
+ domains=domains,
255
+ top_annotations=top_annotations,
256
+ min_cluster_size=min_cluster_size,
257
+ max_cluster_size=max_cluster_size,
258
+ )
259
+
260
+ # Prepare node mapping and enrichment sums for the final NetworkGraph object
261
+ ordered_nodes = annotations["ordered_nodes"]
262
+ node_label_to_id = dict(zip(ordered_nodes, range(len(ordered_nodes))))
263
+ node_enrichment_sums = processed_neighborhoods["node_enrichment_sums"]
264
+
265
+ # Return the fully initialized NetworkGraph object
266
+ return NetworkGraph(
267
+ network=network,
268
+ top_annotations=top_annotations,
269
+ domains=domains,
270
+ trimmed_domains=trimmed_domains,
271
+ node_label_to_id_map=node_label_to_id,
272
+ node_enrichment_sums=node_enrichment_sums,
273
+ )
274
+
275
+ def load_plotter(
276
+ self,
277
+ graph: NetworkGraph,
278
+ figsize: tuple = (10, 10),
279
+ background_color: str = "white",
280
+ plot_outline: bool = True,
281
+ outline_color: str = "black",
282
+ outline_scale: float = 1.00,
283
+ ) -> NetworkPlotter:
284
+ """Get a NetworkPlotter object for plotting.
285
+
286
+ Args:
287
+ graph (NetworkGraph): The graph to plot.
288
+ figsize (tuple, optional): Size of the figure. Defaults to (10, 10).
289
+ background_color (str, optional): Background color of the plot. Defaults to "white".
290
+ plot_outline (bool, optional): Whether to plot the network outline. Defaults to True.
291
+ outline_color (str, optional): Color of the outline. Defaults to "black".
292
+ outline_scale (float, optional): Scaling factor for the outline. Defaults to 1.00.
293
+
294
+ Returns:
295
+ NetworkPlotter: A NetworkPlotter object configured with the given parameters.
296
+ """
297
+ print_header("Loading plotter")
298
+ # Log the plotter settings
299
+ params.log_plotter(
300
+ figsize=figsize,
301
+ background_color=background_color,
302
+ plot_outline=plot_outline,
303
+ outline_color=outline_color,
304
+ outline_scale=outline_scale,
305
+ )
306
+ # Initialize and return a NetworkPlotter object
307
+ return NetworkPlotter(
308
+ graph,
309
+ figsize=figsize,
310
+ background_color=background_color,
311
+ plot_outline=plot_outline,
312
+ outline_color=outline_color,
313
+ outline_scale=outline_scale,
314
+ )
315
+
316
+ def _define_top_annotations(
317
+ self,
318
+ network: nx.Graph,
319
+ annotations: Dict[str, Any],
320
+ neighborhoods: Dict[str, Any],
321
+ min_cluster_size: int = 5,
322
+ max_cluster_size: int = 1000,
323
+ ) -> pd.DataFrame:
324
+ """Define top annotations for the network.
325
+
326
+ Args:
327
+ network (nx.Graph): The network graph.
328
+ annotations (dict): Annotations data for the network.
329
+ neighborhoods (dict): Neighborhood enrichment data.
330
+ min_cluster_size (int, optional): Minimum size for clusters. Defaults to 5.
331
+ max_cluster_size (int, optional): Maximum size for clusters. Defaults to 1000.
332
+
333
+ Returns:
334
+ dict: Top annotations identified within the network.
335
+ """
336
+ # Extract necessary data from annotations and neighborhoods
337
+ ordered_annotations = annotations["ordered_annotations"]
338
+ neighborhood_enrichment_sums = neighborhoods["neighborhood_enrichment_counts"]
339
+ neighborhoods_binary_enrichment_matrix = neighborhoods["binary_enrichment_matrix"]
340
+ # Call external function to define top annotations
341
+ return define_top_annotations(
342
+ network=network,
343
+ ordered_annotation_labels=ordered_annotations,
344
+ neighborhood_enrichment_sums=neighborhood_enrichment_sums,
345
+ binary_enrichment_matrix=neighborhoods_binary_enrichment_matrix,
346
+ min_cluster_size=min_cluster_size,
347
+ max_cluster_size=max_cluster_size,
348
+ )
349
+
350
+ def _define_domains(
351
+ self,
352
+ neighborhoods: Dict[str, Any],
353
+ top_annotations: pd.DataFrame,
354
+ linkage_criterion: str,
355
+ linkage_method: str,
356
+ linkage_metric: str,
357
+ ) -> pd.DataFrame:
358
+ """Define domains in the network based on enrichment data.
359
+
360
+ Args:
361
+ neighborhoods (dict): Enrichment data for neighborhoods.
362
+ top_annotations (pd.DataFrame): Enrichment matrix for top annotations.
363
+ linkage_criterion (str): Clustering criterion for defining domains.
364
+ linkage_method (str): Clustering method to use.
365
+ linkage_metric (str): Metric to use for calculating distances.
366
+
367
+ Returns:
368
+ pd.DataFrame: Matrix of defined domains.
369
+ """
370
+ # Extract the significant enrichment matrix from the neighborhoods data
371
+ significant_neighborhoods_enrichment = neighborhoods["significant_enrichment_matrix"]
372
+ # Call external function to define domains based on the extracted data
373
+ return define_domains(
374
+ top_annotations=top_annotations,
375
+ significant_neighborhoods_enrichment=significant_neighborhoods_enrichment,
376
+ linkage_criterion=linkage_criterion,
377
+ linkage_method=linkage_method,
378
+ linkage_metric=linkage_metric,
379
+ )
risk/stats/__init__.py ADDED
@@ -0,0 +1,6 @@
1
+ """
2
+ risk/stats
3
+ ~~~~~~~~~~
4
+ """
5
+
6
+ from .stats import calculate_significance_matrices, compute_permutation
@@ -0,0 +1,88 @@
1
+ """
2
+ risk/stats/permutation
3
+ ~~~~~~~~~~~~~~~~~~~~~~
4
+ """
5
+
6
+ import numpy as np
7
+
8
+ # Note: Cython optimizations provided minimal performance benefits.
9
+ # The final version with Cython is archived in the `cython_permutation` branch.
10
+
11
+
12
+ def compute_neighborhood_score_by_sum(
13
+ neighborhoods_matrix: np.ndarray, annotation_matrix: np.ndarray
14
+ ) -> np.ndarray:
15
+ """Compute the sum of attribute values for each neighborhood.
16
+
17
+ Args:
18
+ neighborhoods_matrix (np.ndarray): Binary matrix representing neighborhoods.
19
+ annotation_matrix (np.ndarray): Matrix representing annotation values.
20
+
21
+ Returns:
22
+ np.ndarray: Sum of attribute values for each neighborhood.
23
+ """
24
+ # Calculate the neighborhood score as the dot product of neighborhoods and annotations
25
+ neighborhood_score = np.dot(neighborhoods_matrix, annotation_matrix)
26
+ return neighborhood_score
27
+
28
+
29
+ def compute_neighborhood_score_by_stdev(
30
+ neighborhoods_matrix: np.ndarray, annotation_matrix: np.ndarray
31
+ ) -> np.ndarray:
32
+ """Compute the standard deviation of neighborhood scores.
33
+
34
+ Args:
35
+ neighborhoods_matrix (np.ndarray): Binary matrix representing neighborhoods.
36
+ annotation_matrix (np.ndarray): Matrix representing annotation values.
37
+
38
+ Returns:
39
+ np.ndarray: Standard deviation of the neighborhood scores.
40
+ """
41
+ # Calculate the neighborhood score as the dot product of neighborhoods and annotations
42
+ neighborhood_score = np.dot(neighborhoods_matrix, annotation_matrix)
43
+ # Calculate the number of elements in each neighborhood
44
+ N = np.sum(neighborhoods_matrix, axis=1)
45
+ # Compute the mean of the neighborhood scores
46
+ M = neighborhood_score / N[:, None]
47
+ # Compute the mean of squares (EXX) directly using squared annotation matrix
48
+ EXX = np.dot(neighborhoods_matrix, annotation_matrix**2) / N[:, None]
49
+ # Calculate variance as EXX - M^2
50
+ variance = EXX - M**2
51
+ # Compute the standard deviation as the square root of the variance
52
+ stdev = np.sqrt(variance)
53
+ return stdev
54
+
55
+
56
+ def compute_neighborhood_score_by_z_score(
57
+ neighborhoods_matrix: np.ndarray, annotation_matrix: np.ndarray
58
+ ) -> np.ndarray:
59
+ """Compute Z-scores for neighborhood scores.
60
+
61
+ Args:
62
+ neighborhoods_matrix (np.ndarray): Binary matrix representing neighborhoods.
63
+ annotation_matrix (np.ndarray): Matrix representing annotation values.
64
+
65
+ Returns:
66
+ np.ndarray: Z-scores for each neighborhood.
67
+ """
68
+ # Calculate the neighborhood score as the dot product of neighborhoods and annotations
69
+ neighborhood_score = np.dot(neighborhoods_matrix, annotation_matrix)
70
+ # Calculate the number of elements in each neighborhood
71
+ N = np.dot(
72
+ neighborhoods_matrix, np.ones(annotation_matrix.shape[1], dtype=annotation_matrix.dtype)
73
+ )
74
+ # Compute the mean of the neighborhood scores
75
+ M = neighborhood_score / N
76
+ # Compute the mean of squares (EXX)
77
+ EXX = np.dot(neighborhoods_matrix, annotation_matrix**2) / N
78
+ # Calculate the standard deviation for each neighborhood
79
+ variance = EXX - M**2
80
+ std = np.sqrt(variance)
81
+ # Calculate Z-scores, handling cases where std is 0 or N is less than 3
82
+ with np.errstate(divide="ignore", invalid="ignore"):
83
+ z_scores = M / std
84
+ z_scores[(std == 0) | (N < 3)] = (
85
+ np.nan
86
+ ) # Handle division by zero and apply minimum threshold
87
+
88
+ return z_scores