AiiDA 的实际联机使用体验

前言

  Quantum Espresson (以下简称 QE)是一款基于平面波函数的开源第一性原理计算框架,其免费、易安装使用等优点受到了广大第一性原理计算研究人员的喜爱。QE 不仅支持 CPU 的并行高性能计算,还支持 GPU 计算。这看起来有点像是计算机专业里的深度学习框架,有完整的计算加速支持。另外,QE 与 VASP 的使用习惯类似度比较高,不管是输入文件还是赝势文件,都可以类比着使用。对于计算后的输出结果,QE 也有一套完整的工具链辅助用户完成一些常用的分析操作,比如寻找 k 路径、分析能带结构(Band Gap)等等。

  上次我们提到的 AiiDA 这款专门应用于材料计算领域的开源数据管理软件,与 QE 可以非常方便地结合在一起使用,而且 AiiDA 官网上给出的示例就是基于 QE 计算的。现在我们就来体验一下如何把 QE 和 AiiDA 结合起来使用吧。

实践

  上次介绍的安装部署 AiiDA 的文章中的 Quantum Mobile,就开发了 AiiDA 与 QE 的一体化虚拟机和 Docker 镜像,直接使用非常方便。这里为了在服务器上部署比较方便,采用了 Docker 部署的方式。为了缩短篇幅,使用 Docker 启动一个 Quantum Mobile 实例的操作就不在此赘述了,请参照 AiiDA 开源数据管理软件 中的 Docker 安装 部分。

进入环境

  如果创建的容器实例名为 quantum-mobile,那么使用 docker exec -ti -u max quantum-mobile /bin/bash 命令进入容器。由于容器默认是不开启 Anaconda 的虚拟环境的,所以需要使用 workon aiida 命令开启 AiiDA 专用虚拟环境。

初始化配置

  quantum-mobile 容器中默认是没有任何配置和数据的,只有已经正常运行的 aiida-core、PostgreSQL 和 RabbitMQ。这里我们可以使用快速配置来完成初始化。

# 快速初始化
(aiida) max@37440764beb9:~$ verdi quicksetup
Info: enter "?" for help
Info: enter "!" to ignore the default and set no value
Profile name [quicksetup]: qe
Email Address (for sharing data) [aiida@localhost]:
First name [Max]:
Last name [Scientist]:
Institution [Quantum Mobile]:
Trying to become 'postgres' user. You may be asked for your 'sudo' password.
Trying to become 'postgres' user. You may be asked for your 'sudo' password.
Trying to become 'postgres' user. You may be asked for your 'sudo' password.
Trying to become 'postgres' user. You may be asked for your 'sudo' password.
Trying to become 'postgres' user. You may be asked for your 'sudo' password.
Trying to become 'postgres' user. You may be asked for your 'sudo' password.
Success: created new profile `qe`.
Info: migrating the database.
Operations to perform:
  Apply all migrations: auth, contenttypes, db
Running migrations:
  Applying contenttypes.0001_initial... OK
  ......
  Applying db.0045_dbgroup_extras... OK
Success: database migration completed.

# 将新建的 qe 配置设置为默认配置
(aiida) max@37440764beb9:~$ verdi profile setdefault qe
Success: qe set as default profile

导入数据

# 下载测试 aiida 数据
wget http://phonondb.mtl.kyoto-u.ac.jp/aiida_tutorial_2020_07_perovskites_v0.9.aiida

# 导入 aiida 数据到数据库
(aiida) max@37440764beb9:~$ verdi import aiida_tutorial_2020_07_perovskites_v0.9.aiida
Info: starting import: aiida_tutorial_2020_07_perovskites_v0.9.aiida
Info: incompatible version detected for aiida_tutorial_2020_07_perovskites_v0.9.aiida, trying migration
Reading archive version
Migration pathway: 0.9 -> 0.10
Extracting archive to work directory
Info: proceeding with import of migrated archive

IMPORT
--------  ---------
Archive   extracted

Parameters
--------------------------  ------
Comment rules               newest
New Node Extras rules       import
Existing Node Extras rules  kcl
Links - label=pseudos__O                  39.4%|██████████████████████████████████▋                                                     | 941/2388
Summary
-----------------------  ---------------
Auto-import Group label  20210527-074131
User(s)                  1 new
Computer(s)              1 new
Node(s)                  1981 new
Group(s)                 6 new
Link(s)                  2388 new

Success: imported archive aiida_tutorial_2020_07_perovskites_v0.9.aiida

# 下载赝势数据
wget http://phonondb.mtl.kyoto-u.ac.jp/SSSP_1.1_PBE_efficiency.tar.gz
mkdir sssp_pseudos
tar -C sssp_pseudos -zxvf SSSP_1.1_PBE_efficiency.tar.gz

# 导入赝势数据
(aiida) max@37440764beb9:~$ verdi data upf uploadfamily sssp_pseudos 'SSSP' 'SSSP pseudopotential library'
Success: UPF files found: 85. New files uploaded: 74

配置主机和 QE

  使用以下配置文件 computer.yml 和命令 verdi computer setup --config computer.yml 一键配置本地主机,并使用命令 verdi computer configure local localhost 配置 localhost 主机为 local 模式连接(相关配置均使用默认即可)。

# computer.yml
---
description: "localhost"
label: "localhost"
hostname: "localhost"
transport: local
scheduler: "direct"
work_dir: "/home/max/.aiida_run"
mpirun_command: "mpirun -np {tot_num_mpiprocs}"
mpiprocs_per_machine: "2"
shebang: "#!/bin/bash"
prepend_text: " "
append_text: " "

  使用以下配置文件 code.yml 和命令 verdi code setup --config code.yml 一键配置本地 QE 程序。

# code.yml
---
label: "qe-6.5-pw"
description: "quantum_espresso v6.5"
input_plugin: "quantumespresso.pw"
on_computer: true
remote_abs_path: "/usr/local/bin/pw.x"
computer: "localhost"
prepend_text: "ulimit -s unlimited"
append_text: " "

提交计算

确认 aiida 后台状态

# 查看 aiida 后台状态
(aiida) max@37440764beb9:~$ verdi daemon status
Profile: qe
The daemon is not running

# 若如上未运行 aiida 后台程序,则使用以下命令启动
(aiida) max@37440764beb9:~$ verdi daemon start
Starting the daemon... RUNNING

# 再次查看 aiida 后台状态,已正常运行
(aiida) max@37440764beb9:~$ verdi daemon status
Profile: qe
Daemon is running as PID 102244 since 2021-05-29 12:38:55
Active workers [1]:
   PID    MEM %    CPU %  started
------  -------  -------  -------------------
102248    0.005        0  2021-05-29 12:38:55
Use verdi daemon [incr | decr] [num] to increase / decrease the amount of workers

确认代码配置

# 如下所示,列举出 qe-6.5,与已配置信息一致
(aiida) max@37440764beb9:~$ verdi code list
# List of configured codes:
# (use 'verdi code show CODEID' to see the details)
* pk 2056 - qe-6.5-pw@localhost

准备执行脚本

# cal.py

from aiida import load_profile

from aiida.orm import Code
from aiida.plugins import DataFactory
from aiida.engine import submit
from aiida.orm.nodes.data.upf import get_pseudos_from_structure

load_profile()

StructureData = DataFactory('structure')
Dict = DataFactory('dict')
KpointsData = DataFactory('array.kpoints')

###########################################
# Set constant values here
codename = 'qe-6.5-pw@localhost'
pseudo_family = 'SSSP'
###########################################


code = Code.get_from_string(codename)
builder = code.get_builder()

# Metadata settings
builder.metadata.label = "PW test"
builder.metadata.description = "My first AiiDA calc with Quantum ESPRESSO on Si"
builder.metadata.options.resources = {'num_machines': 1}
builder.metadata.options.max_wallclock_seconds = 30 * 60

# Si structure
alat = 4 # angstorm
unit_cell = [[alat/2, alat/2, 0.], [alat/2, 0., alat/2], [0., alat/2, alat/2]]
structure = StructureData(cell=unit_cell)
structure.append_atom(position=(alat/4., alat/4., alat/4.), symbols="Si")
structure.append_atom(position=(0., 0., 0.), symbols="Si")
structure.store()

# kpoints-mesh
kpoints = KpointsData()
kpoints.set_kpoints_mesh([2, 2, 2])
kpoints.store()



# Input file
parameters_dict = {
    'CONTROL': {
        'calculation': 'scf',
    },
    'SYSTEM': {
        'ecutwfc': 30.,
        'ecutrho': 200.,
    },
    'ELECTRONS': {
        'conv_thr': 1.e-6,
    },
}
parameters = Dict(dict=parameters_dict)
parameters.store()

# Builder settings
builder.structure = structure
builder.kpoints = kpoints
builder.pseudos = get_pseudos_from_structure(structure, 'SSSP')
builder.parameters = parameters
builder.metadata.dry_run = False
builder.metadata.store_provenance = True

# Submit the job
calculation = submit(builder)
calculation.set_extra("element", "Si")

# Print the job pk value
print(f'created calculation with Pk={calculation.pk}')

验证计算及结果

验证计算状态

# 查询任务执行状态,如下为 正在排队等待执行
(aiida) max@37440764beb9:~$ verdi process list
  PK  Created    Process label    Process State    Process status
----  ---------  ---------------  ---------------  ---------------------------------------
2087  9s ago     PwCalculation    ⏵ Waiting        Monitoring scheduler: job state RUNNING

# 当执行完后上一条命令是无法查询到任务状态的,需加 -a 选项查看所有任务
(aiida) max@37440764beb9:~$ verdi process list -a
  PK  Created    Process label    Process State     Process status
----  ---------  ---------------  ----------------  ----------------
 648  2405D ago  PwCalculation    ⏹ Finished [0]
 ......
 ......
2087  27s ago    PwCalculation    ⏹ Finished [0]

Total results: 175

Info: last time an entry changed state: 16s ago (at 13:45:38 on 2021-05-29)

验证结果

# 查询计算大致信息,如下可知一切正常并已格式化提取所需的输出信息
(aiida) max@37440764beb9:~$ verdi node show 2087
Property     Value
-----------  -----------------------------------------------
type         PwCalculation
state        Finished [0]
pk           2087
uuid         f1762049-4627-4f87-acac-ad6074b87352
label        PW test
description  My first AiiDA calc with Quantum ESPRESSO on Si
ctime        2021-05-29 13:45:27.167975+00:00
mtime        2021-05-29 13:45:38.615649+00:00
computer     [2] localhost

Inputs      PK    Type
----------  ----  -------------
pseudos
    Si      2043  UpfData
code        2056  Code
kpoints     2085  KpointsData
parameters  2086  Dict
structure   2084  StructureData

Outputs              PK  Type
-----------------  ----  --------------
output_band        2090  BandsData
output_parameters  2092  Dict
output_trajectory  2091  TrajectoryData
remote_folder      2088  RemoteData
retrieved          2089  FolderData

# 查看计算输入文件
(aiida) max@37440764beb9:~$ verdi calcjob inputcat 2087 | less

# 查看计算输出文件
(aiida) max@37440764beb9:~$ verdi calcjob outputcat 2087 | less

# 查看格式化提取的计算结果
(aiida) max@37440764beb9:~$ verdi calcjob res 2087
{
    "beta_real_space": false,
    "charge_density": "./charge-density.dat",
    "constraint_mag": 0,
    "convergence_info": {
        "scf_conv": {
            "convergence_achieved": true,
            "n_scf_steps": 5,
            "scf_error": 2.4316966484325e-08
        }
    },
    "creator_name": "pwscf",
    "creator_version": "6.5",
    "dft_exchange_correlation": "PBE",
    "do_magnetization": true,
    "do_not_use_time_reversal": false,
    "energy": -285.72326235425,
    "energy_accuracy": 6.80284586265e-07,
    "energy_accuracy_units": "eV",
    ......
    ......   
}

总结

  如上所示,经过了一系列的操作 AiiDA 可以非常容易搭配 QE 完成第一性原理计算,并且对计算过程中的输入、输出数据都实现了有效的管理。不过在实践过程中发现, AiiDA 对于我们设定的 QE 输入参数并不会进行校验,甚至在 AiiDA 对这些输入参数进行格式化生成 QE 输入文件之后,QE 会视之为非法字符串。虽然参考了 aiida-toturial 的输入参数配置,但是其中的 mickeymouse 字段使得 QE 计算无法正常运行。

  另外,如果我们设置了比较严苛的输入参数值,QE 计算可能会受限无法完成完整的计算,并且无法格式化抽取到预设的重要数据信息。因此只能在设置输入参数时,除必要精度需要外尽量放宽其他计算的限制。我们除了可以通过 AiiDA 提供的 verdi 命令来交互式查询计算结果之外,也可以进入到计算的目录直接查询 QE 计算的原始输入文件和输出文件(默认本地目录是 ~/.aiida_run)。

参考资料