desinez commited on
Commit
f871eeb
·
1 Parent(s): d7b91b7

adding prior refining

Browse files
backend/PvDeepSetNet/datasets/real_data_PvDeepSet_ready.csv CHANGED
The diff for this file is too large to render. See raw diff
 
backend/PvDeepSetNet/src/DeepSets/DeepSets_pipeline.py CHANGED
@@ -21,14 +21,14 @@ def run_prediction(data, mode='prediction'):
21
 
22
  if mode == 'prediction':
23
  req_column = ['patient_id', 'episode', 'marker', 'allele', 'country']
24
- data, meta_df = (
25
- data
26
- .pipe(DataPreprocessor.removing_single_episode_patients)
27
- .pipe(DataPreprocessor.calculate_population_Allele_frequencies, population='country')
28
- .pipe(DataPreprocessor.calculate_MOIs)
29
- .pipe(DataPreprocessor.paired_episode_assigner)
30
- )
31
-
32
  tensors = DataPreprocessor.build_deepsets_tensors(df=data, mode=mode)
33
  loaded_data = DataPreprocessor.load_tensor(tensors, mode)
34
 
@@ -36,24 +36,24 @@ def run_prediction(data, mode='prediction'):
36
  pair_id=tensors['pair_id'],
37
  data_loader = loaded_data,
38
  basic_summary=True)
39
- elif mode == 'evaluation':
40
- req_column = ['pair_id', 'episode', 'marker', 'allele', 'country', 'prior_C', 'prior_L', 'prior_I', 'post_C', 'post_L', 'post_I']
41
-
42
- data = DataPreprocessor.calculate_MOIs(data)
43
- meta_df = data[['pair_id', 'patient_id', 'episode']].drop_duplicates().reset_index(drop=True)
44
-
45
- tensors = DataPreprocessor.build_deepsets_tensors(df=data, mode=mode)
46
- loaded_data = DataPreprocessor.load_tensor(tensors, mode)
47
-
48
- return PvDeepSet_model.run_evaluation(meta_df=meta_df,
49
- pair_id=tensors['pair_id'],
50
- data_loader=loaded_data,
51
- probability_plot = True,
52
- metrics=True,
53
- confusion_matrix=True,
54
- basic_summary=True)
55
- else:
56
- return 'incorrect mode'
57
 
58
 
59
 
 
21
 
22
  if mode == 'prediction':
23
  req_column = ['patient_id', 'episode', 'marker', 'allele', 'country']
24
+ # data, meta_df = (
25
+ # data
26
+ # .pipe(DataPreprocessor.removing_single_episode_patients)
27
+ # .pipe(DataPreprocessor.calculate_population_Allele_frequencies, population='country')
28
+ # .pipe(DataPreprocessor.calculate_MOIs)
29
+ # .pipe(DataPreprocessor.paired_episode_assigner)
30
+ # )
31
+ meta_df = data[['sample_id_paired', 'patient_id', 'true_episode', 'prior_C', 'prior_L', 'prior_I']].drop_duplicates().reset_index(drop=True)
32
  tensors = DataPreprocessor.build_deepsets_tensors(df=data, mode=mode)
33
  loaded_data = DataPreprocessor.load_tensor(tensors, mode)
34
 
 
36
  pair_id=tensors['pair_id'],
37
  data_loader = loaded_data,
38
  basic_summary=True)
39
+ # elif mode == 'evaluation':
40
+ # req_column = ['pair_id', 'episode', 'marker', 'allele', 'country', 'prior_C', 'prior_L', 'prior_I', 'post_C', 'post_L', 'post_I']
41
+
42
+ # data = DataPreprocessor.calculate_MOIs(data)
43
+ # meta_df = data[['pair_id', 'patient_id', 'episode']].drop_duplicates().reset_index(drop=True)
44
+
45
+ # tensors = DataPreprocessor.build_deepsets_tensors(df=data, mode=mode)
46
+ # loaded_data = DataPreprocessor.load_tensor(tensors, mode)
47
+
48
+ # return PvDeepSet_model.run_evaluation(meta_df=meta_df,
49
+ # pair_id=tensors['pair_id'],
50
+ # data_loader=loaded_data,
51
+ # probability_plot = True,
52
+ # metrics=True,
53
+ # confusion_matrix=True,
54
+ # basic_summary=True)
55
+ # else:
56
+ # return 'incorrect mode'
57
 
58
 
59
 
backend/PvDeepSetNet/src/DeepSets/Model.py CHANGED
@@ -2,6 +2,13 @@ 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
  # =====================================================
@@ -40,19 +47,18 @@ class PvDeepSets(nn.Module):
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
@@ -94,7 +100,7 @@ class PvDeepSets(nn.Module):
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
@@ -104,3 +110,4 @@ class PvDeepSets(nn.Module):
104
 
105
  return probs
106
 
 
 
2
  import torch.nn as nn
3
  import torch.nn.functional as F
4
 
5
+ # =====================================================
6
+ # Deep Sets model for Pv3Rs surrogate
7
+ # =====================================================
8
+ import torch
9
+ import torch.nn as nn
10
+ import torch.nn.functional as F
11
+
12
  # =====================================================
13
  # Deep Sets model for Pv3Rs surrogate
14
  # =====================================================
 
47
  # 3️⃣ Pair-level MLP (aggregate markers + priors + MOI)
48
  # -------------------------------------------------
49
  self.pair_mlp = nn.Sequential(
50
+ nn.Linear(marker_embed_dim + 2, pair_embed_dim), # +2 MOI
51
  nn.ReLU(),
52
  nn.Linear(pair_embed_dim, hidden_dim),
53
  nn.ReLU(),
54
  nn.Linear(hidden_dim, n_classes)
55
  )
56
 
57
+ def forward(self, X_alleles, allele_mask, marker_mask, MOI):
58
  """
59
  X_alleles : (batch, M_max, 2, A_max, 2)
60
  allele_mask: same shape as X_alleles[:,:,:,:,0]
61
  marker_mask: (batch, M_max)
 
62
  MOI : (batch, 2)
63
  """
64
  B, M, E, A, _ = X_alleles.shape
 
100
  # ---------------------------------------------
101
  # 4️⃣ Concatenate priors + MOI
102
  # ---------------------------------------------
103
+ pair_emb = torch.cat([pair_emb, MOI], dim=-1) # (B, marker_dim+4)
104
 
105
  # ---------------------------------------------
106
  # 5️⃣ Pair-level MLP → logits
 
110
 
111
  return probs
112
 
113
+
backend/PvDeepSetNet/src/DeepSets/Model_result.py CHANGED
@@ -39,11 +39,111 @@ class PvDeepSet_model:
39
  # Load the weights (state_dict)
40
  # Get the directory where Preprocess.py is located
41
  base_path = os.path.dirname(__file__)
42
- file_path = os.path.join(base_path, 'pv_deepsets_weights20260402.pth')
43
  model.load_state_dict(torch.load(file_path, weights_only=True, map_location=device))
44
 
45
  return device, model
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
46
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
47
  @staticmethod
48
  def get_model_results(model, dataloader, device, threshold=0.5, mode='prediction'):
49
  model.eval()
@@ -54,15 +154,15 @@ class PvDeepSet_model:
54
  for batch in dataloader:
55
  # Flexible unpacking: if evaluating, 'batch' has one extra item (y)
56
  if mode == 'evaluation':
57
- X_alleles, allele_mask, marker_mask, priors, MOI, y = batch
58
  true_labels = torch.argmax(y, dim=1)
59
  all_actual.append(y.cpu().numpy())
60
  elif mode == 'prediction':
61
- X_alleles, allele_mask, marker_mask, priors, MOI = batch
62
 
63
  # Model Forward Pass
64
  y_pred = model(X_alleles.to(device), allele_mask.to(device),
65
- marker_mask.to(device), priors.to(device), MOI.to(device))
66
 
67
  probs = y_pred # Assuming Softmax is handled inside or by thresholding
68
 
@@ -77,79 +177,79 @@ class PvDeepSet_model:
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,
@@ -174,6 +274,21 @@ class PvDeepSet_model:
174
  # Insert the pair_id as the first column
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]]]
@@ -190,6 +305,8 @@ class PvDeepSet_model:
190
  # Apply the logic to create the new column
191
  results_df['predicted_class'] = results_df.apply(classify_row, axis=1)
192
 
 
 
193
  dist_df = results_df['predicted_class'].value_counts().reset_index()
194
  dist_df.columns = ['class', 'count']
195
 
@@ -268,7 +385,7 @@ class PvDeepSet_model:
268
  var_name='Probability_Type',
269
  value_name='Probability'
270
  )
271
-
272
  fig = px.bar(
273
  df_long,
274
  x=cols[0],
@@ -320,14 +437,14 @@ class PvDeepSet_model:
320
  donut_plot = plot_donut_count(results_df)
321
  probability_dist_plot = plot_probability_dist(results_df)
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 = {
 
39
  # Load the weights (state_dict)
40
  # Get the directory where Preprocess.py is located
41
  base_path = os.path.dirname(__file__)
42
+ file_path = os.path.join(base_path, 'pv_deepsets_weights20260425_154256.pth')
43
  model.load_state_dict(torch.load(file_path, weights_only=True, map_location=device))
44
 
45
  return device, model
46
+ @staticmethod
47
+ def result_post_processing(results_df, calc_NU_post = True, approx_joint = True):
48
+ """
49
+ result_df: PvDeepSet predicted results
50
+ calc_NU_post: calculate non uniform posterior (refine the posterior if the priors were not default)
51
+ approx_joint: approximate marginal probabilities from perwise results
52
+ """
53
+ if calc_NU_post:
54
+
55
+ # 1. Align column names for math operations
56
+ # We create a temporary copy to ensure we multiply the right classes
57
+ df_priors = results_df[['prior_C', 'prior_L', 'prior_I']].rename(columns={'prior_C': 'C', 'prior_L': 'L', 'prior_I': 'I'})
58
+
59
+ df_post_uni = results_df[['prob_C', 'prob_L', 'prob_I']].rename(columns={'prob_C': 'C', 'prob_L': 'L', 'prob_I': 'I'})
60
+
61
+ # 2. Numerator: Multiply P_uniform(s|y) * P(s)
62
+ # Pandas handles row-matching automatically by index
63
+ numerator = df_post_uni * df_priors
64
+
65
+ # 3. Denominator: Sum across the columns for each row (Normalization)
66
+ denominator = numerator.sum(axis=1)
67
+
68
+ # 4. Final Recovery: Divide numerator by denominator
69
+ # axis=0 ensures the division happens row by row
70
+ df_post_non_uniform = numerator.divide(denominator, axis=0)
71
+
72
+ df_post_non_uniform['C'] = df_post_non_uniform['C'].round(4)
73
+ df_post_non_uniform['L'] = df_post_non_uniform['L'].round(4)
74
+ df_post_non_uniform['I'] = df_post_non_uniform['I'].round(4)
75
 
76
+ results_df['prob_C'] = df_post_non_uniform['C'].values
77
+ results_df['prob_L'] = df_post_non_uniform['L'].values
78
+ results_df['prob_I'] = df_post_non_uniform['I'].values
79
+ return df_post_non_uniform
80
+
81
+ if approx_joint:
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
+
87
+ def assign_source_episodes(df):
88
+ df = df.sort_values(['patient_id', 'true_episode']).copy()
89
+
90
+ # We create a counter that resets for every new 'true_episode'
91
+ # This identifies if the row is comparing against the 1st, 2nd, or 3rd previous episode
92
+ df['pair_source'] = df.groupby(['patient_id', 'true_episode']).cumcount() + 1
93
+ return df.sort_values('pair_id')
94
+
95
+ df = assign_source_episodes(results_df)
96
+
97
+ results = []
98
+
99
+
100
+ for pid, group in df.groupby('patient_id'):
101
+ # Get unique episodes in chronological order
102
+ # Based on your data, episodes are 1, 2, 4, 5, 6...
103
+ episodes = sorted(group['true_episode'].unique())
104
+ n_epi = len(episodes)
105
+
106
+ # We start calculating from the first recurrence (index 1)
107
+ for idx in range(1, n_epi):
108
+ curr_epi = episodes[idx]
109
+ prev_epi = episodes[idx-1]
110
+
111
+ # --- CALCULATE C (Recrudescence) ---
112
+ # Rule: Only look at the immediate predecessor
113
+ c_row = group[(group['true_episode'] == curr_epi) & (group['pair_source'] == prev_epi)]
114
+ # If your data doesn't have 'pair_source', we look for the specific pair
115
+ # where j = curr_epi and i = prev_epi
116
+ C_prob = c_row['prob_C'].iloc[0] if not c_row.empty else 0.0
117
+
118
+ # --- CALCULATE L (Relapse) ---
119
+ # Rule: Max( L / (1-C) ) across all previous episodes, then scale by (1-C_total)
120
+
121
+ # Get all pairs where 'episode' is our current episode
122
+ all_prev_pairs = group[group['true_episode'] == curr_epi]
123
+
124
+ # Calculate the 'relapse share': L / (1 - C)
125
+ # Use small epsilon to avoid division by zero
126
+ shares = all_prev_pairs['prob_L'] / (1 - all_prev_pairs['prob_C'] + 1e-9)
127
+ max_share = shares.max()
128
+
129
+ L_prob = max_share * (1 - C_prob)
130
+
131
+ # --- CALCULATE I (Reinfection) ---
132
+ # Rule: The remainder
133
+ I_prob = 1 - (C_prob + L_prob)
134
+
135
+ results.append({
136
+ 'patient_id': pid,
137
+ 'episode': curr_epi,
138
+ 'C_marg': C_prob,
139
+ 'L_marg': L_prob,
140
+ 'I_marg': I_prob
141
+ })
142
+ results_df = pd.DataFrame(results)
143
+ return results_df
144
+
145
+
146
+
147
  @staticmethod
148
  def get_model_results(model, dataloader, device, threshold=0.5, mode='prediction'):
149
  model.eval()
 
154
  for batch in dataloader:
155
  # Flexible unpacking: if evaluating, 'batch' has one extra item (y)
156
  if mode == 'evaluation':
157
+ X_alleles, allele_mask, marker_mask, MOI, y = batch
158
  true_labels = torch.argmax(y, dim=1)
159
  all_actual.append(y.cpu().numpy())
160
  elif mode == 'prediction':
161
+ X_alleles, allele_mask, marker_mask, MOI = batch
162
 
163
  # Model Forward Pass
164
  y_pred = model(X_alleles.to(device), allele_mask.to(device),
165
+ marker_mask.to(device), MOI.to(device))
166
 
167
  probs = y_pred # Assuming Softmax is handled inside or by thresholding
168
 
 
177
 
178
  return pred_stack
179
 
180
+ # @staticmethod
181
+ # def calculate_approx_marginals(df):
182
+ # """
183
+ # Python implementation of the Pv3Rs approx-joint marginalization logic.
184
+ # Assumes df contains: patient_id, episode_i, episode_j, post_C, post_L, post_I
185
+ # """
186
+ # # 1. Identify the unique episodes for this patient (sorted)
187
+ # # We assume 'episode' in your sample refers to the current episode (j)
188
+ # # and we need to identify the source episode (i).
189
+ # # For this example, let's derive i and j from your structure.
190
 
191
 
192
+ # def assign_source_episodes(df):
193
+ # df = df.sort_values(['patient_id', 'true_episode']).copy()
194
 
195
+ # # We create a counter that resets for every new 'true_episode'
196
+ # # This identifies if the row is comparing against the 1st, 2nd, or 3rd previous episode
197
+ # df['pair_source'] = df.groupby(['patient_id', 'true_episode']).cumcount() + 1
198
+ # return df.sort_values('pair_id')
199
 
200
+ # df = assign_source_episodes(df)
201
 
202
+ # results = []
203
 
204
 
205
+ # for pid, group in df.groupby('patient_id'):
206
+ # # Get unique episodes in chronological order
207
+ # # Based on your data, episodes are 1, 2, 4, 5, 6...
208
+ # episodes = sorted(group['true_episode'].unique())
209
+ # n_epi = len(episodes)
210
 
211
+ # # We start calculating from the first recurrence (index 1)
212
+ # for idx in range(1, n_epi):
213
+ # curr_epi = episodes[idx]
214
+ # prev_epi = episodes[idx-1]
215
 
216
+ # # --- CALCULATE C (Recrudescence) ---
217
+ # # Rule: Only look at the immediate predecessor
218
+ # c_row = group[(group['true_episode'] == curr_epi) & (group['pair_source'] == prev_epi)]
219
+ # # If your data doesn't have 'pair_source', we look for the specific pair
220
+ # # where j = curr_epi and i = prev_epi
221
+ # C_prob = c_row['prob_C'].iloc[0] if not c_row.empty else 0.0
222
+
223
+ # # --- CALCULATE L (Relapse) ---
224
+ # # Rule: Max( L / (1-C) ) across all previous episodes, then scale by (1-C_total)
225
 
226
+ # # Get all pairs where 'episode' is our current episode
227
+ # all_prev_pairs = group[group['true_episode'] == curr_epi]
228
 
229
+ # # Calculate the 'relapse share': L / (1 - C)
230
+ # # Use small epsilon to avoid division by zero
231
+ # shares = all_prev_pairs['prob_L'] / (1 - all_prev_pairs['prob_C'] + 1e-9)
232
+ # max_share = shares.max()
233
 
234
+ # L_prob = max_share * (1 - C_prob)
235
 
236
+ # # --- CALCULATE I (Reinfection) ---
237
+ # # Rule: The remainder
238
+ # I_prob = 1 - (C_prob + L_prob)
239
 
240
+ # results.append({
241
+ # 'patient_id': pid,
242
+ # 'episode': curr_epi,
243
+ # 'C_marg': C_prob,
244
+ # 'L_marg': L_prob,
245
+ # 'I_marg': I_prob
246
+ # })
247
+ # marg_result = pd.DataFrame(results)
248
 
249
 
250
 
251
 
252
+ # return marg_result
253
 
254
  @staticmethod
255
  def run_prediction(meta_df,
 
274
  # Insert the pair_id as the first column
275
  results_df.insert(0, 'pair_id', pair_id)
276
 
277
+ results_df = results_df.merge(meta_df, left_on='pair_id', right_on='sample_id_paired', how='inner')
278
+ unique_result = results_df[['pair_id', 'prior_C', 'prior_L', 'prior_I', 'prob_C', 'prob_L', 'prob_I']].drop_duplicates(ignore_index=True)
279
+ results_df = PvDeepSet_model.result_post_processing(unique_result, calc_NU_post=True, approx_joint=False)
280
+ # results_df = PvDeepSet_model.result_post_processing(unique_result, calc_NU_post=False, approx_joint=True)
281
+
282
+ return results_df
283
+
284
+ # get marginal probabilities
285
+ marginal_df = PvDeepSet_model.calculate_approx_marginals(results_df[['pair_id', 'patient_id', 'true_episode', 'prob_C', 'prob_L', 'prob_I']])
286
+ marginal_df['predicted_class'] = marginal_df.apply(classify_row, axis=1, cols=['C_marg', 'L_marg', 'I_marg'])
287
+ donut_plot = plot_donut_count(marginal_df)
288
+ marginal_df['patient_id_epi'] = marginal_df['patient_id'] + "_" + marginal_df['episode'].astype(int).astype('str')
289
+ probability_dist_plot = plot_probability_dist(marginal_df, cols=['patient_id_epi', 'C_marg', 'L_marg','I_marg','predicted_class'])
290
+
291
+
292
  # 4. Hardclass Classification with Threshold Logic
293
  def classify_row(row, cols=['prob_C', 'prob_L', 'prob_I']):
294
  probs = [row[cols[0]], row[cols[1]], row[cols[2]]]
 
305
  # Apply the logic to create the new column
306
  results_df['predicted_class'] = results_df.apply(classify_row, axis=1)
307
 
308
+
309
+
310
  dist_df = results_df['predicted_class'].value_counts().reset_index()
311
  dist_df.columns = ['class', 'count']
312
 
 
385
  var_name='Probability_Type',
386
  value_name='Probability'
387
  )
388
+
389
  fig = px.bar(
390
  df_long,
391
  x=cols[0],
 
437
  donut_plot = plot_donut_count(results_df)
438
  probability_dist_plot = plot_probability_dist(results_df)
439
 
440
+ # results_df = results_df.merge(meta_df, left_on='pair_id', right_on='sample_id_paired', how='inner')
441
+
442
+ # # get marginal probabilities
443
+ # marginal_df = PvDeepSet_model.calculate_approx_marginals(results_df[['pair_id', 'patient_id', 'true_episode', 'prob_C', 'prob_L', 'prob_I']])
444
+ # marginal_df['predicted_class'] = marginal_df.apply(classify_row, axis=1, cols=['C_marg', 'L_marg', 'I_marg'])
445
+ # donut_plot = plot_donut_count(marginal_df)
446
+ # marginal_df['patient_id_epi'] = marginal_df['patient_id'] + "_" + marginal_df['episode'].astype(int).astype('str')
447
+ # probability_dist_plot = plot_probability_dist(marginal_df, cols=['patient_id_epi', 'C_marg', 'L_marg','I_marg','predicted_class'])
448
 
449
  columns = ['pair_id', 'patient_id', 'true_episode', 'prob_C', 'prob_L', 'prob_I', 'predicted_class']
450
  results = {
backend/PvDeepSetNet/src/DeepSets/Preprocess.py CHANGED
@@ -133,7 +133,7 @@ class DataPreprocessor:
133
 
134
  df.rename(columns={'episode':'true_episode', 'episode_order':'episode'}, inplace=True)
135
 
136
- meta_info = df[['sample_id_paired', 'patient_id', 'true_episode']].drop_duplicates().reset_index(drop=True)
137
 
138
  return df, meta_info
139
 
@@ -239,7 +239,6 @@ class DataPreprocessor:
239
  deepset_tensor["X_alleles"],
240
  deepset_tensor["allele_mask"],
241
  deepset_tensor["marker_mask"],
242
- deepset_tensor["priors"],
243
  deepset_tensor["MOI"]
244
  )
245
  elif mode == 'evaluation':
@@ -247,7 +246,6 @@ class DataPreprocessor:
247
  deepset_tensor["X_alleles"],
248
  deepset_tensor["allele_mask"],
249
  deepset_tensor["marker_mask"],
250
- deepset_tensor["priors"],
251
  deepset_tensor["MOI"],
252
  deepset_tensor["y"]
253
  )
 
133
 
134
  df.rename(columns={'episode':'true_episode', 'episode_order':'episode'}, inplace=True)
135
 
136
+ meta_info = df[['sample_id_paired', 'patient_id', 'true_episode', 'prior_C', 'prior_L', 'prior_I']].drop_duplicates().reset_index(drop=True)
137
 
138
  return df, meta_info
139
 
 
239
  deepset_tensor["X_alleles"],
240
  deepset_tensor["allele_mask"],
241
  deepset_tensor["marker_mask"],
 
242
  deepset_tensor["MOI"]
243
  )
244
  elif mode == 'evaluation':
 
246
  deepset_tensor["X_alleles"],
247
  deepset_tensor["allele_mask"],
248
  deepset_tensor["marker_mask"],
 
249
  deepset_tensor["MOI"],
250
  deepset_tensor["y"]
251
  )
backend/PvDeepSetNet/src/DeepSets/__pycache__/DeepSets_pipeline.cpython-310.pyc CHANGED
Binary files a/backend/PvDeepSetNet/src/DeepSets/__pycache__/DeepSets_pipeline.cpython-310.pyc and b/backend/PvDeepSetNet/src/DeepSets/__pycache__/DeepSets_pipeline.cpython-310.pyc differ
 
backend/PvDeepSetNet/src/DeepSets/__pycache__/Model.cpython-310.pyc CHANGED
Binary files a/backend/PvDeepSetNet/src/DeepSets/__pycache__/Model.cpython-310.pyc and b/backend/PvDeepSetNet/src/DeepSets/__pycache__/Model.cpython-310.pyc differ
 
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
 
backend/PvDeepSetNet/src/DeepSets/__pycache__/Preprocess.cpython-310.pyc CHANGED
Binary files a/backend/PvDeepSetNet/src/DeepSets/__pycache__/Preprocess.cpython-310.pyc and b/backend/PvDeepSetNet/src/DeepSets/__pycache__/Preprocess.cpython-310.pyc differ
 
backend/PvDeepSetNet/src/DeepSets/allele_dict.json CHANGED
@@ -1 +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}
 
1
+ {"Chr01-1": 1, "Chr01-2": 2, "Chr02-1": 3, "Chr03-1": 4, "Chr05-6": 5, "Chr07-1": 6, "Chr08-2": 7, "Chr09-7": 8, "Chr10-1": 9, "Chr11-1": 10, "Chr14-1": 11, "Chr13-12": 12, "Chr13-1": 13, "Chr08-1": 14, "Chr07-5": 15, "Chr07-8": 16, "Chr07-4": 17, "Chr07-3": 18, "Chr05-1": 19, "Chr03-2": 20, "Chr03-3": 21, "Chr02-2": 22, "Chr07-2": 23, "Chr11-9": 24, "Chr11-2": 25, "Chr09-1": 26, "Chr09-3": 27, "Chr09-2": 28, "Chr08-3": 29, "Chr01-3": 30, "Chr01-11": 31, "Chr05-5": 32, "Chr05-4": 33, "Chr13-3": 34, "Chr11-5": 35, "Chr05-3": 36, "Chr14-3": 37, "Chr10-2": 38, "Chr08-4": 39, "Chr13-2": 40, "Chr10-3": 41, "Chr05-13": 42, "Chr05-2": 43, "Chr11-17": 44, "Chr14-11": 45, "Chr10-4": 46, "Chr10-7": 47, "Chr11-3": 48, "Chr13-4": 49, "Chr14-10": 50, "Chr10-5": 51, "Chr10-6": 52, "Chr05-7": 53, "Chr09-8": 54, "Chr07-29": 55, "Chr05-15": 56, "Chr02-3": 57, "Chr13-6": 58, "Chr01-5": 59, "Chr03-4": 60, "Chr09-5": 61, "Chr11-4": 62, "Chr11-16": 63, "Chr13-8": 64, "Chr11-12": 65, "Chr09-13": 66, "Chr14-15": 67, "Chr11-22": 68, "Chr14-21": 69, "Chr11-30": 70, "Chr09-4": 71, "Chr11-24": 72, "Chr11-6": 73, "Chr07-30": 74, "Chr14-6": 75, "Chr14-4": 76, "Chr13-7": 77, "Chr02-9": 78, "Chr14-22": 79, "Chr05-8": 80, "Chr09-6": 81, "Chr13-24": 82, "Chr13-11": 83, "Chr13-9": 84, "Chr14-9": 85, "Chr05-9": 86, "Chr13-42": 87, "Chr03-17": 88, "Chr13-49": 89, "Chr14-2": 90, "Chr13-5": 91, "Chr01-4": 92, "Chr14-5": 93, "Chr11-37": 94, "Chr14-12": 95, "Chr14-7": 96, "Chr14-23": 97, "Chr09-12": 98, "Chr13-41": 99, "Chr11-19": 100, "Chr13-21": 101, "Chr14-8": 102, "Chr14-19": 103, "Chr11-18": 104, "Chr08-8": 105, "Chr11-10": 106, "Chr14-17": 107, "Chr14-30": 108, "Chr14-13": 109, "Chr11-29": 110, "Chr11-14": 111, "Chr09-15": 112, "Chr13-46": 113, "Chr13-15": 114, "Chr14-16": 115, "Chr13-17": 116, "Chr09-14": 117, "Chr08-7": 118, "Chr01-9": 119, "Chr08-19": 120, "Chr11-8": 121, "Chr13-20": 122, "Chr13-40": 123, "Chr14-14": 124, "Chr02-4": 125, "Chr07-6": 126, "Chr08-6": 127, "Chr02-5": 128, "Chr02-7": 129, "Chr02-8": 130, "Chr03-5": 131, "Chr02-6": 132, "Chr05-12": 133, "Chr05-11": 134, "Chr07-10": 135, "Chr03-6": 136, "Chr02-11": 137, "Chr09-9": 138, "Chr07-9": 139, "Chr07-11": 140, "Chr05-10": 141, "Chr13-13": 142, "Chr09-16": 143}
backend/PvDeepSetNet/src/DeepSets/pv_deepsets_weights20260425_154256.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:3f9cd530d46c42d69e515e9aeab8e64288dd5bb5844c393de8035c5fa11b2a60
3
+ size 117741
backend/PvDeepSetNet/tests/temp.ipynb CHANGED
@@ -1,5 +1,215 @@
1
  {
2
  "cells": [
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3
  {
4
  "cell_type": "markdown",
5
  "id": "cbf23b97",
 
1
  {
2
  "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "execution_count": 14,
6
+ "id": "cf18a668",
7
+ "metadata": {},
8
+ "outputs": [],
9
+ "source": [
10
+ "import pandas as pd\n",
11
+ "\n",
12
+ "# real data\n",
13
+ "real_data = pd.read_csv('../datasets/real_data_PvDeepSet_ready.csv')\n",
14
+ "real_data['source'] = 'real'\n",
15
+ "real_data_train = real_data[(real_data.sets == 'train') & (real_data.sample_id_paired.str.contains('DF'))].reset_index(drop=True)\n",
16
+ "real_data_test = real_data[(real_data.sets == 'test') & (real_data.sample_id_paired.str.contains('DF'))].reset_index(drop=True)\n",
17
+ "real_data_test_lc = real_data[(real_data.sets == 'test') & (real_data.sample_id_paired.str.contains('LC'))].reset_index(drop=True)\n",
18
+ "\n",
19
+ "\n",
20
+ "\n",
21
+ "pvAmpSeq_simultion_ready = pd.read_csv('../datasets/pvAmpSeq_simulation_ready.csv')\n"
22
+ ]
23
+ },
24
+ {
25
+ "cell_type": "code",
26
+ "execution_count": null,
27
+ "id": "8d3473b2",
28
+ "metadata": {},
29
+ "outputs": [],
30
+ "source": []
31
+ },
32
+ {
33
+ "cell_type": "code",
34
+ "execution_count": 2,
35
+ "id": "b1ecebd2",
36
+ "metadata": {},
37
+ "outputs": [],
38
+ "source": [
39
+ "from DeepSets import run_prediction"
40
+ ]
41
+ },
42
+ {
43
+ "cell_type": "code",
44
+ "execution_count": 3,
45
+ "id": "96c65ae1",
46
+ "metadata": {},
47
+ "outputs": [],
48
+ "source": [
49
+ "pvAmpSeq_simultion_ready['prior_C'] = 1/3\n",
50
+ "pvAmpSeq_simultion_ready['prior_L'] = 1/3\n",
51
+ "pvAmpSeq_simultion_ready['prior_I'] = 1/3"
52
+ ]
53
+ },
54
+ {
55
+ "cell_type": "code",
56
+ "execution_count": 23,
57
+ "metadata": {},
58
+ "outputs": [
59
+ {
60
+ "data": {
61
+ "text/html": [
62
+ "<div>\n",
63
+ "<style scoped>\n",
64
+ " .dataframe tbody tr th:only-of-type {\n",
65
+ " vertical-align: middle;\n",
66
+ " }\n",
67
+ "\n",
68
+ " .dataframe tbody tr th {\n",
69
+ " vertical-align: top;\n",
70
+ " }\n",
71
+ "\n",
72
+ " .dataframe thead th {\n",
73
+ " text-align: right;\n",
74
+ " }\n",
75
+ "</style>\n",
76
+ "<table border=\"1\" class=\"dataframe\">\n",
77
+ " <thead>\n",
78
+ " <tr style=\"text-align: right;\">\n",
79
+ " <th></th>\n",
80
+ " <th>sample_id_paired</th>\n",
81
+ " <th>pair_id</th>\n",
82
+ " <th>patient_id</th>\n",
83
+ " <th>sample_id</th>\n",
84
+ " </tr>\n",
85
+ " </thead>\n",
86
+ " <tbody>\n",
87
+ " <tr>\n",
88
+ " <th>0</th>\n",
89
+ " <td>Sero-040-LC_4</td>\n",
90
+ " <td>Sero-040_4</td>\n",
91
+ " <td>Sero-040</td>\n",
92
+ " <td>Sero-040-R04</td>\n",
93
+ " </tr>\n",
94
+ " <tr>\n",
95
+ " <th>7</th>\n",
96
+ " <td>Sero-040-LC_4</td>\n",
97
+ " <td>Sero-040_4</td>\n",
98
+ " <td>Sero-040</td>\n",
99
+ " <td>Sero-040-R08</td>\n",
100
+ " </tr>\n",
101
+ " <tr>\n",
102
+ " <th>36</th>\n",
103
+ " <td>Sero-182-LC_2</td>\n",
104
+ " <td>Sero-182_2</td>\n",
105
+ " <td>Sero-182</td>\n",
106
+ " <td>Sero-182-R12</td>\n",
107
+ " </tr>\n",
108
+ " <tr>\n",
109
+ " <th>43</th>\n",
110
+ " <td>Sero-182-LC_2</td>\n",
111
+ " <td>Sero-182_2</td>\n",
112
+ " <td>Sero-182</td>\n",
113
+ " <td>Sero-182-R01</td>\n",
114
+ " </tr>\n",
115
+ " <tr>\n",
116
+ " <th>71</th>\n",
117
+ " <td>Sero-194-LC_2</td>\n",
118
+ " <td>Sero-194_2</td>\n",
119
+ " <td>Sero-194</td>\n",
120
+ " <td>Sero-194-R09</td>\n",
121
+ " </tr>\n",
122
+ " </tbody>\n",
123
+ "</table>\n",
124
+ "</div>"
125
+ ],
126
+ "text/plain": [
127
+ " sample_id_paired pair_id patient_id sample_id\n",
128
+ "0 Sero-040-LC_4 Sero-040_4 Sero-040 Sero-040-R04\n",
129
+ "7 Sero-040-LC_4 Sero-040_4 Sero-040 Sero-040-R08\n",
130
+ "36 Sero-182-LC_2 Sero-182_2 Sero-182 Sero-182-R12\n",
131
+ "43 Sero-182-LC_2 Sero-182_2 Sero-182 Sero-182-R01\n",
132
+ "71 Sero-194-LC_2 Sero-194_2 Sero-194 Sero-194-R09"
133
+ ]
134
+ },
135
+ "execution_count": 23,
136
+ "metadata": {},
137
+ "output_type": "execute_result"
138
+ }
139
+ ],
140
+ "source": [
141
+ "real_data_test_lc[['sample_id_paired',\t'pair_id',\t'patient_id',\t'sample_id']].drop_duplicates().head()"
142
+ ]
143
+ },
144
+ {
145
+ "cell_type": "code",
146
+ "execution_count": 17,
147
+ "metadata": {},
148
+ "outputs": [],
149
+ "source": [
150
+ "temp = real_data_test[real_data_test.country == 'Ethiopia'].copy().reset_index(drop=True)\n",
151
+ "\n",
152
+ "temp['pair_order'] = temp['sample_id_paired'].str.split('_').str[1]\n",
153
+ "# temp['sample_id_paired'] = temp['sample_id_paired'].str[:9] + 'P' + temp['sample_id_paired'].str[11:]\n",
154
+ "# temp = temp[data.columns]\n"
155
+ ]
156
+ },
157
+ {
158
+ "cell_type": "code",
159
+ "execution_count": 66,
160
+ "id": "5d400e68",
161
+ "metadata": {},
162
+ "outputs": [
163
+ {
164
+ "name": "stdout",
165
+ "output_type": "stream",
166
+ "text": [
167
+ "The autoreload extension is already loaded. To reload it, use:\n",
168
+ " %reload_ext autoreload\n"
169
+ ]
170
+ }
171
+ ],
172
+ "source": [
173
+ "%load_ext autoreload\n",
174
+ "%autoreload 2"
175
+ ]
176
+ },
177
+ {
178
+ "cell_type": "code",
179
+ "execution_count": 13,
180
+ "id": "7b3c3a1d",
181
+ "metadata": {},
182
+ "outputs": [
183
+ {
184
+ "data": {
185
+ "text/plain": [
186
+ "48"
187
+ ]
188
+ },
189
+ "execution_count": 13,
190
+ "metadata": {},
191
+ "output_type": "execute_result"
192
+ }
193
+ ],
194
+ "source": [
195
+ "temp.sample_id_paired.nunique()"
196
+ ]
197
+ },
198
+ {
199
+ "cell_type": "code",
200
+ "execution_count": null,
201
+ "metadata": {},
202
+ "outputs": [],
203
+ "source": []
204
+ },
205
+ {
206
+ "cell_type": "code",
207
+ "execution_count": null,
208
+ "id": "2c05a857",
209
+ "metadata": {},
210
+ "outputs": [],
211
+ "source": []
212
+ },
213
  {
214
  "cell_type": "markdown",
215
  "id": "cbf23b97",