adding approximate joint probabilities for paired estimation
Browse files
backend/PvDeepSetNet/src/DeepSets/Model_result.py
CHANGED
|
@@ -77,6 +77,80 @@ class PvDeepSet_model:
|
|
| 77 |
|
| 78 |
return pred_stack
|
| 79 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 80 |
@staticmethod
|
| 81 |
def run_prediction(meta_df,
|
| 82 |
pair_id,
|
|
@@ -101,8 +175,8 @@ class PvDeepSet_model:
|
|
| 101 |
results_df.insert(0, 'pair_id', pair_id)
|
| 102 |
|
| 103 |
# 4. Hardclass Classification with Threshold Logic
|
| 104 |
-
def classify_row(row):
|
| 105 |
-
probs = [row[
|
| 106 |
max_p = max(probs)
|
| 107 |
|
| 108 |
# Check if the highest probability meets the 0.5 threshold
|
|
@@ -176,32 +250,32 @@ class PvDeepSet_model:
|
|
| 176 |
return fig
|
| 177 |
|
| 178 |
|
| 179 |
-
def plot_probability_dist(df):
|
| 180 |
|
| 181 |
df = df.copy()
|
| 182 |
-
df = df[
|
| 183 |
|
| 184 |
# Grouped and sorted blocks
|
| 185 |
-
df_C = df[df.predicted_class == 'C'].sort_values(
|
| 186 |
-
df_L = df[df.predicted_class == 'L'].sort_values(
|
| 187 |
-
df_I = df[df.predicted_class == 'I'].sort_values(
|
| 188 |
|
| 189 |
df_sorted = pd.concat([df_C, df_L, df_I], ignore_index=True)
|
| 190 |
|
| 191 |
df_long = df_sorted.melt(
|
| 192 |
-
id_vars=[
|
| 193 |
-
value_vars=[
|
| 194 |
var_name='Probability_Type',
|
| 195 |
value_name='Probability'
|
| 196 |
)
|
| 197 |
|
| 198 |
fig = px.bar(
|
| 199 |
df_long,
|
| 200 |
-
x=
|
| 201 |
y="Probability",
|
| 202 |
color="Probability_Type",
|
| 203 |
color_discrete_sequence=['#ff4d00', '#e6b400', '#1fb3c4'],
|
| 204 |
-
category_orders={
|
| 205 |
template="plotly_white" # Sets white background and clean gridlines
|
| 206 |
)
|
| 207 |
|
|
@@ -248,9 +322,16 @@ class PvDeepSet_model:
|
|
| 248 |
|
| 249 |
results_df = results_df.merge(meta_df, left_on='pair_id', right_on='sample_id_paired', how='inner')
|
| 250 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 251 |
columns = ['pair_id', 'patient_id', 'true_episode', 'prob_C', 'prob_L', 'prob_I', 'predicted_class']
|
| 252 |
results = {
|
| 253 |
-
'results_table':
|
| 254 |
'donut_plot': donut_plot,
|
| 255 |
'distribution_plot': probability_dist_plot
|
| 256 |
}
|
|
|
|
| 77 |
|
| 78 |
return pred_stack
|
| 79 |
|
| 80 |
+
@staticmethod
|
| 81 |
+
def calculate_approx_marginals(df):
|
| 82 |
+
"""
|
| 83 |
+
Python implementation of the Pv3Rs approx-joint marginalization logic.
|
| 84 |
+
Assumes df contains: patient_id, episode_i, episode_j, post_C, post_L, post_I
|
| 85 |
+
"""
|
| 86 |
+
# 1. Identify the unique episodes for this patient (sorted)
|
| 87 |
+
# We assume 'episode' in your sample refers to the current episode (j)
|
| 88 |
+
# and we need to identify the source episode (i).
|
| 89 |
+
# For this example, let's derive i and j from your structure.
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
def assign_source_episodes(df):
|
| 93 |
+
df = df.sort_values(['patient_id', 'true_episode']).copy()
|
| 94 |
+
|
| 95 |
+
# We create a counter that resets for every new 'true_episode'
|
| 96 |
+
# This identifies if the row is comparing against the 1st, 2nd, or 3rd previous episode
|
| 97 |
+
df['pair_source'] = df.groupby(['patient_id', 'true_episode']).cumcount() + 1
|
| 98 |
+
return df.sort_values('pair_id')
|
| 99 |
+
|
| 100 |
+
df = assign_source_episodes(df)
|
| 101 |
+
|
| 102 |
+
results = []
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
for pid, group in df.groupby('patient_id'):
|
| 106 |
+
# Get unique episodes in chronological order
|
| 107 |
+
# Based on your data, episodes are 1, 2, 4, 5, 6...
|
| 108 |
+
episodes = sorted(group['true_episode'].unique())
|
| 109 |
+
n_epi = len(episodes)
|
| 110 |
+
|
| 111 |
+
# We start calculating from the first recurrence (index 1)
|
| 112 |
+
for idx in range(1, n_epi):
|
| 113 |
+
curr_epi = episodes[idx]
|
| 114 |
+
prev_epi = episodes[idx-1]
|
| 115 |
+
|
| 116 |
+
# --- CALCULATE C (Recrudescence) ---
|
| 117 |
+
# Rule: Only look at the immediate predecessor
|
| 118 |
+
c_row = group[(group['true_episode'] == curr_epi) & (group['pair_source'] == prev_epi)]
|
| 119 |
+
# If your data doesn't have 'pair_source', we look for the specific pair
|
| 120 |
+
# where j = curr_epi and i = prev_epi
|
| 121 |
+
C_prob = c_row['prob_C'].iloc[0] if not c_row.empty else 0.0
|
| 122 |
+
|
| 123 |
+
# --- CALCULATE L (Relapse) ---
|
| 124 |
+
# Rule: Max( L / (1-C) ) across all previous episodes, then scale by (1-C_total)
|
| 125 |
+
|
| 126 |
+
# Get all pairs where 'episode' is our current episode
|
| 127 |
+
all_prev_pairs = group[group['true_episode'] == curr_epi]
|
| 128 |
+
|
| 129 |
+
# Calculate the 'relapse share': L / (1 - C)
|
| 130 |
+
# Use small epsilon to avoid division by zero
|
| 131 |
+
shares = all_prev_pairs['prob_L'] / (1 - all_prev_pairs['prob_C'] + 1e-9)
|
| 132 |
+
max_share = shares.max()
|
| 133 |
+
|
| 134 |
+
L_prob = max_share * (1 - C_prob)
|
| 135 |
+
|
| 136 |
+
# --- CALCULATE I (Reinfection) ---
|
| 137 |
+
# Rule: The remainder
|
| 138 |
+
I_prob = 1 - (C_prob + L_prob)
|
| 139 |
+
|
| 140 |
+
results.append({
|
| 141 |
+
'patient_id': pid,
|
| 142 |
+
'episode': curr_epi,
|
| 143 |
+
'C_marg': C_prob,
|
| 144 |
+
'L_marg': L_prob,
|
| 145 |
+
'I_marg': I_prob
|
| 146 |
+
})
|
| 147 |
+
marg_result = pd.DataFrame(results)
|
| 148 |
+
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
|
| 152 |
+
return marg_result
|
| 153 |
+
|
| 154 |
@staticmethod
|
| 155 |
def run_prediction(meta_df,
|
| 156 |
pair_id,
|
|
|
|
| 175 |
results_df.insert(0, 'pair_id', pair_id)
|
| 176 |
|
| 177 |
# 4. Hardclass Classification with Threshold Logic
|
| 178 |
+
def classify_row(row, cols=['prob_C', 'prob_L', 'prob_I']):
|
| 179 |
+
probs = [row[cols[0]], row[cols[1]], row[cols[2]]]
|
| 180 |
max_p = max(probs)
|
| 181 |
|
| 182 |
# Check if the highest probability meets the 0.5 threshold
|
|
|
|
| 250 |
return fig
|
| 251 |
|
| 252 |
|
| 253 |
+
def plot_probability_dist(df, cols=['pair_id', 'prob_C', 'prob_L','prob_I','predicted_class']):
|
| 254 |
|
| 255 |
df = df.copy()
|
| 256 |
+
df = df[cols].drop_duplicates().reset_index(drop=True)
|
| 257 |
|
| 258 |
# Grouped and sorted blocks
|
| 259 |
+
df_C = df[df.predicted_class == 'C'].sort_values(cols[1], ascending=False).reset_index(drop=True)
|
| 260 |
+
df_L = df[df.predicted_class == 'L'].sort_values(cols[2], ascending=False).reset_index(drop=True)
|
| 261 |
+
df_I = df[df.predicted_class == 'I'].sort_values(cols[3], ascending=False).reset_index(drop=True)
|
| 262 |
|
| 263 |
df_sorted = pd.concat([df_C, df_L, df_I], ignore_index=True)
|
| 264 |
|
| 265 |
df_long = df_sorted.melt(
|
| 266 |
+
id_vars=cols[0],
|
| 267 |
+
value_vars=cols[1:4],
|
| 268 |
var_name='Probability_Type',
|
| 269 |
value_name='Probability'
|
| 270 |
)
|
| 271 |
|
| 272 |
fig = px.bar(
|
| 273 |
df_long,
|
| 274 |
+
x=cols[0],
|
| 275 |
y="Probability",
|
| 276 |
color="Probability_Type",
|
| 277 |
color_discrete_sequence=['#ff4d00', '#e6b400', '#1fb3c4'],
|
| 278 |
+
category_orders={cols[0]: df_sorted[cols[0]].tolist()},
|
| 279 |
template="plotly_white" # Sets white background and clean gridlines
|
| 280 |
)
|
| 281 |
|
|
|
|
| 322 |
|
| 323 |
results_df = results_df.merge(meta_df, left_on='pair_id', right_on='sample_id_paired', how='inner')
|
| 324 |
|
| 325 |
+
# get marginal probabilities
|
| 326 |
+
marginal_df = PvDeepSet_model.calculate_approx_marginals(results_df[['pair_id', 'patient_id', 'true_episode', 'prob_C', 'prob_L', 'prob_I']])
|
| 327 |
+
marginal_df['predicted_class'] = marginal_df.apply(classify_row, axis=1, cols=['C_marg', 'L_marg', 'I_marg'])
|
| 328 |
+
donut_plot = plot_donut_count(marginal_df)
|
| 329 |
+
marginal_df['patient_id_epi'] = marginal_df['patient_id'] + "_" + marginal_df['episode'].astype(int).astype('str')
|
| 330 |
+
probability_dist_plot = plot_probability_dist(marginal_df, cols=['patient_id_epi', 'C_marg', 'L_marg','I_marg','predicted_class'])
|
| 331 |
+
|
| 332 |
columns = ['pair_id', 'patient_id', 'true_episode', 'prob_C', 'prob_L', 'prob_I', 'predicted_class']
|
| 333 |
results = {
|
| 334 |
+
'results_table':marginal_df,
|
| 335 |
'donut_plot': donut_plot,
|
| 336 |
'distribution_plot': probability_dist_plot
|
| 337 |
}
|
backend/PvDeepSetNet/src/DeepSets/__pycache__/Model_result.cpython-310.pyc
CHANGED
|
Binary files a/backend/PvDeepSetNet/src/DeepSets/__pycache__/Model_result.cpython-310.pyc and b/backend/PvDeepSetNet/src/DeepSets/__pycache__/Model_result.cpython-310.pyc differ
|
|
|
frontend/app.py
CHANGED
|
@@ -11,7 +11,7 @@ from services.api import PvRecNetAPI
|
|
| 11 |
app = dash.Dash(
|
| 12 |
__name__,
|
| 13 |
external_stylesheets=[dbc.themes.FLATLY],
|
| 14 |
-
title="PvRecNet
|
| 15 |
suppress_callback_exceptions=True
|
| 16 |
)
|
| 17 |
|
|
@@ -240,15 +240,42 @@ def handle_upload(contents, filename):
|
|
| 240 |
State('dataset-id-store', 'data'),
|
| 241 |
prevent_initial_call=True
|
| 242 |
)
|
|
|
|
| 243 |
def run_predict(n_clicks, dataset_id):
|
| 244 |
try:
|
| 245 |
res = PvRecNetAPI.run_prediction(dataset_id)
|
| 246 |
fig1 = json.loads(res['plot_json1'])
|
| 247 |
fig2 = json.loads(res['plot_json2'])
|
| 248 |
|
| 249 |
-
|
| 250 |
-
|
| 251 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 252 |
|
| 253 |
# @app.callback(
|
| 254 |
# Output('analytics-output', 'children'),
|
|
|
|
| 11 |
app = dash.Dash(
|
| 12 |
__name__,
|
| 13 |
external_stylesheets=[dbc.themes.FLATLY],
|
| 14 |
+
title="PvRecNet",
|
| 15 |
suppress_callback_exceptions=True
|
| 16 |
)
|
| 17 |
|
|
|
|
| 240 |
State('dataset-id-store', 'data'),
|
| 241 |
prevent_initial_call=True
|
| 242 |
)
|
| 243 |
+
|
| 244 |
def run_predict(n_clicks, dataset_id):
|
| 245 |
try:
|
| 246 |
res = PvRecNetAPI.run_prediction(dataset_id)
|
| 247 |
fig1 = json.loads(res['plot_json1'])
|
| 248 |
fig2 = json.loads(res['plot_json2'])
|
| 249 |
|
| 250 |
+
# 1. Convert the results list to a DataFrame
|
| 251 |
+
df = pd.DataFrame(res['results_table'])
|
| 252 |
+
|
| 253 |
+
# 2. Identify the probability columns (adjust names based on your actual API output)
|
| 254 |
+
prob_cols = ['C_marg', 'L_marg', 'I_marg'] # or 'post_C', etc.
|
| 255 |
+
|
| 256 |
+
# 3. Apply string formatting for consistent visual alignment
|
| 257 |
+
for col in prob_cols:
|
| 258 |
+
if col in df.columns:
|
| 259 |
+
df[col] = df[col].map(lambda x: f"{x:.4f}" if pd.notnull(x) else x)
|
| 260 |
+
|
| 261 |
+
# 4. Create the DataTable using the formatted data
|
| 262 |
+
table = dash_table.DataTable(
|
| 263 |
+
data=df.to_dict('records'),
|
| 264 |
+
columns=[{"name": i, "id": i} for i in df.columns],
|
| 265 |
+
export_format='csv',
|
| 266 |
+
page_size=10,
|
| 267 |
+
style_table={'height': '400px', 'overflowY': 'auto'},
|
| 268 |
+
style_cell={'textAlign': 'left'} # Optional: improves readability
|
| 269 |
+
)
|
| 270 |
+
|
| 271 |
+
return html.Div([
|
| 272 |
+
dbc.Row([
|
| 273 |
+
dbc.Col([dcc.Graph(figure=fig1), dcc.Graph(figure=fig2)], md=5),
|
| 274 |
+
dbc.Col(table, md=7)
|
| 275 |
+
])
|
| 276 |
+
])
|
| 277 |
+
except Exception as e:
|
| 278 |
+
return dbc.Alert(f"Error: {str(e)}", color="danger")
|
| 279 |
|
| 280 |
# @app.callback(
|
| 281 |
# Output('analytics-output', 'children'),
|