Esempio n. 1
0
    def define(cls, spec):
        super(DdecChargesWorkChain, cls).define(spec)
        #TODO: Change to this when aiida 1.0.0 will be released
        #spec.expose_inputs(Cp2kDftBaseWorkChain, namespace='cp2k', exclude=('structure'))
        spec.input('structure', valid_type=StructureData)
        spec.input('cp2k_code', valid_type=Code)
        spec.input('cp2k_parameters', valid_type=ParameterData, required=False,
                default=ParameterData(dict={}))
        spec.input("cp2k_options", valid_type=ParameterData,
                default=ParameterData(dict=default_options))
        spec.input('cp2k_parent_folder', valid_type=RemoteData,
                default=None, required=False)
        spec.input('ddec_code', valid_type=Code)
        spec.input("ddec_options", valid_type=ParameterData,
                default=ParameterData(dict=default_options))
        spec.input('ddec_parameters', valid_type=ParameterData, required=False,
                default=ParameterData(dict=default_ddec_params))

        spec.outline(
                cls.setup,
                cls.run_cp2k_charge_density,
                cls.run_ddec_point_charges,
                cls.return_results,
                )

        spec.output('output_structure', valid_type=CifData, required=False)
Esempio n. 2
0
 def return_results(self):
     eos = []
     for label in labels:
         eos.append(get_info(self.ctx[label]))
     k = 0
     for i in self.ctx.s0.sites:
         k = k + 1
     vol = []
     en = []
     for s in range(7):
         vol.append(float(eos[s][0]) / k)
         en.append(float(eos[s][1]) / k)
     par, co = fit_birch_murnaghan_params(vol, en)
     #Return information to plot the EOS
     #        ParameterData = DataFactory("parameter")
     #retdict = {
     self.out('initial_structure', self.ctx.s0)  #,
     self.out('result', ParameterData(dict={'eos_data': eos}))  #,
     self.out(
         'fit_res',
         ParameterData(
             dict={
                 'E0': par[0],
                 'E0 units': "eV/atm",
                 'V0': par[1],
                 'V0 units': "ang^3/atm",
                 'B0': par[2],
                 'B0 units': "eV/Ang^3",
                 'B1': par[3]
             }))
Esempio n. 3
0
    def run_relax_and_analyze(self):
        """
        Run the SiestaBaseWorkChain to (relax) and analyze the input structure
        """
        self.report('Running run_relax_and_analyze')

        inputs = dict(self.ctx.inputs)

        ldos_e = "\n {e1} {e2} eV".format(e1=self.inputs.e1, e2=self.inputs.e2)
        inputs['parameters']['%block local-density-of-states'] = ldos_e

        # Final input preparation, wrapping dictionaries in ParameterData nodes
        # The code and options were set above
        # Pseudos was set above in ctx.inputs, and so in inputs

        inputs['kpoints'] = self.ctx.kpoints_mesh
        inputs['basis'] = ParameterData(dict=inputs['basis'])
        inputs['structure'] = self.ctx.structure_initial_primitive
        inputs['parameters'] = ParameterData(dict=inputs['parameters'])
        inputs['settings'] = ParameterData(dict=inputs['settings'])
        inputs['clean_workdir'] = Bool(False)
        inputs['max_iterations'] = Int(20)

        running = submit(SiestaBaseWorkChain, **inputs)
        self.report(
            'launched SiestaBaseWorkChain<{}> in relax+ldos mode'.format(
                running.pid))

        return ToContext(workchain_relax=running)
Esempio n. 4
0
    def define(cls, spec):
        super(Cp2kDftBaseWorkChain, cls).define(spec)
        spec.input('code', valid_type=Code)
        spec.input('structure', valid_type=StructureData)
        spec.input("parameters",
                   valid_type=ParameterData,
                   default=ParameterData(dict={}))
        spec.input("options",
                   valid_type=ParameterData,
                   default=ParameterData(dict=default_options))
        spec.input('parent_folder',
                   valid_type=RemoteData,
                   default=None,
                   required=False)
        spec.input('_guess_multiplisity', valid_type=bool, default=False)

        spec.outline(
            cls.setup,
            while_(cls.should_run_calculation)(
                cls.prepare_calculation,
                cls.run_calculation,
                cls.inspect_calculation,
            ),
            cls.return_results,
        )
        spec.output('output_structure',
                    valid_type=StructureData,
                    required=False)
        spec.output('output_parameters', valid_type=ParameterData)
        spec.output('remote_folder', valid_type=RemoteData)
Esempio n. 5
0
    def run_stm(self):
        """
        Run a STMCalculation with the relaxed_calculation parent folder
        """
        self.report('Running stm calculation')
        # Get the remote folder of the last calculation in the previous workchain
        remote_folder = self.ctx.workchain_relax.get_outputs_dict(
        )['remote_folder']

        stm_inputs = {}
        stm_inputs['code'] = self.ctx.inputs['stm_code']
        stm_inputs['parent_folder'] = remote_folder

        # Height of image plane, in Ang
        stm_inputs['parameters'] = ParameterData(
            dict={'z': self.ctx.inputs['height']})

        # Dummy dict
        settings_dict = {'a': 'b'}
        stm_inputs['settings'] = ParameterData(dict=settings_dict)

        # This should be just a dictionary!
        stm_inputs['_options'] = {
            'resources': {
                'num_machines': 1
            },
            'max_wallclock_seconds': 600
        }

        process = STMCalculation.process()
        running = submit(process, **stm_inputs)

        self.report('launching STMCalculation<{}>'.format(running.pid))

        return ToContext(stm_calc=running)
Esempio n. 6
0
    def run_ph(self):
        """
        Run a PhCalculation either starting from a previous PwCalculation or restarting from a
        previous PhCalculation run in this workchain
        """
        self.ctx.iteration += 1

        # Create local copy of general inputs stored in the context and adapt for next calculation
        inputs = dict(self.ctx.inputs)

        if isinstance(self.ctx.restart_calc, PhCalculation):
            inputs['parameters']['INPUTPH']['recover'] = True
        elif isinstance(self.ctx.restart_calc, PwCalculation):
            pass
        else:
            ctype = type(self.ctx.restart_calc)
            self.abort_nowait(
                "The type '{}' of the parent calculation is invalid".format(
                    ctype))

        inputs['parent_folder'] = self.ctx.restart_calc.out.remote_folder
        inputs['parameters'] = ParameterData(dict=inputs['parameters'])
        inputs['settings'] = ParameterData(dict=inputs['settings'])

        process = PhCalculation.process()
        running = submit(process, **inputs)

        self.report('launching PhCalculation<{}> iteration #{}'.format(
            running.pid, self.ctx.iteration))

        return ToContext(calculations=append_(running))
Esempio n. 7
0
    def _get_output_nodes(self, output_path, error_path):
        """
        Extracts output nodes from the standard output and standard error
        files.
        """
        from aiida.orm.data.parameter import ParameterData
        import re

        formulae = {}
        if output_path is not None:
            with open(output_path) as f:
                content = f.readlines()
            content = [x.strip('\n') for x in content]
            for line in content:
                datablock, formula = re.split('\s+', line, 1)
                formulae[datablock] = formula

        messages = []
        if error_path is not None:
            with open(error_path) as f:
                content = f.readlines()
            messages = [x.strip('\n') for x in content]
            self._check_failed(messages)

        output_nodes = []
        output_nodes.append(
            ('formulae', ParameterData(dict={'formulae': formulae})))
        output_nodes.append(
            ('messages', ParameterData(dict={'output_messages': messages})))

        success = True
        if len(formulae.keys()) == 0:
            success = False

        return success, output_nodes
Esempio n. 8
0
def launch(code, calculation, kpoints, max_num_machines, max_wallclock_seconds,
           daemon, clean_workdir):
    """
    Run the PhBaseWorkChain for a previously completed PwCalculation
    """
    from aiida.orm.data.base import Bool
    from aiida.orm.data.parameter import ParameterData
    from aiida.orm.utils import WorkflowFactory
    from aiida.work.launch import run, submit
    from aiida_quantumespresso.utils.resources import get_default_options

    PhBaseWorkChain = WorkflowFactory('quantumespresso.ph.base')

    parameters = {'INPUTPH': {}}

    options = get_default_options(max_num_machines, max_wallclock_seconds)

    inputs = {
        'code': code,
        'qpoints': kpoints,
        'parent_folder': calculation.out.remote_folder,
        'parameters': ParameterData(dict=parameters),
        'options': ParameterData(dict=options),
    }

    if clean_workdir:
        inputs['clean_workdir'] = Bool(True)

    if daemon:
        workchain = submit(PhBaseWorkChain, **inputs)
        click.echo('Submitted {}<{}> to the daemon'.format(
            PhBaseWorkChain.__name__, workchain.pk))
    else:
        run(PhBaseWorkChain, **inputs)
Esempio n. 9
0
    def prepare_bands_calculation(self):
        """Prepare all the neccessary input links to run the calculation"""
        self.report("prepare calculation 1")
        self.ctx.inputs = AttributeDict({
            'code': self.inputs.code,
            'structure'  : self.ctx.structure,
            '_options'    : self.ctx.options,
            })


        # Conduction band
        cond_band = add_condband(self.ctx.structure)
        self.report("number of states")
        self.report(cond_band)
        self.ctx.parameters['FORCE_EVAL']['DFT']['SCF']['ADDED_MOS'] = cond_band



        # Define path kpoints generated by seekpath
        path = []
        point_coord = {}
        path = self.ctx.kpoints.dict['path']
        point_coord = self.ctx.kpoints.dict['point_coords']

        #self.ctx.parameters = self.ctx.parameters
        kpath = get_kpoints_path_cp2k(point_coord, path)
        self.ctx.parameters['FORCE_EVAL']['DFT']['PRINT']['BAND_STRUCTURE']['KPOINT_SET'] = kpath
        #self.ctx.parameters['FORCE_EVAL']['DFT']['PRINT']['KPOINT_SET']['NPOINTS'] = 14

        # use the new parameters
        p = ParameterData(dict=self.ctx.parameters)
        p.store()
        self.ctx.inputs['parameters'] = p
    def _parser_function(self):
        parser_warnings = {}  # for compatibility

        try:
            errfile = self._params['SCHED_ERROR_FILE']
            errfile = self._out_folder.get_abs_path(errfile)
        except KeyError:
            raise OutputParsingError(
                "{} expects the SCHED_ERROR_FILE to "
                "be provided as a parameter.".format(
                    self.__class__.__name__)
            )
        except OSError:
            raise OutputParsingError(
                "SCHED_ERROR_FILE ({}/{}) not found !".format(
                    self._out_folder.get_abs_path(),
                    self._params['SCHED_ERROR_FILE']
                )
            )

        # === parse errors & warnings ===
        # just a text blob --> no way to parse things more cleanly ?!!
        with open(errfile, 'r') as f:
            errors = f.read()
        # use if/else to make things more explicit
        if errors:
            errors = ParameterData(dict={'runtime_errors': errors})
        else:
            errors = ParameterData(dict={'runtime_errors': None})

        # return [('runtime_errors', errors), ('bad.key', errors)], parser_warnings  # for debug
        return [('runtime_errors', errors)], parser_warnings
Esempio n. 11
0
    def define(cls, spec):
        super(RaspaConvergeWorkChain, cls).define(spec)

        spec.input('code', valid_type=Code)
        spec.input('structure', valid_type=CifData)
        spec.input("parameters",
                   valid_type=ParameterData,
                   default=ParameterData(dict={}))
        spec.input("options",
                   valid_type=ParameterData,
                   default=ParameterData(dict=default_options))
        spec.input('retrieved_parent_folder',
                   valid_type=FolderData,
                   default=None,
                   required=False)

        spec.outline(
            cls.setup,
            while_(cls.should_run_calculation)(
                cls.prepare_calculation,
                cls.run_calculation,
                cls.inspect_calculation,
            ),
            cls.return_results,
        )
        spec.output('retrieved_parent_folder', valid_type=FolderData)
Esempio n. 12
0
    def run_extmol(self):
        """
        Run the SiestaBaseWorkChain to calculate the extended molecule
        structure
        """

        self.report('Running run_extmol')

        siesta_inputs = dict(self.ctx.siesta_inputs)

        rem_inputs = {}
        rem_inputs['code'] = siesta_inputs['siesta_code']
        rem_inputs['kpoints'] = self.ctx.kpoints_em
        rem_inputs['basis'] = ParameterData(dict=siesta_inputs['basis'])
        rem_inputs['structure'] = self.ctx.structure_em
        rem_inputs['pseudos'] = siesta_inputs['pseudos']
        rem_inputs['parameters'] = ParameterData(
            dict=siesta_inputs['parameters'])
        rem_inputs['settings'] = ParameterData(dict=siesta_inputs['settings'])
        rem_inputs['clean_workdir'] = Bool(False)
        rem_inputs['max_iterations'] = Int(20)
        rem_inputs['options'] = siesta_inputs['options']

        running = submit(SiestaBaseWorkChain, **rem_inputs)

        self.report(
            'launched SiestaBaseWorkChain<{}> in run-Siesta mode'.format(
                running.pid))

        return ToContext(workchain_extmol=running)
Esempio n. 13
0
    def run_export_hartree(self):
        self.report("Running pp.x to export hartree potential")

        inputs = {}
        inputs['_label'] = "export_hartree"
        inputs['code'] = self.inputs.pp_code

        prev_calc = self.ctx.scf
        self._check_prev_calc(prev_calc)
        inputs['parent_folder'] = prev_calc.out.remote_folder

        structure = prev_calc.inp.structure
        cell_a = structure.cell[0][0]
        cell_b = structure.cell[1][1]
        cell_c = structure.cell[2][2]

        parameters = ParameterData(
            dict={
                'inputpp': {
                    'plot_num': 11,  # the V_bare + V_H potential
                },
                'plot': {
                    'iflag': 2,  # 2D plot
                    # format suitable for gnuplot   (2D) x, y, f(x,y)
                    'output_format': 7,
                    # 3D vector, origin of the plane (in alat units)
                    'x0(1)': 0.0,
                    'x0(2)': 0.0,
                    'x0(3)': cell_c / cell_a,
                    # 3D vectors which determine the plotting plane
                    # in alat units)
                    'e1(1)': cell_a / cell_a,
                    'e1(2)': 0.0,
                    'e1(3)': 0.0,
                    'e2(1)': 0.0,
                    'e2(2)': cell_b / cell_a,
                    'e2(3)': 0.0,
                    'nx': 10,  # Number of points in the plane
                    'ny': 10,
                    'fileout': 'vacuum_hartree.dat',
                },
            })
        inputs['parameters'] = parameters

        settings = ParameterData(
            dict={'additional_retrieve_list': ['vacuum_hartree.dat']})
        inputs['settings'] = settings

        inputs['_options'] = {
            "resources": {
                "num_machines": 1
            },
            "max_wallclock_seconds": 20 * 60,
            # workaround for flaw in PpCalculator.
            # We don't want to retrive this huge intermediate file.
            "append_text": u"rm -v aiida.filplot\n",
        }

        future = submit(PpCalculation.process(), **inputs)
        return ToContext(hartree=Calc(future))
Esempio n. 14
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
Esempio n. 15
0
    def run_export_orbitals(self):
        self.report("Running pp.x to export KS orbitals")

        inputs = {}
        inputs['_label'] = "export_orbitals"
        inputs['code'] = self.inputs.pp_code
        prev_calc = self.ctx.bands_lowres
        self._check_prev_calc(prev_calc)
        inputs['parent_folder'] = prev_calc.out.remote_folder

        nel = prev_calc.res.number_of_electrons
        nkpt = prev_calc.res.number_of_k_points
        nbnd = prev_calc.res.number_of_bands
        nspin = prev_calc.res.number_of_spin_components
        volume = prev_calc.res.volume
        #for....
        kband1 = max(int(nel/2) - 6, 1)
        kband2 = min(int(nel/2) + 7, nbnd)
        kpoint1 = 1
        kpoint2 = nkpt * nspin
        nhours = 8 #24# 2 + min(22, 2*int(volume/1500))

        for inb in range(kband1,kband2+1):     
            parameters = ParameterData(dict={
                  'inputpp': {
                      # contribution of a selected wavefunction
                      # to charge density
                      'plot_num': 7,
                      'kpoint(1)': kpoint1,
                      'kpoint(2)': kpoint2,
                      #'kband(1)': kband1,
                      #'kband(2)': kband2,
                      'kband(1)': inb,
                      'kband(2)': inb,
                  },
                  'plot': {
                      'iflag': 3,  # 3D plot
                      'output_format': 6,  # CUBE format
                      'fileout': '_orbital.cube',
                  },
            })
            inputs['parameters'] = parameters

            inputs['_options'] = {
                "resources": {"num_machines": 1},
                "max_wallclock_seconds": nhours * 60 * 60,  # 6 hours
                "append_text": self._get_cube_cutter(),
            }

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

        #future = submit(PpCalculation.process(), **inputs)
            submit(PpCalculation.process(), **inputs)
        #return ToContext(orbitals=Calc(future))
        return
Esempio n. 16
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
Esempio n. 17
0
def launch(code, structure, pseudo_family, kpoints, max_num_machines,
           max_wallclock_seconds, daemon, automatic_parallelization,
           clean_workdir, final_scf, group):
    """
    Run the PwRelaxWorkChain for a given input structure
    """
    from aiida.orm.data.base import Bool, Str
    from aiida.orm.data.parameter import ParameterData
    from aiida.orm.utils import WorkflowFactory
    from aiida.work.run import run, submit
    from aiida_quantumespresso.utils.resources import get_default_options

    PwRelaxWorkChain = WorkflowFactory('quantumespresso.pw.relax')

    parameters = {
        'SYSTEM': {
            'ecutwfc': 30.,
            'ecutrho': 240.,
        },
    }

    inputs = {
        'code': code,
        'structure': structure,
        'pseudo_family': Str(pseudo_family),
        'kpoints': kpoints,
        'parameters': ParameterData(dict=parameters),
    }

    if automatic_parallelization:
        parallelization = {
            'max_num_machines': max_num_machines,
            'target_time_seconds': 0.5 * max_wallclock_seconds,
            'max_wallclock_seconds': max_wallclock_seconds
        }
        inputs['automatic_parallelization'] = ParameterData(
            dict=parallelization)
    else:
        options = get_default_options(max_num_machines, max_wallclock_seconds)
        inputs['options'] = ParameterData(dict=options)

    if clean_workdir:
        inputs['clean_workdir'] = Bool(True)

    if final_scf:
        inputs['final_scf'] = Bool(True)

    if group:
        inputs['group'] = Str(group)

    if daemon:
        workchain = submit(PwRelaxWorkChain, **inputs)
        click.echo('Submitted {}<{}> to the daemon'.format(
            PwRelaxWorkChain.__name__, workchain.pid))
    else:
        run(PwRelaxWorkChain, **inputs)
Esempio n. 18
0
def launch(code, structure, pseudo_family, kpoints, max_num_machines,
           max_wallclock_seconds, daemon, mode):
    """
    Run a PwCalculation for a given input structure
    """
    from aiida.orm import load_node
    from aiida.orm.data.parameter import ParameterData
    from aiida.orm.data.upf import get_pseudos_from_structure
    from aiida.orm.utils import CalculationFactory
    from aiida.work.run import run, submit
    from aiida_quantumespresso.utils.resources import get_default_options

    PwCalculation = CalculationFactory('quantumespresso.pw')

    parameters = {
        'CONTROL': {
            'calculation': mode,
        },
        'SYSTEM': {
            'ecutwfc': 30.,
            'ecutrho': 240.,
        },
    }

    inputs = {
        'code': code,
        'structure': structure,
        'pseudo': get_pseudos_from_structure(structure, pseudo_family),
        'kpoints': kpoints,
        'parameters': ParameterData(dict=parameters),
        'settings': ParameterData(dict={}),
        '_options': get_default_options(max_num_machines,
                                        max_wallclock_seconds),
    }

    process = PwCalculation.process()

    if daemon:
        calculation = submit(process, **inputs)
        click.echo('Submitted {}<{}> to the daemon'.format(
            PwCalculation.__name__, calculation.pid))
    else:
        click.echo('Running a PwCalculation in the {} mode... '.format(mode))
        results, pk = run(process, _return_pid=True, **inputs)
        calculation = load_node(pk)

        click.echo('PwCalculation<{}> terminated with state: {}'.format(
            pk, calculation.get_state()))
        click.echo('\n{link:25s} {node}'.format(link='Output link',
                                                node='Node pk and type'))
        click.echo('{s}'.format(s='-' * 60))
        for link, node in sorted(calculation.get_outputs(also_labels=True)):
            click.echo('{:25s} <{}> {}'.format(link, node.pk,
                                               node.__class__.__name__))
Esempio n. 19
0
    def test_statistics_default_class(self):
        """
        Test if the statistics query works properly.

        I try to implement it in a way that does not depend on the past state.
        """
        from aiida.orm import Node, DataFactory, Calculation
        from collections import defaultdict
        from aiida.backends.general.abstractqueries import AbstractQueryManager

        def store_and_add(n, statistics):
            n.store()
            statistics['total'] += 1
            statistics['types'][n._plugin_type_string] += 1
            statistics['ctime_by_day'][n.ctime.strftime('%Y-%m-%d')] += 1

        class QueryManagerDefault(AbstractQueryManager):
            pass

        qmanager_default = QueryManagerDefault()

        current_db_statistics = qmanager_default.get_creation_statistics()
        types = defaultdict(int)
        types.update(current_db_statistics['types'])
        ctime_by_day = defaultdict(int)
        ctime_by_day.update(current_db_statistics['ctime_by_day'])

        expected_db_statistics = {
            'total': current_db_statistics['total'],
            'types': types,
            'ctime_by_day': ctime_by_day
        }

        ParameterData = DataFactory('parameter')

        store_and_add(Node(), expected_db_statistics)
        store_and_add(ParameterData(), expected_db_statistics)
        store_and_add(ParameterData(), expected_db_statistics)
        store_and_add(Calculation(), expected_db_statistics)

        new_db_statistics = qmanager_default.get_creation_statistics()
        # I only check a few fields
        new_db_statistics = {
            k: v
            for k, v in new_db_statistics.iteritems()
            if k in expected_db_statistics
        }

        expected_db_statistics = {
            k: dict(v) if isinstance(v, defaultdict) else v
            for k, v in expected_db_statistics.iteritems()
        }

        self.assertEquals(new_db_statistics, expected_db_statistics)
Esempio n. 20
0
    def _get_output_nodes(self, output_path, bands_path):
        """
        Extracts output nodes from the standard output and standard error
        files. (And XML and JSON files)
        """
        from aiida.orm.data.array.trajectory import TrajectoryData
        import re

        result_list = []

        # Add errors
        successful = True
        if output_path is None:
            errors_list = ['WARNING: No aiida.out file...']
        else:
            successful, errors_list = self.get_errors_from_file(output_path)

        result_dict = {}
        result_dict["errors"] = errors_list

        # Add warnings
        warnings_list = self.get_warnings_from_file(output_path)
        result_dict["warnings"] = warnings_list

        # Add outuput data
        output_dict = self.get_output_from_file(output_path)
        result_dict.update(output_dict)

        # Add parser info dictionary
        parser_info = {}
        parser_version = 'aiida-0.11.0--plugin-0.11.5'
        parser_info['parser_info'] =\
            'AiiDA Vibra Parser V. {}'.format(parser_version)
        parser_info['parser_warnings'] = []
        parsed_dict = dict(result_dict.items() + parser_info.items())

        output_data = ParameterData(dict=parsed_dict)
        
        link_name = self.get_linkname_outparams()
        result_list.append((link_name,output_data))

        # Parse band-structure information if available
        if bands_path is not None:
             bands, coords = self.get_bands(bands_path)
             from aiida.orm.data.array.bands import BandsData
             arraybands = BandsData()
             arraybands.set_kpoints(self._calc.inp.bandskpoints.get_kpoints(cartesian=True))
             arraybands.set_bands(bands,units="eV")
             result_list.append((self.get_linkname_bandsarray(), arraybands))
             bandsparameters = ParameterData(dict={"kp_coordinates": coords})
             result_list.append((self.get_linkname_bandsparameters(), bandsparameters))

        return successful, result_list
    def build_slab_cp2k_inputs(cls, structure, pdos_lists, code, mgrid_cutoff,
                               wfn_file_path, elpa_switch):

        inputs = {}
        inputs['_label'] = "slab_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 = 27
        if len(atoms) > 1500:
            num_machines = 48
        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, pdos_lists)

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

        # settings
        settings = ParameterData(dict={'additional_retrieve_list': ['*.pdos']})
        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
Esempio n. 22
0
    def parse_job_details(self):
        self.submit_details = ParameterData()

        self.struc_folder = None
        if 'struc_folder' in self.job_details.keys():  ## e.g. for the NEB
            self.struc_folder = self.job_details['struc_folder']
            self.job_details.pop('struc_folder')

        self.job_details['walltime'] = self.walltime.value
        self.job_details.pop('slab_analyzed')
        self.job_details.pop('cp2k_code')
        self.job_details.pop('structure')
        self.submit_details.set_dict(self.job_details)
Esempio n. 23
0
    def run_export_spinden(self):
        self.report("Running pp.x to compute spinden")

        inputs = {}
        inputs['_label'] = "export_spinden"
        inputs['code'] = self.inputs.pp_code
        prev_calc = self.ctx.scf
        self._check_prev_calc(prev_calc)
        inputs['parent_folder'] = prev_calc.out.remote_folder

        nspin = prev_calc.res.number_of_spin_components
        bands_cmdline = prev_calc.inp.settings.get_dict()['cmdline']
        nnodes = int(prev_calc.get_resources()['num_machines'])
        npools = int(bands_cmdline[bands_cmdline.index('-npools') + 1])
        nproc_mach = int(
            prev_calc.get_resources()['default_mpiprocs_per_machine'])
        if nspin == 1:
            self.report("Skipping, got only one spin channel")
            return

        parameters = ParameterData(
            dict={
                'inputpp': {
                    'plot_num': 6,  # spin polarization (rho(up)-rho(down))
                },
                'plot': {
                    'iflag': 3,  # 3D plot
                    'output_format': 6,  # CUBE format
                    'fileout': '_spin.cube',
                },
            })
        inputs['parameters'] = parameters

        inputs['_options'] = {
            "resources": {
                "num_machines": nnodes,
                "num_mpiprocs_per_machine": nproc_mach
            },
            "max_wallclock_seconds": 30 * 60,  # 30 minutes
            "append_text": self._get_cube_cutter(),
        }

        settings = ParameterData(
            dict={
                'additional_retrieve_list': ['*.cube.gz'],
                'cmdline': ["-npools", str(npools)]
            })
        inputs['settings'] = settings

        future = submit(PpCalculation.process(), **inputs)
        return ToContext(spinden=Calc(future))
Esempio n. 24
0
    def _prepare_for_submission(self, tempfolder, inputdict):
        from aiida.orm.calculation.job.codtools import commandline_params_from_dict
        import shutil

        try:
            cif = inputdict.pop(self.get_linkname('cif'))
        except KeyError:
            raise InputValidationError(
                "no CIF file is specified for this calculation")
        if not isinstance(cif, CifData):
            raise InputValidationError("cif is not of type CifData")

        parameters = inputdict.pop(self.get_linkname('parameters'), None)
        if parameters is None:
            parameters = ParameterData(dict={})
        if not isinstance(parameters, ParameterData):
            raise InputValidationError(
                "parameters is not of type ParameterData")

        code = inputdict.pop(self.get_linkname('code'), None)
        if code is None:
            raise InputValidationError("Code not found in input")

        self._validate_resources(**self.get_resources())

        input_filename = tempfolder.get_abs_path(self._DEFAULT_INPUT_FILE)
        shutil.copy(cif.get_file_abs_path(), input_filename)

        commandline_params = self._default_commandline_params
        commandline_params.extend(
            commandline_params_from_dict(parameters.get_dict()))

        calcinfo = CalcInfo()
        calcinfo.uuid = self.uuid
        # The command line parameters should be generated from 'parameters'
        calcinfo.local_copy_list = []
        calcinfo.remote_copy_list = []
        calcinfo.retrieve_list = [
            self._DEFAULT_OUTPUT_FILE, self._DEFAULT_ERROR_FILE
        ]
        calcinfo.retrieve_singlefile_list = []

        codeinfo = CodeInfo()
        codeinfo.cmdline_params = commandline_params
        codeinfo.stdin_name = self._DEFAULT_INPUT_FILE
        codeinfo.stdout_name = self._DEFAULT_OUTPUT_FILE
        codeinfo.stderr_name = self._DEFAULT_ERROR_FILE
        codeinfo.code_uuid = code.uuid
        calcinfo.codes_info = [codeinfo]

        return calcinfo
Esempio n. 25
0
def execute(args):
    """
    The main execution of the script, which will run some preliminary checks on the command
    line arguments before passing them to the workchain and running it
    """
    try:
        code = Code.get_from_string(args.codename)
    except NotExistent as exception:
        print "Execution failed: could not retrieve the code '{}'".format(args.codename)
        print "Exception report: {}".format(exception)
        return

    try:
        parent_calc = load_node(args.parent_calc)
    except NotExistent as exception:
        print "Execution failed: failed to load the node for the given parent calculation '{}'".format(args.parent_calc)
        print "Exception report: {}".format(exception)
        return

    if not isinstance(parent_calc, PwCalculation):
        print "The provided parent calculation {} is not of type PwCalculation, aborting...".format(args.parent_calc)
        return

    qpoints = KpointsData()
    qpoints.set_kpoints_mesh(args.qpoints)

    parameters = {
        'INPUTPH': {
            'tr2_ph': 1e-10,
        }
    }
    settings = {}
    options  = {
        'resources': {
            'num_machines': 1
        },
        'max_wallclock_seconds': args.max_wallclock_seconds,
    }

    run(
        PhBaseWorkChain,
        code=code,
        parent_calc=parent_calc,
        qpoints=qpoints,
        parameters=ParameterData(dict=parameters),
        settings=ParameterData(dict=settings),
        options=ParameterData(dict=options),
        max_iterations=Int(args.max_iterations)
    )
Esempio n. 26
0
    def prepare_calculation(self):
        """Prepare all the neccessary input links to run the calculation"""
        self.ctx.inputs = AttributeDict({
            'code': self.inputs.code,
            'structure': self.ctx.structure,
            '_options': self.ctx.options,
        })

        if self.ctx.restart_calc is not None:
            self.ctx.inputs['retrieved_parent_folder'] = self.ctx.restart_calc

        # use the new parameters
        p = ParameterData(dict=self.ctx.parameters)
        p.store()
        self.ctx.inputs['parameters'] = p
Esempio n. 27
0
    def _get_output_nodes(self, output_path, error_path):
        """
        Extracts output nodes from the standard output and standard error
        files.
        """
        from aiida.orm.data.parameter import ParameterData
        import re

        messages = []
        if output_path is not None:
            with open(output_path) as f:
                content = f.readlines()
            lines = [x.strip('\n') for x in content]
            if re.search(' OK$', lines[0]) is not None:
                lines.pop(0)
            messages.extend(lines)

        if error_path is not None:
            with open(error_path) as f:
                content = f.readlines()
            lines = [x.strip('\n') for x in content]
            messages.extend(lines)
            self._check_failed(messages)

        output_nodes = []
        output_nodes.append(('messages',
                             ParameterData(dict={'output_messages':
                                                     messages})))
        return True, output_nodes
Esempio n. 28
0
    def import_kpoints(self, kpoints):
        """
            **Method:** Takes Pymatgen Kpoints object and internally sets
            kpoints node.

            *Input:*
            :kpoints: Pymatgen Kpoints object.
        """
        try:
            assert type(kpoints) == vaspio.Kpoints
            kpoints = ParameterData(dict=kpoints.as_dict())
            self.use_kpoints(kpoints)
        except:
            print("Invalid input type ({})!"
                  "Please provide a valid Pymatgen Kpoints object.").format(
                      type(kpoints))
Esempio n. 29
0
def _legacy_get_kpoints_path(structure, **kwargs):
    """
    Call the get_kpoints_path of the legacy implementation

    :param structure: a StructureData node
    :param bool cartesian: if set to true, reads the coordinates eventually passed in value as cartesian coordinates
    :param epsilon_length: threshold on lengths comparison, used to get the bravais lattice info
    :param epsilon_angle: threshold on angles comparison, used to get the bravais lattice info
    """
    args_recognized = ['cartesian', 'epsilon_length', 'epsilon_angle']
    args_unknown = set(kwargs).difference(args_recognized)

    if args_unknown:
        raise ValueError("unknown arguments {}".format(args_unknown))

    point_coords, path, bravais_info = legacy.get_kpoints_path(
        cell=structure.cell, pbc=structure.pbc, **kwargs)

    parameters = {
        'bravais_info': bravais_info,
        'point_coords': point_coords,
        'path': path,
    }

    return {'parameters': ParameterData(dict=parameters)}
Esempio n. 30
0
    def import_potcar(self, potcar):
        """
            **Method:** Takes Pymatgen Potcar object and internally sets
            potcar node.

            *Input:*
            :kpoints: Pymatgen Potcar object.
        """
        try:
            assert type(potcar) == vaspio.Potcar
            potcar = ParameterData(dict=potcar.as_dict())
            self.use_potcar(potcar)
        except:
            print("Invalid input type ({})!"
                  "Please provide a valid Pymatgen Potcar object.").format(
                      type(potcar))