Пример #1
0
    def get_pseudos(options):
        """
        Find pseudos in paths, return :class:`DojoTable` object sorted by atomic number Z.
        Accepts filepaths or directory.
        """
        exts = ("psp8",)

        paths = options.pseudos
        if len(paths) == 1 and os.path.isdir(paths[0]):
            top = os.path.abspath(paths[0])
            # print("top", top)
            paths = find_exts(top, exts, exclude_dirs="_*")
            # table = DojoTable.from_dir(paths[0])

        pseudos = []
        for p in paths:
            try:
                pseudos.append(Pseudo.from_file(p))
            except Exception as exc:
                warn("Error in %s:\n%s. This pseudo will be ignored" % (p, exc))

        table = DojoTable(pseudos)

        # Here we select a subset of pseudos according to family or rows
        if options.rows:
            table = table.select_rows(options.rows)
        elif options.family:
            table = table.select_families(options.family)

        if options.symbols:
            table = table.select_symbols(options.symbols)

        return table.sort_by_z()
Пример #2
0
def djson_new(options, stream=sys.stdout):
    """Create a new djson file from directory or from text file. Print document to stdout."""
    # Build full table (either from directory or text file.
    if not os.path.isdir(options.top):
        # Assume top is a text file
        table = DojoTable.from_txtfile(options.top)
    else:
        table = DojoTable.from_dojodir(options.top,
                                       exclude_wildcard=options.exclude)
    djson = table.to_djson(options.verbose, ignore_dup=False)
    print(json.dumps(djson, indent=1), file=stream)
    return 0
Пример #3
0
def djson_new(options, stream=sys.stdout):
    """Create a new djson file. Print document to stdout."""
    # Build full table
    table = DojoTable.from_dojodir(options.top, exclude_wildcard=options.exclude)
    djson = table.to_djson(options.verbose, ignore_dup=False)
    print(json.dumps(djson, indent=-1), file=stream)
    return 0
Пример #4
0
    def get_pseudos(options):
        """
        Find pseudos in paths, return :class:`DojoTable` object sorted by atomic number Z.
        Accepts filepaths or directory.
        """
        exts = ("psp8", "xml")

        paths = options.pseudos

        if len(paths) == 1:
            # Handle directory argument
            if os.path.isdir(paths[0]):
                top = os.path.abspath(paths[0])
                paths = find_exts(top, exts, exclude_dirs="_*")
            # Handle glob syntax e.g. "./*.psp8"
            elif "*" in paths[0]:
                paths = glob.glob(paths[0])

        if options.verbose > 1: print("Will read pseudo from: %s" % paths)

        pseudos = []
        for p in paths:
            try:
                pseudo = dojopseudo_from_file(p)
                if pseudo is None:
                    cprint("[%s] Pseudo.from_file returned None. Something wrong in file!" % p, "red")
                    continue
                pseudos.append(pseudo)

            except Exception as exc:
                cprint("[%s] Python exception. This pseudo will be ignored" % p, "red")
                if options.verbose: print(exc)

        table = DojoTable(pseudos)

        # Here we select a subset of pseudos according to family or rows
        if options.rows:
            table = table.select_rows(options.rows)
        elif options.family:
            table = table.select_families(options.family)

        # here we select chemical symbols.
        if options.symbols:
            table = table.select_symbols(options.symbols)

        return table.sort_by_z()
Пример #5
0
    def __getitem__(self, key):
        v = self._tables[key]
        if not isinstance(v, TableMetadata): return v 

        # Parse files, construct table and store it.
        new_table = DojoTable.from_djson(v.djson_path)
        new_table.dojo_name = key
        self._tables[key] = new_table

        return new_table
Пример #6
0
def gbrv_runps(options):
    """
    Run GBRV compound tests given a list of pseudos.
    """
    # Build table and list of symbols
    pseudos = options.pseudos = DojoTable(options.pseudos)
    symbols = [p.symbol for p in pseudos]
    if options.verbose > 1: print(pseudos)

    # Consistency check
    assert len(set(symbols)) == len(symbols)
    xc_list = [p.xc for p in pseudos]
    xc = xc_list[0]
    if any(xc != other_xc for other_xc in xc_list):
        raise ValueError("Pseudos with different XC functional")

    gbrv_factory = GbrvCompoundsFactory(xc=xc)
    db = gbrv_factory.db

    entry = db.match_symbols(symbols)
    if entry is None:
        cprint("Cannot find entry for %s! Returning" % str(symbols), "red")
        return 1

    workdir = "GBRVCOMP_" + "_".join(p.basename for p in pseudos)
    print("Working in:", workdir)
    flow = GbrvCompoundsFlow(workdir=workdir)

    accuracy = "high"
    ecut = max(p.hint_for_accuracy(accuracy).ecut for p in pseudos)
    pawecutdg = max(p.hint_for_accuracy(accuracy).pawecutdg for p in pseudos)
    if ecut <= 0.0: raise RuntimeError("Pseudos do not have hints")
    #ecut = ecut_from_pseudos(pseudos, accuracy)
    print("Adding work for formula:", entry.symbol, ", structure:",
          entry.struct_type, ", ecut:", ecut)

    work = gbrv_factory.relax_and_eos_work(accuracy,
                                           pseudos,
                                           entry.symbol,
                                           entry.struct_type,
                                           ecut=ecut,
                                           pawecutdg=None)
    flow.register_work(work)

    flow.build_and_pickle_dump(abivalidate=options.dry_run)
    if options.dry_run: return 0

    # Run the flow with the scheduler (enable smart_io)
    flow.use_smartio()
    return flow.make_scheduler().start()
Пример #7
0
    def __init__(self, struct_type, formula, pseudos_or_dict, dojo_pptable):
        """
        Initialize the record for the chemical formula and the list of
        pseudopotentials.
        """
        keys = ("basename", "Z_val", "l_max", "md5")

        #if isinstance(pseudos_or_dict, (list, tuple)):
        if all(hasattr(p, "as_dict") for p in pseudos_or_dict):

            def get_info(p):
                """Extract the most important info from the pseudo."""
                #symbol = p.symbol
                d = p.as_dict()
                return {k: d[k] for k in keys}

            meta = {p.symbol: get_info(p) for p in pseudos_or_dict}
            pseudos = pseudos_or_dict

        else:
            meta = pseudos_or_dict
            for v in meta.values():
                assert set(v.keys()) == set(keys)

            def pmatch(ps, esymb, d):
                return (ps.md5 == d["md5"] and ps.symbol == esymb
                        and ps.Z_val == d["Z_val"] and ps.l_max == d["l_max"])

            pseudos = []
            for esymb, d in meta.items():
                for p in dojo_pptable.pseudo_with_symbol(esymb,
                                                         allow_multi=True):
                    if pmatch(p, esymb, d):
                        pseudos.append(p)
                        break
                else:
                    raise ValueError(
                        "Cannot find pseudo:\n %s\n in dojo_pptable" % str(d))

        super(GbrvRecord, self).__init__(formula=formula,
                                         pseudos_metadata=meta,
                                         normal=None,
                                         high=None)

        self.pseudos = DojoTable.as_table(pseudos)
        self.dojo_pptable = dojo_pptable
        self.struct_type = struct_type
Пример #8
0
    def __init__(self, struct_type, formula, pseudos_or_dict, dojo_pptable):
        """
        Initialize the record for the chemical formula and the list of
        pseudopotentials.
        """
        keys = ("basename", "Z_val", "l_max", "md5")

        #if isinstance(pseudos_or_dict, (list, tuple)):
        if all(hasattr(p, "as_dict") for p in pseudos_or_dict):
            def get_info(p):
                """Extract the most important info from the pseudo."""
                #symbol = p.symbol
                d = p.as_dict()
                return {k: d[k] for k in keys}

            meta = {p.symbol: get_info(p) for p in pseudos_or_dict}
            pseudos = pseudos_or_dict

        else:
            meta = pseudos_or_dict
            for v in meta.values():
                assert set(v.keys()) == set(keys)

            def pmatch(ps, esymb, d):
                return (ps.md5 == d["md5"] and
                        ps.symbol == esymb and
                        ps.Z_val == d["Z_val"] and
                        ps.l_max == d["l_max"])

            pseudos = []
            for esymb, d in meta.items():
                for p in dojo_pptable.pseudo_with_symbol(esymb, allow_multi=True):
                    if pmatch(p, esymb, d):
                        pseudos.append(p)
                        break
                else:
                    raise ValueError("Cannot find pseudo:\n %s\n in dojo_pptable" % str(d))

        super(GbrvRecord, self).__init__(formula=formula, pseudos_metadata=meta,
                                         normal=None, high=None)

        self.pseudos = DojoTable.as_table(pseudos)
        self.dojo_pptable = dojo_pptable
        self.struct_type = struct_type
Пример #9
0
    def relax_and_eos_work(self,
                           accuracy,
                           pseudos,
                           formula,
                           struct_type,
                           ecut=None,
                           pawecutdg=None,
                           ref="ae",
                           ngkpt=(8, 8, 8),
                           fband=2.0):
        """
        Returns a :class:`Work` object from the given pseudopotential.

        Args:
            kwargs: Extra variables passed to Abinit.

        .. note::

            GBRV tests are done with the following parameteres:

                - No spin polarization for structural relaxation
                  (only for magnetic moments for which spin-unpolarized structures are used)
                - All calculations are done on an 8x8x8 k-point density and with 0.002 Ry Fermi-Dirac smearing
        """
        pseudos = DojoTable.as_table(pseudos)
        if pseudos.allpaw and pawecutdg is None:
            raise ValueError(
                "pawecutdg must be specified for PAW calculations.")

        structure = self.make_ref_structure(formula,
                                            struct_type=struct_type,
                                            ref=ref)

        return GbrvCompoundRelaxAndEosWork(structure,
                                           formula,
                                           struct_type,
                                           pseudos,
                                           self.db.xc,
                                           accuracy,
                                           ecut=ecut,
                                           pawecutdg=pawecutdg,
                                           ngkpt=ngkpt,
                                           fband=fband)
Пример #10
0
    def test_db_update(self):
        """Testing DB update"""
        dirpath = dojotable_absdir("ONCVPSP-PBE")

        # Init an empty object.
        outdb = RocksaltOutdb.new_from_dojodir(dirpath)

        # No change here
        u = outdb.check_update()
        print(u)
        assert u.nrec_added == 0 and u.nrec_removed == 0

        # Now I hack a bit the object to simulate a pseudo that has been removed
        new_table = [p for p in outdb.dojo_pptable if p.basename != "Si.psp8"]
        outdb.dojo_pptable = DojoTable.as_table(new_table)

        # TODO:
        u = outdb.check_update()
        print(u)
        assert u.nrec_added == 0 and u.nrec_removed == 0
Пример #11
0
    def test_db_update(self):
        """Testing DB update"""
        return
        dirpath = dojotable_absdir("ONCVPSP-PBE")

        # Init an empty object.
        outdb = RocksaltOutdb.new_from_dojodir(dirpath)

        # No change here
        u = outdb.check_update()
        print(u)
        assert u.nrec_added == 0 and u.nrec_removed == 0

        # Now I hack a bit the object to simulate a pseudo that has been removed
        new_table = [p for p in outdb.dojo_pptable if p.basename != "Si.psp8"]
        outdb.dojo_pptable = DojoTable.as_table(new_table)

        # TODO:
        u = outdb.check_update()
        print(u)
        assert u.nrec_added == 0 and u.nrec_removed == 0
Пример #12
0
    def get_pseudos(options):
        """
        Find pseudos in paths, return :class:`DojoTable` object sorted by atomic number Z.
        Accepts filepaths or directory.
        """
        exts = ("psp8", "xml")

        paths = options.pseudos

        if len(paths) == 1:
            # Handle directory argument
            if os.path.isdir(paths[0]):
                top = os.path.abspath(paths[0])
                paths = find_exts(top, exts, exclude_dirs="_*")
            # Handle glob syntax e.g. "./*.psp8"
            elif "*" in paths[0]:
                paths = glob.glob(paths[0])

        if options.verbose > 1: print("Will read pseudo from: %s" % paths)

        pseudos = []
        for p in paths:
            try:
                pseudo = dojopseudo_from_file(p)
                if pseudo is None:
                    cprint("[%s] Pseudo.from_file returned None. Something wrong in file!" % p, "red")
                    continue
                pseudos.append(pseudo)

            except Exception as exc:
                cprint("[%s] Python exception. This pseudo will be ignored" % p, "red")
                if options.verbose: print(exc)

        table = DojoTable(pseudos)

        # Here we select a subset of pseudos according to family or rows
        if options.rows:
            table = table.select_rows(options.rows)
        elif options.family:
            table = table.select_families(options.family)

        # here we select chemical symbols.
        if options.symbols:
            table = table.select_symbols(options.symbols)

        return table.sort_by_z()
Пример #13
0
    def relax_and_eos_work(self, accuracy, pseudos, formula, struct_type,
                           ecut=None, pawecutdg=None, ref="ae", ngkpt=(8, 8, 8), fband=2.0):
        """
        Returns a :class:`Work` object from the given pseudopotential.

        Args:
            kwargs: Extra variables passed to Abinit.

        .. note::

            GBRV tests are done with the following parameteres:

                - No spin polarization for structural relaxation
                  (only for magnetic moments for which spin-unpolarized structures are used)
                - All calculations are done on an 8x8x8 k-point density and with 0.002 Ry Fermi-Dirac smearing
        """
        pseudos = DojoTable.as_table(pseudos)
        if pseudos.allpaw and pawecutdg is None:
            raise ValueError("pawecutdg must be specified for PAW calculations.")

        structure = self.make_ref_structure(formula, struct_type=struct_type, ref=ref)

        return GbrvCompoundRelaxAndEosWork(structure, formula, struct_type, pseudos, self.db.xc, accuracy,
                                           ecut=ecut, pawecutdg=pawecutdg, ngkpt=ngkpt, fband=fband)
Пример #14
0
def pseudos(*filenames):
    """Returns a PseudoTable constructed from the input filenames  located in tests/data/pseudos."""
    return DojoTable(
        [dojopseudo_from_file(os.path.join(dirpath, f)) for f in filenames])
Пример #15
0
def gbrv_runform(options):
    """
    Run GBRV compound tests given a chemical formula.
    """
    # Extract chemical symbols from formula
    formula = options.formula
    symbols = set(species_from_formula(formula))

    # Init pseudo table and construct all possible combinations for the given formula.
    table = DojoTable.from_dir(top=options.pseudo_dir,
                               exts=("psp8", "xml"),
                               exclude_dirs="_*")
    pseudo_list = table.all_combinations_for_elements(symbols)

    #print("Removing relativistic pseudos from list")
    #pseudo_list = [plist for plist in pseudo_list if not any("_r" in p.basename for p in plist)]

    # This is hard-coded since we GBRV results are PBE-only.
    # There's a check between xc and pseudo.xc below.
    xc = "PBE"
    gbrv_factory = GbrvCompoundsFactory(xc=xc)
    db = gbrv_factory.db

    # Consistency check
    entry = db.match_symbols(symbols)
    if entry is None:
        cprint("Cannot find entry for %s! Returning" % str(symbols), "red")
        return 1

    workdir = "GBRVCOMP_" + formula
    print("Working in:", workdir)
    flow = GbrvCompoundsFlow(workdir=workdir)

    accuracy = "high"
    for pseudos in pseudo_list:
        if any(xc != p.xc for p in pseudos):
            raise ValueError("Pseudos with different XC functional")
        ecut = max(p.hint_for_accuracy(accuracy).ecut for p in pseudos)
        pawecutdg = max(
            p.hint_for_accuracy(accuracy).pawecutdg for p in pseudos)
        if ecut <= 0.0: raise RuntimeError("Pseudos do not have hints")
        #ecut = ecut_from_pseudos(pseudos, accuracy)
        print("Adding work for pseudos:", pseudos)
        print("    formula:", entry.symbol, ", structure:", entry.struct_type,
              ", ecut:", ecut)

        work = gbrv_factory.relax_and_eos_work(accuracy,
                                               pseudos,
                                               entry.symbol,
                                               entry.struct_type,
                                               ecut=ecut,
                                               pawecutdg=None)
        flow.register_work(work)

    if options.dry_run:
        flow.build_and_pickle_dump()
        return 0

    # Run the flow with the scheduler (enable smart_io)
    flow.use_smartio()
    return flow.make_scheduler().start()