risk-network 0.0.9b1__py3-none-any.whl → 0.0.9b3__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/__init__.py +1 -1
- risk/annotations/io.py +8 -6
- risk/log/__init__.py +3 -1
- risk/log/{params.py → parameters.py} +9 -34
- risk/neighborhoods/domains.py +3 -3
- risk/neighborhoods/neighborhoods.py +3 -3
- risk/network/graph/__init__.py +6 -0
- risk/network/{graph.py → graph/network.py} +13 -2
- risk/network/graph/summary.py +233 -0
- risk/network/io.py +3 -3
- risk/risk.py +5 -12
- {risk_network-0.0.9b1.dist-info → risk_network-0.0.9b3.dist-info}/METADATA +1 -1
- {risk_network-0.0.9b1.dist-info → risk_network-0.0.9b3.dist-info}/RECORD +16 -15
- risk/log/enrichment.py +0 -18
- {risk_network-0.0.9b1.dist-info → risk_network-0.0.9b3.dist-info}/LICENSE +0 -0
- {risk_network-0.0.9b1.dist-info → risk_network-0.0.9b3.dist-info}/WHEEL +0 -0
- {risk_network-0.0.9b1.dist-info → risk_network-0.0.9b3.dist-info}/top_level.txt +0 -0
risk/__init__.py
CHANGED
risk/annotations/io.py
CHANGED
@@ -76,11 +76,13 @@ class AnnotationsIO:
|
|
76
76
|
_log_loading(filetype, filepath=filepath)
|
77
77
|
|
78
78
|
# Load the specified sheet from the Excel file
|
79
|
-
|
79
|
+
annotation = pd.read_excel(filepath, sheet_name=sheet_name)
|
80
80
|
# Split the nodes column by the specified nodes_delimiter
|
81
|
-
|
81
|
+
annotation[nodes_colname] = annotation[nodes_colname].apply(
|
82
|
+
lambda x: x.split(nodes_delimiter)
|
83
|
+
)
|
82
84
|
# Convert the DataFrame to a dictionary pairing labels with their corresponding nodes
|
83
|
-
label_node_dict =
|
85
|
+
label_node_dict = annotation.set_index(label_colname)[nodes_colname].to_dict()
|
84
86
|
|
85
87
|
# Load the annotations into the provided network
|
86
88
|
return load_annotations(network, label_node_dict)
|
@@ -203,11 +205,11 @@ def _load_matrix_file(
|
|
203
205
|
Dict[str, Any]: A dictionary where each label is paired with its respective list of nodes.
|
204
206
|
"""
|
205
207
|
# Load the CSV or TSV file into a DataFrame
|
206
|
-
|
208
|
+
annotation = pd.read_csv(filepath, delimiter=delimiter)
|
207
209
|
# Split the nodes column by the nodes_delimiter to handle multiple nodes per label
|
208
|
-
|
210
|
+
annotation[nodes_colname] = annotation[nodes_colname].apply(lambda x: x.split(nodes_delimiter))
|
209
211
|
# Create a dictionary pairing labels with their corresponding list of nodes
|
210
|
-
label_node_dict =
|
212
|
+
label_node_dict = annotation.set_index(label_colname)[nodes_colname].to_dict()
|
211
213
|
return label_node_dict
|
212
214
|
|
213
215
|
|
risk/log/__init__.py
CHANGED
@@ -1,50 +1,22 @@
|
|
1
1
|
"""
|
2
|
-
risk/log/
|
3
|
-
|
2
|
+
risk/log/parameters
|
3
|
+
~~~~~~~~~~~~~~~~~~~
|
4
4
|
"""
|
5
5
|
|
6
6
|
import csv
|
7
7
|
import json
|
8
8
|
import warnings
|
9
9
|
from datetime import datetime
|
10
|
-
from functools import wraps
|
11
10
|
from typing import Any, Dict
|
12
11
|
|
13
12
|
import numpy as np
|
14
13
|
|
15
|
-
from .console import logger, log_header
|
14
|
+
from risk.log.console import logger, log_header
|
16
15
|
|
17
16
|
# Suppress all warnings - this is to resolve warnings from multiprocessing
|
18
17
|
warnings.filterwarnings("ignore")
|
19
18
|
|
20
19
|
|
21
|
-
def _safe_param_export(func):
|
22
|
-
"""A decorator to wrap parameter export functions in a try-except block for safe execution.
|
23
|
-
|
24
|
-
Args:
|
25
|
-
func (function): The function to be wrapped.
|
26
|
-
|
27
|
-
Returns:
|
28
|
-
function: The wrapped function with error handling.
|
29
|
-
"""
|
30
|
-
|
31
|
-
@wraps(func)
|
32
|
-
def wrapper(*args, **kwargs):
|
33
|
-
try:
|
34
|
-
result = func(*args, **kwargs)
|
35
|
-
filepath = (
|
36
|
-
kwargs.get("filepath") or args[1]
|
37
|
-
) # Assuming filepath is always the second argument
|
38
|
-
logger.info(f"Parameters successfully exported to filepath: {filepath}")
|
39
|
-
return result
|
40
|
-
except Exception as e:
|
41
|
-
filepath = kwargs.get("filepath") or args[1]
|
42
|
-
logger.error(f"An error occurred while exporting parameters to {filepath}: {e}")
|
43
|
-
return None
|
44
|
-
|
45
|
-
return wrapper
|
46
|
-
|
47
|
-
|
48
20
|
class Params:
|
49
21
|
"""Handles the storage and logging of various parameters for network analysis.
|
50
22
|
|
@@ -106,7 +78,6 @@ class Params:
|
|
106
78
|
"""
|
107
79
|
self.plotter = {**self.plotter, **kwargs}
|
108
80
|
|
109
|
-
@_safe_param_export
|
110
81
|
def to_csv(self, filepath: str) -> None:
|
111
82
|
"""Export the parameters to a CSV file.
|
112
83
|
|
@@ -128,7 +99,8 @@ class Params:
|
|
128
99
|
else:
|
129
100
|
writer.writerow([parent_key, "", parent_value])
|
130
101
|
|
131
|
-
|
102
|
+
logger.info(f"Parameters exported to CSV file: {filepath}")
|
103
|
+
|
132
104
|
def to_json(self, filepath: str) -> None:
|
133
105
|
"""Export the parameters to a JSON file.
|
134
106
|
|
@@ -138,7 +110,8 @@ class Params:
|
|
138
110
|
with open(filepath, "w") as json_file:
|
139
111
|
json.dump(self.load(), json_file, indent=4)
|
140
112
|
|
141
|
-
|
113
|
+
logger.info(f"Parameters exported to JSON file: {filepath}")
|
114
|
+
|
142
115
|
def to_txt(self, filepath: str) -> None:
|
143
116
|
"""Export the parameters to a text file.
|
144
117
|
|
@@ -155,6 +128,8 @@ class Params:
|
|
155
128
|
# Add a blank line after each entry
|
156
129
|
txt_file.write("\n")
|
157
130
|
|
131
|
+
logger.info(f"Parameters exported to text file: {filepath}")
|
132
|
+
|
158
133
|
def load(self) -> Dict[str, Any]:
|
159
134
|
"""Load and process various parameters, converting any np.ndarray values to lists.
|
160
135
|
|
risk/neighborhoods/domains.py
CHANGED
@@ -101,7 +101,7 @@ def trim_domains_and_top_annotations(
|
|
101
101
|
max_cluster_size (int, optional): Maximum size of a cluster to be retained. Defaults to 1000.
|
102
102
|
|
103
103
|
Returns:
|
104
|
-
Tuple[pd.DataFrame, pd.DataFrame, pd.DataFrame]:
|
104
|
+
Tuple[pd.DataFrame, pd.DataFrame, pd.DataFrame]:
|
105
105
|
- Trimmed annotations (pd.DataFrame)
|
106
106
|
- Trimmed domains (pd.DataFrame)
|
107
107
|
- A DataFrame with domain labels (pd.DataFrame)
|
@@ -177,7 +177,7 @@ def _optimize_silhouette_across_linkage_and_metrics(
|
|
177
177
|
linkage_metric (str): Linkage metric for clustering.
|
178
178
|
|
179
179
|
Returns:
|
180
|
-
Tuple[str, str, float]:
|
180
|
+
Tuple[str, str, float]:
|
181
181
|
- Best linkage method (str)
|
182
182
|
- Best linkage metric (str)
|
183
183
|
- Best threshold (float)
|
@@ -231,7 +231,7 @@ def _find_best_silhouette_score(
|
|
231
231
|
resolution (float, optional): Desired resolution for the best threshold. Defaults to 0.001.
|
232
232
|
|
233
233
|
Returns:
|
234
|
-
Tuple[float, float]:
|
234
|
+
Tuple[float, float]:
|
235
235
|
- Best threshold (float): The threshold that yields the best silhouette score.
|
236
236
|
- Best silhouette score (float): The highest silhouette score achieved.
|
237
237
|
"""
|
@@ -233,7 +233,7 @@ def _impute_neighbors(
|
|
233
233
|
max_depth (int): Maximum depth of nodes to traverse for imputing values.
|
234
234
|
|
235
235
|
Returns:
|
236
|
-
|
236
|
+
Tuple[np.ndarray, np.ndarray, np.ndarray]:
|
237
237
|
- np.ndarray: The imputed significance matrix.
|
238
238
|
- np.ndarray: The imputed alpha threshold matrix.
|
239
239
|
- np.ndarray: The significant significance matrix with non-significant entries set to zero.
|
@@ -269,7 +269,7 @@ def _impute_neighbors_with_similarity(
|
|
269
269
|
max_depth (int): Maximum depth of nodes to traverse for imputing values.
|
270
270
|
|
271
271
|
Returns:
|
272
|
-
Tuple[np.ndarray, np.ndarray]:
|
272
|
+
Tuple[np.ndarray, np.ndarray]:
|
273
273
|
- The imputed significance matrix.
|
274
274
|
- The imputed alpha threshold matrix.
|
275
275
|
"""
|
@@ -397,7 +397,7 @@ def _prune_neighbors(
|
|
397
397
|
distance_threshold (float): Rank threshold (0 to 1) to determine outliers.
|
398
398
|
|
399
399
|
Returns:
|
400
|
-
|
400
|
+
Tuple[np.ndarray, np.ndarray, np.ndarray]:
|
401
401
|
- np.ndarray: The updated significance matrix with outliers set to zero.
|
402
402
|
- np.ndarray: The updated alpha threshold matrix with outliers set to zero.
|
403
403
|
- np.ndarray: The significant significance matrix, where non-significant entries are set to zero.
|
@@ -1,6 +1,6 @@
|
|
1
1
|
"""
|
2
|
-
risk/network/graph
|
3
|
-
|
2
|
+
risk/network/graph/network
|
3
|
+
~~~~~~~~~~~~~~~~~~~~~~~~~~
|
4
4
|
"""
|
5
5
|
|
6
6
|
from collections import defaultdict
|
@@ -10,6 +10,8 @@ import networkx as nx
|
|
10
10
|
import numpy as np
|
11
11
|
import pandas as pd
|
12
12
|
|
13
|
+
from risk.network.graph.summary import AnalysisSummary
|
14
|
+
|
13
15
|
|
14
16
|
class NetworkGraph:
|
15
17
|
"""A class to represent a network graph and process its nodes and edges.
|
@@ -23,6 +25,8 @@ class NetworkGraph:
|
|
23
25
|
def __init__(
|
24
26
|
self,
|
25
27
|
network: nx.Graph,
|
28
|
+
annotations: Dict[str, Any],
|
29
|
+
neighborhoods: Dict[str, Any],
|
26
30
|
top_annotations: pd.DataFrame,
|
27
31
|
domains: pd.DataFrame,
|
28
32
|
trimmed_domains: pd.DataFrame,
|
@@ -33,12 +37,15 @@ class NetworkGraph:
|
|
33
37
|
|
34
38
|
Args:
|
35
39
|
network (nx.Graph): The network graph.
|
40
|
+
annotations (Dict[str, Any]): The annotations associated with the network.
|
41
|
+
neighborhoods (Dict[str, Any]): Neighborhood significance data.
|
36
42
|
top_annotations (pd.DataFrame): DataFrame containing annotations data for the network nodes.
|
37
43
|
domains (pd.DataFrame): DataFrame containing domain data for the network nodes.
|
38
44
|
trimmed_domains (pd.DataFrame): DataFrame containing trimmed domain data for the network nodes.
|
39
45
|
node_label_to_node_id_map (Dict[str, Any]): A dictionary mapping node labels to their corresponding IDs.
|
40
46
|
node_significance_sums (np.ndarray): Array containing the significant sums for the nodes.
|
41
47
|
"""
|
48
|
+
# Initialize self.network downstream of the other attributes
|
42
49
|
self.top_annotations = top_annotations
|
43
50
|
self.domain_id_to_node_ids_map = self._create_domain_id_to_node_ids_map(domains)
|
44
51
|
self.domains = domains
|
@@ -58,12 +65,16 @@ class NetworkGraph:
|
|
58
65
|
zip(node_label_to_node_id_map.keys(), node_significance_sums)
|
59
66
|
)
|
60
67
|
self.node_label_to_node_id_map = node_label_to_node_id_map
|
68
|
+
|
61
69
|
# NOTE: Below this point, instance attributes (i.e., self) will be used!
|
62
70
|
self.domain_id_to_node_labels_map = self._create_domain_id_to_node_labels_map()
|
63
71
|
# Unfold the network's 3D coordinates to 2D and extract node coordinates
|
64
72
|
self.network = _unfold_sphere_to_plane(network)
|
65
73
|
self.node_coordinates = _extract_node_coordinates(self.network)
|
66
74
|
|
75
|
+
# NOTE: Only after the above attributes are initialized, we can create the summary
|
76
|
+
self.summary = AnalysisSummary(annotations, neighborhoods, self)
|
77
|
+
|
67
78
|
@staticmethod
|
68
79
|
def _create_domain_id_to_node_ids_map(domains: pd.DataFrame) -> Dict[int, Any]:
|
69
80
|
"""Create a mapping from domains to the list of node IDs belonging to each domain.
|
@@ -0,0 +1,233 @@
|
|
1
|
+
"""
|
2
|
+
risk/network/graph/summary
|
3
|
+
~~~~~~~~~~~~~~~~~~~~~~~~~~
|
4
|
+
"""
|
5
|
+
|
6
|
+
from typing import Any, Dict, Tuple, Union
|
7
|
+
|
8
|
+
import numpy as np
|
9
|
+
import pandas as pd
|
10
|
+
from statsmodels.stats.multitest import fdrcorrection
|
11
|
+
|
12
|
+
from risk.log.console import logger, log_header
|
13
|
+
|
14
|
+
|
15
|
+
class AnalysisSummary:
|
16
|
+
"""Handles the processing, storage, and export of network analysis results.
|
17
|
+
|
18
|
+
The Results class provides methods to process significance and depletion data, compute
|
19
|
+
FDR-corrected q-values, and structure information on domains and annotations into a
|
20
|
+
DataFrame. It also offers functionality to export the processed data in CSV, JSON,
|
21
|
+
and text formats for analysis and reporting.
|
22
|
+
"""
|
23
|
+
|
24
|
+
def __init__(
|
25
|
+
self,
|
26
|
+
annotations: Dict[str, Any],
|
27
|
+
neighborhoods: Dict[str, Any],
|
28
|
+
graph, # Avoid type hinting NetworkGraph to avoid circular import
|
29
|
+
):
|
30
|
+
"""Initialize the Results object with analysis components.
|
31
|
+
|
32
|
+
Args:
|
33
|
+
annotations (Dict[str, Any]): Annotation data, including ordered annotations and matrix of associations.
|
34
|
+
neighborhoods (Dict[str, Any]): Neighborhood data containing p-values for significance and depletion analysis.
|
35
|
+
graph (NetworkGraph): Graph object representing domain-to-node and node-to-label mappings.
|
36
|
+
"""
|
37
|
+
self.annotations = annotations
|
38
|
+
self.neighborhoods = neighborhoods
|
39
|
+
self.graph = graph
|
40
|
+
|
41
|
+
def to_csv(self, filepath: str) -> None:
|
42
|
+
"""Export significance results to a CSV file.
|
43
|
+
|
44
|
+
Args:
|
45
|
+
filepath (str): The path where the CSV file will be saved.
|
46
|
+
"""
|
47
|
+
# Load results and export directly to CSV
|
48
|
+
results = self.load()
|
49
|
+
results.to_csv(filepath, index=False)
|
50
|
+
logger.info(f"Results summary exported to CSV file: {filepath}")
|
51
|
+
|
52
|
+
def to_json(self, filepath: str) -> None:
|
53
|
+
"""Export significance results to a JSON file.
|
54
|
+
|
55
|
+
Args:
|
56
|
+
filepath (str): The path where the JSON file will be saved.
|
57
|
+
"""
|
58
|
+
# Load results and export directly to JSON
|
59
|
+
results = self.load()
|
60
|
+
results.to_json(filepath, orient="records", indent=4)
|
61
|
+
logger.info(f"Results summary exported to JSON file: {filepath}")
|
62
|
+
|
63
|
+
def to_txt(self, filepath: str) -> None:
|
64
|
+
"""Export significance results to a text file.
|
65
|
+
|
66
|
+
Args:
|
67
|
+
filepath (str): The path where the text file will be saved.
|
68
|
+
"""
|
69
|
+
# Load results and export directly to text file
|
70
|
+
results = self.load()
|
71
|
+
with open(filepath, "w") as txt_file:
|
72
|
+
txt_file.write(results.to_string(index=False))
|
73
|
+
|
74
|
+
logger.info(f"Results summary exported to text file: {filepath}")
|
75
|
+
|
76
|
+
def load(self) -> pd.DataFrame:
|
77
|
+
"""Load and process domain and annotation data into a DataFrame with significance metrics.
|
78
|
+
|
79
|
+
Args:
|
80
|
+
graph (Any): Graph object containing domain-to-node and node-to-label mappings.
|
81
|
+
annotations (Dict[str, Any]): Annotation details, including ordered annotations and matrix.
|
82
|
+
|
83
|
+
Returns:
|
84
|
+
pd.DataFrame: Processed DataFrame containing significance scores, p-values, q-values,
|
85
|
+
and annotation member information.
|
86
|
+
"""
|
87
|
+
log_header("Loading analysis summary")
|
88
|
+
# Calculate significance and depletion q-values from p-value matrices in `annotations`
|
89
|
+
enrichment_pvals = self.neighborhoods["enrichment_pvals"]
|
90
|
+
depletion_pvals = self.neighborhoods["depletion_pvals"]
|
91
|
+
enrichment_qvals = self._calculate_qvalues(enrichment_pvals)
|
92
|
+
depletion_qvals = self._calculate_qvalues(depletion_pvals)
|
93
|
+
|
94
|
+
# Initialize DataFrame with domain and annotation details
|
95
|
+
results = pd.DataFrame(
|
96
|
+
[
|
97
|
+
{"Domain ID": domain_id, "Annotation": desc, "Summed Significance Score": score}
|
98
|
+
for domain_id, info in self.graph.domain_id_to_domain_info_map.items()
|
99
|
+
for desc, score in zip(info["full_descriptions"], info["significance_scores"])
|
100
|
+
]
|
101
|
+
)
|
102
|
+
# Sort by Domain ID and Summed Significance Score
|
103
|
+
results = results.sort_values(
|
104
|
+
by=["Domain ID", "Summed Significance Score"], ascending=[True, False]
|
105
|
+
).reset_index(drop=True)
|
106
|
+
|
107
|
+
# Add minimum p-values and q-values to DataFrame
|
108
|
+
results[
|
109
|
+
[
|
110
|
+
"Enrichment P-value",
|
111
|
+
"Enrichment Q-value",
|
112
|
+
"Depletion P-value",
|
113
|
+
"Depletion Q-value",
|
114
|
+
]
|
115
|
+
] = results.apply(
|
116
|
+
lambda row: self._get_significance_values(
|
117
|
+
row["Domain ID"],
|
118
|
+
row["Annotation"],
|
119
|
+
enrichment_pvals,
|
120
|
+
depletion_pvals,
|
121
|
+
enrichment_qvals,
|
122
|
+
depletion_qvals,
|
123
|
+
),
|
124
|
+
axis=1,
|
125
|
+
result_type="expand",
|
126
|
+
)
|
127
|
+
# Add annotation members and their counts
|
128
|
+
results["Annotation Members in Network"] = results["Annotation"].apply(
|
129
|
+
lambda desc: self._get_annotation_members(desc)
|
130
|
+
)
|
131
|
+
results["Annotation Member in Network Count"] = results[
|
132
|
+
"Annotation Members in Network"
|
133
|
+
].apply(lambda x: len(x.split(";")) if x else 0)
|
134
|
+
|
135
|
+
# Reorder columns and drop rows with NaN values
|
136
|
+
results = (
|
137
|
+
results[
|
138
|
+
[
|
139
|
+
"Domain ID",
|
140
|
+
"Annotation",
|
141
|
+
"Annotation Members in Network",
|
142
|
+
"Annotation Member in Network Count",
|
143
|
+
"Summed Significance Score",
|
144
|
+
"Enrichment P-value",
|
145
|
+
"Enrichment Q-value",
|
146
|
+
"Depletion P-value",
|
147
|
+
"Depletion Q-value",
|
148
|
+
]
|
149
|
+
]
|
150
|
+
.dropna()
|
151
|
+
.reset_index(drop=True)
|
152
|
+
)
|
153
|
+
|
154
|
+
return results
|
155
|
+
|
156
|
+
@staticmethod
|
157
|
+
def _calculate_qvalues(pvals: np.ndarray) -> np.ndarray:
|
158
|
+
"""Calculate q-values (FDR) for each row of a p-value matrix.
|
159
|
+
|
160
|
+
Args:
|
161
|
+
pvals (np.ndarray): 2D array of p-values.
|
162
|
+
|
163
|
+
Returns:
|
164
|
+
np.ndarray: 2D array of q-values, with FDR correction applied row-wise.
|
165
|
+
"""
|
166
|
+
return np.apply_along_axis(lambda row: fdrcorrection(row)[1], 1, pvals)
|
167
|
+
|
168
|
+
def _get_significance_values(
|
169
|
+
self,
|
170
|
+
domain_id: int,
|
171
|
+
description: str,
|
172
|
+
enrichment_pvals: np.ndarray,
|
173
|
+
depletion_pvals: np.ndarray,
|
174
|
+
enrichment_qvals: np.ndarray,
|
175
|
+
depletion_qvals: np.ndarray,
|
176
|
+
) -> Tuple[Union[float, None], Union[float, None], Union[float, None], Union[float, None]]:
|
177
|
+
"""Retrieve the most significant p-values and q-values (FDR) for a given annotation.
|
178
|
+
|
179
|
+
Args:
|
180
|
+
domain_id (int): The domain ID associated with the annotation.
|
181
|
+
description (str): The annotation description.
|
182
|
+
enrichment_pvals (np.ndarray): Matrix of significance p-values.
|
183
|
+
depletion_pvals (np.ndarray): Matrix of depletion p-values.
|
184
|
+
enrichment_qvals (np.ndarray): Matrix of significance q-values.
|
185
|
+
depletion_qvals (np.ndarray): Matrix of depletion q-values.
|
186
|
+
|
187
|
+
Returns:
|
188
|
+
Tuple[Union[float, None], Union[float, None], Union[float, None], Union[float, None]]:
|
189
|
+
Minimum significance p-value, significance q-value, depletion p-value, depletion q-value.
|
190
|
+
"""
|
191
|
+
try:
|
192
|
+
annotation_idx = self.annotations["ordered_annotations"].index(description)
|
193
|
+
except ValueError:
|
194
|
+
return None, None, None, None # Description not found
|
195
|
+
|
196
|
+
node_indices = self.graph.domain_id_to_node_ids_map.get(domain_id, [])
|
197
|
+
if not node_indices:
|
198
|
+
return None, None, None, None # No associated nodes
|
199
|
+
|
200
|
+
sig_p = enrichment_pvals[node_indices, annotation_idx]
|
201
|
+
dep_p = depletion_pvals[node_indices, annotation_idx]
|
202
|
+
sig_q = enrichment_qvals[node_indices, annotation_idx]
|
203
|
+
dep_q = depletion_qvals[node_indices, annotation_idx]
|
204
|
+
|
205
|
+
return (
|
206
|
+
np.min(sig_p) if sig_p.size > 0 else None,
|
207
|
+
np.min(sig_q) if sig_q.size > 0 else None,
|
208
|
+
np.min(dep_p) if dep_p.size > 0 else None,
|
209
|
+
np.min(dep_q) if dep_q.size > 0 else None,
|
210
|
+
)
|
211
|
+
|
212
|
+
def _get_annotation_members(self, description: str) -> str:
|
213
|
+
"""Retrieve node labels associated with a given annotation description.
|
214
|
+
|
215
|
+
Args:
|
216
|
+
description (str): The annotation description.
|
217
|
+
|
218
|
+
Returns:
|
219
|
+
str: ';'-separated string of node labels that are associated with the annotation.
|
220
|
+
"""
|
221
|
+
try:
|
222
|
+
annotation_idx = self.annotations["ordered_annotations"].index(description)
|
223
|
+
except ValueError:
|
224
|
+
return "" # Description not found
|
225
|
+
|
226
|
+
# Get nodes present for the annotation and sort by node label
|
227
|
+
nodes_present = np.where(self.annotations["matrix"][:, annotation_idx] == 1)[0]
|
228
|
+
node_labels = sorted(
|
229
|
+
self.graph.node_id_to_node_label_map[node_id]
|
230
|
+
for node_id in nodes_present
|
231
|
+
if node_id in self.graph.node_id_to_node_label_map
|
232
|
+
)
|
233
|
+
return ";".join(node_labels)
|
risk/network/io.py
CHANGED
@@ -165,12 +165,12 @@ class NetworkIO:
|
|
165
165
|
filepath: str,
|
166
166
|
source_label: str = "source",
|
167
167
|
target_label: str = "target",
|
168
|
+
view_name: str = "",
|
168
169
|
compute_sphere: bool = True,
|
169
170
|
surface_depth: float = 0.0,
|
170
171
|
min_edges_per_node: int = 0,
|
171
172
|
include_edge_weight: bool = True,
|
172
173
|
weight_label: str = "weight",
|
173
|
-
view_name: str = "",
|
174
174
|
) -> nx.Graph:
|
175
175
|
"""Load a network from a Cytoscape file.
|
176
176
|
|
@@ -178,7 +178,7 @@ class NetworkIO:
|
|
178
178
|
filepath (str): Path to the Cytoscape file.
|
179
179
|
source_label (str, optional): Source node label. Defaults to "source".
|
180
180
|
target_label (str, optional): Target node label. Defaults to "target".
|
181
|
-
view_name (str, optional): Specific view name to load. Defaults to
|
181
|
+
view_name (str, optional): Specific view name to load. Defaults to "".
|
182
182
|
compute_sphere (bool, optional): Whether to map nodes to a sphere. Defaults to True.
|
183
183
|
surface_depth (float, optional): Surface depth for the sphere. Defaults to 0.0.
|
184
184
|
min_edges_per_node (int, optional): Minimum number of edges per node. Defaults to 0.
|
@@ -215,7 +215,7 @@ class NetworkIO:
|
|
215
215
|
filepath (str): Path to the Cytoscape file.
|
216
216
|
source_label (str, optional): Source node label. Defaults to "source".
|
217
217
|
target_label (str, optional): Target node label. Defaults to "target".
|
218
|
-
view_name (str, optional): Specific view name to load. Defaults to
|
218
|
+
view_name (str, optional): Specific view name to load. Defaults to "".
|
219
219
|
|
220
220
|
Returns:
|
221
221
|
nx.Graph: Loaded and processed network.
|
risk/risk.py
CHANGED
@@ -42,19 +42,10 @@ class RISK(NetworkIO, AnnotationsIO):
|
|
42
42
|
"""
|
43
43
|
# Set global verbosity for logging
|
44
44
|
set_global_verbosity(verbose)
|
45
|
-
#
|
46
|
-
params
|
45
|
+
# Provide public access to the logged network parameters
|
46
|
+
self.params = params
|
47
47
|
super().__init__()
|
48
48
|
|
49
|
-
@property
|
50
|
-
def params(self) -> params:
|
51
|
-
"""Access the logged network parameters.
|
52
|
-
|
53
|
-
Returns:
|
54
|
-
Params: An instance of the Params class with logged parameters and methods to access or update them.
|
55
|
-
"""
|
56
|
-
return params
|
57
|
-
|
58
49
|
def load_neighborhoods_by_hypergeom(
|
59
50
|
self,
|
60
51
|
network: nx.Graph,
|
@@ -274,7 +265,7 @@ class RISK(NetworkIO, AnnotationsIO):
|
|
274
265
|
|
275
266
|
Args:
|
276
267
|
network (nx.Graph): The network graph.
|
277
|
-
annotations (
|
268
|
+
annotations (Dict[str, Any]): The annotations associated with the network.
|
278
269
|
neighborhoods (Dict[str, Any]): Neighborhood significance data.
|
279
270
|
tail (str, optional): Type of significance tail ("right", "left", "both"). Defaults to "right".
|
280
271
|
pval_cutoff (float, optional): p-value cutoff for significance. Defaults to 0.01.
|
@@ -368,6 +359,8 @@ class RISK(NetworkIO, AnnotationsIO):
|
|
368
359
|
# Return the fully initialized NetworkGraph object
|
369
360
|
return NetworkGraph(
|
370
361
|
network=network,
|
362
|
+
annotations=annotations,
|
363
|
+
neighborhoods=neighborhoods,
|
371
364
|
top_annotations=top_annotations,
|
372
365
|
domains=domains,
|
373
366
|
trimmed_domains=trimmed_domains,
|
@@ -1,21 +1,22 @@
|
|
1
|
-
risk/__init__.py,sha256=
|
1
|
+
risk/__init__.py,sha256=japxenqMvqgfrLH-PHOulkDBiW_CZRMVUaDbR92setc,112
|
2
2
|
risk/constants.py,sha256=XInRaH78Slnw_sWgAsBFbUHkyA0h0jL0DKGuQNbOvjM,550
|
3
|
-
risk/risk.py,sha256=
|
3
|
+
risk/risk.py,sha256=De1vn8Xc-TKz6aTL0bvJI-SVrIqU3k0IWAbKc7dde1c,23618
|
4
4
|
risk/annotations/__init__.py,sha256=kXgadEXaCh0z8OyhOhTj7c3qXGmWgOhaSZ4gSzSb59U,147
|
5
5
|
risk/annotations/annotations.py,sha256=m3WeCdE1a2undpSl_Q2I17drD95r2McKtpzhiiSdxHY,13143
|
6
|
-
risk/annotations/io.py,sha256=
|
7
|
-
risk/log/__init__.py,sha256=
|
6
|
+
risk/annotations/io.py,sha256=eOkPD9G6KzkhGRc_ZW2McxQ8665o-H3uDG8bmKlzQ80,9591
|
7
|
+
risk/log/__init__.py,sha256=gy7C5L6D222AYUChq5lkc0LsCJ_QMQPaFiBJKbecdac,201
|
8
8
|
risk/log/console.py,sha256=C52s3FgQ2e9kQWcXL8m7rs_pnKXt5Yy8PBHmQkOTiNo,4537
|
9
|
-
risk/log/
|
10
|
-
risk/log/params.py,sha256=qSTktJ3OazldTzgtDGZkh0s30vu5kiXPkiNGLdSFDvg,6416
|
9
|
+
risk/log/parameters.py,sha256=o4StqYCa0kt7_Ht4mKa1DwwvhGUwkC_dGBaiUIc0GB0,5683
|
11
10
|
risk/neighborhoods/__init__.py,sha256=tKKEg4lsbqFukpgYlUGxU_v_9FOqK7V0uvM9T2QzoL0,206
|
12
11
|
risk/neighborhoods/community.py,sha256=MAgIblbuisEPwVU6mFZd4Yd9NUKlaHK99suw51r1Is0,7065
|
13
|
-
risk/neighborhoods/domains.py,sha256=
|
14
|
-
risk/neighborhoods/neighborhoods.py,sha256=
|
12
|
+
risk/neighborhoods/domains.py,sha256=cMp2McuaSxRp7lQvzjgZnlt5dzxwyj6HAWKyT9u2sng,11662
|
13
|
+
risk/neighborhoods/neighborhoods.py,sha256=0TAP-xi4hgtnrK0cKQPHQHq9IVGHOMF1wYEcx6tsxRA,22241
|
15
14
|
risk/network/__init__.py,sha256=iEPeJdZfqp0toxtbElryB8jbz9_t_k4QQ3iDvKE8C_0,126
|
16
15
|
risk/network/geometry.py,sha256=gFtYUj9j9aul4paKq_qSGJn39Nazxu_MXv8m-tYYtrk,6840
|
17
|
-
risk/network/
|
18
|
-
risk/network/
|
16
|
+
risk/network/io.py,sha256=AWSbZGLZHtl72KSlafQlcYoG00YLSznG7UYDi_wDT7M,22958
|
17
|
+
risk/network/graph/__init__.py,sha256=H0YEiwqZ02LBTkH4blPwUjQ-DOUnhaTTNHM0BcXii6U,81
|
18
|
+
risk/network/graph/network.py,sha256=o7Rdp2S8cxYiT90IvGLqsn93wq9YA1vKRZ7fedLUir0,10208
|
19
|
+
risk/network/graph/summary.py,sha256=f4j-ERlddzAhd9qEELiGdzmPqpzgoRODyHNe9QuRT7k,9190
|
19
20
|
risk/network/plot/__init__.py,sha256=MfmaXJgAZJgXZ2wrhK8pXwzETlcMaLChhWXKAozniAo,98
|
20
21
|
risk/network/plot/canvas.py,sha256=TlCpNtvoceizAumNr9I02JcBrBO6FiAFAa2ZC0bx3SU,13356
|
21
22
|
risk/network/plot/contour.py,sha256=2ZVOlduo4Y4yIpXDJMIKO-v7eULcJ2QacQyOc7pUAxE,15267
|
@@ -31,8 +32,8 @@ risk/stats/stats.py,sha256=z8NrhiVj4BzJ250bVLfytpmfC7RzYu7mBuIZD_l0aCA,7222
|
|
31
32
|
risk/stats/permutation/__init__.py,sha256=neJp7FENC-zg_CGOXqv-iIvz1r5XUKI9Ruxhmq7kDOI,105
|
32
33
|
risk/stats/permutation/permutation.py,sha256=meBNSrbRa9P8WJ54n485l0H7VQJlMSfHqdN4aCKYCtQ,10105
|
33
34
|
risk/stats/permutation/test_functions.py,sha256=lftOude6hee0pyR80HlBD32522JkDoN5hrKQ9VEbuoY,2345
|
34
|
-
risk_network-0.0.
|
35
|
-
risk_network-0.0.
|
36
|
-
risk_network-0.0.
|
37
|
-
risk_network-0.0.
|
38
|
-
risk_network-0.0.
|
35
|
+
risk_network-0.0.9b3.dist-info/LICENSE,sha256=jOtLnuWt7d5Hsx6XXB2QxzrSe2sWWh3NgMfFRetluQM,35147
|
36
|
+
risk_network-0.0.9b3.dist-info/METADATA,sha256=nUhDrkDb3ZbsCcKRxKOgx6yL6t1FHK4SRbrQNjdktII,47497
|
37
|
+
risk_network-0.0.9b3.dist-info/WHEEL,sha256=P9jw-gEje8ByB7_hXoICnHtVCrEwMQh-630tKvQWehc,91
|
38
|
+
risk_network-0.0.9b3.dist-info/top_level.txt,sha256=NX7C2PFKTvC1JhVKv14DFlFAIFnKc6Lpsu1ZfxvQwVw,5
|
39
|
+
risk_network-0.0.9b3.dist-info/RECORD,,
|
risk/log/enrichment.py
DELETED
@@ -1,18 +0,0 @@
|
|
1
|
-
"""
|
2
|
-
risk/log/enrichment
|
3
|
-
~~~~~~~~~~~~~~~~~~~
|
4
|
-
"""
|
5
|
-
|
6
|
-
import csv
|
7
|
-
import json
|
8
|
-
import warnings
|
9
|
-
from datetime import datetime
|
10
|
-
from functools import wraps
|
11
|
-
from typing import Any, Dict
|
12
|
-
|
13
|
-
import numpy as np
|
14
|
-
|
15
|
-
from .console import logger, log_header
|
16
|
-
|
17
|
-
# Suppress all warnings - this is to resolve warnings from multiprocessing
|
18
|
-
warnings.filterwarnings("ignore")
|
File without changes
|
File without changes
|
File without changes
|