chempy
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseChemPy - Physical and Analytical Chemistry
ChemPy - 物理与分析化学
ChemPy provides a systematic way to handle chemical entities and reactions. It can automatically balance complex redox reactions, solve systems of ordinary differential equations (ODEs) for kinetics, and calculate species distribution in equilibria.
ChemPy提供了一种系统化的方式来处理化学实体和反应。它可以自动配平复杂的氧化还原反应,求解动力学相关的常微分方程(ODE)系统,并计算平衡状态下的物种分布。
When to Use
适用场景
- Balancing chemical equations (including ionic and redox reactions).
- Simulating chemical kinetics (concentration vs. time) using ODE solvers.
- Calculating chemical equilibria and speciation (e.g., pH of a buffer).
- Handling physical constants and units in chemical calculations.
- Modeling ionic strength and activity coefficients (Debye-Hückel).
- Parsing chemical formulas and calculating molar masses.
- Generating LaTeX or HTML representations of chemical reactions.
- 配平化学方程式(包括离子反应和氧化还原反应)。
- 使用ODE求解器模拟化学动力学(浓度随时间变化)。
- 计算化学平衡和物种分布(例如缓冲溶液的pH值)。
- 在化学计算中处理物理常数和单位。
- 建模离子强度和活度系数(德拜-休克尔理论)。
- 解析化学式并计算摩尔质量。
- 生成化学反应的LaTeX或HTML表示形式。
Reference Documentation
参考文档
Official docs: https://bjodah.github.io/chempy/
GitHub: https://github.com/bjodah/chempy
Search patterns:, , ,
GitHub: https://github.com/bjodah/chempy
Search patterns:
chempy.Reactionchempy.ReactionSystemchempy.balance_stoichiometrychempy.kinetics官方文档:https://bjodah.github.io/chempy/
GitHub仓库:https://github.com/bjodah/chempy
搜索关键词:, , ,
GitHub仓库:https://github.com/bjodah/chempy
搜索关键词:
chempy.Reactionchempy.ReactionSystemchempy.balance_stoichiometrychempy.kineticsCore Principles
核心原则
Chemical Entities
化学实体
Represented as strings ('H2O', 'Fe+3') or Substance objects. ChemPy can parse these to determine composition and charge.
以字符串(如'H2O'、'Fe+3')或Substance对象表示。ChemPy可以解析这些实体以确定其组成和电荷。
Reaction Systems
反应系统
A collection of Reaction objects. This system can be converted into a mathematical model (ODE) where the rates are defined by mass-action kinetics or custom rate laws.
由多个Reaction对象组成的集合。该系统可以转换为数学模型(ODE),其中反应速率由质量作用定律或自定义速率定律定义。
Units
单位
ChemPy integrates with quantities or pint to ensure dimensional correctness, which is vital for calculating rates (e.g., M⁻¹s⁻¹).
ChemPy与quantities或pint库集成,以确保维度正确性,这对于计算反应速率(如M⁻¹s⁻¹)至关重要。
Quick Reference
快速参考
Installation
安装
bash
pip install chempybash
pip install chempyStandard Imports
标准导入
python
import numpy as np
import matplotlib.pyplot as plt
from chempy import Reaction, ReactionSystem, Substance
from chempy.util.parsing import formula_to_compositionpython
import numpy as np
import matplotlib.pyplot as plt
from chempy import Reaction, ReactionSystem, Substance
from chempy.util.parsing import formula_to_compositionBasic Pattern - Balancing a Reaction
基础示例 - 反应配平
python
from chempy import balance_stoichiometrypython
from chempy import balance_stoichiometry1. Define reactants and products
1. 定义反应物和产物
reac, prod = balance_stoichiometry({'H2', 'O2'}, {'H2O'})
reac, prod = balance_stoichiometry({'H2', 'O2'}, {'H2O'})
2. Output coefficients
2. 输出系数
print(reac) # {'H2': 2, 'O2': 1}
print(prod) # {'H2O': 2}
undefinedprint(reac) # {'H2': 2, 'O2': 1}
print(prod) # {'H2O': 2}
undefinedCritical Rules
重要规则
✅ DO
✅ 推荐做法
- Use Standard Notation - Follow standard chemical notation for formulas ('H2SO4', 'Fe+3') for reliable parsing.
- Define a ReactionSystem - For any complex network, wrap reactions in a ReactionSystem to manage substances and rates together.
- Check Mass/Charge Balance - Always verify that your reactions are balanced before running kinetic simulations.
- Use Units - Whenever possible, use a units library to avoid errors in time scales or concentration units.
- Specify Rate Laws - Be explicit about whether a reaction is elementary (mass-action) or follows a custom rate law.
- Vectorize Concentrations - Use NumPy arrays when providing initial concentrations to solvers.
- 使用标准符号 - 遵循化学式的标准表示法(如'H2SO4'、'Fe+3')以确保解析可靠性。
- 定义ReactionSystem - 对于任何复杂的反应网络,将反应封装在ReactionSystem中,统一管理物质和反应速率。
- 检查质量/电荷平衡 - 在运行动力学模拟之前,务必验证反应是否配平。
- 使用单位 - 尽可能使用单位库,避免时间尺度或浓度单位的错误。
- 明确速率定律 - 明确说明反应是基元反应(质量作用定律)还是遵循自定义速率定律。
- 向量化浓度 - 向求解器提供初始浓度时,使用NumPy数组。
❌ DON'T
❌ 不推荐做法
- Manually Balance Complex Equations - Let balance_stoichiometry handle it, especially for redox reactions.
- Ignore Ionic Strength - In analytical chemistry, remember that activity coefficients change with ionic strength (use chempy.einstein).
- Assume Fast Equilibria - In kinetic models, ensure your rate constants for "instantaneous" steps are high enough but don't cause numerical stiffness.
- Hardcode Molar Masses - Use Substance.from_formula('H2O').mass to ensure precision.
- 手动配平复杂方程式 - 让balance_stoichiometry函数处理,尤其是氧化还原反应。
- 忽略离子强度 - 在分析化学中,记住活度系数会随离子强度变化(使用chempy.einstein)。
- 假设快速平衡 - 在动力学模型中,确保“瞬时”步骤的速率常数足够大,但不会导致数值刚性问题。
- 硬编码摩尔质量 - 使用Substance.from_formula('H2O').mass来确保精度。
Anti-Patterns (NEVER)
反模式(绝对避免)
python
from chempy import balance_stoichiometrypython
from chempy import balance_stoichiometry❌ BAD: Manual string parsing to find mass
❌ 错误:手动解析字符串计算质量
mass = 1.008 * 2 + 16.00 # Fragile and tedious
mass = 1.008 * 2 + 16.00 # 脆弱且繁琐
✅ GOOD: Use Substance properties
✅ 正确:使用Substance属性
from chempy import Substance
water = Substance.from_formula('H2O')
print(water.mass)
from chempy import Substance
water = Substance.from_formula('H2O')
print(water.mass)
❌ BAD: Hardcoding ODEs for kinetics
❌ 错误:硬编码动力学ODE
def dc_dt(c, t): return [-k*c[0]*c[1], ...] # Error-prone
def dc_dt(c, t): return [-k*c[0]*c[1], ...] # 容易出错
✅ GOOD: Generate ODE from ReactionSystem
✅ 正确:从ReactionSystem生成ODE
from chempy.kinetics.ode import get_odesys
rsys = ReactionSystem.from_string("A + B -> C; k")
odesys, extra = get_odesys(rsys)
from chempy.kinetics.ode import get_odesys
rsys = ReactionSystem.from_string("A + B -> C; k")
odesys, extra = get_odesys(rsys)
This handles all derivatives automatically
这会自动处理所有导数
undefinedundefinedStoichiometry and Formulas
化学计量学与化学式
Advanced Balancing (Redox)
进阶配平(氧化还原反应)
python
from chempy import balance_stoichiometrypython
from chempy import balance_stoichiometryBalancing KMn04 + HCl reaction
配平KMnO4 + HCl反应
reactants = {'KMnO4', 'HCl'}
products = {'KCl', 'MnCl2', 'H2O', 'Cl2'}
reac, prod = balance_stoichiometry(reactants, products)
print(f"Balanced: 2 KMnO4 + 16 HCl -> 2 KCl + 2 MnCl2 + 8 H2O + 5 Cl2")
undefinedreactants = {'KMnO4', 'HCl'}
products = {'KCl', 'MnCl2', 'H2O', 'Cl2'}
reac, prod = balance_stoichiometry(reactants, products)
print(f"配平结果:2 KMnO4 + 16 HCl -> 2 KCl + 2 MnCl2 + 8 H2O + 5 Cl2")
undefinedSubstance Properties
物质属性
python
from chempy import Substancepython
from chempy import SubstanceCreate substance with metadata
创建带元数据的物质
ferric = Substance('Fe+3', name='Iron(III) ion', latex='Fe^{3+}')
print(ferric.composition) # {26: 1} - Atomic number 26
print(ferric.charge) # 3
undefinedferric = Substance('Fe+3', name='Iron(III) ion', latex='Fe^{3+}')
print(ferric.composition) # {26: 1} - 原子序数26
print(ferric.charge) # 3
undefinedChemical Kinetics (chempy.kinetics)
化学动力学(chempy.kinetics)
Simulating Concentration over Time
模拟浓度随时间变化
python
from chempy import ReactionSystem
from chempy.kinetics.ode import get_odesys
import numpy as nppython
from chempy import ReactionSystem
from chempy.kinetics.ode import get_odesys
import numpy as np1. Define the system: 2A -> B (rate constant k=0.5)
1. 定义反应系统:2A -> B(速率常数k=0.5)
rsys = ReactionSystem.from_string("2 A -> B; 0.5")
rsys = ReactionSystem.from_string("2 A -> B; 0.5")
2. Get the ODE system
2. 获取ODE系统
odesys, extra = get_odesys(rsys)
odesys, extra = get_odesys(rsys)
3. Integrate
3. 求解积分
tout = np.linspace(0, 10, 50)
c0 = {'A': 1.0, 'B': 0.0}
result = odesys.integrate(tout, c0)
tout = np.linspace(0, 10, 50)
c0 = {'A': 1.0, 'B': 0.0}
result = odesys.integrate(tout, c0)
4. Plot
4. 绘图
plt.plot(result.tout, result.cout)
plt.legend(rsys.substances.keys())
undefinedplt.plot(result.tout, result.cout)
plt.legend(rsys.substances.keys())
undefinedChemical Equilibria
化学平衡
Calculating Speciation
计算物种分布
python
from chempy.equilibria import EqSystempython
from chempy.equilibria import EqSystemDefine equilibria: H2O <-> H+ + OH- (Kw = 1e-14)
定义平衡反应:H2O <-> H+ + OH-(Kw = 1e-14)
and acetic acid dissociation
以及乙酸解离
eqsys = EqSystem.from_string("""
H2O <-> H+ + OH-; 1e-14
CH3COOH <-> CH3COO- + H+; 1.75e-5
""")
eqsys = EqSystem.from_string("""
H2O <-> H+ + OH-; 1e-14
CH3COOH <-> CH3COO- + H+; 1.75e-5
""")
Calculate concentrations given initial state
根据初始状态计算浓度
init_conc = {'H2O': 55.5, 'CH3COOH': 0.1, 'H+': 1e-7, 'OH-': 1e-7, 'CH3COO-': 0}
final_conc, info = eqsys.root(init_conc)
print(f"pH: {-np.log10(final_conc[eqsys.substances.index('H+')]):.2f}")
undefinedinit_conc = {'H2O': 55.5, 'CH3COOH': 0.1, 'H+': 1e-7, 'OH-': 1e-7, 'CH3COO-': 0}
final_conc, info = eqsys.root(init_conc)
print(f"pH值:{-np.log10(final_conc[eqsys.substances.index('H+')]):.2f}")
undefinedPhysical Chemistry Utilities
物理化学工具
Ionic Strength and Activity
离子强度与活度
python
from chempy.electrolytes import ion_strength, davies_activity_coefficientpython
from chempy.electrolytes import ion_strength, davies_activity_coefficientCalculate ionic strength of 0.1M Na2SO4
计算0.1M Na2SO4的离子强度
molalities = {'Na+': 0.2, 'SO4-2': 0.1}
I = ion_strength(molalities)
molalities = {'Na+': 0.2, 'SO4-2': 0.1}
I = ion_strength(molalities)
Davies activity coefficient (extension of Debye-Hückel)
Davies活度系数(德拜-休克尔理论的扩展)
gamma = davies_activity_coefficient(I, z=2, eps=78.3, T=298.15)
print(f"Activity coefficient for SO4-2: {gamma:.3f}")
undefinedgamma = davies_activity_coefficient(I, z=2, eps=78.3, T=298.15)
print(f"SO4-2的活度系数:{gamma:.3f}")
undefinedPractical Workflows
实用工作流
1. Titration Curve Simulation
1. 滴定曲线模拟
python
def simulate_titration(acid_conc, base_concs):
"""Calculates pH as base is added to an acid."""
results = []
for cb in base_concs:
# Define complex equilibrium system for each step
eqsys = EqSystem.from_string(f"HA <-> H+ + A-; 1e-5\nH2O <-> H+ + OH-; 1e-14")
# Solve for H+ concentration
...
return resultspython
def simulate_titration(acid_conc, base_concs):
"""计算加入碱时酸的pH值变化。"""
results = []
for cb in base_concs:
# 为每个步骤定义复杂的平衡系统
eqsys = EqSystem.from_string(f"HA <-> H+ + A-; 1e-5\nH2O <-> H+ + OH-; 1e-14")
# 求解H+浓度
...
return results2. Enzyme Kinetics (Michaelis-Menten ODE)
2. 酶动力学(米氏方程ODE)
python
def enzyme_kinetics():
# E + S <-> ES -> E + P
rsys = ReactionSystem.from_string("""
E + S <-> ES; 1e6, 1e2
ES -> E + P; 1e3
""")
odesys, _ = get_odesys(rsys)
# Integrate to see substrate depletion and product formation
...python
def enzyme_kinetics():
# E + S <-> ES -> E + P
rsys = ReactionSystem.from_string("""
E + S <-> ES; 1e6, 1e2
ES -> E + P; 1e3
""")
odesys, _ = get_odesys(rsys)
# 积分以观察底物消耗和产物生成
...3. Atmospheric Chemistry Model
3. 大气化学模型
python
def ozone_cycle():
# Simple Chapman Cycle
reactions = """
O2 -> 2 O; k1
O + O2 -> O3; k2
O3 -> O + O2; k3
O + O3 -> 2 O2; k4
"""
rsys = ReactionSystem.from_string(reactions)
# Solve for steady-state ozone concentration
...python
def ozone_cycle():
# 简单的查普曼循环
reactions = """
O2 -> 2 O; k1
O + O2 -> O3; k2
O3 -> O + O2; k3
O + O3 -> 2 O2; k4
""")
rsys = ReactionSystem.from_string(reactions)
# 求解稳态臭氧浓度
...Performance Optimization
性能优化
Symbolic Derivation
符号推导
ChemPy uses SymPy under the hood to derive the Jacobian of the ODE system. This makes integration significantly faster and more stable than numerical Jacobian estimation.
ChemPy在底层使用SymPy来推导ODE系统的雅可比矩阵。这使得积分速度比数值雅可比估计更快、更稳定。
Native Code Generation
原生代码生成
For very large systems, ChemPy can use pyodesys to generate C++ or Fortran code from your chemical reaction network, which is then compiled and called from Python.
对于非常大的系统,ChemPy可以使用pyodesys将化学反应网络生成C++或Fortran代码,然后编译并从Python调用。
Common Pitfalls and Solutions
常见陷阱与解决方案
The "Stiff System" Problem
“刚性系统”问题
Chemical systems often have reactions with widely different time scales (fast proton transfer vs. slow combustion).
python
undefined化学系统通常包含时间尺度差异极大的反应(快速质子转移 vs 缓慢燃烧)。
python
undefined✅ Solution: Use a stiff-capable solver (like 'cvode' or 'lsoda')
✅ 解决方案:使用支持刚性系统的求解器(如'cvode'或'lsoda')
result = odesys.integrate(tout, c0, integrator='lsoda')
undefinedresult = odesys.integrate(tout, c0, integrator='lsoda')
undefinedFormula Parsing Ambiguity
化学式解析歧义
'Co' could be Cobalt or Carbon + Oxygen.
python
undefined'Co'可能指钴元素,也可能指碳+氧。
python
undefined❌ Problem: formula_to_composition('Co') -> {27: 1} (Cobalt)
❌ 问题:formula_to_composition('Co') -> {27: 1}(钴)
✅ Solution: Use Substance objects to be explicit
✅ 解决方案:使用Substance对象明确指定
sub = Substance('CO', name='Carbon Monoxide')
undefinedsub = Substance('CO', name='一氧化碳')
undefinedUnits and Floating Point
单位与浮点数问题
Equilibrium constants (K) can span 50 orders of magnitude (10⁻⁵⁰ to 10²⁰).
python
undefined平衡常数(K)的范围可能跨越50个数量级(10⁻⁵⁰到10²⁰)。
python
undefined❌ Problem: Standard root finders might fail on small values
❌ 问题:标准根查找器可能在处理小数值时失败
✅ Solution: Solve in log-space (log-concentrations)
✅ 解决方案:在对数空间中求解(对数浓度)
final_conc, info = eqsys.root(init_conc, use_log=True)
ChemPy brings the precision of physical chemistry to the Python world. By automating the transition from chemical notation to mathematical models, it allows researchers to focus on the chemistry rather than the underlying differential equations.final_conc, info = eqsys.root(init_conc, use_log=True)
ChemPy将物理化学的计算精度带入Python世界。通过自动化从化学符号到数学模型的转换,它让研究人员能够专注于化学本身,而非底层的微分方程。