def inspect(archive, version, data, meta_data): """Inspect contents of an exported archive without importing it. By default a summary of the archive contents will be printed. The various options can be used to change exactly what information is displayed. """ from aiida.tools.importexport import Archive, CorruptArchive with Archive(archive) as archive_object: try: if version: echo.echo(archive_object.version_format) elif data: echo.echo_dictionary(archive_object.data) elif meta_data: echo.echo_dictionary(archive_object.meta_data) else: info = archive_object.get_info() data = sorted([(k.capitalize(), v) for k, v in info.items()]) data.extend( sorted([(k.capitalize(), v) for k, v in archive_object.get_data_statistics().items()])) echo.echo(tabulate.tabulate(data)) except CorruptArchive as exception: echo.echo_critical('corrupt archive: {}'.format(exception))
def echo_node_dict(nodes, keys, fmt, identifier, raw, use_attrs=True): """Show the attributes or extras of one or more nodes.""" all_nodes = [] for node in nodes: if identifier == 'pk': id_name = 'PK' id_value = node.pk else: id_name = 'UUID' id_value = node.uuid if use_attrs: node_dict = node.attributes dict_name = 'attributes' else: node_dict = node.extras dict_name = 'extras' if keys is not None: node_dict = {k: v for k, v in node_dict.items() if k in keys} if raw: all_nodes.append({id_name: id_value, dict_name: node_dict}) else: echo.echo('{}: {}'.format(id_name, id_value), bold=True) echo.echo_dictionary(node_dict, fmt=fmt) if raw: echo.echo_dictionary(all_nodes, fmt=fmt)
def workchain_inputdict(process, info, label, show, keys, fmt): """Print data from Dict nodes input into any fleur process.""" from aiida.orm import Dict returned_dicts_info = [] returned_dicts = [] try: results = process.get_incoming().all() except ValueError as exception: echo.echo_critical(str(exception)) for result in results: if isinstance(result.node, orm.Dict): if label is not None: if label == result.link_label: returned_dicts.append(result.node.get_dict()) returned_dicts_info.append(result) else: returned_dicts.append(result.node.get_dict()) returned_dicts_info.append(result) for i, re_dict in enumerate(returned_dicts): if keys is not None: try: result = {k: re_dict[k] for k in keys} except KeyError as exc: echo.echo_critical("key '{}' was not found in the results dictionary".format(exc.args[0])) else: result = re_dict if info: echo.echo('# Info: {} {} dict:'.format(returned_dicts_info[i].link_label, returned_dicts_info[i].node)) if show: echo.echo_dictionary(result, fmt=fmt)
def array_show(data, fmt): """Visualize ArrayData objects.""" from aiida.cmdline.utils.echo import echo_dictionary for node in data: the_dict = {} for arrayname in node.get_arraynames(): the_dict[arrayname] = node.get_array(arrayname).tolist() echo_dictionary(the_dict, fmt)
def show(nodes): """ Show contents of ParameterData nodes. """ from aiida.orm.data.parameter import ParameterData from aiida.cmdline.utils.echo import echo_dictionary for node in nodes: if not isinstance(node, ParameterData): echo.echo_error("Node {} is of class {} instead of {}".format( node, type(node), ParameterData)) continue the_dict = node.get_dict() echo_dictionary(the_dict, 'json+date')
def show(nodes): """ Visualize array object """ from aiida.orm.data.array import ArrayData from aiida.cmdline.utils.echo import echo_dictionary for node in nodes: if not isinstance(node, ArrayData): echo.echo_critical("Node {} is of class {} instead of" " {}".format(node, type(node), ArrayData)) the_dict = {} for arrayname in node.arraynames(): the_dict[arrayname] = node.get_array(arrayname).tolist() echo_dictionary(the_dict, 'json+date')
def calculation_res(calculation, fmt, keys): """Print data from the result output node of a calculation.""" from aiida.cmdline.utils.echo import echo_dictionary results = calculation.res._get_dict() if keys is not None: try: result = {k: results[k] for k in keys} except KeyError as e: echo.echo_critical( "key '{}' was not found in the .res dictionary".format( e.message)) else: result = results echo_dictionary(result, fmt=fmt)
def calcjob_res(calcjob, fmt, keys): """Print data from the result output Dict node of a calcjob.""" from aiida.cmdline.utils.echo import echo_dictionary try: results = calcjob.res.get_results() except ValueError as exception: echo.echo_critical(str(exception)) if keys is not None: try: result = {k: results[k] for k in keys} except KeyError as exc: echo.echo_critical(f"key '{exc.args[0]}' was not found in the results dictionary") else: result = results echo_dictionary(result, fmt=fmt)
def inspect(archive, version, data, meta_data): """Inspect contents of an exported archive without importing it. By default a summary of the archive contents will be printed. The various options can be used to change exactly what information is displayed. .. deprecated:: 1.5.0 Support for the --data flag """ import dataclasses from aiida.tools.importexport import CorruptArchive, detect_archive_type, get_reader reader_cls = get_reader(detect_archive_type(archive)) with reader_cls(archive) as reader: try: if version: echo.echo(reader.export_version) elif data: # data is an internal implementation detail echo.echo_deprecated( '--data is deprecated and will be removed in v2.0.0') echo.echo_dictionary(reader._get_data()) # pylint: disable=protected-access elif meta_data: echo.echo_dictionary(dataclasses.asdict(reader.metadata)) else: statistics = { 'Version aiida': reader.metadata.aiida_version, 'Version format': reader.metadata.export_version, 'Computers': reader.entity_count('Computer'), 'Groups': reader.entity_count('Group'), 'Links': reader.link_count, 'Nodes': reader.entity_count('Node'), 'Users': reader.entity_count('User'), } if reader.metadata.conversion_info: statistics['Conversion info'] = '\n'.join( reader.metadata.conversion_info) echo.echo(tabulate.tabulate(statistics.items())) except CorruptArchive as exception: echo.echo_critical(f'corrupt archive: {exception}')
def database_summary(verbose): """Summarise the entities in the database.""" from aiida.orm import QueryBuilder, Node, Group, Computer, Comment, Log, User data = {} # User query_user = QueryBuilder().append(User, project=['email']) data['Users'] = {'count': query_user.count()} if verbose: data['Users']['emails'] = query_user.distinct().all(flat=True) # Computer query_comp = QueryBuilder().append(Computer, project=['name']) data['Computers'] = {'count': query_comp.count()} if verbose: data['Computers']['names'] = query_comp.distinct().all(flat=True) # Node count = QueryBuilder().append(Node).count() data['Nodes'] = {'count': count} if verbose: node_types = QueryBuilder().append(Node, project=['node_type']).distinct().all(flat=True) data['Nodes']['node_types'] = node_types process_types = QueryBuilder().append(Node, project=['process_type']).distinct().all(flat=True) data['Nodes']['process_types'] = [p for p in process_types if p] # Group query_group = QueryBuilder().append(Group, project=['type_string']) data['Groups'] = {'count': query_group.count()} if verbose: data['Groups']['type_strings'] = query_group.distinct().all(flat=True) # Comment count = QueryBuilder().append(Comment).count() data['Comments'] = {'count': count} # Log count = QueryBuilder().append(Log).count() data['Logs'] = {'count': count} echo.echo_dictionary(data, sort_keys=False, fmt='yaml')
def verdi_config_show(ctx, option): """Show details of an AiiDA option for the current profile.""" from aiida.manage.configuration import Config, Profile from aiida.manage.configuration.options import NO_DEFAULT config: Config = ctx.obj.config profile: Profile = ctx.obj.profile dct = { 'schema': option.schema, 'values': { 'default': '<NOTSET>' if option.default is NO_DEFAULT else option.default, 'global': config.options.get(option.name, '<NOTSET>'), } } if not profile: echo.echo_warning('no profiles configured: run `verdi setup` to create one') else: dct['values']['profile'] = profile.options.get(option.name, '<NOTSET>') echo.echo_dictionary(dct, fmt='yaml', sort_keys=False)
def cmd_param_import(filename, dry_run, fleurinp, show): """ Extract FLAPW parameters from a Fleur input file and store as Dict in the db. FILENAME is the name/path of the inp.xml file to use. """ from aiida_fleur.data.fleurinp import FleurinpData if not filename.endswith('.xml'): echo.echo_critical('Error: Currently, we can only extract information from an inp.xml file.') fleurinpd = FleurinpData(files=[filename]) if not fleurinp or dry_run: parameters = fleurinpd.get_parameterdata_ncf() else: parameters = fleurinpd.get_parameterdata(fleurinpd) if dry_run: echo.echo_success('parsed FLAPW parameters') else: parameters.store() echo.echo_success(f'parsed and stored FLAPW parameters<{parameters.pk}> <{parameters.uuid}>') if show: echo.echo_dictionary(parameters.get_dict())
def dictionary_show(data, fmt): """Show contents of Dict nodes.""" from aiida.cmdline.utils.echo import echo_dictionary for node in data: echo_dictionary(node.get_dict(), fmt)