如何与 AiiDA 交互#

与 AiiDA 交互有多种方式:

命令行界面#

AiiDA 有一个名为 verdi 的命令行界面。AiiDA Command Line 部分概述了所有可用的命令。更多详细信息,请参阅主题部分 命令行界面

小技巧

verdi 命令行界面也可以作为 text-based user interface <https://en.wikipedia.org/wiki/Text-based_user_interface>`_(TUI)进行探索。这需要在安装 ``aiida-core` 时附加 tui (例如 pip install aiida-core[tui])。然后可以使用 verdi tui 启动 TUI。

脚本#

AiiDA 的 Python API 可以在 Python 脚本中与其他 Python 代码混合使用。唯一的要求是,在使用 API 之前,必须加载 AiiDA 配置文件。推荐的方法是通过命令行界面运行脚本:

verdi run script.py

在调用实际脚本之前,verdi CLI 会自动加载默认配置文件,并传递可能指定的任何命令行参数。

备注

A different profile can be selected using the --profile option, just as for all other verdi commands.

或者,也可以在文件顶部添加 AiiDA 的特定 shebang

#!/usr/bin/env runaiida

当脚本以这个 Shebang 开始时,当它被执行时,它会自动传递给 verdi run,就像直接通过 verdi run 调用一样。这样做的好处是,在运行脚本时不必再明确键入 verdi run,而只需使其可执行并直接执行即可。缺点是不能指定特定的配置文件,而是始终加载默认配置文件。

如果由于某种原因,不能使用 verdi run 或特殊的 Shebang,也可以通过 Python 脚本本身的 API 直接加载配置文件:

from aiida import load_profile
load_profile()

可以向 load_profile() 传递特定的配置文件名称,否则将加载默认配置文件。

在脚本或 Python 实例中,也可以切换到不同的配置文件,或使用上下文管理器中的配置文件:

from aiida import load_profile, profile_context, orm

with profile_context('my_profile_1'):
    # The profile will be loaded within the context
    node_from_profile_1 = orm.load_node(1)
    # then the profile will be unloaded automatically

# load a global profile
load_profile('my_profile_2')
node_from_profile_2 = orm.load_node(1)

# switch to a different global profile
load_profile('my_profile_3', allow_switch=True)
node_from_profile_3 = orm.load_node(1)

交互式 shell#

AiiDA 提供一个 Python API,可以在交互式 shell 中使用,例如 IPython。建议通过命令行界面启动交互式 shell 会话来使用 AiiDA:

$ verdi shell

该命令将打开一个普通的 IPython shell,但会自动加载默认的 AiiDA 配置文件,这是使用 Python API 所必需的。

备注

A different profile can be selected using the --profile option, just as for all other verdi commands.

除了自动加载 AiiDA 配置文件,AiiDA API 中的某些常用模块也会自动 import。可以使用 verdi config 命令配置预加载的模块。

如果由于某种原因无法使用 verdi shell,也可以通过 shell 本身的 API 直接加载配置文件:

In [1]: from aiida import load_profile

In [2]: load_profile()
Out[2]: <aiida.manage.configuration.profile.Profile at 0x7fccfd6c50a0>

可以向 load_profile() 传递特定的配置文件名称,否则将加载默认配置文件。

互动笔记本#

交互式 类似,AiiDA 也直接兼容交互式 Python 笔记本,如 Jupyter。要在笔记本中使用 AiiDA 的 Python API,首先必须加载配置文件:

In [1]: from aiida import load_profile

In [2]: load_profile()
Out[2]: <aiida.manage.configuration.profile.Profile at 0x7fccfd6c50a0>

可以向 load_profile() 传递一个特定的配置文件名称,否则将加载默认配置文件。使用下面的神奇语句也可以达到同样的目的:

%load_ext aiida
%aiida

这条神奇的线路将复制与 verdi shell 提供的 交互式 shell 相同的环境。不过,它需要进行一次性安装,详见如何安装 在 Jupyter 中使用 AiiDA 的章节。

REST API#

AiiDA 内置 REST API,允许你查询特定配置文件的数据。参考 启动 REST API 章节了解如何启动 REST API。查询 REST API 小节提供了如何与运行中的 REST API 交互的信息。