twarner commited on
Commit
884879e
·
1 Parent(s): f2b4327

updated results ++ styling

Browse files
Files changed (1) hide show
  1. app.py +86 -39
app.py CHANGED
@@ -221,38 +221,62 @@ def plot_brain_slices(data, learning_stage):
221
 
222
  return fig
223
 
 
 
 
 
 
 
 
 
 
 
 
 
 
224
  def plot_results(data, region_acts, temporal_pattern, learning_stage):
225
- fig = plt.figure(figsize=(15,10))
226
- gs = gridspec.GridSpec(2, 2)
 
 
 
227
 
228
- # brain slices
229
- ax1 = plt.subplot(gs[0,:])
230
  mean_activation = data.mean(axis=0)
231
  slice_idx = mean_activation.shape[-1]//2
232
  brain_slice = mean_activation[...,slice_idx]
233
 
234
- # find most active region
235
  peak_coords = np.unravel_index(np.argmax(brain_slice), brain_slice.shape)
 
236
 
 
237
  im = ax1.imshow(brain_slice.T, cmap='hot')
238
  plt.colorbar(im, ax=ax1)
239
- ax1.plot(peak_coords[0], peak_coords[1], 'r*', markersize=15,
240
- label=f'peak ({peak_coords[0]}, {peak_coords[1]})')
241
- ax1.legend()
242
- ax1.set_title(f'brain activation (z={slice_idx})\nlearning stage: {learning_stage:.3f}')
 
 
243
 
244
- # region activations
245
- ax2 = plt.subplot(gs[1,0])
246
- max_region = np.argmax(region_acts)
247
- sns.heatmap(region_acts.reshape(1,-1), cmap='RdBu_r', center=0, ax=ax2)
248
- ax2.set_title(f'region activations\nmost active: {max_region}')
249
- ax2.set_xlabel('brain region')
 
 
250
 
251
- # temporal pattern
252
- ax3 = plt.subplot(gs[1,1])
253
- ax3.plot(temporal_pattern.squeeze())
254
- ax3.set_title('temporal dynamics')
255
- ax3.set_xlabel('time')
 
 
256
 
257
  plt.tight_layout()
258
  return fig
@@ -315,15 +339,13 @@ def process_fmri(file_obj):
315
  except Exception as e:
316
  return f"error in {stage} model: {str(e)}", None
317
 
318
- # enhanced results text w/ peak info
319
- stage_results = "\n".join([
320
- f"{stage.upper()} MODEL:"
321
- f"\nlearning stage: {res['learning_stage']:.3f}"
322
- f"\npeak region: {np.argmax(res['region_activation'])}"
323
- f"\npeak activation: {np.max(res['region_activation']):.3f}"
324
- f"\n"
325
- for stage, res in results.items()
326
- ])
327
 
328
  return stage_results, figs[0]
329
 
@@ -332,16 +354,41 @@ def process_fmri(file_obj):
332
 
333
  iface = gr.Interface(
334
  fn=process_fmri,
335
- inputs=gr.File(label="upload 4D fMRI nifti (.nii/.nii.gz)"),
 
 
 
 
336
  outputs=[
337
- gr.Textbox(label="classification results"),
338
- gr.Plot(label="brain activation + analysis")
 
 
 
 
339
  ],
340
- title="fmri learning stage classifier",
341
- description="upload a 4D fMRI nifti file to classify learning stages and visualize brain patterns",
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
342
  examples=[],
343
- cache_examples=False
344
- )
345
-
346
- if __name__ == "__main__":
347
- iface.launch()
 
221
 
222
  return fig
223
 
224
+ def interpret_learning_stage(score):
225
+ """human-readable learning stage"""
226
+ if score < 0.2:
227
+ return "NOVICE: minimal task familiarity, primarily exploratory behavior"
228
+ elif score < 0.4:
229
+ return "EARLY LEARNING: basic pattern recognition emerging"
230
+ elif score < 0.6:
231
+ return "INTERMEDIATE: developing systematic approach"
232
+ elif score < 0.8:
233
+ return "ADVANCED: robust strategy application"
234
+ else:
235
+ return "EXPERT: automated processing, highly optimized performance"
236
+
237
  def plot_results(data, region_acts, temporal_pattern, learning_stage):
238
+ # 16:9 aspect for modern displays
239
+ fig = plt.figure(figsize=(16, 9))
240
+
241
+ # main brain plot: 60% height
242
+ gs = gridspec.GridSpec(2, 2, height_ratios=[6, 4])
243
 
244
+ # brain visualization (now larger)
245
+ ax1 = plt.subplot(gs[0, :])
246
  mean_activation = data.mean(axis=0)
247
  slice_idx = mean_activation.shape[-1]//2
248
  brain_slice = mean_activation[...,slice_idx]
249
 
250
+ # find activation peaks
251
  peak_coords = np.unravel_index(np.argmax(brain_slice), brain_slice.shape)
252
+ peak_val = brain_slice[peak_coords]
253
 
254
+ # enhanced brain viz
255
  im = ax1.imshow(brain_slice.T, cmap='hot')
256
  plt.colorbar(im, ax=ax1)
257
+ ax1.plot(peak_coords[0], peak_coords[1], 'r*', markersize=15)
258
+
259
+ learning_desc = interpret_learning_stage(learning_stage)
260
+ ax1.set_title(f'brain activation map (axial slice z={slice_idx})\n{learning_desc}',
261
+ fontsize=12, pad=20)
262
+ ax1.axis('off')
263
 
264
+ # region plot (lower left)
265
+ ax2 = plt.subplot(gs[1, 0])
266
+ top_n = 5
267
+ region_ranking = np.argsort(-region_acts.flatten())[:top_n]
268
+ region_data = region_acts.reshape(1,-1)
269
+ sns.heatmap(region_data, cmap='RdBu_r', center=0, ax=ax2)
270
+ ax2.set_title('regional activity profile\n' +
271
+ 'top regions: ' + ', '.join(f'{r}' for r in region_ranking))
272
 
273
+ # temporal dynamics (lower right)
274
+ ax3 = plt.subplot(gs[1, 1])
275
+ ax3.plot(temporal_pattern.squeeze(), 'k-', linewidth=2)
276
+ ax3.set_title('temporal evolution')
277
+ ax3.set_xlabel('time (volumes)')
278
+ ax3.set_ylabel('activation (a.u.)')
279
+ ax3.grid(True, alpha=0.3)
280
 
281
  plt.tight_layout()
282
  return fig
 
339
  except Exception as e:
340
  return f"error in {stage} model: {str(e)}", None
341
 
342
+ stage_results = "fMRI ANALYSIS SUMMARY\n" + "="*50 + "\n\n"
343
+ for stage, res in results.items():
344
+ stage_results += f"MODEL: {stage}\n"
345
+ stage_results += f"learning assessment: {interpret_learning_stage(res['learning_stage'])}\n"
346
+ stage_results += f"confidence score: {res['learning_stage']:.3f}\n"
347
+ stage_results += f"dominant regions: {', '.join(str(r) for r in np.argsort(-res['region_activation'])[:3])}\n"
348
+ stage_results += "-"*50 + "\n\n"
 
 
349
 
350
  return stage_results, figs[0]
351
 
 
354
 
355
  iface = gr.Interface(
356
  fn=process_fmri,
357
+ inputs=gr.File(
358
+ label="fMRI Data Input",
359
+ file_types=[".nii", ".nii.gz"],
360
+ file_count="single"
361
+ ),
362
  outputs=[
363
+ gr.Textbox(
364
+ label="Analysis Results",
365
+ placeholder="Upload an fMRI scan to begin analysis...",
366
+ lines=10
367
+ ),
368
+ gr.Plot(label="Neural Activity Analysis")
369
  ],
370
+ title="🧠 fMRI Learning Stage Classifier",
371
+ description="""
372
+ ## Neural Learning Stage Analysis
373
+
374
+ Upload a 4D fMRI scan to:
375
+ - Classify learning stage progression
376
+ - Visualize brain activation patterns
377
+ - Analyze regional activity profiles
378
+ - Track temporal dynamics
379
+
380
+ Supports standard NIFTI format (.nii/.nii.gz)
381
+ """,
382
+ article="""
383
+ ### interpretation guide
384
+
385
+ - learning stage: ranges from novice (0.0) to expert (1.0)
386
+ - brain map: warmer colors = higher activation
387
+ - regional profile: shows activity across 116 brain regions
388
+ - temporal pattern: activation changes over time
389
+
390
+ model trained on weatherprediction task fMRI data from openneuro ds000052
391
+ """,
392
+ theme="default",
393
  examples=[],
394
+ cache_examples=False