-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsinogap_module_fcBypass.py
More file actions
1721 lines (1445 loc) · 63.2 KB
/
Copy pathsinogap_module_fcBypass.py
File metadata and controls
1721 lines (1445 loc) · 63.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from re import sub
from weakref import ref
import IPython
import sys
import os
import random
import time
import gc
import dataclasses
from dataclasses import dataclass, field
from enum import Enum
import glob
import math
import statistics
from cv2 import norm
import numpy as np
import test
import torch
import torch.nn as nn
import torch.nn.functional as fn
import torchvision
from torch import optim, rand, randint
from torchvision import transforms
from torch.utils.tensorboard import SummaryWriter
import matplotlib
import matplotlib.pyplot as plt
from matplotlib.image import imread, imsave
import h5py
from h5py import h5d
import tifffile
import tqdm
import ssim
from eagle_loss import Eagle_Loss
def initIfNew(var, val=None) :
if var in locals() :
return locals()[var]
if var in globals() :
return globals()[var]
return val
@dataclass
class TCfgClass:
exec : int
latentDim: int
batchSize: int
labelSmoothFac: float
learningRateD: float
learningRateG: float
dataDir : str
device: torch.device = torch.device('cpu')
batchSplit : int = 1 # negative to load multiple batches at a time.
nofEpochs: int = 0
num_workers : int = os.cpu_count()
historyHDF : str = field(repr = True, init = False)
logDir : str = field(repr = True, init = False)
def __post_init__(self):
if self.device == torch.device('cpu') :
self.device = torch.device(f"cuda:{self.exec}")
self.historyHDF = f"train_{self.exec}.hdf"
self.logDir = f"runs/experiment_{self.exec}"
if self.batchSplit > 1 and self.batchSize % self.batchSplit :
raise Exception(f"Batch size {self.batchSize} is not divisible by batch split {self.batchSplit}.")
global TCfg
TCfg = initIfNew('TCfg')
@dataclass
class DCfgClass:
gapW : int
brick : bool = field(repr = False)
sinoSh : tuple = field(repr = True, init = False)
gapSh : tuple = field(repr = True, init = False)
gapRngX : type(np.s_[:]) = field(repr = True, init = False)
gapRng : type(np.s_[:]) = field(repr = True, init = False)
readSh : tuple = field(repr = True, init = False)
viewSh : tuple = field(repr = True, init = False)
def __post_init__(self):
self.readSh : tuple = (128 if self.brick else None ,128)
self.sinoSh = ( (8 if self.brick else 256) * self.gapW , 8*self.gapW )
self.viewSh = ( 8 * self.gapW , 8*self.gapW )
self.gapSh = (self.sinoSh[0],self.gapW)
self.gapRngX = np.s_[ self.sinoSh[1]//2 - self.gapW//2 : self.sinoSh[1]//2 + self.gapW//2 ]
self.gapRng = np.s_[...,self.gapRngX]
DCfg = initIfNew('DCfg')
def eprint(*args, **kwargs):
print(*args, file=sys.stderr, **kwargs)
def plotData(dataY, rangeY=None, dataYR=None, rangeYR=None,
dataX=None, rangeX=None, rangeP=None,
figsize=(16,8), saveTo=None, show=True):
if type(dataY) is np.ndarray :
plotData((dataY,), rangeY=rangeY, dataYR=dataYR, rangeYR=rangeYR,
dataX=dataX, rangeX=rangeX, rangeP=rangeP,
figsize=figsize, saveTo=saveTo, show=show)
return
if type(dataYR) is np.ndarray :
plotData(dataY, rangeY=rangeY, dataYR=(dataYR,), rangeYR=rangeYR,
dataX=dataX, rangeX=rangeX, rangeP=rangeP,
figsize=figsize, saveTo=saveTo, show=show)
return
if type(dataY) is not tuple :
eprint(f"Unknown data type to plot: {type(dataY)}.")
return
if type(dataYR) is not tuple and dataYR is not None:
eprint(f"Unknown data type to plot: {type(dataYR)}.")
return
last = min( len(data) for data in dataY )
if dataYR is not None:
last = min( last, min( len(data) for data in dataYR ) )
if dataX is not None:
last = min(last, len(dataX))
if rangeP is None :
rangeP = (0,last)
elif type(rangeP) is int :
rangeP = (0,rangeP) if rangeP > 0 else (-rangeP,last)
elif type(rangeP) is tuple :
rangeP = ( 0 if rangeP[0] is None else rangeP[0],
last if rangeP[1] is None else rangeP[1],)
else :
eprint(f"Bad data type on plotData input rangeP: {type(rangeP)}")
raise Exception(f"Bug in the code.")
rangeP = np.s_[ max(0, rangeP[0]) : min(last, rangeP[1]) ]
if dataX is None :
dataX = np.arange(rangeP.start, rangeP.stop)
#plt.style.use('default')
plt.style.use('dark_background')
fig, ax1 = plt.subplots(figsize=figsize)
ax1.xaxis.grid(True, 'both', linestyle='dotted')
if rangeX is not None :
ax1.set_xlim(rangeX)
else :
ax1.set_xlim(rangeP.start,rangeP.stop-1)
ax1.yaxis.grid(True, 'both', linestyle='dotted')
nofPlots = len(dataY)
if rangeY is not None:
ax1.set_ylim(rangeY)
colors = [ matplotlib.colors.hsv_to_rgb((hv/nofPlots, 1, 1)) for hv in range(nofPlots) ]
for idx , data in enumerate(dataY):
ax1.plot(dataX, data[rangeP], linestyle='-', color=colors[idx])
if dataYR is not None : # right Y axis
ax2 = ax1.twinx()
ax2.yaxis.grid(True, 'both', linestyle='dotted')
nofPlots = len(dataYR)
if rangeYR is not None:
ax2.set_ylim(rangeYR)
colors = [ matplotlib.colors.hsv_to_rgb((hv/nofPlots, 1, 1)) for hv in range(nofPlots) ]
for idx , data in enumerate(dataYR):
ax2.plot(dataX, data[rangeP], linestyle='dashed', color=colors[idx])
if saveTo:
fig.savefig(saveTo)
if not show:
plt.close(fig)
def plotImage(image, frameon=False) :
plt.figure(frameon=frameon)
plt.imshow(image, cmap='gray')
plt.axis("off")
plt.show()
def plotImages(images, frameon=False) :
plt.figure(frameon=frameon)
for i, img in enumerate(images) :
ax = plt.subplot(1, len(images), i + 1)
plt.imshow(img.squeeze(), cmap='gray')
plt.axis("off")
plt.show()
def sliceShape(shape, sl) :
if type(shape) is int :
shape = torch.Size([shape])
if type(sl) is tuple :
if len(shape) != len(sl) :
raise Exception(f"Different sizes of shape {shape} and sl {sl}")
out = []
for i in range(0, len(shape)) :
indeces = sl[i].indices(shape[i])
out.append(indeces[1]-indeces[0])
return out
elif type(sl) is slice :
indeces = sl.indices(shape[0])
return indeces[1]-indeces[0]
else :
raise Exception(f"Incompatible object {sl}")
def tensorStat(stat) :
print(f"{stat.mean().item():.3e}, {stat.std().item():.3e}, "
f"{stat.min().item():.3e}, {stat.max().item():.3e}")
def fillWheights(seq, std=0.001) :
for wh in seq :
if hasattr(wh, 'weight') :
#torch.nn.init.xavier_uniform_(wh.weight)
#torch.nn.init.zeros_(wh.weight)
#torch.nn.init.constant_(wh.weight, 0)
#torch.nn.init.uniform_(wh.weight, a=0.0, b=1.0, generator=None)
torch.nn.init.normal_(wh.weight, mean=0.0, std=std)
if hasattr(wh, 'bias') and wh.bias is not None :
torch.nn.init.normal_(wh.bias, mean=0.0, std=0)
if isinstance(wh, torch.Tensor) :
torch.nn.init.normal_(wh, mean=0.0, std=std)
def unsqeeze4dim(tens):
orgDims = tens.dim()
if tens.dim() == 2 :
tens = tens.unsqueeze(0)
if tens.dim() == 3 :
tens = tens.unsqueeze(1)
return tens, orgDims
def squeezeOrg(tens, orgDims):
if orgDims == tens.dim():
pass
if tens.dim() != 4 or orgDims > 4 or orgDims < 2:
raise Exception(f"Unexpected dimensions to squeeze: {tens.dim()} {orgDims}.")
if orgDims < 4 :
if tens.shape[1] > 1:
raise Exception(f"Cant squeeze dimension 1 in: {tens.shape}.")
tens = tens.squeeze(1)
if orgDims < 3 :
if tens.shape[0] > 1:
raise Exception(f"Cant squeeze dimension 0 in: {tens.shape}.")
tens = tens.squeeze(0)
return tens
def set_seed(SEED_VALUE):
torch.manual_seed(SEED_VALUE)
torch.cuda.manual_seed(SEED_VALUE)
torch.cuda.manual_seed_all(SEED_VALUE)
np.random.seed(SEED_VALUE)
def save_model(model, model_path):
torch.save(model.state_dict(), model_path)
return
def load_model(model, model_path):
model.load_state_dict(torch.load(model_path, map_location=TCfg.device))
return model
def addToHDF(filename, containername, data) :
if len(data.shape) == 2 :
data=np.expand_dims(data, 0)
if len(data.shape) != 3 :
raise Exception(f"Not appropriate input array size {data.shape}.")
with h5py.File(filename,'a') as file :
if containername not in file.keys():
dset = file.create_dataset(containername, data.shape,
maxshape=(None,data.shape[1],data.shape[2]),
dtype='f')
dset[()] = data
return
dset = file[containername]
csh = dset.shape
if csh[1] != data.shape[1] or csh[2] != data.shape[2] :
raise Exception(f"Shape mismatch: input {data.shape}, file {dset.shape}.")
msh = dset.maxshape
newLen = csh[0] + data.shape[0]
if msh[0] is None or msh[0] >= newLen :
dset.resize(newLen, axis=0)
else :
raise Exception(f"Insufficient maximum shape {msh} to add data"
f" {data.shape} to current volume {dset.shape}.")
dset[csh[0]:newLen,...] = data
file.close()
return 0
def loadImage(imageName, expectedShape=None) :
if not imageName:
return None
#imdata = imread(imageName).astype(np.float32)
imdata = tifffile.imread(imageName).astype(np.float32)
if len(imdata.shape) == 3 :
imdata = np.mean(imdata[:,:,0:3], 2)
if not expectedShape is None and imdata.shape != expectedShape :
raise Exception(f"Dimensions of the input image \"{imageName}\" {imdata.shape} "
f"do not match expected shape {expectedShape}.")
return imdata
def residesInMemory(hdfName) :
mmapPrefixes = ["/dev/shm",]
if "CTAS_MMAP_PATH" in os.environ :
mmapPrefixes.extend(os.environ["CTAS_MMAP_PATH"].split(':'))
hdfName = os.path.realpath(hdfName)
for mmapPrefix in mmapPrefixes :
if hdfName.startswith(mmapPrefix) :
return True
return False
def goodForMmap(trgH5F, data) :
fileSize = trgH5F.id.get_filesize()
offset = data.id.get_offset()
plist = data.id.get_create_plist()
if offset < 0 \
or not plist.get_layout() in (h5d.CONTIGUOUS, h5d.COMPACT) \
or plist.get_external_count() \
or plist.get_nfilters() \
or fileSize - offset < math.prod(data.shape) * data.dtype.itemsize :
return None, None
else :
return offset, data.id.dtype
def getInData(inputString, verbose=False, preread=False):
nameSplit = inputString.split(':')
if len(nameSplit) == 1 : # tiff image
data = loadImage(nameSplit[0])
data = np.expand_dims(data, 1)
return data
if len(nameSplit) != 2 :
raise Exception(f"String \"{inputString}\" does not represent an HDF5 format \"fileName:container\".")
hdfName = nameSplit[0]
hdfVolume = nameSplit[1]
try :
trgH5F = h5py.File(hdfName,'r', swmr=True)
except :
raise Exception(f"Failed to open HDF file '{hdfName}'.")
if hdfVolume not in trgH5F.keys():
raise Exception(f"No dataset '{hdfVolume}' in input file {hdfName}.")
data = trgH5F[hdfVolume]
if not data.size :
raise Exception(f"Container \"{inputString}\" is zero size.")
sh = data.shape
if len(sh) != 3 :
raise Exception(f"Dimensions of the container \"{inputString}\" is not 3: {sh}.")
try : # try to mmap hdf5 if it is in memory
if not residesInMemory(hdfName) :
raise Exception()
fileSize = trgH5F.id.get_filesize()
offset = data.id.get_offset()
dtype = data.id.dtype
plist = data.id.get_create_plist()
if offset < 0 \
or not plist.get_layout() in (h5d.CONTIGUOUS, h5d.COMPACT) \
or plist.get_external_count() \
or plist.get_nfilters() \
or fileSize - offset < math.prod(sh) * data.dtype.itemsize :
raise Exception()
# now all is ready
dataN = np.memmap(hdfName, shape=sh, dtype=dtype, mode='r', offset=offset)
data = dataN
trgH5F.close()
#plist = trgH5F.id.get_access_plist()
#fileno = trgH5F.id.get_vfd_handle(plist)
#dataM = mmap.mmap(fileno, fileSize, offset=offset, flags=mmap.MAP_SHARED, prot=mmap.PROT_READ)
except :
if preread :
dataN = np.empty(data.shape, dtype=np.float32)
if verbose :
print("Reading input ... ", end="", flush=True)
data.read_direct(dataN)
if verbose :
print("Done.")
data = dataN
trgH5F.close()
return data
def createWriter(logDir, addToExisting=False) :
if not addToExisting and os.path.exists(logDir) :
raise Exception(f"Log directory \"{logDir}\" for the experiment already exists."
" Remove it or implicitry overwrite with setting addToExisting to True.")
return SummaryWriter(logDir)
writer = initIfNew('writer')
class DevicePlace:
def __call__(self, x):
return x.to(TCfg.device)
class StripesFromHDF :
# Setting exclusize to True makes dataset consisting only out of non-overlapping sinograms
def __init__(self, sampleName, maskName, exclusive=False):
self.volume = getInData(sampleName, False, False)
self.sh = self.volume.shape
self.fsh = self.sh[1:3]
self.mask = loadImage(maskName, self.fsh)
self.mask /= self.mask.max()
if self.mask is None :
self.mask = np.ones(self.fsh, dtype=np.uint8)
#self.mask = self.mask.astype(bool)
forbidenSinos = self.mask.copy()
for shft in range (1, DCfg.readSh[-1]) :
forbidenSinos[:,:-shft] *= self.mask[:,shft:]
forbidenSinos[:, -DCfg.readSh[-1]:] = 0
if exclusive : # non-overlapping sinograms
for yCr in range(0,self.fsh[0]) :
xCr = 0
while xCr < self.fsh[1]-DCfg.readSh[-1] :
if np.all(forbidenSinos[yCr, xCr:xCr+DCfg.readSh[-1]] > 0) :
forbidenSinos[ yCr, xCr+1 : xCr+DCfg.readSh[-1] ] = 0
xCr += DCfg.readSh[-1]
else :
forbidenSinos[ yCr, xCr ] = 0
xCr += 1
self.allAvailableSinos = np.argwhere(forbidenSinos)
self.availableFragments = 1 if DCfg.readSh[0] is None else \
( (self.sh[0] - DCfg.readSh[0] + 1) // ( DCfg.readSh[0] if exclusive else 1 ) )
def __len__(self):
return self.allAvailableSinos.shape[0] * self.availableFragments
def __getitem__(self, index=None):
if index is None :
index = random.randint(0, len(self)-1)
return self.__getitem__(index)
elif isinstance(index, int) :
fdx, zdx = divmod(index, self.availableFragments)
#ydx, xdx = tuple(self.availableSinos[fdx])
ydx, xdx = tuple( int(dx) for dx in self.allAvailableSinos[fdx,:] )
#ydx, xdx = tuple( int(dx) for dx in self.exposedSinos[fdx,:] )
return self.__getitem__((zdx, ydx, xdx))
elif isinstance(index, tuple) and len(index) == 3 :
zdx = 0 if DCfg.readSh[0] is None else index[0]
data = self.volume[ zdx : -1 if DCfg.readSh[0] is None else (zdx+DCfg.readSh[0]),
index[1],
index[2]:index[2]+DCfg.readSh[1]
].copy()
return data, index
raise Exception(f"Bad index for data set: {index}.")
class StripesFromHDFs :
def __init__(self, bases, exclusive=False):
self.collection = []
for base in bases :
print(f"Loading train set {len(self.collection)+1} of {len(bases)}: " + base + " ... ", end="")
self.collection.append(
StripesFromHDF(f"{base}.hdf:/data", f"{base}.mask++.tif", exclusive) )
print("Done")
def __getitem__(self, index=None):
if index is None:
index = random.randint(0,len(self)-1)
return self.__getitem__(index)
elif isinstance(index, int) :
leftover = index
for setdx in range(len(self.collection)) :
setLen = len(self.collection[setdx])
if leftover >= setLen :
leftover -= setLen
else :
data, subIndex = self.collection[setdx].__getitem__(leftover)
return data, (setdx, *subIndex)
elif type(index) is tuple and len(index) == 4 :
return self.collection[index[0]].__getitem__(index[1:])[0], index
raise Exception(f"Bad index for collection of data sets: {index}.")
def __len__(self):
return sum( [ len(set) for set in self.collection ] )
def get_dataset(self, transform=None, expose=1, shuffle=False) :
class Sinos(torch.utils.data.Dataset) :
def __init__(self, root, transform=None, expose=1, shuffle=False):
self.container = root
if not ( 0 < expose <= 1 ) :
raise f"Provided exposure {expose} is outside (0,1] range."
self.expose = expose
self.shuffle = shuffle
self.transform = transform
self.oblTransform = transforms.Compose( [transforms.ToTensor(),
#DevicePlace(),
transforms.Resize(DCfg.sinoSh)] )
def __len__(self):
return int(self.container.__len__() * self.expose)
def __getitem__(self, index=None, doTransform=True):
if self.shuffle and isinstance(index, int) : # randomize dataset
index = random.randint(0,self.container.__len__()-1)
data, rIndex = self.container.__getitem__(index)
data = self.oblTransform(data)
if doTransform and self.transform :
data = self.transform(data)
return data, rIndex
def originalSinoLen(self,setdx) :
return self.container.collection[setdx].sh[0]
return Sinos(self, transform, expose, shuffle)
listOfTrainData = [
"18692a.ExpChicken6mGyShift",
"23574.8965435L.Eiger.32kev_sft",
"19022g.11-EggLard",
"18692b.MinceO",
"23574.8965435L.Eiger.32kev_org",
"19736b.09_Feb.4176862R_Eig_Threshold-4keV",
"20982b.04_774784R",
"18515.Lamb1_Eiger_7m_45keV_360Scan",
"19736c.8733147R_Eig_Threshold-8keV.SAMPLE_Y1",
"18692b_input_PhantomM",
"21836b.2024-08-15-mastectomies.4201381L.35kev.20Hz",
"23574h.9230799R.35kev",
"18515.Lamb4_Excised_Eiger_7m_30keV_360Scan.Y1",
"18648.B_Edist.80keV_0m_Eig_Neoprene.Y2",
"19932.10_8093920_35keV",
"19932.14_2442231_23keV",
"19932.16_4193759_60keV",
]
listOfTestData = [
"19603a.Exposures.70keV_7m_Calf2_Threshold35keV_25ms_Take2",
"22280a_input_Day_4_40keV_7m_Threshold20keV_50ms_Y04_no_shell__0.05deg",
"18515.Lamb4_Eiger_5m_50keV_360Scan.SAMPLE_Y1",
"18692b_input_Phantom0",
#"19603a.ROI-CTs.50keV_7m_Eiger_Sheep1",
]
def createDataSet(path, listOfData, exclusive=False, expose=1) :
#listOfData = [file.removesuffix(".hdf") for file in glob.glob(path+ "/*.hdf", recursive=False)]
listOfData = [ '/'.join((path,file)) for file in listOfData ]
print(listOfData)
sinoRoot = StripesFromHDFs(listOfData, exclusive)
transList = []
#transList.append(transforms.Resize(DCfg.sinoSh))
if not exclusive :
transList.append(transforms.RandomHorizontalFlip()),
transList.append(transforms.RandomVerticalFlip()),
#transList.append(transforms.Normalize(mean=(0.5), std=(1)))
mytransforms = transforms.Compose(transList)
return sinoRoot.get_dataset( transform=mytransforms, expose=expose, shuffle = not exclusive )
trainSet = initIfNew('trainSet')
testSet = initIfNew('testSet')
def createDataLoader(tSet, num_workers=os.cpu_count()) :
return torch.utils.data.DataLoader(
dataset=tSet,
batch_size = TCfg.batchSize * max(1, -TCfg.batchSplit) ,
shuffle=False, # randomize dataset instead of the dataloader because it takes enormous amount of time otherwise
num_workers=num_workers,
drop_last=True
)
examples = [
#(11142, 3150), # (0, 417, 1877)
(38576, 2560), # (3, 476, 2855)
(26289, 6300), # (2, 280, 828)
(24299, 7160), # (2, 113, 988)
(3186, 2455), # (0, 119, 240)
]
def createReferences(tSet, majorIdx = 0) :
if majorIdx :
examples.insert(0, examples.pop(majorIdx))
mytransforms = transforms.Compose([
transforms.Resize(DCfg.sinoSh),
#transforms.Normalize(mean=(0.5), std=(1))
])
refImages = torch.empty((len(examples), 1, *DCfg.sinoSh), dtype=torch.float32).to(TCfg.device)
refBoxes = []
for idx, ex in enumerate(examples) :
if DCfg.readSh[0] is None :
index = (ex[0][0], 0, ex[0][1], ex[0][2])
refBoxes.append( int(ex[1] * refImages.shape[-2]) )
else :
index = (ex[0][0], int(ex[1]*tSet.originalSinoLen(ex[0][0])) , ex[0][1], ex[0][2])
refBoxes.append(0)
data = tSet.__getitem__(index, doTransform=False)[0]
refImages[idx,0,...] = mytransforms(data)
refNoises = torch.randn((refImages.shape[0],TCfg.latentDim)).to(TCfg.device)
return refImages, refNoises, refBoxes
refImages = initIfNew('refImages')
refNoises = initIfNew('refNoises')
refBoxes = initIfNew('refBoxes')
def showMe(tSet, index=None) :
global refImages, refNoises
index = random.randint(0,len(tSet)-1) if index is None else index
image, rindex = tSet[index]
image = image.squeeze().transpose(0,1)
print(index, rindex)
tensorStat(image)
plotImage(image.cpu())
return rindex
def normalizeImages(images) :
images, orgDims = unsqeeze4dim(images)
images = images.clone().detach()
stds, means = torch.std_mean(images, dim=(-1,-2), keepdim=True)
stds += 1e-7
images = (images - means) / stds # normalize per image
return images, (orgDims, stds, means)
def reNormalizeImages(images, norms) :
images = images * norms[1][:,[0],...] + norms[2][:,[0],...] # renormalise
images = squeezeOrg(images, norms[0])
return images
class SubGeneratorTemplate(nn.Module):
def __init__(self, gapW, brick, batchNorm=True, inChannels=1):
super(SubGeneratorTemplate, self).__init__()
self.cfg = DCfgClass(gapW, brick)
self.lowResGenerator = None
self.baseChannels = None
self.inChannels = inChannels
self.amplitude = 4
self.batchNorm = batchNorm
def encblock(self, chIn, chOut, kernel=3, stride=1, norm=None, padding=1) :
if norm is None :
norm = self.batchNorm
chIn = int(chIn*self.baseChannels)
chOut = int(chOut*self.baseChannels)
layers = []
layers.append( nn.Conv2d(chIn, chOut, kernel, stride=stride, bias = not norm,
padding=padding, padding_mode='reflect') )
if norm :
layers.append(nn.BatchNorm2d(chOut))
layers.append(nn.LeakyReLU(0.2))
fillWheights(layers)
return torch.nn.Sequential(*layers)
def encStep(self, chIn, chOut, stride=2, padding=1, header=False) :
return (
self.encblock( self.inChannels/self.baseChannels, chIn, padding=1, norm=False ) \
if header else \
self.encblock( chIn, chIn, padding=padding),
self.encblock( chIn, chOut, padding=padding, stride=stride)
)
def decblock(self, chIn, chOut, kernel=3, stride=1, norm=None, padding=1, outputPadding=None) :
if norm is None :
norm = self.batchNorm
if outputPadding is None :
if isinstance(stride, int) :
outputPadding = stride - 1
else :
outputPadding = tuple( strd - 1 for strd in stride )
chIn = int(chIn*self.baseChannels)
chOut = int(chOut*self.baseChannels)
layers = []
layers.append( nn.ConvTranspose2d(chIn, chOut, kernel, stride=stride, bias = not norm,
padding=padding, padding_mode='zeros', output_padding=outputPadding) )
if norm :
layers.append(nn.BatchNorm2d(chOut))
layers.append(nn.LeakyReLU(0.2))
fillWheights(layers)
return torch.nn.Sequential(*layers)
def decStep(self, chIn, chOut, stride=2, padding=1, footer=False) :
return (
self.decblock( 2*chIn, chOut, padding=padding, stride=stride),
self.decblock( 2*chOut, chOut, padding=1, norm=False) \
if footer else \
self.decblock( 2*chOut, chOut, padding=padding)
)
def createFClinkS(self, mixChan=0) :
smpl = torch.zeros((1, self.inChannels, *self.cfg.sinoSh))
for encoder in self.encoders :
smpl = encoder(smpl)
encSh = smpl.shape
linChannels = math.prod(encSh)
self.fcIn = nn.Sequential(
nn.Flatten(),
nn.Linear(linChannels, linChannels),
nn.LeakyReLU(0.2),
)
fillWheights(self.fcIn)
if mixChan :
self.fcMix = nn.Sequential(
nn.Linear(linChannels+mixChan, linChannels),
nn.LeakyReLU(0.2),
)
fillWheights(self.fcMix)
else :
self.fcMix = None
self.fcOut = nn.Sequential(
nn.Linear(linChannels, linChannels),
nn.LeakyReLU(0.2),
nn.Unflatten(1, encSh[1:]),
)
fillWheights(self.fcOut)
return self.fcIn, self.fcMix, self.fcOut
def createLastTouch(self, chIn=1) :
toRet = nn.Sequential(
nn.Conv2d(chIn*self.baseChannels+self.inChannels, 1, 1),
nn.Tanh(),
)
fillWheights(toRet)
return toRet
def generateImages(self, images, noises=None) :
res = images.clone()
res[self.cfg.gapRng] = self.forward(images)[0][self.cfg.gapRng]
return res
def preFill(self, images) :
images, orgDims = unsqeeze4dim(images)
preMid = None
if self.cfg.gapW == 2:
res = images.clone().detach()
res[...,self.cfg.gapRngX.start] = ( 2*images[:,[0],:,self.cfg.gapRngX.start-1] + \
images[:,[0],:,self.cfg.gapRngX.stop] ) / 3
res[...,self.cfg.gapRngX.start+1] = ( images[:,[0],:,self.cfg.gapRngX.start-1] + \
2*images[:,[0],:,self.cfg.gapRngX.stop] ) / 3
elif self.lowResGenerator is None :
res = images
else :
preImages = torch.nn.functional.interpolate(images, scale_factor=0.5, mode='area')
#with torch.set_grad_enabled(not self.lowResGenerator is None) :
res, preMid = self.lowResGenerator.forward(preImages)
res = torch.nn.functional.interpolate(res, scale_factor=2, mode='nearest')
return squeezeOrg(res, orgDims), preMid
def dropIN(self,images,mix=None) :
dwTrain = [images,]
for encoder in self.encoders :
dwTrain.append(encoder(dwTrain[-1]))
#print(f"{dwTrain[-2].shape} -> {dwTrain[-1].shape}")
link = dwTrain[-1]
link = self.fcIn(link)
if self.fcMix is not None :
link = torch.cat((link, mix), dim=1)
link = self.fcMix(link)
mid = link
link = self.fcOut(link)
upTrain = [link]
for level, decoder in enumerate(self.decoders) :
upTrain.append( decoder( torch.cat( (upTrain[-1], dwTrain[-1-level]), dim=1 ) ) )
#print(f"{upTrain[-2].shape} -> {upTrain[-1].shape} ({dwTrain[-2-level].shape})")
res = self.lastTouch( torch.cat( (upTrain[-1], images ), dim=1 ) )
return res * self.amplitude + images[:,[0],...], mid
def forward(self, images, mix=None):
if self.inChannels > 1 and images.shape[1] == 1 : # fill missing channels with noise
images = images.repeat((1,self.inChannels,1,1))
torch.nn.init.normal_( images[:,1:,:,:] , mean=0.0, std=0.1 )
images = images.clone().detach()
preImages = self.preFill(images)[0]
images[:,[0],*self.cfg.gapRng] = preImages[:,[0],*self.cfg.gapRng]
images, norms = normalizeImages(images)
results, mid = self.dropIN(images, mix)
return reNormalizeImages(results, norms), mid
class GeneratorTemplate(SubGeneratorTemplate):
def __init__(self, gapW, batchNorm=True, inChannels=2):
super(GeneratorTemplate, self).__init__(gapW, False, batchNorm, inChannels=inChannels)
self.brickGenerator = None
self.stripeGenerator = None
def createBricksMask(self):
brickLen = self.brickGenerator.cfg.sinoSh[-2]
halfLine = [i + 0.5 for i in range(brickLen//2)]
halfLine = torch.tensor(halfLine, dtype=torch.float32, device=TCfg.device)
halfLine /= brickLen//2
line = torch.cat( (halfLine, halfLine.flip(0)), dim=0)
self.brickMask = line.view(-1,1).repeat(1,self.brickGenerator.cfg.sinoSh[-1])
self.brickMask = self.brickMask.unsqueeze(0).unsqueeze(0) # add batch and channel dims
def stripe2bricks(self,stripes) :
nofIm = stripes.shape[0]
imsz = math.prod(self.brickGenerator.cfg.sinoSh)
bricks = stripes.view(nofIm,-1)
bricks = bricks.unfold(1,imsz,imsz//2).unfold(2,*self.brickGenerator.cfg.sinoSh)
bricks = bricks.reshape(-1,1,*self.brickGenerator.cfg.sinoSh)
return bricks
def bricks2stripe(self, bricks) :
nofChans = self.cfg.sinoSh[-2] // self.brickGenerator.cfg.sinoSh[-2]
nofChans = nofChans * 2 - 1 # interleaved stripes
bricks = bricks.view(-1,nofChans,*self.brickGenerator.cfg.sinoSh)
nofIm = bricks.shape[0]
stripes = bricks[:,0::2,:,:].reshape(nofIm,1,-1,self.brickGenerator.cfg.sinoSh[-1])
edge = self.brickGenerator.cfg.sinoSh[-2]//2
stripes[:,:,edge:-edge,:] = stripes[:,:,edge:-edge,:] \
+ bricks[:,1::2,:,:].reshape(nofIm,1,-1,self.brickGenerator.cfg.sinoSh[-1])
stripes[:,:,:edge,:] = stripes[:,:,:edge,:] / self.brickMask[:,:,:edge,:]
stripes[:,:,-edge:,:] = stripes[:,:,-edge:,:] / self.brickMask[:,:,-edge:,:]
return stripes
def forward(self, images):
# prepare input
images = images.clone().detach()
preImages, preMid = self.preFill(images)
images[:,[0],*self.cfg.gapRng] = preImages[:,[0],*self.cfg.gapRng]
images, norms = normalizeImages(images)
# refolded images into bricks
bricksOrg = self.stripe2bricks(images)
bricksOut = self.brickMask * self.brickGenerator.forward(bricksOrg)[0]
stripesOut = self.bricks2stripe(bricksOut)
#return sg.reNormalizeImages(stripesOut, norms), None
# prepareStripe
stripeImages, mid = self.stripeGenerator.forward( torch.cat([stripesOut, images], dim=1), preMid )
# combine channels
results = stripeImages
return reNormalizeImages(results, norms), mid
def to(self, whatever):
self.brickMask = self.brickMask.to(whatever)
if self.lowResGenerator is not None :
self.lowResGenerator = self.lowResGenerator.to(whatever)
return super(GeneratorTemplate, self).to(whatever)
### this version of forward is only to calculate what bricks generator does with no main generator.
def __forward(self, images):
# channel 0
with torch.no_grad():
images = images.clone().detach()
images[:,[0],*self.cfg.gapRng] = self.preFill(images)
images, norms = normalizeImages(images)
bricksM = self.brickGenerator.forward(images.view(-1,1, *self.brickGenerator.cfg.sinoSh))
bricksM = bricksM.view(-1,1, *self.cfg.sinoSh)
edge = self.brickGenerator.cfg.sinoSh[-2]//2
bricksP = images.clone()
bricksP[:,:,edge:-edge,:] = self.brickGenerator.forward(images[:,:,edge:-edge,:].reshape(-1,1, *self.brickGenerator.cfg.sinoSh)) \
.view(-1,1, self.cfg.sinoSh[-2]-2*edge, self.cfg.sinoSh[-1] )
results = ( bricksM + bricksM ) / 2
return reNormalizeImages(results, norms)
### this version of forward is to train only stripe generator with no main generator.
### to be used with specific transformGTforStripe - see it below
def __forward(self, images):
with torch.no_grad():
images = images.clone().detach()
images[:,[0],*self.cfg.gapRng] = self.preFill(images)
images, norms = normalizeImages(images)
stripeImages = self.stripeGenerator.forward(images)
return reNormalizeImages(stripeImages, norms)
def transformGT_forStripeTraining(images):
with torch.no_grad():
images, orgdims = unsqeeze4dim(images)
images = torch.nn.functional.interpolate(images, scale_factor=(1/DCfg.gapW,1), mode='bilinear')
images = torch.nn.functional.interpolate(images, scale_factor=( DCfg.gapW,1), mode='bilinear')
return squeezeOrg(images, orgdims)
generator = initIfNew('generator')
lowResGenerators = initIfNew('lowResGenerators', {})
class DiscriminatorTemplate(nn.Module):
def __init__(self, omitEdges=0):
super(DiscriminatorTemplate, self).__init__()
self.baseChannels = 64
self.omitEdges = omitEdges
def encblock(self, chIn, chOut, kernel, stride=1, norm=False, dopadding=False) :
chIn = int(chIn*self.baseChannels)
chOut = int(chOut*self.baseChannels)
layers = []
layers.append( nn.Conv2d(chIn, chOut, kernel, stride=stride, bias=True,
padding='same', padding_mode='reflect') \
if stride == 1 and dopadding else \
nn.Conv2d(chIn, chOut, kernel, stride=stride, bias=True)
)
if norm :
layers.append(nn.BatchNorm2d(chOut))
layers.append(nn.LeakyReLU(0.2))
fillWheights(layers)
return torch.nn.Sequential(*layers)
def createHead(self) :
encSh = self.body(torch.zeros((1,1,*DCfg.sinoSh))).shape
linChannels = math.prod(encSh)
toRet = nn.Sequential(
nn.Flatten(),
#nn.Dropout(0.4),
nn.Linear(linChannels, self.baseChannels*4),
#nn.Linear(linChannels, 1),
nn.LeakyReLU(0.2),
#nn.Dropout(0.4),
nn.Linear(self.baseChannels*4, 1),
nn.Sigmoid(),
)
fillWheights(toRet)
return toRet
def forward(self, images):
if images.dim() == 3:
images = images.unsqueeze(1)
if self.omitEdges :
images = images.clone() # I want to exclude two blocks on the edges :
images[ ..., :self.omitEdges, DCfg.gapRngX ] = 0
images[ ..., -self.omitEdges:, DCfg.gapRngX ] = 0
convRes = self.body(images)
res = self.head(convRes)
return res
discriminator = initIfNew('discriminator')
def createOptimizer(model, lr) :
return optim.AdamW(
filter(lambda p: p.requires_grad, model.parameters()),
lr=lr,
betas=(0.5, 0.999)
)
optimizer_G = initIfNew('optimizer_G')
optimizer_D = initIfNew('optimizer_D')
scheduler_G = initIfNew('scheduler_G')
scheduler_D = initIfNew('scheduler_D')
optimizers_G = []
def adjustScheduler(scheduler, iniLr, target) :
if scheduler is None :
return ""
gamma = scheduler.gamma
curLR = scheduler.get_last_lr()[0] / iniLr
if gamma < 1 and curLR > target \
or gamma > 1 and curLR < target :
scheduler.step()
return f"LR : {scheduler.get_last_lr()[0]:.3e} ({curLR:.3e}). "
def restoreCheckpoint(path=None, logDir=None) :
if logDir is None :
logDir = TCfg.logDir
if path is None :
if os.path.exists(logDir) :
raise Exception(f"Starting new experiment with existing log directory \"{logDir}\"."
" Remove it .")
try : os.remove(TCfg.historyHDF)
except : pass
return 0, 0, 0, None, 0, TrainResClass()
else :
return loadCheckPoint(path, generator, discriminator, optimizer_G, optimizer_D)
def saveModels(path="") :
save_model(generator, model_path = ( path if path else f"model_{TCfg.exec}" ) + "_gen.pt" )
if discriminator is not None :
save_model(discriminator, model_path = ( path if path else f"model_{TCfg.exec}" ) + "_dis.pt" )
BCE = nn.BCELoss(reduction='none')
def loss_Adv(images, truth):