pscotti commited on
Commit
a656a76
·
verified ·
1 Parent(s): a354d59

Delete human_trials_mindeye2.ipynb

Browse files
Files changed (1) hide show
  1. human_trials_mindeye2.ipynb +0 -344
human_trials_mindeye2.ipynb DELETED
@@ -1,344 +0,0 @@
1
- {
2
- "cells": [
3
- {
4
- "cell_type": "code",
5
- "execution_count": null,
6
- "metadata": {},
7
- "outputs": [],
8
- "source": [
9
- "import os, sys, shutil\n",
10
- "from tqdm import tqdm\n",
11
- "import numpy as np\n",
12
- "import pandas as pd\n",
13
- "import matplotlib as plt\n",
14
- "from PIL import Image\n",
15
- "from matplotlib.lines import Line2D\n",
16
- "import matplotlib as mpl\n",
17
- "import math\n",
18
- "import matplotlib.image as mpimg\n",
19
- "import random\n",
20
- "from datetime import datetime\n",
21
- "from torchvision import transforms\n",
22
- "import torch\n",
23
- "# os.chdir(\"..\")\n",
24
- "experiment_version = 4\n",
25
- "os.makedirs(f\"stimuli_v{experiment_version}\", exist_ok=True)\n",
26
- "os.makedirs(f\"responses_v{experiment_version}\", exist_ok=True)\n",
27
- "os.makedirs(f\"dataframes_v{experiment_version}\", exist_ok=True)"
28
- ]
29
- },
30
- {
31
- "cell_type": "markdown",
32
- "metadata": {},
33
- "source": [
34
- "# CREATE EXPERIMENT DATAFRAME AND TRIAL FILES FOR MEADOWS"
35
- ]
36
- },
37
- {
38
- "cell_type": "code",
39
- "execution_count": null,
40
- "metadata": {},
41
- "outputs": [],
42
- "source": [
43
- "#Experiment column key:\n",
44
- "# 1: Experiment 1, mindeye vs second sight\n",
45
- "# 2: Experiment 2, second sight two way identification\n",
46
- "# 3: Experiment 3, mental imagery two way identification\n",
47
- "df_exp = pd.DataFrame(columns=[\"experiment\", \"stim1\", \"stim2\", \"stim3\", \"sample\", \"subject\", \"target_on_left\", \"catch_trial\", \"rep\"])\n",
48
- "i=0\n",
49
- "random_count = 0\n",
50
- "gt_tensor_block = torch.load(\"raw_stimuli/all_images_425.pt\")\n",
51
- "for subj in [1,2,5,7]: #1,2,5,7\n",
52
- " subject_enhanced_recons_40 = torch.load(f\"raw_stimuli/final_subj0{subj}_pretrained_40sess_24bs_all_enhancedrecons.pt\")\n",
53
- " subject_unclip_recons_40 = torch.load(f\"raw_stimuli/final_subj0{subj}_pretrained_40sess_24bs_all_recons.pt\")\n",
54
- " subject_enhanced_recons_1 = torch.load(f\"raw_stimuli/final_subj0{subj}_pretrained_1sess_24bs_all_enhancedrecons.pt\")\n",
55
- " subject_braindiffuser_recons_1 = torch.load(f\"raw_stimuli/subj0{subj}_brain_diffuser_750_all_recons.pt\")\n",
56
- " #Experiment 1, mindeye two way identification\n",
57
- " random_indices = random.sample(range(1000), 300)\n",
58
- " for sample in tqdm(random_indices):\n",
59
- " \n",
60
- " # Get random sample to compare against\n",
61
- " random_number = random.choice([x for x in range(1000) if x != sample])\n",
62
- " # Extract the stimulus images from tensor blocks and save as pngs to stimuli folder\n",
63
- " gt_sample = transforms.ToPILImage()(gt_tensor_block[sample])\n",
64
- " sample_enhanced_recons_40 = transforms.ToPILImage()(subject_enhanced_recons_40[sample]).resize((425,425))\n",
65
- " random_enhanced_recons_40 = transforms.ToPILImage()(subject_enhanced_recons_40[random_number]).resize((425,425))\n",
66
- " sample_enhanced_recons_40.save(f\"stimuli_v{experiment_version}/{sample}_subject{subj}_mindeye_enhanced_40.png\")\n",
67
- " random_enhanced_recons_40.save(f\"stimuli_v{experiment_version}/{random_number}_subject{subj}_mindeye_enhanced_40.png\")\n",
68
- " gt_sample.save(f\"stimuli_v{experiment_version}/{sample}_ground_truth.png\")\n",
69
- " \n",
70
- " # Configure stimuli names and order in experiment dataframe\n",
71
- " sample_names = [f\"{random_number}_subject{subj}_mindeye_enhanced_40\", f\"{sample}_subject{subj}_mindeye_enhanced_40\"]\n",
72
- " order = random.randrange(2)\n",
73
- " left_sample = sample_names.pop(order)\n",
74
- " right_sample = sample_names.pop()\n",
75
- " gt_sample = f\"{sample}_ground_truth\"\n",
76
- " df_exp.loc[i] = {\"experiment\" : 1, \"stim1\" : gt_sample, \"stim2\" : left_sample, \"stim3\" : right_sample, \"sample\" : sample, \"subject\" : subj, \n",
77
- " \"target_on_left\" : order == 1, \"catch_trial\" : None, \"rep\" : 0}\n",
78
- " i+=1\n",
79
- " \n",
80
- " #Experiment 2, refined vs unrefined\n",
81
- " random_indices = random.sample(range(1000), 300)\n",
82
- " for sample in tqdm(random_indices):\n",
83
- " \n",
84
- " # Extract the stimulus images from tensor blocks and save as pngs to stimuli folder\n",
85
- " gt_sample = transforms.ToPILImage()(gt_tensor_block[sample])\n",
86
- " sample_enhanced_recons_40 = transforms.ToPILImage()(subject_enhanced_recons_40[sample]).resize((425,425))\n",
87
- " sample_unclip_recons_40 = transforms.ToPILImage()(subject_unclip_recons_40[sample]).resize((425,425))\n",
88
- " sample_enhanced_recons_40.save(f\"stimuli_v{experiment_version}/{sample}_subject{subj}_mindeye_enhanced_40.png\")\n",
89
- " sample_unclip_recons_40.save(f\"stimuli_v{experiment_version}/{sample}_subject{subj}_mindeye_unclip_40.png\")\n",
90
- " gt_sample.save(f\"stimuli_v{experiment_version}/{sample}_ground_truth.png\")\n",
91
- " \n",
92
- " # Configure stimuli names and order in experiment dataframe\n",
93
- " sample_names = [f\"{sample}_subject{subj}_mindeye_unclip_40\", f\"{sample}_subject{subj}_mindeye_enhanced_40\"]\n",
94
- " order = random.randrange(2)\n",
95
- " left_sample = sample_names.pop(order)\n",
96
- " right_sample = sample_names.pop()\n",
97
- " gt_sample = f\"{sample}_ground_truth\"\n",
98
- " df_exp.loc[i] = {\"experiment\" : 2, \"stim1\" : gt_sample, \"stim2\" : left_sample, \"stim3\" : right_sample, \"sample\" : sample, \"subject\" : subj, \n",
99
- " \"target_on_left\" : order == 1, \"catch_trial\" : None, \"rep\" : 0}\n",
100
- " i+=1\n",
101
- " \n",
102
- " #Experiment 3, refined 1 session vs brain diffuser 1 session\n",
103
- " random_indices = random.sample(range(1000), 300)\n",
104
- " for sample in tqdm(random_indices):\n",
105
- " \n",
106
- " # Extract the stimulus images from tensor blocks and save as pngs to stimuli folder\n",
107
- " gt_sample = transforms.ToPILImage()(gt_tensor_block[sample])\n",
108
- " sample_enhanced_recons_1 = transforms.ToPILImage()(subject_enhanced_recons_1[sample]).resize((425,425))\n",
109
- " sample_braindiffuser_1 = transforms.ToPILImage()(subject_braindiffuser_recons_1[sample]).resize((425,425))\n",
110
- " sample_enhanced_recons_1.save(f\"stimuli_v{experiment_version}/{sample}_subject{subj}_mindeye_enhanced_1.png\")\n",
111
- " sample_braindiffuser_1.save(f\"stimuli_v{experiment_version}/{sample}_subject{subj}_braindiffuser_1.png\")\n",
112
- " gt_sample.save(f\"stimuli_v{experiment_version}/{sample}_ground_truth.png\")\n",
113
- " \n",
114
- " # Configure stimuli names and order in experiment dataframe\n",
115
- " sample_names = [f\"{sample}_subject{subj}_braindiffuser_1\", f\"{sample}_subject{subj}_mindeye_enhanced_1\"]\n",
116
- " order = random.randrange(2)\n",
117
- " left_sample = sample_names.pop(order)\n",
118
- " right_sample = sample_names.pop()\n",
119
- " gt_sample = f\"{sample}_ground_truth\"\n",
120
- " df_exp.loc[i] = {\"experiment\" : 3, \"stim1\" : gt_sample, \"stim2\" : left_sample, \"stim3\" : right_sample, \"sample\" : sample, \"subject\" : subj, \n",
121
- " \"target_on_left\" : order == 1, \"catch_trial\" : None, \"rep\" : 0}\n",
122
- " i+=1\n",
123
- "df_exp = df_exp.sample(frac=1)\n",
124
- "print(len(df_exp))\n",
125
- "print(df_exp)"
126
- ]
127
- },
128
- {
129
- "cell_type": "code",
130
- "execution_count": null,
131
- "metadata": {},
132
- "outputs": [],
133
- "source": [
134
- "# Check if all images are present in final stimuli folder\n",
135
- "count_not_found = 0\n",
136
- "stim_path = f\"stimuli_v{experiment_version}/\"\n",
137
- "for index, row in df_exp.iterrows():\n",
138
- " if not (os.path.exists(f\"{stim_path}{row['stim1']}.png\")):\n",
139
- " print(f\"{row['stim1']}.png\")\n",
140
- " count_not_found += 1\n",
141
- " if not (os.path.exists(f\"{stim_path}{row['stim2']}.png\")):\n",
142
- " print(f\"{row['stim2']}.png\")\n",
143
- " count_not_found += 1\n",
144
- " if not (os.path.exists(f\"{stim_path}{row['stim3']}.png\")):\n",
145
- " print(f\"{row['stim3']}.png\")\n",
146
- " count_not_found += 1\n",
147
- "print(count_not_found)"
148
- ]
149
- },
150
- {
151
- "cell_type": "code",
152
- "execution_count": null,
153
- "metadata": {},
154
- "outputs": [],
155
- "source": [
156
- "#Add participant ID column\n",
157
- "pIDs = []\n",
158
- "for i in range(len(df_exp)):\n",
159
- " pIDs.append(i // 60)\n",
160
- "df_exp.insert(0, \"pID\", pIDs)\n",
161
- "print(len(df_exp[(df_exp['pID'] == 0)]))\n",
162
- "#Add catch trials within each pID section\n",
163
- "for pID in range(max(pIDs)):\n",
164
- " df_pid = df_exp[(df_exp['experiment'] == 1) & (df_exp['pID'] == pID)]\n",
165
- " \n",
166
- " # Ground truth catch trials\n",
167
- " gt_catch_trials = df_pid.sample(n=9)\n",
168
- " gt_catch_trials['catch_trial'] = \"ground_truth\"\n",
169
- " for index, row in gt_catch_trials.iterrows():\n",
170
- " \n",
171
- " order = random.randrange(2)\n",
172
- " ground_truth = row['stim1']\n",
173
- " stims = [row['stim2'], ground_truth]\n",
174
- " \n",
175
- " gt_catch_trials.at[index, 'stim2'] = stims.pop(order)\n",
176
- " gt_catch_trials.at[index, 'stim3'] = stims.pop()\n",
177
- " # Target on left here means the ground truth repeat is on the left\n",
178
- " gt_catch_trials.at[index, 'target_on_left'] = (order == 1)\n",
179
- " \n",
180
- " # repeated trial catch trials, first sample indices\n",
181
- " sampled_indices = df_pid.sample(n=9).index\n",
182
- " #mark the trials at these indices as catch trials\n",
183
- " df_exp.loc[sampled_indices]['catch_trial'] = \"repeat\"\n",
184
- " #create duplicate trials for these samples to repeat\n",
185
- " repeat_catch_trials_rep1 = df_exp.loc[sampled_indices].copy()\n",
186
- " repeat_catch_trials_rep2 = df_exp.loc[sampled_indices].copy()\n",
187
- " repeat_catch_trials_rep1['rep'] = 1\n",
188
- " repeat_catch_trials_rep2['rep'] = 2\n",
189
- " \n",
190
- " \n",
191
- " df_exp = pd.concat([df_exp, gt_catch_trials, repeat_catch_trials_rep1, repeat_catch_trials_rep2])\n",
192
- " \n",
193
- "df_exp = df_exp.sample(frac=1).sort_values(by='pID', kind='mergesort')\n",
194
- "print(len(df_exp))\n",
195
- "print(len(df_exp[(df_exp['pID'] == 0)]))"
196
- ]
197
- },
198
- {
199
- "cell_type": "code",
200
- "execution_count": null,
201
- "metadata": {},
202
- "outputs": [],
203
- "source": [
204
- "\n",
205
- "df_exp.to_csv(f'dataframes_v{experiment_version}/experiment_v{experiment_version}.csv', index=False)\n",
206
- "\n",
207
- "df_exp_tsv = df_exp[['pID', 'stim1', 'stim2', 'stim3']].copy()\n",
208
- "df_exp_tsv.to_csv(f\"dataframes_v{experiment_version}/meadow_trials_v{experiment_version}.tsv\", sep=\"\\t\", index=False, header=False) "
209
- ]
210
- },
211
- {
212
- "cell_type": "markdown",
213
- "metadata": {},
214
- "source": [
215
- "# THE FOLLOWING CELLS ARE FOR PROCESSING RESPONSES"
216
- ]
217
- },
218
- {
219
- "cell_type": "code",
220
- "execution_count": null,
221
- "metadata": {},
222
- "outputs": [],
223
- "source": [
224
- "response_path = f\"responses_v{experiment_version}/\"\n",
225
- "dataframe_path = f\"dataframes_v{experiment_version}/\"\n",
226
- "df_experiment = pd.read_csv(dataframe_path + f\"experiment_v{experiment_version}.csv\")\n",
227
- "response_version = \"2\"\n",
228
- "df_responses = pd.read_csv(f\"{response_path}deployment_v{response_version}.csv\")\n",
229
- "print(df_responses)"
230
- ]
231
- },
232
- {
233
- "cell_type": "code",
234
- "execution_count": null,
235
- "metadata": {},
236
- "outputs": [],
237
- "source": [
238
- "df_responses.head()\n",
239
- "df_trial = pd.DataFrame(columns=[\"experiment\", \"stim1\", \"stim2\", \"stim3\", \"sample\", \"subject\", \"target_on_left\", \"method\", \"catch_trial\", \"rep\", \"picked_left\", \"participant\"])\n",
240
- "df_experiment['picked_left'] = None\n",
241
- "for index, row in tqdm(df_responses.iterrows()):\n",
242
- " if row['label'] == row['stim2_id']:\n",
243
- " picked_left = True\n",
244
- " elif row['label'] == row['stim3_id']:\n",
245
- " picked_left = False\n",
246
- " else:\n",
247
- " print(\"Error\")\n",
248
- " break\n",
249
- " start_timestamp = row['time_trial_start']\n",
250
- " end_timestamp = row['time_trial_response']\n",
251
- " start = datetime.fromisoformat(start_timestamp.replace(\"Z\", \"+00:00\"))\n",
252
- " end = datetime.fromisoformat(end_timestamp.replace(\"Z\", \"+00:00\"))\n",
253
- " # Calculate the difference in seconds\n",
254
- " time_difference_seconds = (end - start).total_seconds()\n",
255
- " \n",
256
- " df_trial.loc[index] = df_experiment[(df_experiment['stim1'] == row['stim1_name']) & (df_experiment['stim2'] == row['stim2_name']) & (df_experiment['stim3'] == row['stim3_name'])].iloc[0]\n",
257
- " df_trial.loc[index, 'picked_left'] = picked_left\n",
258
- " df_trial.loc[index, 'participant'] = row['participation']\n",
259
- " df_trial.loc[index, 'response_time'] = time_difference_seconds\n",
260
- " \n",
261
- "df_trial[\"picked_target\"] = df_trial[\"picked_left\"] == df_trial[\"target_on_left\"]\n",
262
- "print(df_trial)"
263
- ]
264
- },
265
- {
266
- "cell_type": "code",
267
- "execution_count": null,
268
- "metadata": {},
269
- "outputs": [],
270
- "source": [
271
- "# number of participants\n",
272
- "print(\"Total participants:\", len(df_trial[\"participant\"].unique()))\n",
273
- "# print(df_trial)\n",
274
- "\n",
275
- "# Remove participants who failed the ground truth catch trial, no tolerance\n",
276
- "participants_to_remove_rule1 = df_trial[(df_trial['catch_trial'] == 'ground_truth') & (df_trial['picked_target'] == False)]['participant'].unique()\n",
277
- "print(\"Participants to remove 1:\", participants_to_remove_rule1)\n",
278
- "# Remove participants who failed the repeat catch trial, and gave different responses for identical trials\n",
279
- "repeat_trials = df_trial[df_trial['rep'] > 0]\n",
280
- "\n",
281
- "# Group by the 3 stimuli presented to identify unique sets of trials\n",
282
- "grouped_repeat_trials = repeat_trials.groupby(['stim1', 'stim2', 'stim3'])\n",
283
- "\n",
284
- "# Track participant failures\n",
285
- "participant_failures = {}\n",
286
- "\n",
287
- "# Iterate through groups to check consistency in \"picked_target\" across repetitions\n",
288
- "for _, group in grouped_repeat_trials:\n",
289
- " if group['picked_target'].nunique() != 1: # Inconsistent \"picked_target\" within the group\n",
290
- " print(group['picked_target'])\n",
291
- " for participant in group['participant'].unique(): \n",
292
- " participant_failures[participant] = participant_failures.get(participant, 0) + 1\n",
293
- "\n",
294
- "# Identify participants who failed at least one set of trial repetitions\n",
295
- "participants_to_remove_rule2 = [participant for participant, failures in participant_failures.items() if failures > 1]\n",
296
- "print(\"Participants to remove 2:\", participants_to_remove_rule2)\n",
297
- "participants_to_remove = set(participants_to_remove_rule1).union(set(participants_to_remove_rule2))\n",
298
- "filtered_df = df_trial[~df_trial['participant'].isin(participants_to_remove)]\n",
299
- "print(\"Clean participants:\", len(filtered_df[\"participant\"].unique()))\n",
300
- "print(len(df_trial), len(filtered_df))\n",
301
- "print(participants_to_remove)\n",
302
- "filtered_df.to_csv(f'{dataframe_path}filtered_responses_v{response_version}.csv', index=False)"
303
- ]
304
- },
305
- {
306
- "cell_type": "code",
307
- "execution_count": null,
308
- "metadata": {},
309
- "outputs": [],
310
- "source": [
311
- "# Load filtered responses\n",
312
- "filtered_df = pd.read_csv(f'{dataframe_path}filtered_responses_v{response_version}.csv')\n",
313
- "# Filter out catch trials\n",
314
- "df_trial_exp = filtered_df[(filtered_df['catch_trial'].isnull() & (filtered_df['rep'] == 0))]\n",
315
- "\n",
316
- "# Grab results from an individual experiment and print them out\n",
317
- "df_trial_exp1 = df_trial_exp[df_trial_exp['experiment'] == 1]\n",
318
- "print(\"Number of experiment trials:\", len(df_trial_exp1))\n",
319
- "print(\"Success rate: \", len(df_trial_exp1[df_trial_exp1[\"picked_target\"]]) / len(df_trial_exp1))\n"
320
- ]
321
- }
322
- ],
323
- "metadata": {
324
- "kernelspec": {
325
- "display_name": "SS",
326
- "language": "python",
327
- "name": "python3"
328
- },
329
- "language_info": {
330
- "codemirror_mode": {
331
- "name": "ipython",
332
- "version": 3
333
- },
334
- "file_extension": ".py",
335
- "mimetype": "text/x-python",
336
- "name": "python",
337
- "nbconvert_exporter": "python",
338
- "pygments_lexer": "ipython3",
339
- "version": "3.10.12"
340
- }
341
- },
342
- "nbformat": 4,
343
- "nbformat_minor": 2
344
- }