Exemplo n.º 1
0
    def parse_win(self):
        """Create the wannier90 .win file and kpoints output nodes."""
        win = self.get_file('wannier90.win')
        if not win:
            return False, None, None, None
        win_result = WinParser(win).result

        # remove kpoints block from parameters
        kpoints = win_result.pop('kpoints', None)
        success, kpoints_node = self.convert_kpoints(kpoints)

        # remove structure (cannot be given in parameters)
        win_result.pop('unit_cell_cart', None)
        win_result.pop('atoms_cart', None)

        projections = win_result.pop('projections', None)
        if projections is None:
            proj_node = None
        else:
            proj_node = List()
            proj_node.extend(projections)

        param_node = DataFactory('parameter')(dict=win_result)
        return success, kpoints_node, param_node, proj_node
def test_full_nio_afm(new_database):
    from aiida.orm import DataFactory
    from aiida_crystal17.workflows.cry_main_immigrant import migrate_as_main
    # from aiida.common.datastructures import calc_states

    work_dir = TEST_DIR
    inpath = os.path.join("input_files", 'nio_sto3g_afm.crystal.d12')
    outpath = os.path.join("output_files", 'nio_sto3g_afm.crystal.out')

    node = migrate_as_main(
        work_dir,
        inpath,
        outpath,
        input_links={
            'structure': {
                "struct_setup": DataFactory('parameter')()
            }
        })

    print(list(node.attrs()))

    assert node.is_stored

    assert set(node.get_inputs_dict().keys()) == set(
        ['basis_Ni', 'basis_O', 'parameters', 'structure', 'settings'])

    struct = node.inp.structure
    assert "struct_setup" in struct.get_inputs_dict()[
        'structure'].get_inputs_dict()

    print(node.get_outputs_dict())

    assert set(node.get_outputs_dict().keys()).issuperset(
        ['output_parameters', 'retrieved'])

    assert '_aiida_cached_from' not in node.extras()
Exemplo n.º 3
0
    def inner(projections_dict={'kind_name': 'As', 'ang_mtm_name': 'sp3'}):
        from aiida.orm import DataFactory, CalculationFactory
        from aiida_wannier90.orbitals import generate_projections

        res = dict()

        a = 5.367 * pymatgen.core.units.bohr_to_ang
        structure_pmg = pymatgen.Structure(lattice=[[-a, 0, a], [0, a, a],
                                                    [-a, a, 0]],
                                           species=['Ga', 'As'],
                                           coords=[[0] * 3, [0.25] * 3])
        structure = DataFactory('structure')()
        structure.set_pymatgen_structure(structure_pmg)
        res['structure'] = structure

        res['projections'] = generate_projections(projections_dict,
                                                  structure=structure)

        KpointsData = DataFactory('array.kpoints')
        kpoints = KpointsData()
        kpoints.set_kpoints_mesh([2, 2, 2])
        res['kpoints'] = kpoints

        kpoint_path_tmp = KpointsData()
        kpoint_path_tmp.set_cell_from_structure(structure)
        kpoint_path_tmp.set_kpoints_path()
        point_coords, path = kpoint_path_tmp.get_special_points()
        kpoint_path = DataFactory('parameter')(dict={
            'path': path,
            'point_coords': point_coords,
        })
        res['kpoint_path'] = kpoint_path

        res['parameters'] = DataFactory('parameter')(
            dict=dict(num_wann=4, num_iter=12, wvfn_formatted=True))
        return res
# -*- coding: utf-8 -*-
from __future__ import division
import aiida.common
from aiida.common import aiidalogger
from aiida.orm.workflow import Workflow
from aiida.orm import Code, Computer
from aiida.orm import CalculationFactory, DataFactory
from aiida.orm.utils import load_node

__copyright__ = u"Copyright (c), This file is part of the AiiDA platform. For further information please visit http://www.aiida.net/. All rights reserved."
__license__ = "MIT license, see LICENSE.txt file."
__version__ = "0.7.0"
__authors__ = "The AiiDA team."

LapwbasisData = DataFactory('lapwbasis')
ParameterData = DataFactory('parameter')
KpointsData = DataFactory('array.kpoints')
StructureData = DataFactory('structure')

logger = aiidalogger.getChild('WorkflowStressTensor')

## ===============================================
##    Workflow_LAPW_Stress_Tensor_Lagrange
## ===============================================


class Workflow_LAPW_stress_tensor_Lagrange(Workflow):
    def __init__(self, **kwargs):

        super(Workflow_LAPW_stress_tensor_Lagrange, self).__init__(**kwargs)
Exemplo n.º 5
0
"""AiiDA - Workflow to get bandstructure of a material using VASP"""
from aiida.common import aiidalogger
from aiida.orm.workflow import Workflow
from aiida.orm import DataFactory

from aiida_vasp.calcs.maker import VaspMaker

LOGGER = aiidalogger.getChild('Bandstructure')
PARAMETER_CLS = DataFactory('parameter')


class Bandstructure(Workflow):
    """
    AiiDA workflow to get bandstructure of a material using VASP.

    Necessary steps are:
        * selfconsistent run with few kpoints
        * nonselfconsistent run with more kpoints and CHGCAR from
          selfconsistent run
    """
    def get_calc_maker(self):
        """Return an VaspMaker instance."""
        from aiida.orm import Code
        params = self.get_parameters()
        maker = VaspMaker(structure=params['structure'])
        maker.add_parameters(icharg=0,
                             istart=0,
                             lorbit=11,
                             lsorbit=True,
                             sigma=0.05,
                             ismear=0,
Exemplo n.º 6
0
from distutils.spawn import find_executable
from tempfile import NamedTemporaryFile
from subprocess import Popen, PIPE, STDOUT
from pymatgen import Structure, Lattice
from pymatgen.io.cif import CifWriter
import numpy as np
from sys import path
from aiida.orm import Str, Bool, Int, Float
from aiida.orm import DataFactory
from aiida.work.workchain import WorkChain, if_, while_, return_

path.insert(0, 'GLOSIM2')
from libmatch.soap import get_soap
from libmatch.utils import ase2qp, get_spkit, get_spkitMax

StructureData = DataFactory('structure')


class SOAP(WorkChain):

    @classmethod
    def define(cls, spec):
        super(SOAP, cls).define(spec)
        spec.input('aiida_structure', valid_type=StructureData)
        spec.input('spkit_max', valid_type=ParameterData)
        spec.input('aononymize', valid_type=Bool, default=Bool(True))
        spec.input('scale', valid_type=Bool, default=Bool(True))
        spec.input('scale_per', valid_type=Str, default=Str('site'))
        spec.input('soapargs', valid_type=ParameterData, required=False)
        spec.outline(
            cls.get_quippy_atoms,
Exemplo n.º 7
0
def datify(type_or_str):
    if isinstance(type_or_str, str):
        return DataFactory(type_or_str)
    return type_or_str
Exemplo n.º 8
0
quasiparticle = False

from aiida import load_dbenv
from aiida.orm import Code, DataFactory
from aiida.orm.calculation.inline import make_inline

from aiida.orm.workflow import Workflow

if quasiparticle:
    from aiida.workflows.wf_quasiparticle import WorkflowQuasiparticle as WorkflowPhonon
else:
    from aiida.workflows.wf_phonon import WorkflowPhonon

from aiida.orm import load_workflow

StructureData = DataFactory('structure')
ParameterData = DataFactory('parameter')
ArrayData = DataFactory('array')


@make_inline
def calculate_qha_inline(**kwargs):

    from phonopy import PhonopyQHA
    from phonopy.structure.atoms import Atoms as PhonopyAtoms
    import numpy as np

    #   structures = kwargs.pop('structures')
    #   optimized_data = kwargs.pop('optimized_data')
    #   thermodyamic_properties = kwargs.pop('thermodyamic_properties')
Exemplo n.º 9
0
# This file is used to generate inputs for the 3 different supported codes: VASP, QE and LAMMPS. This is implemented
# in 3 functions: generate_vasp_params(), generate_qe_params() and generate_lammps_params().
# generate_inputs() function at the end of the file decides which function to use according to the plugin

from aiida.orm import Code, CalculationFactory, DataFactory
from aiida.common.exceptions import InputValidationError

KpointsData = DataFactory("array.kpoints")
ParameterData = DataFactory('parameter')
StructureData = DataFactory('structure')


# Function obtained from aiida's quantumespresso plugin. Copied here for convenience
def get_pseudos_qe(structure, family_name):
    """
    Set the pseudo to use for all atomic kinds, picking pseudos from the
    family with name family_name.

    :note: The structure must already be set.

    :param family_name: the name of the group containing the pseudos
    """
    from collections import defaultdict
    from aiida.orm.data.upf import get_pseudos_from_structure

    # A dict {kind_name: pseudo_object}
    kind_pseudo_dict = get_pseudos_from_structure(structure, family_name)

    # We have to group the species by pseudo, I use the pseudo PK
    # pseudo_dict will just map PK->pseudo_object
    pseudo_dict = {}
Exemplo n.º 10
0
import json

from aiida.orm.calculation.job import JobCalculation
from aiida.common.utils import classproperty
from aiida.common.exceptions import (InputValidationError, ValidationError)
from aiida.common.datastructures import (CalcInfo, CodeInfo)
from aiida.orm import DataFactory

MultiplyParameters = DataFactory('template.factors')


class MultiplyCalculation(JobCalculation):
    '''AiiDA calculation plugin for simple "multiplication"
    
    Simple AiiDA plugin for wrapping a code that adds two numbers.
    '''
    def _init_internal_params(self):
        # reuse base class function
        super(MultiplyCalculation, self)._init_internal_params()

        self._INPUT_FILE_NAME = 'in.json'
        self._OUTPUT_FILE_NAME = 'out.json'
        # template.product entry point defined in setup.json
        self._default_parser = 'template.product'

    @classproperty
    def _use_methods(cls):
        """Add use_* methods for calculations.
        
        Code below enables the usage
        my_calculation.use_parameters(my_parameters)
Exemplo n.º 11
0
class VaspMaker(object):
    """
    Simplifies creating a Scf, Nscf or AmnCalculation from scratch interactively or as a copy or continuation of a previous calculation.

    Further simplifies creating certain often used types of calculations.

    Most of the required information can be given as keyword arguments to
    the constructor or set via properties later on.

    The input information is stored in the instance and the calculation
    is only built in the :py:meth:`new` method. This also makes it possible
    to create a set of similar calculations in an interactive setting very
    quickly.

    :param structure: A StructureData node or a
        (relative) path to either a .cif file or a POSCAR file. Defaults to
        a new empty structure node recieved from calc_cls.
    :type structure: str or StructureData

    :keyword calc_cls: the class that VaspMaker will use when creating
        Calculation nodes.
        defaults to 'vasp.vasp'.
        if a string is given, it will be passed to aiida's CalculationFactory
    :type calc_cls: str or vasp.BasicCalculation subclass

    :keyword continue_from: A vasp calculation node with charge_density and
        wavefunction output links. VaspMaker will create calculations that
        start with those as inputs.
    :type continue_from: vasp calculation node

    :keyword copy_from: A vasp calculation. It's inputs will be used as
        defaults for the created calculations.
    :type copy_from: vasp calculation node

    :keyword charge_density: chargedensity node from a previously run
        calculation
    :type charge_density: ChargedensityData

    :keyword wavefunctions: wavefunctions node from a previously run
        calculation
    :type wavefunctions: WavefunData

    :keyword array.KpointsData kpoints: kpoints node to use for input

    :keyword str paw_family: The name of a PAW family stored in the db

    :keyword str paw_map: A dictionary mapping element symbols -> PAW symbols

    :keyword str label: value for the calculation label

    :keyword str computer: computer name, defaults to code's if code is given

    :keyword str code: code name, if any Calculations are given, defaults to their code

    :keyword str resources: defaults to copy_from.get_resources() or None

    :keyword str queue: defaults to queue from given calculation, if any, or None


    .. py:method:: new()

        :returns: an instance of :py:attr:`calc_cls`, initialized with the data held by the VaspMaker

    .. py:method:: add_parameters(**kwargs)

        Adds keys to the parameters (INCAR keywords), if parameters is already
        stored, makes a copy.
        Does not overwrite previously set keywords.

    .. py:method:: rewrite_parameters(**kwargs)

        Same as :py:meth:`add_parameters`, but also overwrites keywords.

    .. py:attribute:: structure

        Used to initialize the created calculations as well as other nodes
        (like kpoints).
        When changed, can trigger changes in other data nodes.

    .. py:attribute:: calc_cls

        Vasp calculation class to be used in :py:meth:`new`

    .. py:attribute:: computer

    .. py:attribute:: code

    .. py:attribute:: queue

    .. py:attribute:: parameters

        A readonly shortcut to the contents of the parameters node

    .. py:attribute:: kpoints

        The kpoints node to be used, may be copied to have py:func:set_cell
        called.

    .. py:attribute:: wavefunction

    .. py:attribute:: charge_density

    .. py:attribute:: elements

        Chemical symbols of the elements contained in py:attr:structure
    """
    def __init__(self, *args, **kwargs):
        self._recipe = None
        self._parameters = None
        self._queue = None
        self._computer = None
        self._code = None
        self._wannier_data = None
        self._charge_density = None
        self._wavefunctions = None
        self._wannier_parameters = None
        self._kpoints = None
        self._structure = None

        self._init_defaults(*args, **kwargs)
        self._calcname = kwargs.get('calc_cls')
        if 'continue_from' in kwargs:
            self._init_from(kwargs['continue_from'])
        if 'copy_from' in kwargs:
            self._copy_from(kwargs['copy_from'])

    def _init_defaults(self, *args, **kwargs):  # pylint: disable=unused-argument
        """Set default values"""
        calcname = kwargs.get('calc_cls', 'vasp.vasp')
        if isinstance(calcname, (str, unicode)):
            self.calc_cls = CalculationFactory(calcname)
        else:
            self.calc_cls = calcname
        self.label = kwargs.get('label', 'unlabeled')
        self._computer = kwargs.get('computer')
        self._code = kwargs.get('code')
        self._parameters = kwargs.get('parameters',
                                      self.calc_cls.new_parameters())
        self._set_default_structure(kwargs.get('structure'))
        self._paw_fam = kwargs.get('paw_family', 'PBE')
        self._paw_def = kwargs.get('paw_map')
        self._paws = {}
        self._set_default_paws()
        self._kpoints = kwargs.get('kpoints', self.calc_cls.new_kpoints())
        self.kpoints = self._kpoints
        self._charge_density = kwargs.get('charge_density', None)
        self._wavefunctions = kwargs.get('wavefunctions', None)
        self._wannier_parameters = kwargs.get('wannier_parameters', None)
        self._wannier_data = kwargs.get('wannier_data', None)
        self._recipe = None
        self._queue = kwargs.get('queue')
        self._resources = kwargs.get('resources', {})

    def _copy_from(self, calc):
        """Copy data links from another calculation"""
        ins = calc.get_inputs_dict()
        if not self._calcname:
            self.calc_cls = calc.__class__
        self.label = calc.label + '_copy'
        self._computer = calc.get_computer()
        self._code = calc.get_code()
        self._parameters = ins.get('parameters')
        self._structure = ins.get('structure')
        self._paws = {}
        for paw in [i for i in ins.iteritems() if 'paw' in i[0]]:
            self._paws[paw[0].replace('paw_', '')] = paw[1]
        self._kpoints = ins.get('kpoints')
        self._charge_density = ins.get('charge_density')
        self._wavefunctions = ins.get('wavefunctions')
        self._wannier_parameters = ins.get('wannier_parameters')
        self._wannier_data = ins.get('wannier_data')
        self._queue = calc.get_queue_name()
        self._resources = calc.get_resources()

    def _set_default_structure(self, structure):
        """Set a structure depending on what was given, empty if nothing was given"""
        if not structure:
            self._structure = self.calc_cls.new_structure()
        elif isinstance(structure, (str, unicode)):
            structure = os.path.abspath(os.path.expanduser(structure))
            if os.path.splitext(structure)[1] == '.cif':
                self._structure = DataFactory('cif').get_or_create(
                    structure)[0]
            elif os.path.basename(structure) == 'POSCAR':
                from ase.io.vasp import read_vasp
                atoms = read_vasp(os.path.abspath(structure))
                self._structure = self.calc_cls.new_structure()
                self._structure.set_ase(atoms)
        else:
            self._structure = structure

    def _init_from(self, prev):
        """Initialize from an already run calculation"""
        out = prev.get_outputs_dict()
        self._copy_from(prev)
        if 'structure' in out:
            self.structure = prev.out.structure
        self.rewrite_parameters(istart=1, icharg=11)
        self.wavefunctions = prev.out.wavefunctions
        self.charge_density = prev.out.charge_density
        self._wannier_parameters = out.get('wannier_parameters',
                                           self._wannier_parameters)
        self._wannier_data = out.get('wannier_data', self.wannier_data)

    def new(self):
        """Create a new, unstored Calculation node from previously set properties."""
        calc = self.calc_cls()
        calc.use_code(self._code)
        calc.use_structure(self._structure)
        for k in self.elements:
            calc.use_paw(self._paws[k], kind=k)
        calc.use_parameters(self._parameters)
        calc.use_kpoints(self._kpoints)
        calc.set_computer(self._computer)
        calc.set_queue_name(self._queue)
        if self._charge_density:
            calc.use_charge_density(self._charge_density)
        if self._wavefunctions:
            calc.use_wavefunctions(self._wavefunctions)
        if self._wannier_parameters:
            calc.use_wannier_parameters(self._wannier_parameters)
        if self._wannier_data:
            calc.use_wannier_data(self._wannier_data)
        calc.label = self.label
        calc.set_resources(self._resources)
        return calc

    @property
    def structure(self):
        return self._structure

    @structure.setter
    def structure(self, val):
        self._set_default_structure(val)
        self._set_default_paws()
        if self._kpoints.pk:
            self._kpoints = self._kpoints.copy()
        self._kpoints.set_cell(self._structure.get_ase().get_cell())

    @property
    def parameters(self):
        return self._parameters.get_dict()

    @property
    def kpoints(self):
        return self._kpoints

    @kpoints.setter
    def kpoints(self, kpoints):
        self._kpoints = kpoints
        self._kpoints.set_cell(self._structure.get_ase().get_cell())

    def set_kpoints_path(self, value=None, weights=None, **kwargs):
        """
        Calls kpoints' set_kpoints_path method with value, automatically adds weights.

        Copies the kpoints node if it's already stored.
        """
        if self._kpoints.is_stored:
            self.kpoints = self.calc_cls.new_kpoints()
        self._kpoints.set_kpoints_path(value=value, **kwargs)
        if not weights:
            kp_list = self._kpoints.get_kpoints()
            weights = [1. for _ in kp_list]
            self._kpoints.set_kpoints(kp_list, weights=weights)

    def set_kpoints_mesh(self, *args, **kwargs):
        """Passes arguments on to kpoints.set_kpoints_mesh, copies if it was already stored."""
        if self._kpoints.pk:
            self.kpoints = self.calc_cls.new_kpoints()
        self._kpoints.set_kpoints_mesh(*args, **kwargs)

    def set_kpoints_list(self, kpoints, weights=None, **kwargs):
        """Passes arguments on to kpoints.set_kpoints, copies if it was already stored."""
        import numpy as np
        if self._kpoints.pk:
            self.kpoints = self.calc_cls.new_kpoints()
        if not weights:
            weights = np.ones(len(kpoints), dtype=float)
        self._kpoints.set_kpoints(kpoints, weights=weights, **kwargs)

    @property
    def wavefunctions(self):
        return self._wavefunctions

    @wavefunctions.setter
    def wavefunctions(self, val):
        self._wavefunctions = val
        self.add_parameters(istart=1)

    @property
    def charge_density(self):
        return self._charge_density

    @charge_density.setter
    def charge_density(self, val):
        self._charge_density = val
        self.add_parameters(icharg=11)

    @property
    def wannier_parameters(self):
        return self._wannier_parameters

    @wannier_parameters.setter
    def wannier_parameters(self, val):
        self._wannier_parameters = val
        if 'lwannier90' not in self.parameters:
            self.add_parameters(lwannier90=True)

    @property
    def wannier_data(self):
        return self._wannier_data

    @wannier_data.setter
    def wannier_data(self, val):
        self._wannier_data = val

    @property
    def code(self):
        return self._code

    @code.setter
    def code(self, val):
        self._code = val
        self._computer = val.get_computer()

    @property
    def computer(self):
        return self._computer

    @computer.setter
    def computer(self, val):
        self._computer = val

    @property
    def queue(self):
        return self._queue

    @queue.setter
    def queue(self, val):
        self._queue = val

    @property
    def resources(self):
        return self._resources

    @resources.setter
    def resources(self, val):
        if isinstance(val, dict):
            self._resources.update(val)
        else:
            self._resources['num_machines'] = val[0]
            self._resources['num_mpiprocs_per_machine'] = val[1]

    def add_parameters(self, **kwargs):
        """Add additional parameters to the generated calculation, does not override existing parameters."""
        if self._parameters.pk:
            self._parameters = self._parameters.copy()
        for key, value in kwargs.iteritems():
            if key not in self.parameters:
                self._parameters.update_dict({key: value})

    def rewrite_parameters(self, **kwargs):
        if self._parameters_conflict(kwargs):
            if self._parameters.pk:
                self._parameters = self._parameters.copy()
            self._parameters.update_dict(kwargs)

    def _parameters_conflict(self, parameters):
        conflict = False
        for key, value in parameters.iteritems():
            conflict |= (self.parameters.get(key) != value)
        return conflict

    def _set_default_paws(self):
        """Set default POTCAR potentials from the given mapping."""
        for key in self.elements:
            if key not in self._paws:
                if self._paw_def is None:
                    raise ValueError(
                        "The 'paw_map' keyword is required. Pre-defined potential "
                        "mappings are defined in 'aiida.tools.codespecific.vasp.default_paws'."
                    )
                try:
                    paw = self.calc_cls.Paw.load_paw(
                        family=self._paw_fam, symbol=self._paw_def[key])[0]
                except KeyError:
                    raise ValueError(
                        "The given 'paw_map' does not contain a mapping for element '{}'"
                        .format(key))
                self._paws[key] = paw

    @property
    def elements(self):
        return ordered_unique_list(
            self._structure.get_ase().get_chemical_symbols())

    @staticmethod
    def compare_pk(node_a, node_b):
        """Compare two nodes by primary key"""
        if node_a.pk < node_b.pk:
            return -1
        elif node_a.pk > node_b.pk:
            return 1
        return 0

    def verify_parameters(self):
        """
        Verify input parameters

        :return: (bool, string) success, message
        """
        if not self._structure:
            raise ValueError('need structure,')
        magmom = self.parameters.get('magmom', [])
        lsorb = self.parameters.get('lsorbit', False)
        lnonc = self.parameters.get('lnoncollinear', False)
        parameters_ok = True
        msg = 'Everything ok'
        nmag = len(magmom)
        nsit = self.n_ions
        if lsorb:
            if lnonc:
                if magmom and not nmag == 3 * nsit:
                    parameters_ok = False
                    msg = 'magmom has wrong dimension'
            else:
                if magmom and not nmag == nsit:
                    parameters_ok = False
                    msg = 'magmom has wrong dimension'
        else:
            if magmom and not nmag == nsit:
                parameters_ok = False
                msg = 'magmom has wrong dimension'
        return parameters_ok, msg

    def check_magmom(self):
        """Check that the magnetic moment given in parameters matches the one of the structure"""
        magnetic_moment = self.parameters.get('magmom', [])
        structure_mm = self._structure.get_ase().get_initial_magnetic_moments()
        lsf = 3 if self.noncol else 1
        nio = self.n_ions
        structure_mm_dim = nio * lsf
        magnetic_moment_dim = len(magnetic_moment)
        if magnetic_moment and structure_mm:
            return structure_mm_dim == magnetic_moment_dim
        return True

    def set_magmom_1(self, val):
        magmom = [val]
        magmom *= self.n_ions
        magmom *= self.noncol and 3 or 1
        self.rewrite_parameters(magmom=magmom)

    @property
    def nbands(self):
        return self.n_ions * 3 * (self.noncol and 3 or 1)

    @property
    def n_ions(self):
        return self.structure.get_ase().get_number_of_atoms()

    @property
    def n_elec(self):
        """Get the number of electrons based on the chemical symbols."""
        res = 0
        for k in self._structure.get_ase().get_chemical_symbols():
            res += self._paws[k].valence
        return res

    @property
    def noncol(self):
        lsorb = self.parameters.get('lsorbit', False)
        lnonc = self.parameters.get('lnoncollinear', False)
        return lsorb or lnonc

    @property
    def icharg(self):
        return self.parameters.get('icharg', 'default')

    @icharg.setter
    def icharg(self, value):
        if value not in [0, 1, 2, 4, 10, 11, 12]:
            raise ValueError('invalid ICHARG value for vasp 5.3.5')
        else:
            self.parameters['icharg'] = value

    @property
    def recipe(self):
        return self._recipe

    @recipe.setter
    def recipe(self, val):
        if self._recipe and self._recipe != val:
            raise ValueError('recipe is already set to something else')
        self._init_recipe(val)
        self._recipe = val

    def _init_recipe(self, recipe):
        if recipe == 'test_sc':
            self._init_recipe_test_sc()
        else:
            raise ValueError('recipe not recognized')

    def _init_recipe_test_sc(self):
        self.add_parameters(
            gga='PE',
            gga_compat=False,
            ismear=0,
            lorbit=11,
            lsorbit=True,
            sigma=0.05,
        )
Exemplo n.º 12
0
from aiida.orm import load_node
from aiida.orm.code import Code
from aiida.orm.data.base import Bool, Str
from aiida.work import workfunction as wf
from aiida.work.run import run, submit
from aiida.work.workchain import WorkChain, ToContext, if_, while_, Outputs

# subworkflows
from workflows.charges import DdecChargesWorkChain
from aiida_raspa.workflows import RaspaConvergeWorkChain

# calculations
ZeoppCalculation = CalculationFactory('zeopp.network')

# data objects
ArrayData = DataFactory('array')
CifData = DataFactory('cif')
NetworkParameters = DataFactory('zeopp.parameters')
ParameterData = DataFactory('parameter')
RemoteData = DataFactory('remote')
StructureData = DataFactory('structure')


@wf
def from_cif_to_structuredata(cif):
    """Helper function that converts CifData object into StructureData"""
    a = cif.get_ase()
    return StructureData(ase=a)


class Isotherm(WorkChain):
Exemplo n.º 13
0
#!/usr/bin/env runaiida
# -*- coding: utf-8 -*-
import sys
import os
from aiida.orm import DataFactory, CalculationFactory
from aiida.common.example_helpers import test_and_get_code
from aiida.orm.data.base import List
from aiida.orm import Code
from aiida.orm import DataFactory
import pymatgen
from aiida.work.run import submit
from aiida_yambo.calculations.gw import YamboCalculation
from aiida_quantumespresso.calculations.pw import PwCalculation
from aiida.orm.data.upf import UpfData, get_pseudos_from_structure

ParameterData = DataFactory('parameter')

parameters = ParameterData(
    dict={
        'CONTROL': {
            'calculation': 'nscf',
            'restart_mode': 'from_scratch',
            'wf_collect': True,
            'verbosity': 'high',
        },
        'SYSTEM': {
            'ecutwfc': 80.,
            'nbnd': 50,
            'force_symmorphic': True,
        },
        'ELECTRONS': {
Exemplo n.º 14
0
    def _get_bands(self):
        """
        Create a bands and a kpoints node from values in eigenvalue.

        :returns: bsnode, kpout

        * bsnode: BandsData containing eigenvalues from EIGENVAL
                and occupations from vasprun.xml
        * kpout: KpointsData containing kpoints from EIGENVAL,
        both bsnode as well as kpnode come with cell unset
        """
        eig = self.get_file('EIGENVAL')
        if not eig:
            return {'bands': None, 'kpoints': None}

        _, kpoints, bands = EigParser.parse_eigenval(eig)
        bsnode = DataFactory('array.bands')()
        kpout = DataFactory('array.kpoints')()
        # Take the output structure if available.
        structure = None
        if 'structure' in self._output_nodes:
            structure = self._output_nodes['structure']
        if structure is None:
            structure = self._calc.inp.structure
        bsnode.set_cell(structure.get_ase().get_cell())
        kpout.set_cell(structure.get_ase().get_cell())
        if self._calc.inp.kpoints.get_attrs().get('array|kpoints'):
            bsnode.set_kpointsdata(self._calc.inp.kpoints)
        if self._calc.inp.kpoints.labels:
            bsnode.labels = self._calc.inp.kpoints.labels
        else:
            bsnode.set_kpoints(kpoints[:, :3],
                               weights=kpoints[:, 3],
                               cartesian=False)
        bsnode.set_bands(bands,
                         occupations=self._parsers['vasprun.xml'].occupations)
        kpout.set_kpoints(kpoints[:, :3],
                          weights=kpoints[:, 3],
                          cartesian=False)
        return {'bands': bsnode, 'kpoints': kpout}
Exemplo n.º 15
0
from __future__ import print_function

from aiida.orm import CalculationFactory, DataFactory
from aiida.orm.code import Code
from aiida.work import workfunction as wf
from aiida.work.run import submit
from aiida.work.workchain import WorkChain, ToContext, Outputs
from aiida_cp2k.workflows import Cp2kDftBaseWorkChain
from copy import deepcopy

# calculations 
DdecCalculation = CalculationFactory('ddec')

# data objects
CifData = DataFactory('cif')
ParameterData = DataFactory('parameter')
RemoteData = DataFactory('remote')
StructureData = DataFactory('structure')


def dict_merge(dct, merge_dct):
    """ Taken from https://gist.github.com/angstwad/bf22d1822c38a92ec0a9
    Recursive dict merge. Inspired by :meth:``dict.update()``, instead of
    updating only top-level keys, dict_merge recurses down into dicts nested
    to an arbitrary depth, updating keys. The ``merge_dct`` is merged into
    ``dct``.
    :param dct: dict onto which the merge is executed
    :param merge_dct: dct merged into dct
    :return: None
    """
    import collections
Exemplo n.º 16
0
#!/usr/bin/env python
"""
This test runs the fleur_convergence workflow for path 2
"""
#TODO: overall tests, should create the nodes they use in the db.

from aiida import load_dbenv, is_dbenv_loaded
if not is_dbenv_loaded():
    load_dbenv()
from aiida.orm import Code, DataFactory
from aiida.orm import load_node
#from aiida.work.run import async, run
from aiida_fleur.workflows.scf import fleur_scf_wc

StructureData = DataFactory('structure')
ParameterData = DataFactory('parameter')
KpointsData = DataFactory('array.kpoints')
#FleurinpData = DataFactory('fleurinp.fleurinp')
FleurinpData = DataFactory('fleur.fleurinp')

###############################
# Set your values here
codename = 'inpgen_iff@local_iff'  #'inpgen_mac_30_11_2016@local_mac'
codename2 = 'fleur_iff@local_iff'  #'fleur_mac_v0_27@local_mac'
###############################

code = Code.get_from_string(codename)
code2 = Code.get_from_string(codename2)

wf_para = ParameterData(
    dict={
Exemplo n.º 17
0
from aiida.work.workfunction import workfunction

from aiida.orm import Code, CalculationFactory, load_node, DataFactory, WorkflowFactory
from aiida.work.run import run, submit

from aiida.orm.data.base import Str, Float, Bool, Int
from aiida.work.workchain import _If, _While

import numpy as np
from aiida_phonopy.common.generate_inputs import generate_inputs

# Should be improved by some kind of WorkChainFactory
# For now all workchains should be copied to aiida/workflows
# from aiida.workflows.wc_optimize import OptimizeStructure

ForceConstantsData = DataFactory('phonopy.force_constants')
ForceSetsData = DataFactory('phonopy.force_sets')
BandStructureData = DataFactory('phonopy.band_structure')
PhononDosData = DataFactory('phonopy.phonon_dos')
NacData = DataFactory('phonopy.nac')

ParameterData = DataFactory('parameter')
ArrayData = DataFactory('array')
StructureData = DataFactory('structure')

OptimizeStructure = WorkflowFactory('phonopy.optimize')

__testing__ = False


@workfunction
Exemplo n.º 18
0
__authors__ = "The AiiDA team."

import sys
import os

from aiida.common.example_helpers import test_and_get_code
from aiida.orm import DataFactory
from aiida.common.exceptions import NotExistent

# If set to True, will ask AiiDA to run in serial mode (i.e., AiiDA will not
# invoke the mpirun command in the submission script)
run_in_serial_mode = False

################################################################

UpfData = DataFactory('upf')
ParameterData = DataFactory('parameter')
KpointsData = DataFactory('array.kpoints')
StructureData = DataFactory('structure')
try:
    dontsend = sys.argv[1]
    if dontsend == "--dont-send":
        submit_test = True
    elif dontsend == "--send":
        submit_test = False
    else:
        raise IndexError
except IndexError:
    print >> sys.stderr, ("The first parameter can only be either "
                          "--send or --dont-send")
    sys.exit(1)
Exemplo n.º 19
0
# -*- coding: utf-8 -*-
from __future__ import print_function
from __future__ import absolute_import

from aiida.common.example_helpers import test_and_get_code
from aiida.orm import DataFactory, CalculationFactory
from aiida.work.run import submit
from aiida.orm import load_node

# Data classes
CifData = DataFactory('cif')
ParameterData = DataFactory('parameter')
RaspaCalculation = CalculationFactory('raspa')

# Raspa input parameters
parameters = ParameterData(dict={
    "GeneralSettings": {
         "SimulationType"                : "MonteCarlo",
         "NumberOfCycles"                : 1000,
         "NumberOfInitializationCycles"  : 1000,
         "PrintEvery"                    : 100,

         "CutOff"                        : 12.0,  # (Angstroms)

         "Forcefield"                    : "UFF-TraPPE",
         "ChargeMethod"                  : "None",
         "UnitCells"                     : "<int> <int> <int>",

         "ExternalTemperature"           : <float (K)>,
         "ExternalPressure"              : <float (Pa)>,
    },
Exemplo n.º 20
0
    def generate_calculation_vasp(self,
                                  structure,
                                  parameters,
                                  type='optimize',
                                  pressure=0.0):
        # import pymatgen as mg
        from pymatgen.io import vasp as vaspio

        ParameterData = DataFactory('parameter')

        code = Code.get_from_string(parameters['code'])

        # Set calculation
        calc = code.new_calc(max_wallclock_seconds=3600,
                             resources=parameters['resources'])
        calc.set_withmpi(True)
        calc.label = 'VASP'

        # POSCAR
        calc.use_structure(structure)

        # INCAR
        incar = parameters['parameters']

        if type == 'optimize':
            vasp_input_optimize = dict(incar)
            vasp_input_optimize.update({
                'PREC': 'Accurate',
                'ISTART': 0,
                'IBRION': 2,
                'ISIF': 3,
                'NSW': 100,
                'LWAVE': '.FALSE.',
                'LCHARG': '.FALSE.',
                'EDIFF': 1e-08,
                'EDIFFG': -1e-08,
                'ADDGRID': '.TRUE.',
                'LREAL': '.FALSE.',
                'PSTRESS': pressure
            })  # unit: kb -> kB
            incar = vasp_input_optimize

        if type == 'optimize_constant_volume':
            vasp_input_optimize = dict(incar)
            vasp_input_optimize.update({
                'PREC': 'Accurate',
                'ISTART': 0,
                'IBRION': 2,
                'ISIF': 4,
                'NSW': 100,
                'LWAVE': '.FALSE.',
                'LCHARG': '.FALSE.',
                'EDIFF': 1e-08,
                'EDIFFG': -1e-08,
                'ADDGRID': '.TRUE.',
                'LREAL': '.FALSE.'
            })
            incar = vasp_input_optimize

        if type == 'forces':
            vasp_input_forces = dict(incar)
            vasp_input_forces.update({
                'PREC': 'Accurate',
                'ISYM': 0,
                'ISTART': 0,
                'IBRION': -1,
                'NSW': 1,
                'LWAVE': '.FALSE.',
                'LCHARG': '.FALSE.',
                'EDIFF': 1e-08,
                'ADDGRID': '.TRUE.',
                'LREAL': '.FALSE.'
            })
            incar = vasp_input_forces

        if type == 'born_charges':
            vasp_input_epsilon = dict(incar)
            vasp_input_epsilon.update({
                'PREC': 'Accurate',
                'LEPSILON': '.TRUE.',
                'ISTART': 0,
                'IBRION': 1,
                'NSW': 0,
                'LWAVE': '.FALSE.',
                'LCHARG': '.FALSE.',
                'EDIFF': 1e-08,
                'ADDGRID': '.TRUE.',
                'LREAL': '.FALSE.'
            })
            incar = vasp_input_epsilon

        # KPOINTS
        kpoints = parameters['kpoints']
        if 'kpoints_per_atom' in kpoints:
            kpoints = vaspio.Kpoints.automatic_density(
                structure.get_pymatgen_structure(),
                kpoints['kpoints_per_atom'])
#            num_kpoints = np.product(kpoints.kpts)
#            if num_kpoints < 4:
#                incar['ISMEAR'] = 0
#                incar['SIGMA'] = 0.05

        else:
            if not 'style' in kpoints:
                kpoints['style'] = 'Monkhorst'
            # supported_modes = Enum(("Gamma", "Monkhorst", "Automatic", "Line_mode", "Cartesian", "Reciprocal"))
            kpoints = vaspio.Kpoints(comment='aiida generated',
                                     style=kpoints['style'],
                                     kpts=(kpoints['points'], ),
                                     kpts_shift=kpoints['shift'])

        calc.use_kpoints(ParameterData(dict=kpoints.as_dict()))
        # update incar (just in case something changed with kpoints)
        incar = vaspio.Incar(incar)
        calc.use_incar(ParameterData(dict=incar.as_dict()))

        # POTCAR
        pseudo = parameters['pseudo']
        potcar = vaspio.Potcar(symbols=pseudo['symbols'],
                               functional=pseudo['functional'])
        calc.use_potcar(ParameterData(dict=potcar.as_dict()))

        # Parser settings
        settings = {'PARSER_INSTRUCTIONS': []}
        pinstr = settings['PARSER_INSTRUCTIONS']

        pinstr.append({
            'instr': 'array_data_parser',
            'type': 'data',
            'params': {}
        })
        pinstr.append({
            'instr': 'output_parameters',
            'type': 'data',
            'params': {}
        })

        # additional files to return
        settings.setdefault('ADDITIONAL_RETRIEVE_LIST', [
            'vasprun.xml',
        ])

        calc.use_settings(ParameterData(dict=settings))

        calc.store_all()

        return calc