Beispiel #1
0
def info():
    """Show versions of GPAW and its dependencies."""
    results = [('python-' + sys.version.split()[0], sys.executable)]
    for name in ['gpaw', 'ase', 'numpy', 'scipy']:
        try:
            module = import_module(name)
        except ImportError:
            results.append((name, False))
        else:
            results.append((name + '-' + module.__version__,
                            module.__file__.rsplit('/', 1)[0] + '/'))
    module = import_module('_gpaw')
    results.append(
        ('_gpaw', op.normpath(getattr(module, '__file__', 'built-in'))))
    p = subprocess.Popen(['which', 'gpaw-python'], stdout=subprocess.PIPE)
    results.append(('parallel', p.communicate()[0].strip().decode() or False))
    results.append(('FFTW', fftw.FFTPlan is fftw.FFTWPlan))
    results.append(('scalapack', compiled_with_sl()))
    results.append(('libvdwxc', compiled_with_libvdwxc()))
    paths = [
        '{0}: {1}'.format(i + 1, path)
        for i, path in enumerate(gpaw.setup_paths)
    ]
    results.append(('PAW-datasets', '\n                '.join(paths)))

    for a, b in results:
        if isinstance(b, bool):
            b = ['no', 'yes'][b]
        print('{0:16}{1}'.format(a, b))
Beispiel #2
0
def initialize(format):
    """Import read and write functions."""
    if format in ioformats:
        return  # already done

    _format = format.replace('-', '_')
    module_name = format2modulename.get(format, _format)

    try:
        module = import_module('ase.io.' + module_name)
    except ImportError as err:
        raise ValueError('File format not recognized: %s.  Error: %s' %
                         (format, err))

    read = getattr(module, 'read_' + _format, None)
    write = getattr(module, 'write_' + _format, None)

    if read and not inspect.isgeneratorfunction(read):
        read = functools.partial(wrap_read_function, read)
    if not read and not write:
        raise ValueError('File format not recognized: ' + format)
    code = all_formats[format][1]
    single = code[0] == '1'
    acceptsfd = code[1] == 'F'
    ioformats[format] = IOFormat(read, write, single, acceptsfd)
Beispiel #3
0
def initialize(format):
    """Import read and write functions."""
    if format in ioformats:
        return  # already done

    _format = format.replace('-', '_')
    module_name = format2modulename.get(format, _format)

    try:
        module = import_module('ase.io.' + module_name)
    except ImportError as err:
        raise ValueError('File format not recognized: %s.  Error: %s'
                         % (format, err))

    read = getattr(module, 'read_' + _format, None)
    write = getattr(module, 'write_' + _format, None)

    if read and not inspect.isgeneratorfunction(read):
        read = functools.partial(wrap_read_function, read)
    if not read and not write:
        raise ValueError('File format not recognized: ' + format)
    code = all_formats[format][1]
    single = code[0] == '1'
    acceptsfd = code[1] == 'F'
    ioformats[format] = IOFormat(read, write, single, acceptsfd)
Beispiel #4
0
def info():
    """Show versions of GPAW and its dependencies."""
    results = [('python-' + sys.version.split()[0], sys.executable)]
    for name in ['gpaw', 'ase', 'numpy', 'scipy']:
        try:
            module = import_module(name)
        except ImportError:
            results.append((name, False))
        else:
            # Search for git hash
            githash = search_current_git_hash(module)
            if githash is None:
                githash = ''
            else:
                githash = '-{:.10}'.format(githash)
            results.append((name + '-' + module.__version__ + githash,
                            module.__file__.rsplit('/', 1)[0] + '/'))
    results.append(('libxc-' + _gpaw.libxc_version, ''))
    module = import_module('_gpaw')
    if hasattr(module, 'githash'):
        githash = '-{:.10}'.format(module.githash())
    results.append(
        ('_gpaw' + githash, op.normpath(getattr(module, '__file__',
                                                'built-in'))))
    p = subprocess.Popen(['which', 'gpaw-python'], stdout=subprocess.PIPE)
    results.append(('parallel', p.communicate()[0].strip().decode() or False))
    results.append(('MPI enabled', have_mpi))
    if have_mpi:
        have_sl = compiled_with_sl()
        have_elpa = LibElpa.have_elpa()
    else:
        have_sl = have_elpa = 'no (MPI unavailable)'
    results.append(('scalapack', have_sl))
    results.append(('Elpa', have_elpa))
    results.append(('FFTW', fftw.FFTPlan is fftw.FFTWPlan))
    results.append(('libvdwxc', compiled_with_libvdwxc()))
    paths = [
        '{0}: {1}'.format(i + 1, path)
        for i, path in enumerate(gpaw.setup_paths)
    ]
    results.append(('PAW-datasets', '\n{:25}'.format('').join(paths)))

    if rank == 0:
        for a, b in results:
            if isinstance(b, bool):
                b = ['no', 'yes'][b]
            print('{0:25}{1}'.format(a, b))
Beispiel #5
0
def main(prog='ase', description='ASE command line tool',
         version=__version__, commands=commands, hook=None):
    parser = argparse.ArgumentParser(prog=prog, description=description)
    parser.add_argument('--version', action='version',
                        version='%(prog)s-{}'.format(version))
    parser.add_argument('-T', '--traceback', action='store_true')
    subparsers = parser.add_subparsers(title='Sub-commands',
                                       dest='command')

    subparser = subparsers.add_parser('help',
                                      description='Help',
                                      help='Help for sub-command')
    subparser.add_argument('helpcommand', nargs='?')

    functions = {}
    parsers = {}
    for command, module_name in commands:
        cmd = import_module(module_name).CLICommand
        subparser = subparsers.add_parser(
            command,
            help=cmd.short_description,
            description=getattr(cmd, 'description', cmd.short_description))
        cmd.add_arguments(subparser)
        functions[command] = cmd.run
        parsers[command] = subparser

    if hook:
        args = hook(parser)
    else:
        args = parser.parse_args()

    if args.command == 'help':
        if args.helpcommand is None:
            parser.print_help()
        else:
            parsers[args.helpcommand].print_help()
    elif args.command is None:
        parser.print_usage()
    else:
        f = functions[args.command]
        try:
            if f.__code__.co_argcount == 1:
                f(args)
            else:
                f(args, parsers[args.command])
        except KeyboardInterrupt:
            pass
        except Exception as x:
            if args.traceback:
                raise
            else:
                print('{}: {}'.format(x.__class__.__name__, x),
                      file=sys.stderr)
                print('To get a full traceback, use: {} -T {} ...'
                      .format(prog, args.command), file=sys.stderr)
Beispiel #6
0
def main(prog='ase', description='ASE command line tool',
         version=__version__, commands=commands, hook=None, args=None):
    parser = argparse.ArgumentParser(prog=prog, description=description)
    parser.add_argument('--version', action='version',
                        version='%(prog)s-{}'.format(version))
    parser.add_argument('-T', '--traceback', action='store_true')
    subparsers = parser.add_subparsers(title='Sub-commands',
                                       dest='command')

    subparser = subparsers.add_parser('help',
                                      description='Help',
                                      help='Help for sub-command')
    subparser.add_argument('helpcommand', nargs='?')

    functions = {}
    parsers = {}
    for command, module_name in commands:
        cmd = import_module(module_name).CLICommand
        subparser = subparsers.add_parser(
            command,
            help=cmd.short_description,
            description=getattr(cmd, 'description', cmd.short_description))
        cmd.add_arguments(subparser)
        functions[command] = cmd.run
        parsers[command] = subparser

    if hook:
        args = hook(parser, args)
    else:
        args = parser.parse_args(args)

    if args.command == 'help':
        if args.helpcommand is None:
            parser.print_help()
        else:
            parsers[args.helpcommand].print_help()
    elif args.command is None:
        parser.print_usage()
    else:
        f = functions[args.command]
        try:
            if f.__code__.co_argcount == 1:
                f(args)
            else:
                f(args, parsers[args.command])
        except KeyboardInterrupt:
            pass
        except Exception as x:
            if args.traceback:
                raise
            else:
                print('{}: {}'.format(x.__class__.__name__, x),
                      file=sys.stderr)
                print('To get a full traceback, use: {} -T {} ...'
                      .format(prog, args.command), file=sys.stderr)
Beispiel #7
0
def print_info():
    versions = [('platform', platform.platform()),
                ('python-' + sys.version.split()[0], sys.executable)]
    for name in ['ase', 'numpy', 'scipy']:
        try:
            module = import_module(name)
        except ImportError:
            versions.append((name, 'no'))
        else:
            versions.append((name + '-' + module.__version__,
                             module.__file__.rsplit('/', 1)[0] + '/'))

    for a, b in versions:
        print('{:16}{}'.format(a, b))
Beispiel #8
0
def update(filename, commands):
    """Update commands dict.

    Run this when ever options are changed::

        python3 -m ase.cli.complete

    """

    import textwrap
    from ase.utils import import_module

    dct = {}  # Dict[str, List[str]]

    class Subparser:
        def __init__(self, command):
            self.command = command
            dct[command] = []

        def add_argument(self, *args, **kwargs):
            dct[command].extend(arg for arg in args if arg.startswith('-'))

        def add_mutually_exclusive_group(self, required=False):
            return self

    for command, module_name in commands:
        module = import_module(module_name)
        module.CLICommand.add_arguments(Subparser(command))

    txt = 'commands = {'
    for command, opts in sorted(dct.items()):
        txt += "\n    '" + command + "':\n        ["
        if opts:
            txt += '\n'.join(
                textwrap.wrap("'" + "', '".join(opts) + "'],",
                              width=65,
                              break_on_hyphens=False,
                              subsequent_indent='         '))
        else:
            txt += '],'
    txt = txt[:-1] + '}\n'
    with open(filename) as fd:
        lines = fd.readlines()
        a = lines.index('# Beginning of computer generated data:\n')
        b = lines.index('# End of computer generated data\n')
    lines[a + 1:b] = [txt]
    with open(filename + '.new', 'w') as fd:
        print(''.join(lines), end='', file=fd)
    os.rename(filename + '.new', filename)
    os.chmod(filename, 0o775)
Beispiel #9
0
def print_info():
    versions = [('platform', platform.platform()),
                ('python-' + sys.version.split()[0], sys.executable)]
    for name in ['ase', 'numpy', 'scipy']:
        try:
            module = import_module(name)
        except ImportError:
            versions.append((name, 'no'))
        else:
            versions.append((name + '-' + module.__version__,
                            module.__file__.rsplit('/', 1)[0] + '/'))

    for a, b in versions:
        print('{:16}{}'.format(a, b))
Beispiel #10
0
def update(filename, commands):
    """Update commands dict.

    Run this when ever options are changed::

        python3 -m ase.cli.complete

    """

    import collections
    import textwrap
    from ase.utils import import_module

    dct = collections.defaultdict(list)

    class Subparser:
        def __init__(self, command):
            self.command = command

        def add_argument(self, *args, **kwargs):
            dct[command].extend(arg for arg in args
                                if arg.startswith('-'))

    for command, module_name in commands:
        module = import_module(module_name)
        module.CLICommand.add_arguments(Subparser(command))

    txt = 'commands = {'
    for command, opts in sorted(dct.items()):
        txt += "\n    '" + command + "':\n        ["
        txt += '\n'.join(textwrap.wrap("'" + "', '".join(opts) + "'],",
                         width=65,
                         break_on_hyphens=False,
                         subsequent_indent='         '))
    txt = txt[:-1] + '}\n'
    with open(filename) as fd:
        lines = fd.readlines()
        a = lines.index('# Beginning of computer generated data:\n')
        b = lines.index('# End of computer generated data\n')
    lines[a + 1:b] = [txt]
    with open(filename + '.new', 'w') as fd:
        print(''.join(lines), end='', file=fd)
    os.rename(filename + '.new', filename)
    os.chmod(filename, 0o775)
Beispiel #11
0
def print_info():
    versions = [('platform', platform.platform()),
                ('python-' + sys.version.split()[0], sys.executable)]
    for name in ['ase', 'numpy', 'scipy']:
        try:
            module = import_module(name)
        except ImportError:
            versions.append((name, 'no'))
        else:
            # Search for git hash
            githash = search_current_git_hash(module)
            if githash is None:
                githash = ''
            else:
                githash = '-{:.10}'.format(githash)
            versions.append((name + '-' + module.__version__ + githash,
                            module.__file__.rsplit(os.sep, 1)[0] + os.sep))

    for a, b in versions:
        print('{:25}{}'.format(a, b))
Beispiel #12
0
def main(prog='ase',
         description='ASE command line tool.',
         version=__version__,
         commands=commands,
         hook=None,
         args=None):
    parser = argparse.ArgumentParser(prog=prog,
                                     description=description,
                                     formatter_class=Formatter)
    parser.add_argument('--version',
                        action='version',
                        version='%(prog)s-{}'.format(version))
    parser.add_argument('-T', '--traceback', action='store_true')
    subparsers = parser.add_subparsers(title='Sub-commands', dest='command')

    subparser = subparsers.add_parser('help',
                                      description='Help',
                                      help='Help for sub-command.')
    subparser.add_argument('helpcommand',
                           nargs='?',
                           metavar='sub-command',
                           help='Provide help for sub-command.')

    functions = {}
    parsers = {}
    for command, module_name in commands:
        cmd = import_module(module_name).CLICommand
        docstring = cmd.__doc__
        if docstring is None:
            # Backwards compatibility with GPAW
            short = cmd.short_description
            long = getattr(cmd, 'description', short)
        else:
            parts = docstring.split('\n', 1)
            if len(parts) == 1:
                short = docstring
                long = docstring
            else:
                short, body = parts
                long = short + '\n' + textwrap.dedent(body)
        subparser = subparsers.add_parser(command,
                                          formatter_class=Formatter,
                                          help=short,
                                          description=long)
        cmd.add_arguments(subparser)
        functions[command] = cmd.run
        parsers[command] = subparser

    if hook:
        args = hook(parser, args)
    else:
        args = parser.parse_args(args)

    if args.command == 'help':
        if args.helpcommand is None:
            parser.print_help()
        else:
            parsers[args.helpcommand].print_help()
    elif args.command is None:
        parser.print_usage()
    else:
        f = functions[args.command]
        try:
            if f.__code__.co_argcount == 1:
                f(args)
            else:
                f(args, parsers[args.command])
        except KeyboardInterrupt:
            pass
        except CLIError as x:
            parser.error(x)
        except Exception as x:
            if args.traceback:
                raise
            else:
                l1 = '{}: {}\n'.format(x.__class__.__name__, x)
                l2 = ('To get a full traceback, use: {} -T {} ...'.format(
                    prog, args.command))
                parser.error(l1 + l2)
Beispiel #13
0
def test(verbosity=1, calculators=[],
         testdir=None, display=True, stream=sys.stdout, files=None):
    test_calculator_names.extend(calculators)
    disable_calculators([name for name in calc_names
                         if name not in calculators])
    ts = unittest.TestSuite()
    if files:
        files = [os.path.join(__path__[0], f) for f in files]
    else:
        files = glob(__path__[0] + '/*')
    sdirtests = []  # tests from subdirectories: only one level assumed
    tests = []
    for f in files:
        if os.path.isdir(f):
            # add test subdirectories (like calculators)
            sdirtests.extend(glob(f + '/*.py'))
        else:
            # add py files in testdir
            if f.endswith('.py'):
                tests.append(f)
    tests.sort()
    sdirtests.sort()
    tests.extend(sdirtests)  # run test subdirectories at the end
    lasttest = None  # is COCu111.py in the current set
    for test in tests:
        if test.endswith('__.py'):
            continue
        if test.endswith('COCu111.py'):
            lasttest = test
            continue
        ts.addTest(ScriptTestCase(filename=os.path.abspath(test),
                                  display=display))
    if lasttest:
        ts.addTest(ScriptTestCase(filename=os.path.abspath(lasttest),
                                  display=display))

    versions = [('platform', platform.platform()),
                ('python-' + sys.version.split()[0], sys.executable)]
    for name in ['ase', 'numpy', 'scipy']:
        try:
            module = import_module(name)
        except ImportError:
            versions.append((name, 'no'))
        else:
            versions.append((name + '-' + module.__version__,
                            module.__file__.rsplit('/', 1)[0] + '/'))

    if verbosity:
        for a, b in versions:
            print('{0:16}{1}'.format(a, b))

    sys.stdout = devnull

    if verbosity == 0:
        stream = devnull
    ttr = unittest.TextTestRunner(verbosity=verbosity, stream=stream)

    origcwd = os.getcwd()

    if testdir is None:
        testdir = tempfile.mkdtemp(prefix='ase-test-')
    else:
        if os.path.isdir(testdir):
            shutil.rmtree(testdir)  # clean before running tests!
        os.mkdir(testdir)
    os.chdir(testdir)
    if verbosity:
        print('test-dir       ', testdir, '\n', file=sys.__stdout__)
    try:
        results = ttr.run(ts)
    finally:
        os.chdir(origcwd)
        sys.stdout = sys.__stdout__

    return results
Beispiel #14
0
def test(verbosity=1,
         calculators=[],
         testdir=None,
         display=True,
         stream=sys.stdout):
    test_calculator_names.extend(calculators)
    disable_calculators(
        [name for name in calc_names if name not in calculators])
    ts = unittest.TestSuite()
    files = glob(__path__[0] + '/*')
    sdirtests = []  # tests from subdirectories: only one level assumed
    tests = []
    for f in files:
        if os.path.isdir(f):
            # add test subdirectories (like calculators)
            sdirtests.extend(glob(f + '/*.py'))
        else:
            # add py files in testdir
            if f.endswith('.py'):
                tests.append(f)
    tests.sort()
    sdirtests.sort()
    tests.extend(sdirtests)  # run test subdirectories at the end
    lasttest = None  # is COCu111.py in the current set
    for test in tests:
        if test.endswith('__.py'):
            continue
        if test.endswith('COCu111.py'):
            lasttest = test
            continue
        ts.addTest(
            ScriptTestCase(filename=os.path.abspath(test), display=display))
    if lasttest:
        ts.addTest(
            ScriptTestCase(filename=os.path.abspath(lasttest),
                           display=display))

    versions = [('platform', platform.platform()),
                ('python-' + sys.version.split()[0], sys.executable)]
    for name in ['ase', 'numpy', 'scipy']:
        try:
            module = import_module(name)
        except ImportError:
            versions.append((name, 'no'))
        else:
            versions.append((name + '-' + module.__version__,
                             module.__file__.rsplit('/', 1)[0] + '/'))

    for a, b in versions:
        print('{0:16}{1}'.format(a, b))

    sys.stdout = devnull

    ttr = unittest.TextTestRunner(verbosity=verbosity, stream=stream)

    origcwd = os.getcwd()

    if testdir is None:
        testdir = tempfile.mkdtemp(prefix='ase-test-')
    else:
        if os.path.isdir(testdir):
            shutil.rmtree(testdir)  # clean before running tests!
        os.mkdir(testdir)
    os.chdir(testdir)
    print('test-dir       ', testdir, '\n', file=sys.__stdout__)
    try:
        results = ttr.run(ts)
    finally:
        os.chdir(origcwd)
        sys.stdout = sys.__stdout__

    return results