Esempio n. 1
0
def bulkFromFile(filename, supercell):
    """

    :code:`bulkFromFile` function can help us create a Bulk from the file.

    :param filename: Usually when we create the structural file, we do it from the strcutural file such as .xyz or
                     .cif, etc.
    :type filename: python string object

    :param supercell: A list that contains the dimension of supercell we would like.
    :type supercell: python list object

    :returns: A StructureData file that can be used directly in Aiida.
    :rtype: aiida.orm.StructurData object

    """

    # transfer from aiida.orm types to the common python types

    if len(filename) == 0:
        raise (IOError("You didn't provide an input file."))

    if len(filename.split('.')[1]) == 0:
        raise (IOError(
            "You didn't provide a correct file_type, please try to name your file .xyz, .cif or other data structure "
            "types."))

    file_type = filename.split('.')[1]

    structure = read(filename, format=file_type)

    return StructureData(ase=structure * supercell)
Esempio n. 2
0
def addAdsorbates(slab, adsSiteDictionary):
    """

    :code:`addAdsorbates` will take care of these things:

    * Add each adsorbate to a specific site, and with optimal adsorption distance and angle
    * Put the bottom two layers of the slab fixed, other atoms can be relaxed

    :param slab: The slab that we want to adsorb some adsorbates on.
    :type slab: aiida.orm.StructureData object

    :param adsSiteDictionary: In which contains the adsorbates (for common adsorbates, I can assign the
                              adsorption atom, geometry of the adsorbates and its adsorption angle in
                              :code:`constants.py`) and adsorption sites, also I can add new adsorbates to the
                              adsorbates library. (Do a very simple relax simulation of a molecule in the big cell,
                              and just output the structure and assign the adsorption site. For mono-site adsorption,
                              it is really easy, for bi-site adsorption, it is also easy since we can get the
                              molecule to align; for tri-site or more-site adsorption, well, we can just put the
                              molecule closer to the surface and let the program determine how does this molecule
                              interact with the surface, for our usual research, I don't think this is necessary.)

                              .. code-block:: python

                                    adsSiteDictionary = {
                                        'O': [site1, site2, site3] # each site is a 3x1 list [a, b, c]
                                        'F': [site1, site2, site3]
                                    }
    :type adsSiteDictionary: python dictionary object

    :returns: With the adsorbates and modified constrains on all the atoms, ready for the submit functions.
    :rtype: aiida.orm.StructureData object

    """

    # clean the input parameters from aiida.orm types to usual types
    slab = slab.get_pymatgen_structure()
    slab_tmp = deepcopy(slab)
    # asf = AdsorbateSiteFinder(slab_tmp, selective_dynamics = True)
    # end of cleaning process

    for ads, siteList in adsSiteDictionary.items():
        adsorbate = getMoleculeByName(ads)
        if len(ads) == 1:
            ads_site = [0]
        else:
            ads_site = adsorbates[ads]['ads_site']
        if len(ads_site) == 1:
            for site in siteList:
                slab_tmp = hzd_add_adsMono(slab_tmp,
                                           molecule=adsorbate,
                                           ads_coord=[site],
                                           ads_site=ads_site)
        # elif len(ads_site) == 2:
        #     # treate it as mono-dent
        #     for site in siteList:
        #         for adsite in ads_site:
        #             slab_tmp = hzd_add_adsMono(slab_tmp, molecule = adsorbate, ads_coord = site, ads_site = ads_site)
        #     slab_tmp = hzd_add_adsBi(slab_tmp, molecule = adsorbate, ads_coord = siteList, ads_site = ads_site)

    return StructureData(pymatgen_structure=slab_tmp)
Esempio n. 3
0
def example_multistage_h2o_fail(cp2k_code):
    """Example usage: verdi run thistest.py cp2k@localhost"""

    print("Testing CP2K multistage workchain on H2O")
    print(">>> Making it fail because of an unphysical Multiplicity")

    atoms = ase.build.molecule('H2O')
    atoms.center(vacuum=2.0)
    structure = StructureData(ase=atoms)

    parameters = Dict(
        dict={'FORCE_EVAL': {
            'DFT': {
                'UKS': True,
                'MULTIPLICITY': 666,
            }
        }})

    # Construct process builder
    builder = Cp2kMultistageWorkChain.get_builder()
    builder.structure = structure
    builder.protocol_tag = Str('test')
    builder.cp2k_base.max_iterations = Int(1)
    builder.cp2k_base.cp2k.parameters = parameters
    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)
Esempio n. 4
0
def test_bands_from_castepbin(db_test_app, generate_parser, data_path,
                              generate_calc_job_node, sto_calc_inputs):
    """
    Iterate through internal test cases.
    Check if the results are parsed correctly.
    """

    inputs = sto_calc_inputs
    output_folder = "Si2-castepbin"
    atoms = bulk("Si2", "zincblende", a=4.0)
    inputs.structure = StructureData(ase=atoms).store()

    # Swap the correct structure to allow desort to work
    parser = generate_parser('castep.castep')
    node = generate_calc_job_node('castep.castep', output_folder, inputs)

    out, calcfunc = parser.parse_from_node(node, store_provenance=False)
    assert calcfunc.exit_status == 0

    out_bands = out[ln_name['bands']]

    bands, occ = out_bands.get_bands(also_occupations=True)

    assert bands.shape == (1, 4, 8)
    assert occ.shape == (1, 4, 8)
    assert out_bands.attributes['efermi'][0] == pytest.approx(
        0.248809 * units['Eh'], 1e-5)
def prepare_plotting_structure(return_struc=False, show_empty_atoms=False):

    # find and plot structure, extract if from parent of bandstructure calc
    Sb2Te3_6QL_bandstruc = load_node(
        UUID_HOST_BANDSTRUC)  # -0.5eV..+0.3eV, corrected K-path
    structure0, _ = VoronoiCalculation.find_parent_structure(
        Sb2Te3_6QL_bandstruc)

    if structure0.has_vacancies:
        cell = structure0.cell

        # correct cell ...
        cell[2] = [i * 8 for i in cell[2]]

        stmp = StructureData(cell=cell)
        for site in structure0.sites:
            k = structure0.get_kind(site.kind_name)
            pos = np.array(site.position)
            pos[2] = -pos[2]
            if not k.has_vacancies:
                stmp.append_atom(position=pos, symbols=k.symbol)
            elif show_empty_atoms:
                stmp.append_atom(position=pos, symbols='X')
            #else:
            #    print("removing atom", site)
        stmp.set_pbc(structure0.pbc)
        structure = stmp

    if return_struc:
        return structure

    # now construct ase object and use ase's viewer
    ase_atoms = structure.get_ase()

    return ase_atoms
Esempio n. 6
0
def example_opt_restart(orca_code, opt_calc_pk=None, submit=True):
    """Run simple DFT calculation"""

    # This line is needed for tests only
    if opt_calc_pk is None:
        opt_calc_pk = pytest.opt_calc_pk  # pylint: disable=no-member

    # structure
    thisdir = os.path.dirname(os.path.realpath(__file__))
    xyz_path = os.path.join(thisdir, 'h2co.xyz')
    structure = StructureData(
        pymatgen_molecule=mg.Molecule.from_file(xyz_path))

    # old gbw file
    retr_fldr = load_node(opt_calc_pk).outputs.retrieved
    gbw_file = SinglefileData(
        os.path.join(retr_fldr._repository._get_base_folder().abspath,
                     'aiida.gbw'))  #pylint: disable=protected-access

    # parameters
    parameters = Dict(
        dict={
            'charge': 0,
            'multiplicity': 1,
            'input_blocks': {
                'scf': {
                    'convergence': 'tight',
                    'moinp': '"aiida_old.gbw"',
                },
                'pal': {
                    'nproc': 2,
                },
            },
            'input_keywords': ['B3LYP/G', 'def2-TZVP', 'Opt'],
            'extra_input_keywords': ['MOREAD'],
        })

    # Construct process builder
    builder = OrcaCalculation.get_builder()

    builder.structure = structure
    builder.parameters = parameters
    builder.code = orca_code
    builder.file = {
        'gbw': gbw_file,
    }
    builder.metadata.options.resources = {
        'num_machines': 1,
        'num_mpiprocs_per_machine': 1,
    }
    builder.metadata.options.max_wallclock_seconds = 1 * 10 * 60
    if submit:
        print('Testing Orca Opt Calculations...')
        res, pk = run_get_pk(builder)
        print('calculation pk: ', pk)
        print('SCF Energy is :', res['output_parameters'].dict['scfenergies'])
    else:
        builder.metadata.dry_run = True
        builder.metadata.store_provenance = False
Esempio n. 7
0
def example_relax(code, pseudo_family):
    """Run simple silicon DFT calculation."""

    print("Testing the AbinitBaseWorkChain relaxation on Silicon")

    thisdir = os.path.dirname(os.path.realpath(__file__))
    structure = StructureData(pymatgen=mg.Structure.from_file(
        os.path.join(thisdir, "files", 'Si.cif')))
    pseudo_family = Group.objects.get(label=pseudo_family)
    pseudos = pseudo_family.get_pseudos(structure=structure)

    base_parameters_dict = {
        'kpoints_distance': Float(0.6),  # 1 / Angstrom
        'abinit': {
            'code':
            code,
            'structure':
            structure,
            'pseudos':
            pseudos,
            'parameters':
            Dict(
                dict={
                    'optcell':
                    2,  # Cell optimization
                    'ionmov':
                    22,  # Atoms relaxation
                    'tolmxf':
                    5.0e-5,  # Tolerence on the maximal force
                    'ecutsm':
                    0.5,  # Energy cutoff smearing, in Hartree
                    'ecut':
                    20.0,  # Maximal kinetic energy cut-off, in Hartree
                    'nshiftk':
                    4,  # of the reciprocal space (that form a BCC lattice !)
                    'shiftk': [[0.5, 0.5, 0.5], [0.5, 0.0, 0.0],
                               [0.0, 0.5, 0.0], [0.0, 0.0, 0.5]],
                    'nstep':
                    20,  # Maximal number of SCF cycles
                    'toldfe':
                    1.0e-6,  # Will stop when, twice in a row, the difference 
                    # between two consecutive evaluations of total energy
                    # differ by less than toldfe (in Hartree)
                }),
            'metadata': {
                'options': {
                    'withmpi': True,
                    'max_wallclock_seconds': 10 * 60,
                    'resources': {
                        'num_machines': 1,
                        'num_mpiprocs_per_machine': 4,
                    }
                }
            }
        }
    }

    print("Running work chain...")
    run(AbinitBaseWorkChain, **base_parameters_dict)
Esempio n. 8
0
    def create_structure_bands():
        """Create bands structure object."""
        alat = 4.  # angstrom
        cell = [
            [
                alat,
                0.,
                0.,
            ],
            [
                0.,
                alat,
                0.,
            ],
            [
                0.,
                0.,
                alat,
            ],
        ]
        strct = StructureData(cell=cell)
        strct.append_atom(position=(0., 0., 0.), symbols='Fe')
        strct.append_atom(position=(alat / 2., alat / 2., alat / 2.),
                          symbols='O')
        strct.store()

        @calcfunction
        def connect_structure_bands(strct):  # pylint: disable=unused-argument
            alat = 4.
            cell = np.array([
                [alat, 0., 0.],
                [0., alat, 0.],
                [0., 0., alat],
            ])

            kpnts = KpointsData()
            kpnts.set_cell(cell)
            kpnts.set_kpoints([[0., 0., 0.], [0.1, 0.1, 0.1]])

            bands = BandsData()
            bands.set_kpointsdata(kpnts)
            bands.set_bands([[1.0, 2.0], [3.0, 4.0]])
            return bands

        bands = connect_structure_bands(strct)

        # Create 2 groups and add the data to one of them
        g_ne = Group(label='non_empty_group')
        g_ne.store()
        g_ne.add_nodes(bands)

        g_e = Group(label='empty_group')
        g_e.store()

        return {
            DummyVerdiDataListable.NODE_ID_STR: bands.id,
            DummyVerdiDataListable.NON_EMPTY_GROUP_ID_STR: g_ne.id,
            DummyVerdiDataListable.EMPTY_GROUP_ID_STR: g_e.id
        }
def test_without_kinds(cp2k_code, cp2k_basissets, cp2k_pseudos,
                       clear_database):  # pylint: disable=unused-argument
    """Testing CP2K with the Basis Set stored in gaussian.basisset but without a KIND section"""

    # structure
    atoms = ase.build.molecule("H2O")
    atoms.center(vacuum=2.0)
    structure = StructureData(ase=atoms)

    # parameters
    parameters = Dict(
        dict={
            "FORCE_EVAL": {
                "METHOD": "Quickstep",
                "DFT": {
                    "QS": {
                        "EPS_DEFAULT": 1.0e-12,
                        "WF_INTERPOLATION": "ps",
                        "EXTRAPOLATION_ORDER": 3,
                    },
                    "MGRID": {
                        "NGRIDS": 4,
                        "CUTOFF": 280,
                        "REL_CUTOFF": 30
                    },
                    "XC": {
                        "XC_FUNCTIONAL": {
                            "_": "LDA"
                        }
                    },
                    "POISSON": {
                        "PERIODIC": "none",
                        "PSOLVER": "MT"
                    },
                },
            }
        })

    options = {
        "resources": {
            "num_machines": 1,
            "num_mpiprocs_per_machine": 1
        },
        "max_wallclock_seconds": 1 * 3 * 60,
    }

    inputs = {
        "structure": structure,
        "parameters": parameters,
        "code": cp2k_code,
        "metadata": {
            "options": options
        },
        "basissets": cp2k_basissets,
        "pseudos": cp2k_pseudos,
    }

    _, calc_node = run_get_node(CalculationFactory("cp2k"), **inputs)
    assert calc_node.exit_status == 0
Esempio n. 10
0
def refine_inline(node):
    """
    Refine (reduce) the cell of :py:class:`aiida.orm.nodes.data.cif.CifData`,
    find and remove symmetrically equivalent atoms.

    :param node: a :py:class:`aiida.orm.nodes.data.cif.CifData` instance.
    :return: dict with :py:class:`aiida.orm.nodes.data.cif.CifData`

    .. note:: can be used as inline calculation.
    """
    from aiida.orm.nodes.data.structure import StructureData, ase_refine_cell

    if len(node.values.keys()) > 1:
        raise ValueError('CifData seems to contain more than one data '
                         'block -- multiblock CIF files are not '
                         'supported yet')

    name = list(node.values.keys())[0]

    original_atoms = node.get_ase(index=None)
    if len(original_atoms) > 1:
        raise ValueError('CifData seems to contain more than one crystal '
                         'structure -- such refinement is not supported '
                         'yet')

    original_atoms = original_atoms[0]

    refined_atoms, symmetry = ase_refine_cell(original_atoms)

    cif = CifData(ase=refined_atoms)
    if name != str(0):
        cif.values.rename(str(0), name)

    # Remove all existing symmetry tags before overwriting:
    for tag in symmetry_tags:
        cif.values[name].RemoveCifItem(tag)

    cif.values[name]['_symmetry_space_group_name_H-M'] = symmetry['hm']
    cif.values[name]['_symmetry_space_group_name_Hall'] = symmetry['hall']
    cif.values[name]['_symmetry_Int_Tables_number'] = symmetry['tables']
    cif.values[name]['_symmetry_equiv_pos_as_xyz'] = \
        [symop_string_from_symop_matrix_tr(symmetry['rotations'][i],
                                           symmetry['translations'][i])
         for i in range(len(symmetry['rotations']))]

    # Summary formula has to be calculated from non-reduced set of atoms.
    cif.values[name]['_chemical_formula_sum'] = \
        StructureData(ase=original_atoms).get_formula(mode='hill',
                                                      separator=' ')

    # If the number of reduced atoms multiplies the number of non-reduced
    # atoms, the new Z value can be calculated.
    if '_cell_formula_units_Z' in node.values[name].keys():
        old_Z = node.values[name]['_cell_formula_units_Z']
        if len(original_atoms) % len(refined_atoms):
            new_Z = old_Z * len(original_atoms) // len(refined_atoms)
            cif.values[name]['_cell_formula_units_Z'] = new_Z

    return {'cif': cif}
Esempio n. 11
0
    def create_structure_bands():
        alat = 4.  # angstrom
        cell = [
            [
                alat,
                0.,
                0.,
            ],
            [
                0.,
                alat,
                0.,
            ],
            [
                0.,
                0.,
                alat,
            ],
        ]
        s = StructureData(cell=cell)
        s.append_atom(position=(0., 0., 0.), symbols='Fe')
        s.append_atom(position=(alat / 2., alat / 2., alat / 2.), symbols='O')
        s.store()

        @calcfunction
        def connect_structure_bands(structure):
            alat = 4.
            cell = np.array([
                [alat, 0., 0.],
                [0., alat, 0.],
                [0., 0., alat],
            ])

            k = KpointsData()
            k.set_cell(cell)
            k.set_kpoints([[0., 0., 0.], [0.1, 0.1, 0.1]])

            b = BandsData()
            b.set_kpointsdata(k)
            b.set_bands([[1.0, 2.0], [3.0, 4.0]])

            return b

        b = connect_structure_bands(s)

        # Create 2 groups and add the data to one of them
        g_ne = Group(label='non_empty_group')
        g_ne.store()
        g_ne.add_nodes(b)

        g_e = Group(label='empty_group')
        g_e.store()

        return {
            TestVerdiDataListable.NODE_ID_STR: b.id,
            TestVerdiDataListable.NON_EMPTY_GROUP_ID_STR: g_ne.id,
            TestVerdiDataListable.EMPTY_GROUP_ID_STR: g_e.id
        }
Esempio n. 12
0
    def _generate_structure(structure_id='silicon'):
        """Return a `StructureData` representing bulk silicon or a snapshot of a single water molecule dynamics."""
        from aiida.orm import StructureData

        if structure_id == 'silicon':
            param = 5.43
            cell = [[param / 2., param / 2., 0], [param / 2., 0, param / 2.], [0, param / 2., param / 2.]]
            structure = StructureData(cell=cell)
            structure.append_atom(position=(0., 0., 0.), symbols='Si', name='Si')
            structure.append_atom(position=(param / 4., param / 4., param / 4.), symbols='Si', name='Si')
        elif structure_id == 'water':
            structure = StructureData(cell=[[5.29177209, 0., 0.], [0., 5.29177209, 0.], [0., 0., 5.29177209]])
            structure.append_atom(position=[12.73464656, 16.7741411, 24.35076238], symbols='H', name='H')
            structure.append_atom(position=[-29.3865565, 9.51707929, -4.02515904], symbols='H', name='H')
            structure.append_atom(position=[1.04074437, -1.64320127, -1.27035021], symbols='O', name='O')
        else:
            raise KeyError('Unknown structure_id=\'{}\''.format(structure_id))
        return structure
Esempio n. 13
0
def test_init_from_structure_types(minimal_pymatgen_structure):
    pymatgen_structure = minimal_pymatgen_structure
    pymatgen_poscar = Poscar(minimal_pymatgen_structure)
    aiida_structure = StructureData(pymatgen_structure=pymatgen_structure)
    reference_poscar = pymatgen_poscar
    # initialize poscar using different structure types
    for struct in [pymatgen_structure, pymatgen_poscar, aiida_structure]:
        poscar = VaspPoscarData(structure=struct)
        assert str(poscar.get_poscar()) == str(reference_poscar)
Esempio n. 14
0
def h2_structure(aiida_profile, db_test_app):
    a = 10

    cell = ((a, 0., 0.), (0., a, 0.), (0., 0., a))
    s = StructureData(cell=cell)
    s.append_atom(position=(0., 0., 0.), symbols=["H"])
    s.append_atom(position=(a / 2, a / 2, a / 2), symbols=["H"])
    s.label = "h2"
    return s
Esempio n. 15
0
def to_primitive(structure):
    """Returns aiida StructureData with primitive cell"""
    from aiida.orm import StructureData
    cell, positions, numbers = spglib.find_primitive(structure.get_ase())
    ase_struct = Atoms(numbers,
                       scaled_positions=positions,
                       cell=cell,
                       pbc=True)
    return StructureData(ase=ase_struct)
Esempio n. 16
0
def submit_mixlmp(structure, dummy_index, steps, temp, lambda_f, dft_graphs,
                  dum_graphs):
    builder = TemplateCalculation.get_builder()
    # builder.metadata.dry_run = True
    builder.code = Code.get_from_string('lammps@metal')
    builder.settings = {'additional_retrieve_list': ['*.xyz', '*.out']}
    builder.metadata.options.queue_name = 'large'
    builder.metadata.options.resources = {'tot_num_mpiprocs': 4}
    builder.metadata.options.custom_scheduler_commands = '#BSUB -R "span[ptile=4]"'
    builder.template = os.path.abspath('template_lmp.in')
    files = {}
    for i, graph in enumerate(dft_graphs):
        files.update({
            f'dft_graph_{i}':
            SinglefileData(file=graph, filename=f'dft_graph_{i}.pb')
        })
    for i, graph in enumerate(dum_graphs):
        files.update({
            f'dum_graph_{i}':
            SinglefileData(file=graph, filename=f'dum_graph_{i}.pb')
        })
    builder.file = files
    builder.variables = {
        'TBD_STEPS':
        steps,
        'TBD_TEMP':
        temp,
        'TBD_LAMBDA_f':
        lambda_f,
        'TBD_DFT':
        ' '.join([
            f + '.pb'
            for f in filter(lambda x: x.startswith('dft'), files.keys())
        ]),
        'TBD_DUM':
        ' '.join([
            f + '.pb'
            for f in filter(lambda x: x.startswith('dum'), files.keys())
        ]),
        'TBD_vel':
        np.random.randint(10000000),
        'TBD_INPUT':
        TemplateCalculation._INPUT_STRUCTURE
    }
    builder.kinds = ['O', 'H', 'Na', 'Cl', 'X']
    if isinstance(structure, Atoms):
        atoms = structure
    elif isinstance(structure, StructureData):
        atoms = structure.get_ase()
    else:
        raise TypeError(
            "Unknown structure format, please use ase.Atoms or aiida.orm.StructureData"
        )
    builder.structure = StructureData(
        ase=generate_atoms_dummy(atoms, dummy_index))
    submit(builder)
Esempio n. 17
0
def get_x2_structure(x):
    """Return a O2 molecule in a box"""
    a = 10

    cell = ((a, 0., 0.), (0., a, 0.), (0., 0., a))
    s = StructureData(cell=cell)
    s.append_atom(position=(0., 0., 0.), symbols=[x])
    s.append_atom(position=(1.4, 0., 0.), symbols=[x])
    s.label = "O2"
    return s
Esempio n. 18
0
    def get_aiida_structure(self):
        """
        Create and return a :class:`aiida.orm.StructureData` instance from
        the node's stored structure data contents

        :return: an AiiDA :class:`~aiida.orm.StructureData` instance
        :rtype: :class:`aiida.orm.StructureData`
        """
        structure = self.get_structure()
        return StructureData(pymatgen_structure=structure)
Esempio n. 19
0
def prepare_run(stage, deliverable, inputs):
    inputs["structure"] = StructureData(ase=graphene(vacuum=15))
    inputs["year"] = Int(2050)

    if stage == 2:
        inputs["C_substitute"] = Str("N")
    elif stage in [3, 4]:
        inputs["C_substitute"] = Str("H")
        inputs["max_iterations"] = Int(1)
        inputs["batch_size"] = Int(3)
Esempio n. 20
0
def example_dft(code, pseudo_family):
    """Run simple silicon DFT calculation."""

    print('Testing Abinit Total energy on Silicon using AbinitCalculation')

    thisdir = os.path.dirname(os.path.realpath(__file__))
    structure = StructureData(pymatgen=mg.core.Structure.from_file(
        os.path.join(thisdir, 'files', 'Si.cif')))
    pseudo_family = Group.objects.get(label=pseudo_family)
    pseudos = pseudo_family.get_pseudos(structure=structure)

    kpoints = KpointsData()
    kpoints.set_cell_from_structure(structure)
    kpoints.set_kpoints_mesh([2, 2, 2])
    # kpoints.set_kpoints_mesh_from_density(2.0)

    parameters_dict = {
        'code':
        code,
        'structure':
        structure,
        'pseudos':
        pseudos,
        'kpoints':
        kpoints,
        'parameters':
        Dict(
            dict={
                'ecut':
                8.0,  # Maximal kinetic energy cut-off, in Hartree
                'nshiftk':
                4,  # of the reciprocal space (that form a BCC lattice !)
                'shiftk': [[0.5, 0.5, 0.5], [0.5, 0.0, 0.0], [0.0, 0.5, 0.0],
                           [0.0, 0.0, 0.5]],
                'nstep':
                20,  # Maximal number of SCF cycles
                'toldfe':
                1.0e-6,  # Will stop when, twice in a row, the difference
                # between two consecutive evaluations of total energy
                # differ by less than toldfe (in Hartree)
            }),
        'metadata': {
            'options': {
                'withmpi': True,
                'max_wallclock_seconds': 2 * 60,
                'resources': {
                    'num_machines': 1,
                    'num_mpiprocs_per_machine': 4,
                }
            }
        }
    }

    print('Running calculation...')
    run(AbinitCalculation, **parameters_dict)
Esempio n. 21
0
    def _generate_structure(elements=('Ar',)):
        """Return a ``StructureData``."""
        from aiida.orm import StructureData

        structure = StructureData(cell=[[1, 0, 0], [0, 1, 0], [0, 0, 1]])

        for index, element in enumerate(elements):
            symbol = re.sub(r'[0-9]+', '', element)
            structure.append_atom(position=(index * 0.5, index * 0.5, index * 0.5), symbols=symbol, name=element)

        return structure
Esempio n. 22
0
    def _generate_structure():
        """Return a `StructureData` representing bulk silicon."""
        from aiida.orm import StructureData

        param = 5.43
        cell = [[param / 2., param / 2., 0], [param / 2., 0, param / 2.], [0, param / 2., param / 2.]]
        structure = StructureData(cell=cell)
        structure.append_atom(position=(0., 0., 0.), symbols='Si', name='Si')
        structure.append_atom(position=(param / 4., param / 4., param / 4.), symbols='Si', name='Si')

        return structure
def example_multistage_al(cp2k_code):
    """Example usage: verdi run thistest.py cp2k@localhost"""

    print("Testing CP2K multistage workchain on Al (RKS, needs smearing)...")
    print(
        "EXPECTED: the OT (settings_0) will converge to a negative bandgap, then we switch to SMEARING (settings_1)"
    )

    thisdir = os.path.dirname(os.path.abspath(__file__))
    structure = StructureData(
        ase=ase.io.read(os.path.join(thisdir, '../data/Al.cif')))

    # testing user change of parameters and protocol
    parameters = Dict(
        dict={'FORCE_EVAL': {
            'DFT': {
                'MGRID': {
                    'CUTOFF': 250,
                }
            }
        }})
    protocol_mod = Dict(
        dict={
            'initial_magnetization': {
                'Al': 0
            },
            'settings_0': {
                'FORCE_EVAL': {
                    'DFT': {
                        'SCF': {
                            'OUTER_SCF': {
                                'MAX_SCF': 5,
                            }
                        }
                    }
                }
            }
        })

    # Construct process builder
    builder = Cp2kMultistageWorkChain.get_builder()
    builder.structure = structure
    builder.protocol_tag = Str('test')
    builder.starting_settings_idx = Int(0)
    builder.protocol_modify = protocol_mod
    builder.cp2k_base.cp2k.parameters = parameters
    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)
Esempio n. 24
0
    def _generate_structure(element='Si'):
        """Return a `StructureData` representing bulk silicon."""
        from aiida.orm import StructureData

        a = 5.43
        cell = [[a / 2., a / 2., 0], [a / 2., 0, a / 2.], [0, a / 2., a / 2.]]
        structure = StructureData(cell=cell)
        structure.append_atom(position=(0., 0., 0.), symbols=element)
        structure.append_atom(position=(a / 4., a / 4., a / 4.), symbols=element)

        return structure
Esempio n. 25
0
def example_dft(gaussian_code):
    """Run simple DFT calculation"""

    print("Testing Gaussian Input Creation")

    # structure
    structure = StructureData(
        pymatgen_molecule=mg.Molecule.from_file('./ch4.xyz'))

    num_cores = 2
    memory_mb = 300

    # parameters
    parameters = Dict(
        dict={
            'link0_parameters': {
                '%chk': 'aiida.chk',
                '%mem': '%dMB' % memory_mb,
                '%nprocshared': num_cores,
            },
            'functional': 'PBE1PBE',
            'basis_set': '6-31g',
            'route_parameters': {
                'nosymm': None,
                'Output': 'WFX'
            },
            'input_parameters': {
                'output.wfx': None
            },
        })

    # Construct process builder

    builder = GaussianCalculation.get_builder()

    builder.structure = structure
    builder.parameters = parameters
    builder.code = gaussian_code

    builder.metadata.options.resources = {
        "num_machines": 1,
        "tot_num_mpiprocs": num_cores,
    }

    # Should ask for extra +25% extra memory
    builder.metadata.options.max_memory_kb = int(1.25 * memory_mb) * 1024
    builder.metadata.options.max_wallclock_seconds = 3 * 60

    builder.metadata.dry_run = True
    builder.metadata.store_provenance = False

    process_node = submit(builder)

    print("Submitted dry_run in" + str(process_node.dry_run_info))
Esempio n. 26
0
def _get_aiida_structure_pymatgen_inline(cif, **kwargs):
    """
    Creates :py:class:`aiida.orm.nodes.data.structure.StructureData` using pymatgen.

    :param occupancy_tolerance: If total occupancy of a site is between 1 and occupancy_tolerance,
        the occupancies will be scaled down to 1.
    :param site_tolerance: This tolerance is used to determine if two sites are sitting in the same position,
        in which case they will be combined to a single disordered site. Defaults to 1e-4.

    .. note:: requires pymatgen module.
    """
    from pymatgen.io.cif import CifParser
    from aiida.orm import Dict, StructureData

    parameters = kwargs.get('parameters', {})

    if isinstance(parameters, Dict):
        # Note, if `parameters` is unstored, it might contain stored `Node` instances which might slow down the parsing
        # enormously, because each time their value is used, a database call is made to refresh the value
        parameters = clean_value(parameters.get_dict())

    constructor_kwargs = {}

    parameters['primitive'] = parameters.pop('primitive_cell', False)

    for argument in ['occupancy_tolerance', 'site_tolerance']:
        if argument in parameters:
            constructor_kwargs[argument] = parameters.pop(argument)

    with cif.open() as handle:
        parser = CifParser(handle, **constructor_kwargs)

    try:
        structures = parser.get_structures(**parameters)
    except ValueError:

        # Verify whether the failure was due to wrong occupancy numbers
        try:
            constructor_kwargs['occupancy_tolerance'] = 1E10
            with cif.open() as handle:
                parser = CifParser(handle, **constructor_kwargs)
            structures = parser.get_structures(**parameters)
        except ValueError:
            # If it still fails, the occupancies were not the reason for failure
            raise ValueError(
                'pymatgen failed to provide a structure from the cif file'
            ) from ValueError
        else:
            # If it now succeeds, non-unity occupancies were the culprit
            raise InvalidOccupationsError(
                'detected atomic sites with an occupation number larger than the occupation tolerance'
            ) from ValueError

    return {'structure': StructureData(pymatgen_structure=structures[0])}
Esempio n. 27
0
def get_strain_input(  # pylint: disable=missing-docstring
    strain_kind='three_five.Uniaxial110',
    strain_parameters='InSb',
    strain_strengths=(-0.02, -0.01, 0.01, 0.02)):
    structure = StructureData()
    structure.set_pymatgen(pymatgen.Structure.from_file('POSCAR'))

    return dict(structure=structure,
                strain_kind=Str(strain_kind),
                strain_parameters=Str(strain_parameters),
                strain_strengths=List(list=list(strain_strengths)))
Esempio n. 28
0
def main(codelabel):
    """Example usage: verdi run thistest.py cp2k@localhost"""

    print("Testing CP2K multistage workchain on Al (RKS, needs smearing)...")
    print("EXPECTED: the OT (settings_0) will converge to a negative bandgap, then we switch to SMEARING (settings_1)")

    code = Code.get_from_string(codelabel)

    thisdir = os.path.dirname(os.path.abspath(__file__))
    structure = StructureData(ase=ase.io.read(os.path.join(thisdir, '../data/Al.cif')))

    # testing user change of parameters and protocol
    parameters = Dict(dict={'FORCE_EVAL': {'DFT': {'MGRID': {'CUTOFF': 250,}}}})
    protocol_mod = Dict(dict={
        'initial_magnetization': {
            'Al': 0
        },
        'settings_0': {
            'FORCE_EVAL': {
                'DFT': {
                    'SCF': {
                        'OUTER_SCF': {
                            'MAX_SCF': 5,
                        }
                    }
                }
            }
        }
    })
    options = {
        "resources": {
            "num_machines": 1,
            "num_mpiprocs_per_machine": 1,
        },
        "max_wallclock_seconds": 1 * 3 * 60,
    }
    inputs = {
        'structure': structure,
        'protocol_tag': Str('test'),
        'starting_settings_idx': Int(0),
        'protocol_modify': protocol_mod,
        'cp2k_base': {
            'cp2k': {
                'parameters': parameters,
                'code': code,
                'metadata': {
                    'options': options,
                }
            }
        }
    }

    run(Cp2kMultistageWorkChain, **inputs)
Esempio n. 29
0
def aiida_structure_merge(aiida_structure_a, aiida_structure_b):
    """Merge the coordinates of two StructureData into a sigle one. Note: the two unit cells must be the same."""
    ase_a = aiida_structure_a.get_ase()
    ase_b = aiida_structure_b.get_ase()
    if not ase_cells_are_similar(ase_a, ase_b.cell):
        raise ValueError('Attempting to merge two StructureData with different unit cells.')
    ase_ab = ase.Atoms(  #Maybe there is a more direct way...
        symbols=list(ase_a.symbols) + list(ase_b.symbols),
        cell=ase_a.cell,
        positions=list(ase_a.positions) + list(ase_b.positions),
        pbc=True)
    return StructureData(ase=ase_ab)
Esempio n. 30
0
def launch(dataset_path, group_name, group_description, parse_comments_path,
           parse_comments_structure):
    print("loading dataset: {} to group: {}".format(dataset_path, group_name))

    # Setup/Retrieve the Group
    g = Group.objects.get_or_create(name=group_name,
                                    description=group_description)[0]
    # Loop over structures in the dataset_path, storing the nodes then adding them to the group
    i = 0
    while True:
        try:
            ase_structure = ase.io.read(dataset_path, index=i, format="runner")
        except StopIteration:
            break
        # setup and store the ase structure as an aiida StructureData node
        aiida_structure = StructureData()
        aiida_structure.set_ase(ase_structure)
        aiida_structure_stored = aiida_structure.store()

        # add in the dataset_path line if possible
        if parse_comments_path:
            try:
                structure_path = ase_structure.comment.strip().split()[-1][3:]
                aiida_structure_stored.set_extra("structure_path",
                                                 structure_path)
            except AttributeError:
                print(
                    "could not set structure_path on {}".format(ase_structure))
                pass
        # Add in details of parent structure uuid
        if parse_comments_structure:
            try:
                parent_uuid = ase_structure.comment.strip().split()[-1]
                aiida_structure_stored.set_extra("parent_uuid", parent_uuid)
                add_parentstructure_extras(aiida_structure_stored, parent_uuid)
            except AttributeError:
                print("could not set parent_uuid on {}".format(ase_structure))
                pass

        # add in the chemical formula and number of atoms if possible
        try:
            aiida_structure_stored.set_extra("num_atoms", len(ase_structure))
            aiida_structure_stored.set_extra(
                "chem_formula", ase_structure.get_chemical_formula())
        except AttributeError:
            print("could not set either num_atoms or chemical_formula " \
                  " on {}".format(ase_structure))
            pass

        # add the structure to the group
        g.add_nodes(aiida_structure_stored)
        g.store()
        i += 1