示例#1
0
    def test_dojo_report_base_api(self):
        """Testing dojo report low-level API."""
        report = DojoReport.from_hints(10, "Si")
        #print(report)
        assert report.symbol == "Si"
        assert report.element.symbol == "Si"
        assert report.ecuts
        assert not report.trials
        for trial in report.ALL_TRIALS:
            assert not report.has_trial(trial)
        assert report.check()

        #prev_ecuts = copy(report.ecuts)
        #report.add_ecuts(10000)
        #assert np.all(report.ecuts == prev_ecuts + [10000])

        report.add_hints([10, 20, 30])
        assert report.has_hints
        #assert report.hints.low.ecut == 10
        #assert report.hints.high.ecut == 30
        #assert not report.md5

        # Test add_entry
        with self.assertRaises(ValueError):
            report.add_entry("foobar", ecut=10, entry={})

        assert not report.has_trial("deltafactor", ecut=10)
        report.add_entry("deltafactor", ecut=10, entry={})
        print(report)
示例#2
0
    def copy_hints(from_djrepo, to_djrepo, verbose):
        from_report = DojoReport.from_file(from_djrepo)
        if "hints" not in from_report:
            print("hints are not present in source", to_djrepo)
            return 1
        to_report = DojoReport.from_file(to_djrepo)
        if "hints" in to_report:
            print("hints are already available in destination", to_djrepo)
            return 2

        if verbose:
            print("Copying hints %s --> %s" % (from_djrepo, to_djrepo))

        # Add hints, and tags. Write new json file.
        to_report["hints"] = from_report["hints"]
        to_report["tags"] = from_report.get("tags", [])
        to_report.json_write()
        return 0
示例#3
0
    def copy_hints(from_djrepo, to_djrepo, verbose):
        from_report = DojoReport.from_file(from_djrepo)
        if "hints" not in from_report:
            print("hints are not present in source", to_djrepo)
            return 1
        to_report = DojoReport.from_file(to_djrepo)
        if "hints" in to_report:
            print("hints are already available in destination", to_djrepo)
            return 2

        if verbose:
            print("Copying hints %s --> %s" % (from_djrepo, to_djrepo))

        # Add hints, and tags. Write new json file.
        to_report["hints"] = from_report["hints"]
        to_report["tags"] = from_report.get("tags", [])
        to_report.json_write()
        return 0
示例#4
0
def djrepo_convert(options):
    raise NotImplementedError()
    # Version 1.0 to 2.0
    new_version = "2.0"
    for path in options.paths:
        report = DojoReport.from_file(path)
        old_version = report["version"]
        if  old_version == new_version: continue
        report = report.to_version(new_version)
        report.json_write()

    return 0
示例#5
0
def djrepo_convert(options):
    raise NotImplementedError()
    # Version 1.0 to 2.0
    new_version = "2.0"
    for path in options.paths:
        report = DojoReport.from_file(path)
        old_version = report["version"]
        if old_version == new_version: continue
        report = report.to_version(new_version)
        report.json_write()

    return 0
示例#6
0
def dojopseudo_from_file(filepath):
    """
    Factory function used to construct a :class:`Pseudo` object from file.
    A DojoPseudo has a DojoReport section and this function adds the report
    to the object.

    Args:
        filepath: Path of the pseudopotential file or djrepo file.

    .. note::

        We cannot subclass Pseudo because it's actually the abstract base class
        and Pseudo.from_file is the factory function that returns the concreate subclass.
    """
    filepath = os.path.abspath(filepath)

    dojo_report = None
    if filepath.endswith(".djrepo"):
        dojo_report = DojoReport.from_file(filepath)
        pp_basename = dojo_report["basename"]
        filepath = os.path.join(os.path.dirname(filepath), pp_basename)

    # Init pseudo from file. Return None if parser error.
    pseudo = Pseudo.from_file(filepath)
    if pseudo is None: return pseudo
    #pseudo.__class__.dojo_report = property(lambda self: self.a + 1)

    if dojo_report is not None:
        # We've already read the report.
        pseudo.dojo_report = dojo_report
        return pseudo

    # Read DojoReport and add it to pseudos
    root, ext = os.path.splitext(filepath)
    djrepo = root + ".djrepo"
    if not os.path.exists(djrepo):
        raise RuntimeError("Cannot find djrepo file at %s" % djrepo)
    pseudo.dojo_report = DojoReport.from_file(djrepo)

    return pseudo
示例#7
0
def dojopseudo_from_file(filepath):
    """
    Factory function used to construct a :class:`Pseudo` object from file.
    A DojoPseudo has a DojoReport section and this function adds the report
    to the object.

    Args:
        filepath: Path of the pseudopotential file or djrepo file.

    .. note::

        We cannot subclass Pseudo because it's actually the abstract base class
        and Pseudo.from_file is the factory function that returns the concreate subclass.
    """
    filepath = os.path.abspath(filepath)

    dojo_report = None
    if filepath.endswith(".djrepo"):
        dojo_report = DojoReport.from_file(filepath)
        pp_basename = dojo_report["basename"]
        filepath = os.path.join(os.path.dirname(filepath), pp_basename)

    # Init pseudo from file. Return None if parser error.
    pseudo = Pseudo.from_file(filepath)
    if pseudo is None: return pseudo
    #pseudo.__class__.dojo_report = property(lambda self: self.a + 1)

    if dojo_report is not None:
        # We've already read the report.
        pseudo.dojo_report = dojo_report
        return pseudo

    # Read DojoReport and add it to pseudos
    root, ext = os.path.splitext(filepath)
    djrepo = root + ".djrepo"
    if not os.path.exists(djrepo):
        raise RuntimeError("Cannot find djrepo file at %s" % djrepo)
    pseudo.dojo_report = DojoReport.from_file(djrepo)

    return pseudo
示例#8
0
    def add_entry_to_dojoreport(self,
                                entry,
                                overwrite_data=False,
                                pop_trial=False):
        """
        Write/update the DOJO_REPORT section of the pseudopotential.
        Important paramenters such as the name of the dojo_trial and the energy cutoff
        are provided by the sub-class.
        Client code is responsible for preparing the dictionary with the data.

        Args:
            entry: Dictionary with results.
            overwrite_data: If False, the routine raises an exception if this entry is
                already filled.
            pop_trial: True if the trial should be removed before adding the new entry.
        """
        root, ext = os.path.splitext(self.dojo_pseudo.filepath)
        djrepo = root + ".djrepo"
        self.history.info("Writing dojreport data to %s" % djrepo)

        # Update file content with Filelock.
        with FileLock(djrepo):
            # Read report from file.
            file_report = DojoReport.from_file(djrepo)

            # Create new entry if not already there
            dojo_trial = self.dojo_trial

            if pop_trial:
                file_report.pop(dojo_trial, None)

            if dojo_trial not in file_report:
                file_report[dojo_trial] = {}

            # Convert float to string with 1 decimal digit.
            dojo_ecut = "%.1f" % self.ecut

            # Check that we are not going to overwrite data.
            if dojo_ecut in file_report[dojo_trial]:
                if not overwrite_data:
                    raise RuntimeError(
                        "dojo_ecut %s already exists in %s. Cannot overwrite data"
                        % (dojo_ecut, dojo_trial))
                else:
                    file_report[dojo_trial].pop(dojo_ecut)

            # Update file_report by adding the new entry and write new file
            file_report[dojo_trial][dojo_ecut] = entry

            # Write new dojo report and update the pseudo attribute
            file_report.json_write()
            self._pseudo.dojo_report = file_report
示例#9
0
    def test_dojo_report_base_api(self):
        """Testing dojo report low-level API."""
        #report = DojoReport.from_hints(10, "Si")
        pseudo = pdj_data.pseudo("Si.psp8")
        ppgen_hints = {
            "low": {
                "ecut": 8.0,
                "pawecutdg": 8.0
            },
            "normal": {
                "ecut": 10.0,
                "pawecutdg": 10.0
            },
            "high": {
                "ecut": 16.0,
                "pawecutdg": 16.0
            },
        }

        report = DojoReport.empty_from_pseudo(pseudo, ppgen_hints, devel=False)
        repr(repr)
        str(report)
        assert report.symbol == "Si"
        assert report.element.symbol == "Si"
        assert report.ecuts
        assert not report.trials
        for trial in report.ALL_TRIALS:
            assert not report.has_trial(trial)
        assert not report.has_hints
        assert report.check()

        #prev_ecuts = copy(report.ecuts)
        #report.add_ecuts(10000)
        #assert np.all(report.ecuts == prev_ecuts + [10000])

        report.add_hints([10, 20, 30])
        assert report.has_hints
        assert report["hints"]["low"]["ecut"] == 10
        assert report["hints"]["high"]["ecut"] == 30
        assert not report.isvalidated
        #assert not report.md5

        # Test add_entry
        with self.assertRaises(ValueError):
            report.add_entry("foobar", ecut=10, entry={})

        assert not report.has_trial("deltafactor", ecut=10)
        report.add_entry("deltafactor", ecut=10, entry={})
        repr(report)
        str(report)
        assert report.has_trial("deltafactor", ecut=10)
示例#10
0
    def add_entry_to_dojoreport(self, entry, overwrite_data=False, pop_trial=False):
        """
        Write/update the DOJO_REPORT section of the pseudopotential.
        Important paramenters such as the name of the dojo_trial and the energy cutoff
        are provided by the sub-class.
        Client code is responsible for preparing the dictionary with the data.

        Args:
            entry: Dictionary with results.
            overwrite_data: If False, the routine raises an exception if this entry is
                already filled.
            pop_trial: True if the trial should be removed before adding the new entry.
        """
        #root, ext = os.path.splitext(self.dojo_pseudo.filepath)
        #djrepo = root + ".djrepo"
        djrepo = self.djrepo_path
        self.history.info("Writing dojreport data to %s" % djrepo)

        # Update file content with Filelock.
        with FileLock(djrepo):
            # Read report from file.
            file_report = DojoReport.from_file(djrepo)

            # Create new entry if not already there
            dojo_trial = self.dojo_trial

            if pop_trial:
                file_report.pop(dojo_trial, None)

            if dojo_trial not in file_report:
                file_report[dojo_trial] = {}

            # Convert float to string with 1 decimal digit.
            dojo_ecut = "%.1f" % self.ecut

            # Check that we are not going to overwrite data.
            if dojo_ecut in file_report[dojo_trial]:
                if not overwrite_data:
                    raise RuntimeError("dojo_ecut %s already exists in %s. Cannot overwrite data" %
                            (dojo_ecut, dojo_trial))
                else:
                    file_report[dojo_trial].pop(dojo_ecut)

            # Update file_report by adding the new entry and write new file
            file_report[dojo_trial][dojo_ecut] = entry

            # Write new dojo report and update the pseudo attribute
            file_report.json_write()
            self._pseudo.dojo_report = file_report
示例#11
0
    def test_dojo_report_base_api(self):
        """Testing dojo report low-level API."""
        #report = DojoReport.from_hints(10, "Si")
        pseudo = pdj_data.pseudo("Si.psp8")
        ppgen_hints = {
            "low": {"ecut": 8.0, "pawecutdg": 8.0},
            "normal": {"ecut": 10.0, "pawecutdg": 10.0},
            "high": { "ecut": 16.0, "pawecutdg": 16.0},
        }

        report = DojoReport.empty_from_pseudo(pseudo, ppgen_hints, devel=False)
        repr(repr); str(report)
        assert report.symbol == "Si"
        assert report.element.symbol == "Si"
        assert report.ecuts
        assert not report.trials
        for trial in report.ALL_TRIALS:
            assert not report.has_trial(trial)
        assert not report.has_hints
        assert report.check()

        #prev_ecuts = copy(report.ecuts)
        #report.add_ecuts(10000)
        #assert np.all(report.ecuts == prev_ecuts + [10000])

        report.add_hints([10, 20, 30])
        assert report.has_hints
        assert report["hints"]["low"]["ecut"] == 10
        assert report["hints"]["high"]["ecut"] == 30
        assert not report.isvalidated
        #assert not report.md5

        # Test add_entry
        with self.assertRaises(ValueError):
            report.add_entry("foobar", ecut=10, entry={})

        assert not report.has_trial("deltafactor", ecut=10)
        report.add_entry("deltafactor", ecut=10, entry={})
        repr(report); str(report)
        assert report.has_trial("deltafactor", ecut=10)
def main():
    website = 'website'

    usage = "Usage: " \
            "create_dojosite_tar.py path\n" \
            "creates the tar for the pseudo dojo website. To change the pseudos included change the list\n" \
            "PSEUDOS_TO_INCLUDE in create_dojosite_tar.py"
    if "--help" in sys.argv or "-h" in sys.argv:
        print(usage)
        return 1

    mock = False

    #  create the main directory for the website file-system

    if os.path.isdir(website):
        print(
            'directory website already exists first move it away then rerun.')
        return
    else:
        os.makedirs(website)

    #  walk the current tree, create the directory structure and copy the .in, .psp8, and .djrepo files
    print('copying selected pseudos:\n%s' % PSEUDOS_TO_INCLUDE)

    for pseudo_set in PSEUDOS_TO_INCLUDE:
        xc = pseudo_set.split('-')[1].lower()
        for acc in ACCURACIES:
            with open(os.path.join(pseudo_set, rnACC[acc] + '.txt')) as f:
                pseudos = f.readlines()
            print(pseudos)

            name = "nc-fr-04_%s_%s" % (xc, rnACC[acc])

            os.makedirs(os.path.join(website, name))
            pseudo_data = {}
            for pseudo in pseudos:
                p = pseudo.strip()
                if not os.path.isfile(os.path.join(pseudo_set, p)):
                    continue
                try:
                    for extension in ['in', 'psp8', 'djrepo', 'out']:
                        copyfile(
                            os.path.join(pseudo_set,
                                         p).replace('psp8', extension),
                            os.path.join(
                                website, name,
                                os.path.split(p)[1].replace('psp8',
                                                            extension)))
                    try:
                        write_notebook_html(os.path.join(
                            website, name,
                            os.path.split(p)[1]),
                                            tmpfile=False,
                                            mock=False)
                    except:
                        print('write notebook failed for {}'.format(pseudo))
                    try:
                        nv = make_upf(os.path.join(website, name,
                                                   os.path.split(p)[1]),
                                      mock=mock,
                                      calctype="fully-relativistic")
                    except RuntimeError:
                        nv = 'NA'
                    p_name = os.path.split(p)[1]
                    # todo see if this works
                    el.replace('_r', '')
                    el = p_name.split('-')[0].split('.')[0]
                    el.replace('3+_f', '')
                    for extension in ['psp8', 'upf', 'djrepo', 'html', 'psml']:
                        os.rename(
                            os.path.join(website, name,
                                         p_name.replace('psp8', extension)),
                            os.path.join(website, name, el + '.' + extension))


#                    os.remove(os.path.join(website, name, os.path.split(p)[1].replace('psp8', 'out')))
                    print('%s %s %s %s ' %
                          ('mocked' if mock else 'done', xc, acc, p))
                    dojoreport = DojoReport.from_file(
                        os.path.join(website, name, el + '.djrepo'))
                    try:
                        low_hint = dojoreport["hints"]["low"]["ecut"]
                        normal_hint = dojoreport["hints"]["normal"]["ecut"]
                        high_hint = dojoreport["hints"]["high"]["ecut"]
                    except KeyError:
                        high_hint = 'na'
                        normal_hint = 'na'
                        low_hint = 'na'
                    try:
                        delta_ecuts = list(dojoreport["deltafactor"].keys())
                        print(delta_ecuts)
                        delta_ecut = delta_ecuts[-1]
                        delta = dojoreport["deltafactor"][delta_ecut][
                            "dfact_meV"]
                        delta_s = "%1.1f" % round(delta, 1)
                        deltap = dojoreport["deltafactor"][delta_ecut][
                            "dfactprime_meV"]
                        deltap_s = "%1.1f" % round(deltap, 1)
                    except (KeyError, TypeError):
                        delta_s = 'na'
                        deltap_s = 'na'
                    try:
                        gb_ecuts = dojoreport["gbrv_bcc"].keys()
                        gb_ecut = gb_ecuts[-1]
                        gb = dojoreport["gbrv_bcc"][gb_ecut]["a0_rel_err"]
                        gf_ecuts = dojoreport["gbrv_fcc"].keys()
                        gf_ecut = gf_ecuts[-1]
                        gf = dojoreport["gbrv_fcc"][gf_ecut]["a0_rel_err"]
                        gb_s = "%0.2f" % round((gb + gf) / 2, 1)
                    except KeyError:
                        gb_s = 'na'
                    print("%s %s %s %s %s %s %s" %
                          (nv, low_hint, normal_hint, high_hint, delta_s,
                           deltap_s, gb_s))
                    pseudo_data[el] = {
                        'nv': nv,
                        'hh': high_hint,
                        'hl': low_hint,
                        'hn': normal_hint,
                        'd': delta_s,
                        'dp': deltap_s,
                        'gb': gb_s
                    }
                except RuntimeError:  # (IOError, ValueError, CellExecutionError, OSError):
                    print('missing %s %s ' % (pseudo_set, p))
                    pass
            with open(os.path.join(website, name + '.json'), 'w') as fp:
                json.dump(pseudo_data, fp=fp, indent=2)

    return
示例#13
0
def oncv_run(options):
    """
    Run oncvpsp, generate djrepo file, plot results. Requires input file.
    """
    # Select calc_type
    calc_type = dict(nor="non-relativistic",
                     sr="scalar-relativistic",
                     fr="fully-relativistic")[options.rel]

    # Build names of psp8 and djson files from input and relativistic mode.
    in_path = options.filename
    root, _ = os.path.splitext(in_path)

    # Enforce convention on output files.
    if options.rel == "nor":
        if not root.endswith("_nor"): root += "_nor"
    elif options.rel == "fr":
        if not root.endswith("_r"):
            root += "_r"
            cprint(
                "FR calculation with input file without `_r` suffix. Will add `_r` to output files",
                "yellow")

    # Build names of output files.
    psp8_path = root + ".psp8"
    djrepo_path = root + ".djrepo"
    out_path = root + ".out"
    if os.path.exists(psp8_path):
        cprint(
            "%s already exists and will be overwritten" %
            os.path.relpath(psp8_path), "yellow")
    if os.path.exists(djrepo_path):
        cprint(
            "%s already exists and will be overwritten" %
            os.path.relpath(djrepo_path), "yellow")
    if os.path.exists(out_path):
        cprint(
            "%s already exists and will be overwritten" %
            os.path.relpath(out_path), "yellow")

    # Build Generator and start generation.
    oncv_ppgen = OncvGenerator.from_file(in_path, calc_type, workdir=None)
    print(oncv_ppgen)
    print(oncv_ppgen.input_str)

    oncv_ppgen.start()
    retcode = oncv_ppgen.wait()

    if oncv_ppgen.status != oncv_ppgen.S_OK:
        cprint("oncvpsp returned %s. Exiting" % retcode, "red")
        return 1

    # Tranfer final output file.
    shutil.copy(oncv_ppgen.stdout_path, out_path)

    # Parse the output file
    onc_parser = OncvOutputParser(out_path)
    onc_parser.scan()
    if not onc_parser.run_completed:
        cprint("oncvpsp output is not complete. Exiting", "red")
        return 1

    # Extract psp8 files from the oncvpsp output and write it to file.
    s = onc_parser.get_psp8_str()
    with open(psp8_path, "wt") as fh:
        fh.write(s)

    # Write upf if available.
    upf_str = onc_parser.get_upf_str()
    if upf_str is not None:
        with open(psp8_path.replace(".psp8", ".upf"), "wt") as fh:
            fh.write(upf_str)

    pseudo = Pseudo.from_file(psp8_path)
    if pseudo is None:
        cprint("Cannot parse psp8 file: %s" % psp8_path, "red")
        return 1

    # Initialize and write djson file.
    report = DojoReport.empty_from_pseudo(pseudo,
                                          onc_parser.hints,
                                          devel=False)
    report.json_write()

    return 0
示例#14
0
    def on_all_ok(self):
        """
        Results are written to the dojoreport.
        """
        def vol2a(vol):
            """Function to compute cubic a0 from primitive v0 (depends on struct_type)"""
            return (4 * vol) ** (1/3.)

        entries = {}
        for task in self:
            ecut = task.input["ecut"]
            #final_structure = task.get_final_structure()
            with task.open_hist() as hist:
                final_structure = hist.final_structure
                initial_energy = hist.etotals[0]

                # Convert float to string with 1 decimal digit.
                dojo_ecut = "%.1f" % ecut
                entries[dojo_ecut] = {
                        "relaxed_a": vol2a(final_structure.volume),
                        "initial_energy_ev_per_atom": float(initial_energy) / len(final_structure),
                }

        #print(entries)
        # Convert to JSON and add results to the dojo report.
        #entry = dict(ecut=self.ecut, pawecutdg=self.dojo_pawecutdg, kppa=self.dojo_kppa)
        #self.add_entry_to_dojoreport(entry)
        #return results
        djrepo = self.djrepo_path

        # Update file content with Filelock.
        with FileLock(djrepo):
            # Read report from file.
            file_report = DojoReport.from_file(djrepo)

            # Create new entry if not already there
            dojo_trial = self.dojo_trial

            #if pop_trial:
            #    file_report.pop(dojo_trial, None)

            if dojo_trial not in file_report:
                file_report[dojo_trial] = {}

            # Convert float to string with 1 decimal digit.
            #dojo_ecut = "%.1f" % self.ecut
            # Check that we are not going to overwrite data.
            #if dojo_ecut in file_report[dojo_trial]:
            #    if not overwrite_data:
            #        raise RuntimeError("dojo_ecut %s already exists in %s. Cannot overwrite data" %
            #                (dojo_ecut, dojo_trial))
            #    else:
            #        file_report[dojo_trial].pop(dojo_ecut)

            # Update file_report by adding the new entry and write new file
            for dojo_ecut, entry in entries.items():
                file_report[dojo_trial][dojo_ecut] = entry

            # Write new dojo report and update the pseudo attribute
            file_report.json_write()
            self._pseudo.dojo_report = file_report

        return dict(returncode=0, message="Lattice paramenters computed and stored in djrepo file")
def main():
    website = 'website'

    usage = "Usage: " \
            "create_dojosite_tar.py path\n" \
            "creates the tar for the pseudo dojo website. To change the pseudos included change the list\n" \
            "PSEUDOS_TO_INCLUDE in create_dojosite_tar.py"
    if "--help" in sys.argv or "-h" in sys.argv:
        print(usage)
        return 1

    mock = False

    #  create the main directory for the website file-system

    if os.path.isdir(website):
        print('directory website already exists first move it away then rerun.')
        return
    else:
        os.makedirs(website)

    #  walk the current tree, create the directory structure and copy the .in, .psp8, and .djrepo files
    print('copying selected pseudos:\n%s' % PSEUDOS_TO_INCLUDE)

    for pseudo_set in PSEUDOS_TO_INCLUDE:
        xc = pseudo_set.split('-')[1].lower()
        for acc in ACCURACIES:
            with open(os.path.join(pseudo_set, rnACC[acc]+'.txt')) as f:
                pseudos = f.readlines()
            print(pseudos)

            name = "nc-fr-04_%s_%s" % (xc, rnACC[acc])

            os.makedirs(os.path.join(website, name))
            pseudo_data = {}
            for pseudo in pseudos:
                p = pseudo.strip()
                if not os.path.isfile(os.path.join(pseudo_set, p)):
                    continue
                try:
                    for extension in ['in', 'psp8', 'djrepo', 'out']:
                        copyfile(os.path.join(pseudo_set, p).replace('psp8', extension),
                                 os.path.join(website, name, os.path.split(p)[1].replace('psp8', extension)))
                    try:
                        write_notebook_html(os.path.join(website, name, os.path.split(p)[1]), tmpfile=False, mock=False)
                    except:
                        print('write notebook failed for {}'.format(pseudo))
                    try:
                        nv = make_upf(os.path.join(website, name, os.path.split(p)[1]), mock=mock,
                                      calctype="fully-relativistic")
                    except RuntimeError:
                        nv = 'NA'
                    p_name = os.path.split(p)[1]
                    # todo see if this works
                    el.replace('_r', '')
                    el = p_name.split('-')[0].split('.')[0]
                    el.replace('3+_f', '')
                    for extension in ['psp8', 'upf', 'djrepo', 'html', 'psml']:
                        os.rename(os.path.join(website, name, p_name.replace('psp8', extension)),
                                  os.path.join(website, name, el + '.' + extension))
#                    os.remove(os.path.join(website, name, os.path.split(p)[1].replace('psp8', 'out')))
                    print('%s %s %s %s ' % ('mocked' if mock else 'done', xc, acc, p))
                    dojoreport = DojoReport.from_file(os.path.join(website, name, el + '.djrepo'))
                    try:
                        low_hint = dojoreport["hints"]["low"]["ecut"]
                        normal_hint = dojoreport["hints"]["normal"]["ecut"]
                        high_hint = dojoreport["hints"]["high"]["ecut"]
                    except KeyError:
                        high_hint = 'na'
                        normal_hint = 'na'
                        low_hint = 'na'
                    try:
                        delta_ecuts = list(dojoreport["deltafactor"].keys())
                        print(delta_ecuts)
                        delta_ecut = delta_ecuts[-1]
                        delta = dojoreport["deltafactor"][delta_ecut]["dfact_meV"]
                        delta_s = "%1.1f" % round(delta, 1)
                        deltap = dojoreport["deltafactor"][delta_ecut]["dfactprime_meV"]
                        deltap_s = "%1.1f" % round(deltap, 1)
                    except (KeyError, TypeError):
                        delta_s = 'na'
                        deltap_s = 'na'
                    try:
                        gb_ecuts = dojoreport["gbrv_bcc"].keys()
                        gb_ecut = gb_ecuts[-1]
                        gb = dojoreport["gbrv_bcc"][gb_ecut]["a0_rel_err"]
                        gf_ecuts = dojoreport["gbrv_fcc"].keys()
                        gf_ecut = gf_ecuts[-1]
                        gf = dojoreport["gbrv_fcc"][gf_ecut]["a0_rel_err"]
                        gb_s = "%0.2f" % round((gb + gf)/2, 1)
                    except KeyError:
                        gb_s = 'na'
                    print("%s %s %s %s %s %s %s" % (nv, low_hint, normal_hint, high_hint, delta_s, deltap_s, gb_s))
                    pseudo_data[el] = {'nv': nv, 'hh': high_hint, 'hl': low_hint, 'hn': normal_hint, 'd': delta_s,
                                       'dp': deltap_s, 'gb': gb_s}
                except RuntimeError: # (IOError, ValueError, CellExecutionError, OSError):
                    print('missing %s %s ' % (pseudo_set, p))
                    pass
            with open(os.path.join(website, name + '.json'), 'w') as fp:
                json.dump(pseudo_data, fp=fp, indent=2)

    return
示例#16
0
def add_dojoreport_to_pseudo(pseudo):
    """Add the dojoreport to a pseudo."""
    if not hasattr(pseudo, "dojo_report"):
        pseudo.dojo_report = DojoReport.from_file(pseudo.djrepo_path)
    return pseudo
示例#17
0
def oncv_run(options):
    """
    Run oncvpsp, generate djrepo file, plot results. Requires input file.
    """
    # Select calc_type
    calc_type = dict(nor="non-relativistic",
                     sr="scalar-relativistic",
                     fr="fully-relativistic")[options.rel]

    # Build names of psp8 and djson files from input and relativistic mode.
    in_path = options.filename
    root, _ = os.path.splitext(in_path)

    # Enforce convention on output files.
    if options.rel == "nor":
        if not root.endswith("_nor"): root += "_nor"
    elif options.rel == "fr":
        if not root.endswith("_r"):
            root += "_r"
            cprint("FR calculation with input file without `_r` suffix. Will add `_r` to output files", "yellow")

    # Build names of output files.
    psp8_path = root + ".psp8"
    djrepo_path = root + ".djrepo"
    out_path = root + ".out"
    if os.path.exists(psp8_path):
        cprint("%s already exists and will be overwritten" % os.path.relpath(psp8_path), "yellow")
    if os.path.exists(djrepo_path):
        cprint("%s already exists and will be overwritten" % os.path.relpath(djrepo_path), "yellow")
    if os.path.exists(out_path):
        cprint("%s already exists and will be overwritten" % os.path.relpath(out_path), "yellow")

    # Build Generator and start generation.
    oncv_ppgen = OncvGenerator.from_file(in_path, calc_type, workdir=None)
    print(oncv_ppgen)
    print(oncv_ppgen.input_str)

    oncv_ppgen.start()
    retcode = oncv_ppgen.wait()

    if oncv_ppgen.status != oncv_ppgen.S_OK:
       cprint("oncvpsp returned %s. Exiting" % retcode, "red")
       return 1

    # Tranfer final output file.
    shutil.copy(oncv_ppgen.stdout_path, out_path)

    # Parse the output file
    onc_parser = OncvOutputParser(out_path)
    onc_parser.scan()
    if not onc_parser.run_completed:
        cprint("oncvpsp output is not complete. Exiting", "red")
        return 1

    # Extract psp8 files from the oncvpsp output and write it to file.
    s = onc_parser.get_pseudo_str()
    with open(psp8_path, "wt") as fh:
        fh.write(s)

    pseudo = Pseudo.from_file(psp8_path)
    if pseudo is None:
        cprint("Cannot parse psp8 file: %s" % psp8_path, "red")
        return 1

    # Initialize and write djson file.
    report = DojoReport.empty_from_pseudo(pseudo, onc_parser.hints, devel=False)
    report.json_write()

    return 0
示例#18
0
def add_dojoreport_to_pseudo(pseudo):
    """Add the dojoreport to a pseudo."""
    if not hasattr(pseudo, "dojo_report"):
        pseudo.dojo_report = DojoReport.from_file(pseudo.djrepo_path)
    return pseudo
示例#19
0
def main():
    website = 'website'

    usage = "Usage: " \
            "create_dojosite_tar.py path\n" \
            "creates the tar for the pseudo dojo website. To change the pseudos included change the list\n" \
            "PSEUDOS_TO_INCLUDE in create_dojosite_tar.py"
    if "--help" in sys.argv or "-h" in sys.argv:
        print(usage)
        return 1
    try:
        path = sys.argv[1]
    except:
        print(usage)
        return 1

    mock = False

    #  create the main directory for the website file-system

    if os.path.isdir(website):
        print(
            'directory website already exists first move it away then rerun.')
        return
    else:
        os.makedirs(website)

    #  walk the current tree, create the directory structure and copy the .in, .psp8, and .djrepo files
    print('copying selected pseudos:\n%s' % PSEUDOS_TO_INCLUDE)
    a = 0

    for pseudo_set in PSEUDOS_TO_INCLUDE:
        xc = pseudo_set.split('-')[1].lower()
        for acc in ACCURACIES:
            with open(os.path.join(pseudo_set, acc)) as f:
                pseudos = f.readlines()
            name = "%s_%s_sr" % (xc, acc[0])
            #for fmt in ['psp8', 'upf', 'html', 'djrepo']:
            #    os.makedirs(os.path.join(website, '%s_%s' % (name, fmt)))
            os.makedirs(os.path.join(website, name))
            for pseudo in pseudos:
                p = pseudo.strip()
                try:
                    for extension in ['in', 'psp8', 'djrepo', 'out']:
                        copyfile(
                            os.path.join(pseudo_set,
                                         p).replace('psp8', extension),
                            os.path.join(
                                website, name,
                                os.path.split(p)[1].replace('psp8',
                                                            extension)))
                    try:
                        write_notebook_html(os.path.join(
                            website, name,
                            os.path.split(p)[1]),
                                            tmpfile=False,
                                            mock=mock)
                    except:
                        pass
                    try:
                        nv = make_upf(os.path.join(website, name,
                                                   os.path.split(p)[1]),
                                      mock=mock,
                                      calctype="scalar-relativistic")
                    except None:
                        nv = 'NA'
                    p_name = os.path.split(p)[1]
                    el = p_name.split('-')[0].split('.')[0]
                    for extension in ['psp8', 'upf', 'djrepo', 'html']:
                        os.rename(
                            os.path.join(website, name,
                                         p_name.replace('psp8', extension)),
                            os.path.join(website, name, el + '.' + extension))
                    os.remove(
                        os.path.join(
                            website, name,
                            os.path.split(p)[1].replace('psp8', 'out')))
                    print('%s %s %s %s ' %
                          ('mocked' if mock else 'done', xc, acc, p))
                    dojoreport = DojoReport.from_file(
                        os.path.join(website, name, el + '.djrepo'))
                    try:
                        normal_hint = dojoreport["hints"]["normal"]["ecut"]
                    except KeyError:
                        normal_hint = 'NA'
                    try:
                        delta_ecuts = dojoreport["deltafactor"].keys()
                        delta_ecut = delta_ecuts[-1]
                        delta = dojoreport["deltafactor"][delta_ecut][
                            "dfact_meV"]
                        delta_s = "%1.1f" % round(delta, 1)
                    except KeyError:
                        delta_s = 'NA'
                    print("%s %s %s" % (nv, normal_hint, delta_s))
                    with open(os.path.join(website, name, el + '.txt'),
                              'w') as f:
                        f.write("%s %s %s" % (nv, normal_hint, delta_s))
                except (IOError, ValueError, CellExecutionError, OSError):
                    print('missing %s %s ' % (pseudo_set, p))
                    pass

                #a += 1
                #if a > 0:
                #    mock = True
    return