def convert(self, value, param, ctx): """Attempt to interpret the value as a file first and if that fails try to load as a node.""" from aiida.orm import StructureData, QueryBuilder try: filepath = pathlib.Path( __file__ ).parent.parent / 'common' / 'data' / DEFAULT_STRUCTURES_MAPPING[ value] except KeyError: try: return types.DataParamType( sub_classes=('aiida.data:structure', )).convert( value, param, ctx) except click.BadParameter: filepath = value try: import ase.io except ImportError as exception: raise click.BadParameter( f'failed to load a structure with identifier `{value}`.\n' 'Cannot parse from file because `ase` is not installed.' ) from exception try: filepath = click.Path(exists=True, dir_okay=False, resolve_path=True).convert( filepath, param, ctx) except click.BadParameter as exception: raise click.BadParameter( f'failed to load a structure with identifier `{value}` and it can also not be resolved as a file.' ) from exception try: structure = StructureData(ase=ase.io.read(filepath)) except Exception as exception: # pylint: disable=broad-except raise click.BadParameter( f'file `{value}` could not be parsed into a `StructureData`: {exception}' ) from exception duplicate = QueryBuilder().append(StructureData, filters={ 'extras._aiida_hash': structure._get_hash() }).first() # pylint: disable=protected-access if duplicate: return duplicate[0] return structure
def convert(self, value, param, ctx): is_path = False # Alternative one could check if int or uuid # aiida allows also for shorten uuids from aiida.orm import StructureData, QueryBuilder try: structure = types.DataParamType( sub_classes=('aiida.data:structure', )).convert( value, param, ctx) except (NotExistent, click.exceptions.BadParameter) as er: echo.echo(f'Tried to load node, could not fine one for {value}. ' 'I will further check if it is a filepath.') is_path = True if is_path: # If it is a path to a file try to convert the structure pathtype = click.Path(exists=True, dir_okay=False, resolve_path=True) filename = pathtype.convert(value, param, ctx) try: import ase.io except ImportError: echo.echo_critical( 'You have not installed the package ase. \nYou can install it with: pip install ase' ) try: asecell = ase.io.read(filename) structure = StructureData(ase=asecell) except ValueError as err: echo.echo_critical(str(err)) # do not store structure, since this option is for calculation and workflow # input, which will store the structure anyway. # do not store again if structure is already there. duplicate = QueryBuilder().append(StructureData, filters={ 'extras._aiida_hash': structure._get_hash() }).first() # pylint: disable=protected-access if duplicate: return duplicate[0] return structure
from aiida.cmdline.params import types from aiida.cmdline.params.arguments.overridable import OverridableArgument CALCULATION = OverridableArgument('calculation', type=types.CalculationParamType()) CALCULATIONS = OverridableArgument('calculations', nargs=-1, type=types.CalculationParamType()) CODE = OverridableArgument('code', type=types.CodeParamType()) CODES = OverridableArgument('codes', nargs=-1, type=types.CodeParamType()) COMPUTER = OverridableArgument('computer', type=types.ComputerParamType()) COMPUTERS = OverridableArgument('computers', nargs=-1, type=types.ComputerParamType()) DATUM = OverridableArgument('datum', type=types.DataParamType()) DATA = OverridableArgument('data', nargs=-1, type=types.DataParamType()) GROUP = OverridableArgument('group', type=types.GroupParamType()) GROUPS = OverridableArgument('groups', nargs=-1, type=types.GroupParamType()) NODE = OverridableArgument('node', type=types.NodeParamType()) NODES = OverridableArgument('nodes', nargs=-1, type=types.NodeParamType()) PROCESS = OverridableArgument('process', type=types.CalculationParamType()) PROCESSES = OverridableArgument('processes', nargs=-1, type=types.CalculationParamType())
"""Command line scripts to launch a `MatdynCalculation` for testing and demonstration purposes.""" from __future__ import absolute_import from aiida.cmdline.params import options, types from aiida.cmdline.utils import decorators from ..utils import launch from ..utils import options as options_qe from . import cmd_launch @cmd_launch.command('matdyn') @options.CODE(required=True, type=types.CodeParamType(entry_point='quantumespresso.matdyn')) @options.DATUM( required=True, type=types.DataParamType(sub_classes=('aiida.data:quantumespresso.force_constants',)), help='A ForceConstantsData node produced by a `Q2rCalculation`' ) @options_qe.KPOINTS_MESH(default=[1, 1, 1]) @options_qe.MAX_NUM_MACHINES() @options_qe.MAX_WALLCLOCK_SECONDS() @options_qe.WITH_MPI() @options_qe.DAEMON() @decorators.with_dbenv() def launch_calculation(code, datum, kpoints_mesh, max_num_machines, max_wallclock_seconds, with_mpi, daemon): """Run a MatdynCalculation.""" from aiida.plugins import CalculationFactory from aiida_quantumespresso.utils.resources import get_default_options inputs = { 'code': code,
if isinstance(value, list): entry[i] = ','.join(value) for i in range(len(entry), len(LIST_PROJECT_HEADERS)): entry.append(None) counter += 1 struct_list_data.extend(entry_list) if raw: echo.echo(tabulate(struct_list_data, tablefmt='plain')) else: echo.echo(tabulate(struct_list_data, headers='firstrow')) echo.echo('\nTotal results: {}\n'.format(counter)) @structure.command('show') @arguments.DATA( type=types.DataParamType(sub_classes=('aiida.data:structure', ))) @options.VISUALIZATION_FORMAT(type=click.Choice(VISUALIZATION_FORMATS), default='ase') @decorators.with_dbenv() def structure_show(data, fmt): """Visualize StructureData objects.""" try: show_function = getattr(cmd_show, '_show_{}'.format(fmt)) except AttributeError: echo.echo_critical( 'visualization format {} is not supported'.format(fmt)) show_function(fmt, data) @structure.command('export')
from click_spinner import spinner as cli_spinner from jsonextended import edict import tabulate from aiida_crystal17.cmndline import options @verdi.group("crystal17.basis") def basisset(): """Commandline interface for working with Crystal Basis Set Data.""" @basisset.command() @click.argument( "node", type=types.DataParamType(sub_classes=("aiida.data:crystal17.basisset", ))) @click.option("--content", "-c", is_flag=True, help="include full basis content") @decorators.with_dbenv() def show(node, content): """Show the contents of a basis set node.""" edict.pprint(node.metadata, depth=None, print_func=click.echo) if content: click.echo("---") click.echo(node.content) def try_grab_description(ctx, param, value): """
# Copyright (c), The AiiDA team. All rights reserved. # # This file is part of the AiiDA code. # # # # The code is hosted on GitHub at https://github.com/aiidateam/aiida-core # # For further information on the license, see the LICENSE.txt file # # For further information please visit http://www.aiida.net # ########################################################################### """`verdi data array` command.""" from aiida.cmdline.commands.cmd_data import verdi_data from aiida.cmdline.params import arguments, options, types @verdi_data.group('array') def array(): """Manipulate ArrayData objects (numpy arrays).""" @array.command('show') @arguments.DATA(type=types.DataParamType(sub_classes=('aiida.data:array', ))) @options.DICT_FORMAT() 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)
if isinstance(value, list): entry[i] = ','.join(value) for i in range(len(entry), len(LIST_PROJECT_HEADERS)): entry.append(None) counter += 1 bands_list_data.extend(entry_list) if raw: echo.echo(tabulate(bands_list_data, tablefmt='plain')) else: echo.echo(tabulate(bands_list_data, headers='firstrow')) echo.echo(f'\nTotal results: {counter}\n') @bands.command('show') @arguments.DATA( type=types.DataParamType(sub_classes=('aiida.data:array.bands', ))) @options.VISUALIZATION_FORMAT(type=click.Choice(VISUALIZATION_FORMATS), default='xmgrace') @decorators.with_dbenv() def bands_show(data, fmt): """Visualize BandsData objects.""" try: show_function = getattr(cmd_show, f'_show_{fmt}') except AttributeError: echo.echo_critical(f'visualization format {fmt} is not supported') show_function(fmt, data) @bands.command('export') @arguments.DATUM(
type=types.CodeParamType(), cls=MultipleValueOption, help='One or multiple codes identified by their ID, UUID or label.') COMPUTER = OverridableOption( '-Y', '--computer', 'computer', type=types.ComputerParamType(), help='A single computer identified by its ID, UUID or label.') COMPUTERS = OverridableOption( '-Y', '--computers', 'computers', type=types.ComputerParamType(), cls=MultipleValueOption, help='One or multiple computers identified by their ID, UUID or label.') DATUM = OverridableOption( '-D', '--datum', 'datum', type=types.DataParamType(), help='A single datum identified by its ID, UUID or label.') DATA = OverridableOption( '-D', '--data', 'data', type=types.DataParamType(), cls=MultipleValueOption, help='One or multiple data identified by their ID, UUID or label.') GROUP = OverridableOption( '-G', '--group', 'group', type=types.GroupParamType(), help='A single group identified by its ID, UUID or name.') GROUPS = OverridableOption( '-G', '--groups', 'groups', type=types.GroupParamType(), cls=MultipleValueOption,
# This file is part of the AiiDA code. # # # # The code is hosted on GitHub at https://github.com/aiidateam/aiida-core # # For further information on the license, see the LICENSE.txt file # # For further information please visit http://www.aiida.net # ########################################################################### """`verdi data singlefile` command.""" from aiida.cmdline.commands.cmd_data import verdi_data from aiida.cmdline.params import arguments, types from aiida.cmdline.utils import decorators, echo @verdi_data.group('singlefile') def singlefile(): """Work with SinglefileData nodes.""" @singlefile.command('content') @arguments.DATUM( type=types.DataParamType(sub_classes=('aiida.data:singlefile', ))) @decorators.with_dbenv() def singlefile_content(datum): """Show the content of the file.""" try: echo.echo(datum.get_content()) except (IOError, OSError) as exception: echo.echo_critical( 'could not read the content for SinglefileData<{}>: {}'.format( datum.pk, str(exception)))
# -*- coding: utf-8 -*- """Pre-defined overridable options for commonly used command line interface parameters.""" import click from aiida.cmdline.params import types from aiida.cmdline.params.options import OverridableOption from . import validate STRUCTURE = OverridableOption( '-s', '--structure', type=types.DataParamType(sub_classes=('aiida.data:structure', )), help='StructureData node.') PSEUDO_FAMILY = OverridableOption('-p', '--pseudo-family', 'pseudo_family', type=click.STRING, help='Pseudo potential family name.') KPOINTS_DISTANCE = OverridableOption( '-K', '--kpoints-distance', type=click.FLOAT, default=0.5, show_default=True, help= 'The minimal distance between k-points in reciprocal space in inverse Ångström.' )
help="Title of the publication."), click.option('--author-name', type=click.STRING, default=None, help="Full name of the publication author."), click.option('--author-email', type=click.STRING, default=None, help="E-mail address of the publication author."), click.option('--url', type=click.STRING, default=None, help="URL of the deposition API."), click.option( '--parameters', type=types.DataParamType(sub_classes=('aiida.data:dict', )), help= "Dict to be exported alongside the to be deposited Data node. By default, if " "the node originates from a calculation with single Dict in the output, aforementioned " "Dict is picked automatically. Instead, the option is used in the case the calculation produces " "more than a single instance of Dict."), click.option( '--replace', type=click.INT, default=None, help="ID of the structure to be redeposited (replaced), if any."), click.option( '-m', '--message', type=click.STRING, default=None,
# yapf: disable from __future__ import absolute_import import click from aiida.cmdline.params import options, types from aiida.cmdline.utils import decorators from ..utils import launch, validate from . import cmd_launch @cmd_launch.command('cod-tools') @options.CODE(required=True, help='Code that references a supported cod-tools script.') @click.option( '-N', '--node', 'cif', type=types.DataParamType(sub_classes=('aiida.data:cif',)), required=True, help='CifData node to use as input.') @click.option('-p', '--parameters', type=click.STRING, help='Command line parameters.') @click.option( '-d', '--daemon', is_flag=True, default=False, show_default=True, callback=validate.validate_daemon_dry_run, help='Submit the process to the daemon instead of running it locally.') @options.DRY_RUN(callback=validate.validate_daemon_dry_run) @decorators.with_dbenv() def launch_calculation(code, cif, parameters, daemon, dry_run): """Run any cod-tools calculation for the given ``CifData`` node. The ``-p/--parameters`` option takes a single string with any command line parameters that you want to be passed to the calculation, and by extension the cod-tools script. Example:: aiida-codtools calculation launch cod-tools -X cif-filter -N 95 -p '--use-c-parser --authors "Jane Doe"'
'-S', '--cif-select', required=True, type=types.CodeParamType(entry_point='codtools.cif_select'), help='Code that references the codtools cif_select script.') @click.option( '-r', '--group-cif-raw', required=False, type=types.GroupParamType(), help='Group with the raw CifData nodes to be cleaned.') @click.option( '-c', '--group-cif-clean', required=False, type=types.GroupParamType(), help='Group to which to add the cleaned CifData nodes.') @click.option( '-s', '--group-structure', required=False, type=types.GroupParamType(), help='Group to which to add the final StructureData nodes.') @click.option( '-w', '--group-workchain', required=False, type=types.GroupParamType(), help='Group to which to add the WorkChain nodes.') @click.option( '-N', '--node', type=types.DataParamType(sub_classes=('aiida.data:cif',)), default=None, required=False, help='Specify the explicit CifData node for which to run the clean workchain.') @click.option( '-M', '--max-entries', type=click.INT, default=None, show_default=True, required=False, help='Maximum number of CifData entries to clean.') @click.option( '-f', '--skip-check', is_flag=True, default=False, help='Skip the check whether the CifData node is an input to an already submitted workchain.') @click.option( '-p', '--parse-engine', type=click.Choice(['ase', 'pymatgen']), default='pymatgen', show_default=True, help='Select the parse engine for parsing the structure from the cleaned cif if requested.') @click.option( '-d', '--daemon', is_flag=True, default=False, show_default=True, help='Submit the process to the daemon instead of running it locally.') @decorators.with_dbenv() def launch_cif_clean(cif_filter, cif_select, group_cif_raw, group_cif_clean, group_structure, group_workchain, node,
else: new_entry.append(elm) entry[i] = ','.join(new_entry) for i in range(len(entry), len(LIST_PROJECT_HEADERS)): entry.append(None) counter += 1 cif_list_data.extend(entry_list) if raw: echo.echo(tabulate(cif_list_data, tablefmt='plain')) else: echo.echo(tabulate(cif_list_data, headers='firstrow')) echo.echo('\nTotal results: {}\n'.format(counter)) @cif.command('show') @arguments.DATA(type=types.DataParamType(sub_classes=('aiida.data:cif', ))) @options.VISUALIZATION_FORMAT(type=click.Choice(VISUALIZATION_FORMATS), default='jmol') @decorators.with_dbenv() def cif_show(data, fmt): """Visualize CifData objects.""" try: show_function = getattr(cmd_show, '_show_{}'.format(fmt)) except AttributeError: echo.echo_critical( 'visualization format {} is not supported'.format(fmt)) show_function(fmt, data) @cif.command('content')
from aiida.cmdline.params.options import OverridableOption from .defaults import get_inpgen, get_fleur, get_si_bulk_structure from .types import StructureNodeOrFileParamType STRUCTURE_OR_FILE = OverridableOption( '-s', '--structure', type=StructureNodeOrFileParamType(), help= 'StructureData node, given by pk or uuid or file in any for mat which will be converted.' ) STRUCTURE = OverridableOption( '-s', '--structure', type=types.DataParamType(sub_classes=('aiida.data:structure', )), help='StructureData node, given by pk or uuid.') FULL_PROVENANCE = OverridableOption( '-fp', '--full-provenance', is_flag=True, default=False, show_default=True, help=('Store the full or reduced provenance. Example with the "-as" ' 'also the given file will be stored in the database together with a ' 'calcfunction extracting the structure.')) INPGEN = OverridableOption( '-i', '--inpgen',
if isinstance(value, list): entry[i] = ','.join(value) for i in range(len(entry), len(LIST_PROJECT_HEADERS)): entry.append(None) counter += 1 struct_list_data.extend(entry_list) if raw: echo.echo(tabulate(struct_list_data, tablefmt='plain')) else: echo.echo(tabulate(struct_list_data, headers='firstrow')) echo.echo('\nTotal results: {}\n'.format(counter)) @trajectory.command('show') @arguments.DATA( type=types.DataParamType(sub_classes=('aiida.data:array.trajectory', ))) @options.VISUALIZATION_FORMAT(type=click.Choice(VISUALIZATION_FORMATS), default='jmol') @show_options @decorators.with_dbenv() def trajectory_show(data, fmt): """Visualize a trajectory.""" try: show_function = getattr(cmd_show, '_show_{}'.format(fmt)) except AttributeError: echo.echo_critical( 'visualization format {} is not supported'.format(fmt)) show_function(fmt, data)
# -*- coding: utf-8 -*- ########################################################################### # Copyright (c), The AiiDA team. All rights reserved. # # This file is part of the AiiDA code. # # # # The code is hosted on GitHub at https://github.com/aiidateam/aiida-core # # For further information on the license, see the LICENSE.txt file # # For further information please visit http://www.aiida.net # ########################################################################### """`verdi data dict` command.""" from aiida.cmdline.commands.cmd_data import verdi_data from aiida.cmdline.params import arguments, options, types @verdi_data.group('sirius') def siriusscf(): """Manipulate Dict objects (python dictionaries).""" @siriusscf.command('show') @arguments.DATA( type=types.DataParamType(sub_classes=('aiida.data:sirius.scf', ))) @options.DICT_FORMAT() def siriusscf_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)