almost finesh model packaging
Browse files- __pycache__/app.cpython-312.pyc +0 -0
- app.py +0 -114
- backend/PvDeepSetNet/datasets/pvAmpSeq_simulation_ready.csv +0 -0
- backend/PvDeepSetNet/datasets/real_data_PvDeepSet_ready.csv +0 -0
- backend/PvDeepSetNet/dist/pvdeepsetnet-0.1.0-py3-none-any.whl +0 -0
- backend/PvDeepSetNet/dist/pvdeepsetnet-0.1.0.tar.gz +0 -0
- backend/PvDeepSetNet/pyproject.toml +32 -0
- backend/PvDeepSetNet/src/DeepSets/Build_tensors.py +90 -0
- components/__init__.py → backend/PvDeepSetNet/src/DeepSets/DeepSets_pipeline.py +0 -0
- backend/PvDeepSetNet/src/DeepSets/Model.py +106 -0
- backend/PvDeepSetNet/src/DeepSets/Preprocess.py +132 -0
- backend/PvDeepSetNet/src/DeepSets/__init__.py +2 -0
- backend/PvDeepSetNet/src/DeepSets/__pycache__/Build_tensors.cpython-310.pyc +0 -0
- backend/PvDeepSetNet/src/DeepSets/__pycache__/Preprocess.cpython-310.pyc +0 -0
- backend/PvDeepSetNet/src/DeepSets/__pycache__/__init__.cpython-310.pyc +0 -0
- backend/PvDeepSetNet/src/DeepSets/allele_dict.json +1 -0
- backend/PvDeepSetNet/src/DeepSets/pv_deepsets_weights20260402.pth +3 -0
- backend/PvDeepSetNet/src/PvDeepSetNet.egg-info/PKG-INFO +12 -0
- backend/PvDeepSetNet/src/PvDeepSetNet.egg-info/SOURCES.txt +11 -0
- backend/PvDeepSetNet/src/PvDeepSetNet.egg-info/dependency_links.txt +1 -0
- backend/PvDeepSetNet/src/PvDeepSetNet.egg-info/requires.txt +2 -0
- backend/PvDeepSetNet/src/PvDeepSetNet.egg-info/top_level.txt +1 -0
- backend/PvDeepSetNet/tests/allele_dict.json +1 -0
- backend/PvDeepSetNet/tests/temp.ipynb +496 -0
- components/layouts.py → backend/PvDeepSetNet/tests/tests_utils.py +0 -0
- backend/__pycache__/main.cpython-312.pyc +0 -0
- backend/main.py +24 -0
- frontend/app.py +267 -0
- {services → frontend/components}/__init__.py +0 -0
- frontend/components/layouts.py +0 -0
- frontend/services/__init__.py +0 -0
- {services → frontend/services}/__pycache__/__init__.cpython-310.pyc +0 -0
- {services → frontend/services}/__pycache__/__init__.cpython-312.pyc +0 -0
- {services → frontend/services}/__pycache__/api.cpython-310.pyc +0 -0
- {services → frontend/services}/__pycache__/api.cpython-312.pyc +0 -0
- {services → frontend/services}/api.py +0 -0
__pycache__/app.cpython-312.pyc
CHANGED
|
Binary files a/__pycache__/app.cpython-312.pyc and b/__pycache__/app.cpython-312.pyc differ
|
|
|
app.py
DELETED
|
@@ -1,114 +0,0 @@
|
|
| 1 |
-
import dash
|
| 2 |
-
from dash import dcc, html, Input, Output, State, dash_table
|
| 3 |
-
import dash_bootstrap_components as dbc
|
| 4 |
-
import plotly.express as px
|
| 5 |
-
import pandas as pd
|
| 6 |
-
import base64
|
| 7 |
-
from services.api import PvRecNetAPI
|
| 8 |
-
|
| 9 |
-
# Initialize App with a professional Bootstrap theme (CYBORG or FLATLY)
|
| 10 |
-
app = dash.Dash(__name__, external_stylesheets=[dbc.themes.FLATLY])
|
| 11 |
-
|
| 12 |
-
app.layout = dbc.Container([
|
| 13 |
-
dcc.Store(id='dataset-id-store'),
|
| 14 |
-
|
| 15 |
-
dbc.Row(dbc.Col(html.H1("PvRecNet", className="text-center my-4"))),
|
| 16 |
-
|
| 17 |
-
dbc.Tabs([
|
| 18 |
-
# TAB 1: UPLOAD & PREDICT
|
| 19 |
-
dbc.Tab(label="Prediction Workflow", children=[
|
| 20 |
-
dbc.Row([
|
| 21 |
-
dbc.Col([
|
| 22 |
-
dbc.Card([
|
| 23 |
-
dbc.CardHeader("Step 1: Upload Data"),
|
| 24 |
-
dbc.CardBody([
|
| 25 |
-
dcc.Upload(
|
| 26 |
-
id='upload-data',
|
| 27 |
-
children=html.Div(['Drag/Drop or ', html.A('Select CSV')]),
|
| 28 |
-
style={'width': '100%', 'height': '60px', 'lineHeight': '60px',
|
| 29 |
-
'borderWidth': '1px', 'borderStyle': 'dashed', 'textAlign': 'center'}
|
| 30 |
-
),
|
| 31 |
-
html.Div(id='upload-status', className="mt-2"),
|
| 32 |
-
dbc.Button("Run Prediction", id="predict-btn", color="primary",
|
| 33 |
-
disabled=True, className="mt-3 w-100")
|
| 34 |
-
])
|
| 35 |
-
])
|
| 36 |
-
], md=4),
|
| 37 |
-
dbc.Col([
|
| 38 |
-
dbc.Card([
|
| 39 |
-
dbc.CardHeader("Step 2: Results"),
|
| 40 |
-
dbc.CardBody(dcc.Loading(id="prediction-output"))
|
| 41 |
-
])
|
| 42 |
-
], md=8)
|
| 43 |
-
], className="mt-4")
|
| 44 |
-
]),
|
| 45 |
-
|
| 46 |
-
# TAB 2: ANALYTICS
|
| 47 |
-
dbc.Tab(label="Analytics Tools", children=[
|
| 48 |
-
dbc.Row([
|
| 49 |
-
dbc.Col([
|
| 50 |
-
dbc.Button("Compute MOI", id="moi-btn", color="info", className="m-2"),
|
| 51 |
-
dbc.Button("Compute Allele Freq", id="freq-btn", color="secondary", className="m-2"),
|
| 52 |
-
html.Hr(),
|
| 53 |
-
dcc.Loading(id="analytics-output")
|
| 54 |
-
], md=12)
|
| 55 |
-
], className="mt-4")
|
| 56 |
-
])
|
| 57 |
-
])
|
| 58 |
-
], fluid=True)
|
| 59 |
-
|
| 60 |
-
# --- Callbacks ---
|
| 61 |
-
|
| 62 |
-
@app.callback(
|
| 63 |
-
Output('dataset-id-store', 'data'),
|
| 64 |
-
Output('upload-status', 'children'),
|
| 65 |
-
Output('predict-btn', 'disabled'),
|
| 66 |
-
Input('upload-data', 'contents'),
|
| 67 |
-
State('upload-data', 'filename')
|
| 68 |
-
)
|
| 69 |
-
def handle_upload(contents, filename):
|
| 70 |
-
if not contents: return dash.no_update
|
| 71 |
-
decoded = base64.b64decode(contents.split(',')[1])
|
| 72 |
-
try:
|
| 73 |
-
res = PvRecNetAPI.upload_dataset(decoded, filename)
|
| 74 |
-
return res['dataset_id'], dbc.Alert(f"Ready: {filename}", color="success"), False
|
| 75 |
-
except Exception as e:
|
| 76 |
-
return None, dbc.Alert(f"Error: {e}", color="danger"), True
|
| 77 |
-
|
| 78 |
-
@app.callback(
|
| 79 |
-
Output('prediction-output', 'children'),
|
| 80 |
-
Input('predict-btn', 'n_clicks'),
|
| 81 |
-
State('dataset-id-store', 'data'),
|
| 82 |
-
prevent_initial_call=True
|
| 83 |
-
)
|
| 84 |
-
def run_predict(n, ds_id):
|
| 85 |
-
try:
|
| 86 |
-
res = PvRecNetAPI.run_prediction(ds_id)
|
| 87 |
-
fig = px.bar(x=list(res['probabilities'].keys()), y=list(res['probabilities'].values()), title="Probability")
|
| 88 |
-
return html.Div([
|
| 89 |
-
html.H3(f"Prediction: {res['prediction']}"),
|
| 90 |
-
dcc.Graph(figure=fig)
|
| 91 |
-
])
|
| 92 |
-
except Exception as e: return dbc.Alert(f"Error: {e}", color="danger")
|
| 93 |
-
|
| 94 |
-
@app.callback(
|
| 95 |
-
Output('analytics-output', 'children'),
|
| 96 |
-
Input('moi-btn', 'n_clicks'),
|
| 97 |
-
Input('freq-btn', 'n_clicks'),
|
| 98 |
-
State('dataset-id-store', 'data'),
|
| 99 |
-
prevent_initial_call=True
|
| 100 |
-
)
|
| 101 |
-
def run_analytics(m_n, f_n, ds_id):
|
| 102 |
-
if not ds_id: return dbc.Alert("No dataset found.", color="warning")
|
| 103 |
-
trigger = dash.callback_context.triggered[0]['prop_id']
|
| 104 |
-
try:
|
| 105 |
-
if "moi-btn" in trigger:
|
| 106 |
-
res = PvRecNetAPI.get_moi(ds_id)
|
| 107 |
-
return dash_table.DataTable(res, page_size=10)
|
| 108 |
-
else:
|
| 109 |
-
res = PvRecNetAPI.get_allele_freq(ds_id)
|
| 110 |
-
return dcc.Graph(figure=px.pie(res, names='allele', values='frequency'))
|
| 111 |
-
except Exception as e: return f"Error: {e}"
|
| 112 |
-
|
| 113 |
-
if __name__ == '__main__':
|
| 114 |
-
app.run(debug=True)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
backend/PvDeepSetNet/datasets/pvAmpSeq_simulation_ready.csv
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
backend/PvDeepSetNet/datasets/real_data_PvDeepSet_ready.csv
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
backend/PvDeepSetNet/dist/pvdeepsetnet-0.1.0-py3-none-any.whl
ADDED
|
Binary file (2.78 kB). View file
|
|
|
backend/PvDeepSetNet/dist/pvdeepsetnet-0.1.0.tar.gz
ADDED
|
Binary file (2.63 kB). View file
|
|
|
backend/PvDeepSetNet/pyproject.toml
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
[build-system]
|
| 2 |
+
# These are the tools used to actually create the package files
|
| 3 |
+
requires = ["setuptools>=61.0", "wheel"]
|
| 4 |
+
build-backend = "setuptools.build_meta"
|
| 5 |
+
|
| 6 |
+
[project]
|
| 7 |
+
name = "PvDeepSetNet" # The name you'll use for 'pip install'
|
| 8 |
+
version = "0.1.0" # Increment this (0.1.1, 0.2.0) as you update
|
| 9 |
+
description = "Core utilities shared across my internal projects"
|
| 10 |
+
readme = "README.md" # Links your README file
|
| 11 |
+
requires-python = ">=3.8" # Minimum Python version required
|
| 12 |
+
authors = [
|
| 13 |
+
{ name="Sineshaw L.", email="sinelegese306@gmail.com" },
|
| 14 |
+
]
|
| 15 |
+
classifiers = [
|
| 16 |
+
"Programming Language :: Python :: 3",
|
| 17 |
+
"Operating System :: OS Independent",
|
| 18 |
+
]
|
| 19 |
+
|
| 20 |
+
# LIST YOUR DEPENDENCIES HERE
|
| 21 |
+
# These are installed automatically when you install your package
|
| 22 |
+
dependencies = [
|
| 23 |
+
"requests >= 2.28.0",
|
| 24 |
+
"pandas >= 2.0.0",
|
| 25 |
+
]
|
| 26 |
+
|
| 27 |
+
[tool.setuptools.packages.find]
|
| 28 |
+
# This tells Python to look in the 'src' folder for your code
|
| 29 |
+
where = ["src"]
|
| 30 |
+
|
| 31 |
+
[project.urls]
|
| 32 |
+
"Homepage" = "https://github.com/sineshawl/PvRecNet"
|
backend/PvDeepSetNet/src/DeepSets/Build_tensors.py
ADDED
|
@@ -0,0 +1,90 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
import pandas as pd
|
| 3 |
+
import json
|
| 4 |
+
from collections import defaultdict
|
| 5 |
+
|
| 6 |
+
def build_deepsets_tensors(df, M_max = 11, A_max = 5, purpose='prediction'):
|
| 7 |
+
"""
|
| 8 |
+
df = dataframe
|
| 9 |
+
M_max = the maximum number of unique marker within the dataset (default 11 <- used during training)
|
| 10 |
+
A_max = the maximum number of unique allele per marker (default 5 <- used during training)
|
| 11 |
+
allele_to_id = alleles with their corresponding ids
|
| 12 |
+
Optimized Deep Sets preprocessing for Pv3Rs surrogate
|
| 13 |
+
"""
|
| 14 |
+
# checking the existance of prior columns, otherwise the default values will be assigned
|
| 15 |
+
required_cols = {'prior_C', 'prior_L', 'prior_I'}
|
| 16 |
+
if not required_cols.issubset(df.columns):
|
| 17 |
+
df['prior_C']=df['prior_L']=df['prior_I']=1/3
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
# reading allele dictionary
|
| 21 |
+
with open('allele_dict.json', 'r') as file:
|
| 22 |
+
allele_to_id = json.load(file)
|
| 23 |
+
|
| 24 |
+
# build tensor for target variable only if the purpose == evaluation
|
| 25 |
+
y_given = False
|
| 26 |
+
if purpose == 'evaluation':
|
| 27 |
+
y_given=True
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
# ----------------------------------------------------
|
| 32 |
+
# 1. Encode categorical variables once
|
| 33 |
+
# ----------------------------------------------------
|
| 34 |
+
marker_to_id = {m: i + 1 for i, m in enumerate(df.marker.unique())}
|
| 35 |
+
allele_to_id = allele_to_id
|
| 36 |
+
|
| 37 |
+
grouped = list(df.groupby("sample_id_paired")) #computationally intensive
|
| 38 |
+
N = len(grouped)
|
| 39 |
+
|
| 40 |
+
# ----------------------------------------------------
|
| 41 |
+
# 2. Allocate tensors
|
| 42 |
+
# ----------------------------------------------------
|
| 43 |
+
X_alleles = torch.zeros((N, M_max, 2, A_max, 2))
|
| 44 |
+
allele_mask = torch.zeros((N, M_max, 2, A_max), dtype=torch.bool)
|
| 45 |
+
marker_mask = torch.zeros((N, M_max), dtype=torch.bool)
|
| 46 |
+
|
| 47 |
+
priors = torch.zeros((N, 3))
|
| 48 |
+
MOI = torch.zeros((N, 2))
|
| 49 |
+
y = torch.zeros((N, 3))
|
| 50 |
+
|
| 51 |
+
# ----------------------------------------------------
|
| 52 |
+
# 3. Main loop (optimized)
|
| 53 |
+
# ----------------------------------------------------
|
| 54 |
+
for i, (_, df_pair) in enumerate(grouped):
|
| 55 |
+
# ---- pair-level values (constant)
|
| 56 |
+
priors[i] = torch.tensor(df_pair[["prior_C", "prior_L", "prior_I"]].iloc[0].values)
|
| 57 |
+
MOI1 = df_pair.loc[df_pair.episode == 1, 'MOI'].iloc[0]
|
| 58 |
+
MOI2 = df_pair.loc[df_pair.episode == 2, 'MOI'].iloc[0]
|
| 59 |
+
|
| 60 |
+
MOI[i] = torch.tensor([MOI1, MOI2])
|
| 61 |
+
if y_given:
|
| 62 |
+
y[i] = torch.tensor(df_pair[["post_C", "post_L", "post_I"]].iloc[0].values)
|
| 63 |
+
|
| 64 |
+
# ---- pre-group alleles by (marker, episode)
|
| 65 |
+
allele_dict = defaultdict(list)
|
| 66 |
+
for row in df_pair.itertuples():
|
| 67 |
+
allele_dict[(row.marker, row.episode)].append((row.allele, row.frequency))
|
| 68 |
+
|
| 69 |
+
# ---- marker union
|
| 70 |
+
markers = sorted({m for (m, _) in allele_dict.keys()})[:M_max]
|
| 71 |
+
|
| 72 |
+
for m_idx, marker in enumerate(markers):
|
| 73 |
+
marker_mask[i, m_idx] = True
|
| 74 |
+
|
| 75 |
+
for e_idx, episode in enumerate([1, 2]):
|
| 76 |
+
alleles = allele_dict.get((marker, episode), [])
|
| 77 |
+
|
| 78 |
+
for a_idx, (allele, freq) in enumerate(alleles[:A_max]):
|
| 79 |
+
X_alleles[i, m_idx, e_idx, a_idx, 0] = allele_to_id[allele]
|
| 80 |
+
X_alleles[i, m_idx, e_idx, a_idx, 1] = freq
|
| 81 |
+
allele_mask[i, m_idx, e_idx, a_idx] = True
|
| 82 |
+
final_tensors = {
|
| 83 |
+
"X_alleles": X_alleles, "allele_mask": allele_mask,
|
| 84 |
+
"marker_mask": marker_mask, "priors": priors,
|
| 85 |
+
"MOI": MOI
|
| 86 |
+
}
|
| 87 |
+
if y_given:
|
| 88 |
+
final_tensors['y'] = y
|
| 89 |
+
|
| 90 |
+
return final_tensors
|
components/__init__.py → backend/PvDeepSetNet/src/DeepSets/DeepSets_pipeline.py
RENAMED
|
File without changes
|
backend/PvDeepSetNet/src/DeepSets/Model.py
ADDED
|
@@ -0,0 +1,106 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
import torch.nn as nn
|
| 3 |
+
import torch.nn.functional as F
|
| 4 |
+
|
| 5 |
+
# =====================================================
|
| 6 |
+
# Deep Sets model for Pv3Rs surrogate
|
| 7 |
+
# =====================================================
|
| 8 |
+
class PvDeepSets(nn.Module):
|
| 9 |
+
def __init__(self,
|
| 10 |
+
n_alleles, # total number of unique alleles
|
| 11 |
+
allele_embed_dim=32,
|
| 12 |
+
marker_embed_dim=64,
|
| 13 |
+
pair_embed_dim=64,
|
| 14 |
+
hidden_dim=64,
|
| 15 |
+
n_classes=3):
|
| 16 |
+
super(PvDeepSets, self).__init__()
|
| 17 |
+
|
| 18 |
+
# -------------------------------------------------
|
| 19 |
+
# 1️⃣ Allele embedding (allele ID + frequency)
|
| 20 |
+
# -------------------------------------------------
|
| 21 |
+
self.allele_embedding = nn.Embedding(n_alleles + 1, allele_embed_dim, padding_idx=0)
|
| 22 |
+
self.allele_mlp = nn.Sequential(
|
| 23 |
+
nn.Linear(allele_embed_dim + 1, allele_embed_dim), # +1 for frequency
|
| 24 |
+
nn.ReLU(),
|
| 25 |
+
nn.Linear(allele_embed_dim, allele_embed_dim),
|
| 26 |
+
nn.ReLU()
|
| 27 |
+
)
|
| 28 |
+
|
| 29 |
+
# -------------------------------------------------
|
| 30 |
+
# 2️⃣ Marker-level MLP (after comparing episodes)
|
| 31 |
+
# -------------------------------------------------
|
| 32 |
+
self.marker_mlp = nn.Sequential(
|
| 33 |
+
nn.Linear(allele_embed_dim * 4, marker_embed_dim),
|
| 34 |
+
nn.ReLU(),
|
| 35 |
+
nn.Linear(marker_embed_dim, marker_embed_dim),
|
| 36 |
+
nn.ReLU()
|
| 37 |
+
)
|
| 38 |
+
|
| 39 |
+
# -------------------------------------------------
|
| 40 |
+
# 3️⃣ Pair-level MLP (aggregate markers + priors + MOI)
|
| 41 |
+
# -------------------------------------------------
|
| 42 |
+
self.pair_mlp = nn.Sequential(
|
| 43 |
+
nn.Linear(marker_embed_dim + 3 + 2, pair_embed_dim), # +3 priors +2 MOI
|
| 44 |
+
nn.ReLU(),
|
| 45 |
+
nn.Linear(pair_embed_dim, hidden_dim),
|
| 46 |
+
nn.ReLU(),
|
| 47 |
+
nn.Linear(hidden_dim, n_classes)
|
| 48 |
+
)
|
| 49 |
+
|
| 50 |
+
def forward(self, X_alleles, allele_mask, marker_mask, priors, MOI):
|
| 51 |
+
"""
|
| 52 |
+
X_alleles : (batch, M_max, 2, A_max, 2)
|
| 53 |
+
allele_mask: same shape as X_alleles[:,:,:,:,0]
|
| 54 |
+
marker_mask: (batch, M_max)
|
| 55 |
+
priors : (batch, 3)
|
| 56 |
+
MOI : (batch, 2)
|
| 57 |
+
"""
|
| 58 |
+
B, M, E, A, _ = X_alleles.shape
|
| 59 |
+
|
| 60 |
+
# ---------------------------------------------
|
| 61 |
+
# 1️⃣ Embed alleles
|
| 62 |
+
# ---------------------------------------------
|
| 63 |
+
allele_ids = X_alleles[..., 0].long()
|
| 64 |
+
freqs = X_alleles[..., 1]
|
| 65 |
+
|
| 66 |
+
allele_emb = self.allele_embedding(allele_ids) # (B,M,E,A,allele_embed_dim)
|
| 67 |
+
allele_input = torch.cat([allele_emb, freqs.unsqueeze(-1)], dim=-1)
|
| 68 |
+
allele_out = self.allele_mlp(allele_input) # (B,M,E,A,allele_embed_dim)
|
| 69 |
+
|
| 70 |
+
# Apply allele mask
|
| 71 |
+
allele_out = allele_out * allele_mask.unsqueeze(-1)
|
| 72 |
+
|
| 73 |
+
# ---------------------------------------------
|
| 74 |
+
# 2️⃣ Aggregate alleles → marker embedding per episode
|
| 75 |
+
# ---------------------------------------------
|
| 76 |
+
# Sum pooling over alleles
|
| 77 |
+
marker_ep_emb = allele_out.sum(dim=3) # (B,M,E,allele_embed_dim)
|
| 78 |
+
|
| 79 |
+
# ---------------------------------------------
|
| 80 |
+
# 3️⃣ Compare episodes (ep1 vs ep2)
|
| 81 |
+
# ---------------------------------------------
|
| 82 |
+
ep1 = marker_ep_emb[:, :, 0, :]
|
| 83 |
+
ep2 = marker_ep_emb[:, :, 1, :]
|
| 84 |
+
|
| 85 |
+
marker_pair = torch.cat([ep1, ep2, torch.abs(ep1 - ep2), ep1 * ep2], dim=-1) # (B,M,4*allele_embed_dim)
|
| 86 |
+
|
| 87 |
+
# Apply marker-level MLP
|
| 88 |
+
marker_emb = self.marker_mlp(marker_pair) # (B,M,marker_embed_dim)
|
| 89 |
+
|
| 90 |
+
# Masked sum over markers
|
| 91 |
+
marker_emb = marker_emb * marker_mask.unsqueeze(-1)
|
| 92 |
+
pair_emb = marker_emb.sum(dim=1) # (B, marker_embed_dim)
|
| 93 |
+
|
| 94 |
+
# ---------------------------------------------
|
| 95 |
+
# 4️⃣ Concatenate priors + MOI
|
| 96 |
+
# ---------------------------------------------
|
| 97 |
+
pair_emb = torch.cat([pair_emb, priors, MOI], dim=-1) # (B, marker_dim+4)
|
| 98 |
+
|
| 99 |
+
# ---------------------------------------------
|
| 100 |
+
# 5️⃣ Pair-level MLP → logits
|
| 101 |
+
# ---------------------------------------------
|
| 102 |
+
logits = self.pair_mlp(pair_emb) # (B, n_classes)
|
| 103 |
+
probs = F.softmax(logits, dim=-1)
|
| 104 |
+
|
| 105 |
+
return probs
|
| 106 |
+
|
backend/PvDeepSetNet/src/DeepSets/Preprocess.py
ADDED
|
@@ -0,0 +1,132 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import pandas as pd
|
| 2 |
+
import numpy as np
|
| 3 |
+
from itertools import combinations
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
class DataPreprocessor:
|
| 7 |
+
@staticmethod
|
| 8 |
+
def removing_single_episode_patients(data: pd.DataFrame, patient_id='patient_id', episode='episode') -> pd.DataFrame:
|
| 9 |
+
"""
|
| 10 |
+
To run the recurrence analysis, at least 2 episodes are required. So, we have to remove patients with single episode
|
| 11 |
+
data: data
|
| 12 |
+
patient: name of column for the patient_id
|
| 13 |
+
episode: name of column for the episode
|
| 14 |
+
"""
|
| 15 |
+
|
| 16 |
+
df = data.copy()
|
| 17 |
+
|
| 18 |
+
temp = data[[patient_id, episode]].drop_duplicates(ignore_index=True)
|
| 19 |
+
temp = temp.groupby(patient_id)[episode].count().reset_index(name='count')
|
| 20 |
+
|
| 21 |
+
removed_id = temp[temp['count'] < 2].patient_id
|
| 22 |
+
return df[~df.patient_id.isin(removed_id)].reset_index(drop=True)
|
| 23 |
+
@staticmethod
|
| 24 |
+
def calculate_population_Allele_frequencies(df, population='country', patient_id='patient_id', episode='episode'):
|
| 25 |
+
"""
|
| 26 |
+
Calculate Population Level Allele Frequency
|
| 27 |
+
"""
|
| 28 |
+
# We will collect all frequency data here
|
| 29 |
+
pop_aFreq_list = []
|
| 30 |
+
|
| 31 |
+
# 1. Calculate frequencies per population
|
| 32 |
+
for pop, pop_data in df.groupby(population):
|
| 33 |
+
unique_markers = sorted(pop_data.marker.unique())
|
| 34 |
+
grouped = pop_data.groupby('marker')
|
| 35 |
+
|
| 36 |
+
for marker, group in grouped:
|
| 37 |
+
if marker not in unique_markers:
|
| 38 |
+
continue
|
| 39 |
+
|
| 40 |
+
# FIX APPLIED: Drop duplicates based on the actual biological event (patient+episode)
|
| 41 |
+
# This prevents "pair-inflation"
|
| 42 |
+
unique_counts = group.drop_duplicates([patient_id, episode, 'allele'])
|
| 43 |
+
|
| 44 |
+
counts = unique_counts['allele'].value_counts(normalize=True).reset_index()
|
| 45 |
+
counts.columns = ['allele', 'frequency']
|
| 46 |
+
counts['marker'] = marker
|
| 47 |
+
counts[population] = pop # Add population label here
|
| 48 |
+
|
| 49 |
+
pop_aFreq_list.append(counts)
|
| 50 |
+
|
| 51 |
+
# 2. Combine all frequency tables
|
| 52 |
+
all_frequencies = pd.concat(pop_aFreq_list, ignore_index=True)
|
| 53 |
+
|
| 54 |
+
# 3. Clean up the original df and merge the calculated frequencies
|
| 55 |
+
output_df = df.drop('frequency', axis=1, errors='ignore').copy()
|
| 56 |
+
output_df = output_df.merge(all_frequencies, on=['marker', 'allele', population], how='inner')
|
| 57 |
+
|
| 58 |
+
return output_df
|
| 59 |
+
|
| 60 |
+
@staticmethod
|
| 61 |
+
def calculate_MOIs(data: pd.DataFrame, patient_id = 'patient_id', episode='episode', marker='marker', allele='allele') -> pd.DataFrame:
|
| 62 |
+
"""
|
| 63 |
+
The function to calculcate Multiplicity of Infection (MOI), the maximum number of distinict alleles per sample per marker
|
| 64 |
+
"""
|
| 65 |
+
df = data.copy()
|
| 66 |
+
# calculate the number of distinict allele per sample per marker
|
| 67 |
+
temp_df = (
|
| 68 |
+
data.groupby([patient_id, episode, marker])[allele]
|
| 69 |
+
.nunique()
|
| 70 |
+
.reset_index(name="allele_count")
|
| 71 |
+
)
|
| 72 |
+
|
| 73 |
+
# take the maximum number of alleles across markers per sample
|
| 74 |
+
|
| 75 |
+
moi_df = (
|
| 76 |
+
temp_df.groupby([patient_id, episode])["allele_count"]
|
| 77 |
+
.max()
|
| 78 |
+
.reset_index(name='MOI')
|
| 79 |
+
)
|
| 80 |
+
df.drop('MOIs', axis=1, errors='ignore', inplace=True)
|
| 81 |
+
|
| 82 |
+
df = df.merge(moi_df, on=[patient_id, episode], how='inner')
|
| 83 |
+
return df
|
| 84 |
+
|
| 85 |
+
@staticmethod
|
| 86 |
+
def paired_episode_assigner(data: pd.DataFrame, patient_id='patient_id') -> pd.DataFrame:
|
| 87 |
+
"""
|
| 88 |
+
This function makes all possible pairs of episodes per patient.
|
| 89 |
+
So number of episodes = n^2 - n, where n = number of episode
|
| 90 |
+
"""
|
| 91 |
+
if 'episode' not in data.columns:
|
| 92 |
+
print('There is no column episode in your dataset')
|
| 93 |
+
return pd.DataFrame()
|
| 94 |
+
|
| 95 |
+
all_pairs_list = []
|
| 96 |
+
|
| 97 |
+
for indiv, indiv_data in data.groupby(patient_id):
|
| 98 |
+
# Get all unique episodes for this individual
|
| 99 |
+
episodes = sorted(indiv_data['episode'].unique())
|
| 100 |
+
|
| 101 |
+
# Generate mathematical combinations (n choose 2)
|
| 102 |
+
# combinations(episodes, 2) automatically handles:
|
| 103 |
+
# 1. No self-pairing (i == j is impossible)
|
| 104 |
+
# 2. Uniqueness (if (1,2) is picked, (2,1) is not)
|
| 105 |
+
for pair_order, (ep_i, ep_j) in enumerate(combinations(episodes, 2), 1):
|
| 106 |
+
pair_data = indiv_data[indiv_data['episode'].isin([ep_i, ep_j])].copy()
|
| 107 |
+
|
| 108 |
+
# Create the unique identifiers
|
| 109 |
+
pair_label = f"{indiv}_P{pair_order}"
|
| 110 |
+
pair_data['pair_order'] = pair_order
|
| 111 |
+
pair_data['sample_id_paired'] = pair_label
|
| 112 |
+
|
| 113 |
+
all_pairs_list.append(pair_data)
|
| 114 |
+
|
| 115 |
+
if not all_pairs_list:
|
| 116 |
+
return pd.DataFrame()
|
| 117 |
+
df = pd.concat(all_pairs_list, ignore_index=True)
|
| 118 |
+
cols = ['sample_id_paired', 'pair_order'] + list(df.columns[:-2])
|
| 119 |
+
df = df[cols]
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
# assign episode order: converting every episode into either episode 1 or 2
|
| 123 |
+
df['episode_order'] = (
|
| 124 |
+
df.groupby('sample_id_paired')['episode']
|
| 125 |
+
.rank(method='dense')
|
| 126 |
+
)
|
| 127 |
+
|
| 128 |
+
df.rename(columns={'episode':'true_episode', 'episode_order':'episode'}, inplace=True)
|
| 129 |
+
|
| 130 |
+
return df
|
| 131 |
+
|
| 132 |
+
|
backend/PvDeepSetNet/src/DeepSets/__init__.py
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from .Build_tensors import build_deepsets_tensors
|
| 2 |
+
from .Preprocess import DataPreprocessor
|
backend/PvDeepSetNet/src/DeepSets/__pycache__/Build_tensors.cpython-310.pyc
ADDED
|
Binary file (2.56 kB). View file
|
|
|
backend/PvDeepSetNet/src/DeepSets/__pycache__/Preprocess.cpython-310.pyc
ADDED
|
Binary file (3.66 kB). View file
|
|
|
backend/PvDeepSetNet/src/DeepSets/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (273 Bytes). View file
|
|
|
backend/PvDeepSetNet/src/DeepSets/allele_dict.json
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
{"Chr01-1": 1, "Chr01-2": 2, "Chr02-2": 3, "Chr02-1": 4, "Chr03-3": 5, "Chr03-2": 6, "Chr05-6": 7, "Chr05-4": 8, "Chr07-1": 9, "Chr07-5": 10, "Chr08-3": 11, "Chr09-1": 12, "Chr09-2": 13, "Chr09-3": 14, "Chr10-2": 15, "Chr10-7": 16, "Chr11-1": 17, "Chr13-1": 18, "Chr13-4": 19, "Chr14-1": 20, "Chr03-1": 21, "Chr05-1": 22, "Chr08-1": 23, "Chr11-3": 24, "Chr11-2": 25, "Chr13-3": 26, "Chr14-3": 27, "Chr07-2": 28, "Chr08-2": 29, "Chr10-1": 30, "Chr14-10": 31, "Chr05-3": 32, "Chr10-4": 33, "Chr13-2": 34, "Chr01-5": 35, "Chr02-3": 36, "Chr05-2": 37, "Chr07-3": 38, "Chr07-4": 39, "Chr10-3": 40, "Chr13-6": 41, "Chr01-11": 42, "Chr05-7": 43, "Chr09-4": 44, "Chr14-15": 45, "Chr05-15": 46, "Chr01-3": 47, "Chr11-30": 48, "Chr11-6": 49, "Chr14-11": 50, "Chr03-4": 51, "Chr09-5": 52, "Chr09-7": 53, "Chr11-16": 54, "Chr13-7": 55, "Chr11-5": 56, "Chr07-8": 57, "Chr05-5": 58, "Chr11-12": 59, "Chr07-30": 60, "Chr10-5": 61, "Chr11-17": 62, "Chr09-8": 63, "Chr14-6": 64, "Chr11-22": 65, "Chr13-8": 66, "Chr14-4": 67, "Chr09-14": 68, "Chr11-9": 69, "Chr14-21": 70, "Chr08-4": 71, "Chr07-29": 72, "Chr09-13": 73, "Chr11-24": 74, "Chr10-6": 75, "Chr11-4": 76, "Chr13-5": 77, "Chr05-13": 78, "Chr13-12": 79, "Chr05-12": 80, "Chr14-9": 81, "Chr05-8": 82, "Chr14-22": 83, "Chr09-6": 84, "Chr05-9": 85, "Chr14-5": 86, "Chr13-24": 87, "Chr13-49": 88, "Chr11-37": 89, "Chr14-2": 90, "Chr01-4": 91, "Chr13-9": 92, "Chr13-11": 93, "Chr14-23": 94, "Chr03-17": 95, "Chr02-9": 96, "Chr14-12": 97, "Chr13-42": 98, "Chr14-7": 99, "Chr14-30": 100, "Chr09-12": 101, "Chr14-8": 102, "Chr13-41": 103, "Chr11-19": 104, "Chr08-8": 105, "Chr14-19": 106, "Chr11-18": 107, "Chr11-10": 108, "Chr14-17": 109, "Chr13-21": 110, "Chr08-7": 111, "Chr11-8": 112, "Chr13-40": 113, "Chr08-19": 114, "Chr11-29": 115, "Chr13-17": 116, "Chr11-14": 117, "Chr09-15": 118, "Chr13-13": 119, "Chr14-13": 120, "Chr13-46": 121, "Chr13-20": 122, "Chr01-9": 123, "Chr09-16": 124, "Chr14-16": 125, "Chr13-15": 126, "Chr14-14": 127, "Chr02-4": 128, "Chr07-6": 129, "Chr08-6": 130, "Chr02-5": 131, "Chr02-8": 132, "Chr03-5": 133, "Chr02-7": 134, "Chr02-6": 135, "Chr05-11": 136, "Chr07-10": 137, "Chr02-11": 138, "Chr03-6": 139, "Chr09-9": 140, "Chr07-9": 141, "Chr05-10": 142, "Chr07-11": 143}
|
backend/PvDeepSetNet/src/DeepSets/pv_deepsets_weights20260402.pth
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:365518857580c3808b0bcc4b3c4a650064e8d972fa3ff27ffe565b420052a9a7
|
| 3 |
+
size 118509
|
backend/PvDeepSetNet/src/PvDeepSetNet.egg-info/PKG-INFO
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Metadata-Version: 2.4
|
| 2 |
+
Name: PvDeepSetNet
|
| 3 |
+
Version: 0.1.0
|
| 4 |
+
Summary: Core utilities shared across my internal projects
|
| 5 |
+
Author-email: "Sineshaw L." <sinelegese306@gmail.com>
|
| 6 |
+
Project-URL: Homepage, https://github.com/sineshawl/PvRecNet
|
| 7 |
+
Classifier: Programming Language :: Python :: 3
|
| 8 |
+
Classifier: Operating System :: OS Independent
|
| 9 |
+
Requires-Python: >=3.8
|
| 10 |
+
Description-Content-Type: text/markdown
|
| 11 |
+
Requires-Dist: requests>=2.28.0
|
| 12 |
+
Requires-Dist: pandas>=2.0.0
|
backend/PvDeepSetNet/src/PvDeepSetNet.egg-info/SOURCES.txt
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
pyproject.toml
|
| 2 |
+
src/DeepSets/__init__.py
|
| 3 |
+
src/DeepSets/build_tensors.py
|
| 4 |
+
src/DeepSets/model.py
|
| 5 |
+
src/DeepSets/preprocess.py
|
| 6 |
+
src/PvDeepSetNet.egg-info/PKG-INFO
|
| 7 |
+
src/PvDeepSetNet.egg-info/SOURCES.txt
|
| 8 |
+
src/PvDeepSetNet.egg-info/dependency_links.txt
|
| 9 |
+
src/PvDeepSetNet.egg-info/requires.txt
|
| 10 |
+
src/PvDeepSetNet.egg-info/top_level.txt
|
| 11 |
+
tests/tests_utils.py
|
backend/PvDeepSetNet/src/PvDeepSetNet.egg-info/dependency_links.txt
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
|
backend/PvDeepSetNet/src/PvDeepSetNet.egg-info/requires.txt
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
|
|
|
| 1 |
+
requests>=2.28.0
|
| 2 |
+
pandas>=2.0.0
|
backend/PvDeepSetNet/src/PvDeepSetNet.egg-info/top_level.txt
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
DeepSets
|
backend/PvDeepSetNet/tests/allele_dict.json
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
{"Chr01-1": 1, "Chr01-2": 2, "Chr02-2": 3, "Chr02-1": 4, "Chr03-3": 5, "Chr03-2": 6, "Chr05-6": 7, "Chr05-4": 8, "Chr07-1": 9, "Chr07-5": 10, "Chr08-3": 11, "Chr09-1": 12, "Chr09-2": 13, "Chr09-3": 14, "Chr10-2": 15, "Chr10-7": 16, "Chr11-1": 17, "Chr13-1": 18, "Chr13-4": 19, "Chr14-1": 20, "Chr03-1": 21, "Chr05-1": 22, "Chr08-1": 23, "Chr11-3": 24, "Chr11-2": 25, "Chr13-3": 26, "Chr14-3": 27, "Chr07-2": 28, "Chr08-2": 29, "Chr10-1": 30, "Chr14-10": 31, "Chr05-3": 32, "Chr10-4": 33, "Chr13-2": 34, "Chr01-5": 35, "Chr02-3": 36, "Chr05-2": 37, "Chr07-3": 38, "Chr07-4": 39, "Chr10-3": 40, "Chr13-6": 41, "Chr01-11": 42, "Chr05-7": 43, "Chr09-4": 44, "Chr14-15": 45, "Chr05-15": 46, "Chr01-3": 47, "Chr11-30": 48, "Chr11-6": 49, "Chr14-11": 50, "Chr03-4": 51, "Chr09-5": 52, "Chr09-7": 53, "Chr11-16": 54, "Chr13-7": 55, "Chr11-5": 56, "Chr07-8": 57, "Chr05-5": 58, "Chr11-12": 59, "Chr07-30": 60, "Chr10-5": 61, "Chr11-17": 62, "Chr09-8": 63, "Chr14-6": 64, "Chr11-22": 65, "Chr13-8": 66, "Chr14-4": 67, "Chr09-14": 68, "Chr11-9": 69, "Chr14-21": 70, "Chr08-4": 71, "Chr07-29": 72, "Chr09-13": 73, "Chr11-24": 74, "Chr10-6": 75, "Chr11-4": 76, "Chr13-5": 77, "Chr05-13": 78, "Chr13-12": 79, "Chr05-12": 80, "Chr14-9": 81, "Chr05-8": 82, "Chr14-22": 83, "Chr09-6": 84, "Chr05-9": 85, "Chr14-5": 86, "Chr13-24": 87, "Chr13-49": 88, "Chr11-37": 89, "Chr14-2": 90, "Chr01-4": 91, "Chr13-9": 92, "Chr13-11": 93, "Chr14-23": 94, "Chr03-17": 95, "Chr02-9": 96, "Chr14-12": 97, "Chr13-42": 98, "Chr14-7": 99, "Chr14-30": 100, "Chr09-12": 101, "Chr14-8": 102, "Chr13-41": 103, "Chr11-19": 104, "Chr08-8": 105, "Chr14-19": 106, "Chr11-18": 107, "Chr11-10": 108, "Chr14-17": 109, "Chr13-21": 110, "Chr08-7": 111, "Chr11-8": 112, "Chr13-40": 113, "Chr08-19": 114, "Chr11-29": 115, "Chr13-17": 116, "Chr11-14": 117, "Chr09-15": 118, "Chr13-13": 119, "Chr14-13": 120, "Chr13-46": 121, "Chr13-20": 122, "Chr01-9": 123, "Chr09-16": 124, "Chr14-16": 125, "Chr13-15": 126, "Chr14-14": 127, "Chr02-4": 128, "Chr07-6": 129, "Chr08-6": 130, "Chr02-5": 131, "Chr02-8": 132, "Chr03-5": 133, "Chr02-7": 134, "Chr02-6": 135, "Chr05-11": 136, "Chr07-10": 137, "Chr02-11": 138, "Chr03-6": 139, "Chr09-9": 140, "Chr07-9": 141, "Chr05-10": 142, "Chr07-11": 143}
|
backend/PvDeepSetNet/tests/temp.ipynb
ADDED
|
@@ -0,0 +1,496 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"cells": [
|
| 3 |
+
{
|
| 4 |
+
"cell_type": "markdown",
|
| 5 |
+
"id": "cbf23b97",
|
| 6 |
+
"metadata": {},
|
| 7 |
+
"source": [
|
| 8 |
+
"prepatring for model"
|
| 9 |
+
]
|
| 10 |
+
},
|
| 11 |
+
{
|
| 12 |
+
"cell_type": "code",
|
| 13 |
+
"execution_count": 1,
|
| 14 |
+
"id": "580a4347",
|
| 15 |
+
"metadata": {},
|
| 16 |
+
"outputs": [
|
| 17 |
+
{
|
| 18 |
+
"data": {
|
| 19 |
+
"text/html": [
|
| 20 |
+
"<div>\n",
|
| 21 |
+
"<style scoped>\n",
|
| 22 |
+
" .dataframe tbody tr th:only-of-type {\n",
|
| 23 |
+
" vertical-align: middle;\n",
|
| 24 |
+
" }\n",
|
| 25 |
+
"\n",
|
| 26 |
+
" .dataframe tbody tr th {\n",
|
| 27 |
+
" vertical-align: top;\n",
|
| 28 |
+
" }\n",
|
| 29 |
+
"\n",
|
| 30 |
+
" .dataframe thead th {\n",
|
| 31 |
+
" text-align: right;\n",
|
| 32 |
+
" }\n",
|
| 33 |
+
"</style>\n",
|
| 34 |
+
"<table border=\"1\" class=\"dataframe\">\n",
|
| 35 |
+
" <thead>\n",
|
| 36 |
+
" <tr style=\"text-align: right;\">\n",
|
| 37 |
+
" <th></th>\n",
|
| 38 |
+
" <th>patient_id</th>\n",
|
| 39 |
+
" <th>sample_id</th>\n",
|
| 40 |
+
" <th>episode</th>\n",
|
| 41 |
+
" <th>marker</th>\n",
|
| 42 |
+
" <th>allele</th>\n",
|
| 43 |
+
" <th>frequency</th>\n",
|
| 44 |
+
" <th>country</th>\n",
|
| 45 |
+
" <th>MOIs</th>\n",
|
| 46 |
+
" </tr>\n",
|
| 47 |
+
" </thead>\n",
|
| 48 |
+
" <tbody>\n",
|
| 49 |
+
" <tr>\n",
|
| 50 |
+
" <th>0</th>\n",
|
| 51 |
+
" <td>Sero-040</td>\n",
|
| 52 |
+
" <td>Sero-040-R01</td>\n",
|
| 53 |
+
" <td>1.0</td>\n",
|
| 54 |
+
" <td>Chr01</td>\n",
|
| 55 |
+
" <td>Chr01-1</td>\n",
|
| 56 |
+
" <td>0.531524</td>\n",
|
| 57 |
+
" <td>ethiopia</td>\n",
|
| 58 |
+
" <td>6</td>\n",
|
| 59 |
+
" </tr>\n",
|
| 60 |
+
" <tr>\n",
|
| 61 |
+
" <th>1</th>\n",
|
| 62 |
+
" <td>Sero-182</td>\n",
|
| 63 |
+
" <td>Sero-182-R12</td>\n",
|
| 64 |
+
" <td>3.0</td>\n",
|
| 65 |
+
" <td>Chr11</td>\n",
|
| 66 |
+
" <td>Chr11-2</td>\n",
|
| 67 |
+
" <td>0.149320</td>\n",
|
| 68 |
+
" <td>ethiopia</td>\n",
|
| 69 |
+
" <td>3</td>\n",
|
| 70 |
+
" </tr>\n",
|
| 71 |
+
" <tr>\n",
|
| 72 |
+
" <th>2</th>\n",
|
| 73 |
+
" <td>Sero-182</td>\n",
|
| 74 |
+
" <td>Sero-182-R12</td>\n",
|
| 75 |
+
" <td>3.0</td>\n",
|
| 76 |
+
" <td>Chr13</td>\n",
|
| 77 |
+
" <td>Chr13-1</td>\n",
|
| 78 |
+
" <td>0.729045</td>\n",
|
| 79 |
+
" <td>ethiopia</td>\n",
|
| 80 |
+
" <td>3</td>\n",
|
| 81 |
+
" </tr>\n",
|
| 82 |
+
" <tr>\n",
|
| 83 |
+
" <th>3</th>\n",
|
| 84 |
+
" <td>Sero-182</td>\n",
|
| 85 |
+
" <td>Sero-182-R12</td>\n",
|
| 86 |
+
" <td>3.0</td>\n",
|
| 87 |
+
" <td>Chr13</td>\n",
|
| 88 |
+
" <td>Chr13-2</td>\n",
|
| 89 |
+
" <td>0.129575</td>\n",
|
| 90 |
+
" <td>ethiopia</td>\n",
|
| 91 |
+
" <td>3</td>\n",
|
| 92 |
+
" </tr>\n",
|
| 93 |
+
" <tr>\n",
|
| 94 |
+
" <th>4</th>\n",
|
| 95 |
+
" <td>Sero-182</td>\n",
|
| 96 |
+
" <td>Sero-182-R12</td>\n",
|
| 97 |
+
" <td>3.0</td>\n",
|
| 98 |
+
" <td>Chr14</td>\n",
|
| 99 |
+
" <td>Chr14-1</td>\n",
|
| 100 |
+
" <td>0.931269</td>\n",
|
| 101 |
+
" <td>ethiopia</td>\n",
|
| 102 |
+
" <td>3</td>\n",
|
| 103 |
+
" </tr>\n",
|
| 104 |
+
" </tbody>\n",
|
| 105 |
+
"</table>\n",
|
| 106 |
+
"</div>"
|
| 107 |
+
],
|
| 108 |
+
"text/plain": [
|
| 109 |
+
" patient_id sample_id episode marker allele frequency country MOIs\n",
|
| 110 |
+
"0 Sero-040 Sero-040-R01 1.0 Chr01 Chr01-1 0.531524 ethiopia 6\n",
|
| 111 |
+
"1 Sero-182 Sero-182-R12 3.0 Chr11 Chr11-2 0.149320 ethiopia 3\n",
|
| 112 |
+
"2 Sero-182 Sero-182-R12 3.0 Chr13 Chr13-1 0.729045 ethiopia 3\n",
|
| 113 |
+
"3 Sero-182 Sero-182-R12 3.0 Chr13 Chr13-2 0.129575 ethiopia 3\n",
|
| 114 |
+
"4 Sero-182 Sero-182-R12 3.0 Chr14 Chr14-1 0.931269 ethiopia 3"
|
| 115 |
+
]
|
| 116 |
+
},
|
| 117 |
+
"execution_count": 1,
|
| 118 |
+
"metadata": {},
|
| 119 |
+
"output_type": "execute_result"
|
| 120 |
+
}
|
| 121 |
+
],
|
| 122 |
+
"source": [
|
| 123 |
+
"import pandas as pd\n",
|
| 124 |
+
"real_data = pd.read_csv('../datasets/pvAmpSeq_simulation_ready.csv')\n",
|
| 125 |
+
"real_data.head()"
|
| 126 |
+
]
|
| 127 |
+
},
|
| 128 |
+
{
|
| 129 |
+
"cell_type": "code",
|
| 130 |
+
"execution_count": 2,
|
| 131 |
+
"id": "5be7dab8",
|
| 132 |
+
"metadata": {},
|
| 133 |
+
"outputs": [],
|
| 134 |
+
"source": [
|
| 135 |
+
"from DeepSets import DataPreprocessor\n",
|
| 136 |
+
"data_pre = (\n",
|
| 137 |
+
" real_data\n",
|
| 138 |
+
" .pipe(DataPreprocessor.removing_single_episode_patients)\n",
|
| 139 |
+
" .pipe(DataPreprocessor.calculate_population_Allele_frequencies, population='country')\n",
|
| 140 |
+
" .pipe(DataPreprocessor.calculate_MOIs)\n",
|
| 141 |
+
" .pipe(DataPreprocessor.paired_episode_assigner)\n",
|
| 142 |
+
")"
|
| 143 |
+
]
|
| 144 |
+
},
|
| 145 |
+
{
|
| 146 |
+
"cell_type": "code",
|
| 147 |
+
"execution_count": null,
|
| 148 |
+
"id": "41c16479",
|
| 149 |
+
"metadata": {},
|
| 150 |
+
"outputs": [],
|
| 151 |
+
"source": []
|
| 152 |
+
},
|
| 153 |
+
{
|
| 154 |
+
"cell_type": "code",
|
| 155 |
+
"execution_count": 3,
|
| 156 |
+
"id": "9cb4f6ad",
|
| 157 |
+
"metadata": {},
|
| 158 |
+
"outputs": [],
|
| 159 |
+
"source": [
|
| 160 |
+
"import DeepSets\n",
|
| 161 |
+
"\n",
|
| 162 |
+
"deepest_tensor =DeepSets.build_deepsets_tensors(data_pre)"
|
| 163 |
+
]
|
| 164 |
+
},
|
| 165 |
+
{
|
| 166 |
+
"cell_type": "code",
|
| 167 |
+
"execution_count": 6,
|
| 168 |
+
"id": "cf9dea31",
|
| 169 |
+
"metadata": {},
|
| 170 |
+
"outputs": [
|
| 171 |
+
{
|
| 172 |
+
"data": {
|
| 173 |
+
"text/plain": [
|
| 174 |
+
"torch.Size([394, 11, 2, 5, 2])"
|
| 175 |
+
]
|
| 176 |
+
},
|
| 177 |
+
"execution_count": 6,
|
| 178 |
+
"metadata": {},
|
| 179 |
+
"output_type": "execute_result"
|
| 180 |
+
}
|
| 181 |
+
],
|
| 182 |
+
"source": [
|
| 183 |
+
"deepest_tensor['X_alleles'].shape"
|
| 184 |
+
]
|
| 185 |
+
},
|
| 186 |
+
{
|
| 187 |
+
"cell_type": "code",
|
| 188 |
+
"execution_count": 8,
|
| 189 |
+
"id": "afcf0fd7",
|
| 190 |
+
"metadata": {},
|
| 191 |
+
"outputs": [],
|
| 192 |
+
"source": [
|
| 193 |
+
"from torch.utils.data import DataLoader, TensorDataset\n",
|
| 194 |
+
"\n",
|
| 195 |
+
"# Option 1: TensorDataset\n",
|
| 196 |
+
"test_dataset = TensorDataset(\n",
|
| 197 |
+
" deepest_tensor[\"X_alleles\"],\n",
|
| 198 |
+
" deepest_tensor[\"allele_mask\"],\n",
|
| 199 |
+
" deepest_tensor[\"marker_mask\"],\n",
|
| 200 |
+
" deepest_tensor[\"priors\"],\n",
|
| 201 |
+
" deepest_tensor[\"MOI\"]\n",
|
| 202 |
+
")\n",
|
| 203 |
+
"\n",
|
| 204 |
+
"test_loader = DataLoader(test_dataset, batch_size=32, shuffle=False)\n"
|
| 205 |
+
]
|
| 206 |
+
},
|
| 207 |
+
{
|
| 208 |
+
"cell_type": "code",
|
| 209 |
+
"execution_count": 9,
|
| 210 |
+
"id": "dbed10c3",
|
| 211 |
+
"metadata": {},
|
| 212 |
+
"outputs": [],
|
| 213 |
+
"source": [
|
| 214 |
+
"import torch\n",
|
| 215 |
+
"import torch.nn as nn\n",
|
| 216 |
+
"import torch.nn.functional as F\n",
|
| 217 |
+
"\n",
|
| 218 |
+
"# =====================================================\n",
|
| 219 |
+
"# Deep Sets model for Pv3Rs surrogate\n",
|
| 220 |
+
"# =====================================================\n",
|
| 221 |
+
"class PvDeepSets(nn.Module):\n",
|
| 222 |
+
" def __init__(self,\n",
|
| 223 |
+
" n_alleles, # total number of unique alleles\n",
|
| 224 |
+
" allele_embed_dim=32,\n",
|
| 225 |
+
" marker_embed_dim=64,\n",
|
| 226 |
+
" pair_embed_dim=64,\n",
|
| 227 |
+
" hidden_dim=64,\n",
|
| 228 |
+
" n_classes=3):\n",
|
| 229 |
+
" super(PvDeepSets, self).__init__()\n",
|
| 230 |
+
"\n",
|
| 231 |
+
" # -------------------------------------------------\n",
|
| 232 |
+
" # 1️⃣ Allele embedding (allele ID + frequency)\n",
|
| 233 |
+
" # -------------------------------------------------\n",
|
| 234 |
+
" self.allele_embedding = nn.Embedding(n_alleles + 1, allele_embed_dim, padding_idx=0)\n",
|
| 235 |
+
" self.allele_mlp = nn.Sequential(\n",
|
| 236 |
+
" nn.Linear(allele_embed_dim + 1, allele_embed_dim), # +1 for frequency\n",
|
| 237 |
+
" nn.ReLU(),\n",
|
| 238 |
+
" nn.Linear(allele_embed_dim, allele_embed_dim),\n",
|
| 239 |
+
" nn.ReLU()\n",
|
| 240 |
+
" )\n",
|
| 241 |
+
"\n",
|
| 242 |
+
" # -------------------------------------------------\n",
|
| 243 |
+
" # 2️⃣ Marker-level MLP (after comparing episodes)\n",
|
| 244 |
+
" # -------------------------------------------------\n",
|
| 245 |
+
" self.marker_mlp = nn.Sequential(\n",
|
| 246 |
+
" nn.Linear(allele_embed_dim * 4, marker_embed_dim),\n",
|
| 247 |
+
" nn.ReLU(),\n",
|
| 248 |
+
" nn.Linear(marker_embed_dim, marker_embed_dim),\n",
|
| 249 |
+
" nn.ReLU()\n",
|
| 250 |
+
" )\n",
|
| 251 |
+
"\n",
|
| 252 |
+
" # -------------------------------------------------\n",
|
| 253 |
+
" # 3️⃣ Pair-level MLP (aggregate markers + priors + MOI)\n",
|
| 254 |
+
" # -------------------------------------------------\n",
|
| 255 |
+
" self.pair_mlp = nn.Sequential(\n",
|
| 256 |
+
" nn.Linear(marker_embed_dim + 3 + 2, pair_embed_dim), # +3 priors +2 MOI\n",
|
| 257 |
+
" nn.ReLU(),\n",
|
| 258 |
+
" nn.Linear(pair_embed_dim, hidden_dim),\n",
|
| 259 |
+
" nn.ReLU(),\n",
|
| 260 |
+
" nn.Linear(hidden_dim, n_classes)\n",
|
| 261 |
+
" )\n",
|
| 262 |
+
"\n",
|
| 263 |
+
" def forward(self, X_alleles, allele_mask, marker_mask, priors, MOI):\n",
|
| 264 |
+
" \"\"\"\n",
|
| 265 |
+
" X_alleles : (batch, M_max, 2, A_max, 2)\n",
|
| 266 |
+
" allele_mask: same shape as X_alleles[:,:,:,:,0]\n",
|
| 267 |
+
" marker_mask: (batch, M_max)\n",
|
| 268 |
+
" priors : (batch, 3)\n",
|
| 269 |
+
" MOI : (batch, 2)\n",
|
| 270 |
+
" \"\"\"\n",
|
| 271 |
+
" B, M, E, A, _ = X_alleles.shape\n",
|
| 272 |
+
"\n",
|
| 273 |
+
" # ---------------------------------------------\n",
|
| 274 |
+
" # 1️⃣ Embed alleles\n",
|
| 275 |
+
" # ---------------------------------------------\n",
|
| 276 |
+
" allele_ids = X_alleles[..., 0].long()\n",
|
| 277 |
+
" freqs = X_alleles[..., 1]\n",
|
| 278 |
+
"\n",
|
| 279 |
+
" allele_emb = self.allele_embedding(allele_ids) # (B,M,E,A,allele_embed_dim)\n",
|
| 280 |
+
" allele_input = torch.cat([allele_emb, freqs.unsqueeze(-1)], dim=-1)\n",
|
| 281 |
+
" allele_out = self.allele_mlp(allele_input) # (B,M,E,A,allele_embed_dim)\n",
|
| 282 |
+
"\n",
|
| 283 |
+
" # Apply allele mask\n",
|
| 284 |
+
" allele_out = allele_out * allele_mask.unsqueeze(-1)\n",
|
| 285 |
+
"\n",
|
| 286 |
+
" # ---------------------------------------------\n",
|
| 287 |
+
" # 2️⃣ Aggregate alleles → marker embedding per episode\n",
|
| 288 |
+
" # ---------------------------------------------\n",
|
| 289 |
+
" # Sum pooling over alleles\n",
|
| 290 |
+
" marker_ep_emb = allele_out.sum(dim=3) # (B,M,E,allele_embed_dim)\n",
|
| 291 |
+
"\n",
|
| 292 |
+
" # ---------------------------------------------\n",
|
| 293 |
+
" # 3️⃣ Compare episodes (ep1 vs ep2)\n",
|
| 294 |
+
" # ---------------------------------------------\n",
|
| 295 |
+
" ep1 = marker_ep_emb[:, :, 0, :]\n",
|
| 296 |
+
" ep2 = marker_ep_emb[:, :, 1, :]\n",
|
| 297 |
+
"\n",
|
| 298 |
+
" marker_pair = torch.cat([ep1, ep2, torch.abs(ep1 - ep2), ep1 * ep2], dim=-1) # (B,M,4*allele_embed_dim)\n",
|
| 299 |
+
"\n",
|
| 300 |
+
" # Apply marker-level MLP\n",
|
| 301 |
+
" marker_emb = self.marker_mlp(marker_pair) # (B,M,marker_embed_dim)\n",
|
| 302 |
+
"\n",
|
| 303 |
+
" # Masked sum over markers\n",
|
| 304 |
+
" marker_emb = marker_emb * marker_mask.unsqueeze(-1)\n",
|
| 305 |
+
" pair_emb = marker_emb.sum(dim=1) # (B, marker_embed_dim)\n",
|
| 306 |
+
"\n",
|
| 307 |
+
" # ---------------------------------------------\n",
|
| 308 |
+
" # 4️⃣ Concatenate priors + MOI\n",
|
| 309 |
+
" # ---------------------------------------------\n",
|
| 310 |
+
" pair_emb = torch.cat([pair_emb, priors, MOI], dim=-1) # (B, marker_dim+4)\n",
|
| 311 |
+
"\n",
|
| 312 |
+
" # ---------------------------------------------\n",
|
| 313 |
+
" # 5️⃣ Pair-level MLP → logits\n",
|
| 314 |
+
" # ---------------------------------------------\n",
|
| 315 |
+
" logits = self.pair_mlp(pair_emb) # (B, n_classes)\n",
|
| 316 |
+
" probs = F.softmax(logits, dim=-1)\n",
|
| 317 |
+
"\n",
|
| 318 |
+
" return probs\n"
|
| 319 |
+
]
|
| 320 |
+
},
|
| 321 |
+
{
|
| 322 |
+
"cell_type": "code",
|
| 323 |
+
"execution_count": 11,
|
| 324 |
+
"id": "50b46ac3",
|
| 325 |
+
"metadata": {},
|
| 326 |
+
"outputs": [],
|
| 327 |
+
"source": [
|
| 328 |
+
"import json\n",
|
| 329 |
+
"# reading allele dictionary\n",
|
| 330 |
+
"with open('allele_dict.json', 'r') as file:\n",
|
| 331 |
+
" allele_to_id = json.load(file)"
|
| 332 |
+
]
|
| 333 |
+
},
|
| 334 |
+
{
|
| 335 |
+
"cell_type": "code",
|
| 336 |
+
"execution_count": 12,
|
| 337 |
+
"id": "7c5be94c",
|
| 338 |
+
"metadata": {},
|
| 339 |
+
"outputs": [
|
| 340 |
+
{
|
| 341 |
+
"name": "stdout",
|
| 342 |
+
"output_type": "stream",
|
| 343 |
+
"text": [
|
| 344 |
+
"143\n"
|
| 345 |
+
]
|
| 346 |
+
},
|
| 347 |
+
{
|
| 348 |
+
"name": "stderr",
|
| 349 |
+
"output_type": "stream",
|
| 350 |
+
"text": [
|
| 351 |
+
"C:\\Users\\sinel\\AppData\\Local\\Temp\\ipykernel_38672\\1365319441.py:11: FutureWarning: You are using `torch.load` with `weights_only=False` (the current default value), which uses the default pickle module implicitly. It is possible to construct malicious pickle data which will execute arbitrary code during unpickling (See https://github.com/pytorch/pytorch/blob/main/SECURITY.md#untrusted-models for more details). In a future release, the default value for `weights_only` will be flipped to `True`. This limits the functions that could be executed during unpickling. Arbitrary objects will no longer be allowed to be loaded via this mode unless they are explicitly allowlisted by the user via `torch.serialization.add_safe_globals`. We recommend you start setting `weights_only=True` for any use case where you don't have full control of the loaded file. Please open an issue on GitHub for any issues related to this experimental feature.\n",
|
| 352 |
+
" model.load_state_dict(torch.load(\"../src/DeepSets/pv_deepsets_weights20260402.pth\", map_location=device))\n"
|
| 353 |
+
]
|
| 354 |
+
},
|
| 355 |
+
{
|
| 356 |
+
"data": {
|
| 357 |
+
"text/plain": [
|
| 358 |
+
"<All keys matched successfully>"
|
| 359 |
+
]
|
| 360 |
+
},
|
| 361 |
+
"execution_count": 12,
|
| 362 |
+
"metadata": {},
|
| 363 |
+
"output_type": "execute_result"
|
| 364 |
+
}
|
| 365 |
+
],
|
| 366 |
+
"source": [
|
| 367 |
+
"# 1. Define the device\n",
|
| 368 |
+
"device = torch.device(\"cpu\")\n",
|
| 369 |
+
"\n",
|
| 370 |
+
"# 2. Initialize the model with the same parameters used during training\n",
|
| 371 |
+
"# Make sure len(allele_to_id) matches the training setup!\n",
|
| 372 |
+
"n_alleles = len(allele_to_id) \n",
|
| 373 |
+
"model = PvDeepSets(n_alleles=n_alleles)\n",
|
| 374 |
+
"print(n_alleles)\n",
|
| 375 |
+
"# 3. Load the weights (state_dict)\n",
|
| 376 |
+
"# Replace \"pv_deepsets_weights.pth\" with your actual filename\n",
|
| 377 |
+
"model.load_state_dict(torch.load(\"../src/DeepSets/pv_deepsets_weights20260402.pth\", map_location=device))\n",
|
| 378 |
+
"\n"
|
| 379 |
+
]
|
| 380 |
+
},
|
| 381 |
+
{
|
| 382 |
+
"cell_type": "code",
|
| 383 |
+
"execution_count": 14,
|
| 384 |
+
"id": "581c0365",
|
| 385 |
+
"metadata": {},
|
| 386 |
+
"outputs": [
|
| 387 |
+
{
|
| 388 |
+
"name": "stdout",
|
| 389 |
+
"output_type": "stream",
|
| 390 |
+
"text": [
|
| 391 |
+
"Total undetermined samples removed: 1\n"
|
| 392 |
+
]
|
| 393 |
+
}
|
| 394 |
+
],
|
| 395 |
+
"source": [
|
| 396 |
+
"import numpy as np\n",
|
| 397 |
+
"import seaborn as sns\n",
|
| 398 |
+
"import matplotlib.pyplot as plt\n",
|
| 399 |
+
"from sklearn.metrics import r2_score\n",
|
| 400 |
+
"\n",
|
| 401 |
+
"import numpy as np\n",
|
| 402 |
+
"import seaborn as sns\n",
|
| 403 |
+
"import matplotlib.pyplot as plt\n",
|
| 404 |
+
"from sklearn.metrics import r2_score\n",
|
| 405 |
+
"\n",
|
| 406 |
+
"def get_model_results(model, dataloader, device, threshold=0.5):\n",
|
| 407 |
+
" model.eval()\n",
|
| 408 |
+
" all_predicted = []\n",
|
| 409 |
+
" y_pred_filtered = []\n",
|
| 410 |
+
" undetermined_count = 0\n",
|
| 411 |
+
"\n",
|
| 412 |
+
" with torch.no_grad():\n",
|
| 413 |
+
" for X_alleles, allele_mask, marker_mask, priors, MOI in dataloader:\n",
|
| 414 |
+
" # ... (your existing GPU transfer code) ...\n",
|
| 415 |
+
" y_pred = model(X_alleles, allele_mask, marker_mask, priors, MOI)\n",
|
| 416 |
+
" \n",
|
| 417 |
+
" # Apply Softmax if your model doesn't already output probabilities\n",
|
| 418 |
+
" # probs = torch.softmax(y_pred, dim=1) \n",
|
| 419 |
+
" probs = y_pred \n",
|
| 420 |
+
"\n",
|
| 421 |
+
" # Get max probabilities and their indices\n",
|
| 422 |
+
" max_probs, preds = torch.max(probs, dim=1)\n",
|
| 423 |
+
"\n",
|
| 424 |
+
" for i in range(len(max_probs)):\n",
|
| 425 |
+
" if max_probs[i] >= threshold:\n",
|
| 426 |
+
" y_pred_filtered.append(preds[i].item())\n",
|
| 427 |
+
" else:\n",
|
| 428 |
+
" undetermined_count += 1\n",
|
| 429 |
+
"\n",
|
| 430 |
+
" all_predicted.append(y_pred.cpu().numpy())\n",
|
| 431 |
+
"\n",
|
| 432 |
+
" print(f\"Total undetermined samples removed: {undetermined_count}\")\n",
|
| 433 |
+
" return np.vstack(all_predicted), y_pred_filtered\n",
|
| 434 |
+
"\n",
|
| 435 |
+
"predicted_probs, y_pred_hard = get_model_results(model, test_loader, device)\n",
|
| 436 |
+
"\n",
|
| 437 |
+
"\n"
|
| 438 |
+
]
|
| 439 |
+
},
|
| 440 |
+
{
|
| 441 |
+
"cell_type": "code",
|
| 442 |
+
"execution_count": 17,
|
| 443 |
+
"id": "8f6bda0c",
|
| 444 |
+
"metadata": {},
|
| 445 |
+
"outputs": [
|
| 446 |
+
{
|
| 447 |
+
"data": {
|
| 448 |
+
"text/plain": [
|
| 449 |
+
"np.float32(1.0)"
|
| 450 |
+
]
|
| 451 |
+
},
|
| 452 |
+
"execution_count": 17,
|
| 453 |
+
"metadata": {},
|
| 454 |
+
"output_type": "execute_result"
|
| 455 |
+
}
|
| 456 |
+
],
|
| 457 |
+
"source": [
|
| 458 |
+
"predicted_probs[1].sum()"
|
| 459 |
+
]
|
| 460 |
+
},
|
| 461 |
+
{
|
| 462 |
+
"cell_type": "code",
|
| 463 |
+
"execution_count": null,
|
| 464 |
+
"id": "e6222332",
|
| 465 |
+
"metadata": {},
|
| 466 |
+
"outputs": [],
|
| 467 |
+
"source": [
|
| 468 |
+
"# Step 1: removing patients with only one episode\n",
|
| 469 |
+
"# Step 2: make all possible pair (including making episode 1&2)\n",
|
| 470 |
+
"# step 3: Calculate MOIs\n",
|
| 471 |
+
"# step 4: Calculate Afreq"
|
| 472 |
+
]
|
| 473 |
+
}
|
| 474 |
+
],
|
| 475 |
+
"metadata": {
|
| 476 |
+
"kernelspec": {
|
| 477 |
+
"display_name": "PvRecNet",
|
| 478 |
+
"language": "python",
|
| 479 |
+
"name": "python3"
|
| 480 |
+
},
|
| 481 |
+
"language_info": {
|
| 482 |
+
"codemirror_mode": {
|
| 483 |
+
"name": "ipython",
|
| 484 |
+
"version": 3
|
| 485 |
+
},
|
| 486 |
+
"file_extension": ".py",
|
| 487 |
+
"mimetype": "text/x-python",
|
| 488 |
+
"name": "python",
|
| 489 |
+
"nbconvert_exporter": "python",
|
| 490 |
+
"pygments_lexer": "ipython3",
|
| 491 |
+
"version": "3.10.20"
|
| 492 |
+
}
|
| 493 |
+
},
|
| 494 |
+
"nbformat": 4,
|
| 495 |
+
"nbformat_minor": 5
|
| 496 |
+
}
|
components/layouts.py → backend/PvDeepSetNet/tests/tests_utils.py
RENAMED
|
File without changes
|
backend/__pycache__/main.cpython-312.pyc
ADDED
|
Binary file (1.05 kB). View file
|
|
|
backend/main.py
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# backend/main.py
|
| 2 |
+
from fastapi import FastAPI, UploadFile, File
|
| 3 |
+
import uvicorn
|
| 4 |
+
|
| 5 |
+
app = FastAPI()
|
| 6 |
+
|
| 7 |
+
@app.post("/upload-data")
|
| 8 |
+
async def upload_data(file: UploadFile = File(...)):
|
| 9 |
+
# Your logic to save file and trigger preprocessing
|
| 10 |
+
return {"dataset_id": "test_id_123"}
|
| 11 |
+
|
| 12 |
+
@app.post("/predict")
|
| 13 |
+
async def predict(data: dict):
|
| 14 |
+
# Your Deep Sets Model Inference
|
| 15 |
+
return {
|
| 16 |
+
"prediction": "Relapse",
|
| 17 |
+
"confidence": 0.85,
|
| 18 |
+
"probabilities": {"C": 0.1, "L": 0.85, "I": 0.05}
|
| 19 |
+
}
|
| 20 |
+
|
| 21 |
+
# Add your MOI and Allele Frequency endpoints here...
|
| 22 |
+
|
| 23 |
+
if __name__ == "__main__":
|
| 24 |
+
uvicorn.run(app, host="127.0.0.1", port=8000)
|
frontend/app.py
ADDED
|
@@ -0,0 +1,267 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import dash
|
| 2 |
+
from dash import dcc, html, Input, Output, State, dash_table
|
| 3 |
+
import dash_bootstrap_components as dbc
|
| 4 |
+
import plotly.express as px
|
| 5 |
+
import pandas as pd
|
| 6 |
+
import base64
|
| 7 |
+
import io
|
| 8 |
+
|
| 9 |
+
# Import your custom API service
|
| 10 |
+
from services.api import PvRecNetAPI
|
| 11 |
+
|
| 12 |
+
# 1. Initialize the Dash App
|
| 13 |
+
app = dash.Dash(
|
| 14 |
+
__name__,
|
| 15 |
+
external_stylesheets=[dbc.themes.FLATLY],
|
| 16 |
+
title="PvRecNet Malaria System"
|
| 17 |
+
)
|
| 18 |
+
|
| 19 |
+
# 2. Define the Layout
|
| 20 |
+
app.layout = dbc.Container([
|
| 21 |
+
# Browser-side storage for the dataset ID
|
| 22 |
+
dcc.Store(id='dataset-id-store', storage_type='session'),
|
| 23 |
+
|
| 24 |
+
# Header
|
| 25 |
+
dbc.Row(dbc.Col(html.H1("PvRecNet: Malaria Recurrence Classifier", className="text-center my-4"), width=12)),
|
| 26 |
+
|
| 27 |
+
dbc.Tabs([
|
| 28 |
+
# --- TAB 1: PREDICTION WORKFLOW ---
|
| 29 |
+
dbc.Tab(label="Prediction Workflow", children=[
|
| 30 |
+
dbc.Row([
|
| 31 |
+
# Left Column: Controls
|
| 32 |
+
dbc.Col([
|
| 33 |
+
dbc.Card([
|
| 34 |
+
dbc.CardHeader(html.B("Step 1: Upload & Action")),
|
| 35 |
+
dbc.CardBody([
|
| 36 |
+
dcc.Upload(
|
| 37 |
+
id='upload-data',
|
| 38 |
+
children=html.Div(['Drag/Drop or ', html.A('Select CSV')]),
|
| 39 |
+
style={
|
| 40 |
+
'width': '100%', 'height': '60px', 'lineHeight': '60px',
|
| 41 |
+
'borderWidth': '1px', 'borderStyle': 'dashed',
|
| 42 |
+
'borderRadius': '5px', 'textAlign': 'center'
|
| 43 |
+
}
|
| 44 |
+
),
|
| 45 |
+
html.Div(id='upload-status', className="mt-2"),
|
| 46 |
+
html.Hr(),
|
| 47 |
+
dbc.Button(
|
| 48 |
+
"Run Deep Sets Prediction",
|
| 49 |
+
id="predict-btn",
|
| 50 |
+
color="primary",
|
| 51 |
+
disabled=True,
|
| 52 |
+
className="w-100"
|
| 53 |
+
),
|
| 54 |
+
html.Small("Note: Prediction uses the data currently in the table.",
|
| 55 |
+
className="text-muted mt-2 d-block")
|
| 56 |
+
])
|
| 57 |
+
])
|
| 58 |
+
], md=4),
|
| 59 |
+
|
| 60 |
+
# Right Column: Interactive Data Preview
|
| 61 |
+
dbc.Col([
|
| 62 |
+
dbc.Card([
|
| 63 |
+
dbc.CardHeader(html.B("Step 2: Interactive Data Workbench")),
|
| 64 |
+
dbc.CardBody([
|
| 65 |
+
dcc.Loading(id="loading-preview", children=[
|
| 66 |
+
dash_table.DataTable(
|
| 67 |
+
id='preview-table',
|
| 68 |
+
columns=[], # <--- CRITICAL: Initialize as empty list
|
| 69 |
+
data=[], # <--- CRITICAL: Initialize as empty list
|
| 70 |
+
|
| 71 |
+
# Interactivity
|
| 72 |
+
editable=True,
|
| 73 |
+
# filter_action="native",
|
| 74 |
+
sort_action="native",
|
| 75 |
+
sort_mode="multi",
|
| 76 |
+
row_deletable=True,
|
| 77 |
+
|
| 78 |
+
# Pagination & Scrolling
|
| 79 |
+
page_action="native",
|
| 80 |
+
page_current=0,
|
| 81 |
+
page_size=15,
|
| 82 |
+
fixed_rows={'headers': True},
|
| 83 |
+
|
| 84 |
+
style_table={
|
| 85 |
+
'height': '450px',
|
| 86 |
+
'overflowY': 'auto',
|
| 87 |
+
'overflowX': 'auto',
|
| 88 |
+
},
|
| 89 |
+
|
| 90 |
+
# Visual Styling
|
| 91 |
+
style_header={
|
| 92 |
+
'backgroundColor': '#f8f9fa',
|
| 93 |
+
'fontWeight': 'bold',
|
| 94 |
+
'border': '1px solid #dee2e6'
|
| 95 |
+
},
|
| 96 |
+
style_cell={
|
| 97 |
+
'textAlign': 'left',
|
| 98 |
+
'font-family': 'Segoe UI, Tahoma, Geneva, Verdana, sans-serif',
|
| 99 |
+
'minWidth': '120px', 'width': '150px', 'maxWidth': '300px',
|
| 100 |
+
'padding': '8px'
|
| 101 |
+
},
|
| 102 |
+
style_data_conditional=[
|
| 103 |
+
{'if': {'row_index': 'odd'}, 'backgroundColor': 'rgb(250, 250, 250)'},
|
| 104 |
+
{'if': {'state': 'active'}, 'backgroundColor': 'rgba(0, 123, 255, 0.1)', 'border': '1px solid #007bff'}
|
| 105 |
+
]
|
| 106 |
+
)
|
| 107 |
+
])
|
| 108 |
+
])
|
| 109 |
+
])
|
| 110 |
+
], md=8)
|
| 111 |
+
], className="mt-4"),
|
| 112 |
+
|
| 113 |
+
# Bottom Row: Inference Results
|
| 114 |
+
dbc.Row([
|
| 115 |
+
dbc.Col([
|
| 116 |
+
dbc.Card([
|
| 117 |
+
dbc.CardHeader(html.B("Step 3: Model Output")),
|
| 118 |
+
dbc.CardBody(dcc.Loading(id="prediction-output"))
|
| 119 |
+
], className="mt-4 mb-5")
|
| 120 |
+
], width=12)
|
| 121 |
+
])
|
| 122 |
+
]),
|
| 123 |
+
|
| 124 |
+
# --- TAB 2: ANALYTICS TOOLS ---
|
| 125 |
+
dbc.Tab(label="Analytics Tools", children=[
|
| 126 |
+
dbc.Row([
|
| 127 |
+
dbc.Col([
|
| 128 |
+
dbc.Card([
|
| 129 |
+
dbc.CardHeader(html.B("Genomic Analytics")),
|
| 130 |
+
dbc.CardBody([
|
| 131 |
+
html.P("These tools operate on the uploaded dataset ID independently of the classifier."),
|
| 132 |
+
dbc.Button("Compute MOI", id="moi-btn", color="info", className="me-2"),
|
| 133 |
+
dbc.Button("Compute Allele Freq", id="freq-btn", color="secondary"),
|
| 134 |
+
html.Hr(),
|
| 135 |
+
dcc.Loading(id="analytics-output")
|
| 136 |
+
])
|
| 137 |
+
])
|
| 138 |
+
], md=12)
|
| 139 |
+
], className="mt-4")
|
| 140 |
+
])
|
| 141 |
+
])
|
| 142 |
+
], fluid=True)
|
| 143 |
+
|
| 144 |
+
# --- CALLBACKS ---
|
| 145 |
+
|
| 146 |
+
# 1. Handle File Upload, API Registration, and Table Population
|
| 147 |
+
@app.callback(
|
| 148 |
+
Output('dataset-id-store', 'data'),
|
| 149 |
+
Output('upload-status', 'children'),
|
| 150 |
+
Output('predict-btn', 'disabled'),
|
| 151 |
+
Output('preview-table', 'data'),
|
| 152 |
+
Output('preview-table', 'columns'),
|
| 153 |
+
Output('preview-table', 'fixed_rows'), # NEW: Dynamic fixed rows
|
| 154 |
+
Input('upload-data', 'contents'),
|
| 155 |
+
State('upload-data', 'filename'),
|
| 156 |
+
prevent_initial_call=True
|
| 157 |
+
)
|
| 158 |
+
def handle_upload_and_preview(contents, filename):
|
| 159 |
+
if not contents:
|
| 160 |
+
return dash.no_update
|
| 161 |
+
|
| 162 |
+
try:
|
| 163 |
+
content_type, content_string = contents.split(',')
|
| 164 |
+
decoded = base64.b64decode(content_string)
|
| 165 |
+
df = pd.read_csv(io.BytesIO(decoded))
|
| 166 |
+
|
| 167 |
+
preview_cols = []
|
| 168 |
+
for i in df.columns:
|
| 169 |
+
column_type = 'numeric' if pd.api.types.is_numeric_dtype(df[i]) else 'text'
|
| 170 |
+
preview_cols.append({"name": i, "id": i, "editable": True, "type": column_type})
|
| 171 |
+
|
| 172 |
+
api_response = PvRecNetAPI.upload_dataset(decoded, filename)
|
| 173 |
+
dataset_id = api_response.get("dataset_id")
|
| 174 |
+
|
| 175 |
+
# We now return {'headers': True} as the last argument
|
| 176 |
+
return dataset_id, dbc.Alert(f"Loaded {filename}", color="success"), False, \
|
| 177 |
+
df.head(200).to_dict('records'), preview_cols, {'headers': True}
|
| 178 |
+
|
| 179 |
+
except Exception as e:
|
| 180 |
+
# Return {'headers': False} on error to keep it from crashing
|
| 181 |
+
return None, dbc.Alert(f"Error: {str(e)}", color="danger"), True, [], [], {'headers': False}
|
| 182 |
+
|
| 183 |
+
# 2. Run Model Prediction
|
| 184 |
+
@app.callback(
|
| 185 |
+
Output('prediction-output', 'children'),
|
| 186 |
+
Input('predict-btn', 'n_clicks'),
|
| 187 |
+
State('dataset-id-store', 'data'),
|
| 188 |
+
prevent_initial_call=True
|
| 189 |
+
)
|
| 190 |
+
def run_model_inference(n_clicks, dataset_id):
|
| 191 |
+
if not dataset_id:
|
| 192 |
+
return dbc.Alert("No dataset found. Please upload a file first.", color="warning")
|
| 193 |
+
|
| 194 |
+
try:
|
| 195 |
+
# Call Backend API
|
| 196 |
+
res = PvRecNetAPI.run_prediction(dataset_id)
|
| 197 |
+
|
| 198 |
+
# Plotly Bar Chart for Probability
|
| 199 |
+
probs = res.get('probabilities', {})
|
| 200 |
+
fig = px.bar(
|
| 201 |
+
x=list(probs.keys()),
|
| 202 |
+
y=list(probs.values()),
|
| 203 |
+
labels={'x': 'Class', 'y': 'Probability'},
|
| 204 |
+
title="Deep Sets Probability Distribution",
|
| 205 |
+
color=list(probs.keys()),
|
| 206 |
+
template="plotly_white"
|
| 207 |
+
)
|
| 208 |
+
|
| 209 |
+
return html.Div([
|
| 210 |
+
dbc.Row([
|
| 211 |
+
dbc.Col([
|
| 212 |
+
html.Div([
|
| 213 |
+
html.H4("Classification Result"),
|
| 214 |
+
html.H2(res['prediction'], className="text-primary"),
|
| 215 |
+
html.P(f"Model Confidence: {res['confidence']:.2%}")
|
| 216 |
+
], className="p-3 border rounded bg-light")
|
| 217 |
+
], md=4),
|
| 218 |
+
dbc.Col([
|
| 219 |
+
dcc.Graph(figure=fig, style={'height': '300px'})
|
| 220 |
+
], md=8)
|
| 221 |
+
])
|
| 222 |
+
])
|
| 223 |
+
except Exception as e:
|
| 224 |
+
return dbc.Alert(f"Inference Failed: {str(e)}", color="danger")
|
| 225 |
+
|
| 226 |
+
# 3. Analytics Tools (MOI & Allele Frequency)
|
| 227 |
+
@app.callback(
|
| 228 |
+
Output('analytics-output', 'children'),
|
| 229 |
+
Input('moi-btn', 'n_clicks'),
|
| 230 |
+
Input('freq-btn', 'n_clicks'),
|
| 231 |
+
State('dataset-id-store', 'data'),
|
| 232 |
+
prevent_initial_call=True
|
| 233 |
+
)
|
| 234 |
+
def handle_analytics(moi_n, freq_n, dataset_id):
|
| 235 |
+
if not dataset_id:
|
| 236 |
+
return dbc.Alert("No data available for analytics. Go to Prediction tab to upload.", color="warning")
|
| 237 |
+
|
| 238 |
+
ctx = dash.callback_context
|
| 239 |
+
button_id = ctx.triggered[0]['prop_id'].split('.')[0]
|
| 240 |
+
|
| 241 |
+
try:
|
| 242 |
+
if button_id == "moi-btn":
|
| 243 |
+
res = PvRecNetAPI.get_moi(dataset_id)
|
| 244 |
+
return html.Div([
|
| 245 |
+
html.H5("Multiplicity of Infection (MOI) Table"),
|
| 246 |
+
dash_table.DataTable(
|
| 247 |
+
data=res,
|
| 248 |
+
page_size=10,
|
| 249 |
+
filter_action="native",
|
| 250 |
+
sort_action="native",
|
| 251 |
+
style_table={'overflowX': 'auto'}
|
| 252 |
+
)
|
| 253 |
+
])
|
| 254 |
+
|
| 255 |
+
elif button_id == "freq-btn":
|
| 256 |
+
res = PvRecNetAPI.get_allele_freq(dataset_id)
|
| 257 |
+
# Assuming res is a list of {'allele': str, 'frequency': float}
|
| 258 |
+
fig = px.pie(res, names='allele', values='frequency', title="Allele Frequency Distribution")
|
| 259 |
+
return dcc.Graph(figure=fig)
|
| 260 |
+
|
| 261 |
+
except Exception as e:
|
| 262 |
+
return dbc.Alert(f"Analytical Tool Error: {str(e)}", color="danger")
|
| 263 |
+
|
| 264 |
+
# 4. Main Entry Point
|
| 265 |
+
if __name__ == '__main__':
|
| 266 |
+
# Using app.run() for modern Dash compatibility
|
| 267 |
+
app.run(debug=True, port=8050)
|
{services → frontend/components}/__init__.py
RENAMED
|
File without changes
|
frontend/components/layouts.py
ADDED
|
File without changes
|
frontend/services/__init__.py
ADDED
|
File without changes
|
{services → frontend/services}/__pycache__/__init__.cpython-310.pyc
RENAMED
|
File without changes
|
{services → frontend/services}/__pycache__/__init__.cpython-312.pyc
RENAMED
|
File without changes
|
{services → frontend/services}/__pycache__/api.cpython-310.pyc
RENAMED
|
File without changes
|
{services → frontend/services}/__pycache__/api.cpython-312.pyc
RENAMED
|
File without changes
|
{services → frontend/services}/api.py
RENAMED
|
File without changes
|