Spaces:
Runtime error
Runtime error
Create beeline.py
Browse files- app/services/beeline.py +63 -0
app/services/beeline.py
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
import pandas as pd
|
| 3 |
+
from sklearn.metrics import roc_auc_score, average_precision_score
|
| 4 |
+
from scipy.stats import pearsonr, spearmanr
|
| 5 |
+
from sklearn.ensemble import RandomForestRegressor
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
def run_beeline_algorithm(
|
| 9 |
+
algorithm: str,
|
| 10 |
+
dataset_path: str,
|
| 11 |
+
params: dict
|
| 12 |
+
) -> pd.DataFrame:
|
| 13 |
+
"""
|
| 14 |
+
Returns inferred network as DataFrame:
|
| 15 |
+
[regulator, target, weight]
|
| 16 |
+
"""
|
| 17 |
+
|
| 18 |
+
expr = pd.read_parquet(dataset_path)
|
| 19 |
+
|
| 20 |
+
genes = expr.columns.tolist()
|
| 21 |
+
X = expr.values
|
| 22 |
+
|
| 23 |
+
edges = []
|
| 24 |
+
|
| 25 |
+
if algorithm == "pearson":
|
| 26 |
+
for i, g1 in enumerate(genes):
|
| 27 |
+
for j, g2 in enumerate(genes):
|
| 28 |
+
if i >= j:
|
| 29 |
+
continue
|
| 30 |
+
w, _ = pearsonr(X[:, i], X[:, j])
|
| 31 |
+
edges.append((g1, g2, abs(w)))
|
| 32 |
+
|
| 33 |
+
elif algorithm == "spearman":
|
| 34 |
+
for i, g1 in enumerate(genes):
|
| 35 |
+
for j, g2 in enumerate(genes):
|
| 36 |
+
if i >= j:
|
| 37 |
+
continue
|
| 38 |
+
w, _ = spearmanr(X[:, i], X[:, j])
|
| 39 |
+
edges.append((g1, g2, abs(w)))
|
| 40 |
+
|
| 41 |
+
elif algorithm == "genie3":
|
| 42 |
+
n_trees = params.get("n_estimators", 100)
|
| 43 |
+
|
| 44 |
+
for target_idx, target in enumerate(genes):
|
| 45 |
+
X_other = np.delete(X, target_idx, axis=1)
|
| 46 |
+
y = X[:, target_idx]
|
| 47 |
+
|
| 48 |
+
model = RandomForestRegressor(
|
| 49 |
+
n_estimators=n_trees,
|
| 50 |
+
n_jobs=-1
|
| 51 |
+
)
|
| 52 |
+
model.fit(X_other, y)
|
| 53 |
+
|
| 54 |
+
importances = model.feature_importances_
|
| 55 |
+
regulators = [g for g in genes if g != target]
|
| 56 |
+
|
| 57 |
+
for r, w in zip(regulators, importances):
|
| 58 |
+
edges.append((r, target, w))
|
| 59 |
+
|
| 60 |
+
else:
|
| 61 |
+
raise ValueError(f"Unsupported algorithm: {algorithm}")
|
| 62 |
+
|
| 63 |
+
return pd.DataFrame(edges, columns=["regulator", "target", "weight"])
|