import pandas as pd
from pymatgen.ext.matproj import MPRester
from pymatgen.core import Element
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.ensemble import RandomForestRegressor
from sklearn.metrics import mean_squared_error, r2_score
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
# --- 1. 配置Material Project API Key ---
# 替换为你的API Key
# Option 1: Set as environment variable (recommended)
# export MAPI_KEY="YOUR_API_KEY"
# mp_rest = MPRester() # Will automatically pick up the env variable
# Option 2: Directly in code (less secure)
MP_API_KEY = "YOUR_MATERIAL_PROJECT_API_KEY"
mp_rest = MPRester(MP_API_KEY)
# --- 2. 获取NaVPO4F的基体性质 (示例) ---
# 实际的 NaVPO4F material_id 可能需要你在MP网站上搜索确认
# 假设 NaVPO4F 的 MP ID 是 mp-XXXX (你需要查找确切的ID)
na_v_po4_f_id = "mp-22165" # 这是一个示例ID,请在MP网站上搜索 NaVPO4F 得到正确的ID
try:
na_v_po4_f_data = mp_rest.get_data_by_material_id(na_v_po4_f_id, inc_structure=True)
if na_v_po4_f_data:
na_v_po4_f_entry = na_v_po4_f_data[0] # Usually a list, take the first entry
na_v_po4_f_band_gap = na_v_po4_f_entry.get("band_gap", None)
na_v_po4_f_formation_energy_per_atom = na_v_po4_f_entry.get("formation_energy_per_atom", None)
na_v_po4_f_density = na_v_po4_fo_entry.get("density", None)
print(f"NaVPO4F Band Gap: {na_v_po4_f_band_gap} eV")
print(f"NaVPO4F Formation Energy per Atom: {na_v_po4_f_formation_energy_per_atom} eV/atom")
print(f"NaVPO4F Density: {na_v_po4_f_density} g/cm^3")
else:
print(f"Could not retrieve data for NaVPO4F with ID {na_v_po4_f_id}.")
# Fallback values if data isn't found
na_v_po4_f_band_gap = 2.5 # Example value
na_v_po4_f_formation_energy_per_atom = -2.5 # Example value
na_v_po4_f_density = 3.5 # Example value
except Exception as e:
print(f"Error accessing MP for NaVPO4F: {e}")
# Fallback values if API call fails
na_v_po4_f_band_gap = 2.5 # Example value
na_v_po4_f_formation_energy_per_atom = -2.5 # Example value
na_v_po4_f_density = 3.5 # Example value
# Get properties of Vanadium (V), the element being substituted
v_element = Element("V")
v_electronegativity = v_element.X
# Example ionic radius for V in NaVPO4F (typically V3+ or V4+)
# For V3+ (ionic radius) - need to be careful with coordination number
# pymatgen Element.ionic_radius_dict might not be exhaustive.
# You might need to hardcode common values from literature/database (e.g., Shannon radii)
# For simplicity, let's use a representative ionic radius for V (e.g., V3+ in octahedral coordination)
v_ionic_radius = 0.64 # Example for V3+ high spin, CN=6 from literature
v_valence_electrons = v_element.nvalence
print(f"V Electronegativity: {v_electronegativity}")
print(f"V Ionic Radius (example): {v_ionic_radius}")
print(f"V Valence Electrons: {v_valence_electrons}")
# --- 3. 定义潜在的掺杂元素和浓度范围 ---
# 常见过渡金属和其他可能掺杂的元素
dopant_elements_symbols = ["Fe", "Mn", "Co", "Ni", "Ti", "Cr", "Al", "Mg", "Zn", "Zr", "Nb", "Mo", "W"]
# 掺杂浓度范围 (例如,从 1% 到 10%,步长 1%)
concentrations = np.arange(0.01, 0.11, 0.01) # 1% to 10%
# --- 4. 构建模拟数据集和特征 ---
# 假设我们有一个目标变量,例如 "Theoretical_Capacity_mAh_g" 和 "Average_Voltage_V"
# 实际项目中,你需要从文献/自己的DFT计算中获取这些数据,作为训练模型的标签。
# 在这个高通量筛选场景中,我们先生成一个带标签的“训练集”,其标签是“模拟”的。
# 真实的项目中,你需要收集已有的掺杂NaVPO4F的性能数据作为训练集。
# 如果没有实际数据,这个模型只能学习特征之间的“相关性”,无法预测真实性能。
# 这里我们创建一个假的目标变量,以便演示ML流程。
data = []
# 假设一个简单的函数来模拟掺杂对电池性能的影响 (这个是核心假设,需要真实数据来替换)
# 这是一个非常简化的示例,在实际项目中,你需要通过文献调研、DFT计算或实验数据来获取真实的性能指标
def simulate_battery_performance(dopant_element, concentration, base_voltage=3.8, base_capacity=160,
v_ionic_radius=v_ionic_radius, v_electronegativity=v_electronegativity):
"""
模拟掺杂对电池性能的影响。
这是一个高度简化的函数,用于演示目的。
实际中需要更复杂的物理化学模型或真实数据。
"""
dopant_el = Element(dopant_element)
dopant_ionic_radius = dopant_el.average_ionic_radius # Pymatgen sometimes has this
if not dopant_ionic_radius: # Fallback if specific ionic radius not found for average
# Attempt to get common ionic radius from specific oxidation states if available
# Example: for Fe, check common states like Fe2+, Fe3+
if dopant_element == "Fe": dopant_ionic_radius = 0.645 # Fe3+ high spin CN6
elif dopant_element == "Mn": dopant_ionic_radius = 0.67 # Mn3+ high spin CN6
elif dopant_element == "Co": dopant_ionic_radius = 0.61 # Co3+ low spin CN6
elif dopant_element == "Ni": dopant_ionic_radius = 0.69 # Ni2+ high spin CN6
elif dopant_element == "Ti": dopant_ionic_radius = 0.605 # Ti4+ CN6
elif dopant_element == "Cr": dopant_ionic_radius = 0.615 # Cr3+ CN6
elif dopant_element == "Al": dopant_ionic_radius = 0.535 # Al3+ CN6
elif dopant_element == "Mg": dopant_ionic_radius = 0.72 # Mg2+ CN6
elif dopant_element == "Zn": dopant_ionic_radius = 0.74 # Zn2+ CN6
elif dopant_element == "Zr": dopant_ionic_radius = 0.79 # Zr4+ CN6
elif dopant_element == "Nb": dopant_ionic_radius = 0.64 # Nb5+ CN6
elif dopant_element == "Mo": dopant_ionic_radius = 0.65 # Mo6+ CN6
elif dopant_element == "W": dopant_ionic_radius = 0.66 # W6+ CN6
else: dopant_ionic_radius = dopant_el.atomic_radius # Fallback to atomic radius if ionic not found
if not dopant_ionic_radius: dopant_ionic_radius = 1.0 # Default if still none
delta_ionic_radius = abs(dopant_ionic_radius - v_ionic_radius)
delta_electronegativity = abs(dopant_el.X - v_electronegativity)
# Simulate a simple effect: larger ionic radius difference and higher concentration might reduce stability/capacity
# Electronegativity difference might influence voltage
simulated_voltage = base_voltage + (dopant_el.X - v_electronegativity) * 0.1 - (delta_ionic_radius * 0.5) - (concentration * 5)
simulated_capacity = base_capacity - (delta_ionic_radius * 50) - (concentration * 500)
# Add some noise to make it more realistic for ML training
simulated_voltage += np.random.normal(0, 0.05)
simulated_capacity += np.random.normal(0, 5)
# Ensure capacity is positive
simulated_capacity = max(10, simulated_capacity)
return simulated_voltage, simulated_capacity
for dopant_symbol in dopant_elements_symbols:
dopant_el = Element(dopant_symbol)
# Extract dopant properties
dopant_features = {
"Dopant_Symbol": dopant_symbol,
"Dopant_Atomic_Number": dopant_el.Z,
"Dopant_Pauling_Electronegativity": dopant_el.X,
"Dopant_Atomic_Radius": dopant_el.atomic_radius,
"Dopant_Valence_Electrons": dopant_el.nvalence,
"Dopant_First_Ionization_Energy": dopant_el.ionization_energies[0] if dopant_el.ionization_energies else np.nan,
"Dopant_Electron_Affinity": dopant_el.electron_affinity if dopant_el.electron_affinity else np.nan,
"Dopant_Block": dopant_el.block,
"Dopant_Group": dopant_el.group,
"Dopant_Period": dopant_el.period,
# Common ionic radius - this is tricky and often needs careful selection for specific coordination/valence
"Dopant_Ionic_Radius": dopant_el.average_ionic_radius if dopant_el.average_ionic_radius else np.nan # Fallback strategy needed here
}
# Handle missing ionic radius more robustly - this part is often manual based on known values
if np.isnan(dopant_features["Dopant_Ionic_Radius"]):
# A more robust approach: use a mapping or specific function for common oxidation states
# For this example, we'll assign a placeholder or use atomic radius
if dopant_symbol == "Fe": dopant_features["Dopant_Ionic_Radius"] = 0.645 # Fe3+
elif dopant_symbol == "Mn": dopant_features["Dopant_Ionic_Radius"] = 0.67 # Mn3+
elif dopant_symbol == "Co": dopant_features["Dopant_Ionic_Radius"] = 0.61 # Co3+ low spin
elif dopant_symbol == "Ni": dopant_features["Dopant_Ionic_Radius"] = 0.69 # Ni2+
elif dopant_symbol == "Ti": dopant_features["Dopant_Ionic_Radius"] = 0.605 # Ti4+
elif dopant_symbol == "Cr": dopant_features["Dopant_Ionic_Radius"] = 0.615 # Cr3+
elif dopant_symbol == "Al": dopant_features["Dopant_Ionic_Radius"] = 0.535 # Al3+
elif dopant_symbol == "Mg": dopant_features["Dopant_Ionic_Radius"] = 0.72 # Mg2+
elif dopant_symbol == "Zn": dopant_features["Dopant_Ionic_Radius"] = 0.74 # Zn2+
elif dopant_symbol == "Zr": dopant_features["Dopant_Ionic_Radius"] = 0.79 # Zr4+
elif dopant_symbol == "Nb": dopant_features["Dopant_Ionic_Radius"] = 0.64 # Nb5+
elif dopant_symbol == "Mo": dopant_features["Dopant_Ionic_Radius"] = 0.65 # Mo6+
elif dopant_symbol == "W": dopant_features["Dopant_Ionic_Radius"] = 0.66 # W6+
else:
dopant_features["Dopant_Ionic_Radius"] = dopant_el.atomic_radius # Fallback if still unknown
for conc in concentrations:
row = {
"Dopant_Symbol": dopant_symbol,
"Concentration": conc,
**dopant_features
}
# Interaction features
row["delta_electronegativity"] = abs(dopant_features["Dopant_Pauling_Electronegativity"] - v_electronegativity)
row["delta_ionic_radius"] = abs(dopant_features["Dopant_Ionic_Radius"] - v_ionic_radius)
row["delta_valence_electrons"] = abs(dopant_features["Dopant_Valence_Electrons"] - v_valence_electrons)
# Simulated target variables (replace with actual data if available)
sim_voltage, sim_capacity = simulate_battery_performance(
dopant_symbol, conc, v_ionic_radius=v_ionic_radius, v_electronegativity=v_electronegativity
)
row["Simulated_Average_Voltage_V"] = sim_voltage
row["Simulated_Theoretical_Capacity_mAh_g"] = sim_capacity
data.append(row)
df = pd.DataFrame(data)
# Drop rows with NaN values if any (e.g., for elements without ionization energies easily found)
df.dropna(inplace=True)
# One-hot encode categorical features (e.g., Dopant_Block, Dopant_Group, Dopant_Period)
# For Dopant_Symbol, we will use it for plotting but not directly in ML features
df_encoded = pd.get_dummies(df.drop(columns=["Dopant_Symbol", "Dopant_Block"]), columns=["Dopant_Group", "Dopant_Period"]) # Removed block for simplicity, can add back
# Note: For group/period, directly using the number might be better than one-hot if they are continuous
# Let's revert and just use numbers for group/period, and drop block
df_encoded = df.drop(columns=["Dopant_Symbol", "Dopant_Block"])
df_encoded.columns = df_encoded.columns.str.replace(' ', '_') # Replace spaces in column names
print("Generated Data Head:")
print(df_encoded.head())
print("\nGenerated Data Info:")
df_encoded.info()
# --- 11. 生成高通量筛选的预测数据点 ---
# 假设我们想预测更细粒度的浓度,或是一些新的、未在训练集中出现的掺杂元素(确保其元素性质能获取)
new_dopant_elements_symbols = ["Sc", "Y", "Nb", "Ta", "Cr", "Mo", "W"] # 示例:添加一些新元素
new_concentrations = np.arange(0.005, 0.15, 0.005) # 0.5% 到 15%
new_data = []
for dopant_symbol in new_dopant_elements_symbols:
dopant_el = Element(dopant_symbol)
dopant_features = {
"Dopant_Symbol": dopant_symbol,
"Dopant_Atomic_Number": dopant_el.Z,
"Dopant_Pauling_Electronegativity": dopant_el.X,
"Dopant_Atomic_Radius": dopant_el.atomic_radius,
"Dopant_Valence_Electrons": dopant_el.nvalence,
"Dopant_First_Ionization_Energy": dopant_el.ionization_energies[0] if dopant_el.ionization_energies else np.nan,
"Dopant_Electron_Affinity": dopant_el.electron_affinity if dopant_el.electron_affinity else np.nan,
"Dopant_Group": dopant_el.group,
"Dopant_Period": dopant_el.period,
"Dopant_Ionic_Radius": dopant_el.average_ionic_radius if dopant_el.average_ionic_radius else np.nan
}
# Handle missing ionic radius for new elements as well
if np.isnan(dopant_features["Dopant_Ionic_Radius"]):
if dopant_symbol == "Sc": dopant_features["Dopant_Ionic_Radius"] = 0.745 # Sc3+ CN6
elif dopant_symbol == "Y": dopant_features["Dopant_Ionic_Radius"] = 0.9 # Y3+ CN6
elif dopant_symbol == "Ta": dopant_features["Dopant_Ionic_Radius"] = 0.64 # Ta5+ CN6
else: dopant_features["Dopant_Ionic_Radius"] = dopant_el.atomic_radius # Fallback if still unknown
for conc in new_concentrations:
row = {
"Dopant_Symbol": dopant_symbol,
"Concentration": conc,
**dopant_features
}
row["delta_electronegativity"] = abs(dopant_features["Dopant_Pauling_Electronegativity"] - v_electronegativity)
row["delta_ionic_radius"] = abs(dopant_features["Dopant_Ionic_Radius"] - v_ionic_radius)
row["delta_valence_electrons"] = abs(dopant_features["Dopant_Valence_Electrons"] - v_valence_electrons)
new_data.append(row)
new_df = pd.DataFrame(new_data)
new_df.dropna(inplace=True) # Drop rows with NaN (e.g. elements without data)
# Prepare new data for prediction (same preprocessing as training data)
new_X = new_df.drop(columns=["Dopant_Symbol"])
new_X_scaled = scaler.transform(new_X) # Use the same scaler fitted on training data
new_X_scaled_df = pd.DataFrame(new_X_scaled, columns=new_X.columns)
# --- 12. 进行预测 ---
predicted_voltage = model_voltage.predict(new_X_scaled_df)
predicted_capacity = model_capacity.predict(new_X_scaled_df)
new_df["Predicted_Voltage_V"] = predicted_voltage
new_df["Predicted_Capacity_mAh_g"] = predicted_capacity
# --- 13. 筛选和排序最优结果 ---
# 定义你的优化目标,例如:高电压 AND 高容量
# 这里我们选择电压和容量都高于某个阈值的材料,并按其乘积排序
# 实际阈值应基于你的期望和应用场景
voltage_threshold = 3.6
capacity_threshold = 140
promising_materials = new_df[
(new_df["Predicted_Voltage_V"] >= voltage_threshold) &
(new_df["Predicted_Capacity_mAh_g"] >= capacity_threshold)
].copy()
# 可以计算一个综合性能指标进行排序
promising_materials["Performance_Score"] = (
promising_materials["Predicted_Voltage_V"] * promising_materials["Predicted_Capacity_mAh_g"]
)
promising_materials = promising_materials.sort_values(
by="Performance_Score", ascending=False
).reset_index(drop=True)
print("\n--- Top 10 Promising Doping Combinations ---")
print(promising_materials[["Dopant_Symbol", "Concentration", "Predicted_Voltage_V", "Predicted_Capacity_mAh_g", "Performance_Score"]].head(10))
# 可视化筛选结果 (示例: 电压 vs 容量的散点图)
plt.figure(figsize=(10, 7))
sns.scatterplot(
data=new_df,
x="Predicted_Capacity_mAh_g",
y="Predicted_Voltage_V",
hue="Dopant_Symbol",
size="Concentration",
sizes=(20, 400),
alpha=0.7
)
plt.axhline(y=voltage_threshold, color='r', linestyle='--', label='Voltage Threshold')
plt.axvline(x=capacity_threshold, color='g', linestyle='--', label='Capacity Threshold')
plt.scatter(
promising_materials["Predicted_Capacity_mAh_g"],
promising_materials["Predicted_Voltage_V"],
color='purple',
marker='*',
s=200,
label='Promising Candidates'
)
plt.xlabel("Predicted Theoretical Capacity (mAh/g)")
plt.ylabel("Predicted Average Voltage (V)")
plt.title("Predicted Performance of Doped NaVPO4F Candidates")
plt.legend(bbox_to_anchor=(1.05, 1), loc='upper left')
plt.grid(True)
plt.tight_layout()
plt.show()