altered CNN, encoder and loss function to achieve better stability, and fixed morphing of the images lower than the desired resolution
@@ -0,0 +1,27 @@
|
|||||||
|
{
|
||||||
|
"name": "MSI Hybrid Workflow",
|
||||||
|
"build": {
|
||||||
|
"dockerfile": "../Dockerfile",
|
||||||
|
"context": ".."
|
||||||
|
},
|
||||||
|
"workspaceFolder": "/app",
|
||||||
|
"customizations": {
|
||||||
|
"vscode": {
|
||||||
|
"settings": {
|
||||||
|
"python.defaultInterpreterPath": "/usr/bin/python3",
|
||||||
|
"julia.executablePath": "/usr/local/bin/julia"
|
||||||
|
},
|
||||||
|
"extensions": [
|
||||||
|
"ms-python.python",
|
||||||
|
"ms-python.vscode-pylance",
|
||||||
|
"charliermarsh.ruff",
|
||||||
|
"julialang.language-julia"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"runArgs": [
|
||||||
|
"--gpus=all",
|
||||||
|
"--shm-size=2gb"
|
||||||
|
],
|
||||||
|
"remoteUser": "root"
|
||||||
|
}
|
||||||
|
Before Width: | Height: | Size: 122 KiB After Width: | Height: | Size: 119 KiB |
|
Before Width: | Height: | Size: 425 KiB After Width: | Height: | Size: 248 KiB |
|
Before Width: | Height: | Size: 402 KiB After Width: | Height: | Size: 241 KiB |
|
Before Width: | Height: | Size: 439 KiB After Width: | Height: | Size: 246 KiB |
|
Before Width: | Height: | Size: 386 KiB After Width: | Height: | Size: 239 KiB |
|
Before Width: | Height: | Size: 436 KiB After Width: | Height: | Size: 227 KiB |
|
Before Width: | Height: | Size: 451 KiB After Width: | Height: | Size: 246 KiB |
|
Before Width: | Height: | Size: 444 KiB After Width: | Height: | Size: 247 KiB |
|
Before Width: | Height: | Size: 405 KiB After Width: | Height: | Size: 246 KiB |
|
Before Width: | Height: | Size: 420 KiB After Width: | Height: | Size: 248 KiB |
|
Before Width: | Height: | Size: 429 KiB After Width: | Height: | Size: 236 KiB |
|
After Width: | Height: | Size: 1.3 MiB |
|
After Width: | Height: | Size: 1.3 MiB |
|
After Width: | Height: | Size: 1.3 MiB |
|
After Width: | Height: | Size: 1.3 MiB |
|
After Width: | Height: | Size: 1.3 MiB |
|
After Width: | Height: | Size: 1.3 MiB |
|
After Width: | Height: | Size: 212 KiB |
@@ -0,0 +1,63 @@
|
|||||||
|
filename,mz,similarity
|
||||||
|
ion_304.0.png,304.0,0.9995666
|
||||||
|
ion_304.33.png,304.33,0.9995666
|
||||||
|
ion_120.31.png,120.31,0.9977955
|
||||||
|
ion_371.63.png,371.63,0.995764
|
||||||
|
ion_286.12.png,286.12,0.99534976
|
||||||
|
ion_261.09.png,261.09,0.99487245
|
||||||
|
ion_238.0.png,238.0,0.9945407
|
||||||
|
ion_335.21.png,335.21,0.99350333
|
||||||
|
ion_69.27.png,69.27,0.99221265
|
||||||
|
ion_186.31.png,186.31,0.99207246
|
||||||
|
ion_228.25.png,228.25,0.991964
|
||||||
|
ion_133.64.png,133.64,0.9919308
|
||||||
|
ion_227.92.png,227.92,0.9915842
|
||||||
|
ion_244.18.png,244.18,0.99153364
|
||||||
|
ion_239.95.png,239.95,0.99102235
|
||||||
|
ion_232.15.png,232.15,0.98982406
|
||||||
|
ion_97.23.png,97.23,0.9894692
|
||||||
|
ion_167.78.png,167.78,0.9894244
|
||||||
|
ion_355.05.png,355.05,0.98924905
|
||||||
|
ion_255.23.png,255.23,0.98897374
|
||||||
|
ion_196.71.png,196.71,0.988899
|
||||||
|
ion_229.88.png,229.88,0.9877535
|
||||||
|
ion_240.93.png,240.93,0.9871814
|
||||||
|
ion_105.68.png,105.68,0.98697543
|
||||||
|
ion_144.37.png,144.37,0.9862776
|
||||||
|
ion_256.21.png,256.21,0.9862302
|
||||||
|
ion_329.04.png,329.04,0.9860908
|
||||||
|
ion_391.14.png,391.14,0.98531795
|
||||||
|
ion_242.88.png,242.88,0.98493713
|
||||||
|
ion_169.73.png,169.73,0.9846555
|
||||||
|
ion_279.94.png,279.94,0.98348063
|
||||||
|
ion_124.54.png,124.54,0.98188335
|
||||||
|
ion_245.16.png,245.16,0.9808812
|
||||||
|
ion_194.76.png,194.76,0.98059267
|
||||||
|
ion_246.13.png,246.13,0.9799091
|
||||||
|
ion_144.69.png,144.69,0.97790337
|
||||||
|
ion_217.85.png,217.85,0.9767251
|
||||||
|
ion_225.97.png,225.97,0.97520435
|
||||||
|
ion_257.19.png,257.19,0.9733879
|
||||||
|
ion_234.1.png,234.1,0.9733616
|
||||||
|
ion_198.66.png,198.66,0.9730791
|
||||||
|
ion_104.7.png,104.7,0.971887
|
||||||
|
ion_214.27.png,214.27,0.9714562
|
||||||
|
ion_252.96.png,252.96,0.9714364
|
||||||
|
ion_249.06.png,249.06,0.9709189
|
||||||
|
ion_146.64.png,146.64,0.9706471
|
||||||
|
ion_81.62.png,81.62,0.97054136
|
||||||
|
ion_372.93.png,372.93,0.9699422
|
||||||
|
ion_269.21.png,269.21,0.96917
|
||||||
|
ion_263.04.png,263.04,0.96838164
|
||||||
|
ion_202.24.png,202.24,0.9664346
|
||||||
|
ion_205.82.png,205.82,0.9639652
|
||||||
|
ion_216.22.png,216.22,0.9632674
|
||||||
|
ion_222.72.png,222.72,0.9614939
|
||||||
|
ion_132.66.png,132.66,0.96099925
|
||||||
|
ion_174.28.png,174.28,0.96078146
|
||||||
|
ion_74.79.png,74.79,0.95929277
|
||||||
|
ion_251.01.png,251.01,0.9586576
|
||||||
|
ion_371.3.png,371.3,0.9537004
|
||||||
|
ion_230.2.png,230.2,0.95332444
|
||||||
|
ion_278.64.png,278.64,0.95315814
|
||||||
|
ion_180.78.png,180.78,0.95183814
|
||||||
|
|
Before Width: | Height: | Size: 28 KiB After Width: | Height: | Size: 26 KiB |
|
After Width: | Height: | Size: 617 KiB |
|
After Width: | Height: | Size: 394 KiB |
|
After Width: | Height: | Size: 359 KiB |
|
After Width: | Height: | Size: 341 KiB |
|
After Width: | Height: | Size: 210 KiB |
|
After Width: | Height: | Size: 211 KiB |
|
After Width: | Height: | Size: 273 KiB |
|
After Width: | Height: | Size: 349 KiB |
|
After Width: | Height: | Size: 364 KiB |
|
After Width: | Height: | Size: 363 KiB |
|
After Width: | Height: | Size: 363 KiB |
@@ -1,589 +0,0 @@
|
|||||||
ion_name,cluster_id,tsne_x,tsne_y
|
|
||||||
ion_100.15.png,6,-40.932426,-10.908073
|
|
||||||
ion_100.48.png,9,21.072824,-16.83617
|
|
||||||
ion_100.8.png,6,-44.621838,-11.493084
|
|
||||||
ion_101.45.png,9,34.47281,-16.28591
|
|
||||||
ion_101.78.png,2,-13.818509,5.9901714
|
|
||||||
ion_102.1.png,6,-39.913902,-7.6706624
|
|
||||||
ion_102.75.png,0,3.711694,2.8761594
|
|
||||||
ion_103.73.png,3,25.524195,5.0248933
|
|
||||||
ion_104.7.png,0,6.3908186,3.1167102
|
|
||||||
ion_105.03.png,5,-32.656612,1.0016607
|
|
||||||
ion_105.68.png,0,4.476362,4.953501
|
|
||||||
ion_106.0.png,0,-3.9591544,5.814191
|
|
||||||
ion_106.65.png,2,-23.629314,13.045395
|
|
||||||
ion_106.98.png,6,-41.06501,-11.841768
|
|
||||||
ion_107.3.png,3,26.141336,5.6587133
|
|
||||||
ion_107.63.png,2,-11.70391,8.273663
|
|
||||||
ion_107.95.png,2,-10.682738,12.293447
|
|
||||||
ion_108.28.png,0,5.4774737,4.7060905
|
|
||||||
ion_108.61.png,3,19.261587,3.6005502
|
|
||||||
ion_108.93.png,7,-33.09098,7.1473045
|
|
||||||
ion_109.26.png,0,2.448873,4.068846
|
|
||||||
ion_109.58.png,3,26.700348,-1.6223453
|
|
||||||
ion_109.91.png,5,-34.37336,5.7190495
|
|
||||||
ion_110.23.png,2,-13.548649,12.304782
|
|
||||||
ion_110.56.png,0,8.171888,6.2068224
|
|
||||||
ion_110.88.png,4,-42.90921,-14.561416
|
|
||||||
ion_111.21.png,7,-32.069893,6.121762
|
|
||||||
ion_111.53.png,9,17.032578,-14.9836
|
|
||||||
ion_111.86.png,6,-41.86804,-12.264283
|
|
||||||
ion_112.18.png,6,-39.195858,-6.9346743
|
|
||||||
ion_112.51.png,9,28.834616,-21.248415
|
|
||||||
ion_112.83.png,4,-45.280384,-14.686986
|
|
||||||
ion_113.16.png,1,-38.0473,-4.6447887
|
|
||||||
ion_113.48.png,9,30.0885,-19.64369
|
|
||||||
ion_113.81.png,6,-39.76301,-10.167555
|
|
||||||
ion_114.13.png,6,-39.21211,-12.458875
|
|
||||||
ion_114.46.png,3,24.479866,-2.5599716
|
|
||||||
ion_114.78.png,6,-41.411972,-8.484517
|
|
||||||
ion_115.11.png,4,-44.946033,-12.730046
|
|
||||||
ion_115.43.png,9,27.25728,-22.379305
|
|
||||||
ion_115.76.png,5,-31.31854,3.8297124
|
|
||||||
ion_116.08.png,6,-41.640984,-11.303868
|
|
||||||
ion_116.73.png,2,-14.471555,5.2624044
|
|
||||||
ion_117.06.png,6,-43.930084,-11.334628
|
|
||||||
ion_117.71.png,0,-0.99251306,12.130675
|
|
||||||
ion_118.03.png,0,-1.974164,14.835406
|
|
||||||
ion_118.68.png,0,5.701814,5.353048
|
|
||||||
ion_119.01.png,7,-30.339453,8.254847
|
|
||||||
ion_119.66.png,0,7.0023146,6.2532473
|
|
||||||
ion_119.98.png,2,-17.69502,10.212994
|
|
||||||
ion_120.31.png,3,25.333418,-2.47145
|
|
||||||
ion_120.63.png,2,-21.46605,14.790991
|
|
||||||
ion_120.96.png,5,-35.361584,3.6481993
|
|
||||||
ion_121.28.png,2,-19.833818,7.7952666
|
|
||||||
ion_121.61.png,9,29.773712,-11.878464
|
|
||||||
ion_121.94.png,7,-30.860514,8.846124
|
|
||||||
ion_122.26.png,2,-12.871035,10.980335
|
|
||||||
ion_122.59.png,3,20.165756,0.8244692
|
|
||||||
ion_122.91.png,1,-37.685265,-1.6078014
|
|
||||||
ion_123.24.png,0,-3.8681993,6.9443965
|
|
||||||
ion_123.56.png,9,31.087072,-19.9912
|
|
||||||
ion_123.89.png,2,-20.36767,12.96694
|
|
||||||
ion_124.21.png,2,-16.67268,10.083388
|
|
||||||
ion_124.54.png,0,0.5643915,11.15306
|
|
||||||
ion_124.86.png,6,-39.107998,-10.219036
|
|
||||||
ion_125.19.png,7,-32.009422,9.557379
|
|
||||||
ion_125.51.png,8,11.884864,-13.311716
|
|
||||||
ion_125.84.png,1,-37.684673,-3.4273758
|
|
||||||
ion_126.16.png,1,-36.814728,-2.23065
|
|
||||||
ion_126.49.png,9,31.721008,-19.458025
|
|
||||||
ion_126.81.png,6,-43.756336,-11.9929285
|
|
||||||
ion_127.14.png,5,-34.404408,4.2661257
|
|
||||||
ion_127.46.png,9,16.890953,-15.761453
|
|
||||||
ion_127.79.png,1,-37.11607,-3.4930828
|
|
||||||
ion_128.11.png,1,-38.135204,-3.4246678
|
|
||||||
ion_128.44.png,9,27.918097,-12.72148
|
|
||||||
ion_128.76.png,1,-36.798344,-4.142718
|
|
||||||
ion_129.09.png,4,-45.294636,-13.309718
|
|
||||||
ion_129.41.png,9,27.155005,-20.287508
|
|
||||||
ion_129.74.png,0,9.277016,2.169231
|
|
||||||
ion_130.06.png,8,12.751752,-11.503576
|
|
||||||
ion_130.39.png,9,27.945795,-23.77022
|
|
||||||
ion_130.71.png,2,-15.9459305,14.688283
|
|
||||||
ion_131.04.png,5,-33.40034,4.365237
|
|
||||||
ion_131.69.png,3,20.051266,5.4822
|
|
||||||
ion_132.01.png,0,-2.6060483,14.521514
|
|
||||||
ion_132.66.png,0,6.651698,5.3709097
|
|
||||||
ion_132.99.png,7,-30.735043,7.1117187
|
|
||||||
ion_133.64.png,0,8.923789,7.2876906
|
|
||||||
ion_133.96.png,2,-17.921602,12.313286
|
|
||||||
ion_134.29.png,0,-8.982729,11.345206
|
|
||||||
ion_134.61.png,0,6.684335,3.9621217
|
|
||||||
ion_134.94.png,6,-39.647675,-9.488616
|
|
||||||
ion_135.27.png,0,-7.147459,11.077727
|
|
||||||
ion_135.59.png,9,31.931988,-11.242002
|
|
||||||
ion_135.92.png,6,-38.679104,-8.646229
|
|
||||||
ion_136.24.png,2,-21.387281,13.0522175
|
|
||||||
ion_136.57.png,9,26.215488,-8.447047
|
|
||||||
ion_136.89.png,6,-39.423294,-11.103563
|
|
||||||
ion_137.22.png,2,-18.702082,11.593917
|
|
||||||
ion_137.54.png,0,4.5336566,9.587065
|
|
||||||
ion_137.87.png,2,-20.39063,8.51847
|
|
||||||
ion_138.19.png,0,-3.517939,7.195597
|
|
||||||
ion_138.52.png,8,10.112699,-13.610569
|
|
||||||
ion_138.84.png,6,-39.930943,-11.200036
|
|
||||||
ion_139.17.png,2,-21.219393,9.426966
|
|
||||||
ion_139.49.png,8,10.493626,-14.211387
|
|
||||||
ion_139.82.png,1,-37.167812,-1.3658186
|
|
||||||
ion_140.14.png,7,-28.534073,9.305264
|
|
||||||
ion_140.47.png,9,27.554335,-23.885014
|
|
||||||
ion_140.79.png,6,-43.277565,-12.250897
|
|
||||||
ion_141.12.png,7,-33.104458,7.699927
|
|
||||||
ion_141.44.png,9,17.903873,-16.033558
|
|
||||||
ion_141.77.png,0,-5.5243983,13.699684
|
|
||||||
ion_142.09.png,2,-18.984343,14.215493
|
|
||||||
ion_142.74.png,7,-27.618898,4.4566145
|
|
||||||
ion_143.07.png,4,-46.344624,-14.81412
|
|
||||||
ion_143.72.png,0,-5.9816747,13.293046
|
|
||||||
ion_144.04.png,2,-11.155265,14.170109
|
|
||||||
ion_144.37.png,3,19.259422,1.1916993
|
|
||||||
ion_144.69.png,3,27.138573,5.7115173
|
|
||||||
ion_145.02.png,1,-37.03697,-2.6906428
|
|
||||||
ion_145.67.png,3,27.36732,-0.38681844
|
|
||||||
ion_145.99.png,2,-20.595125,10.809723
|
|
||||||
ion_146.32.png,3,20.659002,0.8583992
|
|
||||||
ion_146.64.png,0,0.5069913,12.077325
|
|
||||||
ion_146.97.png,5,-34.340405,2.3559327
|
|
||||||
ion_147.29.png,2,-11.517773,8.150197
|
|
||||||
ion_147.62.png,3,18.983427,4.159373
|
|
||||||
ion_147.94.png,7,-32.49874,8.392821
|
|
||||||
ion_148.27.png,2,-14.248463,10.451742
|
|
||||||
ion_148.59.png,3,24.674915,-6.1475773
|
|
||||||
ion_148.92.png,6,-40.50674,-10.018055
|
|
||||||
ion_149.25.png,2,-19.732456,14.968335
|
|
||||||
ion_149.57.png,9,28.265984,-21.08255
|
|
||||||
ion_149.9.png,1,-37.801445,-2.135665
|
|
||||||
ion_150.22.png,2,-18.528763,8.687745
|
|
||||||
ion_150.55.png,9,26.87205,-8.916402
|
|
||||||
ion_150.87.png,6,-38.87418,-9.531368
|
|
||||||
ion_151.2.png,2,-21.394608,12.821622
|
|
||||||
ion_151.52.png,9,17.998955,-15.572056
|
|
||||||
ion_151.85.png,5,-31.658724,1.8839927
|
|
||||||
ion_152.17.png,7,-27.798784,9.632678
|
|
||||||
ion_152.5.png,9,26.860607,-22.968582
|
|
||||||
ion_152.82.png,1,-36.320477,-2.7099292
|
|
||||||
ion_153.15.png,7,-27.550566,9.645868
|
|
||||||
ion_153.47.png,9,27.603357,-23.536224
|
|
||||||
ion_153.8.png,7,-31.640509,6.528484
|
|
||||||
ion_154.12.png,7,-31.38128,8.300594
|
|
||||||
ion_154.45.png,3,23.81995,0.47742814
|
|
||||||
ion_154.77.png,5,-31.340246,2.6841404
|
|
||||||
ion_155.1.png,6,-38.985897,-7.9012914
|
|
||||||
ion_155.75.png,3,23.791573,-7.5370507
|
|
||||||
ion_156.07.png,9,23.335367,-9.456169
|
|
||||||
ion_156.4.png,9,32.113476,-20.326483
|
|
||||||
ion_156.72.png,7,-26.680313,5.8982115
|
|
||||||
ion_157.05.png,6,-41.05461,-9.774933
|
|
||||||
ion_157.7.png,9,32.16658,-7.1336193
|
|
||||||
ion_158.02.png,2,-11.812407,14.297634
|
|
||||||
ion_158.67.png,3,24.569906,4.6746826
|
|
||||||
ion_159.0.png,5,-33.735867,2.712962
|
|
||||||
ion_159.65.png,3,22.141064,8.087676
|
|
||||||
ion_159.97.png,2,-18.856886,13.17376
|
|
||||||
ion_160.3.png,2,-14.948667,10.354482
|
|
||||||
ion_160.62.png,3,20.122013,3.8841648
|
|
||||||
ion_160.95.png,7,-30.790535,5.913171
|
|
||||||
ion_161.27.png,0,-4.1914387,12.365071
|
|
||||||
ion_161.6.png,8,10.7571,-13.120692
|
|
||||||
ion_161.92.png,2,-21.266256,8.730152
|
|
||||||
ion_162.25.png,0,-2.8663845,7.336084
|
|
||||||
ion_162.58.png,9,27.714441,-12.068402
|
|
||||||
ion_162.9.png,1,-36.017006,-2.4591231
|
|
||||||
ion_163.23.png,2,-17.248466,6.9128537
|
|
||||||
ion_163.55.png,9,26.516489,-14.088811
|
|
||||||
ion_163.88.png,1,-37.00385,-1.8382791
|
|
||||||
ion_164.2.png,2,-19.261747,10.5906105
|
|
||||||
ion_164.53.png,8,11.775578,-13.3859415
|
|
||||||
ion_164.85.png,5,-33.099106,2.5399122
|
|
||||||
ion_165.18.png,2,-10.854196,11.623945
|
|
||||||
ion_165.5.png,8,10.943736,-14.005076
|
|
||||||
ion_165.83.png,7,-27.53292,8.744625
|
|
||||||
ion_166.15.png,2,-17.272701,11.286682
|
|
||||||
ion_166.48.png,8,14.226561,-14.4455385
|
|
||||||
ion_166.8.png,5,-31.635275,1.0225788
|
|
||||||
ion_167.13.png,1,-36.78637,-0.8704057
|
|
||||||
ion_167.45.png,3,27.44686,-1.43741
|
|
||||||
ion_167.78.png,3,16.833252,4.725952
|
|
||||||
ion_168.1.png,5,-33.255524,3.2703094
|
|
||||||
ion_168.43.png,3,29.844877,-5.1431966
|
|
||||||
ion_168.75.png,5,-30.86539,2.9853792
|
|
||||||
ion_169.08.png,2,-18.081688,8.909306
|
|
||||||
ion_169.73.png,0,-4.49475,9.887941
|
|
||||||
ion_170.05.png,2,-20.052332,14.501295
|
|
||||||
ion_170.7.png,2,-18.27792,17.12719
|
|
||||||
ion_171.03.png,6,-41.992714,-10.252468
|
|
||||||
ion_171.68.png,9,31.992657,-6.449951
|
|
||||||
ion_172.0.png,7,-31.901983,8.909973
|
|
||||||
ion_172.65.png,3,28.201687,1.7387993
|
|
||||||
ion_172.98.png,1,-35.71287,-1.633639
|
|
||||||
ion_173.63.png,3,29.567598,-2.1647427
|
|
||||||
ion_173.95.png,0,2.6752598,9.273825
|
|
||||||
ion_174.28.png,0,-1.4785752,15.294363
|
|
||||||
ion_174.6.png,8,10.788745,-13.70675
|
|
||||||
ion_174.93.png,7,-27.343237,6.6634164
|
|
||||||
ion_175.25.png,2,-16.242544,9.454839
|
|
||||||
ion_175.58.png,8,13.58418,-13.084291
|
|
||||||
ion_175.91.png,2,-19.902641,16.263332
|
|
||||||
ion_176.23.png,0,5.8883977,7.5633116
|
|
||||||
ion_176.56.png,3,26.058708,-0.33804464
|
|
||||||
ion_176.88.png,4,-45.82347,-14.564874
|
|
||||||
ion_177.21.png,5,-33.769085,1.0597107
|
|
||||||
ion_177.53.png,9,28.158157,-22.620466
|
|
||||||
ion_177.86.png,2,-23.884726,12.815301
|
|
||||||
ion_178.18.png,2,-14.489526,9.718306
|
|
||||||
ion_178.83.png,7,-25.836714,9.320589
|
|
||||||
ion_179.16.png,2,-15.42384,11.252816
|
|
||||||
ion_179.81.png,2,-15.41136,15.422945
|
|
||||||
ion_180.13.png,2,-19.366283,8.451141
|
|
||||||
ion_180.46.png,9,27.730162,-7.8079157
|
|
||||||
ion_180.78.png,0,-7.172285,13.136606
|
|
||||||
ion_181.11.png,7,-29.788584,8.512648
|
|
||||||
ion_181.43.png,3,23.71532,-5.6585317
|
|
||||||
ion_181.76.png,3,27.179075,5.278677
|
|
||||||
ion_182.08.png,2,-19.475264,14.344315
|
|
||||||
ion_182.73.png,0,-8.101207,8.876574
|
|
||||||
ion_183.06.png,2,-17.989485,11.640276
|
|
||||||
ion_183.71.png,3,18.50558,4.8625207
|
|
||||||
ion_184.03.png,2,-20.027864,9.215963
|
|
||||||
ion_184.68.png,3,26.700153,4.8592734
|
|
||||||
ion_185.01.png,1,-38.56908,-5.026004
|
|
||||||
ion_185.66.png,9,29.439285,-13.884041
|
|
||||||
ion_185.98.png,2,-20.049011,15.177003
|
|
||||||
ion_186.31.png,0,-2.2016842,10.762651
|
|
||||||
ion_186.63.png,3,29.112328,0.8230599
|
|
||||||
ion_186.96.png,7,-27.437508,6.7763624
|
|
||||||
ion_187.61.png,8,14.746,-15.561341
|
|
||||||
ion_187.93.png,2,-24.653465,11.311923
|
|
||||||
ion_188.58.png,9,26.924181,-16.26996
|
|
||||||
ion_188.91.png,2,-23.250217,12.80303
|
|
||||||
ion_189.24.png,0,-3.1196318,10.865817
|
|
||||||
ion_189.56.png,9,17.892994,-14.850101
|
|
||||||
ion_189.89.png,2,-15.080282,14.058813
|
|
||||||
ion_190.21.png,2,-14.918471,12.226166
|
|
||||||
ion_190.54.png,9,26.066849,-8.028413
|
|
||||||
ion_190.86.png,2,-16.36275,16.187475
|
|
||||||
ion_191.19.png,2,-18.617264,14.443393
|
|
||||||
ion_191.51.png,9,15.985019,-15.161865
|
|
||||||
ion_191.84.png,0,0.07637024,6.4175425
|
|
||||||
ion_192.16.png,7,-29.96435,6.764731
|
|
||||||
ion_192.81.png,2,-24.450735,12.3053665
|
|
||||||
ion_193.14.png,2,-14.9156885,12.590401
|
|
||||||
ion_193.79.png,0,6.8999925,6.922773
|
|
||||||
ion_194.11.png,2,-16.894192,9.066876
|
|
||||||
ion_194.76.png,2,-9.240621,15.130415
|
|
||||||
ion_195.09.png,7,-31.992617,8.856382
|
|
||||||
ion_195.74.png,3,25.191437,-0.08246486
|
|
||||||
ion_196.06.png,2,-19.416407,9.060027
|
|
||||||
ion_196.71.png,0,1.2136008,4.672844
|
|
||||||
ion_197.04.png,7,-28.425535,8.977524
|
|
||||||
ion_197.69.png,9,27.999023,-19.508387
|
|
||||||
ion_198.01.png,0,-8.079587,11.449043
|
|
||||||
ion_198.66.png,0,4.744716,2.964314
|
|
||||||
ion_198.99.png,6,-40.550262,-7.840601
|
|
||||||
ion_199.31.png,0,-6.043486,12.333179
|
|
||||||
ion_199.64.png,9,29.09711,-15.459312
|
|
||||||
ion_199.96.png,2,-20.972567,15.738652
|
|
||||||
ion_200.29.png,2,-13.509321,11.575929
|
|
||||||
ion_200.61.png,9,27.025208,-21.31873
|
|
||||||
ion_200.94.png,2,-16.386883,15.327882
|
|
||||||
ion_201.26.png,2,-13.90451,9.776584
|
|
||||||
ion_201.59.png,9,27.768497,-21.380787
|
|
||||||
ion_201.91.png,0,-1.0409251,13.911233
|
|
||||||
ion_202.24.png,0,1.139871,5.342685
|
|
||||||
ion_202.57.png,9,32.10026,-16.520195
|
|
||||||
ion_202.89.png,2,-18.145033,6.5922
|
|
||||||
ion_203.22.png,0,-5.0403314,12.270527
|
|
||||||
ion_203.87.png,3,18.17732,3.943971
|
|
||||||
ion_204.19.png,0,2.0714018,5.8082066
|
|
||||||
ion_204.52.png,3,9.449215,4.8136754
|
|
||||||
ion_204.84.png,1,-38.05102,-5.3855333
|
|
||||||
ion_205.17.png,2,-15.323726,14.87177
|
|
||||||
ion_205.82.png,3,21.14677,3.581677
|
|
||||||
ion_206.14.png,0,-1.1087127,9.537847
|
|
||||||
ion_206.79.png,2,-14.900894,15.599931
|
|
||||||
ion_207.12.png,5,-34.12811,1.4008504
|
|
||||||
ion_207.77.png,3,34.465927,-9.905594
|
|
||||||
ion_208.09.png,0,5.6138525,8.248161
|
|
||||||
ion_208.74.png,0,7.5379066,4.3042154
|
|
||||||
ion_209.07.png,7,-31.906462,7.4224014
|
|
||||||
ion_209.72.png,3,30.367035,-3.2509553
|
|
||||||
ion_210.04.png,2,-20.77343,14.54681
|
|
||||||
ion_210.69.png,9,30.188074,-9.307119
|
|
||||||
ion_211.02.png,7,-29.426338,7.0815706
|
|
||||||
ion_211.67.png,9,33.281834,-17.332632
|
|
||||||
ion_211.99.png,0,-5.434221,10.356245
|
|
||||||
ion_212.64.png,9,34.94895,-10.69858
|
|
||||||
ion_212.97.png,2,-14.627183,14.259659
|
|
||||||
ion_213.62.png,9,35.294746,-13.719771
|
|
||||||
ion_213.94.png,0,7.8965335,7.9705496
|
|
||||||
ion_214.27.png,3,17.790344,1.8371335
|
|
||||||
ion_214.59.png,3,26.038671,5.301521
|
|
||||||
ion_214.92.png,5,-30.914831,1.2200598
|
|
||||||
ion_215.24.png,0,-7.1221085,11.834678
|
|
||||||
ion_215.57.png,9,31.794752,-17.835423
|
|
||||||
ion_215.89.png,0,-3.2855515,13.961797
|
|
||||||
ion_216.22.png,0,-0.6859162,9.586189
|
|
||||||
ion_216.55.png,7,-26.259516,8.475644
|
|
||||||
ion_216.87.png,6,-43.11727,-10.622378
|
|
||||||
ion_217.2.png,7,-25.998281,9.529986
|
|
||||||
ion_217.52.png,9,34.34466,-17.174564
|
|
||||||
ion_217.85.png,0,-0.25917205,6.3075128
|
|
||||||
ion_218.17.png,0,2.7875588,7.1370487
|
|
||||||
ion_218.82.png,0,3.3789108,5.3887396
|
|
||||||
ion_219.15.png,0,4.9419,8.125323
|
|
||||||
ion_219.8.png,3,23.570993,2.7602973
|
|
||||||
ion_220.12.png,0,-7.2615247,9.177098
|
|
||||||
ion_220.77.png,3,32.593887,-5.763114
|
|
||||||
ion_221.1.png,0,-6.712871,11.301274
|
|
||||||
ion_221.75.png,9,30.484035,-9.331975
|
|
||||||
ion_222.07.png,0,-2.938413,12.682396
|
|
||||||
ion_222.72.png,0,5.9590015,3.8290143
|
|
||||||
ion_223.05.png,5,-33.04995,0.4847193
|
|
||||||
ion_223.7.png,9,30.453188,-16.514444
|
|
||||||
ion_224.02.png,0,1.7316281,5.1408854
|
|
||||||
ion_224.67.png,3,33.902676,-9.881889
|
|
||||||
ion_225.0.png,2,-13.303643,7.322489
|
|
||||||
ion_225.65.png,9,28.50149,-19.001616
|
|
||||||
ion_225.97.png,0,3.9495807,8.52111
|
|
||||||
ion_226.62.png,3,17.701633,6.6655583
|
|
||||||
ion_226.95.png,2,-24.95157,12.440863
|
|
||||||
ion_227.6.png,8,15.005958,-14.606815
|
|
||||||
ion_227.92.png,0,-5.9959893,9.723175
|
|
||||||
ion_228.25.png,0,4.7219896,10.262852
|
|
||||||
ion_228.9.png,2,-17.233511,16.979364
|
|
||||||
ion_229.22.png,0,-4.9454846,11.388046
|
|
||||||
ion_229.88.png,3,21.72242,2.5592306
|
|
||||||
ion_230.2.png,0,3.0545614,8.768679
|
|
||||||
ion_230.85.png,0,3.5411508,4.9265428
|
|
||||||
ion_231.18.png,0,5.736937,6.2244816
|
|
||||||
ion_231.83.png,3,22.28968,3.1365538
|
|
||||||
ion_232.15.png,0,5.1185856,9.96256
|
|
||||||
ion_232.8.png,3,28.587622,-3.1082885
|
|
||||||
ion_233.13.png,0,-6.356156,10.779369
|
|
||||||
ion_233.78.png,9,33.08437,-8.988923
|
|
||||||
ion_234.1.png,0,-5.092869,11.342078
|
|
||||||
ion_234.75.png,3,30.446781,0.8939183
|
|
||||||
ion_235.08.png,2,-23.331598,13.555416
|
|
||||||
ion_235.73.png,9,26.594164,-18.618465
|
|
||||||
ion_236.05.png,2,-17.068436,8.41498
|
|
||||||
ion_236.7.png,3,28.35997,-2.046046
|
|
||||||
ion_237.03.png,3,15.8622055,6.6107087
|
|
||||||
ion_237.68.png,9,17.181717,-15.99207
|
|
||||||
ion_238.0.png,0,8.263369,8.6873
|
|
||||||
ion_238.65.png,9,28.135519,-15.045629
|
|
||||||
ion_238.98.png,0,1.7897984,10.504221
|
|
||||||
ion_239.95.png,3,26.174,-3.077104
|
|
||||||
ion_240.6.png,9,15.474228,-15.669998
|
|
||||||
ion_240.93.png,0,6.4458795,5.3719096
|
|
||||||
ion_241.9.png,3,27.38608,0.54914427
|
|
||||||
ion_242.23.png,3,18.723701,1.9100204
|
|
||||||
ion_242.88.png,0,5.1718507,7.6415257
|
|
||||||
ion_243.21.png,2,-13.767222,10.946924
|
|
||||||
ion_243.86.png,3,28.45869,-0.33844206
|
|
||||||
ion_244.18.png,0,8.380079,4.4239235
|
|
||||||
ion_244.83.png,3,23.159258,0.100792
|
|
||||||
ion_245.16.png,0,3.64497,8.144562
|
|
||||||
ion_245.81.png,3,25.525908,-4.2612433
|
|
||||||
ion_246.13.png,0,-3.549516,12.331077
|
|
||||||
ion_246.78.png,9,31.131891,-12.253968
|
|
||||||
ion_247.11.png,0,0.8747157,11.044132
|
|
||||||
ion_247.76.png,9,34.884518,-15.607239
|
|
||||||
ion_248.08.png,3,26.72761,4.3562646
|
|
||||||
ion_248.73.png,9,28.246988,-10.076125
|
|
||||||
ion_249.06.png,0,-3.017238,11.757186
|
|
||||||
ion_249.71.png,8,14.475118,-15.140657
|
|
||||||
ion_250.03.png,3,25.359653,-3.5558565
|
|
||||||
ion_250.68.png,9,26.263126,-20.95294
|
|
||||||
ion_251.01.png,0,9.693218,7.141149
|
|
||||||
ion_251.98.png,3,25.197989,-3.0150151
|
|
||||||
ion_252.63.png,9,34.998253,-14.195647
|
|
||||||
ion_252.96.png,0,7.398285,9.583776
|
|
||||||
ion_253.93.png,3,24.647907,-4.957775
|
|
||||||
ion_254.91.png,3,20.270203,6.8519335
|
|
||||||
ion_255.23.png,0,3.0325668,8.183513
|
|
||||||
ion_255.88.png,3,25.278559,-5.496368
|
|
||||||
ion_256.21.png,3,22.577757,-4.6108294
|
|
||||||
ion_256.86.png,3,30.956982,-3.893138
|
|
||||||
ion_257.19.png,0,8.345898,7.157985
|
|
||||||
ion_257.84.png,9,32.548405,-10.303978
|
|
||||||
ion_258.16.png,3,30.508417,-4.707207
|
|
||||||
ion_258.81.png,3,19.469334,5.1611023
|
|
||||||
ion_259.14.png,2,-8.376543,13.943265
|
|
||||||
ion_259.79.png,3,30.419836,-8.039713
|
|
||||||
ion_260.11.png,9,33.020374,-7.0337534
|
|
||||||
ion_260.76.png,9,28.17402,-18.515789
|
|
||||||
ion_261.09.png,0,6.6859336,8.302815
|
|
||||||
ion_261.74.png,9,34.7219,-15.372783
|
|
||||||
ion_262.06.png,3,20.93358,3.3292527
|
|
||||||
ion_262.71.png,9,35.46796,-12.1922
|
|
||||||
ion_263.04.png,0,-5.995883,11.587837
|
|
||||||
ion_263.69.png,9,16.308891,-15.314592
|
|
||||||
ion_264.01.png,9,32.272972,-13.530391
|
|
||||||
ion_264.99.png,3,26.751202,-5.154515
|
|
||||||
ion_265.96.png,3,24.902645,-0.7530937
|
|
||||||
ion_266.94.png,3,25.701172,3.553615
|
|
||||||
ion_267.91.png,9,34.188293,-10.638313
|
|
||||||
ion_268.89.png,3,30.478693,-1.8946239
|
|
||||||
ion_269.21.png,2,-13.981171,8.046158
|
|
||||||
ion_269.87.png,9,29.998203,-15.938599
|
|
||||||
ion_270.19.png,3,25.72741,1.5884147
|
|
||||||
ion_270.84.png,3,36.868366,-9.9761715
|
|
||||||
ion_271.17.png,3,19.93252,6.0084004
|
|
||||||
ion_271.82.png,9,33.174046,-16.580727
|
|
||||||
ion_272.14.png,9,26.206633,-7.955533
|
|
||||||
ion_272.79.png,3,28.905403,-7.9051175
|
|
||||||
ion_273.12.png,0,8.056266,5.3453474
|
|
||||||
ion_273.77.png,9,33.81305,-19.9639
|
|
||||||
ion_274.09.png,9,31.556974,-22.127022
|
|
||||||
ion_274.74.png,9,33.679058,-18.526842
|
|
||||||
ion_275.07.png,9,28.535221,-7.1477456
|
|
||||||
ion_276.04.png,3,14.807062,5.5181775
|
|
||||||
ion_277.02.png,3,28.40732,-3.9556458
|
|
||||||
ion_277.99.png,3,26.6683,-4.0368953
|
|
||||||
ion_278.32.png,3,23.75582,1.7946953
|
|
||||||
ion_278.64.png,2,-13.898659,5.659099
|
|
||||||
ion_278.97.png,6,-41.740196,-9.413981
|
|
||||||
ion_279.29.png,5,-29.076683,3.008845
|
|
||||||
ion_279.62.png,3,29.266857,-0.6369429
|
|
||||||
ion_279.94.png,0,0.4989599,12.061284
|
|
||||||
ion_280.92.png,3,32.446533,-4.107399
|
|
||||||
ion_281.89.png,9,31.876614,-15.746353
|
|
||||||
ion_282.87.png,3,28.560238,-1.0499889
|
|
||||||
ion_283.85.png,9,26.621946,-20.67594
|
|
||||||
ion_284.82.png,9,33.796124,-12.506761
|
|
||||||
ion_285.15.png,3,21.241554,5.1587663
|
|
||||||
ion_285.8.png,9,26.547033,-18.30967
|
|
||||||
ion_286.12.png,9,32.822624,-20.686197
|
|
||||||
ion_286.77.png,3,30.250584,0.55641127
|
|
||||||
ion_287.1.png,3,21.9872,2.1390061
|
|
||||||
ion_287.75.png,9,37.12438,-13.494064
|
|
||||||
ion_288.07.png,3,30.606201,-2.640319
|
|
||||||
ion_289.05.png,3,22.890013,3.9677382
|
|
||||||
ion_290.02.png,9,32.2399,-12.798281
|
|
||||||
ion_291.0.png,9,28.448782,-14.007974
|
|
||||||
ion_291.97.png,9,31.225016,-12.040639
|
|
||||||
ion_292.95.png,9,34.69593,-11.920377
|
|
||||||
ion_293.92.png,9,33.119762,-11.329056
|
|
||||||
ion_294.9.png,3,36.564575,-9.625822
|
|
||||||
ion_295.87.png,3,28.584211,-1.8474163
|
|
||||||
ion_296.85.png,3,20.620918,7.438985
|
|
||||||
ion_297.83.png,9,36.039566,-11.209591
|
|
||||||
ion_298.15.png,3,25.659477,-1.8728
|
|
||||||
ion_298.8.png,3,35.617268,-10.148742
|
|
||||||
ion_299.13.png,3,21.799765,7.968525
|
|
||||||
ion_301.08.png,9,27.44734,-13.561337
|
|
||||||
ion_302.05.png,9,30.053375,-14.549845
|
|
||||||
ion_303.03.png,9,29.068108,-14.753645
|
|
||||||
ion_303.68.png,9,28.479387,-21.916006
|
|
||||||
ion_304.0.png,9,29.201258,-23.598558
|
|
||||||
ion_304.33.png,8,13.122702,-12.554004
|
|
||||||
ion_304.98.png,9,24.650152,-7.1270638
|
|
||||||
ion_305.95.png,3,29.059801,-8.600534
|
|
||||||
ion_306.28.png,8,10.460474,-12.517865
|
|
||||||
ion_306.93.png,9,31.42041,-17.013552
|
|
||||||
ion_307.9.png,9,32.330303,-13.718061
|
|
||||||
ion_308.88.png,3,31.862032,-5.8857284
|
|
||||||
ion_309.85.png,9,29.141745,-18.15918
|
|
||||||
ion_310.83.png,9,36.09488,-12.799859
|
|
||||||
ion_311.16.png,3,28.080969,-6.667759
|
|
||||||
ion_312.78.png,3,29.836946,0.27934504
|
|
||||||
ion_313.11.png,2,-8.627648,12.400691
|
|
||||||
ion_314.08.png,3,20.629183,5.6328382
|
|
||||||
ion_315.06.png,3,26.503016,-2.5715907
|
|
||||||
ion_318.96.png,9,31.351917,-11.315838
|
|
||||||
ion_326.76.png,3,32.09507,0.18656318
|
|
||||||
ion_328.71.png,3,18.54395,7.1383853
|
|
||||||
ion_329.04.png,0,-7.3291235,14.529308
|
|
||||||
ion_329.69.png,9,34.27189,-15.177913
|
|
||||||
ion_330.01.png,3,26.687662,1.431783
|
|
||||||
ion_330.99.png,3,31.18035,-0.7660054
|
|
||||||
ion_334.89.png,9,30.313026,-9.015304
|
|
||||||
ion_335.21.png,0,8.570336,5.221153
|
|
||||||
ion_336.84.png,9,31.535072,-16.199507
|
|
||||||
ion_337.17.png,3,21.336227,6.6063633
|
|
||||||
ion_338.14.png,3,26.978844,-5.2260184
|
|
||||||
ion_339.12.png,9,27.873163,-20.949478
|
|
||||||
ion_351.8.png,9,31.467436,-10.136445
|
|
||||||
ion_352.12.png,3,28.709461,0.9844084
|
|
||||||
ion_353.75.png,9,16.17768,-16.142302
|
|
||||||
ion_354.07.png,0,10.21724,8.987664
|
|
||||||
ion_355.05.png,2,-8.144377,15.491125
|
|
||||||
ion_370.33.png,3,29.735342,2.3608685
|
|
||||||
ion_370.65.png,7,-28.00135,5.0777225
|
|
||||||
ion_370.98.png,1,-38.86183,-6.1244082
|
|
||||||
ion_371.3.png,2,-14.572228,4.9324327
|
|
||||||
ion_371.63.png,2,-21.988415,16.459906
|
|
||||||
ion_371.95.png,1,-35.610634,-3.5852711
|
|
||||||
ion_372.6.png,3,32.483067,1.3230696
|
|
||||||
ion_372.93.png,7,-27.402096,5.2922916
|
|
||||||
ion_384.63.png,3,30.532621,2.4404614
|
|
||||||
ion_387.56.png,3,22.448105,8.419394
|
|
||||||
ion_390.81.png,0,-0.39847365,13.831687
|
|
||||||
ion_391.14.png,2,-7.6635137,15.491304
|
|
||||||
ion_401.54.png,3,31.95286,-0.16999035
|
|
||||||
ion_401.86.png,3,17.869164,6.7715282
|
|
||||||
ion_461.69.png,3,31.942822,0.51566416
|
|
||||||
ion_59.51.png,9,35.17394,-13.068886
|
|
||||||
ion_59.84.png,2,-20.054785,12.566305
|
|
||||||
ion_60.16.png,2,-13.147553,13.29442
|
|
||||||
ion_60.81.png,2,-22.018095,16.838892
|
|
||||||
ion_64.71.png,3,30.316786,-0.84601045
|
|
||||||
ion_66.66.png,3,18.554628,6.6652193
|
|
||||||
ion_66.99.png,6,-42.332752,-10.112175
|
|
||||||
ion_67.64.png,3,17.628195,4.6080613
|
|
||||||
ion_67.96.png,5,-32.32362,1.8389728
|
|
||||||
ion_68.62.png,0,5.661518,2.3490248
|
|
||||||
ion_68.94.png,6,-39.790955,-10.437897
|
|
||||||
ion_69.27.png,0,1.6724036,4.168741
|
|
||||||
ion_69.59.png,2,-23.649536,11.986989
|
|
||||||
ion_69.92.png,4,-43.299904,-15.888535
|
|
||||||
ion_70.24.png,0,-0.06470341,8.682315
|
|
||||||
ion_70.57.png,9,29.347612,-20.504143
|
|
||||||
ion_70.89.png,6,-42.5278,-11.181254
|
|
||||||
ion_71.54.png,0,-0.9896617,12.607591
|
|
||||||
ion_71.87.png,6,-39.048397,-8.880032
|
|
||||||
ion_72.19.png,5,-32.476727,1.5677394
|
|
||||||
ion_72.52.png,8,10.250291,-13.858199
|
|
||||||
ion_72.84.png,5,-30.629602,1.8604381
|
|
||||||
ion_73.49.png,9,36.719025,-11.857051
|
|
||||||
ion_73.82.png,4,-45.17158,-16.50476
|
|
||||||
ion_74.14.png,4,-45.596066,-13.342802
|
|
||||||
ion_74.79.png,2,-17.46527,16.901453
|
|
||||||
ion_76.74.png,0,-6.216439,15.702544
|
|
||||||
ion_77.72.png,0,-6.6433234,14.540961
|
|
||||||
ion_78.69.png,0,6.182824,2.9642966
|
|
||||||
ion_79.02.png,4,-46.21426,-15.078558
|
|
||||||
ion_79.34.png,9,28.354658,-15.809483
|
|
||||||
ion_79.67.png,7,-28.589724,7.147096
|
|
||||||
ion_79.99.png,5,-35.044357,0.942713
|
|
||||||
ion_80.32.png,9,31.341908,-17.860785
|
|
||||||
ion_80.64.png,2,-19.469915,16.784105
|
|
||||||
ion_80.97.png,4,-45.72406,-15.982423
|
|
||||||
ion_81.62.png,0,5.452961,5.6512375
|
|
||||||
ion_81.95.png,1,-37.81082,-2.6366253
|
|
||||||
ion_82.27.png,3,22.566402,4.0558753
|
|
||||||
ion_82.6.png,0,-7.4663644,10.1609125
|
|
||||||
ion_82.92.png,2,-17.679209,12.253551
|
|
||||||
ion_83.25.png,0,2.373072,3.9440634
|
|
||||||
ion_83.57.png,5,-31.87277,0.8549705
|
|
||||||
ion_83.9.png,4,-43.896214,-16.96346
|
|
||||||
ion_84.22.png,2,-14.043374,12.942986
|
|
||||||
ion_84.55.png,9,32.700012,-19.502073
|
|
||||||
ion_84.87.png,6,-42.983273,-11.961578
|
|
||||||
ion_85.52.png,9,28.50589,-18.010765
|
|
||||||
ion_85.85.png,4,-42.999424,-14.644611
|
|
||||||
ion_86.17.png,4,-44.66821,-16.437698
|
|
||||||
ion_86.5.png,9,27.44913,-24.501375
|
|
||||||
ion_86.82.png,6,-43.99355,-10.41811
|
|
||||||
ion_87.47.png,9,18.174158,-15.126801
|
|
||||||
ion_87.8.png,6,-40.46243,-9.185634
|
|
||||||
ion_88.12.png,6,-39.640736,-8.055685
|
|
||||||
ion_88.77.png,0,3.8780096,2.591604
|
|
||||||
ion_89.75.png,0,10.09258,6.4302506
|
|
||||||
ion_90.07.png,0,3.625766,9.283005
|
|
||||||
ion_90.72.png,5,-31.266928,4.554381
|
|
||||||
ion_91.05.png,4,-45.765697,-14.986678
|
|
||||||
ion_91.7.png,9,29.559906,-13.975161
|
|
||||||
ion_92.67.png,0,7.893663,5.9997163
|
|
||||||
ion_93.0.png,4,-45.56015,-15.572192
|
|
||||||
ion_93.32.png,9,34.741074,-12.338461
|
|
||||||
ion_93.65.png,0,-5.853657,6.404585
|
|
||||||
ion_93.97.png,2,-17.645025,10.471852
|
|
||||||
ion_94.3.png,0,-3.9838848,6.2626543
|
|
||||||
ion_94.62.png,7,-25.971523,9.763064
|
|
||||||
ion_94.95.png,6,-38.702198,-10.900641
|
|
||||||
ion_95.28.png,0,-7.582129,12.356361
|
|
||||||
ion_95.6.png,0,-0.56754535,11.996512
|
|
||||||
ion_95.93.png,4,-43.824963,-16.213938
|
|
||||||
ion_96.58.png,0,-1.5130029,12.203467
|
|
||||||
ion_96.9.png,5,-35.778248,2.471955
|
|
||||||
ion_97.23.png,3,16.597586,6.1397967
|
|
||||||
ion_97.55.png,3,21.361723,4.0301137
|
|
||||||
ion_97.88.png,4,-44.037876,-16.904804
|
|
||||||
ion_98.2.png,5,-33.773403,2.9667366
|
|
||||||
ion_98.53.png,9,18.12225,-16.086273
|
|
||||||
ion_98.85.png,6,-43.389095,-11.146669
|
|
||||||
ion_99.5.png,9,28.50092,-20.264837
|
|
||||||
ion_99.83.png,4,-44.475746,-16.098194
|
|
||||||
|
@@ -15,7 +15,7 @@ using Statistics, Images, Interpolations, BenchmarkTools
|
|||||||
data_path = "/app/data/Leaf.imzML"
|
data_path = "/app/data/Leaf.imzML"
|
||||||
mask_path = "/app/data/region_of_interest.png"
|
mask_path = "/app/data/region_of_interest.png"
|
||||||
output_folder = "/app/datos_para_ai"
|
output_folder = "/app/datos_para_ai"
|
||||||
img_size = (224, 224)
|
img_size = (256, 256)
|
||||||
tolerance = 0.05
|
tolerance = 0.05
|
||||||
mkpath(output_folder)
|
mkpath(output_folder)
|
||||||
|
|
||||||
@@ -26,6 +26,16 @@ function run_production_pipeline()
|
|||||||
println("Step 1: Ingesting Data...")
|
println("Step 1: Ingesting Data...")
|
||||||
data = OpenMSIData(data_path)
|
data = OpenMSIData(data_path)
|
||||||
|
|
||||||
|
orig_height = data.image_dims[2]
|
||||||
|
orig_width = data.image_dims[1]
|
||||||
|
if orig_height < 256 || orig_width < 256
|
||||||
|
final_img_size = (orig_height, orig_width)
|
||||||
|
println(" [Notice] Original image is smaller than 256x256. Keeping original size: ", final_img_size)
|
||||||
|
else
|
||||||
|
final_img_size = (256, 256)
|
||||||
|
println(" [Notice] Resizing down to target size: ", final_img_size)
|
||||||
|
end
|
||||||
|
|
||||||
# 2. RUN FRAMEWORK ANALYTICS
|
# 2. RUN FRAMEWORK ANALYTICS
|
||||||
println("Step 2: Checking Dataset Precomputed Boundaries...")
|
println("Step 2: Checking Dataset Precomputed Boundaries...")
|
||||||
# This matches the framework's internal logic to safely discover the true boundaries.
|
# This matches the framework's internal logic to safely discover the true boundaries.
|
||||||
@@ -68,23 +78,37 @@ function run_production_pipeline()
|
|||||||
slice_dict = MSI_src.get_multiple_mz_slices(data, target_masses, tolerance, mask_path=mask_path)
|
slice_dict = MSI_src.get_multiple_mz_slices(data, target_masses, tolerance, mask_path=mask_path)
|
||||||
|
|
||||||
# 6. THREADED PROCESSING & EXPORT
|
# 6. THREADED PROCESSING & EXPORT
|
||||||
println("Step 5: Threaded TrIQ Normalization & Resizing (Using $(Threads.nthreads()) threads)...")
|
println("Step 5: Threaded TrIQ Normalization & Safe 256x256 Zero-Padding...")
|
||||||
mask_matrix = MSI_src.load_and_prepare_mask(mask_path, (data.image_dims[1], data.image_dims[2]))
|
mask_matrix = MSI_src.load_and_prepare_mask(mask_path, (data.image_dims[1], data.image_dims[2]))
|
||||||
exported_count = Threads.Atomic{Int}(0)
|
exported_count = Threads.Atomic{Int}(0)
|
||||||
|
|
||||||
|
# Fixed target dimensions for the CNN
|
||||||
|
target_size = (256, 256)
|
||||||
|
|
||||||
Threads.@threads for mz_val in target_masses
|
Threads.@threads for mz_val in target_masses
|
||||||
slice = get(slice_dict, mz_val, nothing)
|
slice = get(slice_dict, mz_val, nothing)
|
||||||
if slice === nothing || all(iszero, slice) continue end
|
if slice === nothing || all(iszero, slice) continue end
|
||||||
|
|
||||||
# Use Framework-Native TrIQ (Standard: 256 bins, 0.98 probability cutoff)
|
# 1. Framework-Native TrIQ (0.0 to 255.0 Scaling)
|
||||||
slice_quant, _ = MSI_src.TrIQ(slice, 256, 0.98, mask_matrix=mask_matrix)
|
slice_quant, _ = MSI_src.TrIQ(slice, 256, 0.98, mask_matrix=mask_matrix)
|
||||||
|
|
||||||
# Resize cleanly to standard CNN dimensions
|
# 2. Allocate an empty 256x256 background matrix
|
||||||
img_resized = imresize(slice_quant, img_size)
|
padded_matrix = zeros(Float32, target_size)
|
||||||
|
|
||||||
# Normalize 0-255 scaling back to 0.0-1.0 float mapping for Gray storage conversion
|
# 3. Compute structural centering offsets based on true resolution (161x106)
|
||||||
|
h_orig, w_orig = size(slice_quant, 1), size(slice_quant, 2)
|
||||||
|
offset_y = div(target_size[1] - h_orig, 2) + 1
|
||||||
|
offset_x = div(target_size[2] - w_orig, 2) + 1
|
||||||
|
|
||||||
|
# 4. Map the pristine, raw pixels directly into the center
|
||||||
|
padded_matrix[offset_y:offset_y+h_orig-1, offset_x:offset_x+w_orig-1] .= slice_quant
|
||||||
|
|
||||||
|
# 5. Convert safely to 0.0 - 1.0 float mapping for Gray image export
|
||||||
|
normalized_gray = padded_matrix ./ 255.0
|
||||||
|
|
||||||
|
# 6. Save the unblurred, structurally perfect map
|
||||||
filename = "ion_$(round(mz_val, digits=2)).png"
|
filename = "ion_$(round(mz_val, digits=2)).png"
|
||||||
save(joinpath(output_folder, filename), Gray.(img_resized ./ 255.0))
|
save(joinpath(output_folder, filename), Gray.(normalized_gray))
|
||||||
|
|
||||||
Threads.atomic_add!(exported_count, 1)
|
Threads.atomic_add!(exported_count, 1)
|
||||||
end
|
end
|
||||||
|
|||||||
@@ -11,7 +11,6 @@ import random
|
|||||||
import time
|
import time
|
||||||
import psutil
|
import psutil
|
||||||
|
|
||||||
# 0. REPRODUCIBILITY
|
|
||||||
def set_seed(seed=42):
|
def set_seed(seed=42):
|
||||||
random.seed(seed)
|
random.seed(seed)
|
||||||
np.random.seed(seed)
|
np.random.seed(seed)
|
||||||
@@ -24,46 +23,65 @@ def set_seed(seed=42):
|
|||||||
|
|
||||||
set_seed(42)
|
set_seed(42)
|
||||||
|
|
||||||
# 1. CONFIGURACIÓN
|
|
||||||
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
|
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
|
||||||
IMG_DIR = os.path.join(BASE_DIR, "..", "datos_para_ai")
|
IMG_DIR = os.path.join(BASE_DIR, "..", "datos_para_ai")
|
||||||
MODEL_SAVE_PATH = os.path.join(BASE_DIR, "..", "models", "msi_encoder_trained.pth")
|
MODEL_SAVE_PATH = os.path.join(BASE_DIR, "..", "models", "msi_encoder_trained.pth")
|
||||||
BATCH_SIZE = 8 # Reduced from 16 to prevent OOM on low-memory GPUs
|
|
||||||
# Epochs: 50 is sufficient for convergence on normalized ion maps.
|
# VRAM OPTIMIZATION ENGINE
|
||||||
# Further training leads to minor overfitting to background noise.
|
BATCH_SIZE = 8 # Physical batch size (keeps VRAM safely under 3.5 GB)
|
||||||
EPOCHS = 50
|
ACCUMULATION_STEPS = 4 # 8 x 4 = Effective Batch Size of 32!
|
||||||
LEARNING_RATE = 0.0003
|
EPOCHS = 60 # Slightly extended to give the larger batch size room to converge
|
||||||
# Temperature (tau): 0.5 was selected via grid search {0.1, 0.5, 1.0}.
|
LEARNING_RATE = 0.0003 # Tuned for an effective batch size of 32
|
||||||
# 0.5 provided the most stable contrastive boundary for anatomical features.
|
|
||||||
TEMPERATURE = 0.5
|
TEMPERATURE = 0.5
|
||||||
DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
||||||
|
|
||||||
# Optimization for fragmented CUDA memory
|
|
||||||
if DEVICE.type == 'cuda':
|
|
||||||
os.environ["PYTORCH_CUDA_ALLOC_CONF"] = "expandable_segments:True"
|
|
||||||
torch.cuda.empty_cache()
|
|
||||||
|
|
||||||
# 2. AUMENTACIONES ESPECÍFICAS DE MSI (Basado en Hu et al. 2022)
|
|
||||||
class MSIAugmentations:
|
class MSIAugmentations:
|
||||||
def __init__(self, size=224):
|
def __init__(self, size=256): # Enforce 256 dimension consistency
|
||||||
self.train_transform = transforms.Compose([
|
self.spatial_transform = transforms.Compose([
|
||||||
transforms.RandomRotation(10),
|
transforms.Resize((size, size)),
|
||||||
transforms.GaussianBlur(kernel_size=3, sigma=(0.1, 2.0)),
|
transforms.RandomRotation(15),
|
||||||
transforms.ColorJitter(brightness=0.4, contrast=0.4),
|
transforms.RandomHorizontalFlip(p=0.5),
|
||||||
transforms.ToTensor(),
|
transforms.RandomVerticalFlip(p=0.5),
|
||||||
# Additive Gaussian Noise: Standard for MSI to bolsters against detector noise.
|
transforms.ToTensor()
|
||||||
# Citations: DeepION (2024), Hu et al. (2022, Table S1).
|
|
||||||
transforms.Lambda(lambda x: x + torch.randn_like(x) * 0.01)
|
|
||||||
])
|
])
|
||||||
|
|
||||||
def __call__(self, x):
|
def apply_msi_chemical_noise(self, tensor):
|
||||||
return self.train_transform(x), self.train_transform(x)
|
x = tensor.clone()
|
||||||
|
|
||||||
# 3. DATASET
|
# 1. Intensity Scaling (Global Concentration Shifts)
|
||||||
class MSIDataset(Dataset):
|
scale_factor = random.uniform(0.8, 1.2)
|
||||||
|
x = x * scale_factor
|
||||||
|
|
||||||
|
# 2. Poisson Noise Simulation (Shot Noise)
|
||||||
|
# Scaled to avoid breaking the 0.0 - 1.0 float bounds
|
||||||
|
vals = len(torch.unique(x))
|
||||||
|
vals = 2 ** np.ceil(np.log2(vals)) if vals > 0 else 32
|
||||||
|
# Add soft, random Gaussian-Poisson approximation
|
||||||
|
noise = torch.randn_like(x) * (torch.sqrt(x + 1e-5) / float(vals))
|
||||||
|
x = x + noise
|
||||||
|
|
||||||
|
# 3. Random Missing Values (Standard Dropout - e.g., 2% pixels lost)
|
||||||
|
random_dropout_mask = (torch.rand_like(x) > 0.02).float()
|
||||||
|
x = x * random_dropout_mask
|
||||||
|
|
||||||
|
# 4. Intensity-Dependent Missing Values (Low-Signal Clipping)
|
||||||
|
# Pixels with very low values have a higher chance of dropping out completely
|
||||||
|
low_signal_mask = torch.rand_like(x)
|
||||||
|
# Drop threshold scales inversely with intensity: lower values drop more easily
|
||||||
|
drop_threshold = 0.15 * (1.0 - x)
|
||||||
|
x = torch.where(low_signal_mask > drop_threshold, x, torch.zeros_like(x))
|
||||||
|
|
||||||
|
return torch.clamp(x, 0.0, 1.0)
|
||||||
|
|
||||||
|
def __call__(self, x):
|
||||||
|
base_tensor = self.spatial_transform(x)
|
||||||
|
# Create two distinct chemical representations of the same underlying coordinate geometry
|
||||||
|
return self.apply_msi_chemical_noise(base_tensor), self.apply_msi_chemical_noise(base_tensor)
|
||||||
|
|
||||||
|
class SimCLRMSIDataset(Dataset):
|
||||||
def __init__(self, img_dir, transform=None):
|
def __init__(self, img_dir, transform=None):
|
||||||
self.img_dir = img_dir
|
self.img_dir = img_dir
|
||||||
self.img_names = sorted([f for f in os.listdir(img_dir) if f.endswith('.png')])
|
self.img_names = [f for f in os.listdir(img_dir) if f.endswith('.png')]
|
||||||
self.transform = transform
|
self.transform = transform
|
||||||
|
|
||||||
def __len__(self):
|
def __len__(self):
|
||||||
@@ -71,101 +89,118 @@ class MSIDataset(Dataset):
|
|||||||
|
|
||||||
def __getitem__(self, idx):
|
def __getitem__(self, idx):
|
||||||
img_path = os.path.join(self.img_dir, self.img_names[idx])
|
img_path = os.path.join(self.img_dir, self.img_names[idx])
|
||||||
image = Image.open(img_path).convert("RGB")
|
image = Image.open(img_path).convert("L")
|
||||||
if self.transform:
|
if self.transform:
|
||||||
return self.transform(image), self.img_names[idx]
|
xi, xj = self.transform(image)
|
||||||
return transforms.ToTensor()(image), self.img_names[idx]
|
return xi, xj
|
||||||
|
|
||||||
# 4. MODELO (EfficientNet-B0 + Projector)
|
class MSI_Structural_Encoder(nn.Module):
|
||||||
class SimCLR_MSI(nn.Module):
|
def __init__(self, projection_dim=128):
|
||||||
def __init__(self):
|
super(MSI_Structural_Encoder, self).__init__()
|
||||||
super(SimCLR_MSI, self).__init__()
|
|
||||||
# EfficientNet-B0: Highly efficient MBConv backbone for CPU/GPU inference.
|
# High-Fidelity Custom Encoder for Padded Data
|
||||||
# Pre-trained on ImageNet (Tan & Le, 2019).
|
self.features = nn.Sequential(
|
||||||
self.encoder = models.efficientnet_b0(weights=models.EfficientNet_B0_Weights.DEFAULT)
|
# Input: 256x256x1 (Resize in transform)
|
||||||
num_ftrs = self.encoder.classifier[1].in_features
|
nn.Conv2d(1, 32, kernel_size=5, stride=2, padding=2, bias=False),
|
||||||
self.encoder.classifier = nn.Identity()
|
nn.GroupNorm(4, 32), # Replaces BatchNorm for perfect stability at batch size = 8
|
||||||
# Projector Head: 128-dim projection is standard for SimCLR (Chen et al., 2020).
|
|
||||||
self.projector = nn.Sequential(
|
|
||||||
nn.Linear(num_ftrs, 512),
|
|
||||||
nn.ReLU(),
|
nn.ReLU(),
|
||||||
nn.Linear(512, 128)
|
|
||||||
|
# 112x112 -> 56x56
|
||||||
|
nn.Conv2d(32, 64, kernel_size=3, stride=2, padding=1, bias=False),
|
||||||
|
nn.GroupNorm(8, 64),
|
||||||
|
nn.ReLU(),
|
||||||
|
|
||||||
|
# 56x56 -> 28x28 (Captures true raw pixel leaf structures)
|
||||||
|
nn.Conv2d(64, 128, kernel_size=3, stride=2, padding=1, bias=False),
|
||||||
|
nn.GroupNorm(16, 128),
|
||||||
|
nn.ReLU(),
|
||||||
|
|
||||||
|
# 28x28 -> 14x14
|
||||||
|
nn.Conv2d(128, 256, kernel_size=3, stride=2, padding=1, bias=False),
|
||||||
|
nn.GroupNorm(32, 256),
|
||||||
|
nn.ReLU(),
|
||||||
|
|
||||||
|
nn.AdaptiveAvgPool2d((1, 1)) # Yields a clean 256-dimensional vector
|
||||||
|
)
|
||||||
|
|
||||||
|
self.projector = nn.Sequential(
|
||||||
|
nn.Linear(256, 128),
|
||||||
|
nn.ReLU(),
|
||||||
|
nn.Linear(128, projection_dim)
|
||||||
)
|
)
|
||||||
|
|
||||||
def forward(self, x):
|
def forward(self, x):
|
||||||
h = self.encoder(x)
|
h = self.features(x).squeeze(-1).squeeze(-1)
|
||||||
z = self.projector(h)
|
h_norm = F.normalize(h, p=2, dim=1) # Projects onto the unit hypersphere
|
||||||
|
z = self.projector(h_norm)
|
||||||
return h, z
|
return h, z
|
||||||
|
|
||||||
# 5. PÉRDIDA NT-Xent
|
|
||||||
def nt_xent_loss(z1, z2, temperature=0.5):
|
def nt_xent_loss(z1, z2, temperature=0.5):
|
||||||
z = torch.cat([F.normalize(z1, dim=1), F.normalize(z2, dim=1)], dim=0)
|
batch_size = z1.shape[0]
|
||||||
sim_matrix = torch.exp(torch.mm(z, z.t()) / temperature)
|
z = torch.cat([z1, z2], dim=0)
|
||||||
mask = ~torch.eye(z.shape[0], device=z.device).bool()
|
z = F.normalize(z, p=2, dim=1)
|
||||||
sim_matrix = sim_matrix.masked_select(mask).view(z.shape[0], -1)
|
|
||||||
n = z1.shape[0]
|
sim_matrix = torch.mm(z, z.t()) / temperature
|
||||||
positives = torch.exp(torch.sum(F.normalize(z1, dim=1) * F.normalize(z2, dim=1), dim=1) / temperature)
|
mask = torch.eye(2 * batch_size, device=z.device).bool()
|
||||||
positives = torch.cat([positives, positives], dim=0)
|
sim_matrix = sim_matrix.masked_fill(mask, -9e15)
|
||||||
loss = -torch.log(positives / sim_matrix.sum(dim=-1))
|
|
||||||
return loss.mean()
|
targets = torch.arange(2 * batch_size, device=z.device)
|
||||||
|
targets[:batch_size] += batch_size
|
||||||
|
targets[batch_size:] -= batch_size
|
||||||
|
|
||||||
|
return F.cross_entropy(sim_matrix, targets)
|
||||||
|
|
||||||
# --- ENTRENAMIENTO CON BENCHMARKING ---
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
print("--- PYTHON TRAINING BENCHMARK ---")
|
print(f"Launching VRAM-Optimized Contrastive Pipeline on: {DEVICE}")
|
||||||
print(f"Device: {DEVICE}")
|
print(f"Physical Batch Size: {BATCH_SIZE} | Accumulation Steps: {ACCUMULATION_STEPS} | Effective Batch Size: {BATCH_SIZE * ACCUMULATION_STEPS}")
|
||||||
process = psutil.Process(os.getpid())
|
|
||||||
start_mem = process.memory_info().rss / 1024 / 1024 # MB
|
|
||||||
print(f"Initial Memory Usage: {start_mem:.2f} MB")
|
|
||||||
|
|
||||||
dataset = MSIDataset(IMG_DIR, transform=MSIAugmentations())
|
|
||||||
print(f"Number of Ion Images: {len(dataset)}")
|
|
||||||
|
|
||||||
# pin_memory=True and num_workers > 0 optimized for CUDA
|
|
||||||
num_workers = 4 if DEVICE.type == 'cuda' else 0
|
|
||||||
loader = DataLoader(dataset, batch_size=BATCH_SIZE, shuffle=True, drop_last=True,
|
|
||||||
pin_memory=(DEVICE.type == 'cuda'), num_workers=num_workers)
|
|
||||||
|
|
||||||
model = SimCLR_MSI().to(DEVICE)
|
|
||||||
optimizer = optim.Adam(model.parameters(), lr=LEARNING_RATE)
|
|
||||||
|
|
||||||
start_time = time.time()
|
|
||||||
|
|
||||||
try:
|
|
||||||
for epoch in range(EPOCHS):
|
|
||||||
epoch_start = time.time()
|
|
||||||
total_loss = 0
|
|
||||||
for (img1, img2), names in loader:
|
|
||||||
img1, img2 = img1.to(DEVICE), img2.to(DEVICE)
|
|
||||||
optimizer.zero_grad()
|
|
||||||
_, z1 = model(img1)
|
|
||||||
_, z2 = model(img2)
|
|
||||||
loss = nt_xent_loss(z1, z2, temperature=TEMPERATURE)
|
|
||||||
loss.backward()
|
|
||||||
optimizer.step()
|
|
||||||
total_loss += loss.item()
|
|
||||||
|
|
||||||
avg_loss = total_loss / len(loader)
|
|
||||||
epoch_end = time.time()
|
|
||||||
curr_mem = process.memory_info().rss / 1024 / 1024 # MB
|
|
||||||
print(f"Epoch [{epoch+1}/{EPOCHS}], Loss: {avg_loss:.4f}, Time: {epoch_end-epoch_start:.2f}s, RAM: {curr_mem:.2f} MB")
|
|
||||||
except RuntimeError as e:
|
|
||||||
if "shared memory" in str(e).lower() or "shm" in str(e).lower() or "no space left on device" in str(e).lower():
|
|
||||||
print("\n" + "!"*60)
|
|
||||||
print("[ERROR] Shared memory (shm) exhaustion detected.")
|
|
||||||
print("This is a common issue when running PyTorch in Docker containers.")
|
|
||||||
print("\nFIX:")
|
|
||||||
print("Add '--shm-size=2gb' (or more) to your 'docker run' command.")
|
|
||||||
print("Example: docker run -it --rm --shm-size=2gb --gpus all ...")
|
|
||||||
print("!"*60 + "\n")
|
|
||||||
raise e
|
|
||||||
|
|
||||||
total_time = time.time() - start_time
|
|
||||||
peak_mem = process.memory_info().rss / 1024 / 1024 # MB
|
|
||||||
|
|
||||||
print("\n--- TRAINING COMPLETE ---")
|
|
||||||
print(f"Total Training Time: {total_time:.2f} seconds ({total_time/60:.2f} minutes)")
|
|
||||||
print(f"Peak Memory Usage: {peak_mem:.2f} MB")
|
|
||||||
|
|
||||||
os.makedirs(os.path.dirname(MODEL_SAVE_PATH), exist_ok=True)
|
os.makedirs(os.path.dirname(MODEL_SAVE_PATH), exist_ok=True)
|
||||||
torch.save(model.encoder.state_dict(), MODEL_SAVE_PATH)
|
|
||||||
|
aug_pipeline = MSIAugmentations(size=256)
|
||||||
|
dataset = SimCLRMSIDataset(IMG_DIR, transform=aug_pipeline)
|
||||||
|
loader = DataLoader(dataset, batch_size=BATCH_SIZE, shuffle=True, drop_last=True, num_workers=2, pin_memory=True)
|
||||||
|
|
||||||
|
model = MSI_Structural_Encoder().to(DEVICE)
|
||||||
|
optimizer = optim.AdamW(model.parameters(), lr=LEARNING_RATE, weight_decay=1e-4)
|
||||||
|
scheduler = optim.lr_scheduler.CosineAnnealingLR(optimizer, T_max=EPOCHS, eta_min=1e-6)
|
||||||
|
|
||||||
|
process = psutil.Process(os.getpid())
|
||||||
|
|
||||||
|
# Environment tweak to combat memory fragmentation
|
||||||
|
os.environ["PYTORCH_CUDA_ALLOC_CONF"] = "expandable_segments:True"
|
||||||
|
torch.cuda.empty_cache()
|
||||||
|
|
||||||
|
for epoch in range(EPOCHS):
|
||||||
|
model.train()
|
||||||
|
total_loss = 0
|
||||||
|
epoch_start = time.time()
|
||||||
|
|
||||||
|
optimizer.zero_grad() # Initialize gradients outside the accumulation loop
|
||||||
|
|
||||||
|
for batch_idx, (xi, xj) in enumerate(loader):
|
||||||
|
xi, xj = xi.to(DEVICE), xj.to(DEVICE)
|
||||||
|
|
||||||
|
_, z1 = model(xi)
|
||||||
|
_, z2 = model(xj)
|
||||||
|
|
||||||
|
# Scale loss by accumulation steps to ensure correct gradient weighting
|
||||||
|
loss = nt_xent_loss(z1, z2, temperature=TEMPERATURE) / ACCUMULATION_STEPS
|
||||||
|
loss.backward()
|
||||||
|
|
||||||
|
total_loss += loss.item() * ACCUMULATION_STEPS
|
||||||
|
|
||||||
|
# Step the optimizer only after gathering enough gradients
|
||||||
|
if (batch_idx + 1) % ACCUMULATION_STEPS == 0 or (batch_idx + 1) == len(loader):
|
||||||
|
optimizer.step()
|
||||||
|
optimizer.zero_grad()
|
||||||
|
|
||||||
|
scheduler.step()
|
||||||
|
|
||||||
|
# Periodic cache flushing keeps VRAM overhead low
|
||||||
|
if epoch % 5 == 0:
|
||||||
|
torch.cuda.empty_cache()
|
||||||
|
|
||||||
|
print(f"Epoch [{epoch+1}/{EPOCHS}], Loss: {total_loss / len(loader):.4f}, Time: {time.time()-epoch_start:.2f}s, RAM Used: {process.memory_info().rss / 1024 / 1024:.1f} MB")
|
||||||
|
|
||||||
|
print(f"--> Exporting optimized 32-BS encoder weights to: {MODEL_SAVE_PATH}")
|
||||||
|
torch.save(model.features.state_dict(), MODEL_SAVE_PATH)
|
||||||
print(f"Model saved to: {MODEL_SAVE_PATH}")
|
print(f"Model saved to: {MODEL_SAVE_PATH}")
|
||||||
|
|||||||
@@ -9,6 +9,7 @@ from sklearn.cluster import KMeans
|
|||||||
from sklearn.decomposition import PCA
|
from sklearn.decomposition import PCA
|
||||||
from sklearn.metrics import silhouette_score, davies_bouldin_score, calinski_harabasz_score
|
from sklearn.metrics import silhouette_score, davies_bouldin_score, calinski_harabasz_score
|
||||||
import matplotlib.pyplot as plt
|
import matplotlib.pyplot as plt
|
||||||
|
import torch.nn.functional as F
|
||||||
|
|
||||||
# 0. REPRODUCIBILITY
|
# 0. REPRODUCIBILITY
|
||||||
def set_seed(seed=42):
|
def set_seed(seed=42):
|
||||||
@@ -27,23 +28,42 @@ set_seed(42)
|
|||||||
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
|
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
|
||||||
IMG_DIR = os.path.join(BASE_DIR, "..", "datos_para_ai")
|
IMG_DIR = os.path.join(BASE_DIR, "..", "datos_para_ai")
|
||||||
MODEL_PATH = os.path.join(BASE_DIR, "..", "models", "msi_encoder_trained.pth")
|
MODEL_PATH = os.path.join(BASE_DIR, "..", "models", "msi_encoder_trained.pth")
|
||||||
# ENABLE CUDA IF AVAILABLE
|
|
||||||
DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
||||||
K_RANGE = range(2, 21) # Testing from 2 to 20 clusters
|
K_RANGE = range(2, 21) # Testing from 2 to 20 clusters
|
||||||
|
|
||||||
|
class MSI_Structural_Encoder(nn.Module):
|
||||||
|
def __init__(self):
|
||||||
|
super(MSI_Structural_Encoder, self).__init__()
|
||||||
|
self.features = nn.Sequential(
|
||||||
|
nn.Conv2d(1, 32, kernel_size=5, stride=2, padding=2, bias=False),
|
||||||
|
nn.GroupNorm(4, 32),
|
||||||
|
nn.ReLU(),
|
||||||
|
nn.Conv2d(32, 64, kernel_size=3, stride=2, padding=1, bias=False),
|
||||||
|
nn.GroupNorm(8, 64),
|
||||||
|
nn.ReLU(),
|
||||||
|
nn.Conv2d(64, 128, kernel_size=3, stride=2, padding=1, bias=False),
|
||||||
|
nn.GroupNorm(16, 128),
|
||||||
|
nn.ReLU(),
|
||||||
|
nn.Conv2d(128, 256, kernel_size=3, stride=2, padding=1, bias=False),
|
||||||
|
nn.GroupNorm(32, 256),
|
||||||
|
nn.ReLU(),
|
||||||
|
nn.AdaptiveAvgPool2d((1, 1))
|
||||||
|
)
|
||||||
|
|
||||||
|
def forward(self, x):
|
||||||
|
return self.features(x).squeeze(-1).squeeze(-1)
|
||||||
|
|
||||||
# 1. LOAD MODEL AND EXTRACT FEATURES
|
# 1. LOAD MODEL AND EXTRACT FEATURES
|
||||||
def extract_features():
|
def extract_features():
|
||||||
# Load the trained encoder
|
model = MSI_Structural_Encoder()
|
||||||
model = models.efficientnet_b0()
|
|
||||||
model.classifier = nn.Identity()
|
|
||||||
if not os.path.exists(MODEL_PATH):
|
if not os.path.exists(MODEL_PATH):
|
||||||
raise FileNotFoundError(f"No se encontró el modelo en {MODEL_PATH}")
|
raise FileNotFoundError(f"No se encontró el modelo en {MODEL_PATH}")
|
||||||
model.load_state_dict(torch.load(MODEL_PATH, map_location=DEVICE))
|
model.features.load_state_dict(torch.load(MODEL_PATH, map_location=DEVICE))
|
||||||
model.to(DEVICE)
|
model.to(DEVICE)
|
||||||
model.eval()
|
model.eval()
|
||||||
|
|
||||||
transform = transforms.Compose([
|
transform = transforms.Compose([
|
||||||
transforms.Resize((224, 224)),
|
transforms.Resize((256, 256)),
|
||||||
transforms.ToTensor(),
|
transforms.ToTensor(),
|
||||||
])
|
])
|
||||||
|
|
||||||
@@ -57,10 +77,12 @@ def extract_features():
|
|||||||
for i, name in enumerate(img_names):
|
for i, name in enumerate(img_names):
|
||||||
if i % 100 == 0: print(f"Processing image {i}/{len(img_names)}...")
|
if i % 100 == 0: print(f"Processing image {i}/{len(img_names)}...")
|
||||||
img_path = os.path.join(IMG_DIR, name)
|
img_path = os.path.join(IMG_DIR, name)
|
||||||
img = Image.open(img_path).convert("RGB")
|
img = Image.open(img_path).convert("L")
|
||||||
img_t = transform(img).unsqueeze(0).to(DEVICE)
|
img_t = transform(img).unsqueeze(0).to(DEVICE)
|
||||||
feat = model(img_t).cpu().numpy().flatten()
|
feat = model(img_t)
|
||||||
features.append(feat)
|
# CRITICAL FIX: Project explicitly onto the unit hypersphere
|
||||||
|
feat_norm = F.normalize(feat, p=2, dim=1)
|
||||||
|
features.append(feat_norm.cpu().numpy().flatten())
|
||||||
|
|
||||||
return np.array(features)
|
return np.array(features)
|
||||||
|
|
||||||
@@ -68,10 +90,7 @@ def extract_features():
|
|||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
X = extract_features()
|
X = extract_features()
|
||||||
|
|
||||||
# Dimensionality reduction (PCA) for stability.
|
pca = PCA(n_components=min(50, X.shape[1]), random_state=42)
|
||||||
# Reducing to 50 components is a heuristic to remove noise and redundant dimensions
|
|
||||||
# while preserving structural anatomical features (Jolliffe, 2002).
|
|
||||||
pca = PCA(n_components=50, random_state=42)
|
|
||||||
X_pca = pca.fit_transform(X)
|
X_pca = pca.fit_transform(X)
|
||||||
|
|
||||||
inertias = []
|
inertias = []
|
||||||
@@ -82,8 +101,6 @@ if __name__ == "__main__":
|
|||||||
print("Evaluating different K values...")
|
print("Evaluating different K values...")
|
||||||
for k in K_RANGE:
|
for k in K_RANGE:
|
||||||
print(f"Calculating for K={k}...")
|
print(f"Calculating for K={k}...")
|
||||||
# Standard scikit-learn k-means with fixed seed for reproducibility.
|
|
||||||
# n_init=10 ensures robust initialization.
|
|
||||||
kmeans = KMeans(n_clusters=k, random_state=42, n_init=10)
|
kmeans = KMeans(n_clusters=k, random_state=42, n_init=10)
|
||||||
labels = kmeans.fit_predict(X_pca)
|
labels = kmeans.fit_predict(X_pca)
|
||||||
|
|
||||||
@@ -92,31 +109,26 @@ if __name__ == "__main__":
|
|||||||
davies_bouldin.append(davies_bouldin_score(X_pca, labels))
|
davies_bouldin.append(davies_bouldin_score(X_pca, labels))
|
||||||
calinski_harabasz.append(calinski_harabasz_score(X_pca, labels))
|
calinski_harabasz.append(calinski_harabasz_score(X_pca, labels))
|
||||||
|
|
||||||
# 3. PLOT RESULTS (Multiple metrics)
|
|
||||||
fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2, figsize=(15, 10))
|
fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2, figsize=(15, 10))
|
||||||
|
|
||||||
# Elbow (Inertia)
|
|
||||||
ax1.plot(K_RANGE, inertias, 'o-', color='tab:red')
|
ax1.plot(K_RANGE, inertias, 'o-', color='tab:red')
|
||||||
ax1.set_title('Elbow Method (Inertia)')
|
ax1.set_title('Elbow Method (Inertia)')
|
||||||
ax1.set_xlabel('Number of Clusters (k)')
|
ax1.set_xlabel('Number of Clusters (k)')
|
||||||
ax1.set_ylabel('Sum of Squared Errors')
|
ax1.set_ylabel('Sum of Squared Errors')
|
||||||
ax1.grid(True)
|
ax1.grid(True)
|
||||||
|
|
||||||
# Silhouette
|
|
||||||
ax2.plot(K_RANGE, silhouettes, 's-', color='tab:blue')
|
ax2.plot(K_RANGE, silhouettes, 's-', color='tab:blue')
|
||||||
ax2.set_title('Silhouette Score (Higher is better)')
|
ax2.set_title('Silhouette Score (Higher is better)')
|
||||||
ax2.set_xlabel('Number of Clusters (k)')
|
ax2.set_xlabel('Number of Clusters (k)')
|
||||||
ax2.set_ylabel('Score')
|
ax2.set_ylabel('Score')
|
||||||
ax2.grid(True)
|
ax2.grid(True)
|
||||||
|
|
||||||
# Davies-Bouldin
|
|
||||||
ax3.plot(K_RANGE, davies_bouldin, '^-', color='tab:green')
|
ax3.plot(K_RANGE, davies_bouldin, '^-', color='tab:green')
|
||||||
ax3.set_title('Davies-Bouldin Index (Lower is better)')
|
ax3.set_title('Davies-Bouldin Index (Lower is better)')
|
||||||
ax3.set_xlabel('Number of Clusters (k)')
|
ax3.set_xlabel('Number of Clusters (k)')
|
||||||
ax3.set_ylabel('Score')
|
ax3.set_ylabel('Score')
|
||||||
ax3.grid(True)
|
ax3.grid(True)
|
||||||
|
|
||||||
# Calinski-Harabasz
|
|
||||||
ax4.plot(K_RANGE, calinski_harabasz, 'd-', color='tab:orange')
|
ax4.plot(K_RANGE, calinski_harabasz, 'd-', color='tab:orange')
|
||||||
ax4.set_title('Calinski-Harabasz Index (Higher is better)')
|
ax4.set_title('Calinski-Harabasz Index (Higher is better)')
|
||||||
ax4.set_xlabel('Number of Clusters (k)')
|
ax4.set_xlabel('Number of Clusters (k)')
|
||||||
@@ -129,14 +141,12 @@ if __name__ == "__main__":
|
|||||||
plt.savefig(output_plot)
|
plt.savefig(output_plot)
|
||||||
print(f"Plot saved as '{output_plot}'")
|
print(f"Plot saved as '{output_plot}'")
|
||||||
|
|
||||||
# Results report for K=10
|
|
||||||
idx_10 = list(K_RANGE).index(10)
|
idx_10 = list(K_RANGE).index(10)
|
||||||
print(f"\n--- RESULTS FOR K=10 ---")
|
print(f"\n--- RESULTS FOR K=10 ---")
|
||||||
print(f"Silhouette Score: {silhouettes[idx_10]:.4f}")
|
print(f"Silhouette Score: {silhouettes[idx_10]:.4f}")
|
||||||
print(f"Davies-Bouldin Index: {davies_bouldin[idx_10]:.4f}")
|
print(f"Davies-Bouldin Index: {davies_bouldin[idx_10]:.4f}")
|
||||||
print(f"Calinski-Harabasz Index: {calinski_harabasz[idx_10]:.4f}")
|
print(f"Calinski-Harabasz Index: {calinski_harabasz[idx_10]:.4f}")
|
||||||
|
|
||||||
# Suggested K by each metric
|
|
||||||
print(f"\n--- MATHEMATICAL SUGGESTIONS ---")
|
print(f"\n--- MATHEMATICAL SUGGESTIONS ---")
|
||||||
print(f"Best K (Silhouette): {K_RANGE[np.argmax(silhouettes)]}")
|
print(f"Best K (Silhouette): {K_RANGE[np.argmax(silhouettes)]}")
|
||||||
print(f"Best K (Davies-Bouldin): {K_RANGE[np.argmin(davies_bouldin)]}")
|
print(f"Best K (Davies-Bouldin): {K_RANGE[np.argmin(davies_bouldin)]}")
|
||||||
|
|||||||
@@ -6,12 +6,13 @@ from torchvision import models, transforms
|
|||||||
from PIL import Image
|
from PIL import Image
|
||||||
import numpy as np
|
import numpy as np
|
||||||
import random
|
import random
|
||||||
from sklearn.cluster import KMeans
|
from sklearn.decomposition import PCA
|
||||||
from sklearn.manifold import TSNE
|
from sklearn.manifold import TSNE
|
||||||
|
from sklearn.cluster import KMeans
|
||||||
import matplotlib.pyplot as plt
|
import matplotlib.pyplot as plt
|
||||||
import pandas as pd
|
import pandas as pd
|
||||||
|
import torch.nn.functional as F
|
||||||
|
|
||||||
# 0. REPRODUCIBILITY
|
|
||||||
def set_seed(seed=42):
|
def set_seed(seed=42):
|
||||||
random.seed(seed)
|
random.seed(seed)
|
||||||
np.random.seed(seed)
|
np.random.seed(seed)
|
||||||
@@ -24,35 +25,54 @@ def set_seed(seed=42):
|
|||||||
|
|
||||||
set_seed(42)
|
set_seed(42)
|
||||||
|
|
||||||
# 1. CONFIGURACIÓN
|
|
||||||
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
|
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
|
||||||
IMG_DIR = os.path.join(BASE_DIR, "..", "datos_para_ai")
|
IMG_DIR = os.path.join(BASE_DIR, "..", "datos_para_ai")
|
||||||
ENCODER_PATH = os.path.join(BASE_DIR, "..", "models", "msi_encoder_trained.pth")
|
ENCODER_PATH = os.path.join(BASE_DIR, "..", "models", "msi_encoder_trained.pth")
|
||||||
N_CLUSTERS = 10
|
|
||||||
DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
||||||
|
TARGET_K = 10 # Enforce your target 10 metabolic domains
|
||||||
|
|
||||||
|
class MSI_Structural_Encoder(nn.Module):
|
||||||
|
def __init__(self):
|
||||||
|
super(MSI_Structural_Encoder, self).__init__()
|
||||||
|
# Matches the high-fidelity GroupNorm architecture
|
||||||
|
self.features = nn.Sequential(
|
||||||
|
nn.Conv2d(1, 32, kernel_size=5, stride=2, padding=2, bias=False),
|
||||||
|
nn.GroupNorm(4, 32),
|
||||||
|
nn.ReLU(),
|
||||||
|
nn.Conv2d(32, 64, kernel_size=3, stride=2, padding=1, bias=False),
|
||||||
|
nn.GroupNorm(8, 64),
|
||||||
|
nn.ReLU(),
|
||||||
|
nn.Conv2d(64, 128, kernel_size=3, stride=2, padding=1, bias=False),
|
||||||
|
nn.GroupNorm(16, 128),
|
||||||
|
nn.ReLU(),
|
||||||
|
nn.Conv2d(128, 256, kernel_size=3, stride=2, padding=1, bias=False),
|
||||||
|
nn.GroupNorm(32, 256),
|
||||||
|
nn.ReLU(),
|
||||||
|
nn.AdaptiveAvgPool2d((1, 1))
|
||||||
|
)
|
||||||
|
|
||||||
|
def forward(self, x):
|
||||||
|
h = self.features(x).squeeze(-1).squeeze(-1)
|
||||||
|
return h
|
||||||
|
|
||||||
# 2. CARGAR EL MODELO ENTRENADO
|
|
||||||
def load_trained_encoder(path):
|
def load_trained_encoder(path):
|
||||||
if not os.path.exists(path):
|
if not os.path.exists(path):
|
||||||
raise FileNotFoundError(f"No se encontró el modelo en {path}")
|
raise FileNotFoundError(f"Missing model checkpoint: {path}")
|
||||||
|
|
||||||
model = models.efficientnet_b0()
|
model = MSI_Structural_Encoder()
|
||||||
model.classifier = nn.Identity()
|
# Loading only the feature extractor weights
|
||||||
|
model.features.load_state_dict(torch.load(path, map_location=DEVICE))
|
||||||
state_dict = torch.load(path, map_location=DEVICE)
|
|
||||||
model.load_state_dict(state_dict)
|
|
||||||
model.to(DEVICE)
|
model.to(DEVICE)
|
||||||
model.eval()
|
model.eval()
|
||||||
return model
|
return model
|
||||||
|
|
||||||
# 3. DATASET PARA INFERENCIA
|
|
||||||
class MSIDatasetInference(Dataset):
|
class MSIDatasetInference(Dataset):
|
||||||
def __init__(self, img_dir):
|
def __init__(self, img_dir):
|
||||||
self.img_dir = img_dir
|
self.img_dir = img_dir
|
||||||
self.img_names = sorted([f for f in os.listdir(img_dir) if f.endswith('.png')])
|
self.img_names = sorted([f for f in os.listdir(img_dir) if f.endswith('.png')])
|
||||||
self.transform = transforms.Compose([
|
self.transform = transforms.Compose([
|
||||||
transforms.Resize((224, 224)),
|
transforms.Resize((256, 256)),
|
||||||
transforms.ToTensor(),
|
transforms.ToTensor()
|
||||||
])
|
])
|
||||||
|
|
||||||
def __len__(self):
|
def __len__(self):
|
||||||
@@ -60,64 +80,73 @@ class MSIDatasetInference(Dataset):
|
|||||||
|
|
||||||
def __getitem__(self, idx):
|
def __getitem__(self, idx):
|
||||||
img_path = os.path.join(self.img_dir, self.img_names[idx])
|
img_path = os.path.join(self.img_dir, self.img_names[idx])
|
||||||
image = Image.open(img_path).convert("RGB")
|
image = Image.open(img_path).convert("L")
|
||||||
return self.transform(image), self.img_names[idx]
|
return self.transform(image), self.img_names[idx]
|
||||||
|
|
||||||
# --- PROCESO ---
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
print("Extrayendo características con el encoder...")
|
print("Loading specialized custom MSI Structural Encoder...")
|
||||||
try:
|
|
||||||
encoder = load_trained_encoder(ENCODER_PATH)
|
encoder = load_trained_encoder(ENCODER_PATH)
|
||||||
except Exception as e:
|
|
||||||
print(f"Error al cargar el modelo: {e}")
|
|
||||||
exit(1)
|
|
||||||
|
|
||||||
dataset = MSIDatasetInference(IMG_DIR)
|
dataset = MSIDatasetInference(IMG_DIR)
|
||||||
if len(dataset) == 0:
|
|
||||||
print(f"No se encontraron imágenes en {IMG_DIR}")
|
|
||||||
exit(1)
|
|
||||||
|
|
||||||
loader = DataLoader(dataset, batch_size=1, shuffle=False)
|
loader = DataLoader(dataset, batch_size=1, shuffle=False)
|
||||||
|
|
||||||
features = []
|
features = []
|
||||||
ion_names = []
|
ion_names = []
|
||||||
|
|
||||||
|
print("Extracting and L2-normalizing features from custom manifold...")
|
||||||
with torch.no_grad():
|
with torch.no_grad():
|
||||||
for img, name in loader:
|
for img, name in loader:
|
||||||
img = img.to(DEVICE)
|
img = img.to(DEVICE)
|
||||||
feat = encoder(img)
|
feat = encoder(img)
|
||||||
# Normalización L2
|
# Re-enforce unit hypersphere mapping
|
||||||
feat = feat / feat.norm(p=2, dim=1, keepdim=True)
|
feat = F.normalize(feat, p=2, dim=1)
|
||||||
features.append(feat.cpu().numpy().flatten())
|
features.append(feat.cpu().numpy().flatten())
|
||||||
ion_names.append(name[0])
|
ion_names.append(name[0])
|
||||||
|
|
||||||
features = np.array(features)
|
features = np.array(features)
|
||||||
|
|
||||||
# 4. CLUSTERING K-MEANS
|
# Dimensionality Reduction Optimization
|
||||||
print(f"Realizando KMeans con {N_CLUSTERS} clusters...")
|
pca_km = PCA(n_components=min(50, len(features)), random_state=42)
|
||||||
km = KMeans(n_clusters=N_CLUSTERS, n_init=20, random_state=42)
|
features_pca_all = pca_km.fit_transform(features)
|
||||||
labels = km.fit_predict(features)
|
|
||||||
|
|
||||||
# 5. VISUALIZACIÓN t-SNE CORREGIDA
|
# FIX: Slice out the first principal component (index 0)
|
||||||
print("Generando visualización t-SNE con escala corregida...")
|
# if it continues to hold the global brightness/intensity bias
|
||||||
tsne = TSNE(n_components=2, perplexity=30, random_state=42)
|
features_pca_km = features_pca_all[:, 1:]
|
||||||
embeddings_2d = tsne.fit_transform(features)
|
|
||||||
|
|
||||||
|
# ENFORCE EXACTLY 10 METABOLIC DOMAINS
|
||||||
|
print(f"Executing K-Means clustering strictly constrained to K={TARGET_K}...")
|
||||||
|
clusterer = KMeans(n_clusters=TARGET_K, init='k-means++', n_init=20, random_state=42)
|
||||||
|
labels = clusterer.fit_predict(features_pca_km)
|
||||||
|
|
||||||
|
# MANIFOLD PROJECTION ADJUSTMENT
|
||||||
|
print("Projecting t-SNE map...")
|
||||||
|
tsne = TSNE(
|
||||||
|
n_components=2,
|
||||||
|
perplexity=15, # Reduced from 25 to force local structural groupings
|
||||||
|
early_exaggeration=12.0, # Adjusted to optimize structural separation distance
|
||||||
|
learning_rate='auto',
|
||||||
|
init='pca', # Changed from 'random' to preserve global cluster seed stability
|
||||||
|
random_state=42
|
||||||
|
)
|
||||||
|
embeddings_2d = tsne.fit_transform(features_pca_km)
|
||||||
|
|
||||||
|
# Plotting
|
||||||
plt.figure(figsize=(10, 8))
|
plt.figure(figsize=(10, 8))
|
||||||
# Aplicando tu corrección específica:
|
scatter = plt.scatter(embeddings_2d[:, 0], embeddings_2d[:, 1], c=labels, cmap='tab10', alpha=0.9, edgecolors='none', s=45)
|
||||||
scatter = plt.scatter(embeddings_2d[:, 0], embeddings_2d[:, 1], c=labels, cmap='tab10', alpha=0.8, edgecolors='w', s=50)
|
cbar = plt.colorbar(scatter, ticks=range(TARGET_K))
|
||||||
|
cbar.set_label('Metabolic Domain ID (K=10)')
|
||||||
|
|
||||||
# Configuración de la barra de colores con los ticks exactos para 10 clusters
|
plt.title("Objectively Segmented Leaf Manifold (Custom Encoder)")
|
||||||
cbar = plt.colorbar(scatter, ticks=range(N_CLUSTERS))
|
plt.xlabel("t-SNE Dimension 1")
|
||||||
cbar.set_label('Cluster ID')
|
plt.ylabel("t-SNE Dimension 2")
|
||||||
|
plt.grid(True, linestyle='--', alpha=0.3)
|
||||||
|
|
||||||
plt.title(f"t-SNE Visualization of MSI Ions (K={N_CLUSTERS})")
|
plt.savefig(os.path.join(BASE_DIR, "..", "msi_tsne_corregido.png"), dpi=300, bbox_inches='tight')
|
||||||
plt.xlabel("t-SNE dimension 1")
|
plt.close()
|
||||||
plt.ylabel("t-SNE dimension 2")
|
|
||||||
plt.grid(True, linestyle='--', alpha=0.5)
|
|
||||||
|
|
||||||
output_file = "msi_tsne_corregido.png"
|
# Save outputs
|
||||||
plt.savefig(output_file, dpi=300, bbox_inches='tight')
|
print("Exporting synchronized cluster assignments...")
|
||||||
# plt.show()
|
df_results = pd.DataFrame({'ion_image': ion_names, 'cluster': labels})
|
||||||
|
df_results['mz'] = df_results['ion_image'].str.extract(r'(\d+\.\d+)').astype(float)
|
||||||
|
df_results.to_csv(os.path.join(BASE_DIR, "..", "msi_clusters_results.csv"), index=False)
|
||||||
|
|
||||||
print(f"Visualización guardada exitosamente en '{output_file}'.")
|
print("Process complete.")
|
||||||
|
|||||||
@@ -0,0 +1,195 @@
|
|||||||
|
import os
|
||||||
|
import torch
|
||||||
|
import torch.nn as nn
|
||||||
|
from torchvision import models, transforms
|
||||||
|
from PIL import Image
|
||||||
|
import numpy as np
|
||||||
|
import pandas as pd
|
||||||
|
import torch.nn.functional as F
|
||||||
|
import matplotlib.pyplot as plt
|
||||||
|
|
||||||
|
# 1. CONFIGURATION
|
||||||
|
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
|
||||||
|
IMG_DIR = os.path.join(BASE_DIR, "..", "datos_para_ai")
|
||||||
|
ENCODER_PATH = os.path.join(BASE_DIR, "..", "models", "msi_encoder_trained.pth")
|
||||||
|
OUTPUT_DIR = os.path.join(BASE_DIR, "..", "figures", "guided_validation")
|
||||||
|
os.makedirs(OUTPUT_DIR, exist_ok=True)
|
||||||
|
|
||||||
|
DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
||||||
|
|
||||||
|
# FIX: Restore the full list of verified vascular landmarks to build a robust structural vector
|
||||||
|
ANCHOR_MZS = [155.75, 156.07, 156.40, 273.77, 274.09, 275.07, 286.12, 304.00, 304.33]
|
||||||
|
SIMI_THRESHOLD = 0.85 # Calibrated to capture true negative space co-exclusions down to 0.85
|
||||||
|
|
||||||
|
class MSI_Structural_Encoder(nn.Module):
|
||||||
|
"""
|
||||||
|
The exact high-fidelity custom architecture used during your successful
|
||||||
|
zero-padded 256x256 contrastive training run.
|
||||||
|
"""
|
||||||
|
def __init__(self):
|
||||||
|
super(MSI_Structural_Encoder, self).__init__()
|
||||||
|
|
||||||
|
self.features = nn.Sequential(
|
||||||
|
# Layer 1: Input 256x256x1 (Standardized size)
|
||||||
|
nn.Conv2d(1, 32, kernel_size=5, stride=2, padding=2, bias=False),
|
||||||
|
nn.GroupNorm(4, 32),
|
||||||
|
nn.ReLU(),
|
||||||
|
|
||||||
|
# Layer 2
|
||||||
|
nn.Conv2d(32, 64, kernel_size=3, stride=2, padding=1, bias=False),
|
||||||
|
nn.GroupNorm(8, 64),
|
||||||
|
nn.ReLU(),
|
||||||
|
|
||||||
|
# Layer 3
|
||||||
|
nn.Conv2d(64, 128, kernel_size=3, stride=2, padding=1, bias=False),
|
||||||
|
nn.GroupNorm(16, 128),
|
||||||
|
nn.ReLU(),
|
||||||
|
|
||||||
|
# Layer 4
|
||||||
|
nn.Conv2d(128, 256, kernel_size=3, stride=2, padding=1, bias=False),
|
||||||
|
nn.GroupNorm(32, 256),
|
||||||
|
nn.ReLU(),
|
||||||
|
|
||||||
|
nn.AdaptiveAvgPool2d((1, 1))
|
||||||
|
)
|
||||||
|
|
||||||
|
def forward(self, x):
|
||||||
|
h = self.features(x).squeeze(-1).squeeze(-1)
|
||||||
|
return h
|
||||||
|
|
||||||
|
def load_trained_encoder(path):
|
||||||
|
if not os.path.exists(path):
|
||||||
|
raise FileNotFoundError(f"Missing model checkpoint: {path}")
|
||||||
|
|
||||||
|
model = MSI_Structural_Encoder()
|
||||||
|
# Load only the feature extractor weights to match the save format in CNN_proof_1.py
|
||||||
|
model.features.load_state_dict(torch.load(path, map_location=DEVICE))
|
||||||
|
print(f"Successfully synchronized weights with custom encoder architecture: {path}")
|
||||||
|
|
||||||
|
model.to(DEVICE)
|
||||||
|
model.eval()
|
||||||
|
return model
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
encoder = load_trained_encoder(ENCODER_PATH)
|
||||||
|
|
||||||
|
transform = transforms.Compose([
|
||||||
|
transforms.Resize((256, 256)), # Standardized size matching training
|
||||||
|
transforms.ToTensor()
|
||||||
|
])
|
||||||
|
|
||||||
|
# 3. SCAN ALL IMAGE MAPS
|
||||||
|
all_files = sorted([f for f in os.listdir(IMG_DIR) if f.endswith('.png')])
|
||||||
|
print(f"Discovered {len(all_files)} total ion slices in data pool.")
|
||||||
|
|
||||||
|
ion_registry = []
|
||||||
|
for f in all_files:
|
||||||
|
try:
|
||||||
|
mz_extracted = float(f.replace("ion_", "").replace(".png", ""))
|
||||||
|
ion_registry.append({"filename": f, "mz": mz_extracted})
|
||||||
|
except ValueError:
|
||||||
|
continue
|
||||||
|
|
||||||
|
df_ions = pd.DataFrame(ion_registry)
|
||||||
|
|
||||||
|
# 4. EXTRACT VECTORS
|
||||||
|
print("Extracting L2-normalized latent fingerprints...")
|
||||||
|
latent_vectors = {}
|
||||||
|
|
||||||
|
with torch.no_grad():
|
||||||
|
for _, row in df_ions.iterrows():
|
||||||
|
fpath = os.path.join(IMG_DIR, row['filename'])
|
||||||
|
img_tensor = transform(Image.open(fpath).convert("L")).unsqueeze(0).to(DEVICE)
|
||||||
|
feat = encoder(img_tensor)
|
||||||
|
feat_norm = F.normalize(feat, p=2, dim=1) # Project onto unit hypersphere
|
||||||
|
latent_vectors[row['filename']] = feat_norm.squeeze(0).cpu().numpy()
|
||||||
|
|
||||||
|
# 5. CONSTRUCT SEED
|
||||||
|
anchor_features = []
|
||||||
|
found_anchors = []
|
||||||
|
|
||||||
|
for anchor in ANCHOR_MZS:
|
||||||
|
match = df_ions[np.isclose(df_ions['mz'], anchor, atol=0.05)]
|
||||||
|
if not match.empty:
|
||||||
|
fname = match.iloc[0]['filename']
|
||||||
|
anchor_features.append(latent_vectors[fname])
|
||||||
|
found_anchors.append(fname)
|
||||||
|
|
||||||
|
if len(anchor_features) == 0:
|
||||||
|
print("Error: None of your specified anchor vein images were located.")
|
||||||
|
exit()
|
||||||
|
|
||||||
|
vascular_profile_centroid = np.mean(anchor_features, axis=0)
|
||||||
|
vascular_profile_centroid /= np.linalg.norm(vascular_profile_centroid)
|
||||||
|
|
||||||
|
print(f"Generated unified vascular profile from {len(found_anchors)} anchor ions.")
|
||||||
|
|
||||||
|
# 6. EVALUATE SIMILARITY
|
||||||
|
guided_matches = []
|
||||||
|
for fname, vector in latent_vectors.items():
|
||||||
|
similarity = np.dot(vector, vascular_profile_centroid)
|
||||||
|
if similarity >= SIMI_THRESHOLD:
|
||||||
|
mz_val = df_ions[df_ions['filename'] == fname]['mz'].values[0]
|
||||||
|
guided_matches.append({"filename": fname, "mz": mz_val, "similarity": similarity})
|
||||||
|
|
||||||
|
df_guided = pd.DataFrame(guided_matches).sort_values(by="similarity", ascending=False)
|
||||||
|
print(f"\nFound {len(df_guided)} ions displaying vascular alignment (Cosine Sim >= {SIMI_THRESHOLD})")
|
||||||
|
|
||||||
|
csv_out = os.path.join(OUTPUT_DIR, "guided_vascular_ions.csv")
|
||||||
|
df_guided.to_csv(csv_out, index=False)
|
||||||
|
|
||||||
|
# 7. GENERATE GALLERIES
|
||||||
|
max_per_page = 12
|
||||||
|
chunks = [df_guided[i:i + max_per_page] for i in range(0, len(df_guided), max_per_page)]
|
||||||
|
|
||||||
|
for page_idx, chunk in enumerate(chunks):
|
||||||
|
num_plots = len(chunk)
|
||||||
|
rows = int(np.ceil(num_plots / 4))
|
||||||
|
cols = min(num_plots, 4)
|
||||||
|
|
||||||
|
fig, axes = plt.subplots(rows, cols, figsize=(16, rows * 4))
|
||||||
|
fig.suptitle(f"Guided Vascular Affinity Grouping - Tier {page_idx + 1}", fontsize=16, y=0.98)
|
||||||
|
|
||||||
|
flat_axes = axes.flatten() if isinstance(axes, np.ndarray) else [axes]
|
||||||
|
|
||||||
|
for idx, (_, row) in enumerate(chunk.iterrows()):
|
||||||
|
ax = flat_axes[idx]
|
||||||
|
img_path = os.path.join(IMG_DIR, row['filename'])
|
||||||
|
img = Image.open(img_path)
|
||||||
|
# Use 'viridis' for improved structural visibility
|
||||||
|
ax.imshow(img, cmap='viridis')
|
||||||
|
ax.set_title(f"m/z {row['mz']:.2f}\nSim: {row['similarity']:.4f}", fontsize=10)
|
||||||
|
ax.axis('off')
|
||||||
|
|
||||||
|
for empty_idx in range(num_plots, len(flat_axes)):
|
||||||
|
flat_axes[empty_idx].axis('off')
|
||||||
|
|
||||||
|
plt.tight_layout()
|
||||||
|
gallery_out = os.path.join(OUTPUT_DIR, f"Guided_Vascular_Gallery_Page_{page_idx + 1}.png")
|
||||||
|
plt.savefig(gallery_out, dpi=200, bbox_inches='tight')
|
||||||
|
plt.close()
|
||||||
|
|
||||||
|
print("\nGuided extraction validation cycle complete.")
|
||||||
|
|
||||||
|
print("\n--- RUNNING ISOTOPIC FUNCTIONAL VALIDATION ---")
|
||||||
|
verified_biological_count = 0
|
||||||
|
|
||||||
|
for idx, row in df_guided.iterrows():
|
||||||
|
target_mz = row['mz']
|
||||||
|
isotope_mz = target_mz + 1.0033
|
||||||
|
|
||||||
|
# Check if the expected isotope exists within your parsed data pool
|
||||||
|
isotope_match = df_ions[np.isclose(df_ions['mz'], isotope_mz, atol=0.02)]
|
||||||
|
|
||||||
|
if not isotope_match.empty:
|
||||||
|
iso_fname = isotope_match.iloc[0]['filename']
|
||||||
|
iso_vector = latent_vectors[iso_fname]
|
||||||
|
|
||||||
|
# Calculate similarity of the isotope to your core vascular vector
|
||||||
|
iso_sim = np.dot(iso_vector, vascular_profile_centroid)
|
||||||
|
|
||||||
|
if iso_sim >= 0.80:
|
||||||
|
print(f"Verified Structural Pair: Base m/z {target_mz:.2f} (Sim: {row['similarity']:.4f}) -> Isotope m/z {isotope_mz:.2f} (Sim: {iso_sim:.4f})")
|
||||||
|
verified_biological_count += 1
|
||||||
|
|
||||||
|
print(f"Validation complete. Confirmed {verified_biological_count} true isotopic structural pairs.")
|
||||||
@@ -0,0 +1,109 @@
|
|||||||
|
import os
|
||||||
|
import torch
|
||||||
|
import torch.nn as nn
|
||||||
|
from torch.utils.data import DataLoader, Dataset
|
||||||
|
from torchvision import models, transforms
|
||||||
|
from PIL import Image
|
||||||
|
import numpy as np
|
||||||
|
from sklearn.cluster import KMeans
|
||||||
|
from sklearn.manifold import TSNE
|
||||||
|
import matplotlib.pyplot as plt
|
||||||
|
import pandas as pd
|
||||||
|
|
||||||
|
# 1. CONFIGURACIÓN
|
||||||
|
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
|
||||||
|
IMG_DIR = os.path.join(BASE_DIR, "../..", "datos_para_ai")
|
||||||
|
ENCODER_PATH = os.path.join(BASE_DIR, "../..", "models", "msi_encoder_trained.pth")
|
||||||
|
N_CLUSTERS = 10
|
||||||
|
DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
||||||
|
|
||||||
|
# 2. CARGAR EL MODELO ENTRENADO
|
||||||
|
def load_trained_encoder(path):
|
||||||
|
if not os.path.exists(path):
|
||||||
|
raise FileNotFoundError(f"No se encontró el modelo en {path}")
|
||||||
|
|
||||||
|
model = models.efficientnet_b0()
|
||||||
|
model.classifier = nn.Identity()
|
||||||
|
|
||||||
|
state_dict = torch.load(path, map_location=DEVICE)
|
||||||
|
model.load_state_dict(state_dict)
|
||||||
|
model.to(DEVICE)
|
||||||
|
model.eval()
|
||||||
|
return model
|
||||||
|
|
||||||
|
# 3. DATASET PARA INFERENCIA
|
||||||
|
class MSIDatasetInference(Dataset):
|
||||||
|
def __init__(self, img_dir):
|
||||||
|
self.img_dir = img_dir
|
||||||
|
self.img_names = sorted([f for f in os.listdir(img_dir) if f.endswith('.png')])
|
||||||
|
self.transform = transforms.Compose([
|
||||||
|
transforms.Resize((224, 224)),
|
||||||
|
transforms.ToTensor(),
|
||||||
|
])
|
||||||
|
|
||||||
|
def __len__(self):
|
||||||
|
return len(self.img_names)
|
||||||
|
|
||||||
|
def __getitem__(self, idx):
|
||||||
|
img_path = os.path.join(self.img_dir, self.img_names[idx])
|
||||||
|
image = Image.open(img_path).convert("RGB")
|
||||||
|
return self.transform(image), self.img_names[idx]
|
||||||
|
|
||||||
|
# --- PROCESO ---
|
||||||
|
if __name__ == "__main__":
|
||||||
|
print("Extrayendo características con el encoder...")
|
||||||
|
try:
|
||||||
|
encoder = load_trained_encoder(ENCODER_PATH)
|
||||||
|
except Exception as e:
|
||||||
|
print(f"Error al cargar el modelo: {e}")
|
||||||
|
exit(1)
|
||||||
|
|
||||||
|
dataset = MSIDatasetInference(IMG_DIR)
|
||||||
|
if len(dataset) == 0:
|
||||||
|
print(f"No se encontraron imágenes en {IMG_DIR}")
|
||||||
|
exit(1)
|
||||||
|
|
||||||
|
loader = DataLoader(dataset, batch_size=1, shuffle=False)
|
||||||
|
|
||||||
|
features = []
|
||||||
|
ion_names = []
|
||||||
|
|
||||||
|
with torch.no_grad():
|
||||||
|
for img, name in loader:
|
||||||
|
img = img.to(DEVICE)
|
||||||
|
feat = encoder(img)
|
||||||
|
# Normalización L2
|
||||||
|
feat = feat / feat.norm(p=2, dim=1, keepdim=True)
|
||||||
|
features.append(feat.cpu().numpy().flatten())
|
||||||
|
ion_names.append(name[0])
|
||||||
|
|
||||||
|
features = np.array(features)
|
||||||
|
|
||||||
|
# 4. CLUSTERING K-MEANS
|
||||||
|
print(f"Realizando KMeans con {N_CLUSTERS} clusters...")
|
||||||
|
km = KMeans(n_clusters=N_CLUSTERS, n_init=20, random_state=42)
|
||||||
|
labels = km.fit_predict(features)
|
||||||
|
|
||||||
|
# 5. VISUALIZACIÓN t-SNE CORREGIDA
|
||||||
|
print("Generando visualización t-SNE con escala corregida...")
|
||||||
|
tsne = TSNE(n_components=2, perplexity=30, random_state=42)
|
||||||
|
embeddings_2d = tsne.fit_transform(features)
|
||||||
|
|
||||||
|
plt.figure(figsize=(10, 8))
|
||||||
|
# Aplicando tu corrección específica:
|
||||||
|
scatter = plt.scatter(embeddings_2d[:, 0], embeddings_2d[:, 1], c=labels, cmap='tab10', alpha=0.8, edgecolors='w', s=50)
|
||||||
|
|
||||||
|
# Configuración de la barra de colores con los ticks exactos para 10 clusters
|
||||||
|
cbar = plt.colorbar(scatter, ticks=range(N_CLUSTERS))
|
||||||
|
cbar.set_label('Cluster ID')
|
||||||
|
|
||||||
|
plt.title(f"t-SNE Visualization of MSI Ions (K={N_CLUSTERS})")
|
||||||
|
plt.xlabel("t-SNE dimension 1")
|
||||||
|
plt.ylabel("t-SNE dimension 2")
|
||||||
|
plt.grid(True, linestyle='--', alpha=0.5)
|
||||||
|
|
||||||
|
output_file = "msi_tsne_corregido.png"
|
||||||
|
plt.savefig(output_file, dpi=300, bbox_inches='tight')
|
||||||
|
# plt.show()
|
||||||
|
|
||||||
|
print(f"Visualización guardada exitosamente en '{output_file}'.")
|
||||||
@@ -11,6 +11,7 @@ from sklearn.decomposition import PCA
|
|||||||
from sklearn.metrics import silhouette_score, davies_bouldin_score, calinski_harabasz_score, adjusted_rand_score
|
from sklearn.metrics import silhouette_score, davies_bouldin_score, calinski_harabasz_score, adjusted_rand_score
|
||||||
import matplotlib.pyplot as plt
|
import matplotlib.pyplot as plt
|
||||||
from scipy.stats import ttest_ind
|
from scipy.stats import ttest_ind
|
||||||
|
import torch.nn.functional as F
|
||||||
|
|
||||||
# 0. REPRODUCIBILITY
|
# 0. REPRODUCIBILITY
|
||||||
def set_seed(seed=42):
|
def set_seed(seed=42):
|
||||||
@@ -29,29 +30,43 @@ set_seed(42)
|
|||||||
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
|
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
|
||||||
IMG_DIR = os.path.join(BASE_DIR, "..", "datos_para_ai")
|
IMG_DIR = os.path.join(BASE_DIR, "..", "datos_para_ai")
|
||||||
MODEL_PATH = os.path.join(BASE_DIR, "..", "models", "msi_encoder_trained.pth")
|
MODEL_PATH = os.path.join(BASE_DIR, "..", "models", "msi_encoder_trained.pth")
|
||||||
# ENABLE CUDA IF AVAILABLE
|
|
||||||
DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
||||||
K = 10
|
K = 10
|
||||||
|
|
||||||
|
class MSI_Structural_Encoder(nn.Module):
|
||||||
|
def __init__(self):
|
||||||
|
super(MSI_Structural_Encoder, self).__init__()
|
||||||
|
self.features = nn.Sequential(
|
||||||
|
nn.Conv2d(1, 32, kernel_size=5, stride=2, padding=2, bias=False),
|
||||||
|
nn.GroupNorm(4, 32),
|
||||||
|
nn.ReLU(),
|
||||||
|
nn.Conv2d(32, 64, kernel_size=3, stride=2, padding=1, bias=False),
|
||||||
|
nn.GroupNorm(8, 64),
|
||||||
|
nn.ReLU(),
|
||||||
|
nn.Conv2d(64, 128, kernel_size=3, stride=2, padding=1, bias=False),
|
||||||
|
nn.GroupNorm(16, 128),
|
||||||
|
nn.ReLU(),
|
||||||
|
nn.Conv2d(128, 256, kernel_size=3, stride=2, padding=1, bias=False),
|
||||||
|
nn.GroupNorm(32, 256),
|
||||||
|
nn.ReLU(),
|
||||||
|
nn.AdaptiveAvgPool2d((1, 1))
|
||||||
|
)
|
||||||
|
|
||||||
|
def forward(self, x):
|
||||||
|
return self.features(x).squeeze(-1).squeeze(-1)
|
||||||
|
|
||||||
# 1. DATA LOADING
|
# 1. DATA LOADING
|
||||||
def load_images():
|
def load_images():
|
||||||
img_names = sorted([f for f in os.listdir(IMG_DIR) if f.endswith('.png')])
|
img_names = sorted([f for f in os.listdir(IMG_DIR) if f.endswith('.png')])
|
||||||
raw_pixels = []
|
raw_pixels = []
|
||||||
mzs = []
|
mzs = []
|
||||||
|
|
||||||
# transform = transforms.Compose([
|
|
||||||
# transforms.Resize((224, 224)),
|
|
||||||
# transforms.Grayscale(),
|
|
||||||
# transforms.ToTensor(),
|
|
||||||
# ])
|
|
||||||
|
|
||||||
print(f"Loading {len(img_names)} images for validation...")
|
print(f"Loading {len(img_names)} images for validation...")
|
||||||
for name in img_names:
|
for name in img_names:
|
||||||
img_path = os.path.join(IMG_DIR, name)
|
img_path = os.path.join(IMG_DIR, name)
|
||||||
img = Image.open(img_path).convert("L")
|
img = Image.open(img_path).convert("L")
|
||||||
raw_pixels.append(np.array(img).flatten())
|
raw_pixels.append(np.array(img).flatten())
|
||||||
|
|
||||||
# Extract mz from filename (ion_XXX.XX.png)
|
|
||||||
try:
|
try:
|
||||||
mz = float(name.split('_')[1].replace('.png', ''))
|
mz = float(name.split('_')[1].replace('.png', ''))
|
||||||
mzs.append(mz)
|
mzs.append(mz)
|
||||||
@@ -61,15 +76,14 @@ def load_images():
|
|||||||
return np.array(raw_pixels), np.array(mzs), img_names
|
return np.array(raw_pixels), np.array(mzs), img_names
|
||||||
|
|
||||||
def extract_simclr_features(img_names):
|
def extract_simclr_features(img_names):
|
||||||
model = models.efficientnet_b0()
|
model = MSI_Structural_Encoder()
|
||||||
model.classifier = nn.Identity()
|
|
||||||
if os.path.exists(MODEL_PATH):
|
if os.path.exists(MODEL_PATH):
|
||||||
model.load_state_dict(torch.load(MODEL_PATH, map_location=DEVICE))
|
model.features.load_state_dict(torch.load(MODEL_PATH, map_location=DEVICE))
|
||||||
model.to(DEVICE)
|
model.to(DEVICE)
|
||||||
model.eval()
|
model.eval()
|
||||||
|
|
||||||
transform = transforms.Compose([
|
transform = transforms.Compose([
|
||||||
transforms.Resize((224, 224)),
|
transforms.Resize((256, 256)),
|
||||||
transforms.ToTensor(),
|
transforms.ToTensor(),
|
||||||
])
|
])
|
||||||
|
|
||||||
@@ -78,25 +92,23 @@ def extract_simclr_features(img_names):
|
|||||||
with torch.no_grad():
|
with torch.no_grad():
|
||||||
for name in img_names:
|
for name in img_names:
|
||||||
img_path = os.path.join(IMG_DIR, name)
|
img_path = os.path.join(IMG_DIR, name)
|
||||||
img = Image.open(img_path).convert("RGB")
|
img = Image.open(img_path).convert("L")
|
||||||
img_t = transform(img).unsqueeze(0).to(DEVICE)
|
img_t = transform(img).unsqueeze(0).to(DEVICE)
|
||||||
feat = model(img_t).cpu().numpy().flatten()
|
feat = model(img_t)
|
||||||
features.append(feat)
|
# CRITICAL FIX: Project explicitly onto the unit hypersphere
|
||||||
|
feat_norm = F.normalize(feat, p=2, dim=1)
|
||||||
|
features.append(feat_norm.cpu().numpy().flatten())
|
||||||
return np.array(features)
|
return np.array(features)
|
||||||
|
|
||||||
# 2. VALIDATION TASKS
|
# 2. VALIDATION TASKS
|
||||||
def baseline_comparison(X_raw, X_simclr):
|
def baseline_comparison(X_raw, X_simclr):
|
||||||
print("\n--- TASK 1: BASELINE COMPARISON (PCA vs SimCLR) ---")
|
print("\n--- TASK 1: BASELINE COMPARISON (PCA vs SimCLR) ---")
|
||||||
|
|
||||||
# Baseline: PCA on Raw Pixels
|
|
||||||
pca_raw = PCA(n_components=50, random_state=42)
|
pca_raw = PCA(n_components=50, random_state=42)
|
||||||
X_pca_raw = pca_raw.fit_transform(X_raw)
|
X_pca_raw = pca_raw.fit_transform(X_raw)
|
||||||
|
|
||||||
# SimCLR: PCA on latent features (as done in the paper)
|
|
||||||
pca_simclr = PCA(n_components=50, random_state=42)
|
pca_simclr = PCA(n_components=50, random_state=42)
|
||||||
X_pca_simclr = pca_simclr.fit_transform(X_simclr)
|
X_pca_simclr = pca_simclr.fit_transform(X_simclr)
|
||||||
|
|
||||||
# Cluster both
|
|
||||||
km_raw = KMeans(n_clusters=K, random_state=42, n_init=10)
|
km_raw = KMeans(n_clusters=K, random_state=42, n_init=10)
|
||||||
labels_raw = km_raw.fit_predict(X_pca_raw)
|
labels_raw = km_raw.fit_predict(X_pca_raw)
|
||||||
|
|
||||||
@@ -129,7 +141,6 @@ def stability_analysis(X_features):
|
|||||||
all_labels.append(labels)
|
all_labels.append(labels)
|
||||||
metrics_list.append(silhouette_score(X_pca, labels))
|
metrics_list.append(silhouette_score(X_pca, labels))
|
||||||
|
|
||||||
# Calculate ARI between all pairs of runs
|
|
||||||
ari_scores = []
|
ari_scores = []
|
||||||
for i in range(len(all_labels)):
|
for i in range(len(all_labels)):
|
||||||
for j in range(i + 1, len(all_labels)):
|
for j in range(i + 1, len(all_labels)):
|
||||||
@@ -140,22 +151,18 @@ def stability_analysis(X_features):
|
|||||||
|
|
||||||
def isotope_validation(X_features, mzs):
|
def isotope_validation(X_features, mzs):
|
||||||
print("\n--- TASK 3: ISOTOPE CO-LOCALIZATION VALIDATION ---")
|
print("\n--- TASK 3: ISOTOPE CO-LOCALIZATION VALIDATION ---")
|
||||||
|
|
||||||
# Normalize features for distance calculation
|
|
||||||
X_norm = X_features / np.linalg.norm(X_features, axis=1, keepdims=True)
|
X_norm = X_features / np.linalg.norm(X_features, axis=1, keepdims=True)
|
||||||
|
|
||||||
isotope_dist = []
|
isotope_dist = []
|
||||||
random_dist = []
|
random_dist = []
|
||||||
|
|
||||||
# Find isotopic pairs (Adjusted to allow for binned channel drift)
|
|
||||||
for i in range(len(mzs)):
|
for i in range(len(mzs)):
|
||||||
for j in range(i + 1, len(mzs)):
|
for j in range(i + 1, len(mzs)):
|
||||||
diff = abs(mzs[i] - mzs[j])
|
diff = abs(mzs[i] - mzs[j])
|
||||||
if 0.95 <= diff <= 1.05: # Accommodates binned spacing variations
|
if 0.95 <= diff <= 1.05:
|
||||||
dist = np.linalg.norm(X_norm[i] - X_norm[j])
|
dist = np.linalg.norm(X_norm[i] - X_norm[j])
|
||||||
isotope_dist.append(dist)
|
isotope_dist.append(dist)
|
||||||
|
|
||||||
# Sample random pairs (same number as isotopes)
|
|
||||||
if len(isotope_dist) > 0:
|
if len(isotope_dist) > 0:
|
||||||
for _ in range(len(isotope_dist)):
|
for _ in range(len(isotope_dist)):
|
||||||
idx1 = random.randint(0, len(mzs)-1)
|
idx1 = random.randint(0, len(mzs)-1)
|
||||||
@@ -171,9 +178,8 @@ def isotope_validation(X_features, mzs):
|
|||||||
t_stat, p_val = ttest_ind(isotope_dist, random_dist)
|
t_stat, p_val = ttest_ind(isotope_dist, random_dist)
|
||||||
print(f"T-test p-value: {p_val:.4e} (Significant if < 0.05)")
|
print(f"T-test p-value: {p_val:.4e} (Significant if < 0.05)")
|
||||||
|
|
||||||
# Plotting
|
|
||||||
plt.figure(figsize=(8, 6))
|
plt.figure(figsize=(8, 6))
|
||||||
plt.boxplot([isotope_dist, random_dist], labels=['Isotopic Pairs', 'Random Pairs'])
|
plt.boxplot([isotope_dist, random_dist], tick_labels=['Isotopic Pairs', 'Random Pairs'])
|
||||||
plt.title('Latent Space Distances: Isotopes vs Random')
|
plt.title('Latent Space Distances: Isotopes vs Random')
|
||||||
plt.ylabel('Euclidean Distance (Normalized Latent Space)')
|
plt.ylabel('Euclidean Distance (Normalized Latent Space)')
|
||||||
plt.savefig(os.path.join(BASE_DIR, "..", "figures", "isotope_validation_plot.png"))
|
plt.savefig(os.path.join(BASE_DIR, "..", "figures", "isotope_validation_plot.png"))
|
||||||
|
|||||||
@@ -0,0 +1,73 @@
|
|||||||
|
import os
|
||||||
|
import torch
|
||||||
|
import torch.nn as nn
|
||||||
|
from torch.utils.data import DataLoader, Dataset
|
||||||
|
from torchvision import models, transforms
|
||||||
|
from PIL import Image
|
||||||
|
import numpy as np
|
||||||
|
from sklearn.cluster import KMeans
|
||||||
|
import torch.nn.functional as F
|
||||||
|
|
||||||
|
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
|
||||||
|
IMG_DIR = os.path.join(BASE_DIR, "..", "datos_para_ai")
|
||||||
|
ENCODER_PATH = os.path.join(BASE_DIR, "..", "models", "msi_encoder_trained.pth")
|
||||||
|
DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
||||||
|
|
||||||
|
class MSI_Structural_Encoder(nn.Module):
|
||||||
|
def __init__(self):
|
||||||
|
super(MSI_Structural_Encoder, self).__init__()
|
||||||
|
self.features = nn.Sequential(
|
||||||
|
nn.Conv2d(1, 32, kernel_size=5, stride=2, padding=2, bias=False),
|
||||||
|
nn.GroupNorm(4, 32),
|
||||||
|
nn.ReLU(),
|
||||||
|
nn.Conv2d(32, 64, kernel_size=3, stride=2, padding=1, bias=False),
|
||||||
|
nn.GroupNorm(8, 64),
|
||||||
|
nn.ReLU(),
|
||||||
|
nn.Conv2d(64, 128, kernel_size=3, stride=2, padding=1, bias=False),
|
||||||
|
nn.GroupNorm(16, 128),
|
||||||
|
nn.ReLU(),
|
||||||
|
nn.Conv2d(128, 256, kernel_size=3, stride=2, padding=1, bias=False),
|
||||||
|
nn.GroupNorm(32, 256),
|
||||||
|
nn.ReLU(),
|
||||||
|
nn.AdaptiveAvgPool2d((1, 1))
|
||||||
|
)
|
||||||
|
|
||||||
|
def forward(self, x):
|
||||||
|
return self.features(x).squeeze(-1).squeeze(-1)
|
||||||
|
|
||||||
|
def load_encoder_diagnostic(path):
|
||||||
|
model = MSI_Structural_Encoder()
|
||||||
|
if os.path.exists(path):
|
||||||
|
state_dict = torch.load(path, map_location=DEVICE)
|
||||||
|
model.features.load_state_dict(state_dict)
|
||||||
|
model.to(DEVICE)
|
||||||
|
model.eval()
|
||||||
|
return model
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
encoder = load_encoder_diagnostic(ENCODER_PATH)
|
||||||
|
|
||||||
|
# Load targets directly to test raw alignment
|
||||||
|
img_155 = os.path.join(IMG_DIR, "ion_155.75.png")
|
||||||
|
img_156 = os.path.join(IMG_DIR, "ion_156.07.png")
|
||||||
|
|
||||||
|
transform = transforms.Compose([
|
||||||
|
transforms.Resize((256, 256)),
|
||||||
|
transforms.ToTensor()
|
||||||
|
])
|
||||||
|
|
||||||
|
if os.path.exists(img_155) and os.path.exists(img_156):
|
||||||
|
# Convert to Grayscale "L"
|
||||||
|
t_155 = transform(Image.open(img_155).convert("L")).unsqueeze(0).to(DEVICE)
|
||||||
|
t_156 = transform(Image.open(img_156).convert("L")).unsqueeze(0).to(DEVICE)
|
||||||
|
|
||||||
|
with torch.no_grad():
|
||||||
|
f_155 = encoder(t_155)
|
||||||
|
f_156 = encoder(t_156)
|
||||||
|
|
||||||
|
# Check directional similarity
|
||||||
|
sim = F.cosine_similarity(f_155, f_156)
|
||||||
|
print(f"\n--- Feature Diagnostics ---")
|
||||||
|
print(f"Cosine Similarity between Vein Ions (155.75 vs 156.07): {sim.item():.4f}")
|
||||||
|
print("If this value is below 0.85, the loaded weight file is treating them as different shapes.")
|
||||||
|
|
||||||
@@ -5,19 +5,7 @@ from PIL import Image
|
|||||||
|
|
||||||
# 1. CONFIGURATION (Relative paths for portability)
|
# 1. CONFIGURATION (Relative paths for portability)
|
||||||
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
|
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
|
||||||
# Discovery logic for the results CSV
|
# Strictly use the root results file generated by graficar_tsne_msi.py
|
||||||
CSV_OPTIONS = [
|
|
||||||
os.path.join(BASE_DIR, "..", "msi_clusters_results.csv"),
|
|
||||||
os.path.join(BASE_DIR, "..", "msi_clusters_direct_results.csv"),
|
|
||||||
os.path.join(BASE_DIR, "..", "pruebas_clusters", "msi_clusters_direct_results.csv"),
|
|
||||||
os.path.join(BASE_DIR, "..", "msi_tsne_results.csv")
|
|
||||||
]
|
|
||||||
|
|
||||||
CSV_PATH = next((opt for opt in CSV_OPTIONS if os.path.exists(opt)), None)
|
|
||||||
|
|
||||||
if not CSV_PATH:
|
|
||||||
print("Warning: No cluster results CSV found in the project root.")
|
|
||||||
# Default path for error reporting
|
|
||||||
CSV_PATH = os.path.join(BASE_DIR, "..", "msi_clusters_results.csv")
|
CSV_PATH = os.path.join(BASE_DIR, "..", "msi_clusters_results.csv")
|
||||||
|
|
||||||
IMG_DIR = os.path.join(BASE_DIR, "..", "datos_para_ai")
|
IMG_DIR = os.path.join(BASE_DIR, "..", "datos_para_ai")
|
||||||
@@ -38,6 +26,7 @@ if os.path.exists(CSV_PATH):
|
|||||||
else:
|
else:
|
||||||
for cluster_id in sorted(df['cluster'].unique()):
|
for cluster_id in sorted(df['cluster'].unique()):
|
||||||
print(f"Generating gallery for Cluster {cluster_id}...")
|
print(f"Generating gallery for Cluster {cluster_id}...")
|
||||||
|
# Take a 3x3 sample of the cluster
|
||||||
cluster_ions = df[df['cluster'] == cluster_id][img_col].head(9).tolist()
|
cluster_ions = df[df['cluster'] == cluster_id][img_col].head(9).tolist()
|
||||||
|
|
||||||
fig, axes = plt.subplots(3, 3, figsize=(10, 10))
|
fig, axes = plt.subplots(3, 3, figsize=(10, 10))
|
||||||
@@ -48,17 +37,19 @@ if os.path.exists(CSV_PATH):
|
|||||||
img_path = os.path.join(IMG_DIR, cluster_ions[i])
|
img_path = os.path.join(IMG_DIR, cluster_ions[i])
|
||||||
if os.path.exists(img_path):
|
if os.path.exists(img_path):
|
||||||
img = Image.open(img_path)
|
img = Image.open(img_path)
|
||||||
ax.imshow(img, cmap='gray')
|
# Using 'viridis' improves human visibility of low-concentration transport traces in the veins
|
||||||
|
ax.imshow(img, cmap='viridis')
|
||||||
ax.set_title(cluster_ions[i], fontsize=8)
|
ax.set_title(cluster_ions[i], fontsize=8)
|
||||||
else:
|
else:
|
||||||
ax.text(0.5, 0.5, 'Image Not Found', ha='center', va='center', fontsize=6)
|
ax.text(0.5, 0.5, 'Image Not Found', ha='center', va='center', fontsize=6)
|
||||||
ax.axis('off')
|
ax.axis('off')
|
||||||
|
|
||||||
plt.tight_layout()
|
plt.tight_layout()
|
||||||
plt.savefig(f"{OUTPUT_DIR}/cluster_gallery_{cluster_id}.png")
|
# Standardized filename for consistency
|
||||||
|
plt.savefig(f"{OUTPUT_DIR}/Gallery_cluster_{cluster_id}.png")
|
||||||
plt.close()
|
plt.close()
|
||||||
|
|
||||||
print(f"\nGalleries successfully saved in: {OUTPUT_DIR}")
|
print(f"\nGalleries successfully saved in: {OUTPUT_DIR}")
|
||||||
else:
|
else:
|
||||||
print(f"Error: Missing required results file: {CSV_PATH}")
|
print(f"Error: Missing required results file: {CSV_PATH}")
|
||||||
print("Please ensure you have run the clustering scripts first.")
|
print("Please run 'python scripts_python/graficar_tsne_msi.py' first to generate results.")
|
||||||
|
|||||||