Beispiel #1
0
    def test_get_kpointsdata_gamma(self):
        """Test get_kpointsdata for all inputs w/ gamma kpoints."""

        # Define reference cell.
        ref_cell = np.array([[2.456, 0., 0.],
                             [-1.228, 2.12695, 0.],
                             [0., 0., 6.69604]])
        # Define reference kpoints mesh.
        ref_mesh = np.array([1, 1, 1])
        # Define reference offset.
        ref_offset = np.array([0., 0., 0.])

        # Filter out all input files with gamma kpoints.
        gamma_input_files = filter(lambda x: 'gamma' in x, INPUT_FILES)

        # Check each input file for agreement with reference values.
        tol = 0.0001
        for input_file in gamma_input_files:
            # Parse the input file and get the kpointsdata.
            pwinputfile = pwinputparser.PwInputFile(input_file)
            kpointsdata = pwinputfile.get_kpointsdata()

            # Check the cell.
            self.assertTrue(np.all(np.abs(kpointsdata.cell - ref_cell) < tol))

            # Check the mesh and offset.
            mesh, offset = kpointsdata.get_kpoints_mesh()
            self.assertTrue(np.all(np.abs(np.array(mesh) - ref_mesh) < tol))
            self.assertTrue(np.all(np.abs(np.array(offset) - ref_offset) < tol))
Beispiel #2
0
    def test_namelists(self):
        """Test the parsing of the QE namelists and their key/value pairs."""

        # Define the reference namelists.
        # NOTE: Only the items important to the proper creation of an AiiDa
        # calculation are included here and checked below.
        ref_namelists = {
            'CONTROL':
                {'calculation': 'scf',
                 'restart_mode': 'from_scratch',
                 'outdir': './tmp'},
            'ELECTRONS':
                {'conv_thr': 1e-05},
            'SYSTEM':
                {'ecutwfc': 30.0,
                 'occupations': 'fixed',
                 'ibrav': 0,
                 'degauss': 0.02,
                 'smearing': 'methfessel-paxton',
                 'nat': 4,
                 'ntyp': 1,
                 'ecutrho': 180.0}
        }

        # Check each input file for agreement with reference values.
        for input_file in INPUT_FILES:

            # Parse the input file
            pwinputfile = pwinputparser.PwInputFile(input_file)

            # Check the key/value pairs for each namelist in ref_namelists.
            for namelist_key, namelist in ref_namelists.items():
                for key, ref_value in namelist.items():
                    self.assertEqual(pwinputfile.namelists[namelist_key][key],
                                     ref_value)
Beispiel #3
0
    def test_get_kpointsdata_manual(self):
        """Test get_kpointsdata for all inputs w/ manually specified kpoints."""

        # Define reference cell.
        ref_cell = np.array([[2.456, 0., 0.],
                             [-1.228, 2.12695, 0.],
                             [0., 0., 6.69604]])
        # Define reference kpoints.
        ref_kpoints = np.array([[0., 0., 0.],
                                [0.25, 0., 0.],
                                [0.5, 0., 0.],
                                [0.3333333, 0.3333333, 0.],
                                [0.1666667, 0.1666667, 0.],
                                [0., 0., 0.],
                                [0., 0., 0.25],
                                [0., 0., 0.5],
                                [0.5, 0., 0.5],
                                [0.3333333, 0.3333333, 0.5],
                                [0., 0., 0.5],
                                [0.5, 0., 0.5],
                                [0.5, 0., 0.],
                                [0.3333333, 0.3333333, 0.],
                                [0.3333333, 0.3333333, 0.5]])
        # Define reference weights.
        ref_weights = np.array(
            [1., 1., 5., 2., 2., 4., 4., 1., 5., 2., 4., 5., 2., 4., 2.]
        )

        # Filter out all input files with manually specified kpoints.
        manual_input_files = filter(
            lambda x: 'automatic' not in x and 'gamma' not in x,
            INPUT_FILES
        )

        # Check each input file for agreement with reference values.
        tol = 0.0001
        for input_file in manual_input_files:
            # Parse the input file and get the kpointsdata.
            pwinputfile = pwinputparser.PwInputFile(input_file)
            kpointsdata = pwinputfile.get_kpointsdata()

            # Check the cell.
            self.assertTrue(np.all(np.abs(kpointsdata.cell - ref_cell) < tol))

            # Check the kpoints and weights.
            kpoints, weights = kpointsdata.get_kpoints(also_weights=True)
            self.assertTrue(np.all(np.abs(kpoints - ref_kpoints) < tol))
            self.assertTrue(np.all(np.abs(weights - ref_weights) < tol))
Beispiel #4
0
    def test_atomic_species(self):
        """Test the parsing of the ATOMIC_SPECIES card."""

        # Define the reference atomic species dictionary.
        ref_atomic_species = {'masses': [12.0],
                              'names': ['C'],
                              'pseudo_file_names': ['C.pbe-rrkjus.UPF']}

        # Check each input file for agreement with reference values.
        for input_file in INPUT_FILES:
            # Parse the input file
            pwinputfile = pwinputparser.PwInputFile(input_file)

            # Check the atomic_species attribute against the reference
            # dictionary.
            self.assertDictEqual(ref_atomic_species, pwinputfile.atomic_species)
Beispiel #5
0
    def test_get_structuredata(self):
        """Test the get_structuredata method of PwInputFile"""

        # Create a reference StructureData object for the structure contained
        # in all the input files.
        ref_structure = StructureData()
        ref_structure.set_cell(
            ((2.456, 0., 0.), (-1.228, 2.12695, 0.), (0., 0., 6.69604)))
        ref_structure.append_atom(name='C',
                                  symbols='C',
                                  position=(0., 0., 0.),
                                  mass=12.)
        ref_structure.append_atom(name='C',
                                  symbols='C',
                                  position=(0., 1.41797, 0.),
                                  mass=12.)
        ref_structure.append_atom(name='C',
                                  symbols='C',
                                  position=(0., 0., 3.34802),
                                  mass=12.)
        ref_structure.append_atom(name='C',
                                  symbols='C',
                                  position=(1.228, 0.70899, 3.34802),
                                  mass=12.)

        # Check each input file for agreement with reference values.
        for input_file in INPUT_FILES:

            # Parse the input file and get the structuredata.
            pwinputfile = pwinputparser.PwInputFile(input_file)
            structure = pwinputfile.get_structuredata()

            # Check the name and the positions of each Kind.
            for ref_site, site in zip(ref_structure.sites, structure.sites):
                self.assertEqual(site.kind_name, ref_site.kind_name)
                for ref_q, q in zip(ref_site.position, site.position):
                    self.assertAlmostEqual(ref_q, q, 4)

            # Check the cell.
            for ref_row, row in zip(ref_structure.cell, structure.cell):
                for ref_q, q in zip(ref_row, row):
                    self.assertAlmostEqual(ref_q, q, 4)

            # Check the mass of each Kind.
            for ref_kind, kind in zip(ref_structure.kinds, structure.kinds):
                self.assertEqual(ref_kind.mass, kind.mass)
Beispiel #6
0
    def create_input_nodes(self, open_transport, input_file_name=None,
                           output_file_name=None, remote_workdir=None):
        """
        Create calculation input nodes based on the job's files.

        :param open_transport: An open instance of the transport class of the
            calculation's computer. See the tutorial for more information.
        :type open_transport: :py:class:`aiida.transport.plugins.local.LocalTransport`
            | :py:class:`aiida.transport.plugins.ssh.SshTransport`

        This method parses the files in the job's remote working directory to
        create the input nodes that would exist if the calculation were
        submitted using AiiDa. These nodes are

            * a ``'parameters'`` ParameterData node, based on the namelists and
              their variable-value pairs;
            * a ``'kpoints'`` KpointsData node, based on the *K_POINTS* card;
            * a ``'structure'`` StructureData node, based on the
              *ATOMIC_POSITIONS* and *CELL_PARAMETERS* cards;
            * one ``'pseudo_X'`` UpfData node for the pseudopotential used for
              the atomic species with name ``X``, as specified in the
              *ATOMIC_SPECIES* card;
            * a ``'settings'`` ParameterData node, if there are any fixed
              coordinates, or if the gamma kpoint is used;

        and can be retrieved as a dictionary using the ``get_inputs_dict()``
        method. *These input links are cached-links; nothing is stored by this
        method (including the calculation node itself).*

        .. note:: QE stores the calculation's pseudopotential files in the
            ``<outdir>/<prefix>.save/`` subfolder of the job's working
            directory, where ``outdir`` and ``prefix`` are QE *CONTROL*
            variables (see
            `pw input file description <http://www.quantum-espresso.org/wp-content/uploads/Doc/INPUT_PW.html>`_).
            This method uses these files to either get--if the a node already
            exists for the pseudo--or create a UpfData node for each
            pseudopotential.


        **Keyword arguments**

        .. note:: These keyword arguments can also be set when instantiating the
            class or using the ``set_`` methods (e.g. ``set_remote_workdir``).
            Offering to set them here simply offers the user an additional
            place to set their values. *Only the values that have not yet been
            set need to be specified.*

        :param input_file_name: The file name of the job's input file.
        :type input_file_name: str

        :param output_file_name: The file name of the job's output file (i.e.
            the file containing the stdout of QE).
        :type output_file_name: str

        :param remote_workdir: Absolute path to the directory where the job
            was run. The transport of the computer you link ask input to the
            calculation is the transport that will be used to retrieve the
            calculation's files. Therefore, ``remote_workdir`` should be the
            absolute path to the job's directory on that computer.
        :type remote_workdir: str

        :raises aiida.common.exceptions.InputValidationError: if
            ``open_transport`` is a different type of transport than the
            computer's.
        :raises aiida.common.exceptions.InvalidOperation: if
            ``open_transport`` is not open.
        :raises aiida.common.exceptions.InputValidationError: if
            ``remote_workdir``, ``input_file_name``, and/or ``output_file_name``
            are not set prior to or during the call of this method.
        :raises aiida.common.exceptions.FeatureNotAvailable: if the input file
            uses anything other than ``ibrav = 0``, which is not currently
            implimented in aiida.
        :raises aiida.common.exceptions.ParsingError: if there are issues
            parsing the input file.
        :raises IOError: if there are issues reading the input file.
        """
        import re
        # Make sure the remote workdir and input + output file names were
        # provided either before or during the call to this method. If they
        # were just provided during this method call, store the values.
        if remote_workdir is not None:
            self.set_remote_workdir(remote_workdir)
        elif self.get_attr('remote_workdir', None) is None:
            raise InputValidationError(
                'The remote working directory has not been specified.\n'
                'Please specify it using one of the following...\n '
                '(a) pass as a keyword argument to create_input_nodes\n'
                '    [create_input_nodes(remote_workdir=your_remote_workdir)]\n'
                '(b) pass as a keyword argument when instantiating\n '
                '    [calc = PwCalculationImport(remote_workdir='
                'your_remote_workdir)]\n'
                '(c) use the set_remote_workdir method\n'
                '    [calc.set_remote_workdir(your_remote_workdir)]'
            )
        if input_file_name is not None:
            self._INPUT_FILE_NAME = input_file_name
        elif self._INPUT_FILE_NAME is None:
            raise InputValidationError(
                'The input file_name has not been specified.\n'
                'Please specify it using one of the following...\n '
                '(a) pass as a keyword argument to create_input_nodes\n'
                '    [create_input_nodes(input_file_name=your_file_name)]\n'
                '(b) pass as a keyword argument when instantiating\n '
                '    [calc = PwCalculationImport(input_file_name='
                'your_file_name)]\n'
                '(c) use the set_input_file_name method\n'
                '    [calc.set_input_file_name(your_file_name)]'
            )
        if output_file_name is not None:
            self._OUTPUT_FILE_NAME = output_file_name
        elif self._OUTPUT_FILE_NAME is None:
            raise InputValidationError(
                'The input file_name has not been specified.\n'
                'Please specify it using one of the following...\n '
                '(a) pass as a keyword argument to create_input_nodes\n'
                '    [create_input_nodes(output_file_name=your_file_name)]\n'
                '(b) pass as a keyword argument when instantiating\n '
                '    [calc = PwCalculationImport(output_file_name='
                'your_file_name)]\n'
                '(c) use the set_output_file_name method\n'
                '    [calc.set_output_file_name(your_file_name)]'
            )

        # Check that open_transport is the correct transport type.
        if type(open_transport) is not self.get_computer().get_transport_class():
            raise InputValidationError(
                "The transport passed as the `open_transport` parameter is "
                "not the same transport type linked to the computer. Please "
                "obtain the correct transport class using the "
                "`get_transport_class` method of the calculation's computer. "
                "See the tutorial for more information."
            )

        # Check that open_transport is actually open.
        if not open_transport._is_open:
            raise InvalidOperation(
                "The transport passed as the `open_transport` parameter is "
                "not open. Please execute the open the transport using it's "
                "`open` method, or execute the call to this method within a "
                "`with` statement context guard. See the tutorial for more "
                "information."
            )

        # Copy the input file and psuedo files to a temp folder for parsing.
        with SandboxFolder() as folder:

            # Copy the input file to the temp folder.
            remote_path = os.path.join(self._get_remote_workdir(),
                                       self._INPUT_FILE_NAME)
            open_transport.get(remote_path, folder.abspath)

            # Parse the input file.
            local_path = os.path.join(folder.abspath, self._INPUT_FILE_NAME)
            with open(local_path) as fin:
                pwinputfile = pwinputparser.PwInputFile(fin)


            # Determine PREFIX, if it hasn't already been set by the user.
            if self._PREFIX is None:
                control_dict = pwinputfile.namelists['CONTROL']
                # If prefix is not set in input file, use the default,
                # 'pwscf'.
                self._PREFIX = control_dict.get('prefix', 'pwscf')

            # Determine _OUTPUT_SUBFOLDER, if it hasn't already been set by
            # the user.
            # TODO: Prompt user before using the environment variable???
            if self._OUTPUT_SUBFOLDER is None:
                # See if it's specified in the CONTROL namelist.
                control_dict = pwinputfile.namelists['CONTROL']
                self._OUTPUT_SUBFOLDER = control_dict.get('outdir', None)
                if self._OUTPUT_SUBFOLDER is None:
                    # See if the $ESPRESSO_TMPDIR is set.
                    envar = open_transport.exec_command_wait(
                        'echo $ESPRESSO_TMPDIR'
                    )[1]
                    if len(envar.strip()) > 0:
                        self._OUTPUT_SUBFOLDER = envar.strip()
                    else:
                        # Use the default dir--the dir job was submitted in.
                        self._OUTPUT_SUBFOLDER = self._get_remote_workdir()

            # Copy the pseudo files to the temp folder.
            for fnm in pwinputfile.atomic_species['pseudo_file_names']:
                remote_path = os.path.join(self._get_remote_workdir(),
                                           self._OUTPUT_SUBFOLDER,
                                           '{}.save/'.format(self._PREFIX),
                                           fnm)
                open_transport.get(remote_path, folder.abspath)

            # Make sure that ibrav = 0, since aiida doesn't support anything
            # else.
            if pwinputfile.namelists['SYSTEM']['ibrav'] != 0:
                raise FeatureNotAvailable(
                    'Found ibrav !=0 while parsing the input file. '
                    'Currently, AiiDa only supports ibrav = 0.'
                )

            # Create ParameterData node based on the namelist and link as input.

            # First, strip the namelist items that aiida doesn't allow or sets
            # later.
            # NOTE: ibrav = 0 is checked above.
            # NOTE: If any of the position or cell units are in alat or crystal
            # units, that will be taken care of by the input parsing tools, and
            # we are safe to fake that they were never there in the first place.
            parameters_dict = deepcopy(pwinputfile.namelists)
            for namelist, blocked_key in self._blocked_keywords:
                keys = parameters_dict[namelist].keys()
                for this_key in parameters_dict[namelist].keys():
                    # take into account that celldm and celldm(*) must be blocked
                    if re.sub("[(0-9)]", "", this_key) == blocked_key:
                        parameters_dict[namelist].pop(this_key, None)

            parameters = ParameterData(dict=parameters_dict)
            self.use_parameters(parameters)

            # Initialize the dictionary for settings parameter data for possible
            # use later for gamma kpoint and fixed coordinates.
            settings_dict = {}

            # Create a KpointsData node based on the K_POINTS card block
            # and link as input.
            kpointsdata = pwinputfile.get_kpointsdata()
            self.use_kpoints(kpointsdata)
            # If only the gamma kpoint is used, add to the settings dictionary.
            if pwinputfile.k_points['type'] == 'gamma':
                settings_dict['gamma_only'] = True

            # Create a StructureData node based on the ATOMIC_POSITIONS,
            # CELL_PARAMETERS, and ATOMIC_SPECIES card blocks, and link as
            # input.
            structuredata = pwinputfile.get_structuredata()
            self.use_structure(structuredata)

            # Get or create a UpfData node for the pseudopotentials used for
            # the calculation.
            names = pwinputfile.atomic_species['names']
            pseudo_file_names = pwinputfile.atomic_species['pseudo_file_names']
            for name, fnm in zip(names, pseudo_file_names):
                local_path = os.path.join(folder.abspath, fnm)
                pseudo, created = UpfData.get_or_create(local_path)
                self.use_pseudo(pseudo, kind=name)

        # If there are any fixed coordinates (i.e. force modification
        # present in the input file, create a ParameterData node for these
        # special settings.
        fixed_coords = pwinputfile.atomic_positions['fixed_coords']
        # NOTE: any() only works for 1-dimensional lists.
        if any((any(fc_xyz) for fc_xyz in fixed_coords)):
            settings_dict['FIXED_COORDS'] = fixed_coords

        # If the settings_dict has been filled in, create a ParameterData
        # node from it and link as input.
        if settings_dict:
            self.use_settings(ParameterData(dict=settings_dict))

        self._set_attr('input_nodes_created', True)
Beispiel #7
0
parser = argparse.ArgumentParser()
parser.add_argument("code",
                    help="code and machine where you would like to run")
parser.add_argument("json_hpc", help="json file with HPC parameters")
args = parser.parse_args()

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

with open(args.json_hpc) as data_file:
    hpc_file = json.load(data_file)

pseudo_family = hpc_file['pseudo']
file_input = pwinputparser.PwInputFile(open('pw.in'))

structure = file_input.get_structuredata()
structure.store()

kpoints = file_input.get_kpointsdata()
kpoints_mesh = kpoints.get_kpoints_mesh()
kpoints.store()

file_input.namelists['SYSTEM'].pop('ibrav', None)
file_input.namelists['SYSTEM'].pop('nat', None)
file_input.namelists['SYSTEM'].pop('ntyp', None)

pw_parameters = ParameterData(dict=file_input.namelists)

pw_parameters.store()
Beispiel #8
0
KpointsData = DataFactory('array.kpoints')
StructureData = DataFactory('structure')

parser = argparse.ArgumentParser()
parser.add_argument("code",
                    help="code and machine where you would like to run")
parser.add_argument("json_hpc", help="json file with HPC parameters")
args = parser.parse_args()

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

pseudo_family = 'sssp_eff_pbe_2'
file_input = pwinputparser.PwInputFile(open('pw_large_scf.in'))

structure = file_input.get_structuredata()
structure.store()

kpoints = file_input.get_kpointsdata()
kpoints_mesh = kpoints.get_kpoints_mesh()
kpoints.store()

file_input.namelists['SYSTEM'].pop('ibrav', None)
file_input.namelists['SYSTEM'].pop('nat', None)
file_input.namelists['SYSTEM'].pop('ntyp', None)

pw_parameters = ParameterData(dict=file_input.namelists)

pw_parameters.store()