예제 #1
0
def schema():
    """view the validation schema"""
    if not is_dbenv_loaded():
        load_dbenv()
    from aiida.orm import DataFactory
    schema = DataFactory('crystal17.structsettings').data_schema
    edict.pprint(schema, depth=None, print_func=click.echo)
예제 #2
0
    def __init__(self, input_plugin, text='Select code:', **kwargs):
        """ Dropdown for Codes for one input plugin.

        :param input_plugin: Input plugin of codes to show
        :type input_plugin: str
        :param text: Text to display before dropdown
        :type text: str
        """

        self.input_plugin = input_plugin
        self.codes = {}

        self.label = ipw.Label(value=text)
        self.dropdown = ipw.Dropdown(options=[], disabled=True)
        self.output = ipw.Output()

        children = [ipw.HBox([self.label, self.dropdown, self.output])]

        super(CodeDropdown, self).__init__(children=children, **kwargs)

        from aiida import load_dbenv, is_dbenv_loaded
        from aiida.backends import settings
        if not is_dbenv_loaded():
            load_dbenv(profile=settings.AIIDADB_PROFILE)
        self.refresh()
예제 #3
0
def parse_data(content, name, date):  # pylint: disable=unused-argument
    if content is None:
        return ''

    content_type, content_string = content.split(',')  # pylint: disable=unused-variable
    decoded = base64.b64decode(content_string)

    fd, path = tempfile.mkstemp()
    try:
        with os.fdopen(fd, 'wb') as tmp:
            # do stuff with temp file
            tmp.write(decoded)

        try:
            from aiida import load_dbenv, is_dbenv_loaded
            if not is_dbenv_loaded():
                load_dbenv()
            from aiida.orm.importexport import import_data
            #from aiida.common import exceptions
            import_data(path)
        except Exception:
            msg = 'an exception occurred while importing the archive {}'.format(
                name)
            msg += traceback.format_exc()
        else:
            msg = 'Success: imported archive {}'.format(name)

    finally:
        os.remove(path)

    print(msg)
    return msg
예제 #4
0
    def aiida(self, line='', local_ns=None):
        """Load AiiDA in ipython (checking if it was already loaded), and
        inserts in the namespace the main AiiDA classes (the same that are
        loaded in ``verdi shell``.

        Usage::

            %aiida [optional parameters]
        
        .. todo:: implement parameters, e.g. for the profile to load.
        """
        import aiida

        from aiida import is_dbenv_loaded, load_dbenv

        self.is_warning = False
        if is_dbenv_loaded():
            self.current_state = "Note! AiiDA DB environment already loaded! I do not reload it again."
            self.is_warning = True
        else:
            load_dbenv()
            self.current_state = "Loaded AiiDA DB environment."

        from aiida.cmdline.commands.shell import Shell
        user_ns = Shell().get_start_namespace()
        for k, v in user_ns.iteritems():
            add_to_ns(local_ns, k, v)

        return self
예제 #5
0
def get_data_aiida(cif_uuid, plot_info):
    """Query the AiiDA database"""
    from aiida import load_dbenv, is_dbenv_loaded
    from aiida.backends import settings
    if not is_dbenv_loaded():
        load_dbenv(profile=settings.AIIDADB_PROFILE)
    from aiida.orm.querybuilder import QueryBuilder
    from aiida.orm.data.parameter import ParameterData
    from aiida.orm.data.cif import CifData

    qb = QueryBuilder()
    qb.append(CifData,
              filters={'uuid': {
                  '==': cif_uuid
              }},
              tag='cifs',
              project='*')
    qb.append(
        ParameterData,
        descendant_of='cifs',
        project='*',
    )

    nresults = qb.count()
    if nresults == 0:
        plot_info.text = "No matching COF found."
        return None
    return qb.one()
예제 #6
0
    def get_start_namespace(self):
        """Load all default and custom modules"""
        from aiida import load_dbenv, is_dbenv_loaded
        from aiida.backends import settings
        if not is_dbenv_loaded():
            load_dbenv(profile=settings.AIIDADB_PROFILE)

        from aiida.common.setup import get_property
        user_ns = {}
        # load default modules
        for app_mod, model_name, alias in default_modules_list:
            user_ns[alias] = getattr(__import__(app_mod, {}, {},
                                                model_name), model_name)

        # load custom modules
        custom_modules_list = [(str(e[0]), str(e[2])) for e in
                               [p.rpartition('.') for p in get_property(
                                   'verdishell.modules', default="").split(
                                   ':')]
                               if e[1] == '.']

        for app_mod, model_name in custom_modules_list:
            try:
                user_ns[model_name] = getattr(
                    __import__(app_mod, {}, {}, model_name), model_name)
            except AttributeError:
                # if the module does not exist, we ignore it
                pass

        return user_ns
예제 #7
0
def get_data_aiida(projections, sliders_dict, quantities, plot_info):
    """Query the AiiDA database"""
    from aiida import load_dbenv, is_dbenv_loaded
    from aiida.backends import settings

    if not is_dbenv_loaded():
        load_dbenv(profile=settings.AIIDADB_PROFILE)
    from aiida.orm.querybuilder import QueryBuilder
    from aiida.orm.data.parameter import ParameterData

    filters = {}

    def add_range_filter(bounds, label):
        # a bit of cheating until this is resolved
        # https://github.com/aiidateam/aiida_core/issues/1389
        # filters['attributes.'+label] = {'>=':bounds[0]}
        filters["attributes." + label] = {
            "and": [{
                ">=": bounds[0]
            }, {
                "<": bounds[1]
            }]
        }

    for k, v in sliders_dict.items():
        # Note: filtering is costly, avoid if possible
        if not v.value == quantities[k]["range"]:
            add_range_filter(v.value, k)

    qb = QueryBuilder()
    qb.append(
        ParameterData,
        filters=filters,
        project=["attributes." + p
                 for p in projections] + ["uuid", "extras.cif_uuid"],
    )

    nresults = qb.count()
    if nresults == 0:
        plot_info.text = "No matching frameworks found."
        return data_empty

    plot_info.text = "{} frameworks found. Plotting...".format(nresults)

    # x,y position
    x, y, clrs, uuids, names, cif_uuids = zip(*qb.all())
    plot_info.text = "{} frameworks queried".format(nresults)
    x = map(float, x)
    y = map(float, y)
    cif_uuids = map(str, cif_uuids)
    uuids = map(str, uuids)

    if projections[2] == "group":
        # clrs = map(lambda clr: bondtypes.index(clr), clrs)
        clrs = map(str, clrs)
    else:
        clrs = map(float, clrs)

    return dict(x=x, y=y, uuid=cif_uuids, color=clrs, name=names)
예제 #8
0
def show(pk, content):
    """show the contents of a basis set"""
    if not is_dbenv_loaded():
        load_dbenv()
    from aiida.orm import load_node

    node = load_node(pk)

    if not isinstance(node, get_data_class('crystal17.basisset')):
        click.echo("The node was not of type 'crystal17.basisset'", err=True)
    else:
        edict.pprint(node.metadata, depth=None, print_func=click.echo)
        if content:
            click.echo("---")
            click.echo(node.content)
예제 #9
0
    def create_profile(self):
        """Not actually create the profile but reuse the test profile"""
        test_profile = os.environ.get('AIIDA_TEST_PROFILE', None)
        if not test_profile:
            return super(ExistingProfileFixtureManager, self).create_profile()

        from aiida import load_dbenv
        load_dbenv(profile=test_profile)
        check_if_tests_can_run()

        # Running on test profile
        self._is_running_on_test_profile = True

        from aiida.backends.djsite.db.testbase import DjangoTests
        self._test_case = DjangoTests()
예제 #10
0
def show(pk, symmetries):
    """show the contents of a StructSettingsData"""
    if not is_dbenv_loaded():
        load_dbenv()
    from aiida.orm import load_node
    from aiida.orm import DataFactory

    node = load_node(pk)

    if not isinstance(node, DataFactory('crystal17.structsettings')):
        click.echo("The node was not of type 'crystal17.structsettings'",
                   err=True)
    elif symmetries:
        edict.pprint(node.data, print_func=click.echo, round_floats=5)
    else:
        edict.pprint(dict(node.iterattrs()), print_func=click.echo)
예제 #11
0
    def __init__(self, text="Upload Structure", node_class=None, **kwargs):
        """ Upload a structure and store it in AiiDA database.

        :param text: Text to display before upload button
        :type text: str
        :param node_class: AiiDA node class for storing the structure.
            Possible values: 'StructureData', 'CifData' or None (let the user decide).
            Note: If your workflows require a specific node class, better fix it here.

        """

        self.file_upload = FileUploadWidget(text)
        self.viewer = nglview.NGLWidget()
        self.btn_store = ipw.Button(description='Store in AiiDA',
                                    disabled=True)
        self.structure_description = ipw.Text(
            placeholder="Description (optional)")

        self.structure_ase = None
        self.structure_node = None
        self.data_format = ipw.RadioButtons(
            options=['StructureData', 'CifData'], description='Data type:')

        if node_class is None:
            store = ipw.HBox(
                [self.btn_store, self.data_format, self.structure_description])
        else:
            self.data_format.value = node_class
            store = ipw.HBox([self.btn_store, self.structure_description])

        children = [self.file_upload, self.viewer, store]

        super(StructureUploadWidget, self).__init__(children=children,
                                                    **kwargs)

        self.file_upload.observe(self._on_file_upload, names='data')
        self.btn_store.on_click(self._on_click_store)

        from aiida import load_dbenv, is_dbenv_loaded
        from aiida.backends import settings
        if not is_dbenv_loaded():
            load_dbenv(profile=settings.AIIDADB_PROFILE)
예제 #12
0
def list():
    """Display all MultiplyParameters nodes"""
    from aiida import is_dbenv_loaded, load_dbenv
    if not is_dbenv_loaded():
        load_dbenv()

    from aiida.orm.querybuilder import QueryBuilder
    from aiida.orm import DataFactory
    MultiplyParameters = DataFactory('template.factors')

    qb = QueryBuilder()
    qb.append(MultiplyParameters)
    results = qb.all()

    vsep = '\t'

    s = ""
    for result in results:
        obj = result[0]
        s += "{}, pk: {}\n".format(str(obj), obj.pk)
    sys.stdout.write(s)
예제 #13
0
def list():  # pylint: disable=redefined-builtin
    """
    Display all KkrstructureData nodes
    """
    from aiida import is_dbenv_loaded, load_dbenv
    if not is_dbenv_loaded():
        load_dbenv()

    from aiida.orm.querybuilder import QueryBuilder
    from aiida.orm import DataFactory
    KKrStructure = DataFactory('kkr.kkrstructure')

    qb = QueryBuilder()
    qb.append(KkrStructure)
    results = qb.all()

    s = ""
    for result in results:
        obj = result[0]
        s += "{}, pk: {}\n".format(str(obj), obj.pk)
    sys.stdout.write(s)
예제 #14
0
def load_dbenv_if_not_loaded():
    from aiida import load_dbenv, is_dbenv_loaded
    if not is_dbenv_loaded():
        load_dbenv()
예제 #15
0
# Copyright (c), The AiiDA-CP2K authors.                                      #
# SPDX-License-Identifier: MIT                                                #
# AiiDA-CP2K is hosted on GitHub at https://github.com/cp2k/aiida-cp2k        #
# For further information on the license, see the LICENSE.txt file.           #
###############################################################################

from __future__ import print_function

import sys
import ase.build
from utils import wait_for_calc

from aiida import load_dbenv, is_dbenv_loaded
from aiida.backends import settings
if not is_dbenv_loaded():
    load_dbenv(profile=settings.AIIDADB_PROFILE)

from aiida.common.example_helpers import test_and_get_code  # noqa
from aiida.orm.data.structure import StructureData  # noqa
from aiida.orm.data.parameter import ParameterData  # noqa
from aiida.orm.data.singlefile import SinglefileData  # noqa

# ==============================================================================
if len(sys.argv) != 2:
    print("Usage: test_dft.py <code_name>")
    sys.exit(1)

codename = sys.argv[1]
code = test_and_get_code(codename, expected_code_type='cp2k')

print("Testing CP2K ENERGY on H2O (DFT)...")
예제 #16
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
This test runs the fleur_convergence workflow for path 1
"""
#TODO: overall tests, should create the nodes they use in the db.
from __future__ import absolute_import
from aiida import load_dbenv, is_dbenv_loaded
if not is_dbenv_loaded():
    load_dbenv(profile='aiida_test')
from aiida.plugins import Code, DataFactory
from aiida.orm import load_node
from aiida_fleur.workflows.scf import FleurScfWorkChain

StructureData = DataFactory('structure')
ParameterData = DataFactory('parameter')
KpointsData = DataFactory('array.kpoints')
#FleurinpData = DataFactory('fleurinp.fleurinp')
FleurinpData = DataFactory('fleur.fleurinp')

###############################
# Set your values here
codename = 'inpgen_iff_0.28@local_iff'  #'inpgen_iff@local_iff'#'inpgen_mac_30_11_2016@local_mac'
#codename2 = 'fleur_iff@local_iff'#'fleur_mac_v0_27@local_mac'
#codename = 'fleur_inpgen_iff003@iff003'#'inpgen_mac_30_11_2016@local_mac'
#codename2 = 'fleur_iff003_v0_27@iff003'#fleur_iff@iff003'#'fleur_mac_v0_27@local_mac'
codename2 = 'fleur_iff_0.28@local_iff'  #'fleur_MPI_iff003_v0_27@iff003'
###############################

code = Code.get_from_string(codename)
code2 = Code.get_from_string(codename2)
예제 #17
0
def setup(profile, only_config, non_interactive=False, **kwargs):
    '''
    setup an aiida profile and aiida user (and the aiida default user).

    :param profile: Profile name
    :param only_config: do not create a new user
    :param non_interactive: do not prompt for configuration values, fail if not all values are given as kwargs.
    :param backend: one of 'django', 'sqlalchemy'
    :param email: valid email address for the user
    :param db_host: hostname for the database
    :param db_port: port to connect to the database
    :param db_user: name of the db user
    :param db_pass: password of the db user
    '''
    from aiida.common.setup import (create_base_dirs, create_configuration,
                                    set_default_profile, DEFAULT_UMASK,
                                    create_config_noninteractive)
    from aiida.backends.profile import BACKEND_SQLA, BACKEND_DJANGO
    from aiida.backends.utils import set_backend_type, get_backend_type
    from aiida.common.exceptions import InvalidOperation

    # ~ cmdline_args = list(args)

    # ~ only_user_config = False
    # ~ try:
    # ~ cmdline_args.remove('--only-config')
    # ~ only_user_config = True
    # ~ except ValueError:
    # ~ # Parameter not provided
    # ~ pass
    only_user_config = only_config

    # ~ if cmdline_args:
    # ~ print >> sys.stderr, "Unknown parameters on the command line: "
    # ~ print >> sys.stderr, ", ".join(cmdline_args)
    # ~ sys.exit(1)

    # create the directories to store the configuration files
    create_base_dirs()
    # gprofile = 'default' if profile is None else profile
    # ~ gprofile = profile if settings_profile.AIIDADB_PROFILE is None \
    # ~ else settings_profile.AIIDADB_PROFILE
    if settings_profile.AIIDADB_PROFILE and profile:
        sys.exit(
            'the profile argument cannot be used if verdi is called with -p option: {} and {}'
            .format(settings_profile.AIIDADB_PROFILE, profile))
    gprofile = settings_profile.AIIDADB_PROFILE or profile
    if gprofile == profile:
        settings_profile.AIIDADB_PROFILE = profile
    if not settings_profile.AIIDADB_PROFILE:
        settings_profile.AIIDADB_PROFILE = 'default'

    # used internally later
    gprofile = settings_profile.AIIDADB_PROFILE

    created_conf = None
    # ask and store the configuration of the DB
    if non_interactive:
        try:
            created_conf = create_config_noninteractive(
                profile=gprofile,
                backend=kwargs['backend'],
                email=kwargs['email'],
                db_host=kwargs['db_host'],
                db_port=kwargs['db_port'],
                db_name=kwargs['db_name'],
                db_user=kwargs['db_user'],
                db_pass=kwargs.get('db_pass', ''),
                repo=kwargs['repo'],
                force_overwrite=kwargs.get('force_overwrite', False))
        except ValueError as e:
            click.echo("Error during configuation: {}".format(e.message),
                       err=True)
            sys.exit(1)
        except KeyError as e:
            sys.exit(
                "--non-interactive requires all values to be given on the commandline! {}"
                .format(e.message),
                err=True)
    else:
        try:
            created_conf = create_configuration(profile=gprofile)
        except ValueError as e:
            print >> sys.stderr, "Error during configuration: {}".format(
                e.message)
            sys.exit(1)

        # set default DB profiles
        set_default_profile('verdi', gprofile, force_rewrite=False)
        set_default_profile('daemon', gprofile, force_rewrite=False)

    if only_user_config:
        print(
            "Only user configuration requested, "
            "skipping the migrate command")
    else:
        print "Executing now a migrate command..."

        backend_choice = created_conf['AIIDADB_BACKEND']
        if backend_choice == BACKEND_DJANGO:
            print("...for Django backend")
            # The correct profile is selected within load_dbenv.
            # Setting os.umask here since sqlite database gets created in
            # this step.
            old_umask = os.umask(DEFAULT_UMASK)

            # This check should be done more properly
            # try:
            #     backend_type = get_backend_type()
            # except KeyError:
            #     backend_type = None
            #
            # if backend_type is not None and backend_type != BACKEND_DJANGO:
            #     raise InvalidOperation("An already existing database found"
            #                            "and a different than the selected"
            #                            "backend was used for its "
            #                            "management.")

            try:
                pass_to_django_manage([execname, 'migrate'], profile=gprofile)
            finally:
                os.umask(old_umask)

            set_backend_type(BACKEND_DJANGO)

        elif backend_choice == BACKEND_SQLA:
            print("...for SQLAlchemy backend")
            from aiida import is_dbenv_loaded, load_dbenv
            if not is_dbenv_loaded():
                load_dbenv()

            from aiida.backends.sqlalchemy.models.base import Base
            from aiida.backends.sqlalchemy.utils import install_tc, reset_session
            from aiida.common.setup import get_profile_config

            # This check should be done more properly
            # try:
            #     backend_type = get_backend_type()
            # except KeyError:
            #     backend_type = None
            #
            # if backend_type is not None and backend_type != BACKEND_SQLA:
            #     raise InvalidOperation("An already existing database found"
            #                            "and a different than the selected"
            #                            "backend was used for its "
            #                            "management.")

            # Those import are necessary for SQLAlchemy to correctly create
            # the needed database tables.
            from aiida.backends.sqlalchemy.models.authinfo import (DbAuthInfo)
            from aiida.backends.sqlalchemy.models.comment import DbComment
            from aiida.backends.sqlalchemy.models.computer import (DbComputer)
            from aiida.backends.sqlalchemy.models.group import (
                DbGroup, table_groups_nodes)
            from aiida.backends.sqlalchemy.models.lock import DbLock
            from aiida.backends.sqlalchemy.models.log import DbLog
            from aiida.backends.sqlalchemy.models.node import (DbLink, DbNode,
                                                               DbPath,
                                                               DbCalcState)
            from aiida.backends.sqlalchemy.models.user import DbUser
            from aiida.backends.sqlalchemy.models.workflow import (
                DbWorkflow, DbWorkflowData, DbWorkflowStep)
            from aiida.backends.sqlalchemy.models.settings import DbSetting

            reset_session(get_profile_config(gprofile))
            from aiida.backends.sqlalchemy import get_scoped_session
            connection = get_scoped_session().connection()
            Base.metadata.create_all(connection)
            install_tc(connection)

            set_backend_type(BACKEND_SQLA)

        else:
            raise InvalidOperation("Not supported backend selected.")

    print "Database was created successfully"

    # I create here the default user
    print "Loading new environment..."
    if only_user_config:
        from aiida.backends.utils import load_dbenv, is_dbenv_loaded
        # db environment has not been loaded in this case
        if not is_dbenv_loaded():
            load_dbenv()

    from aiida.common.setup import DEFAULT_AIIDA_USER
    from aiida.orm.user import User as AiiDAUser

    if not AiiDAUser.search_for_users(email=DEFAULT_AIIDA_USER):
        print "Installing default AiiDA user..."
        nuser = AiiDAUser(email=DEFAULT_AIIDA_USER)
        nuser.first_name = "AiiDA"
        nuser.last_name = "Daemon"
        nuser.is_staff = True
        nuser.is_active = True
        nuser.is_superuser = True
        nuser.force_save()

    from aiida.common.utils import get_configured_user_email
    email = get_configured_user_email()
    print "Starting user configuration for {}...".format(email)
    if email == DEFAULT_AIIDA_USER:
        print "You set up AiiDA using the default Daemon email ({}),".format(
            email)
        print "therefore no further user configuration will be asked."
    else:
        # Ask to configure the new user
        if not non_interactive:
            user.configure.main(args=[email])
        else:
            # or don't ask
            user.do_configure(kwargs['email'], kwargs.get('first_name'),
                              kwargs.get('last_name'),
                              kwargs.get('institution'), True)

    print "Setup finished."
예제 #18
0
    def run(self, *args):
        from aiida.backends.utils import load_dbenv, is_dbenv_loaded

        if not is_dbenv_loaded():
            load_dbenv()
        import argparse
        from aiida.cmdline.commands.shell import default_modules_list
        import aiida.orm.autogroup
        from aiida.orm.autogroup import Autogroup

        parser = argparse.ArgumentParser(
            prog=self.get_full_command_name(),
            description='Execute an AiiDA script.')
        parser.add_argument('-g',
                            '--group',
                            type=bool,
                            default=True,
                            help='Enables the autogrouping, default = True')
        parser.add_argument('-n',
                            '--groupname',
                            type=str,
                            default=None,
                            help='Specify the name of the auto group')
        # parser.add_argument('-o','--grouponly', type=str, nargs='+', default=['all'],
        #                            help='Limit the grouping to specific classes (by default, all classes are grouped')
        parser.add_argument(
            '-e',
            '--exclude',
            type=str,
            nargs='+',
            default=[],
            help=('Autogroup only specific calculation classes.'
                  " Select them by their module name."))
        parser.add_argument(
            '-E',
            '--excludesubclasses',
            type=str,
            nargs='+',
            default=[],
            help=('Autogroup only specific calculation classes.'
                  " Select them by their module name."))
        parser.add_argument('-i',
                            '--include',
                            type=str,
                            nargs='+',
                            default=['all'],
                            help=('Autogroup only specific data classes.'
                                  " Select them by their module name."))
        parser.add_argument('-I',
                            '--includesubclasses',
                            type=str,
                            nargs='+',
                            default=[],
                            help=('Autogroup only specific code classes.'
                                  " Select them by their module name."))
        parser.add_argument('scriptname',
                            metavar='ScriptName',
                            type=str,
                            help='The name of the script you want to execute')
        parser.add_argument('new_args',
                            metavar='ARGS',
                            nargs=argparse.REMAINDER,
                            type=str,
                            help='Further parameters to pass to the script')
        parsed_args = parser.parse_args(args)

        # Prepare the environment for the script to be run
        globals_dict = {
            '__builtins__': globals()['__builtins__'],
            '__name__': '__main__',
            '__file__': parsed_args.scriptname,
            '__doc__': None,
            '__package__': None
        }

        ## dynamically load modules (the same of verdi shell) - but in
        ## globals_dict, not in the current environment
        for app_mod, model_name, alias in default_modules_list:
            globals_dict["{}".format(alias)] = getattr(
                __import__(app_mod, {}, {}, model_name), model_name)

        if parsed_args.group:
            automatic_group_name = parsed_args.groupname
            if automatic_group_name is None:
                import datetime

                now = datetime.datetime.now()
                automatic_group_name = "Verdi autogroup on " + now.strftime(
                    "%Y-%m-%d %H:%M:%S")

            aiida_verdilib_autogroup = Autogroup()
            aiida_verdilib_autogroup.set_exclude(parsed_args.exclude)
            aiida_verdilib_autogroup.set_include(parsed_args.include)
            aiida_verdilib_autogroup.set_exclude_with_subclasses(
                parsed_args.excludesubclasses)
            aiida_verdilib_autogroup.set_include_with_subclasses(
                parsed_args.includesubclasses)
            aiida_verdilib_autogroup.set_group_name(automatic_group_name)
            ## Note: this is also set in the exec environment!
            ## This is the intended behavior
            aiida.orm.autogroup.current_autogroup = aiida_verdilib_autogroup

        try:
            f = open(parsed_args.scriptname)
        except IOError:
            print >> sys.stderr, "{}: Unable to load file '{}'".format(
                self.get_full_command_name(), parsed_args.scriptname)
            sys.exit(1)
        else:
            try:
                # Must add also argv[0]
                new_argv = [parsed_args.scriptname] + parsed_args.new_args
                with update_environment(new_argv=new_argv):
                    # Add local folder to sys.path
                    sys.path.insert(0, os.path.abspath(os.curdir))
                    # Pass only globals_dict
                    exec(f, globals_dict)
                    # print sys.argv
            except SystemExit as e:
                ## Script called sys.exit()
                # print sys.argv, "(sys.exit {})".format(e.message)

                ## Note: remember to re-raise, the exception to have
                ## the error code properly returned at the end!
                raise
            finally:
                f.close()
예제 #19
0
    def run(self, *args):
        from aiida.common.setup import (create_base_dirs, create_configuration,
                                        set_default_profile, DEFAULT_UMASK)
        from aiida.backends.profile import BACKEND_SQLA, BACKEND_DJANGO
        from aiida.backends.utils import set_backend_type, get_backend_type
        from aiida.common.exceptions import InvalidOperation

        cmdline_args = list(args)

        only_user_config = False
        try:
            cmdline_args.remove('--only-config')
            only_user_config = True
        except ValueError:
            # Parameter not provided
            pass

        if cmdline_args:
            print >> sys.stderr, "Unknown parameters on the command line: "
            print >> sys.stderr, ", ".join(cmdline_args)
            sys.exit(1)

        # create the directories to store the configuration files
        create_base_dirs()
        # gprofile = 'default' if profile is None else profile
        gprofile = 'default' if settings_profile.AIIDADB_PROFILE is None \
            else settings_profile.AIIDADB_PROFILE

        created_conf = None
        # ask and store the configuration of the DB
        try:
            created_conf = create_configuration(profile=gprofile)
        except ValueError as e:
            print >> sys.stderr, "Error during configuration: {}".format(
                e.message)
            sys.exit(1)

        # set default DB profiles
        set_default_profile('verdi', gprofile, force_rewrite=False)
        set_default_profile('daemon', gprofile, force_rewrite=False)

        if only_user_config:
            print(
                "Only user configuration requested, "
                "skipping the migrate command")
        else:
            print "Executing now a migrate command..."

            backend_choice = created_conf['AIIDADB_BACKEND']
            if backend_choice == BACKEND_DJANGO:
                print("...for Django backend")
                # The correct profile is selected within load_dbenv.
                # Setting os.umask here since sqlite database gets created in
                # this step.
                old_umask = os.umask(DEFAULT_UMASK)

                # This check should be done more properly
                # try:
                #     backend_type = get_backend_type()
                # except KeyError:
                #     backend_type = None
                #
                # if backend_type is not None and backend_type != BACKEND_DJANGO:
                #     raise InvalidOperation("An already existing database found"
                #                            "and a different than the selected"
                #                            "backend was used for its "
                #                            "management.")

                try:
                    pass_to_django_manage([execname, 'migrate'],
                                          profile=gprofile)
                finally:
                    os.umask(old_umask)

                set_backend_type(BACKEND_DJANGO)

            elif backend_choice == BACKEND_SQLA:
                print("...for SQLAlchemy backend")
                from aiida.backends.sqlalchemy.models.base import Base
                from aiida.backends.sqlalchemy.utils import (get_engine,
                                                             install_tc)
                from aiida.common.setup import get_profile_config
                from aiida import is_dbenv_loaded, load_dbenv

                if not is_dbenv_loaded():
                    load_dbenv()

                # This check should be done more properly
                # try:
                #     backend_type = get_backend_type()
                # except KeyError:
                #     backend_type = None
                #
                # if backend_type is not None and backend_type != BACKEND_SQLA:
                #     raise InvalidOperation("An already existing database found"
                #                            "and a different than the selected"
                #                            "backend was used for its "
                #                            "management.")

                # Those import are necessary for SQLAlchemy to correctly create
                # the needed database tables.
                from aiida.backends.sqlalchemy.models.authinfo import (
                    DbAuthInfo)
                from aiida.backends.sqlalchemy.models.comment import DbComment
                from aiida.backends.sqlalchemy.models.computer import (
                    DbComputer)
                from aiida.backends.sqlalchemy.models.group import (
                    DbGroup, table_groups_nodes)
                from aiida.backends.sqlalchemy.models.lock import DbLock
                from aiida.backends.sqlalchemy.models.log import DbLog
                from aiida.backends.sqlalchemy.models.node import (DbLink,
                                                                   DbNode,
                                                                   DbPath,
                                                                   DbCalcState)
                from aiida.backends.sqlalchemy.models.user import DbUser
                from aiida.backends.sqlalchemy.models.workflow import (
                    DbWorkflow, DbWorkflowData, DbWorkflowStep)
                from aiida.backends.sqlalchemy.models.settings import DbSetting

                connection = get_engine(get_profile_config(gprofile))
                Base.metadata.create_all(connection)
                install_tc(connection)

                set_backend_type(BACKEND_SQLA)

            else:
                raise InvalidOperation("Not supported backend selected.")

        print "Database was created successfully"

        # I create here the default user
        print "Loading new environment..."
        if only_user_config:
            from aiida.backends.utils import load_dbenv, is_dbenv_loaded
            # db environment has not been loaded in this case
            if not is_dbenv_loaded():
                load_dbenv()

        from aiida.common.setup import DEFAULT_AIIDA_USER
        from aiida.orm.user import User as AiiDAUser

        if not AiiDAUser.search_for_users(email=DEFAULT_AIIDA_USER):
            print "Installing default AiiDA user..."
            nuser = AiiDAUser(email=DEFAULT_AIIDA_USER)
            nuser.first_name = "AiiDA"
            nuser.last_name = "Daemon"
            nuser.is_staff = True
            nuser.is_active = True
            nuser.is_superuser = True
            nuser.force_save()

        from aiida.common.utils import get_configured_user_email
        email = get_configured_user_email()
        print "Starting user configuration for {}...".format(email)
        if email == DEFAULT_AIIDA_USER:
            print "You set up AiiDA using the default Daemon email ({}),".format(
                email)
            print "therefore no further user configuration will be asked."
        else:
            # Ask to configure the new user
            User().user_configure(email)

        print "Install finished."
예제 #20
0
#!/usr/bin/env python
import aiida

aiida.load_dbenv()
from aiida.orm import Group
from aiida.orm.utils import load_node
from aiida.orm import StructureData
import ase
import ase.io
import click


def add_parentstructure_extras(structurenode, parent_uuid):
    # NOTE: consider adding a check if parent_extras is already assigned
    structure_extras = structurenode.extras
    parent_extras = load_node(parent_uuid).extras
    for key, value in list(parent_extras.items()):
        if key not in structure_extras:
            structurenode.set_extra(key, value)
    structurenode.set_extra('parent_extras', True)
    return


@click.command()
@click.option('-d', '--dataset_path', required=True)
@click.option('-gn', '--group_name', required=True)
@click.option('-gd', '--group_description', default="")
@click.option('-pcp', '--parse_comments_path', is_flag=True)
@click.option('-pcs', '--parse_comments_structure', is_flag=True)
def launch(dataset_path, group_name, group_description, parse_comments_path,
           parse_comments_structure):
# Works run by the daemon (using submit)

from aiida import load_dbenv, is_dbenv_loaded
if not is_dbenv_loaded():
    load_dbenv()

from aiida.orm import CalculationFactory, DataFactory, WorkflowFactory
from aiida.work.run import run, submit
from aiida.orm.data.structure import StructureData
from aiida.orm.data.base import Str, Float, Bool, Int

KpointsData = DataFactory("array.kpoints")
ParameterData = DataFactory('parameter')

# Define structure
import numpy as np

cell = [[3.1900000, 0.0000000, 0.0000000], [-1.5950000, 2.7626210, 0.0000000],
        [0.0000000, 0.0000000, 5.1890000]]

scaled_positions = [(0.6666669, 0.3333334, 0.0000000),
                    (0.3333331, 0.6666663, 0.5000000),
                    (0.6666669, 0.3333334, 0.3750000),
                    (0.3333331, 0.6666663, 0.8750000)]

symbols = ['Ga', 'Ga', 'N', 'N']

positions = np.dot(scaled_positions, cell)

structure = StructureData(cell=cell)
for i, scaled_position in enumerate(scaled_positions):
예제 #22
0
def load_dbenv_if_not_loaded():
    if not is_dbenv_loaded():
        load_dbenv()