【问题标题】:How can I use Python to create a Stoichiometric Matrix如何使用 Python 创建化学计量矩阵
【发布时间】:2018-04-18 22:07:12
【问题描述】:

我是 Python 和 Pandas 的新手,所以如果有人能在这件事上帮助我,我会非常高兴。我的问题如下:

如果我有一个 .txt 文件,其中包含一组作为字符串(R1、R2...)的反应。每个反应都有化合物 (A,B,C,D...),它们具有各自的化学计量系数 (1, 2, 3...),例如:

R1: A + 2B + C <=> D

R2: A + B <=> C

如何在 python 中以化学计量矩阵的格式(化合物作为行 X 反应作为列)创建数据框,如下所示:

  R1 R2
A -1 -1 
B -2 -1
C -1  1
D  1  0

观察:等式左边的化合物应该有负的化学计量值,而右边的应该是正的

谢谢=D

【问题讨论】:

  • 您的反应数据是如何存储的?作为 txt 文件中的字符串,还是已经有某种结构?另外,R2 中的化合物 C 应该是 +1,对吧?
  • 谢谢@WolfgangK。反应以字符串形式存储在 txt 文件中,我刚刚更正了 R2 中的 C 系数。
  • 这可能适用于您正在做的事情,也可能不适用,但您可以查看cobrapy。这是为反应网络创建和管理化学计量矩阵的好方法。它还具有用于分析的求解器和算法。

标签: python pandas chemistry


【解决方案1】:

试试这个:

import pandas as pd
import re  # regular expressions

def coeff_comp(s):
    # Separate stoichiometric coefficient and compound
    result = re.search('(?P<coeff>\d*)(?P<comp>.*)', s)
    coeff = result.group('coeff')
    comp = result.group('comp')
    if not coeff:
        coeff = '1'                          # coefficient=1 if it is missing
    return comp, int(coeff)

equations = ['R1: A + 2B + C <=> D', 'R2: A + B <=> C']  # some test data
reactions_dict = {}                          # results dictionary

for equation in equations:
    compounds = {}                           # dict -> compound: coeff 
    eq = equation.replace(' ', '')  
    r_id, reaction = eq.split(':')           # separate id from chem reaction
    lhs, rhs = reaction.split('<=>')         # split left and right hand side
    reagents = lhs.split('+')                # get list of reagents
    products = rhs.split('+')                # get list of products
    for reagent in reagents:
        comp, coeff = coeff_comp(reagent)
        compounds[comp] = - coeff            # negative on lhs
    for product in products:
        comp, coeff = coeff_comp(product)
        compounds[comp] = coeff              # positive on rhs
    reactions_dict[r_id] = compounds         

# insert dict into DataFrame, replace NaN with 0, let values be int
df = pd.DataFrame(reactions_dict).fillna(value=0).astype(int)

输出看起来像

   R1  R2
A  -1  -1
B  -2  -1
C  -1   1
D   1   0

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-04
    • 1970-01-01
    • 2014-06-20
    • 2021-09-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多