-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathCryoGAN.py
358 lines (242 loc) · 14.5 KB
/
CryoGAN.py
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
import os
import time
import copy
import numpy as np
import torch as th
import astra
import torch
from torch import Tensor
import sys
from shutil import copyfile
from Networks import *
from Functions.FunctionsCTF import *
from Functions.FunctionsFourier import *
from Functions.Functions import *
import mrcfile
import scipy.io
import libs.plot
# temp timing
from datetime import datetime
from timeit import default_timer as timer
from datetime import timedelta
import dataSet as dataSet
from IPython.core.debugger import set_trace
import IPython.core.debugger
from config import Config as cfg
plt.switch_backend('agg')
class CryoGAN:
def __init__(self, args=None, filename=None):
args.BATCH_SIZE=args.batch_size
self.args=args
self.plot = libs.plot.Plotter()
# Create the Generator and the Discriminator
self.gen = cryoGenerator( args=self.args).to(self.args.device)
if self.args.AlgoType != "generate":
self.dis=DownsamplingCNN(args).to(self.args.device )
self.dis.apply(lambda m: weights_init(m, self.args))
if self.args.UseOtherDis:
try:
listdir = os.listdir('./Results/'+self.args.dataset)
listdir= ['./Results/'+self.args.dataset+'/'+dirname for dirname in listdir if self.args.name[:-5] in dirname and self.args.data_type not in dirname]
if len(listdir)>0:
listdir.sort(key=lambda x: os.path.getctime(x))
dispath=listdir[-1]+'/Discriminator.pth'
print("Loading discriminator from "+dispath)
self.dis.load_state_dict(torch.load(dispath))
except:
print("Couldnt find a previous saved dis for the other half experiment.")
print('gen: ', self.gen)
print('dis: ', self.dis)
self.gen.G.scalar=torch.nn.Parameter(self.gen.G.scalar)
def train(self, dataset, feedback_factor=100, checkpoint_factor=1):
print("Starting the training process ... ")
data = Data_loader(dataset, self.args.batch_size)
dataIter=iter(data)
total_batches = len(dataIter)
epoch_gen_iterations=total_batches//(self.args.dis_iterations+1)
total_gen_iterations=epoch_gen_iterations*self.args.epochs
self.epoch_gen_iterations=epoch_gen_iterations
self.total_gen_iterations=total_gen_iterations
self.gen.train()
self.dis.train()
self.initOptimizer()
self.initScheduler(epoch_gen_iterations)
OUTPUT_PATH=self.output_path()
torch.save(self.dis.state_dict(), OUTPUT_PATH+'/Discriminator.pth')
step=-1
global_time = time.time()
print("starting Training")
for epoch in range(1, self.args.epochs+ 1):
self.epoch=epoch
start =timer() # record time at the start of epoch
if step>-1:
#dataset = dataSet.Cryo(args=self.args)
data = Data_loader(dataset, self.args.batch_size)
dataIter=iter(data)
if self.args.GaussianFilterProjection:
print("Gaussian Blurring everything with sigma " +str(self.args.GaussianSigma ))
self.args.GaussianSigmaEpochInitial=self.args.GaussianSigma
self.args.GaussianSigmaEpochFinal=self.args.GaussianSigma*self.args.GaussianSigmaGamma
for i in range(epoch_gen_iterations):
if self.args.GaussianFilterProjection:
perc=(float(i)/(epoch_gen_iterations-1) )
self.args.GaussianSigma=(perc *self.args.GaussianSigmaEpochFinal+ (1.0-perc)*self.args.GaussianSigmaEpochInitial)
step=step+1
self.step=step
self.ratio=float(step)/(total_gen_iterations)
self.gen.VolumeMaskRadius=self.args.VolumeMaskSize
dis_loss=0
wass_loss=0
for Diter in range(self.args.dis_iterations):
images=dataIter.next()
dis_lossIter, wass_lossIter, real_samples = self.optimize_discriminator(images)
dis_loss=dis_loss + dis_lossIter/float(self.args.dis_iterations)
wass_loss=wass_loss + wass_lossIter/float(self.args.dis_iterations)
gen_loss, fake_samples, projNoisy, projCTF, projClean, Noise = self.optimize_generator(ChangeAngles=True)
with torch.no_grad():
self.gen.Constraint(ratio=self.ratio)
self.plot.tick()
self.plot.plot('DLoss', dis_loss)
self.plot.plot('GLoss', gen_loss)
self.plot.plot('WLoss', wass_loss)
PercentageEpochDone=100.0*float(i)/epoch_gen_iterations
PercentageRecDone=100.0*float(step)/total_gen_iterations
if (i%feedback_factor) == 0:
elapsed = time.time() - global_time
elapsed = str(timedelta(seconds=elapsed)).split(".")[0]
print("Elapsed: [%s] Epoch: %d PercEpoch: %f PercRecDone: %f wass_loss : %f"
% (elapsed, epoch, PercentageEpochDone, PercentageRecDone, wass_loss ))
print("Scalar1: [%f] Scalar2: [%f] "%( torch.exp(self.gen.G.scalar[0]).item(), torch.exp(self.gen.G.scalar[1]).item() ))
with torch.no_grad():
iteration=str(epoch).zfill(3) + "_" +str(i).zfill(4)
save_fig_double(real_samples.cpu().data,fake_samples.cpu().data,
OUTPUT_PATH, "Proj", iteration=iteration,
Title1='Real', Title2='Fake_' + str(iteration),
doCurrent=True, sameColorbar=False)
save_fig_double(projClean.cpu().data,projCTF.cpu().data,
OUTPUT_PATH, "ProjClean", iteration=iteration,
Title1='ProjClean', Title2='ProjCTF' + str(iteration),
doCurrent=True, sameColorbar=False)
save_fig_double(self.projClean_grad.cpu().data,self.projCTF_grad.cpu().data,
OUTPUT_PATH, "ProjGrad", iteration=iteration,
Title1='ProjCleanGrad', Title2='ProjCTFGrad' + str(iteration),
doCurrent=True, sameColorbar=False)
self.SaveVolume(OUTPUT_PATH)
#===================
self.plot.save_plots(OUTPUT_PATH)
torch.save(self.gen.G.scalar,OUTPUT_PATH+"/scalar")
##################Epoch Finish####
self.schedulerD.step()
self.schedulerG.step()
self.schedulerScalar.step()
self.SaveVolume(OUTPUT_PATH, 'reconstruction_Epoch_'+str(int(epoch)))
torch.save(self.gen.G.scalar,OUTPUT_PATH+'/scalar_reconstruction_Epoch_'+str(int(epoch)))
if (10*(epoch))%self.args.epochs==0:
self.SaveVolume(OUTPUT_PATH, 'reconstruction_'+str(int(PercentageRecDone+1)))
torch.save(self.gen.G.scalar,OUTPUT_PATH+'/scalar_reconstruction_'+str(int(PercentageRecDone+1)))
stop = timer()
print("Time taken for epoch: %.3f secs" % (stop - start))
########Train Finish
print("Training completed ...")
def optimize_discriminator(self, real_samples):
"""
performs one step of weight update on discriminator using the batch of data
:param real_batch: real samples batch
:return: current loss (Wasserstein loss)
"""
# generate a batch of samples
with torch.no_grad():
fake_samples,_,_,_,_ = self.gen(real_samples , GaussianSigma=self.args.GaussianSigma, ratio=self.ratio)
fake_samples=fake_samples.detach()
loss, wass_loss = dis_loss(self.dis, real_samples, fake_samples, self.args.lambdaPenalty)
if self.args.dis_clip_grad ==True:
current_clip_val=1e3+(self.args.dis_clip_norm_value-1e3)*0.5*self.step/float(self.epoch_gen_iterations)
clip_norm_value=np.min([current_clip_val, self.args.dis_clip_norm_value])
torch.nn.utils.clip_grad_norm_(self.dis.parameters(), clip_norm_value)
loss.backward()
self.dis_optim.step()
self.dis_optim.zero_grad()
return loss.item(), wass_loss, real_samples
def optimize_generator(self, real_samples, multipleNoise):
"""
performs one step of weight update on generator for the given batch_size
:param real_batch: batch of real samples
:return: current loss (Wasserstein estimate)
"""
# generate fake samples:
fake_samples, projNoisy, projCTF, projClean,Noise = self.gen(real_samples, GaussianSigma=self.args.GaussianSigma, ratio=self.ratio, multipleNoise=multipleNoise)
projClean.retain_grad()
projCTF.retain_grad()
fake_samples=fake_samples.to(self.args.device)
loss= gen_loss(self.dis, fake_samples)
# optimize the generator
loss.backward()
self.projClean_grad=projClean.grad
self.projCTF_grad=projCTF.grad
if self.args.gen_clip_grad ==True:
current_clip_val=1+(self.args.gen_clip_norm_value-1)*0.5*self.step/float(self.epoch_gen_iterations)
clip_norm_value=np.min([current_clip_val, self.args.gen_clip_norm_value])
torch.nn.utils.clip_grad_value_(self.gen.X, clip_norm_value)
self.gen_optim.step()
self.gen_optim.zero_grad()
if self.args.scalar_clip_grad:
torch.nn.utils.clip_grad_value_(self.gen.G.scalar, self.args.scalar_clip_norm_value)
self.scalar_optim.step()
self.scalar_optim.zero_grad()
return loss.item(), fake_samples, projNoisy, projCTF, projClean, Noise
def initOptimizer(self):
# define the optimizers for the discriminator and generator
self.gen_optim = torch.optim.Adam([{'params' : self.gen.X}],
lr=self.args.gen_lr/n,
betas=(self.args.gen_beta_1, self.args.gen_beta_2),
eps=self.args.gen_eps,
weight_decay=self.args.gen_weight_decay)
self.dis_optim = torch.optim.Adam(self.dis.parameters(),
lr=self.args.dis_lr,
betas=(self.args.dis_beta_1, self.args.dis_beta_2),
eps=self.args.dis_eps,
weight_decay=self.args.dis_weight_decay)
dictionary=[ {"params" :self.gen.G.scalar}]
self.scalar_optim=torch.optim.Adam(dictionary ,
lr=self.args.scalar_lr,
betas=(self.args.scalar_beta_1, self.args.scalar_beta_2),
eps=self.args.scalar_eps,
weight_decay=self.args.scalar_weight_decay)
def initScheduler(self, epoch_GIterations):
print("Lr decreases every "+ str(step_size)+ " epochs")
self.schedulerD = optim.lr_scheduler.StepLR(self.dis_optim,
step_size=1,
gamma=self.args.gamma)
self.schedulerG = optim.lr_scheduler.StepLR(self.gen_optim,
step_size=1,
gamma=self.args.gamma)
self.schedulerScalar=optim.lr_scheduler.StepLR(self.scalar_optim,
step_size=1,
gamma=self.args.gamma)
def SaveVolume(self, sample_dir, name=None):
with torch.no_grad():
for i, volumeSingle in enumerate(self.gen.Volume):
if name is not None:
nameSingle=name+"_"+str(i+1)+'.mrc'
else:
nameSingle='volume_'+str(i+1)+'.mrc'
with mrcfile.new(os.path.join(sample_dir, nameSingle), overwrite=True) as m:
m.set_data(volumeSingle.data.cpu().numpy())
def output_path(self):
OUTPUT_PATH= './'+'Results/'
if os.path.exists(OUTPUT_PATH)==False: os.mkdir(OUTPUT_PATH)
OUTPUT_PATH = OUTPUT_PATH+self.args.dataset+'/'
if os.path.exists(OUTPUT_PATH)==False: os.mkdir(OUTPUT_PATH)
date = datetime.now().strftime("%Y-%m-%dT%H-%M")
if self.args.name is not None:
name = self.args.name + '-'
else:
name =''
OUTPUT_PATH= os.path.join(OUTPUT_PATH, name + date)
if os.path.exists(OUTPUT_PATH)==False: os.mkdir(OUTPUT_PATH)
# save the arguments to a file
with open(OUTPUT_PATH + '/config.cfg', 'w') as fp:
self.args.config.write(fp)
with open(OUTPUT_PATH + '/config.txt', 'w') as fp:
self.args.config.write(fp)
return OUTPUT_PATH