用python写的温控系统雏形

题目要求:

§Temperature
§Inputs: current temperature, its time derivatives
§Parameter: target temperature
§Output: the amounts of heat sources to be applied.

§Rules: fuzzy rules
§E.g. If the temperature is moderately high and the pressure is very low, then the output is medium.
具体给出了九条模糊规则,先是模糊化,然后处理,再反模糊处理,我的代码如下:
d = {'NB':(2.0,-4.0),'NS':(2.0,-2.0),'ZO':(2.0,0.0),'PS':(2.0,2.0),'PB':(2.0,4.0)}
#side = {'NB':[-4.0,-2.0],'NS':[-4.0,0.0],'ZO':[-2.0,2.0],'PS':(0.0,4.0),'PB':(2.0,4.0)}
def mx(s,x):
    a,b = d.get(s)
    return max((a - abs(x - b)) / a,0)
def mw(ai,s,x):
    return min(ai,mx(s,x))
def fuzzy_w(e,ve):
    '''select fuzzy(w) by e and ve'''
    w = ''
    if e == "ZO" and ve == "NB":
        return "PB"
    if e == "ZO" and ve == "NS":
        return "PS"
    if e == "NB" and ve == "ZO":
        return "PB"
    if e == "NS" and ve == "ZO":
        return "PS"
    if e == "ZO" and ve == "ZO":
        return "ZO"
    if e == "ZO" and ve == "PS":
        return "NS"
    if e == "ZO" and ve == "PB":
        return "NB"
    if e == "PS" and ve =="ZO":
        return "NS"
    if e == "PB" and ve == "ZO":
        return "NB"
def select_rule(e,ve):
    """选取规则,返回形式['W','E','VE']"""
    li = []
    if mx("ZO",ve) > 0:
        for i in d.keys():
            if mx(i,e) > 0:
                li.append((fuzzy_w(i,"ZO"),i,'ZO'))
    elif mx("ZO",e) > 0 :
        for i in d.keys():
            if mx(i,ve) > 0:
                li.append((fuzzy_w("ZO",i),'ZO',i))
   
    return li
def out(e,ve,w):
    '''输出计算出的w值'''
    a = []
    DOWN,UP = -4,4
    (sum0,sum1,dx) = (0.0,0.0,0.002)
    for i in w:
        '''计算出ai和aj,存到list a[]中'''
        W,E,VE = i
        ai = min(mx(E,e),mx(VE,ve))
        a.append(ai)
    x = DOWN
    while(x  1:
            fx = max(mw(a[0],w[0][0],x),mw(a[1],w[1][0],x))
        elif len(a) == 1:
            fx = mw(a[0],w[0][0],x)
        sum0 += (fx * dx)
        sum1 += (x * fx * dx)
        x += dx
    return sum1 / sum0
def run():
    Tn = -100
    En = Tn
    Ve = 0
    for i in range(40):
    #while(1):
        EEn = En
        VVe = Ve
        if En  4:
            EEn = 4
        if Ve  4:
            VVe = 4
        w_rule = select_rule(EEn,VVe)
        if len(w_rule) > 0:
            w0 = out(EEn,VVe,w_rule)
        Ve += 2*w0
        En += Ve
        #Tn += Ve
        #En = Tn
        print 'E:',En,'VE:',Ve,'w0:',w0
run()
这个是没有图形的,现在能够实时打印一些所有值,下一步就是将它图形化.