Repository: deepmodeling/dpgen (language: python)

Issue:
support automatic training_reuse_old_ratio
set the default value to `auto` instead of raising errors


Discussion / hints:
@robinzyb it seems that unit test for cp2k is broken after dpdata v0.2.15 is released.
## [Codecov](https://app.codecov.io/gh/deepmodeling/dpgen/pull/1209?src=pr&el=h1&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=deepmodeling) Report
Patch coverage: **`31.81`**% and project coverage change: **`-0.03`** :warning:
> Comparison is base [(`84d4a1a`)](https://app.codecov.io/gh/deepmodeling/dpgen/commit/84d4a1a1c16e53ebc26cb39aef3cc7dccaff06bd?el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=deepmodeling) 47.14% compared to head [(`4b2dbd4`)](https://app.codecov.io/gh/deepmodeling/dpgen/pull/1209?src=pr&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=deepmodeling) 47.11%.

<details><summary>Additional details and impacted files</summary>


```diff
@@            Coverage Diff             @@
##            devel    #1209      +/-   ##
==========================================
- Coverage   47.14%   47.11%   -0.03%     
==========================================
  Files          82       82              
  Lines       14633    14652      +19     
==========================================
+ Hits         6898     6903       +5     
- Misses       7735     7749      +14     
```


| [Impacted Files](https://app.codecov.io/gh/deepmodeling/dpgen/pull/1209?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=deepmodeling) | Coverage Δ | |
|---|---|---|
| [dpgen/generator/run.py](https://app.codecov.io/gh/deepmodeling/dpgen/pull/1209?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=deepmodeling#diff-ZHBnZW4vZ2VuZXJhdG9yL3J1bi5weQ==) | `65.65% <28.57%> (-0.29%)` | :arrow_down: |
| [dpgen/generator/arginfo.py](https://app.codecov.io/gh/deepmodeling/dpgen/pull/1209?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=deepmodeling#diff-ZHBnZW4vZ2VuZXJhdG9yL2FyZ2luZm8ucHk=) | `100.00% <100.00%> (ø)` | |


</details>

[:umbrella: View full report in Codecov by Sentry](https://app.codecov.io/gh/deepmodeling/dpgen/pull/1209?src=pr&el=continue&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=deepmodeling).   
:loudspeaker: Do you have feedback about the report comment? [Let us know in this issue](https://about.codecov.io/codecov-pr-comment-feedback/?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=deepmodeling).


Fix patch:
diff --git a/doc/conf.py b/doc/conf.py
index 7c99018a1..b0bcbb400 100644
--- a/doc/conf.py
+++ b/doc/conf.py
@@ -11,13 +11,10 @@
 # documentation root, use os.path.abspath to make it absolute, like shown here.
 #
 import os
-import subprocess
 import sys
 from datetime import date
 
 # import sys
-import recommonmark
-from recommonmark.transform import AutoStructify
 
 # -- Project information -----------------------------------------------------
 
diff --git a/dpgen/__init__.py b/dpgen/__init__.py
index 927705f25..3fad112f2 100644
--- a/dpgen/__init__.py
+++ b/dpgen/__init__.py
@@ -1,5 +1,3 @@
-from __future__ import print_function, unicode_literals
-
 import logging
 import os
 
diff --git a/dpgen/arginfo.py b/dpgen/arginfo.py
index 63405bfdd..cef1f18de 100644
--- a/dpgen/arginfo.py
+++ b/dpgen/arginfo.py
@@ -20,7 +20,6 @@ def general_mdata_arginfo(name: str, tasks: Tuple[str]) -> Argument:
     Argument
         arginfo
     """
-
     doc_api_version = "Please set to 1.0"
     doc_deepmd_version = "DeePMD-kit version, e.g. 2.1.3"
     doc_run_mdata = "machine.json file"
diff --git a/dpgen/collect/collect.py b/dpgen/collect/collect.py
index faadf6336..808341e6f 100644
--- a/dpgen/collect/collect.py
+++ b/dpgen/collect/collect.py
@@ -4,10 +4,8 @@
 import glob
 import json
 import os
-import sys
 
 import dpdata
-import numpy as np
 
 from dpgen.generator.run import data_system_fmt
 
diff --git a/dpgen/data/arginfo.py b/dpgen/data/arginfo.py
index 6bbcd3fa1..ca7ac4b69 100644
--- a/dpgen/data/arginfo.py
+++ b/dpgen/data/arginfo.py
@@ -1,6 +1,6 @@
-from typing import Dict, List
+from typing import List
 
-from dargs import Argument, ArgumentEncoder, Variant
+from dargs import Argument, Variant
 
 from dpgen.arginfo import general_mdata_arginfo
 
diff --git a/dpgen/data/gen.py b/dpgen/data/gen.py
index 14314ada8..83bd59745 100644
--- a/dpgen/data/gen.py
+++ b/dpgen/data/gen.py
@@ -3,14 +3,11 @@
 import argparse
 import glob
 import json
-import logging
 import os
-import random
 import re
 import shutil
 import subprocess as sp
 import sys
-import time
 import warnings
 
 import dpdata
@@ -31,7 +28,6 @@
     get_abacus_STRU,
     make_abacus_scf_kpt,
     make_abacus_scf_stru,
-    make_kspacing_kpoints_stru,
     make_supercell_abacus,
 )
 from dpgen.generator.lib.utils import symlink_user_forward_files
@@ -62,7 +58,7 @@ def create_path(path, back=False):
 
 
 def replace(file_name, pattern, subst):
-    file_handel = open(file_name, "r")
+    file_handel = open(file_name)
     file_string = file_handel.read()
     file_handel.close()
     file_string = re.sub(pattern, subst, file_string)
@@ -130,7 +126,7 @@ def poscar_ele(poscar_in, poscar_out, eles, natoms):
         ele_line += str(ii) + " "
     for ii in natoms:
         natom_line += str(ii) + " "
-    with open(poscar_in, "r") as fin:
+    with open(poscar_in) as fin:
         lines = list(fin)
         lines[5] = ele_line + "\n"
         lines[6] = natom_line + "\n"
@@ -188,7 +184,7 @@ def poscar_natoms(lines):
 
 
 def poscar_shuffle(poscar_in, poscar_out):
-    with open(poscar_in, "r") as fin:
+    with open(poscar_in) as fin:
         lines = list(fin)
     numb_atoms = poscar_natoms(lines)
     idx = np.arange(8, 8 + numb_atoms)
@@ -229,18 +225,18 @@ def poscar_scale_cartesian(str_in, scale):
         boxl = lines[ii].split()
         boxv = [float(ii) for ii in boxl]
         boxv = np.array(boxv) * scale
-        lines[ii] = "%.16e %.16e %.16e\n" % (boxv[0], boxv[1], boxv[2])
+        lines[ii] = f"{boxv[0]:.16e} {boxv[1]:.16e} {boxv[2]:.16e}\n"
     # scale coord
     for ii in range(8, 8 + numb_atoms):
         cl = lines[ii].split()
         cv = [float(ii) for ii in cl]
         cv = np.array(cv) * scale
-        lines[ii] = "%.16e %.16e %.16e\n" % (cv[0], cv[1], cv[2])
+        lines[ii] = f"{cv[0]:.16e} {cv[1]:.16e} {cv[2]:.16e}\n"
     return lines
 
 
 def poscar_scale(poscar_in, poscar_out, scale):
-    with open(poscar_in, "r") as fin:
+    with open(poscar_in) as fin:
         lines = list(fin)
     if "D" == lines[7][0] or "d" == lines[7][0]:
         lines = poscar_scale_direct(lines, scale)
@@ -366,7 +362,7 @@ def make_super_cell_poscar(jdata):
     from_struct.to(to_file, "poscar")
 
     # make system dir (copy)
-    lines = open(to_file, "r").read().split("\n")
+    lines = open(to_file).read().split("\n")
     natoms_str = lines[6]
     natoms_list = [int(ii) for ii in natoms_str.split()]
     dlog.info(natoms_list)
@@ -1079,7 +1075,7 @@ def coll_vasp_md(jdata):
                 # dlog.info("OUTCAR",outcar)
                 if os.path.isfile(outcar):
                     # dlog.info("*"*40)
-                    with open(outcar, "r") as fin:
+                    with open(outcar) as fin:
                         nforce = fin.read().count("TOTAL-FORCE")
                     # dlog.info("nforce is", nforce)
                     # dlog.info("md_nstep", md_nstep)
@@ -1095,8 +1091,8 @@ def coll_vasp_md(jdata):
         arg_cvt = " "
         if len(valid_outcars) == 0:
             raise RuntimeError(
-                "MD dir: %s: find no valid outcar in sys %s, "
-                "check if your vasp md simulation is correctly done" % (path_md, ii)
+                "MD dir: {}: find no valid outcar in sys {}, "
+                "check if your vasp md simulation is correctly done".format(path_md, ii)
             )
 
         flag = True
@@ -1127,7 +1123,7 @@ def coll_vasp_md(jdata):
 
 def _vasp_check_fin(ii):
     if os.path.isfile(os.path.join(ii, "OUTCAR")):
-        with open(os.path.join(ii, "OUTCAR"), "r") as fp:
+        with open(os.path.join(ii, "OUTCAR")) as fp:
             content = fp.read()
             count = content.count("Elapse")
             if count != 1:
@@ -1233,8 +1229,10 @@ def coll_abacus_md(jdata):
         arg_cvt = " "
         if len(valid_outcars) == 0:
             raise RuntimeError(
-                "MD dir: %s: find no valid OUT.ABACUS in sys %s, "
-                "check if your abacus md simulation is correctly done." % (path_md, ii)
+                "MD dir: {}: find no valid OUT.ABACUS in sys {}, "
+                "check if your abacus md simulation is correctly done.".format(
+                    path_md, ii
+                )
             )
 
         flag = True
@@ -1469,17 +1467,17 @@ def run_abacus_md(jdata, mdata):
 def gen_init_bulk(args):
     try:
         import ruamel
-        from monty.serialization import dumpfn, loadfn
+        from monty.serialization import loadfn
 
         warnings.simplefilter("ignore", ruamel.yaml.error.MantissaNoDotYAML1_1Warning)
         jdata = loadfn(args.PARAM)
         if args.MACHINE is not None:
             mdata = loadfn(args.MACHINE)
     except Exception:
-        with open(args.PARAM, "r") as fp:
+        with open(args.PARAM) as fp:
             jdata = json.load(fp)
         if args.MACHINE is not None:
-            with open(args.MACHINE, "r") as fp:
+            with open(args.MACHINE) as fp:
                 mdata = json.load(fp)
 
     if args.MACHINE is not None:
diff --git a/dpgen/data/reaction.py b/dpgen/data/reaction.py
index 2df183796..adbd453ac 100644
--- a/dpgen/data/reaction.py
+++ b/dpgen/data/reaction.py
@@ -1,10 +1,9 @@
-"""
-input: trajectory
+"""input: trajectory
 00: ReaxFF MD (lammps)
 01: build dataset (mddatasetbuilder)
 02: fp (gaussian)
 03: convert to deepmd data
-output: data
+output: data.
 """
 
 import glob
@@ -106,7 +105,7 @@ def run_reaxff(jdata, mdata, log_file="reaxff_log"):
 
 
 def link_trj(jdata):
-    """link lammpstrj"""
+    """Link lammpstrj."""
     create_path(build_path)
     task_path = os.path.join(build_path, "task.000")
     create_path(task_path)
@@ -217,17 +216,17 @@ def convert_data(jdata):
 def gen_init_reaction(args):
     try:
         import ruamel
-        from monty.serialization import dumpfn, loadfn
+        from monty.serialization import loadfn
 
         warnings.simplefilter("ignore", ruamel.yaml.error.MantissaNoDotYAML1_1Warning)
         jdata = loadfn(args.PARAM)
         if args.MACHINE is not None:
             mdata = loadfn(args.MACHINE)
     except Exception:
-        with open(args.PARAM, "r") as fp:
+        with open(args.PARAM) as fp:
             jdata = json.load(fp)
         if args.MACHINE is not None:
-            with open(args.MACHINE, "r") as fp:
+            with open(args.MACHINE) as fp:
                 mdata = json.load(fp)
 
     jdata_arginfo = init_reaction_jdata_arginfo()
diff --git a/dpgen/data/surf.py b/dpgen/data/surf.py
index 88ef0fc83..4a61ac418 100644
--- a/dpgen/data/surf.py
+++ b/dpgen/data/surf.py
@@ -14,7 +14,6 @@
 from ase.build import general_surface
 
 # -----ASE-------
-from ase.io import read
 from pymatgen.core import Element, Structure
 from pymatgen.io.ase import AseAtomsAdaptor
 
@@ -48,7 +47,7 @@ def create_path(path):
 
 
 def replace(file_name, pattern, subst):
-    file_handel = open(file_name, "r")
+    file_handel = open(file_name)
     file_string = file_handel.read()
     file_handel.close()
     file_string = re.sub(pattern, subst, file_string)
@@ -126,7 +125,7 @@ def poscar_ele(poscar_in, poscar_out, eles, natoms):
         ele_line += str(ii) + " "
     for ii in natoms:
         natom_line += str(ii) + " "
-    with open(poscar_in, "r") as fin:
+    with open(poscar_in) as fin:
         lines = list(fin)
         lines[5] = ele_line + "\n"
         lines[6] = natom_line + "\n"
@@ -142,13 +141,13 @@ def _poscar_natoms(lines):
 
 
 def poscar_natoms(poscar_in):
-    with open(poscar_in, "r") as fin:
+    with open(poscar_in) as fin:
         lines = list(fin)
         return _poscar_natoms(lines)
 
 
 def poscar_shuffle(poscar_in, poscar_out):
-    with open(poscar_in, "r") as fin:
+    with open(poscar_in) as fin:
         lines = list(fin)
     numb_atoms = _poscar_natoms(lines)
     idx = np.arange(8, 8 + numb_atoms)
@@ -169,39 +168,8 @@ def poscar_scale_direct(str_in, scale):
     return lines
 
 
-def poscar_scale_cartesian(str_in, scale):
-    lines = str_in.copy()
-    numb_atoms = _poscar_natoms(lines)
-    # scale box
-    for ii in range(2, 5):
-        boxl = lines[ii].split()
-        boxv = [float(ii) for ii in boxl]
-        boxv = np.array(boxv) * scale
-        lines[ii] = "%.16e %.16e %.16e\n" % (boxv[0], boxv[1], boxv[2])
-    # scale coord
-    for ii in range(8, 8 + numb_atoms):
-        cl = lines[ii].split()
-        cv = [float(ii) for ii in cl]
-        cv = np.array(cv) * scale
-        lines[ii] = "%.16e %.16e %.16e\n" % (cv[0], cv[1], cv[2])
-    return lines
-
-
-def poscar_scale(poscar_in, poscar_out, scale):
-    with open(poscar_in, "r") as fin:
-        lines = list(fin)
-    if "D" == lines[7][0] or "d" == lines[7][0]:
-        lines = poscar_scale_direct(lines, scale)
-    elif "C" == lines[7][0] or "c" == lines[7][0]:
-        lines = poscar_scale_cartesian(lines, scale)
-    else:
-        raise RuntimeError("Unknow poscar style at line 7: %s" % lines[7])
-    with open(poscar_out, "w") as fout:
-        fout.write("".join(lines))
-
-
 def poscar_elong(poscar_in, poscar_out, elong, shift_center=True):
-    with open(poscar_in, "r") as fin:
+    with open(poscar_in) as fin:
         lines = list(fin)
     if lines[7][0].upper() != "C":
         raise RuntimeError("only works for Cartesian POSCAR")
@@ -210,7 +178,7 @@ def poscar_elong(poscar_in, poscar_out, elong, shift_center=True):
     boxzl = np.linalg.norm(boxz)
     elong_ratio = elong / boxzl
     boxz = boxz * (1.0 + elong_ratio)
-    lines[4] = "%.16e %.16e %.16e\n" % (boxz[0], boxz[1], boxz[2])
+    lines[4] = f"{boxz[0]:.16e} {boxz[1]:.16e} {boxz[2]:.16e}\n"
     if shift_center:
         poscar_str = "".join(lines)
         st = Structure.from_str(poscar_str, fmt="poscar")
@@ -415,15 +383,6 @@ def make_vasp_relax(jdata):
     os.chdir(cwd)
 
 
-def poscar_scale_direct(str_in, scale):
-    lines = str_in.copy()
-    numb_atoms = _poscar_natoms(lines)
-    pscale = float(lines[1])
-    pscale = pscale * scale
-    lines[1] = str(pscale) + "\n"
-    return lines
-
-
 def poscar_scale_cartesian(str_in, scale):
     lines = str_in.copy()
     numb_atoms = _poscar_natoms(lines)
@@ -432,18 +391,18 @@ def poscar_scale_cartesian(str_in, scale):
         boxl = lines[ii].split()
         boxv = [float(ii) for ii in boxl]
         boxv = np.array(boxv) * scale
-        lines[ii] = "%.16e %.16e %.16e\n" % (boxv[0], boxv[1], boxv[2])
+        lines[ii] = f"{boxv[0]:.16e} {boxv[1]:.16e} {boxv[2]:.16e}\n"
     # scale coord
     for ii in range(8, 8 + numb_atoms):
         cl = lines[ii].split()
         cv = [float(ii) for ii in cl]
         cv = np.array(cv) * scale
-        lines[ii] = "%.16e %.16e %.16e\n" % (cv[0], cv[1], cv[2])
+        lines[ii] = f"{cv[0]:.16e} {cv[1]:.16e} {cv[2]:.16e}\n"
     return lines
 
 
 def poscar_scale(poscar_in, poscar_out, scale):
-    with open(poscar_in, "r") as fin:
+    with open(poscar_in) as fin:
         lines = list(fin)
     if "D" == lines[7][0] or "d" == lines[7][0]:
         lines = poscar_scale_direct(lines, scale)
@@ -582,7 +541,7 @@ def pert_scaled(jdata):
 
 def _vasp_check_fin(ii):
     if os.path.isfile(os.path.join(ii, "OUTCAR")):
-        with open(os.path.join(ii, "OUTCAR"), "r") as fp:
+        with open(os.path.join(ii, "OUTCAR")) as fp:
             content = fp.read()
             count = content.count("Elapse")
             if count != 1:
@@ -645,17 +604,17 @@ def run_vasp_relax(jdata, mdata):
 def gen_init_surf(args):
     try:
         import ruamel
-        from monty.serialization import dumpfn, loadfn
+        from monty.serialization import loadfn
 
         warnings.simplefilter("ignore", ruamel.yaml.error.MantissaNoDotYAML1_1Warning)
         jdata = loadfn(args.PARAM)
         if args.MACHINE is not None:
             mdata = loadfn(args.MACHINE)
     except Exception:
-        with open(args.PARAM, "r") as fp:
+        with open(args.PARAM) as fp:
             jdata = json.load(fp)
         if args.MACHINE is not None:
-            with open(args.MACHINE, "r") as fp:
+            with open(args.MACHINE) as fp:
                 mdata = json.load(fp)
 
     out_dir = out_dir_name(jdata)
diff --git a/dpgen/data/tools/bcc.py b/dpgen/data/tools/bcc.py
index a48baef07..9c471e36b 100644
--- a/dpgen/data/tools/bcc.py
+++ b/dpgen/data/tools/bcc.py
@@ -14,12 +14,12 @@ def poscar_unit(latt):
     ret = ""
     ret += "BCC : a = %f \n" % latt
     ret += "%.16f\n" % (latt)
-    ret += "%.16f %.16f %.16f\n" % (box[0][0], box[0][1], box[0][2])
-    ret += "%.16f %.16f %.16f\n" % (box[1][0], box[1][1], box[1][2])
-    ret += "%.16f %.16f %.16f\n" % (box[2][0], box[2][1], box[2][2])
+    ret += f"{box[0][0]:.16f} {box[0][1]:.16f} {box[0][2]:.16f}\n"
+    ret += f"{box[1][0]:.16f} {box[1][1]:.16f} {box[1][2]:.16f}\n"
+    ret += f"{box[2][0]:.16f} {box[2][1]:.16f} {box[2][2]:.16f}\n"
     ret += "Type\n"
     ret += "%d\n" % numb_atoms()
     ret += "Direct\n"
-    ret += "%.16f %.16f %.16f\n" % (0.0, 0.0, 0.0)
-    ret += "%.16f %.16f %.16f\n" % (0.5, 0.5, 0.5)
+    ret += f"{0.0:.16f} {0.0:.16f} {0.0:.16f}\n"
+    ret += f"{0.5:.16f} {0.5:.16f} {0.5:.16f}\n"
     return ret
diff --git a/dpgen/data/tools/cessp2force_lin.py b/dpgen/data/tools/cessp2force_lin.py
index aa6c91c3a..2a034247b 100755
--- a/dpgen/data/tools/cessp2force_lin.py
+++ b/dpgen/data/tools/cessp2force_lin.py
@@ -102,7 +102,7 @@ def scan_outcar_file(file_handle):
     elif potcar:
         return [configs, potcar, ipt]
     else:
-        sys.stderr.write("Could not determine atom types in file %s.\n" % filename)
+        sys.stderr.write("Could not determine atom types in file.\n")
         sys.exit()
 
 
@@ -121,12 +121,12 @@ def process_outcar_file_v5_dev(
         if outcars[i].endswith(".gz"):
             f = gzip.open(outcars[i], "rb")
         else:
-            f = open(outcars[i], "r")
+            f = open(outcars[i])
 
         # Writing current OUTCAR's information into potfit format files.
         nconfs = data[i][0]
         natoms = sum(data[i][2])  # ipt
-        if windex == None:
+        if windex is None:
             windex = range(nconfs)
         if windex == "final":
             windex = [nconfs - 1]
@@ -165,15 +165,9 @@ def process_outcar_file_v5_dev(
                         "## force file generated from file %s config %d\n"
                         % (outcars[i], count)
                     )
-                    fw.write(
-                        "#X %13.8f %13.8f %13.8f\n" % (box_x[0], box_x[1], box_x[2])
-                    )
-                    fw.write(
-                        "#Y %13.8f %13.8f %13.8f\n" % (box_y[0], box_y[1], box_y[2])
-                    )
-                    fw.write(
-                        "#Z %13.8f %13.8f %13.8f\n" % (box_z[0], box_z[1], box_z[2])
-                    )
+                    fw.write(f"#X {box_x[0]:13.8f} {box_x[1]:13.8f} {box_x[2]:13.8f}\n")
+                    fw.write(f"#Y {box_y[0]:13.8f} {box_y[1]:13.8f} {box_y[2]:13.8f}\n")
+                    fw.write(f"#Z {box_z[0]:13.8f} {box_z[1]:13.8f} {box_z[2]:13.8f}\n")
                     fw.write("#W %f\n" % (args.weight))
                     fw.write("#E %.10f\n" % (energy))
                     if stress:
@@ -303,7 +297,7 @@ def Parser():
         if item.endswith(".gz"):
             f = gzip.open(item, "rb")
         else:
-            f = open(item, "r")
+            f = open(item)
         data.append(scan_outcar_file(f))
         f.close()
         max_types = max(max_types, len(data[-1][1]))
@@ -350,7 +344,7 @@ def Parser():
 
     # process all the outcar files
     sr = args.configs_range
-    if sr == None:
+    if sr is None:
         windex = None
     else:
         sr = sr.split()
diff --git a/dpgen/data/tools/create_random_disturb.py b/dpgen/data/tools/create_random_disturb.py
index b8fb47dfa..591dee232 100755
--- a/dpgen/data/tools/create_random_disturb.py
+++ b/dpgen/data/tools/create_random_disturb.py
@@ -3,8 +3,6 @@
 import argparse
 import glob
 import os
-import shutil
-import sys
 
 import ase.io
 import numpy as np
@@ -244,9 +242,7 @@ def create_disturbs_abacus_dev(
 
 
 def create_random_alloys(fin, alloy_dist, ifmt="vasp", ofmt="vasp"):
-    """
-    In fact, atomsk also gives us the convinient tool to do this
-    """
+    """In fact, atomsk also gives us the convinient tool to do this."""
     # alloy_dist = {'Zr': 0.80, 'Nb': 0.20}
     atomic_symbols = alloy_dist.keys()
     atomic_ratios = alloy_dist.values()
diff --git a/dpgen/data/tools/diamond.py b/dpgen/data/tools/diamond.py
index 312872851..056ce9be9 100644
--- a/dpgen/data/tools/diamond.py
+++ b/dpgen/data/tools/diamond.py
@@ -19,18 +19,18 @@ def poscar_unit(latt):
     ret = ""
     ret += "DIAMOND\n"
     ret += "%.16f\n" % (latt)
-    ret += "%.16f %.16f %.16f\n" % (box[0][0], box[0][1], box[0][2])
-    ret += "%.16f %.16f %.16f\n" % (box[1][0], box[1][1], box[1][2])
-    ret += "%.16f %.16f %.16f\n" % (box[2][0], box[2][1], box[2][2])
+    ret += f"{box[0][0]:.16f} {box[0][1]:.16f} {box[0][2]:.16f}\n"
+    ret += f"{box[1][0]:.16f} {box[1][1]:.16f} {box[1][2]:.16f}\n"
+    ret += f"{box[2][0]:.16f} {box[2][1]:.16f} {box[2][2]:.16f}\n"
     ret += "Type\n"
     ret += "%d\n" % numb_atoms()
     ret += "Direct\n"
-    ret += "%.16f %.16f %.16f\n" % (
+    ret += "{:.16f} {:.16f} {:.16f}\n".format(
         0.12500000000000,
         0.12500000000000,
         0.12500000000000,
     )
-    ret += "%.16f %.16f %.16f\n" % (
+    ret += "{:.16f} {:.16f} {:.16f}\n".format(
         0.87500000000000,
         0.87500000000000,
         0.87500000000000,
diff --git a/dpgen/data/tools/fcc.py b/dpgen/data/tools/fcc.py
index f4576e3c4..80f0b476b 100644
--- a/dpgen/data/tools/fcc.py
+++ b/dpgen/data/tools/fcc.py
@@ -14,14 +14,14 @@ def poscar_unit(latt):
     ret = ""
     ret += "FCC : a = %f \n" % latt
     ret += "%.16f\n" % (latt)
-    ret += "%.16f %.16f %.16f\n" % (box[0][0], box[0][1], box[0][2])
-    ret += "%.16f %.16f %.16f\n" % (box[1][0], box[1][1], box[1][2])
-    ret += "%.16f %.16f %.16f\n" % (box[2][0], box[2][1], box[2][2])
+    ret += f"{box[0][0]:.16f} {box[0][1]:.16f} {box[0][2]:.16f}\n"
+    ret += f"{box[1][0]:.16f} {box[1][1]:.16f} {box[1][2]:.16f}\n"
+    ret += f"{box[2][0]:.16f} {box[2][1]:.16f} {box[2][2]:.16f}\n"
     ret += "Type\n"
     ret += "%d\n" % numb_atoms()
     ret += "Direct\n"
-    ret += "%.16f %.16f %.16f\n" % (0.0, 0.0, 0.0)
-    ret += "%.16f %.16f %.16f\n" % (0.5, 0.5, 0.0)
-    ret += "%.16f %.16f %.16f\n" % (0.5, 0.0, 0.5)
-    ret += "%.16f %.16f %.16f\n" % (0.0, 0.5, 0.5)
+    ret += f"{0.0:.16f} {0.0:.16f} {0.0:.16f}\n"
+    ret += f"{0.5:.16f} {0.5:.16f} {0.0:.16f}\n"
+    ret += f"{0.5:.16f} {0.0:.16f} {0.5:.16f}\n"
+    ret += f"{0.0:.16f} {0.5:.16f} {0.5:.16f}\n"
     return ret
diff --git a/dpgen/data/tools/hcp.py b/dpgen/data/tools/hcp.py
index 60c15f8aa..aeea4afc3 100644
--- a/dpgen/data/tools/hcp.py
+++ b/dpgen/data/tools/hcp.py
@@ -17,12 +17,12 @@ def poscar_unit(latt):
     ret = ""
     ret += "HCP : a = %f / sqrt(2)\n" % latt
     ret += "%.16f\n" % (latt / np.sqrt(2))
-    ret += "%.16f %.16f %.16f\n" % (box[0][0], box[0][1], box[0][2])
-    ret += "%.16f %.16f %.16f\n" % (box[1][0], box[1][1], box[1][2])
-    ret += "%.16f %.16f %.16f\n" % (box[2][0], box[2][1], box[2][2])
+    ret += f"{box[0][0]:.16f} {box[0][1]:.16f} {box[0][2]:.16f}\n"
+    ret += f"{box[1][0]:.16f} {box[1][1]:.16f} {box[1][2]:.16f}\n"
+    ret += f"{box[2][0]:.16f} {box[2][1]:.16f} {box[2][2]:.16f}\n"
     ret += "Type\n"
     ret += "%d\n" % numb_atoms()
     ret += "Direct\n"
-    ret += "%.16f %.16f %.16f\n" % (0, 0, 0)
-    ret += "%.16f %.16f %.16f\n" % (1.0 / 3, 1.0 / 3, 1.0 / 2)
+    ret += f"{0:.16f} {0:.16f} {0:.16f}\n"
+    ret += f"{1.0 / 3:.16f} {1.0 / 3:.16f} {1.0 / 2:.16f}\n"
     return ret
diff --git a/dpgen/data/tools/io_lammps.py b/dpgen/data/tools/io_lammps.py
index 35223c68b..e8c01d228 100755
--- a/dpgen/data/tools/io_lammps.py
+++ b/dpgen/data/tools/io_lammps.py
@@ -1,9 +1,7 @@
 #!/usr/bin/env python3
 
-"""
-
-ASE Atoms convert to LAMMPS configuration
-Some functions are adapted from ASE lammpsrun.py
+"""ASE Atoms convert to LAMMPS configuration
+Some functions are adapted from ASE lammpsrun.py.
 
 """
 
@@ -13,12 +11,12 @@
 
 
 def dir2car(v, A):
-    """Direct to cartesian coordinates"""
+    """Direct to cartesian coordinates."""
     return np.dot(v, A)
 
 
 def car2dir(v, Ainv):
-    """Cartesian to direct coordinates"""
+    """Cartesian to direct coordinates."""
     return np.dot(v, Ainv)
 
 
@@ -44,25 +42,22 @@ def stress6_to_stress9(s6):
 
 
 def is_upper_triangular(mat):
-    """
-    test if 3x3 matrix is upper triangular
-    LAMMPS has a rule for cell matrix definition
+    """Test if 3x3 matrix is upper triangular
+    LAMMPS has a rule for cell matrix definition.
     """
 
     def near0(x):
-        """Test if a float is within .00001 of 0"""
+        """Test if a float is within .00001 of 0."""
         return abs(x) < 0.00001
 
     return near0(mat[1, 0]) and near0(mat[2, 0]) and near0(mat[2, 1])
 
 
 def convert_cell(ase_cell):
-    """
-    Convert a parallel piped (forming right hand basis)
+    """Convert a parallel piped (forming right hand basis)
     to lower triangular matrix LAMMPS can accept. This
-    function transposes cell matrix so the bases are column vectors
+    function transposes cell matrix so the bases are column vectors.
     """
-
     # if ase_cell is lower triangular, cell is upper tri-angular
     cell = np.matrix.transpose(ase_cell)
 
@@ -190,10 +185,10 @@ def ase2lammpsdata(atoms, typeids=None, fout="out.lmp"):
     xz = cell[2, 0]
     yz = cell[2, 1]
 
-    fw.write("%f\t%f\t xlo xhi\n" % (0, xhi))
-    fw.write("%f\t%f\t ylo yhi\n" % (0, yhi))
-    fw.write("%f\t%f\t zlo zhi\n" % (0, zhi))
-    fw.write("%f\t%f\t%f\t xy xz yz\n" % (xy, xz, yz))
+    fw.write(f"{0:f}\t{xhi:f}\t xlo xhi\n")
+    fw.write(f"{0:f}\t{yhi:f}\t ylo yhi\n")
+    fw.write(f"{0:f}\t{zhi:f}\t zlo zhi\n")
+    fw.write(f"{xy:f}\t{xz:f}\t{yz:f}\t xy xz yz\n")
     fw.write("\n")
 
     # write mases
diff --git a/dpgen/data/tools/ovito_file_convert.py b/dpgen/data/tools/ovito_file_convert.py
index 5b3f19c7c..252b70b22 100755
--- a/dpgen/data/tools/ovito_file_convert.py
+++ b/dpgen/data/tools/ovito_file_convert.py
@@ -1,14 +1,10 @@
 #!/usr/bin/env ovitos
-"""
-This Script is adapted from Alexander Stukowski, the author of OVITO.
+"""This Script is adapted from Alexander Stukowski, the author of OVITO.
 See: http://forum.ovito.org/index.php?topic=131.0 for details.
 """
 import argparse
-import os
-import sys
 
-import numpy as np
-from ovito.io import *
+from ovito.io import export_file, import_file
 
 supp_ofmt = ["lammps_dump", "lammps_data", "vasp"]
 supp_exts = ["dump", "lmp", "poscar/POSCAR"]
@@ -35,7 +31,7 @@
         ofmt = "lammps_data"
     elif ext == "poscar" or ext == "POSCAR":
         ofmt = "vasp"
-if not ofmt in supp_ofmt:
+if ofmt not in supp_ofmt:
     raise RuntimeError(
         "output format " + ofmt + " is not supported. use one of " + str(supp_ofmt)
     )
diff --git a/dpgen/data/tools/poscar_copy.py b/dpgen/data/tools/poscar_copy.py
index 24aab403b..fcae43ffe 100755
--- a/dpgen/data/tools/poscar_copy.py
+++ b/dpgen/data/tools/poscar_copy.py
@@ -2,9 +2,8 @@
 
 import argparse
 
-import numpy as np
-from ovito.io import *
-from ovito.modifiers import *
+from ovito.io import export_file, import_file
+from ovito.modifiers import ShowPeriodicImagesModifier
 
 
 def copy_system(ncopy, fin, fout):
diff --git a/dpgen/data/tools/sc.py b/dpgen/data/tools/sc.py
index 2c2c0671a..fff019d6d 100644
--- a/dpgen/data/tools/sc.py
+++ b/dpgen/data/tools/sc.py
@@ -14,11 +14,11 @@ def poscar_unit(latt):
     ret = ""
     ret += "SC : a = %f \n" % latt
     ret += "%.16f\n" % (latt)
-    ret += "%.16f %.16f %.16f\n" % (box[0][0], box[0][1], box[0][2])
-    ret += "%.16f %.16f %.16f\n" % (box[1][0], box[1][1], box[1][2])
-    ret += "%.16f %.16f %.16f\n" % (box[2][0], box[2][1], box[2][2])
+    ret += f"{box[0][0]:.16f} {box[0][1]:.16f} {box[0][2]:.16f}\n"
+    ret += f"{box[1][0]:.16f} {box[1][1]:.16f} {box[1][2]:.16f}\n"
+    ret += f"{box[2][0]:.16f} {box[2][1]:.16f} {box[2][2]:.16f}\n"
     ret += "Type\n"
     ret += "%d\n" % numb_atoms()
     ret += "Direct\n"
-    ret += "%.16f %.16f %.16f\n" % (0.0, 0.0, 0.0)
+    ret += f"{0.0:.16f} {0.0:.16f} {0.0:.16f}\n"
     return ret
diff --git a/dpgen/database/__init__.py b/dpgen/database/__init__.py
index fadd65267..8352dda9b 100644
--- a/dpgen/database/__init__.py
+++ b/dpgen/database/__init__.py
@@ -1,2 +1,4 @@
 from .entry import Entry
 from .vasp import DPPotcar, VaspInput
+
+__all__ = ["Entry", "DPPotcar", "VaspInput"]
diff --git a/dpgen/database/entry.py b/dpgen/database/entry.py
index 41da89320..95563af9c 100644
--- a/dpgen/database/entry.py
+++ b/dpgen/database/entry.py
@@ -1,17 +1,11 @@
 # /usr/bin/env python
-# coding: utf-8
 # Copyright (c) The Dpmodeling Team.
 
 import json
-import warnings
-from uuid import uuid4
 
-from dpdata import LabeledSystem, System
 from monty.json import MontyDecoder, MontyEncoder, MSONable
 from pymatgen.core.composition import Composition
 
-from dpgen.database.vasp import VaspInput
-
 """
 This module implements equivalents of the basic Entry objects, which
 is the basic entity that can be used to perform many analyses. Entries
@@ -21,10 +15,30 @@
 
 
 class Entry(MSONable):
-    """
-    An lightweight Entry object containing key computed data
+    """An lightweight Entry object containing key computed data
     for storing purpose.
 
+    Parameters
+    ----------
+    composition : Composition
+        Composition of the entry. For
+        flexibility, this can take the form of all the typical input
+        taken by a Composition, including a {symbol: amt} dict,
+        a string formula, and others.
+    inputs : dict
+        An dict of parameters associated with
+        the entry. Defaults to None.
+    data : dict
+        An dict of any additional data associated
+        with the entry. Defaults to None.
+    entry_id : obj
+        An optional id to uniquely identify the entry.
+    attribute :
+        Optional attribute of the entry. This can be used to
+        specify that the entry is a newly found compound, or to specify
+        a particular label for the entry, or else ... Used for further
+        analysis and plotting purposes. An attribute can be anything
+        but must be MSONable.
     """
 
     def __init__(
@@ -37,25 +51,7 @@ def __init__(
         attribute=None,
         tag=None,
     ):
-        """
-        Initializes a Entry.
-
-        Args:
-            composition (Composition): Composition of the entry. For
-                flexibility, this can take the form of all the typical input
-                taken by a Composition, including a {symbol: amt} dict,
-                a string formula, and others.
-            inputs (dict): An dict of parameters associated with
-                the entry. Defaults to None.
-            data (dict): An dict of any additional data associated
-                with the entry. Defaults to None.
-            entry_id (obj): An optional id to uniquely identify the entry.
-            attribute: Optional attribute of the entry. This can be used to
-                specify that the entry is a newly found compound, or to specify
-                a particular label for the entry, or else ... Used for further
-                analysis and plotting purposes. An attribute can be anything
-                but must be MSONable.
-        """
+        """Initializes a Entry."""
         self.composition = Composition(composition)
         self.calculator = calculator
         self.inputs = inputs
@@ -88,8 +84,8 @@ def number_element(self):
 
     def __repr__(self):
         output = [
-            "Entry {} - {}".format(self.entry_id, self.composition.formula),
-            "calculator: {}".format(self.calculator),
+            f"Entry {self.entry_id} - {self.composition.formula}",
+            f"calculator: {self.calculator}",
         ]
         return "\n".join(output)
 
diff --git a/dpgen/database/run.py b/dpgen/database/run.py
index 8a2df327d..2930d3f70 100644
--- a/dpgen/database/run.py
+++ b/dpgen/database/run.py
@@ -1,17 +1,12 @@
 # /usr/bin/env python
-# coding: utf-8
 # Copyright (c) The Dpmodeling Team.
 
 import json
 import os
-import time
-import traceback
 from glob import glob
-from threading import Thread
 from uuid import uuid4
 
-import numpy as np
-from dpdata import LabeledSystem, System
+from dpdata import LabeledSystem
 from monty.serialization import dumpfn, loadfn
 
 from dpgen import SHORT_CMD, dlog
@@ -32,7 +27,7 @@ def db_run(args):
 
 
 def _main(param):
-    with open(param, "r") as fp:
+    with open(param) as fp:
         jdata = json.load(fp)
     calculator = jdata["calculator"]
     path = jdata["path"]
@@ -82,7 +77,7 @@ def _parsing_vasp(paths, config_info_dict, id_prefix, iters=True):
         iter_record = []
         iter_record_new = []
         try:
-            with open("record.database", "r") as f_record:
+            with open("record.database") as f_record:
                 iter_record = [i.split()[0] for i in f_record.readlines()]
             iter_record.sort()
             dlog.info("iter_record")
@@ -120,7 +115,7 @@ def _parsing_vasp(paths, config_info_dict, id_prefix, iters=True):
                 attrib["task_info"] = task_info
                 attrib["iter_info"] = iter_info
                 attrib["sys_info"] = sys_info
-                with open(f_outcar, "r") as fin_outcar:
+                with open(f_outcar) as fin_outcar:
                     infile_outcar = fin_outcar.readlines()
                 for line in infile_outcar:
                     if "running on" in line:
diff --git a/dpgen/database/vasp.py b/dpgen/database/vasp.py
index dcbef299d..7b4f94d6a 100644
--- a/dpgen/database/vasp.py
+++ b/dpgen/database/vasp.py
@@ -1,5 +1,4 @@
 # /usr/bin/env python
-# coding: utf-8
 # Copyright (c) PThe Dpmodeling Team.
 
 
@@ -19,13 +18,13 @@
 
 class DPPotcar(MSONable):
     def __init__(self, symbols=None, functional="PBE", pp_file=None, pp_lists=None):
-        if pp_lists and pp_file is None:
+        if pp_lists is not None and pp_file is None:
             for pp in pp_lists:
                 assert isinstance(pp, PotcarSingle)
             self.potcars = pp_lists
-        elif pp_file and pp_list is None:
+        elif pp_file is not None and pp_lists is None:
             self.potcars = Potcar.from_file(pp_file)
-        elif pp_file and pp_list:
+        elif pp_file is not None and pp_lists is not None:
             self.potcars = Potcar.from_file(pp_file)
         else:
             try:
@@ -84,7 +83,7 @@ def from_file(cls, filename):
             potcars = Potcar.from_file(filename)
             return cls(pp_lists=potcars)
         except Exception:
-            with open(filename, "r") as f:
+            with open(filename) as f:
                 content = f.readlines()
             functional = content[0].strip().split(":")[-1].strip()
             symbols = content[1].strip().split()
@@ -96,10 +95,10 @@ def write_file(self, filename):
 
 
 class VaspInput(dict, MSONable):
-    """
-    Class to contain a set of vasp input objects corresponding to a run.
+    """Class to contain a set of vasp input objects corresponding to a run.
 
     Args:
+    ----
         incar: Incar object.
         kpoints: Kpoints object.
         poscar: Poscar object.
@@ -146,14 +145,16 @@ def from_dict(cls, d):
         return cls(**sub_d)
 
     def write_input(self, output_dir=".", make_dir_if_not_present=True):
-        """
-        Write VASP input to a directory.
-
-        Args:
-            output_dir (str): Directory to write to. Defaults to current
-                directory (".").
-            make_dir_if_not_present (bool): Create the directory if not
-                present. Defaults to True.
+        """Write VASP input to a directory.
+
+        Parameters
+        ----------
+        output_dir : str
+            Directory to write to. Defaults to current
+            directory (".").
+        make_dir_if_not_present : bool
+            Create the directory if not
+            present. Defaults to True.
         """
         if make_dir_if_not_present and not os.path.exists(output_dir):
             os.makedirs(output_dir)
@@ -163,16 +164,18 @@ def write_input(self, output_dir=".", make_dir_if_not_present=True):
 
     @staticmethod
     def from_directory(input_dir, optional_files=None):
-        """
-        Read in a set of VASP input from a directory. Note that only the
+        """Read in a set of VASP input from a directory. Note that only the
         standard INCAR, POSCAR, POTCAR and KPOINTS files are read unless
         optional_filenames is specified.
 
-        Args:
-            input_dir (str): Directory to read VASP input from.
-            optional_files (dict): Optional files to read in as well as a
-                dict of {filename: Object type}. Object type must have a
-                static method from_file.
+        Parameters
+        ----------
+        input_dir : str
+            Directory to read VASP input from.
+        optional_files : dict
+            Optional files to read in as well as a
+            dict of {filename: Object type}. Object type must have a
+            static method from_file.
         """
         sub_d = {}
         try:
diff --git a/dpgen/dispatcher/Dispatcher.py b/dpgen/dispatcher/Dispatcher.py
index 0d9e43f16..27399dfed 100644
--- a/dpgen/dispatcher/Dispatcher.py
+++ b/dpgen/dispatcher/Dispatcher.py
@@ -21,7 +21,7 @@ def make_submission(
     errlog,
 ):
     if mdata_machine["local_root"] != "./":
-        raise RuntimeError(f"local_root must be './' in dpgen's machine.json.")
+        raise RuntimeError("local_root must be './' in dpgen's machine.json.")
 
     abs_local_root = os.path.abspath("./")
 
diff --git a/dpgen/generator/arginfo.py b/dpgen/generator/arginfo.py
index 7d2835d8a..bdfdccb6f 100644
--- a/dpgen/generator/arginfo.py
+++ b/dpgen/generator/arginfo.py
@@ -1,5 +1,5 @@
 import textwrap
-from typing import Dict, List
+from typing import List
 
 from dargs import Argument, Variant
 
diff --git a/dpgen/generator/lib/abacus_scf.py b/dpgen/generator/lib/abacus_scf.py
index 96ae2fe98..6a8ea3213 100644
--- a/dpgen/generator/lib/abacus_scf.py
+++ b/dpgen/generator/lib/abacus_scf.py
@@ -191,7 +191,7 @@ def make_abacus_scf_input(fp_params, extra_file_path=""):
         elif key == "calculation":
             pass
         else:
-            ret += "%s %s\n" % (key, str(fp_params[key]))
+            ret += f"{key} {str(fp_params[key])}\n"
     return ret
 
 
@@ -206,7 +206,7 @@ def make_abacus_scf_stru(
 ):
     atom_names = sys_data["atom_names"]
     atom_numbs = sys_data["atom_numbs"]
-    if type_map == None:
+    if type_map is None:
         type_map = atom_names
 
     assert len(atom_names) == len(atom_numbs), "Please check the name of atoms. "
@@ -376,7 +376,7 @@ def get_additional_from_STRU(geometry_inlines, nele):
 def get_abacus_STRU(STRU, INPUT=None, n_ele=None):
     # read in geometry from STRU file. n_ele is the number of elements.
     # Either n_ele or INPUT should be provided.
-    with open(STRU, "r") as fp:
+    with open(STRU) as fp:
         geometry_inlines = fp.read().split("\n")
     for iline, line in enumerate(geometry_inlines):
         if line.split() == [] or len(line) == 0:
diff --git a/dpgen/generator/lib/calypso_check_outcar.py b/dpgen/generator/lib/calypso_check_outcar.py
index e3982335e..668131669 100644
--- a/dpgen/generator/lib/calypso_check_outcar.py
+++ b/dpgen/generator/lib/calypso_check_outcar.py
@@ -1,14 +1,8 @@
 #!/usr/bin/env python3
-# -*- coding: utf-8 -*-
 
-import glob
 import os
-import sys
-import time
 
 import numpy as np
-from ase.io import read
-from deepmd.calculator import DP
 
 """
 check if structure optimization worked well
@@ -17,7 +11,7 @@
 
 
 def Get_Element_Num(elements):
-    """Using the Atoms.symples to Know Element&Num"""
+    """Using the Atoms.symples to Know Element&Num."""
     element = []
     ele = {}
     element.append(elements[0])
@@ -30,12 +24,12 @@ def Get_Element_Num(elements):
 
 
 def Write_Contcar(element, ele, lat, pos):
-    """Write CONTCAR"""
+    """Write CONTCAR."""
     f = open("CONTCAR", "w")
     f.write("ASE-DPKit-FAILED-nan\n")
     f.write("1.0\n")
     for i in range(3):
-        f.write("%15.10f %15.10f %15.10f\n" % tuple(lat[i]))
+        f.write("{:15.10f} {:15.10f} {:15.10f}\n".format(*tuple(lat[i])))
     for x in element:
         f.write(x + "  ")
     f.write("\n")
@@ -46,11 +40,11 @@ def Write_Contcar(element, ele, lat, pos):
     na = sum(ele.values())
     dpos = np.dot(pos, np.linalg.inv(lat))
     for i in range(na):
-        f.write("%15.10f %15.10f %15.10f\n" % tuple(dpos[i]))
+        f.write("{:15.10f} {:15.10f} {:15.10f}\n".format(*tuple(dpos[i])))
 
 
 def Write_Outcar(element, ele, volume, lat, pos, ene, force, stress, pstress):
-    """Write OUTCAR"""
+    """Write OUTCAR."""
     f = open("OUTCAR", "w")
     for x in element:
         f.write("VRHFIN =" + str(x) + "\n")
@@ -70,23 +64,22 @@ def Write_Outcar(element, ele, volume, lat, pos, ene, force, stress, pstress):
     f.write("\n")
     ext_pressure = np.sum(stress[0] + stress[1] + stress[2]) / 3.0 - pstress
     f.write(
-        "external pressure = %20.6f kB    Pullay stress = %20.6f  kB\n"
-        % (ext_pressure, pstress)
+        f"external pressure = {ext_pressure:20.6f} kB    Pullay stress = {pstress:20.6f}  kB\n"
     )
     f.write("volume of cell : %20.6f\n" % volume)
     f.write("direct lattice vectors\n")
     for i in range(3):
-        f.write("%10.6f %10.6f %10.6f\n" % tuple(lat[i]))
+        f.write("{:10.6f} {:10.6f} {:10.6f}\n".format(*tuple(lat[i])))
     f.write("POSITION                                       TOTAL-FORCE(eV/Angst)\n")
     f.write("-------------------------------------------------------------------\n")
     na = sum(ele.values())
     for i in range(na):
-        f.write("%15.6f %15.6f %15.6f" % tuple(pos[i]))
-        f.write("%15.6f %15.6f %15.6f\n" % tuple(force[i]))
+        f.write("{:15.6f} {:15.6f} {:15.6f}".format(*tuple(pos[i])))
+        f.write("{:15.6f} {:15.6f} {:15.6f}\n".format(*tuple(force[i])))
     f.write("-------------------------------------------------------------------\n")
-    f.write("energy  without entropy= %20.6f %20.6f\n" % (ene, ene))
+    f.write(f"energy  without entropy= {ene:20.6f} {ene:20.6f}\n")
     enthalpy = ene + pstress * volume / 1602.17733
-    f.write("enthalpy is  TOTEN    = %20.6f %20.6f\n" % (enthalpy, enthalpy))
+    f.write(f"enthalpy is  TOTEN    = {enthalpy:20.6f} {enthalpy:20.6f}\n")
 
 
 def check():
diff --git a/dpgen/generator/lib/calypso_run_model_devi.py b/dpgen/generator/lib/calypso_run_model_devi.py
index 1f656cc59..5ad3f70bb 100644
--- a/dpgen/generator/lib/calypso_run_model_devi.py
+++ b/dpgen/generator/lib/calypso_run_model_devi.py
@@ -4,7 +4,6 @@
 import math
 import os
 import shutil
-import sys
 
 import dpdata
 import numpy as np
@@ -22,7 +21,7 @@ def write_model_devi_out(devi, fname):
             f"min_devi_{item}",
             f"avg_devi_{item}",
         )
-    header += "%16s" % str("min_dis")
+    header += "%16s" % "min_dis"
     np.savetxt(
         fname,
         devi,
diff --git a/dpgen/generator/lib/calypso_run_opt.py b/dpgen/generator/lib/calypso_run_opt.py
index 99c0fec80..9cb94f958 100644
--- a/dpgen/generator/lib/calypso_run_opt.py
+++ b/dpgen/generator/lib/calypso_run_opt.py
@@ -1,15 +1,12 @@
 #!/usr/bin/env python3
-# -*- coding: utf-8 -*-
 
-import glob
 import os
-import sys
 import time
 
 import numpy as np
-from ase.constraints import ExpCellFilter, UnitCellFilter
+from ase.constraints import UnitCellFilter
 from ase.io import read
-from ase.optimize import BFGS, LBFGS, QuasiNewton
+from ase.optimize import LBFGS
 from deepmd.calculator import DP
 
 """
@@ -19,7 +16,7 @@
 
 
 def Get_Element_Num(elements):
-    """Using the Atoms.symples to Know Element&Num"""
+    """Using the Atoms.symples to Know Element&Num."""
     element = []
     ele = {}
     element.append(elements[0])
@@ -32,12 +29,12 @@ def Get_Element_Num(elements):
 
 
 def Write_Contcar(element, ele, lat, pos):
-    """Write CONTCAR"""
+    """Write CONTCAR."""
     f = open("CONTCAR", "w")
     f.write("ASE-DPKit-Optimization\n")
     f.write("1.0\n")
     for i in range(3):
-        f.write("%15.10f %15.10f %15.10f\n" % tuple(lat[i]))
+        f.write("{:15.10f} {:15.10f} {:15.10f}\n".format(*tuple(lat[i])))
     for x in element:
         f.write(x + "  ")
     f.write("\n")
@@ -48,11 +45,11 @@ def Write_Contcar(element, ele, lat, pos):
     na = sum(ele.values())
     dpos = np.dot(pos, np.linalg.inv(lat))
     for i in range(na):
-        f.write("%15.10f %15.10f %15.10f\n" % tuple(dpos[i]))
+        f.write("{:15.10f} {:15.10f} {:15.10f}\n".format(*tuple(dpos[i])))
 
 
 def Write_Outcar(element, ele, volume, lat, pos, ene, force, stress, pstress):
-    """Write OUTCAR"""
+    """Write OUTCAR."""
     f = open("OUTCAR", "w")
     for x in element:
         f.write("VRHFIN =" + str(x) + "\n")
@@ -72,23 +69,22 @@ def Write_Outcar(element, ele, volume, lat, pos, ene, force, stress, pstress):
     f.write("\n")
     ext_pressure = np.sum(stress[0] + stress[1] + stress[2]) / 3.0 - pstress
     f.write(
-        "external pressure = %20.6f kB    Pullay stress = %20.6f  kB\n"
-        % (ext_pressure, pstress)
+        f"external pressure = {ext_pressure:20.6f} kB    Pullay stress = {pstress:20.6f}  kB\n"
     )
     f.write("volume of cell : %20.6f\n" % volume)
     f.write("direct lattice vectors\n")
     for i in range(3):
-        f.write("%10.6f %10.6f %10.6f\n" % tuple(lat[i]))
+        f.write("{:10.6f} {:10.6f} {:10.6f}\n".format(*tuple(lat[i])))
     f.write("POSITION                                       TOTAL-FORCE(eV/Angst)\n")
     f.write("-------------------------------------------------------------------\n")
     na = sum(ele.values())
     for i in range(na):
-        f.write("%15.6f %15.6f %15.6f" % tuple(pos[i]))
-        f.write("%15.6f %15.6f %15.6f\n" % tuple(force[i]))
+        f.write("{:15.6f} {:15.6f} {:15.6f}".format(*tuple(pos[i])))
+        f.write("{:15.6f} {:15.6f} {:15.6f}\n".format(*tuple(force[i])))
     f.write("-------------------------------------------------------------------\n")
-    f.write("energy  without entropy= %20.6f %20.6f\n" % (ene, ene / na))
+    f.write(f"energy  without entropy= {ene:20.6f} {ene / na:20.6f}\n")
     enthalpy = ene + pstress * volume / 1602.17733
-    f.write("enthalpy is  TOTEN    = %20.6f %20.6f\n" % (enthalpy, enthalpy / na))
+    f.write(f"enthalpy is  TOTEN    = {enthalpy:20.6f} {enthalpy / na:20.6f}\n")
 
 
 def read_stress_fmax():
@@ -96,12 +92,12 @@ def read_stress_fmax():
     fmax = 0.01
     # assert os.path.exists('./input.dat'), 'input.dat does not exist!'
     try:
-        f = open("input.dat", "r")
-    except:
+        f = open("input.dat")
+    except Exception:
         assert os.path.exists(
             "../input.dat"
         ), " now we are in %s, do not find ../input.dat" % (os.getcwd())
-        f = open("../input.dat", "r")
+        f = open("../input.dat")
     lines = f.readlines()
     f.close()
     for line in lines:
@@ -115,8 +111,7 @@ def read_stress_fmax():
 
 
 def run_opt(fmax, stress):
-    """Using the ASE&DP to Optimize Configures"""
-
+    """Using the ASE&DP to Optimize Configures."""
     calc = DP(model="../graph.000.pb")  # init the model before iteration
     os.system("mv OUTCAR OUTCAR-last")
 
@@ -165,7 +160,7 @@ def run_opt(fmax, stress):
     stop = time.time()
     _cwd = os.getcwd()
     _cwd = os.path.basename(_cwd)
-    print("%s is done, time: %s" % (_cwd, stop - start))
+    print(f"{_cwd} is done, time: {stop - start}")
 
 
 def run():
diff --git a/dpgen/generator/lib/cp2k.py b/dpgen/generator/lib/cp2k.py
index 2bfede252..4ab9ae4c5 100644
--- a/dpgen/generator/lib/cp2k.py
+++ b/dpgen/generator/lib/cp2k.py
@@ -1,4 +1,3 @@
-import dpdata
 import numpy as np
 
 default_config = {
@@ -32,10 +31,9 @@
 
 
 def update_dict(old_d, update_d):
-    """
-    a method to recursive update dict
+    """A method to recursive update dict
     :old_d: old dictionary
-    :update_d: some update value written in dictionary form
+    :update_d: some update value written in dictionary form.
     """
     import collections.abc
 
@@ -51,8 +49,7 @@ def update_dict(old_d, update_d):
 
 
 def iterdict(d, out_list, flag=None):
-    """
-    :doc: a recursive expansion of dictionary into cp2k input
+    """:doc: a recursive expansion of dictionary into cp2k input
     :k: current key
     :v: current value
     :d: current dictionary under expansion
@@ -64,7 +61,7 @@ def iterdict(d, out_list, flag=None):
         # if value is dictionary
         if isinstance(v, dict):
             # flag == None, it is now in top level section of cp2k
-            if flag == None:
+            if flag is None:
                 out_list.append("&" + k)
                 out_list.append("&END " + k)
                 iterdict(v, out_list, k)
@@ -98,7 +95,7 @@ def iterdict(d, out_list, flag=None):
 
         else:
             v = str(v)
-            if flag == None:
+            if flag is None:
                 out_list.append(k + " " + v)
                 print(k, ":", v)
             else:
@@ -154,7 +151,7 @@ def make_cp2k_xyz(sys_data):
 
 def make_cp2k_input_from_external(sys_data, exinput_path):
     # read the input content as string
-    with open(exinput_path, "r") as f:
+    with open(exinput_path) as f:
         exinput = f.readlines()
 
     # find the ABC cell string
diff --git a/dpgen/generator/lib/cvasp.py b/dpgen/generator/lib/cvasp.py
index d98d549d4..d4d98f770 100644
--- a/dpgen/generator/lib/cvasp.py
+++ b/dpgen/generator/lib/cvasp.py
@@ -1,5 +1,4 @@
 #!/usr/bin/env python3
-# -*- coding: utf-8 -*-
 
 import argparse
 
@@ -37,9 +36,8 @@ def runvasp(
     auto_npar=False,
     ediffg=-0.05,
 ):
-    """
-    cmd example:
-    cmd=['mpirun', '-np', '32' , '-machinefile', 'hosts','vasp_std']
+    """Cmd example:
+    cmd=['mpirun', '-np', '32' , '-machinefile', 'hosts','vasp_std'].
     """
     if opt:
         jobs = cvj.full_opt_run(
diff --git a/dpgen/generator/lib/ele_temp.py b/dpgen/generator/lib/ele_temp.py
index e2396b6fe..15e1b802c 100644
--- a/dpgen/generator/lib/ele_temp.py
+++ b/dpgen/generator/lib/ele_temp.py
@@ -1,4 +1,3 @@
-import json
 import os
 
 import dpdata
@@ -7,7 +6,7 @@
 from pymatgen.io.vasp.inputs import Incar
 
 
-class NBandsEsti(object):
+class NBandsEsti:
     def __init__(self, test_list):
         if type(test_list) is list:
             ele_t = []
diff --git a/dpgen/generator/lib/gaussian.py b/dpgen/generator/lib/gaussian.py
index eb4c919f2..dca371ee1 100644
--- a/dpgen/generator/lib/gaussian.py
+++ b/dpgen/generator/lib/gaussian.py
@@ -72,7 +72,7 @@ def _crd2mul(symbols, crds):
             f"{atomnumber}\nDPGEN\n",
             "\n".join(
                 [
-                    "{:2s} {:22.15f} {:22.15f} {:22.15f}".format(s, x, y, z)
+                    f"{s:2s} {x:22.15f} {y:22.15f} {z:22.15f}"
                     for s, (x, y, z) in zip(symbols, crds)
                 ]
             ),
@@ -167,20 +167,20 @@ def make_gaussian_input(sys_data, fp_params):
     buff = []
     # keywords, e.g., force b3lyp/6-31g**
     if use_fragment_guesses:
-        keywords[0] = "{} guess=fragment={}".format(keywords[0], frag_numb)
+        keywords[0] = f"{keywords[0]} guess=fragment={frag_numb}"
 
     chkkeywords = []
     if len(keywords) > 1:
-        chkkeywords.append("%chk={}.chk".format(str(uuid.uuid1())))
+        chkkeywords.append(f"%chk={str(uuid.uuid1())}.chk")
 
-    nprockeywords = "%nproc={:d}".format(nproc)
+    nprockeywords = f"%nproc={nproc:d}"
     titlekeywords = "DPGEN"
-    chargekeywords = "{} {}".format(charge, multiplicity)
+    chargekeywords = f"{charge} {multiplicity}"
 
     buff = [
         *chkkeywords,
         nprockeywords,
-        "#{}".format(keywords[0]),
+        f"#{keywords[0]}",
         "",
         titlekeywords,
         "",
@@ -193,7 +193,7 @@ def make_gaussian_input(sys_data, fp_params):
                 "%s(Fragment=%d) %f %f %f" % (symbol, frag_index[ii] + 1, *coordinate)
             )
         else:
-            buff.append("%s %f %f %f" % (symbol, *coordinate))
+            buff.append("{} {:f} {:f} {:f}".format(symbol, *coordinate))
     if "basis_set" in fp_params:
         # custom basis set
         buff.extend(["", fp_params["basis_set"], ""])
@@ -203,7 +203,7 @@ def make_gaussian_input(sys_data, fp_params):
                 "\n--link1--",
                 *chkkeywords,
                 nprockeywords,
-                "#{}".format(kw),
+                f"#{kw}",
                 "",
                 titlekeywords,
                 "",
diff --git a/dpgen/generator/lib/lammps.py b/dpgen/generator/lib/lammps.py
index bd32fd562..0da9c8346 100644
--- a/dpgen/generator/lib/lammps.py
+++ b/dpgen/generator/lib/lammps.py
@@ -1,9 +1,6 @@
 #!/usr/bin/env python3
 
-import os
 import random
-import subprocess as sp
-import sys
 
 import dpdata
 import numpy as np
@@ -101,10 +98,7 @@ def make_lammps_input(
             keywords += "fparam ${ELE_TEMP}"
         if ele_temp_a is not None:
             keywords += "aparam ${ELE_TEMP}"
-        ret += (
-            "pair_style      deepmd %s out_freq ${THERMO_FREQ} out_file model_devi.out %s\n"
-            % (graph_list, keywords)
-        )
+        ret += f"pair_style      deepmd {graph_list} out_freq ${{THERMO_FREQ}} out_file model_devi.out {keywords}\n"
     ret += "pair_coeff      * *\n"
     ret += "\n"
     ret += "thermo_style    custom step temp pe ke etotal press vol lx ly lz xy xz yz\n"
@@ -135,7 +129,7 @@ def make_lammps_input(
         pka_vec = _sample_sphere()
         pka_vec *= pka_vn
         ret += "group           first id 1\n"
-        ret += 'if "${restart} == 0" then "velocity        first set %f %f %f"\n' % (
+        ret += 'if "${{restart}} == 0" then "velocity        first set {:f} {:f} {:f}"\n'.format(
             pka_vec[0],
             pka_vec[1],
             pka_vec[2],
diff --git a/dpgen/generator/lib/make_calypso.py b/dpgen/generator/lib/make_calypso.py
index 2758d76df..b4d84da49 100644
--- a/dpgen/generator/lib/make_calypso.py
+++ b/dpgen/generator/lib/make_calypso.py
@@ -6,8 +6,6 @@
 
 import numpy as np
 
-from dpgen.generator.lib.utils import create_path
-
 
 def make_calypso_input(
     nameofatoms,
@@ -233,7 +231,7 @@ def write_model_devi_out(devi, fname):
             f"min_devi_{item}",
             f"avg_devi_{item}",
         )
-    header += "%16s" % str("min_dis")
+    header += "%16s" % "min_dis"
     np.savetxt(
         fname,
         devi,
diff --git a/dpgen/generator/lib/parse_calypso.py b/dpgen/generator/lib/parse_calypso.py
index 81b2147c2..460d478b6 100644
--- a/dpgen/generator/lib/parse_calypso.py
+++ b/dpgen/generator/lib/parse_calypso.py
@@ -9,7 +9,7 @@ def _parse_calypso_input(var, input_path):
     if not os.path.exists(input_path):
         raise FileNotFoundError(input_path)
 
-    f = open(input_path, "r")
+    f = open(input_path)
     lines = f.readlines()
     f.close()
 
@@ -21,9 +21,9 @@ def _parse_calypso_input(var, input_path):
 
 def _parse_calypso_dis_mtx(numberofspecies, input_path):
     try:
-        f = open(input_path, "r")
-    except:
-        f = open(os.path.join(input_path, "input.dat"), "r")
+        f = open(input_path)
+    except Exception:
+        f = open(os.path.join(input_path, "input.dat"))
     while True:
         line = f.readline()
         if len(line) == 0:
diff --git a/dpgen/generator/lib/pwmat.py b/dpgen/generator/lib/pwmat.py
index 06ef0ddf3..c2100ee69 100644
--- a/dpgen/generator/lib/pwmat.py
+++ b/dpgen/generator/lib/pwmat.py
@@ -1,6 +1,5 @@
 #!/usr/bin/python3
 
-import os
 
 import numpy as np
 
@@ -18,7 +17,7 @@ def _make_pwmat_kp_mp(kpoints):
 
 
 def _make_kspacing_kpoints(config, kspacing):
-    with open(config, "r") as fp:
+    with open(config) as fp:
         lines = fp.read().split("\n")
     box = []
     for idx, ii in enumerate(lines):
@@ -63,8 +62,8 @@ def make_pwmat_input_dict(
                     "94 4 3 " + str(icmix) + " " + str(sigma) + " " + str(smearing)
                 )
             else:
-                SCF_ITER0_1 = "6 4 3 0.0000 " + str(simga) + " 2"
-                SCF_ITER0_2 = "94 4 3 " + str(icmix) + " " + str(simga) + " 2"
+                SCF_ITER0_1 = "6 4 3 0.0000 " + str(sigma) + " 2"
+                SCF_ITER0_2 = "94 4 3 " + str(icmix) + " " + str(sigma) + " 2"
 
         else:
             if smearing is not None:
@@ -107,7 +106,7 @@ def _update_input_dict(input_dict_, user_dict):
         return input_dict_
     input_dict = input_dict_
     for ii in user_dict:
-        input_dict[ci] = user_dict[ii]
+        input_dict[ii] = user_dict[ii]
     return input_dict
 
 
@@ -121,7 +120,7 @@ def write_input_dict(input_dict):
                 rs = "F"
         else:
             rs = str(input_dict[key])
-        lines.append("%s=%s" % (key, rs))
+        lines.append(f"{key}={rs}")
     return "\n".join(lines)
 
 
@@ -135,25 +134,25 @@ def _make_smearing(fp_params):
         smearing = fp_params["smearing"]
     if "sigma" in fp_params:
         sigma = fp_params["sigma"]
-    if icmix == None:
-        if smearing == None:
-            if sigma == None:
+    if icmix is None:
+        if smearing is None:
+            if sigma is None:
                 return None, None, None
             else:
                 return None, None, sigma
         else:
-            if sigma == None:
+            if sigma is None:
                 return None, smearing, None
             else:
                 return None, smearing, sigma
     else:
-        if smearing == None:
-            if sigma == None:
+        if smearing is None:
+            if sigma is None:
                 return icmix, None, None
             else:
                 return icmix, None, sigma
         else:
-            if sigma == None:
+            if sigma is None:
                 return icmix, smearing, None
             else:
                 return icmix, smearing, sigma
@@ -206,4 +205,5 @@ def input_upper(dinput):
     standard_input = {}
     for key, val in dinput.items():
         standard_input[key.upper()] = val
-    return Input(standard_input)
+    # return Input(standard_input)
+    return standard_input
diff --git a/dpgen/generator/lib/pwscf.py b/dpgen/generator/lib/pwscf.py
index bc3c6bab3..39d3174b3 100644
--- a/dpgen/generator/lib/pwscf.py
+++ b/dpgen/generator/lib/pwscf.py
@@ -17,7 +17,7 @@ def _convert_dict(idict):
             ws = "'" + idict[key] + "'"
         else:
             ws = str(idict[key])
-        lines.append("%s=%s," % (key, ws))
+        lines.append(f"{key}={ws},")
     return lines
 
 
@@ -110,7 +110,7 @@ def _make_pwscf_03_config(sys_data):
     cc = 0
     for ii in range(ntypes):
         for jj in range(atom_numbs[ii]):
-            ret += "%s %f %f %f\n" % (
+            ret += "{} {:f} {:f} {:f}\n".format(
                 atom_names[ii],
                 coordinates[cc][0],
                 coordinates[cc][1],
@@ -157,7 +157,7 @@ def _make_smearing(fp_params):
         degauss = fp_params["sigma"]
     if (smearing is not None) and (smearing.split(":")[0] == "mp"):
         smearing = "mp"
-    if not (smearing in [None, "gauss", "mp", "fd"]):
+    if smearing not in [None, "gauss", "mp", "fd"]:
         raise RuntimeError("unknow smearing method " + smearing)
     return smearing, degauss
 
diff --git a/dpgen/generator/lib/run_calypso.py b/dpgen/generator/lib/run_calypso.py
index 1f78ffa97..6af12008d 100644
--- a/dpgen/generator/lib/run_calypso.py
+++ b/dpgen/generator/lib/run_calypso.py
@@ -1,23 +1,18 @@
-"""
-calypso as model devi engine:
-       1. gen_structures
-       2. analysis
-       3. model devi
+"""calypso as model devi engine:
+1. gen_structures
+2. analysis
+3. model devi.
 """
 
-import copy
 import glob
-import math
 import os
 import random
-import re
 import shutil
 import sys
 from itertools import combinations
 from pathlib import Path
 
 import dpdata
-import numpy as np
 from ase.io.trajectory import Trajectory
 from ase.io.vasp import write_vasp
 from packaging.version import Version
@@ -91,7 +86,7 @@ def gen_structures(
             PickUpStep = 1
             try:
                 os.mkdir("opt")
-            except:
+            except Exception:
                 pass
 
         popsize = int(_parse_calypso_input("PopSize", "."))
@@ -109,7 +104,7 @@ def gen_structures(
             for pop in range(ii * int(popsize), (ii + 1) * int(popsize)):
                 try:
                     os.mkdir("task.%03d" % pop)
-                except:
+                except Exception:
                     shutil.rmtree("task.%03d" % pop)
                     os.mkdir("task.%03d" % pop)
                 shutil.copyfile(
@@ -241,7 +236,7 @@ def gen_structures(
             shutil.copyfile(name, "POSCAR_%s" % (idx + 1))
             try:
                 os.mkdir("task.%04d" % (idx + 1))
-            except:
+            except Exception:
                 shutil.rmtree("task.%04d" % (idx + 1))
                 os.mkdir("task.%04d" % (idx + 1))
             shutil.copyfile(
@@ -481,7 +476,7 @@ def run_calypso_model_devi(iter_index, jdata, mdata):
             lines = ["1 0\n"]
             f.close()
         else:
-            f = open(record_calypso_path, "r")
+            f = open(record_calypso_path)
             lines = f.readlines()
             f.close()
 
diff --git a/dpgen/generator/lib/utils.py b/dpgen/generator/lib/utils.py
index 10c1ae360..4eaf4ad87 100644
--- a/dpgen/generator/lib/utils.py
+++ b/dpgen/generator/lib/utils.py
@@ -30,7 +30,7 @@ def create_path(path):
 
 
 def replace(file_name, pattern, subst):
-    file_handel = open(file_name, "r")
+    file_handel = open(file_name)
     file_string = file_handel.read()
     file_handel.close()
     file_string = re.sub(pattern, subst, file_string)
@@ -76,18 +76,20 @@ def record_iter(record, ii, jj):
 
 
 def symlink_user_forward_files(mdata, task_type, work_path, task_format=None):
-    """
-    Symlink user-defined forward_common_files
-    Current path should be work_path, such as 00.train
+    """Symlink user-defined forward_common_files
+    Current path should be work_path, such as 00.train.
 
     Parameters
-    ---------
+    ----------
     mdata : dict
         machine parameters
-    task_type: str
+    task_type : str
         task_type, such as "train"
     work_path : str
         work_path, such as "iter.000001/00.train"
+    task_format : dict
+        formats of tasks
+
     Returns
     -------
     None
@@ -100,7 +102,7 @@ def symlink_user_forward_files(mdata, task_type, work_path, task_format=None):
     for file in user_forward_files:
         assert os.path.isfile(
             file
-        ), "user_forward_file %s of %s stage doesn't exist. " % (file, task_type)
+        ), f"user_forward_file {file} of {task_type} stage doesn't exist. "
         tasks = glob.glob(os.path.join(work_path, task_format[task_type]))
         for task in tasks:
             if os.path.isfile(os.path.join(task, os.path.basename(file))):
diff --git a/dpgen/generator/lib/vasp.py b/dpgen/generator/lib/vasp.py
index dcfbf0e43..fd5a6ff81 100644
--- a/dpgen/generator/lib/vasp.py
+++ b/dpgen/generator/lib/vasp.py
@@ -1,8 +1,6 @@
 #!/usr/bin/python3
 
-import os
 
-import numpy as np
 from pymatgen.io.vasp import Incar
 
 
@@ -68,7 +66,7 @@ def write_incar_dict(incar_dict):
                 rs = "F"
         else:
             rs = str(incar_dict[key])
-        lines.append("%s=%s" % (key, rs))
+        lines.append(f"{key}={rs}")
     return "\n".join(lines)
 
 
@@ -79,7 +77,7 @@ def _make_smearing(fp_params):
         smearing = fp_params["smearing"]
     if "sigma" in fp_params:
         sigma = fp_params["sigma"]
-    if smearing == None:
+    if smearing is None:
         return None, sigma
     smearing_method = (smearing.split(":")[0]).lower()
     if smearing_method == "mp":
diff --git a/dpgen/generator/run.py b/dpgen/generator/run.py
index 9293d93be..3c0ca1e5f 100644
--- a/dpgen/generator/run.py
+++ b/dpgen/generator/run.py
@@ -1,12 +1,11 @@
 #!/usr/bin/env python3
 
-"""
-init: data
+"""init: data
 iter:
         00.train
         01.model_devi
         02.vasp
-        03.data
+        03.data.
 """
 
 import argparse
@@ -20,12 +19,10 @@
 import queue
 import random
 import shutil
-import subprocess as sp
 import sys
 import warnings
 from collections import Counter
 from collections.abc import Iterable
-from pprint import pp
 from typing import List
 
 import dpdata
@@ -33,7 +30,7 @@
 import scipy.constants as pc
 from numpy.linalg import norm
 from packaging.version import Version
-from pymatgen.io.vasp import Incar, Kpoints, Potcar
+from pymatgen.io.vasp import Incar, Kpoints
 
 from dpgen import ROOT_PATH, SHORT_CMD, dlog
 from dpgen.auto_test.lib.vasp import make_kspacing_kpoints
@@ -68,26 +65,21 @@
 
 # from dpgen.generator.lib.pwscf import cvt_1frame
 from dpgen.generator.lib.pwmat import (
-    input_upper,
     make_pwmat_input_dict,
     make_pwmat_input_user_dict,
     write_input_dict,
 )
 from dpgen.generator.lib.pwscf import make_pwscf_input
 from dpgen.generator.lib.run_calypso import (
-    analysis,
-    gen_structures,
     run_calypso_model_devi,
 )
 from dpgen.generator.lib.siesta import make_siesta_input
 from dpgen.generator.lib.utils import (
-    copy_file_list,
     create_path,
     log_iter,
     log_task,
     make_iter_name,
     record_iter,
-    replace,
     symlink_user_forward_files,
 )
 from dpgen.generator.lib.vasp import (
@@ -196,7 +188,7 @@ def poscar_natoms(lines):
 
 
 def poscar_shuffle(poscar_in, poscar_out):
-    with open(poscar_in, "r") as fin:
+    with open(poscar_in) as fin:
         lines = list(fin)
     numb_atoms = poscar_natoms(lines)
     idx = np.arange(8, 8 + numb_atoms)
@@ -530,7 +522,7 @@ def make_train(iter_index, jdata, mdata):
                 os.path.isdir(jj) if "#" not in jj else os.path.isfile(jj.split("#")[0])
             ):
                 raise RuntimeError(
-                    "data sys %s does not exists, cwd is %s" % (jj, os.getcwd())
+                    f"data sys {jj} does not exists, cwd is {os.getcwd()}"
                 )
         os.chdir(cwd)
         # set random seed for each model
@@ -625,9 +617,8 @@ def make_train(iter_index, jdata, mdata):
 
 
 def _link_old_models(work_path, old_model_files, ii):
-    """
-    link the `ii`th old model given by `old_model_files` to
-    the `ii`th training task in `work_path`
+    """Link the `ii`th old model given by `old_model_files` to
+    the `ii`th training task in `work_path`.
     """
     task_path = os.path.join(work_path, train_task_fmt % ii)
     task_old_path = os.path.join(task_path, "old")
@@ -656,6 +647,12 @@ def detect_batch_size(batch_size, system=None):
         raise RuntimeError("Unsupported batch size")
 
 
+def get_nframes(system):
+    format = "deepmd/npy" if "#" not in system else "deepmd/hdf5"
+    s = dpdata.LabeledSystem(system, fmt=format)
+    return s.get_nframes()
+
+
 def run_train(iter_index, jdata, mdata):
     # print("debug:run_train:mdata", mdata)
     # load json param
@@ -702,17 +699,11 @@ def run_train(iter_index, jdata, mdata):
         extra_flags = ""
         if jdata.get("dp_train_skip_neighbor_stat", False):
             extra_flags += " --skip-neighbor-stat"
-        command = "%s train %s%s" % (train_command, train_input_file, extra_flags)
+        command = f"{train_command} train {train_input_file}{extra_flags}"
         if training_init_model:
-            command = (
-                "{ if [ ! -f model.ckpt.index ]; then %s --init-model old/model.ckpt; else %s --restart model.ckpt; fi }"
-                % (command, command)
-            )
+            command = f"{{ if [ ! -f model.ckpt.index ]; then {command} --init-model old/model.ckpt; else {command} --restart model.ckpt; fi }}"
         else:
-            command = (
-                "{ if [ ! -f model.ckpt.index ]; then %s; else %s --restart model.ckpt; fi }"
-                % (command, command)
-            )
+            command = f"{{ if [ ! -f model.ckpt.index ]; then {command}; else {command} --restart model.ckpt; fi }}"
         command = "/bin/sh -c '%s'" % command
         commands.append(command)
         command = "%s freeze" % train_command
@@ -840,8 +831,7 @@ def _get_param_alias(jdata, names):
         if ii in jdata:
             return jdata[ii]
     raise ValueError(
-        "one of the keys %s should be in jdata %s"
-        % (str(names), (json.dumps(jdata, indent=4)))
+        f"one of the keys {str(names)} should be in jdata {json.dumps(jdata, indent=4)}"
     )
 
 
@@ -983,7 +973,7 @@ def revise_lmp_input_plm(lmp_lines, in_plm, out_plm="output.plumed"):
     idx = find_only_one_key(lmp_lines, ["fix", "dpgen_plm"])
     lmp_lines[
         idx
-    ] = "fix            dpgen_plm all plumed plumedfile %s outfile %s\n" % (
+    ] = "fix            dpgen_plm all plumed plumedfile {} outfile {}\n".format(
         in_plm,
         out_plm,
     )
@@ -1833,7 +1823,7 @@ def run_md_model_devi(iter_index, jdata, mdata):
 
     all_task = glob.glob(os.path.join(work_path, "task.*"))
     all_task.sort()
-    fp = open(os.path.join(work_path, "cur_job.json"), "r")
+    fp = open(os.path.join(work_path, "cur_job.json"))
     cur_job = json.load(fp)
 
     run_tasks_ = all_task
@@ -1854,10 +1844,7 @@ def run_md_model_devi(iter_index, jdata, mdata):
 
     model_devi_engine = jdata.get("model_devi_engine", "lammps")
     if model_devi_engine == "lammps":
-        command = (
-            "{ if [ ! -f dpgen.restart.10000 ]; then %s -i input.lammps -v restart 0; else %s -i input.lammps -v restart 1; fi }"
-            % (model_devi_exec, model_devi_exec)
-        )
+        command = f"{{ if [ ! -f dpgen.restart.10000 ]; then {model_devi_exec} -i input.lammps -v restart 0; else {model_devi_exec} -i input.lammps -v restart 1; fi }}"
         command = "/bin/sh -c '%s'" % command
         commands = [command]
 
@@ -1900,20 +1887,17 @@ def run_md_model_devi(iter_index, jdata, mdata):
             deffnm,
             maxwarn,
         )
-        command += "&& %s mdrun -deffnm %s -cpi" % (model_devi_exec, deffnm)
+        command += f"&& {model_devi_exec} mdrun -deffnm {deffnm} -cpi"
         if ndx_filename:
             command += f'&& echo -e "{grp_name}\\n{grp_name}\\n" | {model_devi_exec} trjconv -s {ref_filename} -f {deffnm}.trr -n {ndx_filename} -o {traj_filename} -pbc mol -ur compact -center'
         else:
-            command += (
-                '&& echo -e "%s\\n%s\\n" | %s trjconv -s %s -f %s.trr -o %s -pbc mol -ur compact -center'
-                % (
-                    grp_name,
-                    grp_name,
-                    model_devi_exec,
-                    ref_filename,
-                    deffnm,
-                    traj_filename,
-                )
+            command += '&& echo -e "{}\\n{}\\n" | {} trjconv -s {} -f {}.trr -o {} -pbc mol -ur compact -center'.format(
+                grp_name,
+                grp_name,
+                model_devi_exec,
+                ref_filename,
+                deffnm,
+                traj_filename,
             )
         command += "&& if [ ! -d traj ]; then \n mkdir traj; fi\n"
         command += f"python -c \"import dpdata;system = dpdata.System('{traj_filename}', fmt='gromacs/gro'); [system.to_gromacs_gro('traj/%d.gromacstrj' % (i * {trj_freq}), frame_idx=i) for i in range(system.get_nframes())]; system.to_deepmd_npy('traj_deepmd')\""
@@ -2113,9 +2097,7 @@ def _select_by_model_devi_standard(
         iter_name = modd_system_task[0].split("/")[0]
         _work_path = os.path.join(iter_name, model_devi_name)
         # calypso_run_opt_path = os.path.join(_work_path,calypso_run_opt_name)
-        calypso_run_opt_path = glob.glob(
-            "%s/%s.*" % (_work_path, calypso_run_opt_name)
-        )[0]
+        calypso_run_opt_path = glob.glob(f"{_work_path}/{calypso_run_opt_name}.*")[0]
         numofspecies = _parse_calypso_input("NumberOfSpecies", calypso_run_opt_path)
         min_dis = _parse_calypso_dis_mtx(numofspecies, calypso_run_opt_path)
     fp_candidate = []
@@ -2213,17 +2195,17 @@ def _select_by_model_devi_adaptive_trust_low(
     model_devi_f_avg_relative: bool = False,
     model_devi_merge_traj: bool = False,
 ):
-    """
-    modd_system_task    model deviation tasks belonging to one system
+    """modd_system_task    model deviation tasks belonging to one system
     f_trust_hi
     numb_candi_f        number of candidate due to the f model deviation
     perc_candi_f        percentage of candidate due to the f model deviation
     v_trust_hi
     numb_candi_v        number of candidate due to the v model deviation
     perc_candi_v        percentage of candidate due to the v model deviation
-    model_devi_skip
+    model_devi_skip.
 
-    returns
+    Returns
+    -------
     accur               the accurate set
     candi               the candidate set
     failed              the failed set
@@ -2316,31 +2298,27 @@ def _make_fp_vasp_inner(
     type_map,
     jdata,
 ):
-    """
-    iter_index          int             iter index
+    """iter_index          int             iter index
     modd_path           string          path of model devi
     work_path           string          path of fp
     fp_task_max         int             max number of tasks
     fp_link_files       [string]        linked files for fp, POTCAR for example
-    fp_params           map             parameters for fp
+    fp_params           map             parameters for fp.
     """
-
     # --------------------------------------------------------------------------------------------------------------------------------------
     model_devi_engine = jdata.get("model_devi_engine", "lammps")
     if model_devi_engine == "calypso":
         iter_name = work_path.split("/")[0]
         _work_path = os.path.join(iter_name, model_devi_name)
         # calypso_run_opt_path = os.path.join(_work_path,calypso_run_opt_name)
-        calypso_run_opt_path = glob.glob(
-            "%s/%s.*" % (_work_path, calypso_run_opt_name)
-        )[0]
+        calypso_run_opt_path = glob.glob(f"{_work_path}/{calypso_run_opt_name}.*")[0]
         numofspecies = _parse_calypso_input("NumberOfSpecies", calypso_run_opt_path)
         min_dis = _parse_calypso_dis_mtx(numofspecies, calypso_run_opt_path)
 
         calypso_total_fp_num = 300
         modd_path = os.path.join(modd_path, calypso_model_devi_name)
         model_devi_skip = -1
-        with open(os.path.join(modd_path, "Model_Devi.out"), "r") as summfile:
+        with open(os.path.join(modd_path, "Model_Devi.out")) as summfile:
             summary = np.loadtxt(summfile)
         summaryfmax = summary[:, -4]
         dis = summary[:, -1]
@@ -2354,7 +2332,7 @@ def _make_fp_vasp_inner(
         tot = len(summaryfmax) - nan_num
         candi_num = tot - acc_num - fail_num
         dlog.info(
-            "summary  accurate_ratio: {0:8.4f}%  candidata_ratio: {1:8.4f}%  failed_ratio: {2:8.4f}%  in {3:d} structures".format(
+            "summary  accurate_ratio: {:8.4f}%  candidata_ratio: {:8.4f}%  failed_ratio: {:8.4f}%  in {:d} structures".format(
                 acc_num * 100 / tot, candi_num * 100 / tot, fail_num * 100 / tot, tot
             )
         )
@@ -2451,7 +2429,7 @@ def _trust_limitation_check(sys_idx, lim):
                     model_devi_merge_traj=model_devi_merge_traj,
                 )
                 dlog.info(
-                    "system {0:s} {1:9s} : f_trust_lo {2:6.3f}   v_trust_lo {3:6.3f}".format(
+                    "system {:s} {:9s} : f_trust_lo {:6.3f}   v_trust_lo {:6.3f}".format(
                         ss, "adapted", f_trust_lo_ad, v_trust_lo_ad
                     )
                 )
@@ -2504,13 +2482,11 @@ def _trust_limitation_check(sys_idx, lim):
         fp_sum = sum(counter.values())
 
         if fp_sum == 0:
-            dlog.info(
-                "system {0:s} has no fp task, maybe the model devi is nan %".format(ss)
-            )
+            dlog.info(f"system {ss:s} has no fp task, maybe the model devi is nan %")
             continue
         for cc_key, cc_value in counter.items():
             dlog.info(
-                "system {0:s} {1:9s} : {2:6d} in {3:6d} {4:6.2f} %".format(
+                "system {:s} {:9s} : {:6d} in {:6d} {:6.2f} %".format(
                     ss, cc_key, cc_value, fp_sum, cc_value / fp_sum * 100
                 )
             )
@@ -2586,7 +2562,7 @@ def _trust_limitation_check(sys_idx, lim):
                 numb_task = 0
         # ----------------------------------------------------------------------------
         dlog.info(
-            "system {0:s} accurate_ratio: {1:8.4f}    thresholds: {2:6.4f} and {3:6.4f}   eff. task min and max {4:4d} {5:4d}   number of fp tasks: {6:6d}".format(
+            "system {:s} accurate_ratio: {:8.4f}    thresholds: {:6.4f} and {:6.4f}   eff. task min and max {:4d} {:4d}   number of fp tasks: {:6d}".format(
                 ss,
                 accurate_ratio,
                 fp_accurate_soft_threshold,
@@ -2601,6 +2577,7 @@ def _trust_limitation_check(sys_idx, lim):
         # read all.lammpstrj, save in all_sys for each system_index
         all_sys = []
         trj_freq = None
+        netcdftraj = None
         if model_devi_merge_traj:
             for ii in modd_system_task:
                 all_traj = os.path.join(ii, "all.lammpstrj")
@@ -2665,7 +2642,7 @@ def _trust_limitation_check(sys_idx, lim):
             if cluster_cutoff is not None:
                 # take clusters
                 jj = fp_candidate[cc][2]
-                poscar_name = "{}.cluster.{}.POSCAR".format(conf_name, jj)
+                poscar_name = f"{conf_name}.cluster.{jj}.POSCAR"
                 new_system = take_cluster(conf_name, type_map, jj, jdata)
                 new_system.to_vasp_poscar(poscar_name)
             fp_task_name = make_fp_task_name(int(ss), cc)
@@ -2725,19 +2702,19 @@ def _trust_limitation_check(sys_idx, lim):
             os.chdir(cwd)
         if count_bad_box > 0:
             dlog.info(
-                "system {0:s} skipped {1:6d} confs with bad box, {2:6d} remains".format(
+                "system {:s} skipped {:6d} confs with bad box, {:6d} remains".format(
                     ss, count_bad_box, numb_task - count_bad_box
                 )
             )
         if count_bad_cluster > 0:
             dlog.info(
-                "system {0:s} skipped {1:6d} confs with bad cluster, {2:6d} remains".format(
+                "system {:s} skipped {:6d} confs with bad cluster, {:6d} remains".format(
                     ss, count_bad_cluster, numb_task - count_bad_cluster
                 )
             )
     if model_devi_engine == "calypso":
         dlog.info(
-            "summary  accurate_ratio: {0:8.4f}%  candidata_ratio: {1:8.4f}%  failed_ratio: {2:8.4f}%  in {3:d} structures".format(
+            "summary  accurate_ratio: {:8.4f}%  candidata_ratio: {:8.4f}%  failed_ratio: {:8.4f}%  in {:d} structures".format(
                 acc_num * 100 / tot, candi_num * 100 / tot, fail_num * 100 / tot, tot
             )
         )
@@ -2928,7 +2905,7 @@ def _make_fp_pwmat_input(iter_index, jdata):
 
 def make_fp_vasp_cp_cvasp(iter_index, jdata):
     # Move cvasp interface to jdata
-    if ("cvasp" in jdata) and (jdata["cvasp"] == True):
+    if ("cvasp" in jdata) and (jdata["cvasp"] is True):
         pass
     else:
         return
@@ -3073,14 +3050,13 @@ def _link_fp_abacus_pporb_descript(iter_index, jdata):
         # get value of 'deepks_model' from INPUT
         input_param = get_abacus_input_parameters("INPUT")
         fp_dpks_model = input_param.get("deepks_model", None)
-        if fp_dpks_model != None:
+        if fp_dpks_model is not None:
             model_file = os.path.join(
                 fp_pp_path, os.path.split(fp_dpks_model)[1]
             )  # only the filename
-            assert os.path.isfile(model_file), (
-                "Can not find the deepks model file %s, which is defined in %s/INPUT"
-                % (model_file, ii)
-            )
+            assert os.path.isfile(
+                model_file
+            ), f"Can not find the deepks model file {model_file}, which is defined in {ii}/INPUT"
             os.symlink(model_file, fp_dpks_model)  # link to the model file
 
         # get pp, orb, descriptor filenames from STRU
@@ -3156,7 +3132,7 @@ def _make_fp_vasp_configs(iter_index: int, jdata: dict):
     modd_path = os.path.join(iter_name, model_devi_name)
     task_min = -1
     if os.path.isfile(os.path.join(modd_path, "cur_job.json")):
-        cur_job = json.load(open(os.path.join(modd_path, "cur_job.json"), "r"))
+        cur_job = json.load(open(os.path.join(modd_path, "cur_job.json")))
         if "task_min" in cur_job:
             task_min = cur_job["task_min"]
     else:
@@ -3615,7 +3591,7 @@ def make_fp_calculation(iter_index, jdata, mdata):
 
 def _vasp_check_fin(ii):
     if os.path.isfile(os.path.join(ii, "OUTCAR")):
-        with open(os.path.join(ii, "OUTCAR"), "r") as fp:
+        with open(os.path.join(ii, "OUTCAR")) as fp:
             content = fp.read()
             count = content.count("Elapse")
             if count != 1:
@@ -3627,7 +3603,7 @@ def _vasp_check_fin(ii):
 
 def _qe_check_fin(ii):
     if os.path.isfile(os.path.join(ii, "output")):
-        with open(os.path.join(ii, "output"), "r") as fp:
+        with open(os.path.join(ii, "output")) as fp:
             content = fp.read()
             count = content.count("JOB DONE")
             if count != 1:
@@ -3639,7 +3615,7 @@ def _qe_check_fin(ii):
 
 def _abacus_scf_check_fin(ii):
     if os.path.isfile(os.path.join(ii, "OUT.ABACUS/running_scf.log")):
-        with open(os.path.join(ii, "OUT.ABACUS/running_scf.log"), "r") as fp:
+        with open(os.path.join(ii, "OUT.ABACUS/running_scf.log")) as fp:
             content = fp.read()
             count = content.count("!FINAL_ETOT_IS")
             if count != 1:
@@ -3651,7 +3627,7 @@ def _abacus_scf_check_fin(ii):
 
 def _siesta_check_fin(ii):
     if os.path.isfile(os.path.join(ii, "output")):
-        with open(os.path.join(ii, "output"), "r") as fp:
+        with open(os.path.join(ii, "output")) as fp:
             content = fp.read()
             count = content.count("End of run")
             if count != 1:
@@ -3663,7 +3639,7 @@ def _siesta_check_fin(ii):
 
 def _gaussian_check_fin(ii):
     if os.path.isfile(os.path.join(ii, "output")):
-        with open(os.path.join(ii, "output"), "r") as fp:
+        with open(os.path.join(ii, "output")) as fp:
             content = fp.read()
             count = content.count("termination")
             if count == 0:
@@ -3675,7 +3651,7 @@ def _gaussian_check_fin(ii):
 
 def _cp2k_check_fin(ii):
     if os.path.isfile(os.path.join(ii, "output")):
-        with open(os.path.join(ii, "output"), "r") as fp:
+        with open(os.path.join(ii, "output")) as fp:
             content = fp.read()
             count = content.count("SCF run converged")
             if count == 0:
@@ -3687,7 +3663,7 @@ def _cp2k_check_fin(ii):
 
 def _pwmat_check_fin(ii):
     if os.path.isfile(os.path.join(ii, "REPORT")):
-        with open(os.path.join(ii, "REPORT"), "r") as fp:
+        with open(os.path.join(ii, "REPORT")) as fp:
             content = fp.read()
             count = content.count("time")
             if count != 1:
@@ -3741,9 +3717,8 @@ def run_fp_inner(
                 "-x high_level.nc -y rc.nc -frc high_level.mdfrc -inf high_level.mdinfo && "
             )
             + (
-                'dpamber corr --cutoff %f --parm7_file ../qmmm$SYS.parm7 --nc rc.nc --hl high_level --ll low_level --qm_region "$QM_REGION"'
-            )
-            % (jdata["cutoff"],)
+                'dpamber corr --cutoff {:f} --parm7_file ../qmmm$SYS.parm7 --nc rc.nc --hl high_level --ll low_level --qm_region "$QM_REGION"'
+            ).format(jdata["cutoff"])
         )
 
     fp_run_tasks = fp_tasks
@@ -3787,10 +3762,10 @@ def run_fp(iter_index, jdata, mdata):
         forward_files = ["POSCAR", "INCAR", "POTCAR", "KPOINTS"]
         backward_files = ["fp.log", "OUTCAR", "vasprun.xml"]
         # Move cvasp interface to jdata
-        if ("cvasp" in jdata) and (jdata["cvasp"] == True):
+        if ("cvasp" in jdata) and (jdata["cvasp"] is True):
             mdata["fp_resources"]["cvasp"] = True
         if ("cvasp" in mdata["fp_resources"]) and (
-            mdata["fp_resources"]["cvasp"] == True
+            mdata["fp_resources"]["cvasp"] is True
         ):
             dlog.info("cvasp is on !")
             forward_files.append("cvasp.py")
@@ -4134,12 +4109,12 @@ def post_fp_abacus_scf(iter_index, jdata):
                 oo, fmt="abacus/scf", type_map=jdata["type_map"]
             )
             if len(_sys) > 0:
-                if all_sys == None:
+                if all_sys is None:
                     all_sys = _sys
                 else:
                     all_sys.append(_sys)
 
-        if all_sys != None:
+        if all_sys is not None:
             sys_data_path = os.path.join(work_path, "data.%s" % ss)
             all_sys.to_deepmd_raw(sys_data_path)
             all_sys.to_deepmd_npy(sys_data_path, set_size=len(sys_output))
@@ -4340,7 +4315,7 @@ def post_fp_pwmat(iter_index, jdata, rfailed=None):
     dlog.info("failed frame number: %s " % icount)
     dlog.info("total frame number: %s " % tcount)
     reff = icount / tcount
-    dlog.info("ratio of failed frame:  {:.2%}".format(reff))
+    dlog.info(f"ratio of failed frame:  {reff:.2%}")
 
     if reff > ratio_failed:
         raise RuntimeError("find too many unsuccessfully terminated jobs")
@@ -4434,9 +4409,9 @@ def run_iter(param_file, machine_file):
         jdata = loadfn(param_file)
         mdata = loadfn(machine_file)
     except Exception:
-        with open(param_file, "r") as fp:
+        with open(param_file) as fp:
             jdata = json.load(fp)
-        with open(machine_file, "r") as fp:
+        with open(machine_file) as fp:
             mdata = json.load(fp)
 
     jdata_arginfo = run_jdata_arginfo()
@@ -4495,7 +4470,7 @@ def run_iter(param_file, machine_file):
             if ii * max_tasks + jj <= iter_rec[0] * max_tasks + iter_rec[1]:
                 continue
             task_name = "task %02d" % jj
-            sepline("{} {}".format(iter_name, task_name), "-")
+            sepline(f"{iter_name} {task_name}", "-")
             if jj == 0:
                 log_iter("make_train", ii, jj)
                 make_train(ii, jdata, mdata)
diff --git a/dpgen/main.py b/dpgen/main.py
index c0a94803d..42b65c116 100644
--- a/dpgen/main.py
+++ b/dpgen/main.py
@@ -1,13 +1,11 @@
 #!/usr/bin/env python
-# coding: utf-8
 # Copyright (c) DeepGenerator Development Team.
 
 
 import argparse
-import itertools
 import sys
 
-from dpgen import __version__, info
+from dpgen import info
 from dpgen.auto_test.run import gen_test
 from dpgen.collect.collect import gen_collect
 from dpgen.data.gen import gen_init_bulk
diff --git a/dpgen/remote/decide_machine.py b/dpgen/remote/decide_machine.py
index ced049ef0..e76c61e2d 100644
--- a/dpgen/remote/decide_machine.py
+++ b/dpgen/remote/decide_machine.py
@@ -1,12 +1,10 @@
 #!/usr/bin/env python
-# coding: utf-8
 
 
 def convert_mdata(mdata, task_types=["train", "model_devi", "fp"]):
-    """
-    Convert mdata for DP-GEN main process.
+    """Convert mdata for DP-GEN main process.
     New convension is like mdata["fp"]["machine"],
-    DP-GEN needs mdata["fp_machine"]
+    DP-GEN needs mdata["fp_machine"].
 
     Notice that we deprecate the function which can automatically select one most avalaible machine,
     since this function was only used by Angus, and only supports for Slurm.
diff --git a/dpgen/simplify/simplify.py b/dpgen/simplify/simplify.py
index b7eaa29b5..3124fe115 100644
--- a/dpgen/simplify/simplify.py
+++ b/dpgen/simplify/simplify.py
@@ -14,6 +14,7 @@
 import os
 import queue
 import warnings
+from collections import defaultdict
 from typing import List, Union
 
 import dpdata
@@ -29,24 +30,18 @@
     log_iter,
     make_iter_name,
     record_iter,
-    symlink_user_forward_files,
 )
 from dpgen.generator.run import (
     data_system_fmt,
     fp_name,
     fp_task_fmt,
     make_fp_calculation,
-    make_fp_vasp_cp_cvasp,
-    make_fp_vasp_incar,
-    make_fp_vasp_kp,
     make_train,
     model_devi_name,
-    model_devi_task_fmt,
     post_fp,
     post_train,
     run_fp,
     run_train,
-    sys_link_fp_vasp_pp,
     train_name,
     train_task_fmt,
 )
@@ -137,7 +132,7 @@ def init_model(iter_index, jdata, mdata):
 
 
 def init_pick(iter_index, jdata, mdata):
-    """pick up init data from dataset randomly"""
+    """Pick up init data from dataset randomly."""
     pick_data = jdata["pick_data"]
     init_pick_number = jdata["init_pick_number"]
     # use MultiSystems with System
@@ -183,7 +178,7 @@ def _init_dump_selected_frames(systems, labels, selc_idx, sys_data_path, jdata):
 
 
 def make_model_devi(iter_index, jdata, mdata):
-    """calculate the model deviation of the rest idx"""
+    """Calculate the model deviation of the rest idx."""
     pick_data = jdata["pick_data"]
     iter_name = make_iter_name(iter_index)
     work_path = os.path.join(iter_name, model_devi_name)
@@ -208,7 +203,7 @@ def make_model_devi(iter_index, jdata, mdata):
 
 
 def run_model_devi(iter_index, jdata, mdata):
-    """submit dp test tasks"""
+    """Submit dp test tasks."""
     iter_name = make_iter_name(iter_index)
     work_path = os.path.join(iter_name, model_devi_name)
     # generate command
@@ -269,7 +264,7 @@ def run_model_devi(iter_index, jdata, mdata):
 
 
 def post_model_devi(iter_index, jdata, mdata):
-    """calculate the model deviation"""
+    """Calculate the model deviation."""
     iter_name = make_iter_name(iter_index)
     work_path = os.path.join(iter_name, model_devi_name)
 
@@ -314,7 +309,7 @@ def post_model_devi(iter_index, jdata, mdata):
     fp_sum = sum(counter.values())
     for cc_key, cc_value in counter.items():
         dlog.info(
-            "{0:9s} : {1:6d} in {2:6d} {3:6.2f} %".format(
+            "{:9s} : {:6d} in {:6d} {:6.2f} %".format(
                 cc_key, cc_value, fp_sum, cc_value / fp_sum * 100
             )
         )
@@ -341,7 +336,7 @@ def post_model_devi(iter_index, jdata, mdata):
         dlog.info("no candidate")
     else:
         dlog.info(
-            "total candidate {0:6d}   picked {1:6d} ({2:6.2f} %) rest {3:6d} ({4:6.2f} % )".format(
+            "total candidate {:6d}   picked {:6d} ({:6.2f} %) rest {:6d} ({:6.2f} % )".format(
                 counter["candidate"],
                 len(pick_idx),
                 float(len(pick_idx)) / counter["candidate"] * 100.0,
@@ -425,7 +420,7 @@ def make_fp(iter_index, jdata, mdata):
 
 
 def run_iter(param_file, machine_file):
-    """init (iter 0): init_pick
+    """Init (iter 0): init_pick.
 
     tasks (iter > 0):
     00 make_train (same as generator)
@@ -441,15 +436,15 @@ def run_iter(param_file, machine_file):
     # TODO: function of handling input json should be combined as one function
     try:
         import ruamel
-        from monty.serialization import dumpfn, loadfn
+        from monty.serialization import loadfn
 
         warnings.simplefilter("ignore", ruamel.yaml.error.MantissaNoDotYAML1_1Warning)
         jdata = loadfn(param_file)
         mdata = loadfn(machine_file)
     except Exception:
-        with open(param_file, "r") as fp:
+        with open(param_file) as fp:
             jdata = json.load(fp)
-        with open(machine_file, "r") as fp:
+        with open(machine_file) as fp:
             mdata = json.load(fp)
 
     jdata_arginfo = simplify_jdata_arginfo()
@@ -485,7 +480,7 @@ def run_iter(param_file, machine_file):
             if ii * max_tasks + jj <= iter_rec[0] * max_tasks + iter_rec[1]:
                 continue
             task_name = "task %02d" % jj
-            sepline("{} {}".format(iter_name, task_name), "-")
+            sepline(f"{iter_name} {task_name}", "-")
             jdata["model_devi_jobs"] = [{} for _ in range(ii + 1)]
             if ii == 0 and jj < 6 and (jj >= 3 or not jdata.get("init_data_sys", [])):
                 if jj == 0:
diff --git a/dpgen/tools/auto_gen_param.py b/dpgen/tools/auto_gen_param.py
index df5793be3..6d837dc47 100755
--- a/dpgen/tools/auto_gen_param.py
+++ b/dpgen/tools/auto_gen_param.py
@@ -6,7 +6,7 @@
 from itertools import tee
 
 
-class System(object):
+class System:
     current_num_of_system = 0
     current_num_of_sub_systems = 0
 
@@ -49,7 +49,7 @@ def get_sub_system(self):
         return self.sub_system_list
 
 
-class Iteration(object):
+class Iteration:
     current_num_of_itearation = 0
     current_num_of_sub_itearation = 0
 
@@ -133,8 +133,7 @@ def get_system_list(
     map_iterator=None,
     file_name="POSCAR",
 ):
-    """
-    :type map_iterator: Iterable use to generate sys_configs
+    """:type map_iterator: Iterable use to generate sys_configs
     :Exmaple [['000000', '000001',], ['00000[2-9]',], ['00001?', '000020',],]
     """
     if sub_iteration_num != len(map_list):
diff --git a/dpgen/tools/collect_data.py b/dpgen/tools/collect_data.py
index 2a270a47e..511dacc24 100755
--- a/dpgen/tools/collect_data.py
+++ b/dpgen/tools/collect_data.py
@@ -5,9 +5,6 @@
 import json
 import os
 import subprocess as sp
-import sys
-
-import numpy as np
 
 
 def file_len(fname):
diff --git a/dpgen/tools/relabel.py b/dpgen/tools/relabel.py
index ac5196eaa..140e614fa 100755
--- a/dpgen/tools/relabel.py
+++ b/dpgen/tools/relabel.py
@@ -5,17 +5,14 @@
 import json
 import os
 import shutil
-import subprocess as sp
 import sys
 
-import numpy as np
-
 sys.path.insert(0, os.path.join(os.path.dirname(os.path.realpath(__file__)), ".."))
 import dpdata
 
 from dpgen.generator.lib.pwscf import make_pwscf_input
 from dpgen.generator.lib.siesta import make_siesta_input
-from dpgen.generator.run import make_vasp_incar, update_mass_map
+from dpgen.generator.run import update_mass_map
 
 
 def get_lmp_info(input_file):
@@ -180,7 +177,7 @@ def create_tasks(
     os.chdir(target_folder)
     fp_pp_path = os.path.abspath(fp_pp_path)
     os.chdir(cwd_)
-    # fp_params = fp_jdata['fp_params']
+    fp_params = fp_jdata["fp_params"]
     # collect tasks from iter dirs
     sys_tasks = [[] for ii in sys]
     sys_tasks_record = [[] for ii in sys]
diff --git a/dpgen/tools/run_report.py b/dpgen/tools/run_report.py
index 88b3a4b06..1bc8f3d9f 100755
--- a/dpgen/tools/run_report.py
+++ b/dpgen/tools/run_report.py
@@ -1,14 +1,5 @@
 #!/usr/bin/env python3
 
-import argparse
-import glob
-import json
-import os
-import shutil
-import subprocess as sp
-import sys
-
-import numpy as np
 
 from dpgen.tools.stat_iter import stat_iter
 from dpgen.tools.stat_sys import stat_sys
diff --git a/dpgen/tools/stat_iter.py b/dpgen/tools/stat_iter.py
index 5a3eb8932..43a0617fa 100644
--- a/dpgen/tools/stat_iter.py
+++ b/dpgen/tools/stat_iter.py
@@ -3,7 +3,6 @@
 import json
 import os
 import subprocess
-import sys
 from collections import defaultdict
 
 import dpdata
diff --git a/dpgen/tools/stat_sys.py b/dpgen/tools/stat_sys.py
index 5a0cb6471..c2f704bb1 100644
--- a/dpgen/tools/stat_sys.py
+++ b/dpgen/tools/stat_sys.py
@@ -1,15 +1,10 @@
 #!/usr/bin/env python3
 
-import argparse
 import glob
 import json
 import os
-import shutil
-import subprocess as sp
 import sys
 
-import numpy as np
-
 sys.path.append(os.path.join(os.path.dirname(os.path.realpath(__file__)), ".."))
 from dpgen.tools.relabel import get_lmp_info
 
@@ -62,7 +57,7 @@ def stat_sys(target_folder, param_file="param.json", verbose=True, mute=False):
                 os.path.join(ii, "01.model_devi", linked_keys[-3], "input.lammps")
             )
             trait = [ens, temp, pres]
-            if not trait in sys_tasks_trait[sys_idx]:
+            if trait not in sys_tasks_trait[sys_idx]:
                 sys_tasks_trait[sys_idx].append(trait)
                 sys_tasks_trait_count[sys_idx].append(0)
             t_idx = sys_tasks_trait[sys_idx].index(trait)
@@ -103,4 +98,4 @@ def stat_sys(target_folder, param_file="param.json", verbose=True, mute=False):
 
 
 def run_report(args):
-    stat_tasks(args.JOB_DIR, args.param, args.verbose)
+    stat_sys(args.JOB_DIR, args.param, args.verbose)
diff --git a/dpgen/util.py b/dpgen/util.py
index d25d0a31e..1a6db4814 100644
--- a/dpgen/util.py
+++ b/dpgen/util.py
@@ -1,5 +1,4 @@
 #!/usr/bin/env python
-# coding: utf-8
 import json
 import os
 from pathlib import Path
@@ -20,9 +19,7 @@
 
 
 def sepline(ch="-", sp="-", screen=False):
-    r"""
-    seperate the output by '-'
-    """
+    r"""Seperate the output by '-'."""
     if screen:
         print(ch.center(MaxLength, sp))
     else:
@@ -30,10 +27,8 @@ def sepline(ch="-", sp="-", screen=False):
 
 
 def box_center(ch="", fill=" ", sp="|"):
-    r"""
-    put the string at the center of |  |
-    """
-    strs = ch.center(Len, fill)
+    r"""Put the string at the center of |  |."""
+    strs = ch.center(MaxLength, fill)
     dlog.info(sp + strs[1 : len(strs) - 1 :] + sp)
 
 
@@ -64,9 +59,7 @@ def expand_sys_str(root_dir: Union[str, Path]) -> List[str]:
             f_keys = ["/"]
             f.visit(lambda x: f_keys.append("/" + x))
         matches = [
-            "%s#%s" % (root_dir, d)
-            for d in f_keys
-            if str(Path(d) / "type.raw") in f_keys
+            f"{root_dir}#{d}" for d in f_keys if str(Path(d) / "type.raw") in f_keys
         ]
     else:
         raise OSError(f"{root_dir} does not exist.")
diff --git a/pyproject.toml b/pyproject.toml
index c893bddd1..3bec52c1e 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -57,7 +57,32 @@ write_to = "dpgen/_version.py"
 profile = "black"
 
 [tool.ruff]
-target-version = "py37"
+target-version = "py38"
 select = [
     "I", # isort
+    "E", # errors
+    "F", # pyflakes
+    "D", # pydocstyle
+    "UP", # pyupgrade
 ]
+ignore = [
+    "E501", # line too long
+    "F841", # local variable is assigned to but never used
+    "E741", # ambiguous variable name
+    "E402", # module level import not at top of file
+    "D413", # missing blank line after last section
+    "D416", # section name should end with a colon
+    "D203", # 1 blank line required before class docstring
+    "D107", # missing docstring in __init__
+    "D213", # multi-line docstring summary should start at the second line
+    "D100", # TODO: missing docstring in public module
+    "D101", # TODO: missing docstring in public class
+    "D102", # TODO: missing docstring in public method
+    "D103", # TODO: missing docstring in public function
+    "D104", # TODO: missing docstring in public package
+    "D105", # TODO: missing docstring in magic method
+    "D205", # 1 blank line required between summary line and description
+    "D401", # TODO: first line should be in imperative mood
+    "D404", # TODO: first word of the docstring should not be This
+]
+ignore-init-module-imports = true


Test patch:
diff --git a/dpgen/auto_test/ABACUS.py b/dpgen/auto_test/ABACUS.py
index 54f447638..ea5ec627f 100644
--- a/dpgen/auto_test/ABACUS.py
+++ b/dpgen/auto_test/ABACUS.py
@@ -1,6 +1,5 @@
 import os
 
-import numpy as np
 from dpdata import LabeledSystem
 from monty.serialization import dumpfn
 
@@ -22,7 +21,7 @@ def __init__(self, inter_parameter, path_to_poscar):
         self.deepks = inter_parameter.get("deepks_desc", None)
         self.deepks_model = inter_parameter.get("deepks_model", None)
         self.path_to_poscar = path_to_poscar
-        self.if_define_orb_file = False if self.orbfile == None else True
+        self.if_define_orb_file = False if self.orbfile is None else True
 
     def make_potential_files(self, output_dir):
         stru = os.path.abspath(os.path.join(output_dir, "STRU"))
@@ -41,7 +40,7 @@ def make_potential_files(self, output_dir):
         else:
             stru_path = output_dir
 
-        if pp_files == None:
+        if pp_files is None:
             raise RuntimeError("No pseudopotential information in STRU file")
 
         pp_dir = os.path.abspath(self.potcar_prefix)
@@ -101,8 +100,7 @@ def make_potential_files(self, output_dir):
             filename_in_para = os.path.split(file_param)[1]
             if filename_in_stru != filename_in_para:
                 dlog.warning(
-                    "file name in STRU is not match that defined in parameter setting file: '%s', '%s'."
-                    % (filename_in_stru, filename_in_para)
+                    f"file name in STRU is not match that defined in parameter setting file: '{filename_in_stru}', '{filename_in_para}'."
                 )
 
             src_file = os.path.join(pp_dir, file_param)
@@ -119,7 +117,7 @@ def make_potential_files(self, output_dir):
 
     def modify_input(self, incar, x, y):
         if x in incar and incar[x] != y:
-            dlog.info("setting %s to %s" % (x, y))
+            dlog.info(f"setting {x} to {y}")
         incar[x] = y
 
     def make_input_file(self, output_dir, task_type, task_param):
diff --git a/dpgen/auto_test/EOS.py b/dpgen/auto_test/EOS.py
index 6ccd60fb8..2ab57dfcf 100644
--- a/dpgen/auto_test/EOS.py
+++ b/dpgen/auto_test/EOS.py
@@ -76,7 +76,7 @@ def __init__(self, parameter, inter_param=None):
             parameter["init_from_suffix"] = parameter.get("init_from_suffix", "00")
             self.init_from_suffix = parameter["init_from_suffix"]
         self.parameter = parameter
-        self.inter_param = inter_param if inter_param != None else {"type": "vasp"}
+        self.inter_param = inter_param if inter_param is not None else {"type": "vasp"}
 
     def make_confs(self, path_to_work, path_to_equi, refine=False):
         path_to_work = os.path.abspath(path_to_work)
@@ -259,7 +259,7 @@ def _compute_lower(self, output_file, all_tasks, all_res):
                 res_data[vol] = task_result["energies"][-1] / sum(
                     task_result["atom_numbs"]
                 )
-                ptr_data += "%7.3f  %8.4f \n" % (
+                ptr_data += "{:7.3f}  {:8.4f} \n".format(
                     vol,
                     task_result["energies"][-1] / sum(task_result["atom_numbs"]),
                 )
diff --git a/dpgen/auto_test/Elastic.py b/dpgen/auto_test/Elastic.py
index 7616ec740..389935a06 100644
--- a/dpgen/auto_test/Elastic.py
+++ b/dpgen/auto_test/Elastic.py
@@ -50,7 +50,7 @@ def __init__(self, parameter, inter_param=None):
         # parameter['reproduce'] = False
         # self.reprod = parameter['reproduce']
         self.parameter = parameter
-        self.inter_param = inter_param if inter_param != None else {"type": "vasp"}
+        self.inter_param = inter_param if inter_param is not None else {"type": "vasp"}
 
     def make_confs(self, path_to_work, path_to_equi, refine=False):
         path_to_work = os.path.abspath(path_to_work)
diff --git a/dpgen/auto_test/Gamma.py b/dpgen/auto_test/Gamma.py
index 97eed3b1b..cb66ea52d 100644
--- a/dpgen/auto_test/Gamma.py
+++ b/dpgen/auto_test/Gamma.py
@@ -7,10 +7,8 @@
 import numpy as np
 from ase.lattice.cubic import BodyCenteredCubic as bcc
 from ase.lattice.cubic import FaceCenteredCubic as fcc
-from ase.lattice.hexagonal import HexagonalClosedPacked as hcp
 from monty.serialization import dumpfn, loadfn
 from pymatgen.core.structure import Structure
-from pymatgen.core.surface import SlabGenerator
 from pymatgen.io.ase import AseAtomsAdaptor
 
 import dpgen.auto_test.lib.abacus as abacus
@@ -22,9 +20,7 @@
 
 
 class Gamma(Property):
-    """
-    Calculation of common gamma lines for bcc and fcc
-    """
+    """Calculation of common gamma lines for bcc and fcc."""
 
     def __init__(self, parameter, inter_param=None):
         parameter["reproduce"] = parameter.get("reproduce", False)
@@ -95,7 +91,7 @@ def __init__(self, parameter, inter_param=None):
             parameter["init_from_suffix"] = parameter.get("init_from_suffix", "00")
             self.init_from_suffix = parameter["init_from_suffix"]
         self.parameter = parameter
-        self.inter_param = inter_param if inter_param != None else {"type": "vasp"}
+        self.inter_param = inter_param if inter_param is not None else {"type": "vasp"}
 
     def make_confs(self, path_to_work, path_to_equi, refine=False):
         path_to_work = os.path.abspath(path_to_work)
@@ -359,7 +355,7 @@ def __poscar_fix(self, poscar) -> None:
             + fix_dict[self.add_fix[2]]
             + "\n"
         )
-        with open(poscar, "r") as fin1:
+        with open(poscar) as fin1:
             contents = fin1.readlines()
             contents.insert(insert_pos - 1, "Selective dynamics\n")
             for ii in range(insert_pos, 0, 1):
@@ -387,7 +383,7 @@ def __inLammpes_fix(self, inLammps) -> None:
             + fix_dict[self.add_fix[2]]
             + "\n"
         )
-        with open(inLammps, "r") as fin1:
+        with open(inLammps) as fin1:
             contents = fin1.readlines()
             for ii in range(len(contents)):
                 upper = re.search("variable        N equal count\(all\)", contents[ii])
diff --git a/dpgen/auto_test/Interstitial.py b/dpgen/auto_test/Interstitial.py
index b98f18d15..ae5befc5d 100644
--- a/dpgen/auto_test/Interstitial.py
+++ b/dpgen/auto_test/Interstitial.py
@@ -10,7 +10,6 @@
 
 import dpgen.auto_test.lib.abacus as abacus
 import dpgen.auto_test.lib.lammps as lammps
-import dpgen.generator.lib.abacus_scf as abacus_scf
 from dpgen.auto_test.Property import Property
 from dpgen.auto_test.refine import make_refine
 from dpgen.auto_test.reproduce import make_repro, post_repro
@@ -76,7 +75,7 @@ def __init__(self, parameter, inter_param=None):
             parameter["init_from_suffix"] = parameter.get("init_from_suffix", "00")
             self.init_from_suffix = parameter["init_from_suffix"]
         self.parameter = parameter
-        self.inter_param = inter_param if inter_param != None else {"type": "vasp"}
+        self.inter_param = inter_param if inter_param is not None else {"type": "vasp"}
 
     def make_confs(self, path_to_work, path_to_equi, refine=False):
         path_to_work = os.path.abspath(path_to_work)
@@ -248,7 +247,7 @@ def make_confs(self, path_to_work, path_to_equi, refine=False):
                     num_atom = super_size * 2
                     chl = -num_atom - 2
                     os.chdir(path_to_work)
-                    with open("POSCAR", "r") as fin:
+                    with open("POSCAR") as fin:
                         fin.readline()
                         scale = float(fin.readline().split()[0])
                         latt_param = float(fin.readline().split()[0])
@@ -257,7 +256,7 @@ def make_confs(self, path_to_work, path_to_equi, refine=False):
                     if not os.path.isfile("task.000000/POSCAR"):
                         raise RuntimeError("need task.000000 structure as reference")
 
-                    with open("task.000000/POSCAR", "r") as fin:
+                    with open("task.000000/POSCAR") as fin:
                         pos_line = fin.read().split("\n")
 
                     super_latt_param = float(pos_line[2].split()[0])
@@ -467,13 +466,13 @@ def make_confs(self, path_to_work, path_to_equi, refine=False):
 
     def post_process(self, task_list):
         if True:
-            fin1 = open(os.path.join(task_list[0], "..", "element.out"), "r")
+            fin1 = open(os.path.join(task_list[0], "..", "element.out"))
             for ii in task_list:
                 conf = os.path.join(ii, "conf.lmp")
                 inter = os.path.join(ii, "inter.json")
                 insert_ele = fin1.readline().split()[0]
                 if os.path.isfile(conf):
-                    with open(conf, "r") as fin2:
+                    with open(conf) as fin2:
                         conf_line = fin2.read().split("\n")
                         insert_line = conf_line[-2]
                     type_map = loadfn(inter)["type_map"]
@@ -505,9 +504,7 @@ def _compute_lower(self, output_file, all_tasks, all_res):
         ptr_data = os.path.dirname(output_file) + "\n"
 
         if not self.reprod:
-            with open(
-                os.path.join(os.path.dirname(output_file), "element.out"), "r"
-            ) as fin:
+            with open(os.path.join(os.path.dirname(output_file), "element.out")) as fin:
                 fc = fin.read().split("\n")
             ptr_data += "Insert_ele-Struct: Inter_E(eV)  E(eV) equi_E(eV)\n"
             idid = -1
@@ -528,7 +525,7 @@ def _compute_lower(self, output_file, all_tasks, all_res):
                 supercell_index = loadfn(os.path.join(ii, "supercell.json"))
                 # insert_ele = loadfn(os.path.join(ii, 'task.json'))['insert_ele'][0]
                 insert_ele = fc[idid]
-                ptr_data += "%s: %7.3f  %7.3f %7.3f \n" % (
+                ptr_data += "{}: {:7.3f}  {:7.3f} {:7.3f} \n".format(
                     insert_ele + "-" + str(supercell_index) + "-" + structure_dir,
                     evac,
                     task_result["energies"][-1],
diff --git a/dpgen/auto_test/Lammps.py b/dpgen/auto_test/Lammps.py
index 0cd46b245..38f3d623d 100644
--- a/dpgen/auto_test/Lammps.py
+++ b/dpgen/auto_test/Lammps.py
@@ -138,36 +138,40 @@ def make_input_file(self, output_dir, task_type, task_param):
 
         # deal with user input in.lammps for relaxation
         if os.path.isfile(self.in_lammps) and task_type == "relaxation":
-            with open(self.in_lammps, "r") as fin:
+            with open(self.in_lammps) as fin:
                 fc = fin.read()
         # user input in.lammps for property calculation
         if "input_prop" in cal_setting and os.path.isfile(cal_setting["input_prop"]):
-            with open(os.path.abspath(cal_setting["input_prop"]), "r") as fin:
+            with open(os.path.abspath(cal_setting["input_prop"])) as fin:
                 fc = fin.read()
 
         else:
             if "etol" in cal_setting:
                 dlog.info(
-                    "%s setting etol to %s"
-                    % (self.make_input_file.__name__, cal_setting["etol"])
+                    "{} setting etol to {}".format(
+                        self.make_input_file.__name__, cal_setting["etol"]
+                    )
                 )
                 etol = cal_setting["etol"]
             if "ftol" in cal_setting:
                 dlog.info(
-                    "%s setting ftol to %s"
-                    % (self.make_input_file.__name__, cal_setting["ftol"])
+                    "{} setting ftol to {}".format(
+                        self.make_input_file.__name__, cal_setting["ftol"]
+                    )
                 )
                 ftol = cal_setting["ftol"]
             if "maxiter" in cal_setting:
                 dlog.info(
-                    "%s setting maxiter to %s"
-                    % (self.make_input_file.__name__, cal_setting["maxiter"])
+                    "{} setting maxiter to {}".format(
+                        self.make_input_file.__name__, cal_setting["maxiter"]
+                    )
                 )
                 maxiter = cal_setting["maxiter"]
             if "maxeval" in cal_setting:
                 dlog.info(
-                    "%s setting maxeval to %s"
-                    % (self.make_input_file.__name__, cal_setting["maxeval"])
+                    "{} setting maxeval to {}".format(
+                        self.make_input_file.__name__, cal_setting["maxeval"]
+                    )
                 )
                 maxeval = cal_setting["maxeval"]
 
@@ -300,7 +304,7 @@ def compute(self, output_dir):
             force = []
             virial = []
             stress = []
-            with open(dump_lammps, "r") as fin:
+            with open(dump_lammps) as fin:
                 dump = fin.read().split("\n")
             dumptime = []
             for idx, ii in enumerate(dump):
@@ -354,7 +358,7 @@ def compute(self, output_dir):
                         fz = float(dump[idx + 9 + jj].split()[7])
                         force[-1].append([fx, fy, fz])
 
-            with open(log_lammps, "r") as fp:
+            with open(log_lammps) as fp:
                 if "Total wall time:" not in fp.read():
                     warnings.warn("lammps not finished " + log_lammps + " skip")
                     return None
diff --git a/dpgen/auto_test/Property.py b/dpgen/auto_test/Property.py
index e0fb4d3c1..8b6a18f1b 100644
--- a/dpgen/auto_test/Property.py
+++ b/dpgen/auto_test/Property.py
@@ -11,8 +11,7 @@
 class Property(ABC):
     @abstractmethod
     def __init__(self, parameter):
-        """
-        Constructor
+        """Constructor.
 
         Parameters
         ----------
@@ -23,8 +22,7 @@ def __init__(self, parameter):
 
     @abstractmethod
     def make_confs(self, path_to_work, path_to_equi, refine=False):
-        """
-        Make configurations needed to compute the property.
+        """Make configurations needed to compute the property.
         The tasks directory will be named as path_to_work/task.xxxxxx
         IMPORTANT: handel the case when the directory exists.
 
@@ -47,31 +45,24 @@ def make_confs(self, path_to_work, path_to_equi, refine=False):
 
     @abstractmethod
     def post_process(self, task_list):
-        """
-        post_process the KPOINTS file in elastic.
-        """
+        """post_process the KPOINTS file in elastic."""
         pass
 
     @property
     @abstractmethod
     def task_type(self):
-        """
-        Return the type of each computational task, for example, 'relaxation', 'static'....
-        """
+        """Return the type of each computational task, for example, 'relaxation', 'static'...."""
         pass
 
     @property
     @abstractmethod
     def task_param(self):
-        """
-        Return the parameter of each computational task, for example, {'ediffg': 1e-4}
-        """
+        """Return the parameter of each computational task, for example, {'ediffg': 1e-4}."""
         pass
 
     def compute(self, output_file, print_file, path_to_work):
-        """
-        Postprocess the finished tasks to compute the property.
-        Output the result to a json database
+        """Postprocess the finished tasks to compute the property.
+        Output the result to a json database.
 
         Parameters
         ----------
@@ -107,8 +98,7 @@ def compute(self, output_file, print_file, path_to_work):
 
     @abstractmethod
     def _compute_lower(self, output_file, all_tasks, all_res):
-        """
-        Compute the property.
+        """Compute the property.
 
         Parameters
         ----------
diff --git a/dpgen/auto_test/Surface.py b/dpgen/auto_test/Surface.py
index da5770598..b04123cfb 100644
--- a/dpgen/auto_test/Surface.py
+++ b/dpgen/auto_test/Surface.py
@@ -11,7 +11,6 @@
 
 import dpgen.auto_test.lib.abacus as abacus
 import dpgen.auto_test.lib.vasp as vasp
-import dpgen.generator.lib.abacus_scf as abacus_scf
 from dpgen import dlog
 from dpgen.auto_test.Property import Property
 from dpgen.auto_test.refine import make_refine
@@ -83,7 +82,7 @@ def __init__(self, parameter, inter_param=None):
             parameter["init_from_suffix"] = parameter.get("init_from_suffix", "00")
             self.init_from_suffix = parameter["init_from_suffix"]
         self.parameter = parameter
-        self.inter_param = inter_param if inter_param != None else {"type": "vasp"}
+        self.inter_param = inter_param if inter_param is not None else {"type": "vasp"}
 
     def make_confs(self, path_to_work, path_to_equi, refine=False):
         path_to_work = os.path.abspath(path_to_work)
diff --git a/dpgen/auto_test/Task.py b/dpgen/auto_test/Task.py
index 848a8bebd..f293eb0bf 100644
--- a/dpgen/auto_test/Task.py
+++ b/dpgen/auto_test/Task.py
@@ -4,8 +4,7 @@
 class Task(ABC):
     @abstractmethod
     def __init__(self, inter_parameter, path_to_poscar):
-        """
-        Constructor
+        """Constructor.
 
         Parameters
         ----------
@@ -18,11 +17,10 @@ def __init__(self, inter_parameter, path_to_poscar):
 
     @abstractmethod
     def make_potential_files(self, output_dir):
-        """
-        Prepare potential files for a computational task.
+        """Prepare potential files for a computational task.
         For example, the VASP prepares POTCAR.
         DeePMD prepares frozen model(s).
-        IMPORTANT: Interaction should be stored in output_dir/inter.json
+        IMPORTANT: Interaction should be stored in output_dir/inter.json.
 
         Parameters
         ----------
@@ -40,8 +38,7 @@ def make_potential_files(self, output_dir):
 
     @abstractmethod
     def make_input_file(self, output_dir, task_type, task_param):
-        """
-        Prepare input files for a computational task
+        """Prepare input files for a computational task
         For example, the VASP prepares INCAR.
         LAMMPS (including DeePMD, MEAM...) prepares in.lammps.
 
@@ -62,8 +59,7 @@ def make_input_file(self, output_dir, task_type, task_param):
 
     @abstractmethod
     def compute(self, output_dir):
-        """
-        Compute output of the task.
+        """Compute output of the task.
         IMPORTANT: The output configuration should be converted and stored in a CONTCAR file.
 
         Parameters
@@ -89,25 +85,19 @@ def compute(self, output_dir):
     @staticmethod
     @abstractmethod
     def forward_files(self):
-        """
-        Return forward files.
-        """
+        """Return forward files."""
         pass
 
     @property
     @staticmethod
     @abstractmethod
     def forward_common_files(self):
-        """
-        Return forward common files.
-        """
+        """Return forward common files."""
         pass
 
     @property
     @staticmethod
     @abstractmethod
     def backward_files(self):
-        """
-        Return backward files.
-        """
+        """Return backward files."""
         pass
diff --git a/dpgen/auto_test/VASP.py b/dpgen/auto_test/VASP.py
index cf317a438..e5b38d2e6 100644
--- a/dpgen/auto_test/VASP.py
+++ b/dpgen/auto_test/VASP.py
@@ -41,7 +41,7 @@ def make_potential_files(self, output_dir):
                     for jj in ele_pot_list:
                         if ii == jj:
                             with open(
-                                os.path.join(self.potcar_prefix, self.potcars[jj]), "r"
+                                os.path.join(self.potcar_prefix, self.potcars[jj])
                             ) as fin:
                                 for line in fin:
                                     print(line.strip("\n"), file=fp)
@@ -54,7 +54,6 @@ def make_potential_files(self, output_dir):
                             if ii == jj:
                                 with open(
                                     os.path.join(self.potcar_prefix, self.potcars[jj]),
-                                    "r",
                                 ) as fin:
                                     for line in fin:
                                         print(line.strip("\n"), file=fp)
@@ -137,36 +136,41 @@ def make_input_file(self, output_dir, task_type, task_param):
 
             if "ediff" in cal_setting:
                 dlog.info(
-                    "%s setting EDIFF to %s"
-                    % (self.make_input_file.__name__, cal_setting["ediff"])
+                    "{} setting EDIFF to {}".format(
+                        self.make_input_file.__name__, cal_setting["ediff"]
+                    )
                 )
                 incar["EDIFF"] = cal_setting["ediff"]
 
             if "ediffg" in cal_setting:
                 dlog.info(
-                    "%s setting EDIFFG to %s"
-                    % (self.make_input_file.__name__, cal_setting["ediffg"])
+                    "{} setting EDIFFG to {}".format(
+                        self.make_input_file.__name__, cal_setting["ediffg"]
+                    )
                 )
                 incar["EDIFFG"] = cal_setting["ediffg"]
 
             if "encut" in cal_setting:
                 dlog.info(
-                    "%s setting ENCUT to %s"
-                    % (self.make_input_file.__name__, cal_setting["encut"])
+                    "{} setting ENCUT to {}".format(
+                        self.make_input_file.__name__, cal_setting["encut"]
+                    )
                 )
                 incar["ENCUT"] = cal_setting["encut"]
 
             if "kspacing" in cal_setting:
                 dlog.info(
-                    "%s setting KSPACING to %s"
-                    % (self.make_input_file.__name__, cal_setting["kspacing"])
+                    "{} setting KSPACING to {}".format(
+                        self.make_input_file.__name__, cal_setting["kspacing"]
+                    )
                 )
                 incar["KSPACING"] = cal_setting["kspacing"]
 
             if "kgamma" in cal_setting:
                 dlog.info(
-                    "%s setting KGAMMA to %s"
-                    % (self.make_input_file.__name__, cal_setting["kgamma"])
+                    "{} setting KGAMMA to {}".format(
+                        self.make_input_file.__name__, cal_setting["kgamma"]
+                    )
                 )
                 incar["KGAMMA"] = cal_setting["kgamma"]
 
@@ -201,7 +205,7 @@ def compute(self, output_dir):
         else:
             ls = LabeledSystem(outcar)
             stress = []
-            with open(outcar, "r") as fin:
+            with open(outcar) as fin:
                 lines = fin.read().split("\n")
             for line in lines:
                 if "in kB" in line:
diff --git a/dpgen/auto_test/Vacancy.py b/dpgen/auto_test/Vacancy.py
index 06a65d728..b298407d7 100644
--- a/dpgen/auto_test/Vacancy.py
+++ b/dpgen/auto_test/Vacancy.py
@@ -9,7 +9,6 @@
 from pymatgen.core.structure import Structure
 
 import dpgen.auto_test.lib.abacus as abacus
-import dpgen.generator.lib.abacus_scf as abacus_scf
 from dpgen import dlog
 from dpgen.auto_test.Property import Property
 from dpgen.auto_test.refine import make_refine
@@ -75,7 +74,7 @@ def __init__(self, parameter, inter_param=None):
             parameter["init_from_suffix"] = parameter.get("init_from_suffix", "00")
             self.init_from_suffix = parameter["init_from_suffix"]
         self.parameter = parameter
-        self.inter_param = inter_param if inter_param != None else {"type": "vasp"}
+        self.inter_param = inter_param if inter_param is not None else {"type": "vasp"}
 
     def make_confs(self, path_to_work, path_to_equi, refine=False):
         path_to_work = os.path.abspath(path_to_work)
@@ -242,7 +241,7 @@ def _compute_lower(self, output_file, all_tasks, all_res):
                 evac = task_result["energies"][-1] - equi_epa * natoms
 
                 supercell_index = loadfn(os.path.join(ii, "supercell.json"))
-                ptr_data += "%s: %7.3f  %7.3f %7.3f \n" % (
+                ptr_data += "{}: {:7.3f}  {:7.3f} {:7.3f} \n".format(
                     str(supercell_index) + "-" + structure_dir,
                     evac,
                     task_result["energies"][-1],
diff --git a/dpgen/auto_test/calculator.py b/dpgen/auto_test/calculator.py
index 90e800371..aba707b06 100644
--- a/dpgen/auto_test/calculator.py
+++ b/dpgen/auto_test/calculator.py
@@ -4,9 +4,7 @@
 
 
 def make_calculator(inter_parameter, path_to_poscar):
-    """
-    Make an instance of Task
-    """
+    """Make an instance of Task."""
     inter_type = inter_parameter["type"]
     if inter_type == "vasp":
         return VASP(inter_parameter, path_to_poscar)
diff --git a/dpgen/auto_test/common_equi.py b/dpgen/auto_test/common_equi.py
index 61f3eb115..bd37fb9e8 100644
--- a/dpgen/auto_test/common_equi.py
+++ b/dpgen/auto_test/common_equi.py
@@ -1,8 +1,6 @@
 import glob
 import os
 import shutil
-import warnings
-from multiprocessing import Pool
 
 from monty.serialization import dumpfn
 from packaging.version import Version
diff --git a/dpgen/auto_test/common_prop.py b/dpgen/auto_test/common_prop.py
index 1f3ea3461..1cd821a4a 100644
--- a/dpgen/auto_test/common_prop.py
+++ b/dpgen/auto_test/common_prop.py
@@ -1,6 +1,5 @@
 import glob
 import os
-import warnings
 from multiprocessing import Pool
 
 from packaging.version import Version
@@ -23,9 +22,7 @@
 
 
 def make_property_instance(parameters, inter_param):
-    """
-    Make an instance of Property
-    """
+    """Make an instance of Property."""
     prop_type = parameters["type"]
     if prop_type == "eos":
         return EOS(parameters, inter_param)
diff --git a/dpgen/auto_test/gen_confs.py b/dpgen/auto_test/gen_confs.py
index 9a17173e6..1554efd21 100755
--- a/dpgen/auto_test/gen_confs.py
+++ b/dpgen/auto_test/gen_confs.py
@@ -5,7 +5,7 @@
 import re
 
 from pymatgen.analysis.structure_matcher import StructureMatcher
-from pymatgen.ext.matproj import Composition, MPRester
+from pymatgen.ext.matproj import MPRester
 
 import dpgen.auto_test.lib.crys as crys
 
@@ -136,10 +136,10 @@ def _main():
 
     print("generate %s" % (args.elements))
     if len(args.elements) == 1:
-        gen_element(args.elements[0], key)
+        gen_element(args.elements[0], args.key)
         # gen_element_std(args.elements[0])
     else:
-        gen_alloy(args.elements, key)
+        gen_alloy(args.elements, args.key)
 
 
 if __name__ == "__main__":
diff --git a/dpgen/auto_test/lib/abacus.py b/dpgen/auto_test/lib/abacus.py
index e5f0e2bd5..6a90fea8f 100644
--- a/dpgen/auto_test/lib/abacus.py
+++ b/dpgen/auto_test/lib/abacus.py
@@ -1,7 +1,5 @@
 #!/usr/bin/python3
 import os
-import sys
-from unicodedata import numeric
 
 import dpdata
 import numpy as np
@@ -124,116 +122,6 @@
     "Mt": 268,
     "Rg": 272,
     "Hs": 277,
-    "H": 1.0079,
-    "He": 4.0026,
-    "Li": 6.941,
-    "Be": 9.0122,
-    "B": 10.811,
-    "C": 12.0107,
-    "N": 14.0067,
-    "O": 15.9994,
-    "F": 18.9984,
-    "Ne": 20.1797,
-    "Na": 22.9897,
-    "Mg": 24.305,
-    "Al": 26.9815,
-    "Si": 28.0855,
-    "P": 30.9738,
-    "S": 32.065,
-    "Cl": 35.453,
-    "K": 39.0983,
-    "Ar": 39.948,
-    "Ca": 40.078,
-    "Sc": 44.9559,
-    "Ti": 47.867,
-    "V": 50.9415,
-    "Cr": 51.9961,
-    "Mn": 54.938,
-    "Fe": 55.845,
-    "Ni": 58.6934,
-    "Co": 58.9332,
-    "Cu": 63.546,
-    "Zn": 65.39,
-    "Ga": 69.723,
-    "Ge": 72.64,
-    "As": 74.9216,
-    "Se": 78.96,
-    "Br": 79.904,
-    "Kr": 83.8,
-    "Rb": 85.4678,
-    "Sr": 87.62,
-    "Y": 88.9059,
-    "Zr": 91.224,
-    "Nb": 92.9064,
-    "Mo": 95.94,
-    "Tc": 98,
-    "Ru": 101.07,
-    "Rh": 102.9055,
-    "Pd": 106.42,
-    "Ag": 107.8682,
-    "Cd": 112.411,
-    "In": 114.818,
-    "Sn": 118.71,
-    "Sb": 121.76,
-    "I": 126.9045,
-    "Te": 127.6,
-    "Xe": 131.293,
-    "Cs": 132.9055,
-    "Ba": 137.327,
-    "La": 138.9055,
-    "Ce": 140.116,
-    "Pr": 140.9077,
-    "Nd": 144.24,
-    "Pm": 145,
-    "Sm": 150.36,
-    "Eu": 151.964,
-    "Gd": 157.25,
-    "Tb": 158.9253,
-    "Dy": 162.5,
-    "Ho": 164.9303,
-    "Er": 167.259,
-    "Tm": 168.9342,
-    "Yb": 173.04,
-    "Lu": 174.967,
-    "Hf": 178.49,
-    "Ta": 180.9479,
-    "W": 183.84,
-    "Re": 186.207,
-    "Os": 190.23,
-    "Ir": 192.217,
-    "Pt": 195.078,
-    "Au": 196.9665,
-    "Hg": 200.59,
-    "Tl": 204.3833,
-    "Pb": 207.2,
-    "Bi": 208.9804,
-    "Po": 209,
-    "At": 210,
-    "Rn": 222,
-    "Fr": 223,
-    "Ra": 226,
-    "Ac": 227,
-    "Pa": 231.0359,
-    "Th": 232.0381,
-    "Np": 237,
-    "U": 238.0289,
-    "Am": 243,
-    "Pu": 244,
-    "Cm": 247,
-    "Bk": 247,
-    "Cf": 251,
-    "Es": 252,
-    "Fm": 257,
-    "Md": 258,
-    "No": 259,
-    "Rf": 261,
-    "Lr": 262,
-    "Db": 262,
-    "Bh": 264,
-    "Sg": 266,
-    "Mt": 268,
-    "Rg": 272,
-    "Hs": 277,
 }
 key_words_list = [
     "ATOMIC_SPECIES",
@@ -246,14 +134,13 @@
 
 
 def poscar2stru(poscar, inter_param, stru="STRU"):
-    """
-    - poscar:           POSCAR for input
+    """- poscar:           POSCAR for input
     - inter_param:      dictionary of 'interaction' from param.json
                         some key words for ABACUS are:
                             - atom_masses:  a dictionary of atoms' masses
                             - orb_files:     a dictionary of orbital files
                             - deepks_desc:  a string of deepks descriptor file
-    - stru:            output filename, usally is 'STRU'
+    - stru:            output filename, usally is 'STRU'.
     """
     # if use dpdata.System, the structure will be rotated to make cell to be lower triangular
     with open(poscar) as fp:
@@ -311,15 +198,14 @@ def poscar2stru(poscar, inter_param, stru="STRU"):
 
 
 def stru_fix_atom(struf, fix_atom=[True, True, True]):
-    """
-    ...
+    """...
     ATOMIC_POSITIONS
     Cartesian               #Cartesian(Unit is LATTICE_CONSTANT)
     Si                      #Name of element
     0.0                     #Magnetic for this element.
     2                       #Number of atoms
     0.00 0.00 0.00 0 0 0    #x,y,z, move_x, move_y, move_z
-    0.25 0.25 0.25 0 0 0
+    0.25 0.25 0.25 0 0 0.
     """
     fix_xyz = ["0" if i else "1" for i in fix_atom]
     if os.path.isfile(struf):
@@ -342,7 +228,7 @@ def stru_fix_atom(struf, fix_atom=[True, True, True]):
             elif flag_atom_number:
                 flag_atom_number -= 1
                 x, y, z = lines[i].split()[:3]
-                lines[i] = "%s %s %s %s %s %s\n" % tuple([x, y, z] + fix_xyz)
+                lines[i] = "{} {} {} {} {} {}\n".format(*tuple([x, y, z] + fix_xyz))
             elif flag_read_coord_type and flag_read_atom_number:
                 flag_read_atom_number -= 1
             elif not flag_read_atom_number:
@@ -358,7 +244,7 @@ def stru_fix_atom(struf, fix_atom=[True, True, True]):
 
 
 def stru_scale(stru_in, stru_out, scale):
-    with open(stru_in, "r") as fin:
+    with open(stru_in) as fin:
         lines = fin.readlines()
     for i in range(len(lines)):
         if "LATTICE_CONSTANT" in lines[i]:
@@ -404,7 +290,7 @@ def make_kspacing_kpt(struf, kspacing):
 
 
 def check_finished(fname):
-    with open(fname, "r") as fp:
+    with open(fname) as fp:
         return "Total  Time  :" in fp.read()
 
 
@@ -421,7 +307,7 @@ def final_stru(abacus_path):
             calculation = line.split()[1]
         elif "out_stru" in line and line.split()[0] == "out_stru":
             out_stru = bool(line.split()[1])
-    logf = os.path.join(abacus_path, "OUT.%s/running_%s.log" % (suffix, calculation))
+    logf = os.path.join(abacus_path, f"OUT.{suffix}/running_{calculation}.log")
     if calculation in ["relax", "cell-relax"]:
         if not out_stru:
             return "OUT.%s/STRU_ION_D" % suffix
@@ -439,7 +325,7 @@ def final_stru(abacus_path):
                     else:
                         max_step -= 2
                     break
-            return "OUT.%s/STRU_ION%s_D" % (suffix, str(max_step))
+            return f"OUT.{suffix}/STRU_ION{str(max_step)}_D"
     elif calculation == "md":
         with open(logf) as f1:
             lines = f1.readlines()
diff --git a/dpgen/auto_test/lib/lammps.py b/dpgen/auto_test/lib/lammps.py
index cb27a8e98..d544d0d2b 100644
--- a/dpgen/auto_test/lib/lammps.py
+++ b/dpgen/auto_test/lib/lammps.py
@@ -1,9 +1,6 @@
 #!/usr/bin/env python3
 
 import os
-import random
-import subprocess as sp
-import sys
 
 import dpdata
 from dpdata.periodic_table import Element
@@ -13,9 +10,8 @@
 
 
 def cvt_lammps_conf(fin, fout, type_map, ofmt="lammps/data"):
-    """
-    Format convert from fin to fout, specify the output format by ofmt
-    Imcomplete situation
+    """Format convert from fin to fout, specify the output format by ofmt
+    Imcomplete situation.
     """
     supp_ofmt = ["lammps/dump", "lammps/data", "vasp/poscar"]
     supp_exts = ["dump", "lmp", "poscar/POSCAR"]
@@ -26,7 +22,7 @@ def cvt_lammps_conf(fin, fout, type_map, ofmt="lammps/data"):
         ofmt = "lammps/data"
     elif "poscar" in fout or "POSCAR" in fout:
         ofmt = "vasp/poscar"
-    if not ofmt in supp_ofmt:
+    if ofmt not in supp_ofmt:
         raise RuntimeError(
             "output format " + ofmt + " is not supported. use one of " + str(supp_ofmt)
         )
@@ -40,15 +36,14 @@ def cvt_lammps_conf(fin, fout, type_map, ofmt="lammps/data"):
 
 
 def apply_type_map(conf_file, deepmd_type_map, ptypes):
-    """
-    apply type map.
+    """Apply type map.
     conf_file:          conf file converted from POSCAR
     deepmd_type_map:    deepmd atom type map
-    ptypes:             atom types defined in POSCAR
+    ptypes:             atom types defined in POSCAR.
     """
     natoms = _get_conf_natom(conf_file)
     ntypes = len(deepmd_type_map)
-    with open(conf_file, "r") as fp:
+    with open(conf_file) as fp:
         lines = fp.read().split("\n")
     # with open(conf_file+'.bk', 'w') as fp:
     #     fp.write("\n".join(lines))
@@ -85,7 +80,7 @@ def apply_type_map(conf_file, deepmd_type_map, ptypes):
 
 
 def _get_ntype(conf):
-    with open(conf, "r") as fp:
+    with open(conf) as fp:
         lines = fp.read().split("\n")
     for ii in lines:
         if "atom types" in ii:
@@ -94,7 +89,7 @@ def _get_ntype(conf):
 
 
 def _get_conf_natom(conf):
-    with open(conf, "r") as fp:
+    with open(conf) as fp:
         lines = fp.read().split("\n")
     for ii in lines:
         if "atoms" in ii:
@@ -405,9 +400,7 @@ def make_lammps_press_relax(
 def make_lammps_phonon(
     conf, masses, interaction, param, etol=0, ftol=1e-10, maxiter=5000, maxeval=500000
 ):
-    """
-    make lammps input for elastic calculation
-    """
+    """Make lammps input for elastic calculation."""
     ret = ""
     ret += "clear\n"
     ret += "units 	metal\n"
@@ -426,7 +419,7 @@ def make_lammps_phonon(
 
 def _get_epa(lines):
     for ii in lines:
-        if ("Final energy per atoms" in ii) and (not "print" in ii):
+        if ("Final energy per atoms" in ii) and ("print" not in ii):
             return float(ii.split("=")[1].split()[0])
     raise RuntimeError(
         'cannot find key "Final energy per atoms" in lines, something wrong'
@@ -435,7 +428,7 @@ def _get_epa(lines):
 
 def _get_vpa(lines):
     for ii in lines:
-        if ("Final volume per atoms" in ii) and (not "print" in ii):
+        if ("Final volume per atoms" in ii) and ("print" not in ii):
             return float(ii.split("=")[1].split()[0])
     raise RuntimeError(
         'cannot find key "Final volume per atoms" in lines, something wrong'
@@ -444,7 +437,7 @@ def _get_vpa(lines):
 
 def _get_natoms(lines):
     for ii in lines:
-        if ("Total number of atoms" in ii) and (not "print" in ii):
+        if ("Total number of atoms" in ii) and ("print" not in ii):
             return int(ii.split("=")[1].split()[0])
     raise RuntimeError(
         'cannot find key "Total number of atoms" in lines, something wrong'
@@ -452,10 +445,8 @@ def _get_natoms(lines):
 
 
 def get_nev(log):
-    """
-    get natoms, energy_per_atom and volume_per_atom from lammps log
-    """
-    with open(log, "r") as fp:
+    """Get natoms, energy_per_atom and volume_per_atom from lammps log."""
+    with open(log) as fp:
         lines = fp.read().split("\n")
     epa = _get_epa(lines)
     vpa = _get_vpa(lines)
@@ -464,34 +455,28 @@ def get_nev(log):
 
 
 def get_base_area(log):
-    """
-    get base area
-    """
-    with open(log, "r") as fp:
+    """Get base area."""
+    with open(log) as fp:
         lines = fp.read().split("\n")
     for ii in lines:
-        if ("Final Base area" in ii) and (not "print" in ii):
+        if ("Final Base area" in ii) and ("print" not in ii):
             return float(ii.split("=")[1].split()[0])
 
 
 def get_stress(log):
-    """
-    get stress from lammps log
-    """
-    with open(log, "r") as fp:
+    """Get stress from lammps log."""
+    with open(log) as fp:
         lines = fp.read().split("\n")
     for ii in lines:
-        if ("Final Stress" in ii) and (not "print" in ii):
+        if ("Final Stress" in ii) and ("print" not in ii):
             vstress = [float(jj) for jj in ii.split("=")[1].split()]
     stress = util.voigt_to_stress(vstress)
     return stress
 
 
 def poscar_from_last_dump(dump, poscar_out, deepmd_type_map):
-    """
-    get poscar from the last frame of a lammps MD traj (dump format)
-    """
-    with open(dump, "r") as fp:
+    """Get poscar from the last frame of a lammps MD traj (dump format)."""
+    with open(dump) as fp:
         lines = fp.read().split("\n")
     step_idx = -1
     for idx, ii in enumerate(lines):
@@ -503,7 +488,7 @@ def poscar_from_last_dump(dump, poscar_out, deepmd_type_map):
         fp.write("\n".join(lines[step_idx:]))
     cvt_lammps_conf("tmp_dump", poscar_out, ofmt="vasp")
     os.remove("tmp_dump")
-    with open(poscar_out, "r") as fp:
+    with open(poscar_out) as fp:
         lines = fp.read().split("\n")
     types = [deepmd_type_map[int(ii.split("_")[1])] for ii in lines[5].split()]
     lines[5] = " ".join(types)
@@ -512,15 +497,15 @@ def poscar_from_last_dump(dump, poscar_out, deepmd_type_map):
 
 
 def check_finished_new(fname, keyword):
-    with open(fname, "r") as fp:
+    with open(fname) as fp:
         lines = fp.read().split("\n")
     flag = False
     for jj in lines:
-        if (keyword in jj) and (not "print" in jj):
+        if (keyword in jj) and ("print" not in jj):
             flag = True
     return flag
 
 
 def check_finished(fname):
-    with open(fname, "r") as fp:
+    with open(fname) as fp:
         return "Total wall time:" in fp.read()
diff --git a/dpgen/auto_test/lib/lmp.py b/dpgen/auto_test/lib/lmp.py
index 15705ec8a..e0894398a 100644
--- a/dpgen/auto_test/lib/lmp.py
+++ b/dpgen/auto_test/lib/lmp.py
@@ -170,7 +170,7 @@ def from_system_data(system):
     ret += "0 %f xlo xhi\n" % system["cell"][0][0]
     ret += "0 %f ylo yhi\n" % system["cell"][1][1]
     ret += "0 %f zlo zhi\n" % system["cell"][2][2]
-    ret += "%f %f %f xy xz yz\n" % (
+    ret += "{:f} {:f} {:f} xy xz yz\n".format(
         system["cell"][1][0],
         system["cell"][2][0],
         system["cell"][2][1],
diff --git a/dpgen/auto_test/lib/mfp_eosfit.py b/dpgen/auto_test/lib/mfp_eosfit.py
index 148c9b5f8..06a26d629 100755
--- a/dpgen/auto_test/lib/mfp_eosfit.py
+++ b/dpgen/auto_test/lib/mfp_eosfit.py
@@ -1,17 +1,13 @@
 #!/usr/bin/env python3
 
-from __future__ import division
 
 import argparse
 import os
-import sys
 
 import matplotlib.pyplot as plt
 import numpy as np
-import scipy.integrate as INT
-from scipy.interpolate import *
-from scipy.misc import derivative
-from scipy.optimize import curve_fit, fsolve, leastsq, minimize, root
+from scipy.interpolate import BPoly, LSQUnivariateSpline, UnivariateSpline, interp1d
+from scipy.optimize import fsolve, leastsq
 
 kb = 1.3806488e-23  # J K^-1
 kb_ev = 8.6173324e-05  # eV K^-1
@@ -81,9 +77,8 @@ def res_murnaghan(pars, y, x):
 
 
 def murnaghan(vol, pars):
-    """
-    Four-parameters murnaghan EOS.
-    From PRB 28,5480 (1983)
+    """Four-parameters murnaghan EOS.
+    From PRB 28,5480 (1983).
     """
     e0 = pars[0]
     b0 = pars[1]
@@ -108,10 +103,9 @@ def res_birch(pars, y, x):
 
 
 def birch(v, parameters):
-    """
-    From Intermetallic compounds: Principles and Practice, Vol. I: Princples
+    """From Intermetallic compounds: Principles and Practice, Vol. I: Princples
     Chapter 9 pages 195-210 by M. Mehl. B. Klein, D. Papaconstantopoulos
-    paper downloaded from Web
+    paper downloaded from Web.
 
     case where n=0
     """
@@ -146,9 +140,7 @@ def calc_props_mBM4(pars):
 
 
 def mBM4(vol, pars):
-    """
-    Birch-Murnaghan 4 pars equation from PRB 70, 224107, 3-order BM
-    """
+    """Birch-Murnaghan 4 pars equation from PRB 70, 224107, 3-order BM."""
     e0 = pars[0]
     b0 = pars[1]
     bp = pars[2]
@@ -171,9 +163,7 @@ def res_mBM5(pars, y, x):
 
 
 def mBM5(vol, pars):
-    """
-    modified BM5 EOS, Shang SL comput mater sci, 2010: 1040-1048
-    """
+    """Modified BM5 EOS, Shang SL comput mater sci, 2010: 1040-1048."""
     e0 = pars[0]
     b0 = pars[1]
     bp = pars[2]
@@ -207,9 +197,7 @@ def res_mBM4poly(pars, y, x):
 
 
 def mBM4poly(vol, parameters):
-    """
-    modified BM5 EOS, Shang SL comput mater sci, 2010: 1040-1048, original expressions.
-    """
+    """Modified BM5 EOS, Shang SL comput mater sci, 2010: 1040-1048, original expressions."""
     a = parameters[0]
     b = parameters[1]
     c = parameters[2]
@@ -283,9 +271,7 @@ def res_mBM5poly(pars, y, x):
 
 
 def mBM5poly(vol, pars):
-    """
-    modified BM5 EOS, Shang SL comput mater sci, 2010: 1040-1048, original expressions.
-    """
+    """Modified BM5 EOS, Shang SL comput mater sci, 2010: 1040-1048, original expressions."""
     a = pars[0]
     b = pars[1]
     c = pars[2]
@@ -395,9 +381,7 @@ def calc_props_BM4(pars):
 
 
 def BM4(vol, pars):
-    """
-    Birch-Murnaghan 4 pars equation from PRB 70, 224107, 3-order
-    """
+    """Birch-Murnaghan 4 pars equation from PRB 70, 224107, 3-order."""
     e0 = pars[0]
     b0 = pars[1]
     bp = pars[2]
@@ -416,9 +400,7 @@ def res_BM5(pars, y, x):
 
 
 def BM5(vol, pars):
-    """
-    Birch-Murnaghan 5 pars equation from PRB 70, 224107, 4-Order
-    """
+    """Birch-Murnaghan 5 pars equation from PRB 70, 224107, 4-Order."""
     e0 = pars[0]
     b0 = pars[1]
     b0p = pars[2]
@@ -445,9 +427,8 @@ def BM5(vol, pars):
 
 
 def rBM4(vol, pars):
-    """
-    Implementions as Alberto Otero-de-la-Roza, i.e. rBM4 is used here
-    Comput Physics Comm, 2011, 182: 1708-1720
+    """Implementions as Alberto Otero-de-la-Roza, i.e. rBM4 is used here
+    Comput Physics Comm, 2011, 182: 1708-1720.
     """
     e0 = pars[0]
     b0 = pars[1]
@@ -466,10 +447,9 @@ def res_rBM4(pars, y, x):
 
 
 def rBM4_pv(vol, pars):
-    """
-    Implementions as Alberto Otero-de-la-Roza, i.e. rBM4 is used here
+    """Implementions as Alberto Otero-de-la-Roza, i.e. rBM4 is used here
     Comput Physics Comm, 2011, 182: 1708-1720
-    Fit for V-P relations
+    Fit for V-P relations.
     """
     e0 = pars[0]
     b0 = pars[1]
@@ -482,15 +462,14 @@ def rBM4_pv(vol, pars):
     return P
 
 
-def res_rBM4_pv(par, y, x):
+def res_rBM4_pv(pars, y, x):
     res = y - rBM4_pv(x, pars)
     return res
 
 
 def rBM5(vol, pars):
-    """
-    Implementions as Alberto Otero-de-la-Roza, i.e. rBM5 is used here
-    Comput Physics Comm, 2011, 182: 1708-1720
+    """Implementions as Alberto Otero-de-la-Roza, i.e. rBM5 is used here
+    Comput Physics Comm, 2011, 182: 1708-1720.
     """
     e0 = pars[0]
     b0 = pars[1]
@@ -514,10 +493,9 @@ def res_rBM5(pars, y, x):
 
 
 def rBM5_pv(vol, pars):
-    """
-    Implementions as Alberto Otero-de-la-Roza, i.e. rBM5 is used here
+    """Implementions as Alberto Otero-de-la-Roza, i.e. rBM5 is used here
     Comput Physics Comm, 2011, 182: 1708-1720
-    Fit for V-P relations
+    Fit for V-P relations.
     """
     e0 = pars[0]
     b0 = pars[1]
@@ -538,7 +516,7 @@ def rBM5_pv(vol, pars):
     return P
 
 
-def res_rBM5_pv(par, y, x):
+def res_rBM5_pv(pars, y, x):
     res = y - rBM5_pv(x, pars)
     return res
 
@@ -551,9 +529,7 @@ def res_universal(pars, y, x):
 
 
 def universal(vol, parameters):
-    """
-    Universal equation of state(Vinet P et al., J. Phys.: Condens. Matter 1, p1941 (1989))
-    """
+    """Universal equation of state(Vinet P et al., J. Phys.: Condens. Matter 1, p1941 (1989))."""
     e0 = parameters[0]
     b0 = parameters[1]
     bp = parameters[2]
@@ -580,8 +556,7 @@ def res_LOG4(pars, y, x):
 
 
 def LOG4(vol, pars):
-    """
-    Natrual strain (Poirier-Tarantola)EOS with 4 paramters
+    """Natrual strain (Poirier-Tarantola)EOS with 4 paramters
     Seems only work in near-equillibrium range.
     """
     e0 = pars[0]
@@ -622,8 +597,7 @@ def calc_props_LOG4(pars):
 
 
 def rPT4(vol, pars):
-    """
-    Natrual strain EOS with 4 paramters
+    """Natrual strain EOS with 4 paramters
     Seems only work in near-equillibrium range.
     Implementions as Alberto Otero-de-la-Roza, i.e. rPT4 is used here
     Comput Physics Comm, 2011, 182: 1708-1720,
@@ -647,8 +621,7 @@ def res_rPT4(pars, y, x):
 
 
 def rPT4_pv(vol, pars):
-    """
-    Natrual strain (Poirier-Tarantola)EOS with 4 paramters
+    """Natrual strain (Poirier-Tarantola)EOS with 4 paramters
     Seems only work in near-equillibrium range.
     Implementions as Alberto Otero-de-la-Roza, i.e. rPT4 is used here
     Comput Physics Comm, 2011, 182: 1708-1720,
@@ -677,9 +650,7 @@ def res_LOG5(pars, y, x):
 
 
 def LOG5(vol, parameters):
-    """
-    Natrual strain (Poirier-Tarantola)EOS with 5 paramters
-    """
+    """Natrual strain (Poirier-Tarantola)EOS with 5 paramters."""
     e0 = parameters[0]
     b0 = parameters[1]
     b0p = parameters[2]
@@ -708,8 +679,7 @@ def LOG5(vol, parameters):
 
 
 def rPT5(vol, pars):
-    """
-    Natrual strain EOS with 4 paramters
+    """Natrual strain EOS with 4 paramters
     Seems only work in near-equillibrium range.
     Implementions as Alberto Otero-de-la-Roza, i.e. rPT5 is used here
     Comput Physics Comm, 2011, 182: 1708-1720,
@@ -738,8 +708,7 @@ def res_rPT5(pars, y, x):
 
 
 def rPT5_pv(vol, pars):
-    """
-    Natrual strain (Poirier-Tarantola)EOS with 5 paramters
+    """Natrual strain (Poirier-Tarantola)EOS with 5 paramters
     Implementions as Alberto Otero-de-la-Roza, i.e. rPT5 is used here
     Comput Physics Comm, 2011, 182: 1708-1720,
     in their article, labeled as PT3 (3-order), however, we mention it as
@@ -788,8 +757,7 @@ def calc_props_vinet(pars):
 
 
 def vinet(vol, pars):
-    """
-    Vinet equation from PRB 70, 224107
+    """Vinet equation from PRB 70, 224107
     Following, Shang Shunli et al., comput mater sci, 2010: 1040-1048, original expressions.
     """
     e0 = pars[0]
@@ -816,14 +784,14 @@ def vinet_pv(vol, pars):
     return P
 
 
-def res_vinet_pv(par, y, x):
+def res_vinet_pv(pars, y, x):
     res = y - vinet(x, pars)
     return res
 
 
 # ----------------------------------------------------------------------------------------
 def Li4p(V, parameters):
-    """Li JH, APL, 87, 194111 (2005)"""
+    """Li JH, APL, 87, 194111 (2005)."""
     E0 = parameters[0]
     B0 = parameters[1]
     BP = parameters[2]
@@ -884,9 +852,7 @@ def res_morse(p, en, volume):
 
 
 def morse_AB(volume, p):
-    """
-    morse_AB EOS formula from Song's FVT souces
-    """
+    """morse_AB EOS formula from Song's FVT souces."""
     # p0 = [e0, b0, bp, v0, bpp]
     E0 = p[0]
     A = p[1]
@@ -909,9 +875,8 @@ def res_morse_AB(p, en, volume):
 
 
 def morse_3p(volume, p):
-    """
-    morse_AB EOS formula from Song's FVT souces
-    A= 0.5*B
+    """morse_AB EOS formula from Song's FVT souces
+    A= 0.5*B.
     """
     # p0 = [e0, b0, bp, v0, bpp]
     E0 = p[0]
@@ -935,8 +900,7 @@ def res_morse_3p(p, en, volume):
 
 
 def morse_6p(vol, par):
-    """
-    Generalized Morse EOS proposed by Qin, see:
+    """Generalized Morse EOS proposed by Qin, see:
     Qin et al. Phys Rev B, 2008, 78, 214108.
     Qin et al. Phys Rev B, 2008, 77, 220103(R).
     """
@@ -985,9 +949,7 @@ def res_morse_6p(p, en, volume):
 
 # ----------------------------------------------------------------------------------------
 def mie(v, p):
-    """
-    Mie model for song's FVT
-    """
+    """Mie model for song's FVT."""
     # p0 = [e0, b0, bp, v0, bpp]
     E0 = p[0]
     m = p[1]
@@ -1006,9 +968,7 @@ def res_mie(p, e, v):
 
 
 def mie_simple(v, p):
-    """
-    Mie_simple model for song's FVT
-    """
+    """Mie_simple model for song's FVT."""
     # p0 = [e0, b0, bp, v0, bpp]
     E0 = p[0]
     m = 4
@@ -1028,9 +988,8 @@ def res_mie_simple(p, e, v):
 
 # ----------------------------------------------------------------------------------------
 def TEOS(v, par):
-    """
-    Holland, et al, Journal of Metamorphic Geology, 2011, 29(3): 333-383
-    Modified Tait equation of Huang & Chow
+    """Holland, et al, Journal of Metamorphic Geology, 2011, 29(3): 333-383
+    Modified Tait equation of Huang & Chow.
     """
     e0 = par[0]
     b0 = par[1]
@@ -1056,8 +1015,7 @@ def res_TEOS(p, e, v):
 
 # ----------------------------------------------------------------------------------------
 def SJX_v2(vol, par):
-    """
-    Sun Jiuxun, et al. J phys Chem Solids, 2005, 66: 773-782.
+    """Sun Jiuxun, et al. J phys Chem Solids, 2005, 66: 773-782.
     They said it is satified for the limiting condition at high pressure.
     """
     e0 = par[0]
@@ -1087,9 +1045,7 @@ def res_SJX_v2(p, e, v):
 
 
 def SJX_5p(vol, par):
-    """
-    SJX_5p's five parameters EOS, Physica B: Condens Mater, 2011, 406: 1276-1282
-    """
+    """SJX_5p's five parameters EOS, Physica B: Condens Mater, 2011, 406: 1276-1282."""
     e0 = par[0]
     a = par[1]
     b = par[2]
@@ -1188,7 +1144,7 @@ def read_vlp(fin, fstart, fend):
             cellc.append(c)
             cellba.append(ba)
             cellca.append(ca)
-    print("\n** Vmin = %f, Vmax = %f" % (min(vol), max(vol)))
+    print(f"\n** Vmin = {min(vol):f}, Vmax = {max(vol):f}")
 
     # some special conditions
     if fstart <= 0:
@@ -1268,7 +1224,7 @@ def read_velp(fin, fstart, fend):
             cellc.append(c)
             cellba.append(ba)
             cellca.append(ca)
-    print("\n** Vmin = %f, Vmax = %f" % (min(vol), max(vol)))
+    print(f"\n** Vmin = {min(vol):f}, Vmax = {max(vol):f}")
 
     # some special conditions
     if fstart <= 0:
@@ -1351,8 +1307,7 @@ def repro_vp(func, vol_i, pars):
 def ext_vec(
     func, fin, p0, fs, fe, vols=None, vole=None, ndata=101, refit=0, show_fig=False
 ):
-    """
-    extrapolate the data points for E-V based on the fitted parameters in small or
+    """Extrapolate the data points for E-V based on the fitted parameters in small or
     very large volume range.
     """
     # read fitted-parameters
@@ -1381,7 +1336,7 @@ def ext_vec(
             cax = cellca[-1]
         else:
             cax = sca(vx)
-        fw.write("%f\t%f\t%f\n" % (vx, ex, cax))
+        fw.write(f"{vx:f}\t{ex:f}\t{cax:f}\n")
         fw.flush()
     fw.close()
 
@@ -1406,7 +1361,7 @@ def ext_splint(xp, yp, order=3, method="unispl"):
         SPLINT = interp1d
         return SPLINT(xp, yp, order, bounds_error=False)
     elif method == "piecepoly":
-        SPLINT = PiecewisePolynomial
+        SPLINT = BPoly.from_derivatives
         return SPLINT(xp, yp, order)
     else:
         if method == "unispl":
@@ -1429,9 +1384,7 @@ def ext_velp(
     fout="ext_velp.dat",
     show_fig=False,
 ):
-    """
-    extrapolate the lattice parameters based on input data
-    """
+    """Extrapolate the lattice parameters based on input data."""
     # read file
     vol, eng, cella, cellb, cellc, cellba, cellca = read_velp(fin, fstart, fend)
 
@@ -1488,8 +1441,7 @@ def ext_velp(
     )
     for i in range(ndata):
         fw.write(
-            "%12.6f\t%12.6f\t%12.6f\t%12.6f\t%12.6f\t%12.6f\t%12.6f\t%12.6f\n"
-            % (
+            "{:12.6f}\t{:12.6f}\t{:12.6f}\t{:12.6f}\t{:12.6f}\t{:12.6f}\t{:12.6f}\t{:12.6f}\n".format(
                 vv[i],
                 ee[i],
                 cellaa[i],
@@ -1612,16 +1564,16 @@ def lsqfit_eos(
     if func == "morse_AB":
         e0, A, B, v0 = popt
         print("%12s\t%12s\t%12s\t%12s" % ("V0(A**3)", "A", "B", "E0(eV)"))
-        print("%12f\t%12f\t%12f\t%12f\n" % (v0, A, B, e0))
+        print(f"{v0:12f}\t{A:12f}\t{B:12f}\t{e0:12f}\n")
     elif func == "morse_3p":
         e0, A, v0 = popt
         B = 0.5 * A
         print("%12s\t%12s\t%12s\t%12s" % ("V0(A**3)", "A", "B", "E0(eV)"))
-        print("%12f\t%12f\t%12f\t%12f\n" % (v0, A, B, e0))
+        print(f"{v0:12f}\t{A:12f}\t{B:12f}\t{e0:12f}\n")
     elif func in ["mie", "mie_simple"]:
         e0, m, n, v0 = popt
         print("%12s\t%12s\t%12s\t%12s" % ("V0(A**3)", "m", "n", "E0(eV)"))
-        print("%12f\t%12f\t%12f\t%12f\n" % (v0, m, n, e0))
+        print(f"{v0:12f}\t{m:12f}\t{n:12f}\t{e0:12f}\n")
     elif func == "morse_6p":
         e0, b0, bp, v0, bpp, m, n = calc_props_morse_6p(popt)
         b0 = eV2GPa * b0
@@ -1630,9 +1582,7 @@ def lsqfit_eos(
             "%12s\t%12s\t%12s\t%12s\t%12s\t%12s\t%12s"
             % ("V0(A**3)", "B0(GPa)", "Bp", "E0(eV)", "Bpp(1/GPa)", "m", "n")
         )
-        print(
-            "%12f\t%12f\t%12f\t%12f\t%12f\t%12f\t%12f\n" % (v0, b0, bp, e0, bpp, m, n)
-        )
+        print(f"{v0:12f}\t{b0:12f}\t{bp:12f}\t{e0:12f}\t{bpp:12f}\t{m:12f}\t{n:12f}\n")
     elif func == "SJX_5p":
         e0, b0, bp, v0, n = calc_props_SJX_5p(popt)
         b0 = eV2GPa * b0
@@ -1640,7 +1590,7 @@ def lsqfit_eos(
             "%12s\t%12s\t%12s\t%12s\t%12s"
             % ("V0(A**3)", "B0(GPa)", "Bp", "E0(eV)", "n")
         )
-        print("%12f\t%12f\t%12f\t%12f\t%12f\n" % (v0, b0, bp, e0, n))
+        print(f"{v0:12f}\t{b0:12f}\t{bp:12f}\t{e0:12f}\t{n:12f}\n")
     elif func in ["mBM4poly", "mBM5poly", "mBM4", "LOG4", "vinet", "morse", "BM4"]:
         prop_func = eval("calc_props_" + func)
         e0, b0, bp, v0, bpp = prop_func(popt)
@@ -1650,7 +1600,7 @@ def lsqfit_eos(
             "%12s\t%12s\t%12s\t%12s\t%12s"
             % ("V0(A**3)", "B0(GPa)", "Bp", "E0(eV)", "Bpp(1/GPa)")
         )
-        print("%12f\t%12f\t%12f\t%12f\t%12f\n" % (v0, b0, bp, e0, bpp))
+        print(f"{v0:12f}\t{b0:12f}\t{bp:12f}\t{e0:12f}\t{bpp:12f}\n")
     else:
         e0, b0, bp, v0, bpp = popt
         b0 = eV2GPa * b0
@@ -1659,7 +1609,7 @@ def lsqfit_eos(
             "%12s\t%12s\t%12s\t%12s\t%12s"
             % ("V0(A**3)", "B0(GPa)", "Bp", "E0(eV)", "Bpp(1/GPa)")
         )
-        print("%12f\t%12f\t%12f\t%12f\t%12f\n" % (v0, b0, bp, e0, bpp))
+        print(f"{v0:12f}\t{b0:12f}\t{bp:12f}\t{e0:12f}\t{bpp:12f}\n")
 
     # write the fitted results in fit.out
     fw = open(fout, "w+")
@@ -1712,12 +1662,17 @@ def lsqfit_eos(
     )
     for i in range(len(vol)):
         fve.write(
-            "%20f\t%20f\t%20f\t%20f\n"
-            % (vol[i], repro_en[i], en[i], 100 * np.abs((en[i] - repro_en[i]) / en[i]))
+            "{:20f}\t{:20f}\t{:20f}\t{:20f}\n".format(
+                vol[i], repro_en[i], en[i], 100 * np.abs((en[i] - repro_en[i]) / en[i])
+            )
         )
         fve.flush()
         p_tmp = repro_press[i]
-        fvp.write("%20f\t%20f\t%20f\t%20f\n" % (vol[i], p_tmp, p_tmp / 100, p_tmp * 10))
+        fvp.write(
+            "{:20f}\t{:20f}\t{:20f}\t{:20f}\n".format(
+                vol[i], p_tmp, p_tmp / 100, p_tmp * 10
+            )
+        )
         fvp.flush()
     fve.close()
     fvp.close()
diff --git a/dpgen/auto_test/lib/pwscf.py b/dpgen/auto_test/lib/pwscf.py
index d3844497b..eb3efddcd 100644
--- a/dpgen/auto_test/lib/pwscf.py
+++ b/dpgen/auto_test/lib/pwscf.py
@@ -72,7 +72,7 @@ def _make_pwscf_03_config(sys_data):
     cc = 0
     for ii in range(ntypes):
         for jj in range(atom_numbs[ii]):
-            ret += "%s %f %f %f\n" % (
+            ret += "{} {:f} {:f} {:f}\n".format(
                 atom_names[ii],
                 coordinates[cc][0],
                 coordinates[cc][1],
@@ -116,7 +116,7 @@ def _make_smearing(fp_params):
         degauss = fp_params["sigma"]
     if (smearing is not None) and (smearing.split(":")[0] == "mp"):
         smearing = "mp"
-    if not (smearing in [None, "gauss", "mp", "fd"]):
+    if smearing not in [None, "gauss", "mp", "fd"]:
         raise RuntimeError("unknow smearing method " + smearing)
     return smearing, degauss
 
diff --git a/dpgen/auto_test/lib/util.py b/dpgen/auto_test/lib/util.py
index 76005bdbc..4e355fbd1 100644
--- a/dpgen/auto_test/lib/util.py
+++ b/dpgen/auto_test/lib/util.py
@@ -4,7 +4,6 @@
 import numpy as np
 import requests
 
-from dpgen import dlog
 from dpgen.auto_test.lib import abacus, lammps, vasp
 from dpgen.auto_test.lib.utils import cmd_append_log
 
@@ -28,10 +27,7 @@ def voigt_to_stress(inpt):
 def insert_data(task, task_type, username, file_name):
     assert task in ["eos", "elastic", "surf"]
     assert task_type in ["vasp", "deepmd"]
-    url = (
-        "http://115.27.161.2:5000/insert_test_data?username=%s&expr_type=%s&data_type=%s"
-        % (username, task_type, task)
-    )
+    url = f"http://115.27.161.2:5000/insert_test_data?username={username}&expr_type={task_type}&data_type={task}"
     res = requests.post(url, data=open(file_name).read())
     print("Successful upload!")
 
diff --git a/dpgen/auto_test/lib/utils.py b/dpgen/auto_test/lib/utils.py
index cba2f25fc..1fd4f7af7 100644
--- a/dpgen/auto_test/lib/utils.py
+++ b/dpgen/auto_test/lib/utils.py
@@ -29,7 +29,7 @@ def create_path(path):
 
 
 def replace(file_name, pattern, subst):
-    file_handel = open(file_name, "r")
+    file_handel = open(file_name)
     file_string = file_handel.read()
     file_handel.close()
     file_string = re.sub(pattern, subst, file_string)
@@ -71,4 +71,4 @@ def log_task(message):
 
 def record_iter(record, confs, ii, jj):
     with open(record, "a") as frec:
-        frec.write("%s %s %s\n" % (confs, ii, jj))
+        frec.write(f"{confs} {ii} {jj}\n")
diff --git a/dpgen/auto_test/lib/vasp.py b/dpgen/auto_test/lib/vasp.py
index 1aa0793b7..9efeea04a 100644
--- a/dpgen/auto_test/lib/vasp.py
+++ b/dpgen/auto_test/lib/vasp.py
@@ -3,9 +3,8 @@
 import warnings
 
 import numpy as np
-from pymatgen.io.vasp import Incar, Kpoints, Potcar
+from pymatgen.io.vasp import Incar, Kpoints
 
-import dpgen.auto_test.lib.lammps as lammps
 import dpgen.auto_test.lib.util as util
 from dpgen.generator.lib.vasp import incar_upper
 
@@ -30,14 +29,14 @@ class OutcarItemError(Exception):
 
 
 def regulate_poscar(poscar_in, poscar_out):
-    with open(poscar_in, "r") as fp:
+    with open(poscar_in) as fp:
         lines = fp.read().split("\n")
     names = lines[5].split()
     counts = [int(ii) for ii in lines[6].split()]
     assert len(names) == len(counts)
     uniq_name = []
     for ii in names:
-        if not (ii in uniq_name):
+        if ii not in uniq_name:
             uniq_name.append(ii)
     uniq_count = np.zeros(len(uniq_name), dtype=int)
     for nn, cc in zip(names, counts):
@@ -63,7 +62,7 @@ def regulate_poscar(poscar_in, poscar_out):
 
 
 def sort_poscar(poscar_in, poscar_out, new_names):
-    with open(poscar_in, "r") as fp:
+    with open(poscar_in) as fp:
         lines = fp.read().split("\n")
     names = lines[5].split()
     counts = [int(ii) for ii in lines[6].split()]
@@ -91,7 +90,7 @@ def sort_poscar(poscar_in, poscar_out, new_names):
 
 
 def perturb_xz(poscar_in, poscar_out, pert=0.01):
-    with open(poscar_in, "r") as fp:
+    with open(poscar_in) as fp:
         lines = fp.read().split("\n")
     zz = lines[4]
     az = [float(ii) for ii in zz.split()]
@@ -115,7 +114,7 @@ def reciprocal_box(box):
 def make_kspacing_kpoints(poscar, kspacing, kgamma):
     if type(kspacing) is not list:
         kspacing = [kspacing, kspacing, kspacing]
-    with open(poscar, "r") as fp:
+    with open(poscar) as fp:
         lines = fp.read().split("\n")
     scale = float(lines[1])
     box = []
@@ -135,7 +134,7 @@ def make_kspacing_kpoints(poscar, kspacing, kgamma):
 def get_energies(fname):
     if not check_finished(fname):
         warnings.warn("incomplete outcar: " + fname)
-    with open(fname, "r") as fp:
+    with open(fname) as fp:
         lines = fp.read().split("\n")
     try:
         ener = _get_energies(lines)
@@ -147,7 +146,7 @@ def get_energies(fname):
 def get_boxes(fname):
     if not check_finished(fname):
         warnings.warn("incomplete outcar: " + fname)
-    with open(fname, "r") as fp:
+    with open(fname) as fp:
         lines = fp.read().split("\n")
     try:
         ener = _get_boxes(lines)
@@ -159,7 +158,7 @@ def get_boxes(fname):
 def get_nev(fname):
     if not check_finished(fname):
         warnings.warn("incomplete outcar: " + fname)
-    with open(fname, "r") as fp:
+    with open(fname) as fp:
         lines = fp.read().split("\n")
     try:
         natoms = _get_natoms(lines)
@@ -174,7 +173,7 @@ def get_nev(fname):
 def get_stress(fname):
     if not check_finished(fname):
         warnings.warn("incomplete outcar: " + fname)
-    with open(fname, "r") as fp:
+    with open(fname) as fp:
         lines = fp.read().split("\n")
     try:
         stress = _get_stress(lines)[-1]
@@ -184,7 +183,7 @@ def get_stress(fname):
 
 
 def check_finished(fname):
-    with open(fname, "r") as fp:
+    with open(fname) as fp:
         return "Elapsed time (sec):" in fp.read()
 
 
@@ -397,13 +396,13 @@ def make_vasp_phonon_incar(
 
 
 def get_poscar_types(fname):
-    with open(fname, "r") as fp:
+    with open(fname) as fp:
         lines = fp.read().split("\n")
     return lines[5].split()
 
 
 def get_poscar_natoms(fname):
-    with open(fname, "r") as fp:
+    with open(fname) as fp:
         lines = fp.read().split("\n")
     return [int(ii) for ii in lines[6].split()]
 
@@ -432,24 +431,24 @@ def _poscar_scale_cartesian(str_in, scale):
         boxl = lines[ii].split()
         boxv = [float(ii) for ii in boxl]
         boxv = np.array(boxv) * scale
-        lines[ii] = "%.16e %.16e %.16e\n" % (boxv[0], boxv[1], boxv[2])
+        lines[ii] = f"{boxv[0]:.16e} {boxv[1]:.16e} {boxv[2]:.16e}\n"
     # scale coord
     for ii in range(8, 8 + numb_atoms):
         cl = lines[ii].split()
         cv = [float(ii) for ii in cl]
         cv = np.array(cv) * scale
-        lines[ii] = "%.16e %.16e %.16e\n" % (cv[0], cv[1], cv[2])
+        lines[ii] = f"{cv[0]:.16e} {cv[1]:.16e} {cv[2]:.16e}\n"
     return lines
 
 
 def poscar_natoms(poscar_in):
-    with open(poscar_in, "r") as fin:
+    with open(poscar_in) as fin:
         lines = list(fin)
     return _poscar_natoms(lines)
 
 
 def poscar_scale(poscar_in, poscar_out, scale):
-    with open(poscar_in, "r") as fin:
+    with open(poscar_in) as fin:
         lines = list(fin)
     if "D" == lines[7][0] or "d" == lines[7][0]:
         lines = _poscar_scale_direct(lines, scale)
@@ -462,7 +461,7 @@ def poscar_scale(poscar_in, poscar_out, scale):
 
 
 def poscar_vol(poscar_in):
-    with open(poscar_in, "r") as fin:
+    with open(poscar_in) as fin:
         lines = list(fin)
     box = []
     for ii in range(2, 5):
diff --git a/dpgen/auto_test/mpdb.py b/dpgen/auto_test/mpdb.py
index c6409013a..db1121e41 100644
--- a/dpgen/auto_test/mpdb.py
+++ b/dpgen/auto_test/mpdb.py
@@ -1,6 +1,5 @@
 import os
 
-from pymatgen.core import Structure
 from pymatgen.ext.matproj import MPRester, MPRestError
 
 from dpgen import dlog
diff --git a/dpgen/auto_test/refine.py b/dpgen/auto_test/refine.py
index d44bd15d7..cd0fcd8f0 100644
--- a/dpgen/auto_test/refine.py
+++ b/dpgen/auto_test/refine.py
@@ -58,7 +58,7 @@ def make_refine(init_from_suffix, output_suffix, path_to_work):
             os.symlink(os.path.relpath(init_poscar), POSCAR)
         else:
             raise FileNotFoundError(
-                "no %s or %s in the init_from directory" % (CONTCAR, POSCAR)
+                f"no {CONTCAR} or {POSCAR} in the init_from directory"
             )
     os.chdir(cwd)
 
diff --git a/dpgen/auto_test/reproduce.py b/dpgen/auto_test/reproduce.py
index ce4c7483c..ada3102fb 100644
--- a/dpgen/auto_test/reproduce.py
+++ b/dpgen/auto_test/reproduce.py
@@ -46,7 +46,7 @@ def make_repro(
         if os.path.exists(os.path.join(path_to_work, "element.out")):
             os.remove(os.path.join(path_to_work, "element.out"))
         fout_element = open(os.path.join(path_to_work, "element.out"), "a+")
-        fin_element = open(os.path.join(init_data_path_todo, "element.out"), "r")
+        fin_element = open(os.path.join(init_data_path_todo, "element.out"))
 
     for ii in init_data_task_todo:
         # get frame number
@@ -153,7 +153,7 @@ def post_repro(
             output_ener_tot.extend(output_task_result["energies"])
 
             init_epa = init_ener[jj - idid] / natoms
-            ptr_data += "%s %7.3f  %7.3f  %7.3f\n" % (
+            ptr_data += "{} {:7.3f}  {:7.3f}  {:7.3f}\n".format(
                 ii,
                 init_epa,
                 output_epa,
diff --git a/tests/auto_test/context.py b/tests/auto_test/context.py
index 454820555..37f558c74 100644
--- a/tests/auto_test/context.py
+++ b/tests/auto_test/context.py
@@ -2,7 +2,7 @@
 import sys
 
 sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "..")))
-from dpgen.auto_test.lib.vasp import *
+from dpgen.auto_test.lib.vasp import *  # noqa: F403
 
 
 def setUpModule():
diff --git a/tests/auto_test/test_abacus.py b/tests/auto_test/test_abacus.py
index bc3d4f9ca..9cfedd3d1 100644
--- a/tests/auto_test/test_abacus.py
+++ b/tests/auto_test/test_abacus.py
@@ -12,7 +12,7 @@
 
 sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), "..")))
 __package__ = "auto_test"
-from .context import setUpModule
+from .context import setUpModule  # noqa: F401
 
 
 class TestABACUS(unittest.TestCase):
diff --git a/tests/auto_test/test_abacus_equi.py b/tests/auto_test/test_abacus_equi.py
index d5583567d..c2a5ce144 100644
--- a/tests/auto_test/test_abacus_equi.py
+++ b/tests/auto_test/test_abacus_equi.py
@@ -1,5 +1,3 @@
-import glob
-import json
 import os
 import shutil
 import sys
@@ -12,7 +10,7 @@
 
 sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), "..")))
 __package__ = "auto_test"
-from .context import setUpModule
+from .context import setUpModule  # noqa: F401
 
 
 class TestEqui(unittest.TestCase):
diff --git a/tests/auto_test/test_abacus_property.py b/tests/auto_test/test_abacus_property.py
index 2e366278f..edcc3985c 100644
--- a/tests/auto_test/test_abacus_property.py
+++ b/tests/auto_test/test_abacus_property.py
@@ -20,7 +20,7 @@
 from dpgen.auto_test.Surface import Surface
 from dpgen.auto_test.Vacancy import Vacancy
 
-from .context import setUpModule
+from .context import setUpModule  # noqa: F401
 
 
 class TestABACUS(unittest.TestCase):
diff --git a/tests/auto_test/test_elastic.py b/tests/auto_test/test_elastic.py
index 0a4b83725..1a56655ae 100644
--- a/tests/auto_test/test_elastic.py
+++ b/tests/auto_test/test_elastic.py
@@ -1,14 +1,9 @@
 import glob
-import json
 import os
 import shutil
 import sys
 import unittest
 
-import dpdata
-import numpy as np
-from monty.serialization import dumpfn, loadfn
-from pymatgen.analysis.elasticity.strain import Deformation, Strain
 from pymatgen.core import Structure
 from pymatgen.io.vasp import Incar
 
@@ -17,7 +12,7 @@
 
 from dpgen.auto_test.Elastic import Elastic
 
-from .context import make_kspacing_kpoints, setUpModule
+from .context import setUpModule  # noqa: F401
 
 
 class TestElastic(unittest.TestCase):
diff --git a/tests/auto_test/test_eos.py b/tests/auto_test/test_eos.py
index de68fae95..bd3d15251 100644
--- a/tests/auto_test/test_eos.py
+++ b/tests/auto_test/test_eos.py
@@ -1,5 +1,4 @@
 import glob
-import json
 import os
 import shutil
 import sys
@@ -7,7 +6,7 @@
 
 import dpdata
 import numpy as np
-from monty.serialization import dumpfn, loadfn
+from monty.serialization import loadfn
 from pymatgen.io.vasp import Incar
 
 sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), "..")))
@@ -15,7 +14,7 @@
 
 from dpgen.auto_test.EOS import EOS
 
-from .context import make_kspacing_kpoints, setUpModule
+from .context import setUpModule  # noqa: F401
 
 
 class TestEOS(unittest.TestCase):
diff --git a/tests/auto_test/test_gamma.py b/tests/auto_test/test_gamma.py
index 7cdd97371..7268c58a2 100644
--- a/tests/auto_test/test_gamma.py
+++ b/tests/auto_test/test_gamma.py
@@ -1,33 +1,18 @@
 import glob
-import json
 import os
 import shutil
 import sys
 import unittest
 
-import dpdata
-import numpy as np
-from ase.lattice.cubic import BodyCenteredCubic as bcc
-from ase.lattice.cubic import FaceCenteredCubic as fcc
-from ase.lattice.hexagonal import HexagonalClosedPacked as hcp
-from monty.serialization import dumpfn, loadfn
 from pymatgen.core.structure import Structure
-from pymatgen.core.surface import SlabGenerator
-from pymatgen.io.ase import AseAtomsAdaptor
 from pymatgen.io.vasp import Incar
 
-import dpgen.auto_test.lib.vasp as vasp
-from dpgen import dlog
-from dpgen.auto_test.Property import Property
-from dpgen.auto_test.refine import make_refine
-from dpgen.auto_test.reproduce import make_repro, post_repro
-
 sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), "..")))
 __package__ = "auto_test"
 
 from dpgen.auto_test.Gamma import Gamma
 
-from .context import make_kspacing_kpoints, setUpModule
+from .context import setUpModule  # noqa: F401
 
 
 class TestGamma(unittest.TestCase):
@@ -115,7 +100,7 @@ def test_make_confs_bcc(self):
             st1_file = os.path.join(ii, "POSCAR.tmp")
             self.assertTrue(os.path.isfile(st1_file))
             st1 = Structure.from_file(st1_file)
-            with open(st1_file, mode="r") as f:
+            with open(st1_file) as f:
                 z_coord_str = f.readlines()[-1].split()[-2]
                 z_coord = float(z_coord_str)
             self.assertTrue(z_coord <= 1)
diff --git a/tests/auto_test/test_interstitial.py b/tests/auto_test/test_interstitial.py
index ce22631bb..51e8ec276 100644
--- a/tests/auto_test/test_interstitial.py
+++ b/tests/auto_test/test_interstitial.py
@@ -1,24 +1,20 @@
 import glob
-import json
 import os
 import shutil
 import sys
 import unittest
 
-import dpdata
 import numpy as np
-from monty.serialization import dumpfn, loadfn
 from pymatgen.analysis.defects.core import Interstitial as pmg_Interstitial
 from pymatgen.core import Structure
 from pymatgen.io.vasp import Incar
-from pymatgen.symmetry.analyzer import SpacegroupAnalyzer
 
 sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), "..")))
 __package__ = "auto_test"
 
 from dpgen.auto_test.Interstitial import Interstitial
 
-from .context import make_kspacing_kpoints, setUpModule
+from .context import setUpModule  # noqa: F401
 
 
 class TestInterstitial(unittest.TestCase):
diff --git a/tests/auto_test/test_lammps.py b/tests/auto_test/test_lammps.py
index a13f5c6a8..5bf420558 100644
--- a/tests/auto_test/test_lammps.py
+++ b/tests/auto_test/test_lammps.py
@@ -1,13 +1,9 @@
-import glob
-import json
 import os
 import shutil
 import sys
 import unittest
 
-import dpdata
-import numpy as np
-from monty.serialization import dumpfn, loadfn
+from monty.serialization import loadfn
 
 sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), "..")))
 __package__ = "auto_test"
@@ -15,7 +11,7 @@
 from dpgen.auto_test.Lammps import Lammps
 from dpgen.auto_test.lib.lammps import inter_deepmd
 
-from .context import make_kspacing_kpoints, setUpModule
+from .context import setUpModule  # noqa: F401
 
 
 class TestLammps(unittest.TestCase):
diff --git a/tests/auto_test/test_make_prop.py b/tests/auto_test/test_make_prop.py
index 2c63b5845..5e6649508 100644
--- a/tests/auto_test/test_make_prop.py
+++ b/tests/auto_test/test_make_prop.py
@@ -1,13 +1,10 @@
 import glob
-import json
 import os
 import shutil
 import sys
 import unittest
 
-import dpdata
-import numpy as np
-from monty.serialization import dumpfn, loadfn
+from monty.serialization import loadfn
 
 sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), "..")))
 __package__ = "auto_test"
@@ -16,7 +13,7 @@
 
 from dpgen.auto_test.common_prop import make_property
 
-from .context import make_kspacing_kpoints, setUpModule
+from .context import setUpModule  # noqa: F401
 
 
 class TestMakeProperty(unittest.TestCase):
diff --git a/tests/auto_test/test_mpdb.py b/tests/auto_test/test_mpdb.py
index 055240908..b27a84227 100644
--- a/tests/auto_test/test_mpdb.py
+++ b/tests/auto_test/test_mpdb.py
@@ -2,7 +2,6 @@
 import sys
 import unittest
 
-from monty.serialization import dumpfn, loadfn
 from pymatgen.analysis.structure_matcher import StructureMatcher
 from pymatgen.core import Structure
 
@@ -10,7 +9,7 @@
 __package__ = "auto_test"
 from dpgen.auto_test.mpdb import get_structure
 
-from .context import make_kspacing_kpoints, setUpModule
+from .context import setUpModule  # noqa: F401
 
 try:
     os.environ["MAPI_KEY"]
diff --git a/tests/auto_test/test_refine.py b/tests/auto_test/test_refine.py
index 279d43e90..5b698952c 100644
--- a/tests/auto_test/test_refine.py
+++ b/tests/auto_test/test_refine.py
@@ -1,22 +1,15 @@
 import glob
-import json
 import os
 import shutil
 import sys
 import unittest
 
-import dpdata
-import numpy as np
-from monty.serialization import dumpfn, loadfn
-from pymatgen.io.vasp import Incar
-
 sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), "..")))
 __package__ = "auto_test"
 
 from dpgen.auto_test.common_prop import make_property
-from dpgen.auto_test.refine import make_refine
 
-from .context import make_kspacing_kpoints, setUpModule
+from .context import setUpModule  # noqa: F401
 
 
 class TestMakeProperty(unittest.TestCase):
diff --git a/tests/auto_test/test_surface.py b/tests/auto_test/test_surface.py
index b6abdfa26..228fb2504 100644
--- a/tests/auto_test/test_surface.py
+++ b/tests/auto_test/test_surface.py
@@ -1,13 +1,10 @@
 import glob
-import json
 import os
 import shutil
 import sys
 import unittest
 
-import dpdata
-import numpy as np
-from monty.serialization import dumpfn, loadfn
+from monty.serialization import loadfn
 from pymatgen.core import Structure
 from pymatgen.core.surface import SlabGenerator
 from pymatgen.io.vasp import Incar
@@ -17,7 +14,7 @@
 
 from dpgen.auto_test.Surface import Surface
 
-from .context import make_kspacing_kpoints, setUpModule
+from .context import setUpModule  # noqa: F401
 
 
 class TestSurface(unittest.TestCase):
diff --git a/tests/auto_test/test_vacancy.py b/tests/auto_test/test_vacancy.py
index b2e348573..8ee680b69 100644
--- a/tests/auto_test/test_vacancy.py
+++ b/tests/auto_test/test_vacancy.py
@@ -1,13 +1,10 @@
 import glob
-import json
 import os
 import shutil
 import sys
 import unittest
 
-import dpdata
 import numpy as np
-from monty.serialization import dumpfn, loadfn
 from pymatgen.analysis.defects.core import Vacancy as pmg_Vacancy
 from pymatgen.core import Structure
 from pymatgen.io.vasp import Incar
@@ -18,7 +15,7 @@
 
 from dpgen.auto_test.Vacancy import Vacancy
 
-from .context import make_kspacing_kpoints, setUpModule
+from .context import setUpModule  # noqa: F401
 
 
 class TestVacancy(unittest.TestCase):
diff --git a/tests/auto_test/test_vasp.py b/tests/auto_test/test_vasp.py
index e994c8906..0fbe60b60 100644
--- a/tests/auto_test/test_vasp.py
+++ b/tests/auto_test/test_vasp.py
@@ -1,14 +1,10 @@
-import glob
-import json
 import os
 import shutil
 import sys
 import unittest
 
-import dpdata
 import numpy as np
-from dpdata import LabeledSystem
-from monty.serialization import dumpfn, loadfn
+from monty.serialization import loadfn
 from pymatgen.io.vasp import Incar
 
 sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), "..")))
@@ -17,7 +13,7 @@
 from dpgen.auto_test.VASP import VASP
 from dpgen.generator.lib.vasp import incar_upper
 
-from .context import make_kspacing_kpoints, setUpModule
+from .context import setUpModule  # noqa: F401
 
 
 class TestVASP(unittest.TestCase):
@@ -123,7 +119,7 @@ def test_make_input_file_5(self):
         incar = incar_upper(Incar.from_file(os.path.join(self.equi_path, "INCAR")))
         self.assertEqual(incar["ISIF"], 6)
 
-    def test_make_input_file_5(self):
+    def test_make_input_file_6(self):
         param = self.task_param.copy()
         param["cal_setting"] = {
             "relax_pos": False,
diff --git a/tests/auto_test/test_vasp_equi.py b/tests/auto_test/test_vasp_equi.py
index 37c7f6c60..1195660d0 100644
--- a/tests/auto_test/test_vasp_equi.py
+++ b/tests/auto_test/test_vasp_equi.py
@@ -1,23 +1,18 @@
-import glob
-import json
 import os
 import shutil
 import sys
 import unittest
 
-import dpdata
-import numpy as np
-from monty.serialization import dumpfn, loadfn
+from monty.serialization import loadfn
 
 sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), "..")))
 __package__ = "auto_test"
 
 from pymatgen.io.vasp import Incar
 
-from dpgen.auto_test.calculator import make_calculator
 from dpgen.auto_test.common_equi import make_equi, post_equi
 
-from .context import make_kspacing_kpoints, setUpModule
+from .context import setUpModule  # noqa: F401
 
 
 class TestEqui(unittest.TestCase):
diff --git a/tests/auto_test/test_vasp_equi_std.py b/tests/auto_test/test_vasp_equi_std.py
index 5f513dbaa..d5f3061be 100644
--- a/tests/auto_test/test_vasp_equi_std.py
+++ b/tests/auto_test/test_vasp_equi_std.py
@@ -1,23 +1,18 @@
-import glob
-import json
 import os
 import shutil
 import sys
 import unittest
 
-import dpdata
-import numpy as np
-from monty.serialization import dumpfn, loadfn
+from monty.serialization import loadfn
 
 sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), "..")))
 __package__ = "auto_test"
 
 from pymatgen.io.vasp import Incar
 
-from dpgen.auto_test.calculator import make_calculator
-from dpgen.auto_test.common_equi import make_equi, post_equi
+from dpgen.auto_test.common_equi import make_equi
 
-from .context import make_kspacing_kpoints, setUpModule
+from .context import setUpModule  # noqa: F401
 
 
 class TestEqui(unittest.TestCase):
diff --git a/tests/auto_test/test_vasp_kspacing.py b/tests/auto_test/test_vasp_kspacing.py
index cac726a8a..43adfc2c3 100644
--- a/tests/auto_test/test_vasp_kspacing.py
+++ b/tests/auto_test/test_vasp_kspacing.py
@@ -1,18 +1,17 @@
 import glob
-import json
 import os
-import shutil
 import sys
 import unittest
 
-import dpdata
 import numpy as np
 
 sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), "..")))
 __package__ = "auto_test"
-from pymatgen.io.vasp import Incar, Kpoints
 
-from .context import make_kspacing_kpoints, setUpModule
+from .context import (
+    make_kspacing_kpoints,
+    setUpModule,  # noqa: F401
+)
 
 
 class TestVASPMakeKpoint(unittest.TestCase):
diff --git a/tests/data/context.py b/tests/data/context.py
index 4c65e8fd7..4697fc89d 100644
--- a/tests/data/context.py
+++ b/tests/data/context.py
@@ -2,7 +2,7 @@
 import sys
 
 sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "..")))
-from dpgen.data.gen import *
+from dpgen.data.gen import *  # noqa: F403
 
 param_file = "al.json"
 abacus_param_file = "ch4.json"
diff --git a/tests/data/context_bulk.py b/tests/data/context_bulk.py
index 9602a2e12..a6b3567a7 100644
--- a/tests/data/context_bulk.py
+++ b/tests/data/context_bulk.py
@@ -2,7 +2,7 @@
 import sys
 
 sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "..")))
-from dpgen.data.gen import *
+from dpgen.data.gen import *  # noqa: F403
 
 param_file = "alloy.json"
 abacus_param_file = "CuW.json"
diff --git a/tests/data/context_surf.py b/tests/data/context_surf.py
index e4ad3516a..4a5bd2ecb 100644
--- a/tests/data/context_surf.py
+++ b/tests/data/context_surf.py
@@ -2,6 +2,6 @@
 import sys
 
 sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "..")))
-from dpgen.data.surf import *
+from dpgen.data.surf import *  # noqa: F403
 
 param_file = "surf.json"
diff --git a/tests/data/context_surf_poscar.py b/tests/data/context_surf_poscar.py
index 11d15717f..f3cf6bc77 100644
--- a/tests/data/context_surf_poscar.py
+++ b/tests/data/context_surf_poscar.py
@@ -2,6 +2,6 @@
 import sys
 
 sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "..")))
-from dpgen.data.surf import *
+from dpgen.data.surf import *  # noqa: F403
 
 param_file = "surf_poscar.json"
diff --git a/tests/data/test_coll_abacus.py b/tests/data/test_coll_abacus.py
index e6e1fd564..63e2d6e7d 100644
--- a/tests/data/test_coll_abacus.py
+++ b/tests/data/test_coll_abacus.py
@@ -1,4 +1,3 @@
-import glob
 import json
 import os
 import shutil
@@ -10,12 +9,17 @@
 
 sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), "..")))
 __package__ = "data"
-from .context import abacus_param_file, coll_abacus_md, out_dir_name, setUpModule
+from .context import (
+    abacus_param_file,
+    coll_abacus_md,
+    out_dir_name,
+    setUpModule,  # noqa: F401
+)
 
 
 class TestCollAbacus(unittest.TestCase):
     def setUp(self):
-        with open(abacus_param_file, "r") as fp:
+        with open(abacus_param_file) as fp:
             jdata = json.load(fp)
         self.odir = out_dir_name(jdata)
         assert os.path.isdir(
@@ -40,7 +44,7 @@ def tearDown(self):
         shutil.rmtree(self.odir)
 
     def test_coll(self):
-        with open(abacus_param_file, "r") as fp:
+        with open(abacus_param_file) as fp:
             jdata = json.load(fp)
         jdata["out_dir"] = self.odir
         print(os.getcwd())
diff --git a/tests/data/test_coll_vasp.py b/tests/data/test_coll_vasp.py
index 75afc41d1..bb3d9c877 100644
--- a/tests/data/test_coll_vasp.py
+++ b/tests/data/test_coll_vasp.py
@@ -1,4 +1,3 @@
-import glob
 import json
 import os
 import shutil
@@ -10,12 +9,17 @@
 
 sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), "..")))
 __package__ = "data"
-from .context import coll_vasp_md, out_dir_name, param_file, setUpModule
+from .context import (
+    coll_vasp_md,
+    out_dir_name,
+    param_file,
+    setUpModule,  # noqa: F401
+)
 
 
 class TestCollVasp(unittest.TestCase):
     def setUp(self):
-        with open(param_file, "r") as fp:
+        with open(param_file) as fp:
             jdata = json.load(fp)
         self.odir = out_dir_name(jdata)
         assert os.path.isdir("out_data_02_md"), "out data for post fp vasp should exist"
@@ -49,7 +53,7 @@ def tearDown(self):
         shutil.rmtree(self.odir)
 
     def test_coll(self):
-        with open(param_file, "r") as fp:
+        with open(param_file) as fp:
             jdata = json.load(fp)
         jdata["out_dir"] = self.odir
         coll_vasp_md(jdata)
diff --git a/tests/data/test_disturb_abacus.py b/tests/data/test_disturb_abacus.py
index f64d8554c..365d3e723 100644
--- a/tests/data/test_disturb_abacus.py
+++ b/tests/data/test_disturb_abacus.py
@@ -8,7 +8,11 @@
 
 sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), "..")))
 __package__ = "data"
-from .context import *
+from .context import (
+    abacus_stru_file,
+    get_abacus_STRU,
+    setUpModule,  # noqa: F401
+)
 
 
 class TestPertAbacus(unittest.TestCase):
diff --git a/tests/data/test_gen_bulk.py b/tests/data/test_gen_bulk.py
index a8eefad87..64df71bc8 100644
--- a/tests/data/test_gen_bulk.py
+++ b/tests/data/test_gen_bulk.py
@@ -9,14 +9,24 @@
 
 sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), "..")))
 __package__ = "data"
-from .context import setUpModule
-from .context_bulk import *
+from .context import setUpModule  # noqa: F401
+from .context_bulk import (
+    create_path,
+    make_scale,
+    make_super_cell,
+    make_unit_cell,
+    make_vasp_relax,
+    out_dir_name,
+    param_file,
+    pert_scaled,
+    place_element,
+)
 
 
 class TestGenBulk(unittest.TestCase):
     def setUp(self):
         self.alloy = []
-        with open(param_file, "r") as fp:
+        with open(param_file) as fp:
             jdata = json.load(fp)
         if "init_fp_style" not in jdata:
             jdata["init_fp_style"] = "VASP"
diff --git a/tests/data/test_gen_bulk_abacus.py b/tests/data/test_gen_bulk_abacus.py
index 7223db6cf..83ef45fb9 100644
--- a/tests/data/test_gen_bulk_abacus.py
+++ b/tests/data/test_gen_bulk_abacus.py
@@ -7,14 +7,26 @@
 
 sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), "..")))
 __package__ = "data"
-from .context import setUpModule
-from .context_bulk import *
+from .context import setUpModule  # noqa: F401
+from .context_bulk import (
+    abacus_param_file,
+    create_path,
+    get_abacus_STRU,
+    make_abacus_relax,
+    make_scale_ABACUS,
+    make_super_cell_ABACUS,
+    make_super_cell_STRU,
+    make_unit_cell_ABACUS,
+    out_dir_name,
+    pert_scaled,
+    place_element_ABACUS,
+)
 
 
 class TestGenBulkABACUS(unittest.TestCase):
     def setUp(self):
         self.alloy = []
-        with open(abacus_param_file, "r") as fp:
+        with open(abacus_param_file) as fp:
             jdata = json.load(fp)
         out_dir = out_dir_name(jdata)
         self.out_dir = out_dir
diff --git a/tests/data/test_gen_surf.py b/tests/data/test_gen_surf.py
index e1a484d9b..1db270a09 100644
--- a/tests/data/test_gen_surf.py
+++ b/tests/data/test_gen_surf.py
@@ -9,8 +9,17 @@
 
 sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), "..")))
 __package__ = "data"
-from .context import setUpModule
-from .context_surf import *
+from .context import setUpModule  # noqa: F401
+from .context_surf import (
+    create_path,
+    make_scale,
+    make_super_cell_pymatgen,
+    make_vasp_relax,
+    out_dir_name,
+    param_file,
+    pert_scaled,
+    place_element,
+)
 
 
 class TestGenSurf(unittest.TestCase):
@@ -30,7 +39,7 @@ def setUp(self):
             "elong-7.000",
             "elong-8.000",
         ]
-        with open(param_file, "r") as fp:
+        with open(param_file) as fp:
             jdata = json.load(fp)
         out_dir = out_dir_name(jdata)
         jdata["out_dir"] = out_dir
diff --git a/tests/data/test_gen_surf_poscar.py b/tests/data/test_gen_surf_poscar.py
index 89ebfc33c..06f559a1e 100644
--- a/tests/data/test_gen_surf_poscar.py
+++ b/tests/data/test_gen_surf_poscar.py
@@ -9,8 +9,17 @@
 
 sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), "..")))
 __package__ = "data"
-from .context import setUpModule
-from .context_surf_poscar import *
+from .context import setUpModule  # noqa: F401
+from .context_surf_poscar import (
+    create_path,
+    make_scale,
+    make_super_cell_pymatgen,
+    make_vasp_relax,
+    out_dir_name,
+    param_file,
+    pert_scaled,
+    place_element,
+)
 
 
 class TestGenSurfPOSCAR(unittest.TestCase):
@@ -23,7 +32,7 @@ def setUp(self):
             "elong-2.000",
             "elong-4.000",
         ]
-        with open(param_file, "r") as fp:
+        with open(param_file) as fp:
             jdata = json.load(fp)
         out_dir = out_dir_name(jdata)
         jdata["out_dir"] = out_dir
diff --git a/tests/database/context.py b/tests/database/context.py
index fbe0aa186..f9fe353fd 100644
--- a/tests/database/context.py
+++ b/tests/database/context.py
@@ -2,10 +2,10 @@
 import sys
 
 sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "..")))
-import dpgen
-from dpgen.database.entry import Entry
-from dpgen.database.run import parsing_vasp
-from dpgen.database.vasp import DPPotcar, VaspInput
+import dpgen  # noqa: F401
+from dpgen.database.entry import Entry  # noqa: F401
+from dpgen.database.run import parsing_vasp  # noqa: F401
+from dpgen.database.vasp import DPPotcar, VaspInput  # noqa: F401
 
 
 def setUpModule():
diff --git a/tests/database/test_db_vasp.py b/tests/database/test_db_vasp.py
index 73b8f8ad9..514ef3fe2 100644
--- a/tests/database/test_db_vasp.py
+++ b/tests/database/test_db_vasp.py
@@ -6,16 +6,20 @@
 import unittest
 from glob import glob
 
-import numpy as np
-
 sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), "..")))
 __package__ = "database"
-from dpdata import LabeledSystem, System
-from monty.serialization import dumpfn, loadfn
-from monty.shutil import remove
+from dpdata import LabeledSystem
+from monty.serialization import loadfn
 from pymatgen.io.vasp import Incar, Kpoints, Poscar, Potcar
 
-from .context import DPPotcar, Entry, VaspInput, dpgen, parsing_vasp, setUpModule
+from .context import (
+    DPPotcar,
+    Entry,
+    VaspInput,
+    dpgen,
+    parsing_vasp,
+    setUpModule,  # noqa: F401
+)
 
 iter_pat = "02.fp/task.007.00000*"
 init_pat = "al.bcc.02x02x02/02.md/sys-0016/scale-1.000/00000*"
@@ -44,7 +48,7 @@ def setUp(self):
         self.ref_entries = loadfn(os.path.join(self.cwd, "data/entries.json"))
         self.init_path = sorted(glob(os.path.join(self.r_init_path, init_pat)))
         self.iter_path = sorted(glob(os.path.join(self.r_iter_path, iter_pat)))
-        with open("param_Al.json", "r") as fr:
+        with open("param_Al.json") as fr:
             jdata = json.load(fr)
         self.config_info_dict = jdata["config_info_dict"]
         self.skip_init = jdata["skip_init"]
diff --git a/tests/generator/context.py b/tests/generator/context.py
index 033f4cb50..619684d9a 100644
--- a/tests/generator/context.py
+++ b/tests/generator/context.py
@@ -2,15 +2,21 @@
 import sys
 
 sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "..")))
-from dpgen.generator.lib.ele_temp import NBandsEsti
-from dpgen.generator.lib.gaussian import _crd2frag, detect_multiplicity
-from dpgen.generator.lib.lammps import get_all_dumped_forces, get_dumped_forces
-from dpgen.generator.lib.make_calypso import make_calypso_input, write_model_devi_out
+from dpgen.generator.lib.ele_temp import NBandsEsti  # noqa: F401
+from dpgen.generator.lib.gaussian import _crd2frag, detect_multiplicity  # noqa: F401
+from dpgen.generator.lib.lammps import (
+    get_all_dumped_forces,  # noqa: F401
+    get_dumped_forces,  # noqa: F401
+)
+from dpgen.generator.lib.make_calypso import (
+    make_calypso_input,  # noqa: F401
+    write_model_devi_out,  # noqa: F401
+)
 from dpgen.generator.lib.parse_calypso import (
-    _parse_calypso_dis_mtx,
-    _parse_calypso_input,
+    _parse_calypso_dis_mtx,  # noqa: F401
+    _parse_calypso_input,  # noqa: F401
 )
-from dpgen.generator.run import *
+from dpgen.generator.run import *  # noqa: F403
 
 param_file = "param-mg-vasp.json"
 param_file_merge_traj = "param-mg-vasp_merge_traj.json"
diff --git a/tests/generator/gromacs/model_devi_case/model_devi.py b/tests/generator/gromacs/model_devi_case/model_devi.py
index 6c0b81568..7ce46e301 100755
--- a/tests/generator/gromacs/model_devi_case/model_devi.py
+++ b/tests/generator/gromacs/model_devi_case/model_devi.py
@@ -9,9 +9,7 @@
 
 
 def calc_model_devi_f(fs):
-    """
-    fs : numpy.ndarray, size of `n_models x n_frames x n_atoms x 3`
-    """
+    """Fs : numpy.ndarray, size of `n_models x n_frames x n_atoms x 3`."""
     fs_mean = np.mean(fs, axis=0)
     # print(fs_mean.shape)
     fs_err = np.sum((fs - fs_mean) ** 2, axis=-1)
diff --git a/tests/generator/test_calypso.py b/tests/generator/test_calypso.py
index cb4546bca..5d9abb854 100644
--- a/tests/generator/test_calypso.py
+++ b/tests/generator/test_calypso.py
@@ -1,13 +1,8 @@
-import glob
-import json
 import os
-import shutil
 import sys
-import textwrap
 import unittest
 from pathlib import Path
 
-import dpdata
 import numpy as np
 
 sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), "..")))
@@ -17,6 +12,7 @@
     _parse_calypso_dis_mtx,
     _parse_calypso_input,
     make_calypso_input,
+    setUpModule,  # noqa: F401
     write_model_devi_out,
 )
 
diff --git a/tests/generator/test_check_bad_box.py b/tests/generator/test_check_bad_box.py
index e40b42853..7de9070bd 100644
--- a/tests/generator/test_check_bad_box.py
+++ b/tests/generator/test_check_bad_box.py
@@ -1,16 +1,13 @@
-import glob
-import json
 import os
-import shutil
 import sys
 import unittest
 
-import dpdata
-import numpy as np
-
 sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), "..")))
 __package__ = "generator"
-from .context import check_bad_box
+from .context import (
+    check_bad_box,
+    setUpModule,  # noqa: F401
+)
 
 
 class TestCheckBadBox(unittest.TestCase):
diff --git a/tests/generator/test_check_cluster.py b/tests/generator/test_check_cluster.py
index fb969e047..e5e92ee49 100644
--- a/tests/generator/test_check_cluster.py
+++ b/tests/generator/test_check_cluster.py
@@ -1,14 +1,13 @@
-import importlib
 import os
 import sys
 import unittest
 
-import dpdata
-import numpy as np
-
 sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), "..")))
 __package__ = "generator"
-from .context import check_cluster, setUpModule
+from .context import (
+    check_cluster,
+    setUpModule,  # noqa: F401
+)
 
 
 class Test_check_cluster(unittest.TestCase):
diff --git a/tests/generator/test_cluster.py b/tests/generator/test_cluster.py
index 87151b4ef..193306d1d 100644
--- a/tests/generator/test_cluster.py
+++ b/tests/generator/test_cluster.py
@@ -9,7 +9,11 @@
 sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), "..")))
 __package__ = "generator"
 from .comp_sys import CompSys
-from .context import _crd2frag, setUpModule, take_cluster
+from .context import (
+    _crd2frag,
+    setUpModule,  # noqa: F401
+    take_cluster,
+)
 
 
 @unittest.skipIf(importlib.util.find_spec("openbabel") is None, "requires openbabel")
diff --git a/tests/generator/test_concat_fp_vasp_pp.py b/tests/generator/test_concat_fp_vasp_pp.py
index 989a09bd2..a9efcd5f6 100644
--- a/tests/generator/test_concat_fp_vasp_pp.py
+++ b/tests/generator/test_concat_fp_vasp_pp.py
@@ -1,16 +1,16 @@
-import glob
-import json
 import os
 import shutil
 import sys
 import unittest
 
-import dpdata
-import numpy as np
-
 sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), "..")))
 __package__ = "generator"
-from .context import fp_name, make_iter_name, setUpModule, sys_link_fp_vasp_pp
+from .context import (
+    fp_name,
+    make_iter_name,
+    setUpModule,  # noqa: F401
+    sys_link_fp_vasp_pp,
+)
 
 
 class TestConcatVASPPP(unittest.TestCase):
@@ -53,10 +53,10 @@ def test(self):
         )
         self.assertTrue(os.path.isfile(os.path.join(work_path, "POTCAR.000")))
         self.assertTrue(os.path.isfile(os.path.join(work_path, "POTCAR.001")))
-        with open((os.path.join(work_path, "POTCAR.000"))) as fp:
+        with open(os.path.join(work_path, "POTCAR.000")) as fp:
             pot = fp.read()
             self.assertEqual(pot, "O\nH\n")
-        with open((os.path.join(work_path, "POTCAR.001"))) as fp:
+        with open(os.path.join(work_path, "POTCAR.001")) as fp:
             pot = fp.read()
             self.assertEqual(pot, "H\nC\n")
         for ii in ["task.000.000000", "task.000.000001"]:
diff --git a/tests/generator/test_gromacs_engine.py b/tests/generator/test_gromacs_engine.py
index 4386b11b9..d74d1333d 100644
--- a/tests/generator/test_gromacs_engine.py
+++ b/tests/generator/test_gromacs_engine.py
@@ -1,6 +1,4 @@
-import glob
 import importlib
-import json
 import os
 import shutil
 import sys
@@ -12,7 +10,11 @@
 __package__ = "generator"
 dirname = os.path.join(os.path.abspath(os.path.dirname(__file__)), "gromacs")
 
-from .context import make_fp, make_model_devi
+from .context import (
+    make_fp,
+    make_model_devi,
+    setUpModule,  # noqa: F401
+)
 
 
 def _make_fake_graphs(train_path):
@@ -53,7 +55,6 @@ def setUp(self):
             ],
             "shuffle_poscar": False,
             "fp_style": "gaussian",
-            "shuffle_poscar": False,
             "fp_task_max": 20,
             "fp_task_min": 1,
             "fp_pp_path": "./",
@@ -105,7 +106,7 @@ def _copy_outputs(self, path_1, path_2):
         shutil.copytree(os.path.join(path_1, "traj"), os.path.join(path_2, "traj"))
 
     @unittest.skipIf(
-        importlib.util.find_spec("openbabel") != None,
+        importlib.util.find_spec("openbabel") is not None,
         "when openbabel is found, this test will be skipped. ",
     )
     def test_make_model_devi_gromacs_without_openbabel(self):
diff --git a/tests/generator/test_lammps.py b/tests/generator/test_lammps.py
index 2fbf011ca..df2d6acf0 100644
--- a/tests/generator/test_lammps.py
+++ b/tests/generator/test_lammps.py
@@ -1,17 +1,17 @@
-import glob
-import json
 import os
-import shutil
 import sys
 import textwrap
 import unittest
 
-import dpdata
 import numpy as np
 
 sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), "..")))
 __package__ = "generator"
-from .context import get_all_dumped_forces, get_dumped_forces
+from .context import (
+    get_all_dumped_forces,
+    get_dumped_forces,
+    setUpModule,  # noqa: F401
+)
 
 
 class TestGetDumpForce(unittest.TestCase):
@@ -54,7 +54,7 @@ def test_read_dump(self):
             self.assertAlmostEqual(ff[ii], self.expected_f[ii])
 
 
-class TestGetDumpForce(unittest.TestCase):
+class TestGetDumpForce2(unittest.TestCase):
     def setUp(self):
         file_content = textwrap.dedent(
             """\
diff --git a/tests/generator/test_make_fp.py b/tests/generator/test_make_fp.py
index a98c2b5d2..1b222dc90 100644
--- a/tests/generator/test_make_fp.py
+++ b/tests/generator/test_make_fp.py
@@ -14,7 +14,7 @@
 import scipy.constants as pc
 from pymatgen.io.vasp import Incar, Kpoints
 
-from .comp_sys import test_atom_names, test_atom_types, test_cell, test_coord
+from .comp_sys import test_atom_names
 from .context import (
     detect_multiplicity,
     machine_file,
@@ -36,10 +36,9 @@
     param_pwscf_file,
     param_pwscf_old_file,
     param_siesta_file,
-    parse_cur_job,
     ref_cp2k_file_exinput,
     ref_cp2k_file_input,
-    setUpModule,
+    setUpModule,  # noqa: F401
 )
 
 vasp_incar_ref = "PREC=A\n\
@@ -232,7 +231,7 @@ def _write_lammps_dump(sys, dump_file, f_idx=0):
         fp.write(str(natoms) + "\n")
         fp.write("ITEM: BOX BOUNDS xy xz yz pp pp pp\n")
         for ii in range(3):
-            fp.write("%f %f %f\n" % (bd[ii][0], bd[ii][1], tilt[ii]))
+            fp.write(f"{bd[ii][0]:f} {bd[ii][1]:f} {tilt[ii]:f}\n")
         fp.write("ITEM: ATOMS id type x y z\n")
         for ii in range(natoms):
             fp.write(
@@ -242,11 +241,10 @@ def _write_lammps_dump(sys, dump_file, f_idx=0):
 
 
 def _make_fake_md(idx, md_descript, atom_types, type_map, ele_temp=None):
-    """
-    md_descript: list of dimension
+    """md_descript: list of dimension
                  [n_sys][n_MD][n_frame]
     ele_temp: list of dimension
-                 [n_sys][n_MD]
+                 [n_sys][n_MD].
     """
     natoms = len(atom_types)
     ntypes = len(type_map)
@@ -281,11 +279,10 @@ def _make_fake_md(idx, md_descript, atom_types, type_map, ele_temp=None):
 
 
 def _make_fake_md_merge_traj(idx, md_descript, atom_types, type_map, ele_temp=None):
-    """
-    md_descript: list of dimension
+    """md_descript: list of dimension
                  [n_sys][n_MD][n_frame]
     ele_temp: list of dimension
-                 [n_sys][n_MD]
+                 [n_sys][n_MD].
     """
     natoms = len(atom_types)
     ntypes = len(type_map)
@@ -626,9 +623,9 @@ def test_make_fp_pwscf(self):
         setUpModule()
         if os.path.isdir("iter.000000"):
             shutil.rmtree("iter.000000")
-        with open(param_pwscf_file, "r") as fp:
+        with open(param_pwscf_file) as fp:
             jdata = json.load(fp)
-        with open(machine_file, "r") as fp:
+        with open(machine_file) as fp:
             mdata = json.load(fp)
         md_descript = []
         nsys = 2
@@ -659,9 +656,9 @@ def test_make_fp_pwscf_old(self):
         setUpModule()
         if os.path.isdir("iter.000000"):
             shutil.rmtree("iter.000000")
-        with open(param_pwscf_old_file, "r") as fp:
+        with open(param_pwscf_old_file) as fp:
             jdata = json.load(fp)
-        with open(machine_file, "r") as fp:
+        with open(machine_file) as fp:
             mdata = json.load(fp)
         md_descript = []
         nsys = 2
@@ -708,10 +705,10 @@ def test_make_fp_abacus(self):
         setUpModule()
         if os.path.isdir("iter.000000"):
             shutil.rmtree("iter.000000")
-        with open(param_abacus_post_file, "r") as fp:
+        with open(param_abacus_post_file) as fp:
             jdata = json.load(fp)
         fp.close()
-        with open(machine_file, "r") as fp:
+        with open(machine_file) as fp:
             mdata = json.load(fp)
         fp.close()
         md_descript = []
@@ -744,12 +741,12 @@ def test_make_fp_abacus_kspacing(self):
         setUpModule()
         if os.path.isdir("iter.000000"):
             shutil.rmtree("iter.000000")
-        with open(param_abacus_post_file, "r") as fp:
+        with open(param_abacus_post_file) as fp:
             jdata = json.load(fp)
         fp.close()
         jdata["user_fp_params"]["gamma_only"] = 0
         jdata["user_fp_params"]["kspacing"] = [0.04, 0.05, 0.06]
-        with open(machine_file, "r") as fp:
+        with open(machine_file) as fp:
             mdata = json.load(fp)
         fp.close()
         md_descript = []
@@ -788,10 +785,10 @@ def test_make_fp_abacus_from_input(self):
         setUpModule()
         if os.path.isdir("iter.000000"):
             shutil.rmtree("iter.000000")
-        with open(param_diy_abacus_post_file, "r") as fp:
+        with open(param_diy_abacus_post_file) as fp:
             jdata = json.load(fp)
         fp.close()
-        with open(machine_file, "r") as fp:
+        with open(machine_file) as fp:
             mdata = json.load(fp)
         fp.close()
         md_descript = []
@@ -826,7 +823,7 @@ def test_make_fp_amber_diff(self):
         setUpModule()
         if os.path.isdir("iter.000000"):
             shutil.rmtree("iter.000000")
-        with open(param_amber_file, "r") as fp:
+        with open(param_amber_file) as fp:
             jdata = json.load(fp)
         jdata["mdin_prefix"] = os.path.abspath(jdata["mdin_prefix"])
         task_dir = os.path.join(
@@ -851,9 +848,9 @@ def test_make_fp_siesta(self):
         setUpModule()
         if os.path.isdir("iter.000000"):
             shutil.rmtree("iter.000000")
-        with open(param_siesta_file, "r") as fp:
+        with open(param_siesta_file) as fp:
             jdata = json.load(fp)
-        with open(machine_file, "r") as fp:
+        with open(machine_file) as fp:
             mdata = json.load(fp)
         md_descript = []
         nsys = 2
@@ -886,9 +883,9 @@ def test_make_fp_vasp(self):
         setUpModule()
         if os.path.isdir("iter.000000"):
             shutil.rmtree("iter.000000")
-        with open(param_file, "r") as fp:
+        with open(param_file) as fp:
             jdata = json.load(fp)
-        with open(machine_file, "r") as fp:
+        with open(machine_file) as fp:
             mdata = json.load(fp)
         md_descript = []
         nsys = 2
@@ -923,9 +920,9 @@ def test_make_fp_vasp_merge_traj(self):
         setUpModule()
         if os.path.isdir("iter.000000"):
             shutil.rmtree("iter.000000")
-        with open(param_file_merge_traj, "r") as fp:
+        with open(param_file_merge_traj) as fp:
             jdata = json.load(fp)
-        with open(machine_file, "r") as fp:
+        with open(machine_file) as fp:
             mdata = json.load(fp)
         md_descript = []
         nsys = 2
@@ -954,9 +951,9 @@ def test_make_fp_vasp_old(self):
         setUpModule()
         if os.path.isdir("iter.000000"):
             shutil.rmtree("iter.000000")
-        with open(param_old_file, "r") as fp:
+        with open(param_old_file) as fp:
             jdata = json.load(fp)
-        with open(machine_file, "r") as fp:
+        with open(machine_file) as fp:
             mdata = json.load(fp)
         md_descript = []
         nsys = 2
@@ -990,9 +987,9 @@ def test_make_fp_vasp_old(self):
     def test_make_fp_vasp_less_sel(self):
         if os.path.isdir("iter.000000"):
             shutil.rmtree("iter.000000")
-        with open(param_file, "r") as fp:
+        with open(param_file) as fp:
             jdata = json.load(fp)
-        with open(machine_file, "r") as fp:
+        with open(machine_file) as fp:
             mdata = json.load(fp)
         md_descript = []
         nsys = 1
@@ -1028,10 +1025,10 @@ def test_make_fp_vasp_from_incar(self):
         setUpModule()
         if os.path.isdir("iter.000000"):
             shutil.rmtree("iter.000000")
-        with open(param_diy_file, "r") as fp:
+        with open(param_diy_file) as fp:
             jdata = json.load(fp)
         fp.close()
-        with open(machine_file, "r") as fp:
+        with open(machine_file) as fp:
             mdata = json.load(fp)
         fp.close()
         md_descript = []
@@ -1068,10 +1065,10 @@ def test_make_fp_vasp_ele_temp(self):
         setUpModule()
         if os.path.isdir("iter.000000"):
             shutil.rmtree("iter.000000")
-        with open(param_diy_file, "r") as fp:
+        with open(param_diy_file) as fp:
             jdata = json.load(fp)
         fp.close()
-        with open(machine_file, "r") as fp:
+        with open(machine_file) as fp:
             mdata = json.load(fp)
         fp.close()
         md_descript = []
@@ -1109,10 +1106,10 @@ def test_make_fp_vasp_multiple_trust_level(self):
         setUpModule()
         if os.path.isdir("iter.000000"):
             shutil.rmtree("iter.000000")
-        with open(param_multiple_trust_file, "r") as fp:
+        with open(param_multiple_trust_file) as fp:
             jdata = json.load(fp)
         fp.close()
-        with open(machine_file, "r") as fp:
+        with open(machine_file) as fp:
             mdata = json.load(fp)
         fp.close()
         md_descript = []
@@ -1151,10 +1148,10 @@ def make_fp_gaussian(self, multiplicity="auto"):
         setUpModule()
         if os.path.isdir("iter.000000"):
             shutil.rmtree("iter.000000")
-        with open(param_gaussian_file, "r") as fp:
+        with open(param_gaussian_file) as fp:
             jdata = json.load(fp)
         jdata["user_fp_params"]["multiplicity"] = multiplicity
-        with open(machine_file, "r") as fp:
+        with open(machine_file) as fp:
             mdata = json.load(fp)
         md_descript = []
         nsys = 2
@@ -1211,9 +1208,9 @@ def test_make_fp_cp2k(self):
         setUpModule()
         if os.path.isdir("iter.000000"):
             shutil.rmtree("iter.000000")
-        with open(param_cp2k_file, "r") as fp:
+        with open(param_cp2k_file) as fp:
             jdata = json.load(fp)
-        with open(machine_file, "r") as fp:
+        with open(machine_file) as fp:
             mdata = json.load(fp)
         md_descript = []
         nsys = 2
@@ -1236,7 +1233,7 @@ def test_make_fp_cp2k(self):
             jdata["model_devi_f_trust_hi"],
         )
         _check_poscars(self, 0, jdata["fp_task_max"], jdata["type_map"])
-        with open(ref_cp2k_file_input, "r") as f:
+        with open(ref_cp2k_file_input) as f:
             cp2k_input_ref = "".join(f.readlines())
         _check_cp2k_input_head(self, 0, cp2k_input_ref)
         _check_potcar(self, 0, jdata["fp_pp_path"], jdata["fp_pp_files"])
@@ -1246,9 +1243,9 @@ def test_make_fp_cp2k_exinput(self):
         setUpModule()
         if os.path.isdir("iter.000000"):
             shutil.rmtree("iter.000000")
-        with open(param_cp2k_file_exinput, "r") as fp:
+        with open(param_cp2k_file_exinput) as fp:
             jdata = json.load(fp)
-        with open(machine_file, "r") as fp:
+        with open(machine_file) as fp:
             mdata = json.load(fp)
         md_descript = []
         nsys = 2
@@ -1271,7 +1268,7 @@ def test_make_fp_cp2k_exinput(self):
             jdata["model_devi_f_trust_hi"],
         )
         _check_poscars(self, 0, jdata["fp_task_max"], jdata["type_map"])
-        with open(ref_cp2k_file_exinput, "r") as f:
+        with open(ref_cp2k_file_exinput) as f:
             cp2k_exinput_ref = "".join(f.readlines())
         _check_cp2k_input_head(self, 0, cp2k_exinput_ref)
         _check_potcar(self, 0, jdata["fp_pp_path"], jdata["fp_pp_files"])
@@ -1283,9 +1280,9 @@ def test_make_fp_pwmat(self):
         setUpModule()
         if os.path.isdir("iter.000000"):
             shutil.rmtree("iter.000000")
-        with open(param_pwmat_file, "r") as fp:
+        with open(param_pwmat_file) as fp:
             jdata = json.load(fp)
-        with open(machine_file, "r") as fp:
+        with open(machine_file) as fp:
             mdata = json.load(fp)
         md_descript = []
         nsys = 2
diff --git a/tests/generator/test_make_md.py b/tests/generator/test_make_md.py
index f22bb4236..165475939 100644
--- a/tests/generator/test_make_md.py
+++ b/tests/generator/test_make_md.py
@@ -5,10 +5,8 @@
 import shutil
 import sys
 import unittest
-from pathlib import Path
 
 import dpdata
-import numpy as np
 
 from dpgen.generator.run import parse_cur_job_sys_revmat
 
@@ -28,7 +26,6 @@
     revise_lmp_input_dump,
     revise_lmp_input_model,
     revise_lmp_input_plm,
-    setUpModule,
 )
 
 
@@ -143,9 +140,9 @@ def tearDown(self):
     def test_make_model_devi(self):
         if os.path.isdir("iter.000000"):
             shutil.rmtree("iter.000000")
-        with open(param_file, "r") as fp:
+        with open(param_file) as fp:
             jdata = json.load(fp)
-        with open(machine_file, "r") as fp:
+        with open(machine_file) as fp:
             mdata = json.load(fp)
         _make_fake_models(0, jdata["numb_models"])
         make_model_devi(0, jdata, mdata)
@@ -158,10 +155,10 @@ def test_make_model_devi(self):
     def test_make_model_devi_nopbc_npt(self):
         if os.path.isdir("iter.000000"):
             shutil.rmtree("iter.000000")
-        with open(param_file, "r") as fp:
+        with open(param_file) as fp:
             jdata = json.load(fp)
             jdata["model_devi_nopbc"] = True
-        with open(machine_file, "r") as fp:
+        with open(machine_file) as fp:
             mdata = json.load(fp)
         _make_fake_models(0, jdata["numb_models"])
         cwd = os.getcwd()
@@ -172,11 +169,11 @@ def test_make_model_devi_nopbc_npt(self):
     def test_make_model_devi_nopbc_nvt(self):
         if os.path.isdir("iter.000000"):
             shutil.rmtree("iter.000000")
-        with open(param_file, "r") as fp:
+        with open(param_file) as fp:
             jdata = json.load(fp)
             jdata["model_devi_nopbc"] = True
             jdata["model_devi_jobs"][0]["ensemble"] = "nvt"
-        with open(machine_file, "r") as fp:
+        with open(machine_file) as fp:
             mdata = json.load(fp)
         _make_fake_models(0, jdata["numb_models"])
         make_model_devi(0, jdata, mdata)
@@ -532,9 +529,9 @@ def tearDown(self):
     def test_make_model_devi(self):
         if os.path.isdir("iter.000000"):
             shutil.rmtree("iter.000000")
-        with open(param_amber_file, "r") as fp:
+        with open(param_amber_file) as fp:
             jdata = json.load(fp)
-        with open(machine_file, "r") as fp:
+        with open(machine_file) as fp:
             mdata = json.load(fp)
         jdata["sys_prefix"] = os.path.abspath(jdata["sys_prefix"])
         _make_fake_models(0, jdata["numb_models"])
diff --git a/tests/generator/test_make_train.py b/tests/generator/test_make_train.py
index e93cba251..c9e78338d 100644
--- a/tests/generator/test_make_train.py
+++ b/tests/generator/test_make_train.py
@@ -22,7 +22,7 @@
     param_file_v1,
     param_file_v1_et,
     run_train,
-    setUpModule,
+    setUpModule,  # noqa: F401
 )
 
 
@@ -52,7 +52,7 @@ def _comp_init_data(testCase, iter_idx, init_data_prefix, init_data_sys):
         sys1 = os.path.join("iter.%06d" % iter_idx, "00.train", "data.init", ii)
         testCase.assertTrue(
             _comp_sys_files(sys0, sys1),
-            "systems %s %s are not identical" % (sys0, sys1),
+            f"systems {sys0} {sys1} are not identical",
         )
 
 
@@ -197,7 +197,7 @@ def _check_model_inputs_v1(testCase, iter_idx, jdata, reuse=False):
             old_ratio = jdata["training_reuse_old_ratio"]
             testCase.assertEqual(
                 jdata0["training"]["auto_prob_style"],
-                "prob_sys_size; 0:1:%f; 1:2:%f" % (old_ratio, 1 - old_ratio),
+                f"prob_sys_size; 0:1:{old_ratio:f}; 1:2:{1 - old_ratio:f}",
             )
 
 
@@ -230,9 +230,9 @@ class TestMakeTrain(unittest.TestCase):
     def test_0(self):
         # No longer support for DeePMD-kit-0.x version.
         return
-        with open(param_file, "r") as fp:
+        with open(param_file) as fp:
             jdata = json.load(fp)
-        with open(machine_file, "r") as fp:
+        with open(machine_file) as fp:
             mdata = json.load(fp)
         fp_task_min = jdata["fp_task_min"]
         make_train(0, jdata, mdata)
@@ -250,9 +250,9 @@ def test_0(self):
     def test_1_data(self):
         # No longer support for DeePMD-kit-0.x version.
         return
-        with open(param_file, "r") as fp:
+        with open(param_file) as fp:
             jdata = json.load(fp)
-        with open(machine_file, "r") as fp:
+        with open(machine_file) as fp:
             mdata = json.load(fp)
         make_train(0, jdata, mdata)
         # make fake fp results #data == fp_task_min
@@ -276,9 +276,9 @@ def test_1_data(self):
     def test_1_skip(self):
         # No longer support for DeePMD-kit-0.x version.
         return
-        with open(param_file, "r") as fp:
+        with open(param_file) as fp:
             jdata = json.load(fp)
-        with open(machine_file, "r") as fp:
+        with open(machine_file) as fp:
             mdata = json.load(fp)
         make_train(0, jdata, mdata)
         # make fake fp results #data == fp_task_min - 1
@@ -295,10 +295,10 @@ def test_1_skip(self):
         shutil.rmtree("iter.000000")
 
     def test_1_data_v1(self):
-        with open(param_file_v1, "r") as fp:
+        with open(param_file_v1) as fp:
             jdata = json.load(fp)
             jdata.pop("use_ele_temp", None)
-        with open(machine_file_v1, "r") as fp:
+        with open(machine_file_v1) as fp:
             mdata = json.load(fp)
         make_train(0, jdata, mdata)
         # make fake fp results #data == fp_task_min
@@ -320,7 +320,7 @@ def test_1_data_v1(self):
         shutil.rmtree("iter.000000")
 
     def test_1_data_reuse_v1(self):
-        with open(param_file_v1, "r") as fp:
+        with open(param_file_v1) as fp:
             jdata = json.load(fp)
             jdata.pop("use_ele_temp", None)
             jdata["training_reuse_iter"] = 1
@@ -329,7 +329,7 @@ def test_1_data_reuse_v1(self):
             jdata["training_reuse_start_lr"] = 1e-4
             jdata["training_reuse_start_pref_e"] = 0.1
             jdata["training_reuse_start_pref_f"] = 100
-        with open(machine_file_v1, "r") as fp:
+        with open(machine_file_v1) as fp:
             mdata = json.load(fp)
         make_train(0, jdata, mdata)
         # make fake fp results #data == fp_task_min
@@ -364,9 +364,9 @@ def test_1_data_reuse_v1(self):
         shutil.rmtree("iter.000000")
 
     def test_1_data_v1_eletron_temp(self):
-        with open(param_file_v1_et, "r") as fp:
+        with open(param_file_v1_et) as fp:
             jdata = json.load(fp)
-        with open(machine_file_v1, "r") as fp:
+        with open(machine_file_v1) as fp:
             mdata = json.load(fp)
         make_train(0, jdata, mdata)
         # make fake fp results #data == fp_task_min
@@ -392,12 +392,12 @@ def test_1_data_v1_h5(self):
         dpdata.LabeledSystem("data/deepmd", fmt="deepmd/npy").to_deepmd_hdf5(
             "data/deepmd.hdf5"
         )
-        with open(param_file_v1, "r") as fp:
+        with open(param_file_v1) as fp:
             jdata = json.load(fp)
         jdata.pop("use_ele_temp", None)
         jdata["init_data_sys"].append("deepmd.hdf5")
         jdata["init_batch_size"].append("auto")
-        with open(machine_file_v1, "r") as fp:
+        with open(machine_file_v1) as fp:
             mdata = json.load(fp)
         make_train(0, jdata, mdata)
         # make fake fp results #data == fp_task_min
@@ -461,13 +461,13 @@ def test_1_data_v1_one_h5(self):
         dpdata.LabeledSystem("data/deepmd", fmt="deepmd/npy").to_deepmd_hdf5(
             "data/deepmd.hdf5"
         )
-        with open(param_file_v1, "r") as fp:
+        with open(param_file_v1) as fp:
             jdata = json.load(fp)
         jdata.pop("use_ele_temp", None)
         jdata["init_data_sys"].append("deepmd.hdf5")
         jdata["init_batch_size"].append("auto")
         jdata["one_h5"] = True
-        with open(machine_file_v1, "r") as fp:
+        with open(machine_file_v1) as fp:
             mdata = json.load(fp)
         make_train(0, jdata, mdata)
         # make fake fp results #data == fp_task_min
diff --git a/tests/generator/test_nbands_esti.py b/tests/generator/test_nbands_esti.py
index c5d9bcdb5..4d2dccafa 100644
--- a/tests/generator/test_nbands_esti.py
+++ b/tests/generator/test_nbands_esti.py
@@ -1,14 +1,13 @@
-import importlib
 import os
 import sys
 import unittest
 
-import dpdata
-import numpy as np
-
 sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), "..")))
 __package__ = "generator"
-from .context import NBandsEsti
+from .context import (
+    NBandsEsti,
+    setUpModule,  # noqa: F401
+)
 
 
 class TestNBandsEsti(unittest.TestCase):
@@ -54,7 +53,7 @@ def test_get_default_nbands(self):
         nb = NBandsEsti._get_default_nbands(res)
         self.assertEqual(nb, 66)
 
-    def test_get_default_nbands(self):
+    def test_get_default_nbands2(self):
         res = NBandsEsti._get_res("out_data_nbands_esti/mgal/")
         nb = NBandsEsti._get_default_nbands(res)
         self.assertEqual(nb, 124)
diff --git a/tests/generator/test_parse_cur_job.py b/tests/generator/test_parse_cur_job.py
index e03c920ea..fb0a5a911 100644
--- a/tests/generator/test_parse_cur_job.py
+++ b/tests/generator/test_parse_cur_job.py
@@ -2,11 +2,12 @@
 import sys
 import unittest
 
-import numpy as np
-
 sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), "..")))
 __package__ = "generator"
-from .context import machine_file, param_file, parse_cur_job, setUpModule
+from .context import (
+    parse_cur_job,
+    setUpModule,  # noqa: F401
+)
 
 
 class TestParseCurJob(unittest.TestCase):
diff --git a/tests/generator/test_post_fp.py b/tests/generator/test_post_fp.py
index c2404c1c4..5d3f5cc45 100644
--- a/tests/generator/test_post_fp.py
+++ b/tests/generator/test_post_fp.py
@@ -1,4 +1,3 @@
-import glob
 import json
 import os
 import shutil
@@ -12,31 +11,19 @@
 __package__ = "generator"
 from .comp_sys import (
     CompLabeledSys,
-    test_atom_names,
-    test_atom_types,
-    test_cell,
-    test_coord,
 )
 from .context import (
-    machine_file,
     param_abacus_post_file,
     param_amber_file,
     param_cp2k_file,
     param_file,
     param_gaussian_file,
-    param_old_file,
     param_pwmat_file,
     param_pwscf_file,
-    param_pwscf_old_file,
     param_siesta_file,
     post_fp,
-    post_fp_abacus_scf,
-    post_fp_cp2k,
-    post_fp_gaussian,
-    post_fp_pwscf,
-    post_fp_siesta,
     post_fp_vasp,
-    setUpModule,
+    setUpModule,  # noqa: F401
 )
 
 
@@ -76,7 +63,7 @@ def tearDown(self):
         shutil.rmtree("iter.000000")
 
     def test_post_fp_vasp_0(self):
-        with open(param_file, "r") as fp:
+        with open(param_file) as fp:
             jdata = json.load(fp)
         jdata["use_ele_temp"] = 2
         post_fp_vasp(0, jdata, rfailed=0.3)
@@ -126,7 +113,7 @@ def test_post_fp_vasp_0(self):
         self.assertEqual(list(list(aparam)[1]), [1, 1])
 
     def test_post_fp_vasp_1(self):
-        with open(param_file, "r") as fp:
+        with open(param_file) as fp:
             jdata = json.load(fp)
         jdata["use_ele_temp"] = 1
         post_fp_vasp(0, jdata, rfailed=0.3)
@@ -173,7 +160,7 @@ def test_post_fp_vasp_1(self):
         self.assertEqual(list(fparam), [100000])
 
     def test_post_fp_vasp_2(self):
-        with open(param_file, "r") as fp:
+        with open(param_file) as fp:
             jdata = json.load(fp)
         jdata["use_ele_temp"] = 1
         with self.assertRaises(RuntimeError):
@@ -192,7 +179,7 @@ def setUp(self):
         if os.path.isdir("iter.000000"):
             shutil.rmtree("iter.000000")
         shutil.copytree("out_data_post_fp_pwscf", "iter.000000")
-        with open(param_pwscf_file, "r") as fp:
+        with open(param_pwscf_file) as fp:
             jdata = json.load(fp)
         post_fp(0, jdata)
         self.system_1 = dpdata.LabeledSystem("iter.000000/orig", fmt="deepmd/raw")
@@ -213,7 +200,7 @@ def setUp(self):
         if os.path.isdir("iter.000000"):
             shutil.rmtree("iter.000000")
         shutil.copytree("out_data_post_fp_abacus", "iter.000000")
-        with open(param_abacus_post_file, "r") as fp:
+        with open(param_abacus_post_file) as fp:
             jdata = json.load(fp)
         post_fp(0, jdata)
         self.system_1 = dpdata.LabeledSystem("iter.000000/orig", fmt="deepmd/raw")
@@ -237,7 +224,7 @@ def setUp(self):
         if os.path.isdir("iter.000000"):
             shutil.rmtree("iter.000000")
         shutil.copytree("out_data_post_fp_siesta", "iter.000000")
-        with open(param_siesta_file, "r") as fp:
+        with open(param_siesta_file) as fp:
             jdata = json.load(fp)
         post_fp(0, jdata)
         self.system_1 = dpdata.LabeledSystem("iter.000000/orig", fmt="deepmd/raw")
@@ -258,7 +245,7 @@ def setUp(self):
         if os.path.isdir("iter.000000"):
             shutil.rmtree("iter.000000")
         shutil.copytree("out_data_post_fp_gaussian", "iter.000000")
-        with open(param_gaussian_file, "r") as fp:
+        with open(param_gaussian_file) as fp:
             jdata = json.load(fp)
         post_fp(0, jdata)
         self.system_1 = dpdata.LabeledSystem("iter.000000/orig", fmt="deepmd/raw")
@@ -279,7 +266,7 @@ def setUp(self):
         if os.path.isdir("iter.000000"):
             shutil.rmtree("iter.000000")
         shutil.copytree("out_data_post_fp_cp2k", "iter.000000")
-        with open(param_cp2k_file, "r") as fp:
+        with open(param_cp2k_file) as fp:
             jdata = json.load(fp)
         post_fp(0, jdata)
         self.system_1 = dpdata.LabeledSystem("iter.000000/orig", fmt="deepmd/raw")
@@ -300,7 +287,7 @@ def setUp(self):
         if os.path.isdir("iter.000000"):
             shutil.rmtree("iter.000000")
         shutil.copytree("out_data_post_fp_pwmat", "iter.000000")
-        with open(param_pwmat_file, "r") as fp:
+        with open(param_pwmat_file) as fp:
             jdata = json.load(fp)
         post_fp(0, jdata)
         self.system_1 = dpdata.LabeledSystem("iter.000000/orig", fmt="deepmd/raw")
@@ -325,7 +312,7 @@ def setUp(self):
             os.path.join("iter.000000", "02.fp", "task.000.000000", "dataset")
         )
         self.system_1 = list(ms.systems.values())[0]
-        with open(param_amber_file, "r") as fp:
+        with open(param_amber_file) as fp:
             jdata = json.load(fp)
         jdata["type_map"] = self.system_1.get_atom_names()
         post_fp(0, jdata)
diff --git a/tests/simplify/context.py b/tests/simplify/context.py
index 88f06f91b..c68902eca 100644
--- a/tests/simplify/context.py
+++ b/tests/simplify/context.py
@@ -2,5 +2,4 @@
 import sys
 
 sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "..")))
-
-import dpgen.simplify.simplify
+import dpgen.simplify.simplify  # noqa: F401
diff --git a/tests/test_cli.py b/tests/test_cli.py
index cd2a4a7a3..0c2125d2a 100644
--- a/tests/test_cli.py
+++ b/tests/test_cli.py
@@ -1,5 +1,4 @@
 import subprocess as sp
-import sys
 import unittest
 
 
diff --git a/tests/tools/context.py b/tests/tools/context.py
index 3f1ab8fbb..a51ca9249 100644
--- a/tests/tools/context.py
+++ b/tests/tools/context.py
@@ -2,7 +2,7 @@
 import sys
 
 sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "..")))
-from dpgen.tools.run_report import *
+from dpgen.tools.run_report import *  # noqa: F403
 
 
 def my_file_cmp(test, f0, f1):
diff --git a/tests/tools/test_convert_mdata.py b/tests/tools/test_convert_mdata.py
index 1f0c020c8..57e15b52c 100644
--- a/tests/tools/test_convert_mdata.py
+++ b/tests/tools/test_convert_mdata.py
@@ -8,7 +8,7 @@
 __package__ = "tools"
 from dpgen.remote.decide_machine import convert_mdata
 
-from .context import setUpModule
+from .context import setUpModule  # noqa: F401
 
 
 class TestConvertMdata(unittest.TestCase):
diff --git a/tests/tools/test_run_report.py b/tests/tools/test_run_report.py
index 0553d99f0..44474c366 100644
--- a/tests/tools/test_run_report.py
+++ b/tests/tools/test_run_report.py
@@ -6,7 +6,10 @@
 test_dir = os.path.abspath(os.path.join(os.path.dirname(__file__)))
 sys.path.insert(0, os.path.join(test_dir, ".."))
 __package__ = "tools"
-from .context import stat_sys
+from .context import (
+    setUpModule,  # noqa: F401
+    stat_sys,
+)
 
 
 class TestRunReport(unittest.TestCase):