risk-network 0.0.11__py3-none-any.whl → 0.0.12b0__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.
Files changed (42) hide show
  1. risk/__init__.py +1 -1
  2. risk/risk.py +5 -5
  3. {risk_network-0.0.11.dist-info → risk_network-0.0.12b0.dist-info}/METADATA +10 -12
  4. risk_network-0.0.12b0.dist-info/RECORD +7 -0
  5. {risk_network-0.0.11.dist-info → risk_network-0.0.12b0.dist-info}/WHEEL +1 -1
  6. risk/annotations/__init__.py +0 -7
  7. risk/annotations/annotations.py +0 -354
  8. risk/annotations/io.py +0 -240
  9. risk/annotations/nltk_setup.py +0 -85
  10. risk/log/__init__.py +0 -11
  11. risk/log/console.py +0 -141
  12. risk/log/parameters.py +0 -172
  13. risk/neighborhoods/__init__.py +0 -8
  14. risk/neighborhoods/api.py +0 -442
  15. risk/neighborhoods/community.py +0 -412
  16. risk/neighborhoods/domains.py +0 -358
  17. risk/neighborhoods/neighborhoods.py +0 -508
  18. risk/network/__init__.py +0 -6
  19. risk/network/geometry.py +0 -150
  20. risk/network/graph/__init__.py +0 -6
  21. risk/network/graph/api.py +0 -200
  22. risk/network/graph/graph.py +0 -269
  23. risk/network/graph/summary.py +0 -254
  24. risk/network/io.py +0 -550
  25. risk/network/plotter/__init__.py +0 -6
  26. risk/network/plotter/api.py +0 -54
  27. risk/network/plotter/canvas.py +0 -291
  28. risk/network/plotter/contour.py +0 -330
  29. risk/network/plotter/labels.py +0 -924
  30. risk/network/plotter/network.py +0 -294
  31. risk/network/plotter/plotter.py +0 -143
  32. risk/network/plotter/utils/colors.py +0 -416
  33. risk/network/plotter/utils/layout.py +0 -94
  34. risk/stats/__init__.py +0 -15
  35. risk/stats/permutation/__init__.py +0 -6
  36. risk/stats/permutation/permutation.py +0 -237
  37. risk/stats/permutation/test_functions.py +0 -70
  38. risk/stats/significance.py +0 -166
  39. risk/stats/stat_tests.py +0 -267
  40. risk_network-0.0.11.dist-info/RECORD +0 -41
  41. {risk_network-0.0.11.dist-info → risk_network-0.0.12b0.dist-info/licenses}/LICENSE +0 -0
  42. {risk_network-0.0.11.dist-info → risk_network-0.0.12b0.dist-info}/top_level.txt +0 -0
risk/network/graph/api.py DELETED
@@ -1,200 +0,0 @@
1
- """
2
- risk/network/graph/api
3
- ~~~~~~~~~~~~~~~~~~~~~~
4
- """
5
-
6
- import copy
7
- from typing import Any, Dict, Union
8
-
9
- import networkx as nx
10
- import pandas as pd
11
-
12
- from risk.annotations import define_top_annotations
13
- from risk.log import logger, log_header, params
14
- from risk.neighborhoods import (
15
- define_domains,
16
- process_neighborhoods,
17
- trim_domains,
18
- )
19
- from risk.network.graph.graph import Graph
20
- from risk.stats import calculate_significance_matrices
21
-
22
-
23
- class GraphAPI:
24
- """Handles the loading of network graphs and associated data.
25
-
26
- The GraphAPI class provides methods to load and process network graphs, annotations, and neighborhoods.
27
- """
28
-
29
- def __init__() -> None:
30
- pass
31
-
32
- def load_graph(
33
- self,
34
- network: nx.Graph,
35
- annotations: Dict[str, Any],
36
- neighborhoods: Dict[str, Any],
37
- tail: str = "right",
38
- pval_cutoff: float = 0.01,
39
- fdr_cutoff: float = 0.9999,
40
- impute_depth: int = 0,
41
- prune_threshold: float = 0.0,
42
- linkage_criterion: str = "distance",
43
- linkage_method: str = "average",
44
- linkage_metric: str = "yule",
45
- linkage_threshold: Union[float, str] = 0.2,
46
- min_cluster_size: int = 5,
47
- max_cluster_size: int = 1000,
48
- ) -> Graph:
49
- """Load and process the network graph, defining top annotations and domains.
50
-
51
- Args:
52
- network (nx.Graph): The network graph.
53
- annotations (Dict[str, Any]): The annotations associated with the network.
54
- neighborhoods (Dict[str, Any]): Neighborhood significance data.
55
- tail (str, optional): Type of significance tail ("right", "left", "both"). Defaults to "right".
56
- pval_cutoff (float, optional): p-value cutoff for significance. Defaults to 0.01.
57
- fdr_cutoff (float, optional): FDR cutoff for significance. Defaults to 0.9999.
58
- impute_depth (int, optional): Depth for imputing neighbors. Defaults to 0.
59
- prune_threshold (float, optional): Distance threshold for pruning neighbors. Defaults to 0.0.
60
- linkage_criterion (str, optional): Clustering criterion for defining domains. Defaults to "distance".
61
- linkage_method (str, optional): Clustering method to use. Choose "auto" to optimize. Defaults to "average".
62
- linkage_metric (str, optional): Metric to use for calculating distances. Choose "auto" to optimize.
63
- Defaults to "yule".
64
- linkage_threshold (float, str, optional): Threshold for clustering. Choose "auto" to optimize.
65
- Defaults to 0.2.
66
- min_cluster_size (int, optional): Minimum size for clusters. Defaults to 5.
67
- max_cluster_size (int, optional): Maximum size for clusters. Defaults to 1000.
68
-
69
- Returns:
70
- Graph: A fully initialized and processed Graph object.
71
- """
72
- # Log the parameters and display headers
73
- log_header("Finding significant neighborhoods")
74
- params.log_graph(
75
- tail=tail,
76
- pval_cutoff=pval_cutoff,
77
- fdr_cutoff=fdr_cutoff,
78
- impute_depth=impute_depth,
79
- prune_threshold=prune_threshold,
80
- linkage_criterion=linkage_criterion,
81
- linkage_method=linkage_method,
82
- linkage_metric=linkage_metric,
83
- linkage_threshold=linkage_threshold,
84
- min_cluster_size=min_cluster_size,
85
- max_cluster_size=max_cluster_size,
86
- )
87
-
88
- # Make a copy of the network to avoid modifying the original
89
- network = copy.deepcopy(network)
90
-
91
- logger.debug(f"p-value cutoff: {pval_cutoff}")
92
- logger.debug(f"FDR BH cutoff: {fdr_cutoff}")
93
- logger.debug(
94
- f"Significance tail: '{tail}' ({'enrichment' if tail == 'right' else 'depletion' if tail == 'left' else 'both'})"
95
- )
96
- # Calculate significant neighborhoods based on the provided parameters
97
- significant_neighborhoods = calculate_significance_matrices(
98
- neighborhoods["depletion_pvals"],
99
- neighborhoods["enrichment_pvals"],
100
- tail=tail,
101
- pval_cutoff=pval_cutoff,
102
- fdr_cutoff=fdr_cutoff,
103
- )
104
-
105
- log_header("Processing neighborhoods")
106
- # Process neighborhoods by imputing and pruning based on the given settings
107
- processed_neighborhoods = process_neighborhoods(
108
- network=network,
109
- neighborhoods=significant_neighborhoods,
110
- impute_depth=impute_depth,
111
- prune_threshold=prune_threshold,
112
- )
113
-
114
- log_header("Finding top annotations")
115
- logger.debug(f"Min cluster size: {min_cluster_size}")
116
- logger.debug(f"Max cluster size: {max_cluster_size}")
117
- # Define top annotations based on processed neighborhoods
118
- top_annotations = self._define_top_annotations(
119
- network=network,
120
- annotations=annotations,
121
- neighborhoods=processed_neighborhoods,
122
- min_cluster_size=min_cluster_size,
123
- max_cluster_size=max_cluster_size,
124
- )
125
-
126
- log_header("Optimizing distance threshold for domains")
127
- # Extract the significant significance matrix from the neighborhoods data
128
- significant_neighborhoods_significance = processed_neighborhoods[
129
- "significant_significance_matrix"
130
- ]
131
- # Define domains in the network using the specified clustering settings
132
- domains = define_domains(
133
- top_annotations=top_annotations,
134
- significant_neighborhoods_significance=significant_neighborhoods_significance,
135
- linkage_criterion=linkage_criterion,
136
- linkage_method=linkage_method,
137
- linkage_metric=linkage_metric,
138
- linkage_threshold=linkage_threshold,
139
- )
140
- # Trim domains and top annotations based on cluster size constraints
141
- domains, trimmed_domains = trim_domains(
142
- domains=domains,
143
- top_annotations=top_annotations,
144
- min_cluster_size=min_cluster_size,
145
- max_cluster_size=max_cluster_size,
146
- )
147
-
148
- # Prepare node mapping and significance sums for the final Graph object
149
- ordered_nodes = annotations["ordered_nodes"]
150
- node_label_to_id = dict(zip(ordered_nodes, range(len(ordered_nodes))))
151
- node_significance_sums = processed_neighborhoods["node_significance_sums"]
152
-
153
- # Return the fully initialized Graph object
154
- return Graph(
155
- network=network,
156
- annotations=annotations,
157
- neighborhoods=neighborhoods,
158
- domains=domains,
159
- trimmed_domains=trimmed_domains,
160
- node_label_to_node_id_map=node_label_to_id,
161
- node_significance_sums=node_significance_sums,
162
- )
163
-
164
- def _define_top_annotations(
165
- self,
166
- network: nx.Graph,
167
- annotations: Dict[str, Any],
168
- neighborhoods: Dict[str, Any],
169
- min_cluster_size: int = 5,
170
- max_cluster_size: int = 1000,
171
- ) -> pd.DataFrame:
172
- """Define top annotations for the network.
173
-
174
- Args:
175
- network (nx.Graph): The network graph.
176
- annotations (Dict[str, Any]): Annotations data for the network.
177
- neighborhoods (Dict[str, Any]): Neighborhood significance data.
178
- min_cluster_size (int, optional): Minimum size for clusters. Defaults to 5.
179
- max_cluster_size (int, optional): Maximum size for clusters. Defaults to 1000.
180
-
181
- Returns:
182
- Dict[str, Any]: Top annotations identified within the network.
183
- """
184
- # Extract necessary data from annotations and neighborhoods
185
- ordered_annotations = annotations["ordered_annotations"]
186
- neighborhood_significance_sums = neighborhoods["neighborhood_significance_counts"]
187
- significant_significance_matrix = neighborhoods["significant_significance_matrix"]
188
- significant_binary_significance_matrix = neighborhoods[
189
- "significant_binary_significance_matrix"
190
- ]
191
- # Call external function to define top annotations
192
- return define_top_annotations(
193
- network=network,
194
- ordered_annotation_labels=ordered_annotations,
195
- neighborhood_significance_sums=neighborhood_significance_sums,
196
- significant_significance_matrix=significant_significance_matrix,
197
- significant_binary_significance_matrix=significant_binary_significance_matrix,
198
- min_cluster_size=min_cluster_size,
199
- max_cluster_size=max_cluster_size,
200
- )
@@ -1,269 +0,0 @@
1
- """
2
- risk/network/graph/graph
3
- ~~~~~~~~~~~~~~~~~~~~~~~~
4
- """
5
-
6
- from collections import defaultdict
7
- from typing import Any, Dict, List
8
-
9
- import networkx as nx
10
- import numpy as np
11
- import pandas as pd
12
-
13
- from risk.network.graph.summary import Summary
14
-
15
-
16
- class Graph:
17
- """A class to represent a network graph and process its nodes and edges.
18
-
19
- The Graph class provides functionality to handle and manipulate a network graph,
20
- including managing domains, annotations, and node significance data. It also includes methods
21
- for transforming and mapping graph coordinates, as well as generating colors based on node
22
- significance.
23
- """
24
-
25
- def __init__(
26
- self,
27
- network: nx.Graph,
28
- annotations: Dict[str, Any],
29
- neighborhoods: Dict[str, Any],
30
- domains: pd.DataFrame,
31
- trimmed_domains: pd.DataFrame,
32
- node_label_to_node_id_map: Dict[str, Any],
33
- node_significance_sums: np.ndarray,
34
- ):
35
- """Initialize the Graph object.
36
-
37
- Args:
38
- network (nx.Graph): The network graph.
39
- annotations (Dict[str, Any]): The annotations associated with the network.
40
- neighborhoods (Dict[str, Any]): Neighborhood significance data.
41
- domains (pd.DataFrame): DataFrame containing domain data for the network nodes.
42
- trimmed_domains (pd.DataFrame): DataFrame containing trimmed domain data for the network nodes.
43
- node_label_to_node_id_map (Dict[str, Any]): A dictionary mapping node labels to their corresponding IDs.
44
- node_significance_sums (np.ndarray): Array containing the significant sums for the nodes.
45
- """
46
- # Initialize self.network downstream of the other attributes
47
- # All public attributes can be accessed after initialization
48
- self.domain_id_to_node_ids_map = self._create_domain_id_to_node_ids_map(domains)
49
- self.domain_id_to_domain_terms_map = self._create_domain_id_to_domain_terms_map(
50
- trimmed_domains
51
- )
52
- self.domain_id_to_domain_info_map = self._create_domain_id_to_domain_info_map(
53
- trimmed_domains
54
- )
55
- self.node_id_to_domain_ids_and_significance_map = (
56
- self._create_node_id_to_domain_ids_and_significances(domains)
57
- )
58
- self.node_id_to_node_label_map = {v: k for k, v in node_label_to_node_id_map.items()}
59
- self.node_label_to_significance_map = dict(
60
- zip(node_label_to_node_id_map.keys(), node_significance_sums)
61
- )
62
- self.node_significance_sums = node_significance_sums
63
- self.node_label_to_node_id_map = node_label_to_node_id_map
64
-
65
- # NOTE: Below this point, instance attributes (i.e., self) will be used!
66
- self.domain_id_to_node_labels_map = self._create_domain_id_to_node_labels_map()
67
- # Unfold the network's 3D coordinates to 2D and extract node coordinates
68
- self.network = _unfold_sphere_to_plane(network)
69
- self.node_coordinates = _extract_node_coordinates(self.network)
70
-
71
- # NOTE: Only after the above attributes are initialized, we can create the summary
72
- self.summary = Summary(annotations, neighborhoods, self)
73
-
74
- def pop(self, domain_id: str) -> None:
75
- """Remove domain ID from instance domain ID mappings. This can be useful for cleaning up
76
- domain-specific mappings based on a given criterion, as domain attributes are stored and
77
- accessed only in dictionaries modified by this method.
78
-
79
- Args:
80
- key (str): The domain ID key to be removed from each mapping.
81
- """
82
- # Define the domain mappings to be updated
83
- domain_mappings = [
84
- self.domain_id_to_node_ids_map,
85
- self.domain_id_to_domain_terms_map,
86
- self.domain_id_to_domain_info_map,
87
- self.domain_id_to_node_labels_map,
88
- ]
89
- # Remove the specified domain_id key from each mapping if it exists
90
- for mapping in domain_mappings:
91
- if domain_id in mapping:
92
- mapping.pop(domain_id)
93
-
94
- # Remove the domain_id from the node_id_to_domain_ids_and_significance_map
95
- for _, domain_info in self.node_id_to_domain_ids_and_significance_map.items():
96
- if domain_id in domain_info["domains"]:
97
- domain_info["domains"].remove(domain_id)
98
- domain_info["significances"].pop(domain_id)
99
-
100
- @staticmethod
101
- def _create_domain_id_to_node_ids_map(domains: pd.DataFrame) -> Dict[int, Any]:
102
- """Create a mapping from domains to the list of node IDs belonging to each domain.
103
-
104
- Args:
105
- domains (pd.DataFrame): DataFrame containing domain information, including the 'primary domain' for each node.
106
-
107
- Returns:
108
- Dict[int, Any]: A dictionary where keys are domain IDs and values are lists of node IDs belonging to each domain.
109
- """
110
- cleaned_domains_matrix = domains.reset_index()[["index", "primary_domain"]]
111
- node_to_domains_map = cleaned_domains_matrix.set_index("index")["primary_domain"].to_dict()
112
- domain_id_to_node_ids_map = defaultdict(list)
113
- for k, v in node_to_domains_map.items():
114
- domain_id_to_node_ids_map[v].append(k)
115
-
116
- return domain_id_to_node_ids_map
117
-
118
- @staticmethod
119
- def _create_domain_id_to_domain_terms_map(trimmed_domains: pd.DataFrame) -> Dict[int, Any]:
120
- """Create a mapping from domain IDs to their corresponding terms.
121
-
122
- Args:
123
- trimmed_domains (pd.DataFrame): DataFrame containing domain IDs and their corresponding labels.
124
-
125
- Returns:
126
- Dict[int, Any]: A dictionary mapping domain IDs to their corresponding terms.
127
- """
128
- return dict(
129
- zip(
130
- trimmed_domains.index,
131
- trimmed_domains["normalized_description"],
132
- )
133
- )
134
-
135
- @staticmethod
136
- def _create_domain_id_to_domain_info_map(
137
- trimmed_domains: pd.DataFrame,
138
- ) -> Dict[int, Dict[str, Any]]:
139
- """Create a mapping from domain IDs to their corresponding full description and significance score,
140
- with scores sorted in descending order.
141
-
142
- Args:
143
- trimmed_domains (pd.DataFrame): DataFrame containing domain IDs, full descriptions, and significance scores.
144
-
145
- Returns:
146
- Dict[int, Dict[str, Any]]: A dictionary mapping domain IDs (int) to a dictionary with 'full_descriptions' and
147
- 'significance_scores', both sorted by significance score in descending order.
148
- """
149
- # Initialize an empty dictionary to store full descriptions and significance scores of domains
150
- domain_info_map = {}
151
- # Domain IDs are the index of the DataFrame (it's common for some IDs to be missing)
152
- for domain_id in trimmed_domains.index:
153
- # Sort full_descriptions and significance_scores by significance_scores in descending order
154
- descriptions_and_scores = sorted(
155
- zip(
156
- trimmed_domains.at[domain_id, "full_descriptions"],
157
- trimmed_domains.at[domain_id, "significance_scores"],
158
- ),
159
- key=lambda x: x[1], # Sort by significance score
160
- reverse=True, # Descending order
161
- )
162
- # Unzip the sorted tuples back into separate lists
163
- sorted_descriptions, sorted_scores = zip(*descriptions_and_scores)
164
- # Assign to the domain info map
165
- domain_info_map[int(domain_id)] = {
166
- "full_descriptions": list(sorted_descriptions),
167
- "significance_scores": list(sorted_scores),
168
- }
169
-
170
- return domain_info_map
171
-
172
- @staticmethod
173
- def _create_node_id_to_domain_ids_and_significances(domains: pd.DataFrame) -> Dict[int, Dict]:
174
- """Creates a dictionary mapping each node ID to its corresponding domain IDs and significance values.
175
-
176
- Args:
177
- domains (pd.DataFrame): A DataFrame containing domain information for each node. Assumes the last
178
- two columns are 'all domains' and 'primary domain', which are excluded from processing.
179
-
180
- Returns:
181
- Dict[int, Dict]: A dictionary where the key is the node ID (index of the DataFrame), and the value is another dictionary
182
- with 'domain' (a list of domain IDs with non-zero significance) and 'significance'
183
- (a dict of domain IDs and their corresponding significance values).
184
- """
185
- # Initialize an empty dictionary to store the result
186
- node_id_to_domain_ids_and_significances = {}
187
- # Get the list of domain columns (excluding 'all domains' and 'primary domain')
188
- domain_columns = domains.columns[
189
- :-2
190
- ] # The last two columns are 'all domains' and 'primary domain'
191
- # Iterate over each row in the dataframe
192
- for idx, row in domains.iterrows():
193
- # Get the domains (column names) where the significance score is greater than 0
194
- all_domains = domain_columns[row[domain_columns] > 0].tolist()
195
- # Get the significance values for those domains
196
- significance_values = row[all_domains].to_dict()
197
- # Store the result in the dictionary with index as the key
198
- node_id_to_domain_ids_and_significances[idx] = {
199
- "domains": all_domains, # The column names where significance > 0
200
- "significances": significance_values, # The actual significance values for those columns
201
- }
202
-
203
- return node_id_to_domain_ids_and_significances
204
-
205
- def _create_domain_id_to_node_labels_map(self) -> Dict[int, List[str]]:
206
- """Create a map from domain IDs to node labels.
207
-
208
- Returns:
209
- Dict[int, List[str]]: A dictionary mapping domain IDs to the corresponding node labels.
210
- """
211
- domain_id_to_label_map = {}
212
- for domain_id, node_ids in self.domain_id_to_node_ids_map.items():
213
- domain_id_to_label_map[domain_id] = [
214
- self.node_id_to_node_label_map[node_id] for node_id in node_ids
215
- ]
216
-
217
- return domain_id_to_label_map
218
-
219
-
220
- def _unfold_sphere_to_plane(G: nx.Graph) -> nx.Graph:
221
- """Convert 3D coordinates to 2D by unfolding a sphere to a plane.
222
-
223
- Args:
224
- G (nx.Graph): A network graph with 3D coordinates. Each node should have 'x', 'y', and 'z' attributes.
225
-
226
- Returns:
227
- nx.Graph: The network graph with updated 2D coordinates (only 'x' and 'y').
228
- """
229
- for node in G.nodes():
230
- if "z" in G.nodes[node]:
231
- # Extract 3D coordinates
232
- x, y, z = G.nodes[node]["x"], G.nodes[node]["y"], G.nodes[node]["z"]
233
- # Calculate spherical coordinates theta and phi from Cartesian coordinates
234
- r = np.sqrt(x**2 + y**2 + z**2)
235
- theta = np.arctan2(y, x)
236
- phi = np.arccos(z / r)
237
-
238
- # Convert spherical coordinates to 2D plane coordinates
239
- unfolded_x = (theta + np.pi) / (2 * np.pi) # Shift and normalize theta to [0, 1]
240
- unfolded_x = unfolded_x + 0.5 if unfolded_x < 0.5 else unfolded_x - 0.5
241
- unfolded_y = (np.pi - phi) / np.pi # Reflect phi and normalize to [0, 1]
242
- # Update network node attributes
243
- G.nodes[node]["x"] = unfolded_x
244
- G.nodes[node]["y"] = -unfolded_y
245
- # Remove the 'z' coordinate as it's no longer needed
246
- del G.nodes[node]["z"]
247
-
248
- return G
249
-
250
-
251
- def _extract_node_coordinates(G: nx.Graph) -> np.ndarray:
252
- """Extract 2D coordinates of nodes from the graph.
253
-
254
- Args:
255
- G (nx.Graph): The network graph with node coordinates.
256
-
257
- Returns:
258
- np.ndarray: Array of node coordinates with shape (num_nodes, 2).
259
- """
260
- # Extract x and y coordinates from graph nodes
261
- x_coords = dict(G.nodes.data("x"))
262
- y_coords = dict(G.nodes.data("y"))
263
- coordinates_dicts = [x_coords, y_coords]
264
- # Combine x and y coordinates into a single array
265
- node_positions = {
266
- node: np.array([coords[node] for coords in coordinates_dicts]) for node in x_coords
267
- }
268
- node_coordinates = np.vstack(list(node_positions.values()))
269
- return node_coordinates