def InitSteps(self): ''' Function that deals with the amount of steps that need to be done in this run ''' #See how many steps have been performed previously, that are not stored in the gsd try: timedata=read_csv(self.params.timestepName, sep=' ', comment='#') except FileNotFoundError: killer = sig.GracefulKiller() print(self.params.timestepName," does not exist, so we:\n \ x) create "+self.params.timestepName+"\n\ x) fill it with the time step we read in the initial gsd configuration\n\ x) set to zero the time step on the gsd configuration\n\ x) Exit.\n\ xx) Now you can rerun and it should proceed smoothly." ) self.params.numFullCycles=0 self.params.iCycle=0 self.params.stepsPerCycle=hoomd.get_step() self.params.totOldCycleStep=hoomd.get_step() #steps done in previous cycles self.CreateTimeDataFile() hoomd.dump.gsd(filename=self.params.finalstatename, overwrite=True, truncate=True, period=None, time_step=0, group=hoomd.group.all()) self.RemoveBackup() raise SystemExit else: self.numFullCycles=np.int64(len(timedata)) if self.numFullCycles==0: raise SystemExit(self.params.timestepName+" looks empty (at most it has the header). Please delete it and then rerun.") self.params.iCycle=np.int64(timedata['iCycle'][self.numFullCycles-1]) #take the last line of the file self.params.stepsPerCycle=np.int64(timedata['stepsPerCycle'][self.numFullCycles-1]) self.params.totOldCycleStep=np.int64(timedata['totSteps'][self.numFullCycles-1]) #steps done in previous cycles #How many steps need to be done, considering the ones already done, and the addsteps option (which tells you to forget about the past steps) if self.params.addsteps==True: self.params.runSteps = self.params.nSteps % (HOOMDMAXSTEPS-self.params.iniStep) else: totStepsRemaining = self.params.nSteps-(self.params.totOldCycleStep+self.params.iniStep) self.params.runSteps = totStepsRemaining% HOOMDMAXSTEPS print("#-----------------------------------------------------#") print("# initial step = ",self.params.iniStep) print("# older steps = ",self.params.totOldCycleStep) print("# total steps simulated for this sample = ", self.params.totOldCycleStep + self.params.iniStep) print("# total steps requested for this sample = ", self.params.nSteps) print("# HOOMDMAXSTEPS = ", HOOMDMAXSTEPS) print("# steps to do in this run =",self.params.runSteps) print("#-----------------------------------------------------#") return
def sample(job): "Sample operation." import logging import hoomd from hoomd import md if hoomd.context.exec_conf is None: hoomd.context.initialize('') with job: with hoomd.context.SimulationContext(): hoomd.init.read_gsd('init.gsd', restart='restart.gsd') group = hoomd.group.all() gsd_restart = hoomd.dump.gsd( 'restart.gsd', truncate=True, period=100, phase=0, group=group) lj = md.pair.lj(r_cut=job.sp.r_cut, nlist=md.nlist.cell()) lj.pair_coeff.set('A', 'A', epsilon=job.sp.epsilon, sigma=job.sp.sigma) md.integrate.mode_standard(dt=0.005) md.integrate.npt( group=group, kT=job.sp.kT, tau=job.sp.tau, P=job.sp.p, tauP=job.sp.tauP) hoomd.analyze.log('dump.log', ['volume'], 100, phase=0) try: hoomd.run_upto(5000) except hoomd.WalltimeLimitReached: logging.warning("Reached walltime limit.") finally: gsd_restart.write_restart() job.document['sample_step'] = hoomd.get_step()
def check_timesteps(self): """Returns True and cancels saving when exiting this context if the stage has already been completed (i.e. it can be skipped) """ passed = hoomd.get_step() >= self.scope.get('cumulative_steps', 0) if passed: self.cancel_saving() return passed
def Finalize(self): ''' Do some final stuff for the simulation, such as saving configuration and removing conflicting files. ''' #First, we make sure that this function is not interrupted #When initiated, the class GracefulKiller catches all the sigterm,sigint #and sets to True the flag kill_now killer = sig.GracefulKiller() #If the cycle is finished (we did the maximum number of steps allowed by hoomd) #then we need to set the count to zero, and update the configuration curTimeStep=hoomd.get_step() if (curTimeStep + (self.params.iniStep%HOOMDMAXSTEPS) >= HOOMDMAXSTEPS): self.params.endatzero=True self.AppendTimeDataFile() else: print("# step:",hoomd.get_step()," maxsteps:",HOOMDMAXSTEPS) #disable integrator if self.integrator.enabled: self.integrator.disable() #save final configuration and remove backup timestep=0 if self.params.endatzero==True else curTimeStep hoomd.dump.gsd(filename=self.params.finalstatename, overwrite=True, truncate=True, period=None, time_step=timestep,group=hoomd.group.all()) if os.path.isfile(self.params.finalstatename): self.RemoveBackup() else: raise SystemExit('Error writing '+self.params.finalstatename) #Close open streams if self.params.heavyTraj.freq>0: self.params.heavyTraj.outTimes.close() self.params.heavyTraj.outPos.close() if self.params.heavyTraj.dumpAcc: self.params.heavyTraj.outVel.close() self.params.heavyTraj.outAcc.close() #If a sigterm was sent, now we can terminate the process if killer.kill_now: raise SystemExit("Termination signal was caught. Exiting Gracefully...") killer.resetSignals() #Now that we are past the dangerous zone, we go back to normal signal handling del killer return
def AppendTimeDataFile(self): ''' Write the final time in the timestep.in file, so that when it is read again we know how long the configuration has been thermalized. This crap is necessary because shitty hoomd does not handle runs of more than 2^32~10^9 steps (and I need like 10^13) ''' newiCycle = self.params.iCycle + 1 newStepsPerCycle = hoomd.get_step() totCycleStep = np.int64(newStepsPerCycle) + self.params.totOldCycleStep with open(self.params.timestepName,"at") as outf: print("%g %g %g"%(newiCycle,newStepsPerCycle,totCycleStep),file=outf) return
def RunNormal(self): ''' Function that runs the dynamics. If trajFreq>=0, it just does hoomd.run() otherwise, it takes care of saving the trajectory in logarithmic steps. ''' print("# ",self.params.runSteps," steps with the ",self.params.thermostat," thermostat at T=",self.params.temperature) sys.stdout.flush() if self.params.trajFreq>=0: hoomd.run(int(self.params.runSteps), quiet=False, callback=self.runCallback, callback_period=self.runCallbackFreq) else: for it in range(self.params.nt-1): curstep = hoomd.get_step()-self.params.iniStep if curstep>=self.params.listat[it+1]: continue fewSteps=self.params.listat[it+1]-curstep;#self.params.listat[it] hoomd.run(fewSteps, quiet=False) hoomd.dump.gsd(filename=self.params.trajName, overwrite=False, period=None, group=hoomd.group.all(),phase=-1) it+=1 return
def randomize_velocities(self, seed): R""" Assign random velocities and angular momenta to particles in the group, sampling from the Maxwell-Boltzmann distribution. This method considers the dimensionality of the system and particle anisotropy, and removes drift (the center of mass velocity). .. versionadded:: 2.3 Args: seed (int): Random number seed Note: Randomization is applied at the start of the next call to ```hoomd.run```. Example:: integrator = md.integrate.berendsen(group=group.all(), kT=1.0, tau=0.5) integrator.randomize_velocities(seed=42) run(100) """ timestep = hoomd.get_step() kT = self.kT.cpp_variant.getValue(timestep) self.cpp_method.setRandomizeVelocitiesParams(kT, seed)
def run(self, num_comp_cycles=1): ## construct exponentially growing pressure variant # \param num_comp_steps number of steps in pressure variant # \param pmin minimum pressure # \param pmax maximum pressure # \returns P pressure variant for use in NPT updater def makePvariant(num_comp_steps, pmin, pmax): num_points = 101 # number of points defining the curve interval = num_comp_steps / num_points pressures=np.logspace(np.log10(pmin), np.log10(pmax), num_points) P = hoomd.variant.linear_interp(points = [(i*interval, prs) for i,prs in enumerate(pressures)]) return P num_comp_cycles = int(num_comp_cycles) dim = self.dim pmin = self.pmin pmax = self.pmax allowShearing = self.allowShearing num_comp_steps = self.num_comp_steps tot_pvol = self.tot_pvol (Lx, Ly, Lz, xy, xz, yz) = self.box_params relax = self.relax refine_steps = self.refine_steps quiet = self.quiet tuner_period = self.tuner_period log_file = self.log_file ptypes = self.ptypes pf_tol = self.pf_tol self.mclog.enable() # Since a logger will output on the current step and then every period steps, we need to take one step # to get the logger in sync with our for loop. hoomd.run(1, quiet=True) # # set up NPT npt_updater # Lscale = 0.001 Ascale = A3scale = 0.01 if (dim==2): A3scale=0.0 self.npt_updater.set_betap(pmin) self.npt_updater.length(delta=Lscale) if allowShearing: self.npt_updater.shear(delta=A3scale, reduce=0.6) #calculate initial packing fraction volume = Lx*Ly if dim==2 else Lx*Ly*Lz last_eta = tot_pvol / volume hoomd.context.msg.notice(5,'Starting eta = {}. '.format(last_eta)) hoomd.context.msg.notice(5,'Starting volume = {}. '.format(volume)) hoomd.context.msg.notice(5,'overlaps={}.\n'.format(self.mc.count_overlaps())) for i in range(num_comp_cycles): hoomd.context.msg.notice(5,'Compressor sweep {}. '.format(i)) # if not first sweep, relax the system if i != 0: # set box volume to original hoomd.update.box_resize(Lx = Lx, Ly = Ly, Lz = Lz, period=None) # reset tunables self.npt_updater.set_betap(pmin) self.npt_updater.length(delta=Lscale) if allowShearing: self.npt_updater.shear(delta=A3scale) self.mc.set_params(d=0.1, a=0.01) noverlaps = self.mc.count_overlaps() if noverlaps != 0: hoomd.util.quiet_status() hoomd.context.msg.warning("Tuner cannot run properly if overlaps exist in the system. Expanding box...\n") while noverlaps != 0: hoomd.context.msg.notice(5,"{} overlaps at step {}... ".format(noverlaps, hoomd.get_step())) Lx *= 1.0+Lscale Ly *= 1.0+Lscale Lz *= 1.0+Lscale hoomd.update.box_resize(Lx = Lx, Ly = Ly, Lz = Lz, period=None) noverlaps = self.mc.count_overlaps() hoomd.util.unquiet_status() #randomize the initial configuration #initial box, no shear pretuning_steps = relax hoomd.run(pretuning_steps, quiet=quiet) # update pressure variant P = makePvariant(num_comp_steps, pmin, pmax) self.npt_updater.set_betap(P) # determine number of iterations for tuner loops loop_length = 0 for tuner in self.tuners: loop_length += int(tuner_period) #num_iterations = (num_comp_steps) // loop_length num_iterations = (num_comp_steps - pretuning_steps) // loop_length # run short loops with tuners until pressure is maxed out for j in range(num_iterations): for tuner in self.tuners: hoomd.run(tuner_period, quiet=quiet) tuner.update() #calculate packing fraction for zeroth iteration hoomd.context.msg.notice(5,"Checking eta at step {0}. ".format(hoomd.get_step())) L = hoomd.context.current.system_definition.getParticleData().getGlobalBox().getL() volume = L.x * L.y if dim==2 else L.x*L.y*L.z eta = tot_pvol / volume hoomd.context.msg.notice(5,'eta = {}, '.format(eta)) hoomd.context.msg.notice(5,"volume: {0}\n".format(volume)) step = hoomd.get_step() last_step = step j = 0 max_eta_checks = 100 # If packing has not converged, iterate until it does. Run at least one iteration last_eta = 0.0 while (eta - last_eta) > pf_tol: hoomd.run(refine_steps, quiet=quiet) # check eta hoomd.context.msg.notice(5,"Checking eta at step {0}. ".format(hoomd.get_step())) #calculate the new packing fraction L = hoomd.context.current.system_definition.getParticleData().getGlobalBox().getL() volume = L.x * L.y if dim==2 else L.x*L.y*L.z last_eta = eta eta = tot_pvol / volume hoomd.context.msg.notice(5,"eta: {0}, ".format(eta)) hoomd.context.msg.notice(5,"volume: {0}\n".format(volume)) last_step = step step = hoomd.get_step() # Check if we've gone too far if j == max_eta_checks: hoomd.context.msg.notice(5,"Eta did not converge in {0} iterations. Continuing to next cycle anyway.\n".format(max_eta_checks)) j += 1 hoomd.context.msg.notice(5,"Step: {step}, Packing fraction: {eta}, ".format(step=last_step, eta=last_eta)) hoomd.context.msg.notice(5,'overlaps={}\n'.format(self.mc.count_overlaps())) self.eta_list.append(last_eta) #take a snapshot of the system snap = snapshot() self.mc.setup_pos_writer(snap) self.snap_list.append(snap) self.mclog.disable() return (self.eta_list,self.snap_list)
def frenkel_ladd(job): import hoomd from hoomd import hpmc from hoomd import deprecated import sys sys.path.append('../utils/') import shapetools from garnett.reader import GSDHOOMDFileReader #import initialization_structures as structs from euclid.FreudShape import ConvexPolyhedron import numpy as np import os import json import time hoomd.context.initialize("--mode=cpu") with job: sp = job.statepoint() truncation = sp['truncation'] #structure = sp['structure'] pf = sp['pf'] polyhedra_type = "A" # polyhedra_type = "Polyhedra" mverts = 8 if truncation == 1 else 12 # Set up variables c_val = (2 * ((-truncation) + 1) + 1 ) # Mapping 0-1 truncation onto the 3-1 range of shapetools log_quantities = [ 'time', 'hpmc_sweeps', 'hpmc_translate_acceptance', 'hpmc_rotate_acceptance', 'hpmc_d', 'hpmc_a', 'hpmc_overlap_count', 'volume', 'hpmc_move_ratio', 'lattice_energy_pp_avg', 'lattice_energy_pp_sigma', 'lattice_translational_spring_constant', 'lattice_rotational_spring_constant', 'lattice_num_samples' ] # Construct the shape particle_vertices = shapetools.setVolumeVerts(a=1, b=2, c=c_val, Vol=PARTICLE_VOLUME) freud_shape = ConvexPolyhedron(points=particle_vertices) particle_radius = freud_shape.getCircumsphereRadius() #uc = structs.get_unit_cell(structure, truncation, type_name = polyhedra_type) # Determine how much to replicate #desired_N = 2**9 fname_base = 'calc_FL' log_file = fname_base + '.log' restart_file = fname_base + '_restart.gsd' output_file = fname_base + '.gsd' pos_file = fname_base + '.pos' snap = hoomd.data.gsd_snapshot( "/scratch/sglotzer_fluxoe/plawton/transfercode/frenkel-ladd/" + sp['structure'] + ".gsd") #n = int(round((desired_N/snap.particles.N)**(1./3.))) system = hoomd.init.read_snapshot( snap) if not job.isfile(restart_file) else hoomd.init.read_gsd( restart_file) #hoomd.init.create_lattice(uc, n) num_particles = len(system.particles) job.document['N'] = num_particles # Resize the system to the appropriate size. Needs to be isotropic. vol_init = system.box.Lx * system.box.Ly * system.box.Lz pf_init = num_particles * PARTICLE_VOLUME / vol_init if pf > pf_init: # First check that the new packing fraction is even feasible (i.e. it must be < the initial volume, otherwise we're trying a state point that can't be compressed to. job.document['valid_pf'] = False raise ValueError( 'This packing fraction is higher than the densest packing determined!' ) else: job.document['valid_pf'] = True vol = (num_particles * PARTICLE_VOLUME) / pf scale = (vol / vol_init)**(1. / 3) hoomd.update.box_resize(Lx=system.box.Lx * scale, Ly=system.box.Ly * scale, Lz=system.box.Lz * scale, period=None) job.document['random_seed'] = job.document.get( 'random_seed', np.random.randint(1, 1e5)) seed = job.document['random_seed'] mc = hpmc.integrate.convex_polyhedron(seed=seed, max_verts=mverts) mc.shape_param.set(polyhedra_type, vertices=particle_vertices) mc.set_params(d=0.1, a=0.1) snap = system.take_snapshot() fl = hpmc.field.frenkel_ladd_energy(mc=mc, ln_gamma=0.0, q_factor=10.0, r0=snap.particles.position, q0=snap.particles.orientation, drift_period=1000) hoomd.dump.gsd(filename=restart_file, group=hoomd.group.all(), period=10000, phase=0, truncate=True) hoomd.dump.gsd(filename=output_file, group=hoomd.group.all(), phase=0, period=10000, overwrite=False) # pos = deprecated.dump.pos(filename = pos_file, phase = 0, period = 10000) # mc.setup_pos_writer(pos) particle_tunables = ['d', 'a'] max_part_moves = [particle_radius, 0.5] particle_tuner = hpmc.util.tune(obj=mc, tunables=particle_tunables, max_val=max_part_moves, gamma=2.0, target=0.3) N_target_moves = int(2e5) num_tuning_steps = 20 tuner_period = int(np.floor(N_target_moves / num_tuning_steps)) + 1 fl_period = int(2e5) fl_eq_buffer = int(4e4) hoomd.run(1) log = hoomd.analyze.log(filename=log_file, header_prefix='#', quantities=log_quantities, period=fl_period + fl_eq_buffer + num_tuning_steps * tuner_period, overwrite=False) #sweep of spring constants try: ln_gammas = np.linspace(15, -5, 21) start = ln_gammas.index( job.document('gamma_completed' )) + 1 if 'gamma_completed' in job.document else 0 for ln_gam in ln_gammas[start:]: #tune the step size fl.set_params(ln_gamma=ln_gam) for i in range(num_tuning_steps): #hoomd.run(tuner_period, quiet = True) hoomd.run(tuner_period) particle_tuner.update() hoomd.run(fl_eq_buffer) fl.reset_statistics() hoomd.run(fl_period) job.document['steps_completed'] = hoomd.get_step() job.document['gamma_completed'] = ln_gam except hoomd.WalltimeLimitReached: # Since I've already run a bunch of these jobs without any thought to restartability, # for now I'm just going to write this such that I will restart the run if something # terminates the run. Since the runs are relatively short this is not a big loss. job.document['steps_completed'] = hoomd.get_step() job.document['completed'] = False job.document['completed'] = True
#Set to true to verify that nested callbacks are not supported youWantSegmentationFault = False if youWantSegmentationFault: cb.nestedcallbacks() hoomd.run(nsteps) # Every cb.heavyTrajFreq time steps save a trajectory of cb.heavyTrajLen steps # Examples I and II impose cb.heavyTrajFreq = cb.heavyTrajLen # Examples III and IV have impose cb.heavyTrajFreq > cb.heavyTrajLen #I) cb.heavyTrajFreq=cb.heavyTrajLen print('#######') print('## I ##') print('#######') for ht in range(nsteps // cb.heavyTrajFreq): cb.localcallback(hoomd.get_step()) hoomd.run(cb.heavyTrajFreq) #II) cb.heavyTrajFreq=cb.heavyTrajLen print('########') print('## II ##') print('########') hoomd.run(nsteps, callback_period=cb.heavyTrajFreq, callback=cb.localcallback) cb.lc.disable() #III) cb.heavyTrajFreq>cb.heavyTrajLen print('#########') print('## III ##') print('#########') for ht in range(nsteps // cb.heavyTrajFreq): print('ht:', ht)
assert (nNVTsteps > 0) assert (TemperatureGoal > 0) assert (tauT > 0) assert (dt > 0 and dt < 0.1) ################################################################ # # READ CONFIGURATION # ################################################################ backupname = label + "_backup.gsd" system = hoomd.init.read_gsd(filename=filename, restart=backupname, frame=iframe) assert (Natoms == len(system.particles)) iniStep = hoomd.get_step() print("iframe: ", iframe) print("Initial step: ", iniStep) ################################################################ # # SET UP POTENTIAL # ################################################################ NeighborsList = md.nlist.cell() if Natoms < 500: myLjPair = pot.LJ(NeighborsList, type="KAshort") else: myLjPair = pot.LJ(NeighborsList, type="KA") ################################################################
integrator_nvt = md.integrate.nve(group=hoomd.group.all()) for iterations in range(0, int(nNVTsteps / stepsTauT)): snap = system.take_snapshot() # each component is a gaussian of variance sigma, that's it. vel = np.random.normal(0, sqrt(TemperatureGoal), (Natoms, 3)) print('\nVelocities were rescaled by ', TemperatureGoal**0.5 / np.std(vel), '\n') vel *= sqrt(TemperatureGoal) / np.std( vel ) #Riscalo le velocita` per essere sicuro che non ci sono effetti di taglia finita sulla varianza della distribuzione snap.particles.velocity[:] = vel system.restore_snapshot(snap) hoomd.run(stepsTauT, quiet=False) else: print( "In this tutorial the only implemented thermostats are NVT (Nose-Hoover) and MB (Anderson)\n" ) sys.exit() integrator_nvt.disable() ######## NVE ######## print(nNVEsteps, " NVE steps via Velocity-Verlet") if nNVEsteps > 0: curStep = hoomd.get_step() integrator_nve = md.integrate.nve(group=hoomd.group.all()) hoomd.run(nNVEsteps, profile=False, quiet=False) integrator_nve.disable() analyzerManyVariables.disable()
myLjPair = pot.KApotentialShort(NeighborsListLJ) ################################################################ # # MD Dynamics # ################################################################ # #Write Initial configuration and make sure the center of mass is still # hoomd.md.update.zero_momentum(phase=-1) hoomd.md.update.zero_momentum(period=int(1. / dt), phase=0) print("Now dynamics") print("Current step:", hoomd.get_step()) print("Target step:", tchunk) md.integrate.mode_standard(dt=dt) integrator = md.integrate.nvt(group=hoomd.group.all(), kT=temperature, tau=tauT) hoomd.md.update.zero_momentum(phase=-1) hoomd.dump.gsd(filename="trajChunk" + str(ichunk) + label + ".gsd", overwrite=True, period=1, group=hoomd.group.all(), phase=0) #Now the MD steps hoomd.run(tchunk) hoomd.dump.gsd(filename=restart_name_current,
sig_AB=0.8 sig_BB=0.88 ## specify Lennard-Jones interactions between particle pairs NeighborsListLJ = md.nlist.cell() myLjPair = md.pair.lj(r_cut=r_cutoff, nlist=NeighborsListLJ) myLjPair.pair_coeff.set('A', 'A', epsilon=eps_AA, sigma=sig_AA, r_cut=r_cutoff*sig_AA) myLjPair.pair_coeff.set('A', 'B', epsilon=eps_AB, sigma=sig_AB, r_cut=r_cutoff*sig_AB) myLjPair.pair_coeff.set('B', 'B', epsilon=eps_BB, sigma=sig_BB, r_cut=r_cutoff*sig_BB) myLjPair.set_params(mode="shift") ### run FIRE minnimization/quench fire=hoomd.md.integrate.mode_minimize_fire(group=hoomd.group.all(), dt=0.001, ftol=ftol, Etol=Etol) while not(fire.has_converged()): hoomd.run(500, quiet=True) print 'steps to converge the step #t0=',t0,' : ', hoomd.get_step() - step , ' FIRE time steps and computeTime=',int(time.time() - computeTime0 ) ### record quenched state. gsd_restart = hoomd.dump.gsd(filename=outName, group=hoomd.group.all(), period=None, overwrite=False, truncate=False) #### FOR TESTING CONVERGENCE: / DEBUG PURPOSES : # pos = system.take_snapshot().particles.position # with open("StatesForCompare_"+str(step)+'_Etol='+str(Etol)+'_ftol='+str(ftol)+'_.dump', 'w') as outFlow: # np.savetxt(outFlow, pos) ########### ftol = 1e-5: #steps to converge: 10000.0 #steps to converge: 9000.0 #steps to converge: 15000.0
#hoomd.md.update.zero_momentum(int(1e6/Natoms), phase=0) #hoomd.md.update.zero_momentum(10, phase=0) ### other possibilities: ##md.integrate.berendsen Applies the Berendsen thermostat. ##md.integrate.brownian Brownian dynamics. ##md.integrate.langevin Langevin dynamics. ##md.integrate.mode_standard Enables a variety of standard integration methods. ###################################### ############# integrators ############ ###################################### module_filenamesHandler.log_action( rootname, "Runs (all) starting: ... (currently we are the step #" + str(hoomd.get_step()) + " of the simulation)\n" ) ## we put a space in case a run is aborted, to have notes.txt look cleaner. t0INIT = time.time() ######## NVT ######## if tstepsThermostat > 0: if glueing_flag == 'glueNVT': curStep = hoomd.get_step() gsd_HeavyTrajectory = hoomd.dump.gsd( filename=rootname + "_type=HeavyTraj" + "_cst=" + str(int(curStep / 1e9)) + "e9_rP=" + str(int(recPeriod)) + ".gsd", group=hoomd.group.all(), period=recPeriod, phase=0, overwrite=False,
def run(self, num_comp_cycles=1): ## construct exponentially growing pressure variant # \param num_comp_steps number of steps in pressure variant # \param pmin minimum pressure # \param pmax maximum pressure # \returns P pressure variant for use in NPT updater def makePvariant(num_comp_steps, pmin, pmax): num_points = 101 # number of points defining the curve interval = num_comp_steps / num_points pressures = np.logspace(np.log10(pmin), np.log10(pmax), num_points) P = hoomd.variant.linear_interp( points=[(i * interval, prs) for i, prs in enumerate(pressures)]) return P num_comp_cycles = int(num_comp_cycles) dim = self.dim pmin = self.pmin pmax = self.pmax allowShearing = self.allowShearing num_comp_steps = self.num_comp_steps tot_pvol = self.tot_pvol (Lx, Ly, Lz, xy, xz, yz) = self.box_params relax = self.relax refine_steps = self.refine_steps quiet = self.quiet tuner_period = self.tuner_period log_file = self.log_file ptypes = self.ptypes pf_tol = self.pf_tol self.mclog.enable() # Since a logger will output on the current step and then every period steps, we need to take one step # to get the logger in sync with our for loop. hoomd.run(1, quiet=True) # # set up NPT npt_updater # Lscale = 0.001 Ascale = A3scale = 0.01 if (dim == 2): A3scale = 0.0 self.npt_updater.set_betap(pmin) self.npt_updater.length(delta=Lscale) if allowShearing: self.npt_updater.shear(delta=A3scale, reduce=0.6) #calculate initial packing fraction volume = Lx * Ly if dim == 2 else Lx * Ly * Lz last_eta = tot_pvol / volume hoomd.context.msg.notice(5, 'Starting eta = {}. '.format(last_eta)) hoomd.context.msg.notice(5, 'Starting volume = {}. '.format(volume)) hoomd.context.msg.notice( 5, 'overlaps={}.\n'.format(self.mc.count_overlaps())) for i in range(num_comp_cycles): hoomd.context.msg.notice(5, 'Compressor sweep {}. '.format(i)) # if not first sweep, relax the system if i != 0: # set box volume to original hoomd.update.box_resize(Lx=Lx, Ly=Ly, Lz=Lz, period=None) # reset tunables self.npt_updater.set_betap(pmin) self.npt_updater.length(delta=Lscale) if allowShearing: self.npt_updater.shear(delta=A3scale) self.mc.set_params(d=0.1, a=0.01) noverlaps = self.mc.count_overlaps() if noverlaps != 0: hoomd.util.quiet_status() hoomd.context.msg.warning( "Tuner cannot run properly if overlaps exist in the system. Expanding box...\n" ) while noverlaps != 0: hoomd.context.msg.notice( 5, "{} overlaps at step {}... ".format( noverlaps, hoomd.get_step())) Lx *= 1.0 + Lscale Ly *= 1.0 + Lscale Lz *= 1.0 + Lscale hoomd.update.box_resize(Lx=Lx, Ly=Ly, Lz=Lz, period=None) noverlaps = self.mc.count_overlaps() hoomd.util.unquiet_status() #randomize the intial configuration #intial box, no shear pretuning_steps = relax hoomd.run(pretuning_steps, quiet=quiet) # update pressure variant P = makePvariant(num_comp_steps, pmin, pmax) self.npt_updater.set_betap(P) # determine number of iterations for tuner loops loop_length = 0 for tuner in self.tuners: loop_length += int(tuner_period) #num_iterations = (num_comp_steps) // loop_length num_iterations = (num_comp_steps - pretuning_steps) // loop_length # run short loops with tuners until pressure is maxed out for j in range(num_iterations): for tuner in self.tuners: hoomd.run(tuner_period, quiet=quiet) tuner.update() #calculate packing fraction for zeroth iteration hoomd.context.msg.notice( 5, "Checking eta at step {0}. ".format(hoomd.get_step())) L = hoomd.context.current.system_definition.getParticleData( ).getGlobalBox().getL() volume = L.x * L.y if dim == 2 else L.x * L.y * L.z eta = tot_pvol / volume hoomd.context.msg.notice(5, 'eta = {}, '.format(eta)) hoomd.context.msg.notice(5, "volume: {0}\n".format(volume)) step = hoomd.get_step() last_step = step j = 0 max_eta_checks = 100 # If packing has not converged, iterate until it does. Run at least one iteration last_eta = 0.0 while (eta - last_eta) > pf_tol: hoomd.run(refine_steps, quiet=quiet) # check eta hoomd.context.msg.notice( 5, "Checking eta at step {0}. ".format(hoomd.get_step())) #calculate the new packing fraction L = hoomd.context.current.system_definition.getParticleData( ).getGlobalBox().getL() volume = L.x * L.y if dim == 2 else L.x * L.y * L.z last_eta = eta eta = tot_pvol / volume hoomd.context.msg.notice(5, "eta: {0}, ".format(eta)) hoomd.context.msg.notice(5, "volume: {0}\n".format(volume)) last_step = step step = hoomd.get_step() # Check if we've gone too far if j == max_eta_checks: hoomd.context.msg.notice( 5, "Eta did not converge in {0} iterations. Continuing to next cycle anyway.\n" .format(max_eta_checks)) j += 1 hoomd.context.msg.notice( 5, "Step: {step}, Packing fraction: {eta}, ".format( step=last_step, eta=last_eta)) hoomd.context.msg.notice( 5, 'overlaps={}\n'.format(self.mc.count_overlaps())) self.eta_list.append(last_eta) #take a snapshot of the system snap = snapshot() self.mc.setup_pos_writer(snap) self.snap_list.append(snap) self.mclog.disable() return (self.eta_list, self.snap_list)
def InitConf(self): self.params.iniStep=0 if self.params.startfromzero==True else None self.system = hoomd.init.read_gsd(filename=self.params.initconfname, restart=self.params.backupName, frame=self.params.iframe, time_step=self.params.iniStep) if not self.params.Natoms==len(self.system.particles): raise SystemExit("Read configuration has Natoms="+str(len(self.system.particles))+"!="+str(self.params.Natoms)) self.params.iniStep = np.int64(hoomd.get_step()) return
def evaluate(self): hoomd.util.print_status_line() self.cpp_analyzer.evaluate(hoomd.get_step())
md.update.zero_momentum(phase=0, period=int(1./args.dt)) #Thermalize extraThermalizing=False if extraThermalizing: print('Thermalizing with NVT') integratorNVT = md.integrate.nvt(group=hoomd.group.all(), kT=args.temperature, tau=args.tauT) hoomd.run(int(10./args.dt), quiet=False) hoomd.dump.gsd(filename='./sample-states/rotenberg.gsd', overwrite=True, truncate=True, period=None, time_step=0, group=hoomd.group.all()) integratorNVT.disable() #The trajectory print('Measurement trajectory') modeT.set_params(dt=args.dt) integratorMeasure = md.integrate.nve(group=hoomd.group.all()) iniStep=hoomd.get_step() # analyzerManyVariables = hoomd.analyze.log(filename=args.label+".txt", quantities=['temperature','potential_energy', 'kinetic_energy', 'momentum'], period=int(1./args.dt), header_prefix = '#', overwrite=True, phase=0) # hoomd.dump.gsd(filename='./sample-states/trajectory'+args.label+'.gsd', overwrite=True, period=1, group=hoomd.group.all(),phase=-1) callback=hoomd.analyze.callback(callback = SaveMomentumForce, period = 1, phase=0) hoomd.run(args.Ntraj, quiet=False) integratorMeasure.disable() ################################################################ # CALCULATE STANDARD CORRELATORS ################################################################ print('Measure Correlations') corrPP=np.zeros((args.nchunk,Ncorr)) corrFF=np.zeros((args.nchunk,Ncorr)) corrFP=np.zeros((args.nchunk,Ncorr))
assert (TemperatureGoal > 0) assert (tauT > 0) assert (dt > 0 and dt < 0.1) ################################################################ # # READ CONFIGURATION # ################################################################ backupname = label + "_backup.gsd" system = hoomd.init.read_gsd(filename=filename, restart=backupname, frame=iframe) print("The read configuration has ", len(system.particles), " particles") assert (Natoms == len(system.particles)) iniStep = hoomd.get_step() print("iframe: ", iframe) print("Initial step: ", iniStep) ################################################################ # # SET UP POTENTIAL # ################################################################ NeighborsListLJ = md.nlist.cell() print(" *** Setting Kob-Anderesen Potential *** ") if Natoms < 500: myLjPair = pot.KApotentialShort(NeighborsListLJ) else: myLjPair = pot.KApotential(NeighborsListLJ)
Nframes = len(hoomdTraj) print('There are Nframes=', Nframes, 'in the file.') assert(Nframes==tchunk) posizioni=[hoomdTraj[i].particles.position[:] for i in range(Nframes)] HoomdFlow.close() ################################################################ # # Initialize # ################################################################ system = hoomd.init.read_gsd(filename=filename) t0=hoomd.get_step() print("Initial time:", t0) snap_ini=system.take_snapshot() snap_final=system.take_snapshot() snap_final.particles.position[:]=posizioni[Nframes-1] #If it's the first chunk, there is no list of energies. #Otherwise, we open it and make sure that the time step is consistent. if(ichunk>0): elist_old=np.loadtxt('elistIS.txt',skiprows=skiprows) assert(int(elist_old[len(elist_old)-1][0])==t0-1) ################################################################ # # Set potential #
snapshot = system.take_snapshot() np.copyto(snapshot.particles.velocity, np.random.random(snapshot.particles.velocity.shape)) system.restore_snapshot(snapshot) hoomd.dump.gsd(filename='init.gsd', period=None, group=hoomd.group.all()) hoomd.deprecated.dump.xml(hoomd.group.all(), filename='init.xml', vis=True) with hoomd.context.SimulationContext(): hoomd.init.read_gsd(filename='init.gsd', restart='restart.gsd') print("tstep", hoomd.get_step()) lj = md.pair.lj(r_cut=sp['r_cut'], nlist=md.nlist.cell()) lj.pair_coeff.set('A', 'A', epsilon=sp['epsilon'], sigma=sp['sigma']) group = hoomd.group.all() md.integrate.mode_standard(dt=0.01) md.integrate.nvt(group, kT=sp['kT'], tau=sp['tau']) gsd_restart = hoomd.dump.gsd(filename='restart.gsd', group=group, truncate=True,