正德本义:整平道路

用Python3实现的Mycin专家系统简单实例

  1 from sys import stderr
  2 #########################
  3 TRUE = 1 #定义返回值
  4 FALSE = 0
  5 FACT_LENGTH = 9  #'''前提与结论总数'''
  6 PRMS_LENGTH = 2  #'''每条规则的前提个数'''
  7 PREMISE = 7 #'''前提数量''' 
  8 RULE_LENGTH = 4  #'''规则数量'''
  9 LIMIT = 0.5      #'''结论阈值'''
 10 AND = 1         #'''规则前提逻辑关系'''
 11 OR = 0
 12 VH = 0.9       #'''规则前提可信度初始化'''
 13 H = 0.7
 14 M = 0.5
 15 #double Rule_CF[RULE_LENGTH]
 16 Rule_CF = [0.0]*(RULE_LENGTH+1)
 17 Str = ["E1", "E2", "E3", "E4", "E5",
 18 "E6", "E7", "H1", "H", "\0"]
 19 Fuzz = [None]*10
 20 Input = [None]*PREMISE
 21 Repeat = -111   #'''重新输入变量'''
 22 
 23 #'''知识表达'''
 24 Sign=[0,0,0,0,0,0,0,0,1]
 25 Rulep=[[1,2,0],[4,5,0],[6,8,0],[3,7,0]]
 26 Rulec=[[9,'AND'],[8,'AND'],[7,'AND'],[9,'OR']]
 27 ##
 28 def Max(a, b): #  '''可信度计算'''
 29     return a if a>b else b
 30 def Min(a, b):  
 31     return b if a>b else a
 32 def Mix(x, y):
 33     return (x+y-x*y)
 34 
 35 class fact(object):  #'''定义事实类''' 
 36     def __init__(self,Num,NamInput):
 37         self.Number=Num    #'''事实编号'''
 38         self.Active=False  #'''记录事实的激活状态'''
 39         self.CF=0  #'''事实可信度'''
 40         self.SignNum=0  #'''输出标记'''
 41         self.Name=NamInput  #'''事实内容'''
 42     def Fuzz(i):   #'''定义可信度模糊函数'''
 43         pass
 44 ###        
 45     def Input(self,int):
 46         pass
 47     def GetName(self):
 48         return self.Name    
 49     def GetNumber(self):
 50         return self.Number
 51     def GetAct(self):
 52         return self.Active
 53     def PutAct(self,Act):
 54         self.Active=Act
 55     def PutFunc(self,f):
 56         self.Fuzz=f
 57     def GetCF(self):
 58         return self.CF
 59     def PutCF(self,i):
 60         if isinstance(i,int):
 61             self.CF=self.Fuzz(i)
 62             return self.CF
 63         else:
 64             self.CF=i    
 65     def PutSign(self,i):
 66             self.Sign =i        
 67     def GetSign(self):
 68         return self.Sign
 69 
 70 
 71 
 72 class rule(object):   #'''定义规则类'''
 73 
 74     def GetConc():
 75         return self.Conc
 76     def GetName():
 77         return self.Name
 78     def __init__(self,P,C,Rule_CF_Val):  
 79          #'''构造规则函数''' 
 80         #print(P)
 81         self.List=[None]*2
 82         self.Name="Rule Name"   
 83         self.List[0]=P[0]
 84         self.List[1]=P[1]
 85         self.Logic=C[1]
 86         self.Conc=C[0]
 87         self.RCFi=Rule_CF_Val
 88         self.Next=None    
 89 
 90                
 91 
 92     def __del__(self):  #'''构造释放规则空间函数'''
 93         #delete Name
 94         #delete []List
 95         pass
 96 
 97     def Query(self):  #  '''构造推理函数'''
 98         sign=0
 99         temps=['']*10
100         choose=""
101         #fact* (*temp)=Fact
102         temp=Fact
103         while (sign<PRMS_LENGTH):
104             #for(;(*temp)!=NULL;temp=temp+1)
105             for index in range(len(temp)):
106                 if(temp[index].GetNumber()==self.List[sign]): break
107             if(temp[index]==None): return FALSE
108             if(temp[index].GetAct()>0):
109                 sign=sign+1
110                 temp=Fact
111             else:
112                 temp[index].Input(temp[index].GetNumber())
113                 choose=input() #scanf("%s",choose)
114                 # flushall()
115                 print()                
116                 if choose.lower()=="q":
117                     return TRUE
118                 if str(int(choose))!= choose :
119                     continue
120                 if temp[index].PutCF(int(choose))==int(Repeat):
121                     continue
122                 temp[index].PutAct(TRUE)
123         for index in range(len(temp)):
124             if(temp[index].GetNumber()==self.Conc): break
125         if(temp[index]==None): return FALSE
126         temp[index].PutCF(Mix(temp[index].GetCF(),self.CF()))
127         temp[index].PutAct(1)
128         return FALSE
129 
130     def CF(self):  #'''构造可信度推理函数'''
131         if self.Logic:
132             i=Min(Fact[self.List[0]-1].GetCF(),Fact[self.List[1]-1].GetCF())
133             i=i*self.RCFi
134             return i
135 
136      
137      #################
138 ##
139 Fact=[fact]*FACT_LENGTH
140 
141 #########################
142 def Init():  #'''初始化函数'''
143     DefFuncArray()
144     DefInput()
145     DefRule_CF()
146 
147 
148 def Input1(i):
149      print("按q或Q退出")
150      print("请输入事实:E[",i,"的可信度")
151      print("可信度为:") 
152      print(" [1]高")
153      print(" [2]中")
154      print(" [3]低")
155 
156 def Input2(i=3):
157      print("按q或Q退出")
158      print("请输入事实 E[",i,"]数值[30-45]:")  
159 
160 def Input3(i=4):
161      print("按q或Q退出")
162      print("请输入事实 E[",i,"]数值[60,160]:")
163 
164 def Fuzz1(sign):
165     switcher = {
166         1: VH,
167         2: H,
168         3: M,
169     }
170     if(sign in switcher.keys()):
171         return switcher[sign]
172     else:
173         stderr.write("请重新输入!")
174         return Repeat    
175 
176 
177 def Fuzz2(sign):
178     if sign<30 or sign>45:
179         stderr.write("请重新输入!")
180         return Repeat
181     i=(sign-37.0)/9.0
182     return i if i>0 else -i
183 
184 def Fuzz3(sign):
185     if sign<60 or sign>160:
186         stderr.write("请重新输入!")
187         return Repeat
188 
189     i=(sign-60.0)/100.0
190     return(i)
191 
192 def DefFuncArray():
193     for i in range(4):
194         Fuzz[i]=Fuzz1
195     Fuzz[4]=Fuzz2
196     Fuzz[5]=Fuzz3
197 
198 def DefInput():
199     for i in range(4):
200         Input[i]=Input1
201     Input[4]=Input2
202     Input[5]=Input3
203 
204 #'''定义规则的可信度'''
205 def DefRule_CF():
206     Rule_CF[0]=0.9
207     Rule_CF[1]=1.0
208     Rule_CF[2]=0.9
209     Rule_CF[3]=0.9
210 
211 
212 def main():
213     #rule *Rule,*R    
214     #int i=0
215     Init()
216     #while(*Str[i]) #   '''激活事实对象集'''
217     for i in range(len(Fact)):
218         Fact[i]=fact((i+1),Str[i])
219         #print(Fact[i].GetName())
220         Fact[i].PutSign(Sign[i])
221     for s in range(PREMISE):
222         Fact[s].Input=Input[s]
223         Fact[s].PutFunc(Fuzz[s])
224 
225     Rule=None
226     for i in range(RULE_LENGTH-1,-1,-1): #'''激活规则对象集'''
227         if(i<0): return FALSE  
228         print(i)      
229         R=rule(Rulep[i],Rulec[i],Rule_CF[i])
230         R.Next=Rule
231         Rule=R
232 
233     R=Rule
234     while(True):
235            if(R.Query()): break
236            R=R.Next
237            if(not R): break
238 
239     #for(i=0;i<FACT_LENGTH;i++)  '''给出结论'''
240     for i in range(FACT_LENGTH):
241          if Fact[i].GetCF()>LIMIT and Fact[i].GetSign()==1:
242                 Fact[i].PutSign(0)
243                 print(" 结论为:")
244                 print(Fact[i].GetName())
245                 print(" 其可信度为:")
246                 print(Fact[i].GetCF())
247 
248     print("运行结束。")
249     input()
250     return TRUE
251 
252 if __name__=='__main__':
253     main() 
254  

 

posted @ 2017-12-15 15:19  Jason Wang  阅读(4991)  评论(0编辑  收藏  举报
欲望的奴隶,文化的俘虏,演化的工具