File size: 30,682 Bytes
4ba4ba4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "ab23242e-3c5e-4ba6-9cb9-dfc4d8c22321",
   "metadata": {},
   "source": [
    "<img src=\"./figs/IOAI-Logo.png\" alt=\"IOAI Logo\" width=\"200\" height=\"auto\">\n",
    "\n",
    "[IOAI 2025 (Beijing, China), Individual Contest](https://ioai-official.org/china-2025)\n",
    "\n",
    "[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/IOAI-official/IOAI-2025/blob/main/Individual-Contest/Radar/Solution/Radar_Solution.ipynb)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f2ea67c2-ec81-4ced-b8a4-a19b591376bb",
   "metadata": {},
   "source": [
    "# Radar: Reference Solution"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "97ae6685",
   "metadata": {},
   "source": [
    "## Configs"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "4243ca5d",
   "metadata": {
    "jupyter": {
     "source_hidden": false
    }
   },
   "outputs": [],
   "source": [
    "radar_configs = {\n",
    "    'c': 3e8, \n",
    "    'startFreq': 77e9, \n",
    "    'Tr': 60e-6,                    # Sweeping frequency time\n",
    "    'Idle_time': 100e-6,            # free time\n",
    "    'Fs': 10e6,                     # Sampling frequency\n",
    "    'Slope': 29.982e12,             # chirp slope\n",
    "    'Bandwidth': 60e-6 * 29.982e12, # Transmission signal bandwidth\n",
    "    'BandwidthValid': 0.767539200e9,# Effective bandwidth of the transmitted signal\n",
    "    'range_size': 256,              # range size\n",
    "    'azimuth_size': 181,            # azimuth size\n",
    "    'elevation_size': 181,          # elevation size\n",
    "    'crop_num': 3,                  # crop some indices in range domain\n",
    "    'n_chirps': 128,                # number of chirps in one frame\n",
    "    'min_azimuth': -90,             # min radar azimuth\n",
    "    'max_azimuth': 90,              # max radar azimuth\n",
    "    'min_elevation': -90,           # min radar elevation\n",
    "    'max_elevation': 90,            # max radar elevation    \n",
    "    'min_range': 1.0,               # min radar range\n",
    "    'max_range': 25.0,              # max radar range\n",
    "    'range_res': 3e8/(2*0.767539200e9), \n",
    "    'angle_res': 1\n",
    "}\n",
    "\n",
    "dimssnet_configs = {\n",
    "    'n_epoch': 10,\n",
    "    'batch_size': 2,\n",
    "    'learning_rate': 1e-5,\n",
    "    'range_size': 50,\n",
    "    'azimuth_size': 181,\n",
    "    'elevation_size': 181,\n",
    "    'doppler_size': 181, \n",
    "    'min_azimuth': -90,             # min radar azimuth\n",
    "    'max_azimuth': 90,              # max radar azimuth\n",
    "    'min_elevation': -90,           # min radar elevation\n",
    "    'max_elevation': 90,            # max radar elevation    \n",
    "    'min_range': 1.0,               # min radar range\n",
    "    'max_range': 25.0,              # max radar range\n",
    "}\n",
    "\n",
    "n_class = 5\n",
    "class_table = {\n",
    "    -1: 'background', \n",
    "    0: 'suicase', \n",
    "    1: 'chair', \n",
    "    2: 'person',\n",
    "    3: 'wall'\n",
    "}"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c39a54f5",
   "metadata": {},
   "source": [
    "## Models"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "10817ce8",
   "metadata": {
    "jupyter": {
     "source_hidden": false
    }
   },
   "outputs": [],
   "source": [
    "import torch\n",
    "import torch.nn as nn\n",
    "import torch.nn.functional as F\n",
    "\n",
    "class BaseEncoder(nn.Module):\n",
    "    def __init__(self):\n",
    "        super(BaseEncoder, self).__init__()\n",
    "        self.conv1a = nn.Conv2d(in_channels=1, out_channels=64, \n",
    "                                kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))\n",
    "        self.conv1b = nn.Conv2d(in_channels=64, out_channels=64, \n",
    "                                kernel_size=(3, 3), stride=(2, 2), padding=(1, 1))\n",
    "        self.conv2a = nn.Conv2d(in_channels=64, out_channels=128, \n",
    "                                kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))\n",
    "        self.conv2b = nn.Conv2d(in_channels=128, out_channels=128, \n",
    "                                kernel_size=(3, 3), stride=(2, 2), padding=(1, 1))\n",
    "        self.conv3a = nn.Conv2d(in_channels=128, out_channels=256, \n",
    "                                kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))\n",
    "        self.conv3b = nn.Conv2d(in_channels=256, out_channels=256, \n",
    "                                kernel_size=(3, 3), stride=(2, 2), padding=(1, 1))\n",
    "\n",
    "        self.bn1a = nn.BatchNorm2d(num_features=64)\n",
    "        self.bn1b = nn.BatchNorm2d(num_features=64)\n",
    "        self.bn2a = nn.BatchNorm2d(num_features=128)\n",
    "        self.bn2b = nn.BatchNorm2d(num_features=128)\n",
    "        self.bn3a = nn.BatchNorm2d(num_features=256)\n",
    "        self.bn3b = nn.BatchNorm2d(num_features=256)\n",
    "\n",
    "        self.relu = nn.ReLU()\n",
    "        \n",
    "    def forward(self, x):\n",
    "        x = self.relu(self.bn1a(self.conv1a(x)))\n",
    "        x = self.relu(self.bn1b(self.conv1b(x)))\n",
    "        x = self.relu(self.bn2a(self.conv2a(x)))\n",
    "        x = self.relu(self.bn2b(self.conv2b(x)))\n",
    "        x = self.relu(self.bn3a(self.conv3a(x)))\n",
    "        x = self.relu(self.bn3b(self.conv3b(x)))\n",
    "        \n",
    "        return x\n",
    "\n",
    "\n",
    "class BaseDecoder(nn.Module):\n",
    "    def __init__(self):\n",
    "        super(BaseDecoder, self).__init__()\n",
    "        self.convt1 = nn.ConvTranspose2d(in_channels=256, out_channels=128,\n",
    "                                         kernel_size=(3, 3), stride=(2, 2), padding=(1, 1))\n",
    "        self.convt2 = nn.ConvTranspose2d(in_channels=128, out_channels=64,\n",
    "                                         kernel_size=(3, 3), stride=(2, 2), padding=(1, 1))\n",
    "        self.convt3 = nn.ConvTranspose2d(in_channels=64, out_channels=32,\n",
    "                                         kernel_size=(3, 3), stride=(2, 2), padding=(1, 1))\n",
    "        self.prelu = nn.PReLU()\n",
    "\n",
    "    def forward(self, x):\n",
    "        x = self.prelu(self.convt1(x))\n",
    "        x = self.prelu(self.convt2(x))\n",
    "        x = self.prelu(self.convt3(x))\n",
    "\n",
    "        return x"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ddb913e6",
   "metadata": {
    "jupyter": {
     "source_hidden": false
    }
   },
   "outputs": [],
   "source": [
    "range_size=radar_configs['range_size']\n",
    "azimuth_size=radar_configs['azimuth_size']\n",
    "elevation_size=radar_configs['elevation_size']\n",
    "\n",
    "class Fuse_fea(nn.Module):\n",
    "    def __init__(self):\n",
    "        super(Fuse_fea, self).__init__()\n",
    "        self.convt1 = nn.Conv2d(in_channels=192, out_channels=96,\n",
    "                                kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))\n",
    "        self.convt2 = nn.Conv2d(in_channels=96, out_channels=48,\n",
    "                                kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))\n",
    "        self.convt3 = nn.Conv2d(in_channels=48, out_channels=24,\n",
    "                                kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))\n",
    "        self.convt4 = nn.Conv2d(in_channels=24, out_channels=n_class,\n",
    "                                kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))        \n",
    "        self.relu = nn.ReLU()\n",
    "        self.sigmoid = nn.Sigmoid()\n",
    "\n",
    "    def forward(self, feas_sra, feas_dra, feas_sre, feas_dre, feas_srd, feas_drd):\n",
    "        feas_sre = torch.sum(feas_sre, 3, keepdim=True) # (B, 32, 50, 181) -> (B, 32, 50, 1)\n",
    "        feas_sre = feas_sre.expand(-1, -1, -1, azimuth_size)\n",
    "        \n",
    "        feas_dre = torch.sum(feas_dre, 3, keepdim=True)  # (B, 32, 50, 181) -> (B, 32, 50, 1)\n",
    "        feas_dre = feas_dre.expand(-1, -1, -1, azimuth_size)\n",
    "\n",
    "        feas_srd = torch.sum(feas_srd, 3, keepdim=True)  # (B, 32, 50, 181) -> (B, 32, 50, 1)\n",
    "        feas_srd = feas_srd.expand(-1, -1, -1, azimuth_size)\n",
    "\n",
    "        feas_drd = torch.sum(feas_drd, 3, keepdim=True)  # (B, 32, 50, 181) -> (B, 32, 50, 1)\n",
    "        feas_drd = feas_drd.expand(-1, -1, -1, azimuth_size)\n",
    "\n",
    "        # Resize using bilinear interpolation\n",
    "        feas_sra = F.interpolate(feas_sra, size=(range_size, azimuth_size), mode='bilinear', align_corners=False)\n",
    "        feas_dra = F.interpolate(feas_dra, size=(range_size, azimuth_size), mode='bilinear', align_corners=False)\n",
    "        feas_sre = F.interpolate(feas_sre, size=(range_size, azimuth_size), mode='bilinear', align_corners=False)\n",
    "        feas_dre = F.interpolate(feas_dre, size=(range_size, azimuth_size), mode='bilinear', align_corners=False)\n",
    "        feas_srd = F.interpolate(feas_srd, size=(range_size, azimuth_size), mode='bilinear', align_corners=False)\n",
    "        feas_drd = F.interpolate(feas_drd, size=(range_size, azimuth_size), mode='bilinear', align_corners=False)\n",
    "        \n",
    "        feas_ra = torch.cat((feas_sra, feas_dra, feas_sre, feas_dre, feas_srd, feas_drd), 1) # 6*(B, 32, 50, 181) -> (B, 192, 50, 181)\n",
    "\n",
    "        x = self.relu(self.convt1(feas_ra))  # (B, 192, 50, 181) -> (B, 96, 50, 181)\n",
    "        x = self.relu(self.convt2(x))  # (B, 96, 50, 181) -> (B, 48, 50, 181)\n",
    "        x = self.relu(self.convt3(x))  # (B, 48, 50, 181) -> (B, 24, 50, 181)        \n",
    "        x = self.sigmoid(self.convt4(x))  # (B, 24, 50, 181) -> (B, 5, 50, 181)\n",
    "        \n",
    "        return x\n",
    "    "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "483a5ba6",
   "metadata": {
    "jupyter": {
     "source_hidden": false
    }
   },
   "outputs": [],
   "source": [
    "class DIMSSNet(nn.Module):\n",
    "    def __init__(self):\n",
    "        super(DIMSSNet, self).__init__()\n",
    "        self.encode_sra, self.decode_sra = BaseEncoder(), BaseDecoder()\n",
    "        self.encode_dra, self.decode_dra = BaseEncoder(), BaseDecoder()\n",
    "        self.encode_sre, self.decode_sre = BaseEncoder(), BaseDecoder()\n",
    "        self.encode_dre, self.decode_dre = BaseEncoder(), BaseDecoder()\n",
    "        self.encode_srd, self.decode_srd = BaseEncoder(), BaseDecoder()\n",
    "        self.encode_drd, self.decode_drd = BaseEncoder(), BaseDecoder()\n",
    "        \n",
    "        self.fuse_fea = Fuse_fea()\n",
    "        \n",
    "    def forward(self, x_sra, x_dra, x_sre, x_dre, x_srd, x_drd):\n",
    "        x_sra = self.encode_sra(x_sra)\n",
    "        feas_sra = self.decode_sra(x_sra)  # (B, 32, 50, 181)\n",
    "        \n",
    "        x_dra = self.encode_dra(x_dra)\n",
    "        feas_dra = self.decode_dra(x_dra)  # (B, 32, 50, 181)\n",
    "        \n",
    "        x_sre = self.encode_sre(x_sre)\n",
    "        feas_sre = self.decode_sre(x_sre)  # (B, 32, 50, 181)\n",
    "        \n",
    "        x_dre = self.encode_dre(x_dre)\n",
    "        feas_dre = self.decode_dre(x_dre)  # (B, 32, 50, 181)\n",
    "\n",
    "        x_srd = self.encode_sre(x_srd)\n",
    "        feas_srd = self.decode_sre(x_srd)  # (B, 32, 50, 181)\n",
    "        \n",
    "        x_drd = self.encode_dre(x_drd)\n",
    "        feas_drd = self.decode_dre(x_drd)  # (B, 32, 50, 181)        \n",
    "        \n",
    "        feas = self.fuse_fea(feas_sra, feas_dra, feas_sre, feas_dre, feas_srd, feas_drd) # (B, 32, 50, 181)\n",
    "\n",
    "        return feas"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b8d86ece",
   "metadata": {},
   "source": [
    "## Utils"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "49705a8f",
   "metadata": {
    "jupyter": {
     "source_hidden": false
    }
   },
   "outputs": [],
   "source": [
    "import scipy.io\n",
    "import numpy as np\n",
    "\n",
    "# Define the target size\n",
    "TARGET_HEIGHT = 50\n",
    "TARGET_WIDTH = 181\n",
    "\n",
    "def load_raw_data(file_path):\n",
    "    data = scipy.io.loadmat(file_path)\n",
    "\n",
    "    # Range-Azimuth Static\n",
    "    range_az_static = data['range_az_static']\n",
    "    range_az_static_prob = data['range_az_music_average_static_probability']\n",
    "    range_az_static_class2_prob = range_az_static_prob[:, :, 1]\n",
    "\n",
    "    # Range-Elevation Static\n",
    "    range_ele_static = data['range_ele_static_all']\n",
    "\n",
    "    # Range-Azimuth Dynamic\n",
    "    range_az_dynamic = data['range_az_dynamic']\n",
    "    range_az_dynamic_prob = data['range_az_music_average_dynamic_probability']\n",
    "    range_az_dynamic_class1_prob = range_az_dynamic_prob[:, :, 0]\n",
    "\n",
    "    # Range-Elevation Dynamic\n",
    "    range_ele_dynamic = data['range_ele_dynamic_all'] \n",
    "\n",
    "    return [range_az_static, range_az_dynamic, range_ele_static,\n",
    "            range_ele_dynamic, range_az_dynamic_class1_prob, range_az_static_class2_prob]\n",
    "\n",
    "def generate_parameter():\n",
    "    parameter = {\n",
    "        'c': 3e8,  # the speed of light\n",
    "        'start_freq': 77e9,  # starting frequency\n",
    "        'tr': 60e-6,  # Sweeping time, that is, the cycle\n",
    "        'samples': 256,  # sampling point\n",
    "        'fs': 10e6,  # Sampling rate\n",
    "        'tframe_set': 80e-3,  # Frame period\n",
    "        'range_bin': 256,  # range bin\n",
    "        'chirps': 128,  # chirp number\n",
    "        'doppler_bin': 128,  # doppler bin\n",
    "        'slope': 29.982e12,  # chirp slope\n",
    "        'bandwidth': 29.982e12 * 60e-6,  # Effective bandwidth of the transmitted signal\n",
    "        'bandwidth_valid': 256 / 10e6 * 29.982e12,  # Transmission signal bandwidth\n",
    "        'center_freq': 77e9 + (29.982e12 * 60e-6) / 2,  # center frequency\n",
    "        'lambda': 3e8 / (77e9 + (29.982e12 * 60e-6) / 2),  # wavelength\n",
    "        'tx_antenna': [1, 1, 1],  # The number of transmitting antennas\n",
    "        'rx_antenna': [1, 1, 1, 1],  # Number of receiving antennas\n",
    "        'tx_num': 3,  # The number of transmitting antennas\n",
    "        'rx_num': 4,  # The number of receiving antennas\n",
    "        'virtual_antenna': 12,  # Number of virtual antennas\n",
    "        'dz': (3e8 / (77e9 + (29.982e12 * 60e-6) / 2)) / 2,  # Pitch spacing of the receiving antenna\n",
    "        'dx': (3e8 / (77e9 + (29.982e12 * 60e-6) / 2)) / 2,  # Horizontal spacing of receiving antennas\n",
    "        'num_cpi': 50,  # frames\n",
    "    }\n",
    "    return parameter\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c266f24b",
   "metadata": {},
   "source": [
    "## Dataloaders"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "892cfb3a",
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "from torch.utils.data import Dataset, DataLoader\n",
    "from sklearn.model_selection import train_test_split\n",
    "\n",
    "class CustomDataset(Dataset):\n",
    "    def __init__(self, file_paths, transform=None):\n",
    "        self.file_paths = file_paths\n",
    "        self.transform = transform\n",
    "        self.file_names = [os.path.basename(path) for path in file_paths]\n",
    "\n",
    "    def __len__(self):\n",
    "        return len(self.file_paths)\n",
    "\n",
    "    def __getitem__(self, idx):\n",
    "        data = torch.load(self.file_paths[idx], weights_only=True)\n",
    "        \n",
    "        images = data[:6]  #first 6 channels are the heatmaps\n",
    "        labels = data[6]   #last channel is the label\n",
    "        \n",
    "        images = images.float()  \n",
    "        labels = labels.long()   \n",
    "        labels = labels + 1     #labels are -1 to 3, add 1 to make them 0 to 4\n",
    "\n",
    "        if self.transform:\n",
    "            images = self.transform(images)\n",
    "            labels = self.transform(labels)\n",
    "        \n",
    "        return images, labels, self.file_names[idx]\n",
    "\n",
    "class CustomDataset_test(Dataset):\n",
    "    def __init__(self, file_paths, transform=None):\n",
    "        self.file_paths = file_paths\n",
    "        self.transform = transform\n",
    "        self.file_names = [os.path.basename(path) for path in file_paths]\n",
    "\n",
    "    def __len__(self):\n",
    "        return len(self.file_paths)\n",
    "\n",
    "    def __getitem__(self, idx):\n",
    "        data = torch.load(self.file_paths[idx], weights_only=True)\n",
    "        \n",
    "        images = data[:6] #only load first 6 channels, labels are not in val_set and test_set\n",
    "        \n",
    "        images = images.float()  \n",
    "\n",
    "        if self.transform:\n",
    "            images = self.transform(images)\n",
    "        \n",
    "        return images, self.file_names[idx]\n",
    "\n",
    "# extend base_path to file_path\n",
    "def generate_file_paths(base_path):\n",
    "    file_paths = []\n",
    "    for frame in os.listdir(base_path):\n",
    "        frame_path = os.path.join(base_path, frame)\n",
    "        if frame_path.endswith('.mat.pt'):\n",
    "            file_paths.append(frame_path)\n",
    "    return [path for path in file_paths if os.path.exists(path)]\n",
    "\n",
    "def load_data(base_path, batch_size=4, num_workers=2, test_size=0.2):\n",
    "    file_paths = generate_file_paths(base_path)\n",
    "    \n",
    "    train_paths, test_paths = train_test_split(file_paths, test_size=test_size, random_state=42)\n",
    "    \n",
    "    train_dataset = CustomDataset(file_paths=train_paths)\n",
    "    test_dataset = CustomDataset(file_paths=test_paths)\n",
    "    \n",
    "    train_loader = DataLoader(\n",
    "        train_dataset, \n",
    "        batch_size=batch_size, \n",
    "        shuffle=True, \n",
    "        num_workers=num_workers, \n",
    "        drop_last=True\n",
    "    )\n",
    "    \n",
    "    test_loader = DataLoader(\n",
    "        test_dataset, \n",
    "        batch_size=batch_size, \n",
    "        shuffle=False, \n",
    "        num_workers=num_workers, \n",
    "        drop_last=True\n",
    "    )\n",
    "    \n",
    "    return train_loader, test_loader\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "67cd6c15",
   "metadata": {},
   "source": [
    "## Loss Function"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "4c573803",
   "metadata": {},
   "outputs": [],
   "source": [
    "#Used to handle the problem of class imbalance\n",
    "\n",
    "def to_one_hot(tensor, nClasses):\n",
    "    n, h, w = tensor.size()\n",
    "    one_hot = torch.zeros(n, nClasses, h, w, device=tensor.device)\n",
    "    index_tensor = tensor.long().view(n, 1, h, w)\n",
    "    one_hot = one_hot.scatter_(1, index_tensor, 1)\n",
    "    return one_hot\n",
    "\n",
    "def _neg_loss(pred, gt):\n",
    "    pred = torch.clamp(pred, 1e-5, 1-1e-5)\n",
    "\n",
    "    pos_inds = gt.eq(1).float()\n",
    "    neg_inds = gt.eq(0).float()\n",
    "\n",
    "    balance_cof = 1.0\n",
    "    pos_loss = torch.log(pred) * torch.pow(1 - pred, 2) * pos_inds * balance_cof\n",
    "    neg_loss = torch.log(1 - pred) * torch.pow(pred, 2) * neg_inds\n",
    "    num_pos = pos_inds.float().sum()\n",
    "    pos_loss_sum = pos_loss.sum()\n",
    "    neg_loss_sum = neg_loss.sum()\n",
    "    if num_pos == 0:\n",
    "        loss = -neg_loss_sum\n",
    "    else:\n",
    "        loss = -(pos_loss_sum + neg_loss_sum) / num_pos\n",
    "    return loss\n",
    "\n",
    "class FocalLoss(nn.Module):\n",
    "    def __init__(self):\n",
    "        super(FocalLoss, self).__init__()\n",
    "        self.neg_loss = _neg_loss\n",
    "\n",
    "    def forward(self, out, target):\n",
    "        return self.neg_loss(out, target)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "dec2b582",
   "metadata": {},
   "source": [
    "## Train"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "7c2f0301",
   "metadata": {},
   "outputs": [],
   "source": [
    "import torch.optim as optim\n",
    "import matplotlib.pyplot as plt\n",
    "import time\n",
    "\n",
    "device = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n",
    "\n",
    "num_epochs = 20\n",
    "\n",
    "base_path = '../training_set'\n",
    "train_loader, test_loader = load_data(\n",
    "    base_path=base_path,\n",
    "    batch_size=4,\n",
    "    num_workers=2,\n",
    "    test_size=0.2\n",
    ")\n",
    "\n",
    "dimssnet = DIMSSNet().to(device)\n",
    "criterion = FocalLoss()\n",
    "optimizer = optim.Adam(dimssnet.parameters(), lr=0.001)\n",
    "start_time = time.time()\n",
    "test_loss_record = []\n",
    "train_loss_record = []\n",
    "\n",
    "for epoch in range(num_epochs):\n",
    "    dimssnet.train()\n",
    "    running_loss = 0.0\n",
    "    for images, labels, _ in train_loader:\n",
    "        images = images.to(device)\n",
    "        labels = labels.to(device)\n",
    "        \n",
    "        images = [image.unsqueeze(1) for image in images]\n",
    "        images = torch.stack(images, dim=0)\n",
    "        images = images.float()\n",
    "        \n",
    "        outputs = dimssnet(images[:, 0, :, :], images[:, 1, :, :], images[:, 2, :, :],\n",
    "                            images[:, 3, :, :], images[:, 4, :, :], images[:, 5, :, :])\n",
    "\n",
    "        outputs_resized = F.interpolate(outputs, size=(TARGET_HEIGHT, TARGET_WIDTH), mode='bilinear', align_corners=False)\n",
    "        labels = to_one_hot(labels, n_class)\n",
    "        \n",
    "        loss = criterion(outputs_resized, labels.long())\n",
    "        optimizer.zero_grad()\n",
    "        loss.backward()\n",
    "        optimizer.step()\n",
    "        \n",
    "        running_loss += loss.item()\n",
    "\n",
    "    test_loss = 0.0\n",
    "    dimssnet.eval()\n",
    "    with torch.no_grad():\n",
    "        for images, labels, _ in test_loader:\n",
    "            images = images.to(device)\n",
    "            labels = labels.to(device)\n",
    "            \n",
    "            images = [image.unsqueeze(1) for image in images]\n",
    "            images = torch.stack(images, dim=0)\n",
    "            images = images.float()\n",
    "            \n",
    "            outputs = dimssnet(images[:, 0, :, :], images[:, 1, :, :], images[:, 2, :, :],\n",
    "                                images[:, 3, :, :], images[:, 4, :, :], images[:, 5, :, :])\n",
    "            \n",
    "            outputs_resized = F.interpolate(outputs, size=(TARGET_HEIGHT, TARGET_WIDTH), mode='bilinear', align_corners=False)\n",
    "            labels = to_one_hot(labels, n_class)\n",
    "            \n",
    "            loss = criterion(outputs_resized, labels.long())\n",
    "            test_loss += loss.item()\n",
    "    \n",
    "    test_loss_record.append(test_loss/len(test_loader))\n",
    "    train_loss_record.append(running_loss/len(train_loader))\n",
    "    print(f\"Epoch {epoch+1}/{num_epochs}, Training Loss: {running_loss/len(train_loader):.4f}, Test Loss: {test_loss/len(test_loader):.4f}\")\n",
    "\n",
    "# Create a new state_dict and add the \"model\" prefix, in order to match the loading method in metrics\n",
    "new_state_dict = {}\n",
    "for k, v in dimssnet.state_dict().items():\n",
    "    new_key = f\"model.{k}\" \n",
    "    new_state_dict[new_key] = v\n",
    "\n",
    "print(\"dimssnet successfully saved!\")    \n",
    "print(\"Training finished.\")\n",
    "end_time = time.time()\n",
    "total_time = end_time - start_time\n",
    "print(f\"Training completed in {total_time} seconds\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f001aee8",
   "metadata": {},
   "source": [
    "## Inference"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "8b330819",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Run inference on validation set and testing set\n",
    "import pandas as pd\n",
    "\n",
    "def run_inference(model, data_loader):\n",
    "    model.eval()\n",
    "    predictions = []\n",
    "    filenames = []\n",
    "    \n",
    "    with torch.no_grad():\n",
    "        for images, file_names in data_loader:\n",
    "            images = images.cuda() if torch.cuda.is_available() else images\n",
    "            \n",
    "            x = [image.unsqueeze(1) for image in images]\n",
    "            x = torch.stack(x, dim=0)\n",
    "            x = x.float()\n",
    "            \n",
    "            # Forward propagation\n",
    "            outputs = model(x[:, 0, :, :], x[:, 1, :, :], x[:, 2, :, :],\n",
    "                            x[:, 3, :, :], x[:, 4, :, :], x[:, 5, :, :])\n",
    "            \n",
    "            # Adjust the output size\n",
    "            outputs = F.interpolate(outputs, size=(50, 181), mode='bilinear', align_corners=False)\n",
    "\n",
    "            preds = torch.argmax(outputs, dim=1)\n",
    "            \n",
    "            preds = preds - 1\n",
    "            \n",
    "            for i, pred in enumerate(preds):\n",
    "                predictions.append(pred.cpu().numpy().flatten())\n",
    "                filenames.append(file_names[i])\n",
    "    \n",
    "    return predictions, filenames\n",
    "\n",
    "# Load validation set\n",
    "if os.environ.get('DATA_PATH'):\n",
    "    DATA_PATH = os.environ.get(\"DATA_PATH\") + \"/\" \n",
    "else:\n",
    "    DATA_PATH = \"\"  # Fallback for local testing\n",
    "# Load validation set\n",
    "val_paths = generate_file_paths(DATA_PATH + 'validation_set')\n",
    "val_dataset = CustomDataset_test(file_paths=val_paths)\n",
    "val_loader = DataLoader(\n",
    "    val_dataset,\n",
    "    batch_size=1,\n",
    "    shuffle=False,\n",
    "    num_workers=0\n",
    ")\n",
    "\n",
    "# Load testing set\n",
    "if os.environ.get('DATA_PATH'):\n",
    "    DATA_PATH = os.environ.get(\"DATA_PATH\") + \"/\" \n",
    "else:\n",
    "    DATA_PATH = \"\"  # Fallback for local testing\n",
    "# Load testing set\n",
    "test_paths = generate_file_paths(DATA_PATH + 'testing_set')\n",
    "test_dataset = CustomDataset_test(file_paths=test_paths)\n",
    "test_loader = DataLoader(\n",
    "    test_dataset,\n",
    "    batch_size=1,\n",
    "    shuffle=False,\n",
    "    num_workers=0\n",
    ")\n",
    "\n",
    "# Run inference on validation set\n",
    "print(\"Running inference on validation set...\")\n",
    "val_predictions, val_filenames = run_inference(dimssnet, val_loader)\n",
    "\n",
    "# Save validation results to CSV\n",
    "val_results = []\n",
    "for filename, pred in zip(val_filenames, val_predictions):\n",
    "    # Create a row with filename and flattened predictions\n",
    "    row = {'filename': filename}\n",
    "    for i, p in enumerate(pred):\n",
    "        row[f'pixel_{i}'] = p\n",
    "    val_results.append(row)\n",
    "\n",
    "val_df = pd.DataFrame(val_results)\n",
    "val_df.to_csv('submission_val.csv', index=False)\n",
    "print(f\"Validation results saved to output_validation.csv with shape: {val_df.shape}\")\n",
    "\n",
    "# Run inference on testing set\n",
    "print(\"Running inference on testing set...\")\n",
    "test_predictions, test_filenames = run_inference(dimssnet, test_loader)\n",
    "\n",
    "# Save testing results to CSV\n",
    "test_results = []\n",
    "for filename, pred in zip(test_filenames, test_predictions):\n",
    "    # Create a row with filename and flattened predictions\n",
    "    row = {'filename': filename}\n",
    "    for i, p in enumerate(pred):\n",
    "        row[f'pixel_{i}'] = p\n",
    "    test_results.append(row)\n",
    "\n",
    "test_df = pd.DataFrame(test_results)\n",
    "test_df.to_csv('submission_test.csv', index=False)\n",
    "print(f\"Testing results saved to output_testing.csv with shape: {test_df.shape}\")\n",
    "\n",
    "print(\"\\nInference completed! Results saved to:\")\n",
    "print(\"- submission_val_ref.csv (for validation set leaderboard)\")\n",
    "print(\"- submission_test_ref.csv (for testing set leaderboard)\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "72fde72d",
   "metadata": {},
   "outputs": [],
   "source": [
    "import zipfile\n",
    "import os\n",
    "\n",
    "# Define the files to zip and the zip file name.\n",
    "files_to_zip = ['submission_val.csv', 'submission_test.csv']\n",
    "zip_filename = 'submission.zip'\n",
    "\n",
    "# Create a zip file\n",
    "with zipfile.ZipFile(zip_filename, 'w') as zipf:\n",
    "    for file in files_to_zip:\n",
    "        # Add the file to the zip fil\n",
    "        zipf.write(file, os.path.basename(file))\n",
    "\n",
    "print(f'{zip_filename} Created successfully!')"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "ioai",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.12.11"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}