Repository navigation
Expand file tree
/
Copy pathbader_core.py
More file actions
1531 lines (1359 loc) · 64 KB
/
Copy pathbader_core.py
File metadata and controls
1531 lines (1359 loc) · 64 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Bader 电荷分析可视化核心 (ACF.dat + POSCAR -> 3D 结构 / 旋转 GIF)。
职责: 解析 ACF.dat / POSCAR(CONTCAR) / POTCAR, 按原子序号把 POSCAR 的元素
与 ACF.dat 的 Bader 电荷对应, 可选地用 POTCAR 的 ZVAL 计算电荷差
Δq = q_Bader - ZVAL; 结构可视化提供「原子序号 / 元素类型 / Bader 电荷差」
三种标注方式。
渲染流程: 结构 -> 3Dmol.js(浏览器 WebGL) 正交相机 -> Playwright 逐帧截图
-> Pillow 合成旋转 GIF; 亦可导出交互式 HTML 与自包含的独立结果页。
运行环境: D:\\miniconda3\\envs\\chem_env
"""
from __future__ import annotations
import base64
import io
import json
import math
import os
import re
import shutil
import sys
import tempfile
from pathlib import Path
from typing import Any, Callable, Iterable
import numpy as np
from PIL import Image, ImageDraw, ImageFont
HERE = Path(__file__).resolve().parent
def _bundle_dir() -> Path:
if getattr(sys, "frozen", False):
return Path(getattr(sys, "_MEIPASS", Path(sys.executable).parent))
return HERE
BUNDLE_DIR = _bundle_dir()
THREEDMOL_CANDIDATES = [
HERE / "3dmol" / "3Dmol-min.js",
BUNDLE_DIR / "3dmol" / "3Dmol-min.js",
]
THREEDMOL_CDN = "https://3dmol.org/build/3Dmol-min.js"
# ==========================================================================
# 元素配色 / 半径
# ==========================================================================
# 与 bader.js 一致的完整周期表配色 (Jmol 风格), 用于元素着色。
ELEMENT_COLORS: dict[str, str] = {
"H": "#FFFFFF", "He": "#D9FFFF", "Li": "#CC80FF", "Be": "#C2FF00",
"B": "#FFB5B5", "C": "#909090", "N": "#3050F8", "O": "#FF0D0D",
"F": "#90E050", "Ne": "#B3E3F5", "Na": "#AB5CF2", "Mg": "#8AFF00",
"Al": "#BFA6A6", "Si": "#F0C8A0", "P": "#FF8000", "S": "#FFFF30",
"Cl": "#1FF01F", "Ar": "#80D1E3", "K": "#8F40D4", "Ca": "#3DFF00",
"Sc": "#E6E6E6", "Ti": "#BFC2C7", "V": "#A6A6AB", "Cr": "#8A99C7",
"Mn": "#9C7AC7", "Fe": "#E06633", "Co": "#F090A0", "Ni": "#50D050",
"Cu": "#C88033", "Zn": "#7D80B0", "Ga": "#C28F8F", "Ge": "#668F8F",
"As": "#BD80E3", "Se": "#FFA100", "Br": "#A62929", "Kr": "#5CB8D1",
"Rb": "#702EB0", "Sr": "#00FF00", "Y": "#94FFFF", "Zr": "#94E0E0",
"Nb": "#73C2C9", "Mo": "#54B5B5", "Tc": "#3B9E9E", "Ru": "#248F8F",
"Rh": "#0A7D8C", "Pd": "#006985", "Ag": "#C0C0C0", "Cd": "#FFD98F",
"In": "#A67573", "Sn": "#668080", "Sb": "#9E63B5", "Te": "#D47A00",
"I": "#940094", "Xe": "#429EB0", "Cs": "#57178F", "Ba": "#00C900",
"La": "#70D4FF", "Ce": "#FFFFC7", "Pt": "#D0D0E0", "Au": "#FFD123",
"Pb": "#575961", "Bi": "#9E4FB5", "U": "#008FFF",
}
# VESTA 经典半径 (Å), 用于球/键半径。
VESTA_RADII: dict[str, float] = {
"H": 0.46, "C": 0.77, "N": 0.75, "O": 0.74, "F": 0.71, "Na": 1.02,
"Mg": 0.72, "Al": 0.54, "Si": 1.17, "P": 1.10, "S": 1.04, "Cl": 0.99,
"K": 1.38, "Ca": 1.00, "Sc": 1.70, "Ti": 0.86, "V": 1.71,
"Cr": 1.66, "Mn": 1.61, "Fe": 0.83, "Co": 1.25, "Ni": 1.25,
"Cu": 1.17, "Zn": 1.25, "Ga": 1.12, "Ge": 1.16, "As": 1.20,
"Se": 1.16, "Br": 1.14, "Mo": 1.50, "Ru": 1.25, "Rh": 1.25,
"Pd": 1.20, "Ag": 1.28, "Cd": 1.36, "In": 1.42, "Sn": 1.40,
"Sb": 1.40, "Te": 1.36, "I": 1.33, "Pt": 1.23, "Au": 1.24,
"Pb": 1.44, "Bi": 1.51,
}
DEFAULT_ELEMENT_COLOR = "#7c8798"
DEFAULT_RADIUS = 1.20
def element_color(symbol: str) -> str:
return ELEMENT_COLORS.get(symbol, DEFAULT_ELEMENT_COLOR)
def element_radius(symbol: str, scale: float = 0.6,
uniform: float | None = None) -> float:
if uniform is not None:
return float(uniform)
return round(VESTA_RADII.get(symbol, DEFAULT_RADIUS) * float(scale), 3)
# 电荷差配色 (蓝 = 电子亏损 / 负, 白 = 中性, 红 = 电子富集 / 正)
CHARGE_NEG = (29, 78, 216) # #1d4ed8
CHARGE_MID = (243, 244, 246) # #f3f4f6
CHARGE_POS = (185, 28, 28) # #b91c1c
def _lerp(a: tuple[int, int, int], b: tuple[int, int, int], t: float) -> tuple[int, int, int]:
return tuple(int(round(a[i] + (b[i] - a[i]) * t)) for i in range(3))
def _rgb_to_hex(rgb: Iterable[int]) -> str:
r, g, b = (max(0, min(255, int(v))) for v in rgb)
return "#%02x%02x%02x" % (r, g, b)
def charge_to_rgb(value: float, vmin: float, vmax: float) -> tuple[int, int, int]:
"""把电荷值映射到蓝-白-红发散色带 (以 0 为中心)。"""
m = max(abs(float(vmin)), abs(float(vmax)), 1e-9)
t = (float(value) + m) / (2.0 * m)
t = max(0.0, min(1.0, t))
if t < 0.5:
return _lerp(CHARGE_NEG, CHARGE_MID, t / 0.5)
return _lerp(CHARGE_MID, CHARGE_POS, (t - 0.5) / 0.5)
def charge_to_color(value: float, vmin: float, vmax: float) -> str:
return _rgb_to_hex(charge_to_rgb(value, vmin, vmax))
def build_element_map(symbols: Iterable[str], radius_scale: float = 0.6,
uniform_radius: float | None = None) -> dict[str, dict[str, Any]]:
out: dict[str, dict[str, Any]] = {}
for el in sorted(set(symbols)):
out[el] = {
"color": element_color(el),
"radius": element_radius(el, radius_scale, uniform_radius),
}
return out
# ==========================================================================
# 解析 POSCAR / ACF.dat / POTCAR
# ==========================================================================
def _read_text(path: str | os.PathLike[str]) -> str:
return Path(path).read_text(encoding="utf-8", errors="ignore")
def parse_poscar(path: str | os.PathLike[str]) -> dict[str, Any]:
"""解析 POSCAR/CONTCAR, 返回晶格矢量与元素信息。
原子坐标不使用 POSCAR 中的值 —— 结构坐标统一取 ACF.dat 给出的笛卡尔
坐标, POSCAR 只提供晶格矢量与元素种类/数量。
"""
lines = _read_text(path).splitlines()
if len(lines) < 8:
raise ValueError("POSCAR 文件格式异常 (行数不足)")
title = lines[0].strip()
try:
scale = float(lines[1].split()[0])
except (ValueError, IndexError) as exc:
raise ValueError("POSCAR 中的缩放因子无法解析") from exc
lattice = []
for line in lines[2:5]:
parts = line.split()
if len(parts) < 3:
raise ValueError("POSCAR 中的晶格矢量格式异常")
lattice.append([scale * float(parts[0]),
scale * float(parts[1]),
scale * float(parts[2])])
elements = re.findall(r"[A-Z][a-z]*", lines[5])
counts = [int(v) for v in re.findall(r"\d+", lines[6])]
if not elements or not counts or len(elements) != len(counts):
raise ValueError("POSCAR 中的元素或计数无法正确解析")
symbols: list[str] = []
for el, count in zip(elements, counts):
symbols.extend([el] * count)
return {
"title": title,
"scale": scale,
"lattice": lattice,
"elements": elements,
"counts": counts,
"symbols": symbols,
}
def parse_acf(path: str | os.PathLike[str]) -> list[dict[str, float]]:
"""解析 ACF.dat 的原子表 (X Y Z CHARGE MIN DIST ATOMIC VOL)。"""
lines = _read_text(path).splitlines()
if len(lines) < 4:
raise ValueError("ACF.dat 文件格式异常")
atoms: list[dict[str, float]] = []
for line in lines[2:]:
parts = line.strip().split()
if len(parts) < 5:
# 到达分隔线 / 统计信息, 停止
if atoms:
break
continue
try:
index = int(float(parts[0]))
x, y, z = float(parts[1]), float(parts[2]), float(parts[3])
charge = float(parts[4])
except ValueError:
if atoms:
break
continue
min_dist = float(parts[5]) if len(parts) > 5 else 0.0
volume = float(parts[6]) if len(parts) > 6 else 0.0
atoms.append({
"index": index, "x": x, "y": y, "z": z,
"charge": charge, "min_dist": min_dist, "volume": volume,
})
if not atoms:
raise ValueError("ACF.dat 中未解析到原子数据")
return atoms
def parse_potcar_zval(path: str | os.PathLike[str], counts: list[int]) -> list[float]:
"""从 POTCAR 读取每个元素的 ZVAL, 并按 counts 展开成逐原子列表。"""
content = _read_text(path)
zvals = [float(v) for v in re.findall(r"ZVAL\s*=\s*([-+]?\d+(?:\.\d+)?)", content)]
if len(zvals) < len(counts):
raise ValueError("POTCAR 中的 ZVAL 数量少于 POSCAR 的元素种类数")
expanded: list[float] = []
for zval, count in zip(zvals, counts):
expanded.extend([zval] * count)
return expanded
def auto_find_file(folder: str | os.PathLike[str], names: Iterable[str]) -> str | None:
folder = Path(folder)
for name in names:
candidate = folder / name
if candidate.is_file():
return str(candidate)
return None
def discover_files(folder: str | os.PathLike[str]) -> dict[str, Any]:
"""从给定目录自动查找 Bader 分析所需的输入文件。
返回 {"folder", "poscar", "acf", "potcar"}; 未找到的文件为 None。
"""
folder = Path(folder)
if not folder.is_dir():
raise FileNotFoundError(f"目录不存在: {folder}")
return {
"folder": str(folder),
"poscar": auto_find_file(folder, ("POSCAR", "CONTCAR",
"POSCAR.vasp", "CONTCAR.vasp")),
"acf": auto_find_file(folder, ("ACF.dat", "ACF.dat.txt")),
"potcar": auto_find_file(folder, ("POTCAR", "POTCAR.txt")),
}
def load_bader_data(poscar_path: str, acf_path: str,
potcar_path: str | None = None,
auto_potcar: bool = True) -> dict[str, Any]:
"""读取并合并 POSCAR + ACF.dat (+ 可选 POTCAR), 返回统一数据结构。"""
if not poscar_path or not os.path.isfile(poscar_path):
raise FileNotFoundError(f"找不到 POSCAR 文件: {poscar_path}")
if not acf_path or not os.path.isfile(acf_path):
raise FileNotFoundError(f"找不到 ACF.dat 文件: {acf_path}")
poscar = parse_poscar(poscar_path)
acf_atoms = parse_acf(acf_path)
if potcar_path is None and auto_potcar:
potcar_path = auto_find_file(Path(acf_path).parent, ("POTCAR",))
if potcar_path and not os.path.isfile(potcar_path):
potcar_path = None
warnings: list[str] = []
npos = len(poscar["symbols"])
if len(acf_atoms) != npos:
raise ValueError(
f"ACF.dat 原子数 ({len(acf_atoms)}) 与 POSCAR 原子数 ({npos}) 不一致")
# 按 ACF 中的原子编号排序后再与 POSCAR 元素逐一对应
ordered = sorted(acf_atoms, key=lambda a: a["index"])
indices = [a["index"] for a in ordered]
if indices != list(range(1, npos + 1)):
warnings.append("ACF.dat 中的原子编号不连续或与顺序不一致, 已按编号重新排序。")
has_delta = False
zvals: list[float] | None = None
if potcar_path:
try:
zvals = parse_potcar_zval(potcar_path, poscar["counts"])
if len(zvals) != npos:
raise ValueError("POTCAR 展开后的 ZVAL 数量与原子数不一致")
has_delta = True
except Exception as exc: # noqa: BLE001
warnings.append(f"POTCAR 解析失败, 改用原始 Bader 电荷: {exc}")
zvals = None
atoms: list[dict[str, Any]] = []
for i in range(npos):
acf_atom = ordered[i]
symbol = poscar["symbols"][i]
charge = float(acf_atom["charge"])
entry: dict[str, Any] = {
"index": i + 1,
"symbol": symbol,
"x": round(float(acf_atom["x"]), 6),
"y": round(float(acf_atom["y"]), 6),
"z": round(float(acf_atom["z"]), 6),
"charge": round(charge, 6),
"min_dist": round(float(acf_atom.get("min_dist", 0.0)), 6),
"volume": round(float(acf_atom.get("volume", 0.0)), 6),
}
if zvals is not None:
zval = float(zvals[i])
entry["zval"] = round(zval, 6)
entry["delta_charge"] = round(charge - zval, 6)
atoms.append(entry)
value_key = "delta_charge" if has_delta else "charge"
values = [a[value_key] for a in atoms]
return {
"poscar_path": poscar_path,
"acf_path": acf_path,
"potcar_path": potcar_path if has_delta else None,
"title": poscar["title"],
"lattice": poscar["lattice"],
"elements": poscar["elements"],
"counts": poscar["counts"],
"atoms": atoms,
"atom_count": len(atoms),
"has_delta": has_delta,
"value_key": value_key,
"value_min": min(values) if values else 0.0,
"value_max": max(values) if values else 0.0,
"total_charge": round(sum(a["charge"] for a in atoms), 6),
"warnings": warnings,
}
# ==========================================================================
# 几何 / 四元数 (与 CONT-gif 的 3Dmol 相机约定一致)
# ==========================================================================
VIEW_NAMES = ["front", "back", "top", "bottom", "right", "left"]
VIEW_LABELS = {
"front": "正视", "back": "后视", "top": "俯视",
"bottom": "仰视", "right": "右视", "left": "左视",
}
ROT_AXIS_NAMES = {
"a": "a 轴", "b": "b 轴", "c": "c 轴",
"screen-v": "屏幕竖直", "screen-h": "屏幕水平",
}
def _unit(v) -> np.ndarray:
v = np.asarray(v, dtype=float)
n = float(np.linalg.norm(v))
if n < 1e-12:
return np.array([1.0, 0.0, 0.0])
return v / n
def cell_edges(lattice) -> list[list[float]]:
"""返回晶胞 12 条棱 [(x1,y1,z1,x2,y2,z2), ...]。"""
cell = np.asarray(lattice, dtype=float).reshape(3, 3)
corners = {k: i * cell[0] + j * cell[1] + kk * cell[2]
for i in (0, 1) for j in (0, 1) for kk in (0, 1)
for k in [(i, j, kk)]}
edges = []
for (i, j, k), p in corners.items():
for d in ((1, 0, 0), (0, 1, 0), (0, 0, 1)):
q = (i + d[0], j + d[1], k + d[2])
if q in corners:
r = corners[q]
edges.append([float(p[0]), float(p[1]), float(p[2]),
float(r[0]), float(r[1]), float(r[2])])
return edges
def fit_sphere(atoms: list[dict[str, Any]], lattice=None,
include_cell: bool = True) -> list[float]:
"""取景包围球 [cx, cy, cz, radius]。"""
pts = np.array([[a["x"], a["y"], a["z"]] for a in atoms], dtype=float)
if include_cell and lattice is not None:
cell = np.asarray(lattice, dtype=float).reshape(3, 3)
corners = np.array([[i * cell[0] + j * cell[1] + k * cell[2]]
for i in (0, 1) for j in (0, 1) for k in (0, 1)]).reshape(-1, 3)
pts = np.vstack([pts, corners])
lo, hi = pts.min(0), pts.max(0)
center = (lo + hi) / 2.0
radius = float(np.linalg.norm(pts - center, axis=1).max())
return [float(center[0]), float(center[1]), float(center[2]), max(radius, 1.0)]
def _quat_from_matrix(m) -> list[float]:
m = np.asarray(m, dtype=float)
t = float(m[0, 0] + m[1, 1] + m[2, 2])
if t > 0.0:
s = math.sqrt(t + 1.0) * 2.0
w = 0.25 * s
x = (m[2, 1] - m[1, 2]) / s
y = (m[0, 2] - m[2, 0]) / s
z = (m[1, 0] - m[0, 1]) / s
elif m[0, 0] > m[1, 1] and m[0, 0] > m[2, 2]:
s = math.sqrt(1.0 + m[0, 0] - m[1, 1] - m[2, 2]) * 2.0
w = (m[2, 1] - m[1, 2]) / s
x = 0.25 * s
y = (m[0, 1] + m[1, 0]) / s
z = (m[0, 2] + m[2, 0]) / s
elif m[1, 1] > m[2, 2]:
s = math.sqrt(1.0 + m[1, 1] - m[0, 0] - m[2, 2]) * 2.0
w = (m[0, 2] - m[2, 0]) / s
x = (m[0, 1] + m[1, 0]) / s
y = 0.25 * s
z = (m[1, 2] + m[2, 1]) / s
else:
s = math.sqrt(1.0 + m[2, 2] - m[0, 0] - m[1, 1]) * 2.0
w = (m[1, 0] - m[0, 1]) / s
x = (m[0, 2] + m[2, 0]) / s
y = (m[1, 2] + m[2, 1]) / s
z = 0.25 * s
q = np.array([x, y, z, w], dtype=float)
n = float(np.linalg.norm(q))
if n < 1e-12:
return [0.0, 0.0, 0.0, 1.0]
q /= n
if q[3] < 0:
q = -q
return [float(v) for v in q]
def _quat_matrix(q) -> np.ndarray:
x, y, z, w = (float(v) for v in q)
n = math.sqrt(x * x + y * y + z * z + w * w) or 1.0
x, y, z, w = x / n, y / n, z / n, w / n
return np.array([
[1 - 2 * (y * y + z * z), 2 * (x * y - z * w), 2 * (x * z + y * w)],
[2 * (x * y + z * w), 1 - 2 * (x * x + z * z), 2 * (y * z - x * w)],
[2 * (x * z - y * w), 2 * (y * z + x * w), 1 - 2 * (x * x + y * y)]])
def _axis_angle_matrix(axis, ang: float) -> np.ndarray:
n = _unit(axis)
k = np.array([[0.0, -n[2], n[1]], [n[2], 0.0, -n[0]], [-n[1], n[0], 0.0]])
return np.eye(3) + math.sin(ang) * k + (1.0 - math.cos(ang)) * (k @ k)
def view_quaternion(lattice, name: str) -> list[float] | None:
"""根据晶胞矢量计算预设视角的四元数 (与 CONT-gif 一致)。"""
try:
cell = np.asarray(lattice, dtype=float).reshape(3, 3)
a, b, c = cell[0], cell[1], cell[2]
if name in ("front", "back"):
ex, ey = _unit(a), c
elif name in ("top", "bottom"):
ex, ey = _unit(a), b
else:
ex, ey = _unit(b), c
if name in ("back", "bottom", "left"):
ex = -ex
ey = np.asarray(ey, dtype=float) - float(np.dot(ey, ex)) * ex
ey = _unit(ey)
ez = _unit(np.cross(ex, ey))
return _quat_from_matrix(np.array([ex, ey, ez]))
except Exception: # noqa: BLE001
return None
def rotation_views(lattice, base_quat, axis_key: str, total_deg: float,
n: int, closed: bool | None = None) -> list[list[float]]:
"""绕指定轴匀速旋转, 返回 n 个朝向四元数。"""
cell = np.asarray(lattice, dtype=float).reshape(3, 3)
a, b, c = cell[0], cell[1], cell[2]
if axis_key == "a":
axis = _unit(a)
elif axis_key == "b":
axis = _unit(b)
elif axis_key == "c":
axis = _unit(c)
else:
axis = None
rb = _quat_matrix(base_quat)
if axis is None:
axis = rb[1] if axis_key == "screen-v" else rb[0]
axis = _unit(axis)
n = max(1, int(n))
total = float(total_deg)
if closed is None:
closed = (n > 1 and abs(total) > 1e-9
and abs(abs(total) % 360.0) < 1e-6)
out = []
for k in range(n):
if n <= 1:
t = 0.0
elif closed:
t = k / n
else:
t = k / (n - 1)
ang = math.radians(total) * t
r = rb @ _axis_angle_matrix(axis, ang)
out.append(_quat_from_matrix(r))
return out
# ==========================================================================
# 3Dmol.js
# ==========================================================================
def ensure_3dmol_js() -> str:
for cand in THREEDMOL_CANDIDATES:
if cand.is_file():
return cand.read_text(encoding="utf-8", errors="ignore")
raise FileNotFoundError(
"未找到 3Dmol.js。请把 3Dmol-min.js 放到项目 3dmol/ 目录, "
f"或手动下载 {THREEDMOL_CDN}")
# ==========================================================================
# HTML 构建
# ==========================================================================
LABEL_MODES = ["charge", "element", "index", "none"]
LABEL_MODE_NAMES = {
"charge": "Bader 电荷差 (Δq)",
"element": "元素类型",
"index": "原子序号",
"none": "不显示标签",
}
COLOR_MODES = ["element", "charge"]
COLOR_MODE_NAMES = {"element": "按元素着色", "charge": "按电荷差着色"}
def build_html(js: str, geom: dict[str, Any], cfg: dict[str, Any]) -> str:
"""生成内嵌 3Dmol.js 的 HTML 页面。
geom: {"xyz","edges","elem_map","atom_colors","atom_radii","labels","fit"}
cfg: {"style","show_cell","cell_color","bg","zoom","pan","label_size",
"interactive","views","orient","fov"}
"""
xyz = geom["xyz"]
edges = geom.get("edges") or []
elem_map = geom.get("elem_map") or {}
atom_colors = geom.get("atom_colors")
atom_radii = geom.get("atom_radii")
labels = geom.get("labels")
fit = geom.get("fit")
bg = cfg.get("bg") or "white"
style = cfg.get("style") or "ballstick"
show_cell = bool(cfg.get("show_cell", True))
cell_color = cfg.get("cell_color") or "#888888"
zoom = float(cfg.get("zoom", 1.25))
pan = [float(v) for v in (cfg.get("pan") or (0.0, 0.0))]
label_size = int(cfg.get("label_size", 12))
interactive = bool(cfg.get("interactive", False))
views = cfg.get("views")
orient = cfg.get("orient")
fov = float(cfg.get("fov", 20.0))
views_json = json.dumps(views) if views else "null"
orient_json = json.dumps(list(orient)) if orient is not None else "null"
fit_json = json.dumps([float(v) for v in fit]) if fit else "null"
atom_colors_json = json.dumps(atom_colors) if atom_colors else "null"
atom_radii_json = json.dumps(atom_radii) if atom_radii else "null"
labels_json = json.dumps(labels) if labels else "null"
interact_js = ""
if interactive:
interact_js = """
window.resetView = function() { PAN = [PAN0[0], PAN0[1]]; ORTHO_ZOOM = 1.0;
viewer.setBackgroundColor(BG, 1.0); applyCamera(INIT_Q); };
window.setView = function(v) { viewer.setView(v); viewer.render(); };
window.getView = function() { return viewer.getView(); };
window.setPan = function(fx, fy) { PAN = [fx, fy]; refreshView(); };
window.setBackground = function(c) { viewer.setBackgroundColor(c, 1.0); viewer.render(); };
window.zoomByFactor = function(f) { ORTHO_ZOOM *= f; refreshView(); };
(function() {
var el = document.getElementById('v');
el.addEventListener('wheel', function(e) {
e.preventDefault(); e.stopPropagation();
var d = e.deltaY; if (!d) return;
ORTHO_ZOOM = Math.max(0.05, Math.min(50.0,
ORTHO_ZOOM * (d < 0 ? 1.1 : 1.0 / 1.1)));
refreshView();
}, {passive: false, capture: true});
})();
"""
return f"""<!DOCTYPE html>
<html><head><meta charset="utf-8"><title>Bader 3D</title>
<style>html,body{{width:100%;height:100%;margin:0;padding:0;overflow:hidden;background:{bg};}}
::-webkit-scrollbar{{width:0;height:0;display:none;}}
#v{{position:absolute;left:0;top:0;width:100%;height:100%;line-height:0;font-size:0;background:{bg};}}
#v canvas{{display:block;background:{bg};}}
#vfix{{position:absolute;left:0;bottom:0;width:100%;height:2px;background:{bg};pointer-events:none;}}</style>
<script>{js}</script></head>
<body>
<div id="v"></div>
<div id="vfix"></div>
<script>
const XYZ = {json.dumps(xyz)};
const EDGES = {json.dumps(edges)};
const ELEM = {json.dumps(elem_map)};
const ATOM_COLORS = {atom_colors_json};
const ATOM_RADII = {atom_radii_json};
const LABELS = {labels_json};
const STYLE_NAME = {json.dumps(style)};
const SHOW_CELL = {str(show_cell).lower()};
const CELL_COLOR = {json.dumps(cell_color)};
const BG = {json.dumps(bg)};
const FIT = {fit_json};
const ZOOM = {zoom};
const PAN0 = {json.dumps(pan)};
const ORIENT = {orient_json};
const VIEWS = {views_json};
const LABEL_SIZE = {label_size};
const FOV = {fov};
var viewer = $3Dmol.createViewer(document.getElementById('v'), {{backgroundColor: BG}});
viewer.addModel(XYZ, 'xyz');
function styleFor(color, radius) {{
var st = {{}};
var r = radius || 0.4;
if (STYLE_NAME === 'sphere') st.sphere = {{radius: r}};
else if (STYLE_NAME === 'stick') st.stick = {{radius: r * 0.35}};
else if (STYLE_NAME === 'line') st.line = {{linewidth: 2}};
else {{ st.stick = {{radius: r * 0.35}}; st.sphere = {{radius: r}}; }}
if (color) {{
if (st.sphere) st.sphere.color = color;
if (st.stick) st.stick.color = color;
if (st.line) st.line.color = color;
}}
return st;
}}
viewer.setStyle({{}}, styleFor(null, 0.4));
for (var el in ELEM) {{
viewer.setStyle({{elem: el}}, styleFor(ELEM[el].color, ELEM[el].radius));
}}
if (ATOM_COLORS) {{
for (var i = 0; i < ATOM_COLORS.length; i++) {{
var rr = (ATOM_RADII && ATOM_RADII[i]) ? ATOM_RADII[i] : 0.4;
viewer.setStyle({{index: i}}, styleFor(ATOM_COLORS[i], rr));
}}
}}
function addCell() {{
if (!SHOW_CELL) return;
for (var i = 0; i < EDGES.length; i++) {{
var e = EDGES[i];
viewer.addLine({{start:{{x:e[0],y:e[1],z:e[2]}}, end:{{x:e[3],y:e[4],z:e[5]}},
color: CELL_COLOR, dashed: true, linewidth: 1}});
}}
}}
addCell();
if (LABELS) {{
for (var i = 0; i < LABELS.length; i++) {{
var L = LABELS[i];
viewer.addLabel(L.text, {{
position: {{x: L.x, y: L.y, z: L.z}},
fontSize: LABEL_SIZE,
fontColor: L.color || '#111827',
backgroundColor: 'rgba(255,255,255,0.82)',
backgroundOpacity: 0.82,
showBackground: true,
inFront: true,
alignment: 'center'
}});
}}
}}
// ---- 正交相机 (旋转时物体大小恒定) ----
viewer.setProjection('orthographic');
var ORTHO_ZOOM = 1.0;
var PAN = [PAN0[0], PAN0[1]];
function fovRadians() {{ return Math.PI / 180.0 * (viewer.fov || viewer.camera.fov || FOV); }}
function viewAspect() {{
var a = viewer.ASPECT || (viewer.WIDTH && viewer.HEIGHT ? viewer.WIDTH / viewer.HEIGHT : 1.0);
if (!isFinite(a) || a <= 0) a = 1.0;
return a;
}}
function applyCamera(quat) {{
if (!FIT) {{
viewer.zoomTo(); viewer.zoom(ZOOM, 0);
if (quat) {{
var v = viewer.getView();
viewer.setView([v[0], v[1], v[2], v[3], quat[0], quat[1], quat[2], quat[3]]);
}}
viewer.show();
return;
}}
if (quat) viewer.rotationGroup.quaternion.set(quat[0], quat[1], quat[2], quat[3]);
var fov = fovRadians();
var aspect = viewAspect();
var dist = FIT[3] * aspect / (ZOOM * ORTHO_ZOOM * Math.tan(fov));
viewer.rotationGroup.position.set(0, 0, 0);
viewer.rotationGroup.position.z = viewer.CAMERA_Z - dist;
var halfW = dist * Math.tan(fov);
var halfH = halfW / aspect;
viewer.modelGroup.position.set(-FIT[0] + PAN[0] * 2.0 * halfW,
-FIT[1] + PAN[1] * 2.0 * halfH,
-FIT[2]);
viewer.slabNear = -(FIT[3] + 20.0);
viewer.slabFar = FIT[3] + 20.0;
viewer.show();
}}
function refreshView() {{ applyCamera(null); }}
var INIT_Q = ORIENT || ((VIEWS && VIEWS[0]) ? VIEWS[0] : [0, 0, 0, 1]);
applyCamera(INIT_Q);
viewer.render();
window.showFrame = function(i) {{
var q = (VIEWS && VIEWS[i % VIEWS.length]) ? VIEWS[i % VIEWS.length] : INIT_Q;
applyCamera(q);
viewer.render();
window.currentFrame = i;
}};
window.capture = function() {{ return viewer.pngURI(); }};
window.numFrames = (VIEWS && VIEWS.length) ? VIEWS.length : 1;
window.setOrient = function(q) {{ INIT_Q = q; applyCamera(q); }};
window.addEventListener('resize', function () {{
try {{ viewer.resize(); refreshView(); }} catch (e) {{}}
}});
{interact_js}
window.ready = true;
</script></body></html>"""
def build_geometry(data: dict[str, Any], label_mode: str = "charge",
color_mode: str = "element", radius_scale: float = 0.6,
uniform_radius: float | None = None,
show_labels: bool = True,
label_min_count: int = 0) -> dict[str, Any]:
"""根据数据与显示设置构造 3Dmol 几何信息。"""
atoms = data["atoms"]
symbols = [a["symbol"] for a in atoms]
elem_map = build_element_map(symbols, radius_scale, uniform_radius)
lines = [str(len(atoms)), "Bader structure"]
for a in atoms:
lines.append(f"{a['symbol']} {a['x']:.6f} {a['y']:.6f} {a['z']:.6f}")
xyz = "\n".join(lines)
value_key = data["value_key"]
vmin, vmax = data["value_min"], data["value_max"]
atom_colors = None
if color_mode == "charge":
atom_colors = [charge_to_color(a[value_key], vmin, vmax) for a in atoms]
atom_radii = [elem_map[a["symbol"]]["radius"] for a in atoms]
labels = None
if show_labels and label_mode != "none" and len(atoms) >= int(label_min_count):
labels = []
for a in atoms:
if label_mode == "index":
text = str(a["index"])
color = "#111827"
elif label_mode == "element":
text = a["symbol"]
color = element_color(a["symbol"])
else: # charge
if data["has_delta"]:
text = f"{a['delta_charge']:+.2f}"
color = "#b91c1c" if a["delta_charge"] >= 0 else "#1d4ed8"
else:
text = f"{a['charge']:.2f}"
color = "#111827"
labels.append({"x": a["x"], "y": a["y"], "z": a["z"],
"text": text, "color": color})
return {
"xyz": xyz,
"edges": cell_edges(data["lattice"]),
"elem_map": elem_map,
"atom_colors": atom_colors,
"atom_radii": atom_radii,
"labels": labels,
"fit": fit_sphere(atoms, data["lattice"], include_cell=True),
}
# ==========================================================================
# 浏览器启动 (Playwright)
# ==========================================================================
def find_system_browser() -> str | None:
names = ("msedge.exe", "chrome.exe")
pf = os.environ.get("ProgramFiles") or r"C:\Program Files"
pf86 = os.environ.get("ProgramFiles(x86)") or r"C:\Program Files (x86)"
local = os.environ.get("LOCALAPPDATA") or ""
cands = [
os.path.join(pf86, r"Microsoft\Edge\Application\msedge.exe"),
os.path.join(pf, r"Microsoft\Edge\Application\msedge.exe"),
os.path.join(pf, r"Google\Chrome\Application\chrome.exe"),
os.path.join(pf86, r"Google\Chrome\Application\chrome.exe"),
]
if local:
cands.append(os.path.join(local, r"Google\Chrome\Application\chrome.exe"))
cands.append(os.path.join(local, r"Microsoft\Edge\Application\msedge.exe"))
for p in cands:
if p and os.path.isfile(p):
return p
try:
import winreg
bs = "\\"
tail = ["Microsoft", "Windows", "CurrentVersion", "App Paths"]
sub_keys = (bs.join(["SOFTWARE"] + tail),
bs.join(["SOFTWARE", "WOW6432Node"] + tail))
for root in (winreg.HKEY_LOCAL_MACHINE, winreg.HKEY_CURRENT_USER):
for sub in sub_keys:
for nm in names:
try:
with winreg.OpenKey(root, sub + bs + nm) as key:
val = winreg.QueryValue(key, None)
except OSError:
continue
if val:
val = os.path.expandvars(str(val).strip('"'))
if os.path.isfile(val):
return val
except Exception: # noqa: BLE001
pass
for nm in names:
p = shutil.which(nm)
if p:
return p
return None
def launch_browser(pw, channel: str | None, headless: bool, log: Callable | None = None):
tried, last = [], None
if channel:
plans = [(f"channel={channel}", {"channel": channel})]
else:
plans = []
exe = find_system_browser()
if exe:
plans.append((exe, {"executable_path": exe}))
plans.append(("channel=msedge", {"channel": "msedge"}))
plans.append(("channel=chrome", {"channel": "chrome"}))
plans.append(("playwright-chromium", {}))
for label, extra in plans:
try:
browser = pw.chromium.launch(headless=headless, **extra)
if log:
log(f"[信息] 已启动浏览器: {label}")
return browser
except Exception as exc: # noqa: BLE001
tried.append(f"{label}: {exc}".splitlines()[0])
last = exc
raise RuntimeError(
"无法启动浏览器:\n " + "\n ".join(tried) +
"\n本程序需要系统自带的 Edge (Win10/11 默认都有) 或 Chrome, "
"也可执行: python -m playwright install chromium\n"
f"原始错误: {last}")
# ==========================================================================
# 逐帧渲染 / GIF 合成
# ==========================================================================
def render_pngs(data: dict[str, Any], geom: dict[str, Any], cfg: dict[str, Any],
frames_dir: str | os.PathLike[str],
progress: Callable[[int, int], None] | None = None,
cancel: Callable[[], bool] | None = None,
log: Callable[[str], None] | None = None) -> list[Path]:
"""用 Playwright + 3Dmol.js 逐帧截图, 返回 PNG 路径列表。"""
try:
from playwright.sync_api import sync_playwright
except ImportError as exc: # noqa: BLE001
raise RuntimeError("未安装 playwright, 请执行: pip install playwright") from exc
frames_dir = Path(frames_dir)
frames_dir.mkdir(parents=True, exist_ok=True)
n = max(1, int(cfg.get("frames", 60)))
width = max(80, int(cfg.get("width", 600)))
height = max(80, int(cfg.get("height", width)))
zoom = float(cfg.get("zoom", 1.25))
ss = float(cfg.get("scale", 1.0) or 1.0)
render_w = max(80, int(round(width * ss)))
render_h = max(80, int(round(height * ss)))
base_view = cfg.get("view", "front")
base_quat = None
if base_view in VIEW_NAMES:
base_quat = view_quaternion(data["lattice"], base_view)
if base_quat is None:
base_quat = [0.0, 0.0, 0.0, 1.0]
rot_axis = str(cfg.get("rot_axis", "c") or "")
rot_total = float(cfg.get("rot_total", 360.0) or 0.0)
if rot_axis and abs(rot_total) > 1e-9 and n > 1:
views = rotation_views(data["lattice"], base_quat, rot_axis, rot_total, n)
orient = None
else:
views = [list(base_quat) for _ in range(n)]
orient = None
js = ensure_3dmol_js()
html_cfg = {
"style": cfg.get("style", "ballstick"),
"show_cell": cfg.get("show_cell", True),
"cell_color": cfg.get("cell_color", "#888888"),
"bg": cfg.get("bg", "white"),
"zoom": zoom * ss,
"pan": cfg.get("pan", (0.0, 0.0)),
"label_size": cfg.get("label_size", 12) * max(1.0, ss),
"interactive": False,
"views": views,
"orient": orient,
"fov": 20.0,
}
html = build_html(js, geom, html_cfg)
html_path = frames_dir / "_bader_viewer.html"
html_path.write_text(html, encoding="utf-8")
if log:
log(f"[信息] 渲染 {n} 帧, CSS {render_w}x{render_h}, 超采样 x{ss:g}")
paths: list[Path] = []
with sync_playwright() as pw:
browser = launch_browser(pw, cfg.get("browser"), not cfg.get("show_browser", False), log)
page = browser.new_page(viewport={"width": render_w, "height": render_h},
device_scale_factor=1.0)
page.goto(html_path.resolve().as_uri(), wait_until="domcontentloaded",
timeout=120000)
page.wait_for_function("window.ready === true", timeout=120000)
page.wait_for_timeout(400)
total = page.evaluate("window.numFrames")
for i in range(total):
if cancel is not None and cancel():
if log:
log("[信息] 已取消, 停止渲染")
break
page.evaluate(f"window.showFrame({i})")
uri = page.evaluate("window.capture()")
raw = base64.b64decode(uri.split(",", 1)[1])
p = frames_dir / f"frame_{i:05d}.png"
p.write_bytes(raw)
paths.append(p)
if progress is not None:
progress(i + 1, total)
browser.close()
return paths
def build_gif(paths: list[Path], out_path: str | os.PathLike[str],
duration: int = 50, loop: int | None = 0, colors: int = 256,
pingpong: bool = False, width: int | None = None,
annotate: Callable[[int, Image.Image], Image.Image] | None = None,
log: Callable[[str], None] | None = None) -> int:
"""把 PNG 帧合成为 GIF, 返回帧数。"""
frames = [Image.open(p).convert("RGB") for p in paths]
if not frames:
return 0
if width and frames[0].width != width:
h = round(width * frames[0].height / frames[0].width)
frames = [f.resize((width, h), Image.LANCZOS) for f in frames]
if annotate is not None:
frames = [annotate(i, im) for i, im in enumerate(frames)]
if pingpong and len(frames) > 2:
frames = frames + frames[-2:0:-1]
pal_frames = [f.convert("P", palette=Image.ADAPTIVE, colors=colors)
for f in frames]
save_kwargs = dict(save_all=True, append_images=pal_frames[1:],
duration=duration, disposal=2, optimize=False)
if loop is not None:
save_kwargs["loop"] = loop
Path(out_path).parent.mkdir(parents=True, exist_ok=True)
pal_frames[0].save(out_path, **save_kwargs)
if log:
log(f"[信息] GIF 已写入 {out_path} ({len(pal_frames)} 帧)")
return len(pal_frames)
# ==========================================================================
# 图例 / 信息条 (PIL)
# ==========================================================================
_FONT_CANDIDATES = [
"C:/Windows/Fonts/msyh.ttc",
"C:/Windows/Fonts/msyhbd.ttc",
"C:/Windows/Fonts/simhei.ttf",
"C:/Windows/Fonts/simsun.ttc",
"/System/Library/Fonts/PingFang.ttc",
"/usr/share/fonts/opentype/noto/NotoSansCJK-Regular.ttc",
"/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf",
]