def test_binary_file( clear_database_before_test, # pylint: disable=unused-argument check_singlefile_content_with_store # pylint: disable=redefined-outer-name ): """Test that the constructor accepts binary files.""" byte_array = [120, 3, 255, 0, 100] content_binary = bytearray(byte_array) with tempfile.NamedTemporaryFile(mode='wb+') as handle: basename = os.path.basename(handle.name) handle.write(bytearray(content_binary)) handle.flush() handle.seek(0) node = SinglefileData(handle.name) check_singlefile_content_with_store( node=node, content_reference=content_binary, filename=basename, open_mode='rb', )
def test_construct_from_filelike(self): """Test constructing an instance from filelike instead of filepath.""" content_original = 'some testing text\nwith a newline' with tempfile.NamedTemporaryFile(mode='wb+') as handle: basename = os.path.basename(handle.name) handle.write(content_original.encode('utf-8')) handle.flush() handle.seek(0) node = SinglefileData(file=handle) with node.open() as handle: content_stored = handle.read() self.assertEqual(content_stored, content_original) self.assertEqual(node.list_object_names(), [basename]) node.store() with node.open() as handle: content_stored = handle.read() self.assertEqual(content_stored, content_original) self.assertEqual(node.list_object_names(), [basename])
def main(codelabel): """Example usage: verdi run thistest.py cp2k@localhost""" print("Testing CP2K multistage workchain on H2O") print(">>> Loading a custom protocol from file testfile.yaml") code = Code.get_from_string(codelabel) atoms = ase.build.molecule('H2O') atoms.center(vacuum=2.0) structure = StructureData(ase=atoms) thisdir = os.path.dirname(os.path.abspath(__file__)) options = { "resources": { "num_machines": 1, "num_mpiprocs_per_machine": 1, }, "max_wallclock_seconds": 1 * 3 * 60, } inputs = { 'structure': structure, 'protocol_yaml': SinglefileData(file=os.path.abspath( os.path.join(thisdir, '..', 'data', 'testfile.yaml'))), 'cp2k_base': { 'cp2k': { 'code': code, 'metadata': { 'options': options, } } } } run(Cp2kMultistageWorkChain, **inputs)
def run_ppm(self): self.report("Running PPM") inputs = {} inputs['metadata'] = {} inputs['metadata']['label'] = "hrstm_ppm" inputs['code'] = self.inputs.ppm_code inputs['parameters'] = self.inputs.ppm_params inputs['parent_calc_folder'] = self.ctx.scf_diag.outputs.remote_folder # TODO set atom types properly inputs['atomtypes'] = SinglefileData( file="/home/aiida/apps/scanning_probe/hrstm/atomtypes_2pp.ini") inputs['metadata']['options'] = { "resources": { "num_machines": 1 }, "max_wallclock_seconds": 21600, } self.report("PPM inputs: " + str(inputs)) future = self.submit(AfmCalculation, **inputs) return ToContext(ppm=future)
def parse(self, **kwargs): """ Receives in input a dictionary of retrieved nodes. Does all the logic here. """ try: output_folder = self.retrieved except NotExistent: return self.exit_codes.ERROR_NO_RETRIEVED_FOLDER output_folder_name = self.node.process_class.OUTPUT_FOLDER if output_folder_name not in output_folder._repository.list_object_names(): # pylint: disable=protected-access return self.exit_codes.ERROR_NO_OUTPUT_FILE output_parameters = {} ev_output_file = {} output_files = output_folder._repository.list_object_names(self.node.process_class.OUTPUT_FOLDER) # pylint: disable=protected-access for fname in output_files: output_abs_path = os.path.join( output_folder._repository._get_base_folder().abspath, # pylint: disable=protected-access self.node.process_class.OUTPUT_FOLDER, fname ) ev_output_file[fname[:-4]] = SinglefileData(file=output_abs_path) dict_key1 = fname[:-4].split('_')[-1] dict_key2 = fname[:-4].split('_')[-2] if dict_key1 not in output_parameters.keys(): output_parameters[dict_key1] = {} output_parameters[dict_key1][dict_key2 + '_probe'] = parse_base_output(output_abs_path) self.out('ev_output_file', ev_output_file) self.out('output_parameters', Dict(dict=output_parameters)) return ExitCode(0)
def parse(self, **kwargs): """ Parse outputs, store results in database. :returns: an exit code, if parsing fails (or nothing if parsing succeeds) """ from aiida.orm import SinglefileData output_filename = self.node.get_option('output_filename') # # Check that folder content is as expected # files_retrieved = self.retrieved.list_object_names() # files_expected = [output_filename] # # Note: set(A) <= set(B) checks whether A is a subset of B # if not set(files_expected) <= set(files_retrieved): # self.logger.error("Found files '{}', expected to find '{}'".format( # files_retrieved, files_expected)) # return self.exit_codes.ERROR_MISSING_OUTPUT_FILES # figure out which files were input input_files = [] for label in self.node.inputs: node = self.node.inputs[label] if isinstance(node, SinglefileData): input_files.append(node.filename) for filename in self.retrieved.list_object_names(): # select some output files for further parsing # logic based on file extension could go here if filename not in input_files and filename.endswith('json'): self.logger.info("Adding '{}'".format(filename)) with self.retrieved.open(filename, 'rb') as handle: output_node = SinglefileData(file=handle) self.out('files.{}'.format(os.path.splitext(filename)[0]), output_node) return ExitCode(0)
def parse(self, **kwargs): """ Parse outputs, store results in database. :returns: an exit code, if parsing fails (or nothing if parsing succeeds) """ from aiida.orm import SinglefileData output_filename = self.node.get_option('output_filename') print('output_filename (PARSER):', output_filename) # Check that folder content is as expected files_retrieved = self.retrieved.list_object_names() files_expected = [output_filename, 'md_results.json'] # Note: set(A) <= set(B) checks whether A is a subset of B # this will fail if calcuation did not converge if not set(files_expected) <= set(files_retrieved): self.logger.error("Found files '{}', expected to find '{}'".format( files_retrieved, files_expected)) return self.exit_codes.ERROR_MISSING_OUTPUT_FILES # add output file self.logger.info("Parsing '{}'".format(output_filename)) with self.retrieved.open(output_filename, 'rb') as handle: output_node = SinglefileData(file=handle) # output_node.store() # set json output md_results = json.load(self.retrieved.open('md_results.json', 'r')) md_results_node = List() md_results_node.set_list(md_results) self.out('md', output_node) self.out('md_results', md_results_node) return ExitCode(0)
def example_multistage_h2o_testfile(cp2k_code): """Example usage: verdi run thistest.py cp2k@localhost""" print("Testing CP2K multistage workchain on H2O") print(">>> Loading a custom protocol from file testfile.yaml") atoms = ase.build.molecule('H2O') atoms.center(vacuum=2.0) structure = StructureData(ase=atoms) thisdir = os.path.dirname(os.path.abspath(__file__)) # Construct process builder builder = Cp2kMultistageWorkChain.get_builder() builder.structure = structure builder.protocol_yaml = SinglefileData(file=os.path.abspath(os.path.join(thisdir, '..', 'data', 'testfile.yaml'))) builder.cp2k_base.cp2k.code = cp2k_code builder.cp2k_base.cp2k.metadata.options.resources = { "num_machines": 1, "num_mpiprocs_per_machine": 1, } builder.cp2k_base.cp2k.metadata.options.max_wallclock_seconds = 1 * 3 * 60 run(builder)
def example_precision(cp2k_code): """Test structure roundtrip precision ase->aiida->cp2k->aiida->ase""" print( "Testing structure roundtrip precision ase->aiida->cp2k->aiida->ase..." ) pwd = os.path.dirname(os.path.realpath(__file__)) # structure epsilon = 1e-10 # expected precision in Angstrom dist = 0.74 + epsilon positions = [(0, 0, 0), (0, 0, dist)] cell = np.diag([4, -4, 4 + epsilon]) atoms = ase.Atoms('H2', positions=positions, cell=cell) structure = StructureData(ase=atoms) # basis set basis_file = SinglefileData( file=os.path.join(pwd, "..", "files", "BASIS_MOLOPT")) # pseudopotentials pseudo_file = SinglefileData( file=os.path.join(pwd, "..", "files", "GTH_POTENTIALS")) # parameters parameters = Dict( dict={ 'GLOBAL': { 'RUN_TYPE': 'MD', }, 'MOTION': { 'MD': { 'TIMESTEP': 0.0, # do not move atoms 'STEPS': 1, }, }, 'FORCE_EVAL': { 'METHOD': 'Quickstep', 'DFT': { 'BASIS_SET_FILE_NAME': 'BASIS_MOLOPT', 'POTENTIAL_FILE_NAME': 'GTH_POTENTIALS', 'SCF': { 'MAX_SCF': 1, }, 'XC': { 'XC_FUNCTIONAL': { '_': 'LDA', }, }, }, 'SUBSYS': { 'KIND': { '_': 'DEFAULT', 'BASIS_SET': 'DZVP-MOLOPT-SR-GTH', 'POTENTIAL': 'GTH-LDA', }, }, }, }) # Construct process builder builder = Cp2kCalculation.get_builder() builder.structure = structure builder.parameters = parameters builder.code = cp2k_code builder.file = { 'basis': basis_file, 'pseudo': pseudo_file, } builder.metadata.options.resources = { "num_machines": 1, "num_mpiprocs_per_machine": 1, } builder.metadata.options.max_wallclock_seconds = 1 * 60 * 60 print("submitted calculation...") calc = run(builder) # check structure preservation atoms2 = calc['output_structure'].get_ase() # zeros should be preserved exactly if np.all(atoms2.positions[0] == 0.0): print("OK, zeros in structure were preserved exactly") else: print("ERROR!") print("Zeros in structure changed: ", atoms2.positions[0]) sys.exit(3) # other values should be preserved with epsilon precision dist2 = atoms2.get_distance(0, 1) if abs(dist2 - dist) < epsilon: print("OK, structure preserved with %.1e Angstrom precision" % epsilon) else: print("ERROR!") print("Structure changed by %e Angstrom" % abs(dist - dist2)) sys.exit(3) # check cell preservation cell_diff = np.amax(np.abs(atoms2.cell - cell)) if cell_diff < epsilon: print("OK, cell preserved with %.1e Angstrom precision" % epsilon) else: print("ERROR!") print("Cell changed by %e Angstrom" % cell_diff) sys.exit(3)
def example_structure_through_file(cp2k_code): """Run simple DFT calculation""" print( "Testing CP2K ENERGY on H2O (DFT). Water molecule is provided through a file input..." ) thisdir = os.path.dirname(os.path.realpath(__file__)) # structure structure = StructureData( ase=ase.io.read(os.path.join(thisdir, "..", "files", "h2o.xyz"))) # basis set basis_file = SinglefileData( file=os.path.join(thisdir, "..", "files", "BASIS_MOLOPT")) # pseudopotentials pseudo_file = SinglefileData( file=os.path.join(thisdir, "..", "files", "GTH_POTENTIALS")) # parameters 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': { 'TOPOLOGY': { 'COORD_FILE_NAME': 'water.xyz', 'COORD_FILE_FORMAT': 'XYZ' }, 'CELL': { 'ABC': '{:<15} {:<15} {:<15}'.format( *[structure.cell[i][i] for i in range(3)]), }, 'KIND': [ { '_': 'O', 'BASIS_SET': 'DZVP-MOLOPT-SR-GTH', 'POTENTIAL': 'GTH-LDA-q6' }, { '_': 'H', 'BASIS_SET': 'DZVP-MOLOPT-SR-GTH', 'POTENTIAL': 'GTH-LDA-q1' }, ], }, } }) # Construct process builder builder = cp2k_code.get_builder() builder.parameters = parameters builder.code = cp2k_code builder.file = { 'basis': basis_file, 'pseudo': pseudo_file, 'water': structure, } builder.metadata.options.resources = { "num_machines": 1, "num_mpiprocs_per_machine": 1, } builder.metadata.options.max_wallclock_seconds = 1 * 3 * 60 print("Submitted calculation...") run(builder)
def example_restart(cp2k_code): """Test CP2K restart""" print("Testing CP2K restart...") pwd = os.path.dirname(os.path.realpath(__file__)) # structure atoms1 = ase.build.molecule('H2O') atoms1.center(vacuum=2.0) structure1 = StructureData(ase=atoms1) # basis set basis_file = SinglefileData( file=os.path.join(pwd, "..", "files", "BASIS_MOLOPT")) # pseudopotentials pseudo_file = SinglefileData( file=os.path.join(pwd, "..", "files", "GTH_POTENTIALS")) # CP2K input params1 = Dict( dict={ 'GLOBAL': { 'RUN_TYPE': 'GEO_OPT', 'WALLTIME': '00:00:10', # too short }, 'MOTION': { 'GEO_OPT': { 'MAX_FORCE': 1e-20, # impossible to reach 'MAX_ITER': 100000 # run forever }, }, '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', }, 'SCF': { 'PRINT': { 'RESTART': { '_': 'ON' } } }, }, 'SUBSYS': { 'KIND': [ { '_': 'O', 'BASIS_SET': 'DZVP-MOLOPT-SR-GTH', 'POTENTIAL': 'GTH-LDA-q6' }, { '_': 'H', 'BASIS_SET': 'DZVP-MOLOPT-SR-GTH', 'POTENTIAL': 'GTH-LDA-q1' }, ], }, } }) # ------------------------------------------------------------------------------ # Construct process builder builder = Cp2kCalculation.get_builder() # Set up the first calculation builder.structure = structure1 builder.parameters = params1 builder.code = cp2k_code builder.file = { 'basis': basis_file, 'pseudo': pseudo_file, } builder.metadata.options.resources = { "num_machines": 1, "num_mpiprocs_per_machine": 1, } builder.metadata.options.max_wallclock_seconds = 1 * 2 * 60 print("submitted calculation 1:") calc1 = run(builder) # check walltime exceeded assert calc1['output_parameters'].dict.exceeded_walltime is True assert calc1['output_parameters'].dict.energy is not None assert 'output_structure' in calc1 print("OK, walltime exceeded as expected") # ------------------------------------------------------------------------------ # Set up and start the second calculation # parameters params2 = deepcopy(params1.get_dict()) del params2['GLOBAL']['WALLTIME'] del params2['MOTION']['GEO_OPT']['MAX_FORCE'] restart_wfn_fn = './parent_calc/aiida-RESTART.wfn' params2['FORCE_EVAL']['DFT']['RESTART_FILE_NAME'] = restart_wfn_fn params2['FORCE_EVAL']['DFT']['SCF']['SCF_GUESS'] = 'RESTART' params2['EXT_RESTART'] = { 'RESTART_FILE_NAME': './parent_calc/aiida-1.restart' } params2 = Dict(dict=params2) # structure atoms2 = ase.build.molecule('H2O') atoms2.center(vacuum=2.0) atoms2.positions *= 0.0 # place all atoms at origin -> nuclear fusion :-) structure2 = StructureData(ase=atoms2) # Update the process builder. builder.structure = structure2 builder.parameters = params2 builder.parent_calc_folder = calc1['remote_folder'] print("submitted calculation 2") calc2 = run(builder) # check energy expected_energy = -17.1566455959 if abs(calc2['output_parameters'].dict.energy - expected_energy) < 1e-10: print("OK, energy has the expected value") # ensure that this warning originates from overwritting coordinates output = calc2['retrieved']._repository.get_object_content('aiida.out') # pylint: disable=protected-access assert re.search("WARNING .* :: Overwriting coordinates", output)
def example_multiple_force_eval(cp2k_code): """Run DFT calculation with multiple force eval sections""" print("Testing CP2K ENERGY on H2O dimer (Mixed: DFT+MM)...") pwd = os.path.dirname(os.path.realpath(__file__)) # structure pos = [[0.934, 2.445, 1.844], [1.882, 2.227, 1.982], [0.81, 3.165, 2.479], [3.59, 2.048, 2.436], [4.352, 2.339, 1.906], [3.953, 1.304, 2.946]] atoms = ase.Atoms(symbols='OH2OH2', pbc=True, cell=[5.0, 5.0, 5.0]) atoms.set_positions(pos) structure = StructureData(ase=atoms) # basis set basis_file = SinglefileData(file=os.path.join(pwd, "..", "files", "BASIS_MOLOPT")) # pseudopotentials pseudo_file = SinglefileData(file=os.path.join(pwd, "..", "files", "GTH_POTENTIALS")) # parameters parameters = Dict( dict={ 'MULTIPLE_FORCE_EVALS': { 'FORCE_EVAL_ORDER': '2 3', 'MULTIPLE_SUBSYS': 'T', }, 'FORCE_EVAL': [ { 'METHOD': 'MIXED', 'MIXED': { 'MIXING_TYPE': 'GENMIX', 'GENERIC': { 'ERROR_LIMIT': 1.0E-10, 'MIXING_FUNCTION': 'E1+E2', 'VARIABLES': 'E1 E2', }, 'MAPPING': { 'FORCE_EVAL_MIXED': { 'FRAGMENT': [ { '_': 1, '1': '3' }, { '_': 2, '4': '6' }, ], }, 'FORCE_EVAL': [{ '_': 1, 'DEFINE_FRAGMENTS': '1 2', }, { '_': 2, 'DEFINE_FRAGMENTS': '1 2', }], } }, }, { 'METHOD': 'FIST', 'MM': { 'FORCEFIELD': { 'SPLINE': { 'EPS_SPLINE': 1.30E-5, 'EMAX_SPLINE': 0.8, }, 'CHARGE': [ { 'ATOM': 'H', 'CHARGE': 0.0, }, { 'ATOM': 'O', 'CHARGE': 0.0, }, ], 'BOND': { 'ATOMS': 'H O', 'K': 0.0, 'R0': 2.0, }, 'BEND': { 'ATOMS': 'H O H', 'K': 0.0, 'THETA0': 2.0, }, 'NONBONDED': { 'LENNARD-JONES': [ { 'ATOMS': 'H H', 'EPSILON': 0.2, 'SIGMA': 2.4, }, { 'ATOMS': 'H O', 'EPSILON': 0.4, 'SIGMA': 3.0, }, { 'ATOMS': 'O O', 'EPSILON': 0.8, 'SIGMA': 3.6, }, ] }, }, 'POISSON': { 'EWALD': { 'EWALD_TYPE': 'none', } } }, 'SUBSYS': { 'TOPOLOGY': { 'CONNECTIVITY': 'GENERATE', 'GENERATE': { 'CREATE_MOLECULES': True, } } } }, { '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' }, ], }, }, ] }) # Construct process builder builder = Cp2kCalculation.get_builder() builder.structure = structure builder.parameters = parameters builder.code = cp2k_code builder.file = { 'basis': basis_file, 'pseudo': pseudo_file, } builder.metadata.options.resources = { "num_machines": 1, "num_mpiprocs_per_machine": 1, } builder.metadata.options.max_wallclock_seconds = 1 * 3 * 60 print("Submitted calculation...") run(builder)
def example_base_workchain_widom_2(raspa_code): """Run base workchain for widom insertion calculation (1 component).""" # pylint: disable=no-member print("Testing RASPA Xenon and Krypton widom insertion through RaspaBaseWorkChain ...") parameters = Dict( dict={ "GeneralSettings": { "SimulationType": "MonteCarlo", "NumberOfCycles": 50, "PrintEvery": 10, "Forcefield": "GenericMOFs", "EwaldPrecision": 1e-6, "CutOff": 12.0, }, "System": { "tcc1rs": { "type": "Framework", "ExternalTemperature": 300.0, } }, "Component": { "krypton": { "MoleculeDefinition": "TraPPE", "WidomProbability": 1.0, "CreateNumberOfMolecules": 0, "BlockPocketsFileName": "block_tcc1rs_methane", }, "xenon": { "MoleculeDefinition": "TraPPE", "WidomProbability": 1.0, "CreateNumberOfMolecules": 0, "BlockPocketsFileName": "block_tcc1rs_xenon", }, }, }) # framework pwd = os.path.dirname(os.path.realpath(__file__)) structure = CifData(file=os.path.join(pwd, '..', 'files', 'TCC1RS.cif')) structure_label = structure.filename[:-4].lower() block_pocket_node1 = SinglefileData(file=os.path.join(pwd, '..', 'files', 'block_pocket.block')).store() block_pocket_node2 = SinglefileData(file=os.path.join(pwd, '..', 'files', 'block_pocket.block')).store() # Constructing builder builder = RaspaBaseWorkChain.get_builder() # Specifying the code builder.raspa.code = raspa_code # Specifying the framework builder.raspa.framework = { structure_label: structure, } # Specifying the input parameters builder.raspa.parameters = parameters # Specifying the block pockets builder.raspa.block_pocket = { "block_tcc1rs_methane": block_pocket_node1, "block_tcc1rs_xenon": block_pocket_node2, } # Add fixers that could handle physics-related problems. builder.fixers = { 'fixer_001': ('aiida_raspa.utils', 'check_widom_convergence', 0.1, 2000), } # Specifying the scheduler options builder.raspa.metadata.options = { "resources": { "num_machines": 1, "num_mpiprocs_per_machine": 1, }, "max_wallclock_seconds": 1 * 30 * 60, # 30 min "withmpi": False, } run(builder)
def example_geopt(cp2k_code): """Run DFT geometry optimization.""" print("Testing CP2K GEO_OPT on H2O (DFT)...") thisdir = os.path.dirname(os.path.realpath(__file__)) # Structure. structure = StructureData( ase=ase.io.read(os.path.join(thisdir, '..', "files", 'h2.xyz'))) # Basis set. basis_file = SinglefileData( file=os.path.join(thisdir, "..", "files", "BASIS_MOLOPT")) # Pseudopotentials. pseudo_file = SinglefileData( file=os.path.join(thisdir, "..", "files", "GTH_POTENTIALS")) # Parameters. parameters = Dict( dict={ 'GLOBAL': { 'RUN_TYPE': 'GEO_OPT', }, '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': { '_': 'PBE', }, }, 'POISSON': { 'PERIODIC': 'none', 'PSOLVER': 'MT', }, }, 'SUBSYS': { 'KIND': [ { '_': 'O', 'BASIS_SET': 'DZVP-MOLOPT-SR-GTH', 'POTENTIAL': 'GTH-PBE-q6' }, { '_': 'H', 'BASIS_SET': 'DZVP-MOLOPT-SR-GTH', 'POTENTIAL': 'GTH-PBE-q1' }, ], }, } }) # Construct process builder. builder = cp2k_code.get_builder() builder.structure = structure builder.parameters = parameters builder.code = cp2k_code builder.file = { 'basis': basis_file, 'pseudo': pseudo_file, } builder.metadata.options.resources = { "num_machines": 1, "num_mpiprocs_per_machine": 1, } builder.metadata.options.max_wallclock_seconds = 1 * 3 * 60 print("Submitted calculation...") calc = run(builder) # Check walltime not exceeded. assert calc['output_parameters']['exceeded_walltime'] is False # Check energy. expected_energy = -1.17212345935 if abs(calc['output_parameters']['energy'] - expected_energy) < 1e-10: print("OK, energy has the expected value.") else: print("ERROR!") print("Expected energy value: {}".format(expected_energy)) print("Actual energy value: {}".format( calc['output_parameters']['energy'])) sys.exit(3) # Check geometry. expected_dist = 0.732594809575 dist = calc['output_structure'].get_ase().get_distance(0, 1) if abs(dist - expected_dist) < 1e-7: print("OK, H-H distance has the expected value.") else: print("ERROR!") print("Expected dist value: {}".format(expected_dist)) print("Actual dist value: {}".format(dist)) sys.exit(3)
15.0, ], ] s = StructureData(cell=cell) s.append_atom(position=(0.000, 0.000, 0.000), symbols=['O']) #1 s.append_atom(position=(0.757, 0.586, 0.000), symbols=['H']) #2 s.append_atom(position=(-0.757, 0.586, 0.000), symbols=['H']) #3 s.append_atom(position=(0.000, 3.500, 0.000), symbols=['O']) #4 s.append_atom(position=(0.757, 2.914, 0.000), symbols=['H']) #5 s.append_atom(position=(-0.757, 2.914, 0.000), symbols=['H']) #6 #-------------------- Lua block # lua script absname = op.abspath( op.join(op.dirname(__file__), "../../fixtures/lua_scripts/neb.lua")) lua_script = SinglefileData(absname) # Lua input files xyz_folder = op.abspath( op.join(op.dirname(__file__), "../../fixtures/neb_data")) lua_input_files = FolderData(tree=xyz_folder) # Lua parameters lua_parameters = { 'number_of_internal_images_in_path': 5, 'neb_spring_constant': 0.45, 'neb_image_file_prefix': "image-" } # Lua retrieve list: output image files and results lua_retrieve_list = ['*.xyz', 'NEB.results']
def run_cp2k_ddec_zn_mof74(cp2k_code, ddec_code): # pylint: disable=redefined-outer-name """Run example for the DdecCp2kChargesWorkChain """ builder = Cp2kDdecWorkChain.get_builder() builder.metadata.label = 'test-MOF-74' builder.cp2k_base.cp2k.code = cp2k_code atoms = ase.build.molecule('H2O') atoms.center(vacuum=2.0) builder.cp2k_base.cp2k.structure = StructureData(ase=ase.io.read(DATA_DIR / 'Zn-MOF-74.cif')) 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, }, 'SCF': { 'MAX_SCF': 3, # limited for testing purpose }, 'XC': { 'XC_FUNCTIONAL': { '_': 'PBE', }, }, }, 'SUBSYS': { 'KIND': [ { '_': 'H', 'BASIS_SET': 'SZV-MOLOPT-SR-GTH', 'POTENTIAL': 'GTH-PBE' }, { '_': 'C', 'BASIS_SET': 'SZV-MOLOPT-SR-GTH', 'POTENTIAL': 'GTH-PBE' }, { '_': 'O', 'BASIS_SET': 'SZV-MOLOPT-SR-GTH', 'POTENTIAL': 'GTH-PBE' }, { '_': 'Zn', 'BASIS_SET': 'SZV-MOLOPT-SR-GTH', 'POTENTIAL': 'GTH-PBE' }, ], }, } } ) # 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 example_dft(cp2k_code): """Run simple DFT calculation.""" print("Testing CP2K ENERGY on H2O (DFT)...") thisdir = os.path.dirname(os.path.realpath(__file__)) # Structure. structure = StructureData(ase=ase.io.read(os.path.join(thisdir, '..', "files", 'h2o.xyz'))) # Basis set. basis_file = SinglefileData(file=os.path.join(thisdir, "..", "files", "BASIS_MOLOPT")) # Pseudopotentials. pseudo_file = SinglefileData(file=os.path.join(thisdir, "..", "files", "GTH_POTENTIALS")) # Parameters. 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' }, ], }, } }) # Construct process builder. builder = cp2k_code.get_builder() builder.structure = structure builder.parameters = parameters builder.code = cp2k_code builder.file = { 'basis': basis_file, 'pseudo': pseudo_file, } builder.metadata.options.resources = { "num_machines": 1, "num_mpiprocs_per_machine": 1, } builder.metadata.options.max_wallclock_seconds = 1 * 3 * 60 print("Submitted calculation...") run(builder)
import os from . import TEST_DIR def test_process({{cookiecutter.entry_point_prefix}}_code): """Test running a calculation note this does not test that the expected outputs are created of output parsing""" from aiida.plugins import DataFactory, CalculationFactory from aiida.engine import run # Prepare input parameters DiffParameters = DataFactory('{{cookiecutter.entry_point_prefix}}') parameters = DiffParameters({'ignore-case': True}) from aiida.orm import SinglefileData file1 = SinglefileData( file=os.path.join(TEST_DIR, "input_files", 'file1.txt')) file2 = SinglefileData( file=os.path.join(TEST_DIR, "input_files", 'file2.txt')) # set up calculation inputs = { 'code': {{cookiecutter.entry_point_prefix}}_code, 'parameters': parameters, 'file1': file1, 'file2': file2, 'metadata': { 'options': { 'max_wallclock_seconds': 30 }, }, }
def example_base_workchain_gcmc(raspa_code): """Run base workchain for GCMC calculations with 2 components.""" # pylint: disable=no-member print("Testing RASPA Xenon:Krypton GCMC through RaspaBaseWorkChain ...") parameters = Dict( dict={ "GeneralSettings": { "SimulationType": "MonteCarlo", "NumberOfCycles": 2000, "NumberOfInitializationCycles": 2000, "PrintEvery": 200, "Forcefield": "GenericMOFs", "RemoveAtomNumberCodeFromLabel": True, "EwaldPrecision": 1e-6, "CutOff": 12.0, }, "System": { "irmof_1": { "type": "Framework", "UnitCells": "1 1 1", "HeliumVoidFraction": 0.149, "ExternalTemperature": 300.0, "ExternalPressure": 1e5, } }, "Component": { "krypton": { "MoleculeDefinition": "TraPPE", "TranslationProbability": 0.5, "ReinsertionProbability": 0.5, "SwapProbability": 1.0, "BlockPocketsFileName": { "irmof_1": "irmof_1_krypton", }, }, "xenon": { "MoleculeDefinition": "TraPPE", "TranslationProbability": 0.5, "ReinsertionProbability": 0.5, "SwapProbability": 1.0, "BlockPocketsFileName": { "irmof_1": "irmof_1_xenon", }, }, }, }) # framework pwd = os.path.dirname(os.path.realpath(__file__)) structure = CifData(file=os.path.join(pwd, '..', 'files', 'IRMOF-1.cif')) structure_label = "irmof_1" block_pocket_node1 = SinglefileData( file=os.path.join(pwd, '..', 'files', 'IRMOF-1_test.block')).store() block_pocket_node2 = SinglefileData( file=os.path.join(pwd, '..', 'files', 'IRMOF-1_test.block')).store() # Constructing builder builder = RaspaBaseWorkChain.get_builder() # Specifying the code builder.raspa.code = raspa_code # Specifying the framework builder.raspa.framework = { structure_label: structure, } # Specifying the input parameters builder.raspa.parameters = parameters # Specifying the block pockets builder.raspa.block_pocket = { "irmof_1_krypton": block_pocket_node1, "irmof_1_xenon": block_pocket_node2, } # Add fixers that could handle physics-related problems. builder.fixers = { 'fixer_001': ('aiida_raspa.utils', 'check_gcmc_convergence', 0.10, 2000, 2000), } # Specifying the scheduler options builder.raspa.metadata.options = { "resources": { "num_machines": 1, "num_mpiprocs_per_machine": 1, }, "max_wallclock_seconds": 1 * 30 * 60, # 30 min "withmpi": False, } run(builder)
def example_block_pockets(raspa_code, submit=True): """Prepare and submit RASPA calculation with blocked pockets.""" # parameters parameters = Dict( dict={ "GeneralSettings": { "SimulationType": "MonteCarlo", "NumberOfCycles": 50, "NumberOfInitializationCycles": 50, "PrintEvery": 10, "Forcefield": "GenericMOFs", "RemoveAtomNumberCodeFromLabel": True, "EwaldPrecision": 1e-6, "CutOff": 12.0, }, "System": { "irmof_1": { "type": "Framework", "UnitCells": "1 1 1", "HeliumVoidFraction": 0.149, "ExternalTemperature": 300.0, "ExternalPressure": 1e5, }, "irmof_10": { "type": "Framework", "UnitCells": "1 1 1", "HeliumVoidFraction": 0.149, "ExternalTemperature": 300.0, "ExternalPressure": 1e5, } }, "Component": { "methane": { "MoleculeDefinition": "TraPPE", "TranslationProbability": 0.5, "ReinsertionProbability": 0.5, "SwapProbability": 1.0, "CreateNumberOfMolecules": { "irmof_1": 1, "irmof_10": 2, }, "BlockPocketsFileName": { "irmof_1": "irmof_1_test", "irmof_10": "irmof_10_test", }, }, "xenon": { "MoleculeDefinition": "TraPPE", "TranslationProbability": 0.5, "ReinsertionProbability": 0.5, "SwapProbability": 1.0, "CreateNumberOfMolecules": { "irmof_1": 3, "irmof_10": 4, }, "BlockPocketsFileName": { "irmof_1": "irmof_1_test", "irmof_10": "irmof_10_test", }, }, }, }) # frameworks pwd = os.path.dirname(os.path.realpath(__file__)) framework_1 = CifData(file=os.path.join(pwd, '..', 'files', 'IRMOF-1.cif')) framework_10 = CifData(file=os.path.join(pwd, '..', 'files', 'IRMOF-10.cif')) # block pocket block_pocket_1 = SinglefileData(file=os.path.join(pwd, '..', 'files', 'IRMOF-1_test.block')).store() block_pocket_10 = SinglefileData(file=os.path.join(pwd, '..', 'files', 'IRMOF-10_test.block')).store() # Contructing builder builder = raspa_code.get_builder() builder.framework = { "irmof_1": framework_1, "irmof_10": framework_10, } builder.block_pocket = { "irmof_1_test": block_pocket_1, "irmof_10_test": block_pocket_10, } builder.parameters = parameters builder.metadata.options = { "resources": { "num_machines": 1, "num_mpiprocs_per_machine": 1, }, "max_wallclock_seconds": 1 * 30 * 60, # 30 min "withmpi": False, } builder.metadata.dry_run = False builder.metadata.store_provenance = True if submit: print("Testing RASPA calculation with two frameworks each one " "containing 2 molecules (metahne/xenon) and block pockets ...") res, pk = run_get_pk(builder) print("calculation pk: ", pk) print("Average number of methane molecules/uc (irmof-1):", res['output_parameters'].dict.irmof_1['components']['methane']['loading_absolute_average']) print("Average number of methane molecules/uc (irmof-10):", res['output_parameters'].dict.irmof_1['components']['methane']['loading_absolute_average']) print("OK, calculation has completed successfully") else: print("Generating test input ...") builder.metadata.dry_run = True builder.metadata.store_provenance = False run(builder) print("Submission test successful") print("In order to actually submit, add '--submit'")
def parse(self, **kwargs): #pylint: disable=too-many-branches """ Parse output data folder, store results in database. :param retrieved: a dictionary of retrieved nodes, where the key is the link name :returns: a tuple with two values ``(bool, node_list)``, where: * ``bool``: variable to tell if the parsing succeeded * ``node_list``: list of new nodes to be stored in the db (as a list of tuples ``(link_name, node)``) """ # pylint: disable=too-many-locals # Check that the retrieved folder is there try: self.retrieved except exceptions.NotExistent: return self.exit_codes.ERROR_NO_RETRIEVED_FOLDER # Check the folder content is as expected list_of_files = self.retrieved.list_object_names() # pylint: disable=protected-access inp_params = self.node.inputs.parameters output_files = inp_params.output_files # Note: set(A) <= set(B) checks whether A is a subset of B if set(output_files) <= set(list_of_files): pass else: msg = 'Expected output files {}; found only {}.'\ .format(output_files, list_of_files) self.logger.error(msg) return self.exit_codes.ERROR_OUTPUT_FILES_MISSING # Parse output files output_parsers = inp_params.output_parsers output_links = inp_params.output_links output_parameters = Dict(dict={}) empty_block = False for fname, parser, link in list( zip(output_files, output_parsers, output_links)): with self.retrieved.open(fname, 'rb') as handle: if parser is None: # just add file, if no parser implemented parsed = SinglefileData(file=handle) self.out(link, parsed) # workaround: if block pocket file is empty, raise an error # (it indicates the calculation did not finish) if link == 'block': if not parsed.get_content().strip(): self.logger.error( 'Empty block file. This indicates the calculation of blocked pockets did not finish.' ) empty_block = True else: output_parameters.update_dict({ 'Number_of_blocking_spheres': int(parsed.get_content().split()[0]) }) else: # else parse and add keys to output_parameters try: # Note: We join it to the output_params #parsed = parser.parse_aiida(f.read()) parsed_dict = parser.parse( handle.read().decode('utf8')) except ValueError: self.logger.error( 'Error parsing file {} with parser {}'.format( fname, parser)) output_parameters.update_dict(parsed_dict) # add name of input structures as parameter output_parameters.set_attribute( 'Input_structure_filename', inp_params.get_structure_file_name(self.node.inputs.structure)) # add input parameters for convenience # note: should be added at top-level in order to allow tab completion # of <calcnode>.res.Input_... for k in inp_params.keys(): output_parameters.set_attribute('Input_{}'.format(k), inp_params.get_attribute(k)) self.out('output_parameters', output_parameters) if empty_block: return self.exit_codes.ERROR_EMPTY_BLOCK return self.exit_codes.SUCCESS
def cubegen_step(self): if not self._check_if_previous_calc_ok(self.ctx.formchk_node): return self.exit_codes.ERROR_TERMINATION # pylint: disable=no-member self.report("Running Cubegen") gout_params = dict(self.inputs.gaussian_output_params) # -------------------------------------------------------------- # Create the stencil ase_atoms = ase.Atoms(gout_params['atomnos'], positions=gout_params['atomcoords'][0]) es = self.inputs.edge_space.value + self.inputs.dx.value xmin = np.min(ase_atoms.positions[:, 0]) - es xmax = np.max(ase_atoms.positions[:, 0]) + es ymin = np.min(ase_atoms.positions[:, 1]) - es ymax = np.max(ase_atoms.positions[:, 1]) + es zmin = np.min(ase_atoms.positions[:, 2]) - es zmax = np.max(ase_atoms.positions[:, 2]) + es geom_center = np.array([xmin + xmax, ymin + ymax, zmin + zmax]) / 2.0 cell = np.array([xmax - xmin, ymax - ymin, zmax - zmin]) cell_n = (np.round(cell / self.inputs.dx.value)).astype(int) stencil = b"-1 %f %f %f\n" % tuple(geom_center - cell / 2) stencil += b"%d %f 0.0 0.0\n" % (cell_n[0], self.inputs.dx.value) stencil += b"%d 0.0 %f 0.0\n" % (cell_n[1], self.inputs.dx.value) stencil += b"%d 0.0 0.0 %f\n" % (cell_n[2], self.inputs.dx.value) # -------------------------------------------------------------- # Create the parameters dict params_dict = {} orb_indexes = list(self.inputs.orbital_indexes) abs_orb_indexes = [] if self.inputs.orbital_index_ref == 'half_num_el': total_num_electrons = sum(gout_params['num_electrons']) ref_index = total_num_electrons // 2 for i_orb in orb_indexes: abs_orb_indexes.append(i_orb + ref_index) elif self.inputs.orbital_index_ref == 'abs': abs_orb_indexes = orb_indexes # remove negative and 0 indexes abs_orb_indexes = [i for i in abs_orb_indexes if i >= 1] for i_orb in abs_orb_indexes: if self.inputs.natural_orbitals: params_dict[f"{i_orb}_no"] = { "kind": "MO=%d" % i_orb, "npts": -1, } else: homos = gout_params['homos'] # use the cubegen convention, where counting starts from 1 homos = [h + 1 for h in homos] for i_spin, h in enumerate(homos): label = self._get_orbital_label(i_orb - h) if len(homos) == 1: params_dict["%d_%s" % (i_orb, label)] = { "kind": "MO=%d" % i_orb, "npts": -1, } else: spin_letter = "a" if i_spin == 0 else "b" params_dict["%d_%s_%s" % (i_orb, spin_letter, label)] = { "kind": "%sMO=%d" % (spin_letter.upper(), i_orb), "npts": -1, } if not self.inputs.natural_orbitals: if self.inputs.generate_density: params_dict['density'] = { "kind": "Density=SCF", "npts": -1, } if self.inputs.generate_spin_density: if 'homos' in gout_params and len(gout_params['homos']) == 2: params_dict['spin'] = { "kind": "Spin=SCF", "npts": -1, } # -------------------------------------------------------------- # Create the builder and submit! builder = CubegenCalculation.get_builder() builder.parent_calc_folder = self.ctx.formchk_node.outputs.remote_folder builder.code = self.inputs.cubegen_code builder.stencil = SinglefileData(io.BytesIO(stencil)) builder.parameters = Dict(dict=params_dict) builder.retrieve_cubes = self.inputs.retrieve_cubes builder.parser_params = self.inputs.cubegen_parser_params builder.metadata.options.resources = self._set_resources() builder.metadata.options.max_wallclock_seconds = 2 * 60 * 60 builder.metadata.options.parser_name = self.inputs.cubegen_parser_name future = self.submit(builder) return ToContext(cubegen_node=future)
def example_base_restart_timeout(raspa_code): """Run base workchain for GCMC with restart after timeout.""" # pylint: disable=no-member print("Testing RaspaBaseWorkChain restart after timeout...") print( "This long simulation will require ca. 3 iterations (i.e., 2 restarts)." ) parameters = Dict( dict={ "GeneralSettings": { "SimulationType": "MonteCarlo", "NumberOfInitializationCycles": 5000, # many, to pass timeout "NumberOfCycles": 5000, # many, to pass timeout "PrintEvery": 1000, "Forcefield": "GenericMOFs", "RemoveAtomNumberCodeFromLabel": True, "ChargeMethod": "None", "CutOff": 12.0, # WriteBinaryRestartFileEvery not needed: if missing RaspaBaseWorkChain will assign a default of 1000 }, "System": { "irmof_1": { "type": "Framework", "UnitCells": "1 1 1", "ExternalTemperature": 300.0, "ExternalPressure": 1e5, } }, "Component": { "krypton": { "MoleculeDefinition": "TraPPE", "TranslationProbability": 0.5, "ReinsertionProbability": 0.5, "SwapProbability": 1.0, "BlockPocketsFileName": { "irmof_1": "irmof_1_krypton", }, }, }, }) # framework pwd = os.path.dirname(os.path.realpath(__file__)) structure = CifData(file=os.path.join(pwd, '..', 'files', 'IRMOF-1.cif')) structure_label = "irmof_1" block_pocket_node1 = SinglefileData( file=os.path.join(pwd, '..', 'files', 'IRMOF-1_test.block')).store() # Constructing builder builder = RaspaBaseWorkChain.get_builder() # Specifying the code builder.raspa.code = raspa_code # Specifying the framework builder.raspa.framework = { structure_label: structure, } # Specifying the input parameters builder.raspa.parameters = parameters # Specifying the block pockets builder.raspa.block_pocket = { "irmof_1_krypton": block_pocket_node1, } # Specifying the scheduler options builder.raspa.metadata.options = { "resources": { "num_machines": 1, "num_mpiprocs_per_machine": 1, }, "max_wallclock_seconds": 1 * 30 * 60, # 30 min "withmpi": True, "mpirun_extra_params": ["timeout", "5"], # kill the calculation after 5 seconds, to test restart } # Specify RaspaBaseWorkChain options builder.max_iterations = Int( 8 ) # number of maximum iterations: prevent for infinite restart (default: 5) run(builder)
def test_cp2k_energy_on_H2O(new_workdir, new_filedir): """Testing CP2K ENERGY on H2O (MM)""" import ase.build from aiida.engine import run from aiida.plugins import CalculationFactory from aiida.orm import Dict, SinglefileData computer = get_computer(workdir=new_workdir) code = get_code(entry_point="cp2k", computer=computer) # force field potfile_fn = path.join(new_filedir, "water.pot") with io.open(potfile_fn, mode="w", encoding="utf8") as fhandle: fhandle.write(u"""\ BONDS H H 0.000 1.5139 O H 450.000 0.9572 ANGLES H O H 55.000 104.5200 DIHEDRALS IMPROPER NONBONDED H 0.000000 -0.046000 0.224500 O 0.000000 -0.152100 1.768200 HBOND CUTHB 0.5 END""") water_pot = SinglefileData(file=potfile_fn) # pylint: disable=no-value-for-parameter # structure using pdb format, because it also carries topology information pdbfile_fn = path.join(new_filedir, "coords.pdb") atoms = ase.build.molecule("H2O") atoms.center(vacuum=10.0) atoms.write(pdbfile_fn, format="proteindatabank") coords_pdb = SinglefileData(file=pdbfile_fn) # pylint: disable=no-value-for-parameter # parameters # based on cp2k/tests/Fist/regtest-1-1/water_1.inp parameters = Dict( dict={ "FORCE_EVAL": { "METHOD": "fist", "MM": { "FORCEFIELD": { "PARM_FILE_NAME": "water.pot", "PARMTYPE": "CHM", "CHARGE": [ { "ATOM": "O", "CHARGE": -0.8476 }, { "ATOM": "H", "CHARGE": 0.4238 }, ], }, "POISSON": { "EWALD": { "EWALD_TYPE": "spme", "ALPHA": 0.44, "GMAX": 24, "O_SPLINE": 6, } }, }, "SUBSYS": { "CELL": { "ABC": "%f %f %f" % tuple(atoms.cell.diagonal()) }, "TOPOLOGY": { "COORD_FILE_NAME": "coords.pdb", "COORD_FILE_FORMAT": "PDB", }, }, }, "GLOBAL": { "CALLGRAPH": "master", "CALLGRAPH_FILE_NAME": "runtime" }, }) # settings settings = Dict(dict={"additional_retrieve_list": ["runtime.callgraph"]}) # resources options = { "resources": { "num_machines": 1, "num_mpiprocs_per_machine": 1 }, "max_wallclock_seconds": 1 * 3 * 60, # 3 minutes } # collect all inputs inputs = { "parameters": parameters, "settings": settings, "code": code, "file": { "water_pot": water_pot, "coords_pdb": coords_pdb }, "metadata": { "options": options }, } result = run(CalculationFactory("cp2k"), **inputs) # check warnings assert result["output_parameters"].dict.nwarnings == 0 # check energy expected_energy = 0.146927412614e-3 assert abs(result["output_parameters"].dict.energy - expected_energy) < 1e-10 # check if callgraph is there assert ("runtime.callgraph" in result["retrieved"]._repository.list_object_names()) # pylint: disable=protected-access
def example_no_struct(cp2k_code): """Run DFT calculation with structure specified in the input file.""" print("Testing CP2K ENERGY on H2 (DFT) without StructureData...") thisdir = os.path.dirname(os.path.realpath(__file__)) # Basis set. basis_file = SinglefileData( file=os.path.join(thisdir, "..", "files", "BASIS_MOLOPT")) # Pseudopotentials. pseudo_file = SinglefileData( file=os.path.join(thisdir, "..", "files", "GTH_POTENTIALS")) # Parameters. 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': { # structure directly included in parameters 'CELL': { 'ABC': '4.0 4.0 4.75' }, 'COORD': { ' ': [ 'H 2.0 2.0 2.737166', 'H 2.0 2.0 2.000000' ] }, 'KIND': [ { '_': 'O', 'BASIS_SET': 'DZVP-MOLOPT-SR-GTH', 'POTENTIAL': 'GTH-LDA-q6' }, { '_': 'H', 'BASIS_SET': 'DZVP-MOLOPT-SR-GTH', 'POTENTIAL': 'GTH-LDA-q1' }, ], }, } }) # Construct process builder. builder = cp2k_code.get_builder() builder.parameters = parameters builder.code = cp2k_code builder.file = { 'basis': basis_file, 'pseudo': pseudo_file, } builder.metadata.options.resources = { "num_machines": 1, "num_mpiprocs_per_machine": 1, } builder.metadata.options.max_wallclock_seconds = 1 * 3 * 60 print("Submitted calculation...") calc = run(builder) # Check energy. expected_energy = -1.14005678487 if abs(calc['output_parameters']['energy'] - expected_energy) < 1e-10: print("OK, energy has the expected value.") else: print("ERROR!") print(f"Expected energy value: {expected_energy}") print(f"Actual energy value: {calc['output_parameters']['energy']}") sys.exit(3)
def example_base(cp2k_code): """Run simple DFT calculation through a workchain""" pwd = os.path.dirname(os.path.realpath(__file__)) print("Testing CP2K ENERGY on H2O (DFT) through a workchain...") # basis set basis_file = SinglefileData( file=os.path.join(pwd, "..", "files", "BASIS_MOLOPT")) # pseudopotentials pseudo_file = SinglefileData( file=os.path.join(pwd, "..", "files", "GTH_POTENTIALS")) # structure atoms = ase.build.molecule('H2O') atoms.center(vacuum=2.0) structure = StructureData(ase=atoms) # parameters 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' }, ], }, } }) # Construct process builder builder = Cp2kBaseWorkChain.get_builder() builder.cp2k.structure = structure builder.cp2k.parameters = parameters builder.cp2k.code = cp2k_code builder.cp2k.file = { 'basis': basis_file, 'pseudo': pseudo_file, } builder.cp2k.metadata.options.resources = { "num_machines": 1, "num_mpiprocs_per_machine": 1, } builder.cp2k.metadata.options.max_wallclock_seconds = 1 * 3 * 60 print("Submitted calculation...") run(builder)
def example_ff_files(raspa_code, submit=True): """Prepare and submit RASPA calculation with components mixture.""" # parameters parameters = Dict( dict={ "GeneralSettings": { "SimulationType": "MonteCarlo", "NumberOfInitializationCycles": 200, "NumberOfCycles": 300, "PrintEvery": 100, "Forcefield": "Local", "ChargeMethod": "Ewald", "EwaldPrecision": 1e-6, "CutOff": 12.0, }, "System": { "irmof_1": { "type": "Framework", "UnitCells": "1 1 1", "HeliumVoidFraction": 0.149, "ExternalTemperature": 300.0, "ExternalPressure": 1e5, } }, "Component": { "CO2": { "MoleculeDefinition": "Local", "MolFraction": 0.30, "TranslationProbability": 1.0, "RotationProbability": 1.0, "ReinsertionProbability": 1.0, "SwapProbability": 1.0, "CreateNumberOfMolecules": 0, }, "N2": { "MoleculeDefinition": "Local", "MolFraction": 0.70, "TranslationProbability": 1.0, "RotationProbability": 1.0, "ReinsertionProbability": 1.0, "SwapProbability": 1.0, "CreateNumberOfMolecules": 0, }, }, }) # Contructing builder pwd = os.path.dirname(os.path.realpath(__file__)) builder = raspa_code.get_builder() builder.framework = { "irmof_1": CifData(file=os.path.join(pwd, '..', 'files', 'IRMOF-1_eqeq.cif')), } # Note: Here the SinglefileData in the dict are stored otherwise the dry_run crashes. # However, this is not needed for real calculations (e.g., using --submit), since the work chains stores them. builder.file = { "file_1": SinglefileData(file=os.path.join( pwd, '..', 'files', 'force_field_mixing_rules.def')).store(), "file_2": SinglefileData( file=os.path.join(pwd, '..', 'files', 'pseudo_atoms.def')).store(), "file_3": SinglefileData( file=os.path.join(pwd, '..', 'files', 'CO2.def')).store(), "file_4": SinglefileData( file=os.path.join(pwd, '..', 'files', 'N2.def')).store(), } builder.parameters = parameters builder.metadata.options = { "resources": { "num_machines": 1, "num_mpiprocs_per_machine": 1, }, "max_wallclock_seconds": 1 * 30 * 60, # 30 min "withmpi": False, } builder.metadata.dry_run = False builder.metadata.store_provenance = True if submit: print( "Testing RASPA CO2/N2 adsorption in IRMOF-1, using Local force field ..." ) res, pk = run_get_pk(builder) print("calculation pk: ", pk) print("CO2/N2 uptake ({:s}): {:.2f}/{:.2f} ".format( res['output_parameters']["irmof_1"]["components"]['N2'] ["loading_absolute_unit"], res['output_parameters']["irmof_1"]["components"]['CO2'] ["loading_absolute_average"], res['output_parameters']["irmof_1"]["components"]['N2'] ["loading_absolute_average"], )) print("OK, calculation has completed successfully") else: print("Generating test input ...") builder.metadata.dry_run = True builder.metadata.store_provenance = False run(builder) print("Submission test successful") print("In order to actually submit, add '--submit'") print("-----")
def example_base(cp2k_code): """Run simple DFT calculation through a workchain.""" thisdir = os.path.dirname(os.path.realpath(__file__)) print("Testing CP2K ENERGY on H2O (DFT) through a workchain...") # Basis set. basis_file = SinglefileData( file=os.path.join(thisdir, "..", "files", "BASIS_MOLOPT")) # Pseudopotentials. pseudo_file = SinglefileData( file=os.path.join(thisdir, "..", "files", "GTH_POTENTIALS")) # Structure. structure = StructureData( ase=ase.io.read(os.path.join(thisdir, "..", "files", "h2o.xyz"))) # Parameters. parameters = Dict( dict={ 'GLOBAL': { 'RUN_TYPE': 'GEO_OPT', 'WALLTIME': '00:00:20', # too short }, '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', }, 'SCF': { 'PRINT': { 'RESTART': { '_': 'ON' } } }, }, 'SUBSYS': { 'KIND': [ { '_': 'O', 'BASIS_SET': 'DZVP-MOLOPT-SR-GTH', 'POTENTIAL': 'GTH-LDA-q6' }, { '_': 'H', 'BASIS_SET': 'DZVP-MOLOPT-SR-GTH', 'POTENTIAL': 'GTH-LDA-q1' }, ], }, } }) # Construct process builder. builder = Cp2kBaseWorkChain.get_builder() # Switch on resubmit_unconverged_geometry disabled by default. builder.handler_overrides = Dict( dict={'resubmit_unconverged_geometry': True}) # Input structure. builder.cp2k.structure = structure builder.cp2k.parameters = parameters builder.cp2k.code = cp2k_code builder.cp2k.file = { 'basis': basis_file, 'pseudo': pseudo_file, } builder.cp2k.metadata.options.resources = { "num_machines": 1, "num_mpiprocs_per_machine": 1, } builder.cp2k.metadata.options.max_wallclock_seconds = 1 * 3 * 60 print("Submitted calculation...") calc = run(builder) if 'EXT_RESTART' in calc['final_input_parameters'].dict: print( "OK, EXT_RESTART section is present in the final_input_parameters." ) else: print( "ERROR, EXT_RESTART section is NOT present in the final_input_parameters." ) sys.exit(3)
def example_geopt(cp2k_code): """Run DFT geometry optimization""" print("Testing CP2K GEO_OPT on H2 (DFT)...") pwd = os.path.dirname(os.path.realpath(__file__)) # structure atoms = ase.build.molecule('H2') atoms.center(vacuum=2.0) structure = StructureData(ase=atoms) # basis set basis_file = SinglefileData( file=os.path.join(pwd, "..", "files", "BASIS_MOLOPT")) # pseudopotentials pseudo_file = SinglefileData( file=os.path.join(pwd, "..", "files", "GTH_POTENTIALS")) # parameters parameters = Dict( dict={ 'GLOBAL': { 'RUN_TYPE': 'GEO_OPT', }, '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' }, ], }, } }) # Construct process builder builder = Cp2kCalculation.get_builder() builder.structure = structure builder.parameters = parameters builder.code = cp2k_code builder.file = { 'basis': basis_file, 'pseudo': pseudo_file, } builder.metadata.options.resources = { "num_machines": 1, "num_mpiprocs_per_machine": 1, } builder.metadata.options.max_wallclock_seconds = 1 * 3 * 60 print("Submitted calculation...") calc = run(builder) # check walltime not exceeded assert calc['output_parameters'].dict.exceeded_walltime is False # check energy expected_energy = -1.14009973178 if abs(calc['output_parameters'].dict.energy - expected_energy) < 1e-10: print("OK, energy has the expected value") else: print("ERROR!") print("Expected energy value: {}".format(expected_energy)) print("Actual energy value: {}".format( calc['output_parameters'].dict.energy)) sys.exit(3) # check geometry expected_dist = 0.736103879818 dist = calc['output_structure'].get_ase().get_distance(0, 1) if abs(dist - expected_dist) < 1e-7: print("OK, H-H distance has the expected value") else: print("ERROR!") print("Expected dist value: {}".format(expected_dist)) print("Actual dist value: {}".format(dist)) sys.exit(3)
def example_dft_atomic_kinds(cp2k_code): """Run DFT calculation with different atomic kinds.""" print("Testing CP2K GEOP_OPT on Si with different atomic kinds (DFT)...") thisdir = os.path.dirname(os.path.realpath(__file__)) # Structure. pos = [[0., 0., 0.], [1.90598, 1.10041807, 0.77811308]] cell = [[3.81196, 0.0, 0.0], [1.90598, 3.3012541982101, 0.0], [1.90598, 1.10041806607, 3.1124523066333]] tags = [0, 1] atoms = ase.Atoms(symbols='Si2', pbc=True, cell=cell, positions=pos, tags=tags) structure = StructureData(ase=atoms) # Basis set. basis_file = SinglefileData( file=os.path.join(thisdir, "..", "files", "BASIS_MOLOPT")) # Pseudopotentials. pseudo_file = SinglefileData( file=os.path.join(thisdir, "..", "files", "GTH_POTENTIALS")) # Parameters. 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': [ { '_': 'Si', 'ELEMENT': 'Si', 'BASIS_SET': 'DZVP-MOLOPT-SR-GTH', 'POTENTIAL': 'GTH-LDA-q4' }, { '_': 'Si1', 'ELEMENT': 'Si', 'BASIS_SET': 'DZVP-MOLOPT-SR-GTH', 'POTENTIAL': 'GTH-LDA-q4' }, ], }, }, 'MOTION': { 'GEO_OPT': { 'MAX_FORCE': 1e-4, 'MAX_ITER': '3', 'OPTIMIZER': 'BFGS', 'BFGS': { 'TRUST_RADIUS': '[bohr] 0.1', }, }, }, 'GLOBAL': { 'RUN_TYPE': 'GEO_OPT', } }) # Construct process builder. builder = cp2k_code.get_builder() builder.structure = structure builder.parameters = parameters builder.code = cp2k_code builder.file = { 'basis': basis_file, 'pseudo': pseudo_file, } builder.metadata.options.resources = { "num_machines": 1, "num_mpiprocs_per_machine": 1, } builder.metadata.options.max_wallclock_seconds = 1 * 3 * 60 print("Submitted calculation...") run(builder)