-
Notifications
You must be signed in to change notification settings - Fork 0
/
start_simulation
executable file
·439 lines (365 loc) · 18.1 KB
/
start_simulation
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
#!/usr/bin/env python2
"""
Copyright (C) 2017
Jakub Krajniak (jkrajniak at gmail.com)
This file is part of AdResSLab.
AdResSLab is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
AdResSLab is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
import espressopp # NOQA
import logging
import numpy
from mpi4py import MPI
import random
import os
import time
from scipy.signal import savgol_filter
from adresslab import files_io, tools_adress
from adresslab import tools_sim as tools
from adresslab import gromacs_topology
from adresslab.app_args import _args_adress as _args
# GROMACS units, kJ/mol K
kb = 0.0083144621
# Storage options
# Mostly you do not need to modify lines below.
def main(): # NOQA
time0 = time.time()
args = _args().parse_args()
max_cutoff = args.cutoff
print('Welcome in AdResSLab!')
if args.debug:
for s in args.debug.split(','):
log_name, log_level = s.split(':')
logging.getLogger(log_name).setLevel(log_level)
generate_exclusions = args.exclusion_list is None or not os.path.exists(args.exclusion_list)
input_conf = gromacs_topology.read(args.top, doRegularExcl=generate_exclusions)
input_gro_conf = files_io.GROFile(args.conf)
input_gro_conf.read()
if not generate_exclusions:
exclusion_file = open(args.exclusion_list, 'r')
exclusions = [map(int, x.split()) for x in exclusion_file.readlines()]
print('Read exclusion list from {} (total: {})'.format(args.exclusion_list, len(exclusions)))
input_conf = input_conf._replace(exclusions=exclusions)
else:
exclusion_list_file = 'exclusion_{}.list'.format(args.top.split('.')[0])
with open(exclusion_list_file, 'w') as fel:
for p in input_conf.exclusions:
fel.write('{} {}\n'.format(*p))
print('Save exclusion list: {} ({})'.format(exclusion_list_file, len(input_conf.exclusions)))
box = input_gro_conf.box
print('Setting up simulation...')
# Tune simulation parameter according to arguments
integrator_step = args.int_step
k_steps = int(args.run / integrator_step)
if args.skin:
skin = args.skin
else:
skin = 0.16
rng_seed = args.rng_seed
if args.rng_seed == -1:
rng_seed = random.randint(1, 10000)
args.rng_seed = rng_seed
# Initialize RNG
random.seed(rng_seed)
# Save the params to the the file.
_args().save_to_file('{}_{}_params.out'.format(args.output_prefix, rng_seed), args)
print('Skin: {}'.format(skin))
print('RNG Seed: {}'.format(rng_seed))
print('Time step: {}'.format(args.dt))
print('Cutoff: {}'.format(max_cutoff))
print('Boltzmann constant = {}'.format(kb))
# Setup system
system = espressopp.System()
system.rng = espressopp.esutil.RNG(rng_seed)
# Temperature in kb units
temperature = args.temperature * kb
# Generate particle lists.
part_prop, all_particles, adress_tuple = tools.genParticleList(
input_conf, input_gro_conf, adress=True, use_charge=True, temperature=temperature)
print('Reads {} particles with properties {}'.format(len(all_particles), part_prop))
if input_conf.charges:
print('Total charge: {}'.format(sum(input_conf.charges)))
print('Running with box {}'.format(box))
system.bc = espressopp.bc.OrthorhombicBC(system.rng, box)
system.skin = skin
if args.node_grid:
nodeGrid = map(int, args.node_grid.split(','))
else:
nodeGrid = espressopp.tools.decomp.nodeGrid(MPI.COMM_WORLD.size)
print('Number of nodes {}, node-grid: {}'.format(
MPI.COMM_WORLD.size, nodeGrid))
if args.cell_grid:
cellGrid = map(int, args.cell_grid.split(','))
else:
cellGrid = espressopp.tools.decomp.cellGrid(box, nodeGrid, max_cutoff, skin)
print('Cell grid: {}'.format(cellGrid))
system.storage = espressopp.storage.DomainDecompositionAdress(system, nodeGrid, cellGrid)
integrator = espressopp.integrator.VelocityVerlet(system)
integrator.dt = args.dt
system.integrator = integrator
# Adds particles here
# Apparently AdResS required to first add CG particle and then the corresponding AT particles...
tmpp = []
new_plist = []
for p in all_particles:
if p.adrat == 1: # atomistic particle
tmpp.append(tuple(p))
else: # CG particle
new_plist.append(tuple(p))
new_plist.extend(tmpp)
tmpp = []
system.storage.addParticles(new_plist, *part_prop)
print('Set {} AdResS tuples'.format(len(adress_tuple)))
ftpl = espressopp.FixedTupleListAdress(system.storage)
ftpl.addTuples(adress_tuple)
system.storage.setFixedTuplesAdress(ftpl)
system.storage.decompose()
print('Prepared:')
print('Bonds: {}'.format(sum(len(x) for x in input_conf.bondtypes.values())))
print('Angles: {}'.format(sum(len(x) for x in input_conf.angletypes.values())))
print('Dihedrals: {}'.format(sum(len(x) for x in input_conf.dihedraltypes.values())))
print('Pairs: {}'.format(sum(len(x) for x in input_conf.pairtypes.values())))
print('Setting AdResS module')
print('Excplicit: {}'.format(args.adress_ex))
print('Hybrid: {}'.format(args.adress_hy))
if args.adress_centre == 'box_centre':
adr_centre = [box[0]/2.0, box[1]/2.0, box[2]/2.0]
else:
adr_centre = map(float, args.adress_centre.split(','))
if args.adress_use_sphere and args.calculate_tf:
# TODO(jakub): Add support for spherical AdResS region in case of TD-force calculation.
raise RuntimeError('Sphere AdResS region not supported for TD-force calculation')
print('Centre coordinates: {}'.format(adr_centre))
print('Spherical region: {}'.format(args.adress_use_sphere))
# Define interactions.
verletlist = espressopp.VerletListAdress(system, cutoff=max_cutoff, adrcut=max_cutoff,
dEx=args.adress_ex, dHy=args.adress_hy,
adrCenter=adr_centre,
sphereAdr=args.adress_use_sphere)
verletlist.exclude(input_conf.exclusions)
lj_interaction = tools.setLennardJonesInteractions(
input_conf, verletlist, max_cutoff, input_conf.nonbond_params, ftpl=ftpl)
coulomb_interaction = gromacs_topology.setCoulombInteractions(system,
verletlist,
max_cutoff,
input_conf.atomtypeparams,
epsilon1=args.coulomb_epsilon1,
epsilon2=args.coulomb_epsilon2,
kappa=args.coulomb_kappa,
ftpl=ftpl)
tools.setTabulatedInteractions(input_conf.atomtypeparams, max_cutoff, lj_interaction)
tools.setBondedInteractions(system, input_conf, ftpl)
tools.setAngleInteractions(system, input_conf, ftpl)
tools.setDihedralInteractions(system, input_conf, ftpl)
system.addInteraction(lj_interaction, 'lj')
system.addInteraction(coulomb_interaction, 'coulomb')
print('Number of interactions: {}'.format(system.getNumberOfInteractions()))
# Define the thermostat
print('Temperature: {} ({}), gamma: {}'.format(args.temperature, temperature, args.thermostat_gamma))
print('Thermostat: {}'.format(args.thermostat))
if args.thermostat == 'lv':
thermostat = espressopp.integrator.LangevinThermostat(system)
thermostat.temperature = temperature
thermostat.gamma = args.thermostat_gamma
thermostat.adress = True
elif args.thermostat == 'vr':
raise RuntimeError('Stochastic velocity rescale does not support AdResS, use Langevin.')
# thermostat = espressopp.integrator.StochasticVelocityRescaling(system)
# thermostat.temperature = temperature
# thermostat.coupling = args.thermostat_gamma
print("Added tuples, decomposing now ...")
ext_analysis, system_analysis = tools.setSystemAnalysis(
system, integrator, args, args.energy_collect,
particle_types=[t for t, d in input_conf.atomtypeparams.items() if d['particletype'] == 'A'])
if args.remove_com > 0:
print('Removes total velocity of the system every {} steps'.format(args.remove_com))
total_velocity = espressopp.analysis.CMVelocity(system)
ext_remove_com = espressopp.integrator.ExtAnalyze(total_velocity, args.remove_com)
integrator.addExtension(ext_remove_com)
print('Number of particles: {}'.format(len(all_particles)))
# Thermodynamic force
use_thforce = False
single_thforce = False
if args.tabletf:
use_thforce = True
print('Setting thermodynamic force: {}'.format(args.tabletf))
tabletfs = args.tabletf.split(',')
thdforce = espressopp.integrator.TDforce(system, verletlist)
if len(tabletfs) > 1 and ':' not in args.tabletf:
raise RuntimeError('Only single global thermodynamic force can be specify')
if len(tabletfs) == 1:
# Set TF force for CG types
tools_adress.set_single_th_force(thdforce, input_conf, tabletfs[0])
single_thforce = True
else:
type_name2type_id = {
td.get('atnum', td.get('atname')): tid
for tid, td in input_conf.atomtypeparams.items()}
for tblfs in tabletfs:
table_name, type_name = tblfs.split(':')
if type_name not in type_name2type_id:
raise RuntimeError('Type name {} not found'.format(type_name))
thdforce.addForce(itype=3, filename=table_name, type=type_name2type_id[type_name])
print('Set TF force for type: {} table: {}'.format(type_name, table_name))
if args.tf_initial_table:
use_thforce = True
single_thforce = True
thdforce = espressopp.integrator.TDforce(system, verletlist)
tools_adress.set_single_th_force(thdforce, input_conf, args.tf_initial_table)
# add AdResS
adress = espressopp.integrator.Adress(system, verletlist, ftpl)
integrator.addExtension(adress)
if use_thforce:
integrator.addExtension(thdforce)
integrator.addExtension(thermostat)
if args.cap_force:
print('Define maximum cap-force in the system (max: {})'.format(args.cap_force))
cap_force = espressopp.integrator.CapForce(system, args.cap_force)
cap_force.adress = True
integrator.addExtension(cap_force)
print('Decomposing...')
espressopp.tools.AdressDecomp(system, integrator)
# Let's compute density along X-axis
xdensity_dr = 0.05
xdensity_bins = int(box[0]/xdensity_dr)
compute_density_profile = args.compute_density_profile or args.calculate_tf
# Only atomistic particles
at_masses = [m for i, m in enumerate(input_conf.masses)
if input_conf.atomtypeparams[input_conf.types[i]]['particletype'] == 'A']
average_density = sum(at_masses)/(box[0]*box[1]*box[2])
print('Average density: {}'.format(average_density))
if compute_density_profile:
print('Compute x-density profile')
xdensity_comp = espressopp.analysis.XDensity(system)
xdensity = numpy.array(xdensity_comp.compute(xdensity_bins))
if args.calculate_tf and not single_thforce:
# TODO(jakub): Generalized it.
raise RuntimeError('Calculation of TD-force only for a single table.')
if args.calculate_tf:
savgol_filter_window = 21
x_r = numpy.arange(0, box[0], xdensity_dr)
adr_centre_idx = int(adr_centre[0]/xdensity_dr)
# Indexes with respect to adr_centre_idx (0)
adr_ex_idx = int((args.adress_ex)/xdensity_dr) # end of ex region
adr_hy_idx = int((args.adress_ex + args.adress_hy) / xdensity_dr) # end of hy region
# Read initial table from the file
if args.tf_initial_table:
zero_th = numpy.loadtxt(args.tf_initial_table)
last_th_force = zero_th[:, 2]
else:
tf_new = '{}_{}_th_s{}.xvg'.format(args.output_prefix, rng_seed, 0)
zero_th = numpy.zeros((x_r[adr_centre_idx-1:].shape[0], 3))
zero_th[:, 0] = x_r[:adr_centre_idx+1]
numpy.savetxt(tf_new, zero_th)
tools_adress.set_single_th_force(thdforce, input_conf, tf_new)
last_th_force = zero_th[:, 2]
for _s in range(args.tf_initial_step, args.tf_max_steps+1):
# Main integrator loop.
xdensity = numpy.array(xdensity_comp.compute(xdensity_bins))
print('Step {}, run for {} steps'.format(_s, k_steps*args.int_step))
integrator.step = 0
for k in range(k_steps):
integrator.run(args.int_step)
system_analysis.info()
xdensity += numpy.array(xdensity_comp.compute(xdensity_bins))
xdensity = xdensity / (k_steps + 1)
xdensity *= average_density
xdensity_file = '{}_{}_xdensity_s{}.csv'.format(args.output_prefix, rng_seed, _s)
print('Saved x-density: {}'.format(xdensity_file))
numpy.savetxt(xdensity_file, numpy.column_stack((x_r, xdensity)))
# For TF we need only part of the density profile.
rho = xdensity[adr_centre_idx-1:]
#rho[adr_ex_idx-1:adr_hy_idx+1] = xdensity[adr_centre_idx+adr_ex_idx-1:adr_centre_idx+adr_hy_idx+1]
rho_s = savgol_filter(rho, savgol_filter_window, 5, mode='nearest') # Make it smooth
drho_s = savgol_filter(rho_s, savgol_filter_window, 5, deriv=1, mode='nearest') # Get the force
drho_s[:adr_ex_idx-1] = 0.0
drho_s[adr_hy_idx+1:] = 0.0
# Substract the force from the previouse step (with prefactor)
new_th_force = last_th_force - args.tf_prefactor*drho_s
# Save the new table
tf_new = '{}_{}_th_s{}.xvg'.format(args.output_prefix, rng_seed, _s)
tf_new_raw = '{}_{}_th_s{}_raw.xvg'.format(args.output_prefix, rng_seed, _s)
numpy.savetxt(tf_new, numpy.column_stack((x_r[:adr_centre_idx+1], rho_s, new_th_force)))
numpy.savetxt(tf_new_raw, numpy.column_stack((x_r[:adr_centre_idx+1], rho, rho_s, new_th_force, drho_s)))
print('Saved new tf force to: {}'.format(tf_new))
# Save force from current step as last step and set new TD force
last_th_force = new_th_force
tools_adress.set_single_th_force(thdforce, input_conf, tf_new)
else: # Standard simulation
# Do not store trajectory when requested calculate TF.
trj_filename = '{}_{}_traj_at'.format(args.output_prefix, rng_seed)
dump_conf = None
if args.output_format == 'gro':
trj_filename = '{}.gro'.format(trj_filename)
dump_conf = espressopp.io.DumpGROAdress(
system,
ftpl,
integrator,
filename='{}.gro'.format(trj_filename),
unfolded=True)
elif args.output_format == 'xtc':
trj_filename = '{}.gro'.format(trj_filename)
dump_conf = espressopp.io.DumpXTCAdress(
system,
ftpl,
integrator,
unfolded=True,
append=True,
filename='{}.xtc'.format(trj_filename))
elif args.output_format:
raise RuntimeError('Traj dump {} not supported'.format(args.output_format))
if dump_conf and args.trj_collect > 0:
ext_dump = espressopp.integrator.ExtAnalyze(dump_conf, args.trj_collect)
integrator.addExtension(ext_dump)
print('Collect trajectory every {} in {}'.format(args.trj_collect, trj_filename))
# Main integrator loop.
time_vv = 0.0
print('Run simulation for {} steps'.format(k_steps*args.int_step))
system_analysis.dump()
system_analysis.info()
for k in range(k_steps):
time_s = time.time()
integrator.run(args.int_step)
time_vv += (time.time() - time_s)
system_analysis.info()
if compute_density_profile:
xdensity += numpy.array(xdensity_comp.compute(xdensity_bins))
# Calculate average of the density profile.
if compute_density_profile:
xdensity = xdensity / (k_steps+1)
xdensity = numpy.column_stack((
numpy.arange(0, box[0], xdensity_dr),
xdensity*average_density))
xdensity_file = '{}_{}_xdensity.csv'.format(args.output_prefix, rng_seed)
numpy.savetxt(xdensity_file, xdensity)
print('Saved x-density: {}'.format(xdensity_file))
print('Finished!')
print('Total time: {}'.format(time.time() - time0))
print('VV time: {}'.format(time_vv))
vv_timers = integrator.getTimers()
global_timers = {}
for cpu_timer in vv_timers:
# First consolidate
for k, v in cpu_timer:
if k not in global_timers:
global_timers[k] = 0.0
global_timers[k] += v
for k, v in global_timers.items():
global_timers[k] /= len(vv_timers)
print('VV {}: {:.2f}'.format(k, global_timers[k]))
print('Total # of AT neighbors = %d' % verletlistAT.totalSize())
print('Neighbor AT list builds = %d' % verletlistAT.builds)
print('Total # of CG neighbors = %d' % verletlistCG.totalSize())
print('Neighbor CG list builds = %d' % verletlistCG.builds)
print('Integration steps = %d' % integrator.step)
print('Total time: {}'.format(time.time() - time0))
if __name__ == '__main__':
main()