Exemplo n.º 1
0
    def test_database(self):
        """Testing database of ABINIT variables."""
        database = get_abinit_variables()
        assert database is get_abinit_variables()

        # The text of this variable contaings greek symbols in HTML.
        var = database["cd_frqim_method"]
        repr(var)
        str(var)

        # Print all variables in the database.
        for name, var in database.items():
            #print("testing variable: ", name)
            assert var.name == name
            repr(var)
            str(var)
            str(var.info)
            if sys.version[0:3] > '2.7':
                str(var._repr_html_())

        # Database methods.
        database.apropos("ecut")
        #assert len(database.json_dumps_varnames())

        print("vargeo section:\n", database.vars_with_varset("vargeo"))
        for section in database.my_varset_list:
            assert len(database.vars_with_varset(section))

        for charact in database.my_characteristics:
            #print("character:", charact)
            assert len(database.vars_with_char(charact))

        name2varset = database.name2varset
        assert name2varset["ecut"] == "basic" and name2varset["ionmov"] == "rlx"

        assert database.group_by_varset("ecut") == {'basic': ['ecut']}

        natom_var = database["natom"]
        ecut_var = database["ecut"]
        assert ecut_var.name == "ecut"
        assert not ecut_var.isarray
        assert not ecut_var.depends_on_dimension("natom")
        assert not ecut_var.depends_on_dimension(natom_var)
        assert ecut_var.website_url
        assert ecut_var.html_link() and ecut_var.html_link(label="foo")

        spinat_var = database["spinat"]
        assert spinat_var.isarray
        assert spinat_var.depends_on_dimension("natom")
        assert spinat_var.depends_on_dimension(natom_var)
        assert not spinat_var.depends_on_dimension("ntypat")

        abinit_help("ecut", info=True)
        # Should not raise
        abinit_help("foobar", info=True)

        ecut_var = docvar("ecut")
        assert ecut_var.name == "ecut"
Exemplo n.º 2
0
    def test_database(self):
        """Testing database of ABINIT variables."""
        database = get_abinit_variables()
        assert database is get_abinit_variables()

        # The text of this variable contaings greek symbols in HTML.
        var = database["cd_frqim_method"]
        repr(var); str(var)

        # Print all variables in the database.
        for name, var in database.items():
            #print("testing variable: ", name)
            assert var.name == name
            repr(var); str(var)
            str(var.info)
            if sys.version[0:3] > '2.7':
                str(var._repr_html_())

        # Database methods.
        database.apropos("ecut")
        #assert len(database.json_dumps_varnames())

        print("vargeo section:\n", database.vars_with_varset("vargeo"))
        for section in database.my_varset_list:
            assert len(database.vars_with_varset(section))

        for charact in database.my_characteristics:
            #print("character:", charact)
            assert len(database.vars_with_char(charact))

        name2varset = database.name2varset
        assert name2varset["ecut"] == "basic" and name2varset["ionmov"] == "rlx"

        assert database.group_by_varset("ecut") == {'basic': ['ecut']}

        natom_var = database["natom"]
        ecut_var = database["ecut"]
        assert ecut_var.name == "ecut"
        assert not ecut_var.isarray
        assert not ecut_var.depends_on_dimension("natom")
        assert not ecut_var.depends_on_dimension(natom_var)
        assert ecut_var.website_url
        assert ecut_var.html_link() and ecut_var.html_link(label="foo")

        spinat_var = database["spinat"]
        assert spinat_var.isarray
        assert spinat_var.depends_on_dimension("natom")
        assert spinat_var.depends_on_dimension(natom_var)
        assert not spinat_var.depends_on_dimension("ntypat")

        abinit_help("ecut", info=True)
        # Should not raise
        abinit_help("foobar", info=True)

        ecut_var = docvar("ecut")
        assert ecut_var.name == "ecut"
Exemplo n.º 3
0
    def to_string(self, sortmode=None, post=None):
        """
        String representation.

        Args:
            sortmode: "a" for alphabetical order, None if no sorting is wanted
            post: String that will be appended to the name of the variables
                Note that post is usually autodetected when we have multiple datatasets
                It is mainly used when we have an input file with a single dataset
                so that we can prevent the code from adding "1" to the name of the variables 
                (In this case, indeed, Abinit complains if ndtset=1 is not specified 
                and we don't want ndtset=1 simply because the code will start to add 
                _DS1_ to all the input and output files.
        """
        lines = []
        app = lines.append

        if self.comment:
            app("# " + self.comment.replace("\n", "\n#"))

        if post is None:
            post = "" if self.index == 0 else str(self.index)
        else:
            post = post

        if sortmode is None:
            # no sorting.
            keys = self.keys()
        elif sortmode == "a":
            # alphabetical order.
            keys = sorted(self.keys())
        else:
            raise ValueError("Unsupported value for sortmode %s" %
                             str(sortmode))

        with_mnemonics = self.mnemonics
        if with_mnemonics:
            var_database = get_abinit_variables()

        for var in keys:
            value = self[var]
            # Do not print NO_MULTI variables except for dataset 0.
            if self.index != 0 and var in _ABINIT_NO_MULTI:
                continue

            # Print ndtset only if we really have datasets.
            # This trick prevents abinit from adding DS# to the output files.
            # thus complicating the creation of workflows made of separated calculations.
            if var == "ndtset" and value == 1:
                continue

            if with_mnemonics:
                v = var_database[var]
                app("# <" + v.definition + ">")

            varname = var + post
            variable = InputVariable(varname, value)
            app(str(variable))

        return "\n".join(lines)
Exemplo n.º 4
0
def test_database():
    """Testing database of ABINIT variables."""
    database = get_abinit_variables()

    # The text of this variable contaings greek symbols in HTML.
    var = database["cd_frqim_method"]
    print(var)

    # Print all variables in the database.
    for name, var in database.items():
        print("testing variable: ", name)
        print(repr(var))
        print(var)
        print(var.info)
        print(var._repr_html_())

    # Database methods.
    database.apropos("ecut")
    print(database.json_dumps_varnames())

    print("vargeo section:\n", database.vars_with_section("vargeo"))
    for section in database.sections:
        database.vars_with_section(section)

    name2section = database.name2section
    assert name2section["ecut"] == "varbas" and name2section["ionmov"] == "varrlx"

    assert database.group_by_section("ecut") == {'varbas': ['ecut']}

    assert not database["ecut"].isarray
    assert database["spinat"].isarray
Exemplo n.º 5
0
def test_database():
    """Testing database of ABINIT variables."""
    database = get_abinit_variables()

    # The text of this variable contaings greek symbols in HTML.
    var = database["cd_frqim_method"]
    print(var)

    # Print all variables in the database.
    for name, var in database.items():
        print("testing variable: ", name)
        print(repr(var))
        print(var)
        print(var.info)
        print(var._repr_html_())

    # Database methods.
    database.apropos("ecut")
    print(database.json_dumps_varnames())

    print("vargeo section:\n", database.vars_with_section("vargeo"))
    for section in database.sections:
        database.vars_with_section(section)

    name2section = database.name2section
    assert name2section["ecut"] == "varbas" and name2section[
        "ionmov"] == "varrlx"

    assert database.group_by_section("ecut") == {'varbas': ['ecut']}
Exemplo n.º 6
0
Arquivo: input.py Projeto: kidaa/abipy
    def to_string(self, sortmode=None, post=None):
        """
        String representation.

        Args:
            sortmode: "a" for alphabetical order, None if no sorting is wanted
            post: String that will be appended to the name of the variables
                Note that post is usually autodetected when we have multiple datatasets
                It is mainly used when we have an input file with a single dataset
                so that we can prevent the code from adding "1" to the name of the variables 
                (In this case, indeed, Abinit complains if ndtset=1 is not specified 
                and we don't want ndtset=1 simply because the code will start to add 
                _DS1_ to all the input and output files.
        """
        lines = []
        app = lines.append

        if self.comment:
            app("# " + self.comment.replace("\n", "\n#"))

        if post is None:
            post = "" if self.index == 0 else str(self.index)
        else:
            post = post

        if sortmode is None:
            # no sorting.
            keys = self.keys()
        elif sortmode == "a":
            # alphabetical order.
            keys = sorted(self.keys())
        else:
            raise ValueError("Unsupported value for sortmode %s" % str(sortmode))

        with_mnemonics = self.mnemonics
        if with_mnemonics:
            var_database = get_abinit_variables()

        for var in keys:
            value = self[var]
            # Do not print NO_MULTI variables except for dataset 0.
            if self.index != 0 and var in _ABINIT_NO_MULTI:
                continue

            # Print ndtset only if we really have datasets. 
            # This trick prevents abinit from adding DS# to the output files.
            # thus complicating the creation of workflows made of separated calculations.
            if var == "ndtset" and value == 1:
                continue

            if with_mnemonics:
                v = var_database[var]
                app("# <" + v.definition + ">")

            varname = var + post
            variable = InputVariable(varname, value)
            app(str(variable))

        return "\n".join(lines)
Exemplo n.º 7
0
    def to_string(self, post=None, mode="text", verbose=0):
        """
        String representation.

        Args:
            post: String that will be appended to the name of the variables
            mode: Either `text` or `html` if HTML output with links is wanted.
            verbose: Verbosity level.
        """
        post = post if post is not None else ""
        if mode == "html":
            from abipy.abio.abivars_db import get_abinit_variables
            var_database = get_abinit_variables()

        lines = []
        app = lines.append
        for k in sorted(list(self.keys())):
            vname = k + post
            if mode == "html": vname = var_database[k].html_link(label=vname)
            app("%s %s" % (vname, str(self[k])))

        return "\n".join(lines) if mode=="text" else "\n".join(lines).replace("\n", "<br>")
Exemplo n.º 8
0
    def to_string(self, post=None, mode="text", verbose=0):
        """
        String representation.

        Args:
            post: String that will be appended to the name of the variables
            mode: Either `text` or `html` if HTML output with links is wanted.
            verbose: Verbosity level.
        """
        post = post if post is not None else ""
        if mode == "html":
            from abipy.abio.abivars_db import get_abinit_variables
            var_database = get_abinit_variables()

        lines = []
        app = lines.append
        for k in sorted(list(self.keys())):
            vname = k + post
            if mode == "html": vname = var_database[k].html_link(label=vname)
            app("%s %s" % (vname, str(self[k])))

        return "\n".join(lines) if mode == "text" else "\n".join(
            lines).replace("\n", "<br>")
Exemplo n.º 9
0
def main():
    def str_examples():
        examples = """\
Usage example:
    abidoc.py man ecut      --> Show documentation for ecut input variable.
    abidoc.py apropos ecut  --> To search in the database for the variables related to ecut.
    abidoc.py find paw      --> To search in the database for the variables whose name contains paw
    abidoc.py list          --> Print full list of variables
"""
        return examples

    def show_examples_and_exit(err_msg=None, error_code=1):
        """Display the usage of the script."""
        sys.stderr.write(str_examples())
        if err_msg: sys.stderr.write("Fatal Error\n" + err_msg + "\n")
        sys.exit(error_code)

    # Build the main parser.
    parser = argparse.ArgumentParser(epilog=str_examples(), formatter_class=argparse.RawDescriptionHelpFormatter)
    parser.add_argument('-V', '--version', action='version', version="%(prog)s version " + __version__)


    # Parent parser for common options.
    copts_parser = argparse.ArgumentParser(add_help=False)
    copts_parser.add_argument('-v', '--verbose', default=0, action='count', # -vv --> verbose=2
                              help='verbose, can be supplied multiple times to increase verbosity')
    copts_parser.add_argument('--loglevel', default="ERROR", type=str,
                              help="set the loglevel. Possible values: CRITICAL, ERROR (default), WARNING, INFO, DEBUG")

    var_parser = argparse.ArgumentParser(add_help=False)
    var_parser.add_argument('varname', help="ABINIT variable")

    # Create the parsers for the sub-commands
    subparsers = parser.add_subparsers(dest='command', help='sub-command help', description="Valid subcommands")

    # Subparser for man.
    p_man = subparsers.add_parser('man', parents=[copts_parser, var_parser], help="Show documentation for varname.")

    # Subparser for apropos.
    p_apropos = subparsers.add_parser('apropos', parents=[copts_parser, var_parser], help="Find variables related to varname.")

    # Subparser for find.
    p_find = subparsers.add_parser('find', parents=[copts_parser, var_parser],
                                   help="Find all variables whose name contains varname.")

    # Subparser for require.
    #p_require = subparsers.add_parser('require', parents=[copts_parser], help="Find all variables required by varname.")

    # Subparser for list.
    p_list = subparsers.add_parser('list', parents=[copts_parser], help="List all variables.")
    p_list.add_argument('--mode', default="a",
                        help="Sorte mode, `a` for alphabethical, `s` for sections, `c` for characteristics.")

    try:
        options = parser.parse_args()
    except Exception as exc:
        show_examples_and_exit(error_code=1)

    # loglevel is bound to the string value obtained from the command line argument.
    # Convert to upper case to allow the user to specify --loglevel=DEBUG or --loglevel=debug
    import logging
    numeric_level = getattr(logging, options.loglevel.upper(), None)
    if not isinstance(numeric_level, int):
        raise ValueError('Invalid log level: %s' % options.loglevel)
    logging.basicConfig(level=numeric_level)

    database = get_abinit_variables()

    if options.command == "man":
        abinit_help(options.varname)

    elif options.command == "apropos":
        vlist = database.apropos(options.varname)
        print_vlist(vlist, options)

    elif options.command == "find":
        vlist = [v for v in database.values() if options.varname in v.varname]
        print("find results:\n")
        print_vlist(vlist, options)

    elif options.command == "list":
        if options.mode == "a":
            # Alphabetical
            for i, var in enumerate(database.values()):
                print(i, repr(var))

        elif options.mode == "s":
            # Grouped by sections.
            for section in database.sections:
                header = 30*"#" +  " Section: " + section + " " + 30*"#"
                print(header)
                print_vlist(database.vars_with_section(section), options)

        elif options.mode == "c":
            # Grouped by characteristics.
            for char in database.characteristics:
                header = 30*"#" +  " Characteristic: " + char + 30*"#"
                print(header)
                print_vlist(database.vars_with_char(char), options)

        else:
            raise ValueError("Wrong mode %s" % options.mode)

    else:
        raise ValueError("Don't know how to handle command %s" % options.command)
Exemplo n.º 10
0
 def docvar(varname):
     from abipy.abio.abivars_db import get_abinit_variables
     if varname == "inputvariable":
         return "inputvariable is a very complicated input variable. Better to ask for help immediately"
     return get_abinit_variables()[varname]
Exemplo n.º 11
0
def main():
    def str_examples():
        examples = """\
Usage example:
    abidoc.py man ecut      --> Show documentation for ecut input variable.
    abidoc.py apropos ecut  --> To search in the database for the variables related to ecut.
    abidoc.py find paw      --> To search in the database for the variables whose name contains paw 
    abidoc.py list          --> Print full list of variables 
"""
        return examples

    def show_examples_and_exit(err_msg=None, error_code=1):
        """Display the usage of the script."""
        sys.stderr.write(str_examples())
        if err_msg: sys.stderr.write("Fatal Error\n" + err_msg + "\n")
        sys.exit(error_code)

    # Build the main parser.
    parser = argparse.ArgumentParser(epilog=str_examples(), formatter_class=argparse.RawDescriptionHelpFormatter)

    base_parser = argparse.ArgumentParser(add_help=False)

    base_parser.add_argument('-v', '--verbose', default=0, action='count', # -vv --> verbose=2
                        help='verbose, can be supplied multiple times to increase verbosity')

    var_parser = argparse.ArgumentParser(add_help=False)
    var_parser.add_argument('varname', help="ABINIT variable")

    # Create the parsers for the sub-commands
    subparsers = parser.add_subparsers(dest='command', help='sub-command help', description="Valid subcommands")

    # Subparser for man.
    p_man = subparsers.add_parser('man', parents=[base_parser, var_parser], help="Show documentation for varname.")

    # Subparser for apropos.
    p_apropos = subparsers.add_parser('apropos', parents=[base_parser, var_parser], help="Find variables related to varname.")

    # Subparser for find.
    p_find = subparsers.add_parser('find', parents=[base_parser, var_parser], help="Find all variables whose name contains varname.")

    # Subparser for require.
    #p_require = subparsers.add_parser('require', parents=[base_parser], help="Find all variables required by varname.")

    # Subparser for list.
    p_list = subparsers.add_parser('list', parents=[base_parser], help="List all variables.")
    p_list.add_argument('--mode', default="a", help="Sorte mode, `a` for alphabethical, `s` for sections, `c` for characteristics.")

    try:
        options = parser.parse_args()
    except Exception as exc: 
        show_examples_and_exit(error_code=1)

    database = get_abinit_variables()

    if options.command == "man":
        abinit_help(options.varname)

    elif options.command == "apropos":
        vlist = database.apropos(options.varname)
        print("apropos results:\n")
        print_vlist(vlist, options)

    elif options.command == "find":
        vlist = [v for v in database.values() if options.varname in v.varname]
        print("find results:\n")
        print_vlist(vlist, options)

    elif options.command == "list":

        if options.mode == "a":
            # Alphabetical
            for i, var in enumerate(database.values()):
                print(i, repr(var))

        elif options.mode == "s":
            # Grouped by sections.
            for section in database.sections:
                header = 30*"#" +  " Section: " + section + " " + 30*"#"
                print(header)
                print_vlist(database.vars_with_section(section), options)

        elif options.mode == "c":
            # Grouped by characteristics.
            for char in database.characteristics:
                header = 30*"#" +  " Characteristic: " + char + 30*"#"
                print(header)
                print_vlist(database.vars_with_char(char), options)

        else:
            raise ValueError("Wrong mode %s" % options.mode)

    else:
        raise ValueError("Don't know how to handle command %s" % options.command)
Exemplo n.º 12
0
def main():
    def str_examples():
        examples = """\
Usage example:
    abidoc.py man ecut        --> Show documentation for ecut input variable.
    abidoc.py apropos ecut    --> To search in the database for the variables related to ecut.
    abidoc.py find paw        --> To search in the database for the variables whose name contains paw
    abidoc.py list            --> Print full list of variables
    abidoc.py withdim natom   --> Print arrays depending on natom.
"""
        return examples

    def show_examples_and_exit(err_msg=None, error_code=1):
        """Display the usage of the script."""
        sys.stderr.write(str_examples())
        if err_msg: sys.stderr.write("Fatal Error\n" + err_msg + "\n")
        sys.exit(error_code)

    # Build the main parser.
    parser = argparse.ArgumentParser(
        epilog=str_examples(),
        formatter_class=argparse.RawDescriptionHelpFormatter)
    parser.add_argument('-V',
                        '--version',
                        action='version',
                        version="%(prog)s version " + __version__)

    # Parent parser for common options.
    copts_parser = argparse.ArgumentParser(add_help=False)
    copts_parser.add_argument(
        '-v',
        '--verbose',
        default=0,
        action='count',  # -vv --> verbose=2
        help='verbose, can be supplied multiple times to increase verbosity')
    copts_parser.add_argument(
        '--loglevel',
        default="ERROR",
        type=str,
        help=
        "set the loglevel. Possible values: CRITICAL, ERROR (default), WARNING, INFO, DEBUG"
    )

    var_parser = argparse.ArgumentParser(add_help=False)
    var_parser.add_argument('varname', help="ABINIT variable")

    # Create the parsers for the sub-commands
    subparsers = parser.add_subparsers(dest='command',
                                       help='sub-command help',
                                       description="Valid subcommands")

    # Subparser for man.
    p_man = subparsers.add_parser('man',
                                  parents=[copts_parser, var_parser],
                                  help="Show documentation for varname.")

    # Subparser for apropos.
    p_apropos = subparsers.add_parser(
        'apropos',
        parents=[copts_parser, var_parser],
        help="Find variables related to varname.")

    # Subparser for find.
    p_find = subparsers.add_parser(
        'find',
        parents=[copts_parser, var_parser],
        help="Find all variables whose name contains varname.")

    # Subparser for require.
    #p_require = subparsers.add_parser('require', parents=[copts_parser], help="Find all variables required by varname.")

    # Subparser for withdim.
    p_withdim = subparsers.add_parser(
        'withdim',
        parents=[copts_parser],
        help="Find all arrays depending on the given dimension.")
    p_withdim.add_argument("dimname", help="Dimension name")

    # Subparser for list.
    p_list = subparsers.add_parser('list',
                                   parents=[copts_parser],
                                   help="List all variables.")
    p_list.add_argument(
        '--mode',
        default="a",
        help=
        "Sorte mode, `a` for alphabethical, `s` for sections, `c` for characteristics."
    )

    try:
        options = parser.parse_args()
    except Exception as exc:
        show_examples_and_exit(error_code=1)

    # loglevel is bound to the string value obtained from the command line argument.
    # Convert to upper case to allow the user to specify --loglevel=DEBUG or --loglevel=debug
    import logging
    numeric_level = getattr(logging, options.loglevel.upper(), None)
    if not isinstance(numeric_level, int):
        raise ValueError('Invalid log level: %s' % options.loglevel)
    logging.basicConfig(level=numeric_level)

    database = get_abinit_variables()

    if options.command == "man":
        abinit_help(options.varname)

    elif options.command == "apropos":
        vlist = database.apropos(options.varname)
        print_vlist(vlist, options)

    elif options.command == "find":
        vlist = [v for v in database.values() if options.varname in v.varname]
        print("find results:\n")
        print_vlist(vlist, options)

    elif options.command == "list":
        if options.mode == "a":
            # Alphabetical
            for i, var in enumerate(database.values()):
                print(i, repr(var))

        elif options.mode == "s":
            # Grouped by sections.
            for section in database.sections:
                header = 30 * "#" + " Section: " + section + " " + 30 * "#"
                print(header)
                print_vlist(database.vars_with_section(section), options)

        elif options.mode == "c":
            # Grouped by characteristics.
            for char in database.characteristics:
                header = 30 * "#" + " Characteristic: " + char + 30 * "#"
                print(header)
                print_vlist(database.vars_with_char(char), options)

        else:
            raise ValueError("Wrong mode %s" % options.mode)

    elif options.command == "withdim":
        for var in database.values():
            if var.isarray and options.dimname in str(var.dimensions):
                print(repr(var), "\n", str(var.dimensions),
                      "\n")  # type(var.dimensions)

    else:
        raise ValueError("Don't know how to handle command %s" %
                         options.command)