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

cif_inf_pymatgen.py をダウンロード

cif_inf_pymatgen.py
cif_inf_pymatgen.py
  1"""
  2CIFファイルから結晶構造情報を読み込み、pymatgenを用いて解析・表示するスクリプト。
  3
  4概要:
  5    本スクリプトは、指定されたCIFファイルから結晶構造データを読み込み、
  6    pymatgenライブラリの機能を用いて、その構造に関する詳細な情報を解析し、標準出力に表示します。
  7    具体的には、空間群の情報、格子定数、対称操作、原子サイトの座標と組成などが含まれます。
  8    また、元の構造に加え、対称化された構造の解析結果も提示します。
  9
 10詳細説明:
 11    1.  コマンドライン引数またはデフォルト設定に基づいて入力CIFファイルパスを決定します。
 12    2.  `tklib.tkApplication` を使用して、標準出力に加え、ログファイルへの出力リダイレクトを設定します。
 13    3.  pymatgenの`Structure.from_file`メソッドでCIFファイルを読み込み、`Structure`オブジェクトを作成します。
 14    4.  作成された`Structure`オブジェクトについて、`print_inf`関数を呼び出して詳細情報を表示します。
 15    5.  `SpacegroupAnalyzer`を用いて構造を対称化し、その対称化された`Structure`オブジェクトについても
 16        同様に`print_inf`関数で詳細情報を表示します。
 17    6.  表示される情報には、空間群のシンボルと番号、対称操作の行列、格子定数、格子ベクトル、
 18        単位胞体積、独立なサイトおよび全サイトの原子種、分数座標、占有率が含まれます。
 19
 20関連リンク:
 21    :doc:`cif_inf_pymatgen_usage`
 22"""
 23from pprint import pprint
 24import re
 25
 26from pymatgen.io.cif import CifParser
 27from pymatgen.symmetry.analyzer import SpacegroupAnalyzer
 28from pymatgen.core.structure import Structure
 29from pymatgen.core.lattice import Lattice
 30from pymatgen.core.periodic_table import Element
 31
 32
 33from tklib.tkapplication import tkApplication
 34from tklib.tkutils import terminate, pint, pfloat, getarg, getintarg, getfloatarg
 35
 36
 37infile = 'SrTiO3.cif'
 38
 39
 40app    = tkApplication()
 41infile      = getarg( 1, infile)
 42
 43
 44#==========================================
 45# Main prgram
 46#==========================================
 47def print_matrix(m):
 48    """
 49    3x3行列を整形して標準出力に表示します。
 50
 51    概要:
 52        与えられた3x3の数値行列を行と列にフォーマットして表示します。
 53
 54    詳細説明:
 55        行列の各要素は小数点以下4桁の浮動小数点数としてフォーマットされ、
 56        パイプ記号で囲まれた見やすい形式で出力されます。
 57
 58    :param m: 表示する3x3の数値行列。リストのリスト形式で指定します。
 59    :type m: list[list[float]]
 60    :returns: None
 61    """
 62    print(f"| {m[0][0]:8.4f} {m[0][1]:8.4f} {m[0][2]:8.4f} |")
 63    print(f"| {m[1][0]:8.4f} {m[1][1]:8.4f} {m[1][2]:8.4f} |")
 64    print(f"| {m[2][0]:8.4f} {m[2][1]:8.4f} {m[2][2]:8.4f} |")
 65
 66def print_inf(structure):
 67    """
 68    pymatgenのStructureオブジェクトから詳細な結晶構造情報を抽出し、表示します。
 69
 70    概要:
 71        与えられたStructureオブジェクトの空間群、対称操作、格子情報、およびサイト情報を整形して表示します。
 72
 73    詳細説明:
 74        以下の情報が表示されます。
 75        - 構造全体の概要 (`structure.__str__`)
 76        - 空間群のシンボルと番号
 77        - 全ての対称操作の数と各対称操作の行列
 78        - 格子定数 (a, b, c, alpha, beta, gamma)
 79        - 格子ベクトル
 80        - 単位胞の体積
 81        - 独立なサイトの原子種と分数座標
 82        - 全てのサイトの原子種、分数座標、および占有率
 83
 84    :param structure: 解析対象のpymatgen Structureオブジェクト。
 85    :type structure: pymatgen.core.structure.Structure
 86    :returns: None
 87    """
 88    print(structure)
 89
 90    structure_dict = structure.as_dict()
 91    print("structure keys:", structure_dict.keys())
 92    structure_inf  = structure_dict.get('structure', None)
 93    spacegroup_inf = structure_dict.get('spacegroup', None)
 94    charge_inf     = structure_dict.get('charge', None)
 95#    print("  structure: ", structure_inf)
 96#    print("    keys:", structure_inf.keys())
 97#    print("  spacegroup: ", spacegroup_inf)
 98#    print("  charge : ", charge_inf)
 99
100    analyzer = SpacegroupAnalyzer(structure)
101#    spacegroup = analyzer.get_space_group_symbol()
102    spg_name, spg_num = structure.get_space_group_info()
103    symmetry_ops = analyzer.get_symmetry_operations()
104    symmetry_matrix = [op.as_dict()['matrix'] for op in symmetry_ops]
105    nsym = len(symmetry_matrix)
106    print("")
107    print(f"Space group: {spg_name} #{spg_num}")
108    print(f"Symmetry operatoins: {nsym}")
109    for i in range(nsym):
110        print(f"op #{i+1}")
111        print_matrix(symmetry_matrix[i])
112
113    print("")
114    print("Lattice: ")
115    lattice_inf = structure.lattice
116    a, b, c, alpha, beta, gamma = lattice_inf.parameters
117    volume = lattice_inf.volume
118    aij    = lattice_inf.matrix
119    print("  Lattice parameters:", a, b, c, alpha, beta, gamma)
120    print("  Lattice vectors:")
121    pprint(aij)
122    print("  Volume: ", volume)
123#    lattice_inf = structure_dict['structure']['lattice']
124#    a, b, c            = structure.lattice.abc
125#    alpha, beta, gamma = structure.lattice.angles
126
127    """
128    print("")
129    print("Species  : ")
130    species_inf = structure.species
131    print("dir(spec)=", dir(species_inf))
132#    print("vars(spec)=", vars(species_inf))
133    print("species_inf=", species_inf)
134#    print("dir(species_inf)=", dir(species_inf))
135#    print("vars(species_inf)=", vars(species_inf))
136    mat_spec_occ = symmetrized_structure.species_and_occu
137    print("mat_spec_occ:")
138    print("mat_spec_occ=", mat_spec_occ)
139#    for occ in mat_spec_occ:
140#        print("  occ:", occ.to_data_dict)
141#        print("  occ:", dir(occ))
142    exit()
143    """
144
145    print("")
146    eq_sites = getattr(structure, "equivalent_sites", None)
147    if eq_sites is None:
148        print("No information for equivalent sites")
149    else:
150        print("Independent sites:")
151        for sites in eq_sites:
152            print("  ", sites[0].species, sites[0].frac_coords)
153# 以降のデータは等価位置なので表示しない        
154#        print("dir(sites[0])=", dir(sites[0]))
155#        for site in sites:
156#            print("  ", site)
157
158    print("")
159    print("All sites:")
160    sites_inf = structure.sites
161    for site in sites_inf:
162#        print("  ", site)
163#    print(sites_inf[0].coords)
164        composition = site.species
165        for atom_name in composition.keys():
166            print("  ", atom_name, site.frac_coords, "  occ=", composition[atom_name])
167
168
169def main():
170    """
171    プログラムの主要な実行フローを定義します。
172
173    概要:
174        指定されたCIFファイルを読み込み、元の構造と対称化された構造の両方について詳細情報を表示します。
175
176    詳細説明:
177        1. 入力CIFファイル名からログファイル名と対称化されたCIFファイルの出力パスを生成します。
178        2. 標準出力をログファイルにもリダイレクトします。
179        3. 入力CIFファイルを`pymatgen.core.structure.Structure`オブジェクトとして読み込みます。
180        4. 読み込んだ元の構造の情報を`print_inf`関数を使って表示します。
181        5. `SpacegroupAnalyzer`を使用して構造を対称化し、その対称化された構造の情報を`print_inf`関数を使って表示します。
182        6. プログラムの実行終了時に一時停止します。
183
184    :returns: None
185    """
186    logfile = app.replace_path(infile, template = ["{dirname}", "{filebody}-out.txt"])
187    print(f"Open logfile [{logfile}]")
188    app.redirect(targets = ["stdout", logfile], mode = 'w')
189
190    convCIFfile = app.replace_path(infile, template = ["{dirname}", "{filebody}-symmetrized.cif"])
191
192    print("")
193    print(f"input: {infile}")   
194    print(f"log file: {logfile}")
195    print(f"output symmetrized CIF file: {convCIFfile}")
196
197    print("")
198    print(f"Read [{infile}]")
199    structure = Structure.from_file(infile)
200    
201    print("")
202    print("Structure as original input:")
203    print_inf(structure)
204
205    print("")
206    print("Symmetrized structure:")
207    analyzer = SpacegroupAnalyzer(structure)
208    symmetrized_structure = analyzer.get_symmetrized_structure()
209    print_inf(symmetrized_structure)
210
211    app.terminate(pause = True)
212
213
214if __name__ == "__main__":
215    main()