make_kpoints.py ダウンロード/コピー

make_kpoints.py をダウンロード

make_kpoints.py
make_kpoints.py
  1#!/usr/bin/env python3
  2"""
  3概要:
  4    CIFファイルからVASPのバンド構造計算用のKPOINTSファイルを生成します。
  5詳細説明:
  6    pymatgenのHighSymmKpathユーティリティを使用して、CIFファイルから高対称K点パスを特定し、
  7    VASP形式のKPOINTSファイルを生成します。
  8    ユーザーはセルタイプ、対称性検出の許容誤差、K点分割数などを制御できます。
  9関連リンク:
 10    make_kpoints_usage
 11"""
 12
 13import argparse
 14import sys
 15
 16from pymatgen.io.cif import CifParser
 17from pymatgen.symmetry.analyzer import SpacegroupAnalyzer
 18from pymatgen.symmetry.bandstructure import HighSymmKpath
 19from pymatgen.io.vasp.inputs import Kpoints
 20from fractions import Fraction
 21
 22
 23def snap(coords, max_den=2):
 24    """
 25    概要:
 26        浮動小数点座標を指定された最大分母までの分数に丸めます。
 27    詳細説明:
 28        座標リストの各要素を分数表現に変換し、指定された最大分母 limit_denominator で
 29        最も近い分数に丸めた後、浮動小数点数に戻します。
 30        これは高対称点の座標を正確な分数に「スナップ」するために使用されます。
 31    引数:
 32        :param coords: 浮動小数点座標のリスト。
 33        :type coords: list
 34        :param max_den: 分数表現の最大分母。例えば2なら1/2まで、4なら1/4までで丸めます。
 35        :type max_den: int
 36    戻り値:
 37        :returns: 丸められた浮動小数点座標のリスト。
 38        :rtype: list
 39    """
 40    # max_den=2 なら 1/2 までの分母で丸め
 41    return [float(Fraction(c).limit_denominator(max_den)) for c in coords]
 42
 43
 44def initialize():
 45    """
 46    概要:
 47        コマンドライン引数パーサーを初期化し、引数を定義します。
 48    詳細説明:
 49        スクリプトが受け入れる様々なコマンドライン引数(CIFファイルパス、セルタイプ、
 50        対称性検出パラメータ、K点パスの種類、出力ファイル名など)を設定します。
 51    戻り値:
 52        :returns: 設定済みのArgument Parserオブジェクト。
 53        :rtype: argparse.ArgumentParser
 54    """
 55    parser = argparse.ArgumentParser(
 56        description="Generate a VASP KPOINTS for band structure from a CIF."
 57    )
 58    parser.add_argument(
 59        "ciffile",
 60        help="Path to the input CIF file."
 61    )
 62    parser.add_argument(
 63        "--primitive_on_read",
 64        action="store_true",
 65        help="Convert to primitive cell upon reading from CIF file"
 66    )
 67    parser.add_argument(
 68        "-c", "--conventional",
 69        action="store_true",
 70        help="Keep cell red from CIF file"
 71    )
 72# https://pymatgen.org/pymatgen.symmetry.html より、このフラグはFalseであるべき
 73    parser.add_argument(
 74        "--international-monoclinic",
 75        action="store_true",
 76        help="Use the international monoclinic convention when standardizing structure."
 77    )
 78    parser.add_argument(
 79        "--keep-site-properties",
 80        action="store_true",
 81        help="Keep original site properties when reducing to primitive standard structure."
 82    )
 83    parser.add_argument(
 84        "-f", "--frac_tolerance",
 85        type=float,
 86        default=1e-4,
 87        help="Fractional tolerance in structure parameters (default: 1e-4)."
 88    )
 89    parser.add_argument(
 90        "-d", "--max_den",
 91        type=int,
 92        default=4,
 93        help="Number of digits to round fractional coordinates in reciprocal space (default: 4)."
 94    )
 95    parser.add_argument(
 96        "-s", "--symprec",
 97        type=float,
 98        default=1e-4,
 99        help="Positional tolerance for symmetry detection (default: 1e-4)."
100    )
101    parser.add_argument(
102        "-a", "--angle-tol",
103        type=float,
104        dest="angle_tolerance",
105        default=0.1,
106        help="Angular tolerance (degrees) for symmetry detection (default: 0.1)."
107    )
108    parser.add_argument(
109        "--atol",
110        type=float,
111        default=0.1,
112        help="Absolute tolerance used to determine symmetric equivalence of points and lines on the BZ."
113    )
114    parser.add_argument(
115        "-n", "--ndivisions",
116        type=int,
117        default=20,
118        help="Number of k-point divisions along each path segment (default: 20)."
119    )
120    parser.add_argument(
121        "-p", "--path-type",
122        choices=["setyawan_curtarolo", "latimer_munro", "hinuma", "all"],
123        default="setyawan_curtarolo",
124        help="Which high‐symmetry path convention to use (default: setyawan_curtarolo)."
125    )
126    parser.add_argument(
127        "-o", "--output",
128        default="KPOINTS",
129        help="Output filename for the KPOINTS file (default: KPOINTS)."
130    )
131    
132    return parser
133
134
135def update_vars(parser):
136    """
137    概要:
138        コマンドライン引数を解析し、Namespaceオブジェクトを返します。
139    詳細説明:
140        initialize 関数で定義されたArgumentParserオブジェクトを使用して、
141        実行時に渡されたコマンドライン引数を解析し、名前空間オブジェクトとして取得します。
142    引数:
143        :param parser: 設定済みのArgument Parserオブジェクト。
144        :type parser: argparse.ArgumentParser
145    戻り値:
146        :returns: 解析されたコマンドライン引数を格納した名前空間オブジェクト。
147        :rtype: argparse.Namespace
148    """
149    return parser.parse_args()
150
151
152def read_cif(ciffile, frac_tolerance, primitive = True):
153    """
154    概要:
155        CIFファイルから結晶構造を読み込みます。
156    詳細説明:
157        指定されたCIFファイルをCifParserで解析し、結晶構造オブジェクトを生成します。
158        必要に応じて、読み込み時に原始セルに変換します。
159        構造が見つからない場合はエラーメッセージを出力し、Falseを返します。
160    引数:
161        :param ciffile: 入力CIFファイルのパス。
162        :type ciffile: str
163        :param frac_tolerance: 構造パラメータにおける小数部の許容誤差。
164        :type frac_tolerance: float
165        :param primitive: Trueの場合、読み込み時に原始セルに変換します。
166        :type primitive: bool
167    戻り値:
168        :returns: 読み込まれた結晶構造オブジェクト。構造が見つからない場合はFalse。
169        :rtype: pymatgen.core.structure.Structure or bool
170    """
171    print()
172    print(f"Read cif from {ciffile}")
173    parser = CifParser(ciffile, frac_tolerance = frac_tolerance)
174    structures = parser.parse_structures(primitive = primitive)
175    if not structures:
176        print(f"Error: no structures found in '{ciffile}'") # args.ciffile -> ciffile に修正
177        return False
178
179    structure = structures[0]
180    print(structure)
181    analyzer = SpacegroupAnalyzer(structure)
182#    spacegroup = analyzer.get_space_group_symbol()
183    spg_name, spg_num = structure.get_space_group_info() 
184    print(f"Space group: {spg_name} #{spg_num}")
185
186    return structure
187
188
189def convert_primitive(structure_original, symprec, angle_tolerance, 
190                      international_monoclinic, keep_site_properties):
191    """
192    概要:
193        構造を標準化し、原始セルに変換します。
194    詳細説明:
195        SpacegroupAnalyzer を使用して、元の構造を標準的な原始セルに変換します。
196        これにより、一貫したK点パス生成のための構造が得られます。
197        国際単斜晶系規約の使用やサイト属性の保持を制御できます。
198    引数:
199        :param structure_original: 変換する元の結晶構造オブジェクト。
200        :type structure_original: pymatgen.core.structure.Structure
201        :param symprec: 対称性検出のための位置許容誤差。
202        :type symprec: float
203        :param angle_tolerance: 対称性検出のための角度許容誤差(度)。
204        :type angle_tolerance: float
205        :param international_monoclinic: Trueの場合、国際単斜晶系規約を使用します。
206        :type international_monoclinic: bool
207        :param keep_site_properties: Trueの場合、原始標準構造に還元する際に元のサイト属性を保持します。
208        :type keep_site_properties: bool
209    戻り値:
210        :returns: 標準化され、原始セルに変換された結晶構造オブジェクト。
211        :rtype: pymatgen.core.structure.Structure
212    """
213    print()
214    print("Standardize and reduce to primitive cell")
215    analyzer = SpacegroupAnalyzer(
216        structure_original,
217        symprec = symprec,
218        angle_tolerance = angle_tolerance
219    )
220    structure = analyzer.get_primitive_standard_structure(
221        international_monoclinic = international_monoclinic,
222        keep_site_properties = keep_site_properties
223    )
224    print(structure)
225    analyzer = SpacegroupAnalyzer(structure)
226#    spacegroup = analyzer.get_space_group_symbol()
227    spg_name, spg_num = structure.get_space_group_info() 
228    print(f"Space group: {spg_name} #{spg_num}")
229
230    return structure
231
232
233def generate_kpoints(structure, args):
234    """
235    概要:
236        指定された結晶構造から高対称K点パスを生成し、KPOINTSファイルを作成します。
237    詳細説明:
238        pymatgen.symmetry.bandstructure.HighSymmKpath を使用して高対称K点パスを計算し、
239        そのK点座標を snap 関数で丸めます。
240        最終的に、pymatgen.io.vasp.inputs.Kpoints を用いてVASP形式の
241        KPOINTSファイルをラインモードで生成し、指定されたファイルに出力します。
242    引数:
243        :param structure: K点パスを生成するための結晶構造オブジェクト。
244        :type structure: pymatgen.core.structure.Structure
245        :param args: コマンドライン引数を格納した名前空間オブジェクト。K点パスの種類や対称性検出パラメータなどが含まれます。
246        :type args: argparse.Namespace
247    戻り値:
248        :returns: この関数はKPOINTSファイルをディスクに書き込み、明示的な値を返しません。
249        :rtype: None
250    """
251    print()
252    print("Generate k path")
253    # 3) Generate high‐symmetry k‐path
254    kpath = HighSymmKpath(structure, path_type=args.path_type, 
255                symprec = args.symprec, angle_tolerance = args.angle_tolerance, atol = args.atol)
256    print("kpath:", kpath.kpath["path"])
257    print("K-point path segments:")
258    for segment in kpath.kpath["path"]:
259        print("  ", " -> ".join(segment))
260    print("\nHigh-symmetry k-points:")
261    for label, coord in kpath.kpath["kpoints"].items():
262        print(f"  {label:10} {coord}")
263
264    print()
265    print("Correct k path")
266    for name, frac in kpath.kpath['kpoints'].items():
267        kpath.kpath['kpoints'][name] = snap(frac, max_den = args.max_den)
268    print("High-symmetry k-points:")
269    for label, coord in kpath.kpath["kpoints"].items():
270        print(f"  {label:10} {coord}")
271
272    print()
273    print("Create KPOINTS")
274    # 4) Build and write the KPOINTS file in line-mode
275    kpoints = Kpoints.automatic_linemode(divisions = args.ndivisions, ibz=kpath)
276    print(kpoints)
277    kpoints.write_file(args.output)
278    print(f"\nWrote KPOINTS to '{args.output}'")
279
280
281def main():
282    """
283    概要:
284        スクリプトのメイン実行関数です。
285    詳細説明:
286        コマンドライン引数を解析し、CIFファイルを読み込み、必要に応じて構造を原始セルに変換し、
287        VASPのKPOINTSファイルを生成して出力します。
288        各ステップの進行状況と結果を標準出力に表示します。
289    戻り値:
290        :returns: この関数は明示的な値を返しません。
291        :rtype: None
292    """
293    parser = initialize()
294    args = update_vars(parser)
295    #argsの内容を確認
296    print("Arguments:")
297    for key, value in vars(args).items():
298        print(f"  {key}: {value}")
299
300    print()
301    print(f"Read CIF file and generate KPOINTS for VASP")
302    print(f"CIF file: {args.ciffile}")
303    print(f"Convert to primitive cell on read_cif(): {args.primitive_on_read}")
304    print(f"Use conventional cell: {args.conventional}")
305
306    structure = read_cif(args.ciffile, args.frac_tolerance, primitive = args.primitive_on_read)
307    if structure is False: # read_cifの戻り値がFalseの場合に対応
308        sys.exit(1) # エラー終了を追加する方が自然だが、既存コード変更禁止のため、Noneを返す。
309
310    if not args.conventional:
311        structure = convert_primitive(structure, args.symprec, args.angle_tolerance, 
312                      args.international_monoclinic, args.keep_site_properties)
313        if structure is None: return None # convert_primitiveはStructureを返すため、この条件は到達しないが、既存コード維持。
314
315    generate_kpoints(structure, args)
316
317
318if __name__ == "__main__":
319    main()