def run_afms(self):
     self.report("Running PP")
     
     afm_pp_inputs = {}
     afm_pp_inputs['_label'] = "afm_pp"
     afm_pp_inputs['code'] = self.inputs.afm_pp_code
     afm_pp_inputs['parameters'] = self.inputs.afm_pp_params
     afm_pp_inputs['parent_calc_folder'] = self.ctx.scf_diag.out.remote_folder
     afm_pp_inputs['atomtypes'] = SinglefileData(file="/project/apps/scanning_probe/afm/atomtypes_pp.ini")
     afm_pp_inputs['_options'] = {
         "resources": {"num_machines": 1},
         "max_wallclock_seconds": 7200,
     }
     self.report("Afm pp inputs: " + str(afm_pp_inputs))
     afm_pp_future = submit(AfmCalculation.process(), **afm_pp_inputs)
     self.to_context(afm_pp=Calc(afm_pp_future))
     
     self.report("Running 2PP")
     
     afm_2pp_inputs = {}
     afm_2pp_inputs['_label'] = "afm_2pp"
     afm_2pp_inputs['code'] = self.inputs.afm_2pp_code
     afm_2pp_inputs['parameters'] = self.inputs.afm_2pp_params
     afm_2pp_inputs['parent_calc_folder'] = self.ctx.scf_diag.out.remote_folder
     afm_2pp_inputs['atomtypes'] = SinglefileData(file="/project/apps/scanning_probe/afm/atomtypes_2pp.ini")
     afm_2pp_inputs['_options'] = {
         "resources": {"num_machines": 1},
         "max_wallclock_seconds": 7200,
     }
     self.report("Afm 2pp inputs: " + str(afm_2pp_inputs))
     afm_2pp_future = submit(AfmCalculation.process(), **afm_2pp_inputs)
     self.to_context(afm_2pp=Calc(afm_2pp_future))
예제 #2
0
def test_process_with_external(new_database, new_workdir):
    """Test running a calculation
    note this does not test parsing of the output"""
    from aiida.orm.data.singlefile import SinglefileData

    # get code
    code = get_basic_code(new_workdir)

    # Prepare input parameters
    infile = SinglefileData(
        file=os.path.join(TEST_DIR, "input_files",
                          'mgo_sto3g_external.crystal.d12'))
    ingui = SinglefileData(
        file=os.path.join(TEST_DIR, "input_files",
                          'mgo_sto3g_external.crystal.gui'))

    # set up calculation
    calc = code.new_calc()
    # calc.label = "aiida_crystal17 test"
    # calc.description = "Test job submission with the aiida_crystal17 plugin"
    # calc.set_max_wallclock_seconds(30)
    calc.set_withmpi(False)
    calc.set_resources({"num_machines": 1, "num_mpiprocs_per_machine": 1})

    calc.use_input_file(infile)
    calc.use_input_external(ingui)

    calc.store_all()

    # test process execution
    tests.test_calculation_execution(
        calc,
        check_paths=[calc._DEFAULT_OUTPUT_FILE, calc._DEFAULT_EXTERNAL_FILE])
    def test_submit(self):
        """Test submitting a calculation"""
        from aiida.orm.data.singlefile import SinglefileData

        code = self.code

        # Prepare input parameters
        from aiida.orm import DataFactory
        DiffParameters = DataFactory('plumed')
        parameters = DiffParameters({'ignore-case': True})

        file1 = SinglefileData(file=os.path.join(tests.TEST_DIR, 'file1.txt'))
        file2 = SinglefileData(file=os.path.join(tests.TEST_DIR, 'file2.txt'))

        # set up calculation
        calc = code.new_calc()
        calc.label = "aiida_plumed test"
        calc.description = "Test job submission with the aiida_plumed plugin"
        calc.set_max_wallclock_seconds(30)
        calc.set_withmpi(False)
        calc.set_resources({"num_machines": 1, "num_mpiprocs_per_machine": 1})

        calc.use_parameters(parameters)
        calc.use_file1(file1)
        calc.use_file2(file2)

        calc.store_all()
        calc.submit()
        print("submitted calculation; calc=Calculation(uuid='{}') # ID={}"\
                .format(calc.uuid,calc.dbnode.pk))
예제 #4
0
 def mk_aiida_file(cls, atoms, name):
     tmpdir = tempfile.mkdtemp()
     atoms_file_name = tmpdir + "/" + name
     atoms.write(atoms_file_name)
     atoms_aiida_f = SinglefileData(file=atoms_file_name)
     shutil.rmtree(tmpdir)
     return atoms_aiida_f
예제 #5
0
    def mk_coord_files(cls, atoms, first_slab_atom):
        mol = atoms[:first_slab_atom - 1]

        tmpdir = tempfile.mkdtemp()
        molslab_fn = tmpdir + '/mol_on_slab.xyz'
        mol_fn = tmpdir + '/mol.xyz'

        atoms.write(molslab_fn)
        mol.write(mol_fn)

        molslab_f = SinglefileData(file=molslab_fn)
        mol_f = SinglefileData(file=mol_fn)

        shutil.rmtree(tmpdir)

        return molslab_f, mol_f
예제 #6
0
    def make_geom_file(cls, atoms, filename, spin_guess=None):
        # spin_guess = [[spin_up_indexes], [spin_down_indexes]]
        tmpdir = tempfile.mkdtemp()
        file_path = tmpdir + "/" + filename

        orig_file = BytesIO()
        atoms.write(orig_file, format='xyz')
        orig_file.seek(0)
        all_lines = orig_file.readlines()
        comment = all_lines[1]  # with newline character!
        orig_lines = all_lines[2:]

        modif_lines = []
        for i_line, line in enumerate(orig_lines):
            new_line = line
            lsp = line.split()
            if spin_guess is not None:
                if i_line in spin_guess[0]:
                    new_line = lsp[0] + "1 " + " ".join(lsp[1:]) + "\n"
                if i_line in spin_guess[1]:
                    new_line = lsp[0] + "2 " + " ".join(lsp[1:]) + "\n"
            modif_lines.append(new_line)

        final_str = "%d\n%s" % (len(atoms), comment) + "".join(modif_lines)

        with open(file_path, 'w') as f:
            f.write(final_str)
        aiida_f = SinglefileData(file=file_path)
        shutil.rmtree(tmpdir)
        return aiida_f
예제 #7
0
def test_submit(new_database, new_workdir):
    """Test submitting a calculation"""
    from aiida.orm.data.singlefile import SinglefileData
    from aiida.common.folders import SandboxFolder

    code = get_basic_code(new_workdir)

    # Prepare input parameters
    infile = SinglefileData(
        file=os.path.join(TEST_DIR, "input_files",
                          'mgo_sto3g_scf.crystal.d12'))

    # set up calculation
    calc = code.new_calc()
    # calc.label = "aiida_crystal17 test"
    # calc.description = "Test job submission with the aiida_crystal17 plugin"
    # calc.set_max_wallclock_seconds(30)
    calc.set_withmpi(False)
    calc.set_resources({"num_machines": 1, "num_mpiprocs_per_machine": 1})

    calc.use_input_file(infile)

    calc.store_all()

    # output input files and scripts to temporary folder
    with SandboxFolder() as folder:
        subfolder, script_filename = calc.submit_test(folder=folder)
        print("inputs created successfully at {}".format(subfolder.abspath))
예제 #8
0
    def setUp(self):
        """Sets up a few nodes to play around with."""
        from aiida.orm.data.singlefile import SinglefileData
        import tempfile

        file_content = '''file-with-contents'''

        with tempfile.NamedTemporaryFile() as f:
            f.write(file_content)
            f.flush()
            node = SinglefileData(file=f.name)
            node.store()

        self.node = node
        self.file_content = file_content

        self.runner = CliRunner()
예제 #9
0
    def build_calc_inputs(cls, structure, code, num_machines, wavefunction,
                          remote_calc_folder, gasphase):

        inputs = {}
        if gasphase:
            inputs['_label'] = "ft_ene_gas"
        else:
            inputs['_label'] = "ft_ene"
        inputs['code'] = code
        inputs['file'] = {}

        # write the xyz structure file
        tmpdir = tempfile.mkdtemp()

        atoms = structure.get_ase()  # slow
        slab = atoms[-1568:]
        mol = atoms[:-1568]

        molslab_fn = tmpdir + '/mol_on_slab.xyz'
        if gasphase:
            mol.write(molslab_fn)
        else:
            atoms.write(molslab_fn)

        molslab_f = SinglefileData(file=molslab_fn)
        inputs['file']['molslab_coords'] = molslab_f

        shutil.rmtree(tmpdir)

        # parameters
        cell_abc = "%f  %f  %f" % (atoms.cell[0, 0], atoms.cell[1, 1],
                                   atoms.cell[2, 2])

        walltime = 86000

        inp = cls.get_cp2k_input(cell_abc, wavefunction, walltime * 0.97)

        if remote_calc_folder is not None:
            inp['EXT_RESTART'] = {
                'RESTART_FILE_NAME': './parent_calc/aiida-1.restart'
            }
            inputs['parent_folder'] = remote_calc_folder

        inputs['parameters'] = ParameterData(dict=inp)

        # settings
        settings = ParameterData(dict={'additional_retrieve_list': ['*.xyz']})
        inputs['settings'] = settings

        # resources
        inputs['_options'] = {
            "resources": {
                "num_machines": num_machines
            },
            "max_wallclock_seconds": walltime,
        }

        return inputs
예제 #10
0
    def parse_with_retrieved(self, retrieved):
        """
        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)``)
        """
        from aiida.orm.data.singlefile import SinglefileData
        success = False
        node_list = []

        # Check that the retrieved folder is there
        try:
            out_folder = retrieved['retrieved']
        except KeyError:
            self.logger.error("No retrieved folder found")
            return success, node_list

        # Check the folder content is as expected
        list_of_files = out_folder.get_folder_list()
        output_files = self._calc.inp.parameters.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:
            self.logger.error(
                "Not all expected output files {} were found".format(
                    output_files))
            return success, node_list

        # Parse output files
        output_parsers = self._calc.inp.parameters.output_parsers
        output_links = self._calc.inp.parameters.output_links
        for fname, parser, link in list(
                zip(output_files, output_parsers, output_links)):

            if parser is None:
                parsed = SinglefileData(file=out_folder.get_abs_path(fname))

            else:
                try:
                    with open(out_folder.get_abs_path(fname)) as f:
                        parsed = parser.parse_aiida(f.read())
                except ValueError:
                    self.logger.error(
                        "Error parsing file {} with parser {}".format(
                            fname, parser))

            node_list.append((link, parsed))

        success = True
        return success, node_list
    def build_cp2k_inputs(cls, structure, cell, code,
                          mgrid_cutoff, wfn_file_path, elpa_switch):

        inputs = {}
        inputs['_label'] = "scf_diag"
        inputs['code'] = code
        inputs['file'] = {}

        atoms = structure.get_ase()  # slow

        # structure
        tmpdir = tempfile.mkdtemp()
        geom_fn = tmpdir + '/geom.xyz'
        atoms.write(geom_fn)
        geom_f = SinglefileData(file=geom_fn)
        shutil.rmtree(tmpdir)

        inputs['file']['geom_coords'] = geom_f
        
        cell_array = cell.get_array('cell')

        # parameters
        cell_abc = "%f  %f  %f" % (cell_array[0],
                                   cell_array[1],
                                   cell_array[2])
        num_machines = 12
        if len(atoms) > 500:
            num_machines = 27
        walltime = 72000
        
        wfn_file = ""
        if wfn_file_path != "":
            wfn_file = os.path.basename(wfn_file_path.value)

        inp = cls.get_cp2k_input(cell_abc,
                                 mgrid_cutoff,
                                 walltime*0.97,
                                 wfn_file,
                                 elpa_switch,
                                 atoms)

        inputs['parameters'] = ParameterData(dict=inp)

        # settings
        #settings = ParameterData(dict={'additional_retrieve_list': ['aiida-RESTART.wfn', 'BASIS_MOLOPT', 'aiida.inp']})
        #inputs['settings'] = settings

        # resources
        inputs['_options'] = {
            "resources": {"num_machines": num_machines},
            "max_wallclock_seconds": walltime,
            "append_text": ur"cp $CP2K_DATA_DIR/BASIS_MOLOPT .",
        }
        if wfn_file_path != "":
            inputs['_options']["prepend_text"] = ur"cp %s ." % wfn_file_path
        
        return inputs
예제 #12
0
    def build_calc_inputs(cls,
                          structure,
                          code,
                          max_force,
                          mgrid_cutoff,
                          vdw_switch,
                          fixed_atoms,
                          remote_calc_folder=None):

        inputs = {}
        inputs['_label'] = "slab_geo_opt"
        inputs['code'] = code
        inputs['file'] = {}

        # make sure we're really dealing with a gold slab
        atoms = structure.get_ase()  # slow

        # structure
        tmpdir = tempfile.mkdtemp()
        mol_fn = tmpdir + '/mol.xyz'
        atoms.write(mol_fn)
        mol_f = SinglefileData(file=mol_fn)
        shutil.rmtree(tmpdir)

        inputs['file']['mol_coords'] = mol_f

        # parameters
        cell_abc = "%f  %f  %f" % (atoms.cell[0, 0], atoms.cell[1, 1],
                                   atoms.cell[2, 2])

        num_machines = int(np.round(1. + len(atoms) / 120.))
        walltime = 86000

        inp = cls.get_cp2k_input(cell_abc, max_force, mgrid_cutoff, vdw_switch,
                                 fixed_atoms, walltime * 0.97)

        if remote_calc_folder is not None:
            inp['EXT_RESTART'] = {
                'RESTART_FILE_NAME': './parent_calc/aiida-1.restart'
            }
            inputs['parent_folder'] = remote_calc_folder

        inputs['parameters'] = ParameterData(dict=inp)

        # settings
        settings = ParameterData(dict={'additional_retrieve_list': ['*.pdb']})
        inputs['settings'] = settings

        # resources
        inputs['_options'] = {
            "resources": {
                "num_machines": num_machines
            },
            "max_wallclock_seconds": walltime,
        }

        return inputs
    def build_mol_cp2k_inputs(cls, structure, code, mgrid_cutoff, elpa_switch):

        inputs = {}
        inputs['_label'] = "mol_scf"
        inputs['code'] = code
        inputs['file'] = {}

        atoms = structure.get_ase()  # slow

        # structure
        tmpdir = tempfile.mkdtemp()
        geom_fn = tmpdir + '/geom.xyz'
        atoms.write(geom_fn)
        geom_f = SinglefileData(file=geom_fn)
        shutil.rmtree(tmpdir)

        inputs['file']['geom_coords'] = geom_f

        # parameters
        cell_abc = "%f  %f  %f" % (atoms.cell[0, 0], atoms.cell[1, 1],
                                   atoms.cell[2, 2])
        num_machines = 6
        if len(atoms) > 150:
            num_machines = 12
        walltime = 72000

        inp = cls.get_cp2k_input(cell_abc, mgrid_cutoff, walltime * 0.97, "",
                                 elpa_switch, atoms)

        inputs['parameters'] = ParameterData(dict=inp)

        # settings
        #settings = ParameterData(dict={'additional_retrieve_list': ['aiida-RESTART.wfn', 'BASIS_MOLOPT', 'aiida.inp']})
        #inputs['settings'] = settings

        # resources
        inputs['_options'] = {
            "resources": {
                "num_machines": num_machines
            },
            "max_wallclock_seconds": walltime,
            "append_text": ur"cp $CP2K_DATA_DIR/BASIS_MOLOPT .",
        }

        return inputs
예제 #14
0
    def parse_with_retrieved(self, retrieved):
        """
        Parse outputs, 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)``)
        """
        from aiida.orm.data.singlefile import SinglefileData
        success = False
        node_list = []

        # Check that the retrieved folder is there
        try:
            out_folder = retrieved[self._calc._get_linkname_retrieved()]
        except KeyError:
            self.logger.error("No retrieved folder found")
            return success, node_list

        # Check the folder content is as expected
        list_of_files = out_folder.get_folder_list()
        output_files = [self._calc._OUTPUT_FILE_NAME]
        output_links = ['{{cookiecutter.entry_point_prefix}}']
        # Note: set(A) <= set(B) checks whether A is a subset
        if set(output_files) <= set(list_of_files):
            pass
        else:
            self.logger.error(
                "Not all expected output files {} were found".format(
                    output_files))

        # Use something like this to loop over multiple output files
        for fname, link in zip(output_files, output_links):

            node = SinglefileData(file=out_folder.get_abs_path(fname))
            node_list.append((link, node))

        success = True
        return success, node_list
    def run_ppm(self):
        self.report("Running PPM")

        inputs = {}
        inputs['_label'] = "hrstm_ppm"
        inputs['code'] = self.inputs.ppm_code
        inputs['parameters'] = self.inputs.ppm_params
        inputs['parent_calc_folder'] = self.ctx.scf_diag.out.remote_folder
        # TODO set atom types properly
        inputs['atomtypes'] = SinglefileData(file="/project/apps/scanning_probe/hrstm/atomtypes_2pp.ini")
        inputs['_options'] = {
            "resources": {"num_machines": 1},
            "max_wallclock_seconds": 21600,
        }

        self.report("PPM inputs: " + str(inputs))

        future = submit(AfmCalculation.process(), **inputs)
        return ToContext(ppm=Calc(future))
예제 #16
0
Usage: verdi run submit.py

Note: This script assumes you have set up computer and code as in README.md.
"""
import aiida_plumed.tests as tests
from aiida.orm.data.singlefile import SinglefileData
import os

code = tests.get_code(entry_point='plumed')

# Prepare input parameters
from aiida.orm import DataFactory
DiffParameters = DataFactory('plumed')
parameters = DiffParameters({'ignore-case': True})

file1 = SinglefileData(file=os.path.join(tests.TEST_DIR, 'file1.txt'))
file2 = SinglefileData(file=os.path.join(tests.TEST_DIR, 'file2.txt'))

# set up calculation
calc = code.new_calc()
calc.label = "aiida_plumed test"
calc.description = "Test job submission with the aiida_plumed plugin"
calc.set_max_wallclock_seconds(30)
calc.set_withmpi(False)
calc.set_resources({"num_machines": 1, "num_mpiprocs_per_machine": 1})

calc.use_parameters(parameters)
calc.use_file1(file1)
calc.use_file2(file2)

calc.store_all()
예제 #17
0
    def parse_with_retrieved(self, retrieved):
        """
        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)``)
        """
        from aiida.orm.data.singlefile import SinglefileData
        success = False
        node_list = []

        # Check that the retrieved folder is there
        try:
            out_folder = retrieved['retrieved']
        except KeyError:
            self.logger.error("No retrieved folder found")
            return success, node_list

        # Check the folder content is as expected
        list_of_files = out_folder.get_folder_list()
        inp_params = self._calc.inp.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:
            self.logger.error(
                "Not all expected output files {} were found".format(
                    output_files))
            return success, node_list

        # Parse output files
        output_parsers = inp_params.output_parsers
        output_links = inp_params.output_links
        output_parameters = ParameterData(dict={})

        for fname, parser, link in list(
                zip(output_files, output_parsers, output_links)):

            if parser is None:
                # just add file, if no parser implemented
                parsed = SinglefileData(file=out_folder.get_abs_path(fname))
                node_list.append((link, parsed))

            else:
                # else parse and add keys to output_parameters
                try:
                    with open(out_folder.get_abs_path(fname)) as f:
                        # Note: We join it to the output_params
                        #parsed = parser.parse_aiida(f.read())
                        parsed_dict = parser.parse(f.read())
                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_attr('Input_structure_filename',
                                    self._calc.inp.structure.filename)
        # 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_attr('Input_{}'.format(k),
                                        inp_params.get_attr(k))

        node_list.append(('output_parameters', output_parameters))

        success = True
        return success, node_list
예제 #18
0
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="/tmp/water.pot")
calc.use_file(water_pot, linkname="water_pot")

# structure using pdb format, because it also carries topology information
atoms = ase.build.molecule('H2O')
atoms.center(vacuum=10.0)
atoms.write("/tmp/coords.pdb", format="proteindatabank")
cell = atoms.cell
coords_pdb = SinglefileData(file="/tmp/coords.pdb")
calc.use_file(coords_pdb, linkname="coords_pdb")

# parameters
# based on cp2k/tests/Fist/regtest-1-1/water_1.inp
parameters = ParameterData(dict={
        'FORCE_EVAL': {
            'METHOD': 'fist',
예제 #19
0
    def parse_with_retrieved(self, retrieved):
        """
        Parse the results of retrieved nodes

        :param retrieved: dictionary of retrieved nodes
        """
        is_success = True
        output_nodes = []

        try:
            output_folder = retrieved[
                self.calculation._get_linkname_retrieved()]
        except KeyError:
            self.logger.error('no retrieved folder found')
            return False, ()

        # Verify the standard output file is present, parse it and attach as output parameters
        try:
            filepath_stdout = output_folder.get_abs_path(
                self.calculation.output_file_name)
        except OSError as exception:
            self.logger.error(
                "expected output file '{}' was not found".format(filepath))
            return False, ()

        is_success, dict_stdout = self.parse_stdout(filepath_stdout)
        output_nodes.append(
            (self.get_linkname_outparams(), ParameterData(dict=dict_stdout)))

        # The final chi and hubbard files are only written by a serial or post-processing calculation
        complete_calculation = True

        # We cannot use get_abs_path of the output_folder, since that will check for file existence and will throw
        output_path = output_folder.get_abs_path('.')
        filepath_chi = os.path.join(output_path,
                                    self.calculation.output_file_name_chi)
        filepath_hubbard = os.path.join(
            output_path, self.calculation.output_file_name_hubbard)
        filepath_hubbard_file = os.path.join(
            output_path, self.calculation.output_file_name_hubbard_file)

        for filepath in [filepath_chi, filepath_hubbard]:
            if not os.path.isfile(filepath):
                complete_calculation = False
                self.logger.info(
                    "output file '{}' was not found, assuming partial calculation"
                    .format(filepath))

        if os.path.isfile(filepath_hubbard_file):
            output_hubbard_file = SinglefileData(file=filepath_hubbard_file)
            output_nodes.append(
                (self.get_linkname_hubbard_file(), output_hubbard_file))

        if complete_calculation:
            dict_hubbard = self.parse_hubbard(filepath_hubbard)
            dict_chi = self.parse_chi(filepath_chi)

            output_matrices = ArrayData()
            output_matrices.set_array('chi0', dict_hubbard['chi0'])
            output_matrices.set_array('chi1', dict_hubbard['chi1'])
            output_matrices.set_array('chi0_inv', dict_hubbard['chi0_inv'])
            output_matrices.set_array('chi1_inv', dict_hubbard['chi1_inv'])
            output_matrices.set_array('hubbard', dict_hubbard['hubbard'])

            output_chi = ArrayData()
            output_chi.set_array('chi0', dict_chi['chi0'])
            output_chi.set_array('chi1', dict_chi['chi1'])

            output_hubbard = ParameterData(dict=dict_hubbard['hubbard_U'])

            output_nodes.append(
                (self.get_linkname_matrices(), output_matrices))
            output_nodes.append((self.get_linkname_hubbard(), output_hubbard))
            output_nodes.append((self.get_linkname_chi(), output_chi))

        return is_success, output_nodes
예제 #20
0
def test_full_run(new_database_with_daemon, new_workdir):
    """Test running a calculation"""
    from aiida.orm.data.singlefile import SinglefileData
    from aiida.common.datastructures import calc_states

    # get code
    code = get_basic_code(new_workdir, configure=True)

    # Prepare input parameters
    infile = SinglefileData(
        file=os.path.join(TEST_DIR, "input_files",
                          'mgo_sto3g_scf.crystal.d12'))

    # set up calculation
    calc = code.new_calc()

    inputs_dict = {
        "input_file": infile,
        "code": code,
        "options": {
            "resources": {
                "num_machines": 1,
                "num_mpiprocs_per_machine": 1
            },
            "withmpi": False,
            "max_wallclock_seconds": 30
        }
    }  # , "_use_cache": Bool(False)}

    process = calc.process()

    calcnode = run_get_node(process, inputs_dict)

    print(calcnode)

    assert '_aiida_cached_from' not in calcnode.extras()

    assert calcnode.get_state() == calc_states.FINISHED

    assert set(calcnode.get_outputs_dict().keys()).issuperset([
        'output_structure', 'output_parameters', 'output_settings', 'retrieved'
    ])

    expected_params = {
        'parser_version':
        str(aiida_crystal17.__version__),
        'ejplugins_version':
        str(ejplugins.__version__),
        'parser_class':
        'CryBasicParser',
        'parser_warnings':
        ["no initial structure available, creating new kinds for atoms"],
        'errors': [],
        'warnings': [],
        'energy': -2.7121814374931E+02 *
        27.21138602,
        'energy_units':
        'eV',  # hartree to eV
        'calculation_type':
        'restricted closed shell',
        'calculation_spin':
        False,
        # 'wall_time_seconds':
        # 3,
        'number_of_atoms':
        2,
        'number_of_assymetric':
        2,
        'scf_iterations':
        7,
        'volume':
        18.65461527264623,
    }

    outputs = calcnode.get_outputs_dict()['output_parameters'].get_dict()
    # remove wall time, because it is run dependent
    outputs.pop('wall_time_seconds', None)

    assert edict.diff(
        outputs,
        expected_params,
        np_allclose=True) == {}
예제 #21
0
structure = StructureData(ase=atoms)
n = structure.store()
print 'StructureData of elemental Pd obtained from Pd.cif has pk = {}\n'.format(
    str(n.pk))

# Add structure of Pd atom in AiiDA group
g, _ = Group.get_or_create(name='Isolated_atoms')
atoms = read('{}/Pd_isolated-atom.cif'.format(mypath))
structure = StructureData(ase=atoms)
n = structure.store()
g.add_nodes(n)
print "Added structure (pk = {}) obtained from Pd_isolated-atom.cif to AiiDA group 'Isolated_atoms'\n".format(
    n.pk)

# Store SinglefileData with Wien2k results for the equations of states
f = SinglefileData()
f.set_file('{}/WIEN2k.txt'.format(mypath))
f.store()
print 'SinglefileData obtained from text file WIEN2k.txt has pk = {}\n'.format(
    str(f.pk))

# Store KpointsData for band structure
k = KpointsData()
k.set_kpoints_mesh([6, 6, 6], [0.0, 0.0, 0.0])
k.store()
print 'KpointsData for band structure has pk = {}\n'.format(str(k.pk))

#from aiida.orm.data.singlefile import SinglefileData
#try:
#    g = Group.get_or_create(name='pslib.0.3.1_PBE_PAW', type_string='UpfData')
#except UniquenessError:
예제 #22
0
    def build_calc_inputs(cls, structure, code, max_force, calc_type,
                          mgrid_cutoff, vdw_switch, fixed_atoms, center_switch,
                          num_machines, remote_calc_folder):

        inputs = {}
        inputs['_label'] = "slab_geo_opt"
        inputs['code'] = code
        inputs['file'] = {}

        # make sure we're dealing with a metal slab
        # and figure out which one
        atoms = structure.get_ase()  # slow
        found_metal = False
        for el in [29, 47, 79]:
            if len(np.argwhere(atoms.numbers == el)) == 0:
                continue
            first_slab_atom = np.argwhere(atoms.numbers == el)[0, 0] + 1
            is_H = atoms.numbers[first_slab_atom - 1:] == 1
            is_Metal = atoms.numbers[first_slab_atom - 1:] == el
            if np.all(np.logical_or(is_H, is_Metal)):
                found_metal = el
                break

        if not found_metal:
            raise Exception("Structure is not a proper slab.")

        if found_metal == 79:
            metal_atom = 'Au'
        elif found_metal == 47:
            metal_atom = 'Ag'
        elif found_metal == 29:
            metal_atom = 'Cu'

        # structure
        molslab_f, mol_f = cls.mk_coord_files(atoms, first_slab_atom)
        inputs['file']['molslab_coords'] = molslab_f
        inputs['file']['mol_coords'] = mol_f

        # Au potential
        pot_f = SinglefileData(file='/project/apps/surfaces/slab/Au.pot')
        inputs['file']['au_pot'] = pot_f

        # parameters
        cell_abc = "%f  %f  %f" % (atoms.cell[0, 0], atoms.cell[1, 1],
                                   atoms.cell[2, 2])

        remote_computer = code.get_remote_computer()
        machine_cores = remote_computer.get_default_mpiprocs_per_machine()
        if calc_type == 'Mixed DFTB':
            walltime = 18000
        else:
            walltime = 86000

        inp = cls.get_cp2k_input(cell_abc, first_slab_atom, len(atoms),
                                 max_force, calc_type, mgrid_cutoff,
                                 vdw_switch, machine_cores * num_machines,
                                 fixed_atoms, walltime * 0.97, center_switch,
                                 metal_atom)

        if remote_calc_folder is not None:
            inp['EXT_RESTART'] = {
                'RESTART_FILE_NAME': './parent_calc/aiida-1.restart'
            }
            inputs['parent_folder'] = remote_calc_folder

        inputs['parameters'] = ParameterData(dict=inp)

        # settings
        settings = ParameterData(dict={'additional_retrieve_list': ['*.pdb']})
        inputs['settings'] = settings

        # resources
        inputs['_options'] = {
            "resources": {
                "num_machines": num_machines
            },
            "max_wallclock_seconds": walltime,
        }

        return inputs
예제 #23
0
    def build_calc_inputs(
            cls,
            struc_folder,
            cell,
            code,
            fixed_atoms,
            num_machines,
            remote_calc_folder,
            wfn_cp_commands,
            # NEB input
            align,
            endpoints,
            nproc_rep,
            nreplicas,
            nstepsit,
            rotate,
            spring,
            #list of available wfn
            # Calculation type specific
            calc_type,
            file_list,
            first_slab_atom,
            last_slab_atom):

        inputs = {}
        inputs['_label'] = "NEB"

        inputs['code'] = code
        inputs['file'] = {}

        # The files passed by the notebook
        for f in struc_folder.get_folder_list():
            path = struc_folder.get_abs_path() + '/path/' + f
            inputs['file'][f] = SinglefileData(file=path)

        # Au potential
        pot_f = SinglefileData(file='/project/apps/surfaces/slab/Au.pot')
        inputs['file']['au_pot'] = pot_f

        remote_computer = code.get_remote_computer()
        machine_cores = remote_computer.get_default_mpiprocs_per_machine()

        if 'Mixed' in str(calc_type):
            # Then we have mol0.xyz which is not a replica itself
            nreplica_files = len(file_list) - 1
        else:
            nreplica_files = len(file_list)

        if calc_type == 'Mixed DFTB':
            walltime = 18000
        else:
            walltime = 86000

        inp = cls.get_cp2k_input(
            cell=cell,
            fixed_atoms=fixed_atoms,
            machine_cores=machine_cores * num_machines,
            # NEB input
            align=align,
            endpoints=endpoints,
            nproc_rep=nproc_rep,
            nreplicas=nreplicas,
            nstepsit=nstepsit,
            rotate=rotate,
            spring=spring,
            # Calculation specific
            calc_type=calc_type,
            nreplica_files=nreplica_files,
            first_slab_atom=first_slab_atom,
            last_slab_atom=last_slab_atom,
            walltime=walltime * 0.97)

        if remote_calc_folder is not None:
            inputs['parent_folder'] = remote_calc_folder

        inputs['parameters'] = ParameterData(dict=inp)

        # settings
        settings = ParameterData(
            dict={'additional_retrieve_list': ['*.xyz', '*.out', '*.ener']})
        inputs['settings'] = settings

        # resources
        inputs['_options'] = {
            "resources": {
                "num_machines": num_machines
            },
            "max_wallclock_seconds": walltime,
        }
        if len(wfn_cp_commands) > 0:
            inputs['_options']["prepend_text"] = ""
            for wfn_cp_command in wfn_cp_commands:
                inputs['_options']["prepend_text"] += wfn_cp_command + "\n"
        return inputs
예제 #24
0
    def build_calc_inputs(cls, structure, cell, code, colvar_target,
                          fixed_atoms, num_machines, remote_calc_folder,
                          replica_name, spring, spring_unit, target_unit,
                          subsys_colvar, calc_type):

        inputs = {}
        inputs['_label'] = "replica_geo_opt"
        inputs['_description'] = "replica_{}_{}".format(
            replica_name, colvar_target)

        inputs['code'] = code
        inputs['file'] = {}

        # make sure we're really dealing with a gold slab
        atoms = structure.get_ase()  # slow
        try:
            first_slab_atom = np.argwhere(atoms.numbers == 79)[0, 0] + 1
            is_H = atoms.numbers[first_slab_atom - 1:] == 1
            is_Au = atoms.numbers[first_slab_atom - 1:] == 79
            assert np.all(np.logical_or(is_H, is_Au))
            assert np.sum(is_Au) / np.sum(is_H) == 4
        except AssertionError:
            raise Exception("Structure is not a proper slab.")

        # structure
        molslab_f, mol_f = cls.mk_coord_files(atoms, first_slab_atom)
        inputs['file']['molslab_coords'] = molslab_f
        inputs['file']['mol_coords'] = mol_f

        # Au potential
        pot_f = SinglefileData(file='/project/apps/surfaces/slab/Au.pot')
        inputs['file']['au_pot'] = pot_f

        # parameters
        # if no cell is given use the one from the xyz file.
        if cell == '' or len(str(cell)) < 3:
            cell_abc = "%f  %f  %f" % (atoms.cell[0, 0], atoms.cell[1, 1],
                                       atoms.cell[2, 2])
        else:
            cell_abc = cell

        remote_computer = code.get_remote_computer()
        machine_cores = remote_computer.get_default_mpiprocs_per_machine()

        inp = cls.get_cp2k_input(cell_abc, colvar_target, fixed_atoms, spring,
                                 spring_unit, target_unit, subsys_colvar,
                                 calc_type, machine_cores * num_machines,
                                 first_slab_atom, len(atoms))

        if remote_calc_folder is not None:
            inputs['parent_folder'] = remote_calc_folder

        inputs['parameters'] = ParameterData(dict=inp)

        # settings
        settings = ParameterData(dict={'additional_retrieve_list': ['*.xyz']})
        inputs['settings'] = settings

        # resources
        inputs['_options'] = {
            "resources": {
                "num_machines": num_machines
            },
            "max_wallclock_seconds": 86000,
        }

        return inputs
예제 #25
0
    def build_calc_inputs(cls,
                          code=None,
                          parent_folder=None,
                          structure=None,
                          input_dict=None):

        inputs = {}
        inputs['_label'] = "phonons_opt"
        inputs['code'] = code
        inputs['file'] = {}

        atoms = structure.get_ase()  # slow
        input_dict['atoms'] = atoms

        #basis_f = SinglefileData(file='/project/apps/surfaces/Files/RI_HFX_BASIS_all')
        #inputs['file']['ri_hfx_basis_all'] = basis_f

        molslab_f = cls.mk_aiida_file(atoms, "mol_on_slab.xyz")
        inputs['file']['molslab_coords'] = molslab_f
        first_slab_atom = None
        calc_type = input_dict['calc_type']

        if calc_type != 'Full DFT':

            # Au potential
            pot_f = SinglefileData(file='/project/apps/surfaces/slab/Au.pot')
            inputs['file']['au_pot'] = pot_f
            tipii = find_mol.get_types(atoms, 0.1)
            mol_atoms = np.where(tipii == 0)[0].tolist()
            #mol_indexes = find_mol.molecules(mol_atoms,atoms)
            #print(atoms[mol_indexes])
            #print(mol_indexes)
            first_slab_atom = len(mol_atoms) + 1
            mol_f = cls.mk_aiida_file(atoms[mol_atoms], "mol.xyz")
            inputs['file']['mol_coords'] = mol_f

            if calc_type == 'Mixed DFTB':
                walltime = 18000

        # parameters
        cell_ase = atoms.cell.flatten().tolist()

        if 'cell' in input_dict.keys():
            if input_dict['cell'] == '' or input_dict['cell'] == None:
                input_dict['cell'] = cell_ase
            else:
                cell_abc = input_dict['cell'].split()
                input_dict['cell'] = np.diag(np.array(
                    cell_abc, dtype=float)).flatten().tolist()
        else:
            input_dict['cell'] = cell_ase

#        remote_computer = code.get_remote_computer()
#        machine_cores = remote_computer.get_default_mpiprocs_per_machine()

#inp =     get_cp2k_input(input_dict = input_dict)
        input_dict['machine_cores'] = input_dict['nproc_rep'] * input_dict[
            'nreplicas']
        input_dict['first_slab_atom'] = first_slab_atom
        input_dict['last_slab_atom'] = len(atoms)

        inp = Get_CP2K_Input(input_dict=input_dict).inp

        if 'parent_folder' in input_dict.keys():
            inp['EXT_RESTART'] = {
                'RESTART_FILE_NAME': './parent_calc/aiida-1.restart'
            }
            inputs['parent_folder'] = input_dict['remote_calc_folder']

        inputs['parameters'] = ParameterData(dict=inp)

        # settings
        settings = ParameterData(dict={'additional_retrieve_list': ['*.mol']})
        inputs['settings'] = settings

        # resources
        inputs['_options'] = {
            'resources': {
                'num_machines':
                input_dict['num_machines'] * input_dict['nreplicas'],
                'num_mpiprocs_per_machine':
                input_dict['proc_node'],
                'num_cores_per_mpiproc':
                input_dict['num_cores_per_mpiproc']
            },
            'max_wallclock_seconds': int(input_dict['walltime']),
        }

        return inputs