def test_tree(self): aselist = [Atoms('C'), Atoms('H'), Atoms('N'), Atoms('O')] testcoll = AtomsCollection(aselist) testcoll.save_tree('test_save', 'xyz', safety_check=2) loadcoll = AtomsCollection.load_tree('test_save', 'xyz') self.assertTrue(''.join(loadcoll.all.get_chemical_formula()) == 'CHNO') # Try a custom save format def custom_save(a, path, format_string): with open(os.path.join(path, 'struct.custom'), 'w') as f: f.write(format_string.format(''.join( a.get_chemical_formula()))) def custom_load(path, marker): with open(os.path.join(path, 'struct.custom')) as f: l = f.read().strip() return Atoms(l.split(marker)[1].strip()) testcoll.save_tree('test_save', custom_save, opt_args={'format_string': 'Formula:{0}'}, safety_check=2) loadcoll = AtomsCollection.load_tree('test_save', custom_load, opt_args={'marker': ':'}) self.assertTrue(''.join(loadcoll.all.get_chemical_formula()) == 'CHNO')
def load_muairss_collection(struct, params, batch_path=''): # Output folder out_path = os.path.join(batch_path, params['out_folder']) load_formats = { 'dftb+': dftb_read_input, 'castep': castep_read_input, 'uep': uep_read_input } calcs = [s.strip().lower() for s in params['calculator'].split(',')] if 'all' in calcs: calcs = load_formats.keys() loaded = {} for cname in calcs: opt_args = {} if cname == 'uep': opt_args['atoms'] = struct calc_path = os.path.join(out_path, cname) dc = AtomsCollection.load_tree(calc_path, load_formats[cname], opt_args=opt_args, safety_check=2) loaded[cname] = dc return loaded
def load_muairss_collection(struct, params, batch_path=""): # Output folder out_path = os.path.join(batch_path, params["out_folder"]) io_formats = { "castep": ReadWriteCastep, "dftb+": ReadWriteDFTB, "uep": ReadWriteUEP, } calcs = [s.strip().lower() for s in params["calculator"].split(",")] if "all" in calcs: calcs = io_formats.keys() loaded = {} for cname in calcs: rw = io_formats[cname](params) calc_path = os.path.join(out_path, cname) dc = AtomsCollection.load_tree( calc_path, rw.read, safety_check=2, tolerant=True ) alln = len(glob.glob(calc_path + "/*")) total_structures = len(dc.structures) if total_structures == 0: return elif total_structures / alln < 0.9: print( """If more than 10% of structures could not be loaded, we advise adjusting the parameters and re-running the {0} optimisation for the structures that failed.""".format( cname ) ) loaded[cname] = dc return loaded
def load_muairss_collection(struct, params, batch_path=''): # Output folder out_path = os.path.join(batch_path, params['out_folder']) io_formats = { 'castep': ReadWriteCastep, 'dftb+': ReadWriteDFTB, 'uep': ReadWriteUEP } calcs = [s.strip().lower() for s in params['calculator'].split(',')] if 'all' in calcs: calcs = io_formats.keys() loaded = {} for cname in calcs: rw = io_formats[cname](params) calc_path = os.path.join(out_path, cname) dc = AtomsCollection.load_tree(calc_path, rw.read, safety_check=2, tolerant=True) print("If more than 10% of structures could not be loaded, \ we advise adjusting the parameters and re-running the {0} \ optimisation for the structures that failed.".format(cname)) total_structures = len(dc.structures) if total_structures == 0: return loaded[cname] = dc return loaded
def muon_vibrational_average_read(structure, calculator="castep", avgprop="hyperfine", average_T=0, average_file="averages.dat", **kwargs): # Open the structure file sname = seedname(structure) io_formats = {"castep": ReadWriteCastep, "dftb+": ReadWriteDFTB} try: displaced_coll = AtomsCollection.load_tree( sname + "_displaced", io_formats[calculator]().read, opt_args={"read_magres": True}, safety_check=2, ) except Exception: raise return mu_i = displaced_coll.info["muon_index"] displsch = displaced_coll.info["displacement_scheme"] to_avg = [] for a in displaced_coll: if avgprop == "hyperfine": to_avg.append(a.get_array("hyperfine")[mu_i]) elif avgprop == "charge": # Used mostly as test try: to_avg.append(a.get_charges()[mu_i]) except RuntimeError: raise (IOError("Could not read charges.")) to_avg = np.array(to_avg) displsch.recalc_weights(T=average_T) # New shape N = len(displaced_coll) shape = tuple([slice(N)] + [None] * (len(to_avg.shape) - 1)) weights = displsch.weights[shape] avg = np.sum(weights * to_avg, axis=0) # Print output report with open(average_file, "w") as f: avgname = { "hyperfine": "hyperfine tensor", "charge": "charge" }[avgprop] f.write(""" Quantum average of {property} calculated on {cell}. Scheme details: {scheme} Averaged value: {avg} All values, by configuration: {vals} """.format( property=avgname, cell=structure, scheme=displsch, avg=avg, vals="\n".join([ "Conf: {0} (Weight = {1})\n{2}\n".format( i, displsch.weights[i], v) for i, v in enumerate(to_avg) ]), ))
def muon_vibrational_average_read(cell_file, calculator='castep', avgprop='hyperfine', average_T=0, average_file='averages.dat', **kwargs): # Open the structure file cell = io.read(cell_file) path = os.path.split(cell_file)[0] sname = seedname(cell_file) num_atoms = len(cell) reader_function = { 'castep': read_output_castep, 'dftb+': read_output_dftbp }[calculator] displaced_coll = AtomsCollection.load_tree(sname + '_displaced', reader_function, safety_check=2, opt_args={'avgprop': avgprop}) mu_i = displaced_coll.info['muon_index'] displsch = displaced_coll.info['displacement_scheme'] to_avg = [] for a in displaced_coll: if avgprop == 'hyperfine': to_avg.append(a.get_array('hyperfine')[mu_i]) elif avgprop == 'charge': # Used mostly as test to_avg.append(a.get_charges()[mu_i]) to_avg = np.array(to_avg) displsch.recalc_weights(T=average_T) # New shape N = len(displaced_coll) shape = tuple([slice(N)] + [None] * (len(to_avg.shape) - 1)) avg = np.sum(displsch.weights[shape] * to_avg, axis=0) # Print output report with open(average_file, 'w') as f: avgname = { 'hyperfine': 'hyperfine tensor', 'charge': 'charge' }[avgprop] f.write(""" Quantum average of {property} calculated on {cell}. Scheme details: {scheme} Averaged value: {avg} All values, by configuration: {vals} """.format(property=avgname, cell=cell_file, scheme=displsch, avg=avg, vals='\n'.join([ '{0}\n{1}\n'.format(i, v) for i, v in enumerate(to_avg) ])))