def example_gdt(cp2k_code): """ Testing CP2K with the Basis Set and Pseudopotential stored in gaussian.basisset/pseudo. In this example the names of the basissets and pseudopotentials are still explicitly named in the CP2K input section. The plugin will then validate the names against the data objects passed to ensure consistency, and alter the generated CP2K input file to include the parameters contained in the specified basisset and pseudopotential objects, rather than relying on the data being present on the target node. Use this mode if you are migrating from implicitly tracked basissets and pseudos or if you you have more complicated setups (e.g. having different basissets for the same kind on different sites). """ thisdir = os.path.dirname(os.path.realpath(__file__)) # Structure. structure = StructureData( ase=ase.io.read(os.path.join(thisdir, '..', "files", 'h2o.xyz'))) # in your actual code you may want to get the basisset and pseudopotential # with a lookup in the database, here we can simply call load_data() bsets, pseudos = load_data(prefix="MY-EXPLICIT-") # in your code you will probably use something like: # bsets = [ # BasisSet.get(element="H", name="DZVP-MOLOPT-GTH") # BasisSet.get(element="O", name="DZVP-MOLOPT-SR-GTH") # ] # ... # parameters parameters = Dict( dict={ "FORCE_EVAL": { "METHOD": "Quickstep", "DFT": { "QS": { "EPS_DEFAULT": 1.0e-12, "WF_INTERPOLATION": "ps", "EXTRAPOLATION_ORDER": 3, }, "MGRID": { "NGRIDS": 4, "CUTOFF": 280, "REL_CUTOFF": 30 }, "XC": { "XC_FUNCTIONAL": { "_": "LDA" } }, "POISSON": { "PERIODIC": "none", "PSOLVER": "MT" }, }, "SUBSYS": { "KIND": [ { "_": "O", "POTENTIAL": "GTH {p.name}".format(p=pseudos["O"]), "BASIS_SET": "ORB {b.name}".format(b=bsets["O"]), }, { "_": "H", "POTENTIAL": "GTH {p.name}".format(p=pseudos["H"]), "BASIS_SET": "ORB {b.name}".format(b=bsets["H"]), }, ] }, } }) # Construct process builder. builder = cp2k_code.get_builder() builder.structure = structure builder.parameters = parameters builder.code = cp2k_code builder.metadata.options.resources = { "num_machines": 1, "num_mpiprocs_per_machine": 1, } builder.metadata.options.max_wallclock_seconds = 1 * 3 * 60 builder.basissets = bsets builder.pseudos = pseudos print("Submitted calculation...") run(builder)
0., ], [ 0., 0.5 * alat, 0.5 * alat, ], [ 0.5 * alat, 0., 0.5 * alat, ], ] #The atom positions were originally given in the "ScaledCartesian" format #but standard for aiida structures is Cartesian in Angstrom structure = StructureData(cell=cell) structure.append_atom(position=(0.000 * alat, 0.000 * alat, 0.000 * alat), symbols=['Si']) structure.append_atom(position=(0.260 * alat, 0.250 * alat, 0.250 * alat), symbols=['Si']) #The parameters parameters = Dict( dict={ 'xc-functional': 'LDA', 'xc-authors': 'CA', 'max-scfiterations': 50, 'dm-numberpulay': 4, 'dm-mixingweight': 0.3, 'dm-tolerance': 1.e-3, 'Solution-method': 'diagon',
def execute(args): """ The main execution of the script, which will run some preliminary checks on the command line arguments before passing them to the workchain and running it """ try: code = Code.get_from_string(args.codename) except NotExistent as exception: print("Execution failed: could not retrieve the code '{}'".format( args.codename)) print("Exception report: {}".format(exception)) return try: protocol = args.protocol except: print("Cannot seem to get protocol...") protocol = "standard" protocol = Str(protocol) try: structure = load_node(args.structure) except: # # Slightly distorted structure # alat = 5.430 # angstrom cell = [ [ 0.5 * alat, 0.5 * alat, 0., ], [ 0., 0.5 * alat, 0.5 * alat, ], [ 0.5 * alat, 0., 0.5 * alat, ], ] # Si # This was originally given in the "ScaledCartesian" format # structure = StructureData(cell=cell) structure.append_atom(position=(0.000 * alat, 0.000 * alat, 0.000 * alat), symbols=['Si']) structure.append_atom(position=(0.250 * alat, 0.245 * alat, 0.250 * alat), symbols=['Si']) #print "Execution failed: failed to load the node for the given structure pk '{}'".format(args.structure) #print "Exception report: {}".format(exception) #return if not isinstance(structure, StructureData): print( "The provided pk {} for the structure does not correspond to StructureData, aborting..." .format(args.parent_calc)) return run(SiestaBandsWorkChain, code=code, structure=structure, protocol=protocol)
def _parse_trajectory(self): """Abinit trajectory parser.""" def _voigt_to_tensor(voigt): tensor = np.zeros((3, 3)) tensor[0, 0] = voigt[0] tensor[1, 1] = voigt[1] tensor[2, 2] = voigt[2] tensor[1, 2] = voigt[3] tensor[0, 2] = voigt[4] tensor[0, 1] = voigt[5] tensor[2, 1] = tensor[1, 2] tensor[2, 0] = tensor[0, 2] tensor[1, 0] = tensor[0, 1] return tensor # Absolute path of the folder in which aiidao_GSR.nc is stored path = self.node.get_remote_workdir() # HIST Abinit NetCDF file - Default name is aiidao_HIST.nc fname = self.node.get_attribute('output_hist') if fname not in self.retrieved.list_object_names(): return self.exit_codes.ERROR_MISSING_OUTPUT_FILES with HistFile(path + '/' + fname) as hf: structures = hf.structures output_structure = StructureData(pymatgen=structures[-1]) with nc.Dataset(path + '/' + fname, 'r') as ds: # pylint: disable=no-member n_steps = ds.dimensions['time'].size energy_ha = ds.variables['etotal'][:].data # Ha energy_kin_ha = ds.variables['ekin'][:].data # Ha forces_cart_ha_bohr = ds.variables[ 'fcart'][:, :, :].data # Ha/bohr positions_cart_bohr = ds.variables['xcart'][:, :, :].data # bohr stress_voigt = ds.variables['strten'][:, :].data # Ha/bohr^3 stepids = np.arange(n_steps) symbols = np.array([specie.symbol for specie in structures[0].species], dtype='<U2') cells = np.array( [structure.lattice.matrix for structure in structures]).reshape( (n_steps, 3, 3)) energy = energy_ha * units.Ha_to_eV energy_kin = energy_kin_ha * units.Ha_to_eV forces = forces_cart_ha_bohr * units.Ha_to_eV / units.bohr_to_ang positions = positions_cart_bohr * units.bohr_to_ang stress = np.array([_voigt_to_tensor(sv) for sv in stress_voigt ]) * units.Ha_to_eV / units.bohr_to_ang**3 total_force = np.array([np.sum(f) for f in forces_cart_ha_bohr ]) * units.Ha_to_eV / units.bohr_to_ang output_trajectory = TrajectoryData() output_trajectory.set_trajectory(stepids=stepids, cells=cells, symbols=symbols, positions=positions) output_trajectory.set_array("energy", energy) # eV output_trajectory.set_array("energy_kin", energy_kin) # eV output_trajectory.set_array("forces", forces) # eV/angstrom output_trajectory.set_array("stress", stress) # eV/angstrom^3 output_trajectory.set_array("total_force", total_force) # eV/angstrom self.out("output_trajectory", output_trajectory) self.out("output_structure", output_structure)
# Fe BCC cell = [ [2.848116, 0.000000, 0.000000], [0.000000, 2.848116, 0.000000], [0.000000, 0.000000, 2.848116], ] scaled_positions = [ (0.0000000, 0.0000000, 0.0000000), (0.5000000, 0.5000000, 0.5000000), ] symbols = ["Fe", "Fe"] structure = StructureData(cell=cell) positions = np.dot(scaled_positions, cell) for i, scaled_position in enumerate(scaled_positions): structure.append_atom(position=np.dot(scaled_position, cell).tolist(), symbols=symbols[i]) structure.store() with open("Fe_mm.eam.fs") as handle: eam_data = {"type": "fs", "file_contents": handle.readlines()} potential = {"pair_style": "eam", "data": eam_data} lammps_machine = { "num_machines": 1,
def run_cp2k_ddec_h2o(cp2k_code, ddec_code): # pylint: disable=redefined-outer-name """Run example for the DdecCp2kChargesWorkChain """ print('Testing CP2K ENERGY calculation + DDEC on H2O...') builder = Cp2kDdecWorkChain.get_builder() builder.metadata.label = 'test-h2o' builder.cp2k_base.cp2k.code = cp2k_code atoms = ase.build.molecule('H2O') atoms.center(vacuum=2.0) builder.cp2k_base.cp2k.structure = StructureData(ase=atoms) builder.cp2k_base.cp2k.metadata.options.resources = { 'num_machines': 1, 'num_mpiprocs_per_machine': 1, } builder.cp2k_base.cp2k.metadata.options.withmpi = False builder.cp2k_base.cp2k.metadata.options.max_wallclock_seconds = 10 * 60 builder.cp2k_base.cp2k.parameters = Dict( dict={ 'FORCE_EVAL': { 'METHOD': 'Quickstep', 'DFT': { 'BASIS_SET_FILE_NAME': 'BASIS_MOLOPT', 'POTENTIAL_FILE_NAME': 'GTH_POTENTIALS', 'QS': { 'EPS_DEFAULT': 1.0e-12, 'WF_INTERPOLATION': 'ps', 'EXTRAPOLATION_ORDER': 3, }, 'MGRID': { 'NGRIDS': 4, 'CUTOFF': 280, 'REL_CUTOFF': 30, }, 'XC': { 'XC_FUNCTIONAL': { '_': 'LDA', }, }, 'POISSON': { 'PERIODIC': 'none', 'PSOLVER': 'MT', }, }, 'SUBSYS': { 'KIND': [ { '_': 'O', 'BASIS_SET': 'DZVP-MOLOPT-SR-GTH', 'POTENTIAL': 'GTH-LDA-q6' }, { '_': 'H', 'BASIS_SET': 'DZVP-MOLOPT-SR-GTH', 'POTENTIAL': 'GTH-LDA-q1' }, ], }, } }) # The following is not needed, if the files are available in the data directory of your CP2K executable cp2k_dir = DATA_DIR / 'cp2k' builder.cp2k_base.cp2k.file = { 'basis': SinglefileData(file=str(cp2k_dir / 'BASIS_MOLOPT')), 'pseudo': SinglefileData(file=str(cp2k_dir / 'GTH_POTENTIALS')), } builder.ddec.code = ddec_code builder.ddec.parameters = Dict( dict={ 'net charge': 0.0, 'charge type': 'DDEC6', 'periodicity along A, B, and C vectors': [True, True, True], 'compute BOs': False, 'input filename': 'valence_density', }) builder.ddec.metadata.options.max_wallclock_seconds = 10 * 60 results = engine.run(builder) assert 'structure_ddec' in results, results
def resize_unit_cell(struct, resize): """Resize the StructureData according to the resize Dict""" resize_tuple = tuple([resize[x] for x in ['nx', 'ny', 'nz']]) return StructureData(ase=struct.get_ase().repeat(resize_tuple))
def example(gaussian_code, formchk_code, cubegen_code): # geometry ase_geom = ase.io.read("./p-quinodimethane.xyz") ase_geom.cell = np.diag([10.0, 10.0, 10.0]) struct_node = StructureData(ase=ase_geom) # Run Gaussian calculation num_cores = 2 memory_mb = 500 builder = GaussianCalculation.get_builder() builder.code = gaussian_code builder.structure = struct_node builder.parameters = Dict( dict={ 'link0_parameters': { '%chk': 'aiida.chk', '%mem': "%dMB" % memory_mb, '%nprocshared': str(num_cores), }, 'functional': 'UB3LYP', 'basis_set': '6-31g', 'charge': 0, 'multiplicity': 1, 'route_parameters': { 'scf': { 'cdiis': None, }, 'guess': 'mix', 'nosymm': None, 'sp': None, }, }) builder.metadata.options.resources = { "tot_num_mpiprocs": num_cores, "num_machines": 1, } # Should ask for extra +25% extra memory builder.metadata.options.max_memory_kb = int(1.25 * memory_mb) * 1024 builder.metadata.options.max_wallclock_seconds = 5 * 60 res, calc_node = run_get_node(builder) # Run cubes workchain _, wc_node = run_get_node( GaussianCubesWorkChain, formchk_code=formchk_code, cubegen_code=cubegen_code, gaussian_calc_folder=calc_node.outputs.remote_folder, gaussian_output_params=res['output_parameters'], orbital_indexes=List(list=[0, 1]), dx=Float(0.2), edge_space=Float(2.5), retrieve_cubes=Bool(False), ) assert wc_node.is_finished_ok # Plot cube planes res = wc_node.outputs['cube_planes_array'] h_arr = res.get_array('h_arr') for aname in res.get_arraynames(): if aname.startswith("cube_"): h = h_arr[0] data = res.get_array(aname)[:, :, 0].T amax = np.max(np.abs(data)) plt.imshow(data, vmin=-amax, vmax=amax, cmap='seismic') plt.axis('off') filename = f"./{aname}_h{h:.1f}.png" plt.savefig(filename, dpi=200, bbox_inches='tight') plt.close() print("Saved %s!" % filename)
# Codenames for pw.x, pw2wannier90.x, projwfc.x and wannier90.x # Please modify these according to your machine pw_code = Code.get_from_string("<CODE LABEL>") # e.g. 'qe-6.5-pw@localhost' pw2wan_code = Code.get_from_string( "<CODE LABEL>") # e.g. 'qe-6.5-pw2wannier90@localhost' projwfc_code = Code.get_from_string( "<CODE LABEL>") # e.g. 'qe-6.5-projwfc@localhost' wan_code = Code.get_from_string( "<CODE LABEL>") # e.g. 'wannier90-3.1.0-wannier@localhost' # The 1st commandline argument specifies the structure to be calculated xsf_file = sys.argv[1] # e.g. 'CsH.xsf' # Read xsf file and convert into a stored StructureData structure = StructureData(ase=aseread(xsf_file)) # Prepare the builder to launch the workchain builder = Wannier90BandsWorkChain.get_builder() builder.structure = structure builder.code = { 'pw': pw_code, 'pw2wannier90': pw2wan_code, 'projwfc': projwfc_code, 'wannier90': wan_code } # For this tutorial, we are using the 'testing' protocol, # with all cutoffs halved, to speed up the simulations builder.protocol = Dict(dict={'name': 'testing'}) # Flags to control the workchain behaviour builder.controls = {
def create_structure_data(): """Create StructureData object.""" alat = 4. # angstrom cell = [ [ alat, 0., 0., ], [ 0., alat, 0., ], [ 0., 0., alat, ], ] # BaTiO3 cubic structure struc = StructureData(cell=cell) struc.append_atom(position=(0., 0., 0.), symbols='Ba') struc.append_atom(position=(alat / 2., alat / 2., alat / 2.), symbols='Ti') struc.append_atom(position=(alat / 2., alat / 2., 0.), symbols='O') struc.append_atom(position=(alat / 2., 0., alat / 2.), symbols='O') struc.append_atom(position=(0., alat / 2., alat / 2.), symbols='O') struc.store() # Create 2 groups and add the data to one of them g_ne = Group(label='non_empty_group') g_ne.store() g_ne.add_nodes(struc) g_e = Group(label='empty_group') g_e.store() return { DummyVerdiDataListable.NODE_ID_STR: struc.id, DummyVerdiDataListable.NON_EMPTY_GROUP_ID_STR: g_ne.id, DummyVerdiDataListable.EMPTY_GROUP_ID_STR: g_e.id }
def create_structure_bands(): """Create bands structure object.""" alat = 4. # angstrom cell = [ [ alat, 0., 0., ], [ 0., alat, 0., ], [ 0., 0., alat, ], ] strct = StructureData(cell=cell) strct.append_atom(position=(0., 0., 0.), symbols='Fe') strct.append_atom(position=(alat / 2., alat / 2., alat / 2.), symbols='O') strct.store() @calcfunction def connect_structure_bands(strct): # pylint: disable=unused-argument alat = 4. cell = np.array([ [alat, 0., 0.], [0., alat, 0.], [0., 0., alat], ]) kpnts = KpointsData() kpnts.set_cell(cell) kpnts.set_kpoints([[0., 0., 0.], [0.1, 0.1, 0.1]]) bands = BandsData() bands.set_kpointsdata(kpnts) bands.set_bands([[1.0, 2.0], [3.0, 4.0]]) return bands bands = connect_structure_bands(strct) bands_isolated = BandsData() bands_isolated.store() # Create 2 groups and add the data to one of them g_ne = Group(label='non_empty_group') g_ne.store() g_ne.add_nodes(bands) g_ne.add_nodes(bands_isolated) g_e = Group(label='empty_group') g_e.store() return { DummyVerdiDataListable.NODE_ID_STR: bands.id, DummyVerdiDataListable.NON_EMPTY_GROUP_ID_STR: g_ne.id, DummyVerdiDataListable.EMPTY_GROUP_ID_STR: g_e.id }