class OTF(object): def __init__(self, dft_input: str, dt: float, number_of_steps: int, gp: gp.GaussianProcess, dft_loc: str, std_tolerance_factor: float = 1, prev_pos_init: np.ndarray = None, par: bool = False, skip: int = 0, init_atoms: List[int] = None, calculate_energy=False, output_name='otf_run', max_atoms_added=1, freeze_hyps=10, rescale_steps=[], rescale_temps=[], dft_softwarename="qe", no_cpus=1, npool=None, mpi="srun"): self.dft_input = dft_input self.dt = dt self.number_of_steps = number_of_steps self.gp = gp self.dft_loc = dft_loc self.std_tolerance = std_tolerance_factor self.skip = skip self.dft_step = True self.freeze_hyps = freeze_hyps self.dft_module = dft_software[dft_softwarename] # parse input file positions, species, cell, masses = \ self.dft_module.parse_dft_input(self.dft_input) _, coded_species = struc.get_unique_species(species) self.structure = struc.Structure(cell=cell, species=coded_species, positions=positions, mass_dict=masses, prev_positions=prev_pos_init, species_labels=species) self.noa = self.structure.positions.shape[0] self.atom_list = list(range(self.noa)) self.curr_step = 0 self.max_atoms_added = max_atoms_added # initialize local energies if calculate_energy: self.local_energies = np.zeros(self.noa) else: self.local_energies = None # set atom list for initial dft run if init_atoms is None: self.init_atoms = [int(n) for n in range(self.noa)] else: self.init_atoms = init_atoms self.dft_count = 0 # set pred function if not par and not calculate_energy: self.pred_func = predict.predict_on_structure elif par and not calculate_energy: self.pred_func = predict.predict_on_structure_par elif not par and calculate_energy: self.pred_func = predict.predict_on_structure_en elif par and calculate_energy: self.pred_func = predict.predict_on_structure_par_en self.par = par # set rescale attributes self.rescale_steps = rescale_steps self.rescale_temps = rescale_temps self.output = Output(output_name, always_flush=True) # set number of cpus and npool for qe runs self.no_cpus = no_cpus self.npool = npool self.mpi = mpi def run(self): self.output.write_header(self.gp.cutoffs, self.gp.kernel_name, self.gp.hyps, self.gp.algo, self.dt, self.number_of_steps, self.structure, self.std_tolerance) counter = 0 self.start_time = time.time() while self.curr_step < self.number_of_steps: print('curr_step:', self.curr_step) # run DFT and train initial model if first step and DFT is on if self.curr_step == 0 and self.std_tolerance != 0: # call dft and update positions self.run_dft() dft_frcs = copy.deepcopy(self.structure.forces) new_pos = md.update_positions(self.dt, self.noa, self.structure) self.update_temperature(new_pos) self.record_state() # make initial gp model and predict forces self.update_gp(self.init_atoms, dft_frcs) if (self.dft_count - 1) < self.freeze_hyps: self.train_gp() # after step 1, try predicting with GP model else: self.gp.check_L_alpha() self.pred_func(self.structure, self.gp, self.no_cpus) self.dft_step = False new_pos = md.update_positions(self.dt, self.noa, self.structure) # get max uncertainty atoms std_in_bound, target_atoms = is_std_in_bound( self.std_tolerance, self.gp.hyps[-1], self.structure, self.max_atoms_added) if not std_in_bound: # record GP forces self.update_temperature(new_pos) self.record_state() gp_frcs = copy.deepcopy(self.structure.forces) # run DFT and record forces self.dft_step = True self.run_dft() dft_frcs = copy.deepcopy(self.structure.forces) new_pos = md.update_positions(self.dt, self.noa, self.structure) self.update_temperature(new_pos) self.record_state() # compute mae and write to output mae = np.mean(np.abs(gp_frcs - dft_frcs)) mac = np.mean(np.abs(dft_frcs)) self.output.write_to_log('\nmean absolute error:' ' %.4f eV/A \n' % mae) self.output.write_to_log('mean absolute dft component:' ' %.4f eV/A \n' % mac) # add max uncertainty atoms to training set self.update_gp(target_atoms, dft_frcs) if (self.dft_count - 1) < self.freeze_hyps: self.train_gp() # write gp forces if counter >= self.skip and not self.dft_step: self.update_temperature(new_pos) self.record_state() counter = 0 counter += 1 self.update_positions(new_pos) self.curr_step += 1 self.output.conclude_run() def run_dft(self): self.output.write_to_log('\nCalling DFT...\n') # calculate DFT forces forces = self.dft_module.run_dft_par(self.dft_input, self.structure, self.dft_loc, no_cpus=self.no_cpus, npool=self.npool, mpi=self.mpi) self.structure.forces = forces # write wall time of DFT calculation self.dft_count += 1 self.output.write_to_log('QE run complete.\n') time_curr = time.time() - self.start_time self.output.write_to_log('number of DFT calls: %i \n' % self.dft_count) self.output.write_to_log('wall time from start: %.2f s \n' % time_curr) def update_gp(self, train_atoms, dft_frcs): self.output.write_to_log( '\nAdding atom {} to the training set.\n'.format(train_atoms)) self.output.write_to_log('Uncertainty: {}.\n'.format( self.structure.stds[train_atoms[0]])) # update gp model self.gp.update_db(self.structure, dft_frcs, custom_range=train_atoms) self.gp.set_L_alpha() def train_gp(self): self.gp.train(self.output) self.output.write_hyps(self.gp.hyp_labels, self.gp.hyps, self.start_time, self.gp.likelihood, self.gp.likelihood_gradient) def update_positions(self, new_pos): if self.curr_step in self.rescale_steps: rescale_ind = self.rescale_steps.index(self.curr_step) temp_fac = self.rescale_temps[rescale_ind] / self.temperature vel_fac = np.sqrt(temp_fac) self.structure.prev_positions = \ new_pos - self.velocities * self.dt * vel_fac else: self.structure.prev_positions = self.structure.positions self.structure.positions = new_pos self.structure.wrap_positions() def update_temperature(self, new_pos): KE, temperature, velocities = \ md.calculate_temperature(new_pos, self.structure, self.dt, self.noa) self.KE = KE self.temperature = temperature self.velocities = velocities def record_state(self): self.output.write_md_config(self.dt, self.curr_step, self.structure, self.temperature, self.KE, self.local_energies, self.start_time, self.dft_step, self.velocities) self.output.write_xyz_config(self.curr_step, self.structure, self.dft_step)
class OTF(object): def __init__(self, qe_input: str, dt: float, number_of_steps: int, gp: gp.GaussianProcess, pw_loc: str, std_tolerance_factor: float = 1, prev_pos_init: np.ndarray = None, par: bool = False, skip: int = 0, init_atoms: List[int] = None, calculate_energy=False, output_name='otf_run', max_atoms_added=1, freeze_hyps=10, rescale_steps=[], rescale_temps=[], no_cpus=1): self.qe_input = qe_input self.dt = dt self.number_of_steps = number_of_steps self.gp = gp self.pw_loc = pw_loc self.std_tolerance = std_tolerance_factor self.skip = skip self.dft_step = True self.freeze_hyps = freeze_hyps # parse input file positions, species, cell, masses = \ qe_util.parse_qe_input(self.qe_input) _, coded_species = struc.get_unique_species(species) self.structure = struc.Structure(cell=cell, species=coded_species, positions=positions, mass_dict=masses, prev_positions=prev_pos_init, species_labels=species) self.noa = self.structure.positions.shape[0] self.atom_list = list(range(self.noa)) self.curr_step = 0 self.max_atoms_added = max_atoms_added # initialize local energies if calculate_energy: self.local_energies = np.zeros(self.noa) else: self.local_energies = None # set atom list for initial dft run if init_atoms is None: self.init_atoms = [int(n) for n in range(self.noa)] else: self.init_atoms = init_atoms self.dft_count = 0 # set pred function if not par and not calculate_energy: self.pred_func = self.predict_on_structure elif par and not calculate_energy: self.pred_func = self.predict_on_structure_par elif not par and calculate_energy: self.pred_func = self.predict_on_structure_en elif par and calculate_energy: self.pred_func = self.predict_on_structure_par_en self.par = par # set rescale attributes self.rescale_steps = rescale_steps self.rescale_temps = rescale_temps self.output = Output(output_name) # set number of cpus for qe runs self.no_cpus = no_cpus def run(self): self.output.write_header(self.gp.cutoffs, self.gp.kernel_name, self.gp.hyps, self.gp.algo, self.dt, self.number_of_steps, self.structure, self.std_tolerance) counter = 0 self.start_time = time.time() while self.curr_step < self.number_of_steps: print('curr_step:', self.curr_step) # run DFT and train initial model if first step and DFT is on if self.curr_step == 0 and self.std_tolerance != 0: # call dft and update positions self.run_dft() dft_frcs = copy.deepcopy(self.structure.forces) new_pos = md.update_positions(self.dt, self.noa, self.structure) self.update_temperature(new_pos) self.record_state() # make initial gp model and predict forces self.update_gp(self.init_atoms, dft_frcs) if (self.dft_count - 1) < self.freeze_hyps: self.train_gp() # after step 1, try predicting with GP model else: self.pred_func() self.dft_step = False new_pos = md.update_positions(self.dt, self.noa, self.structure) # get max uncertainty atoms std_in_bound, target_atoms = self.is_std_in_bound() if not std_in_bound: # record GP forces self.update_temperature(new_pos) self.record_state() gp_frcs = copy.deepcopy(self.structure.forces) # run DFT and record forces self.dft_step = True self.run_dft() dft_frcs = copy.deepcopy(self.structure.forces) new_pos = md.update_positions(self.dt, self.noa, self.structure) self.update_temperature(new_pos) self.record_state() # compute mae and write to output mae = np.mean(np.abs(gp_frcs - dft_frcs)) mac = np.mean(np.abs(dft_frcs)) self.output.write_to_log('\nmean absolute error:' ' %.4f eV/A \n' % mae) self.output.write_to_log('mean absolute dft component:' ' %.4f eV/A \n' % mac) # add max uncertainty atoms to training set self.update_gp(target_atoms, dft_frcs) if (self.dft_count - 1) < self.freeze_hyps: self.train_gp() # write gp forces if counter >= self.skip and not self.dft_step: self.update_temperature(new_pos) self.record_state() counter = 0 counter += 1 self.update_positions(new_pos) self.curr_step += 1 self.output.conclude_run() def predict_on_atom(self, atom): chemenv = env.AtomicEnvironment(self.structure, atom, self.gp.cutoffs) comps = [] stds = [] # predict force components and standard deviations for i in range(3): force, var = self.gp.predict(chemenv, i + 1) comps.append(float(force)) stds.append(np.sqrt(np.abs(var))) return comps, stds def predict_on_atom_en(self, atom): chemenv = env.AtomicEnvironment(self.structure, atom, self.gp.cutoffs) comps = [] stds = [] # predict force components and standard deviations for i in range(3): force, var = self.gp.predict(chemenv, i + 1) comps.append(float(force)) stds.append(np.sqrt(np.abs(var))) # predict local energy local_energy = self.gp.predict_local_energy(chemenv) return comps, stds, local_energy def predict_on_structure_par(self): n = 0 with concurrent.futures.ProcessPoolExecutor() as executor: for res in executor.map(self.predict_on_atom, self.atom_list): for i in range(3): self.structure.forces[n][i] = res[0][i] self.structure.stds[n][i] = res[1][i] n += 1 def predict_on_structure_par_en(self): n = 0 with concurrent.futures.ProcessPoolExecutor() as executor: for res in executor.map(self.predict_on_atom_en, self.atom_list): for i in range(3): self.structure.forces[n][i] = res[0][i] self.structure.stds[n][i] = res[1][i] self.local_energies[n] = res[2] n += 1 def predict_on_structure(self): for n in range(self.structure.nat): chemenv = env.AtomicEnvironment(self.structure, n, self.gp.cutoffs) for i in range(3): force, var = self.gp.predict(chemenv, i + 1) self.structure.forces[n][i] = float(force) self.structure.stds[n][i] = np.sqrt(np.abs(var)) def predict_on_structure_en(self): for n in range(self.structure.nat): chemenv = env.AtomicEnvironment(self.structure, n, self.gp.cutoffs) for i in range(3): force, var = self.gp.predict(chemenv, i + 1) self.structure.forces[n][i] = float(force) self.structure.stds[n][i] = np.sqrt(np.abs(var)) self.local_energies[n] = self.gp.predict_local_energy(chemenv) def run_dft(self): self.output.write_to_log('\nCalling Quantum Espresso...\n') # calculate DFT forces forces = qe_util.run_espresso_par(self.qe_input, self.structure, self.pw_loc, self.no_cpus) self.structure.forces = forces # write wall time of DFT calculation self.dft_count += 1 self.output.write_to_log('QE run complete.\n') time_curr = time.time() - self.start_time self.output.write_to_log('number of DFT calls: %i \n' % self.dft_count) self.output.write_to_log('wall time from start: %.2f s \n' % time_curr) def update_gp(self, train_atoms, dft_frcs): self.output.write_to_log( '\nAdding atom {} to the training set.\n'.format(train_atoms)) self.output.write_to_log('Uncertainty: {}.\n'.format( self.structure.stds[train_atoms[0]])) # update gp model self.gp.update_db(self.structure, dft_frcs, custom_range=train_atoms) self.gp.set_L_alpha() # if self.curr_step == 0: # self.gp.set_L_alpha() # else: # self.gp.update_L_alpha() def train_gp(self): self.gp.train(self.output) self.output.write_hyps(self.gp.hyp_labels, self.gp.hyps, self.start_time, self.gp.like, self.gp.like_grad) def is_std_in_bound(self): # set uncertainty threshold if self.std_tolerance == 0: return True, -1 elif self.std_tolerance > 0: threshold = self.std_tolerance * np.abs(self.gp.hyps[-1]) else: threshold = np.abs(self.std_tolerance) # sort max stds max_stds = np.zeros((self.noa)) for atom, std in enumerate(self.structure.stds): max_stds[atom] = np.max(std) stds_sorted = np.argsort(max_stds) target_atoms = list(stds_sorted[-self.max_atoms_added:]) # if above threshold, return atom if max_stds[stds_sorted[-1]] > threshold: return False, target_atoms else: return True, [-1] def update_positions(self, new_pos): if self.curr_step in self.rescale_steps: rescale_ind = self.rescale_steps.index(self.curr_step) temp_fac = self.rescale_temps[rescale_ind] / self.temperature vel_fac = np.sqrt(temp_fac) self.structure.prev_positions = \ new_pos - self.velocities * self.dt * vel_fac else: self.structure.prev_positions = self.structure.positions self.structure.positions = new_pos self.structure.wrap_positions() def update_temperature(self, new_pos): KE, temperature, velocities = \ md.calculate_temperature(new_pos, self.structure, self.dt, self.noa) self.KE = KE self.temperature = temperature self.velocities = velocities def record_state(self): self.output.write_md_config(self.dt, self.curr_step, self.structure, self.temperature, self.KE, self.local_energies, self.start_time, self.dft_step, self.velocities) self.output.write_xyz_config(self.curr_step, self.structure, self.dft_step)
class TrajectoryTrainer(object): def __init__(self, frames: List[Structure], gp: GaussianProcess, rel_std_tolerance: float = 1, abs_std_tolerance: float = 1, parallel: bool = False, skip: int = 0, calculate_energy: bool = False, output_name: str = 'gp_from_aimd', max_atoms_from_frame: int = np.inf, max_trains: int = np.inf, min_atoms_added: int = 1, n_cpus: int = 1, shuffle_frames: bool = False, verbose: int = 0, model_write: str = '', pre_train_on_skips: bool = False, pre_train_seed_frames: List[Structure] = None, pre_train_seed_envs: List[Tuple[AtomicEnvironment, np.array]] = None, pre_train_atoms_per_element: dict = None): """ Class which trains a GP off of an AIMD trajectory, and generates error statistics between the DFT and GP calls. :param frames: List of structures to evaluate / train GP on :param gp: Gaussian Process object :param rel_std_tolerance: Train if uncertainty is above this * noise variance hyperparameter :param abs_std_tolerance: Train if uncertainty is above this :param parallel: Use parallel functions or not :param skip: Skip through frames :param calculate_energy: Use local energy kernel or not :param output_name: Write output of training to this file :param max_atoms_from_frame: Largest # of atoms added from one frame :param min_atoms_added: Only train when this many atoms have been added :param max_trains: Stop training GP after this many calls to train :param n_cpus: Number of CPUs to parallelize over :param shuffle_frames: Randomize order of frames for better training :param verbose: 0: Silent, 1: Minimal, 2: Lots of information :param model_write: Write output model here :param pre_train_on_skips: Train model on every n frames before running :param pre_train_seed_frames: Frames to train on before running :param pre_train_seed_envs: Environments to train on before running :param pre_train_atoms_per_element: Max # of environments to add from each species in the seed pre-training steps """ self.frames = frames if shuffle_frames: np.random.shuffle(frames) self.gp = gp self.rel_std_tolerance = rel_std_tolerance self.abs_std_tolerance = abs_std_tolerance self.skip = skip self.max_trains = max_trains self.curr_step = 0 self.max_atoms_from_frame = max_atoms_from_frame self.min_atoms_added = min_atoms_added self.verbose = verbose self.train_count = 0 self.parallel = parallel # set pred function if parallel: if calculate_energy: self.pred_func = predict_on_structure_par_en else: self.pred_func = predict_on_structure_par else: if calculate_energy: self.pred_func = predict_on_structure_en else: self.pred_func = predict_on_structure self.output = Output(output_name) # set number of cpus for parallelization self.n_cpus = n_cpus # To later be filled in using the time library self.start_time = None self.pickle_name = model_write self.pre_train_on_skips = pre_train_on_skips self.seed_envs = [] if pre_train_seed_envs is None else \ pre_train_seed_envs self.seed_frames = [] if pre_train_seed_frames is None \ else pre_train_seed_frames self.pre_train_env_per_species = {} if pre_train_atoms_per_element \ is None else pre_train_atoms_per_element def pre_run(self): """ Various tasks to set up the AIMD training before commencing the run through the AIMD trajectory. 1. Print the output. 2. Pre-train the GP with the seed frames and environments. If no seed frames or environments and the GP has no training set, then seed with at least one atom from each """ self.output.write_header(self.gp.cutoffs, self.gp.kernel_name, self.gp.hyps, self.gp.algo, dt=0, Nsteps=len(self.frames), structure=self.frames[0], std_tolerance=(self.rel_std_tolerance, self.abs_std_tolerance)) self.start_time = time.time() # If seed environments were passed in, add them to the GP. for point in self.seed_envs: self.gp.add_one_env(point[0], point[1], train=False) # No training set ("blank slate" run) and no seeds specified: # Take one of each atom species in the first frame # so all atomic species are represented in the first step. # Otherwise use the seed frames passed in by user. if len(self.gp.training_data) == 0 and self.seed_frames is None: self.seed_frames = [self.frames[0]] for frame in self.seed_frames: train_atoms = [] for species_i in set(frame.coded_species): # Get a randomized set of atoms of species i from the frame # So that it is not always the lowest-indexed atoms chosen atoms_of_specie = frame.indices_of_specie(species_i) np.random.shuffle(atoms_of_specie) n_at = len(atoms_of_specie) # Determine how many to add based on user defined cutoffs n_to_add = min(n_at, self.pre_train_env_per_species.get( species_i, np.inf), self.max_atoms_from_frame) for atom in atoms_of_specie[:n_to_add]: train_atoms.append(atom) self.update_gp_and_print(frame, train_atoms, train=False) # These conditions correspond to if either the GP was never trained # or if data was added to it during the pre-run. if (self.gp.l_mat is None) \ or (self.seed_frames is not None or self.seed_envs is not None): self.gp.train(output=self.output if self.verbose > 0 else None) def run(self): """ Loop through frames and record the error between the GP predictions and the ground-truth forces. Train the GP and update the training set upon the triggering of the uncertainty threshold. :return: """ self.pre_run() # Loop through trajectory for i, cur_frame in enumerate(self.frames): if self.verbose >= 2: print("=====NOW ON FRAME {}=====".format(i)) dft_forces = deepcopy(cur_frame.forces) self.pred_func(cur_frame, self.gp) # Convert to meV/A mae = np.mean(np.abs(cur_frame.forces - dft_forces)) * 1000 mac = np.mean(np.abs(dft_forces)) * 1000 self.output.write_gp_dft_comparison( curr_step=i, frame=cur_frame, start_time=time.time(), dft_forces=dft_forces, mae=mae, mac=mac, local_energies=None) # get max uncertainty atoms std_in_bound, train_atoms = self.is_std_in_bound(cur_frame) if not std_in_bound: # compute mae and write to output # add max uncertainty atoms to training set self.update_gp_and_print(cur_frame, train_atoms, train=False) if self.train_count < self.max_trains: self.train_gp() self.output.conclude_run() if self.pickle_name: with open(self.pickle_name, 'wb') as f: pickle.dump(self.gp, f) def update_gp_and_print(self, frame: Structure, train_atoms: List[int], train: bool=True): """ Update the internal GP model training set with a list of training atoms indexing atoms within the frame. If train is True, re-train the GP by optimizing hyperparameters. :param frame: Structure to train on :param train_atoms: Index atoms to train on :param train: Train or not :return: """ self.output.write_to_log('\nAdding atom(s) {} to the ' 'training set.\n' .format(train_atoms, )) self.output.write_to_log('Uncertainties: {}.\n' .format(frame.stds[train_atoms])) # update gp model self.gp.update_db(frame, frame.forces, custom_range=train_atoms) self.gp.set_L_alpha() if train: self.train_gp() def train_gp(self): """ Train the Gaussian process and write the results to the output file. """ self.gp.train(output=self.output if self.verbose >= 2 else None) self.output.write_hyps(self.gp.hyp_labels, self.gp.hyps, self.start_time, self.gp.like, self.gp.like_grad) self.train_count += 1 def is_std_in_bound(self, frame: Structure)->(bool, List[int]): """ If the predicted variance is too high, returns a list of atoms with the highest uncertainty :param frame: Structure :return: """ # This indicates test mode, as the GP is not being modified in any way if self.rel_std_tolerance == 0 and self.abs_std_tolerance == 0: return True, [-1] # set uncertainty threshold if self.rel_std_tolerance == 0: threshold = self.abs_std_tolerance elif self.abs_std_tolerance == 0: threshold = self.rel_std_tolerance * np.abs(self.gp.hyps[-1]) else: threshold = min(self.rel_std_tolerance * np.abs(self.gp.hyps[-1]), self.abs_std_tolerance) # sort max stds max_stds = np.zeros(frame.nat) for atom_idx, std in enumerate(frame.stds): max_stds[atom_idx] = np.max(std) stds_sorted = np.argsort(max_stds) # Handle case where unlimited atoms are added # or if max # of atoms exceeds size of frame if self.max_atoms_from_frame == np.inf or \ self.max_atoms_from_frame > len(frame): target_atoms = list(stds_sorted) else: target_atoms = list(stds_sorted[-self.max_atoms_from_frame:]) # if above threshold, return atom if max_stds[stds_sorted[-1]] > threshold: return False, target_atoms else: return True, [-1]
class TrajectoryTrainer: def __init__(self, frames: List[Structure], gp: Union[GaussianProcess, MappedGaussianProcess], rel_std_tolerance: float = 4, abs_std_tolerance: float = 1, abs_force_tolerance: float = 0, max_force_error: float = inf, parallel: bool = False, n_cpus: int = 1, skip: int = 1, validate_ratio: float = 0.0, calculate_energy: bool = False, output_name: str = 'gp_from_aimd', pre_train_max_iter: int = 50, max_atoms_from_frame: int = np.inf, max_trains: int = np.inf, min_atoms_per_train: int = 1, shuffle_frames: bool = False, verbose: int = 1, pre_train_on_skips: int = -1, pre_train_seed_frames: List[Structure] = None, pre_train_seed_envs: List[Tuple[AtomicEnvironment, 'np.array']] = None, pre_train_atoms_per_element: dict = None, train_atoms_per_element: dict = None, predict_atoms_per_element: dict = None, train_checkpoint_interval: int = 1, checkpoint_interval: int = 1, atom_checkpoint_interval: int = 100, model_format: str = 'json'): """ Class which trains a GP off of an AIMD trajectory, and generates error statistics between the DFT and GP calls. There are a variety of options which can give you a finer control over the training process. :param frames: List of structures to evaluate / train GP on :param gp: Gaussian Process object :param rel_std_tolerance: Train if uncertainty is above this * noise variance hyperparameter :param abs_std_tolerance: Train if uncertainty is above this :param abs_force_tolerance: Add atom force error exceeds this :param max_force_error: Don't add atom if force error exceeds this :param parallel: Use parallel functions or not :param validate_ratio: Fraction of frames used for validation :param skip: Skip through frames :param calculate_energy: Use local energy kernel or not :param output_name: Write output of training to this file :param max_atoms_from_frame: Largest # of atoms added from one frame :param min_atoms_per_train: Only train when this many atoms have been added :param max_trains: Stop training GP after this many calls to train :param n_cpus: Number of CPUs to parallelize over for parallelization over atoms :param shuffle_frames: Randomize order of frames for better training :param verbose: 0: Silent, NO output written or printed at all. 1: Minimal, 2: Lots of information :param pre_train_on_skips: Train model on every n frames before running :param pre_train_seed_frames: Frames to train on before running :param pre_train_seed_envs: Environments to train on before running :param pre_train_atoms_per_element: Max # of environments to add from each species in the seed pre-training steps :param train_atoms_per_element: Max # of environments to add from each species in the training steps :param predict_atoms_per_element: Choose a random subset of N random atoms from each specified element to predict on. For instance, {"H":5} will only predict the forces and uncertainties associated with 5 Hydrogen atoms per frame. Elements not specified will be predicted as normal. This is useful for systems where you are most interested in a subset of elements. This will result in a faster but less exhaustive learning process. :param checkpoint_interval: Will be deprecated. Same as train_checkpoint_interval :param train_checkpoint_interval: How often to write model after trainings :param atom_checkpoint_interval: How often to write model after atoms are added (since atoms may be added without training) :param model_format: Format to write GP model to """ # Set up parameters self.frames = frames if shuffle_frames: np.random.shuffle(frames) # GP Training and Execution parameters self.gp = gp # Check to see if GP is MGP for later flagging self.mgp = isinstance(gp, MappedGaussianProcess) self.rel_std_tolerance = rel_std_tolerance self.abs_std_tolerance = abs_std_tolerance self.abs_force_tolerance = abs_force_tolerance self.max_force_error = max_force_error self.max_trains = max_trains self.max_atoms_from_frame = max_atoms_from_frame self.min_atoms_per_train = min_atoms_per_train self.predict_atoms_per_element = predict_atoms_per_element self.verbose = verbose self.train_count = 0 self.calculate_energy = calculate_energy self.n_cpus = n_cpus if parallel is True: warnings.warn( "Parallel flag will be deprecated;" "we will instead use n_cpu alone.", DeprecationWarning) # Set prediction function based on if forces or energies are # desired, and parallelization accordingly if not self.mgp: if calculate_energy: self.pred_func = predict_on_structure_par_en else: self.pred_func = predict_on_structure_par elif self.mgp: self.pred_func = predict_on_structure_mgp # Parameters for negotiating with the training frames # To later be filled in using the time library self.start_time = None self.skip = skip assert (isinstance(skip, int) and skip >= 1), "Skip needs to be a " \ "positive integer." self.validate_ratio = validate_ratio assert (0 <= validate_ratio <= 1), \ "validate_ratio needs to be [0,1]" # Set up for pretraining self.pre_train_max_iter = pre_train_max_iter self.pre_train_on_skips = pre_train_on_skips self.seed_envs = [] if pre_train_seed_envs is None else \ pre_train_seed_envs self.seed_frames = [] if pre_train_seed_frames is None \ else pre_train_seed_frames self.pre_train_env_per_species = {} if pre_train_atoms_per_element \ is None else pre_train_atoms_per_element self.train_env_per_species = {} if train_atoms_per_element \ is None else train_atoms_per_element # Convert to Coded Species if self.pre_train_env_per_species: pre_train_species = list(self.pre_train_env_per_species.keys()) for key in pre_train_species: self.pre_train_env_per_species[element_to_Z(key)] = \ self.pre_train_env_per_species[key] # Output parameters self.verbose = verbose if self.verbose: self.output = Output(output_name, always_flush=True) else: self.output = None self.train_checkpoint_interval = train_checkpoint_interval or \ checkpoint_interval self.atom_checkpoint_interval = atom_checkpoint_interval self.model_format = model_format self.output_name = output_name # Defining variables to be used later self.curr_step = 0 self.train_count = 0 self.start_time = None def pre_run(self): """ Various tasks to set up the AIMD training before commencing the run through the AIMD trajectory. 1. Print the output. 2. Pre-train the GP with the seed frames and environments. If no seed frames or environments and the GP has no training set, then seed with at least one atom from each """ if self.mgp: raise NotImplementedError("Pre-running not" "yet configured for MGP") if self.verbose: self.output.write_header( self.gp.cutoffs, self.gp.kernel_name, self.gp.hyps, self.gp.opt_algorithm, dt=0, Nsteps=len(self.frames), structure=None, std_tolerance=(self.rel_std_tolerance, self.abs_std_tolerance), optional={ 'GP Statistics': json.dumps(self.gp.training_statistics), 'GP Name': self.gp.name, 'GP Write Name': self.output_name + "_model." + self.model_format }) self.start_time = time.time() if self.verbose >= 3: print("Now beginning pre-run activity.") # If seed environments were passed in, add them to the GP. for point in self.seed_envs: self.gp.add_one_env(point[0], point[1], train=False) # No training set ("blank slate" run) and no seeds specified: # Take one of each atom species in the first frame # so all atomic species are represented in the first step. # Otherwise use the seed frames passed in by user. # Remove frames used as seed from later part of training if self.pre_train_on_skips > 0: self.seed_frames = [] newframes = [] for i in range(len(self.frames)): if (i % self.pre_train_on_skips) == 0: self.seed_frames += [self.frames[i]] else: newframes += [self.frames[i]] self.frames = newframes # If the GP is empty, use the first frame as a seed frame. elif len(self.gp.training_data) == 0 and len(self.seed_frames) == 0: self.seed_frames = [self.frames[0]] self.frames = self.frames[1:] atom_count = 0 for frame in self.seed_frames: train_atoms = [] for species_i in set(frame.coded_species): # Get a randomized set of atoms of species i from the frame # So that it is not always the lowest-indexed atoms chosen atoms_of_specie = frame.indices_of_specie(species_i) np.random.shuffle(atoms_of_specie) n_at = len(atoms_of_specie) # Determine how many to add based on user defined cutoffs n_to_add = min( n_at, self.pre_train_env_per_species.get(species_i, inf), self.max_atoms_from_frame) for atom in atoms_of_specie[:n_to_add]: train_atoms.append(atom) atom_count += 1 self.update_gp_and_print(frame=frame, train_atoms=train_atoms, uncertainties=[], train=False) if self.verbose and atom_count > 0: self.output.write_to_log( f"Added {atom_count} atoms to " f"pretrain.\n" f"Pre-run GP Statistics: " f"{json.dumps(self.gp.training_statistics)} \n", flush=True) if (self.seed_envs or atom_count or self.seed_frames) and \ (self.pre_train_max_iter or self.max_trains): if self.verbose >= 3: print("Now commencing pre-run training of GP (which has " "non-empty training set)") self.train_gp(max_iter=self.pre_train_max_iter) else: if self.verbose >= 3: print("Now commencing pre-run set up of GP (which has " "non-empty training set)") self.gp.set_L_alpha() if self.model_format and not self.mgp: self.gp.write_model(f'{self.output_name}_prerun', self.model_format) def run(self): """ Loop through frames and record the error between the GP predictions and the ground-truth forces. Train the GP and update the training set upon the triggering of the uncertainty or force error threshold. :return: None """ # Perform pre-run, in which seed trames are used. if self.verbose >= 3: print("Commencing run with pre-run...") if not self.mgp: self.pre_run() # Past this frame, stop adding atoms to the training set # (used for validation of model) train_frame = int( len(self.frames[::self.skip]) * (1 - self.validate_ratio)) # Loop through trajectory. cur_atoms_added_train = 0 # Track atoms added for training cur_atoms_added_write = 0 # Track atoms added for writing cur_trains_done_write = 0 # Track training done for writing for i, cur_frame in enumerate(self.frames[::self.skip]): if self.verbose >= 2: print(f"=====NOW ON FRAME {i}=====") # If no predict_atoms_per_element was specified, predict_atoms # will be equal to every atom in the frame. predict_atoms = subset_of_frame_by_element( cur_frame, self.predict_atoms_per_element) # Atoms which are skipped will have NaN as their force / std values local_energies = None # Three different predictions: Either MGP, GP with energy, # or GP without if self.mgp: pred_forces, pred_stds = self.pred_func( structure=cur_frame, mgp=self.gp, write_to_structure=False, selective_atoms=predict_atoms, skipped_atom_value=np.nan) elif self.calculate_energy: pred_forces, pred_stds, local_energies = self.pred_func( structure=cur_frame, gp=self.gp, n_cpus=self.n_cpus, write_to_structure=False, selective_atoms=predict_atoms, skipped_atom_value=np.nan) else: pred_forces, pred_stds = self.pred_func( structure=cur_frame, gp=self.gp, n_cpus=self.n_cpus, write_to_structure=False, selective_atoms=predict_atoms, skipped_atom_value=np.nan) # Get Error dft_forces = cur_frame.forces error = np.abs(pred_forces - dft_forces) # Create dummy frame with the predicted forces written dummy_frame = deepcopy(cur_frame) dummy_frame.forces = pred_forces dummy_frame.stds = pred_stds if self.verbose: self.output.write_gp_dft_comparison( curr_step=i, frame=dummy_frame, start_time=time.time(), dft_forces=dft_forces, error=error, local_energies=local_energies) if i < train_frame: # Noise hyperparameter & relative std tolerance is not for mgp. if self.mgp: noise = 0 else: noise = self.gp.hyps[-1] std_in_bound, std_train_atoms = is_std_in_bound_per_species( rel_std_tolerance=self.rel_std_tolerance, abs_std_tolerance=self.abs_std_tolerance, noise=noise, structure=dummy_frame, max_atoms_added=self.max_atoms_from_frame, max_by_species=self.train_env_per_species) # Get max force error atoms force_in_bound, force_train_atoms = \ is_force_in_bound_per_species( abs_force_tolerance=self.abs_force_tolerance, predicted_forces=pred_forces, label_forces=dft_forces, structure=dummy_frame, max_atoms_added=self.max_atoms_from_frame, max_by_species=self.train_env_per_species, max_force_error=self.max_force_error) if not std_in_bound or not force_in_bound: # -1 is returned from the is_in_bound methods, # so filter that out and the use sets to remove repeats train_atoms = list( set(std_train_atoms).union(force_train_atoms) - {-1}) # Compute mae and write to output; # Add max uncertainty atoms to training set self.update_gp_and_print( cur_frame, train_atoms=train_atoms, uncertainties=pred_stds[train_atoms], train=False) cur_atoms_added_train += len(train_atoms) cur_atoms_added_write += len(train_atoms) # Re-train if number of sampled atoms is high enough if cur_atoms_added_train >= self.min_atoms_per_train or ( i + 1) == train_frame: if self.train_count < self.max_trains: self.train_gp() cur_trains_done_write += 1 else: self.gp.update_L_alpha() cur_atoms_added_train = 0 else: self.gp.update_L_alpha() # Loop to decide of a model should be written this # iteration will_write = False if self.train_checkpoint_interval and \ cur_trains_done_write and \ self.train_checkpoint_interval \ % cur_trains_done_write == 0: will_write = True cur_trains_done_write = 0 if self.atom_checkpoint_interval \ and cur_atoms_added_write \ and self.atom_checkpoint_interval \ % cur_atoms_added_write == 0: will_write = True cur_atoms_added_write = 0 if self.model_format and will_write: self.gp.write_model(f'{self.output_name}_checkpt', self.model_format) if (i + 1) == train_frame and not self.mgp: self.gp.check_L_alpha() if self.verbose: self.output.conclude_run() if self.model_format and not self.mgp: self.gp.write_model(f'{self.output_name}_model', self.model_format) def update_gp_and_print(self, frame: Structure, train_atoms: List[int], uncertainties: List[int] = None, train: bool = True): """ Update the internal GP model training set with a list of training atoms indexing atoms within the frame. If train is True, re-train the GP by optimizing hyperparameters. :param frame: Structure to train on :param train_atoms: Index atoms to train on :param uncertainties: Uncertainties to print, pass in [] to silence :param train: Train or not :return: None """ # Group added atoms by species for easier output added_species = [ Z_to_element(frame.coded_species[at]) for at in train_atoms ] added_atoms = {spec: [] for spec in set(added_species)} for atom, spec in zip(train_atoms, added_species): added_atoms[spec].append(atom) if self.verbose: self.output.write_to_log( '\nAdding atom(s) ' f'{json.dumps(added_atoms,cls=NumpyEncoder)}' ' to the training set.\n') if uncertainties is None or len(uncertainties) != 0: uncertainties = frame.stds[train_atoms] if self.verbose and len(uncertainties) != 0: self.output.write_to_log(f'Uncertainties: ' f'{uncertainties}.\n', flush=True) # update gp model; handling differently if it's an MGP if not self.mgp: self.gp.update_db(frame, frame.forces, custom_range=train_atoms) if train: self.train_gp() else: raise NotImplementedError def train_gp(self, max_iter: int = None): """ Train the Gaussian process and write the results to the output file. :param max_iter: Maximum iterations associated with this training run, overriding the Gaussian Process's internally set maxiter. :type max_iter: int """ if self.verbose >= 1: self.output.write_to_log('Train GP\n') # TODO: Improve flexibility in GP training to make this next step # unnecessary, so maxiter can be passed as an argument # Don't train if maxiter == 0 if max_iter == 0: self.gp.check_L_alpha() elif max_iter is not None: temp_maxiter = self.gp.maxiter self.gp.maxiter = max_iter self.gp.train(output=self.output if self.verbose >= 2 else None) self.gp.maxiter = temp_maxiter else: self.gp.train(output=self.output if self.verbose >= 2 else None) if self.verbose: self.output.write_hyps(self.gp.hyp_labels, self.gp.hyps, self.start_time, self.gp.likelihood, self.gp.likelihood_gradient, hyps_mask=self.gp.hyps_mask) self.train_count += 1
class TrajectoryTrainer: def __init__(self, frames: List[Structure], gp: GaussianProcess, rel_std_tolerance: float = 4, abs_std_tolerance: float = 1, abs_force_tolerance: float = 0, max_force_error: float = inf, parallel: bool = False, n_cpus: int = None, skip: int = 1, validate_ratio: float = 0.1, calculate_energy: bool = False, output_name: str = 'gp_from_aimd', pre_train_max_iter: int = 50, max_atoms_from_frame: int = np.inf, max_trains: int = np.inf, min_atoms_per_train: int = 1, shuffle_frames: bool = False, verbose: int = 0, pre_train_on_skips: int = -1, pre_train_seed_frames: List[Structure] = None, pre_train_seed_envs: List[Tuple[AtomicEnvironment, 'np.array']] = None, pre_train_atoms_per_element: dict = None, train_atoms_per_element: dict = None, checkpoint_interval: int = None, model_format: str = 'json'): """ Class which trains a GP off of an AIMD trajectory, and generates error statistics between the DFT and GP calls. There are a variety of options which can give you a finer control over the training process. :param frames: List of structures to evaluate / train GP on :param gp: Gaussian Process object :param rel_std_tolerance: Train if uncertainty is above this * noise variance hyperparameter :param abs_std_tolerance: Train if uncertainty is above this :param abs_force_tolerance: Add atom force error exceeds this :param max_force_error: Don't add atom if force error exceeds this :param parallel: Use parallel functions or not :param validate_ratio: Fraction of frames used for validation :param n_cpus: number of cpus to run with multithreading :param skip: Skip through frames :param calculate_energy: Use local energy kernel or not :param output_name: Write output of training to this file :param max_atoms_from_frame: Largest # of atoms added from one frame :param min_atoms_added: Only train when this many atoms have been added :param max_trains: Stop training GP after this many calls to train :param n_cpus: Number of CPUs to parallelize over :param shuffle_frames: Randomize order of frames for better training :param verbose: 0: Silent, 1: Minimal, 2: Lots of information :param pre_train_on_skips: Train model on every n frames before running :param pre_train_seed_frames: Frames to train on before running :param pre_train_seed_envs: Environments to train on before running :param pre_train_atoms_per_element: Max # of environments to add from each species in the seed pre-training steps :param train_atoms_per_element: Max # of environments to add from each species in the training steps :param checkpoint_interval: How often to write model after trainings :param model_format: Format to write GP model to """ # Set up parameters self.frames = frames if shuffle_frames: np.random.shuffle(frames) # GP Training and Execution parameters self.gp = gp self.rel_std_tolerance = rel_std_tolerance self.abs_std_tolerance = abs_std_tolerance self.abs_force_tolerance = abs_force_tolerance self.max_force_error = max_force_error self.max_trains = max_trains self.max_atoms_from_frame = max_atoms_from_frame self.min_atoms_per_train = min_atoms_per_train self.verbose = verbose self.train_count = 0 self.parallel = parallel self.n_cpus = n_cpus # Set prediction function based on if forces or energies are # desired, and parallelization accordingly if (parallel and gp.par and gp.per_atom_par): if calculate_energy: self.pred_func = predict_on_structure_par_en else: self.pred_func = predict_on_structure_par else: if calculate_energy: self.pred_func = predict_on_structure_en else: self.pred_func = predict_on_structure # Parameters for negotiating with the training frames self.output = Output(output_name, always_flush=True) # To later be filled in using the time library self.start_time = None self.skip = skip assert (isinstance(skip, int) and skip >= 1), "Skip needs to be a " \ "positive integer." self.validate_ratio = validate_ratio assert (validate_ratio>=0 and validate_ratio<=1), \ "validate_ratio needs to be [0,1]" # Set up for pretraining self.pre_train_max_iter = pre_train_max_iter self.pre_train_on_skips = pre_train_on_skips self.seed_envs = [] if pre_train_seed_envs is None else \ pre_train_seed_envs self.seed_frames = [] if pre_train_seed_frames is None \ else pre_train_seed_frames self.pre_train_env_per_species = {} if pre_train_atoms_per_element \ is None else pre_train_atoms_per_element self.train_env_per_species = {} if train_atoms_per_element \ is None else train_atoms_per_element # Convert to Coded Species if self.pre_train_env_per_species: pre_train_species = list(self.pre_train_env_per_species.keys()) for key in pre_train_species: self.pre_train_env_per_species[element_to_Z(key)] = \ self.pre_train_env_per_species[key] # Output parameters self.output = Output(output_name, always_flush=True) self.verbose = verbose self.checkpoint_interval = checkpoint_interval self.model_format = model_format self.output_name = output_name # Defining variables to be used later self.curr_step = 0 self.train_count = 0 self.start_time = None def pre_run(self): """ Various tasks to set up the AIMD training before commencing the run through the AIMD trajectory. 1. Print the output. 2. Pre-train the GP with the seed frames and environments. If no seed frames or environments and the GP has no training set, then seed with at least one atom from each """ self.output.write_header(self.gp.cutoffs, self.gp.kernel_name, self.gp.hyps, self.gp.algo, dt=0, Nsteps=len(self.frames), structure=self.frames[0], std_tolerance=(self.rel_std_tolerance, self.abs_std_tolerance)) self.start_time = time.time() if self.verbose >= 3: print("Now beginning pre-run activity.") # If seed environments were passed in, add them to the GP. for point in self.seed_envs: self.gp.add_one_env(point[0], point[1], train=False) # No training set ("blank slate" run) and no seeds specified: # Take one of each atom species in the first frame # so all atomic species are represented in the first step. # Otherwise use the seed frames passed in by user. # Remove frames used as seed from later part of training if self.pre_train_on_skips > 0: self.seed_frames = [] newframes = [] for i in range(len(self.frames)): if (i % self.pre_train_on_skips) == 0: self.seed_frames += [self.frames[i]] else: newframes += [self.frames[i]] self.frames = newframes elif len(self.gp.training_data) == 0 and len(self.seed_frames) == 0: self.seed_frames = [self.frames[0]] self.frames = self.frames[1:] atom_count = 0 for frame in self.seed_frames: train_atoms = [] for species_i in set(frame.coded_species): # Get a randomized set of atoms of species i from the frame # So that it is not always the lowest-indexed atoms chosen atoms_of_specie = frame.indices_of_specie(species_i) np.random.shuffle(atoms_of_specie) n_at = len(atoms_of_specie) # Determine how many to add based on user defined cutoffs n_to_add = min(n_at, self.pre_train_env_per_species.get( species_i, inf), self.max_atoms_from_frame) for atom in atoms_of_specie[:n_to_add]: train_atoms.append(atom) atom_count += 1 self.update_gp_and_print(frame, train_atoms, train=False) if self.verbose >= 3 and atom_count > 0: print(f"Added {atom_count} atoms to pretrain") if (self.seed_envs or atom_count or self.seed_frames) and self.max_trains>0: if self.verbose >= 3: print("Now commencing pre-run training of GP (which has " "non-empty training set)") self.train_gp(max_iter=self.pre_train_max_iter) else: if self.verbose >= 3: print("Now commencing pre-run set up of GP (which has " "non-empty training set)") self.gp.set_L_alpha() if self.model_format: self.gp.write_model(f'{self.output_name}_prerun', self.model_format) def run(self): """ Loop through frames and record the error between the GP predictions and the ground-truth forces. Train the GP and update the training set upon the triggering of the uncertainty or force error threshold. :return: None """ if self.verbose >= 3: print("Commencing run with pre-run...") self.pre_run() train_frame = int(len(self.frames) * (1 - self.validate_ratio)) # Loop through trajectory nsample = 0 for i, cur_frame in enumerate(self.frames[::self.skip]): if self.verbose >= 2: print("=====NOW ON FRAME {}=====".format(i)) dft_forces = deepcopy(cur_frame.forces) self.pred_func(cur_frame, self.gp, self.n_cpus) # Convert to meV/A error = np.abs(cur_frame.forces - dft_forces) self.output.write_gp_dft_comparison( curr_step=i, frame=cur_frame, start_time=time.time(), dft_forces=dft_forces, error=error, local_energies=None) if i < train_frame: # Get max uncertainty atoms std_in_bound, std_train_atoms = is_std_in_bound_per_species( rel_std_tolerance=self.rel_std_tolerance, abs_std_tolerance=self.abs_std_tolerance, noise=self.gp.hyps[-1], structure=cur_frame, max_atoms_added=self.max_atoms_from_frame, max_by_species=self.train_env_per_species) # Get max force error atoms force_in_bound, force_train_atoms = \ is_force_in_bound_per_species( abs_force_tolerance=self.abs_force_tolerance, predicted_forces=cur_frame.forces, label_forces=dft_forces, structure=cur_frame, max_atoms_added=self.max_atoms_from_frame, max_by_species=self.train_env_per_species, max_force_error=self.max_force_error) if (not std_in_bound) or (not force_in_bound): train_atoms = list(set(std_train_atoms).union( force_train_atoms) - {-1}) # Compute mae and write to output; # Add max uncertainty atoms to training set self.update_gp_and_print( cur_frame, train_atoms, train=False) nsample += len(train_atoms) # Re-train if number of sampled atoms is high enough if nsample >= self.min_atoms_per_train or ( i + 1) == train_frame: if self.train_count < self.max_trains: self.train_gp() else: self.gp.update_L_alpha() nsample = 0 else: self.gp.update_L_alpha() if self.checkpoint_interval \ and self.train_count % self.checkpoint_interval == 0 \ and self.model_format: self.gp.write_model(f'{self.output_name}_ckpt', self.model_format) if (i + 1) == train_frame: self.gp.check_L_alpha() self.output.conclude_run() if self.model_format: self.gp.write_model(f'{self.output_name}_model', self.model_format) def update_gp_and_print(self, frame: Structure, train_atoms: List[int], train: bool = True): """ Update the internal GP model training set with a list of training atoms indexing atoms within the frame. If train is True, re-train the GP by optimizing hyperparameters. :param frame: Structure to train on :param train_atoms: Index atoms to train on :param train: Train or not :return: None """ self.output.write_to_log('\nAdding atom(s) {} to the ' 'training set.\n' .format(train_atoms, )) self.output.write_to_log('Uncertainties: {}.\n' .format(frame.stds[train_atoms]), flush=True) # update gp model self.gp.update_db(frame, frame.forces, custom_range=train_atoms) if train: self.train_gp() def train_gp(self, max_iter: int = None): """ Train the Gaussian process and write the results to the output file. :param max_iter: Maximum iterations associated with this training run, overriding the Gaussian Process's internally set maxiter. :type max_iter: int """ if self.verbose >= 1: self.output.write_to_log('Train GP\n') # TODO: Improve flexibility in GP training to make this next step # unnecessary, so maxiter can be passed as an argument # Don't train if maxiter == 0 if max_iter == 0: self.gp.check_L_alpha() elif max_iter is not None: temp_maxiter = self.gp.maxiter self.gp.maxiter = max_iter self.gp.train(output=self.output if self.verbose >= 2 else None) self.gp.maxiter = temp_maxiter else: self.gp.train(output=self.output if self.verbose >= 2 else None) self.output.write_hyps(self.gp.hyp_labels, self.gp.hyps, self.start_time, self.gp.likelihood, self.gp.likelihood_gradient) self.train_count += 1
class OTF: """Trains a Gaussian process force field on the fly during molecular dynamics. Args: dft_input (str): Input file. dt (float): MD timestep. number_of_steps (int): Number of timesteps in the training simulation. gp (gp.GaussianProcess): Initial GP model. dft_loc (str): Location of DFT executable. std_tolerance_factor (float, optional): Threshold that determines when DFT is called. Specifies a multiple of the current noise hyperparameter. If the epistemic uncertainty on a force component exceeds this value, DFT is called. Defaults to 1. prev_pos_init ([type], optional): Previous positions. Defaults to None. par (bool, optional): If True, force predictions are made in parallel. Defaults to False. skip (int, optional): Number of frames that are skipped when dumping to the output file. Defaults to 0. init_atoms (List[int], optional): List of atoms from the input structure whose local environments and force components are used to train the initial GP model. If None is specified, all atoms are used to train the initial GP. Defaults to None. calculate_energy (bool, optional): If True, the energy of each frame is calculated with the GP. Defaults to False. output_name (str, optional): Name of the output file. Defaults to 'otf_run'. max_atoms_added (int, optional): Number of atoms added each time DFT is called. Defaults to 1. freeze_hyps (int, optional): Specifies the number of times the hyperparameters of the GP are optimized. After this many updates to the GP, the hyperparameters are frozen. Defaults to 10. rescale_steps (List[int], optional): List of frames for which the velocities of the atoms are rescaled. Defaults to []. rescale_temps (List[int], optional): List of rescaled temperatures. Defaults to []. dft_softwarename (str, optional): DFT code used to calculate ab initio forces during training. Defaults to "qe". no_cpus (int, optional): Number of cpus used during training. Defaults to 1. npool (int, optional): Number of k-point pools for DFT calculations. Defaults to None. mpi (str, optional): Determines how mpi is called. Defaults to "srun". dft_kwargs ([type], optional): Additional arguments which are passed when DFT is called; keyword arguments vary based on the program (e.g. ESPRESSO vs. VASP). Defaults to None. store_dft_output (Tuple[Union[str,List[str]],str], optional): After DFT calculations are called, copy the file or files specified in the first element of the tuple to a directory specified as the second element of the tuple. Useful when DFT calculations are expensive and want to be kept for later use. The first element of the tuple can either be a single file name, or a list of several. Copied files will be prepended with the date and time with the format 'Year.Month.Day:Hour:Minute:Second:'. """ def __init__(self, dft_input: str, dt: float, number_of_steps: int, gp: gp.GaussianProcess, dft_loc: str, std_tolerance_factor: float = 1, prev_pos_init: 'ndarray' = None, par: bool = False, skip: int = 0, init_atoms: List[int] = None, calculate_energy: bool = False, output_name: str = 'otf_run', max_atoms_added: int = 1, freeze_hyps: int = 10, rescale_steps: List[int] = [], rescale_temps: List[int] = [], dft_softwarename: str = "qe", no_cpus: int = 1, npool: int = None, mpi: str = "srun", dft_kwargs=None, store_dft_output: Tuple[Union[str, List[str]], str] = None): self.dft_input = dft_input self.dt = dt self.number_of_steps = number_of_steps self.gp = gp self.dft_loc = dft_loc self.std_tolerance = std_tolerance_factor self.skip = skip self.dft_step = True self.freeze_hyps = freeze_hyps self.dft_module = dft_software[dft_softwarename] # parse input file positions, species, cell, masses = \ self.dft_module.parse_dft_input(self.dft_input) _, coded_species = struc.get_unique_species(species) self.structure = struc.Structure(cell=cell, species=coded_species, positions=positions, mass_dict=masses, prev_positions=prev_pos_init, species_labels=species) self.noa = self.structure.positions.shape[0] self.atom_list = list(range(self.noa)) self.curr_step = 0 self.max_atoms_added = max_atoms_added # initialize local energies if calculate_energy: self.local_energies = np.zeros(self.noa) else: self.local_energies = None # set atom list for initial dft run if init_atoms is None: self.init_atoms = [int(n) for n in range(self.noa)] else: self.init_atoms = init_atoms self.dft_count = 0 # set pred function if not par and not calculate_energy: self.pred_func = predict.predict_on_structure elif par and not calculate_energy: self.pred_func = predict.predict_on_structure_par elif not par and calculate_energy: self.pred_func = predict.predict_on_structure_en elif par and calculate_energy: self.pred_func = predict.predict_on_structure_par_en self.par = par # set rescale attributes self.rescale_steps = rescale_steps self.rescale_temps = rescale_temps self.output = Output(output_name, always_flush=True) # set number of cpus and npool for DFT runs self.no_cpus = no_cpus self.npool = npool self.mpi = mpi self.dft_kwargs = dft_kwargs self.store_dft_output = store_dft_output def run(self): """ Performs an on-the-fly training run. """ self.output.write_header(self.gp.cutoffs, self.gp.kernel_name, self.gp.hyps, self.gp.algo, self.dt, self.number_of_steps, self.structure, self.std_tolerance) counter = 0 self.start_time = time.time() while self.curr_step < self.number_of_steps: print('curr_step:', self.curr_step) # run DFT and train initial model if first step and DFT is on if self.curr_step == 0 and self.std_tolerance != 0: # call dft and update positions self.run_dft() dft_frcs = copy.deepcopy(self.structure.forces) new_pos = md.update_positions(self.dt, self.noa, self.structure) self.update_temperature(new_pos) self.record_state() # make initial gp model and predict forces self.update_gp(self.init_atoms, dft_frcs) if (self.dft_count - 1) < self.freeze_hyps: self.train_gp() # after step 1, try predicting with GP model else: self.gp.check_L_alpha() self.pred_func(self.structure, self.gp, self.no_cpus) self.dft_step = False new_pos = md.update_positions(self.dt, self.noa, self.structure) # get max uncertainty atoms std_in_bound, target_atoms = \ is_std_in_bound(self.std_tolerance, self.gp.hyps[-1], self.structure, self.max_atoms_added) if not std_in_bound: # record GP forces self.update_temperature(new_pos) self.record_state() gp_frcs = copy.deepcopy(self.structure.forces) # run DFT and record forces self.dft_step = True self.run_dft() dft_frcs = copy.deepcopy(self.structure.forces) new_pos = md.update_positions(self.dt, self.noa, self.structure) self.update_temperature(new_pos) self.record_state() # compute mae and write to output mae = np.mean(np.abs(gp_frcs - dft_frcs)) mac = np.mean(np.abs(dft_frcs)) self.output.write_to_log('\nmean absolute error:' ' %.4f eV/A \n' % mae) self.output.write_to_log('mean absolute dft component:' ' %.4f eV/A \n' % mac) # add max uncertainty atoms to training set self.update_gp(target_atoms, dft_frcs) if (self.dft_count - 1) < self.freeze_hyps: self.train_gp() # write gp forces if counter >= self.skip and not self.dft_step: self.update_temperature(new_pos) self.record_state() counter = 0 counter += 1 self.update_positions(new_pos) self.curr_step += 1 self.output.conclude_run() def run_dft(self): """Calculates DFT forces on atoms in the current structure. If OTF has store_dft_output set, then the specified DFT files will be copied with the current date and time prepended in the format 'Year.Month.Day:Hour:Minute:Second:'. """ self.output.write_to_log('\nCalling DFT...\n') # calculate DFT forces forces = self.dft_module.run_dft_par(self.dft_input, self.structure, self.dft_loc, ncpus=self.no_cpus, npool=self.npool, mpi=self.mpi, dft_kwargs=self.dft_kwargs) self.structure.forces = forces # write wall time of DFT calculation self.dft_count += 1 self.output.write_to_log('DFT run complete.\n') time_curr = time.time() - self.start_time self.output.write_to_log('number of DFT calls: %i \n' % self.dft_count) self.output.write_to_log('wall time from start: %.2f s \n' % time_curr) # Store DFT outputs in another folder if desired # specified in self.store_dft_output if self.store_dft_output is not None: dest = self.store_dft_output[1] target_files = self.store_dft_output[0] now = datetime.now() dt_string = now.strftime("%Y.%m.%d:%H:%M:%S:") if isinstance(target_files, str): to_copy = [target_files] else: to_copy = target_files for file in to_copy: copyfile(file, dest + '/' + dt_string + file) def update_gp(self, train_atoms: List[int], dft_frcs: 'ndarray'): """Updates the current GP model. Args: train_atoms (List[int]): List of atoms whose local environments will be added to the training set. dft_frcs (np.ndarray): DFT forces on all atoms in the structure. """ self.output.write_to_log( '\nAdding atom {} to the training set.\n'.format(train_atoms)) self.output.write_to_log('Uncertainty: {}.\n'.format( self.structure.stds[train_atoms[0]])) # update gp model self.gp.update_db(self.structure, dft_frcs, custom_range=train_atoms) self.gp.set_L_alpha() def train_gp(self): """Optimizes the hyperparameters of the current GP model.""" self.gp.train(self.output) self.output.write_hyps(self.gp.hyp_labels, self.gp.hyps, self.start_time, self.gp.likelihood, self.gp.likelihood_gradient) def update_positions(self, new_pos: 'ndarray'): """Performs a Verlet update of the atomic positions. Args: new_pos (np.ndarray): Positions of atoms in the next MD frame. """ if self.curr_step in self.rescale_steps: rescale_ind = self.rescale_steps.index(self.curr_step) temp_fac = self.rescale_temps[rescale_ind] / self.temperature vel_fac = np.sqrt(temp_fac) self.structure.prev_positions = \ new_pos - self.velocities * self.dt * vel_fac else: self.structure.prev_positions = self.structure.positions self.structure.positions = new_pos self.structure.wrap_positions() def update_temperature(self, new_pos: 'ndarray'): """Updates the instantaneous temperatures of the system. Args: new_pos (np.ndarray): Positions of atoms in the next MD frame. """ KE, temperature, velocities = \ md.calculate_temperature(new_pos, self.structure, self.dt, self.noa) self.KE = KE self.temperature = temperature self.velocities = velocities def record_state(self): self.output.write_md_config(self.dt, self.curr_step, self.structure, self.temperature, self.KE, self.local_energies, self.start_time, self.dft_step, self.velocities) self.output.write_xyz_config(self.curr_step, self.structure, self.dft_step)