pflex 1.0__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.
- pflex/__init__.py +44 -0
- pflex/analysis.py +1647 -0
- pflex/data/__init__.py +0 -0
- pflex/data/dataset/__init__.py +0 -0
- pflex/data/dataset/liver_cell_lines_500_genes.csv +501 -0
- pflex/data/dataset/melanoma_cell_lines_500_genes.csv +501 -0
- pflex/data/dataset/neuroblastoma_cell_lines_500_genes.csv +501 -0
- pflex/data/gold_standard/CORUM.parquet +0 -0
- pflex/data/gold_standard/GOBP.parquet +0 -0
- pflex/data/gold_standard/PATHWAY.parquet +0 -0
- pflex/data/gold_standard/__init__.py +0 -0
- pflex/data/gold_standard/corum.csv +2917 -0
- pflex/data/gold_standard/gobp.csv +4829 -0
- pflex/data/gold_standard/pathway.csv +1330 -0
- pflex/examples/basic_usage.py +95 -0
- pflex/logging_config.py +56 -0
- pflex/old_functions.py +422 -0
- pflex/plotting.py +2234 -0
- pflex/preprocessing.py +290 -0
- pflex/utils.py +128 -0
- pflex-1.0.dist-info/METADATA +167 -0
- pflex-1.0.dist-info/RECORD +25 -0
- pflex-1.0.dist-info/WHEEL +4 -0
- pflex-1.0.dist-info/entry_points.txt +2 -0
- pflex-1.0.dist-info/licenses/LICENSE +7 -0
pflex/preprocessing.py
ADDED
|
@@ -0,0 +1,290 @@
|
|
|
1
|
+
import os
|
|
2
|
+
import pandas as pd
|
|
3
|
+
import numpy as np
|
|
4
|
+
from .utils import dsave, dload, normalize_analysis_genes
|
|
5
|
+
from tqdm import tqdm
|
|
6
|
+
from .logging_config import log
|
|
7
|
+
tqdm.pandas()
|
|
8
|
+
# Locate package data path once at module level
|
|
9
|
+
from importlib.metadata import distribution
|
|
10
|
+
from importlib.resources import files
|
|
11
|
+
import json
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def return_package_dir():
|
|
16
|
+
try:
|
|
17
|
+
# Get the distribution
|
|
18
|
+
dist = distribution('pflex')
|
|
19
|
+
|
|
20
|
+
# Check for direct_url.json
|
|
21
|
+
try:
|
|
22
|
+
direct_url_text = dist.read_text('direct_url.json')
|
|
23
|
+
except FileNotFoundError:
|
|
24
|
+
direct_url_text = None
|
|
25
|
+
|
|
26
|
+
if direct_url_text:
|
|
27
|
+
direct_url = json.loads(direct_url_text)
|
|
28
|
+
if direct_url.get('dir_info', {}).get('editable'):
|
|
29
|
+
# Editable install detected
|
|
30
|
+
project_url = direct_url['url']
|
|
31
|
+
# Remove 'file:///' prefix and handle Windows paths
|
|
32
|
+
project_root = project_url.removeprefix('file:///').replace('/', os.sep)
|
|
33
|
+
# Assuming src layout: project_root/src/pflex
|
|
34
|
+
package_dir = os.path.join(project_root, 'src', 'pflex')
|
|
35
|
+
else:
|
|
36
|
+
# Non-editable
|
|
37
|
+
package_dir = str(files('pflex'))
|
|
38
|
+
else:
|
|
39
|
+
# No direct_url, assume non-editable
|
|
40
|
+
package_dir = str(files('pflex'))
|
|
41
|
+
|
|
42
|
+
except Exception: # PackageNotFoundError or other issues
|
|
43
|
+
# Fallback to local directory relative to this file
|
|
44
|
+
# precise location: src/pflex/preprocessing.py -> package dir is parent
|
|
45
|
+
package_dir = str(Path(__file__).parent)
|
|
46
|
+
|
|
47
|
+
return package_dir
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def get_example_data_path(filename: str):
|
|
52
|
+
return files("pflex.data").joinpath("dataset").joinpath(filename)
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def _load_file(filepath, ext):
|
|
56
|
+
loaders = {
|
|
57
|
+
".csv": lambda f: pd.read_csv(f, index_col=0),
|
|
58
|
+
".xlsx": lambda f: pd.read_excel(f, index_col=0),
|
|
59
|
+
".parquet": pd.read_parquet,
|
|
60
|
+
".p": pd.read_parquet
|
|
61
|
+
}
|
|
62
|
+
if ext not in loaders:
|
|
63
|
+
raise ValueError(f"Unsupported file extension: {ext}")
|
|
64
|
+
|
|
65
|
+
return loaders[ext](filepath)
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def load_datasets(files, continue_with_common_genes=False):
|
|
69
|
+
config = dload("config")
|
|
70
|
+
preprocessing = config["preprocessing"]
|
|
71
|
+
analysis_genes_raw = config.get("analysis_genes", "")
|
|
72
|
+
analysis_genes_missing = (
|
|
73
|
+
analysis_genes_raw is None or str(analysis_genes_raw).strip() == ""
|
|
74
|
+
)
|
|
75
|
+
analysis_genes = normalize_analysis_genes(
|
|
76
|
+
analysis_genes_raw,
|
|
77
|
+
legacy_use_common_genes=(
|
|
78
|
+
config.get("use_common_genes") if analysis_genes_missing else None
|
|
79
|
+
),
|
|
80
|
+
)
|
|
81
|
+
data_dict= {}
|
|
82
|
+
|
|
83
|
+
for filename, meta in files.items():
|
|
84
|
+
if isinstance(meta, pd.DataFrame):
|
|
85
|
+
df = meta
|
|
86
|
+
elif isinstance(meta, dict):
|
|
87
|
+
filepath = meta["path"]
|
|
88
|
+
if isinstance(filepath, pd.DataFrame):
|
|
89
|
+
df = filepath
|
|
90
|
+
else:
|
|
91
|
+
ext = os.path.splitext(filepath)[1]
|
|
92
|
+
df = _load_file(filepath, ext)
|
|
93
|
+
else:
|
|
94
|
+
raise ValueError(f"Unsupported data structure for '{filename}': {type(meta)}")
|
|
95
|
+
|
|
96
|
+
df.index = df.index.str.split().str[0]
|
|
97
|
+
if preprocessing.get('normalize'):
|
|
98
|
+
log.info(f"{filename}: Normalization.")
|
|
99
|
+
df = (df - df.mean()) / df.std(ddof=0)
|
|
100
|
+
|
|
101
|
+
if preprocessing.get('drop_na'):
|
|
102
|
+
log.info(f"{filename}: Dropping missing values.")
|
|
103
|
+
df = df.dropna(how="any")
|
|
104
|
+
|
|
105
|
+
if preprocessing.get('fill_na'):
|
|
106
|
+
log.info(f"{filename}: Filling missing values with column mean.")
|
|
107
|
+
#df = df.T.fillna(df.mean(axis=1)).T
|
|
108
|
+
df = data_imputation(df)
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
data_dict[filename] = df
|
|
112
|
+
|
|
113
|
+
common_genes = get_common_genes(data_dict)
|
|
114
|
+
|
|
115
|
+
# Apply common gene filtering only when analysis_genes='shared' (or forced by arg)
|
|
116
|
+
if analysis_genes == "shared" or continue_with_common_genes:
|
|
117
|
+
log.info(f"Applying common gene filtering: {len(common_genes)} genes")
|
|
118
|
+
for filename, df in data_dict.items():
|
|
119
|
+
if df.index.isin(common_genes).any():
|
|
120
|
+
data_dict[filename] = df.loc[common_genes]
|
|
121
|
+
else:
|
|
122
|
+
log.info(
|
|
123
|
+
f"Skipping common gene filtering (analysis_genes='dataset_specific'). Common genes found: {len(common_genes)}"
|
|
124
|
+
)
|
|
125
|
+
|
|
126
|
+
dsave({
|
|
127
|
+
"datasets": data_dict,
|
|
128
|
+
"sorting": {
|
|
129
|
+
k: v.get("sort", "high") if isinstance(v, dict) else "high"
|
|
130
|
+
for k, v in files.items()
|
|
131
|
+
},
|
|
132
|
+
"colors": {
|
|
133
|
+
k: v.get("color", None) if isinstance(v, dict) else None
|
|
134
|
+
for k, v in files.items()
|
|
135
|
+
}
|
|
136
|
+
}, "input")
|
|
137
|
+
log.done(f"Datasets loaded.")
|
|
138
|
+
return data_dict , common_genes
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def drop_bad_samples(df, max_na=0.1):
|
|
144
|
+
total_elements = df.shape[0] * df.shape[1]
|
|
145
|
+
percent_nan = np.isnan(df.values).sum() / total_elements if total_elements > 0 else 0
|
|
146
|
+
has_nan_per_sample = np.isnan(df.values).any(axis=0) # how many samples has NA.
|
|
147
|
+
|
|
148
|
+
log.info(f"Total: {total_elements}, Percent NaN: {percent_nan:.2%}, Samples with NaN: {np.sum(has_nan_per_sample)} / {df.shape[1]}")
|
|
149
|
+
|
|
150
|
+
num_genes = df.shape[0] # E.g., 1178 (total rows/genes)
|
|
151
|
+
na_per_sample = np.isnan(df.values).sum(axis=0) / num_genes # Fraction NA per sample (column)
|
|
152
|
+
good_samples = na_per_sample <= max_na # Keep if <=10% NA
|
|
153
|
+
data_filtered = df.loc[:, good_samples] # Drop bad samples (those >10% NA)
|
|
154
|
+
|
|
155
|
+
log.info(f"Filtered samples: {data_filtered.shape[1]} (removed {df.shape[1] - data_filtered.shape[1]} samples with >{max_na*100:.0f}% NAs)")
|
|
156
|
+
return data_filtered
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
def data_imputation(df):
|
|
161
|
+
log.info("Imputing missing values with gene means ...")
|
|
162
|
+
gene_means = np.nanmean(df.values, axis=1) # 1D array: means per gene
|
|
163
|
+
data_values = df.values.copy()
|
|
164
|
+
rows, cols = np.where(np.isnan(data_values))
|
|
165
|
+
if len(rows) > 0:
|
|
166
|
+
data_values[rows, cols] = np.take(gene_means, rows)
|
|
167
|
+
|
|
168
|
+
df = pd.DataFrame(data_values, index=df.index, columns=df.columns)
|
|
169
|
+
log.info(f"Data after imputation: {df.shape[0]} genes, {df.shape[1]} samples")
|
|
170
|
+
return df
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
def get_common_genes(datasets):
|
|
176
|
+
log.started("Finding common genes across datasets.")
|
|
177
|
+
gene_sets = [set(df.index) for df in datasets.values()]
|
|
178
|
+
common_genes = set.intersection(*gene_sets)
|
|
179
|
+
log.done(f"Common genes found: {len(common_genes)}")
|
|
180
|
+
dsave(common_genes, "common", "common_genes")
|
|
181
|
+
return list(common_genes)
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
def filter_matrix_by_genes(matrix, genes_present_in_terms):
|
|
185
|
+
log.started("Filtering matrix using genes present in terms.")
|
|
186
|
+
genes = matrix.index.intersection(genes_present_in_terms)
|
|
187
|
+
matrix = matrix.loc[genes, genes]
|
|
188
|
+
log.done(f"Filtering matrix: {matrix.shape}")
|
|
189
|
+
return matrix
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
def load_gold_standard():
|
|
195
|
+
|
|
196
|
+
package_dir = return_package_dir()
|
|
197
|
+
data_dir_path = os.path.join(package_dir, 'data')
|
|
198
|
+
|
|
199
|
+
config = dload("config")
|
|
200
|
+
analysis_genes_raw = config.get("analysis_genes", "")
|
|
201
|
+
analysis_genes_missing = (
|
|
202
|
+
analysis_genes_raw is None or str(analysis_genes_raw).strip() == ""
|
|
203
|
+
)
|
|
204
|
+
analysis_genes = normalize_analysis_genes(
|
|
205
|
+
analysis_genes_raw,
|
|
206
|
+
legacy_use_common_genes=(
|
|
207
|
+
config.get("use_common_genes") if analysis_genes_missing else None
|
|
208
|
+
),
|
|
209
|
+
)
|
|
210
|
+
|
|
211
|
+
gold_standard_source = config['gold_standard']
|
|
212
|
+
jaccard_enabled = bool(config.get("jaccard", False))
|
|
213
|
+
log.done(
|
|
214
|
+
f"Loading gold standard: {gold_standard_source}, Min complex size: {config['min_genes_in_complex']}, "
|
|
215
|
+
f"Jaccard filtering: {jaccard_enabled} (exact duplicate used_genes after dataset filtering), "
|
|
216
|
+
f"analysis_genes: {analysis_genes}"
|
|
217
|
+
)
|
|
218
|
+
|
|
219
|
+
# Define gold standard file paths for predefined sources
|
|
220
|
+
gold_standard_files = {
|
|
221
|
+
"CORUM": "gold_standard/CORUM.parquet",
|
|
222
|
+
"GOBP": "gold_standard/GOBP.parquet",
|
|
223
|
+
"PATHWAY": "gold_standard/PATHWAY.parquet"
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
if gold_standard_source in gold_standard_files:
|
|
227
|
+
# Load predefined gold standard from package resources
|
|
228
|
+
filename = gold_standard_files[gold_standard_source]
|
|
229
|
+
filename_path = Path(data_dir_path).joinpath(filename)
|
|
230
|
+
if not filename_path.exists(): # Check if the file exists
|
|
231
|
+
raise ValueError(f"Invalid Gold Standard type: {gold_standard_source}. File not found.")
|
|
232
|
+
terms = pd.read_parquet(filename_path) # type: ignore
|
|
233
|
+
elif Path(gold_standard_source).suffix.lower() == '.csv':
|
|
234
|
+
# Load user-provided custom gold standard from CSV file
|
|
235
|
+
filename_path = Path(gold_standard_source)
|
|
236
|
+
if not filename_path.exists():
|
|
237
|
+
raise ValueError(f"Custom gold standard CSV file not found: {gold_standard_source}")
|
|
238
|
+
log.done(f"Loading custom gold standard from CSV: {gold_standard_source}")
|
|
239
|
+
terms = pd.read_csv(filename_path)
|
|
240
|
+
else:
|
|
241
|
+
raise ValueError(f"Invalid gold standard source: {gold_standard_source}. Must be one of {list(gold_standard_files.keys())} or a path to a .csv file.")
|
|
242
|
+
|
|
243
|
+
# Store raw gold standard for later per-dataset filtering
|
|
244
|
+
terms["all_genes"] = terms["Genes"].apply(lambda x: list(set(x.split(";"))))
|
|
245
|
+
log.done(f"Gold standard loaded with {len(terms)} terms")
|
|
246
|
+
|
|
247
|
+
# Basic filtering by minimum complex size (before gene filtering)
|
|
248
|
+
terms["n_all_genes"] = terms["all_genes"].apply(len)
|
|
249
|
+
terms = terms[terms["n_all_genes"] >= config['min_genes_in_complex']]
|
|
250
|
+
log.done(f"After min_genes_in_complex filtering: {len(terms)} terms")
|
|
251
|
+
|
|
252
|
+
# if there is column called "ID", set it as index
|
|
253
|
+
if "ID" in terms.columns:
|
|
254
|
+
terms = terms.set_index("ID")
|
|
255
|
+
|
|
256
|
+
dsave(terms, "common", "terms")
|
|
257
|
+
log.done("Gold standard loading completed.")
|
|
258
|
+
return terms, None # Return None for genes_present_in_terms - will be computed per dataset
|
|
259
|
+
|
|
260
|
+
|
|
261
|
+
|
|
262
|
+
|
|
263
|
+
|
|
264
|
+
def filter_duplicate_terms(terms: pd.DataFrame) -> pd.DataFrame:
|
|
265
|
+
"""Backward-compatible wrapper for exact-duplicate filtering.
|
|
266
|
+
|
|
267
|
+
This removes exact duplicate `used_genes` sets and keeps the smallest ID.
|
|
268
|
+
"""
|
|
269
|
+
log.started("Filtering duplicate terms using exact used_genes sets.")
|
|
270
|
+
before = len(terms)
|
|
271
|
+
terms = terms.copy()
|
|
272
|
+
terms["gene_set"] = terms["used_genes"].map(lambda x: frozenset(x))
|
|
273
|
+
grouped = terms.groupby("gene_set", sort=False)
|
|
274
|
+
|
|
275
|
+
id_values = terms["ID"] if "ID" in terms.columns else terms.index
|
|
276
|
+
keep_ids = set(id_values)
|
|
277
|
+
for _, group in grouped:
|
|
278
|
+
if len(group) <= 1:
|
|
279
|
+
continue
|
|
280
|
+
cluster = group["ID"].values if "ID" in group.columns else group.index.values
|
|
281
|
+
sorted_ids = sorted(cluster)
|
|
282
|
+
keep_ids.difference_update(sorted_ids[1:])
|
|
283
|
+
|
|
284
|
+
if "ID" in terms.columns:
|
|
285
|
+
filtered = terms[terms["ID"].isin(keep_ids)].copy()
|
|
286
|
+
else:
|
|
287
|
+
filtered = terms[terms.index.isin(keep_ids)].copy()
|
|
288
|
+
filtered.drop(columns=["gene_set"], inplace=True, errors="ignore")
|
|
289
|
+
log.done(f"{before - len(filtered)} terms removed due to identical gene sets.")
|
|
290
|
+
return filtered
|
pflex/utils.py
ADDED
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
import os
|
|
2
|
+
import re
|
|
3
|
+
import tempfile
|
|
4
|
+
import joblib
|
|
5
|
+
import numpy as np
|
|
6
|
+
import pandas as pd
|
|
7
|
+
|
|
8
|
+
from .logging_config import log
|
|
9
|
+
|
|
10
|
+
# Constants
|
|
11
|
+
TMP_ROOT = ".tmp"
|
|
12
|
+
VALID_EXTS = {".parquet", ".npy", ".pkl"} # Removed .feather
|
|
13
|
+
|
|
14
|
+
ANALYSIS_GENES_ALIASES = {
|
|
15
|
+
"shared": "shared",
|
|
16
|
+
"common": "shared",
|
|
17
|
+
"dataset_specific": "dataset_specific",
|
|
18
|
+
"dataset": "dataset_specific",
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def normalize_analysis_genes(value=None, legacy_use_common_genes=None):
|
|
23
|
+
"""Normalize analysis_genes config values while keeping legacy names working."""
|
|
24
|
+
if value is None or str(value).strip() == "":
|
|
25
|
+
if legacy_use_common_genes is not None:
|
|
26
|
+
return "shared" if bool(legacy_use_common_genes) else "dataset_specific"
|
|
27
|
+
value = "shared"
|
|
28
|
+
|
|
29
|
+
key = str(value).strip().lower().replace("-", "_").replace(" ", "_")
|
|
30
|
+
if key not in ANALYSIS_GENES_ALIASES:
|
|
31
|
+
raise ValueError(
|
|
32
|
+
"config['analysis_genes'] must be one of "
|
|
33
|
+
"['shared', 'dataset_specific'] "
|
|
34
|
+
"(legacy aliases ['common', 'dataset'] are also supported), "
|
|
35
|
+
f"got {value!r}"
|
|
36
|
+
)
|
|
37
|
+
return ANALYSIS_GENES_ALIASES[key]
|
|
38
|
+
|
|
39
|
+
# Helper to sanitize names (make filesystem-safe)
|
|
40
|
+
def _sanitize(name):
|
|
41
|
+
if not name:
|
|
42
|
+
return "data"
|
|
43
|
+
# Replace forbidden/problematic chars with '_', collapse multiples, strip edges
|
|
44
|
+
safe = re.sub(r'[<>:"/\\|?*$,\s]+', '_', str(name).strip())
|
|
45
|
+
safe = re.sub(r'_+', '_', safe).strip('_')
|
|
46
|
+
return safe if safe else "data"
|
|
47
|
+
|
|
48
|
+
# Helper to get safe path
|
|
49
|
+
def _safe_path(category, name=None, ext=".pkl"):
|
|
50
|
+
safe_category = _sanitize(category)
|
|
51
|
+
dir_path = os.path.join(TMP_ROOT, safe_category)
|
|
52
|
+
os.makedirs(dir_path, exist_ok=True)
|
|
53
|
+
safe_name = _sanitize(name) if name else "data"
|
|
54
|
+
return os.path.join(dir_path, f"{safe_name}{ext}")
|
|
55
|
+
|
|
56
|
+
# Save function - Parquet for DataFrames
|
|
57
|
+
def dsave(data, category, name=None, path=None):
|
|
58
|
+
# If data is dict and no name, recurse on each item
|
|
59
|
+
if name is None and isinstance(data, dict):
|
|
60
|
+
for k, v in data.items():
|
|
61
|
+
dsave(v, category, k)
|
|
62
|
+
return
|
|
63
|
+
|
|
64
|
+
# Choose format based on type
|
|
65
|
+
if isinstance(data, pd.DataFrame):
|
|
66
|
+
ext = ".parquet"
|
|
67
|
+
save_func = lambda p: data.to_parquet(p)
|
|
68
|
+
elif isinstance(data, np.ndarray):
|
|
69
|
+
ext = ".npy"
|
|
70
|
+
save_func = lambda p: np.save(p, data, allow_pickle=False)
|
|
71
|
+
else:
|
|
72
|
+
ext = ".pkl"
|
|
73
|
+
save_func = lambda p: joblib.dump(data, p, compress=0)
|
|
74
|
+
|
|
75
|
+
target = _safe_path(category, name, ext)
|
|
76
|
+
|
|
77
|
+
# Atomic save: Write to temp file, then rename
|
|
78
|
+
with tempfile.NamedTemporaryFile(dir=os.path.dirname(target), delete=False, suffix=ext) as tf:
|
|
79
|
+
tmp_path = tf.name
|
|
80
|
+
tf.close()
|
|
81
|
+
save_func(tmp_path)
|
|
82
|
+
os.replace(tmp_path, target)
|
|
83
|
+
|
|
84
|
+
# Load function - Parquet for DataFrames
|
|
85
|
+
def dload(category, name=None, path=None):
|
|
86
|
+
dir_path = os.path.join(TMP_ROOT, _sanitize(category))
|
|
87
|
+
|
|
88
|
+
if not os.path.exists(dir_path):
|
|
89
|
+
return {} if name is None else None
|
|
90
|
+
|
|
91
|
+
if name is None:
|
|
92
|
+
# Load all in category as dict
|
|
93
|
+
out = {}
|
|
94
|
+
for filename in os.listdir(dir_path):
|
|
95
|
+
if not any(filename.endswith(ext) for ext in VALID_EXTS):
|
|
96
|
+
continue
|
|
97
|
+
k = os.path.splitext(filename)[0]
|
|
98
|
+
full_path = os.path.join(dir_path, filename)
|
|
99
|
+
try:
|
|
100
|
+
if filename.endswith(".parquet"):
|
|
101
|
+
out[k] = pd.read_parquet(full_path)
|
|
102
|
+
elif filename.endswith(".npy"):
|
|
103
|
+
out[k] = np.load(full_path, mmap_mode="r")
|
|
104
|
+
elif filename.endswith(".pkl"):
|
|
105
|
+
out[k] = joblib.load(full_path, mmap_mode="r")
|
|
106
|
+
except (EOFError, ValueError, OSError):
|
|
107
|
+
log.warning(f"'{full_path}' is corrupted. Skipping...")
|
|
108
|
+
os.remove(full_path)
|
|
109
|
+
return out
|
|
110
|
+
|
|
111
|
+
# Load specific name - try extensions in order
|
|
112
|
+
for ext in VALID_EXTS:
|
|
113
|
+
target = _safe_path(category, name, ext)
|
|
114
|
+
if os.path.exists(target):
|
|
115
|
+
try:
|
|
116
|
+
if ext == ".parquet":
|
|
117
|
+
return pd.read_parquet(target)
|
|
118
|
+
elif ext == ".npy":
|
|
119
|
+
return np.load(target, mmap_mode="r")
|
|
120
|
+
elif ext == ".pkl":
|
|
121
|
+
return joblib.load(target, mmap_mode="r")
|
|
122
|
+
except (EOFError, ValueError, OSError) as e:
|
|
123
|
+
log.warning(f"'{target}' is corrupted ({e}). Trying next format...")
|
|
124
|
+
os.remove(target)
|
|
125
|
+
continue
|
|
126
|
+
|
|
127
|
+
log.warning(f"No valid file found for {category}/{name}")
|
|
128
|
+
return None
|
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: pflex
|
|
3
|
+
Version: 1.0
|
|
4
|
+
Summary: pflex is a benchmarking toolkit for evaluating CRISPR screen results against biological gold standards. The toolkit computes gene-level and complex-level performance metrics, helping researchers systematically assess the biological relevance and resolution of their CRISPR screening data.
|
|
5
|
+
Author-email: Yasir Demirtas <tyasird@hotmail.com>
|
|
6
|
+
License-File: LICENSE
|
|
7
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
8
|
+
Classifier: Operating System :: OS Independent
|
|
9
|
+
Classifier: Programming Language :: Python :: 3
|
|
10
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
11
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
12
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
13
|
+
Requires-Python: >=3.9
|
|
14
|
+
Requires-Dist: adjusttext
|
|
15
|
+
Requires-Dist: art
|
|
16
|
+
Requires-Dist: bitarray
|
|
17
|
+
Requires-Dist: emoji
|
|
18
|
+
Requires-Dist: importlib-resources
|
|
19
|
+
Requires-Dist: ipython
|
|
20
|
+
Requires-Dist: joblib
|
|
21
|
+
Requires-Dist: loguru
|
|
22
|
+
Requires-Dist: matplotlib
|
|
23
|
+
Requires-Dist: numba
|
|
24
|
+
Requires-Dist: numpy
|
|
25
|
+
Requires-Dist: pandas
|
|
26
|
+
Requires-Dist: pyarrow
|
|
27
|
+
Requires-Dist: python-slugify
|
|
28
|
+
Requires-Dist: scikit-learn
|
|
29
|
+
Requires-Dist: scipy
|
|
30
|
+
Requires-Dist: tqdm
|
|
31
|
+
Description-Content-Type: text/markdown
|
|
32
|
+
|
|
33
|
+
# pflex
|
|
34
|
+
|
|
35
|
+

|
|
36
|
+

|
|
37
|
+

|
|
38
|
+

|
|
39
|
+

|
|
40
|
+

|
|
41
|
+

|
|
42
|
+
|
|
43
|
+
**pflex** is a benchmarking toolkit for evaluating CRISPR screen results against biological gold standards. It provides precision-recall analysis using reference gene sets from CORUM protein complexes, Gene Ontology Biological Processes (GO-BP), KEGG pathways, and other curated resources. The toolkit computes gene-level and complex-level performance metrics, helping researchers systematically assess the biological relevance and resolution of their CRISPR screening data.
|
|
44
|
+
|
|
45
|
+
---
|
|
46
|
+
|
|
47
|
+
## Features
|
|
48
|
+
|
|
49
|
+
- Precision-recall curve generation for ranked gene lists
|
|
50
|
+
- Evaluation using CORUM complexes, GO terms, pathways
|
|
51
|
+
- Complex-level resolution analysis and visualization
|
|
52
|
+
- Easy integration into CRISPR screen workflows
|
|
53
|
+
|
|
54
|
+
---
|
|
55
|
+
|
|
56
|
+
## Installation
|
|
57
|
+
|
|
58
|
+
Suggested to use Python version `3.10` with `virtual env`.
|
|
59
|
+
|
|
60
|
+
Create `venv`:
|
|
61
|
+
|
|
62
|
+
```bash
|
|
63
|
+
conda create -n p310 python=3.10
|
|
64
|
+
conda activate p310
|
|
65
|
+
pip install uv
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
Install pflex via pip:
|
|
69
|
+
|
|
70
|
+
```bash
|
|
71
|
+
uv pip install pflex
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
or:
|
|
75
|
+
|
|
76
|
+
```bash
|
|
77
|
+
pip install pflex
|
|
78
|
+
```
|
|
79
|
+
|
|
80
|
+
or install pflex via git to develop the package locally:
|
|
81
|
+
|
|
82
|
+
```bash
|
|
83
|
+
git clone https://github.com/tyasird/pflex.git
|
|
84
|
+
cd pflex
|
|
85
|
+
uv pip install -e .
|
|
86
|
+
```
|
|
87
|
+
|
|
88
|
+
---
|
|
89
|
+
|
|
90
|
+
## Quickstart
|
|
91
|
+
|
|
92
|
+
```python
|
|
93
|
+
import pflex as flex
|
|
94
|
+
|
|
95
|
+
inputs = {
|
|
96
|
+
"Melanoma (63 Screens)": {
|
|
97
|
+
"path": flex.get_example_data_path("melanoma_cell_lines_500_genes.csv"),
|
|
98
|
+
"sort": "high",
|
|
99
|
+
"color": "#FF0000",
|
|
100
|
+
},
|
|
101
|
+
"Liver (24 Screens)": {
|
|
102
|
+
"path": flex.get_example_data_path("liver_cell_lines_500_genes.csv"),
|
|
103
|
+
"sort": "high",
|
|
104
|
+
"color": "#FFDD00",
|
|
105
|
+
},
|
|
106
|
+
"Neuroblastoma (37 Screens)": {
|
|
107
|
+
"path": flex.get_example_data_path("neuroblastoma_cell_lines_500_genes.csv"),
|
|
108
|
+
"sort": "high",
|
|
109
|
+
"color": "#FFDDDD",
|
|
110
|
+
},
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
default_config = {
|
|
114
|
+
"min_genes_in_complex": 0,
|
|
115
|
+
"min_genes_per_complex_analysis": 3,
|
|
116
|
+
"output_folder": "CORUM",
|
|
117
|
+
"gold_standard": "CORUM",
|
|
118
|
+
"color_map": "BuGn",
|
|
119
|
+
"jaccard": False,
|
|
120
|
+
"use_common_genes": False,
|
|
121
|
+
"plotting": {
|
|
122
|
+
"save_plot": True,
|
|
123
|
+
"output_type": "png",
|
|
124
|
+
},
|
|
125
|
+
"preprocessing": {
|
|
126
|
+
"fill_na": True,
|
|
127
|
+
"normalize": False,
|
|
128
|
+
},
|
|
129
|
+
"corr_function": "numpy",
|
|
130
|
+
"logging": {
|
|
131
|
+
"visible_levels": ["DONE"],
|
|
132
|
+
},
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
flex.initialize(default_config)
|
|
136
|
+
|
|
137
|
+
data, _ = flex.load_datasets(inputs)
|
|
138
|
+
terms, genes_in_terms = flex.load_gold_standard()
|
|
139
|
+
|
|
140
|
+
for name, dataset in data.items():
|
|
141
|
+
pra = flex.pra(name, dataset, is_corr=False)
|
|
142
|
+
fpc = flex.pra_percomplex(name, dataset, is_corr=False)
|
|
143
|
+
cc = flex.complex_contributions(name)
|
|
144
|
+
flex.mpr_prepare(name)
|
|
145
|
+
|
|
146
|
+
flex.plot_precision_recall_curve()
|
|
147
|
+
flex.plot_auc_scores()
|
|
148
|
+
flex.plot_significant_complexes()
|
|
149
|
+
flex.plot_percomplex_scatter(n_top=20)
|
|
150
|
+
flex.plot_percomplex_scatter_bysize()
|
|
151
|
+
flex.plot_complex_contributions()
|
|
152
|
+
flex.plot_mpr_tp_multi()
|
|
153
|
+
flex.plot_mpr_complexes_multi()
|
|
154
|
+
flex.save_results_to_csv()
|
|
155
|
+
```
|
|
156
|
+
|
|
157
|
+
---
|
|
158
|
+
|
|
159
|
+
## Examples
|
|
160
|
+
|
|
161
|
+
- [src/pflex/examples/basic_usage.py](src/pflex/examples/basic_usage.py)
|
|
162
|
+
|
|
163
|
+
---
|
|
164
|
+
|
|
165
|
+
## License
|
|
166
|
+
|
|
167
|
+
MIT
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
pflex/__init__.py,sha256=6LpK3NPF8P3AxTCA2dKktahdGuF4NM1WoR-k3nAZhl8,2616
|
|
2
|
+
pflex/analysis.py,sha256=CQPeSGqO3DtXgYTy87VHLmQ8S0OuljMqtErxrhdJlmE,64659
|
|
3
|
+
pflex/logging_config.py,sha256=k83cHv_NH_aALCil2LSpgaigD26JU2fCTGrdFQcItuo,2010
|
|
4
|
+
pflex/old_functions.py,sha256=muMvXo0AEu6O-vepCBdx5cPG-0PNYfEbowarBRrMWS8,19025
|
|
5
|
+
pflex/plotting.py,sha256=2nSB0vyP-NkyVefwW-Zx851Z2gqbKsqND8AFTFWGZVQ,83438
|
|
6
|
+
pflex/preprocessing.py,sha256=6Zf-aWCIQYKj33MXmMr9noFFNwdWlrXJv0AmKC-Thq8,11241
|
|
7
|
+
pflex/utils.py,sha256=r9GVNqhaPmIFc8Ap2r-ThhZvJLDvmJXGmSJKJ2zKLfA,4694
|
|
8
|
+
pflex/data/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
9
|
+
pflex/data/dataset/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
10
|
+
pflex/data/dataset/liver_cell_lines_500_genes.csv,sha256=qfKsqPjL41Y1GuxxAhc-MfaNO0mX6Qju_SeynKSpEiM,238639
|
|
11
|
+
pflex/data/dataset/melanoma_cell_lines_500_genes.csv,sha256=ByxcaDDqLlRtAyuCKhHeFQCitIBk2-Q4Hn6k8BNUF6c,620887
|
|
12
|
+
pflex/data/dataset/neuroblastoma_cell_lines_500_genes.csv,sha256=IxJI8E-smagbxHRvTjvQLZxuu89MuCw8XrReMSsViUI,365992
|
|
13
|
+
pflex/data/gold_standard/CORUM.parquet,sha256=AkLiflQAeQ6K3HG-PIdLbZ8vEF9GtNObtlY7TkxHyaw,131858
|
|
14
|
+
pflex/data/gold_standard/GOBP.parquet,sha256=YQGhRcHSiN_cMKytCUYNCfcDwYj9L3TLFNwobiS2f3M,1025099
|
|
15
|
+
pflex/data/gold_standard/PATHWAY.parquet,sha256=bFRDe3PQ_TFc7B1uZuynwOGcgxESLaOy1Zt5gpQ1Oso,277386
|
|
16
|
+
pflex/data/gold_standard/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
17
|
+
pflex/data/gold_standard/corum.csv,sha256=2rZeyr2Ghm7f-gFxCZnhPtxI2jxRoiZMUEH2EJwAgsI,208889
|
|
18
|
+
pflex/data/gold_standard/gobp.csv,sha256=TO9yfx9mO8WkXvWfSB-pFId9T8xYfqdZpshAXC0Fyj8,1739167
|
|
19
|
+
pflex/data/gold_standard/pathway.csv,sha256=J3HKVLUZ_Oxucmn_14ieYp3Wr2lcKtp0nIl4_8_K2Yc,489424
|
|
20
|
+
pflex/examples/basic_usage.py,sha256=1bHXIfLWh9KybRjl9SggI5pb5z3UKNiKLCET312MA_I,2683
|
|
21
|
+
pflex-1.0.dist-info/METADATA,sha256=oeRzs-Mm57oT6odp8eWX4EF_vAQPc2o_EAaRvMiBp0U,4553
|
|
22
|
+
pflex-1.0.dist-info/WHEEL,sha256=mffPy8wBnZQn2VnJUU5jE99KsxaSfiyMHV9Yt0aLVxs,87
|
|
23
|
+
pflex-1.0.dist-info/entry_points.txt,sha256=-lujthYZb6oSvLVNFA9I7k-lK0iD57hTW7P_L_ybI40,37
|
|
24
|
+
pflex-1.0.dist-info/licenses/LICENSE,sha256=buBzPy38DV0g95acwIGUqsWZwhbpc0tQXnz6nBhjyS8,1091
|
|
25
|
+
pflex-1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
Copyright 2026, Yasir Demirtas, Maximilian Billmann
|
|
2
|
+
|
|
3
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
|
4
|
+
|
|
5
|
+
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
|
|
6
|
+
|
|
7
|
+
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|