Exemple #1
0
def work_play(calculations):
    """
    Play paused work calculations
    """
    from aiida.work import RemoteException, DeliveryFailed, new_blocking_control_panel

    with new_blocking_control_panel() as control_panel:
        for calculation in calculations:

            if calculation.is_terminated:
                echo.echo_error('Calculation<{}> is already terminated'.format(
                    calculation.pk))
                continue

            try:
                if control_panel.play_process(calculation.pk):
                    echo.echo_success('played Calculation<{}>'.format(
                        calculation.pk))
                else:
                    echo.echo_critical(
                        'problem playing Calculation<{}>'.format(
                            calculation.pk))
            except (RemoteException, DeliveryFailed) as exception:
                echo.echo_critical('failed to play Calculation<{}>: {}'.format(
                    calculation.pk, exception.message))
Exemple #2
0
def cmd_mark(force):
    """Mark all `StructureData` nodes with partial occupancies.

    A `StructureData` is said to have partial occupancies if any of its kinds contain more than one symbol (an alloy) or
    the total weight is not unity (vacancies). Any `StructureData` that matches this definition will get an extra set
    with the name `partial_occupancies=True`, otherwise it will be `False`. The reason for setting this extra also on
    structures that do not have partial occupancies, is to make it easy in the future which structures have already been
    considered from marking. When the command is then executed only those structures without mark have to be considered.
    """
    from aiida.manage.manager import get_manager

    builder = get_unmarked_structure_builder()
    unmarked = builder.count()
    echo.echo_info('found {} unmarked structures'.format(unmarked))

    if not unmarked:
        echo.echo_success('nothing to be done')
        return

    total = 0

    with click.progressbar(label='Marking structures', length=unmarked, show_pos=True) as progress:
        with get_manager().get_backend().transaction():
            for [structure] in builder.iterall():

                partial_occupancies = structure.is_alloy or structure.has_vacancies
                structure.set_extra(KEY_PARTIAL_OCCUPANCIES, partial_occupancies)

                if partial_occupancies:
                    total += 1

                progress.update(1)

    echo.echo_success('marked {} structures as containing partial occupancies'.format(total))
Exemple #3
0
def cmd_family_cutoffs_set(family, cutoffs, stringency, unit):  # noqa: D301
    """Set the recommended cutoffs for a pseudo potential family and a specified stringency.

    The cutoffs should be provided as a JSON file through the argument `CUTOFFS` which should have the structure:

    \b
        {
            "Ag": {
                "cutoff_wfc": 50.0,
                "cutoff_rho": 200.0
            },
            ...
        }

    where the cutoffs are expected to be in electronvolt by default.
    """
    if not isinstance(family, RecommendedCutoffMixin):
        raise click.BadParameter(f'family `{family}` does not support recommended cutoffs to be set.')

    try:
        data = json.load(cutoffs)
    except ValueError as exception:
        raise click.BadParameter(f'`{cutoffs.name}` contains invalid JSON: {exception}', param_hint='CUTOFFS')

    try:
        family.set_cutoffs(data, stringency, unit=unit)
    except ValueError as exception:
        raise click.BadParameter(f'`{cutoffs.name}` contains invalid cutoffs: {exception}', param_hint='CUTOFFS')

    echo.echo_success(f'set cutoffs for `{family}` with the stringency `{stringency}`.')
Exemple #4
0
def cmd_add_source(database):
    from aiida import orm

    group_label = '{}/structure/primitive'.format(database)
    filters_group = {'label': group_label}
    filters_structure = {'extras': {'!has_key': KEY_SOURCE}}

    builder = orm.QueryBuilder().append(
        orm.Group, filters=filters_group, tag='group').append(
        orm.StructureData, filters=filters_structure, with_group='group', project='*', tag='structure').append(
        orm.WorkChainNode, with_outgoing='structure', tag='workchain').append(
        orm.CifData, with_outgoing='workchain', project=['attributes.source.id', 'attributes.source.version'])

    count = builder.count()
    label = 'Adding source info to extras of structure in `{}`'.format(group_label)

    if count == 0:
        echo.echo_success('No structures in group `{}` without source extra'.format(group_label))
        return

    with click.progressbar(label=label, length=count, show_pos=True) as progress:
        for structure, source_id, source_version in builder.all():
            source = {
                'database': database,
                'id': source_id,
                'version': source_version,
            }
            structure.set_extra(KEY_SOURCE, source)
            structure.backend_entity.dbmodel.save()
            progress.update(1)

    echo.echo_success('Added source info to {} structures in group `{}`'.format(count, group_label))
Exemple #5
0
def group_delete(group, clear, force):
    """Delete a group.

    Note that a group that contains nodes cannot be deleted if it contains any nodes. If you still want to delete the
    group, use the `-c/--clear` flag to remove the contents before deletion. Note that in any case, the nodes themselves
    will not actually be deleted from the database.
    """
    from aiida import orm

    label = group.label

    if group.count() > 0 and not clear:
        echo.echo_critical((
            'Group<{}> contains {} nodes. Pass `--clear` if you want to empty it before deleting the group'
            .format(label, group.count())))

    if not force:
        click.confirm('Are you sure to delete Group<{}>?'.format(label),
                      abort=True)

    if clear:
        group.clear()

    orm.Group.objects.delete(group.pk)
    echo.echo_success('Group<{}> deleted.'.format(label))
Exemple #6
0
def process_pause(processes, timeout):
    """Pause running processes."""
    from aiida.work import RemoteException, DeliveryFailed, TimeoutError, new_blocking_control_panel

    with new_blocking_control_panel(timeout=timeout) as control_panel:
        for process in processes:

            if process.is_terminated:
                echo.echo_error('Process<{}> is already terminated'.format(
                    process.pk))
                continue

            try:
                if control_panel.pause_process(
                        process.pk,
                        msg='Paused through `verdi process pause`'):
                    echo.echo_success('paused Process<{}>'.format(process.pk))
                else:
                    echo.echo_error('problem pausing Process<{}>'.format(
                        process.pk))
            except TimeoutError:
                echo.echo_error('call to pause Process<{}> timed out'.format(
                    process.pk))
            except (RemoteException, DeliveryFailed) as exception:
                echo.echo_error('failed to pause Process<{}>: {}'.format(
                    process.pk, exception.message))
Exemple #7
0
def setup_code(non_interactive, **kwargs):
    """Add a Code."""
    from aiida.common.exceptions import ValidationError

    if not non_interactive:
        pre, post = ensure_scripts(kwargs.pop('prepend_text', ''),
                                   kwargs.pop('append_text', ''), kwargs)
        kwargs['prepend_text'] = pre
        kwargs['append_text'] = post

    if kwargs.pop('on_computer'):
        kwargs['code_type'] = CodeBuilder.CodeType.ON_COMPUTER
    else:
        kwargs['code_type'] = CodeBuilder.CodeType.STORE_AND_UPLOAD
    code_builder = CodeBuilder(**kwargs)
    code = code_builder.new()

    try:
        code.store()
        code.reveal()  # newly setup code shall not be hidden
    except ValidationError as err:
        echo.echo_critical(
            'unable to store the code: {}. Exiting...'.format(err))

    echo.echo_success('code "{}" stored in DB.'.format(code.label))
    echo.echo_info('pk: {}, uuid: {}'.format(code.pk, code.uuid))
Exemple #8
0
def hide(codes):
    """
    Hide one or more codes from the verdi show command
    """
    for code in codes:
        code.hide()
        echo.echo_success("Code '{}' hidden.".format(code.pk))
Exemple #9
0
def reveal(codes):
    """
    Reveal one or more hidden codes to the verdi show command
    """
    for code in codes:
        code.reveal()
        echo.echo_success("Code '{}' revealed.".format(code.pk))
Exemple #10
0
def node_description(nodes, description, force, raw):
    """View or set the description of one or more nodes."""
    table = []

    if description is None:
        for node in nodes:

            if raw:
                table.append([node.description])
            else:
                table.append([node.pk, node.description])

        if raw:
            echo.echo(tabulate.tabulate(table, tablefmt='plain'))
        else:
            echo.echo(tabulate.tabulate(table, headers=['ID', 'Description']))

    else:
        if not force:
            warning = 'Are you sure you want to set the description for  {} nodes?'.format(len(nodes))
            click.confirm(warning, abort=True)

        for node in nodes:
            node.description = description

        echo.echo_success('Set description for {} nodes'.format(len(nodes)))
Exemple #11
0
def cmd_install_family(archive, label, description, archive_format, family_type, traceback):  # pylint: disable=too-many-arguments
    """Install a standard pseudo potential family from an ARCHIVE on the local file system or from a URL.

    The command will attempt to infer the archive format from the filename extension of the ARCHIVE. If this fails, the
    archive format can be specified explicitly with the archive format option, which will also display which formats
    are supported.

    By default, the command will create a base `PseudoPotentialFamily`, but the type can be changed with the family
    type option. If the base type is used, the pseudo potential files in the archive *have* to have filenames that
    strictly follow the format `ELEMENT.EXTENSION`, because otherwise the element cannot be determined automatically.
    """
    from .utils import attempt, create_family_from_archive

    # The `archive` is now either a `http.client.HTTPResponse` or a normal filelike object, so we get the original file
    # name in a different way.
    try:
        suffix = os.path.basename(archive.url)
    except AttributeError:
        suffix = os.path.basename(archive.name)

    # Write the content of the archive to a temporary file, because `create_family_from_archive` does currently not
    # accept filelike objects because the underlying `shutil.unpack_archive` does not. Likewise, `unpack_archive` will
    # attempt to deduce the archive format from the filename extension, so it is important we maintain the original
    # filename. Of course if this fails, users can specify the archive format explicitly wiht the corresponding option.
    with tempfile.NamedTemporaryFile(mode='w+b', suffix=suffix) as handle:
        shutil.copyfileobj(archive, handle)
        handle.flush()

        with attempt('unpacking archive and parsing pseudos... ', include_traceback=traceback):
            family = create_family_from_archive(family_type, label, pathlib.Path(handle.name), fmt=archive_format)

    family.description = description
    echo.echo_success(f'installed `{label}` containing {family.count()} pseudo potentials')
Exemple #12
0
def import_upf(filename):
    """
    Import upf data object
    """
    from aiida.orm.data.upf import UpfData
    node, _ = UpfData.get_or_create(filename)
    echo.echo_success("Imported: {}".format(node))
Exemple #13
0
def computer_setup(ctx, non_interactive, **kwargs):
    """Create a new computer."""
    from aiida.orm.utils.builders.computer import ComputerBuilder

    if kwargs['label'] in get_computer_names():
        echo.echo_critical(
            'A computer called {c} already exists. '
            'Use "verdi computer duplicate {c}" to set up a new '
            'computer starting from the settings of {c}.'.format(
                c=kwargs['label']))

    kwargs['transport'] = kwargs['transport'].name
    kwargs['scheduler'] = kwargs['scheduler'].name

    computer_builder = ComputerBuilder(**kwargs)
    try:
        computer = computer_builder.new()
    except (ComputerBuilder.ComputerValidationError, ValidationError) as e:
        echo.echo_critical(f'{type(e).__name__}: {e}')

    try:
        computer.store()
    except ValidationError as err:
        echo.echo_critical(f'unable to store the computer: {err}. Exiting...')
    else:
        echo.echo_success(f'Computer<{computer.pk}> {computer.label} created')

    echo.echo_info(
        'Note: before the computer can be used, it has to be configured with the command:'
    )
    echo.echo_info(
        f'  verdi computer configure {computer.transport_type} {computer.label}'
    )
Exemple #14
0
def verdi_config(ctx, option, value, globally, unset):
    """Configure profile-specific or global AiiDA options."""
    config = ctx.obj.config
    profile = ctx.obj.profile

    if option.global_only:
        globally = True

    # Define the string that determines the scope: for specific profile or globally
    scope = profile.name if (not globally and profile) else None
    scope_text = 'for {}'.format(profile.name) if (not globally
                                                   and profile) else 'globally'

    # Unset the specified option
    if unset:
        config.unset_option(option.name, scope=scope)
        config.store()
        echo.echo_success('{} unset {}'.format(option.name, scope_text))

    # Get the specified option
    elif value is None:
        option_value = config.get_option(option.name,
                                         scope=scope,
                                         default=False)
        if option_value:
            echo.echo('{}'.format(option_value))

    # Set the specified option
    else:
        config.set_option(option.name, value, scope=scope)
        config.store()
        echo.echo_success('{} set to {} {}'.format(option.name, value,
                                                   scope_text))
Exemple #15
0
def calculation_kill(calculations, force):
    """Kill one or multiple running calculations."""
    from aiida import work

    if not force:
        warning = 'Are you sure you want to kill {} calculations?'.format(
            len(calculations))
        click.confirm(warning, abort=True)

    with work.new_control_panel() as control_panel:
        futures = []
        for calculation in calculations:
            try:
                future = control_panel.kill_process(calculation)
                futures.append((calculation, future))
            except (work.RemoteException, work.DeliveryFailed) as e:
                echo.echo_error('Calculation<{}> killing failed {}'.format(
                    calculation, e.message))

        for future in futures:
            result = control_panel._communicator. await (future[1])
            if result:
                echo.echo_success('Calculation<{}> successfully killed'.format(
                    future[0]))
            else:
                echo.echo_error('Calculation<{}> killing failed {}'.format(
                    future[0], result))
def computer_duplicate(ctx, computer, non_interactive, **kwargs):
    """Duplicate a computer allowing to change some parameters."""
    from aiida import orm
    from aiida.orm.utils.builders.computer import ComputerBuilder

    if kwargs['label'] in get_computer_names():
        echo.echo_critical('A computer called {} already exists'.format(kwargs['label']))

    kwargs['transport'] = kwargs['transport'].name
    kwargs['scheduler'] = kwargs['scheduler'].name

    computer_builder = ctx.computer_builder
    for key, value in kwargs.items():
        if value is not None:
            setattr(computer_builder, key, value)

    try:
        computer = computer_builder.new()
    except (ComputerBuilder.ComputerValidationError, ValidationError) as e:
        echo.echo_critical('{}: {}'.format(type(e).__name__, e))
    else:
        echo.echo_success('stored computer {}<{}>'.format(computer.label, computer.pk))

    try:
        computer.store()
    except ValidationError as err:
        echo.echo_critical('unable to store the computer: {}. Exiting...'.format(err))
    else:
        echo.echo_success('Computer<{}> {} created'.format(computer.pk, computer.label))

    is_configured = computer.is_user_configured(orm.User.objects.get_default())

    if not is_configured:
        echo.echo_info('Note: before the computer can be used, it has to be configured with the command:')
        echo.echo_info('  verdi computer configure {} {}'.format(computer.transport_type, computer.label))
Exemple #17
0
def detect_invalid_nodes():
    """Scan the database for invalid nodes."""
    from tabulate import tabulate

    from aiida.manage.database.integrity.sql.nodes import INVALID_NODE_SELECT_STATEMENTS
    from aiida.manage.manager import get_manager

    integrity_violated = False

    backend = get_manager().get_backend()

    for check in INVALID_NODE_SELECT_STATEMENTS:

        result = backend.execute_prepared_statement(check.sql,
                                                    check.parameters)

        if result:
            integrity_violated = True
            echo.echo_warning(f'{check.message}:\n')
            echo.echo(tabulate(result, headers=check.headers))

    if not integrity_violated:
        echo.echo_success('no integrity violations detected')
    else:
        echo.echo_critical('one or more integrity violations detected')
def code_duplicate(ctx, code, non_interactive, **kwargs):
    """Duplicate a code allowing to change some parameters."""
    from aiida.common.exceptions import ValidationError
    from aiida.orm.utils.builders.code import CodeBuilder

    if kwargs.pop('on_computer'):
        kwargs['code_type'] = CodeBuilder.CodeType.ON_COMPUTER
    else:
        kwargs['code_type'] = CodeBuilder.CodeType.STORE_AND_UPLOAD

    if kwargs.pop('hide_original'):
        code.hide()

    code_builder = ctx.code_builder
    for key, value in kwargs.items():
        if value is not None:
            setattr(code_builder, key, value)
    new_code = code_builder.new()

    try:
        new_code.store()
        new_code.reveal()
    except ValidationError as exception:
        echo.echo_critical('Unable to store the Code: {}'.format(exception))

    echo.echo_success('Code<{}> {} created'.format(new_code.pk, new_code.full_label))
Exemple #19
0
def rehash(nodes, entry_point):
    """Recompute the hash for nodes in the database

    The set of nodes that will be rehashed can be filtered by their identifier and/or based on their class.
    """
    from aiida.orm.querybuilder import QueryBuilder

    if nodes:
        to_hash = [(node,) for node in nodes if isinstance(node, entry_point)]
    else:
        builder = QueryBuilder()
        builder.append(entry_point, tag='node')
        to_hash = builder.all()

    if not to_hash:
        echo.echo_critical('no matching nodes found')

    count = 0

    for i, (node,) in enumerate(to_hash):

        if i % 100 == 0:
            echo.echo('.', nl=False)

        node.rehash()
        count += 1

    echo.echo('')
    echo.echo_success('{} nodes re-hashed'.format(count))
Exemple #20
0
def _gather_imports(archives, webpages) -> List[Tuple[str, bool]]:
    """Gather archives to import and sort into local files and URLs.

    :returns: list of (archive path, whether it is web based)

    """
    from aiida.tools.importexport.common.utils import get_valid_import_links

    final_archives = []

    # Build list of archives to be imported
    for archive in archives:
        if archive.startswith('http://') or archive.startswith('https://'):
            final_archives.append((archive, True))
        else:
            final_archives.append((archive, False))

    # Discover and retrieve *.aiida files at URL(s)
    if webpages is not None:
        for webpage in webpages:
            try:
                echo.echo_info(f'retrieving archive URLS from {webpage}')
                urls = get_valid_import_links(webpage)
            except Exception as error:
                echo.echo_critical(
                    f'an exception occurred while trying to discover archives at URL {webpage}:\n{error}'
                )
            else:
                echo.echo_success(f'{len(urls)} archive URLs discovered and added')
                final_archives.extend([(u, True) for u in urls])

    return final_archives
Exemple #21
0
def detect_duplicate_uuid(table, apply_patch):
    """Detect and fix entities with duplicate UUIDs.

    Before aiida-core v1.0.0, there was no uniqueness constraint on the UUID column of the node table in the database
    and a few other tables as well. This made it possible to store multiple entities with identical UUIDs in the same
    table without the database complaining. This bug was fixed in aiida-core=1.0.0 by putting an explicit uniqueness
    constraint on UUIDs on the database level. However, this would leave databases created before this patch with
    duplicate UUIDs in an inconsistent state. This command will run an analysis to detect duplicate UUIDs in a given
    table and solve it by generating new UUIDs. Note that it will not delete or merge any rows.
    """
    from aiida.manage.database.integrity.duplicate_uuid import deduplicate_uuids
    from aiida.manage.manager import get_manager

    manager = get_manager()
    manager._load_backend(schema_check=False)  # pylint: disable=protected-access

    try:
        messages = deduplicate_uuids(table=table, dry_run=not apply_patch)
    except Exception as exception:  # pylint: disable=broad-except
        echo.echo_critical('integrity check failed: {}'.format(str(exception)))
    else:
        for message in messages:
            echo.echo_info(message)

        if apply_patch:
            echo.echo_success('integrity patch completed')
        else:
            echo.echo_success('dry-run of integrity patch completed')
Exemple #22
0
def cmd_install_basis_set(archive, label, description, archive_format, basis_set_type, basis_type, traceback):  # pylint: disable=too-many-arguments
    """Install a standard basis set from an ARCHIVE."""
    if isinstance(archive, pathlib.Path) and archive.is_dir():
        with attempt(f'creating a basis_set from directory `{archive}`...', include_traceback=traceback):
            basis_set = basis_set_type.create_from_folder(archive, label, basis_type=basis_type)
    elif isinstance(archive, pathlib.Path) and archive.is_file():
        with attempt('unpacking archive and parsing basis... ', include_traceback=traceback):
            basis_set = create_basis_set_from_archive(
                basis_set_type, label, archive, fmt=archive_format, basis_type=basis_type
            )
    else:
        # At this point, we can assume that it is not a valid filepath on disk, but rather a URL and the ``archive``
        # variable will contain the result objects from the ``requests`` library. The validation of the URL will already
        # have been done by the ``PathOrUrl`` parameter type, so the URL is reachable. The content of the URL must be
        # copied to a local temporary file because `create_basis_set_from_archive` does currently not accept filelike
        # objects, because in turn the underlying `shutil.unpack_archive` does not. In addition, `unpack_archive` will
        # attempt to deduce the archive format from the filename extension, so it is important we maintain the original
        # filename. Of course if this fails, users can specify the archive format explicitly with the corresponding
        # option. We get the filename by converting the URL to a ``Path`` object and taking the filename, using that as
        # a suffix for the temporary file that is generated on disk to copy the content to.
        suffix = pathlib.Path(archive.url).name
        with tempfile.NamedTemporaryFile(mode='w+b', suffix=suffix) as handle:
            handle.write(archive.content)
            handle.flush()

            with attempt('unpacking archive and parsing basis... ', include_traceback=traceback):
                basis_set = create_basis_set_from_archive(
                    basis_set_type, label, pathlib.Path(handle.name), fmt=archive_format, basis_type=basis_type
                )

    basis_set.description = description
    echo.echo_success(f'installed `{label}` containing {basis_set.count()} bases')
Exemple #23
0
def _try_import(migration_performed, file_to_import, archive, group, migration, non_interactive, **kwargs):
    """Utility function for `verdi import` to try to import archive

    :param migration_performed: Boolean to determine the exception message to throw for
        `~aiida.tools.importexport.common.exceptions.IncompatibleArchiveVersionError`
    :param file_to_import: Absolute path, including filename, of file to be migrated.
    :param archive: Filename of archive to be migrated, and later attempted imported.
    :param group: AiiDA Group into which the import will be associated.
    :param migration: Whether or not to force migration of archive, if needed.
    :param non_interactive: Whether or not the user should be asked for input for any reason.
    :param kwargs: Key-word-arguments that _must_ contain:
        * `'extras_mode_existing'`: `import_data`'s `'extras_mode_existing'` keyword, determining import rules for
        Extras.
        * `'extras_mode_new'`: `import_data`'s `'extras_mode_new'` keyword, determining import rules for Extras.
        * `'comment_mode'`: `import_data`'s `'comment_mode'` keyword, determining import rules for Comments.
    """
    from aiida.tools.importexport import import_data, IncompatibleArchiveVersionError

    # Checks
    expected_keys = ['extras_mode_existing', 'extras_mode_new', 'comment_mode']
    for key in expected_keys:
        if key not in kwargs:
            raise ValueError("{} needed for utility function '{}' to use in 'import_data'".format(key, '_try_import'))

    # Initialization
    migrate_archive = False

    try:
        import_data(file_to_import, group, **kwargs)
    except IncompatibleArchiveVersionError as exception:
        if migration_performed:
            # Migration has been performed, something is still wrong
            crit_message = '{} has been migrated, but it still cannot be imported.\n{}'.format(archive, exception)
            echo.echo_critical(crit_message)
        else:
            # Migration has not yet been tried.
            if migration:
                # Confirm migration
                echo.echo_warning(str(exception).splitlines()[0])
                if non_interactive:
                    migrate_archive = True
                else:
                    migrate_archive = click.confirm(
                        'Do you want to try and migrate {} to the newest export file version?\n'
                        'Note: This will not change your current file.'.format(archive),
                        default=True,
                        abort=True
                    )
            else:
                # Abort
                echo.echo_critical(str(exception))
    except Exception:
        echo.echo_error('an exception occurred while importing the archive {}'.format(archive))
        echo.echo(traceback.format_exc())
        if not non_interactive:
            click.confirm('do you want to continue?', abort=True)
    else:
        echo.echo_success('imported archive {}'.format(archive))

    return migrate_archive
Exemple #24
0
def node_label(nodes, label, raw, force):
    """View or set the label of one or more nodes."""
    table = []

    if label is None:
        for node in nodes:

            if raw:
                table.append([node.label])
            else:
                table.append([node.pk, node.label])

        if raw:
            echo.echo(tabulate.tabulate(table, tablefmt='plain'))
        else:
            echo.echo(tabulate.tabulate(table, headers=['ID', 'Label']))

    else:
        if not force:
            warning = 'Are you sure you want to set the label for {} nodes?'.format(len(nodes))
            click.confirm(warning, abort=True)

        for node in nodes:
            node.label = label

        echo.echo_success("Set label '{}' for {} nodes".format(label, len(nodes)))
Exemple #25
0
def setup_code(non_interactive, **kwargs):
    """Setup a new code."""
    from aiida.common.exceptions import ValidationError
    from aiida.orm.utils.builders.code import CodeBuilder

    if not non_interactive:
        try:
            pre, post = ensure_scripts(kwargs.pop('prepend_text', ''),
                                       kwargs.pop('append_text', ''), kwargs)
        except InputValidationError as exception:
            raise click.BadParameter(
                'invalid prepend and or append text: {}'.format(exception))

        kwargs['prepend_text'] = pre
        kwargs['append_text'] = post

    if kwargs.pop('on_computer'):
        kwargs['code_type'] = CodeBuilder.CodeType.ON_COMPUTER
    else:
        kwargs['code_type'] = CodeBuilder.CodeType.STORE_AND_UPLOAD

    code_builder = CodeBuilder(**kwargs)
    code = code_builder.new()

    try:
        code.store()
        code.reveal()
    except ValidationError as exception:
        echo.echo_critical('Unable to store the Code: {}'.format(exception))

    echo.echo_success('Code<{}> {} created'.format(code.pk, code.full_label))
Exemple #26
0
def cmd_import(filename, dry_run, fleurinp):
    """
    Import a `StructureData` from a Fleur input file.

    FILENAME is the name/path of the inp.xml file to use.

    If you want to import a structure from any file type you can use
    'verdi data structure import -ase <filename>' instead.
    """
    from aiida_fleur.data.fleurinp import FleurinpData

    if not filename.endswith('.xml'):
        echo.echo_critical(
            'Error: Currently, only StructureData from a inp.xml file can be extracted.'
        )
    fleurinpd = FleurinpData(files=[filename])
    if not fleurinp or dry_run:
        structure = fleurinpd.get_structuredata_ncf()
    else:
        structure = fleurinpd.get_structuredata()
    formula = structure.get_formula()

    if dry_run:
        echo.echo_success(f'parsed structure with formula {formula}')
    else:
        structure.store()
        echo.echo_success(
            f'parsed and stored StructureData<{structure.pk}> with formula {formula}, also stored FleurinpData<{fleurinpd.pk}>'
        )
Exemple #27
0
def create(output_file, codes, computers, groups, nodes, archive_format, force,
           input_calc_forward, input_work_forward, create_backward,
           return_backward, call_calc_backward, call_work_backward,
           include_comments, include_logs):
    """
    Export subsets of the provenance graph to file for sharing.

    Besides Nodes of the provenance graph, you can export Groups, Codes, Computers, Comments and Logs.

    By default, the export file will include not only the entities explicitly provided via the command line but also
    their provenance, according to the rules outlined in the documentation.
    You can modify some of those rules using options of this command.
    """
    from aiida.tools.importexport import export, export_zip

    entities = []

    if codes:
        entities.extend(codes)

    if computers:
        entities.extend(computers)

    if groups:
        entities.extend(groups)

    if nodes:
        entities.extend(nodes)

    kwargs = {
        'input_calc_forward': input_calc_forward,
        'input_work_forward': input_work_forward,
        'create_backward': create_backward,
        'return_backward': return_backward,
        'call_calc_backward': call_calc_backward,
        'call_work_backward': call_work_backward,
        'include_comments': include_comments,
        'include_logs': include_logs,
        'overwrite': force
    }

    if archive_format == 'zip':
        export_function = export_zip
        kwargs.update({'use_compression': True})
    elif archive_format == 'zip-uncompressed':
        export_function = export_zip
        kwargs.update({'use_compression': False})
    elif archive_format == 'tar.gz':
        export_function = export

    try:
        export_function(entities, outfile=output_file, **kwargs)

    except IOError as exception:
        echo.echo_critical(
            'failed to write the export archive file: {}'.format(exception))
    else:
        echo.echo_success(
            'wrote the export archive file to {}'.format(output_file))
def psf_import(filename):
    """
    Import a PSF pseudopotential from a file.
    """
    from aiida_siesta.data.psf import PsfData

    node, _ = PsfData.get_or_create(filename)
    echo.echo_success('Imported: {}'.format(node))
Exemple #29
0
def upf_import(filename):
    """
    Import a UPF pseudopotential from a file.
    """
    from aiida.orm import UpfData

    node, _ = UpfData.get_or_create(filename)
    echo.echo_success('Imported: {}'.format(node))
Exemple #30
0
def group_relabel(group, label):
    """Change the label of a group."""
    try:
        group.label = label
    except UniquenessError as exception:
        echo.echo_critical(f'Error: {exception}.')
    else:
        echo.echo_success(f'Label changed to {label}')