首页 > Chemistry, Script > 获取所有符合条件分子式的脚本

获取所有符合条件分子式的脚本

[总点击:325次]
2009年12月24日

在某些时候我们只知道某一个分子的分子量和大概的碳氢氧的个数范围,在这种情况下要算出符合这些条件的分子式,用手工的方法算是很麻烦的,于是就有了下面的这个脚本,其特点是:
1) 全面,无漏网之鱼
2) 用了不饱和度检测,不饱和度不正常的(如为小数)分子式均被排除
3) python 写的,可跨平台使用。

例子:

xiooli@XIOOLI> python  .bin/fmcom.py
Please input: 173 c,8,18 h,0,20 o,0,10 n,0,6
The results are as follows:
MF: C8H3O2N3   Ω: 9
MF: C8H7N5     Ω: 8
MF: C8H15O3N   Ω: 2
MF: C8H19ON3   Ω: 1
MF: C9H3O3N    Ω: 9
MF: C9H7ON3    Ω: 8
MF: C9H19O2N   Ω: 1
MF: C10H7O2N   Ω: 8
MF: C10H11N3   Ω: 7
MF: C11H11ON   Ω: 7
MF: C12H15N    Ω: 6
MF: C13H3N     Ω: 13

说明一下: 173 c,8,18 h,0,20 o,0,10
这里 173 是分子量, 后边的表达式都是一样的如:c,8,18 表示 碳原子 个数范围为 8 到 18。
注意分隔符是英文逗号。

源码:

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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Name:     fmcom.py
# Author:   xiooli <xioooli[at]yahoo.com.cn>
# Site:     http://joolix.com
# Licence:  GPLv3
# Version:  091224
 
'''compute out the formula of a given molecular weight'''
 
import sys
 
# dictionary for the elements: { 'element': (atomic weight, omiga factor)
edic = { 'C': (12, 1),
        'H': (1, -0.5),
        'O': (16, 0),
        'N': (14, 0.5)
        }
 
args = sys.argv
 
def gen_formula(args):
    '''Main function for generating the formula'''
 
    mw = args[0]
    e_info = []
    formula = ''
    omiga = ''
    fors = ''
    ifs =''
 
    E = lambda x, y: (y==0 and ' ') or (y==1 and x.upper()) or x.upper() + str(y)
    L = lambda x, y: (x, len(x), y)
 
    for tmp in args[1:]:
        e_info.append(tmp.split(','))
        element, num1, num2 = tmp.split(',')
        element = element.upper()
        formula += 'E("' + str(element) + '",' + element + ') + '
        fors += ' for ' + element + ' in range(' + num1 + ',' + num2 + ') '
        ifs += str(edic[element][0]) + '*' + element + ' + '
        omiga += str(edic[element][1]) + '*' + element + ' + '
 
    formula = formula.strip('+ ')
    omiga += '1'
    ifs = ifs.strip('+ ')
 
    cmd = '[ L((' + formula + ').replace(\' \',\'\'), ' + omiga + ')' + fors + \
            'if ' + ifs + ' == ' + mw + ' and int(' + omiga + ') == ' + omiga + ']'
    l = eval(cmd)
 
    if l:
        print 'The results are as follows:'
        for f in l:
            str_omiga = str(int(f[2]))
            print 'MF: ' + f[0] + ('Ω: ' + str_omiga).rjust(15 - f[1] + len(str_omiga))
    else:
        print 'No suitable molecular formula found.'
 
if __name__ == '__main__':
    if len(args) <= 1:
        input = raw_input('Please input: ')
        args = input.split(' ')
        gen_formula(args)
    elif args[1] == '-h' or args[1] == '--help':
        print args[0] + ' [molecular weight] [element1, least, most] [element2, least, most] ...'
    else:
        gen_formula(args[1:])

Chemistry, Script , ,

本文的评论功能被关闭了.